Compare commits

...
3 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 3bd749428e Release v0.16.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 cd6702de55 Lead back to the last conversation from settings and the rail pages
The last-visited cookie now records the workspace too (`<bot>:<workspace>`),
the landing page still reading only the bot. Settings and the rail pages get
that conversation, access-checked, as `last_conversation`, shown above their
rail list as a way back naming the bot and its workspace.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:38:37 +01:00
tbenandClaude Opus 5.5 1a6ae71286 Keep replies on the picked model, with fallbacks of its own
A production chat dropped from the pinned DeepSeek to a free Nemotron
after one failed call mid-run, and every reply for the next half hour
ran on it: it called browser tools from chat replies, then said it had
no browser. Nothing recorded why.

- A failed model (or provider, for a key or credits) rests for the
  install's model rest, 2 minutes by default (Settings > General run
  limits, harness_model_rest_seconds), never longer, Retry-After
  included. A refused request (400, 422) benches nothing.
- The text model takes up to 3 fallback models, from any provider,
  tried in order after the pick and before the free automatic picks
  (fallback_model_ids in the setting's options; defaults, bots and
  workspaces).
- A run that fell back to an automatic pick goes back to the pick or
  its fallbacks once they've rested.
- Every model failure is logged with the provider's error and its rest.
- A message answered in place of the model ahead of it shows the
  fallback on its usage chip; the details list what failed and what
  was passed over while resting.
- A computer or browser tool called from a reply is told to start a
  task instead of getting a list of names.
- The work-under-way check catches "I'll open/drive/check ... now /
  directly / and see" with no run started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-07 11:31:36 +01:00
59 changed files with 1169 additions and 165 deletions
+3 -3
View File
@@ -90,7 +90,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **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). Enums in `src/dict/bot-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), 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. 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.
- **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 (cookie `cobble_last_visited_bot_id`, never a workspace conversation) 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`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?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]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **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`; 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, no right panel; `?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]/chatrooms` that workspace's chatrooms; `/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.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it.
@@ -211,10 +211,10 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model, caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
- **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`), 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`). 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`; a long run is told once, `AppData.HarnessStepsLowWarning` steps before the wrap up, to save its report, since the wrap up has no tools) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up).
- **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: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, 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; otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). 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`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, 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. 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). 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). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.16.1",
"version": "0.16.2",
"module": "index.ts",
"type": "module",
"private": true,
+19 -3
View File
@@ -387,10 +387,10 @@ export const AppData = {
HarnessAutoMinScore: 12,
HarnessAutoMinSizeB: 20,
/**
* Models tried per harness call before giving up (pinned plus
* automatic fallbacks).
* Models tried per harness call before giving up (the pick, its
* fallback models, then automatic picks).
*/
HarnessMaxCandidates: 5,
HarnessMaxCandidates: 6,
HarnessRequestTimeoutMs: 3 * 60 * 1000,
/**
* One tool call gives up after this long, whatever the tool is (bot
@@ -405,6 +405,22 @@ export const AppData = {
*/
HarnessCooldownMs: 60 * 1000,
HarnessMaxCooldownMs: 24 * 60 * 60 * 1000,
/**
* How long a model (or a provider, for a bad key or no credits) that
* failed is passed over before it is tried again, provider's
* `Retry-After` included. The install may save its own
* (`harness_model_rest_seconds`, Settings > General), read through
* `grabModelRestMs`. One failure once benched the pinned model for an
* hour and every reply ran on a weak free model meanwhile.
*/
HarnessModelRestMs: 2 * 60 * 1000,
HarnessModelRestMinSeconds: 10,
HarnessModelRestMaxSeconds: 60 * 60,
/**
* Models the text harness tries, in order, after its pick and before
* the automatic free picks (`fallback_model_ids` in its options).
*/
HarnessTextFallbackModelsMax: 3,
/**
* Model turns in one text run before it must stop and report. The
* install may save its own limit (the `harness_max_tool_steps` setting,
+6
View File
@@ -125,6 +125,12 @@ export const RunMaxPromptTokensSettingKey = "run_max_prompt_tokens";
*/
export const HarnessContextBudgetSettingKey = "harness_context_budget_tokens";
/**
* The `app_settings` key holding how long a failed model rests, in
* seconds. Unset means `AppData.HarnessModelRestMs`.
*/
export const HarnessModelRestSettingKey = "harness_model_rest_seconds";
/**
* Vendors preferred for automatic picks, best first. Free models from any
* other vendor come after these, and only if they look competent.
@@ -3,6 +3,7 @@ import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
import {
HarnessContextBudgetSettingKey,
HarnessMaxToolStepsSettingKey,
HarnessModelRestSettingKey,
RunMaxPromptTokensSettingKey,
UnattendedMaxToolStepsSettingKey,
} from "@/src/dict/harness-dict";
@@ -79,17 +80,32 @@ export async function grabContextBudgetTokens() {
});
}
/**
* How long a model that failed is passed over, in seconds: the install's
* own (`harness_model_rest_seconds`), else `AppData.HarnessModelRestMs`.
*/
export async function grabModelRestSeconds() {
return readStepLimit({
saved: await grabAppSetting({ key: HarnessModelRestSettingKey }),
fallback: AppData.HarnessModelRestMs / 1000,
min: AppData.HarnessModelRestMinSeconds,
max: AppData.HarnessModelRestMaxSeconds,
});
}
/**
* Every run limit with its default, for the settings page.
*/
export default async function grabRunLimitsOverview() {
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens] = await Promise.all([
grabHarnessMaxToolSteps(),
grabReplyMaxToolSteps(),
grabUnattendedMaxToolSteps(),
grabRunMaxPromptTokens(),
grabContextBudgetTokens(),
]);
const [task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds] =
await Promise.all([
grabHarnessMaxToolSteps(),
grabReplyMaxToolSteps(),
grabUnattendedMaxToolSteps(),
grabRunMaxPromptTokens(),
grabContextBudgetTokens(),
grabModelRestSeconds(),
]);
const overview: RunLimitsOverview = {
task_steps,
@@ -97,6 +113,7 @@ export default async function grabRunLimitsOverview() {
unattended_steps,
run_tokens,
context_tokens,
model_rest_seconds,
task_default: AppData.HarnessMaxToolSteps,
reply_default: AppData.BotReplyMaxToolSteps,
unattended_default: AppData.UnattendedMaxToolSteps,
@@ -107,6 +124,9 @@ export default async function grabRunLimitsOverview() {
run_tokens_max: AppData.RunMaxPromptTokensMax,
context_tokens_min: AppData.HarnessContextBudgetMinTokens,
context_tokens_max: AppData.HarnessContextBudgetMaxTokens,
model_rest_default: AppData.HarnessModelRestMs / 1000,
model_rest_min: AppData.HarnessModelRestMinSeconds,
model_rest_max: AppData.HarnessModelRestMaxSeconds,
};
return overview;
@@ -0,0 +1,54 @@
import type { LastConversation } from "@/src/types";
import conversationHref from "@/src/utils/conversation-href";
import readLastVisitedBot from "@/src/utils/read-last-visited-bot";
import grabUserConversation, { type UserConversation } from "./grab-user-conversation";
type Params = {
user_id: number | string;
req: Request;
};
/**
* The conversation the last-visited cookie names, for the rail's way back
* on settings and the rail pages, only while the user still reaches it
* (`grabUserConversation`, the conversation pages' own check). A workspace
* conversation the user lost falls back to the bot's own chat; with
* neither, null and the rail shows no way back.
*/
export default async function grabLastConversation({
user_id,
req,
}: Params): Promise<LastConversation | null> {
const visited = readLastVisitedBot({ req });
if (!visited) return null;
const reach = ({ workspace_id }: { workspace_id: number | null }) =>
grabUserConversation({ user_id, bot_id: visited.bot_id, workspace_id }).catch(
() => null,
);
const conversation: UserConversation | null =
(visited.workspace_id ? await reach({ workspace_id: visited.workspace_id }) : null) ||
(await reach({ workspace_id: null }));
if (!conversation) return null;
const { bot, workspace } = conversation;
return {
href: conversationHref({ bot_id: bot.id, workspace_id: workspace?.id }),
bot: {
id: bot.id,
name: bot.name || `Bot ${bot.id}`,
kind: bot.kind || null,
color: bot.color || null,
stone: bot.stone || null,
hue: bot.hue || null,
image_media_id: bot.image_media_id || null,
},
workspace: workspace?.id
? { id: workspace.id, name: workspace.name || `Workspace ${workspace.id}` }
: null,
};
}
@@ -0,0 +1,59 @@
import { AppData } from "@/src/data/app-data";
import type { HarnessKind } from "@/src/dict/harness-dict";
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
import AppError from "@/src/utils/app-error";
import assertHarnessModel from "./assert-harness-model";
type Params = {
harness: HarnessKind;
/**
* The options the setting row holds now (`{}` for a new row).
*/
existing: Record<string, unknown>;
/**
* The picked model, never also a fallback.
*/
model_id: number | null;
voice?: string;
sees_images?: boolean;
fallback_model_ids?: number[];
params?: Record<string, number | string>;
};
/**
* A harness setting's options as the settings forms save them: what the
* row held beyond the form's own fields, then the voice (speech), whether
* the text model reads images itself, the text harness's fallback models
* (each checked like a pick, on any provider) and the generation settings.
*/
export default async function buildHarnessSettingOptions({
harness,
existing,
model_id,
voice,
sees_images,
fallback_model_ids = [],
params = {},
}: Params) {
const { voice: _voice, sees_images: _sees, fallback_model_ids: _fallbacks, ...options } = existing;
const fallbacks =
harness == "text" ? [...new Set(fallback_model_ids)].filter((id) => id != model_id) : [];
if (fallbacks.length > AppData.HarnessTextFallbackModelsMax) {
throw new AppError(`Pick at most ${AppData.HarnessTextFallbackModelsMax} fallback models.`);
}
for (const id of fallbacks) {
await assertHarnessModel({ harness, model_id: id });
}
return withHarnessParameters({
options: {
...options,
...(voice ? { voice } : {}),
...(harness == "text" && sees_images ? { sees_images: true } : {}),
...(fallbacks.length ? { fallback_model_ids: fallbacks } : {}),
},
params,
});
}
@@ -9,10 +9,19 @@ type Params = {
message_ids: number[];
};
/**
* A text call that a model answered in place of one ahead of it: one
* failed during the call, or was passed over while resting.
*/
const FellBackSql = `(harness = 'text' AND (
COALESCE(json_array_length(json_extract(settings, '$.fell_back_from')), 0) > 0
OR COALESCE(json_array_length(json_extract(settings, '$.resting')), 0) > 0))`;
/**
* What each of these messages cost, summed over every model call it took
* (chat turns, media readings, image generations). This is what a
* message's token line shows.
* (chat turns, media readings, image generations), and the fallback model
* that answered for it, if one did. This is what a message's token line
* shows.
*/
export default async function grabMessageUsage({ message_ids }: Params) {
const totals = new Map<number, TokenUsageSummary>();
@@ -26,12 +35,16 @@ export default async function grabMessageUsage({ message_ids }: Params) {
completion_tokens: number | null;
cost: number | null;
calls: number;
fallback_model: string | null;
fallback_calls: number | null;
}>({
sql: `SELECT message_id,
SUM(prompt_tokens) AS prompt_tokens,
SUM(completion_tokens) AS completion_tokens,
SUM(cost) AS cost,
COUNT(*) AS calls
COUNT(*) AS calls,
MAX(CASE WHEN ${FellBackSql} THEN model_slug END) AS fallback_model,
SUM(CASE WHEN ${FellBackSql} THEN 1 ELSE 0 END) AS fallback_calls
FROM token_usages
WHERE message_id IN (${ids.map(() => "?").join(", ")})
GROUP BY message_id`,
@@ -49,6 +62,9 @@ export default async function grabMessageUsage({ message_ids }: Params) {
total_tokens: prompt_tokens + completion_tokens,
...(Number.isFinite(cost) && cost > 0 ? { cost } : {}),
calls: Number(row.calls) || 0,
...(row.fallback_model
? { fallback_model: row.fallback_model, fallback_calls: Number(row.fallback_calls) || 1 }
: {}),
});
}
@@ -6,20 +6,26 @@ type Params = {
req: Request;
res: Response;
bot_id: number | string;
/**
* The workspace the conversation is in; none for the bot's own chat.
*/
workspace_id?: number | string | null;
};
/**
* The page's response with the last-visited cookie set, so `/admin/bots`
* opens this bot's own chat again next time. Called from the conversation
* opens this bot's own chat again next time and the rail on settings and
* the rail pages leads back to this conversation. Called from the conversation
* pages' `res_transform`, which is why it takes and returns the response.
*/
export default function withLastVisitedBotCookies({ req, res, bot_id }: Params): Response {
export default function withLastVisitedBotCookies({ req, res, bot_id, workspace_id }: Params): Response {
const new_res = res.clone();
setCookies(
new_res,
lastVisitedBotCookies({
bot_id,
workspace_id,
secure: isSecureRequest({ req }),
}),
);
+2 -1
View File
@@ -55,13 +55,14 @@ export default async function speakText({
* completion count to read: the call is recorded as it is, with
* the text's length standing in for what was spoken.
*/
on_success: async ({ candidate, failed }) =>
on_success: async ({ candidate, failed, resting }) =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "speech",
candidate,
usage: { prompt_tokens: text.length, completion_tokens: 0 },
failed,
resting,
settings: {
settings_source: setting.source,
voice: voiceFor(candidate),
+2 -1
View File
@@ -51,12 +51,13 @@ export default async function transcribeAudio({
const { result } = await withCandidates<{ text: string; usage?: HarnessUsage }>({
harness: "transcription",
candidates,
on_success: async ({ candidate, result: transcript, failed }): Promise<void> =>
on_success: async ({ candidate, result: transcript, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "transcription",
candidate,
failed,
resting,
usage: transcript.usage,
}),
}),
+2 -1
View File
@@ -63,12 +63,13 @@ export default async function embedText({
const { result, candidate: answered } = await withCandidates<HarnessEmbedResult>({
harness: "embedding",
candidates,
on_success: async ({ candidate, result: embedded, failed }): Promise<void> =>
on_success: async ({ candidate, result: embedded, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "embedding",
candidate,
failed,
resting,
usage: embedded.usage,
}),
}),
+2 -1
View File
@@ -67,12 +67,13 @@ export default async function generateImage({
const { result } = await withCandidates<{ images: HarnessImageOutput[]; usage?: HarnessUsage }>({
harness: edit?.picked ? "image_edit" : "image",
candidates: ordered.map(({ candidate }) => candidate),
on_success: async ({ candidate, result: made, failed }): Promise<void> =>
on_success: async ({ candidate, result: made, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: harness_of.get(candidate.key) || "image",
candidate,
failed,
resting,
usage: made.usage,
}),
}),
+2 -1
View File
@@ -53,13 +53,14 @@ export default async function readImage({ url, focus, signal, bot_id, workspace_
}>({
harness: "vision",
candidates,
on_success: async ({ candidate, result: answer, failed }): Promise<void> =>
on_success: async ({ candidate, result: answer, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "vision",
candidate,
usage: answer.usage,
failed,
resting,
settings: {
settings_source: saved_params.source,
params: flattenSentParams({ params: answer.sent_params }),
+15
View File
@@ -0,0 +1,15 @@
import { AppData } from "@/src/data/app-data";
import { grabModelRestSeconds } from "@/src/functions/backend/db/app-settings/grab-run-limits";
/**
* How long a failed model rests, in ms (`grabModelRestSeconds`). Falls
* back to `AppData.HarnessModelRestMs` when the setting can't be read, so
* a harness call never fails over it.
*/
export default async function grabModelRestMs() {
try {
return (await grabModelRestSeconds()) * 1000;
} catch {
return AppData.HarnessModelRestMs;
}
}
@@ -0,0 +1,49 @@
import logEvent from "@/src/functions/backend/logger";
import type HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
type Params = {
harness: string;
candidate: HarnessCandidate;
error: HarnessError;
/**
* Unix ms it may be tried again, if it rests.
*/
rests_until?: number;
};
/**
* Writes a model's failure to the activity log: which model, what the
* provider said and how long it rests, so a switch to a fallback can be
* explained afterwards. Once per failure, and a resting model isn't tried,
* so an outage logs at most once per rest per model. Never throws.
*/
export default async function logCandidateFailure({ harness, candidate, error, rests_until }: Params) {
const provider = candidate.provider.name || candidate.provider.kind;
const rest = rests_until
? ` It rests for ${Math.max(1, Math.round((rests_until - Date.now()) / 1000))} seconds.`
: " It isn't benched; the next model takes this call.";
try {
await logEvent({
title: "Model failed",
category: "system",
plain_text: `${candidate.model.slug} on ${provider} failed a ${harness} call (${candidate.source} pick): ${error.message}.${rest}`,
details: [
{ label: "Model", value: candidate.model.slug },
{ label: "Provider", value: provider },
{ label: "Pick", value: candidate.source },
{ label: "Status", value: error.status ?? "none" },
],
metadata: {
harness,
candidate_key: candidate.key,
source: candidate.source,
status: error.status,
retryable: error.retryable,
provider_wide: error.provider_wide,
rests_until,
},
});
} catch {}
}
@@ -10,6 +10,7 @@ import harnessModelRowToCatalog from "@/src/functions/backend/db/harness/harness
import resolveProviderConfig from "@/src/functions/backend/db/harness/resolve-provider-config";
import modelServesHarness from "../catalog/model-serves-harness";
import rankAutoModels from "../catalog/rank-auto-models";
import harnessFallbackModelIds from "@/src/utils/harness-fallback-model-ids";
import HarnessError from "../harness-error";
import type {
HarnessCandidate,
@@ -35,12 +36,14 @@ type CatalogEntry = HarnessCatalogModel & {
};
/**
* The models a harness call tries, in order: the pick (the bot's own, else
* the super admin's), then
* (if it has fallback on, or there is no pick) the automatic free picks.
* Only enabled providers with a usable key count, and only the setting's
* provider when it has one. Empty when nothing is
* set up; throws `unavailable` when the harness is turned off.
* The models a harness call tries, in order: the pick (the workspace's,
* the bot's own, else the super admin's), then the setting's fallback
* models in their order (`fallback_model_ids`, each on its own provider),
* then (if it has fallback on, or there is no pick) the automatic free
* picks. Only enabled providers with a usable key count, and only the
* setting's provider for the pick and automatic picks when it has one.
* Empty when nothing is set up; throws `unavailable` when the harness is
* turned off.
*/
export default async function resolveHarnessCandidates({
harness,
@@ -65,25 +68,32 @@ export default async function resolveHarnessCandidates({
if (!providers.size) return [];
const fallback_ids = harnessFallbackModelIds({ options: setting.options }).filter(
(id) => id != setting.model_id,
);
const picked_ids = [setting.model_id ?? 0, ...fallback_ids];
const rows =
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_HARNESS_MODELS>({
sql: `SELECT * FROM harness_models
WHERE available = 1 AND (free = 1 OR id = ?)`,
values: [setting.model_id ?? 0],
WHERE available = 1 AND (free = 1 OR id IN (${picked_ids.map(() => "?").join(", ")}))`,
values: picked_ids,
})
).payload || [];
const entries: CatalogEntry[] = rows.flatMap((row) => {
const toEntry = ({ row, any_provider }: { row: BUN_SQLITE_COBBLE_HARNESS_MODELS; any_provider: boolean }) => {
const provider =
row.provider_id && (!setting.provider_id || row.provider_id == setting.provider_id)
row.provider_id && (any_provider || !setting.provider_id || row.provider_id == setting.provider_id)
? providers.get(row.provider_id)
: undefined;
return provider && row.id
? [{ ...harnessModelRowToCatalog({ row }), row_id: row.id, provider }]
: [];
});
};
const entries: CatalogEntry[] = rows.flatMap((row) => toEntry({ row, any_provider: false }));
const pinned = entries.find(
(entry) =>
@@ -91,8 +101,21 @@ export default async function resolveHarnessCandidates({
modelServesHarness({ model: entry, harness }),
);
/**
* Each fallback model names its own provider, so the setting's
* provider limit doesn't apply to them.
*/
const fallbacks: CatalogEntry[] = fallback_ids.flatMap((id) => {
const row = rows.find((r) => r.id == id);
return row
? toEntry({ row, any_provider: true }).filter((entry) => modelServesHarness({ model: entry, harness }))
: [];
});
const ordered = [
...(pinned ? [{ entry: pinned, source: "pinned" as const }] : []),
...fallbacks.map((entry) => ({ entry, source: "fallback" as const })),
...(!pinned || setting.fallback
? rankAutoModels({ models: entries, harness }).map((entry) => ({
entry,
+113 -2
View File
@@ -4,7 +4,11 @@ import type { HarnessCandidate } from "../types";
import createCooldowns from "./create-cooldowns";
import withCandidates from "./with-candidates";
function candidate(slug: string, provider_id = 1): HarnessCandidate {
function candidate(
slug: string,
provider_id = 1,
source: HarnessCandidate["source"] = "auto",
): HarnessCandidate {
return {
key: `${provider_id}:${slug}`,
provider: {
@@ -18,7 +22,7 @@ function candidate(slug: string, provider_id = 1): HarnessCandidate {
output_modalities: ["text"],
supports_tools: true,
},
source: "auto",
source,
};
}
@@ -173,4 +177,111 @@ describe("withCandidates", () => {
expect(await run(bug)).toBe(bug);
});
test("a failed model rests no longer than the model rest, whatever it was", async () => {
const now = 1_000_000;
const rest_ms = 120_000;
for (const error of [
new HarnessError({ message: "gone", status: 404 }),
new HarnessError({ message: "refused", status: 403 }),
rateLimited("1:a", now + 60 * 60 * 1000),
new HarnessError({ message: "down", status: 503, retryable: true }),
]) {
const cooldowns = createCooldowns();
const a = candidate("a", 1, "pinned");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms,
now: () => now,
run: async (c) => {
if (c == a) throw error;
},
});
expect(cooldowns.get({ key: a.key, now })).toBe(now + rest_ms);
}
});
test("a provider that says to come back sooner rests only that long", async () => {
const now = 1_000_000;
const cooldowns = createCooldowns();
const a = candidate("a");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms: 120_000,
now: () => now,
run: async (c) => {
if (c == a) throw rateLimited(a.key, now + 5_000);
},
});
expect(cooldowns.get({ key: a.key, now })).toBe(now + 5_000);
});
test("a refused request benches nothing", async () => {
const cooldowns = createCooldowns();
const a = candidate("a");
await withCandidates({
harness: "text",
candidates: [a, candidate("b")],
cooldowns,
rest_ms: 120_000,
run: async (c) => {
if (c == a) throw new HarnessError({ message: "bad request", status: 400 });
},
});
expect(cooldowns.get({ key: a.key })).toBeUndefined();
});
test("tells the answer which models failed and which were resting", async () => {
const cooldowns = createCooldowns();
const pinned = candidate("pinned", 1, "pinned");
const first = candidate("first", 2, "fallback");
const second = candidate("second", 3, "fallback");
let seen: { failed: string[]; resting: string[] } | undefined;
cooldowns.set({ key: pinned.key, at: Date.now() + 60_000 });
await withCandidates({
harness: "text",
candidates: [pinned, first, second],
cooldowns,
rest_ms: 120_000,
run: async (c) => {
if (c == first) throw rateLimited(first.key);
},
on_success: ({ failed, resting }) => {
seen = { failed: [...failed], resting: [...resting] };
},
});
expect(seen).toEqual({ failed: [first.key], resting: [pinned.key] });
});
test("a run on an automatic pick goes back to the pick and its fallbacks once they rested", async () => {
const tried: string[] = [];
await withCandidates({
harness: "text",
candidates: [candidate("pinned", 1, "pinned"), candidate("fallback", 2, "fallback"), candidate("free-a"), candidate("free-b")],
prefer_key: "1:free-b",
cooldowns: createCooldowns(),
rest_ms: 120_000,
run: async (c) => {
tried.push(c.model.slug);
if (c.source != "auto") throw rateLimited(c.key);
},
});
expect(tried).toEqual(["pinned", "fallback", "free-b"]);
});
});
+85 -35
View File
@@ -3,15 +3,19 @@ import { Harnesses, type HarnessKind } from "@/src/dict/harness-dict";
import HarnessError from "../harness-error";
import type { HarnessCandidate } from "../types";
import type { HarnessCooldowns } from "./create-cooldowns";
import grabModelRestMs from "./grab-model-rest-ms";
import DefaultCooldowns from "./harness-cooldowns";
import logCandidateFailure from "./log-candidate-failure";
type Params<T> = {
harness: HarnessKind;
candidates: HarnessCandidate[];
run: (candidate: HarnessCandidate) => Promise<T>;
/**
* Tried first when it's a candidate: the model a multi-step run already
* uses, so it doesn't switch models mid-task without a reason.
* The model a multi-step run already uses, so it doesn't switch models
* mid-task without a reason. It goes before the other automatic picks,
* never before the pick or its fallback models: a run that fell back
* goes back to them once they've rested.
*/
prefer_key?: string;
/**
@@ -26,26 +30,32 @@ type Params<T> = {
* The candidates that failed before this one answered, by key.
*/
failed: string[];
/**
* The candidates ahead of this one that were passed over because
* they were resting after an earlier failure, by key.
*/
resting: string[];
}) => Promise<void> | void;
cooldowns?: HarnessCooldowns;
/**
* How long a failed candidate rests. Read from the install's setting
* (`grabModelRestMs`) when not given.
*/
rest_ms?: number;
/**
* Writes each failure to the activity log (`logCandidateFailure`). On
* by default for the process-wide cooldowns, i.e. real calls.
*/
log_failures?: boolean;
now?: () => number;
};
/**
* Bad keys and missing credits keep a provider out this long.
*/
const ProviderCooldownMs = 10 * 60 * 1000;
/**
* A model the provider no longer has (404) or won't serve to us (403)
* stays out this long.
*/
const GoneCooldownMs = 60 * 60 * 1000;
/**
* Runs a harness call on the first candidate that works, in order (the
* preferred one first), up to `AppData.HarnessMaxCandidates` tries.
* Runs a harness call on the first candidate that works, in order
* (`orderCandidates`), up to `AppData.HarnessMaxCandidates` tries.
* Candidates (and providers) on cooldown are skipped; a failure puts its
* candidate, or its whole provider for a key problem, on cooldown.
* candidate, or its whole provider for a key problem, on cooldown for the
* install's model rest (`coolDown`) and is logged.
*
* Throws a `HarnessError`: `unavailable` when there is nothing to try,
* otherwise the last failure, `retryable` if any failure was.
@@ -57,6 +67,8 @@ export default async function withCandidates<T>({
prefer_key,
on_success,
cooldowns = DefaultCooldowns,
rest_ms,
log_failures = cooldowns === DefaultCooldowns,
now = Date.now,
}: Params<T>): Promise<{ result: T; candidate: HarnessCandidate }> {
const title = Harnesses.find((h) => h.value == harness)?.title || harness;
@@ -68,10 +80,7 @@ export default async function withCandidates<T>({
});
}
const ordered = [
...candidates.filter((c) => c.key == prefer_key),
...candidates.filter((c) => c.key != prefer_key),
];
const ordered = orderCandidates({ candidates, prefer_key });
const isReady = (candidate: HarnessCandidate) =>
!cooldowns.get({ key: candidate.key, now: now() }) &&
@@ -97,6 +106,9 @@ export default async function withCandidates<T>({
}
const errors: HarnessError[] = [];
const failed: string[] = [];
const resting: string[] = [];
const rest = rest_ms ?? (await grabModelRestMs());
for (const candidate of ordered) {
if (errors.length >= AppData.HarnessMaxCandidates) break;
@@ -104,16 +116,15 @@ export default async function withCandidates<T>({
/**
* Checked each time: a failure can bench the rest of its provider.
*/
if (!isReady(candidate)) continue;
if (!isReady(candidate)) {
resting.push(candidate.key);
continue;
}
try {
const result = await run(candidate);
await on_success?.({
candidate,
result,
failed: errors.flatMap((e) => (e.candidate_key ? [e.candidate_key] : [])),
});
await on_success?.({ candidate, result, failed, resting });
return { result, candidate };
} catch (error: unknown) {
@@ -121,7 +132,13 @@ export default async function withCandidates<T>({
if (error.code == "aborted") throw error;
errors.push(error);
coolDown({ candidate, error, cooldowns, now: now() });
failed.push(candidate.key);
const rests_until = coolDown({ candidate, error, cooldowns, now: now(), rest_ms: rest });
if (log_failures) {
await logCandidateFailure({ harness, candidate, error, rests_until });
}
}
}
@@ -155,33 +172,66 @@ function providerKey(candidate: HarnessCandidate) {
return `provider:${candidate.provider.id ?? candidate.provider.base_url}`;
}
/**
* The order candidates are tried in: as resolved (the pick, its fallback
* models, then the automatic picks), with the model a run already uses
* moved ahead of the other automatic picks.
*/
function orderCandidates({
candidates,
prefer_key,
}: {
candidates: HarnessCandidate[];
prefer_key?: string;
}) {
const preferred = candidates.find((c) => c.key == prefer_key);
if (!preferred || preferred.source != "auto") return candidates;
return [
...candidates.filter((c) => c.source != "auto"),
preferred,
...candidates.filter((c) => c.source == "auto" && c != preferred),
];
}
/**
* Benches a failed candidate (or its whole provider, for a bad key or no
* credits) for `rest_ms`, or until the provider says to come back when
* that's sooner. A request the model refused (400, 422) benches nothing:
* it's about that request. Returns when it may be tried again, if benched.
*/
function coolDown({
candidate,
error,
cooldowns,
now,
rest_ms,
}: {
candidate: HarnessCandidate;
error: HarnessError;
cooldowns: HarnessCooldowns;
now: number;
rest_ms: number;
}) {
const until = now + rest_ms;
if (error.provider_wide) {
cooldowns.set({ key: providerKey(candidate), at: now + ProviderCooldownMs });
return;
cooldowns.set({ key: providerKey(candidate), at: until });
return until;
}
if (error.retryable) {
const at = error.retry_at || now + AppData.HarnessCooldownMs;
const at = Math.min(Math.max(error.retry_at || until, now), until);
cooldowns.set({
key: candidate.key,
at: Math.min(at, now + AppData.HarnessMaxCooldownMs),
});
return;
cooldowns.set({ key: candidate.key, at });
return at;
}
if (error.status == 403 || error.status == 404) {
cooldowns.set({ key: candidate.key, at: now + GoneCooldownMs });
cooldowns.set({ key: candidate.key, at: until });
return until;
}
return undefined;
}
+2 -1
View File
@@ -96,13 +96,14 @@ export default async function generateText({
harness: "text",
candidates: resolved,
prefer_key,
on_success: async ({ candidate: answered, result: answer, failed }): Promise<void> =>
on_success: async ({ candidate: answered, result: answer, failed, resting }): Promise<void> =>
await recordHarnessUsage({
call: buildUsageCall({
harness: "text",
candidate: answered,
usage: answer.usage,
failed,
resting,
settings: {
...(saved_params ? { settings_source: saved_params.source } : {}),
params: flattenSentParams({ params: answer.sent_params }),
+2 -1
View File
@@ -5,6 +5,7 @@ import TaskTimeoutError from "@/src/utils/task-timeout-error";
import withTimeout from "@/src/utils/with-timeout";
import HarnessError from "../harness-error";
import unknownToolArgs from "./unknown-tool-args";
import unknownToolMessage from "./unknown-tool-message";
import type { HarnessTool, HarnessToolCall, HarnessToolImage } from "../types";
type Params = {
@@ -47,7 +48,7 @@ async function runTool({ call, tools, signal }: Params) {
const tool = tools.find((t) => t.name == call.name);
if (!tool) {
return `Error: There is no tool called "${call.name}". Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
return unknownToolMessage({ name: call.name, tools });
}
let raw: unknown;
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test";
import unknownToolMessage from "./unknown-tool-message";
describe("unknownToolMessage", () => {
test("lists the tools for an unknown tool", () => {
expect(unknownToolMessage({ name: "nope", tools: [{ name: "a" }, { name: "b" }] })).toBe(
`Error: There is no tool called "nope". Available: a, b.`,
);
});
test("points a reply's browser call to start_task", () => {
const text = unknownToolMessage({ name: "browser_navigate", tools: [{ name: "start_task" }] });
expect(text).toContain("only exist in a task on a computer");
expect(text).toContain("call start_task");
});
test("says where computer tools live without offering start_task when there is none", () => {
const text = unknownToolMessage({ name: "computer_bash", tools: [{ name: "list_files" }] });
expect(text).toContain("only exist in a task on a computer");
expect(text).not.toContain("start_task");
});
});
+35
View File
@@ -0,0 +1,35 @@
import type { HarnessTool } from "@/src/harness/types";
type Params = {
name: string;
tools: Pick<HarnessTool, "name">[];
};
/**
* Computer tools: the app's own shell and file tools and Playwright MCP's
* browser tools, which only a task run on a computer has.
*/
const ComputerToolPattern = /^(?:computer_|browser_)/;
/**
* What a call to a tool the run doesn't have gets back. A computer or
* browser tool called from a run without one (a chat reply, seeing them in
* its history's app records) is told to start a task: a weak model called
* `browser_navigate` from a reply three times, then told the user it had
* no browser.
*/
export default function unknownToolMessage({ name, tools }: Params) {
const available = `Available: ${tools.map((t) => t.name).join(", ") || "none"}.`;
if (!ComputerToolPattern.test(name)) {
return `Error: There is no tool called "${name}". ${available}`;
}
const can_start = tools.some((t) => t.name == "start_task");
return `Error: There is no tool called "${name}" here: computer and browser tools only exist in a task on a computer.${
can_start
? " To use the computer or its browser (an open tab, a site the user is logged in to), call start_task with a clear brief, then tell the user what you're doing. You can use the computer that way; never say you can't."
: ""
} ${available}`;
}
+4 -2
View File
@@ -175,9 +175,11 @@ export type HarnessCandidate = {
provider: HarnessProviderConfig;
model: HarnessModelInfo;
/**
* `pinned`: the super admin's pick. `auto`: an automatic free pick.
* `pinned`: the setting's pick. `fallback`: one of the setting's
* fallback models, tried in order after it. `auto`: an automatic free
* pick.
*/
source: "pinned" | "auto";
source: "pinned" | "fallback" | "auto";
};
export type HarnessUsage = {
+7 -2
View File
@@ -10,11 +10,15 @@ type Params = {
* whose they were. The model's source and the fallback are filled in
* here.
*/
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from">;
settings?: Omit<HarnessCallSettings, "model_source" | "fell_back_from" | "resting">;
/**
* The candidates that failed before this one (`withCandidates`).
*/
failed?: string[];
/**
* The candidates ahead of it passed over while resting.
*/
resting?: string[];
};
/**
@@ -23,7 +27,7 @@ type Params = {
* still get a row (no tokens), so a call is never invisible. Its settings
* say how it was made, for a message's details.
*/
export default function buildUsageCall({ harness, candidate, usage, settings, failed }: Params): HarnessUsageCall {
export default function buildUsageCall({ harness, candidate, usage, settings, failed, resting }: Params): HarnessUsageCall {
return {
harness,
provider_id: candidate.provider.id,
@@ -38,6 +42,7 @@ export default function buildUsageCall({ harness, candidate, usage, settings, fa
model_source: candidate.source,
...settings,
...(failed?.length ? { fell_back_from: failed } : {}),
...(resting?.length ? { resting } : {}),
},
};
}
+15 -2
View File
@@ -32,9 +32,10 @@ export type HarnessUsageScope = {
*/
export type HarnessCallSettings = {
/**
* `pinned`: the model picked in the setting. `auto`: an automatic pick.
* `pinned`: the model picked in the setting. `fallback`: one of its
* fallback models. `auto`: an automatic pick.
*/
model_source: "pinned" | "auto";
model_source: "pinned" | "fallback" | "auto";
/**
* Whose setting the call used: the workspace's, the bot's own or the
* install's default. Left out when the call overrode it.
@@ -55,6 +56,11 @@ export type HarnessCallSettings = {
* answered, in the order they were tried.
*/
fell_back_from?: string[];
/**
* The candidates ahead of this one passed over because they were
* resting after an earlier failure, in order.
*/
resting?: string[];
};
export type HarnessUsageCall = {
@@ -94,4 +100,11 @@ export type TokenUsageSummary = {
* How many model calls it took.
*/
calls: number;
/**
* Messages only: a model that answered text calls in place of the one
* ahead of it (it failed or was resting), and how many calls it
* answered so. Left out when every text call ran on the first choice.
*/
fallback_model?: string;
fallback_calls?: number;
};
@@ -0,0 +1,60 @@
import Link from "@moduletrace/twui/layout/Link";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { ArrowLeft } from "lucide-react";
import { twMerge } from "tailwind-merge";
import BotAvatar from "@/src/components/general/bot-avatar";
import type { LastConversation } from "@/src/types";
import botStoneProps from "@/src/utils/bot-stone-props";
type Props = {
conversation: LastConversation;
};
/**
* Above the rail's list on settings and the rail pages: back to the
* conversation this browser was last in, the bot's own chat or a
* workspace's (named under the bot). The logo still goes to `/admin/bots`.
* Avatar only when the rail collapses. The stone stays idle: this row
* isn't live, so it never shows a status it can't keep current.
*/
export default function RailLastConversation({ conversation }: Props) {
const { bot, workspace, href } = conversation;
const title = workspace
? `Back to ${bot.name} in ${workspace.name}`
: `Back to ${bot.name}`;
return (
<Stack className="shrink-0 gap-0! items-stretch px-2 @rail:px-3 pb-3">
<Link
href={href}
title={title}
aria-label={title}
className={twMerge(
"flex shrink-0 h-14 items-center gap-3 rounded-default px-1 @rail:px-3 leading-normal text-ink",
"border-0 @rail:border @rail:border-solid @rail:border-hairline",
"hover:opacity-100 hover:bg-sunken transition-colors duration-[var(--m-fast)]",
"focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper",
)}
>
<Span className="hidden @rail:flex shrink-0 items-center justify-center text-ink-secondary">
<ArrowLeft size={16} aria-hidden />
</Span>
<Span className="shrink-0 flex items-center justify-center mx-auto @rail:mx-0">
<BotAvatar
image_media_id={bot.image_media_id}
{...botStoneProps({ color: bot.color, stone: bot.stone, hue: bot.hue })}
/>
</Span>
<Stack className="hidden @rail:flex grow min-w-0 gap-0!">
<Span className="w-full text-sm font-bold leading-5 text-ink truncate">
{bot.name}
</Span>
<Span className="w-full text-xs leading-4 text-ink-secondary truncate">
{workspace ? `In ${workspace.name}` : "Back to the conversation"}
</Span>
</Stack>
</Link>
</Stack>
);
}
+8 -3
View File
@@ -8,6 +8,7 @@ import useLiveWorkspaces from "../(hooks)/use-live-workspaces";
import { RailPages } from "@/src/dict/rail-pages-dict";
import { RailDrawerContext } from "../(data)/rail-drawer-context";
import RailHeader from "../(partials)/rail-header";
import RailLastConversation from "../(partials)/rail-last-conversation";
import RailPagesList from "../(partials)/rail-pages-list";
import RailCrewList from "../(partials)/rail-crew-list";
import RailSettingsAside from "../(partials)/rail-settings-aside";
@@ -17,9 +18,10 @@ import RailWorkspaceList from "../(partials)/rail-workspace-list";
/**
* Left rail: wordmark and Add, then the crew (pinned coordinator first,
* the latest bots, the workspaces). Inside a workspace it lists that
* workspace's crew instead; on `/admin/settings/*` a back link and the
* settings sub pages, and on routines, activity and help a back link and
* those pages (`RailPages`). Below `md` it is a slide-over drawer from the
* workspace's crew instead; on `/admin/settings/*` the settings sub pages,
* and on routines, files, usage, activity and help those pages
* (`RailPages`), both under a way back to the last conversation
* (`last_conversation`, the bot's own chat or a workspace's). Below `md` it is a slide-over drawer from the
* pane header's menu button; from `md` it is a 64px icon rail, and from
* `lg` the full 260px rail. Its own width, not the viewport's, decides
* whether it shows names (a container query), so the drawer opens full.
@@ -77,6 +79,9 @@ export default function BotsRail() {
}
>
<RailHeader show_add={!is_settings_page && !is_rail_page} />
{(is_settings_page || is_rail_page) && pageProps?.last_conversation ? (
<RailLastConversation conversation={pageProps.last_conversation} />
) : null}
<Stack className="grow min-h-0 overflow-y-auto gap-0! items-stretch px-2 @rail:px-3 pt-1 pb-3">
{is_settings_page ? (
<RailSettingsAside pathname={pathname} />
+11
View File
@@ -8,6 +8,8 @@ import isUnknownSettingsPath from "../utils/is-unknown-settings-path";
import { SettingsDefaultPath } from "../dict/settings-pages-dict";
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
import grabLastConversation from "../functions/backend/db/bot-sessions/grab-last-conversation";
import isPagesRailPath from "../utils/is-pages-rail-path";
/**
* Routing for a local install. There are no public pages:
@@ -17,6 +19,9 @@ import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-i
* - an unknown `/admin/settings/*` page: `/admin/settings/general`
* - `/admin/*` logged out: `/auth/login`
* - `/auth/*` logged in (except logout): `/admin/bots`
*
* Settings and the rail pages also get the conversation this browser was
* last in (`last_conversation`), for their rail's way back.
*/
const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
const { user, user_types } = await userAuth({ req });
@@ -84,6 +89,12 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
user_types,
install_name: await grabInstallName().catch(() => ""),
install_icon: await grabInstallIcon().catch(() => null),
last_conversation:
user?.id && isPagesRailPath({ pathname: url.pathname })
? await grabLastConversation({ user_id: user.id, req }).catch(
() => null,
)
: null,
},
};
};
@@ -9,17 +9,21 @@ type Props = {
/**
* What one answer cost, in the row under it beside its timestamp: the
* tokens every model call behind it spent (a chat turn, reading an image,
* making one), and the price when the provider reported it. The hover
* title breaks it down.
* making one), the price when the provider reported it, and the fallback
* model when one answered in place of the pick. The hover title breaks it
* down.
*/
export default function MessageUsageChip({ usage }: Props) {
if (!usage || usage.total_tokens <= 0) return null;
const { prompt_tokens, completion_tokens, total_tokens, cost, calls } = usage;
const { prompt_tokens, completion_tokens, total_tokens, cost, calls, fallback_model, fallback_calls } = usage;
const title = [
`${formatTokens({ tokens: prompt_tokens })} in, ${formatTokens({ tokens: completion_tokens })} out`,
`${calls} model ${calls == 1 ? "call" : "calls"}`,
typeof cost == "number" && cost > 0 ? `$${cost.toFixed(4)}` : "",
fallback_model
? `${fallback_calls ?? 1} answered by the fallback ${fallback_model}: the model ahead of it failed or was resting`
: "",
]
.filter(Boolean)
.join(" · ");
@@ -30,6 +34,7 @@ export default function MessageUsageChip({ usage }: Props) {
className="text-[11px] leading-4 text-ink-secondary tabular-nums whitespace-nowrap cursor-help"
>
{formatTokens({ tokens: total_tokens })} tokens
{fallback_model ? ` · fallback: ${fallback_model.slice(fallback_model.indexOf("/") + 1)}` : ""}
</Span>
);
}
@@ -17,6 +17,7 @@ type Values = {
unattended_steps: string;
run_tokens: string;
context_tokens: string;
model_rest_seconds: string;
};
const valuesOf = (limits?: RunLimitsOverview | null): Values => ({
@@ -25,6 +26,7 @@ const valuesOf = (limits?: RunLimitsOverview | null): Values => ({
unattended_steps: String(limits?.unattended_steps ?? ""),
run_tokens: String(limits?.run_tokens ?? ""),
context_tokens: String(limits?.context_tokens ?? ""),
model_rest_seconds: String(limits?.model_rest_seconds ?? ""),
});
const count = (value?: number) => (value ?? 0).toLocaleString("en-US");
@@ -32,7 +34,7 @@ const count = (value?: number) => (value ?? 0).toLocaleString("en-US");
/**
* How long a bot may work on one run (model turns per task, reply and
* routine or hook call, the prompt tokens one run may spend) and how much
* of its work it resends per turn, saved on its own without a reload. Zero
* of its work it resends per turn, and how long a failed model rests, saved on its own without a reload. Zero
* puts the code's default back for that one.
*/
export default function RunLimitsForm({ limits }: Props) {
@@ -74,6 +76,7 @@ export default function RunLimitsForm({ limits }: Props) {
unattended_steps: Number(values.unattended_steps) || 0,
run_tokens: Number(values.run_tokens) || 0,
context_tokens: Number(values.context_tokens) || 0,
model_rest_seconds: Number(values.model_rest_seconds) || 0,
},
},
).catch(() => null);
@@ -154,6 +157,14 @@ export default function RunLimitsForm({ limits }: Props) {
onChange={change("context_tokens")}
info={`How much a run sends per turn (its prompt, its tools and what it has done so far) before the oldest tool output is cut, whatever the model's window. Smaller costs less per turn; larger lets a bot keep more of what it read. Between ${count(overview?.context_tokens_min)} and ${count(overview?.context_tokens_max)}; 0 uses the default (${count(overview?.context_tokens_default)}).`}
/>
<RunLimitInput
label="Model rest after a failure"
value={values.model_rest_seconds}
max={overview?.model_rest_max}
suffix="seconds"
onChange={change("model_rest_seconds")}
info={`When a model errors or is rate limited, it is passed over for this long and the next model in line answers (its fallback models, then the free picks). Shorter goes back to your pick sooner. Between ${overview?.model_rest_min ?? ""} and ${count(overview?.model_rest_max)}; 0 uses the default (${overview?.model_rest_default ?? ""}).`}
/>
</Stack>
<SettingsSaveBar
dirty={dirty}
@@ -17,7 +17,11 @@ export default function HarnessCurrentModel({ harness }: Props) {
: "Turned off."
: harness.current
? `Now using ${harness.current.name} on ${harness.current.provider_name}${
harness.current.source == "auto" ? ", picked automatically" : ""
harness.current.source == "auto"
? ", picked automatically"
: harness.current.source == "fallback"
? ", a fallback model (the pick isn't available)"
: ""
}.${
harness.candidate_count > 1
? ` ${harness.candidate_count - 1} more to fall back on.`
@@ -0,0 +1,37 @@
import SearchSelect from "@moduletrace/twui/form/SearchSelect";
import type { HarnessModelOption } from "@/src/types";
import harnessFallbackModelOptions, { NoFallbackValue } from "../(utils)/harness-fallback-model-options";
type Props = {
id: string;
/**
* 0-based place in the fallback order.
*/
index: number;
models: HarnessModelOption[];
model_id?: number;
taken: number[];
onChange: (params: { index: number; model_id: number | null }) => void;
};
/**
* One fallback model slot: a searchable pick from every provider, or none.
*/
export default function HarnessFallbackModelSelect({ id, index, models, model_id, taken, onChange }: Props) {
return (
<SearchSelect
id={`${id}-${index}`}
title={`Fallback model ${index + 1}`}
label={`Fallback model ${index + 1}`}
showLabel
placeholder="Search models"
options={harnessFallbackModelOptions({ models, model_id, taken })}
defaultValues={[model_id ? String(model_id) : NoFallbackValue]}
changeHandler={(value) => {
const picked = Array.isArray(value) ? value[0] : value;
onChange({ index, model_id: !picked || picked == NoFallbackValue ? null : Number(picked) });
}}
/>
);
}
@@ -0,0 +1,56 @@
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { AppData } from "@/src/data/app-data";
import type { HarnessModelOption } from "@/src/types";
import HarnessFallbackModelSelect from "./harness-fallback-model-select";
type Props = {
id: string;
/**
* Every model that can do the job, on any provider.
*/
models: HarnessModelOption[];
/**
* The pick, which can't also be a fallback.
*/
model_id: number;
fallback_model_ids: number[];
onChange: (fallback_model_ids: number[]) => void;
};
/**
* The models tried, in order, when the pick fails or rests, before the
* automatic free picks: the filled slots plus one empty one, up to
* `AppData.HarnessTextFallbackModelsMax`. Clearing a slot closes the gap.
*/
export default function HarnessFallbackModels({ id, models, model_id, fallback_model_ids, onChange }: Props) {
const ids = fallback_model_ids.filter((fallback_id) => fallback_id != model_id);
const slots: (number | undefined)[] =
ids.length < AppData.HarnessTextFallbackModelsMax ? [...ids, undefined] : ids;
const change = ({ index, model_id: picked }: { index: number; model_id: number | null }) => {
const next: (number | null)[] = [...ids];
next[index] = picked;
onChange(next.filter((value): value is number => Boolean(value)));
};
return (
<Stack className="w-full gap-2! items-stretch">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{`When the model above fails or is resting, these are tried in order before the free automatic picks. Pick up to ${AppData.HarnessTextFallbackModelsMax}, from any provider.`}
</Span>
{slots.map((slot, index) => (
<HarnessFallbackModelSelect
key={`${index}-${slot ?? "none"}-${ids.join(",")}`}
id={`${id}-fallback`}
index={index}
models={models}
model_id={slot}
taken={[model_id, ...ids.filter((_, other) => other != index)]}
onChange={change}
/>
))}
</Stack>
);
}
@@ -4,6 +4,7 @@ import { HarnessParameterHarnesses } from "@/src/dict/harness-parameter-dict";
import type { HarnessFormValue, HarnessOverview } from "@/src/types";
import SettingsGroup from "../../(partials)/settings-group";
import HarnessCurrentModel from "./harness-current-model";
import HarnessFallbackModels from "./harness-fallback-models";
import HarnessModelSelect from "./harness-model-select";
import HarnessParameterModal from "./harness-parameter-modal";
import HarnessProviderSelect from "./harness-provider-select";
@@ -18,7 +19,7 @@ type Props = {
/**
* One harness: its provider, then its model (narrowed to that provider),
* whether it falls back to the automatic picks (for a harness that has
* the text harness's fallback models (any provider), whether it falls back to the automatic picks (for a harness that has
* them), whether it's on, and its voice for speech, with a sample to hear
* it before saving. On a bot's page the provider select can also use the
* default, which hides the rest.
@@ -82,6 +83,15 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
onChange={(model_id) => onChange({ ...value, model_id, voice: undefined })}
/>
)}
{!value.inherit && value.model_id && harness.harness == "text" ? (
<HarnessFallbackModels
id={id}
models={harness.models}
model_id={value.model_id}
fallback_model_ids={value.fallback_model_ids || []}
onChange={(fallback_model_ids) => onChange({ ...value, fallback_model_ids })}
/>
) : null}
{value.inherit && harness.default ? (
<HarnessCurrentModel harness={{ ...harness, ...harness.default }} />
) : (
@@ -89,8 +99,8 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
)}
{!value.inherit && value.model_id && harness.automatic ? (
<Checkbox
title="Fall back to the automatic picks if this model fails"
label={`Fall back to the automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
title="Fall back to the free automatic picks if this model fails"
label={`${harness.harness == "text" ? "Then fall back" : "Fall back"} to the free automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
checked={value.fallback}
changeHandler={(fallback) => onChange({ ...value, fallback })}
/>
@@ -62,4 +62,15 @@ describe("changedHarnessSettings", () => {
}),
).toEqual([]);
});
test("lists a change to the fallback models, in order", () => {
const with_fallbacks = { ...saved, text: { ...saved.text, model_id: 9, fallback_model_ids: [3, 5] } };
expect(changedHarnessSettings({ form: structuredClone(with_fallbacks), saved: with_fallbacks })).toEqual([]);
expect(
changedHarnessSettings({
form: { ...with_fallbacks, text: { ...with_fallbacks.text, fallback_model_ids: [5, 3] } },
saved: with_fallbacks,
}).map((setting) => setting.harness),
).toEqual(["text"]);
});
});
@@ -32,6 +32,7 @@ function isSame({ a, b }: { a: HarnessFormValue; b?: HarnessFormValue }) {
a.enabled == b!.enabled &&
(a.voice || "") == (b!.voice || "") &&
Boolean(a.sees_images) == Boolean(b!.sees_images) &&
(a.fallback_model_ids || []).join(",") == (b!.fallback_model_ids || []).join(",") &&
paramsKey({ params: a.params }) == paramsKey({ params: b!.params })
);
}
@@ -0,0 +1,37 @@
import type { TWUISelectOptionObject } from "@moduletrace/twui/form/Select";
import type { HarnessModelOption } from "@/src/types";
export const NoFallbackValue = "none";
type Params = {
/**
* Every model that can do the job, on any provider.
*/
models: HarnessModelOption[];
/**
* This slot's model, if any.
*/
model_id?: number;
/**
* The pick and the other slots' models, left out here.
*/
taken: number[];
};
/**
* One fallback slot's options: none, then every model that can do the
* job on any provider (named with its provider), except the ones already
* picked elsewhere.
*/
export default function harnessFallbackModelOptions({ models, model_id, taken }: Params): TWUISelectOptionObject[] {
return [
{ value: NoFallbackValue, title: "None", default: !model_id },
...models
.filter((model) => model.id == model_id || !taken.includes(model.id))
.map((model) => ({
value: String(model.id),
title: `${model.name} · ${model.provider_name}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
default: model.id == model_id,
})),
];
}
@@ -1,4 +1,5 @@
import { harnessParametersFromOptions } from "@/src/dict/harness-parameter-dict";
import harnessFallbackModelIds from "@/src/utils/harness-fallback-model-ids";
import textSeesImages from "@/src/utils/text-sees-images";
import type {
HarnessOverview,
@@ -29,6 +30,7 @@ export default function toHarnessForm({
? harness.options.voice
: undefined,
sees_images: textSeesImages({ options: harness.options }),
fallback_model_ids: harnessFallbackModelIds({ options: harness.options }),
params: harnessParametersFromOptions({
options: harness.options,
}),
@@ -11,8 +11,9 @@ import type { BunextPageServerFn } from "@moduletrace/bunext/types";
* A bot's conversation inside a workspace: the bot works with the
* workspace's context, computers and models. Only the coordinator and the
* workspace's bots have one; anyone else goes back to the workspace
* settings (managers) or their bots. Rendering it records the bot in the
* last-visited cookie, so `/admin/bots` opens its own chat again.
* settings (managers) or their bots. Rendering it records the bot and the
* workspace in the last-visited cookie, so `/admin/bots` opens the bot's
* own chat again and the rail on settings leads back here.
*/
export const server: BunextPageServerFn<PagePropsType> = async (params) => {
const query: PageQueryObject = params.query;
@@ -39,6 +40,7 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
}
const bot_id = props.bot.id;
const workspace_id = props.workspace?.id || null;
await recordBotVisit({ user_id: user.id, bot_id });
@@ -49,7 +51,7 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
return {
props,
res_transform(res) {
return withLastVisitedBotCookies({ req: params.req, res, bot_id });
return withLastVisitedBotCookies({ req: params.req, res, bot_id, workspace_id });
},
};
};
@@ -4,7 +4,7 @@ import grabBotHarnessOverview from "@/src/functions/backend/db/harness/grab-bot-
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
import saveBotHarnessSetting from "@/src/functions/backend/db/harness/save-bot-harness-setting";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
import buildHarnessSettingOptions from "@/src/functions/backend/db/harness/build-harness-setting-options";
import { SaveBotHarnessSettingsRequestSchema } from "@/src/schemas/harness-schema";
import type { BotHarnessOverviewPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
@@ -62,7 +62,6 @@ export const handler: BunextAPIRouteHandler<
for (const setting of settings) {
const existing = await grabHarnessSetting({ harness: setting.harness, bot_id: bot.id });
const { voice, sees_images, ...options } = existing.source == "bot" ? existing.options : {};
await saveBotHarnessSetting({
bot_id: bot.id,
@@ -72,13 +71,14 @@ export const handler: BunextAPIRouteHandler<
provider_id: setting.provider_id,
fallback: setting.fallback,
enabled: setting.enabled,
options: withHarnessParameters({
options: {
...options,
...(setting.voice ? { voice: setting.voice } : {}),
...(setting.harness == "text" && setting.sees_images ? { sees_images: true } : {}),
},
params: setting.params || {},
options: await buildHarnessSettingOptions({
harness: setting.harness,
existing: existing.source == "bot" ? existing.options : {},
model_id: setting.model_id,
voice: setting.voice,
sees_images: setting.sees_images,
fallback_model_ids: setting.inherit ? [] : setting.fallback_model_ids,
params: setting.params,
}),
});
}
+9 -9
View File
@@ -5,7 +5,7 @@ import grabHarnessOverview from "@/src/functions/backend/db/harness/grab-harness
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
import saveHarnessSetting from "@/src/functions/backend/db/harness/save-harness-setting";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
import buildHarnessSettingOptions from "@/src/functions/backend/db/harness/build-harness-setting-options";
import { SaveHarnessSettingsRequestSchema } from "@/src/schemas/harness-schema";
import type { HarnessOverviewPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
@@ -42,7 +42,6 @@ export const handler: BunextAPIRouteHandler<
for (const setting of settings) {
const existing = await grabHarnessSetting({ harness: setting.harness });
const { voice, sees_images, ...options } = existing.options;
await saveHarnessSetting({
harness: setting.harness,
@@ -50,13 +49,14 @@ export const handler: BunextAPIRouteHandler<
provider_id: setting.provider_id,
fallback: setting.fallback,
enabled: setting.enabled,
options: withHarnessParameters({
options: {
...options,
...(setting.voice ? { voice: setting.voice } : {}),
...(setting.harness == "text" && setting.sees_images ? { sees_images: true } : {}),
},
params: setting.params || {},
options: await buildHarnessSettingOptions({
harness: setting.harness,
existing: existing.options,
model_id: setting.model_id,
voice: setting.voice,
sees_images: setting.sees_images,
fallback_model_ids: setting.fallback_model_ids,
params: setting.params,
}),
});
}
+10 -4
View File
@@ -8,6 +8,7 @@ import { BotReplyMaxToolStepsSettingKey } from "@/src/dict/bot-dict";
import {
HarnessContextBudgetSettingKey,
HarnessMaxToolStepsSettingKey,
HarnessModelRestSettingKey,
RunMaxPromptTokensSettingKey,
UnattendedMaxToolStepsSettingKey,
} from "@/src/dict/harness-dict";
@@ -20,7 +21,7 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune
/**
* Super admin only: how many model turns a task run, a chat reply and a
* routine run or hook call may take, the prompt tokens one run may spend
* and the working context it keeps. Zero puts the code's default back for
* the working context it keeps and how long a failed model rests. Zero puts the code's default back for
* that one.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>> = async ({
@@ -34,7 +35,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
if (!user?.id) throw new AppError(`Only a super admin can change the run limits.`);
const { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens } = parseWithSchema({
const { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds } = parseWithSchema({
schema: SaveRunLimitsRequestSchema,
data: body,
});
@@ -60,12 +61,17 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
value: context_tokens > 0 ? String(context_tokens) : null,
});
await saveAppSetting({
key: HarnessModelRestSettingKey,
value: model_rest_seconds > 0 ? String(model_rest_seconds) : null,
});
await logEvent({
title: "Bot run limits changed",
category: "system",
user_id: user.id,
plain_text: `User #${user.id} set the tool step limits to ${task_steps || "default"} per task, ${reply_steps || "default"} per chat reply and ${unattended_steps || "default"} per routine or hook call, the tokens per run to ${run_tokens || "default"} and the working context to ${context_tokens || "default"}.`,
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens },
plain_text: `User #${user.id} set the tool step limits to ${task_steps || "default"} per task, ${reply_steps || "default"} per chat reply and ${unattended_steps || "default"} per routine or hook call, the tokens per run to ${run_tokens || "default"}, the working context to ${context_tokens || "default"} and the model rest to ${model_rest_seconds ? `${model_rest_seconds} seconds` : "default"}.`,
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds },
ip_address: grabRequestIP(req),
});
@@ -4,7 +4,7 @@ import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-
import saveWorkspaceHarnessSetting from "@/src/functions/backend/db/harness/save-workspace-harness-setting";
import grabUserWorkspace from "@/src/functions/backend/db/workspaces/grab-user-workspace";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { withHarnessParameters } from "@/src/dict/harness-parameter-dict";
import buildHarnessSettingOptions from "@/src/functions/backend/db/harness/build-harness-setting-options";
import { SaveWorkspaceHarnessSettingsRequestSchema } from "@/src/schemas/harness-schema";
import type { BotHarnessOverviewPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
@@ -60,7 +60,6 @@ export const handler: BunextAPIRouteHandler<
harness: setting.harness,
workspace_id: workspace.id,
});
const { voice, sees_images, ...options } = existing.source == "workspace" ? existing.options : {};
await saveWorkspaceHarnessSetting({
workspace_id: Number(workspace.id),
@@ -70,13 +69,14 @@ export const handler: BunextAPIRouteHandler<
provider_id: setting.provider_id,
fallback: setting.fallback,
enabled: setting.enabled,
options: withHarnessParameters({
options: {
...options,
...(setting.voice ? { voice: setting.voice } : {}),
...(setting.harness == "text" && setting.sees_images ? { sees_images: true } : {}),
},
params: setting.params || {},
options: await buildHarnessSettingOptions({
harness: setting.harness,
existing: existing.source == "workspace" ? existing.options : {},
model_id: setting.model_id,
voice: setting.voice,
sees_images: setting.sees_images,
fallback_model_ids: setting.inherit ? [] : setting.fallback_model_ids,
params: setting.params,
}),
});
}
+23
View File
@@ -50,6 +50,14 @@ export const SaveHarnessSettingsRequestSchema = z.object({
* Text only: the model looks at images itself when it can.
*/
sees_images: z.boolean().optional(),
/**
* Text only: models tried in order after the pick, before
* the automatic picks.
*/
fallback_model_ids: z
.array(z.coerce.number().int().positive())
.max(AppData.HarnessTextFallbackModelsMax, `Pick at most ${AppData.HarnessTextFallbackModelsMax} fallback models.`)
.optional(),
/**
* Generation settings (temperature, reasoning effort, ...).
* Only the ones in `HarnessParameters` are kept.
@@ -131,6 +139,21 @@ export const SaveRunLimitsRequestSchema = z.object({
max: AppData.HarnessContextBudgetMaxTokens,
label: "Working context",
}).default(0),
/**
* Seconds a failed model rests; 0 puts the default back.
*/
model_rest_seconds: z.coerce
.number()
.int()
.refine(
(value) =>
value == 0 ||
(value >= AppData.HarnessModelRestMinSeconds && value <= AppData.HarnessModelRestMaxSeconds),
{
message: `Model rest must be 0 (the default) or between ${AppData.HarnessModelRestMinSeconds} and ${AppData.HarnessModelRestMaxSeconds} seconds.`,
},
)
.default(0),
});
export type SaveRunLimitsRequest = z.infer<typeof SaveRunLimitsRequestSchema>;
+41 -1
View File
@@ -589,7 +589,7 @@ export type HarnessOverview = {
/**
* The first model it would try now, if any.
*/
current?: HarnessModelOption & { source: "pinned" | "auto" };
current?: HarnessModelOption & { source: "pinned" | "fallback" | "auto" };
/**
* How many models it would try in all.
*/
@@ -621,6 +621,11 @@ export type HarnessFormValue = {
* instead of the media reading harness (`textSeesImages`).
*/
sees_images?: boolean;
/**
* Text only: models tried in order after the pick, before the
* automatic picks, on any provider.
*/
fallback_model_ids?: number[];
/**
* Generation settings (temperature, reasoning effort, ...), only the
* ones the picked model takes.
@@ -1293,6 +1298,14 @@ export type RunLimitsOverview = {
run_tokens_max: number;
context_tokens_min: number;
context_tokens_max: number;
/**
* How long a failed model rests right now, in seconds, its default and
* the range the settings page accepts.
*/
model_rest_seconds: number;
model_rest_default: number;
model_rest_min: number;
model_rest_max: number;
};
export type SkillLimitsOverview = {
@@ -1972,6 +1985,27 @@ export type PrecacheManifest = {
files: string[];
};
/**
* A conversation to lead back to from settings and the rail pages: the bot
* (as the rail draws it) and, inside a workspace, that workspace.
*/
export type LastConversation = {
href: string;
bot: {
id: number;
name: string;
kind?: string | null;
color?: string | null;
stone?: string | null;
hue?: string | null;
image_media_id?: number | null;
};
workspace: {
id: number;
name: string;
} | null;
};
export type PagePropsType = {
user?: User | null;
user_types?: BUN_SQLITE_COBBLE_USER_TYPES[] | null;
@@ -2123,6 +2157,12 @@ export type PagePropsType = {
* General, and the root's icon links).
*/
install_icon?: PwaInstallIcon | null;
/**
* The conversation this browser was last in, for the rail's way back
* on settings and the rail pages. Only on those pages, and only while
* the user still reaches it.
*/
last_conversation?: LastConversation | null;
/**
* The release the server is running, for the General settings page.
*/
+6
View File
@@ -11,6 +11,9 @@ describe("claimsWorkUnderWay", () => {
"Creating tasks now. Report follows in the next message.",
"I'll report back with the links once that run completes.",
"I’m checking your inbox now.",
"I'll drive the browser to ideogram.ai directly and see what's there.",
"I'll open the contest page now.",
"I'll go ahead and check the tab right away.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(true);
}
@@ -23,6 +26,9 @@ describe("claimsWorkUnderWay", () => {
"I'm sorry, that contest isn't open any more.",
"I checked the board: 3 web design contests are open.",
"Right now there are 147 open contests.",
"I'll keep that in mind going forward.",
"Want me to check it now? I'll wait for your go-ahead.",
"I'll use the navy palette in the next round.",
]) {
expect(claimsWorkUnderWay({ text })).toBe(false);
}
+6
View File
@@ -15,6 +15,12 @@ const UnderWayPatterns = [
/\b(?:report|results?|details|update)\s+(?:follows|will follow|to follow|coming)\b/i,
/\bin (?:my|the|a) (?:next|following) message\b/i,
/\b(?:when|once) (?:it|that|the (?:run|scan|search|check))(?:'|’)?s? (?:back|done|finished|complete)\b/i,
/**
* "I'll drive the browser to ideogram.ai directly and see what's
* there." A dot inside a word (a domain, a file name) doesn't end the
* sentence.
*/
/\bI(?:'|’)ll\s+(?:now\s+|go\s+ahead\s+and\s+)?(?:drive|open|go|head|browse|navigate|check|look|run|start|search|scan|dig|pull|grab|fetch|try|use)\b(?:[^.!?\n]|\.(?=\S)){0,160}\b(?:and see|see what|right away|straight away|directly|now)\b/i,
];
/**
+18 -3
View File
@@ -7,6 +7,12 @@ const SettingsSources: Record<NonNullable<HarnessCallSettings["settings_source"]
workspace: "The workspace's",
};
const ModelSources: Record<HarnessCallSettings["model_source"], string> = {
pinned: "Picked in the settings",
fallback: "A fallback model from the settings",
auto: "Automatic",
};
type Params = {
settings: HarnessCallSettings;
/**
@@ -19,12 +25,13 @@ type Params = {
* A call's settings as label and value pairs, in the order Settings,
* under Models, lists them: the model's pick, whose settings they were,
* every generation setting sent (by its title), then the token limit, the
* voice and any models that failed before it.
* voice, any models that failed before it and any passed over while
* resting.
*/
export default function describeCallSettings({ settings, harness }: Params) {
const chat = (HarnessParameterHarnesses as readonly string[]).includes(harness);
const rows: { label: string; value: string }[] = [
{ label: "Model pick", value: settings.model_source == "pinned" ? "Picked in the settings" : "Automatic" },
{ label: "Model pick", value: ModelSources[settings.model_source] },
];
if (settings.settings_source) {
@@ -49,9 +56,17 @@ export default function describeCallSettings({ settings, harness }: Params) {
if (settings.fell_back_from?.length) {
rows.push({
label: "Fell back from",
value: settings.fell_back_from.map((key) => key.slice(key.indexOf(":") + 1)).join(", "),
value: settings.fell_back_from.map(slugOfKey).join(", "),
});
}
if (settings.resting?.length) {
rows.push({ label: "Passed over (resting)", value: settings.resting.map(slugOfKey).join(", ") });
}
return rows;
}
function slugOfKey(key: string) {
return key.slice(key.indexOf(":") + 1);
}
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import { AppData } from "@/src/data/app-data";
import harnessFallbackModelIds from "./harness-fallback-model-ids";
describe("harnessFallbackModelIds", () => {
test("keeps distinct positive ids in order", () => {
expect(harnessFallbackModelIds({ options: { fallback_model_ids: [7, "3", 7, -1, 0, 2.5, "x"] } })).toEqual([7, 3]);
});
test("caps the list", () => {
const ids = Array.from({ length: AppData.HarnessTextFallbackModelsMax + 2 }, (_, i) => i + 1);
expect(harnessFallbackModelIds({ options: { fallback_model_ids: ids } })).toHaveLength(
AppData.HarnessTextFallbackModelsMax,
);
});
test("is empty without a list", () => {
expect(harnessFallbackModelIds({ options: {} })).toEqual([]);
expect(harnessFallbackModelIds({ options: { fallback_model_ids: "1,2" } })).toEqual([]);
expect(harnessFallbackModelIds({})).toEqual([]);
});
});
+31
View File
@@ -0,0 +1,31 @@
import { AppData } from "@/src/data/app-data";
type Params = {
/**
* A harness setting's options.
*/
options?: Record<string, unknown>;
};
/**
* The fallback models a text harness setting tries, in order, after its
* pick and before the automatic picks (`fallback_model_ids`): distinct
* positive `harness_models` ids, at most
* `AppData.HarnessTextFallbackModelsMax`. Anything else in the options is
* ignored.
*/
export default function harnessFallbackModelIds({ options }: Params): number[] {
const raw = options?.fallback_model_ids;
if (!Array.isArray(raw)) return [];
const ids: number[] = [];
for (const value of raw) {
const id = Number(value);
if (Number.isInteger(id) && id > 0 && !ids.includes(id)) ids.push(id);
}
return ids.slice(0, AppData.HarnessTextFallbackModelsMax);
}
+22
View File
@@ -0,0 +1,22 @@
import { describe, expect, test } from "bun:test";
import isPagesRailPath from "./is-pages-rail-path";
describe("isPagesRailPath", () => {
test("settings and the rail pages", () => {
expect(isPagesRailPath({ pathname: "/admin/settings" })).toBe(true);
expect(isPagesRailPath({ pathname: "/admin/settings/general" })).toBe(true);
expect(isPagesRailPath({ pathname: "/admin/usage" })).toBe(true);
expect(isPagesRailPath({ pathname: "/admin/routines" })).toBe(true);
expect(isPagesRailPath({ pathname: "/admin/files/bots" })).toBe(true);
expect(isPagesRailPath({ pathname: "/admin/logs" })).toBe(true);
});
test("not the crew's pages", () => {
expect(isPagesRailPath({})).toBe(false);
expect(isPagesRailPath({ pathname: "/admin/bots/3" })).toBe(false);
expect(isPagesRailPath({ pathname: "/admin/workspaces/2/bots/3" })).toBe(false);
expect(isPagesRailPath({ pathname: "/admin/chatrooms" })).toBe(false);
expect(isPagesRailPath({ pathname: "/admin/settingsx" })).toBe(false);
expect(isPagesRailPath({ pathname: "/admin/usagex" })).toBe(false);
});
});
+22
View File
@@ -0,0 +1,22 @@
import { RailPages } from "@/src/dict/rail-pages-dict";
type Params = {
pathname?: string | null;
};
/**
* Whether the page's rail lists pages rather than the crew: settings and
* the rail pages (routines, files, usage, activity, help). Those rails lead
* back to the last conversation (`last_conversation`).
*/
export default function isPagesRailPath({ pathname }: Params): boolean {
if (!pathname) return false;
if (pathname == "/admin/settings" || pathname.startsWith("/admin/settings/")) {
return true;
}
return RailPages.some(
(page) => pathname == page.url || pathname.startsWith(`${page.url}/`),
);
}
+14 -2
View File
@@ -21,10 +21,22 @@ function requestWithCookies(): Request {
describe("last visited bot cookies", () => {
test("round-trip a bot", () => {
expect(readLastVisitedBot({ req: requestWithCookies() })).toEqual({ bot_id: 4 });
expect(readLastVisitedBot({ req: requestWithCookies() })).toEqual({ bot_id: 4, workspace_id: null });
});
test("only the bot cookie is written, never a workspace one", () => {
test("round-trip a workspace conversation in the same cookie", () => {
const res = new Response();
setCookies(res, lastVisitedBotCookies({ bot_id: 4, workspace_id: 9, secure: false }));
const headers = res.headers.getSetCookie();
const req = new Request("http://localhost/admin/settings", {
headers: { Cookie: headers.map((header) => header.split(";")[0]).join("; ") },
});
expect(headers).toHaveLength(1);
expect(readLastVisitedBot({ req })).toEqual({ bot_id: 4, workspace_id: 9 });
});
test("only the bot cookie is written, never a second one", () => {
const res = new Response();
setCookies(res, lastVisitedBotCookies({ bot_id: 4, secure: false }));
const [header, ...others] = res.headers.getSetCookie();
+12 -7
View File
@@ -3,6 +3,10 @@ import type { CookieOptions } from "./cookies";
type Params = {
bot_id: number | string;
/**
* The workspace the conversation is in; none for the bot's own chat.
*/
workspace_id?: number | string | null;
/**
* From `isSecureRequest`, so plain HTTP over a VPN still keeps it.
*/
@@ -10,17 +14,18 @@ type Params = {
};
/**
* The cookie that remembers the bot this browser is in, for `setCookies`:
* read back by `readLastVisitedBot` on the bots' landing page. `HttpOnly`,
* since only the server reads it, and it holds nothing but an id. A
* conversation inside a workspace is never remembered, so the landing page
* always reopens the bot's own chat.
* The cookie that remembers the conversation this browser is in, for
* `setCookies`: `<bot_id>`, or `<bot_id>:<workspace_id>` inside a
* workspace, read back by `readLastVisitedBot`. The bots' landing page uses
* only the bot (it always reopens the bot's own chat); the rail's way back
* from settings and the rail pages uses both. `HttpOnly`, since only the
* server reads it, and it holds nothing but ids.
*/
export default function lastVisitedBotCookies({ bot_id, secure }: Params): CookieOptions[] {
export default function lastVisitedBotCookies({ bot_id, workspace_id, secure }: Params): CookieOptions[] {
return [
{
name: AppData["LastVisitedBotCookieName"],
value: String(bot_id),
value: workspace_id ? `${bot_id}:${workspace_id}` : String(bot_id),
secure,
maxAge: AppData["LastVisitedCookieMaxAgeSeconds"],
},
+4 -1
View File
@@ -36,7 +36,7 @@ export default function parseCallSettings({ json }: Params): HarnessCallSettings
) as Record<string, number | string>;
return {
model_source: value.model_source == "pinned" ? "pinned" : "auto",
model_source: value.model_source == "pinned" ? "pinned" : value.model_source == "fallback" ? "fallback" : "auto",
...(SettingsSources.includes(value.settings_source as SettingsSource)
? { settings_source: value.settings_source as SettingsSource }
: {}),
@@ -46,5 +46,8 @@ export default function parseCallSettings({ json }: Params): HarnessCallSettings
...(Array.isArray(value.fell_back_from)
? { fell_back_from: value.fell_back_from.filter((k): k is string => typeof k == "string") }
: {}),
...(Array.isArray(value.resting)
? { resting: value.resting.filter((k): k is string => typeof k == "string") }
: {}),
};
}
+24 -12
View File
@@ -2,24 +2,36 @@ import { describe, expect, test } from "bun:test";
import parseLastVisitedBot from "./parse-last-visited-bot";
describe("parseLastVisitedBot", () => {
test("a bot id becomes the bot", () => {
expect(parseLastVisitedBot({ bot_id: "3" })).toEqual({ bot_id: 3 });
expect(parseLastVisitedBot({ bot_id: 3 })).toEqual({ bot_id: 3 });
test("a bot id becomes the bot's own chat", () => {
expect(parseLastVisitedBot({ value: "3" })).toEqual({ bot_id: 3, workspace_id: null });
expect(parseLastVisitedBot({ value: 3 })).toEqual({ bot_id: 3, workspace_id: null });
});
test("a bot and workspace become the workspace conversation", () => {
expect(parseLastVisitedBot({ value: "3:7" })).toEqual({ bot_id: 3, workspace_id: 7 });
});
test("a bad workspace part keeps only the bot", () => {
expect(parseLastVisitedBot({ value: "3:" })).toEqual({ bot_id: 3, workspace_id: null });
expect(parseLastVisitedBot({ value: "3:0" })).toEqual({ bot_id: 3, workspace_id: null });
expect(parseLastVisitedBot({ value: "3:abc" })).toEqual({ bot_id: 3, workspace_id: null });
});
test("rejects ids that aren't positive whole numbers", () => {
expect(parseLastVisitedBot({})).toBeNull();
expect(parseLastVisitedBot({ bot_id: null })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "0" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "-1" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "1.5" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "abc" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "1 OR 1=1" })).toBeNull();
expect(parseLastVisitedBot({ bot_id: "99999999999999999999" })).toBeNull();
expect(parseLastVisitedBot({ value: null })).toBeNull();
expect(parseLastVisitedBot({ value: "" })).toBeNull();
expect(parseLastVisitedBot({ value: "0" })).toBeNull();
expect(parseLastVisitedBot({ value: "-1" })).toBeNull();
expect(parseLastVisitedBot({ value: "1.5" })).toBeNull();
expect(parseLastVisitedBot({ value: "abc" })).toBeNull();
expect(parseLastVisitedBot({ value: "1 OR 1=1" })).toBeNull();
expect(parseLastVisitedBot({ value: "99999999999999999999" })).toBeNull();
expect(parseLastVisitedBot({ value: ":7" })).toBeNull();
expect(parseLastVisitedBot({ value: "3:7:9" })).toBeNull();
});
test("trims what a cookie header may carry", () => {
expect(parseLastVisitedBot({ bot_id: " 3 " })).toEqual({ bot_id: 3 });
expect(parseLastVisitedBot({ value: " 3 " })).toEqual({ bot_id: 3, workspace_id: null });
});
});
+24 -9
View File
@@ -2,22 +2,37 @@ import parsePositiveId from "./parse-positive-id";
export type LastVisitedBot = {
bot_id: number;
/**
* The workspace the conversation was in; null for the bot's own chat.
*/
workspace_id: number | null;
};
type Params = {
bot_id?: string | number | null;
/**
* The cookie's value: `<bot_id>`, or `<bot_id>:<workspace_id>` for a
* conversation inside a workspace.
*/
value?: string | number | null;
};
/**
* The bot the last-visited cookie names, or null when it doesn't name one.
* The id is checked to be a positive whole number, so a hand-edited cookie
* never reaches a query; whether the user still reaches that bot's own chat
* is the caller's check.
* The conversation the last-visited cookie names, or null when it doesn't
* name one. Ids are checked to be positive whole numbers, so a hand-edited
* cookie never reaches a query; a bad workspace part drops only the
* workspace. Whether the user still reaches that conversation is the
* caller's check.
*/
export default function parseLastVisitedBot({ bot_id }: Params): LastVisitedBot | null {
const bot = parsePositiveId({ value: bot_id });
export default function parseLastVisitedBot({ value }: Params): LastVisitedBot | null {
if (value === undefined || value === null) return null;
if (bot == null) return null;
const [bot_part, workspace_part, ...rest] = String(value).split(":");
const bot_id = parsePositiveId({ value: bot_part });
return { bot_id: bot };
if (bot_id == null || rest.length) return null;
return {
bot_id,
workspace_id: parsePositiveId({ value: workspace_part }),
};
}
+5 -5
View File
@@ -7,13 +7,13 @@ type Params = {
};
/**
* The bot this browser was last in, from the last-visited cookie (see
* `lastVisitedBotCookies`). Null when it has none, or when it doesn't name
* a bot. Whether the user still reaches that bot's own chat is the caller's
* check: a stale grant must fall back, never redirect.
* The conversation this browser was last in, from the last-visited cookie
* (see `lastVisitedBotCookies`). Null when it has none, or when it doesn't
* name a bot. Whether the user still reaches it is the caller's check: a
* stale grant must fall back, never redirect.
*/
export default function readLastVisitedBot({ req }: Params): LastVisitedBot | null {
return parseLastVisitedBot({
bot_id: getCookie(req, AppData["LastVisitedBotCookieName"]),
value: getCookie(req, AppData["LastVisitedBotCookieName"]),
});
}