Compare commits

...
10 Commits
Author SHA1 Message Date
tben bab6683295 v0.28.6
CI / check (push) Waiting to run
Release image / image (release) Waiting to run
Release image / computer-image (release) Waiting to run
2026-11-25 07:00:02 +01:00
tben 1757311262 Tell a bot who it's working for, and show user ids in the People list
A bot asked a member to confirm their identity because no run's prompt
ever carried the user's name; it had guessed one from the workspace name.
Every run now gets a who-you're-working-for section from grabUserName
(first and last, else username), and each row on Settings > Users ends
with the user's id.
2026-11-25 06:59:22 +01:00
tben d4469e6848 Give every provider its generation settings, not just OpenRouter
Only OpenRouter's /models says what each model takes, so every other provider's models carried no supported_parameters and the settings page hid temperature, effort and the rest. A provider now declares them (its saved pick, else its preset's list, else its host's: Alibaba's Token Plan hosts included) and the sync writes them into every model that reports none of its own. Reasoning effort goes flat as reasoning_effort outside OpenRouter, where the nested form was ignored, and thinking on/off goes as a boolean.
2026-11-25 06:55:07 +01:00
tben 15a74cacde v0.28.5
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:52:19 +01:00
tben 67395500b5 Show a person's and a bot's picture at the size it is set up at
A picture preview was drawn whatever the size asked for, so setting up a
photo meant judging a thumbnail. BotAvatar passes its size through to the
image, UserAvatar gains xl and xxl, and the profile photo and the bot form's
preview use them.
2026-11-25 04:52:19 +01:00
tben 95c8ee7c39 v0.28.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-25 04:37:37 +01:00
tben edd451342e Give the routine form's brief room to read 2026-11-25 04:37:37 +01:00
tben b635eeb543 Keep the hook form's buttons from being clipped away by the modal 2026-11-25 04:36:05 +01:00
tben 4cadde55e2 Size the bot form's preview picture from the form
The preview takes an avatar size, so the new-bot form shows it at 100px
rather than the 56px it uses in a list.
2026-11-25 04:32:23 +01:00
tben e000b09898 Let a user delete a chat session
The sessions modal now deletes a session and everything in it, refused
while a run is open in it. Deleting the active one gives the conversation
a fresh session instead of leaving it pointing at a removed one, and the
list rows truncate their summary to the row's width.
2026-11-25 04:32:19 +01:00
52 changed files with 988 additions and 134 deletions
+3 -3
View File
@@ -89,7 +89,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Bots, sessions, chat
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Sending a message and answering a question card both hold the conversation's lock (`conversationLock`, `src/functions/backend/db/bot-sessions/conversation-lock.ts`, a `createKeyLock` per user, bot and workspace), since two sends 78 ms apart both read the same full session and one then wrote into the session the other had just closed; when its own rollover writes nothing, `rollOverBotSession` returns the conversation's current active session rather than the stale one. The composer holds its send until it answers (`sending`), so a double tap sends once. An open plan follows its conversation across a rollover (`carry-over-bot-session` moves `bot_plans.session_id`). A routine and a hook each keep a thread of their own, marked by `bot_sessions.routine_id` and `hook_id`, with the routine's or hook's title, rolled over at the same session max into a new linked session (`rollOverLinkedSession`, `previous_session_id`, the summary opening the new one), and read and chatted in with `?session_id=` like any session. `ensureRoutineSession`/`ensureHookSession` open it `closed` and then make it the conversation's active session (`activateBotSession`, a routine and a non-silent hook alike), so a run takes the chat over instead of landing in a sidebar; a silent hook is the opt-out (`bot_hooks.silent`). A deleted routine or hook detaches its thread (`routine_id`/`hook_id` set to null) and keeps the messages; a silent hook's thread is the one exception to being followed (`followedSessionSql`: no rail row, no unread, no push, no face change) **until the user writes in it**: a human message takes the thread from the hook (`adoptHookSession`, from `insertUserMessage`, so a chat message and a question's answer alike), so the thread is theirs from then on and the hook opens a new one next time, while a hook that isn't silent makes its thread the conversation's active session for its run. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The sessions modal deletes a session too (`delete-session` -> `deleteBotSession` -> `deleteSessionRows`), refused while a run is open in it; deleting the active one starts the conversation a fresh session. The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; recorded before the crew is read, so the conversation opened is already on top in that render, and its bot leads whatever the visits say (`pinned_id`); a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, the bot panel (`BotPanel`) sliding in from the right when its stone (beside the name or beside its messages in the thread) or its name is tapped, or a phone swipes that way, over the conversation rather than taking width; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
@@ -119,7 +119,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
### Prompt and memory
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
`composeBotPrompt` (`src/utils/compose-bot-prompt.ts`, via `grab-bot-prompt`): core `system_prompt`, install-wide append (`bot_system_prompt_append`), the name of the user the run is for (`grabUserName`; first and last, else username, and no section when they have neither, so no bot asks who it's talking to), then in a workspace its context, the bot's instructions there and the run's user's role there (`workspace_user_roles`), then core `memory`, per-user memory (`bot_user_memories`), workspace memory (`workspace_bots.memory`). Core memory is never about one user. `update_memory` defaults to `user` (`workspace` in a workspace); core only for what holds for everyone. Whole-text replace, capped at `AppData.PromptMaxLength`. Each whole-text replace (`update_workspace`'s context, `set_bot_workspace_instructions`, `update_memory`) refuses once a save that would drop a section (`markdownHeadings`) or cut the text below `AppData.SharedTextShrinkShare` of its length (`sharedTextProblem`, `src/utils/shared-text-guard.ts`), until the caller passes `replace: true`; the context is read before it is rewritten with `find_workspace` `include_context` (coordinator wherever it works, and a workspace admin), and each of them reads its save back before reporting it. Each memory section says it shapes how the bot does the work, never what it does beyond the request.
Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user's request sets the scope, and crew changes (create, place, remove, assign a computer, change a role) and handing work out (delegating, handing over a task or routine) happen only once the user asked for them, through one `ask_user` card in a reply or task, or as a proposal in a run nobody watches (routine, hook call, crew request). The way they named is part of the request too: a tool, app, service, provider or path they asked for is the one to use, a blocked one is reported and asked about, never swapped for another way that reaches the same result, and a probe is not a deliverable. Memory, habits and the bot's own initiative never widen a request. Every prompt ends with `RoadblockNote`: a run that is blocked (a tool failing again and again, a computer or page down, access it does not have) stops after two or three attempts and reports what failed and what the user must do, never works around it another way or describes the work as done. The app enforces the tool-loop half itself: `AppData.HarnessStuckToolRepeats` consecutive calls of one tool with the same answer end the run at a wrap up (`stuckToolNote`, `run-text-loop.ts`).
@@ -240,7 +240,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars` (a namespace of `HarnessDeferredNamespaceMin` tools or more is listed by name alone on one line: one GitHub connection's 905 tools were 148,000 characters of descriptions on every turn), and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`). Only OpenRouter's `/models` says what each model takes; every other provider lists ids only, so its models get what its provider declares (`harness_providers.parameters`, else its preset's list in `harness-provider-dict.ts`, else its host's: `provider-parameter-keys.ts`, which knows Alibaba's Token Plan hosts) written into `supported_parameters` at sync (`modelSupportedParameters`), and a provider that declares none hides the Model settings target. A super admin ticks them in the provider form. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model, and `reasoning_effort` nests as `reasoning: { effort }` on OpenRouter alone (`toWireChatParams`). Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. A prompt-kind tool's filled template is the model's own input, so a secret env fills in as its `[KEY]` marker there, never its value (`runPromptTool`); http and script tools use secrets server-side, where the value never reaches the model. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); knowledgebases are the exception it fills itself, since they live on the install (see Knowledgebases). Its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). A pending proposal for the same thing in the same conversation is replaced when another is made or one is confirmed (`replacePendingExtensionProposals`: a skill by `data.slug`, else the extension id, else the normalised name; `replacePendingHookProposals` by `hook_id`, then title), so a conversation carried into a new session no longer leaves a second card pending for the same skill (#41 stayed pending for ever while #42 made it, and the same target churned through #60-#63). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
+5
View File
@@ -3237,6 +3237,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
fieldDescription: `Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown`,
dataType: "INTEGER",
},
{
fieldName: "parameters",
fieldDescription: `JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none`,
dataType: "TEXT",
},
{
fieldName: "last_synced_at",
fieldDescription: `Unix timestamp of the last model list sync`,
+4
View File
@@ -2009,6 +2009,10 @@ export type BUN_SQLITE_COBBLE_HARNESS_PROVIDERS = {
* Context window, in tokens, for the models this provider lists without one of their own (a custom provider lists ids only). The sync writes it into harness_models.context_length; null leaves them unknown
*/
context_length?: number | "";
/**
* JSON array of the generation settings this provider's models are offered, for the models whose own list carries none (a custom provider lists ids only). Null follows the preset's or host's own list; an empty array means it takes none
*/
parameters?: string;
/**
* Unix timestamp of the last model list sync
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.3",
"version": "0.28.6",
"module": "index.ts",
"type": "module",
"private": true,
+6 -1
View File
@@ -31,7 +31,11 @@ type Props = ComponentProps<typeof BotStone> & {
* never a circle, so it isn't mistaken for a person), else its stone. Its
* colour still marks it everywhere else, e.g. the unread dot.
*/
export default function BotAvatar({ image_media_id, src: picked, ...stone }: Props) {
export default function BotAvatar({
image_media_id,
src: picked,
...stone
}: Props) {
const saved = profileImageUrls({ media_id: image_media_id });
const thumbnail_src = picked || saved.thumbnail_src;
const src = picked || saved.src;
@@ -49,6 +53,7 @@ export default function BotAvatar({ image_media_id, src: picked, ...stone }: Pro
BotAvatarSizeClasses[size] || BotAvatarSizeClasses[32],
stone.className,
)}
size={size}
/>
);
}
+65 -48
View File
@@ -2,16 +2,23 @@ import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Trash2 } from "lucide-react";
import { twMerge } from "tailwind-merge";
import type { BotSessionListItem } from "@/src/types";
import messagePreview from "@/src/utils/message-preview";
import relativeTime from "@/src/utils/relative-time";
import RowIconButton from "./row-icon-button";
type Props = {
session: BotSessionListItem;
loading?: boolean;
disabled?: boolean;
onOpen: () => void;
/**
* Deletes the session and its messages; left out where sessions can't be
* deleted (the rail).
*/
onDelete?: () => void;
/**
* The session the page shows (`?session_id=`, else the active one):
* marked Current and greyed out.
@@ -25,7 +32,7 @@ type Props = {
* recent. The one on screen is Current (greyed out); any other opens on
* click (reopening a closed one, going back to the active one).
*/
export default function BotSessionRow({ session, loading, disabled, onOpen, current }: Props) {
export default function BotSessionRow({ session, loading, disabled, onOpen, onDelete, current }: Props) {
const preview = session.summary || session.last_message_text || "";
const at = session.last_activity_at || session.created_at;
const tag = session.routine_title
@@ -35,56 +42,66 @@ export default function BotSessionRow({ session, loading, disabled, onOpen, curr
: null;
return (
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"w-full justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{session.title || "Untitled session"}
</Span>
{tag ? (
<Row className="w-full flex-nowrap items-center gap-1">
<Button
title={
current
? "This is the session on screen"
: session.status == "active"
? "Go back to the active session"
: `Reopen "${session.title || "Untitled"}"`
}
type="button"
variant="ghost"
color="text"
loading={loading}
disabled={current || disabled}
onClick={onOpen}
buttonContentProps={{ className: "w-full min-w-0 flex-nowrap" }}
className={twMerge(
"grow min-w-0 justify-start! items-start! gap-0! px-3! py-2.5! rounded-default text-left text-ink dark:text-ink hover:bg-ink/5 hover:dark:bg-ink/5 focus-visible:ring-2 focus-visible:ring-ink",
current && "bg-sunken hover:bg-sunken hover:dark:bg-sunken opacity-100!",
)}
>
<Stack className="w-full min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
className={twMerge(
"grow min-w-0 truncate text-sm font-bold leading-5",
current ? "text-ink-secondary" : "text-ink",
)}
>
{tag.label}
{session.title || "Untitled session"}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
{tag ? (
<Span
title={tag.title}
className="shrink-0 rounded-default bg-ink/5 px-1.5 text-[11px] leading-4 text-ink-secondary"
>
{tag.label}
</Span>
) : null}
{session.unread && !current ? (
<Span className="shrink-0 text-[11px] font-bold leading-4 text-ink">New</Span>
) : null}
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{current ? "Current" : at ? relativeTime({ at: Number(at) }) : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Row>
<Span className="w-full truncate text-xs leading-4 text-ink-secondary">
{`${session.message_count} message${session.message_count == 1 ? "" : "s"}`}
{preview ? ` · ${messagePreview({ text: preview })}` : ""}
</Span>
</Stack>
</Button>
</Stack>
</Button>
{onDelete ? (
<RowIconButton
icon={Trash2}
title={`Delete "${session.title || "Untitled"}"`}
disabled={Boolean(loading) || disabled}
onClick={onDelete}
/>
) : null}
</Row>
);
}
+37 -17
View File
@@ -43,7 +43,7 @@ type Props = {
* The sessions icon (or another target) that opens a conversation's
* sessions. A conversation is split into sessions so a bot's context never
* grows without bound; this lists them, searches them, starts a fresh one,
* or reopens an old one to carry on.
* reopens an old one to carry on, or deletes one.
*/
export default function BotSessionsModal({
bot,
@@ -139,22 +139,42 @@ export default function BotSessionsModal({
</Span>
) : null}
<Stack className="w-full mt-2 max-h-[60vh] overflow-y-auto gap-0! items-stretch">
{sessions.sessions.map((session) => (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={on_screen?.id ? on_screen.id == session.id : session.status == "active"}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
/>
))}
{sessions.sessions.map((session) => {
const is_current = on_screen?.id
? on_screen.id == session.id
: session.status == "active";
return (
<BotSessionRow
key={session.id}
session={session}
loading={sessions.busy_id == session.id}
disabled={Boolean(sessions.busy_id)}
current={is_current}
onOpen={() =>
session.status == "active"
? window.location.assign(conversationHref({ bot_id: Number(bot.id), workspace_id }))
: sessions.reopenSession({
session_id: Number(session.id),
})
}
onDelete={() => {
if (
!window.confirm(
`Delete "${session.title || "this session"}"? Its messages go with it, and this can't be undone.`,
)
) {
return;
}
sessions.deleteSession({
session_id: Number(session.id),
current: is_current,
});
}}
/>
);
})}
{sessions.loading ? (
<LoadingBlock className="w-full h-[300px]" />
) : !sessions.sessions.length ? (
+2 -1
View File
@@ -193,8 +193,9 @@ export default function HookForm({
};
return (
// shrink-0: a capped flex column (the modal) would squash the form and clip the buttons away.
<Form
className="w-full gap-4! items-stretch pt-4 overflow-hidden px-1"
className="w-full shrink-0 gap-4! items-stretch pt-4 overflow-hidden px-1"
onSubmit={submit}
>
<Input
+8 -4
View File
@@ -34,7 +34,7 @@ export default function ImagePickField({
const input_ref = useRef<HTMLInputElement>(null);
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<Row className="w-full gap-4! items-center">
{preview}
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
@@ -60,14 +60,17 @@ export default function ImagePickField({
disabled={disabled || loading}
onClick={() => {
onRemove();
if (input_ref.current) input_ref.current.value = "";
if (input_ref.current)
input_ref.current.value = "";
}}
>
Remove
</Button>
) : null}
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">{note}</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{note}
</Span>
</Stack>
{/*
* Raw on purpose: twui `Input` writes `value` on change, which
@@ -85,7 +88,8 @@ export default function ImagePickField({
if (!e.target.files?.[0]) return;
imageInputToBase64({ imageInput: e.target }).then((res) => {
if (res?.imageBase64Full) onPick({ data_url: res.imageBase64Full });
if (res?.imageBase64Full)
onPick({ data_url: res.imageBase64Full });
});
}}
/>
+10 -3
View File
@@ -19,7 +19,9 @@ type Props = {
export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
const [title, setTitle] = useState(cron_job.title || "");
const [schedule, setSchedule] = useState(cron_job.schedule || "");
const [instructions, setInstructions] = useState(cron_job.instructions || "");
const [instructions, setInstructions] = useState(
cron_job.instructions || "",
);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -69,13 +71,18 @@ export default function RoutineForm({ cron_job, onCancel, onSaved }: Props) {
/>
<CodeEditor
mode="markdown"
className="h-40"
className="h-[300px]"
title="Brief"
content={instructions}
info="What the bot does at every run, and how it knows it's done."
onChange={(value) => setInstructions(value)}
/>
<AddFormActions submit_label="Save" loading={loading} error={error} onCancel={onCancel} />
<AddFormActions
submit_label="Save"
loading={loading}
error={error}
onCancel={onCancel}
/>
</Form>
);
}
+5 -1
View File
@@ -12,6 +12,8 @@ const UserAvatarSizeClasses = {
sm: "size-6 text-[11px]",
md: "size-8 text-xs",
lg: "size-16 text-lg",
xl: "size-24 text-xl",
xxl: "size-32 text-2xl",
} as const;
type Props = {
@@ -47,7 +49,9 @@ export default function UserAvatar({
size = "md",
className,
}: Props) {
const photo = person?.profile_media_id ? grabMediaURL({ user: person }) : {};
const photo = person?.profile_media_id
? grabMediaURL({ user: person })
: {};
const src = passed_src || photo.media_thumbnail_url || photo.media_url;
const img_err_src = passed_src ? passed_err_src : photo.media_url;
const initials = passed_initials || userInitials(person || {});
+11
View File
@@ -5,6 +5,7 @@ import {
harnessParametersFromOptions,
harnessParameterValue,
modelAdvertisesParameter,
providerSupportedParameters,
withHarnessParameters,
} from "./harness-parameter-dict";
@@ -68,4 +69,14 @@ describe("harness parameters", () => {
harnessParameterValue({ harness: "text", params: { temperature: 0 }, key: "temperature" }),
).toEqual({ value: 0, saved: true });
});
test("a provider's declared settings go under the names its models advertise", () => {
expect(
providerSupportedParameters({
keys: ["temperature", "reasoning_effort"],
}),
).toEqual(["temperature", "reasoning"]);
expect(providerSupportedParameters({})).toBeUndefined();
expect(providerSupportedParameters({ keys: [] })).toEqual([]);
});
});
+55
View File
@@ -8,6 +8,7 @@
* - `advertised`: the name a provider's model list uses for it, when it
* differs (OpenRouter's `supported_parameters`)
* - `wire`: how the field is written, for providers that nest it
* - `wire_boolean`: saved as "true"/"false", sent as a JSON boolean
*/
export const HarnessParameters = [
{
@@ -104,12 +105,42 @@ export const HarnessParameters = [
{ value: "high", title: "High" },
],
},
{
key: "enable_thinking",
title: "Thinking",
description: `Whether it thinks before it answers, which is slower and costs more. "Default" leaves each model's own setting alone. Providers that turn thinking on by another field ignore it.`,
value_type: "select",
wire_boolean: true,
options: [
{ value: "true", title: "On" },
{ value: "false", title: "Off" },
],
},
{
key: "thinking_budget",
title: "Thinking budget",
description: `How many tokens it may think with, up to 32768. Only some models take it, and usually only while thinking is on.`,
value_type: "number",
min: 0,
max: 32768,
step: 1,
},
] as const;
export type HarnessParameter = (typeof HarnessParameters)[number];
export type HarnessParameterKey = HarnessParameter["key"];
export type HarnessParameterValue = number | string;
/**
* The generation settings as they go on the wire: OpenRouter's reasoning
* effort nests as `reasoning: { effort }`, a boolean setting as a JSON
* boolean, the rest as they are.
*/
export type HarnessWireParams = Record<
string,
number | string | boolean | { effort: string }
>;
/**
* The harnesses whose models are chat models, so the only ones the
* generation settings apply to.
@@ -189,6 +220,30 @@ export function modelAdvertisesParameter({
);
}
/**
* The names a provider's declared settings go under: what its models'
* `supported_parameters` should carry, so the same advertised names
* OpenRouter's catalog uses. Undefined when the provider declares nothing,
* which leaves its models with none.
*/
export function providerSupportedParameters({
keys,
}: {
keys?: readonly HarnessParameterKey[] | null;
}) {
if (!keys) return undefined;
return keys.flatMap((key) => {
const parameter = HarnessParameters.find((p) => p.key == key);
if (!parameter) return [];
return [
"advertised" in parameter ? parameter.advertised : parameter.key,
];
});
}
/**
* The generation settings a saved `options` object holds.
*/
+13
View File
@@ -8,6 +8,9 @@
* tools support and prices; `openai-compatible` gives only ids, so
* capabilities are guessed from the names
* - `local`: runs on the user's own hardware, so its models count as free
* - `parameters`: the generation settings its models get when its own model
* list carries none (`HarnessParameters` keys). Empty for a provider whose
* catalog decides (OpenRouter) or whose host is checked instead (custom)
* - `image_path`: image generation endpoint
* - `image_edit_path`: where images made from reference images go. OpenRouter
* takes them on `image_path` (`input_references`); the others take a
@@ -22,6 +25,7 @@ export const HarnessProviderKinds = [
{
title: "OpenRouter",
value: "openrouter",
parameters: [],
base_url: "https://openrouter.ai/api/v1",
needs_key: true,
key_env: "OPENROUTER_API_KEY",
@@ -34,6 +38,7 @@ export const HarnessProviderKinds = [
{
title: "OpenAI",
value: "openai",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty", "seed", "reasoning_effort"],
base_url: "https://api.openai.com/v1",
needs_key: true,
key_env: "OPENAI_API_KEY",
@@ -46,6 +51,7 @@ export const HarnessProviderKinds = [
{
title: "Anthropic",
value: "anthropic",
parameters: ["temperature", "top_p", "top_k"],
base_url: "https://api.anthropic.com/v1",
needs_key: true,
key_env: "ANTHROPIC_API_KEY",
@@ -58,6 +64,7 @@ export const HarnessProviderKinds = [
{
title: "Google Gemini",
value: "google",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
needs_key: true,
key_env: "GEMINI_API_KEY",
@@ -70,6 +77,7 @@ export const HarnessProviderKinds = [
{
title: "DeepSeek",
value: "deepseek",
parameters: ["temperature", "top_p", "frequency_penalty", "presence_penalty"],
base_url: "https://api.deepseek.com",
needs_key: true,
key_env: "DEEPSEEK_API_KEY",
@@ -82,6 +90,7 @@ export const HarnessProviderKinds = [
{
title: "Groq",
value: "groq",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty", "reasoning_effort"],
base_url: "https://api.groq.com/openai/v1",
needs_key: true,
key_env: "GROQ_API_KEY",
@@ -94,6 +103,7 @@ export const HarnessProviderKinds = [
{
title: "Mistral",
value: "mistral",
parameters: ["temperature", "top_p", "top_k", "seed", "frequency_penalty", "presence_penalty"],
base_url: "https://api.mistral.ai/v1",
needs_key: true,
key_env: "MISTRAL_API_KEY",
@@ -106,6 +116,7 @@ export const HarnessProviderKinds = [
{
title: "xAI",
value: "xai",
parameters: ["temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "reasoning_effort"],
base_url: "https://api.x.ai/v1",
needs_key: true,
key_env: "XAI_API_KEY",
@@ -118,6 +129,7 @@ export const HarnessProviderKinds = [
{
title: "Ollama",
value: "ollama",
parameters: ["temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed"],
base_url: "http://localhost:11434/v1",
needs_key: false,
key_env: "",
@@ -130,6 +142,7 @@ export const HarnessProviderKinds = [
{
title: "Other (OpenAI-compatible)",
value: "custom",
parameters: [],
base_url: "",
needs_key: false,
key_env: "",
@@ -0,0 +1,48 @@
import AppError from "@/src/utils/app-error";
import deleteSessionRows from "./delete-session-rows";
import grabUserBotSession from "./grab-user-bot-session";
import hasOpenSessionJob from "./has-open-session-job";
import startBotSession from "./start-bot-session";
type Params = {
session_id: number | string;
user_id: number | string;
};
/**
* Deletes one of the user's sessions and everything in it. Deleting the
* active one hands the conversation a fresh session, since a conversation
* always has one to write in. A session with a run in progress is refused:
* the run would keep writing into rows that are gone.
*/
export default async function deleteBotSession({
session_id,
user_id,
}: Params): Promise<void> {
const session = await grabUserBotSession({ session_id, user_id });
if (!session?.id) {
throw new AppError(`Session not found.`);
}
/**
* A bot's part of a crew request is only ever read there.
*/
if (session.ask_id) {
throw new AppError(`Session not found.`);
}
if (await hasOpenSessionJob({ session_id: session.id })) {
throw new AppError(`This session has a run in progress. Stop it first, then delete the session.`);
}
await deleteSessionRows({ session_ids: [session.id] });
if (session.status != "active") return;
await startBotSession({
user_id: session.user_id!,
bot_id: session.bot_id!,
workspace_id: session.workspace_id,
});
}
@@ -12,7 +12,9 @@ type Params = {
* traces, jobs, what the runs were billed (`token_usages`), job tasks,
* reactions, message files, messages, tasks, then the sessions.
* Files a message carried are unlinked, and their media row is deleted once
* nothing else points at it.
* nothing else points at it. A newer session's `previous_session_id` and a
* message's `carried_from_session_id` that named one of these are cleared,
* since neither is a foreign key.
*/
export default async function deleteSessionRows({ session_ids }: Params) {
const ids = session_ids.map(Number).filter(Boolean);
@@ -107,6 +109,20 @@ export default async function deleteSessionRows({ session_ids }: Params) {
values: ids,
});
await deleteBotPlanRows({ session_ids: ids });
/**
* A newer session may carry on from one of these, and a message may have
* carried one over: neither link is a foreign key, so it dangles.
*/
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET previous_session_id = NULL WHERE previous_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `UPDATE bot_messages SET carried_from_session_id = NULL WHERE carried_from_session_id IN (${session_placeholders})`,
values: ids,
});
await BunSQLite.sql({
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
values: ids,
@@ -3,13 +3,15 @@ import AppError from "@/src/utils/app-error";
import grabSystemPromptAppend from "../app-settings/grab-system-prompt-append";
import grabWorkspaceBot from "../workspaces/grab-workspace-bot";
import grabWorkspaceUserRole from "../workspaces/grab-workspace-user-role";
import grabUserName from "../users/grab-user-name";
import grabBotUserMemory from "./grab-bot-user-memory";
import grabUserBot from "./grab-user-bot";
type Params = {
bot_id: number | string;
/**
* The user the bot works with: only their memory joins the prompt.
* The user the bot works with: their name and their memory join the
* prompt.
*/
user_id: number | string;
/**
@@ -23,8 +25,9 @@ type Params = {
/**
* The full prompt for one of the user's bots (`composeBotPrompt`): who it
* is (its name and id), its core instructions, the install-wide appendix,
* its memory, what it remembers about this user, and in a workspace that
* workspace's context, what the bot has for it and who this user is there.
* who the user it's working for is, its memory, what it remembers about this
* user, and in a workspace that workspace's context, what the bot has for it
* and who this user is there.
*/
export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: Params) {
const bot = await grabUserBot({ bot_id, user_id });
@@ -45,6 +48,7 @@ export default async function grabBotPrompt({ bot_id, user_id, workspace_id }: P
bot: { id: bot.id, name: bot.name, kind: bot.kind, role: bot.role },
system_prompt: bot.system_prompt,
appendix: await grabSystemPromptAppend(),
user_name: await grabUserName({ user_id }),
memory: bot.memory,
user_memory: await grabBotUserMemory({ bot_id: bot.id, user_id }),
workspace: found?.workspace,
@@ -0,0 +1,26 @@
import { describe, expect, test } from "bun:test";
import modelSupportedParameters from "./model-supported-parameters";
describe("model supported parameters", () => {
test("the provider's own list wins", () => {
expect(
modelSupportedParameters({
model: { supported_parameters: ["temperature"] },
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature"]);
});
test("a model that lists none gets the provider's", () => {
expect(
modelSupportedParameters({
model: {},
provider_parameters: ["temperature", "seed"],
}),
).toEqual(["temperature", "seed"]);
});
test("nothing declared stays nothing", () => {
expect(modelSupportedParameters({ model: {} })).toBeNull();
});
});
@@ -0,0 +1,23 @@
import type { HarnessCatalogModel } from "@/src/harness/types";
type Params = {
model: Pick<HarnessCatalogModel, "supported_parameters">;
/**
* The names the provider's own row declares, for the models it lists
* without any (a custom provider lists ids only).
*/
provider_parameters?: string[] | null;
};
/**
* The parameters a `harness_models` row keeps: what the provider's own list
* said, else the settings the provider declares (its preset, its host or a
* super admin's pick). A model's own list wins, so OpenRouter's catalog is
* never overridden.
*/
export default function modelSupportedParameters({
model,
provider_parameters,
}: Params) {
return model.supported_parameters ?? provider_parameters ?? null;
}
@@ -0,0 +1,32 @@
import {
HarnessParameterKeys,
type HarnessParameterKey,
} from "@/src/dict/harness-parameter-dict";
type Params = {
text?: string | null;
};
/**
* The generation settings a provider row saved, or undefined when it saved
* none (which follows its preset or host instead). Unknown keys are dropped,
* so an older release's name can't reach a model's `supported_parameters`
* and be offered as a field that never gets sent.
*/
export default function parseProviderParameters({
text,
}: Params): HarnessParameterKey[] | undefined {
if (!text) return undefined;
try {
const value = JSON.parse(text);
if (!Array.isArray(value)) return undefined;
return value.filter((key): key is HarnessParameterKey =>
HarnessParameterKeys.includes(key as HarnessParameterKey),
);
} catch {
return undefined;
}
}
@@ -4,6 +4,7 @@ import type {
BunSQLiteTables,
} from "@/db/types/db";
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import AppError from "@/src/utils/app-error";
import { encrypt } from "@/src/utils/crypt";
@@ -27,6 +28,11 @@ type Params = {
* leaves them unknown.
*/
context_length?: number;
/**
* The generation settings its models are offered. Left out follows its
* preset or host; an empty array means it takes none.
*/
parameters?: HarnessParameterKey[];
enabled: boolean;
};
@@ -42,6 +48,7 @@ export default async function saveHarnessProvider({
api_key,
clear_key,
context_length,
parameters,
enabled,
}: Params) {
const preset = grabProviderPreset({ kind });
@@ -75,6 +82,7 @@ export default async function saveHarnessProvider({
* cleared with null (the plugin binds it as NULL).
*/
context_length: (context_length && context_length > 0 ? context_length : null) as number,
parameters: (parameters ? JSON.stringify(parameters) : null) as string,
...key_update,
};
@@ -1,6 +1,9 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabHarnessAdapter from "@/src/harness/providers/grab-harness-adapter";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import { providerSupportedParameters } from "@/src/dict/harness-parameter-dict";
import parseProviderParameters from "./parse-provider-parameters";
import resolveProviderConfig from "./resolve-provider-config";
import upsertHarnessModels from "./upsert-harness-models";
@@ -29,6 +32,15 @@ export default async function syncHarnessProviderModels({ provider }: Params) {
provider_id: provider.id,
models,
provider_context_length: provider.context_length || null,
provider_parameters: providerSupportedParameters({
keys: providerParameterKeys({
kind: config.kind,
base_url: provider.base_url,
declared: parseProviderParameters({
text: provider.parameters,
}),
}),
}),
});
await BunSQLite.sql({
@@ -1,5 +1,7 @@
import type { BUN_SQLITE_COBBLE_HARNESS_PROVIDERS } from "@/db/types/db";
import grabProviderPreset from "@/src/harness/providers/grab-provider-preset";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import parseProviderParameters from "./parse-provider-parameters";
import type { PublicHarnessProvider } from "@/src/types";
type Params = {
@@ -14,19 +16,29 @@ export default function toPublicHarnessProvider({
provider,
}: Params): PublicHarnessProvider {
const preset = grabProviderPreset({ kind: provider.kind });
const base_url = provider.base_url || preset.base_url;
return {
id: provider.id || 0,
kind: preset.value,
name: provider.name || preset.title,
base_url: provider.base_url || preset.base_url,
base_url,
enabled: provider.enabled != 0,
has_key: Boolean(provider.api_key),
has_env_key: Boolean(preset.key_env && process.env[preset.key_env]),
needs_key: preset.needs_key,
key_env: preset.key_env || undefined,
context_length: provider.context_length || undefined,
/**
* What its form shows ticked, and what its models get on the next
* sync: its saved pick, else its preset's or host's list.
*/
parameters: providerParameterKeys({
kind: preset.value,
base_url,
declared: parseProviderParameters({ text: provider.parameters }),
}),
last_synced_at: provider.last_synced_at || undefined,
sync_error: provider.sync_error || undefined,
};
}
}
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { HarnessCatalogModel } from "@/src/harness/types";
import modelContextLength from "./model-context-length";
import modelSupportedParameters from "./model-supported-parameters";
type Params = {
provider_id: number;
@@ -10,6 +11,11 @@ type Params = {
* of their own (a custom provider lists ids only).
*/
provider_context_length?: number | null;
/**
* The generation settings its provider declares, as the names a model's
* `supported_parameters` carries, for the models it lists without any.
*/
provider_parameters?: string[] | null;
now?: number;
};
@@ -49,6 +55,7 @@ export default async function upsertHarnessModels({
provider_id,
models,
provider_context_length,
provider_parameters,
now = Date.now(),
}: Params) {
const unique = [...new Map(models.map((m) => [m.slug, m])).values()];
@@ -63,27 +70,36 @@ export default async function upsertHarnessModels({
${Columns.filter((c) => c != "created_at" && c != "provider_id" && c != "slug")
.map((c) => `${c} = excluded.${c}`)
.join(", ")}`,
values: chunk.flatMap((model) => [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
model.supported_parameters ? JSON.stringify(model.supported_parameters) : null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
]),
values: chunk.flatMap((model) => {
const supported_parameters = modelSupportedParameters({
model,
provider_parameters,
});
return [
now,
now,
provider_id,
model.slug,
model.name || model.slug,
model.free ? 1 : 0,
1,
JSON.stringify(model.input_modalities),
JSON.stringify(model.output_modalities),
model.supports_tools ? 1 : 0,
modelContextLength({ model, provider_context_length }),
model.max_output_tokens ?? null,
model.voices ? JSON.stringify(model.voices) : null,
supported_parameters
? JSON.stringify(supported_parameters)
: null,
model.intelligence_score ?? null,
model.agentic_score ?? null,
model.released_at ?? null,
model.expires_at ?? null,
now,
];
}),
});
if (!res.success) {
@@ -0,0 +1,31 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
};
type UserNameRow = {
first_name: string | null;
last_name: string | null;
username: string | null;
};
/**
* The user's name as the app shows it (first and last, else username), or
* empty when they have neither. Every run's prompt gets it, so its bot knows
* who it's working for instead of asking them to confirm it.
*/
export default async function grabUserName({ user_id }: Params): Promise<string> {
const row = (
await BunSQLite.sql<UserNameRow>({
sql: `SELECT first_name, last_name, username FROM users WHERE id = ? LIMIT 1`,
values: [user_id],
})
).payload?.[0];
return (
[row?.first_name, row?.last_name].filter(Boolean).join(" ").trim() ||
row?.username?.trim() ||
""
);
}
@@ -9,6 +9,7 @@ type Params = {
| "new-session"
| "continue-session"
| "reopen-session"
| "delete-session"
| "session-messages"
| "older-messages";
body: Record<string, unknown>;
+2 -1
View File
@@ -1,4 +1,5 @@
import { ReadImagePrompt } from "@/src/data/harness-prompts";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
@@ -56,7 +57,7 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
const { result } = await withCandidates<{
text: string;
usage?: HarnessUsage;
sent_params: Record<string, number | string | { effort: string }>;
sent_params: HarnessWireParams;
}>({
harness: "vision",
candidates,
@@ -2,6 +2,7 @@ import type { HarnessAdapter } from "../../types";
import grabProviderPreset from "../grab-provider-preset";
import providerRequest from "./provider-request";
import readChatResponse from "./read-chat-response";
import toWireChatParams from "./to-wire-chat-params";
import toWireMessages from "./to-wire-messages";
/**
@@ -24,7 +25,7 @@ const chat: HarnessAdapter["chat"] = async ({
// Generation settings first, so the core fields below always win:
// a saved parameter must never override the model, the messages,
// the tools or the token ceiling (R12).
...(params || {}),
...toWireChatParams({ params, kind: provider.kind }),
model: model.slug,
messages: toWireMessages({ messages }),
...(tools?.length
@@ -0,0 +1,35 @@
import { describe, expect, test } from "bun:test";
import toWireChatParams from "./to-wire-chat-params";
describe("toWireChatParams", () => {
test("OpenRouter nests the reasoning effort", () => {
expect(
toWireChatParams({
kind: "openrouter",
params: { temperature: 0.3, reasoning: { effort: "high" } },
}),
).toEqual({ temperature: 0.3, reasoning: { effort: "high" } });
});
test("everyone else takes it flat", () => {
expect(
toWireChatParams({
kind: "custom",
params: { temperature: 0.3, reasoning: { effort: "high" } },
}),
).toEqual({ temperature: 0.3, reasoning_effort: "high" });
});
test("the other settings pass through as they are", () => {
expect(
toWireChatParams({
kind: "openai",
params: { top_p: 0.5, enable_thinking: false },
}),
).toEqual({ top_p: 0.5, enable_thinking: false });
});
test("nothing saved sends nothing", () => {
expect(toWireChatParams({ kind: "openai" })).toEqual({});
});
});
@@ -0,0 +1,28 @@
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
type Params = {
params?: HarnessWireParams;
kind: HarnessProviderKind;
};
/**
* The generation settings as a provider's `/chat/completions` takes them.
* OpenRouter nests the reasoning effort as `reasoning: { effort }`; everyone
* else (OpenAI, Groq, Alibaba, a custom host) takes it flat as
* `reasoning_effort`, where the nested form is ignored.
*/
export default function toWireChatParams({ params, kind }: Params) {
const wire: HarnessWireParams = { ...(params || {}) };
if (kind == "openrouter") return wire;
const reasoning = wire.reasoning;
if (reasoning && typeof reasoning == "object") {
delete wire.reasoning;
wire.reasoning_effort = reasoning.effort;
}
return wire;
}
@@ -0,0 +1,53 @@
import { describe, expect, test } from "bun:test";
import providerParameterKeys from "./provider-parameter-keys";
describe("provider parameter keys", () => {
test("a provider's own saved pick wins over its preset", () => {
expect(
providerParameterKeys({
kind: "openai",
declared: ["seed"],
}),
).toEqual(["seed"]);
});
test("an empty saved pick means it takes none", () => {
expect(
providerParameterKeys({ kind: "openai", declared: [] }),
).toEqual([]);
});
test("a preset's list fills a provider that saved none", () => {
expect(
providerParameterKeys({ kind: "groq", base_url: "https://api.groq.com/openai/v1" }),
).toContain("temperature");
});
test("a custom provider on Alibaba gets Alibaba's list", () => {
const keys = providerParameterKeys({
kind: "custom",
base_url: "https://token-plan.us-east-1.maas.aliyuncs.com/compatible-mode/v1",
});
expect(keys).toContain("enable_thinking");
expect(keys).toContain("thinking_budget");
});
test("a custom provider elsewhere gets nothing rather than a guess", () => {
expect(
providerParameterKeys({
kind: "custom",
base_url: "http://localhost:8000/v1",
}),
).toBeUndefined();
});
test("OpenRouter keeps its catalog's own list", () => {
expect(
providerParameterKeys({
kind: "openrouter",
base_url: "https://openrouter.ai/api/v1",
}),
).toBeUndefined();
});
});
@@ -0,0 +1,59 @@
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import {
HarnessProviderKinds,
type HarnessProviderKind,
} from "@/src/dict/harness-provider-dict";
import { isDashScopeHost } from "./openai-compatible/dashscope-hosts";
/**
* What Alibaba's compatible mode documents taking, the Token Plan hosts
* included. `thinking_budget` is refused by a few of their models, so it is
* offered but not sent until asked for.
*/
const DashScopeParameters: readonly HarnessParameterKey[] = [
"temperature",
"top_p",
"presence_penalty",
"seed",
"enable_thinking",
"thinking_budget",
];
type Params = {
kind: HarnessProviderKind;
base_url?: string | null;
/**
* What the provider's own row saved, when a super admin set it. An empty
* array is a real answer (it takes none); null or undefined follows the
* preset, then the host.
*/
declared?: readonly HarnessParameterKey[] | null;
};
/**
* The generation settings a provider's models are offered: what its row
* saved, else its preset's list, else the list for its host (a custom
* provider pointed at Alibaba). Undefined when nobody knows, which leaves its
* models with no settings rather than sending a field it might refuse.
*/
export default function providerParameterKeys({
kind,
base_url,
declared,
}: Params): HarnessParameterKey[] | undefined {
if (declared) return [...declared];
const preset = HarnessProviderKinds.find((p) => p.value == kind);
if (preset?.parameters.length) return [...preset.parameters];
/**
* OpenRouter's catalog says what each model takes, so its models keep
* their own list.
*/
if (kind != "openrouter" && isDashScopeHost({ base_url })) {
return [...DashScopeParameters];
}
return undefined;
}
+3 -2
View File
@@ -2,6 +2,7 @@ import HarnessError from "../harness-error";
import grabHarnessAdapter from "../providers/grab-harness-adapter";
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
import withCandidates from "../resolve/with-candidates";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
import type {
HarnessCandidate,
HarnessChatResult,
@@ -38,7 +39,7 @@ export type GenerateTextParams = {
/**
* Overrides the saved generation settings (media reading wants 0).
*/
params?: Record<string, number | string | { effort: string }>;
params?: HarnessWireParams;
signal?: AbortSignal;
/**
* Media readings shared across calls of one run.
@@ -67,7 +68,7 @@ type ChatAnswer = Omit<HarnessChatResult, "text"> & {
/**
* The generation settings sent to this candidate, for its usage row.
*/
sent_params?: Record<string, number | string | { effort: string }>;
sent_params?: HarnessWireParams;
};
/**
@@ -83,6 +83,15 @@ describe("grabChatParams", () => {
expect(paramsFor(model(["reasoning_effort"]))).toEqual({});
});
test("thinking on/off goes on the wire as a boolean", async () => {
options = { enable_thinking: "false" };
const { paramsFor } = await grabChatParams({ harness: "text" });
expect(paramsFor(model(["enable_thinking"]))).toEqual({
enable_thinking: false,
});
});
test("the vision default is a literal 0", async () => {
const { paramsFor } = await grabChatParams({ harness: "vision" });
+11 -2
View File
@@ -2,6 +2,7 @@ import {
HarnessParameters,
harnessParameterValue,
modelAdvertisesParameter,
type HarnessWireParams,
} from "@/src/dict/harness-parameter-dict";
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
import type { HarnessModelInfo } from "../types";
@@ -26,7 +27,7 @@ export default async function grabChatParams({
bot_id,
workspace_id,
}: Params): Promise<{
paramsFor: (model: HarnessModelInfo) => Record<string, number | string | { effort: string }>;
paramsFor: (model: HarnessModelInfo) => HarnessWireParams;
source: "default" | "bot" | "workspace";
}> {
const setting = await grabHarnessSetting({
@@ -55,9 +56,17 @@ export default async function grabChatParams({
return [];
const key = "wire" in parameter ? parameter.wire : parameter.key;
const boolean = "wire_boolean" in parameter;
return [
[key, key == "reasoning" ? { effort: String(value) } : value],
[
key,
key == "reasoning"
? { effort: String(value) }
: boolean
? value === "true"
: value,
],
];
}),
);
+2 -1
View File
@@ -1,6 +1,7 @@
import type { z } from "zod";
import type { HarnessKind } from "@/src/dict/harness-dict";
import type { HarnessProviderKind } from "@/src/dict/harness-provider-dict";
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
/**
* Part of a user message. Images are an https or `data:` URL; audio is
@@ -234,7 +235,7 @@ export type HarnessChatParams = {
* Sampling and reasoning fields, keyed by their wire name. The caller
* only includes what the model advertises.
*/
params?: Record<string, number | string | { effort: string }>;
params?: HarnessWireParams;
signal: AbortSignal;
};
@@ -13,6 +13,12 @@ describe("flattenSentParams", () => {
expect(flattenSentParams({ params: { temperature: 0, seed: "" } })).toEqual({ temperature: 0 });
});
test("reads a boolean setting back as on or off", () => {
expect(
flattenSentParams({ params: { enable_thinking: false, temperature: 0.3 } }),
).toEqual({ enable_thinking: "off", temperature: 0.3 });
});
test("is undefined when nothing was sent", () => {
expect(flattenSentParams({ params: {} })).toBeUndefined();
expect(flattenSentParams({ params: null })).toBeUndefined();
+5 -1
View File
@@ -1,8 +1,10 @@
import type { HarnessWireParams } from "@/src/dict/harness-parameter-dict";
type Params = {
/**
* Keyed by the field sent on the wire (`grabChatParams`).
*/
params?: Record<string, number | string | { effort: string }> | null;
params?: HarnessWireParams | null;
};
/**
@@ -17,6 +19,8 @@ export default function flattenSentParams({ params }: Params) {
for (const [key, value] of Object.entries(params || {})) {
if (value && typeof value == "object") {
if (value.effort) flat[key == "reasoning" ? "reasoning_effort" : key] = String(value.effort);
} else if (typeof value == "boolean") {
flat[key] = value ? "on" : "off";
} else if (typeof value == "number" || (typeof value == "string" && value)) {
flat[key] = value;
}
+24 -2
View File
@@ -123,7 +123,21 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
};
}, [open, query, bot_id, workspace_id, limit, attended_only, revision, refresh_key]);
const act = async ({ id, path, body }: { id: number | "new"; path: "new-session" | "reopen-session"; body: Record<string, unknown> }) => {
const act = async ({
id,
path,
body,
reload = true,
}: {
id: number | "new";
path: "new-session" | "reopen-session" | "delete-session";
body: Record<string, unknown>;
/**
* Whether it lands the conversation on its session; a deleted
* session other than the one on screen only reloads the list.
*/
reload?: boolean;
}) => {
if (busy_id) return;
setBusyId(id);
@@ -135,7 +149,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
* The plain address, not a reload: one showing a session to read
* (`?session_id=`) would stay on it.
*/
if (res?.success) {
if (res?.success && reload) {
window.location.assign(conversationHref({ bot_id, workspace_id }));
return;
}
@@ -150,6 +164,12 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
}
setBusyId(undefined);
if (res?.success) {
setRevision((value) => value + 1);
return;
}
setError(res?.msg || "That didn't work.");
};
@@ -163,5 +183,7 @@ export default function useBotSessions({ bot_id, workspace_id, open, limit, atte
startSession: () => act({ id: "new", path: "new-session", body: { bot_id, workspace_id } }),
reopenSession: ({ session_id }: { session_id: number }) =>
act({ id: session_id, path: "reopen-session", body: { session_id } }),
deleteSession: ({ session_id, current }: { session_id: number; current: boolean }) =>
act({ id: session_id, path: "delete-session", body: { session_id }, reload: current }),
};
}
@@ -16,6 +16,7 @@ type Props = {
stone: BotStoneShape;
image_media_id?: number | string | null;
picked_src?: string;
avatar_size?: number;
};
/**
@@ -30,6 +31,7 @@ export default function BotFormPreview({
stone,
image_media_id,
picked_src,
avatar_size = 56,
}: Props) {
const has_picture = Boolean(picked_src || image_media_id);
/** A palette colour by name, else a colour the user made up. */
@@ -42,7 +44,7 @@ export default function BotFormPreview({
<BotAvatar
color={color}
stone={stone}
size={56}
size={avatar_size}
image_media_id={image_media_id}
src={picked_src}
/>
+9 -1
View File
@@ -91,7 +91,14 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
})
: await postAdminApi<{ bot_id: number }>({
path: "bots/create-bot",
body: { name, role, color, stone, system_prompt, workspace_id },
body: {
name,
role,
color,
stone,
system_prompt,
workspace_id,
},
});
const bot_id =
bot?.id ||
@@ -158,6 +165,7 @@ export default function BotForm({ bot, onCancel, onSaved }: Props) {
stone={stone}
image_media_id={image.image_media_id}
picked_src={image.data_url}
avatar_size={120}
/>
}
has_image={image.has_image}
@@ -54,7 +54,13 @@ type PanelTab = "settings" | "tools";
* without a conversation has nobody listening). The tab's data loads when it
* opens, and Escape, the backdrop or the X closes it.
*/
export default function BotPanel({ bot, workspace, open, on_open, on_close }: Props) {
export default function BotPanel({
bot,
workspace,
open,
on_open,
on_close,
}: Props) {
const { pageProps } = useContext(AppContext);
const name = bot.name || "This bot";
const can_edit = canManageCrew({ user_types: pageProps?.user_types });
@@ -109,7 +115,11 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
<Stack className="shrink-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
{...botStoneProps({
color: bot.color,
stone: bot.stone,
hue: bot.hue,
})}
face={(bot.face || "idle") as BotFace}
size={35}
/>
@@ -134,8 +144,16 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
aria-label={`Edit ${name}`}
className="shrink-0 gap-1! flex-nowrap items-center px-3 py-2 border-0 border-b border-solid border-hairline"
>
<TabButton title="Settings" active={tab == "settings"} onPick={() => setTab("settings")} />
<TabButton title="Tools" active={tab == "tools"} onPick={() => setTab("tools")} />
<TabButton
title="Settings"
active={tab == "settings"}
onPick={() => setTab("settings")}
/>
<TabButton
title="Tools"
active={tab == "tools"}
onPick={() => setTab("tools")}
/>
</Row>
<Stack className="grow min-h-0 overflow-y-auto gap-4! items-stretch px-4 pt-4 pb-6 [&>*]:shrink-0">
{open && tab == "settings" ? (
@@ -161,13 +179,22 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
bot_id={Number(bot.id) || 0}
bot_name={name}
memory={memory || ""}
workspace_id={workspace_id || undefined}
workspace_id={
workspace_id || undefined
}
workspace_name={workspace?.name}
workspace_memory={workspace_instructions.instructions?.memory || ""}
workspace_memory={
workspace_instructions
.instructions?.memory ||
""
}
onCancel={on_close}
/>
<Divider className="my-2 border-hairline dark:border-hairline" />
<BotUserMemory bot_name={name} memory={user_memory || ""} />
<BotUserMemory
bot_name={name}
memory={user_memory || ""}
/>
</>
) : loaded_error ? (
<Span className="py-6 text-[13px] leading-[18px] text-ink-secondary">
@@ -203,4 +230,4 @@ export default function BotPanel({ bot, workspace, open, on_open, on_close }: Pr
</SidePanel>
</>
);
}
}
@@ -0,0 +1,27 @@
import Checkbox from "@moduletrace/twui/form/Checkbox";
import type { HarnessParameter } from "@/src/dict/harness-parameter-dict";
type Props = {
parameter: HarnessParameter;
checked: boolean;
onChange: (checked: boolean) => void;
};
/**
* One generation setting a provider's models are offered.
*/
export default function HarnessProviderParameterCheckbox({
parameter,
checked,
onChange,
}: Props) {
return (
<Checkbox
title={parameter.title}
label={parameter.title}
info={parameter.description}
checked={checked}
clickDispatchHandler={onChange}
/>
);
}
@@ -0,0 +1,47 @@
import P from "@moduletrace/twui/layout/P";
import Stack from "@moduletrace/twui/layout/Stack";
import {
HarnessParameters,
type HarnessParameterKey,
} from "@/src/dict/harness-parameter-dict";
import HarnessProviderParameterCheckbox from "./harness-provider-parameter-checkbox";
type Props = {
parameters: HarnessParameterKey[];
onChange: (parameters: HarnessParameterKey[]) => void;
};
/**
* The generation settings a provider's models are offered, for the models
* whose own list carries none (a custom provider lists ids only).
*/
export default function HarnessProviderParameters({
parameters,
onChange,
}: Props) {
return (
<Stack className="gap-2! items-stretch">
<P className="text-sm text-ink-secondary">
The generation settings its models are offered, for the models
whose own list carries none (a custom provider lists ids only).
Models that list their own (OpenRouter) keep theirs. A provider
that takes none unticks all of them, so no field it would refuse
is ever sent.
</P>
{HarnessParameters.map((parameter) => (
<HarnessProviderParameterCheckbox
key={parameter.key}
parameter={parameter}
checked={parameters.includes(parameter.key)}
onChange={(checked) =>
onChange(
checked
? [...parameters, parameter.key]
: parameters.filter((key) => key != parameter.key),
)
}
/>
))}
</Stack>
);
}
@@ -10,6 +10,9 @@ import {
HarnessProviderKinds,
type HarnessProviderKind,
} from "@/src/dict/harness-provider-dict";
import type { HarnessParameterKey } from "@/src/dict/harness-parameter-dict";
import providerParameterKeys from "@/src/harness/providers/provider-parameter-keys";
import HarnessProviderParameters from "./harness-provider-parameters";
import type {
HarnessOverviewPayload,
PublicHarnessProvider,
@@ -43,12 +46,27 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
const [context_length, setContextLength] = useState(
provider?.context_length ? String(provider.context_length) : "",
);
/**
* What the admin ticked. Null follows the preset, then the host, so a
* custom provider pointed at Alibaba starts with its settings ticked.
*/
const [chosen_parameters, setChosenParameters] = useState<
HarnessParameterKey[] | null
>(provider ? (provider.parameters ?? []) : null);
const [enabled, setEnabled] = useState(provider?.enabled ?? true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
const id = `provider-${provider?.id || "new"}`;
const parameters =
chosen_parameters ??
providerParameterKeys({
kind,
base_url: base_url || preset.base_url,
}) ??
[];
const submit = async () => {
if (loading) return;
if (
@@ -73,6 +91,7 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
api_key: api_key || undefined,
clear_key: clear_key || undefined,
context_length: Number(context_length) || 0,
parameters,
enabled,
},
});
@@ -174,6 +193,10 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
onChange={(e) => setContextLength(e.target.value)}
placeholder="Eg. 1,000,000"
/>
<HarnessProviderParameters
parameters={parameters}
onChange={setChosenParameters}
/>
<Checkbox
title="Turn this provider on"
label="Turned on"
@@ -32,7 +32,12 @@ export default function ProfilePhotoField({
return (
<Row className="w-full gap-4! flex-nowrap items-center">
<UserAvatar src={preview_src} initials={initials} alt="Your photo" size="lg" />
<UserAvatar
src={preview_src}
initials={initials}
alt="Your photo"
size="xxl"
/>
<Stack className="gap-2! min-w-0">
<Row className="gap-2!">
<Button
@@ -17,7 +17,8 @@ type Props = {
};
/**
* One user: their photo, name, user types and email. The title opens
* One user: their photo, name, user types, email and id (`#7`, so a crew
* manager can name one to a bot or in a log). The title opens
* their settings page; Revoke (not once revoked) and Delete sit at the
* end where the actor may (`canRevokeUser`; never yourself).
*/
@@ -48,7 +49,7 @@ export default function UserSettingsRow({
href={`/admin/settings/users/${person.id}`}
title={name}
badge={is_self ? "You" : undefined}
subtitle={[types_title, person.email].filter(Boolean).join(" · ")}
subtitle={[types_title, person.email, `#${person.id}`].filter(Boolean).join(" · ")}
>
{can_revoke ? (
<SettingsRowAction
@@ -0,0 +1,44 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import deleteBotSession from "@/src/functions/backend/db/bot-sessions/delete-bot-session";
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type {
APIResponseObject,
BunextAPIRouteHandler,
} from "@moduletrace/bunext/types";
/**
* Deletes one of the session user's sessions, with its messages. The
* active one hands the conversation a fresh session.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { session_id } = parseWithSchema({
schema: BotSessionIdRequestSchema,
data: body,
});
await deleteBotSession({ session_id, user_id: user.id });
return { success: true, msg: `Session deleted.` };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+20
View File
@@ -5,6 +5,10 @@ import {
HarnessProviderKinds,
type HarnessProviderKind,
} from "@/src/dict/harness-provider-dict";
import {
HarnessParameterKeys,
type HarnessParameterKey,
} from "@/src/dict/harness-parameter-dict";
const ProviderIdSchema = z.coerce
.number()
@@ -43,6 +47,22 @@ export const SaveHarnessProviderRequestSchema = z.object({
},
)
.default(0),
/**
* The generation settings its models are offered, for the models whose
* own list carries none. Left out follows its preset or host; an empty
* array means it takes none.
*/
parameters: z
.array(
z.enum(
HarnessParameterKeys as [
HarnessParameterKey,
...HarnessParameterKey[],
],
"That is not a generation setting",
),
)
.optional(),
});
export const HarnessProviderIdRequestSchema = z.object({
+6
View File
@@ -38,6 +38,7 @@ import type { APIResponseObject, BunextPageModuleServerReturnURLObject } from "@
import type { BUN_SQLITE_COBBLE_USERS_JOIN } from "./sql-joins";
import type { ImageInputToBase64FunctionReturn } from "@moduletrace/twui/utils/form/imageInputToBase64";
import type { HarnessKind } from "../dict/harness-dict";
import type { HarnessParameterKey } from "../dict/harness-parameter-dict";
import type { HarnessProviderKind } from "../dict/harness-provider-dict";
import type { EnvParadigm, KnownEnv, SecretRequestStatus } from "../dict/env-dict";
import type { BotQuestionKind, BotQuestionStatus } from "../dict/bot-question-dict";
@@ -794,6 +795,11 @@ export type PublicHarnessProvider = {
* own (a custom provider lists ids only).
*/
context_length?: number;
/**
* The generation settings its models are offered (its saved pick, else
* its preset's or host's list). Undefined: it takes none.
*/
parameters?: HarnessParameterKey[];
last_synced_at?: number;
sync_error?: string;
};
+24
View File
@@ -106,6 +106,30 @@ describe("composeBotPrompt", () => {
expect(composeBotPrompt({ system_prompt: "Core.", appendix: " " })).toBe("Core.");
});
test("says who it's working for, so it never asks them to confirm it", () => {
expect(composeBotPrompt({ system_prompt: "Core.", user_name: " Ada Lane " })).toBe(
"Core.\n\n# Who you're working for\n\nYou're working for Ada Lane. Every message in this conversation is theirs (the app marks anything another bot passed on), so never ask them to confirm who they are.",
);
const prompt = composeBotPrompt({
appendix: "Be brief.",
user_name: "Ada Lane",
workspace: { name: "Launch" },
});
expect(prompt.indexOf("# Install-wide instructions")).toBeLessThan(
prompt.indexOf("# Who you're working for"),
);
expect(prompt.indexOf("# Who you're working for")).toBeLessThan(
prompt.indexOf("# Workspace: Launch"),
);
});
test("leaves the user out when the caller doesn't name them", () => {
expect(composeBotPrompt({ system_prompt: "Core.", user_name: " " })).toBe("Core.");
expect(composeBotPrompt({ system_prompt: "Core." })).toBe("Core.");
});
test("leaves out empty parts and has no workspace outside one", () => {
expect(
composeBotPrompt({
+21 -5
View File
@@ -38,6 +38,11 @@ type Params = {
* instructions (Settings > General).
*/
appendix?: string | null;
/**
* The name of the user whose conversation this run is for, so the bot
* never has to ask who it's talking to.
*/
user_name?: string | null;
memory?: string | null;
/**
* What the bot remembers about the user it's working with.
@@ -61,16 +66,18 @@ type Params = {
/**
* The full prompt a bot runs with (markdown): who it is (its name and id,
* so it always knows which bot it is), its own core instructions, then the
* install-wide appendix, then, in a workspace, the workspace's
* context, the bot's instructions there and the user's role there, then its core memory, its
* memory about the user and its memory in the workspace (said to be the
* bot's own notes, not the workspace's context). Empty parts are left out;
* the workspace heading always shows, so the bot knows where it is.
* install-wide appendix, then who the user it's working for is, then, in a
* workspace, the workspace's context, the bot's instructions there and the
* user's role there, then its core memory, its memory about the user and its
* memory in the workspace (said to be the bot's own notes, not the
* workspace's context). Empty parts are left out; the workspace heading
* always shows, so the bot knows where it is.
*/
export default function composeBotPrompt({
bot,
system_prompt,
appendix,
user_name,
memory,
user_memory,
workspace,
@@ -93,6 +100,15 @@ export default function composeBotPrompt({
parts.push(`# Install-wide instructions\n\n${appendix.trim()}`);
}
if (user_name?.trim()) {
parts.push(
[
`# Who you're working for`,
`You're working for ${user_name.trim()}. Every message in this conversation is theirs (the app marks anything another bot passed on), so never ask them to confirm who they are.`,
].join("\n\n"),
);
}
if (workspace) {
const context = [workspace.description?.trim(), workspace.system_prompt?.trim()].filter(
Boolean,