Compare commits

...
1 Commits
Author SHA1 Message Date
tben 9f03120526 Share one model bench between the queue and the API, and wake the jobs it parks
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A run-limits save cleared the API bundle's copy of the cooldowns while the queue kept its own benches, so a model set to rest until the setting changed stayed benched until a restart, and the job it deferred slept out its day-long available_at with nothing left to wait for.

The cooldown object now lives on a globalCache slot (cobble.harnessCooldowns), and both the run-limits save and queue startup release the jobs a rest parked ahead of time (releaseRestingBotJobs), sparing any job that really failed a turn.
2026-11-18 08:52:36 +01:00
10 changed files with 189 additions and 7 deletions
+1 -1
View File
@@ -223,7 +223,7 @@ 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`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `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, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; the newest messages are never trimmed; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; only the newest `browser_snapshot` and `browser_find` per browser stay (`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: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.24.1",
"version": "0.24.2",
"module": "index.ts",
"type": "module",
"private": true,
+12 -1
View File
@@ -3,6 +3,7 @@ import { AppData } from "@/src/data/app-data";
import type { BotJobKind } from "@/src/dict/bot-queue-dict";
import claimBotJobs from "@/src/functions/backend/db/bots-queue/claim-bot-jobs";
import releaseWorkerBotJobs from "@/src/functions/backend/db/bots-queue/release-worker-bot-jobs";
import releaseRestingBotJobs from "@/src/functions/backend/db/bots-queue/release-resting-bot-jobs";
import { logError } from "@/src/functions/backend/logger";
import processBotJob from "./process-bot-job";
import reportLostBotJobs from "./report-lost-bot-jobs";
@@ -45,9 +46,19 @@ export default async function botsQueue() {
if (released) {
bunext.bunextLog.info(`Bots queue: released ${released} cut-off job(s)`);
}
/**
* A restart forgets every model rest (the cooldowns are in memory),
* so the jobs one parked would wait for benches that no longer exist.
*/
const woken = await releaseRestingBotJobs();
if (woken) {
bunext.bunextLog.info(`Bots queue: woke ${woken} job(s) parked on a model rest`);
}
} catch (error) {
await logError({
title: "Bots queue couldn't release cut-off jobs",
title: "Bots queue couldn't release held jobs",
error,
}).catch(() => {});
}
@@ -0,0 +1,13 @@
/**
* Wakes the pending jobs a model rest parked ahead of time.
*
* `deferBotJob` pushes `available_at` up to a day out when every model is
* resting with no end, and `claimBotJobs` only claims what is already
* available. Nothing else would ever move it: the benches live in memory, so
* a restart forgets them, and a run-limits save clears them, while the job
* they parked kept sleeping. `last_error IS NULL` keeps a real failure
* backoff out of it: a job deferred for a rest has never failed a turn.
*/
export const ReleaseRestingBotJobsSql = `UPDATE bots_queue SET available_at = ?, updated_at = ?
WHERE status = 'pending' AND last_error IS NULL AND available_at > ?
RETURNING id`;
@@ -0,0 +1,84 @@
import { Database } from "bun:sqlite";
import { beforeEach, describe, expect, test } from "bun:test";
import { ReleaseRestingBotJobsSql } from "./release-resting-bot-jobs-sql";
const db = new Database(":memory:");
const now = 1_800_000_000_000;
beforeEach(() => {
db.run(`DROP TABLE IF EXISTS bots_queue`);
db.run(`CREATE TABLE bots_queue (
id INTEGER PRIMARY KEY,
status TEXT NOT NULL,
available_at INTEGER NOT NULL,
last_error TEXT,
updated_at INTEGER
)`);
});
function insert(row: {
id: number;
status: string;
available_at: number;
last_error?: string | null;
updated_at?: number;
}) {
db.run(
`INSERT INTO bots_queue (id, status, available_at, last_error, updated_at)
VALUES (?, ?, ?, ?, ?)`,
[row.id, row.status, row.available_at, row.last_error ?? null, row.updated_at ?? 0],
);
}
function available(id: number) {
return db.query(`SELECT available_at FROM bots_queue WHERE id = ?`).get(id) as {
available_at: number;
};
}
function release() {
return db.query(ReleaseRestingBotJobsSql).all(now, now, now) as { id: number }[];
}
/**
* A job parked on a model rest must wake when the benches it waited on are
* gone (a run-limits save, a restart), while a job backing off a real failure
* keeps its delay and work in flight is left alone.
*/
describe("ReleaseRestingBotJobsSql", () => {
test("wakes a pending job parked by a rest", () => {
insert({ id: 1, status: "pending", available_at: now + 86_400_000 });
const woken = release();
expect(woken.map((row) => row.id)).toEqual([1]);
expect(available(1).available_at).toBe(now);
});
test("leaves a job backing off a real failure", () => {
insert({ id: 2, status: "pending", available_at: now + 60_000, last_error: "Provider is down" });
expect(release()).toEqual([]);
expect(available(2).available_at).toBe(now + 60_000);
});
test("leaves work in flight, and a job already available", () => {
insert({ id: 3, status: "processing", available_at: now + 86_400_000 });
insert({ id: 4, status: "pending", available_at: now - 1_000 });
expect(release()).toEqual([]);
expect(available(3).available_at).toBe(now + 86_400_000);
expect(available(4).available_at).toBe(now - 1_000);
});
test("wakes every parked job at once", () => {
insert({ id: 5, status: "pending", available_at: now + 86_400_000 });
insert({ id: 6, status: "pending", available_at: now + 3_600_000 });
insert({ id: 7, status: "failed", available_at: now + 86_400_000 });
expect(release().map((row) => row.id).sort()).toEqual([5, 6]);
expect(available(5).available_at).toBe(now);
expect(available(6).available_at).toBe(now);
expect(available(7).available_at).toBe(now + 86_400_000);
});
});
@@ -0,0 +1,23 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { ReleaseRestingBotJobsSql } from "./release-resting-bot-jobs-sql";
/**
* Puts every pending job a model rest parked ahead of time back in the queue
* now, and returns how many woke.
*
* Called where the benches they waited on stop existing: when the run limits
* (and with them the model rest) are saved, and when the queue starts, since
* the cooldowns are in memory and a restart forgets them. Without this the
* job sleeps until its day-long `available_at` cap with nothing left to wait
* for, and the bot shows "Waiting for a free model" over a stopped queue.
*/
export default async function releaseRestingBotJobs() {
const now = Date.now();
const res = await BunSQLite.sql({
sql: ReleaseRestingBotJobsSql,
values: [now, now, now],
});
return res.payload?.length || 0;
}
@@ -0,0 +1,31 @@
import { describe, expect, test } from "bun:test";
import HarnessCooldowns from "./harness-cooldowns";
/**
* The benches must be one store for the whole process. bunext bundles API
* routes and the server entry separately, so a module-scoped map let a
* run-limits save clear the API bundle's copy while the queue kept its own:
* a rest with no end survived the save that was supposed to end it.
*/
describe("HarnessCooldowns", () => {
test("lives on the shared global slot", () => {
const holder = globalThis as Record<symbol, unknown>;
expect(holder[Symbol.for("cobble.harnessCooldowns")]).toBe(HarnessCooldowns);
});
test("a second copy of the module is the same store", async () => {
const specifier = "./harness-cooldowns.ts?bundle=2";
const other = (await import(specifier)).default;
expect(other).toBe(HarnessCooldowns);
HarnessCooldowns.set({ key: "9:test-model", at: Date.now() + 60_000 });
expect(other.get({ key: "9:test-model" })).toBeGreaterThan(Date.now());
other.clear();
expect(HarnessCooldowns.get({ key: "9:test-model" })).toBeUndefined();
});
});
+14 -2
View File
@@ -1,9 +1,21 @@
import globalCache from "@/src/utils/global-cache";
import createCooldowns from "./create-cooldowns";
import type { HarnessCooldowns } from "./create-cooldowns";
/**
* The process-wide cooldowns every harness call shares, so one job's rate
* limit spares the next job the same failed call.
*
* Held on `globalThis`, not in a module variable: bunext bundles API routes
* and the server entry separately, so a module-scoped map let a run-limits
* save (`HarnessCooldowns.clear()`) empty the API bundle's copy while the
* queue kept its own benches, and a rest with no end survived the save that
* was supposed to end it.
*/
const HarnessCooldowns = createCooldowns();
const slot = globalCache<HarnessCooldowns>({ name: "cobble.harnessCooldowns" });
export default HarnessCooldowns;
const HarnessCooldowns = slot.get() || createCooldowns();
slot.set(HarnessCooldowns);
export default HarnessCooldowns;
+8 -1
View File
@@ -17,6 +17,7 @@ import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import { UnlimitedLimit } from "@/src/utils/run-limit";
import HarnessCooldowns from "@/src/harness/resolve/harness-cooldowns";
import releaseRestingBotJobs from "@/src/functions/backend/db/bots-queue/release-resting-bot-jobs";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
@@ -68,6 +69,12 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
*/
HarnessCooldowns.clear();
/**
* The jobs a rest parked ahead of time were waiting on those same
* benches, which just went away: nothing else would wake them.
*/
const released = await releaseRestingBotJobs();
await logEvent({
title: "Bot run limits changed",
category: "system",
@@ -75,7 +82,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<RunLimitsOverview>
plain_text: `User #${user.id} set the tool step limits to ${loggedValue(task_steps)} per task, ${loggedValue(reply_steps)} per chat reply and ${loggedValue(unattended_steps)} per routine or hook call, the tokens per run to ${loggedValue(run_tokens)}, the working context to ${loggedValue(context_tokens)} and the model rest to ${
model_rest_seconds == -1 ? "unlimited" : model_rest_seconds > 0 ? `${model_rest_seconds} seconds` : "default"
}.`,
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds },
metadata: { task_steps, reply_steps, unattended_steps, run_tokens, context_tokens, model_rest_seconds, jobs_released: released },
ip_address: grabRequestIP(req),
});
+2 -1
View File
@@ -19,7 +19,8 @@ type Slot<Value> = {
*/
export type GlobalCacheName =
| "cobble.grabAllEnvs.cache"
| "cobble.grabAppSettings.cache";
| "cobble.grabAppSettings.cache"
| "cobble.harnessCooldowns";
export default function globalCache<Value>({
name,