Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3671d9b72e | ||
|
|
78d7f66528 | ||
|
|
09b8269ced | ||
|
|
8b30480ceb |
@@ -219,8 +219,8 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 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 any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: 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`).
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) 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.
|
||||
- **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; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: 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`.
|
||||
- **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 `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `read_settings`, `read_message_usage`, `start_task`, `hand_over_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
|
||||
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.20.0",
|
||||
"version": "0.20.1",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
type Props = {
|
||||
text: string;
|
||||
@@ -12,17 +12,7 @@ type Props = {
|
||||
export default function FilePreviewCode({ text }: Props) {
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full overflow-auto p-4 items-stretch">
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10 whitespace-pre-wrap wrap-anywhere"
|
||||
>
|
||||
{text}
|
||||
</CodeBlock>
|
||||
<SunkenCodeBlock wrapAnywhere>{text}</SunkenCodeBlock>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
/**
|
||||
* twui's CodeBlock is a fixed dark block with a white copy icon. Everywhere
|
||||
* the app shows code it wants the theme's sunken surface instead, so this
|
||||
* wrapper is the one place that decides that: a light-mode Details modal
|
||||
* once showed dark-on-dark text because the block stayed `#28272b`.
|
||||
*/
|
||||
describe("SunkenCodeBlock", () => {
|
||||
test("rides the theme's sunken surface", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls -la</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("outline-hairline");
|
||||
});
|
||||
|
||||
test("draws the copy icon and its label in ink", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("stroke-ink-secondary");
|
||||
expect(html).toContain("twui-code-block-copied-text]:text-ink");
|
||||
});
|
||||
|
||||
test("sets code at 13px, and only breaks anywhere when asked", () => {
|
||||
const closing = renderToString(<SunkenCodeBlock>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
const wrapping = renderToString(<SunkenCodeBlock wrapAnywhere>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
|
||||
expect(closing).toContain("text-[13px]");
|
||||
expect(closing).not.toContain("wrap-anywhere");
|
||||
expect(wrapping).toContain("wrap-anywhere");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
children?: ReactNode;
|
||||
/**
|
||||
* Break long words as well as lines, so one unbroken token (a JSON
|
||||
* argument, a long path) never pushes the block wider than its panel.
|
||||
*/
|
||||
wrapAnywhere?: boolean;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A block of code on the theme's sunken surface rather than twui's own dark
|
||||
* block (it defaults to `#28272b`): the surface follows light and dark, so
|
||||
* the text stays legible in both. twui draws the copy icon and its "Copied!"
|
||||
* label white, so both are recoloured to the ink scale, and the block is set
|
||||
* at 13px, the size the dense views around it use.
|
||||
*/
|
||||
export default function SunkenCodeBlock({ children, wrapAnywhere, className }: Props) {
|
||||
return (
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary [&_.twui-code-block-copied-text]:text-ink",
|
||||
}}
|
||||
className={twMerge(
|
||||
"font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10",
|
||||
wrapAnywhere && "whitespace-pre-wrap wrap-anywhere",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
+29
-1
@@ -527,8 +527,36 @@ export const AppData = {
|
||||
* always holds, since step limits are unlimited by default, for runs
|
||||
* whose turns are large. The install may save its own
|
||||
* (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
*
|
||||
* 4M, not 40M: at 40M a run could spend 195 turns re-reading its own
|
||||
* notes and still be under the ceiling, which is what one task run did
|
||||
* (30M tokens, zero rows written, Nov 2026). A run that needs more than
|
||||
* 4M is a run to split, and an install can raise it to
|
||||
* `RunMaxPromptTokensMax`.
|
||||
*/
|
||||
RunMaxPromptTokens: 40_000_000,
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
/**
|
||||
* Share of its token budget a run is told about, once: past half of
|
||||
* it, every further turn costs what the answer costs, so it lands the
|
||||
* work rather than going on gathering (`tokensLowNote`).
|
||||
*/
|
||||
HarnessRunTokensWarnShare: 0.5,
|
||||
/**
|
||||
* Share of its token budget a run may spend before it is told, once,
|
||||
* that nothing has been produced yet: a quarter in, it still has room
|
||||
* to land the work, and a run that spends the whole budget measuring
|
||||
* ends with a report of what it found and none of what it was asked for
|
||||
* (`commitEarlyNote`). 0 turns it off.
|
||||
*/
|
||||
HarnessRunTokensCommitShare: 0.25,
|
||||
/**
|
||||
* How many times an identical call may fail before the run is answered
|
||||
* from that failure instead of paying for it again: one retry (a
|
||||
* transient error is worth retrying), then the note that the call
|
||||
* itself is wrong. A failing command was once repeated five times in a
|
||||
* row, each repeat resending the whole transcript.
|
||||
*/
|
||||
HarnessSameFailureRetries: 1,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
|
||||
@@ -373,6 +373,58 @@ ${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.don
|
||||
export const alreadyRanToolNote = ({ name, step }: { name: string; step: number }) =>
|
||||
`You already called ${name} with these exact arguments on step ${step + 1} of this run, and nothing has changed since. Its output is above: use that instead of calling it again.`;
|
||||
|
||||
/**
|
||||
* What a run gets back instead of paying for the same failure again: an
|
||||
* identical call (same tool, same arguments) that failed, retried once
|
||||
* (`AppData.HarnessSameFailureRetries`), fails the same way, and the error
|
||||
* is almost never about luck: it is the call itself. Nothing that could
|
||||
* have changed the outcome has run since, or the memory would have been
|
||||
* dropped.
|
||||
*/
|
||||
export const failedToolCallNote = ({
|
||||
name,
|
||||
step,
|
||||
attempts,
|
||||
error,
|
||||
}: {
|
||||
name: string;
|
||||
step: number;
|
||||
attempts: number;
|
||||
error: string;
|
||||
}) =>
|
||||
`You called ${name} with these exact arguments ${attempts} times since step ${step + 1} of this run, and it failed the same way each time: ${error}
|
||||
|
||||
Nothing has run since that could change that answer, so calling it once more only buys the same error (and resends this whole conversation). Fix the call itself: change the arguments, do the step it is missing first, or report it as blocked.`;
|
||||
|
||||
/**
|
||||
* Told once, when a run has spent `AppData.HarnessRunTokensWarnShare` of
|
||||
* the prompt tokens it may send: every further turn resends everything, so
|
||||
* what it does from here is paid for out of the answer's budget.
|
||||
*/
|
||||
export const tokensLowNote = ({ left }: { left: number }) =>
|
||||
`You have about ${Math.max(0, Math.round(left)).toLocaleString("en-US")} prompt tokens left in this run, and every further turn resends this whole conversation, so each one costs more than the last. Land the work now: write what you have to a file and finish the rest of the answer from it, or hand the rest on with start_task. Another round of gathering is not worth what is left.`;
|
||||
|
||||
/**
|
||||
* Sent once, a quarter of the way into a run's token budget, when nothing
|
||||
* has been produced yet: no file written, no record changed, nothing handed
|
||||
* on. One task run spent 195 turns and 30M tokens reading its own notes and
|
||||
* writing a single row to the database, because nothing ever asked it when
|
||||
* the work would start; the budget was far too large to arrive as a
|
||||
* deadline (`commitEarlyNote` says it while there is still room).
|
||||
*
|
||||
* It says a run already delivered through a shell reports that instead: the
|
||||
* harness can't tell an `UPDATE` from a `SELECT` (`isWritingTool`).
|
||||
*/
|
||||
export const commitEarlyNote = ({ spent, of }: { spent: number; of: number }) => {
|
||||
const share = Math.round((spent / Math.max(1, of)) * 100);
|
||||
|
||||
return `About ${share}% of this run's prompt-token budget is gone and nothing has been produced yet: no file written, nothing changed, nothing handed on. Reading is not the work.
|
||||
|
||||
Land one piece of what was asked for now, all the way through, before you open anything else: the first row, the first file, the first item of the list. Then the next. A run that finishes with everything understood and nothing delivered has failed at the job, however good the notes are.
|
||||
|
||||
If part of it has already landed some other way (a command that wrote it, a message that sent it), say plainly what landed and carry on from there.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Added to a chat reply while the bot has runs open in this conversation
|
||||
* that take in what the user writes here: a correction to one reaches it,
|
||||
|
||||
@@ -28,12 +28,50 @@ describe("fitTranscriptToContext", () => {
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
|
||||
expect(String(transcript[2]!.content)).toContain("characters of the middle of this computer_bash output");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
});
|
||||
|
||||
test("keeps both ends of what it trimmed, so the run need not call it again", () => {
|
||||
const content = `HEAD${'x'.repeat(30000)}TAIL`;
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 8000 });
|
||||
|
||||
const trimmed = String(transcript[2]!.content);
|
||||
|
||||
expect(trimmed).toStartWith("HEAD");
|
||||
expect(trimmed).toEndWith("TAIL");
|
||||
expect(trimmed).toContain("than repeating it");
|
||||
expect(trimmed.length).toBeLessThan(content.length);
|
||||
});
|
||||
|
||||
test("says nothing about ends it did not keep, for a short result", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: "short answer" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 50 });
|
||||
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 12 characters of this computer_bash output");
|
||||
});
|
||||
|
||||
test("never trims the newest messages, even over budget", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
@@ -56,7 +94,7 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
});
|
||||
|
||||
|
||||
@@ -46,6 +46,14 @@ const CharsPerToken = 3;
|
||||
* What an image or audio part is counted as, in tokens.
|
||||
*/
|
||||
const MediaTokens = 1500;
|
||||
/**
|
||||
* Characters of a trimmed tool result that are kept at each end. A trimmed
|
||||
* result used to be replaced whole, with a note telling the model to call
|
||||
* the tool again if it still needed it, so it did: the same `SELECT`, the
|
||||
* same `cat`, re-run and resent. Keeping the start and the end (the command
|
||||
* and its totals, as `truncate` does) is usually all the run still needs.
|
||||
*/
|
||||
const TrimmedKeepChars = 500;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
@@ -90,6 +98,24 @@ export default function fitTranscriptToContext({
|
||||
trimmed++;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 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 message = transcript[index]!;
|
||||
|
||||
@@ -101,7 +127,7 @@ export default function fitTranscriptToContext({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1097,3 +1097,173 @@ describe("runTextLoop trace", () => {
|
||||
expect(result.text).toBe("Done.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop repeated failures", () => {
|
||||
const failing = (id: string) => ({
|
||||
id,
|
||||
name: "computer_bash",
|
||||
arguments: JSON.stringify({ command: "python3 rb.py 22" }),
|
||||
});
|
||||
|
||||
const makeTools = () => {
|
||||
const counts = { commands: 0, writes: 0 };
|
||||
|
||||
const bash: HarnessTool<{ command: string }> = {
|
||||
name: "computer_bash",
|
||||
description: "Runs a command.",
|
||||
schema: z.object({ command: z.string() }),
|
||||
run: async () => {
|
||||
counts.commands++;
|
||||
|
||||
return "Error: Exit code: 1\nFileNotFoundError: plan/0.json";
|
||||
},
|
||||
};
|
||||
const write: HarnessTool<{ path: string }> = {
|
||||
name: "computer_write_file",
|
||||
description: "Writes a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async () => {
|
||||
counts.writes++;
|
||||
|
||||
return "Written.";
|
||||
},
|
||||
};
|
||||
|
||||
return { tools: [bash, write], counts };
|
||||
};
|
||||
|
||||
test("answers an identical failing call from its failure, after one retry", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [failing("c1")] },
|
||||
{ tool_calls: [failing("c2")] },
|
||||
{ tool_calls: [failing("c3")] },
|
||||
{ text: "Blocked: the engine path is wrong." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Run it." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.commands).toBe(1 + AppData.HarnessSameFailureRetries);
|
||||
expect(result.text).toBe("Blocked: the engine path is wrong.");
|
||||
|
||||
const results = seen[3]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(String(results[2]!.content)).toContain("failed the same way each time");
|
||||
expect(result.tool_uses.filter((use) => !use.ok)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("runs the same call again once something could have changed its answer", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate } = scripted([
|
||||
{ tool_calls: [failing("c1")] },
|
||||
{ tool_calls: [{ id: "c2", name: "computer_write_file", arguments: `{"path":"plan/22.json"}` }] },
|
||||
{ tool_calls: [failing("c3")] },
|
||||
{ text: "Done." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Set the plan up, then run it." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.writes).toBe(1);
|
||||
expect(counts.commands).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop token warning", () => {
|
||||
test("says half the token budget is gone, once", async () => {
|
||||
const turn = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
};
|
||||
const { generate, seen } = scripted([turn, turn, turn, turn, { text: "Landing it here." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const warned = ({ turn }: { turn: number }) =>
|
||||
seen[turn]!.messages.filter(
|
||||
(message) =>
|
||||
message.role == "user" &&
|
||||
typeof message.content == "string" &&
|
||||
message.content.includes("prompt tokens left in this run"),
|
||||
).length;
|
||||
|
||||
expect(warned({ turn: 1 })).toBe(0);
|
||||
expect(warned({ turn: 2 })).toBe(1);
|
||||
expect(warned({ turn: 4 })).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop commit early", () => {
|
||||
const reading = (id: string) => ({
|
||||
tool_calls: [{ id, name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
});
|
||||
const wrote = (id: string) => ({
|
||||
tool_calls: [{ id, name: "write_file", arguments: "{}" }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
});
|
||||
const write_file: HarnessTool = {
|
||||
name: "write_file",
|
||||
description: "Writes a file.",
|
||||
schema: z.object({}),
|
||||
run: async () => "Written.",
|
||||
};
|
||||
const committed = ({ turn, seen }: { turn: number; seen: GenerateTextParams[] }) =>
|
||||
seen[turn]!.messages.filter(
|
||||
(message) =>
|
||||
message.role == "user" &&
|
||||
typeof message.content == "string" &&
|
||||
message.content.includes("nothing has been produced yet"),
|
||||
).length;
|
||||
|
||||
test("tells a run that has only been reading to land a piece of the work, once", async () => {
|
||||
const { generate, seen } = scripted([reading("a"), reading("b"), reading("c"), { text: "Done." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(committed({ turn: 0, seen })).toBe(0);
|
||||
expect(committed({ turn: 1, seen })).toBe(1);
|
||||
expect(committed({ turn: 3, seen })).toBe(1);
|
||||
});
|
||||
|
||||
test("says nothing to a run that has already written something", async () => {
|
||||
const { generate, seen } = scripted([wrote("a"), wrote("b"), wrote("c"), { text: "Done." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [write_file],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(committed({ turn: 1, seen })).toBe(0);
|
||||
expect(committed({ turn: 3, seen })).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, commitEarlyNote, failedToolCallNote, tokensLowNote } from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import HarnessError from "../harness-error";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey from "../tools/repeat-tool-call-key";
|
||||
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
import isRepeatableTool from "../tools/repeatable-tool-names";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import type { ToolCallResult } from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import isWritingTool from "../tools/writing-tool-names";
|
||||
import type { HarnessTrace, HarnessTracer } from "../trace/types";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
@@ -327,6 +329,16 @@ export default async function runTextLoop({
|
||||
* read again.
|
||||
*/
|
||||
const repeated_reads = new Map<string, number>();
|
||||
/**
|
||||
* The calls that failed, by the call they answer (`toolCallKey`), with
|
||||
* the step the first of them ran on and the error it gave. An identical
|
||||
* call past `AppData.HarnessSameFailureRetries` is answered from here
|
||||
* instead of being run: it fails the same way, and each repeat resends
|
||||
* the whole transcript (one run paid five times for the same
|
||||
* `FileNotFoundError`). Anything that could change the outcome clears
|
||||
* them, so a call retried after the missing piece was put in place runs.
|
||||
*/
|
||||
const failed_calls = new Map<string, { step: number; attempts: number; error: string }>();
|
||||
/**
|
||||
* The tools a wrap up may still call: what saves the work, and
|
||||
* `start_task` for the work it can't finish. A run that spent every
|
||||
@@ -359,6 +371,28 @@ export default async function runTextLoop({
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
let warned_steps = isUnlimitedLimit(max_steps) || max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
/**
|
||||
* The prompt tokens past which the run is told to land the work
|
||||
* (`AppData.HarnessRunTokensWarnShare` of its budget), and whether it has
|
||||
* been told. A run with no token budget has none to be near the end of.
|
||||
*/
|
||||
const tokens_warn_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensWarnShare)
|
||||
: Infinity;
|
||||
let warned_tokens = tokens_warn_at == Infinity;
|
||||
/**
|
||||
* A quarter of the budget with nothing produced yet: research is not
|
||||
* progress, and a run that spends the whole budget reading lands its
|
||||
* report but none of the work (one task run did exactly that: 195
|
||||
* turns, 30M tokens, zero rows written, Nov 2026). Said once, while
|
||||
* there is still budget to land the rest.
|
||||
*/
|
||||
const commits_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensCommitShare)
|
||||
: Infinity;
|
||||
let told_to_commit = commits_at == Infinity;
|
||||
/**
|
||||
* The wrap up is announced once, and may save until it has: a run told
|
||||
* to stop with its report unwritten gets a turn to write it (at most
|
||||
@@ -563,6 +597,10 @@ export default async function runTextLoop({
|
||||
for (const call of tool_calls) {
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
const call_key = toolCallKey({ call });
|
||||
const failed_before = call_key ? failed_calls.get(call_key) : undefined;
|
||||
const give_up =
|
||||
failed_before !== undefined && failed_before.attempts > AppData.HarnessSameFailureRetries;
|
||||
|
||||
const result: ToolCallResult =
|
||||
already_read !== undefined
|
||||
@@ -571,9 +609,21 @@ export default async function runTextLoop({
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
: give_up
|
||||
? {
|
||||
text: failedToolCallNote({
|
||||
name: call.name,
|
||||
step: failed_before.step,
|
||||
attempts: failed_before.attempts,
|
||||
error: failed_before.error,
|
||||
}),
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
const { text: content, images } = result;
|
||||
const ok = !give_up && !content.startsWith("Error:");
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
@@ -583,7 +633,7 @@ export default async function runTextLoop({
|
||||
loaded.push(call.name);
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
tool_uses.push({ name: call.name, ok });
|
||||
|
||||
await traced({
|
||||
kind: "tool",
|
||||
@@ -591,10 +641,10 @@ export default async function runTextLoop({
|
||||
name: call.name,
|
||||
arguments: call.arguments,
|
||||
result: content,
|
||||
ok: !content.startsWith("Error:"),
|
||||
ok,
|
||||
images: images.length,
|
||||
duration_ms: result.duration_ms,
|
||||
repeat_of: already_read ?? null,
|
||||
repeat_of: (give_up ? failed_before.step : already_read) ?? null,
|
||||
});
|
||||
|
||||
if (!repeat_key) {
|
||||
@@ -604,6 +654,22 @@ export default async function runTextLoop({
|
||||
else repeated_reads.set(repeat_key, index);
|
||||
}
|
||||
|
||||
if (give_up) {
|
||||
failed_calls.set(call_key!, { ...failed_before, attempts: failed_before.attempts + 1 });
|
||||
} else if (content.startsWith("Error:")) {
|
||||
if (call_key) {
|
||||
const earlier = failed_calls.get(call_key);
|
||||
|
||||
failed_calls.set(call_key, {
|
||||
step: earlier?.step ?? index,
|
||||
attempts: (earlier?.attempts ?? 0) + 1,
|
||||
error: earlier?.error ?? clipFailure({ text: content }),
|
||||
});
|
||||
}
|
||||
} else if (!call_key || !isRepeatableTool({ name: call.name })) {
|
||||
failed_calls.clear();
|
||||
}
|
||||
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
|
||||
if (images.length) shown.push({ tool_name: call.name, images });
|
||||
@@ -628,6 +694,31 @@ export default async function runTextLoop({
|
||||
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote, index });
|
||||
|
||||
/**
|
||||
* What this turn spent: past the budget, the wrap up says it better
|
||||
* (`wrapUpPrompt`) than either note below.
|
||||
*/
|
||||
const spent_out =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens;
|
||||
|
||||
/**
|
||||
* Something produced, or a quarter of the budget gone without it:
|
||||
* said before the steps are nearly out, so a run still has room to
|
||||
* land the work rather than reporting on it. A run that has written
|
||||
* anything at all is left alone; one that landed its work through a
|
||||
* shell says so (`commitEarlyNote`).
|
||||
*/
|
||||
if (tool_uses.some((used) => used.ok && isWritingTool({ name: used.name }))) told_to_commit = true;
|
||||
|
||||
if (!told_to_commit && !spent_out && usage.prompt_tokens >= commits_at) {
|
||||
told_to_commit = true;
|
||||
|
||||
const note = commitEarlyNote({ spent: usage.prompt_tokens, of: max_prompt_tokens as number });
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "commit_early", text: note });
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
* An unlimited run is never told it's nearly out: it has no budget
|
||||
@@ -640,6 +731,21 @@ export default async function runTextLoop({
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
await traced({ kind: "event", index, name: "steps_low", text: stepsLowNote({ left }) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Half the token budget gone, once: every further turn resends this
|
||||
* whole conversation, so what the run does next is paid for out of
|
||||
* the answer. Skipped when the turn just spent the budget out: the
|
||||
* wrap up says it better (`wrapUpPrompt`).
|
||||
*/
|
||||
if (!warned_tokens && !spent_out && usage.prompt_tokens >= tokens_warn_at) {
|
||||
warned_tokens = true;
|
||||
|
||||
const tokens_left = (max_prompt_tokens as number) - usage.prompt_tokens;
|
||||
|
||||
pushUserTurn({ transcript, content: tokensLowNote({ left: tokens_left }) });
|
||||
await traced({ kind: "event", index, name: "tokens_low", text: tokensLowNote({ left: tokens_left }) });
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unreachable: the text loop ended without an answer.`);
|
||||
@@ -673,3 +779,16 @@ export default async function runTextLoop({
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Characters of a failure a repeated call's note keeps: a failing command
|
||||
* can print a whole traceback, and the note is resent with every turn
|
||||
* after it.
|
||||
*/
|
||||
const FailureNoteChars = 400;
|
||||
|
||||
/**
|
||||
* The error a repeated call's note reuses, cut to `FailureNoteChars`.
|
||||
*/
|
||||
const clipFailure = ({ text }: { text: string }) =>
|
||||
text.length <= FailureNoteChars ? text : `${text.slice(0, FailureNoteChars)}...`;
|
||||
|
||||
@@ -4,13 +4,14 @@ import isRepeatableTool from "./repeatable-tool-names";
|
||||
/**
|
||||
* What makes two calls the same call: the tool and its arguments, whatever
|
||||
* order the model wrote their keys in (a model re-reads a file it read
|
||||
* before with the same fields in another order). Null for a tool whose
|
||||
* answer may change, and for arguments that aren't a JSON object, which
|
||||
* `runToolCall` turns down anyway.
|
||||
* before with the same fields in another order). Null for arguments that
|
||||
* aren't a JSON object, which `runToolCall` turns down anyway.
|
||||
*
|
||||
* Every tool has one, not only the reads: a failing call repeated word for
|
||||
* word is answered from its failure (`runTextLoop`), since it fails the
|
||||
* same way rather than by luck.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
export function toolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
let args: unknown;
|
||||
|
||||
try {
|
||||
@@ -24,6 +25,16 @@ export default function repeatToolCallKey({ call }: { call: HarnessToolCall }):
|
||||
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two reads the same read: null for a tool whose answer may
|
||||
* change (anything with a side effect), which is answered by running it.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
return toolCallKey({ call });
|
||||
}
|
||||
|
||||
/**
|
||||
* The value with every object's keys sorted, so two spellings of the same
|
||||
* arguments compare equal.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import isWritingTool, { WritingToolNames } from "./writing-tool-names";
|
||||
|
||||
test("counts the tools that leave something behind", () => {
|
||||
for (const name of ["write_file", "import_file", "computer_edit_file", "update_task", "start_task", "set_picture"]) {
|
||||
expect(isWritingTool({ name })).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("counts none of the tools that only read", () => {
|
||||
for (const name of ["read_file", "list_files", "computer_read_file", "list_tasks", "search_computers", "load_tools"]) {
|
||||
expect(isWritingTool({ name })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves computer_bash out, so a shell-driven run can still be told to land the work", () => {
|
||||
expect(isWritingTool({ name: "computer_bash" })).toBe(false);
|
||||
expect(WritingToolNames.includes("computer_bash")).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Tools that leave something behind: a file written, a record changed, a
|
||||
* graphic or a picture made, work handed on. `runTextLoop` reads this to
|
||||
* tell a run that has produced something from one that has only been
|
||||
* reading, so a run measuring its way through a whole budget is told to
|
||||
* land a piece of the work while there is still room (`commitEarlyNote`).
|
||||
*
|
||||
* `computer_bash` is deliberately not here: it is the one tool that both
|
||||
* reads and writes (a `SELECT` and an `UPDATE` look the same to the
|
||||
* harness), so counting it would let a shell-driven run research its way to
|
||||
* the ceiling and never be told. A run that has already landed work that
|
||||
* way says so in its answer, and the note asks it to.
|
||||
*/
|
||||
export const WritingToolNames: readonly string[] = [
|
||||
"write_file",
|
||||
"import_file",
|
||||
"copy_file",
|
||||
"move_file",
|
||||
"delete_file",
|
||||
"computer_write_file",
|
||||
"computer_edit_file",
|
||||
"make_pdf",
|
||||
"create_graphic",
|
||||
"update_graphic",
|
||||
"set_picture",
|
||||
"transform_image",
|
||||
"generate_image",
|
||||
"generate_video",
|
||||
"create_task",
|
||||
"update_task",
|
||||
"delete_task",
|
||||
"create_schedule",
|
||||
"update_schedule",
|
||||
"delete_schedule",
|
||||
"hand_over_schedule",
|
||||
"hand_over_task",
|
||||
"update_memory",
|
||||
"update_instructions",
|
||||
"set_bot_workspace_instructions",
|
||||
"capture_secret",
|
||||
"request_install",
|
||||
"answer_install_request",
|
||||
"start_task",
|
||||
"delegate_task",
|
||||
"ask_crew",
|
||||
"create_bot",
|
||||
"update_bot",
|
||||
"delete_bot",
|
||||
"create_workspace",
|
||||
"update_workspace",
|
||||
"delete_workspace",
|
||||
"add_bot_to_workspace",
|
||||
"remove_bot_from_workspace",
|
||||
"assign_computer",
|
||||
"set_workspace_computer",
|
||||
"set_bot_type",
|
||||
"set_extension_access",
|
||||
"set_user_workspace_role",
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a successful call to this tool produced something.
|
||||
*/
|
||||
export default function isWritingTool({ name }: { name: string }) {
|
||||
return WritingToolNames.includes(name);
|
||||
}
|
||||
@@ -33,8 +33,9 @@ export type HarnessToolTrace = {
|
||||
images: number;
|
||||
duration_ms: number;
|
||||
/**
|
||||
* The step whose identical read answered this call, when the loop
|
||||
* skipped it (`alreadyRanToolNote`).
|
||||
* The step this call was answered from instead of being run: the one
|
||||
* whose identical read answered it (`alreadyRanToolNote`), or the one
|
||||
* whose identical failure did (`failedToolCallNote`).
|
||||
*/
|
||||
repeat_of?: number | null;
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Bug } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
@@ -10,7 +11,12 @@ import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
import TracePanel from "./trace-panel";
|
||||
|
||||
/**
|
||||
* The debug strip is its own chunk: most conversations never open it, and
|
||||
* the page's first load is what the bundle budget is about.
|
||||
*/
|
||||
const TracePanel = lazy(() => import("./trace-panel"));
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -131,7 +137,9 @@ export default function BotThinkingRow({
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
{debug_open && on_toggle_debug ? (
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
<Suspense fallback={null}>
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isValidElement, type ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import SunkenCodeBlock from "@/src/components/general/sunken-code-block";
|
||||
|
||||
/**
|
||||
* A fenced code block in a bot message, on the sunken surface with
|
||||
@@ -10,17 +10,5 @@ export default function MarkdownCodeBlock({ children }: { children?: ReactNode }
|
||||
? (children.props as { children?: ReactNode }).children
|
||||
: children;
|
||||
|
||||
return (
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10"
|
||||
>
|
||||
{code}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
return <SunkenCodeBlock>{code}</SunkenCodeBlock>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
@@ -10,10 +10,15 @@ import { Info } from "lucide-react";
|
||||
import useMessageDetails from "../(hooks)/use-message-details";
|
||||
import CopyMessageDetailsButton from "./copy-message-details-button";
|
||||
import MessageActionButton from "./message-action-button";
|
||||
import MessageDebugLogs from "./message-debug-logs";
|
||||
import MessageDetailsBody from "./message-details-body";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
/**
|
||||
* Only the modal's second tab needs the logs, and only once it's opened, so
|
||||
* it loads as its own chunk rather than with the conversation.
|
||||
*/
|
||||
const MessageDebugLogs = lazy(() => import("./message-debug-logs"));
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
@@ -94,7 +99,9 @@ export default function MessageDetailsModal({ message_id, tool_log, chatroom_id
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
<Suspense fallback={null}>
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
import TraceBlock from "./trace-block";
|
||||
|
||||
/**
|
||||
* A trace block is read inside the Details modal and the debug strip, on
|
||||
* whichever theme the user has. Code used to come out of twui's own dark
|
||||
* block (a fixed `#28272b`), which left dark-on-dark text in light mode and
|
||||
* set the block larger than the log around it.
|
||||
*/
|
||||
describe("TraceBlock", () => {
|
||||
test("code sits on the theme's sunken surface, never twui's dark block", () => {
|
||||
const html = renderToString(<TraceBlock label="What it was sent" kind="code" text={'{"command":"ls"}'} />);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("text-ink");
|
||||
});
|
||||
|
||||
test("code and prose share the log's size", () => {
|
||||
const code = renderToString(<TraceBlock kind="code" text={"ls -la"} />);
|
||||
const prose = renderToString(<TraceBlock text="Two tabs are open." />);
|
||||
|
||||
expect(code).toContain("text-[13px]");
|
||||
expect(code).toContain("leading-5");
|
||||
expect(prose).toContain("text-[13px]");
|
||||
expect(prose).toContain("leading-5");
|
||||
});
|
||||
|
||||
test("a long text is cut until it is opened", () => {
|
||||
const text = `start ${"x".repeat(TracePreviewChars)}end`;
|
||||
|
||||
const cut = renderToString(<TraceBlock kind="code" text={text} />);
|
||||
const whole = renderToString(<TraceBlock kind="code" text="short" />);
|
||||
|
||||
expect(cut).toContain("start");
|
||||
expect(cut).not.toContain("end");
|
||||
expect(cut).toContain(`Show all ${text.length.toLocaleString()} characters`);
|
||||
expect(whole).not.toContain("Show all");
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import SunkenCodeBlock from "@/src/components/general/sunken-code-block";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
|
||||
type Props = {
|
||||
@@ -40,11 +39,9 @@ export default function TraceBlock({ label, text, kind = "text" }: Props) {
|
||||
</Span>
|
||||
) : null}
|
||||
{kind == "code" ? (
|
||||
<CodeBlock>{shown}</CodeBlock>
|
||||
<SunkenCodeBlock wrapAnywhere>{shown}</SunkenCodeBlock>
|
||||
) : (
|
||||
<P className={twMerge("py-0 whitespace-pre-wrap text-sm text-ink")}>
|
||||
{shown}
|
||||
</P>
|
||||
<P className="py-0 whitespace-pre-wrap text-[13px] leading-5 text-ink">{shown}</P>
|
||||
)}
|
||||
{long ? (
|
||||
<Row className="w-full items-center gap-2">
|
||||
|
||||
Reference in New Issue
Block a user