@mikode13/harness 6.2.0 → 6.3.1
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 +4 -2
- package/dist/engines/domain/model/llmAgent.js +38 -4
- package/dist/engines/domain/model/llmAgent.js.map +1 -1
- package/dist/llm/infrastructure/claudeLLMClient.js +31 -3
- package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
- package/dist/tools/domain/preparedCall.d.ts +6 -0
- package/dist/tools/domain/preparedCall.js.map +1 -1
- package/dist/tools/infrastructure/commandTool.js +14 -1
- package/dist/tools/infrastructure/commandTool.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -508,8 +508,10 @@ or per role, with no upper bound:
|
|
|
508
508
|
createLLMOrchestrator({ workspace, maxSteps: { executor: 120 } });
|
|
509
509
|
```
|
|
510
510
|
|
|
511
|
-
A run also stops sooner when five answers in a row ask for exactly
|
|
512
|
-
|
|
511
|
+
A run also stops sooner when the model is stuck: when five answers in a row ask for exactly
|
|
512
|
+
the same tool calls, or when one command, with the same input, ends the same way with exactly
|
|
513
|
+
the same output five times in a row, whatever the model did between them. `createLLMAgent`
|
|
514
|
+
takes one number, 65 by default.
|
|
513
515
|
|
|
514
516
|
No conversation is compacted unless you ask. `compactAt` is the number of input tokens at
|
|
515
517
|
which the provider compacts it on its side, replacing the turns before that call with its own
|
|
@@ -79,6 +79,28 @@ class RepeatedCalls {
|
|
|
79
79
|
return this.times;
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
|
+
// A command that ends exactly as it did the last times, in output too, this many times in a row
|
|
83
|
+
// means the model's changes in between are not reaching what the command checks.
|
|
84
|
+
const maxRepeatedEndings = 5;
|
|
85
|
+
/**
|
|
86
|
+
* How many times in a row each command call, by tool and input, has ended exactly the same way.
|
|
87
|
+
* Calls in between to other tools, or to other commands, do not break the count.
|
|
88
|
+
*/
|
|
89
|
+
class RepeatedEndings {
|
|
90
|
+
last = new Map();
|
|
91
|
+
count(call, ending) {
|
|
92
|
+
const key = JSON.stringify([call.name, canonical(call.input)]);
|
|
93
|
+
// A call that never ran a command, such as one denied, says nothing of how it ends.
|
|
94
|
+
if (ending === undefined) {
|
|
95
|
+
this.last.delete(key);
|
|
96
|
+
return 0;
|
|
97
|
+
}
|
|
98
|
+
const previous = this.last.get(key);
|
|
99
|
+
const times = previous?.ending === ending ? previous.times + 1 : 1;
|
|
100
|
+
this.last.set(key, { ending, times });
|
|
101
|
+
return times;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
82
104
|
/**
|
|
83
105
|
* An agent whose conversation is owned by MiKode: every run sends the whole context to a
|
|
84
106
|
* stateless `LLMClient`. Within a run the model may call the agent's tools; the agent runs them
|
|
@@ -346,15 +368,19 @@ export class LLMAgent {
|
|
|
346
368
|
// Set before `execute`, so a tool that fails halfway still counts: it may have had effects.
|
|
347
369
|
effects.toolRan = true;
|
|
348
370
|
try {
|
|
371
|
+
const output = await prepared.run(signal);
|
|
372
|
+
const ending = prepared.ending?.();
|
|
349
373
|
return {
|
|
350
|
-
result: { ...result, output
|
|
374
|
+
result: { ...result, output, isError: false },
|
|
351
375
|
denied: false,
|
|
352
376
|
...(summary === undefined ? {} : { summary }),
|
|
353
377
|
...(prepared.diff === undefined ? {} : { diff: prepared.diff }),
|
|
378
|
+
...(ending === undefined ? {} : { ending }),
|
|
354
379
|
};
|
|
355
380
|
}
|
|
356
381
|
catch (error) {
|
|
357
382
|
signal.throwIfAborted();
|
|
383
|
+
const ending = prepared.ending?.();
|
|
358
384
|
return {
|
|
359
385
|
result: { ...result, output: describeFailure(error), isError: true },
|
|
360
386
|
denied: false,
|
|
@@ -362,6 +388,7 @@ export class LLMAgent {
|
|
|
362
388
|
...(error instanceof ToolExecutionError && error.exitCode !== undefined
|
|
363
389
|
? { exitCode: error.exitCode }
|
|
364
390
|
: {}),
|
|
391
|
+
...(ending === undefined ? {} : { ending }),
|
|
365
392
|
};
|
|
366
393
|
}
|
|
367
394
|
}
|
|
@@ -404,7 +431,7 @@ export class LLMAgent {
|
|
|
404
431
|
/** One at a time and in order, so their effects and their narration never interleave. */
|
|
405
432
|
async runTools(calls, options, effects, toolCall,
|
|
406
433
|
// Throws the failure of a progress callback a call narrated through.
|
|
407
|
-
throwIfProgressFailed) {
|
|
434
|
+
throwIfProgressFailed, endings) {
|
|
408
435
|
const { signal, onProgress: callback = ignoreProgress } = options;
|
|
409
436
|
const results = [];
|
|
410
437
|
for (const call of calls) {
|
|
@@ -413,7 +440,7 @@ export class LLMAgent {
|
|
|
413
440
|
signal.throwIfAborted();
|
|
414
441
|
// `runTool` announces the call only once it is allowed to run, so a consumer never
|
|
415
442
|
// shows a call as running early, nor while the user is still being asked.
|
|
416
|
-
const { result, denied, diff, summary, exitCode } = await this.runTool(call, options, effects, toolCall);
|
|
443
|
+
const { result, denied, diff, summary, exitCode, ending } = await this.runTool(call, options, effects, toolCall);
|
|
417
444
|
// A call that failed to narrate ends the run before the next one can start.
|
|
418
445
|
throwIfProgressFailed();
|
|
419
446
|
if (denied) {
|
|
@@ -439,6 +466,12 @@ export class LLMAgent {
|
|
|
439
466
|
else
|
|
440
467
|
narrate(result, callback, summary, exitCode);
|
|
441
468
|
results.push(result);
|
|
469
|
+
// After its result is narrated, so the consumer sees the ending that stopped the run.
|
|
470
|
+
if (endings.count(call, ending) >= maxRepeatedEndings) {
|
|
471
|
+
throw new UnrecoverableError('The LLM kept getting the same result from a command', {
|
|
472
|
+
cause: `${summary === undefined ? `"${call.name}"` : `"${summary}"`} ended the same way, with the same output, ${String(maxRepeatedEndings)} times in a row.`,
|
|
473
|
+
});
|
|
474
|
+
}
|
|
442
475
|
}
|
|
443
476
|
return { role: 'tool', content: results };
|
|
444
477
|
}
|
|
@@ -521,6 +554,7 @@ export class LLMAgent {
|
|
|
521
554
|
// After following the history, which may have made every earlier read stale.
|
|
522
555
|
const reads = this.reads.begin();
|
|
523
556
|
const repeats = new RepeatedCalls();
|
|
557
|
+
const endings = new RepeatedEndings();
|
|
524
558
|
// A tool that does its own work on the model, such as running subagents, counts it here.
|
|
525
559
|
const spend = (spent, unreportedCall) => {
|
|
526
560
|
tokens = addTokens(tokens, spent);
|
|
@@ -599,7 +633,7 @@ export class LLMAgent {
|
|
|
599
633
|
}
|
|
600
634
|
// On the last step no call is left to send the results to, so the tools do not run.
|
|
601
635
|
if (step < this.maxSteps) {
|
|
602
|
-
const results = await this.runTools(calls, options, effects, { run: context, reads, onProgress, spend }, throwIfProgressFailed);
|
|
636
|
+
const results = await this.runTools(calls, options, effects, { run: context, reads, onProgress, spend }, throwIfProgressFailed, endings);
|
|
603
637
|
runMessages.push(results);
|
|
604
638
|
}
|
|
605
639
|
}
|
|
@@ -1 +1 @@
|
|
|
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;AAE/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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AAC;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 {\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};\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\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/**\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\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}: {\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}) {\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.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}> {\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\treturn {\n\t\t\t\tresult: { ...result, output: await prepared.run(signal), 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};\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\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};\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): 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 } = 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}\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 { 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\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\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\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);\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,OA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AAC;gBACJ,CAAC;gBAED,oFAAoF;gBACpF,IAAI,IAAI,GAAG,IAAI,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 {\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};\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\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\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}: {\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}) {\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.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 { 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\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\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"]}
|
|
@@ -132,6 +132,14 @@ function describeBlock(block, logger) {
|
|
|
132
132
|
case 'tool_use':
|
|
133
133
|
return [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];
|
|
134
134
|
case 'compaction': {
|
|
135
|
+
// A compaction that failed, with no summary. Claude reads one sent back as if it were not
|
|
136
|
+
// there, so it is left out: the context goes on whole, and Claude compacts again later.
|
|
137
|
+
if (!block.content) {
|
|
138
|
+
treatErrors(() => {
|
|
139
|
+
logger.warn('Claude could not compact the conversation; it is sent whole until Claude compacts it');
|
|
140
|
+
}, classifyHostFailure, 'Claude client logger failed while mapping a response');
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
135
143
|
// Claude's summary of the context before it, readable, with what it alone reads back.
|
|
136
144
|
const compaction = {
|
|
137
145
|
type: 'compaction',
|
|
@@ -197,7 +205,11 @@ function toTokens(usage, logger) {
|
|
|
197
205
|
outputTokens: usage.output_tokens,
|
|
198
206
|
};
|
|
199
207
|
}
|
|
200
|
-
|
|
208
|
+
/**
|
|
209
|
+
* @param summaries each compaction's summary as it was streamed, by the index of its block. The
|
|
210
|
+
* SDK joins a delta that carries none as the text "null", so the final message cannot tell.
|
|
211
|
+
*/
|
|
212
|
+
function toLLMResponse(response, logger, summaries) {
|
|
201
213
|
let usage;
|
|
202
214
|
try {
|
|
203
215
|
// Inside the try: it warns when the usage is missing, and that warning can throw too.
|
|
@@ -205,7 +217,12 @@ function toLLMResponse(response, logger) {
|
|
|
205
217
|
return {
|
|
206
218
|
message: {
|
|
207
219
|
role: 'assistant',
|
|
208
|
-
content: response.content.flatMap(
|
|
220
|
+
content: response.content.flatMap((block, index) => {
|
|
221
|
+
const summary = summaries.get(index);
|
|
222
|
+
return describeBlock(block.type === 'compaction' && summary !== undefined
|
|
223
|
+
? { ...block, content: summary }
|
|
224
|
+
: block, logger);
|
|
225
|
+
}),
|
|
209
226
|
},
|
|
210
227
|
usage,
|
|
211
228
|
stopReason: toStopReason(response),
|
|
@@ -317,6 +334,8 @@ export class ClaudeLLMClient {
|
|
|
317
334
|
async send({ context, tools }, signal) {
|
|
318
335
|
let response;
|
|
319
336
|
let stream;
|
|
337
|
+
// What each compaction streamed of its summary, by block index, its missing parts left out.
|
|
338
|
+
const summaries = new Map();
|
|
320
339
|
try {
|
|
321
340
|
// Streamed only to lift the timeout: the client still answers with the whole message.
|
|
322
341
|
const sent = this.client.beta.messages.stream({
|
|
@@ -354,6 +373,15 @@ export class ClaudeLLMClient {
|
|
|
354
373
|
}),
|
|
355
374
|
}, { signal });
|
|
356
375
|
stream = sent;
|
|
376
|
+
sent.on('streamEvent', event => {
|
|
377
|
+
if (event.type === 'content_block_start' && event.content_block.type === 'compaction') {
|
|
378
|
+
summaries.set(event.index, event.content_block.content ?? '');
|
|
379
|
+
}
|
|
380
|
+
else if (event.type === 'content_block_delta' &&
|
|
381
|
+
event.delta.type === 'compaction_delta') {
|
|
382
|
+
summaries.set(event.index, (summaries.get(event.index) ?? '') + (event.delta.content ?? ''));
|
|
383
|
+
}
|
|
384
|
+
});
|
|
357
385
|
response = await sent.finalMessage();
|
|
358
386
|
}
|
|
359
387
|
catch (error) {
|
|
@@ -365,7 +393,7 @@ export class ClaudeLLMClient {
|
|
|
365
393
|
// never finished sending, so the run's count cannot be known.
|
|
366
394
|
throw connected ? withSpentTokens(failure, undefined, true) : failure;
|
|
367
395
|
}
|
|
368
|
-
return treatErrors(() => toLLMResponse(response, this.logger), classifyLocalFailure, 'Claude response mapping failed');
|
|
396
|
+
return treatErrors(() => toLLMResponse(response, this.logger, summaries), classifyLocalFailure, 'Claude response mapping failed');
|
|
369
397
|
}
|
|
370
398
|
}
|
|
371
399
|
//# sourceMappingURL=claudeLLMClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAgBxE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,u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GAAG,IAAI,CAAC;YACd,QAAQ,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,mFAAmF;YACnF,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC5C,MAAM,OAAO,GAAG,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACxD,uFAAuF;YACvF,8DAA8D;YAC9D,MAAM,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\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 { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku runs without thinking: it has no adaptive thinking\n// and takes no reasoning effort, and it is here for short, simple calls such as a summary.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet', 'haiku'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n\thaiku: 'claude-haiku-4-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. 64,000 is the most Haiku 4.5 writes; the\n// other models write up to 128,000, which a single answer here has not needed.\nconst maxOutputTokens = 64_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: AnthropicMessage, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap(block => describeBlock(block, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\t// Missing for Haiku, which runs without thinking.\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort | undefined;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which Anthropic compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (model === 'haiku' && reasoningEffort !== undefined) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t'Claude Haiku takes no reasoning effort: it runs without thinking',\n\t\t\t);\n\t\t}\n\t\tconst effort = model === 'haiku' ? undefined : (reasoningEffort ?? 'high');\n\t\tif (effort !== undefined && !isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined) {\n\t\t\t// The alias names Claude Haiku 4.5, which Anthropic does not compact.\n\t\t\tif (model === 'haiku') {\n\t\t\t\tthrow new InvalidAgentConfigError('Claude Haiku cannot compact: leave compactAt out');\n\t\t\t}\n\t\t\tif (!(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\tthis.compactAt === undefined || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\t\t\t\tmessages: sentContext(context, claudeSource).flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\t// Haiku has no adaptive thinking, and an effort is refused with a 400.\n\t\t\t\t\t...(this.reasoningEffort !== undefined && {\n\t\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t}),\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tbetas: [compactionBeta],\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: this.compactAt },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed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,KAAK,CAAC,IAAI,KAAK,qBAAqB;oBACpC,KAAK,CAAC,KAAK,CAAC,IAAI,KAAK,kBAAkB,EACtC,CAAC;oBACF,SAAS,CAAC,GAAG,CACZ,KAAK,CAAC,KAAK,EACX,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,IAAI,EAAE,CAAC,CAChE,CAAC;gBACH,CAAC;YACF,CAAC,CAAC,CAAC;YACH,QAAQ,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,mFAAmF;YACnF,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC5C,MAAM,OAAO,GAAG,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACxD,uFAAuF;YACvF,8DAA8D;YAC9D,MAAM,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EACrD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\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 { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku runs without thinking: it has no adaptive thinking\n// and takes no reasoning effort, and it is here for short, simple calls such as a summary.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet', 'haiku'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n\thaiku: 'claude-haiku-4-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. 64,000 is the most Haiku 4.5 writes; the\n// other models write up to 128,000, which a single answer here has not needed.\nconst maxOutputTokens = 64_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// A compaction that failed, with no summary. Claude reads one sent back as if it were not\n\t\t\t// there, so it is left out: the context goes on whole, and Claude compacts again later.\n\t\t\tif (!block.content) {\n\t\t\t\ttreatErrors(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'Claude could not compact the conversation; it is sent whole until Claude compacts it',\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t\t);\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\n/**\n * @param summaries each compaction's summary as it was streamed, by the index of its block. The\n * SDK joins a delta that carries none as the text \"null\", so the final message cannot tell.\n */\nfunction toLLMResponse(\n\tresponse: AnthropicMessage,\n\tlogger: ILogger,\n\tsummaries: ReadonlyMap<number, string>,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap((block, index) => {\n\t\t\t\t\tconst summary = summaries.get(index);\n\t\t\t\t\treturn describeBlock(\n\t\t\t\t\t\tblock.type === 'compaction' && summary !== undefined\n\t\t\t\t\t\t\t? { ...block, content: summary }\n\t\t\t\t\t\t\t: block,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\t// Missing for Haiku, which runs without thinking.\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort | undefined;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which Anthropic compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (model === 'haiku' && reasoningEffort !== undefined) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t'Claude Haiku takes no reasoning effort: it runs without thinking',\n\t\t\t);\n\t\t}\n\t\tconst effort = model === 'haiku' ? undefined : (reasoningEffort ?? 'high');\n\t\tif (effort !== undefined && !isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined) {\n\t\t\t// The alias names Claude Haiku 4.5, which Anthropic does not compact.\n\t\t\tif (model === 'haiku') {\n\t\t\t\tthrow new InvalidAgentConfigError('Claude Haiku cannot compact: leave compactAt out');\n\t\t\t}\n\t\t\tif (!(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\t\t// What each compaction streamed of its summary, by block index, its missing parts left out.\n\t\tconst summaries = new Map<number, string>();\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\tthis.compactAt === undefined || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\t\t\t\tmessages: sentContext(context, claudeSource).flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\t// Haiku has no adaptive thinking, and an effort is refused with a 400.\n\t\t\t\t\t...(this.reasoningEffort !== undefined && {\n\t\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t}),\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tbetas: [compactionBeta],\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: this.compactAt },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tsent.on('streamEvent', event => {\n\t\t\t\tif (event.type === 'content_block_start' && event.content_block.type === 'compaction') {\n\t\t\t\t\tsummaries.set(event.index, event.content_block.content ?? '');\n\t\t\t\t} else if (\n\t\t\t\t\tevent.type === 'content_block_delta' &&\n\t\t\t\t\tevent.delta.type === 'compaction_delta'\n\t\t\t\t) {\n\t\t\t\t\tsummaries.set(\n\t\t\t\t\t\tevent.index,\n\t\t\t\t\t\t(summaries.get(event.index) ?? '') + (event.delta.content ?? ''),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, summaries),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
|
|
@@ -12,6 +12,12 @@ export interface PreparedCall {
|
|
|
12
12
|
readonly diff?: string;
|
|
13
13
|
/** For a call that runs a configured command, what it will run, fixed when prepared. */
|
|
14
14
|
readonly command?: CommandLine;
|
|
15
|
+
/**
|
|
16
|
+
* For a call that runs a configured command, how it ended once it has: its outcome and its
|
|
17
|
+
* output, without how long it took, so two runs that ended alike give the same text.
|
|
18
|
+
* `undefined` before it runs, and when it never did.
|
|
19
|
+
*/
|
|
20
|
+
readonly ending?: () => string | undefined;
|
|
15
21
|
run(signal: AbortSignal): Promise<string>;
|
|
16
22
|
}
|
|
17
23
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"preparedCall.js","sourceRoot":"","sources":["../../../src/tools/domain/preparedCall.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"preparedCall.js","sourceRoot":"","sources":["../../../src/tools/domain/preparedCall.ts"],"names":[],"mappings":"AAwBA;;;;GAIG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IACnC,QAAQ,CAAqB;IAEtC,YAAY,OAAe,EAAE,EAAE,QAAQ,KAA4B,EAAE;QACpE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAgBD,SAAS,WAAW,CAAC,IAAe;IACnC,OAAO,SAAS,IAAI,IAAI,CAAC;AAC1B,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAChC,IAAe,EACf,KAAc,EACd,MAAmB,EACnB,IAAqB;IAErB,IAAI,WAAW,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;IAEhE,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;AACnE,CAAC","sourcesContent":["import type { CommandLine, ToolRisk } from '#src/agent/domain/approval';\nimport type { ToolDefinition } from '#src/llm/domain/tool';\nimport type { ToolCallContext } from './readRegistry.ts';\nimport type { Tool, ToolSummarizer } from './tool.ts';\n\n/**\n * A tool call checked and fixed before anyone approves it: its risk is judged on what will\n * really happen, and `run` does exactly that, nothing worked out again.\n */\nexport interface PreparedCall {\n\treadonly risk: ToolRisk;\n\t/** For a change to a file, what it will change as a unified diff, fixed when prepared. */\n\treadonly diff?: string;\n\t/** For a call that runs a configured command, what it will run, fixed when prepared. */\n\treadonly command?: CommandLine;\n\t/**\n\t * For a call that runs a configured command, how it ended once it has: its outcome and its\n\t * output, without how long it took, so two runs that ended alike give the same text.\n\t * `undefined` before it runs, and when it never did.\n\t */\n\treadonly ending?: () => string | undefined;\n\trun(signal: AbortSignal): Promise<string>;\n}\n\n/**\n * A tool ran and produced a result the model should see as an error. Internal tools use this\n * instead of a plain error when the result also carries narrative metadata, such as a command's\n * non-zero exit code.\n */\nexport class ToolExecutionError extends Error {\n\treadonly exitCode: number | undefined;\n\n\tconstructor(message: string, { exitCode }: { exitCode?: number } = {}) {\n\t\tsuper(message);\n\t\tthis.exitCode = exitCode;\n\t}\n}\n\n/**\n * A tool built by the harness, such as a write tool, which prepares each call against the\n * state of the run before it is approved. Internal: consumers build a `Tool`.\n */\nexport interface PreparingTool extends ToolDefinition {\n\t/** Describes the model's input without exposing preparation details to the provider. */\n\tsummarize?: ToolSummarizer;\n\t/** Rejects with a message for the model when the call cannot run. */\n\tprepare(input: unknown, signal: AbortSignal, call: ToolCallContext): Promise<PreparedCall>;\n}\n\n/** What an agent can run: a consumer's `Tool`, or one the harness built. */\nexport type AgentTool = Tool | PreparingTool;\n\nfunction isPreparing(tool: AgentTool): tool is PreparingTool {\n\treturn 'prepare' in tool;\n}\n\n/**\n * Brings any tool into the one lifecycle of prepare, approve, run. A consumer's `Tool` has its\n * risk judged now, and later runs on the input as the model sent it.\n */\nexport async function prepareCall(\n\ttool: AgentTool,\n\tinput: unknown,\n\tsignal: AbortSignal,\n\tcall: ToolCallContext,\n): Promise<PreparedCall> {\n\tif (isPreparing(tool)) return tool.prepare(input, signal, call);\n\n\tconst risk = tool.risk(input);\n\treturn { risk, run: runSignal => tool.execute(input, runSignal) };\n}\n"]}
|
|
@@ -71,21 +71,26 @@ export async function createCommandTool({ commands, policy, writes, covered, bas
|
|
|
71
71
|
args: Object.freeze(buildArguments(command.definition, paramValues)),
|
|
72
72
|
cwd: command.cwd,
|
|
73
73
|
});
|
|
74
|
+
let ending;
|
|
74
75
|
return {
|
|
75
76
|
// A command can change anything its user can: it is always asked about.
|
|
76
77
|
risk: 'destructive',
|
|
77
78
|
command: line,
|
|
79
|
+
ending: () => ending,
|
|
78
80
|
run: runSignal => runCommand({
|
|
79
81
|
name,
|
|
80
82
|
line,
|
|
81
83
|
definition: command.definition,
|
|
82
84
|
context: run,
|
|
83
85
|
signal: runSignal,
|
|
86
|
+
ended: text => {
|
|
87
|
+
ending = text;
|
|
88
|
+
},
|
|
84
89
|
}),
|
|
85
90
|
};
|
|
86
91
|
},
|
|
87
92
|
});
|
|
88
|
-
async function runCommand({ name, line, definition, context, signal, }) {
|
|
93
|
+
async function runCommand({ name, line, definition, context, signal, ended, }) {
|
|
89
94
|
signal.throwIfAborted();
|
|
90
95
|
const session = writes.sessionFor(context);
|
|
91
96
|
const journal = await session.journalForChange();
|
|
@@ -132,6 +137,14 @@ export async function createCommandTool({ commands, policy, writes, covered, bas
|
|
|
132
137
|
// After its changes are recorded: a cancelled command is never reported as finished.
|
|
133
138
|
if (result.outcome === 'cancelled')
|
|
134
139
|
signal.throwIfAborted();
|
|
140
|
+
// Everything but the duration, which differs between two runs of the same check.
|
|
141
|
+
ended(JSON.stringify([
|
|
142
|
+
result.outcome,
|
|
143
|
+
result.exitCode,
|
|
144
|
+
result.signal,
|
|
145
|
+
result.printedBytes,
|
|
146
|
+
result.output,
|
|
147
|
+
]));
|
|
135
148
|
if (result.outcome !== 'exited')
|
|
136
149
|
throw new ToolExecutionError(report);
|
|
137
150
|
if (result.exitCode !== 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commandTool.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/commandTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,OAAO,EACN,cAAc,EAId,yBAAyB,EACzB,uBAAuB,EAEvB,YAAY,EACZ,gBAAgB,GAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAChF,OAAO,EAAE,kBAAkB,EAAsB,MAAM,2BAA2B,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAqB,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAA6B,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAGtD,2FAA2F;AAC3F,wCAAwC;AACxC,MAAM,kBAAkB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,QA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ACf,MAAM,MAAM,GAAG,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAA+B,CAAC,CAAC;YACjE,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI;gBACjC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,CAAC;gBACxC,CAAC,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC,WAAW,wBAAwB,CAAC,CAAC;QACjF,CAAC;QACD,KAAK,MAAM,CAAC,CAAC,CAAC;YACb,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;YACxB,MAAM,WAAW,GAAG,GAAG,SAAS,CAAC,WAAW,sCAAsC,SAAS,CAAC,OAAO,2BAA2B,CAAC;YAC/H,OAAO,SAAS,CAAC,QAAQ,KAAK,IAAI;gBACjC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC;gBAC5B,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,GAAG,WAAW,wBAAwB,CAAC,CAAC;QACrE,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { realpath } from 'node:fs/promises';\nimport { isAbsolute, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport type { CommandLine } from '#src/agent/domain/approval';\nimport type { RunContext } from '#src/agent/domain/runContext';\nimport { displayPath } from '#src/recovery/domain/runChanges';\nimport { InvalidAgentConfigError } from '#src/shared/domain/errors';\nimport type { AccessPolicy } from '../domain/accessPolicy.ts';\nimport {\n\tbuildArguments,\n\ttype CommandDefinition,\n\ttype CommandParameter,\n\ttype Commands,\n\tdefaultCommandOutputBytes,\n\tdefaultCommandTimeoutMs,\n\ttype ParameterValue,\n\tparametersOf,\n\tvalidateCommands,\n} from '../domain/commands.ts';\nimport { EditRefusedError, EditUnconfirmedError } from '../domain/fileEdits.ts';\nimport { ToolExecutionError, type PreparingTool } from '../domain/preparedCall.ts';\nimport { CommandCheckpoint, type CoveredFiles } from './commandCheckpoint.ts';\nimport { type CommandProcessResult, runCommandProcess } from './commandProcess.ts';\nimport { definePreparingTool } from './defineTool.ts';\nimport type { WorkspaceWrites } from './workspaceWrites.ts';\n\n// Only what a toolchain needs to find itself and its locale. Everything else, the provider\n// keys included, stays in this process.\nconst inheritedVariables = ['PATH', 'HOME', 'TMPDIR', 'USER', 'SHELL', 'LANG'];\n// Long enough for a slow disk, short enough not to hold up building an agent.\nconst cwdCheckMs = 10_000;\n\n/** A command ready to run: its definition, and where it runs as a real path. */\ninterface ResolvedCommand {\n\tdefinition: CommandDefinition;\n\tcwd: string;\n}\n\n/**\n * `runCommand`, which runs one of the commands the consumer configured, by name, with the\n * parameters each one declares. Every call asks the approver, showing the program exactly as\n * it will run; `autoApprove` skips that.\n *\n * Around each command, the covered files are captured before and compared after, so what it\n * changed is in the run's history and can be undone: see `CommandCheckpoint`. If the capture\n * fails, the command does not run. A timeout or a cancellation stops its whole process group,\n * and is never reported as a completed command. If the group cannot be confirmed stopped, what\n * changed so far is recorded, the observation stays open, and writing stops for the run.\n *\n * This is not a sandbox: a command runs the repository's code, with everything this user can\n * reach. See \"Configured commands are trusted, not sandboxed\" in decisions.md.\n *\n * @throws {InvalidAgentConfigError} for an invalid configuration, a working directory outside\n * every `write` root, or on Windows, where a process group cannot be stopped.\n */\nexport async function createCommandTool({\n\tcommands,\n\tpolicy,\n\twrites,\n\tcovered,\n\tbase,\n\tplatform = process.platform,\n\trunProcess = runCommandProcess,\n}: {\n\tcommands: Commands;\n\tpolicy: AccessPolicy;\n\twrites: WorkspaceWrites;\n\tcovered: CoveredFiles;\n\t/** The real path of the first root, where a relative `cwd` starts. */\n\tbase: string;\n\tplatform?: NodeJS.Platform;\n\t/** Runs the program. Replaced in tests, to reach what a real process rarely does. */\n\trunProcess?: typeof runCommandProcess;\n}): Promise<PreparingTool> {\n\tif (platform === 'win32') {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t'Configured commands are not supported on Windows yet: the harness cannot stop a command and everything it started there',\n\t\t);\n\t}\n\tvalidateCommands(commands);\n\tconst resolved = new Map<string, ResolvedCommand>();\n\tfor (const [name, definition] of Object.entries(commands)) {\n\t\tresolved.set(name, {\n\t\t\tdefinition,\n\t\t\tcwd: await resolveCwd(`Command \"${name}\"`, definition.cwd, policy, base),\n\t\t});\n\t}\n\n\treturn definePreparingTool({\n\t\tname: 'runCommand',\n\t\tdescription: describeTool(commands),\n\t\tinput: inputSchema(commands),\n\t\tsummarize: ({ command: { name, ...values } }) => {\n\t\t\tconst definition = commands[name];\n\t\t\t// The schema only permits configured names, but keep this defensive for callers that\n\t\t\t// use a tool outside LLMAgent. This description never uses the resolved cwd.\n\t\t\treturn definition ? visibleCommand(definition, values) : name;\n\t\t},\n\t\tprepare: async ({ command: { name, ...values } }, signal, { run }) => {\n\t\t\tconst command = resolved.get(name);\n\t\t\t// The schema allows only the configured names.\n\t\t\tif (!command) throw new Error(`There is no command named \"${name}\"`);\n\t\t\tconst paramValues: Record<string, ParameterValue> = {};\n\t\t\tfor (const parameter of parametersOf(command.definition)) {\n\t\t\t\tconst value =\n\t\t\t\t\t(values as Record<string, ParameterValue | undefined>)[parameter.name] ?? null;\n\t\t\t\tparamValues[parameter.name] =\n\t\t\t\t\tparameter.type === 'paths' && Array.isArray(value)\n\t\t\t\t\t\t? await resolvePaths(value, command.cwd, policy, signal)\n\t\t\t\t\t\t: value;\n\t\t\t}\n\t\t\tconst line: CommandLine = Object.freeze({\n\t\t\t\texecutable: command.definition.executable,\n\t\t\t\targs: Object.freeze(buildArguments(command.definition, paramValues)) as string[],\n\t\t\t\tcwd: command.cwd,\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t// A command can change anything its user can: it is always asked about.\n\t\t\t\trisk: 'destructive',\n\t\t\t\tcommand: line,\n\t\t\t\trun: runSignal =>\n\t\t\t\t\trunCommand({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tdefinition: command.definition,\n\t\t\t\t\t\tcontext: run,\n\t\t\t\t\t\tsignal: runSignal,\n\t\t\t\t\t}),\n\t\t\t};\n\t\t},\n\t});\n\n\tasync function runCommand({\n\t\tname,\n\t\tline,\n\t\tdefinition,\n\t\tcontext,\n\t\tsignal,\n\t}: {\n\t\tname: string;\n\t\tline: CommandLine;\n\t\tdefinition: CommandDefinition;\n\t\tcontext: RunContext;\n\t\tsignal: AbortSignal;\n\t}): Promise<string> {\n\t\tsignal.throwIfAborted();\n\t\tconst session = writes.sessionFor(context);\n\t\tconst journal = await session.journalForChange();\n\t\tlet checkpoint: CommandCheckpoint;\n\t\ttry {\n\t\t\tcheckpoint = await CommandCheckpoint.begin({ journal, covered, by: name, signal });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new EditRefusedError(\n\t\t\t\t`The harness could not capture the files before \"${name}\", so it did not run`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tlet result: CommandProcessResult | undefined;\n\t\tlet startFailure: unknown;\n\t\ttry {\n\t\t\tresult = await runProcess(line.executable, line.args, {\n\t\t\t\tcwd: line.cwd,\n\t\t\t\tenv: environmentFor(definition),\n\t\t\t\ttimeoutMs: definition.timeoutMs ?? defaultCommandTimeoutMs,\n\t\t\t\toutputBytes: definition.outputBytes ?? defaultCommandOutputBytes,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tstartFailure = error;\n\t\t}\n\n\t\tconst complete = result?.stopped ?? true;\n\t\tlet observed: Awaited<ReturnType<CommandCheckpoint['end']>>;\n\t\ttry {\n\t\t\tobserved = await checkpoint.end({ complete });\n\t\t} catch (error) {\n\t\t\tsession.stop('Writing stopped: the harness could not record what a command changed');\n\t\t\tthrow new EditUnconfirmedError(\n\t\t\t\t`\"${name}\" ran, but the harness could not record what it changed; writing has stopped for this run`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tif (!result) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new EditRefusedError(`\"${name}\" could not be started`, { cause: startFailure });\n\t\t}\n\t\tconst report = describeRun(name, definition, result, observed);\n\t\tif (!complete) {\n\t\t\tsession.stop('Writing stopped: a command could not be stopped');\n\t\t\tthrow new EditUnconfirmedError(\n\t\t\t\t`${report}\\n\"${name}\" could not be stopped: something it started may still be changing files, and the history may not hold all of it. Writing has stopped for this run.`,\n\t\t\t);\n\t\t}\n\t\t// After its changes are recorded: a cancelled command is never reported as finished.\n\t\tif (result.outcome === 'cancelled') signal.throwIfAborted();\n\t\tif (result.outcome !== 'exited') throw new ToolExecutionError(report);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new ToolExecutionError(report, {\n\t\t\t\t...(result.exitCode === null ? {} : { exitCode: result.exitCode }),\n\t\t\t});\n\t\t}\n\t\treturn report;\n\t}\n\n\tfunction describeRun(\n\t\tname: string,\n\t\tdefinition: CommandDefinition,\n\t\tresult: CommandProcessResult,\n\t\t{ changes, unrecorded }: Awaited<ReturnType<CommandCheckpoint['end']>>,\n\t): string {\n\t\tconst seconds = (result.durationMs / 1000).toFixed(1);\n\t\tconst lines: string[] = [];\n\t\tif (result.outcome === 'timedOut') {\n\t\t\tconst limit = (definition.timeoutMs ?? defaultCommandTimeoutMs) / 1000;\n\t\t\tlines.push(`\"${name}\" ran past its limit of ${String(limit)} s and was stopped.`);\n\t\t} else if (result.outcome === 'cancelled') {\n\t\t\tlines.push(`\"${name}\" was stopped: the run was cancelled.`);\n\t\t} else if (result.exitCode !== null) {\n\t\t\tlines.push(`\"${name}\" exited with code ${String(result.exitCode)} after ${seconds} s.`);\n\t\t} else {\n\t\t\tlines.push(`\"${name}\" was killed by ${result.signal ?? 'a signal'} after ${seconds} s.`);\n\t\t}\n\n\t\tconst shown = (path: string) => displayPath(base, path);\n\t\tlines.push(\n\t\t\tchanges.length === 0\n\t\t\t\t? 'It changed no file the history covers.'\n\t\t\t\t: `Files it changed, recorded in the history: ${changes.map(change => shown(change.path)).join(', ')}.`,\n\t\t);\n\t\tif (unrecorded.length > 0) {\n\t\t\tlines.push(\n\t\t\t\t`Not recorded, because the history cannot copy them (a folder, a link, or a file over 64 MB): ${unrecorded.map(shown).join(', ')}.`,\n\t\t\t);\n\t\t}\n\n\t\tconst limit = definition.outputBytes ?? defaultCommandOutputBytes;\n\t\tif (result.printedBytes === 0) {\n\t\t\tlines.push('It printed nothing.');\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\tresult.printedBytes > limit\n\t\t\t\t\t? `Output, the last ${kilobytes(limit)} of ${kilobytes(result.printedBytes)}:`\n\t\t\t\t\t: 'Output:',\n\t\t\t\tresult.output,\n\t\t\t);\n\t\t}\n\t\treturn lines.join('\\n');\n\t}\n}\n\nfunction kilobytes(bytes: number): string {\n\treturn `${String(Math.ceil(bytes / 1024))} KB`;\n}\n\n/** The command line the model can see, before paths are resolved against the host workspace. */\nfunction visibleCommand(\n\tdefinition: CommandDefinition,\n\tvalues: Record<string, ParameterValue | undefined>,\n): string {\n\tconst args: string[] = [];\n\tfor (const argument of definition.args ?? []) {\n\t\tif (typeof argument === 'string') {\n\t\t\targs.push(argument);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst value = values[argument.name] ?? null;\n\t\tif (argument.type === 'paths') {\n\t\t\tif (Array.isArray(value)) args.push(...value);\n\t\t} else if (value !== null && typeof value === 'string') {\n\t\t\targs.push(value);\n\t\t}\n\t}\n\n\treturn [definition.executable, ...args].join(' ');\n}\n\n/**\n * Where a configured program runs, as a real path inside a `write` root. `program` names it in\n * the error, as `Command \"test\"`.\n */\nexport async function resolveCwd(\n\tprogram: string,\n\tcwd: string | undefined,\n\tpolicy: AccessPolicy,\n\tbase: string,\n): Promise<string> {\n\tconst named = resolve(base, cwd ?? '.');\n\tlet real: string;\n\ttry {\n\t\treal = await realpath(named);\n\t\tawait policy.check(real, 'write', AbortSignal.timeout(cwdCheckMs));\n\t} catch (error) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${program} needs a cwd inside a write root of the workspace`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\treturn real;\n}\n\n/**\n * Each path, once the policy lets the agent read it, relative to where the command runs. One\n * that would read as a flag is given as `./` and its name.\n */\nasync function resolvePaths(\n\tpaths: string[],\n\tcwd: string,\n\tpolicy: AccessPolicy,\n\tsignal: AbortSignal,\n): Promise<string[]> {\n\tconst resolved: string[] = [];\n\tfor (const path of paths) {\n\t\tconst { absolute } = await policy.check(path, 'read', signal);\n\t\tconst fromCwd = relative(cwd, absolute) || '.';\n\t\tresolved.push(fromCwd.startsWith('-') && !isAbsolute(fromCwd) ? `./${fromCwd}` : fromCwd);\n\t}\n\treturn resolved;\n}\n\n/** A small environment of its own: the inherited few, then what the consumer set. */\nexport function environmentFor(\n\tdefinition: Pick<CommandDefinition, 'env'>,\n\tenv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n\tconst inherited: NodeJS.ProcessEnv = {};\n\tfor (const [variable, value] of Object.entries(env)) {\n\t\tif (value === undefined) continue;\n\t\tif (inheritedVariables.includes(variable) || variable.startsWith('LC_')) {\n\t\t\tinherited[variable] = value;\n\t\t}\n\t}\n\treturn { ...inherited, ...definition.env };\n}\n\nfunction describeTool(commands: Commands): string {\n\tconst list = Object.entries(commands)\n\t\t.map(([name, { description }]) => `- ${name}: ${description}`)\n\t\t.join('\\n');\n\treturn [\n\t\t\"Runs one of the project's configured commands, by name, such as its tests or its formatter.\",\n\t\t'Files it changes are recorded in the history, so they can be undone. Its output is cut to its end.',\n\t\t'Commands:',\n\t\tlist,\n\t].join('\\n');\n}\n\n/**\n * One object per command, told apart by `name`, each with the parameters that command takes.\n * Strict mode needs every key present, so a parameter that may be left out takes `null`.\n */\nfunction inputSchema(commands: Commands) {\n\tconst variants = Object.entries(commands).map(([name, definition]) =>\n\t\tz.object({\n\t\t\tname: z.enum([name]),\n\t\t\t...Object.fromEntries(\n\t\t\t\tparametersOf(definition).map(parameter => [parameter.name, parameterSchema(parameter)]),\n\t\t\t),\n\t\t}),\n\t);\n\tconst [first, ...rest] = variants;\n\t// `validateCommands` refuses an empty configuration.\n\tif (!first) throw new InvalidAgentConfigError('No command is configured');\n\treturn z.object({\n\t\tcommand: (rest.length === 0 ? first : z.union([first, ...rest])).describe(\n\t\t\t'The command to run, and its parameters.',\n\t\t),\n\t});\n}\n\nfunction parameterSchema(parameter: CommandParameter): z.ZodType {\n\tswitch (parameter.type) {\n\t\tcase 'paths':\n\t\t\treturn z\n\t\t\t\t.array(z.string())\n\t\t\t\t.describe(`${parameter.description} Paths inside the workspace; [] for none.`);\n\t\tcase 'choice': {\n\t\t\tconst values = z.enum(parameter.values as [string, ...string[]]);\n\t\t\treturn parameter.required === true\n\t\t\t\t? values.describe(parameter.description)\n\t\t\t\t: values.nullable().describe(`${parameter.description} null to leave it out.`);\n\t\t}\n\t\tcase 'text': {\n\t\t\tconst text = z.string();\n\t\t\tconst description = `${parameter.description} Must match the regular expression ${parameter.pattern}, and not start with \"-\".`;\n\t\t\treturn parameter.required === true\n\t\t\t\t? text.describe(description)\n\t\t\t\t: text.nullable().describe(`${description} null to leave it out.`);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"commandTool.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/commandTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,OAAO,EACN,cAAc,EAId,yBAAyB,EACzB,uBAAuB,EAEvB,YAAY,EACZ,gBAAgB,GAChB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAA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I;gBACjC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC;gBAC5B,CAAC,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,GAAG,WAAW,wBAAwB,CAAC,CAAC;QACrE,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { realpath } from 'node:fs/promises';\nimport { isAbsolute, relative, resolve } from 'node:path';\nimport { z } from 'zod';\nimport type { CommandLine } from '#src/agent/domain/approval';\nimport type { RunContext } from '#src/agent/domain/runContext';\nimport { displayPath } from '#src/recovery/domain/runChanges';\nimport { InvalidAgentConfigError } from '#src/shared/domain/errors';\nimport type { AccessPolicy } from '../domain/accessPolicy.ts';\nimport {\n\tbuildArguments,\n\ttype CommandDefinition,\n\ttype CommandParameter,\n\ttype Commands,\n\tdefaultCommandOutputBytes,\n\tdefaultCommandTimeoutMs,\n\ttype ParameterValue,\n\tparametersOf,\n\tvalidateCommands,\n} from '../domain/commands.ts';\nimport { EditRefusedError, EditUnconfirmedError } from '../domain/fileEdits.ts';\nimport { ToolExecutionError, type PreparingTool } from '../domain/preparedCall.ts';\nimport { CommandCheckpoint, type CoveredFiles } from './commandCheckpoint.ts';\nimport { type CommandProcessResult, runCommandProcess } from './commandProcess.ts';\nimport { definePreparingTool } from './defineTool.ts';\nimport type { WorkspaceWrites } from './workspaceWrites.ts';\n\n// Only what a toolchain needs to find itself and its locale. Everything else, the provider\n// keys included, stays in this process.\nconst inheritedVariables = ['PATH', 'HOME', 'TMPDIR', 'USER', 'SHELL', 'LANG'];\n// Long enough for a slow disk, short enough not to hold up building an agent.\nconst cwdCheckMs = 10_000;\n\n/** A command ready to run: its definition, and where it runs as a real path. */\ninterface ResolvedCommand {\n\tdefinition: CommandDefinition;\n\tcwd: string;\n}\n\n/**\n * `runCommand`, which runs one of the commands the consumer configured, by name, with the\n * parameters each one declares. Every call asks the approver, showing the program exactly as\n * it will run; `autoApprove` skips that.\n *\n * Around each command, the covered files are captured before and compared after, so what it\n * changed is in the run's history and can be undone: see `CommandCheckpoint`. If the capture\n * fails, the command does not run. A timeout or a cancellation stops its whole process group,\n * and is never reported as a completed command. If the group cannot be confirmed stopped, what\n * changed so far is recorded, the observation stays open, and writing stops for the run.\n *\n * This is not a sandbox: a command runs the repository's code, with everything this user can\n * reach. See \"Configured commands are trusted, not sandboxed\" in decisions.md.\n *\n * @throws {InvalidAgentConfigError} for an invalid configuration, a working directory outside\n * every `write` root, or on Windows, where a process group cannot be stopped.\n */\nexport async function createCommandTool({\n\tcommands,\n\tpolicy,\n\twrites,\n\tcovered,\n\tbase,\n\tplatform = process.platform,\n\trunProcess = runCommandProcess,\n}: {\n\tcommands: Commands;\n\tpolicy: AccessPolicy;\n\twrites: WorkspaceWrites;\n\tcovered: CoveredFiles;\n\t/** The real path of the first root, where a relative `cwd` starts. */\n\tbase: string;\n\tplatform?: NodeJS.Platform;\n\t/** Runs the program. Replaced in tests, to reach what a real process rarely does. */\n\trunProcess?: typeof runCommandProcess;\n}): Promise<PreparingTool> {\n\tif (platform === 'win32') {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t'Configured commands are not supported on Windows yet: the harness cannot stop a command and everything it started there',\n\t\t);\n\t}\n\tvalidateCommands(commands);\n\tconst resolved = new Map<string, ResolvedCommand>();\n\tfor (const [name, definition] of Object.entries(commands)) {\n\t\tresolved.set(name, {\n\t\t\tdefinition,\n\t\t\tcwd: await resolveCwd(`Command \"${name}\"`, definition.cwd, policy, base),\n\t\t});\n\t}\n\n\treturn definePreparingTool({\n\t\tname: 'runCommand',\n\t\tdescription: describeTool(commands),\n\t\tinput: inputSchema(commands),\n\t\tsummarize: ({ command: { name, ...values } }) => {\n\t\t\tconst definition = commands[name];\n\t\t\t// The schema only permits configured names, but keep this defensive for callers that\n\t\t\t// use a tool outside LLMAgent. This description never uses the resolved cwd.\n\t\t\treturn definition ? visibleCommand(definition, values) : name;\n\t\t},\n\t\tprepare: async ({ command: { name, ...values } }, signal, { run }) => {\n\t\t\tconst command = resolved.get(name);\n\t\t\t// The schema allows only the configured names.\n\t\t\tif (!command) throw new Error(`There is no command named \"${name}\"`);\n\t\t\tconst paramValues: Record<string, ParameterValue> = {};\n\t\t\tfor (const parameter of parametersOf(command.definition)) {\n\t\t\t\tconst value =\n\t\t\t\t\t(values as Record<string, ParameterValue | undefined>)[parameter.name] ?? null;\n\t\t\t\tparamValues[parameter.name] =\n\t\t\t\t\tparameter.type === 'paths' && Array.isArray(value)\n\t\t\t\t\t\t? await resolvePaths(value, command.cwd, policy, signal)\n\t\t\t\t\t\t: value;\n\t\t\t}\n\t\t\tconst line: CommandLine = Object.freeze({\n\t\t\t\texecutable: command.definition.executable,\n\t\t\t\targs: Object.freeze(buildArguments(command.definition, paramValues)) as string[],\n\t\t\t\tcwd: command.cwd,\n\t\t\t});\n\n\t\t\tlet ending: string | undefined;\n\t\t\treturn {\n\t\t\t\t// A command can change anything its user can: it is always asked about.\n\t\t\t\trisk: 'destructive',\n\t\t\t\tcommand: line,\n\t\t\t\tending: () => ending,\n\t\t\t\trun: runSignal =>\n\t\t\t\t\trunCommand({\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tdefinition: command.definition,\n\t\t\t\t\t\tcontext: run,\n\t\t\t\t\t\tsignal: runSignal,\n\t\t\t\t\t\tended: text => {\n\t\t\t\t\t\t\tending = text;\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t};\n\t\t},\n\t});\n\n\tasync function runCommand({\n\t\tname,\n\t\tline,\n\t\tdefinition,\n\t\tcontext,\n\t\tsignal,\n\t\tended,\n\t}: {\n\t\tname: string;\n\t\tline: CommandLine;\n\t\tdefinition: CommandDefinition;\n\t\tcontext: RunContext;\n\t\tsignal: AbortSignal;\n\t\t/** Told how the command ended, once it ran to an end and everything it changed is recorded. */\n\t\tended: (ending: string) => void;\n\t}): Promise<string> {\n\t\tsignal.throwIfAborted();\n\t\tconst session = writes.sessionFor(context);\n\t\tconst journal = await session.journalForChange();\n\t\tlet checkpoint: CommandCheckpoint;\n\t\ttry {\n\t\t\tcheckpoint = await CommandCheckpoint.begin({ journal, covered, by: name, signal });\n\t\t} catch (error) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new EditRefusedError(\n\t\t\t\t`The harness could not capture the files before \"${name}\", so it did not run`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tlet result: CommandProcessResult | undefined;\n\t\tlet startFailure: unknown;\n\t\ttry {\n\t\t\tresult = await runProcess(line.executable, line.args, {\n\t\t\t\tcwd: line.cwd,\n\t\t\t\tenv: environmentFor(definition),\n\t\t\t\ttimeoutMs: definition.timeoutMs ?? defaultCommandTimeoutMs,\n\t\t\t\toutputBytes: definition.outputBytes ?? defaultCommandOutputBytes,\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tstartFailure = error;\n\t\t}\n\n\t\tconst complete = result?.stopped ?? true;\n\t\tlet observed: Awaited<ReturnType<CommandCheckpoint['end']>>;\n\t\ttry {\n\t\t\tobserved = await checkpoint.end({ complete });\n\t\t} catch (error) {\n\t\t\tsession.stop('Writing stopped: the harness could not record what a command changed');\n\t\t\tthrow new EditUnconfirmedError(\n\t\t\t\t`\"${name}\" ran, but the harness could not record what it changed; writing has stopped for this run`,\n\t\t\t\t{ cause: error },\n\t\t\t);\n\t\t}\n\n\t\tif (!result) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow new EditRefusedError(`\"${name}\" could not be started`, { cause: startFailure });\n\t\t}\n\t\tconst report = describeRun(name, definition, result, observed);\n\t\tif (!complete) {\n\t\t\tsession.stop('Writing stopped: a command could not be stopped');\n\t\t\tthrow new EditUnconfirmedError(\n\t\t\t\t`${report}\\n\"${name}\" could not be stopped: something it started may still be changing files, and the history may not hold all of it. Writing has stopped for this run.`,\n\t\t\t);\n\t\t}\n\t\t// After its changes are recorded: a cancelled command is never reported as finished.\n\t\tif (result.outcome === 'cancelled') signal.throwIfAborted();\n\t\t// Everything but the duration, which differs between two runs of the same check.\n\t\tended(\n\t\t\tJSON.stringify([\n\t\t\t\tresult.outcome,\n\t\t\t\tresult.exitCode,\n\t\t\t\tresult.signal,\n\t\t\t\tresult.printedBytes,\n\t\t\t\tresult.output,\n\t\t\t]),\n\t\t);\n\t\tif (result.outcome !== 'exited') throw new ToolExecutionError(report);\n\t\tif (result.exitCode !== 0) {\n\t\t\tthrow new ToolExecutionError(report, {\n\t\t\t\t...(result.exitCode === null ? {} : { exitCode: result.exitCode }),\n\t\t\t});\n\t\t}\n\t\treturn report;\n\t}\n\n\tfunction describeRun(\n\t\tname: string,\n\t\tdefinition: CommandDefinition,\n\t\tresult: CommandProcessResult,\n\t\t{ changes, unrecorded }: Awaited<ReturnType<CommandCheckpoint['end']>>,\n\t): string {\n\t\tconst seconds = (result.durationMs / 1000).toFixed(1);\n\t\tconst lines: string[] = [];\n\t\tif (result.outcome === 'timedOut') {\n\t\t\tconst limit = (definition.timeoutMs ?? defaultCommandTimeoutMs) / 1000;\n\t\t\tlines.push(`\"${name}\" ran past its limit of ${String(limit)} s and was stopped.`);\n\t\t} else if (result.outcome === 'cancelled') {\n\t\t\tlines.push(`\"${name}\" was stopped: the run was cancelled.`);\n\t\t} else if (result.exitCode !== null) {\n\t\t\tlines.push(`\"${name}\" exited with code ${String(result.exitCode)} after ${seconds} s.`);\n\t\t} else {\n\t\t\tlines.push(`\"${name}\" was killed by ${result.signal ?? 'a signal'} after ${seconds} s.`);\n\t\t}\n\n\t\tconst shown = (path: string) => displayPath(base, path);\n\t\tlines.push(\n\t\t\tchanges.length === 0\n\t\t\t\t? 'It changed no file the history covers.'\n\t\t\t\t: `Files it changed, recorded in the history: ${changes.map(change => shown(change.path)).join(', ')}.`,\n\t\t);\n\t\tif (unrecorded.length > 0) {\n\t\t\tlines.push(\n\t\t\t\t`Not recorded, because the history cannot copy them (a folder, a link, or a file over 64 MB): ${unrecorded.map(shown).join(', ')}.`,\n\t\t\t);\n\t\t}\n\n\t\tconst limit = definition.outputBytes ?? defaultCommandOutputBytes;\n\t\tif (result.printedBytes === 0) {\n\t\t\tlines.push('It printed nothing.');\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\tresult.printedBytes > limit\n\t\t\t\t\t? `Output, the last ${kilobytes(limit)} of ${kilobytes(result.printedBytes)}:`\n\t\t\t\t\t: 'Output:',\n\t\t\t\tresult.output,\n\t\t\t);\n\t\t}\n\t\treturn lines.join('\\n');\n\t}\n}\n\nfunction kilobytes(bytes: number): string {\n\treturn `${String(Math.ceil(bytes / 1024))} KB`;\n}\n\n/** The command line the model can see, before paths are resolved against the host workspace. */\nfunction visibleCommand(\n\tdefinition: CommandDefinition,\n\tvalues: Record<string, ParameterValue | undefined>,\n): string {\n\tconst args: string[] = [];\n\tfor (const argument of definition.args ?? []) {\n\t\tif (typeof argument === 'string') {\n\t\t\targs.push(argument);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst value = values[argument.name] ?? null;\n\t\tif (argument.type === 'paths') {\n\t\t\tif (Array.isArray(value)) args.push(...value);\n\t\t} else if (value !== null && typeof value === 'string') {\n\t\t\targs.push(value);\n\t\t}\n\t}\n\n\treturn [definition.executable, ...args].join(' ');\n}\n\n/**\n * Where a configured program runs, as a real path inside a `write` root. `program` names it in\n * the error, as `Command \"test\"`.\n */\nexport async function resolveCwd(\n\tprogram: string,\n\tcwd: string | undefined,\n\tpolicy: AccessPolicy,\n\tbase: string,\n): Promise<string> {\n\tconst named = resolve(base, cwd ?? '.');\n\tlet real: string;\n\ttry {\n\t\treal = await realpath(named);\n\t\tawait policy.check(real, 'write', AbortSignal.timeout(cwdCheckMs));\n\t} catch (error) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${program} needs a cwd inside a write root of the workspace`,\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\treturn real;\n}\n\n/**\n * Each path, once the policy lets the agent read it, relative to where the command runs. One\n * that would read as a flag is given as `./` and its name.\n */\nasync function resolvePaths(\n\tpaths: string[],\n\tcwd: string,\n\tpolicy: AccessPolicy,\n\tsignal: AbortSignal,\n): Promise<string[]> {\n\tconst resolved: string[] = [];\n\tfor (const path of paths) {\n\t\tconst { absolute } = await policy.check(path, 'read', signal);\n\t\tconst fromCwd = relative(cwd, absolute) || '.';\n\t\tresolved.push(fromCwd.startsWith('-') && !isAbsolute(fromCwd) ? `./${fromCwd}` : fromCwd);\n\t}\n\treturn resolved;\n}\n\n/** A small environment of its own: the inherited few, then what the consumer set. */\nexport function environmentFor(\n\tdefinition: Pick<CommandDefinition, 'env'>,\n\tenv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n\tconst inherited: NodeJS.ProcessEnv = {};\n\tfor (const [variable, value] of Object.entries(env)) {\n\t\tif (value === undefined) continue;\n\t\tif (inheritedVariables.includes(variable) || variable.startsWith('LC_')) {\n\t\t\tinherited[variable] = value;\n\t\t}\n\t}\n\treturn { ...inherited, ...definition.env };\n}\n\nfunction describeTool(commands: Commands): string {\n\tconst list = Object.entries(commands)\n\t\t.map(([name, { description }]) => `- ${name}: ${description}`)\n\t\t.join('\\n');\n\treturn [\n\t\t\"Runs one of the project's configured commands, by name, such as its tests or its formatter.\",\n\t\t'Files it changes are recorded in the history, so they can be undone. Its output is cut to its end.',\n\t\t'Commands:',\n\t\tlist,\n\t].join('\\n');\n}\n\n/**\n * One object per command, told apart by `name`, each with the parameters that command takes.\n * Strict mode needs every key present, so a parameter that may be left out takes `null`.\n */\nfunction inputSchema(commands: Commands) {\n\tconst variants = Object.entries(commands).map(([name, definition]) =>\n\t\tz.object({\n\t\t\tname: z.enum([name]),\n\t\t\t...Object.fromEntries(\n\t\t\t\tparametersOf(definition).map(parameter => [parameter.name, parameterSchema(parameter)]),\n\t\t\t),\n\t\t}),\n\t);\n\tconst [first, ...rest] = variants;\n\t// `validateCommands` refuses an empty configuration.\n\tif (!first) throw new InvalidAgentConfigError('No command is configured');\n\treturn z.object({\n\t\tcommand: (rest.length === 0 ? first : z.union([first, ...rest])).describe(\n\t\t\t'The command to run, and its parameters.',\n\t\t),\n\t});\n}\n\nfunction parameterSchema(parameter: CommandParameter): z.ZodType {\n\tswitch (parameter.type) {\n\t\tcase 'paths':\n\t\t\treturn z\n\t\t\t\t.array(z.string())\n\t\t\t\t.describe(`${parameter.description} Paths inside the workspace; [] for none.`);\n\t\tcase 'choice': {\n\t\t\tconst values = z.enum(parameter.values as [string, ...string[]]);\n\t\t\treturn parameter.required === true\n\t\t\t\t? values.describe(parameter.description)\n\t\t\t\t: values.nullable().describe(`${parameter.description} null to leave it out.`);\n\t\t}\n\t\tcase 'text': {\n\t\t\tconst text = z.string();\n\t\t\tconst description = `${parameter.description} Must match the regular expression ${parameter.pattern}, and not start with \"-\".`;\n\t\t\treturn parameter.required === true\n\t\t\t\t? text.describe(description)\n\t\t\t\t: text.nullable().describe(`${description} null to leave it out.`);\n\t\t}\n\t}\n}\n"]}
|