@mikode13/harness 8.0.0 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -3
- package/dist/engines/domain/model/llmAgent.js +26 -8
- package/dist/engines/domain/model/llmAgent.js.map +1 -1
- package/dist/factory/infrastructure/agentLLMFactory.d.ts +2 -2
- package/dist/factory/infrastructure/agentLLMFactory.js +13 -9
- package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
- package/dist/llm/infrastructure/claudeLLMClient.js +3 -3
- package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
- package/dist/tools/infrastructure/fileTools.d.ts +3 -2
- package/dist/tools/infrastructure/fileTools.js +7 -6
- package/dist/tools/infrastructure/fileTools.js.map +1 -1
- package/dist/tools/infrastructure/trackedReadFile.d.ts +5 -0
- package/dist/tools/infrastructure/trackedReadFile.js +21 -1
- package/dist/tools/infrastructure/trackedReadFile.js.map +1 -1
- package/dist/tools/infrastructure/workspaceTools.d.ts +23 -1
- package/dist/tools/infrastructure/workspaceTools.js +53 -1
- package/dist/tools/infrastructure/workspaceTools.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -449,7 +449,9 @@ ends the run with an `UnrecoverableError`. The Agent SDK engines ignore `ask`, a
|
|
|
449
449
|
`createFileTools` gives an agent the file tools of its provider, over the folders you
|
|
450
450
|
declare, each `read` or `write`:
|
|
451
451
|
|
|
452
|
-
- **OpenAI** gets `listFiles`, `searchText`, `readFile` and its native
|
|
452
|
+
- **OpenAI** gets `listFiles`, `searchText`, `readFile`, `readFiles` and its native
|
|
453
|
+
`apply_patch`. `readFiles` reads up to 10 files or ranges in one call, and reports a file
|
|
454
|
+
it cannot read in its place.
|
|
453
455
|
- **Anthropic** gets `listFiles`, `searchText`, its native text editor (whose `view`
|
|
454
456
|
reads) and `delete_file`.
|
|
455
457
|
|
|
@@ -505,8 +507,9 @@ model APIs:
|
|
|
505
507
|
- the planner and the reviewer read, with a `showChanges` tool that gives the current task's
|
|
506
508
|
changes as far as each may read them, and an `explore` tool that sends up to 4 read-only
|
|
507
509
|
explorers at once, one per question, on the role's provider's cheaper model at `medium`:
|
|
508
|
-
Claude Haiku 5.5, or `gpt-5.6-luna`. Each starts from its question alone and reports
|
|
509
|
-
|
|
510
|
+
Claude Haiku 5.5, or `gpt-5.6-luna`. Each starts from its question alone and reports where
|
|
511
|
+
the answer is, the files and line ranges, as a librarian says where a book is; the role
|
|
512
|
+
then reads those ranges itself, with `readFiles`, instead of searching the repository. Their
|
|
510
513
|
usage counts in the run's, and their narration arrives as `subagent` events;
|
|
511
514
|
- the executor gets its provider's file tools. `autoApprove` reaches only the executor;
|
|
512
515
|
- each role gets the commands whose `roles` name it; a command names only the executor unless
|
|
@@ -625,6 +625,15 @@ export class LLMAgent {
|
|
|
625
625
|
const offersAsk = options.ask !== undefined && !this.tools.has(askUserName);
|
|
626
626
|
const tools = offersAsk ? [...this.toolDefinitions, askUserDefinition] : this.toolDefinitions;
|
|
627
627
|
seen.tools = tools;
|
|
628
|
+
// Recorded only once the run ends in a way that keeps it, so it never leaves a tool call
|
|
629
|
+
// without its result; a run that is not kept gives its note on what was undone again.
|
|
630
|
+
const remember = () => {
|
|
631
|
+
this.conversation.addRunAfter(after, runMessages, context.historyRun);
|
|
632
|
+
// With the turns that read them, and only then.
|
|
633
|
+
reads.commit();
|
|
634
|
+
if (followed)
|
|
635
|
+
this.seenRevision = followed.latestRevision;
|
|
636
|
+
};
|
|
628
637
|
for (let step = 1; step <= this.maxSteps; step++) {
|
|
629
638
|
const { response, context: sent } = await this.llmCall(runMessages, after, {
|
|
630
639
|
signal,
|
|
@@ -637,8 +646,23 @@ export class LLMAgent {
|
|
|
637
646
|
// After the tokens are counted, so a throwing callback still reports them, and for an
|
|
638
647
|
// unusable answer too: the call was sent, and billed.
|
|
639
648
|
this.narrateStep(step, response.usage, { context: sent, tools }, callback);
|
|
649
|
+
if (response.stopReason === 'truncated') {
|
|
650
|
+
// What it wrote before the output limit, kept with the run so the next run can
|
|
651
|
+
// take it up. Not its calls, whose input may be cut, nor what only the provider
|
|
652
|
+
// reads back, which it may refuse incomplete.
|
|
653
|
+
const written = response.message.content.filter(part => part.type === 'text' || part.type === 'reasoning');
|
|
654
|
+
for (const part of written)
|
|
655
|
+
narrate(part, callback);
|
|
656
|
+
if (written.length > 0)
|
|
657
|
+
runMessages.push({ role: 'assistant', content: written });
|
|
658
|
+
remember();
|
|
659
|
+
throw new UnrecoverableError('The LLM stopped before completing its answer', {
|
|
660
|
+
cause: 'The model stopped with "truncated". The run, and what the answer held before the limit, are kept in the conversation.',
|
|
661
|
+
});
|
|
662
|
+
}
|
|
640
663
|
if (response.stopReason !== 'completed') {
|
|
641
|
-
// Its tokens are already counted with the run's, which the failure carries.
|
|
664
|
+
// Its tokens are already counted with the run's, which the failure carries. A run
|
|
665
|
+
// that ends so is not remembered.
|
|
642
666
|
throw new UnrecoverableError('The LLM stopped before completing its answer', {
|
|
643
667
|
cause: `The model stopped with "${response.stopReason}".`,
|
|
644
668
|
});
|
|
@@ -651,13 +675,7 @@ export class LLMAgent {
|
|
|
651
675
|
}
|
|
652
676
|
const calls = response.message.content.filter(part => part.type === 'toolCall');
|
|
653
677
|
if (calls.length === 0) {
|
|
654
|
-
|
|
655
|
-
// note about what was undone is given again to the next run.
|
|
656
|
-
this.conversation.addRunAfter(after, runMessages, context.historyRun);
|
|
657
|
-
// With the turns that read them, and only then: a failed run is not remembered.
|
|
658
|
-
reads.commit();
|
|
659
|
-
if (followed)
|
|
660
|
-
this.seenRevision = followed.latestRevision;
|
|
678
|
+
remember();
|
|
661
679
|
return {
|
|
662
680
|
// Only the final answer: text from earlier steps was narrated as it came.
|
|
663
681
|
response: response.message.content
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llmAgent.js","sourceRoot":"","sources":["../../../../src/engines/domain/model/llmAgent.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,YAAY,GACZ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I,CAAC,QAAQ,EAAE,CAAC;oBAC1B,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,QAAQ,CAClC,KAAK,EACL,OAAO,EACP,OAAO,EACP,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,EAC1C,qBAAqB,EACrB,OAAO,CACP,CAAC;oBACF,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC3B,CAAC;YACF,CAAC;YAED,MAAM,IAAI,kBAAkB,CAAC,8CAA8C,EAAE;gBAC5E,KAAK,EAAE,2CAA2C,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS;aAChF,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,OAAO,GAAG,KAAK,CAAC;YACpB,IAAI,OAAO,CAAC,OAAO,IAAI,KAAK,YAAY,gBAAgB,EAAE,CAAC;gBAC1D,kFAAkF;gBAClF,wEAAwE;gBACxE,MAAM,aAAa,GAAG,IAAI,kBAAkB,CAAC,KAAK,CAAC,OAAO,EAAE;oBAC3D,KAAK,EAAE,KAAK,CAAC,KAAK;oBAClB,MAAM,EAAE,KAAK,CAAC,MAAM;oBACpB,eAAe,EAAE,KAAK,CAAC,eAAe;iBACtC,CAAC,CAAC;gBACH,aAAa,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;gBAClC,OAAO,GAAG,aAAa,CAAC;YACzB,CAAC;YAED,qEAAqE;YACrE,MAAM,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;QACpD,CAAC;IACF,CAAC;CACD","sourcesContent":["import {\n\ttype ApprovalDecision,\n\ttype ApprovalRequest,\n\ttype Approver,\n\treadDecision,\n} from '#src/agent/domain/approval';\nimport {\n\ttype Agent,\n\ttype AgentResponse,\n\ttype Callback,\n\ttype ProgressEvent,\n\ttype RunOptions,\n\tignoreProgress,\n} from '#src/agent/domain/agent';\nimport {\n\ttype RunEnd,\n\tRunContext,\n\trunContextOf,\n\twithRunContext,\n} from '#src/agent/domain/runContext';\nimport {\n\tInvalidAgentConfigError,\n\tRecoverableError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { Conversation } from '#src/llm/domain/conversation';\nimport type { LLMClient, LLMResponse } from '#src/llm/domain/llm';\nimport type { Message, MessagePart, ToolCallPart, ToolResultPart } from '#src/llm/domain/message';\nimport { asNative, nativeOf, type ToolDefinition } from '#src/llm/domain/tool';\nimport type { Asker } from '#src/agent/domain/question';\nimport type { Transcript, TranscriptCallback } from '#src/agent/domain/transcript';\nimport {\n\ttype AgentTool,\n\ttype PreparedCall,\n\tprepareCall,\n\tToolExecutionError,\n} from '#src/tools/domain/preparedCall';\nimport { ReadRegistry, type ToolCallContext } from '#src/tools/domain/readRegistry';\n\n/** What every tool call of one batch shares; each call adds its own id. */\ntype RunToolContext = Omit<ToolCallContext, 'callId'>;\nimport { InvalidToolInputError } from '#src/tools/domain/tool';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { measureContext } from './stepContext.ts';\nimport {\n\taskUserDefinition,\n\taskUserName,\n\tdescribeAnswers,\n\treadAnswers,\n\treadQuestions,\n\tsummarizeQuestions,\n} from './askUser.ts';\nimport {\n\ttype Followed,\n\tfollowHistory,\n\ttype HistoryReader,\n\ttranscriptOf,\n\tundoNote,\n} from './historyFollower.ts';\n\nfunction describePart(part: MessagePart): ProgressEvent | undefined {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn { type: 'agentMessage', message: part.text };\n\t\tcase 'reasoning':\n\t\t\treturn { type: 'reasoning', message: part.text };\n\t\tcase 'toolCall':\n\t\t\treturn { type: 'tool', id: part.id, name: part.name, status: 'in_progress' };\n\t\tcase 'toolResult':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tid: part.callId,\n\t\t\t\tname: part.name,\n\t\t\t\tstatus: part.isError ? 'error' : 'completed',\n\t\t\t\t...(part.isError ? { error: part.output } : {}),\n\t\t\t};\n\t\tcase 'providerData':\n\t\t\t// Opaque by design: its readable side, if any, arrives as a reasoning part.\n\t\t\treturn undefined;\n\t\tcase 'compaction':\n\t\t\t// The provider's, for its client to send back; the step's context shows its effect.\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether a run reached a tool's `execute`. A missing tool or a denied call never does, so it\n * has no effect a retry could repeat.\n */\ninterface RunEffects {\n\ttoolRan: boolean;\n}\n\n/** What a run has shown the model, for its transcript. */\ninterface Seen {\n\tmessages: () => Message[];\n\ttools: ToolDefinition[];\n}\n\nfunction narrate(part: MessagePart, callback: Callback, summary?: string, exitCode?: number): void {\n\tconst event = describePart(part);\n\tif (!event) return;\n\tif (event.type === 'tool') {\n\t\tif (summary !== undefined) event.summary = summary;\n\t\tif (exitCode !== undefined) event.exitCode = exitCode;\n\t}\n\temit(event, callback);\n}\n\nfunction emit(event: ProgressEvent, callback: Callback): void {\n\ttreatErrors(\n\t\t() => {\n\t\t\tcallback(event);\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'LLM agent progress callback failed',\n\t);\n}\n\n/** `value` with the keys of every object sorted, so equal inputs serialize alike. */\nfunction canonical(value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map(canonical);\n\tif (typeof value !== 'object' || value === null) return value;\n\treturn Object.fromEntries(\n\t\tObject.entries(value)\n\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t\t.map(([key, inner]) => [key, canonical(inner)]),\n\t);\n}\n\n// A model that asks for exactly the same calls this many times in a row is stuck: it already\n// has what they return, and running them again changes nothing.\nconst maxRepeatedSteps = 5;\n\n/** How many steps in a row have asked for exactly the same tool calls, with the same input. */\nclass RepeatedCalls {\n\tprivate last: string | undefined;\n\tprivate times = 0;\n\n\tcount(calls: readonly ToolCallPart[]): number {\n\t\t// Keys sorted at every level: the same input with its properties in another order is the\n\t\t// same call. Arrays, and the order of the calls, keep theirs.\n\t\tconst key = JSON.stringify(calls.map(call => [call.name, canonical(call.input)]));\n\t\tthis.times = key === this.last ? this.times + 1 : 1;\n\t\tthis.last = key;\n\t\treturn this.times;\n\t}\n}\n\n// A command that ends exactly as it did the last times, in output too, this many times in a row\n// means the model's changes in between are not reaching what the command checks.\nconst maxRepeatedEndings = 5;\n\n/**\n * How many times in a row each command call, by tool and input, has ended exactly the same way.\n * Calls in between to other tools, or to other commands, do not break the count.\n */\nclass RepeatedEndings {\n\tprivate readonly last = new Map<string, { ending: string; times: number }>();\n\n\tcount(call: ToolCallPart, ending: string | undefined): number {\n\t\tconst key = JSON.stringify([call.name, canonical(call.input)]);\n\t\t// A call that never ran a command, such as one denied, says nothing of how it ends.\n\t\tif (ending === undefined) {\n\t\t\tthis.last.delete(key);\n\t\t\treturn 0;\n\t\t}\n\t\tconst previous = this.last.get(key);\n\t\tconst times = previous?.ending === ending ? previous.times + 1 : 1;\n\t\tthis.last.set(key, { ending, times });\n\t\treturn times;\n\t}\n}\n\n/**\n * An agent whose conversation is owned by MiKode: every run sends the whole context to a\n * stateless `LLMClient`. Within a run the model may call the agent's tools; the agent runs them\n * and sends their results back until the model answers without calling one. Turn boundaries\n * are the consumer's to emit, as with the other engines; this agent only narrates what the\n * model produced and what its tools did.\n */\nexport class LLMAgent implements Agent {\n\tprivate readonly llmClient: LLMClient;\n\tprivate readonly conversation: Conversation;\n\tprivate readonly tools: Map<string, AgentTool>;\n\tprivate readonly toolDefinitions: ToolDefinition[];\n\t// Each call's summary, as its tool gave it when the call ran, so measuring a step that\n\t// resends the call never runs a consumer's summarizer again.\n\tprivate readonly callSummaries = new Map<string, string>();\n\tprivate readonly maxSteps: number;\n\tprivate readonly autoApprove: boolean;\n\tprivate readonly logger: ILogger | undefined;\n\tprivate readonly history: HistoryReader | undefined;\n\tprivate readonly summarizer: LLMClient | undefined;\n\tprivate readonly onTranscript: TranscriptCallback | undefined;\n\t// The latest move through the history this conversation has followed.\n\tprivate seenRevision = 0;\n\t// What this conversation has seen of each file, so an edit starts from a version it read.\n\tprivate readonly reads = new ReadRegistry();\n\n\tconstructor({\n\t\tllmClient,\n\t\tmessages,\n\t\ttools = [],\n\t\tmaxSteps = 65,\n\t\tautoApprove = false,\n\t\tlogger,\n\t\thistory,\n\t\tsummarizer,\n\t\tonTranscript,\n\t}: {\n\t\tllmClient: LLMClient;\n\t\tmessages?: Message[];\n\t\ttools?: AgentTool[];\n\t\t/** How many calls to the model one run may make before it fails. Defaults to 65. */\n\t\tmaxSteps?: number;\n\t\t/** Runs every tool call without asking, `destructive` ones included. Meant for CI. */\n\t\tautoApprove?: boolean;\n\t\t/** Where a failure the agent absorbs is reported. The factories always pass one. */\n\t\tlogger?: ILogger;\n\t\t/**\n\t\t * The history of the workspace this agent writes to. With it, each run first follows the\n\t\t * moves the user made through that history: the conversation goes back with the\n\t\t * workspace, and the model is told what was undone.\n\t\t */\n\t\thistory?: HistoryReader;\n\t\t/**\n\t\t * A cheap model that summarizes what the undone turns tried and what went wrong. Without\n\t\t * one, the model is told what those turns asked, word for word.\n\t\t */\n\t\tsummarizer?: LLMClient;\n\t\t/** Receives what the model saw in each run, once the run ended. */\n\t\tonTranscript?: TranscriptCallback;\n\t}) {\n\t\tif (!Number.isInteger(maxSteps) || maxSteps < 1) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`maxSteps must be a positive integer; got ${String(maxSteps)}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.llmClient = llmClient;\n\t\tthis.conversation = new Conversation(messages);\n\t\tthis.maxSteps = maxSteps;\n\t\tthis.autoApprove = autoApprove;\n\t\tthis.logger = logger;\n\t\tthis.history = history;\n\t\tthis.summarizer = summarizer;\n\t\tthis.onTranscript = onTranscript;\n\t\tthis.tools = new Map(tools.map(tool => [tool.name, tool]));\n\t\tif (this.tools.size !== tools.length) {\n\t\t\t// The model calls tools by name, so a second one with the same name could never run.\n\t\t\tthrow new InvalidAgentConfigError('Two tools share a name; each name must be unique');\n\t\t}\n\t\t// The client only describes the tools to the model; running them stays with the agent.\n\t\tthis.toolDefinitions = tools.map(tool => {\n\t\t\tconst definition = {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tinputSchema: tool.inputSchema,\n\t\t\t};\n\t\t\tconst native = nativeOf(tool);\n\t\t\tif (native === undefined) return definition;\n\t\t\t// Checked now, not on the first call: an agent its client cannot serve is a setup error.\n\t\t\tif (llmClient.supportsNative?.(native) !== true) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`The tool \"${tool.name}\" is the native \"${native}\" tool, which this model client cannot declare`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn asNative(definition, native);\n\t\t});\n\t}\n\n\tprivate async followHistory(history: HistoryReader): Promise<Followed> {\n\t\ttry {\n\t\t\treturn await followHistory(this.conversation, history, this.seenRevision);\n\t\t} catch (error) {\n\t\t\tthrow classifyLocalFailure(error, 'The workspace history could not be read');\n\t\t}\n\t}\n\n\t/**\n\t * Asks the summarizer what the undone turns tried and what went wrong. A summary is a help,\n\t * not a need: one that fails is reported and the plain note is used instead.\n\t */\n\tprivate async summarizeUndone(\n\t\tfollowed: Followed,\n\t\tsignal: AbortSignal,\n\t): Promise<{ text?: string; usage?: Tokens; called: boolean }> {\n\t\tif (!this.summarizer) return { called: false };\n\t\tconst reasons = followed.revisions.flatMap(revision =>\n\t\t\trevision.reason ? [revision.reason] : [],\n\t\t);\n\t\tconst prompt = [\n\t\t\t'The user undid the work in the conversation below and moved the workspace back to before it.',\n\t\t\treasons.length > 0 ? `Their reason: ${reasons.map(reason => `«${reason}»`).join(' ')}` : '',\n\t\t\t'In at most five short lines, say what was tried, why it went wrong or why the user went back, and what could be done better. Plain text, no preamble.',\n\t\t\t'',\n\t\t\ttranscriptOf(this.conversation, followed.undone),\n\t\t].join('\\n');\n\n\t\tlet response: LLMResponse;\n\t\ttry {\n\t\t\tresponse = await this.summarizer.send(\n\t\t\t\t{ context: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], tools: [] },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) throw error;\n\t\t\tthis.warnSummaryFailed(describeFailure(error));\n\t\t\treturn { called: true };\n\t\t}\n\n\t\tconst usage = response.usage ? { usage: response.usage } : {};\n\t\t// A refused or cut summary is not one: the model would read it as what was tried.\n\t\tif (response.stopReason !== 'completed') {\n\t\t\tthis.warnSummaryFailed(`the model stopped with \"${response.stopReason}\"`);\n\t\t\treturn { ...usage, called: true };\n\t\t}\n\t\tconst text = response.message.content\n\t\t\t.filter(part => part.type === 'text')\n\t\t\t.map(part => part.text)\n\t\t\t.join('\\n')\n\t\t\t.trim();\n\t\treturn { ...(text ? { text } : {}), ...usage, called: true };\n\t}\n\n\tprivate warnSummaryFailed(why: string): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger?.warn(`The summary of the undone turns failed: ${why}`);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'LLM agent logger failed',\n\t\t);\n\t}\n\n\tprivate async llmCall(\n\t\trunMessages: Message[],\n\t\tafter: number | undefined,\n\t\t{\n\t\t\tsignal,\n\t\t\tstep,\n\t\t\tcallback,\n\t\t\ttools,\n\t\t}: { signal: AbortSignal; step: number; callback: Callback; tools: ToolDefinition[] },\n\t): Promise<{ response: LLMResponse; context: Message[] }> {\n\t\t// Sent as a copy, so what the run records is what the agent built, whatever the client does.\n\t\tconst context = [...this.conversation.contextAfter(after), ...structuredClone(runMessages)];\n\t\tlet response: LLMResponse;\n\t\ttry {\n\t\t\tresponse = await this.llmClient.send({ context, tools }, signal);\n\t\t} catch (error) {\n\t\t\tconst failure = classifyProviderFailure(error, 'The LLM call failed');\n\t\t\t// A client turns some answers into errors, such as a stop at the context window. The\n\t\t\t// call was billed, and the failure carries what it spent: it is still a step.\n\t\t\tif (\n\t\t\t\t(failure instanceof RecoverableError || failure instanceof UnrecoverableError) &&\n\t\t\t\t(failure.tokens !== undefined || failure.usageUnreported)\n\t\t\t) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.narrateStep(step, failure.tokens, { context, tools }, callback);\n\t\t\t\t} catch (hostFailure) {\n\t\t\t\t\t// The callback's failure ends the run, and must carry this call's tokens too.\n\t\t\t\t\tthrow withSpentTokens(hostFailure, failure.tokens, failure.usageUnreported);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow failure;\n\t\t}\n\n\t\treturn { response, context };\n\t}\n\n\tprivate narrateStep(\n\t\tstep: number,\n\t\ttokens: Tokens | undefined,\n\t\tsent: { context: Message[]; tools: ToolDefinition[] },\n\t\tcallback: Callback,\n\t) {\n\t\temit(\n\t\t\t{\n\t\t\t\ttype: 'step',\n\t\t\t\tstep,\n\t\t\t\t...(tokens ? { tokens } : {}),\n\t\t\t\tcontext: measureContext({\n\t\t\t\t\tinstructions: this.llmClient.systemPrompt,\n\t\t\t\t\tproviderDataSource: this.llmClient.providerDataSource,\n\t\t\t\t\ttools: sent.tools,\n\t\t\t\t\tcontext: sent.context,\n\t\t\t\t\tsummarize: call => this.callSummaries.get(call.id),\n\t\t\t\t}),\n\t\t\t},\n\t\t\tcallback,\n\t\t);\n\t}\n\n\t/**\n\t * Undefined when the call may run; otherwise why it may not, which the model receives in its\n\t * place. Only a `destructive` call is asked about: git can undo a `mutating` one. A throwing\n\t * approver ends the run, as any host callback does.\n\t */\n\tprivate async denial(\n\t\tcall: ToolCallPart,\n\t\t{ risk, command }: PreparedCall,\n\t\tsignal: AbortSignal,\n\t\tapprove: Approver | undefined,\n\t): Promise<string | undefined> {\n\t\tif (this.autoApprove || risk !== 'destructive') return undefined;\n\n\t\tconst retry = 'Do not retry the same call; choose another way, or ask the user.';\n\t\tif (!approve) {\n\t\t\treturn `The call to \"${call.name}\" was denied: it is destructive, and no one was asked to allow it. ${retry}`;\n\t\t}\n\n\t\tlet decision: ApprovalDecision;\n\t\ttry {\n\t\t\t// A copy, so what runs and what the conversation keeps is exactly what was approved.\n\t\t\tconst input: unknown = structuredClone(call.input);\n\t\t\t// Read inside the boundary: an untyped approver can answer anything, and a bad answer\n\t\t\t// is its failure, which must carry the run's tokens like any other.\n\t\t\tconst request: ApprovalRequest = {\n\t\t\t\ttool: call.name,\n\t\t\t\tinput,\n\t\t\t\trisk,\n\t\t\t\t// A copy too: the approver must not be able to change what runs.\n\t\t\t\t...(command ? { command: structuredClone(command) } : {}),\n\t\t\t};\n\t\t\tdecision = readDecision(await approve(request, signal));\n\t\t} catch (error) {\n\t\t\t// An approver that gives up on a cancellation, whatever it throws, did not fail.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyHostFailure(error, 'The tool call approver failed');\n\t\t}\n\t\t// The user may cancel the run while they are being asked.\n\t\tsignal.throwIfAborted();\n\t\tif (decision.approved) return undefined;\n\n\t\tconst reason = decision.reason ? ` Their reason: ${decision.reason}` : '';\n\t\treturn `The user denied the call to \"${call.name}\".${reason} ${retry}`;\n\t}\n\n\t/**\n\t * Always answers the call: a missing tool, a denied call or a failing one becomes an error\n\t * result, so the model can correct itself. Only a cancellation, or a failing approver,\n\t * escapes, whatever error the tool turned it into.\n\t */\n\tprivate async runTool(\n\t\tcall: ToolCallPart,\n\t\t{ signal, onProgress: callback = ignoreProgress, approve, ask }: RunOptions,\n\t\teffects: RunEffects,\n\t\ttoolCall: RunToolContext,\n\t): Promise<{\n\t\tresult: ToolResultPart;\n\t\tdenied: boolean;\n\t\tdiff?: string;\n\t\tsummary?: string;\n\t\texitCode?: number;\n\t\tending?: string;\n\t}> {\n\t\tconst result = { type: 'toolResult' as const, callId: call.id, name: call.name };\n\t\tsignal.throwIfAborted();\n\t\tif (call.name === askUserName && ask && !this.tools.has(askUserName)) {\n\t\t\treturn this.askUser(call, ask, signal, callback);\n\t\t}\n\t\tconst tool = this.tools.get(call.name);\n\t\tif (!tool) {\n\t\t\treturn {\n\t\t\t\tresult: {\n\t\t\t\t\t...result,\n\t\t\t\t\toutput: `There is no tool named \"${call.name}\". Available tools: ${[...this.tools.keys()].join(', ') || 'none'}.`,\n\t\t\t\t\tisError: true,\n\t\t\t\t},\n\t\t\t\tdenied: false,\n\t\t\t};\n\t\t}\n\n\t\tlet summary: string | undefined;\n\t\ttry {\n\t\t\t// This is deliberately before preparation and approval. A consumer-supplied\n\t\t\t// summarizer is host code, and a failed one must never leave an ambiguous call that\n\t\t\t// could be replayed by RetryingAgent.\n\t\t\tsummary = tool.summarize?.(call.input);\n\t\t\tif (summary !== undefined) this.callSummaries.set(call.id, summary);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (error instanceof InvalidToolInputError) {\n\t\t\t\treturn {\n\t\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\t\tdenied: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow classifyHostFailure(error, 'The tool call summarizer failed');\n\t\t}\n\n\t\tlet prepared: PreparedCall;\n\t\ttry {\n\t\t\tprepared = await prepareCall(tool, call.input, signal, { ...toolCall, callId: call.id });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\t// A call that cannot be prepared, or whose tool cannot judge it, does not run; the\n\t\t\t// model reads why, such as a refused path, and can correct itself.\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t};\n\t\t}\n\n\t\t// Preparing may have finished after a cancellation it did not notice; nobody is asked to\n\t\t// approve a call in a run that has already stopped.\n\t\tsignal.throwIfAborted();\n\t\tconst denial = await this.denial(call, prepared, signal, approve);\n\t\tif (denial !== undefined) {\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: denial, isError: true },\n\t\t\t\tdenied: true,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t};\n\t\t}\n\n\t\t// Deciding took at least one await, and the run may have been cancelled meanwhile.\n\t\tsignal.throwIfAborted();\n\t\t// Announced only once it will run: a missing, failing-to-judge or denied call never is.\n\t\temit(\n\t\t\t{\n\t\t\t\ttype: 'tool',\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.name,\n\t\t\t\tstatus: 'in_progress',\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t},\n\t\t\tcallback,\n\t\t);\n\t\t// Checked again at the last moment: the consumer may cancel on the announcement itself.\n\t\tsignal.throwIfAborted();\n\t\t// Set before `execute`, so a tool that fails halfway still counts: it may have had effects.\n\t\teffects.toolRan = true;\n\t\ttry {\n\t\t\tconst output = await prepared.run(signal);\n\t\t\tconst ending = prepared.ending?.();\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output, isError: false },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t...(prepared.diff === undefined ? {} : { diff: prepared.diff }),\n\t\t\t\t...(ending === undefined ? {} : { ending }),\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst ending = prepared.ending?.();\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t...(error instanceof ToolExecutionError && error.exitCode !== undefined\n\t\t\t\t\t? { exitCode: error.exitCode }\n\t\t\t\t\t: {}),\n\t\t\t\t...(ending === undefined ? {} : { ending }),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Asks the user through the run's `ask`. Questions the model wrote wrong go back to it, to\n\t * correct; an asker that fails or answers wrongly is host code, and ends the run.\n\t */\n\tprivate async askUser(\n\t\tcall: ToolCallPart,\n\t\task: Asker,\n\t\tsignal: AbortSignal,\n\t\tcallback: Callback,\n\t): Promise<{ result: ToolResultPart; denied: boolean; summary?: string }> {\n\t\tconst result = { type: 'toolResult' as const, callId: call.id, name: call.name };\n\t\tconst questions = readQuestions(call.input);\n\t\tif (typeof questions === 'string') {\n\t\t\treturn { result: { ...result, output: questions, isError: true }, denied: false };\n\t\t}\n\t\tconst summary = summarizeQuestions(questions);\n\t\tthis.callSummaries.set(call.id, summary);\n\t\temit({ type: 'tool', id: call.id, name: call.name, status: 'in_progress', summary }, callback);\n\t\tsignal.throwIfAborted();\n\n\t\tlet answers: unknown;\n\t\ttry {\n\t\t\tanswers = await ask(questions, signal);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyHostFailure(error, 'The asker failed');\n\t\t}\n\t\t// An answer that arrives after a cancellation is not given to the model.\n\t\tsignal.throwIfAborted();\n\t\tconst read = readAnswers(answers, questions);\n\t\tif (!read) {\n\t\t\tthrow new UnrecoverableError('The asker failed', {\n\t\t\t\tcause: `It must answer each of the ${String(questions.length)} questions with some text, in order.`,\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tresult: { ...result, output: describeAnswers(questions, read), isError: false },\n\t\t\tdenied: false,\n\t\t\tsummary,\n\t\t};\n\t}\n\n\t/** One at a time and in order, so their effects and their narration never interleave. */\n\tprivate async runTools(\n\t\tcalls: ToolCallPart[],\n\t\toptions: RunOptions,\n\t\teffects: RunEffects,\n\t\ttoolCall: RunToolContext,\n\t\t// Throws the failure of a progress callback a call narrated through.\n\t\tthrowIfProgressFailed: () => void,\n\t\tendings: RepeatedEndings,\n\t): Promise<Message> {\n\t\tconst { signal, onProgress: callback = ignoreProgress } = options;\n\t\tconst results: MessagePart[] = [];\n\t\tfor (const call of calls) {\n\t\t\t// A call before this one may have ignored the cancellation; this one must not start,\n\t\t\t// nor be announced as running.\n\t\t\tsignal.throwIfAborted();\n\t\t\t// `runTool` announces the call only once it is allowed to run, so a consumer never\n\t\t\t// shows a call as running early, nor while the user is still being asked.\n\t\t\tconst { result, denied, diff, summary, exitCode, ending } = await this.runTool(\n\t\t\t\tcall,\n\t\t\t\toptions,\n\t\t\t\teffects,\n\t\t\t\ttoolCall,\n\t\t\t);\n\t\t\t// A call that failed to narrate ends the run before the next one can start.\n\t\t\tthrowIfProgressFailed();\n\t\t\tif (denied) {\n\t\t\t\temit(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'tool',\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\tstatus: 'denied',\n\t\t\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t\t},\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The diff of a change it made, for the person watching; only once it was made.\n\t\t\telse if (diff !== undefined) {\n\t\t\t\temit(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'tool',\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\tdiff,\n\t\t\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t\t},\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t} else narrate(result, callback, summary, exitCode);\n\t\t\tresults.push(result);\n\t\t\t// After its result is narrated, so the consumer sees the ending that stopped the run.\n\t\t\tif (endings.count(call, ending) >= maxRepeatedEndings) {\n\t\t\t\tthrow new UnrecoverableError('The LLM kept getting the same result from a command', {\n\t\t\t\t\tcause: `${summary === undefined ? `\"${call.name}\"` : `\"${summary}\"`} ended the same way, with the same output, ${String(maxRepeatedEndings)} times in a row.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn { role: 'tool', content: results };\n\t}\n\n\t/**\n\t * Runs inside the context of the run that reached it, or in one of its own that it ends with\n\t * the run: completed, failed or cancelled. Only a run that owns its context names the history\n\t * run it recorded, since the run is over only when that context ends.\n\t */\n\tasync run(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst inherited = runContextOf(options);\n\t\tif (inherited) return this.runSteps(prompt, options, inherited);\n\n\t\tconst context = new RunContext();\n\t\tlet end: RunEnd = 'failed';\n\t\tlet response: AgentResponse;\n\t\ttry {\n\t\t\tresponse = await this.runSteps(prompt, withRunContext(options, context), context);\n\t\t\tend = 'completed';\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) end = 'cancelled';\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait this.finishContext(context, end);\n\t\t}\n\t\t// Read once the run ended: a run that changed nothing left the history then.\n\t\tconst { runId } = context.historyRun;\n\t\treturn runId ? { ...response, runId } : response;\n\t}\n\n\t/**\n\t * What the run started ends here, but its result stands: the changes it recorded are already\n\t * on disk, so a record that could not be closed is reported, not turned into a failure.\n\t */\n\tprivate async finishContext(context: RunContext, end: RunEnd): Promise<void> {\n\t\ttry {\n\t\t\tawait context.finish(end);\n\t\t} catch (error) {\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tthis.logger?.warn(`The run could not close its records: ${describeFailure(error)}`);\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'LLM agent logger failed',\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async runSteps(\n\t\tprompt: string,\n\t\toptions: RunOptions,\n\t\tcontext: RunContext,\n\t): Promise<AgentResponse> {\n\t\tconst seen: Seen = { messages: () => [], tools: this.toolDefinitions };\n\t\tlet response: AgentResponse;\n\t\ttry {\n\t\t\tresponse = await this.takeSteps(prompt, options, context, seen);\n\t\t} catch (error) {\n\t\t\tawait this.transcribe(seen, isAbortError(error) ? 'cancelled' : 'failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tawait this.transcribe(seen, 'completed');\n\t\treturn response;\n\t}\n\n\t/** Hands the run's transcript to the consumer, whose failure is logged, not the run's. */\n\tprivate async transcribe(\n\t\tseen: Seen,\n\t\toutcome: Transcript['outcome'],\n\t\terror?: unknown,\n\t): Promise<void> {\n\t\tif (!this.onTranscript) return;\n\t\ttry {\n\t\t\t// A copy, so a consumer that changes it cannot change the agent's tools or conversation.\n\t\t\tconst content: unknown = structuredClone({\n\t\t\t\tinstructions: this.llmClient.systemPrompt,\n\t\t\t\ttools: seen.tools.map(({ name, description, inputSchema }) => ({\n\t\t\t\t\tname,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t})),\n\t\t\t\tmessages: seen.messages(),\n\t\t\t\t...(outcome === 'completed' ? {} : { error: describeFailure(error) }),\n\t\t\t});\n\t\t\tawait this.onTranscript({ outcome, content });\n\t\t} catch (failure) {\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tthis.logger?.warn(\n\t\t\t\t\t\t`The run's transcript could not be handed over: ${describeFailure(failure)}`,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'LLM agent logger failed',\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async takeSteps(\n\t\tprompt: string,\n\t\toptions: RunOptions,\n\t\tcontext: RunContext,\n\t\tseen: Seen,\n\t): Promise<AgentResponse> {\n\t\tconst { signal, onProgress: callback = ignoreProgress } = options;\n\t\tconst start = Date.now();\n\t\tconst runMessages: Message[] = [{ role: 'user', content: [{ type: 'text', text: prompt }] }];\n\t\tlet tokens: Tokens | undefined;\n\t\t// Once one call went unreported the run's total is unknown, however many report later.\n\t\tlet unreported = false;\n\t\t// Per run, not per instance: what one run executed says nothing about another.\n\t\tconst effects: RunEffects = { toolRan: false };\n\t\t// The turn this one follows: the last recorded, unless the workspace moved since.\n\t\tlet after = this.conversation.currentTurn;\n\t\tlet followed: Followed | undefined;\n\t\t// What the model has seen so far, whichever turn the run ends up following.\n\t\tseen.messages = () => [...this.conversation.contextAfter(after), ...runMessages];\n\n\t\ttry {\n\t\t\tif (this.history) {\n\t\t\t\tfollowed = await this.followHistory(this.history);\n\t\t\t\tafter = followed.turn;\n\t\t\t\t// The files may no longer hold what the conversation saw of them.\n\t\t\t\tif (followed.revisions.length > 0) this.reads.clear();\n\t\t\t\tif (followed.undone.length > 0) {\n\t\t\t\t\tconst summary = await this.summarizeUndone(followed, signal);\n\t\t\t\t\ttokens = addTokens(tokens, summary.usage);\n\t\t\t\t\tunreported ||= summary.called && !summary.usage;\n\t\t\t\t\tconst note = await undoNote({\n\t\t\t\t\t\tconversation: this.conversation,\n\t\t\t\t\t\thistory: this.history,\n\t\t\t\t\t\tfollowed,\n\t\t\t\t\t\t...(summary.text ? { summary: summary.text } : {}),\n\t\t\t\t\t}).catch((error: unknown) => {\n\t\t\t\t\t\tthrow classifyLocalFailure(error, 'The workspace history could not be read');\n\t\t\t\t\t});\n\t\t\t\t\trunMessages[0]?.content.unshift({ type: 'text', text: note });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// After following the history, which may have made every earlier read stale.\n\t\t\tconst reads = this.reads.begin();\n\t\t\tconst repeats = new RepeatedCalls();\n\t\t\tconst endings = new RepeatedEndings();\n\t\t\t// A tool that does its own work on the model, such as running subagents, counts it here.\n\t\t\tconst spend = (spent: Tokens | undefined, unreportedCall: boolean) => {\n\t\t\t\ttokens = addTokens(tokens, spent);\n\t\t\t\tunreported ||= unreportedCall;\n\t\t\t};\n\t\t\t// A tool narrates through this without ever failing: a failing callback would reach\n\t\t\t// only the tool, which turns any failure into a result for the model. The run ends on\n\t\t\t// it once that tool returns.\n\t\t\tlet progressFailure: { error: unknown } | undefined;\n\t\t\tconst onProgress = (event: ProgressEvent) => {\n\t\t\t\tif (progressFailure) return;\n\t\t\t\ttry {\n\t\t\t\t\temit(event, callback);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tprogressFailure = { error };\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst throwIfProgressFailed = () => {\n\t\t\t\tif (progressFailure) throw progressFailure.error;\n\t\t\t};\n\t\t\t// The agent's own `askUser` exists only for a run someone can answer, and never beside\n\t\t\t// a consumer's tool of that name, which the consumer gave first and which stays theirs.\n\t\t\tconst offersAsk = options.ask !== undefined && !this.tools.has(askUserName);\n\t\t\tconst tools = offersAsk ? [...this.toolDefinitions, askUserDefinition] : this.toolDefinitions;\n\t\t\tseen.tools = tools;\n\t\t\tfor (let step = 1; step <= this.maxSteps; step++) {\n\t\t\t\tconst { response, context: sent } = await this.llmCall(runMessages, after, {\n\t\t\t\t\tsignal,\n\t\t\t\t\tstep,\n\t\t\t\t\tcallback,\n\t\t\t\t\ttools,\n\t\t\t\t});\n\t\t\t\ttokens = addTokens(tokens, response.usage);\n\t\t\t\tunreported ||= !response.usage;\n\t\t\t\t// After the tokens are counted, so a throwing callback still reports them, and for an\n\t\t\t\t// unusable answer too: the call was sent, and billed.\n\t\t\t\tthis.narrateStep(step, response.usage, { context: sent, tools }, callback);\n\t\t\t\tif (response.stopReason !== 'completed') {\n\t\t\t\t\t// Its tokens are already counted with the run's, which the failure carries.\n\t\t\t\t\tthrow new UnrecoverableError('The LLM stopped before completing its answer', {\n\t\t\t\t\t\tcause: `The model stopped with \"${response.stopReason}\".`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\trunMessages.push(response.message);\n\n\t\t\t\t// Tool calls are narrated as they start, in `runTools`, and never if they do not run.\n\t\t\t\tfor (const part of response.message.content) {\n\t\t\t\t\tif (part.type !== 'toolCall') narrate(part, callback);\n\t\t\t\t}\n\n\t\t\t\tconst calls = response.message.content.filter(part => part.type === 'toolCall');\n\t\t\t\tif (calls.length === 0) {\n\t\t\t\t\t// Recorded only now, so a failed run leaves no tool call without its result, and a\n\t\t\t\t\t// note about what was undone is given again to the next run.\n\t\t\t\t\tthis.conversation.addRunAfter(after, runMessages, context.historyRun);\n\t\t\t\t\t// With the turns that read them, and only then: a failed run is not remembered.\n\t\t\t\t\treads.commit();\n\t\t\t\t\tif (followed) this.seenRevision = followed.latestRevision;\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\t// Only the final answer: text from earlier steps was narrated as it came.\n\t\t\t\t\t\tresponse: response.message.content\n\t\t\t\t\t\t\t.filter(part => part.type === 'text')\n\t\t\t\t\t\t\t.map(part => part.text)\n\t\t\t\t\t\t\t.join('\\n'),\n\t\t\t\t\t\ttokens: unreported ? undefined : tokens,\n\t\t\t\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Before running them again: the model has already seen what they return.\n\t\t\t\tif (repeats.count(calls) >= maxRepeatedSteps) {\n\t\t\t\t\tthrow new UnrecoverableError('The LLM repeated the same tool calls', {\n\t\t\t\t\t\tcause: `The model asked for the same tool calls ${String(maxRepeatedSteps)} times in a row.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// On the last step no call is left to send the results to, so the tools do not run.\n\t\t\t\tif (step < this.maxSteps) {\n\t\t\t\t\tconst results = await this.runTools(\n\t\t\t\t\t\tcalls,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\teffects,\n\t\t\t\t\t\t{ run: context, reads, onProgress, spend },\n\t\t\t\t\t\tthrowIfProgressFailed,\n\t\t\t\t\t\tendings,\n\t\t\t\t\t);\n\t\t\t\t\trunMessages.push(results);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new UnrecoverableError('The LLM did not finish within its step limit', {\n\t\t\t\tcause: `The model was still calling tools after ${String(this.maxSteps)} steps.`,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlet failure = error;\n\t\t\tif (effects.toolRan && error instanceof RecoverableError) {\n\t\t\t\t// RetryingAgent would run the whole prompt again, and with it every tool this run\n\t\t\t\t// already executed, so a failure after one ran must not invite a retry.\n\t\t\t\tconst unrecoverable = new UnrecoverableError(error.message, {\n\t\t\t\t\tcause: error.cause,\n\t\t\t\t\ttokens: error.tokens,\n\t\t\t\t\tusageUnreported: error.usageUnreported,\n\t\t\t\t});\n\t\t\t\tunrecoverable.stack = error.stack;\n\t\t\t\tfailure = unrecoverable;\n\t\t\t}\n\n\t\t\t// The run spent the tokens of every step before the one that failed.\n\t\t\tthrow withSpentTokens(failure, tokens, unreported);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"llmAgent.js","sourceRoot":"","sources":["../../../../src/engines/domain/model/llmAgent.ts"],"names":[],"mappings":"AAAA,OAAO,EAIN,YAAY,GACZ,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAMN,cAAc,GACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAEN,UAAU,EACV,YAAY,EACZ,cAAc,GACd,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAG5D,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAuB,MAAM,sBAAsB,CAAC;AAG/E,OAAO,EAGN,WAAW,EACX,kBAAkB,GAClB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,YAAY,EAAwB,MAAM,gCAAgC,CAAC;AAIpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACN,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,WAAW,EACX,aAAa,EACb,kBAAkB,GAClB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEN,aAAa,EAEb,YAAY,EACZ,QAAQ,GACR,MAAM,sBAAsB,CAAC;AAE9B,SAAS,YAAY,CAAC,IAAiB;IACtC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,MAAM;YACV,OAAO,EAAE,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AE;gBAC5E,KAAK,EAAE,2CAA2C,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS;aAChF,CAAC,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,IAAI,OAAO,GAAG,KAAK,CAAC;YACpB,IAAI,OAAO,CAAC,OAAO,IAAI,KAAK,YAAY,gBAAgB,EAAE,CAAC;gBAC1D,kFAAkF;gBAClF,wEAAwE;gBACxE,MAAM,aAAa,GAAG,IAAI,kBAAkB,CAAC,KAAK,CAAC,OAAO,EAAE;oBAC3D,KAAK,EAAE,KAAK,CAAC,KAAK;oBAClB,MAAM,EAAE,KAAK,CAAC,MAAM;oBACpB,eAAe,EAAE,KAAK,CAAC,eAAe;iBACtC,CAAC,CAAC;gBACH,aAAa,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;gBAClC,OAAO,GAAG,aAAa,CAAC;YACzB,CAAC;YAED,qEAAqE;YACrE,MAAM,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;QACpD,CAAC;IACF,CAAC;CACD","sourcesContent":["import {\n\ttype ApprovalDecision,\n\ttype ApprovalRequest,\n\ttype Approver,\n\treadDecision,\n} from '#src/agent/domain/approval';\nimport {\n\ttype Agent,\n\ttype AgentResponse,\n\ttype Callback,\n\ttype ProgressEvent,\n\ttype RunOptions,\n\tignoreProgress,\n} from '#src/agent/domain/agent';\nimport {\n\ttype RunEnd,\n\tRunContext,\n\trunContextOf,\n\twithRunContext,\n} from '#src/agent/domain/runContext';\nimport {\n\tInvalidAgentConfigError,\n\tRecoverableError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { Conversation } from '#src/llm/domain/conversation';\nimport type { LLMClient, LLMResponse } from '#src/llm/domain/llm';\nimport type { Message, MessagePart, ToolCallPart, ToolResultPart } from '#src/llm/domain/message';\nimport { asNative, nativeOf, type ToolDefinition } from '#src/llm/domain/tool';\nimport type { Asker } from '#src/agent/domain/question';\nimport type { Transcript, TranscriptCallback } from '#src/agent/domain/transcript';\nimport {\n\ttype AgentTool,\n\ttype PreparedCall,\n\tprepareCall,\n\tToolExecutionError,\n} from '#src/tools/domain/preparedCall';\nimport { ReadRegistry, type ToolCallContext } from '#src/tools/domain/readRegistry';\n\n/** What every tool call of one batch shares; each call adds its own id. */\ntype RunToolContext = Omit<ToolCallContext, 'callId'>;\nimport { InvalidToolInputError } from '#src/tools/domain/tool';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { measureContext } from './stepContext.ts';\nimport {\n\taskUserDefinition,\n\taskUserName,\n\tdescribeAnswers,\n\treadAnswers,\n\treadQuestions,\n\tsummarizeQuestions,\n} from './askUser.ts';\nimport {\n\ttype Followed,\n\tfollowHistory,\n\ttype HistoryReader,\n\ttranscriptOf,\n\tundoNote,\n} from './historyFollower.ts';\n\nfunction describePart(part: MessagePart): ProgressEvent | undefined {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn { type: 'agentMessage', message: part.text };\n\t\tcase 'reasoning':\n\t\t\treturn { type: 'reasoning', message: part.text };\n\t\tcase 'toolCall':\n\t\t\treturn { type: 'tool', id: part.id, name: part.name, status: 'in_progress' };\n\t\tcase 'toolResult':\n\t\t\treturn {\n\t\t\t\ttype: 'tool',\n\t\t\t\tid: part.callId,\n\t\t\t\tname: part.name,\n\t\t\t\tstatus: part.isError ? 'error' : 'completed',\n\t\t\t\t...(part.isError ? { error: part.output } : {}),\n\t\t\t};\n\t\tcase 'providerData':\n\t\t\t// Opaque by design: its readable side, if any, arrives as a reasoning part.\n\t\t\treturn undefined;\n\t\tcase 'compaction':\n\t\t\t// The provider's, for its client to send back; the step's context shows its effect.\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether a run reached a tool's `execute`. A missing tool or a denied call never does, so it\n * has no effect a retry could repeat.\n */\ninterface RunEffects {\n\ttoolRan: boolean;\n}\n\n/** What a run has shown the model, for its transcript. */\ninterface Seen {\n\tmessages: () => Message[];\n\ttools: ToolDefinition[];\n}\n\nfunction narrate(part: MessagePart, callback: Callback, summary?: string, exitCode?: number): void {\n\tconst event = describePart(part);\n\tif (!event) return;\n\tif (event.type === 'tool') {\n\t\tif (summary !== undefined) event.summary = summary;\n\t\tif (exitCode !== undefined) event.exitCode = exitCode;\n\t}\n\temit(event, callback);\n}\n\nfunction emit(event: ProgressEvent, callback: Callback): void {\n\ttreatErrors(\n\t\t() => {\n\t\t\tcallback(event);\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'LLM agent progress callback failed',\n\t);\n}\n\n/** `value` with the keys of every object sorted, so equal inputs serialize alike. */\nfunction canonical(value: unknown): unknown {\n\tif (Array.isArray(value)) return value.map(canonical);\n\tif (typeof value !== 'object' || value === null) return value;\n\treturn Object.fromEntries(\n\t\tObject.entries(value)\n\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t\t.map(([key, inner]) => [key, canonical(inner)]),\n\t);\n}\n\n// A model that asks for exactly the same calls this many times in a row is stuck: it already\n// has what they return, and running them again changes nothing.\nconst maxRepeatedSteps = 5;\n\n/** How many steps in a row have asked for exactly the same tool calls, with the same input. */\nclass RepeatedCalls {\n\tprivate last: string | undefined;\n\tprivate times = 0;\n\n\tcount(calls: readonly ToolCallPart[]): number {\n\t\t// Keys sorted at every level: the same input with its properties in another order is the\n\t\t// same call. Arrays, and the order of the calls, keep theirs.\n\t\tconst key = JSON.stringify(calls.map(call => [call.name, canonical(call.input)]));\n\t\tthis.times = key === this.last ? this.times + 1 : 1;\n\t\tthis.last = key;\n\t\treturn this.times;\n\t}\n}\n\n// A command that ends exactly as it did the last times, in output too, this many times in a row\n// means the model's changes in between are not reaching what the command checks.\nconst maxRepeatedEndings = 5;\n\n/**\n * How many times in a row each command call, by tool and input, has ended exactly the same way.\n * Calls in between to other tools, or to other commands, do not break the count.\n */\nclass RepeatedEndings {\n\tprivate readonly last = new Map<string, { ending: string; times: number }>();\n\n\tcount(call: ToolCallPart, ending: string | undefined): number {\n\t\tconst key = JSON.stringify([call.name, canonical(call.input)]);\n\t\t// A call that never ran a command, such as one denied, says nothing of how it ends.\n\t\tif (ending === undefined) {\n\t\t\tthis.last.delete(key);\n\t\t\treturn 0;\n\t\t}\n\t\tconst previous = this.last.get(key);\n\t\tconst times = previous?.ending === ending ? previous.times + 1 : 1;\n\t\tthis.last.set(key, { ending, times });\n\t\treturn times;\n\t}\n}\n\n/**\n * An agent whose conversation is owned by MiKode: every run sends the whole context to a\n * stateless `LLMClient`. Within a run the model may call the agent's tools; the agent runs them\n * and sends their results back until the model answers without calling one. Turn boundaries\n * are the consumer's to emit, as with the other engines; this agent only narrates what the\n * model produced and what its tools did.\n */\nexport class LLMAgent implements Agent {\n\tprivate readonly llmClient: LLMClient;\n\tprivate readonly conversation: Conversation;\n\tprivate readonly tools: Map<string, AgentTool>;\n\tprivate readonly toolDefinitions: ToolDefinition[];\n\t// Each call's summary, as its tool gave it when the call ran, so measuring a step that\n\t// resends the call never runs a consumer's summarizer again.\n\tprivate readonly callSummaries = new Map<string, string>();\n\tprivate readonly maxSteps: number;\n\tprivate readonly autoApprove: boolean;\n\tprivate readonly logger: ILogger | undefined;\n\tprivate readonly history: HistoryReader | undefined;\n\tprivate readonly summarizer: LLMClient | undefined;\n\tprivate readonly onTranscript: TranscriptCallback | undefined;\n\t// The latest move through the history this conversation has followed.\n\tprivate seenRevision = 0;\n\t// What this conversation has seen of each file, so an edit starts from a version it read.\n\tprivate readonly reads = new ReadRegistry();\n\n\tconstructor({\n\t\tllmClient,\n\t\tmessages,\n\t\ttools = [],\n\t\tmaxSteps = 65,\n\t\tautoApprove = false,\n\t\tlogger,\n\t\thistory,\n\t\tsummarizer,\n\t\tonTranscript,\n\t}: {\n\t\tllmClient: LLMClient;\n\t\tmessages?: Message[];\n\t\ttools?: AgentTool[];\n\t\t/** How many calls to the model one run may make before it fails. Defaults to 65. */\n\t\tmaxSteps?: number;\n\t\t/** Runs every tool call without asking, `destructive` ones included. Meant for CI. */\n\t\tautoApprove?: boolean;\n\t\t/** Where a failure the agent absorbs is reported. The factories always pass one. */\n\t\tlogger?: ILogger;\n\t\t/**\n\t\t * The history of the workspace this agent writes to. With it, each run first follows the\n\t\t * moves the user made through that history: the conversation goes back with the\n\t\t * workspace, and the model is told what was undone.\n\t\t */\n\t\thistory?: HistoryReader;\n\t\t/**\n\t\t * A cheap model that summarizes what the undone turns tried and what went wrong. Without\n\t\t * one, the model is told what those turns asked, word for word.\n\t\t */\n\t\tsummarizer?: LLMClient;\n\t\t/** Receives what the model saw in each run, once the run ended. */\n\t\tonTranscript?: TranscriptCallback;\n\t}) {\n\t\tif (!Number.isInteger(maxSteps) || maxSteps < 1) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`maxSteps must be a positive integer; got ${String(maxSteps)}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.llmClient = llmClient;\n\t\tthis.conversation = new Conversation(messages);\n\t\tthis.maxSteps = maxSteps;\n\t\tthis.autoApprove = autoApprove;\n\t\tthis.logger = logger;\n\t\tthis.history = history;\n\t\tthis.summarizer = summarizer;\n\t\tthis.onTranscript = onTranscript;\n\t\tthis.tools = new Map(tools.map(tool => [tool.name, tool]));\n\t\tif (this.tools.size !== tools.length) {\n\t\t\t// The model calls tools by name, so a second one with the same name could never run.\n\t\t\tthrow new InvalidAgentConfigError('Two tools share a name; each name must be unique');\n\t\t}\n\t\t// The client only describes the tools to the model; running them stays with the agent.\n\t\tthis.toolDefinitions = tools.map(tool => {\n\t\t\tconst definition = {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tinputSchema: tool.inputSchema,\n\t\t\t};\n\t\t\tconst native = nativeOf(tool);\n\t\t\tif (native === undefined) return definition;\n\t\t\t// Checked now, not on the first call: an agent its client cannot serve is a setup error.\n\t\t\tif (llmClient.supportsNative?.(native) !== true) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`The tool \"${tool.name}\" is the native \"${native}\" tool, which this model client cannot declare`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn asNative(definition, native);\n\t\t});\n\t}\n\n\tprivate async followHistory(history: HistoryReader): Promise<Followed> {\n\t\ttry {\n\t\t\treturn await followHistory(this.conversation, history, this.seenRevision);\n\t\t} catch (error) {\n\t\t\tthrow classifyLocalFailure(error, 'The workspace history could not be read');\n\t\t}\n\t}\n\n\t/**\n\t * Asks the summarizer what the undone turns tried and what went wrong. A summary is a help,\n\t * not a need: one that fails is reported and the plain note is used instead.\n\t */\n\tprivate async summarizeUndone(\n\t\tfollowed: Followed,\n\t\tsignal: AbortSignal,\n\t): Promise<{ text?: string; usage?: Tokens; called: boolean }> {\n\t\tif (!this.summarizer) return { called: false };\n\t\tconst reasons = followed.revisions.flatMap(revision =>\n\t\t\trevision.reason ? [revision.reason] : [],\n\t\t);\n\t\tconst prompt = [\n\t\t\t'The user undid the work in the conversation below and moved the workspace back to before it.',\n\t\t\treasons.length > 0 ? `Their reason: ${reasons.map(reason => `«${reason}»`).join(' ')}` : '',\n\t\t\t'In at most five short lines, say what was tried, why it went wrong or why the user went back, and what could be done better. Plain text, no preamble.',\n\t\t\t'',\n\t\t\ttranscriptOf(this.conversation, followed.undone),\n\t\t].join('\\n');\n\n\t\tlet response: LLMResponse;\n\t\ttry {\n\t\t\tresponse = await this.summarizer.send(\n\t\t\t\t{ context: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], tools: [] },\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) throw error;\n\t\t\tthis.warnSummaryFailed(describeFailure(error));\n\t\t\treturn { called: true };\n\t\t}\n\n\t\tconst usage = response.usage ? { usage: response.usage } : {};\n\t\t// A refused or cut summary is not one: the model would read it as what was tried.\n\t\tif (response.stopReason !== 'completed') {\n\t\t\tthis.warnSummaryFailed(`the model stopped with \"${response.stopReason}\"`);\n\t\t\treturn { ...usage, called: true };\n\t\t}\n\t\tconst text = response.message.content\n\t\t\t.filter(part => part.type === 'text')\n\t\t\t.map(part => part.text)\n\t\t\t.join('\\n')\n\t\t\t.trim();\n\t\treturn { ...(text ? { text } : {}), ...usage, called: true };\n\t}\n\n\tprivate warnSummaryFailed(why: string): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger?.warn(`The summary of the undone turns failed: ${why}`);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'LLM agent logger failed',\n\t\t);\n\t}\n\n\tprivate async llmCall(\n\t\trunMessages: Message[],\n\t\tafter: number | undefined,\n\t\t{\n\t\t\tsignal,\n\t\t\tstep,\n\t\t\tcallback,\n\t\t\ttools,\n\t\t}: { signal: AbortSignal; step: number; callback: Callback; tools: ToolDefinition[] },\n\t): Promise<{ response: LLMResponse; context: Message[] }> {\n\t\t// Sent as a copy, so what the run records is what the agent built, whatever the client does.\n\t\tconst context = [...this.conversation.contextAfter(after), ...structuredClone(runMessages)];\n\t\tlet response: LLMResponse;\n\t\ttry {\n\t\t\tresponse = await this.llmClient.send({ context, tools }, signal);\n\t\t} catch (error) {\n\t\t\tconst failure = classifyProviderFailure(error, 'The LLM call failed');\n\t\t\t// A client turns some answers into errors, such as a stop at the context window. The\n\t\t\t// call was billed, and the failure carries what it spent: it is still a step.\n\t\t\tif (\n\t\t\t\t(failure instanceof RecoverableError || failure instanceof UnrecoverableError) &&\n\t\t\t\t(failure.tokens !== undefined || failure.usageUnreported)\n\t\t\t) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.narrateStep(step, failure.tokens, { context, tools }, callback);\n\t\t\t\t} catch (hostFailure) {\n\t\t\t\t\t// The callback's failure ends the run, and must carry this call's tokens too.\n\t\t\t\t\tthrow withSpentTokens(hostFailure, failure.tokens, failure.usageUnreported);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow failure;\n\t\t}\n\n\t\treturn { response, context };\n\t}\n\n\tprivate narrateStep(\n\t\tstep: number,\n\t\ttokens: Tokens | undefined,\n\t\tsent: { context: Message[]; tools: ToolDefinition[] },\n\t\tcallback: Callback,\n\t) {\n\t\temit(\n\t\t\t{\n\t\t\t\ttype: 'step',\n\t\t\t\tstep,\n\t\t\t\t...(tokens ? { tokens } : {}),\n\t\t\t\tcontext: measureContext({\n\t\t\t\t\tinstructions: this.llmClient.systemPrompt,\n\t\t\t\t\tproviderDataSource: this.llmClient.providerDataSource,\n\t\t\t\t\ttools: sent.tools,\n\t\t\t\t\tcontext: sent.context,\n\t\t\t\t\tsummarize: call => this.callSummaries.get(call.id),\n\t\t\t\t}),\n\t\t\t},\n\t\t\tcallback,\n\t\t);\n\t}\n\n\t/**\n\t * Undefined when the call may run; otherwise why it may not, which the model receives in its\n\t * place. Only a `destructive` call is asked about: git can undo a `mutating` one. A throwing\n\t * approver ends the run, as any host callback does.\n\t */\n\tprivate async denial(\n\t\tcall: ToolCallPart,\n\t\t{ risk, command }: PreparedCall,\n\t\tsignal: AbortSignal,\n\t\tapprove: Approver | undefined,\n\t): Promise<string | undefined> {\n\t\tif (this.autoApprove || risk !== 'destructive') return undefined;\n\n\t\tconst retry = 'Do not retry the same call; choose another way, or ask the user.';\n\t\tif (!approve) {\n\t\t\treturn `The call to \"${call.name}\" was denied: it is destructive, and no one was asked to allow it. ${retry}`;\n\t\t}\n\n\t\tlet decision: ApprovalDecision;\n\t\ttry {\n\t\t\t// A copy, so what runs and what the conversation keeps is exactly what was approved.\n\t\t\tconst input: unknown = structuredClone(call.input);\n\t\t\t// Read inside the boundary: an untyped approver can answer anything, and a bad answer\n\t\t\t// is its failure, which must carry the run's tokens like any other.\n\t\t\tconst request: ApprovalRequest = {\n\t\t\t\ttool: call.name,\n\t\t\t\tinput,\n\t\t\t\trisk,\n\t\t\t\t// A copy too: the approver must not be able to change what runs.\n\t\t\t\t...(command ? { command: structuredClone(command) } : {}),\n\t\t\t};\n\t\t\tdecision = readDecision(await approve(request, signal));\n\t\t} catch (error) {\n\t\t\t// An approver that gives up on a cancellation, whatever it throws, did not fail.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyHostFailure(error, 'The tool call approver failed');\n\t\t}\n\t\t// The user may cancel the run while they are being asked.\n\t\tsignal.throwIfAborted();\n\t\tif (decision.approved) return undefined;\n\n\t\tconst reason = decision.reason ? ` Their reason: ${decision.reason}` : '';\n\t\treturn `The user denied the call to \"${call.name}\".${reason} ${retry}`;\n\t}\n\n\t/**\n\t * Always answers the call: a missing tool, a denied call or a failing one becomes an error\n\t * result, so the model can correct itself. Only a cancellation, or a failing approver,\n\t * escapes, whatever error the tool turned it into.\n\t */\n\tprivate async runTool(\n\t\tcall: ToolCallPart,\n\t\t{ signal, onProgress: callback = ignoreProgress, approve, ask }: RunOptions,\n\t\teffects: RunEffects,\n\t\ttoolCall: RunToolContext,\n\t): Promise<{\n\t\tresult: ToolResultPart;\n\t\tdenied: boolean;\n\t\tdiff?: string;\n\t\tsummary?: string;\n\t\texitCode?: number;\n\t\tending?: string;\n\t}> {\n\t\tconst result = { type: 'toolResult' as const, callId: call.id, name: call.name };\n\t\tsignal.throwIfAborted();\n\t\tif (call.name === askUserName && ask && !this.tools.has(askUserName)) {\n\t\t\treturn this.askUser(call, ask, signal, callback);\n\t\t}\n\t\tconst tool = this.tools.get(call.name);\n\t\tif (!tool) {\n\t\t\treturn {\n\t\t\t\tresult: {\n\t\t\t\t\t...result,\n\t\t\t\t\toutput: `There is no tool named \"${call.name}\". Available tools: ${[...this.tools.keys()].join(', ') || 'none'}.`,\n\t\t\t\t\tisError: true,\n\t\t\t\t},\n\t\t\t\tdenied: false,\n\t\t\t};\n\t\t}\n\n\t\tlet summary: string | undefined;\n\t\ttry {\n\t\t\t// This is deliberately before preparation and approval. A consumer-supplied\n\t\t\t// summarizer is host code, and a failed one must never leave an ambiguous call that\n\t\t\t// could be replayed by RetryingAgent.\n\t\t\tsummary = tool.summarize?.(call.input);\n\t\t\tif (summary !== undefined) this.callSummaries.set(call.id, summary);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (error instanceof InvalidToolInputError) {\n\t\t\t\treturn {\n\t\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\t\tdenied: false,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthrow classifyHostFailure(error, 'The tool call summarizer failed');\n\t\t}\n\n\t\tlet prepared: PreparedCall;\n\t\ttry {\n\t\t\tprepared = await prepareCall(tool, call.input, signal, { ...toolCall, callId: call.id });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\t// A call that cannot be prepared, or whose tool cannot judge it, does not run; the\n\t\t\t// model reads why, such as a refused path, and can correct itself.\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t};\n\t\t}\n\n\t\t// Preparing may have finished after a cancellation it did not notice; nobody is asked to\n\t\t// approve a call in a run that has already stopped.\n\t\tsignal.throwIfAborted();\n\t\tconst denial = await this.denial(call, prepared, signal, approve);\n\t\tif (denial !== undefined) {\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: denial, isError: true },\n\t\t\t\tdenied: true,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t};\n\t\t}\n\n\t\t// Deciding took at least one await, and the run may have been cancelled meanwhile.\n\t\tsignal.throwIfAborted();\n\t\t// Announced only once it will run: a missing, failing-to-judge or denied call never is.\n\t\temit(\n\t\t\t{\n\t\t\t\ttype: 'tool',\n\t\t\t\tid: call.id,\n\t\t\t\tname: call.name,\n\t\t\t\tstatus: 'in_progress',\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t},\n\t\t\tcallback,\n\t\t);\n\t\t// Checked again at the last moment: the consumer may cancel on the announcement itself.\n\t\tsignal.throwIfAborted();\n\t\t// Set before `execute`, so a tool that fails halfway still counts: it may have had effects.\n\t\teffects.toolRan = true;\n\t\ttry {\n\t\t\tconst output = await prepared.run(signal);\n\t\t\tconst ending = prepared.ending?.();\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output, isError: false },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t...(prepared.diff === undefined ? {} : { diff: prepared.diff }),\n\t\t\t\t...(ending === undefined ? {} : { ending }),\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst ending = prepared.ending?.();\n\t\t\treturn {\n\t\t\t\tresult: { ...result, output: describeFailure(error), isError: true },\n\t\t\t\tdenied: false,\n\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t...(error instanceof ToolExecutionError && error.exitCode !== undefined\n\t\t\t\t\t? { exitCode: error.exitCode }\n\t\t\t\t\t: {}),\n\t\t\t\t...(ending === undefined ? {} : { ending }),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Asks the user through the run's `ask`. Questions the model wrote wrong go back to it, to\n\t * correct; an asker that fails or answers wrongly is host code, and ends the run.\n\t */\n\tprivate async askUser(\n\t\tcall: ToolCallPart,\n\t\task: Asker,\n\t\tsignal: AbortSignal,\n\t\tcallback: Callback,\n\t): Promise<{ result: ToolResultPart; denied: boolean; summary?: string }> {\n\t\tconst result = { type: 'toolResult' as const, callId: call.id, name: call.name };\n\t\tconst questions = readQuestions(call.input);\n\t\tif (typeof questions === 'string') {\n\t\t\treturn { result: { ...result, output: questions, isError: true }, denied: false };\n\t\t}\n\t\tconst summary = summarizeQuestions(questions);\n\t\tthis.callSummaries.set(call.id, summary);\n\t\temit({ type: 'tool', id: call.id, name: call.name, status: 'in_progress', summary }, callback);\n\t\tsignal.throwIfAborted();\n\n\t\tlet answers: unknown;\n\t\ttry {\n\t\t\tanswers = await ask(questions, signal);\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyHostFailure(error, 'The asker failed');\n\t\t}\n\t\t// An answer that arrives after a cancellation is not given to the model.\n\t\tsignal.throwIfAborted();\n\t\tconst read = readAnswers(answers, questions);\n\t\tif (!read) {\n\t\t\tthrow new UnrecoverableError('The asker failed', {\n\t\t\t\tcause: `It must answer each of the ${String(questions.length)} questions with some text, in order.`,\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tresult: { ...result, output: describeAnswers(questions, read), isError: false },\n\t\t\tdenied: false,\n\t\t\tsummary,\n\t\t};\n\t}\n\n\t/** One at a time and in order, so their effects and their narration never interleave. */\n\tprivate async runTools(\n\t\tcalls: ToolCallPart[],\n\t\toptions: RunOptions,\n\t\teffects: RunEffects,\n\t\ttoolCall: RunToolContext,\n\t\t// Throws the failure of a progress callback a call narrated through.\n\t\tthrowIfProgressFailed: () => void,\n\t\tendings: RepeatedEndings,\n\t): Promise<Message> {\n\t\tconst { signal, onProgress: callback = ignoreProgress } = options;\n\t\tconst results: MessagePart[] = [];\n\t\tfor (const call of calls) {\n\t\t\t// A call before this one may have ignored the cancellation; this one must not start,\n\t\t\t// nor be announced as running.\n\t\t\tsignal.throwIfAborted();\n\t\t\t// `runTool` announces the call only once it is allowed to run, so a consumer never\n\t\t\t// shows a call as running early, nor while the user is still being asked.\n\t\t\tconst { result, denied, diff, summary, exitCode, ending } = await this.runTool(\n\t\t\t\tcall,\n\t\t\t\toptions,\n\t\t\t\teffects,\n\t\t\t\ttoolCall,\n\t\t\t);\n\t\t\t// A call that failed to narrate ends the run before the next one can start.\n\t\t\tthrowIfProgressFailed();\n\t\t\tif (denied) {\n\t\t\t\temit(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'tool',\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\tstatus: 'denied',\n\t\t\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t\t},\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// The diff of a change it made, for the person watching; only once it was made.\n\t\t\telse if (diff !== undefined) {\n\t\t\t\temit(\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'tool',\n\t\t\t\t\t\tid: call.id,\n\t\t\t\t\t\tname: call.name,\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\tdiff,\n\t\t\t\t\t\t...(summary === undefined ? {} : { summary }),\n\t\t\t\t\t},\n\t\t\t\t\tcallback,\n\t\t\t\t);\n\t\t\t} else narrate(result, callback, summary, exitCode);\n\t\t\tresults.push(result);\n\t\t\t// After its result is narrated, so the consumer sees the ending that stopped the run.\n\t\t\tif (endings.count(call, ending) >= maxRepeatedEndings) {\n\t\t\t\tthrow new UnrecoverableError('The LLM kept getting the same result from a command', {\n\t\t\t\t\tcause: `${summary === undefined ? `\"${call.name}\"` : `\"${summary}\"`} ended the same way, with the same output, ${String(maxRepeatedEndings)} times in a row.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn { role: 'tool', content: results };\n\t}\n\n\t/**\n\t * Runs inside the context of the run that reached it, or in one of its own that it ends with\n\t * the run: completed, failed or cancelled. Only a run that owns its context names the history\n\t * run it recorded, since the run is over only when that context ends.\n\t */\n\tasync run(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst inherited = runContextOf(options);\n\t\tif (inherited) return this.runSteps(prompt, options, inherited);\n\n\t\tconst context = new RunContext();\n\t\tlet end: RunEnd = 'failed';\n\t\tlet response: AgentResponse;\n\t\ttry {\n\t\t\tresponse = await this.runSteps(prompt, withRunContext(options, context), context);\n\t\t\tend = 'completed';\n\t\t} catch (error) {\n\t\t\tif (isAbortError(error)) end = 'cancelled';\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait this.finishContext(context, end);\n\t\t}\n\t\t// Read once the run ended: a run that changed nothing left the history then.\n\t\tconst { runId } = context.historyRun;\n\t\treturn runId ? { ...response, runId } : response;\n\t}\n\n\t/**\n\t * What the run started ends here, but its result stands: the changes it recorded are already\n\t * on disk, so a record that could not be closed is reported, not turned into a failure.\n\t */\n\tprivate async finishContext(context: RunContext, end: RunEnd): Promise<void> {\n\t\ttry {\n\t\t\tawait context.finish(end);\n\t\t} catch (error) {\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tthis.logger?.warn(`The run could not close its records: ${describeFailure(error)}`);\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'LLM agent logger failed',\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async runSteps(\n\t\tprompt: string,\n\t\toptions: RunOptions,\n\t\tcontext: RunContext,\n\t): Promise<AgentResponse> {\n\t\tconst seen: Seen = { messages: () => [], tools: this.toolDefinitions };\n\t\tlet response: AgentResponse;\n\t\ttry {\n\t\t\tresponse = await this.takeSteps(prompt, options, context, seen);\n\t\t} catch (error) {\n\t\t\tawait this.transcribe(seen, isAbortError(error) ? 'cancelled' : 'failed', error);\n\t\t\tthrow error;\n\t\t}\n\t\tawait this.transcribe(seen, 'completed');\n\t\treturn response;\n\t}\n\n\t/** Hands the run's transcript to the consumer, whose failure is logged, not the run's. */\n\tprivate async transcribe(\n\t\tseen: Seen,\n\t\toutcome: Transcript['outcome'],\n\t\terror?: unknown,\n\t): Promise<void> {\n\t\tif (!this.onTranscript) return;\n\t\ttry {\n\t\t\t// A copy, so a consumer that changes it cannot change the agent's tools or conversation.\n\t\t\tconst content: unknown = structuredClone({\n\t\t\t\tinstructions: this.llmClient.systemPrompt,\n\t\t\t\ttools: seen.tools.map(({ name, description, inputSchema }) => ({\n\t\t\t\t\tname,\n\t\t\t\t\tdescription,\n\t\t\t\t\tinputSchema,\n\t\t\t\t})),\n\t\t\t\tmessages: seen.messages(),\n\t\t\t\t...(outcome === 'completed' ? {} : { error: describeFailure(error) }),\n\t\t\t});\n\t\t\tawait this.onTranscript({ outcome, content });\n\t\t} catch (failure) {\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tthis.logger?.warn(\n\t\t\t\t\t\t`The run's transcript could not be handed over: ${describeFailure(failure)}`,\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'LLM agent logger failed',\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate async takeSteps(\n\t\tprompt: string,\n\t\toptions: RunOptions,\n\t\tcontext: RunContext,\n\t\tseen: Seen,\n\t): Promise<AgentResponse> {\n\t\tconst { signal, onProgress: callback = ignoreProgress } = options;\n\t\tconst start = Date.now();\n\t\tconst runMessages: Message[] = [{ role: 'user', content: [{ type: 'text', text: prompt }] }];\n\t\tlet tokens: Tokens | undefined;\n\t\t// Once one call went unreported the run's total is unknown, however many report later.\n\t\tlet unreported = false;\n\t\t// Per run, not per instance: what one run executed says nothing about another.\n\t\tconst effects: RunEffects = { toolRan: false };\n\t\t// The turn this one follows: the last recorded, unless the workspace moved since.\n\t\tlet after = this.conversation.currentTurn;\n\t\tlet followed: Followed | undefined;\n\t\t// What the model has seen so far, whichever turn the run ends up following.\n\t\tseen.messages = () => [...this.conversation.contextAfter(after), ...runMessages];\n\n\t\ttry {\n\t\t\tif (this.history) {\n\t\t\t\tfollowed = await this.followHistory(this.history);\n\t\t\t\tafter = followed.turn;\n\t\t\t\t// The files may no longer hold what the conversation saw of them.\n\t\t\t\tif (followed.revisions.length > 0) this.reads.clear();\n\t\t\t\tif (followed.undone.length > 0) {\n\t\t\t\t\tconst summary = await this.summarizeUndone(followed, signal);\n\t\t\t\t\ttokens = addTokens(tokens, summary.usage);\n\t\t\t\t\tunreported ||= summary.called && !summary.usage;\n\t\t\t\t\tconst note = await undoNote({\n\t\t\t\t\t\tconversation: this.conversation,\n\t\t\t\t\t\thistory: this.history,\n\t\t\t\t\t\tfollowed,\n\t\t\t\t\t\t...(summary.text ? { summary: summary.text } : {}),\n\t\t\t\t\t}).catch((error: unknown) => {\n\t\t\t\t\t\tthrow classifyLocalFailure(error, 'The workspace history could not be read');\n\t\t\t\t\t});\n\t\t\t\t\trunMessages[0]?.content.unshift({ type: 'text', text: note });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// After following the history, which may have made every earlier read stale.\n\t\t\tconst reads = this.reads.begin();\n\t\t\tconst repeats = new RepeatedCalls();\n\t\t\tconst endings = new RepeatedEndings();\n\t\t\t// A tool that does its own work on the model, such as running subagents, counts it here.\n\t\t\tconst spend = (spent: Tokens | undefined, unreportedCall: boolean) => {\n\t\t\t\ttokens = addTokens(tokens, spent);\n\t\t\t\tunreported ||= unreportedCall;\n\t\t\t};\n\t\t\t// A tool narrates through this without ever failing: a failing callback would reach\n\t\t\t// only the tool, which turns any failure into a result for the model. The run ends on\n\t\t\t// it once that tool returns.\n\t\t\tlet progressFailure: { error: unknown } | undefined;\n\t\t\tconst onProgress = (event: ProgressEvent) => {\n\t\t\t\tif (progressFailure) return;\n\t\t\t\ttry {\n\t\t\t\t\temit(event, callback);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tprogressFailure = { error };\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst throwIfProgressFailed = () => {\n\t\t\t\tif (progressFailure) throw progressFailure.error;\n\t\t\t};\n\t\t\t// The agent's own `askUser` exists only for a run someone can answer, and never beside\n\t\t\t// a consumer's tool of that name, which the consumer gave first and which stays theirs.\n\t\t\tconst offersAsk = options.ask !== undefined && !this.tools.has(askUserName);\n\t\t\tconst tools = offersAsk ? [...this.toolDefinitions, askUserDefinition] : this.toolDefinitions;\n\t\t\tseen.tools = tools;\n\t\t\t// Recorded only once the run ends in a way that keeps it, so it never leaves a tool call\n\t\t\t// without its result; a run that is not kept gives its note on what was undone again.\n\t\t\tconst remember = () => {\n\t\t\t\tthis.conversation.addRunAfter(after, runMessages, context.historyRun);\n\t\t\t\t// With the turns that read them, and only then.\n\t\t\t\treads.commit();\n\t\t\t\tif (followed) this.seenRevision = followed.latestRevision;\n\t\t\t};\n\t\t\tfor (let step = 1; step <= this.maxSteps; step++) {\n\t\t\t\tconst { response, context: sent } = await this.llmCall(runMessages, after, {\n\t\t\t\t\tsignal,\n\t\t\t\t\tstep,\n\t\t\t\t\tcallback,\n\t\t\t\t\ttools,\n\t\t\t\t});\n\t\t\t\ttokens = addTokens(tokens, response.usage);\n\t\t\t\tunreported ||= !response.usage;\n\t\t\t\t// After the tokens are counted, so a throwing callback still reports them, and for an\n\t\t\t\t// unusable answer too: the call was sent, and billed.\n\t\t\t\tthis.narrateStep(step, response.usage, { context: sent, tools }, callback);\n\t\t\t\tif (response.stopReason === 'truncated') {\n\t\t\t\t\t// What it wrote before the output limit, kept with the run so the next run can\n\t\t\t\t\t// take it up. Not its calls, whose input may be cut, nor what only the provider\n\t\t\t\t\t// reads back, which it may refuse incomplete.\n\t\t\t\t\tconst written = response.message.content.filter(\n\t\t\t\t\t\tpart => part.type === 'text' || part.type === 'reasoning',\n\t\t\t\t\t);\n\t\t\t\t\tfor (const part of written) narrate(part, callback);\n\t\t\t\t\tif (written.length > 0) runMessages.push({ role: 'assistant', content: written });\n\t\t\t\t\tremember();\n\t\t\t\t\tthrow new UnrecoverableError('The LLM stopped before completing its answer', {\n\t\t\t\t\t\tcause:\n\t\t\t\t\t\t\t'The model stopped with \"truncated\". The run, and what the answer held before the limit, are kept in the conversation.',\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (response.stopReason !== 'completed') {\n\t\t\t\t\t// Its tokens are already counted with the run's, which the failure carries. A run\n\t\t\t\t\t// that ends so is not remembered.\n\t\t\t\t\tthrow new UnrecoverableError('The LLM stopped before completing its answer', {\n\t\t\t\t\t\tcause: `The model stopped with \"${response.stopReason}\".`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\trunMessages.push(response.message);\n\n\t\t\t\t// Tool calls are narrated as they start, in `runTools`, and never if they do not run.\n\t\t\t\tfor (const part of response.message.content) {\n\t\t\t\t\tif (part.type !== 'toolCall') narrate(part, callback);\n\t\t\t\t}\n\n\t\t\t\tconst calls = response.message.content.filter(part => part.type === 'toolCall');\n\t\t\t\tif (calls.length === 0) {\n\t\t\t\t\tremember();\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\t// Only the final answer: text from earlier steps was narrated as it came.\n\t\t\t\t\t\tresponse: response.message.content\n\t\t\t\t\t\t\t.filter(part => part.type === 'text')\n\t\t\t\t\t\t\t.map(part => part.text)\n\t\t\t\t\t\t\t.join('\\n'),\n\t\t\t\t\t\ttokens: unreported ? undefined : tokens,\n\t\t\t\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// Before running them again: the model has already seen what they return.\n\t\t\t\tif (repeats.count(calls) >= maxRepeatedSteps) {\n\t\t\t\t\tthrow new UnrecoverableError('The LLM repeated the same tool calls', {\n\t\t\t\t\t\tcause: `The model asked for the same tool calls ${String(maxRepeatedSteps)} times in a row.`,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// On the last step no call is left to send the results to, so the tools do not run.\n\t\t\t\tif (step < this.maxSteps) {\n\t\t\t\t\tconst results = await this.runTools(\n\t\t\t\t\t\tcalls,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\teffects,\n\t\t\t\t\t\t{ run: context, reads, onProgress, spend },\n\t\t\t\t\t\tthrowIfProgressFailed,\n\t\t\t\t\t\tendings,\n\t\t\t\t\t);\n\t\t\t\t\trunMessages.push(results);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthrow new UnrecoverableError('The LLM did not finish within its step limit', {\n\t\t\t\tcause: `The model was still calling tools after ${String(this.maxSteps)} steps.`,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlet failure = error;\n\t\t\tif (effects.toolRan && error instanceof RecoverableError) {\n\t\t\t\t// RetryingAgent would run the whole prompt again, and with it every tool this run\n\t\t\t\t// already executed, so a failure after one ran must not invite a retry.\n\t\t\t\tconst unrecoverable = new UnrecoverableError(error.message, {\n\t\t\t\t\tcause: error.cause,\n\t\t\t\t\ttokens: error.tokens,\n\t\t\t\t\tusageUnreported: error.usageUnreported,\n\t\t\t\t});\n\t\t\t\tunrecoverable.stack = error.stack;\n\t\t\t\tfailure = unrecoverable;\n\t\t\t}\n\n\t\t\t// The run spent the tokens of every step before the one that failed.\n\t\t\tthrow withSpentTokens(failure, tokens, unreported);\n\t\t}\n\t}\n}\n"]}
|
|
@@ -133,7 +133,7 @@ export declare function createLLMAgent(provider: AgentProvider, { model, reasoni
|
|
|
133
133
|
* The file tools for an agent from `createLLMAgent` on `provider`, over `workspace`, in the
|
|
134
134
|
* provider's own format:
|
|
135
135
|
*
|
|
136
|
-
* - OpenAI: `listFiles`, `searchText`, `readFile` and its native `apply_patch`;
|
|
136
|
+
* - OpenAI: `listFiles`, `searchText`, `readFile`, `readFiles` and its native `apply_patch`;
|
|
137
137
|
* - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and
|
|
138
138
|
* `delete_file`.
|
|
139
139
|
*
|
|
@@ -171,7 +171,7 @@ export declare function createFileTools(provider: AgentProvider, workspace: Work
|
|
|
171
171
|
* holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the
|
|
172
172
|
* workspace's roots.
|
|
173
173
|
*
|
|
174
|
-
* - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `showChanges`,
|
|
174
|
+
* - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `readFiles`, `showChanges`,
|
|
175
175
|
* the current task's changes as far as each may read them, and `explore`, which sends up to 4
|
|
176
176
|
* read-only explorers at once on the role's provider's cheaper model, each a new agent that
|
|
177
177
|
* starts from its question.
|
|
@@ -12,7 +12,7 @@ import { commandsFor, validateCommands, validateFormatter, } from '#src/tools/do
|
|
|
12
12
|
import { commandToolFor, fileToolsFor, openStore, openWorkspace, stateDirectoryOf, } from '#src/tools/infrastructure/fileTools';
|
|
13
13
|
import { createExploreTool } from '#src/tools/infrastructure/exploreTool';
|
|
14
14
|
import { createShowChangesTool } from '#src/tools/infrastructure/showChangesTool';
|
|
15
|
-
import { createTrackedReadFile } from '#src/tools/infrastructure/trackedReadFile';
|
|
15
|
+
import { createTrackedReadFile, createTrackedReadFiles, } from '#src/tools/infrastructure/trackedReadFile';
|
|
16
16
|
import { createWorkspaceTools } from '#src/tools/infrastructure/workspaceTools';
|
|
17
17
|
import { isAgentProvider, orchestratorRolesFor } from "./agentFactory.js";
|
|
18
18
|
import { agentProviders, } from "./types.js";
|
|
@@ -215,7 +215,7 @@ export function createLLMAgent(provider, { model, reasoningEffort, systemPrompt,
|
|
|
215
215
|
* The file tools for an agent from `createLLMAgent` on `provider`, over `workspace`, in the
|
|
216
216
|
* provider's own format:
|
|
217
217
|
*
|
|
218
|
-
* - OpenAI: `listFiles`, `searchText`, `readFile` and its native `apply_patch`;
|
|
218
|
+
* - OpenAI: `listFiles`, `searchText`, `readFile`, `readFiles` and its native `apply_patch`;
|
|
219
219
|
* - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and
|
|
220
220
|
* `delete_file`.
|
|
221
221
|
*
|
|
@@ -264,8 +264,8 @@ async function executorTools(provider, workspace, commands) {
|
|
|
264
264
|
}
|
|
265
265
|
/** What an explorer finds and reads with: no edits, no changes, no commands. */
|
|
266
266
|
function explorerTools({ read, policy }) {
|
|
267
|
-
const finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile');
|
|
268
|
-
return [...finding, createTrackedReadFile(policy)];
|
|
267
|
+
const finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile' && tool.name !== 'readFiles');
|
|
268
|
+
return [...finding, createTrackedReadFile(policy), createTrackedReadFiles(policy)];
|
|
269
269
|
}
|
|
270
270
|
/**
|
|
271
271
|
* What the planner and the reviewer read with: no edits, the current task's changes, `explore`
|
|
@@ -284,28 +284,32 @@ async function readingTools(workspace, role, commands, explorer) {
|
|
|
284
284
|
return [...tools, await commandToolFor(workspace, own)];
|
|
285
285
|
}
|
|
286
286
|
const batching = 'When you know you need several files, or several searches, ask for all of them in one answer rather than one at a time: each answer is a step, and steps are limited.';
|
|
287
|
-
|
|
287
|
+
// For the roles that have `readFiles`, which the executor on Claude does not.
|
|
288
|
+
const batchingReads = 'When you know you need several files, or several ranges, read them in one readFiles call, and ask for several searches in one answer, rather than one at a time: each answer is a step, and steps are limited.';
|
|
289
|
+
// The explorers find and the role reads, as a reader asks a librarian where a book is and then
|
|
290
|
+
// reads it: their reports are where to look, not a summary to work from.
|
|
291
|
+
const exploring = 'To find where something is in the repository, ask explorers instead of searching yourself: send `explore` the independent questions you have in one call, and each answers with the files and line ranges that hold what you asked. Then read those ranges yourself, all of them in one readFiles call.';
|
|
288
292
|
// Each provider's cheaper model, which only finds and reads.
|
|
289
293
|
const explorerRoles = {
|
|
290
294
|
anthropic: { model: 'haiku', reasoningEffort: 'medium' },
|
|
291
295
|
openai: { model: 'gpt-5.6-luna', reasoningEffort: 'medium' },
|
|
292
296
|
};
|
|
293
297
|
const explorerSteps = 30;
|
|
294
|
-
const explorerInstructions = `You
|
|
298
|
+
const explorerInstructions = `You find things in a repository for another agent, which is planning or reviewing a change and asked you one question, as a reader asks a librarian where a book is. Find where the answer is with listFiles, searchText, readFile and readFiles, reading only what you need to be sure. Answer with where it is: each file and the line ranges that matter, and in a sentence what each range holds and why it answers the question. The other agent reads those ranges itself, so do not copy code beyond a line that marks a place. Say what you looked for and could not find. Do not propose changes or a plan. ${batchingReads}`;
|
|
295
299
|
// How each role finds its way, sent after the workspace's roots, so it stays short. Only the
|
|
296
300
|
// planner learns the repository; the executor and the reviewer work from its plan, so a plan
|
|
297
301
|
// that leaves them guessing is the planner's to fix, not theirs to make up for.
|
|
298
302
|
const repositoryGuidance = {
|
|
299
|
-
planner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${exploring} ${
|
|
303
|
+
planner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${exploring} ${batchingReads}`,
|
|
300
304
|
executor: `Work from the plan: read the files it names, and only what you need to change them. Do not study the repository's architecture or decisions; the plan already applied them. ${batching}`,
|
|
301
|
-
reviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${exploring} ${
|
|
305
|
+
reviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${exploring} ${batchingReads}`,
|
|
302
306
|
};
|
|
303
307
|
/**
|
|
304
308
|
* Builds the planner → executor → reviewer workflow with every role on the model APIs, each
|
|
305
309
|
* holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the
|
|
306
310
|
* workspace's roots.
|
|
307
311
|
*
|
|
308
|
-
* - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `showChanges`,
|
|
312
|
+
* - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `readFiles`, `showChanges`,
|
|
309
313
|
* the current task's changes as far as each may read them, and `explore`, which sends up to 4
|
|
310
314
|
* read-only explorers at once on the role's provider's cheaper model, each a new agent that
|
|
311
315
|
* starts from its question.
|