Compare commits
2
Commits
5ea9b608be
...
da6a73f740
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da6a73f740 | ||
|
|
2afe35954c |
@@ -233,9 +233,9 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
|
||||
- **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.
|
||||
- **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 then works to `AppData.HarnessUnknownContextWindow` (1,000,000) less the answer reserve. That guess is not silent: the model picker marks a model with no declared window, and a provider that refuses the prompt for size stops the run with its own message and the fix (`fatal`, below). Never learn a smaller window into the constant: the provider has the last word.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited; the bench lives on a `globalCache` slot (`cobble.harnessCooldowns`) so a run-limits save clears the copy the queue reads, and that save, like queue startup, wakes the jobs a rest had parked ahead of time (`releaseRestingBotJobs`)), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). A call that only reaches benched models records a failed-call row for each resting candidate (`recordHarnessFailure`, no re-log of the outage) so the message shows why nothing was tried, and its error names Settings > Models; a resting call says how long the wait is ("The next try is possible in 27s."), since told only "trying again shortly" a bot told the user the models were benched until a restart. A failure carries the model the candidate ran on, the request's method and address, and a hint when a 404/405 came back with an empty body (no endpoint there), so the tool's message names the pick instead of leaving the bot to guess it: with only "HTTP 404", a production bot invented a model and its routing. Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `send_reply` for a reply's answer or `start_task` for work a task run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-answer turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and works. So a run whose brief can be wrong is told the tree wins over the brief, and told that handing the rest on with `start_task` is following the plan. `computer_bash` whose command provably only reads (`isReadOnlyCommand`: an allow-listed program and no redirect, no `tee`/`xargs`, no writing git subcommand) is a read here too; any other tool (a write, a bash command that isn't one) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `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`).
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: the working context is the model's declared window less the room its answer needs (`workingContextTokens`: `max_output_tokens` when declared, else a tenth of the window clamped to 8,000-64,000), capped by `grabContextBudgetTokens` when the install sets one (unlimited by default, so the window decides, never a flat share of a guessed window); `fitTranscriptToContext` trims to it, cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output, and a result under `TrimmedKeepChars * 4` is never cut at all (the same note once replaced a 14-character shell answer and the run read nothing for thirty steps); the newest turn's results are cut last, only once everything older is gone; every `AppData.HarnessTrimNoteEvery` trimmed turns the run is told its earlier readings were cut (`contextTrimmedNote`, traced as `trimmed`), since trimming is otherwise invisible and a run re-reads what it thinks it never saw; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`, which says how much of the overage is the app's own instructions and tools and how much is the conversation: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget: "request"`; when the system prompt and tool definitions alone pass the working context it is `over_budget: "static"` instead and `runTextLoop` stops at once with a `HarnessError` (`fatal: true`, `staticPromptOverBudgetNote`: the arithmetic, Settings > Models, a bigger-window model, fewer extensions) rather than trimming every turn and answering from nothing. Only the newest `browser_snapshot` and `browser_find` per browser stay (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP, connector and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, and so are the bot's own tools by family (`groupTools` over `ToolGroups`, `HarnessTool.group`, once they pass `HarnessDeferBuiltinToolsMinChars` and `HarnessDeferBuiltinToolsShare` of the working context, since they are ~100k characters every turn: `load_tools` takes exact names, a family's name or `<prefix>*`, and `WrapUpToolNames`, the closing tools and `load_tools` itself are never deferred); loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`. A provider that embeds a passage and a query differently (NVIDIA's asymmetric models) is told which through `input_type`, from `embedText`'s `purpose`; `embed.ts` finds that out on the first 400 that names the field and remembers it per provider and model for the process. A provider that caps a batch below `AppData.EmbeddingBatchSize` (Alibaba's Model Studio: "batch size is invalid, it should not be larger than 20") is answered by retrying the refused batch at the size it named, remembered per provider and model (`smaller-batch-limit.ts`), so one document's large batch no longer fails the whole ingest.
|
||||
- **Generation settings follow the model:** a model takes only the parameters its provider advertises (`modelAdvertisesParameter`, `src/dict/harness-parameter-dict.ts`); a custom provider's `/models` lists ids only, so its models take none and the form hides the Model settings target. The wire sends only advertised parameters (`grabChatParams`), never a value saved on another model. Switching the model or the provider clears the saved generation settings and voice (`nextHarnessModelValue` / `nextHarnessProviderValue`), so a temperature tuned for one model never rides to another that rejects it.
|
||||
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `send_reply` with work, or `start_task` in a task run (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `send_reply`, `start_task`, `hand_over_task`, `update_requester` (an interim word to the bot that asked while a crew request is open), coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.4",
|
||||
"version": "0.27.5",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -45,6 +45,7 @@ import runTextLoop from "@/src/harness/text/run-text-loop";
|
||||
import type { HarnessTool } from "@/src/harness/types";
|
||||
import grabBotChatTools from "@/src/harness/tools/bot/grab-bot-chat-tools";
|
||||
import gatePlanModeTools from "@/src/harness/tools/bot/plan-mode-tools";
|
||||
import groupTools from "@/src/harness/tools/group-tools";
|
||||
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
|
||||
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
|
||||
import grabRunScopes from "@/src/functions/backend/db/bot-files/grab-run-scopes";
|
||||
@@ -714,7 +715,9 @@ export default async function runBotReply({
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
messages: await messagesToTurns({ messages: history, user_id }),
|
||||
tools: plan_mode ? gatePlanModeTools({ tools: reply_tools }) : reply_tools,
|
||||
tools: plan_mode
|
||||
? gatePlanModeTools({ tools: groupTools({ tools: reply_tools }) })
|
||||
: groupTools({ tools: reply_tools }),
|
||||
max_steps: reply_max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
|
||||
@@ -51,6 +51,7 @@ import openBotExtensions, { type OpenBotExtensions } from "@/src/harness/tools/e
|
||||
import openBotSkills, { type OpenBotSkills } from "@/src/harness/tools/skills/open-bot-skills";
|
||||
import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-knowledgebases";
|
||||
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
|
||||
import groupTools from "@/src/harness/tools/group-tools";
|
||||
import grabCoordinatorKnowledgebaseTools from "@/src/harness/tools/bot/knowledgebases/grab-coordinator-knowledgebase-tools";
|
||||
import isHiddenSession from "@/src/functions/backend/db/bot-sessions/is-hidden-session";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
@@ -696,7 +697,8 @@ export default async function runBotTask({
|
||||
const result = await runTextLoop({
|
||||
system,
|
||||
messages: opening,
|
||||
tools: [
|
||||
tools: groupTools({
|
||||
tools: [
|
||||
...tools,
|
||||
/**
|
||||
* A task report ends with `send_reply`, the same protocol a
|
||||
@@ -727,7 +729,8 @@ export default async function runBotTask({
|
||||
...connectors.tools,
|
||||
...skills.tools,
|
||||
...knowledge.tools,
|
||||
],
|
||||
],
|
||||
}),
|
||||
max_steps,
|
||||
max_prompt_tokens: await grabRunMaxPromptTokens(),
|
||||
context_budget: await grabContextBudgetTokens(),
|
||||
|
||||
+33
-16
@@ -545,15 +545,15 @@ export const AppData = {
|
||||
HarnessAutoMinContext: 32_000,
|
||||
/**
|
||||
* The window a run assumes for a model whose catalog never said
|
||||
* (`run-text-loop.ts`): a custom provider lists ids and nothing else,
|
||||
* and at 32000 the base prompt alone (system and tool definitions,
|
||||
* ~25000 tokens here) was already past the 70% working window, so every
|
||||
* turn trimmed the output the run was reading. 70% of this is the
|
||||
* widest such a model is ever given, whatever
|
||||
* `harness_context_budget_tokens` asks for, so it must stay at or above
|
||||
* that budget.
|
||||
* (`run-text-loop.ts`): a custom provider lists ids and nothing else.
|
||||
* It is a guess, and the provider has the last word: a model that is
|
||||
* smaller refuses a prompt past its real window, and that refusal
|
||||
* stops the run with the provider's own message, which names the
|
||||
* limit to set on the model (`Settings > Models`). Never learn a
|
||||
* smaller window into this: a run that quietly assumed 131072 here
|
||||
* gave a model a 91,750-token working context and went blind.
|
||||
*/
|
||||
HarnessUnknownContextWindow: 131_072,
|
||||
HarnessUnknownContextWindow: 1_000_000,
|
||||
/**
|
||||
* A provider's declared window (`harness_providers.context_length`),
|
||||
* handed to the models it lists without one of their own: the least and
|
||||
@@ -694,15 +694,17 @@ export const AppData = {
|
||||
*/
|
||||
HarnessReplyDraftsMax: 2,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
* output is trimmed, whatever the model's window. Every turn resends
|
||||
* all of it, so a run that only trims at a 1M window pays for its whole
|
||||
* history on every step. The install may save its own
|
||||
* (`harness_context_budget_tokens`), read through
|
||||
* `grabContextBudgetTokens`.
|
||||
* An optional tighter cap on the working context: how many tokens
|
||||
* (estimated) of system prompt, tool definitions and transcript a run
|
||||
* sends per turn before old tool output is trimmed. Unlimited by
|
||||
* default, so the model's own window decides (minus the reserve it
|
||||
* needs for its answer, `workingContextTokens`): an install that
|
||||
* saved `harness_context_budget_tokens` asks for less, for a model
|
||||
* whose window it pays for by the token. Every turn resends all of
|
||||
* it, so a run that only trims at a 1M window pays for its whole
|
||||
* history on every step; that is what this setting is for.
|
||||
*/
|
||||
HarnessContextBudgetTokens: 200_000,
|
||||
HarnessContextBudgetTokens: UnlimitedLimit,
|
||||
/**
|
||||
* The least a saved working context may be: below it a run would trim
|
||||
* the output it is reading right now (one full tool result is ~20000
|
||||
@@ -733,6 +735,21 @@ export const AppData = {
|
||||
* pass this many characters; below it they're simply all given.
|
||||
*/
|
||||
HarnessDeferToolsMinChars: 6000,
|
||||
/**
|
||||
* The bot's own tools (tasks, schedules, hooks, files, plans, crew,
|
||||
* knowledgebases, graphics) are deferred the same way, but only when
|
||||
* they are both this large and past `HarnessDeferBuiltinToolsShare` of
|
||||
* the working context: at 25 tools they were ~33k tokens of every
|
||||
* turn, which on a 131k-window model left the conversation about 50k
|
||||
* to work in. Deferring costs a turn to load them, so a model with a
|
||||
* window that holds them comfortably keeps them inline.
|
||||
*/
|
||||
HarnessDeferBuiltinToolsMinChars: 20_000,
|
||||
/**
|
||||
* Share of the working context the bot's own tool definitions must
|
||||
* pass before they are deferred rather than sent every turn.
|
||||
*/
|
||||
HarnessDeferBuiltinToolsShare: 0.1,
|
||||
/**
|
||||
* How much of a deferred tool's description its line in the list
|
||||
* shows.
|
||||
|
||||
@@ -577,20 +577,50 @@ export const repairedAnswerNote = `_Part of this answer was left out: it describ
|
||||
|
||||
/**
|
||||
* Told once, when the prompt no longer fits the working context even after
|
||||
* everything trimmable was trimmed: what is left is what the user wrote,
|
||||
* which the app never cuts. A run that keeps reading whole files into the
|
||||
* conversation only makes the next turn larger, and its answer is paid for
|
||||
* out of whatever room is left. Told rather than trimming the request: the
|
||||
* model has to know it may not be seeing all of a pasted brief, so it says
|
||||
* what it could not reach instead of inventing the rest.
|
||||
* everything trimmable was trimmed. What is left is the conversation, most
|
||||
* of it what the user wrote, which the app never cuts, and the app's own
|
||||
* instructions and tool definitions, which it cannot cut either. A run that
|
||||
* keeps reading whole files into the conversation only makes the next turn
|
||||
* larger, and its answer is paid for out of whatever room is left. Told
|
||||
* rather than trimming the request: the model has to know it may not be
|
||||
* seeing all of a pasted brief, so it says what it could not reach instead
|
||||
* of inventing the rest.
|
||||
*/
|
||||
export const oversizedRequestNote = ({ budget }: { budget: number }) =>
|
||||
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and none of what is over is yours to trim: the app cuts tool output, never what the user wrote. Every turn resends all of it, so reading more makes the next one worse.
|
||||
export const oversizedRequestNote = ({ budget, base, conversation }: { budget: number; base: number; conversation: number }) =>
|
||||
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and everything the app is allowed to cut has been cut. Of what is left, about ${base.toLocaleString("en-US")} tokens are the app's own instructions and tool definitions, and about ${conversation.toLocaleString("en-US")} are the conversation itself. Every turn resends all of it, so reading more makes the next one worse.
|
||||
|
||||
From here: stop pulling whole files, whole pages or entire command outputs into the conversation. Work from what you already have, read only the piece you need (a line range, a filter, grep), write what must be kept to a file rather than into a message, and answer on this turn.
|
||||
|
||||
If what you need sits in a part of the request you cannot reach in one piece, say plainly what you could and could not read, and ask the user to attach it as a file, put it in a knowledgebase, or point you at a path. A guess presented as a reading of it is worse than saying it was too long.`;
|
||||
|
||||
/**
|
||||
* The failure a run stops on when its instructions and tool definitions
|
||||
* alone are past the working context (`fitTranscriptToContext`'s
|
||||
* `over_budget: "static"`). Nothing can be trimmed into that room, so a
|
||||
* run that went on trimmed every tool result of every turn and answered
|
||||
* from nothing: one read a 14-character shell answer as "Trimmed: 14
|
||||
* characters" for thirty steps. The user is told the arithmetic and where
|
||||
* to fix it, instead of watching a bot go blind.
|
||||
*/
|
||||
export const staticPromptOverBudgetNote = ({
|
||||
working,
|
||||
window,
|
||||
assumed,
|
||||
base,
|
||||
system,
|
||||
tools,
|
||||
}: {
|
||||
working: number;
|
||||
window: number;
|
||||
assumed: boolean;
|
||||
base: number;
|
||||
system: number;
|
||||
tools: number;
|
||||
}) =>
|
||||
`This run stopped before its first answer: the model's working context is about ${working.toLocaleString("en-US")} tokens${assumed ? " (the model declares no context window, so the app assumed one)" : ` (a ${window.toLocaleString("en-US")} token window)`}, and this run's own instructions and tool definitions already take about ${base.toLocaleString("en-US")} of them (system prompt about ${system.toLocaleString("en-US")}, tools about ${tools.toLocaleString("en-US")}), which leaves no room for the conversation. Nothing was trimmed, because trimming could not have helped.
|
||||
|
||||
If the model's real window is bigger than that, set it on its provider in Settings > Models. If it is not, choose a model with a larger window for this bot, or give it fewer extensions (MCP servers, browsers and connectors add tool definitions to every turn).`;
|
||||
|
||||
/**
|
||||
* Told when the app has had to trim earlier tool output from the transcript
|
||||
* (`fitTranscriptToContext`'s `trimmed` count, every
|
||||
|
||||
@@ -70,8 +70,9 @@ export async function grabRunMaxPromptTokens() {
|
||||
/**
|
||||
* The working context a run keeps per turn, in estimated tokens: the
|
||||
* install's own (`harness_context_budget_tokens`), else
|
||||
* `AppData.HarnessContextBudgetTokens`. Unlimited keeps the model's whole
|
||||
* window.
|
||||
* `AppData.HarnessContextBudgetTokens`. Unlimited (the default) keeps the
|
||||
* model's own window, less the reserve its answer needs
|
||||
* (`workingContextTokens`), so this is only a way to hold runs below that.
|
||||
*/
|
||||
export async function grabContextBudgetTokens() {
|
||||
return readRunLimit({
|
||||
|
||||
@@ -56,6 +56,7 @@ export default async function grabHarnessModelEntries({
|
||||
voices: model.voices,
|
||||
input_modalities: model.input_modalities,
|
||||
supported_parameters: model.supported_parameters,
|
||||
context_length: model.context_length,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -14,6 +14,13 @@ export type RunUsageLimits = {
|
||||
steps: RunLimit | null;
|
||||
run_tokens: RunLimit | null;
|
||||
context_tokens: RunLimit | null;
|
||||
/**
|
||||
* How much of the working context the app's own prompt and tool
|
||||
* definitions took before the conversation did, when the run recorded
|
||||
* them: the usual answer to "why was there room for so little".
|
||||
*/
|
||||
system_tokens?: number;
|
||||
tools_tokens?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -137,6 +144,8 @@ const limitsOf = ({ calls }: { calls: RunUsageCall[] }): RunUsageLimits | null =
|
||||
steps: kept(limits.steps),
|
||||
run_tokens: kept(limits.run_tokens),
|
||||
context_tokens: kept(limits.context_tokens),
|
||||
...(typeof limits.system_tokens == "number" ? { system_tokens: limits.system_tokens } : {}),
|
||||
...(typeof limits.tools_tokens == "number" ? { tools_tokens: limits.tools_tokens } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -26,6 +26,12 @@ type Params = {
|
||||
* instead of leaving the bot to guess one.
|
||||
*/
|
||||
model_name?: string;
|
||||
/**
|
||||
* No fallback and no retry can help: another model fails the same way
|
||||
* (or the caller's own prompt is the problem), so the run stops with
|
||||
* this message rather than spending the next candidate on it.
|
||||
*/
|
||||
fatal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -57,6 +63,11 @@ export default class HarnessError extends Error {
|
||||
method?: string;
|
||||
url?: string;
|
||||
model_name?: string;
|
||||
/**
|
||||
* Nothing else can be tried: `withCandidates` rethrows it at once,
|
||||
* without resting the candidate or falling back to another model.
|
||||
*/
|
||||
fatal: boolean;
|
||||
|
||||
constructor({
|
||||
message,
|
||||
@@ -70,6 +81,7 @@ export default class HarnessError extends Error {
|
||||
method,
|
||||
url,
|
||||
model_name,
|
||||
fatal = false,
|
||||
}: Params) {
|
||||
super(message);
|
||||
this.name = "HarnessError";
|
||||
@@ -83,5 +95,6 @@ export default class HarnessError extends Error {
|
||||
this.method = method;
|
||||
this.url = url;
|
||||
this.model_name = model_name;
|
||||
this.fatal = fatal;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import isContextOverflowError from "./is-context-overflow-error";
|
||||
|
||||
describe("isContextOverflowError", () => {
|
||||
test.each([
|
||||
"This model's maximum context length is 131072 tokens",
|
||||
"context_length_exceeded",
|
||||
"The prompt is too long for this model",
|
||||
"Please reduce the length of the messages",
|
||||
"input length and max_tokens exceed the model's context",
|
||||
"This request exceeds the maximum number of tokens",
|
||||
"Your request is 200000 tokens which exceeds the maximum",
|
||||
])("reads %p as a window the prompt went past", (detail) => {
|
||||
expect(isContextOverflowError({ status: 400, detail })).toBe(true);
|
||||
});
|
||||
|
||||
test("a plain 400 about something else is not a context overflow", () => {
|
||||
expect(isContextOverflowError({ status: 400, detail: "Invalid `temperature`: must be between 0 and 2" })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("a server error or a rate limit is never read as one, whatever it says", () => {
|
||||
expect(isContextOverflowError({ status: 500, detail: "maximum context length" })).toBe(false);
|
||||
expect(isContextOverflowError({ status: 429, detail: "context length exceeded" })).toBe(false);
|
||||
});
|
||||
|
||||
test("an empty detail is not one", () => {
|
||||
expect(isContextOverflowError({ status: 400 })).toBe(false);
|
||||
expect(isContextOverflowError({ status: 400, detail: "" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* The shapes providers use when the prompt was too long for the model it
|
||||
* was sent to. Their message carries the real limit and what was sent
|
||||
* ("prompt is too long: 1,038,402 tokens > 1,000,000 maximum"), which is
|
||||
* the only place a model with no declared window states its window.
|
||||
*/
|
||||
const ContextOverflowPhrases = [
|
||||
"maximum context length",
|
||||
"context length exceeded",
|
||||
"context_length_exceeded",
|
||||
"prompt is too long",
|
||||
"reduce the length of the messages",
|
||||
"input length and max_tokens exceed",
|
||||
"exceeds the maximum number of tokens",
|
||||
"maximum number of input tokens",
|
||||
];
|
||||
|
||||
/**
|
||||
* "1,038,402 tokens > 1,000,000 maximum": a count compared against a
|
||||
* limit, which no other kind of 400 phrases that way.
|
||||
*/
|
||||
const OverLimitTokens = /\b\d[\d,]{2,}\s*tokens?\b[^.]{0,30}\b(maximum|max|limit)\b/;
|
||||
|
||||
type Params = {
|
||||
status: number;
|
||||
/**
|
||||
* The provider's own words, already read out of its error body.
|
||||
*/
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a provider refused a call because the prompt did not fit its
|
||||
* model. A 400 usually means "only another model can help", but this one
|
||||
* means the window this run was sized for is too big: no fallback model
|
||||
* and no retry fixes it, and the message says what the real limit is
|
||||
* (`isContextOverflowError` -> `toHarnessError`).
|
||||
*/
|
||||
export default function isContextOverflowError({ status, detail }: Params) {
|
||||
if (status != 400 && status != 413 && status != 422) return false;
|
||||
|
||||
const text = (detail || "").toLowerCase();
|
||||
|
||||
return ContextOverflowPhrases.some((phrase) => text.includes(phrase)) || OverLimitTokens.test(text);
|
||||
}
|
||||
@@ -159,4 +159,32 @@ describe("toHarnessError", () => {
|
||||
|
||||
expect(error.message.match(/images\/generations/g)?.length).toBe(1);
|
||||
});
|
||||
|
||||
test("a prompt past the model's window is fatal, keeps the provider's limit and says what to set", () => {
|
||||
const error = toHarnessError({
|
||||
status: 400,
|
||||
body: JSON.stringify({
|
||||
error: { message: "This model's maximum context length is 65536 tokens. However, your messages resulted in 99812 tokens." },
|
||||
}),
|
||||
provider_name: "Nvidia Cloud",
|
||||
});
|
||||
|
||||
expect(error.fatal).toBe(true);
|
||||
expect(error.retryable).toBe(false);
|
||||
expect(error.provider_wide).toBe(false);
|
||||
expect(error.message).toContain("maximum context length is 65536 tokens");
|
||||
expect(error.message).toContain("Set this model's context window under Settings > Models");
|
||||
expect(error.message).toContain("assumed to have 1,000,000");
|
||||
});
|
||||
|
||||
test("any other 400 is only about the model, never fatal", () => {
|
||||
const error = toHarnessError({
|
||||
status: 400,
|
||||
body: JSON.stringify({ error: { message: "temperature is not supported" } }),
|
||||
provider_name: "Example",
|
||||
});
|
||||
|
||||
expect(error.fatal).toBe(false);
|
||||
expect(error.message).not.toContain("Settings > Models");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import HarnessError from "../harness-error";
|
||||
import isContextOverflowError from "./is-context-overflow-error";
|
||||
import parseRetryAt from "./parse-retry-at";
|
||||
import redactProviderError from "./redact-provider-error";
|
||||
|
||||
@@ -26,6 +27,8 @@ type Params = {
|
||||
* the same way, so it is `provider_wide`
|
||||
* - 408, 409, 425, 429, 5xx: `retryable`, with `retry_at` when the
|
||||
* provider says
|
||||
* - a 400 saying the prompt did not fit the model's window: `fatal`, and
|
||||
* the run stops with the provider's own limit (`isContextOverflowError`)
|
||||
* - anything else (400, 403, 404, 422): only another model can help. A
|
||||
* 403 is about the model (OpenRouter refuses some free models to most
|
||||
* apps), not the key
|
||||
@@ -54,12 +57,26 @@ export default function toHarnessError({
|
||||
address = addressText({ detail, method, url }),
|
||||
hint = missing_endpoint ? " - no endpoint at that address; check the provider's base URL" : "";
|
||||
|
||||
/**
|
||||
* A prompt that did not fit the model's window is the one 400 no
|
||||
* fallback model or retry fixes: the run was sized for a window this
|
||||
* model does not have, and the provider has just said what it is. The
|
||||
* run stops with this message, so the user reads the real limit rather
|
||||
* than a bot that trimmed every result and answered from nothing.
|
||||
*/
|
||||
const overflow = isContextOverflowError({ status, detail: provider_detail });
|
||||
|
||||
const advice = overflow
|
||||
? "\nSet this model's context window under Settings > Models: a model with none declared is assumed to have 1,000,000."
|
||||
: "";
|
||||
|
||||
const retryable = [408, 409, 425, 429].includes(status) || status >= 500;
|
||||
|
||||
return new HarnessError({
|
||||
message: redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, 400),
|
||||
message: `${redactProviderError({ text: `${provider_name}: ${detail}${address}${hint}` }).slice(0, overflow ? 320 : 400)}${advice}`,
|
||||
status,
|
||||
retryable,
|
||||
fatal: overflow,
|
||||
retry_at: retryable && headers ? parseRetryAt({ headers }) : undefined,
|
||||
provider_wide: status == 401 || status == 402,
|
||||
candidate_key,
|
||||
|
||||
@@ -70,6 +70,36 @@ describe("withCandidates", () => {
|
||||
expect(tried).toEqual(["b"]);
|
||||
});
|
||||
|
||||
test("a fatal failure is thrown at once, with no fallback and nothing rested", async () => {
|
||||
const cooldowns = createCooldowns();
|
||||
const tried: string[] = [];
|
||||
const a = candidate("a");
|
||||
const b = candidate("b");
|
||||
const fatal = new HarnessError({
|
||||
message: "prompt is too long for this model",
|
||||
status: 400,
|
||||
fatal: true,
|
||||
candidate_key: a.key,
|
||||
});
|
||||
|
||||
const call = withCandidates({
|
||||
harness: "text",
|
||||
candidates: [a, b],
|
||||
cooldowns,
|
||||
run: async (c) => {
|
||||
tried.push(c.model.slug);
|
||||
throw fatal;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(call).rejects.toBe(fatal);
|
||||
|
||||
// A smaller window is not a fault of the model: no other model can
|
||||
// answer the same prompt, so none is tried and none is rested.
|
||||
expect(tried).toEqual(["a"]);
|
||||
expect(cooldowns.get({ key: a.key })).toBeUndefined();
|
||||
});
|
||||
|
||||
test("tries the preferred model first", async () => {
|
||||
const tried: string[] = [];
|
||||
|
||||
|
||||
@@ -69,7 +69,8 @@ type Params<T> = {
|
||||
* 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.
|
||||
* otherwise the last failure, `retryable` if any failure was. A `fatal`
|
||||
* failure is rethrown at once: no cooldown, no next candidate.
|
||||
*/
|
||||
export default async function withCandidates<T>({
|
||||
harness,
|
||||
@@ -166,6 +167,27 @@ export default async function withCandidates<T>({
|
||||
} catch (error: unknown) {
|
||||
if (!(error instanceof HarnessError)) throw error;
|
||||
if (error.code == "aborted") throw error;
|
||||
/**
|
||||
* A fatal failure is the run's own: another model fails the same
|
||||
* way, and the message (the provider's own limit, or the app's
|
||||
* arithmetic on a window) is what the user needs to read. It
|
||||
* rests nothing and falls back to nothing. It is still written
|
||||
* down as a failed call, so the notice the message carries can
|
||||
* say which model refused it and why.
|
||||
*/
|
||||
if (error.fatal) {
|
||||
error.model_name ||= candidate.model.slug;
|
||||
|
||||
if (log_failures) {
|
||||
await recordHarnessFailure({
|
||||
harness: harness_of?.get(candidate.key) || harness,
|
||||
candidate,
|
||||
error,
|
||||
});
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's own name goes on the failure: a tool tells the bot
|
||||
|
||||
@@ -3,14 +3,30 @@ import type { HarnessTool } from "../types";
|
||||
import { LoadToolsToolName } from "../tools/load-tools-tool";
|
||||
|
||||
/**
|
||||
* The system prompt's list of the tools a run may load (`load_tools`):
|
||||
* each by name with the start of its description, so the model knows
|
||||
* what is there without every definition riding along on each turn.
|
||||
* The system prompt's list of the tools a run may load (`load_tools`): the
|
||||
* bot's own tools by family, each with the names in it, and every extension
|
||||
* tool by name with the start of its description, so the model knows what is
|
||||
* there without every definition riding along on each turn.
|
||||
*/
|
||||
export default function deferredToolsNote({ tools }: { tools: HarnessTool[] }) {
|
||||
const lines = tools.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`);
|
||||
const families = new Map<string, string[]>();
|
||||
const loose: HarnessTool[] = [];
|
||||
|
||||
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with the names you need (one call can load several), then call them. Don't load what you won't use.\n${lines.join("\n")}`;
|
||||
for (const tool of tools) {
|
||||
if (!tool.group) {
|
||||
loose.push(tool);
|
||||
continue;
|
||||
}
|
||||
|
||||
families.set(tool.group, [...(families.get(tool.group) ?? []), tool.name]);
|
||||
}
|
||||
|
||||
const lines = [
|
||||
...[...families].map(([group, names]) => `- ${group}: ${names.join(", ")} (load the family by its name)`),
|
||||
...loose.map((tool) => `- ${tool.name}: ${shortDescription({ text: tool.description })}`),
|
||||
];
|
||||
|
||||
return `Tools you can load: these are available to you but not loaded yet, to keep each step small. Call ${LoadToolsToolName} with what you need (one call can load several), then call them: exact names, a family's name for all of it, or "<prefix>*". Don't load what you won't use.\n${lines.join("\n")}`;
|
||||
}
|
||||
|
||||
function shortDescription({ text }: { text: string }) {
|
||||
|
||||
@@ -23,7 +23,7 @@ function transcript(): HarnessMessage[] {
|
||||
];
|
||||
}
|
||||
|
||||
const params = { system: "s", context_length: 200, keep_last: 4 };
|
||||
const params = { system: "s", working_tokens: 140, keep_last: 4 };
|
||||
|
||||
describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", () => {
|
||||
test("a long result is cut to its start and end, not replaced whole", () => {
|
||||
@@ -54,3 +54,89 @@ describe("fitTranscriptToContext keeps a head+tail trim across passes (M4)", ()
|
||||
expect(messages[0]!.content as string).toContain("_END_MARKER");
|
||||
});
|
||||
});
|
||||
|
||||
describe("fitTranscriptToContext never leaves a run reading a note instead of an answer", () => {
|
||||
test("a result short enough to keep whole is kept whole", () => {
|
||||
const messages: HarnessMessage[] = [
|
||||
{ role: "tool", tool_call_id: "c1", content: "/usr/bin/pdftoppm" },
|
||||
];
|
||||
|
||||
// Far below the result, so every pass that could cut it runs.
|
||||
const result = fitTranscriptToContext({ system: "s", transcript: messages, working_tokens: 10 });
|
||||
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(messages[0]!.content).toBe("/usr/bin/pdftoppm");
|
||||
});
|
||||
|
||||
test("the newest turn's results are cut last, only once the older ones are gone", () => {
|
||||
const old = `OLD_START_${"x".repeat(30_000)}_OLD_END`;
|
||||
const fresh = `FRESH_START_${"y".repeat(6000)}_FRESH_END`;
|
||||
|
||||
const messages: HarnessMessage[] = [
|
||||
{ role: "tool", tool_call_id: "old", content: old },
|
||||
{ role: "user", content: "u1" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "a1",
|
||||
tool_calls: [{ id: "new", name: "computer_bash", arguments: "{}" }],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "new", content: fresh },
|
||||
];
|
||||
|
||||
// Enough room once the older result is cut, so the newest one stays.
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript: messages,
|
||||
working_tokens: 5_000,
|
||||
keep_last: 0,
|
||||
});
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(messages[0]!.content as string).toContain("OLD_START_");
|
||||
expect(messages[3]!.content).toBe(fresh);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fitTranscriptToContext names what is over the working context", () => {
|
||||
test("its own instructions alone past the context is static", () => {
|
||||
const result = fitTranscriptToContext({
|
||||
system: "x".repeat(3_000),
|
||||
transcript: [],
|
||||
working_tokens: 500,
|
||||
});
|
||||
|
||||
expect(result.over_budget).toBe("static");
|
||||
expect(result.base).toBe(result.system_tokens);
|
||||
});
|
||||
|
||||
test("tool definitions count toward the static part", () => {
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript: [],
|
||||
working_tokens: 500,
|
||||
tools_chars: 3_000,
|
||||
});
|
||||
|
||||
expect(result.over_budget).toBe("static");
|
||||
expect(result.tools_tokens).toBe(1_000);
|
||||
});
|
||||
|
||||
test("a conversation the user made too long is the request", () => {
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript: [{ role: "user", content: "y".repeat(3_000) }],
|
||||
working_tokens: 500,
|
||||
keep_last: 0,
|
||||
});
|
||||
|
||||
expect(result.over_budget).toBe("request");
|
||||
// The user's own text is never cut.
|
||||
expect(result.trimmed).toBe(0);
|
||||
});
|
||||
|
||||
test("a prompt that fits says nothing is over", () => {
|
||||
const result = fitTranscriptToContext({ system: "s", transcript: [], working_tokens: 500 });
|
||||
|
||||
expect(result.over_budget).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,30 +8,35 @@ type Params = {
|
||||
*/
|
||||
transcript: HarnessMessage[];
|
||||
/**
|
||||
* The model's context window, in tokens.
|
||||
* The working context (`workingContextTokens`): the most a turn may
|
||||
* send, the model's window less the room its answer needs, or the
|
||||
* install's own tighter cap.
|
||||
*/
|
||||
context_length: number;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most the prompt
|
||||
* may be per turn, whatever the window. Left out, only the window
|
||||
* limits it.
|
||||
*/
|
||||
budget_tokens?: number;
|
||||
working_tokens: number;
|
||||
/**
|
||||
* Characters of the tool definitions sent with every turn: they count
|
||||
* against the budget like the prompt.
|
||||
*/
|
||||
tools_chars?: number;
|
||||
/**
|
||||
* The newest messages, never trimmed: the model needs them to go on.
|
||||
* The newest messages: the passes that cut everything else leave them
|
||||
* alone, so the turn the run is working from keeps its answer. Only the
|
||||
* last resort (still over budget with nothing older left to cut) cuts
|
||||
* their tool results, and what the user wrote is never cut at all.
|
||||
*/
|
||||
keep_last?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Share of the window the prompt may fill; the rest is for the answer.
|
||||
* Why the prompt still doesn't fit:
|
||||
* - `static`: the system prompt and tool definitions alone are past the
|
||||
* working context, so no amount of trimming can help and the run must
|
||||
* stop and say so
|
||||
* - `request`: what is over is the conversation itself, most often what
|
||||
* the user wrote, which is never cut
|
||||
*/
|
||||
const PromptShare = 0.7;
|
||||
export type OverBudgetCause = "static" | "request";
|
||||
|
||||
/**
|
||||
* Once over budget, trimming goes on down to this share of it. Cutting in
|
||||
* one block, rather than one message each turn, keeps the start of the
|
||||
@@ -54,6 +59,14 @@ const MediaTokens = 1500;
|
||||
* and its totals, as `truncate` does) is usually all the run still needs.
|
||||
*/
|
||||
const TrimmedKeepChars = 500;
|
||||
/**
|
||||
* A result no longer than this is kept whole. Cutting it saved nothing
|
||||
* worth a note, and a short result used to be replaced by the note alone:
|
||||
* a 14-character answer from a shell reached the model as "Trimmed: 14
|
||||
* characters", so the run was reading nothing at all and went on doing it
|
||||
* for the rest of its steps.
|
||||
*/
|
||||
const ResultKeepWholeChars = TrimmedKeepChars * 4;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
@@ -62,35 +75,51 @@ const ArgumentsKeepChars = 1500;
|
||||
|
||||
/**
|
||||
* Keeps a long tool run inside its working context: once the estimated
|
||||
* prompt (system, tool definitions, transcript) passes the budget (the
|
||||
* working context, or 70% of the window when that is smaller), the
|
||||
* oldest tool results, then long tool call arguments, then the oldest
|
||||
* assistant texts are replaced with a note of what was cut, down to 60%
|
||||
* of the budget. Returns how many messages were trimmed, and whether the
|
||||
* prompt still doesn't fit (nothing trimmable was left: the conversation
|
||||
* is the user's own text, which is never cut).
|
||||
* prompt (system, tool definitions, transcript) passes it, the oldest tool
|
||||
* results, then long tool call arguments, then the oldest assistant texts
|
||||
* are replaced with a note of what was cut, down to 60% of it. The newest
|
||||
* turn's results are cut last, and only once everything older is gone.
|
||||
* Reports how many messages were trimmed, and, when the prompt still
|
||||
* doesn't fit, whether the static part is the cause.
|
||||
*/
|
||||
export default function fitTranscriptToContext({
|
||||
system,
|
||||
transcript,
|
||||
context_length,
|
||||
budget_tokens,
|
||||
working_tokens,
|
||||
tools_chars = 0,
|
||||
keep_last = 4,
|
||||
}: Params) {
|
||||
const window_budget = Math.floor(context_length * PromptShare);
|
||||
const budget = budget_tokens && budget_tokens > 0 ? Math.min(window_budget, budget_tokens) : window_budget;
|
||||
let total =
|
||||
estimateTokens({ text: system }) +
|
||||
Math.ceil(tools_chars / CharsPerToken) +
|
||||
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
const budget = working_tokens;
|
||||
const system_tokens = estimateTokens({ text: system });
|
||||
const tools_tokens = Math.ceil(tools_chars / CharsPerToken);
|
||||
const base = system_tokens + tools_tokens;
|
||||
let total = base + transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
let trimmed = 0;
|
||||
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget, over_budget: false };
|
||||
if (total <= budget) {
|
||||
return {
|
||||
trimmed,
|
||||
estimated_tokens: total,
|
||||
budget,
|
||||
base,
|
||||
system_tokens,
|
||||
tools_tokens,
|
||||
over_budget: false as false | OverBudgetCause,
|
||||
};
|
||||
}
|
||||
|
||||
const target = Math.floor(budget * TrimToShare);
|
||||
const trimmable = transcript.length - keep_last;
|
||||
const names = toolNames({ transcript });
|
||||
/**
|
||||
* Everything after the newest user turn is what the run is working
|
||||
* from right now. Cutting it is the last resort, not the first: it is
|
||||
* why a run over budget kept its command and lost its answer.
|
||||
*/
|
||||
const newest_turn = Math.max(
|
||||
0,
|
||||
Math.min(trimmable, transcript.reduce((last, message, index) => (message.role == "user" ? index : last), trimmable)),
|
||||
);
|
||||
|
||||
const replace = ({ index, message }: { index: number; message: HarnessMessage }) => {
|
||||
const before = messageTokens({ message: transcript[index]! });
|
||||
@@ -104,24 +133,22 @@ export default function fitTranscriptToContext({
|
||||
* A tool result cut down to its two ends and a note: the run works from
|
||||
* what it kept, rather than paying for the call again.
|
||||
*/
|
||||
const trimResult = ({ index, content, name }: { index: number; content: string; name: string | undefined }) => {
|
||||
const kept = content.length > TrimmedKeepChars * 4;
|
||||
const head = kept ? content.slice(0, TrimmedKeepChars) : "";
|
||||
const tail = kept ? content.slice(-TrimmedKeepChars) : "";
|
||||
const trimResult = ({ content, name }: { content: string; name: string | undefined }) => {
|
||||
const head = content.slice(0, TrimmedKeepChars);
|
||||
const tail = content.slice(-TrimmedKeepChars);
|
||||
const cut = content.length - head.length - tail.length;
|
||||
const label = name ? `${name} output` : "tool output";
|
||||
|
||||
if (!kept) return `[Trimmed: ${cut} characters of this ${label} to fit the working context.]`;
|
||||
|
||||
const note = `[Trimmed: ${cut} characters of the middle of this ${label} to fit the working context. Its start and end are kept here: work from them, and narrow the call (a smaller range, a filter, one row) rather than repeating it.]`;
|
||||
|
||||
return `${head}\n\n${note}\n\n${tail}`;
|
||||
};
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const trimToolResult = ({ index }: { index: number }) => {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) return;
|
||||
if (message.content.length <= ResultKeepWholeChars) return;
|
||||
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
@@ -129,12 +156,14 @@ export default function fitTranscriptToContext({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
content: trimResult({ content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
for (let index = 0; index < newest_turn && total > target; index++) trimToolResult({ index });
|
||||
|
||||
for (let index = 0; index < newest_turn && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || !message.tool_calls?.some((call) => call.arguments.length > ArgumentsKeepChars)) {
|
||||
@@ -159,7 +188,7 @@ export default function fitTranscriptToContext({
|
||||
});
|
||||
}
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
for (let index = 0; index < newest_turn && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
if (message.role != "assistant" || typeof message.content != "string" || isTrimmed({ text: message.content })) {
|
||||
@@ -183,23 +212,17 @@ export default function fitTranscriptToContext({
|
||||
* they are cut last, and only once everything older is gone. A user's
|
||||
* own text is never touched.
|
||||
*/
|
||||
for (let index = Math.max(trimmable, 0); index < transcript.length && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
for (let index = newest_turn; index < transcript.length && total > target; index++) trimToolResult({ index });
|
||||
|
||||
if (message.role != "tool" || isTrimmed({ text: message.content })) continue;
|
||||
|
||||
const name = names.get(message.tool_call_id);
|
||||
|
||||
replace({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
|
||||
return {
|
||||
trimmed,
|
||||
estimated_tokens: total,
|
||||
budget,
|
||||
base,
|
||||
system_tokens,
|
||||
tools_tokens,
|
||||
over_budget: total > budget ? (base >= budget ? ("static" as const) : ("request" as const)) : (false as const),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, mock, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, closingFailedNote, closingMixedNote, closingNoTextNote, contextTrimmedNote, DroppedToolImageNote, repeatedAnswerNote, replyClosingMixedNote, replyClosingRequiredNote, replyDraftNote, replyNoTextNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -14,6 +14,7 @@ import runTextLoop, {
|
||||
stepsLowWarningLeft,
|
||||
wrapUpPrompt,
|
||||
} from "./run-text-loop";
|
||||
import { WorkingContextReserveMax } from "./working-context";
|
||||
|
||||
/**
|
||||
* A reviewer that threw is logged (`logError`), and the log goes to the
|
||||
@@ -280,7 +281,7 @@ describe("runTextLoop", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("a run with no step limit keeps going, and records that its limits were off", async () => {
|
||||
test("a run with no step limit keeps going, and records the window it works to", async () => {
|
||||
memory.length = 0;
|
||||
const loop_call = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
@@ -304,7 +305,11 @@ describe("runTextLoop", () => {
|
||||
expect(seen[0]!.limits).toEqual({
|
||||
steps: UnlimitedLimit,
|
||||
run_tokens: UnlimitedLimit,
|
||||
context_tokens: UnlimitedLimit,
|
||||
// The working context is a number even with no cap: the model's
|
||||
// window less the room its answer needs.
|
||||
context_tokens: AppData.HarnessUnknownContextWindow - WorkingContextReserveMax,
|
||||
system_tokens: 1,
|
||||
tools_tokens: expect.any(Number),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1039,6 +1044,99 @@ describe("runTextLoop", () => {
|
||||
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "srv__small"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).not.toContain("Tools you can load");
|
||||
});
|
||||
|
||||
/**
|
||||
* A model with a small window, which is where a bot's own tool
|
||||
* definitions are a real share of the prompt (the default candidate
|
||||
* declares none, so its working context is ~936,000 tokens).
|
||||
*/
|
||||
const narrow = async () => [{ ...candidate, model: { ...candidate.model, context_length: 20_000 } }];
|
||||
|
||||
const bulk = (name: string, group?: string): HarnessTool => ({
|
||||
name,
|
||||
description: "Works on the tracker. ".repeat(220),
|
||||
parameters: { type: "object", properties: {} },
|
||||
group,
|
||||
deferred: true,
|
||||
run: async () => "done",
|
||||
});
|
||||
|
||||
const family = ["list_tasks", "create_task", "update_task", "delete_task", "defer_task"].map((name) =>
|
||||
bulk(name, "tasks"),
|
||||
);
|
||||
|
||||
test("defers a family of the bot's own tools once it is worth a load turn", async () => {
|
||||
const { generate, seen } = scripted([{ text: "Hi." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, ...family],
|
||||
generate,
|
||||
resolveCandidates: narrow,
|
||||
});
|
||||
|
||||
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", "load_tools"]);
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain("Tools you can load");
|
||||
expect(String(seen[0]!.messages[0]!.content)).toContain(
|
||||
"- tasks: list_tasks, create_task, update_task, delete_task, defer_task (load the family by its name)",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps the tools that end a run loaded, however big they are", async () => {
|
||||
const { generate, seen } = scripted([{ text: "Hi." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, ...family, bulk("send_reply", "sessions"), bulk("write_file", "files")],
|
||||
generate,
|
||||
resolveCandidates: narrow,
|
||||
});
|
||||
|
||||
const names = seen[0]!.tools!.map((tool) => tool.name);
|
||||
|
||||
expect(names).toContain("send_reply");
|
||||
expect(names).toContain("write_file");
|
||||
expect(names).toContain("load_tools");
|
||||
expect(names).not.toContain("list_tasks");
|
||||
});
|
||||
|
||||
test("defers its own tools only once together they take a share of the context", async () => {
|
||||
// The same family on a model with room to spare: the turn a load
|
||||
// costs is not worth saving 7,000 tokens out of 936,000.
|
||||
const { generate, seen } = scripted([{ text: "Hi." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember, ...family],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen[0]!.tools!.map((tool) => tool.name)).toEqual(["remember", ...family.map((tool) => tool.name)]);
|
||||
});
|
||||
|
||||
test("stops at once when its own instructions alone are past the working context", async () => {
|
||||
const { generate, seen } = scripted([{ text: "never" }]);
|
||||
|
||||
const call = runTextLoop({
|
||||
system: "x".repeat(3_000),
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
context_budget: 100,
|
||||
});
|
||||
|
||||
await expect(call).rejects.toBeInstanceOf(HarnessError);
|
||||
await expect(call).rejects.toThrow("stopped before its first answer");
|
||||
|
||||
// Nothing was sent, and no turn was spent trimming its way to an
|
||||
// answer it could not write.
|
||||
expect(seen).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop repeated reads", () => {
|
||||
@@ -2338,7 +2436,11 @@ describe("runTextLoop answer not sent", () => {
|
||||
describe("runTextLoop over budget", () => {
|
||||
test("tells a run whose own request is over the working context, once", async () => {
|
||||
const brief = "x".repeat(30_000);
|
||||
const note = oversizedRequestNote({ budget: 4_000 });
|
||||
/**
|
||||
* A phrase from `oversizedRequestNote`: the note's numbers are the
|
||||
* loop's own arithmetic, so only its fixed words are matched here.
|
||||
*/
|
||||
const note = "larger than the working context this model may be sent";
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "One piece.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
|
||||
@@ -2364,7 +2466,7 @@ describe("runTextLoop over budget", () => {
|
||||
});
|
||||
|
||||
test("says nothing when the transcript fits, or when trimming was enough", async () => {
|
||||
const note = oversizedRequestNote({ budget: 20_000 });
|
||||
const note = "larger than the working context this model may be sent";
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "One.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
replyClosingRequiredNote,
|
||||
replyDraftNote,
|
||||
replyNoTextNote,
|
||||
staticPromptOverBudgetNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
@@ -26,9 +27,9 @@ import { logError } from "@/src/functions/backend/logger";
|
||||
import type { ReplyStatus } from "@/src/dict/reply-status-dict";
|
||||
import { ReplyStatuses } from "@/src/dict/reply-status-dict";
|
||||
import HarnessError from "../harness-error";
|
||||
import isClosingTool, { SendReplyToolName } from "../tools/closing-tool-names";
|
||||
import isClosingTool, { ClosingToolNames, SendReplyToolName } from "../tools/closing-tool-names";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import loadToolsTool, { LoadToolsToolName } from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
import isRepeatableTool from "../tools/repeatable-tool-names";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
@@ -53,6 +54,7 @@ import generateText from "./generate-text";
|
||||
import pushUserTurn from "./push-user-turn";
|
||||
import supersedeToolOutputs from "./supersede-tool-outputs";
|
||||
import toolImagesTurn from "./tool-images-turn";
|
||||
import workingContextTokens from "./working-context";
|
||||
|
||||
export type TextLoopStep = {
|
||||
index: number;
|
||||
@@ -72,8 +74,12 @@ type Params = {
|
||||
messages: HarnessMessage[];
|
||||
/**
|
||||
* The run's tools. Deferred ones (`HarnessTool.deferred`) are listed
|
||||
* by name and loaded with `load_tools`, when together they're large
|
||||
* enough to be worth it (`AppData.HarnessDeferToolsMinChars`).
|
||||
* by name and loaded with `load_tools` when they are large enough to
|
||||
* be worth keeping out of every turn: an extension's definitions
|
||||
* together past `AppData.HarnessDeferToolsMinChars`, or the bot's own
|
||||
* (`HarnessTool.group`) past `AppData.HarnessDeferBuiltinToolsMinChars`
|
||||
* and `AppData.HarnessDeferBuiltinToolsShare` of the working context.
|
||||
* The tools that save or send the answer are never deferred.
|
||||
*/
|
||||
tools?: HarnessTool[];
|
||||
max_steps?: RunLimit;
|
||||
@@ -84,9 +90,10 @@ type Params = {
|
||||
*/
|
||||
max_prompt_tokens?: RunLimit;
|
||||
/**
|
||||
* The working context (`grabContextBudgetTokens`): the most each turn
|
||||
* sends before old tool output is trimmed, whatever the model's
|
||||
* window. Unlimited or left out, the window decides.
|
||||
* A tighter cap on the working context (`grabContextBudgetTokens`),
|
||||
* when the install set one: the most each turn sends before old tool
|
||||
* output is trimmed. Unlimited or left out, the model's window decides
|
||||
* (`workingContextTokens`).
|
||||
*/
|
||||
context_budget?: RunLimit;
|
||||
signal?: AbortSignal;
|
||||
@@ -232,6 +239,19 @@ export const WrapUpAnswerToolNames = [SendReplyToolName];
|
||||
*/
|
||||
export const WrapUpToolNames = [...WrapUpSaveToolNames, ...WrapUpHandOffToolNames, ...WrapUpAnswerToolNames];
|
||||
|
||||
/**
|
||||
* Tools a run keeps loaded whatever their size: the ones a wrap up saves
|
||||
* or answers with, the closing tools that end the run, and `load_tools`
|
||||
* itself. Deferring any of them leaves a run that can no longer act.
|
||||
*/
|
||||
const KeepLoadedToolNames: readonly string[] = [...WrapUpToolNames, ...ClosingToolNames, LoadToolsToolName];
|
||||
|
||||
/**
|
||||
* Rough characters per token for the tool definitions: the same estimate
|
||||
* the transcript is sized with, so the two are compared on one scale.
|
||||
*/
|
||||
const DefinitionCharsPerToken = 3;
|
||||
|
||||
/**
|
||||
* Saving turns a wrap up may take: the first, and one more when it reached
|
||||
* for a tool it no longer has. After them the run answers with no tools.
|
||||
@@ -415,13 +435,47 @@ export default async function runTextLoop({
|
||||
}: Params): Promise<TextLoopResult> {
|
||||
const candidates = await resolveCandidates();
|
||||
/**
|
||||
* Deferred tools wait to be loaded only when their definitions
|
||||
* together are worth keeping out of every turn.
|
||||
* The model the run is on, or will start on: its window sizes every
|
||||
* turn (`workingContextTokens`) and decides whether the bot's own
|
||||
* tools are worth keeping out of it.
|
||||
*/
|
||||
const deferrable = tools.filter((tool) => tool.deferred);
|
||||
const defer =
|
||||
deferrable.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0) >=
|
||||
AppData.HarnessDeferToolsMinChars;
|
||||
const start_model = (candidates.find((candidate) => candidate.key == planned_key) || candidates[0])?.model;
|
||||
const start_context = workingContextTokens({
|
||||
context_length: start_model?.context_length,
|
||||
max_output_tokens: start_model?.max_output_tokens,
|
||||
context_budget,
|
||||
});
|
||||
const definitionChars = ({ list }: { list: HarnessTool[] }) =>
|
||||
list.reduce((sum, tool) => sum + JSON.stringify(toolDefinition({ tool })).length, 0);
|
||||
/**
|
||||
* What may wait to be loaded at all: the tools a wrap up saves or
|
||||
* answers with, the closing tools and `load_tools` itself never do,
|
||||
* since a run out of steps with its saving tools deferred would have
|
||||
* nothing left to save with.
|
||||
*/
|
||||
const can_defer = ({ tool }: { tool: HarnessTool }) => Boolean(tool.deferred) && !KeepLoadedToolNames.includes(tool.name);
|
||||
const builtin_deferrable = tools.filter((tool) => can_defer({ tool }) && tool.group);
|
||||
const extension_deferrable = tools.filter((tool) => can_defer({ tool }) && !tool.group);
|
||||
const builtin_chars = definitionChars({ list: builtin_deferrable });
|
||||
const extension_chars = definitionChars({ list: extension_deferrable });
|
||||
/**
|
||||
* Extensions are deferred once they are heavy in absolute terms: an MCP
|
||||
* server can be a hundred thousand characters on its own. The bot's own
|
||||
* tools are deferred only when they are heavy *for this model*: at
|
||||
* about 33k tokens of definitions they left a 131k-window model less
|
||||
* than half its window for the conversation, while a 1M-window model
|
||||
* holds them comfortably and pays a turn to load them for nothing.
|
||||
*/
|
||||
const defer_builtin =
|
||||
builtin_chars >= AppData.HarnessDeferBuiltinToolsMinChars &&
|
||||
builtin_chars / DefinitionCharsPerToken > start_context.tokens * AppData.HarnessDeferBuiltinToolsShare;
|
||||
const defer_extensions = extension_chars >= AppData.HarnessDeferToolsMinChars;
|
||||
const deferrable: HarnessTool[] = [
|
||||
...(defer_builtin ? builtin_deferrable : []),
|
||||
...(defer_extensions ? extension_deferrable : []),
|
||||
];
|
||||
const defer = deferrable.length > 0;
|
||||
const deferred_names = new Set(deferrable.map((tool) => tool.name));
|
||||
/**
|
||||
* Loaded deferred tools, in the order they were loaded: their
|
||||
* definitions go after the others, so the start of the list (and of
|
||||
@@ -440,7 +494,7 @@ export default async function runTextLoop({
|
||||
: tools;
|
||||
const all_definitions = new Map(run_tools.map((tool) => [tool.name, toolDefinition({ tool })]));
|
||||
const definitionsNow = () => [
|
||||
...run_tools.filter((tool) => !defer || !tool.deferred).map((tool) => all_definitions.get(tool.name)!),
|
||||
...run_tools.filter((tool) => !deferred_names.has(tool.name)).map((tool) => all_definitions.get(tool.name)!),
|
||||
...loaded.map((name) => all_definitions.get(name)!),
|
||||
];
|
||||
const run_system = defer ? `${system}\n\n${deferredToolsNote({ tools: deferrable })}` : system;
|
||||
@@ -492,7 +546,20 @@ export default async function runTextLoop({
|
||||
const call_limits = {
|
||||
steps: max_steps,
|
||||
run_tokens: max_prompt_tokens ?? UnlimitedLimit,
|
||||
context_tokens: context_budget ?? UnlimitedLimit,
|
||||
/**
|
||||
* The working context actually used, in tokens, not the setting:
|
||||
* a bot asked to explain a cost has to be able to name the window
|
||||
* it was held to, and "unlimited" told the user nothing when the
|
||||
* real ceiling was 70% of a guessed window.
|
||||
*/
|
||||
context_tokens: start_context.tokens,
|
||||
/**
|
||||
* What the app itself spends of it before the conversation starts:
|
||||
* the system prompt and the tool definitions, which are resent on
|
||||
* every turn and which nothing may trim.
|
||||
*/
|
||||
system_tokens: Math.ceil(run_system.length / DefinitionCharsPerToken),
|
||||
tools_tokens: Math.ceil(JSON.stringify(definitionsNow()).length / DefinitionCharsPerToken),
|
||||
};
|
||||
/**
|
||||
* A step count to count against, for the loop itself: an unlimited run
|
||||
@@ -754,29 +821,62 @@ export default async function runTextLoop({
|
||||
: definitionsNow();
|
||||
|
||||
/**
|
||||
* Sized for the model the run is on (or will start on). A fallback
|
||||
* with a smaller window gets a 400 and the next model is tried.
|
||||
* Sized for the model the run is on (or will start on): its own
|
||||
* window, less the room its answer needs (`workingContextTokens`),
|
||||
* never a fixed share of a guessed one. A provider that says the
|
||||
* prompt was too long stops the run with its own message
|
||||
* (`isContextOverflowError`), naming the real limit.
|
||||
*/
|
||||
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
|
||||
|
||||
const working = workingContextTokens({
|
||||
context_length: model?.context_length,
|
||||
max_output_tokens: model?.max_output_tokens,
|
||||
context_budget,
|
||||
});
|
||||
|
||||
const fit = fitTranscriptToContext({
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
|
||||
budget_tokens: typeof context_budget == "number" ? context_budget : undefined,
|
||||
working_tokens: working.tokens,
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
/**
|
||||
* The app's own instructions and tool definitions are already past
|
||||
* the working context on their own, so nothing trimmable can make
|
||||
* room. A run that went on trimmed every tool result of every turn
|
||||
* and answered from nothing: stop here and say what the arithmetic
|
||||
* is, instead of blinding it (`staticPromptOverBudgetNote`).
|
||||
*/
|
||||
if (fit.over_budget == "static") {
|
||||
const note = staticPromptOverBudgetNote({
|
||||
working: working.tokens,
|
||||
window: working.window,
|
||||
assumed: working.assumed,
|
||||
base: fit.base,
|
||||
system: fit.system_tokens,
|
||||
tools: fit.tools_tokens,
|
||||
});
|
||||
|
||||
await traced({ kind: "event", index, name: "over_budget", text: note });
|
||||
throw new HarnessError({ message: note, fatal: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything trimmable was trimmed and it still doesn't fit: what is
|
||||
* over is what the user wrote, which is never cut. Told once, so it
|
||||
* works in pieces and says what it could not reach instead of
|
||||
* inventing the rest (`oversizedRequestNote`).
|
||||
*/
|
||||
if (fit.over_budget && !told_over_budget) {
|
||||
if (fit.over_budget == "request" && !told_over_budget) {
|
||||
told_over_budget = true;
|
||||
|
||||
const note = oversizedRequestNote({ budget: fit.budget });
|
||||
const note = oversizedRequestNote({
|
||||
budget: fit.budget,
|
||||
base: fit.base,
|
||||
conversation: fit.estimated_tokens - fit.base,
|
||||
});
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "over_budget", text: note });
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import workingContextTokens, { WorkingContextReserveMax, WorkingContextReserveMin } from "./working-context";
|
||||
|
||||
describe("workingContextTokens", () => {
|
||||
test("a declared window keeps a tenth of it for the answer", () => {
|
||||
const context = workingContextTokens({ context_length: 131_072 });
|
||||
|
||||
expect(context.window).toBe(131_072);
|
||||
expect(context.assumed).toBe(false);
|
||||
expect(context.reserve).toBe(13_107);
|
||||
expect(context.tokens).toBe(117_965);
|
||||
});
|
||||
|
||||
test("a 200,000 token window keeps 20,000 back", () => {
|
||||
expect(workingContextTokens({ context_length: 200_000 }).tokens).toBe(180_000);
|
||||
});
|
||||
|
||||
test("a 1,000,000 token window keeps the most a run ever reserves", () => {
|
||||
const context = workingContextTokens({ context_length: 1_000_000 });
|
||||
|
||||
expect(context.reserve).toBe(WorkingContextReserveMax);
|
||||
expect(context.tokens).toBe(936_000);
|
||||
});
|
||||
|
||||
test("a model that declares its output size keeps exactly that back", () => {
|
||||
const context = workingContextTokens({ context_length: 131_072, max_output_tokens: 4_096 });
|
||||
|
||||
expect(context.reserve).toBe(4_096);
|
||||
expect(context.tokens).toBe(126_976);
|
||||
});
|
||||
|
||||
test("a model with no declared window is worked to the install's assumption", () => {
|
||||
const context = workingContextTokens({});
|
||||
|
||||
expect(context.window).toBe(AppData.HarnessUnknownContextWindow);
|
||||
expect(context.assumed).toBe(true);
|
||||
expect(context.tokens).toBe(AppData.HarnessUnknownContextWindow - WorkingContextReserveMax);
|
||||
});
|
||||
|
||||
test("the install's cap holds a run below its window, never above it", () => {
|
||||
expect(workingContextTokens({ context_length: 1_000_000, context_budget: 50_000 }).tokens).toBe(50_000);
|
||||
expect(workingContextTokens({ context_length: 1_000_000, context_budget: 990_000 }).tokens).toBe(936_000);
|
||||
});
|
||||
|
||||
test("an unlimited cap leaves the window deciding", () => {
|
||||
expect(workingContextTokens({ context_length: 200_000, context_budget: "unlimited" }).tokens).toBe(180_000);
|
||||
});
|
||||
|
||||
test("the reserve never swallows the window, on the smallest model", () => {
|
||||
const context = workingContextTokens({ context_length: 12_000, max_output_tokens: 12_000 });
|
||||
|
||||
expect(context.reserve).toBe(11_999);
|
||||
expect(context.tokens).toBe(1);
|
||||
});
|
||||
|
||||
test("the smallest reserve is kept even on a tiny window", () => {
|
||||
expect(workingContextTokens({ context_length: 50_000 }).reserve).toBe(WorkingContextReserveMin);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { RunLimit } from "@/src/utils/run-limit";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The model's declared window, in tokens
|
||||
* (`harness_models.context_length`), left out when its catalog never
|
||||
* said.
|
||||
*/
|
||||
context_length?: number | null;
|
||||
/**
|
||||
* The room the model wants kept for its answer, when it declares one
|
||||
* (`harness_models.max_output_tokens`).
|
||||
*/
|
||||
max_output_tokens?: number | null;
|
||||
/**
|
||||
* An optional tighter cap on the prompt (`grabContextBudgetTokens`).
|
||||
* Unlimited or left out, the window decides.
|
||||
*/
|
||||
context_budget?: RunLimit;
|
||||
};
|
||||
|
||||
/**
|
||||
* The most a turn may send, and the arithmetic behind it.
|
||||
*/
|
||||
export type WorkingContext = {
|
||||
/**
|
||||
* The window the run works to: the model's own, or
|
||||
* `AppData.HarnessUnknownContextWindow` when it never said.
|
||||
*/
|
||||
window: number;
|
||||
/**
|
||||
* The window is the install's assumption, not the model's own: the
|
||||
* provider's refusal is then the only real limit, and the run says so
|
||||
* when it hits one.
|
||||
*/
|
||||
assumed: boolean;
|
||||
/**
|
||||
* Tokens kept back for the model's answer.
|
||||
*/
|
||||
reserve: number;
|
||||
/**
|
||||
* What a turn may send: the window less the reserve, or less the
|
||||
* install's own cap when that is smaller.
|
||||
*/
|
||||
tokens: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The least a run keeps for its answer.
|
||||
*/
|
||||
export const WorkingContextReserveMin = 8_000;
|
||||
/**
|
||||
* The most a run keeps for its answer, however big the window: a 1M
|
||||
* window does not need a 100,000-token answer.
|
||||
*/
|
||||
export const WorkingContextReserveMax = 64_000;
|
||||
/**
|
||||
* The share of the window a run keeps for its answer when the model
|
||||
* doesn't say what it needs. This replaced a flat 70% of the window,
|
||||
* which turned an assumed 131,072-token window into a 91,750-token
|
||||
* working context and left a run's own tool definitions most of it
|
||||
* (`over_budget`, then every turn trimmed blind).
|
||||
*/
|
||||
export const WorkingContextReserveShare = 0.1;
|
||||
|
||||
/**
|
||||
* The working context: the model's window less the room its answer
|
||||
* needs, or the install's own cap when that is tighter.
|
||||
*/
|
||||
export default function workingContextTokens({ context_length, max_output_tokens, context_budget }: Params): WorkingContext {
|
||||
const declared = Number(context_length || 0);
|
||||
const assumed = !(declared > 0);
|
||||
const window = assumed ? AppData.HarnessUnknownContextWindow : declared;
|
||||
const reserve =
|
||||
Number(max_output_tokens || 0) > 0
|
||||
? Math.min(Number(max_output_tokens), Math.max(1, window - 1))
|
||||
: Math.min(
|
||||
WorkingContextReserveMax,
|
||||
Math.max(WorkingContextReserveMin, Math.round(window * WorkingContextReserveShare)),
|
||||
);
|
||||
const from_window = Math.max(1, window - reserve);
|
||||
const cap = typeof context_budget == "number" && context_budget > 0 ? context_budget : 0;
|
||||
|
||||
return {
|
||||
window,
|
||||
assumed,
|
||||
reserve,
|
||||
tokens: cap ? Math.min(from_window, cap) : from_window,
|
||||
};
|
||||
}
|
||||
@@ -60,24 +60,42 @@ describe("Plan mode's tool gate", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a blocked tool's description, schema and deferral, so the model still sees what it is", async () => {
|
||||
test("keeps a blocked tool's description and schema, and lists the bot's own tools now, so the model still sees what it is", async () => {
|
||||
const deferred: HarnessTool = {
|
||||
...tool("browser_navigate"),
|
||||
description: "Open a page in the browser",
|
||||
...tool("create_task"),
|
||||
description: "Add a task to the tracker",
|
||||
parameters: { type: "object" },
|
||||
deferred: true,
|
||||
group: "tasks",
|
||||
timeout_ms: 5_000,
|
||||
};
|
||||
|
||||
const planned = gatePlanModeTools({ tools: [deferred] })[0]!;
|
||||
|
||||
expect(planned.description).toBe("Open a page in the browser");
|
||||
expect(planned.description).toBe("Add a task to the tracker");
|
||||
expect(planned.parameters).toEqual({ type: "object" });
|
||||
expect(planned.deferred).toBe(true);
|
||||
/**
|
||||
* A family tool is listed inline in a planning run: a write has to
|
||||
* be visible to be refused by name, and a read has to be callable
|
||||
* without a load step (`load_tools` is refused here too).
|
||||
*/
|
||||
expect(planned.deferred).toBe(false);
|
||||
expect(planned.timeout_ms).toBe(5_000);
|
||||
expect(planned.run).not.toBe(deferred.run);
|
||||
});
|
||||
|
||||
test("leaves an extension tool deferred, since load_tools is refused here", () => {
|
||||
const off: HarnessTool = { ...tool("exa__search"), deferred: true };
|
||||
|
||||
expect(gatePlanModeTools({ tools: [off] })[0]!.deferred).toBe(true);
|
||||
});
|
||||
|
||||
test("lists an allowed tool it was holding off, so a read needs no load step", () => {
|
||||
const off: HarnessTool = { ...tool("list_tasks"), deferred: true, group: "tasks" };
|
||||
|
||||
expect(gatePlanModeTools({ tools: [off] })[0]!.deferred).toBe(false);
|
||||
});
|
||||
|
||||
test("holds a tool nobody named yet off, so the list stays an allowlist", async () => {
|
||||
const [planned] = gatePlanModeTools({ tools: [tool("a_tool_shipped_later")] });
|
||||
|
||||
|
||||
@@ -73,13 +73,23 @@ function planModeRefusal({ name }: { name: string }) {
|
||||
* `run` is replaced, and it throws so the call is reported as failed.
|
||||
* `load_tools` is here too, so a deferred MCP or browser tool can never
|
||||
* be pulled into a planning run.
|
||||
*
|
||||
* The bot's own tools (`groupTools` has named their family by now) are
|
||||
* listed inline rather than deferred: the reads it is allowed (`list_tasks`,
|
||||
* `read_file`) have to be callable without a loading step, and the writes it
|
||||
* is refused have to be visible to be refused by name. Extensions stay as
|
||||
* deferred as they were: `load_tools` is refused here, so listing their
|
||||
* definitions inline would spend the run's context on tools it cannot call.
|
||||
*/
|
||||
export default function gatePlanModeTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
|
||||
const listed = ({ tool }: { tool: HarnessTool }) => (tool.group ? false : tool.deferred);
|
||||
|
||||
return tools.map((tool) =>
|
||||
allowed.has(tool.name)
|
||||
? tool
|
||||
? { ...tool, deferred: listed({ tool }) }
|
||||
: {
|
||||
...tool,
|
||||
deferred: listed({ tool }),
|
||||
run: async () => {
|
||||
throw new Error(planModeRefusal({ name: tool.name }));
|
||||
},
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { HarnessTool } from "../types";
|
||||
import { ToolGroups } from "./tool-groups";
|
||||
|
||||
/**
|
||||
* Names the bot's own tools into their families (`ToolGroups`) so a run
|
||||
* with a narrow window can defer whole families and load them by name
|
||||
* (`runTextLoop` decides by size, so a model with room keeps them all
|
||||
* inline). A tool in no family is left alone, and one an extension already
|
||||
* deferred keeps its own flag.
|
||||
*/
|
||||
export default function groupTools({ tools }: { tools: HarnessTool[] }): HarnessTool[] {
|
||||
const group_of = new Map<string, string>();
|
||||
|
||||
for (const [group, names] of Object.entries(ToolGroups)) {
|
||||
for (const name of names) {
|
||||
if (!group_of.has(name)) group_of.set(name, group);
|
||||
}
|
||||
}
|
||||
|
||||
return tools.map((tool) => {
|
||||
const group = group_of.get(tool.name);
|
||||
|
||||
return group ? { ...tool, group, deferred: true } : tool;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { HarnessTool } from "../types";
|
||||
import loadToolsTool, { LoadToolsToolName } from "./load-tools-tool";
|
||||
|
||||
const tool = ({ name, group }: { name: string; group?: string }): HarnessTool => ({
|
||||
name,
|
||||
description: `The ${name} tool.`,
|
||||
schema: undefined as unknown as HarnessTool["schema"],
|
||||
group,
|
||||
deferred: true,
|
||||
run: async () => "",
|
||||
});
|
||||
|
||||
const deferred = [
|
||||
tool({ name: "list_tasks", group: "tasks" }),
|
||||
tool({ name: "create_task", group: "tasks" }),
|
||||
tool({ name: "create_plan", group: "plans" }),
|
||||
tool({ name: "exa__web_search_exa" }),
|
||||
tool({ name: "exa__crawling_exa" }),
|
||||
];
|
||||
|
||||
function loading() {
|
||||
const loaded: string[][] = [];
|
||||
const is_loaded = new Set<string>();
|
||||
|
||||
const loader = loadToolsTool({
|
||||
deferred,
|
||||
isLoaded: (name) => is_loaded.has(name),
|
||||
onLoad: (names) => {
|
||||
loaded.push(names);
|
||||
for (const name of names) is_loaded.add(name);
|
||||
},
|
||||
});
|
||||
|
||||
return { loader, loaded };
|
||||
}
|
||||
|
||||
describe(`loadToolsTool (${LoadToolsToolName})`, () => {
|
||||
test("exact names load exactly those tools", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
const result = await loader.run({ args: { names: ["list_tasks"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["list_tasks"]]);
|
||||
expect(String(result)).toContain("Loaded: list_tasks.");
|
||||
});
|
||||
|
||||
test("a family's name loads the whole family", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
await loader.run({ args: { names: ["tasks"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["list_tasks", "create_task"]]);
|
||||
});
|
||||
|
||||
test("a prefix loads every tool under it", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
await loader.run({ args: { names: ["exa__*"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["exa__web_search_exa", "exa__crawling_exa"]]);
|
||||
});
|
||||
|
||||
test("a family and a name can be loaded in one call, each once", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
await loader.run({ args: { names: ["tasks", "list_tasks", "create_plan"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["list_tasks", "create_task", "create_plan"]]);
|
||||
});
|
||||
|
||||
test("a tool already loaded is named as such, not loaded twice", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
await loader.run({ args: { names: ["create_plan"] }, context: {} } as never);
|
||||
const second = await loader.run({ args: { names: ["create_plan", "tasks"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["create_plan"], ["list_tasks", "create_task"]]);
|
||||
expect(String(second)).toContain("Already loaded: create_plan.");
|
||||
});
|
||||
|
||||
test("a name nothing answers says so, without spoiling the rest", async () => {
|
||||
const { loader, loaded } = loading();
|
||||
|
||||
const result = await loader.run({ args: { names: ["tasks", "no_such_tool"] }, context: {} } as never);
|
||||
|
||||
expect(loaded).toEqual([["list_tasks", "create_task"]]);
|
||||
expect(String(result)).toContain("Not in the list: no_such_tool.");
|
||||
expect(String(result)).toContain("family names");
|
||||
});
|
||||
});
|
||||
@@ -22,12 +22,13 @@ export const LoadToolsToolName = "load_tools";
|
||||
* Brings deferred tools into the run (`runTextLoop`): the model sees them
|
||||
* listed by name in its prompt and loads the ones it needs, rather than
|
||||
* every turn carrying every extension's definitions. A name ending in `*`
|
||||
* loads every deferred tool it starts.
|
||||
* loads every deferred tool it starts; a family's name (`tasks`, `plans`)
|
||||
* loads every tool in it.
|
||||
*/
|
||||
export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): HarnessTool<{ names: string[] }> {
|
||||
return {
|
||||
name: LoadToolsToolName,
|
||||
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names; "<prefix>*" loads every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
|
||||
description: `Loads tools from the "Tools you can load" list in your instructions, so you can call them from your next step. Give their exact names, a family's name to load all of it ("tasks"), or "<prefix>*" to load every listed tool starting with the prefix (e.g. one server's). Load only what you're about to use.`,
|
||||
schema: z.object({
|
||||
names: z.array(z.string().trim().min(1).max(200)).min(1).max(40),
|
||||
}),
|
||||
@@ -38,7 +39,7 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
|
||||
for (const name of args.names) {
|
||||
const matches = name.endsWith("*")
|
||||
? deferred.filter((tool) => tool.name.startsWith(name.slice(0, -1)))
|
||||
: deferred.filter((tool) => tool.name == name);
|
||||
: deferred.filter((tool) => tool.name == name || tool.group == name);
|
||||
|
||||
if (!matches.length) missing.push(name);
|
||||
|
||||
@@ -53,7 +54,9 @@ export default function loadToolsTool({ deferred, isLoaded, onLoad }: Params): H
|
||||
return [
|
||||
fresh.length ? `Loaded: ${fresh.join(", ")}. Call them from your next step.` : "",
|
||||
already.length ? `Already loaded: ${already.join(", ")}.` : "",
|
||||
missing.length ? `Not in the list: ${missing.join(", ")}. Use the exact names under "Tools you can load".` : "",
|
||||
missing.length
|
||||
? `Not in the list: ${missing.join(", ")}. Use the exact names or family names under "Tools you can load".`
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* The bot's own tools, by family (`groupTools`). A run short of window keeps
|
||||
* a whole family out of every turn and the model loads it by name with
|
||||
* `load_tools` (`deferredToolsNote`), while a model with room for them keeps
|
||||
* every one inline and pays no loading turn at all.
|
||||
*
|
||||
* A family is worth a group when it is a coherent thing to load at once:
|
||||
* the tracker's tools are used together or not at all, the same for a
|
||||
* routine's or a knowledgebase's. The tools a run cannot act without
|
||||
* (`send_reply`, `ask_user`, `suggest_next_steps`, `start_task`,
|
||||
* `write_file`, `import_file`) are in none of them, and `runTextLoop`
|
||||
* refuses to defer them whatever their size.
|
||||
*/
|
||||
export const ToolGroups: Record<string, readonly string[]> = {
|
||||
computer: [
|
||||
"computer_bash",
|
||||
"computer_read_file",
|
||||
"computer_write_file",
|
||||
"computer_edit_file",
|
||||
"search_computers",
|
||||
"export_file",
|
||||
"request_install",
|
||||
"capture_secret",
|
||||
"ask_user_to_take_over",
|
||||
],
|
||||
crew: [
|
||||
"create_bot",
|
||||
"update_bot",
|
||||
"delete_bot",
|
||||
"find_bot",
|
||||
"create_workspace",
|
||||
"update_workspace",
|
||||
"delete_workspace",
|
||||
"find_workspace",
|
||||
"list_workspace_bots",
|
||||
"list_workspace_people",
|
||||
"set_user_workspace_role",
|
||||
"set_bot_workspace_instructions",
|
||||
"set_workspace_computer",
|
||||
"add_bot_to_workspace",
|
||||
"remove_bot_from_workspace",
|
||||
"assign_computer",
|
||||
"set_bot_type",
|
||||
"delegate_task",
|
||||
"hand_over_task",
|
||||
"hand_over_schedule",
|
||||
"ask_bot",
|
||||
"list_asks",
|
||||
"update_requester",
|
||||
"answer_install_request",
|
||||
],
|
||||
extensions: [
|
||||
"list_extensions",
|
||||
"propose_custom_tool",
|
||||
"update_custom_tool",
|
||||
"propose_mcp_server",
|
||||
"update_mcp_server",
|
||||
"propose_skill",
|
||||
"update_skill",
|
||||
"delete_extension",
|
||||
"set_extension_access",
|
||||
],
|
||||
files: [
|
||||
"list_files",
|
||||
"read_file",
|
||||
"copy_file",
|
||||
"move_file",
|
||||
"delete_file",
|
||||
"make_pdf",
|
||||
"transform_image",
|
||||
"generate_image",
|
||||
"generate_video",
|
||||
],
|
||||
graphics: ["create_graphic", "update_graphic", "read_graphic", "list_graphics"],
|
||||
hooks: ["list_hooks", "propose_hook", "pause_hook", "delete_hook", "search_hook_calls", "read_hook_call"],
|
||||
knowledgebase: [
|
||||
"list_knowledgebases",
|
||||
"search_knowledgebase",
|
||||
"read_knowledgebase_document",
|
||||
"save_knowledgebase",
|
||||
"add_knowledgebase_document",
|
||||
"delete_knowledgebase_document",
|
||||
"delete_knowledgebase",
|
||||
"retry_failed_documents",
|
||||
"reindex_knowledgebase",
|
||||
],
|
||||
memory: ["update_memory", "update_instructions", "set_picture", "read_settings", "read_message_usage"],
|
||||
plans: ["create_plan", "update_plan", "cancel_plan", "complete_plan_step"],
|
||||
schedules: [
|
||||
"create_schedule",
|
||||
"update_schedule",
|
||||
"delete_schedule",
|
||||
"list_schedules",
|
||||
"report_run_failed",
|
||||
],
|
||||
secrets: ["request_secret", "show_secret"],
|
||||
sessions: [
|
||||
"search_past_sessions",
|
||||
"read_past_session",
|
||||
"send_message",
|
||||
"continue_in_new_session",
|
||||
"react_to_message",
|
||||
],
|
||||
tasks: ["list_tasks", "create_task", "update_task", "delete_task"],
|
||||
};
|
||||
@@ -107,6 +107,13 @@ export type HarnessTool<Args = any> = {
|
||||
* definitions would otherwise ride along on every turn.
|
||||
*/
|
||||
deferred?: boolean;
|
||||
/**
|
||||
* The bot's own tools are named by group (`tasks`, `plans`, `files`,
|
||||
* ...) so a run short of window can keep a whole family out of every
|
||||
* turn and load it by name, while a model with room keeps them all
|
||||
* inline (`groupTools`). Extensions have none: they are deferred whole.
|
||||
*/
|
||||
group?: string;
|
||||
/**
|
||||
* This call's deadline, overriding `AppData.HarnessToolTimeoutMs`: a
|
||||
* bigger one for a tool with its own slow work, `null` for none at all
|
||||
|
||||
@@ -80,6 +80,14 @@ export type HarnessCallLimits = {
|
||||
steps: RunLimit | null;
|
||||
run_tokens: RunLimit | null;
|
||||
context_tokens: RunLimit | null;
|
||||
/**
|
||||
* How much of the working context the app's own prompt spends before
|
||||
* the conversation: the system prompt and the tool definitions, resent
|
||||
* on every turn. A bot asked to explain why a run had room for so
|
||||
* little needs both halves, not just the total.
|
||||
*/
|
||||
system_tokens?: number;
|
||||
tools_tokens?: number;
|
||||
};
|
||||
|
||||
export type HarnessUsageCall = {
|
||||
|
||||
@@ -53,7 +53,14 @@ const valuesOf = (limits?: RunLimitsOverview | null): Values => {
|
||||
* per task, ...".
|
||||
*/
|
||||
const savedMessage = (limits: RunLimitsOverview) =>
|
||||
`Saved: ${described(limits.task_steps)} steps per task, ${described(limits.reply_steps)} per chat reply, ${described(limits.unattended_steps)} per routine or hook call, ${described(limits.run_tokens)} prompt tokens per run, ${described(limits.context_tokens)} tokens of working context, and ${described(limits.model_rest_seconds)} seconds of model rest.`;
|
||||
`Saved: ${described(limits.task_steps)} steps per task, ${described(limits.reply_steps)} per chat reply, ${described(limits.unattended_steps)} per routine or hook call, ${described(limits.run_tokens)} prompt tokens per run, ${workingContextText(limits.context_tokens)}, and ${described(limits.model_rest_seconds)} seconds of model rest.`;
|
||||
|
||||
/**
|
||||
* A working context that is unlimited is the model's own window, not a
|
||||
* number: "unlimited tokens" read as if a run could send anything.
|
||||
*/
|
||||
const workingContextText = (limit: RunLimit) =>
|
||||
isUnlimitedLimit(limit) ? "the model's own window as working context" : `${count(limit)} tokens of working context`;
|
||||
|
||||
/**
|
||||
* How long a bot may work on one run: the model turns a task, a chat
|
||||
@@ -282,7 +289,7 @@ export default function RunLimitsForm({ limits }: Props) {
|
||||
suffix="tokens"
|
||||
onChange={change("context_tokens")}
|
||||
onUnlimitedChange={changeUnlimited("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 (${described(overview?.context_tokens_default ?? 0)}). With No limit on, the model's own window decides.`}
|
||||
info={`How much of the model's window a run may use per turn, once the room its answer needs is kept back (a tenth of the window, between 8,000 and 64,000 tokens, unless the model declares its own output size). What the app's instructions and tool definitions take comes out of it first, and only what is left holds the conversation. Unset, the model's own window decides; a number holds every run below it (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 puts the default back.`}
|
||||
/>
|
||||
<RunLimitInput
|
||||
id="model_rest_seconds"
|
||||
|
||||
@@ -11,6 +11,7 @@ import HarnessParamsButton from "./harness-params-button";
|
||||
import HarnessProviderSelect from "./harness-provider-select";
|
||||
import HarnessTextFallbacks from "./harness-text-fallbacks";
|
||||
import HarnessVoiceControls from "./harness-voice-controls";
|
||||
import HarnessWindowNote from "./harness-window-note";
|
||||
|
||||
type Props = {
|
||||
harness: HarnessOverview;
|
||||
@@ -70,6 +71,9 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
<HarnessCurrentModel
|
||||
harness={value.inherit && harness.default ? { ...harness, ...harness.default } : harness}
|
||||
/>
|
||||
{harness.harness == "text" ? (
|
||||
<HarnessWindowNote model={value.inherit ? harness.default?.current : picked || harness.current} />
|
||||
) : null}
|
||||
<HarnessOptionsCheckboxes
|
||||
harness={harness}
|
||||
value={value}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import HarnessWindowNote from "./harness-window-note";
|
||||
|
||||
const model = (context_length?: number) => ({
|
||||
id: 1,
|
||||
provider_id: 10,
|
||||
provider_name: "Nvidia Cloud",
|
||||
slug: "nvidia/nemotron-3-ultra-550b-a55b",
|
||||
name: "nemotron-3-ultra",
|
||||
free: false,
|
||||
context_length,
|
||||
});
|
||||
|
||||
describe("HarnessWindowNote", () => {
|
||||
test("says what a run assumes for a model with no declared window", () => {
|
||||
const html = renderToString(<HarnessWindowNote model={model()} />);
|
||||
|
||||
expect(html).toContain("declares no context window");
|
||||
expect(html).toContain("1,000,000");
|
||||
expect(html).toContain("936,000");
|
||||
expect(html).toContain("stops the run with its own limit");
|
||||
});
|
||||
|
||||
test("says nothing for a model that declares one", () => {
|
||||
expect(renderToString(<HarnessWindowNote model={model(131_072)} />)).toBe("");
|
||||
});
|
||||
|
||||
test("says nothing when there's no model to judge", () => {
|
||||
expect(renderToString(<HarnessWindowNote />)).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import workingContextTokens from "@/src/harness/text/working-context";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
model?: HarnessModelOption;
|
||||
};
|
||||
|
||||
/**
|
||||
* A word when the text model never declared a window: a run assumes
|
||||
* `AppData.HarnessUnknownContextWindow` and works to that less the room its
|
||||
* answer needs. Said out loud because the app used to size runs at 70% of a
|
||||
* guessed 131,072 without a word, which left one chat 91,750 tokens of
|
||||
* working context and then reading nothing at all (`workingContextTokens`).
|
||||
*/
|
||||
export default function HarnessWindowNote({ model }: Props) {
|
||||
if (!model || model.context_length) return null;
|
||||
|
||||
const working = workingContextTokens({});
|
||||
|
||||
return (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{`${model.name} declares no context window, so a run assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} tokens and works to ${working.tokens.toLocaleString("en-US")} of them, keeping the rest for its answer. A model smaller than that refuses the prompt and stops the run with its own limit: set the window on its provider, or pick a model that declares one.`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -170,7 +170,7 @@ export default function ProviderForm({ provider, onSaved, onCancel }: Props) {
|
||||
rawNumber
|
||||
defaultValue={context_length}
|
||||
suffix="tokens"
|
||||
info={`The window every model this provider lists without one of its own is given. Leave empty if its list carries them (OpenRouter's does); a run assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} when nothing says.`}
|
||||
info={`The window every model this provider lists without one of its own is given. Leave empty if its list carries them (OpenRouter's does). A run sizes itself to the model's window less the room its answer needs, so with nothing declared it assumes ${AppData.HarnessUnknownContextWindow.toLocaleString("en-US")} tokens, and a smaller model refuses such a prompt and stops the run with its own limit.`}
|
||||
onChange={(e) => setContextLength(e.target.value)}
|
||||
placeholder="Eg. 1,000,000"
|
||||
/>
|
||||
|
||||
@@ -57,8 +57,19 @@ export default function harnessModelSelectOptions({
|
||||
},
|
||||
...models.map((model) => ({
|
||||
value: String(model.id),
|
||||
title: `${model.name}${provider_name ? "" : ` · ${model.provider_name}`}${model.free && !/free/i.test(model.name) ? " · free" : ""}`,
|
||||
title: `${model.name}${provider_name ? "" : ` · ${model.provider_name}`}${model.free && !/free/i.test(model.name) ? " · free" : ""}${windowText({ model })}`,
|
||||
default: model.id == model_id,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* What the model's window is, on its picker line: a model with none
|
||||
* declared is the one whose runs are sized for a guess, and the user is
|
||||
* picking it right here.
|
||||
*/
|
||||
function windowText({ model }: { model: HarnessModelOption }) {
|
||||
if (model.context_length) return ` · ${model.context_length.toLocaleString("en-US")} tokens`;
|
||||
|
||||
return " · no context window declared";
|
||||
}
|
||||
|
||||
@@ -819,6 +819,12 @@ export type HarnessModelOption = {
|
||||
* The generation settings the model takes; undefined: all of them.
|
||||
*/
|
||||
supported_parameters?: string[];
|
||||
/**
|
||||
* Its context window, when the catalog or its provider declares one. A
|
||||
* model with none is given `AppData.HarnessUnknownContextWindow` by
|
||||
* every run, which the picker says out loud.
|
||||
*/
|
||||
context_length?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -65,6 +65,23 @@ describe("describeRunUsage", () => {
|
||||
expect(text).toContain("Today's settings: unlimited steps per task, 20 per reply, unlimited per routine or hook call");
|
||||
});
|
||||
|
||||
test("an unlimited working-context setting names the model's own window", () => {
|
||||
const text = describeRunUsage({
|
||||
usage: {
|
||||
...usage,
|
||||
current_limits: {
|
||||
task_steps: 60,
|
||||
reply_steps: 20,
|
||||
unattended_steps: 12,
|
||||
run_tokens: 250_000,
|
||||
context_tokens: "unlimited",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(text).toContain("the model's own window, less the room its answer needs of working context per turn.");
|
||||
});
|
||||
|
||||
test("a call recorded before runs kept their limits says so", () => {
|
||||
expect(describeRunUsage({ usage: { ...usage, limits: null } })).toContain("recorded no limits");
|
||||
});
|
||||
|
||||
@@ -20,11 +20,18 @@ const when = (value: number | null) => (value ? new Date(value).toISOString().re
|
||||
const limitsLine = ({ limits }: { limits: RunUsage["limits"] }) => {
|
||||
if (!limits) return "Their calls recorded no limits (made before runs kept them).";
|
||||
|
||||
return [
|
||||
`The run was allowed ${limitText({ value: limits.steps, none: "an unrecorded number of" })} steps,`,
|
||||
`${limitText({ value: limits.run_tokens, none: "an unrecorded number of" })} prompt tokens in all,`,
|
||||
`and ${limits.context_tokens === null ? "an unrecorded working context" : `${limitText({ value: limits.context_tokens, none: "an unrecorded working context" })} tokens of working context`} per turn.`,
|
||||
].join(" ");
|
||||
const staticSplit =
|
||||
limits.system_tokens || limits.tools_tokens
|
||||
? ` Of that, its own instructions took ${count(limits.system_tokens || 0)} and its tool definitions ${count(limits.tools_tokens || 0)}, before any of the conversation.`
|
||||
: "";
|
||||
|
||||
return (
|
||||
[
|
||||
`The run was allowed ${limitText({ value: limits.steps, none: "an unrecorded number of" })} steps,`,
|
||||
`${limitText({ value: limits.run_tokens, none: "an unrecorded number of" })} prompt tokens in all,`,
|
||||
`and ${limits.context_tokens === null ? "an unrecorded working context" : `${limitText({ value: limits.context_tokens, none: "an unrecorded working context" })} tokens of working context`} per turn.`,
|
||||
].join(" ") + staticSplit
|
||||
);
|
||||
};
|
||||
|
||||
const changeLimitsLine = [
|
||||
@@ -37,8 +44,21 @@ const changeLimitsLine = [
|
||||
|
||||
const costDriversLine = `More steps is the usual reason a run costs more than the work looks: every turn resends the prompt, the tool list and the whole transcript, so a long run grows with the square of its turns. A long session makes every reply cost more too (${generalSettingsRef({ section: "sessions", field: "max_messages" })} starts a new one sooner).`;
|
||||
|
||||
/**
|
||||
* The working-context setting as a run reads it today: unlimited means the
|
||||
* model's own window, less the room its answer needs, never "no ceiling",
|
||||
* since a bot reporting "unlimited of context per turn" tells the user
|
||||
* nothing about what actually bounded the run.
|
||||
*/
|
||||
const contextToday = (value: RunLimit | null) => {
|
||||
if (value === null) return "an unrecorded amount";
|
||||
if (isUnlimitedLimit(value)) return "the model's own window, less the room its answer needs";
|
||||
|
||||
return `${count(value)} tokens`;
|
||||
};
|
||||
|
||||
const todayLine = ({ current }: { current: CurrentRunLimits }) =>
|
||||
`Today's settings: ${limitText({ value: current.task_steps, none: "an unrecorded number of" })} steps per task, ${limitText({ value: current.reply_steps, none: "an unrecorded number of" })} per reply, ${limitText({ value: current.unattended_steps, none: "an unrecorded number of" })} per routine or hook call, ${limitText({ value: current.run_tokens, none: "an unrecorded number of" })} prompt tokens per run, ${limitText({ value: current.context_tokens, none: "an unrecorded working context" })} tokens of working context per turn.`;
|
||||
`Today's settings: ${limitText({ value: current.task_steps, none: "an unrecorded number of" })} steps per task, ${limitText({ value: current.reply_steps, none: "an unrecorded number of" })} per reply, ${limitText({ value: current.unattended_steps, none: "an unrecorded number of" })} per routine or hook call, ${limitText({ value: current.run_tokens, none: "an unrecorded number of" })} prompt tokens per run, ${contextToday(current.context_tokens)} of working context per turn.`;
|
||||
|
||||
/**
|
||||
* What one run spent, in the shape a bot reports it: what it cost, the
|
||||
|
||||
Reference in New Issue
Block a user