@mikode13/harness 6.0.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -491,7 +491,11 @@ run in `AgentResponse.runId`. Progress reports each change as a unified `diff` o
491
491
  model APIs:
492
492
 
493
493
  - the planner and the reviewer read, with a `showChanges` tool that gives the current task's
494
- changes as far as each may read them;
494
+ changes as far as each may read them, and an `explore` tool that sends up to 4 read-only
495
+ explorers at once, one per question, on the role's provider's cheaper model: Claude Haiku
496
+ 4.5, or `gpt-5.6-luna` at `medium`. Each starts from its question alone and reports what it
497
+ found, so the role reads the reports instead of filling its own context with files. Their
498
+ usage counts in the run's, and their narration arrives as `subagent` events;
495
499
  - the executor gets its provider's file tools. `autoApprove` reaches only the executor;
496
500
  - each role gets the commands whose `roles` name it; a command names only the executor unless
497
501
  it says otherwise.
@@ -697,7 +701,8 @@ heading. Reasoning is dim italic and complete by default; pass
697
701
  updates the spinner rather than printing a second line, and cancelling a turn clears
698
702
  its pending spinner state. Pass `--steps <file>` to append one JSON line per call to the
699
703
  model to that file: the call's tokens and what its context held, by origin, for measuring
700
- what a run spends.
704
+ what a run spends. An explorer's call is written as the `subagent` event that carries it,
705
+ which names the role that sent the explorer and its number.
701
706
 
702
707
  `cli/cli.ts` currently enables `autoApprove` for its Agent SDK agents, not for `--llm`.
703
708
  This maps to each provider's permission-bypass mode and grants those processes
@@ -156,6 +156,20 @@ export type ProgressEvent = {
156
156
  /** Absent after `stop` or `complete`. */
157
157
  nextStage?: string;
158
158
  agent?: ProgressAgent;
159
+ }
160
+ /**
161
+ * An event of a subagent that a tool call started, such as one of the explorers an `explore`
162
+ * call runs at once. `callId` is the `id` of that call's `tool` events, and `subagent`
163
+ * numbers its subagents from 1, so the events of agents running in parallel stay apart.
164
+ */
165
+ | {
166
+ type: 'subagent';
167
+ callId: string;
168
+ subagent: number;
169
+ /** What the subagent was asked. */
170
+ task: string;
171
+ event: ProgressEvent;
172
+ agent?: ProgressAgent;
159
173
  };
160
174
  /**
161
175
  * What one call to the model sent, in characters by where it came from: an estimate of size
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../../../src/agent/domain/agent.ts"],"names":[],"mappings":"AAwDA,gDAAgD;AAChD,MAAM,CAAC,MAAM,cAAc,GAAa,GAAG,EAAE,CAAC,SAAS,CAAC","sourcesContent":["import type { Tokens } from '#src/shared/domain/tokens';\nimport type { Approver } from './approval.ts';\nimport type { Asker } from './question.ts';\n\n/**\n * How a run ended when it did not fail. Every token a run spends travels with its end: here\n * when it finishes, in `RecoverableError.tokens` or `UnrecoverableError.tokens` when it fails.\n */\nexport interface AgentResponse {\n\t/** The final text. Empty when the run produced none, for example a turn that only edited files. */\n\tresponse: string;\n\t/**\n\t * Missing when any call in the run completed without reporting usage, which is not the same\n\t * as zero: a partial sum would look complete.\n\t */\n\ttokens?: Tokens;\n\t/** Wall-clock seconds the consumer waited for the run, retries and every role included. */\n\tduration: number;\n\t/**\n\t * The run the workspace's history recorded, when this run wrote through the harness's write\n\t * tools. Absent for a run that wrote nothing, and from the Agent SDK engines, whose changes\n\t * the history does not record.\n\t */\n\trunId?: string;\n}\n\nexport type Callback = (item: ProgressEvent) => void;\n\n/**\n * What a run needs besides its prompt. InstructedAgent passes it on whole. OrchestratorAgent\n * copies its own enumerable fields and replaces only `onProgress` per role; RetryingAgent does\n * the same for a run with `ask`, replacing only `ask`. A field must therefore be an own\n * enumerable one to reach every agent.\n */\nexport interface RunOptions {\n\t/**\n\t * Cancels the run, which then rejects with the signal's reason: an `AbortError`, or a\n\t * `TimeoutError` from `AbortSignal.timeout`. `isAbortError` recognizes both.\n\t */\n\tsignal: AbortSignal;\n\t/** Receives the run's live activity. Without it, the run is silent. */\n\tonProgress?: Callback | undefined;\n\t/**\n\t * Asked before a model-backed agent runs a `destructive` tool call. Without it, such a call\n\t * is denied. An agent built with `autoApprove` never asks, and the Agent SDK engines ignore\n\t * it: their own permission systems decide.\n\t */\n\tapprove?: Approver | undefined;\n\t/**\n\t * Answers what a model-backed agent asks the user, through its `askUser` tool, when a\n\t * decision is the user's to make. Without it the agent has no such tool. The Agent SDK\n\t * engines ignore it.\n\t */\n\task?: Asker | undefined;\n}\n\n/** The `onProgress` of a run that gave none. */\nexport const ignoreProgress: Callback = () => undefined;\n\n/**\n * Live activity during a run, for narration only: the result travels in `AgentResponse`.\n * New event types can arrive in a minor release, so render the types you know and ignore\n * the rest instead of switching over them exhaustively with a `never` check.\n */\nexport type ProgressEvent =\n\t| { type: 'command'; command: string; exitCode?: number; agent?: ProgressAgent }\n\t| { type: 'reasoning'; message: string; agent?: ProgressAgent }\n\t| { type: 'search'; query: string; agent?: ProgressAgent }\n\t| {\n\t\t\ttype: 'fileChange';\n\t\t\tchanges: { path: string; kind: 'add' | 'update' | 'delete' }[];\n\t\t\tagent?: ProgressAgent;\n\t }\n\t| { type: 'mcpTool'; server: string; tool: string; status: string; agent?: ProgressAgent }\n\t| { type: 'agentMessage'; message: string; agent?: ProgressAgent }\n\t/** `id` pairs a call's end with its start when one step calls the same tool more than once. */\n\t| {\n\t\t\ttype: 'tool';\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\tagent?: ProgressAgent;\n\t\t\t/** A short, tool-owned description of the call. Narration only. */\n\t\t\tsummary?: string;\n\t\t\t/** The exit code of a configured command that ended with an error. Narration only. */\n\t\t\texitCode?: number;\n\t\t\t/**\n\t\t\t * `in_progress` only once the call is about to run, after any approval. `denied` when\n\t\t\t * it never ran because no one allowed it, with no `in_progress` before it.\n\t\t\t */\n\t\t\tstatus: 'in_progress' | 'completed' | 'error' | 'denied';\n\t\t\t/**\n\t\t\t * On `completed`, for a call that changed a file through the harness's write tools: the\n\t\t\t * change as a unified diff, for the person watching. Narration only; the run's whole\n\t\t\t * record is the history's `changes`.\n\t\t\t */\n\t\t\tdiff?: string;\n\t }\n\t| { type: 'todoList'; items: { text: string; completed: boolean }[]; agent?: ProgressAgent }\n\t| { type: 'turnStarted'; agent?: ProgressAgent }\n\t| { type: 'turnEnded'; agent?: ProgressAgent }\n\t/**\n\t * One billed call to the model by an agent on the model APIs, including one the model\n\t * stopped early or the client turned into an error: what the call sent and what it cost.\n\t * Narration only: the run's total is `AgentResponse.tokens`, or the failure's `tokens`.\n\t */\n\t| {\n\t\t\ttype: 'step';\n\t\t\t/** 1 for the first call of the run. */\n\t\t\tstep: number;\n\t\t\t/** Missing when the provider did not report this call's usage. */\n\t\t\ttokens?: Tokens;\n\t\t\tcontext: StepContext;\n\t\t\tagent?: ProgressAgent;\n\t }\n\t/**\n\t * A workflow's stage asks its agent for an answer; `attempt` is 2 or more when the previous\n\t * answer was invalid. Stages run one at a time, so the events that follow, until the next\n\t * workflow event, are this stage's agent's.\n\t */\n\t| { type: 'workflowStage'; stage: string; attempt: number; agent?: ProgressAgent }\n\t/** The transition a stage's valid answer selected, and the stage it leads to. */\n\t| {\n\t\t\ttype: 'workflowTransition';\n\t\t\tstage: string;\n\t\t\ttransition: 'go' | 'stop' | 'complete';\n\t\t\t/** Absent after `stop` or `complete`. */\n\t\t\tnextStage?: string;\n\t\t\tagent?: ProgressAgent;\n\t };\n\n/**\n * What one call to the model sent, in characters by where it came from: an estimate of size\n * for finding what fills a context, not a token count.\n */\nexport interface StepContext {\n\t/** The system prompt. */\n\tinstructions: number;\n\t/** The tool definitions. */\n\ttools: number;\n\t/**\n\t * The text of the user's prompts and the model's answers, and the provider's summary of the\n\t * turns before it once it has compacted them: only what the call sent.\n\t */\n\tmessages: number;\n\t/** Reasoning the model produced earlier and is sent back: its provider's own signed or encrypted blocks. */\n\treasoning: number;\n\t/** The input of every tool call so far. */\n\ttoolCalls: number;\n\t/** Every tool result so far, by tool, largest first. */\n\ttoolResults: { tool: string; characters: number; calls: number }[];\n\t/** The largest single results, each with its call's summary when the tool gives one. */\n\tlargestResults: { tool: string; characters: number; summary?: string }[];\n}\n\n/** A role in the fixed planner → executor → reviewer workflow. */\nexport type ProgressAgent = 'planner' | 'executor' | 'reviewer';\n\n/**\n * The contract every engine (CodexAgent, ClaudeAgent, future providers) and every\n * decorator (RetryingAgent, OrchestratorAgent) is built against.\n *\n * Implementers MUST only ever reject with `RecoverableError` or `UnrecoverableError`\n * (see src/shared/domain/errors.ts) — never a raw SDK error, a plain `Error`, or anything else leaked\n * unclassified. Every consumer of `Agent` (RetryingAgent's retry decision,\n * OrchestratorAgent's failure handling) `instanceof`-checks against those two types to\n * decide what to do next; a leaked, unclassified error bypasses that decision\n * entirely — it gets retried when it shouldn't be, or crashes a run that a retry\n * would have recovered. Wrap every call into the underlying SDK so nothing escapes\n * unclassified, including failures the SDK itself doesn't model as a domain error\n * (network errors, malformed responses, etc.); `classifyProviderFailure` does this.\n *\n * Cancellation is the one exception: an `AbortError`, or the `TimeoutError` of\n * `AbortSignal.timeout`, must propagate unchanged, because\n * consumers check for it before either error type.\n */\nexport interface Agent {\n\trun(prompt: string, options: RunOptions): Promise<AgentResponse>;\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../../../src/agent/domain/agent.ts"],"names":[],"mappings":"AAwDA,gDAAgD;AAChD,MAAM,CAAC,MAAM,cAAc,GAAa,GAAG,EAAE,CAAC,SAAS,CAAC","sourcesContent":["import type { Tokens } from '#src/shared/domain/tokens';\nimport type { Approver } from './approval.ts';\nimport type { Asker } from './question.ts';\n\n/**\n * How a run ended when it did not fail. Every token a run spends travels with its end: here\n * when it finishes, in `RecoverableError.tokens` or `UnrecoverableError.tokens` when it fails.\n */\nexport interface AgentResponse {\n\t/** The final text. Empty when the run produced none, for example a turn that only edited files. */\n\tresponse: string;\n\t/**\n\t * Missing when any call in the run completed without reporting usage, which is not the same\n\t * as zero: a partial sum would look complete.\n\t */\n\ttokens?: Tokens;\n\t/** Wall-clock seconds the consumer waited for the run, retries and every role included. */\n\tduration: number;\n\t/**\n\t * The run the workspace's history recorded, when this run wrote through the harness's write\n\t * tools. Absent for a run that wrote nothing, and from the Agent SDK engines, whose changes\n\t * the history does not record.\n\t */\n\trunId?: string;\n}\n\nexport type Callback = (item: ProgressEvent) => void;\n\n/**\n * What a run needs besides its prompt. InstructedAgent passes it on whole. OrchestratorAgent\n * copies its own enumerable fields and replaces only `onProgress` per role; RetryingAgent does\n * the same for a run with `ask`, replacing only `ask`. A field must therefore be an own\n * enumerable one to reach every agent.\n */\nexport interface RunOptions {\n\t/**\n\t * Cancels the run, which then rejects with the signal's reason: an `AbortError`, or a\n\t * `TimeoutError` from `AbortSignal.timeout`. `isAbortError` recognizes both.\n\t */\n\tsignal: AbortSignal;\n\t/** Receives the run's live activity. Without it, the run is silent. */\n\tonProgress?: Callback | undefined;\n\t/**\n\t * Asked before a model-backed agent runs a `destructive` tool call. Without it, such a call\n\t * is denied. An agent built with `autoApprove` never asks, and the Agent SDK engines ignore\n\t * it: their own permission systems decide.\n\t */\n\tapprove?: Approver | undefined;\n\t/**\n\t * Answers what a model-backed agent asks the user, through its `askUser` tool, when a\n\t * decision is the user's to make. Without it the agent has no such tool. The Agent SDK\n\t * engines ignore it.\n\t */\n\task?: Asker | undefined;\n}\n\n/** The `onProgress` of a run that gave none. */\nexport const ignoreProgress: Callback = () => undefined;\n\n/**\n * Live activity during a run, for narration only: the result travels in `AgentResponse`.\n * New event types can arrive in a minor release, so render the types you know and ignore\n * the rest instead of switching over them exhaustively with a `never` check.\n */\nexport type ProgressEvent =\n\t| { type: 'command'; command: string; exitCode?: number; agent?: ProgressAgent }\n\t| { type: 'reasoning'; message: string; agent?: ProgressAgent }\n\t| { type: 'search'; query: string; agent?: ProgressAgent }\n\t| {\n\t\t\ttype: 'fileChange';\n\t\t\tchanges: { path: string; kind: 'add' | 'update' | 'delete' }[];\n\t\t\tagent?: ProgressAgent;\n\t }\n\t| { type: 'mcpTool'; server: string; tool: string; status: string; agent?: ProgressAgent }\n\t| { type: 'agentMessage'; message: string; agent?: ProgressAgent }\n\t/** `id` pairs a call's end with its start when one step calls the same tool more than once. */\n\t| {\n\t\t\ttype: 'tool';\n\t\t\tid: string;\n\t\t\tname: string;\n\t\t\tagent?: ProgressAgent;\n\t\t\t/** A short, tool-owned description of the call. Narration only. */\n\t\t\tsummary?: string;\n\t\t\t/** The exit code of a configured command that ended with an error. Narration only. */\n\t\t\texitCode?: number;\n\t\t\t/**\n\t\t\t * `in_progress` only once the call is about to run, after any approval. `denied` when\n\t\t\t * it never ran because no one allowed it, with no `in_progress` before it.\n\t\t\t */\n\t\t\tstatus: 'in_progress' | 'completed' | 'error' | 'denied';\n\t\t\t/**\n\t\t\t * On `completed`, for a call that changed a file through the harness's write tools: the\n\t\t\t * change as a unified diff, for the person watching. Narration only; the run's whole\n\t\t\t * record is the history's `changes`.\n\t\t\t */\n\t\t\tdiff?: string;\n\t }\n\t| { type: 'todoList'; items: { text: string; completed: boolean }[]; agent?: ProgressAgent }\n\t| { type: 'turnStarted'; agent?: ProgressAgent }\n\t| { type: 'turnEnded'; agent?: ProgressAgent }\n\t/**\n\t * One billed call to the model by an agent on the model APIs, including one the model\n\t * stopped early or the client turned into an error: what the call sent and what it cost.\n\t * Narration only: the run's total is `AgentResponse.tokens`, or the failure's `tokens`.\n\t */\n\t| {\n\t\t\ttype: 'step';\n\t\t\t/** 1 for the first call of the run. */\n\t\t\tstep: number;\n\t\t\t/** Missing when the provider did not report this call's usage. */\n\t\t\ttokens?: Tokens;\n\t\t\tcontext: StepContext;\n\t\t\tagent?: ProgressAgent;\n\t }\n\t/**\n\t * A workflow's stage asks its agent for an answer; `attempt` is 2 or more when the previous\n\t * answer was invalid. Stages run one at a time, so the events that follow, until the next\n\t * workflow event, are this stage's agent's.\n\t */\n\t| { type: 'workflowStage'; stage: string; attempt: number; agent?: ProgressAgent }\n\t/** The transition a stage's valid answer selected, and the stage it leads to. */\n\t| {\n\t\t\ttype: 'workflowTransition';\n\t\t\tstage: string;\n\t\t\ttransition: 'go' | 'stop' | 'complete';\n\t\t\t/** Absent after `stop` or `complete`. */\n\t\t\tnextStage?: string;\n\t\t\tagent?: ProgressAgent;\n\t }\n\t/**\n\t * An event of a subagent that a tool call started, such as one of the explorers an `explore`\n\t * call runs at once. `callId` is the `id` of that call's `tool` events, and `subagent`\n\t * numbers its subagents from 1, so the events of agents running in parallel stay apart.\n\t */\n\t| {\n\t\t\ttype: 'subagent';\n\t\t\tcallId: string;\n\t\t\tsubagent: number;\n\t\t\t/** What the subagent was asked. */\n\t\t\ttask: string;\n\t\t\tevent: ProgressEvent;\n\t\t\tagent?: ProgressAgent;\n\t };\n\n/**\n * What one call to the model sent, in characters by where it came from: an estimate of size\n * for finding what fills a context, not a token count.\n */\nexport interface StepContext {\n\t/** The system prompt. */\n\tinstructions: number;\n\t/** The tool definitions. */\n\ttools: number;\n\t/**\n\t * The text of the user's prompts and the model's answers, and the provider's summary of the\n\t * turns before it once it has compacted them: only what the call sent.\n\t */\n\tmessages: number;\n\t/** Reasoning the model produced earlier and is sent back: its provider's own signed or encrypted blocks. */\n\treasoning: number;\n\t/** The input of every tool call so far. */\n\ttoolCalls: number;\n\t/** Every tool result so far, by tool, largest first. */\n\ttoolResults: { tool: string; characters: number; calls: number }[];\n\t/** The largest single results, each with its call's summary when the tool gives one. */\n\tlargestResults: { tool: string; characters: number; summary?: string }[];\n}\n\n/** A role in the fixed planner → executor → reviewer workflow. */\nexport type ProgressAgent = 'planner' | 'executor' | 'reviewer';\n\n/**\n * The contract every engine (CodexAgent, ClaudeAgent, future providers) and every\n * decorator (RetryingAgent, OrchestratorAgent) is built against.\n *\n * Implementers MUST only ever reject with `RecoverableError` or `UnrecoverableError`\n * (see src/shared/domain/errors.ts) — never a raw SDK error, a plain `Error`, or anything else leaked\n * unclassified. Every consumer of `Agent` (RetryingAgent's retry decision,\n * OrchestratorAgent's failure handling) `instanceof`-checks against those two types to\n * decide what to do next; a leaked, unclassified error bypasses that decision\n * entirely — it gets retried when it shouldn't be, or crashes a run that a retry\n * would have recovered. Wrap every call into the underlying SDK so nothing escapes\n * unclassified, including failures the SDK itself doesn't model as a domain error\n * (network errors, malformed responses, etc.); `classifyProviderFailure` does this.\n *\n * Cancellation is the one exception: an `AbortError`, or the `TimeoutError` of\n * `AbortSignal.timeout`, must propagate unchanged, because\n * consumers check for it before either error type.\n */\nexport interface Agent {\n\trun(prompt: string, options: RunOptions): Promise<AgentResponse>;\n}\n"]}
@@ -308,7 +308,7 @@ export class LLMAgent {
308
308
  }
309
309
  let prepared;
310
310
  try {
311
- prepared = await prepareCall(tool, call.input, signal, toolCall);
311
+ prepared = await prepareCall(tool, call.input, signal, { ...toolCall, callId: call.id });
312
312
  }
313
313
  catch (error) {
314
314
  signal.throwIfAborted();
@@ -517,6 +517,25 @@ export class LLMAgent {
517
517
  // After following the history, which may have made every earlier read stale.
518
518
  const reads = this.reads.begin();
519
519
  const repeats = new RepeatedCalls();
520
+ // A tool that does its own work on the model, such as running subagents, counts it here.
521
+ const spend = (spent, unreportedCall) => {
522
+ tokens = addTokens(tokens, spent);
523
+ unreported ||= unreportedCall;
524
+ };
525
+ // A tool narrates through this without ever failing: a failing callback would reach
526
+ // only the tool, which turns any failure into a result for the model. The run ends on
527
+ // it once the tools return.
528
+ let progressFailure;
529
+ const onProgress = (event) => {
530
+ if (progressFailure)
531
+ return;
532
+ try {
533
+ emit(event, callback);
534
+ }
535
+ catch (error) {
536
+ progressFailure = { error };
537
+ }
538
+ };
520
539
  // The agent's own `askUser` exists only for a run someone can answer, and never beside
521
540
  // a consumer's tool of that name, which the consumer gave first and which stays theirs.
522
541
  const offersAsk = options.ask !== undefined && !this.tools.has(askUserName);
@@ -572,7 +591,15 @@ export class LLMAgent {
572
591
  }
573
592
  // On the last step no call is left to send the results to, so the tools do not run.
574
593
  if (step < this.maxSteps) {
575
- runMessages.push(await this.runTools(calls, options, effects, { run: context, reads }));
594
+ const results = await this.runTools(calls, options, effects, {
595
+ run: context,
596
+ reads,
597
+ onProgress,
598
+ spend,
599
+ });
600
+ if (progressFailure)
601
+ throw progressFailure.error;
602
+ runMessages.push(results);
576
603
  }
577
604
  }
578
605
  throw new UnrecoverableError('The LLM did not finish within its step limit', {
@@ -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;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EACN,iBAAiB,EACjB,WAAW,EACX,eAAe,EACf,WAAW,EACX,aAAa,EACb,kBAAkB,GAClB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEN,aAAa,EAEb,YAAY,EACZ,QAAQ,GACR,MAAM,sBAAsB,CAAC;AAE9B,SAAS,YAAY,CAAC,IAAiB;IACtC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;QACnB,KAAK,MAAM;YACV,O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FAAkF;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';\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: ToolCallContext,\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);\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: ToolCallContext,\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\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// 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\trunMessages.push(await this.runTools(calls, options, effects, { run: context, reads }));\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,y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wBACZ,KAAK;wBACL,UAAU;wBACV,KAAK;qBACL,CAAC,CAAC;oBACH,IAAI,eAAe;wBAAE,MAAM,eAAe,CAAC,KAAK,CAAC;oBACjD,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/**\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): 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\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 the tools return.\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\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(calls, options, effects, {\n\t\t\t\t\t\trun: context,\n\t\t\t\t\t\treads,\n\t\t\t\t\t\tonProgress,\n\t\t\t\t\t\tspend,\n\t\t\t\t\t});\n\t\t\t\t\tif (progressFailure) throw progressFailure.error;\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"]}
@@ -147,8 +147,10 @@ export declare function createFileTools(provider: AgentProvider, workspace: Work
147
147
  * holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the
148
148
  * workspace's roots.
149
149
  *
150
- * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, and
151
- * `showChanges`, the current task's changes as far as each may read them.
150
+ * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `showChanges`,
151
+ * the current task's changes as far as each may read them, and `explore`, which sends up to 4
152
+ * read-only explorers at once on the role's provider's cheaper model, each a new agent that
153
+ * starts from its question.
152
154
  * - The executor gets its provider's file tools (see `createFileTools`), and changes files only
153
155
  * in a `write` root; `autoApprove` reaches only it.
154
156
  * - Each role has its own step limit: `maxSteps`, 80 for the executor and 65 for the others by
@@ -10,6 +10,7 @@ import { isOneOf } from '#src/shared/domain/isOneOf';
10
10
  import { Logger } from '#src/shared/infrastructure/logger';
11
11
  import { commandsFor, validateCommands, } from '#src/tools/domain/commands';
12
12
  import { commandToolFor, fileToolsFor, openStore, openWorkspace, stateDirectoryOf, } from '#src/tools/infrastructure/fileTools';
13
+ import { createExploreTool } from '#src/tools/infrastructure/exploreTool';
13
14
  import { createShowChangesTool } from '#src/tools/infrastructure/showChangesTool';
14
15
  import { createTrackedReadFile } from '#src/tools/infrastructure/trackedReadFile';
15
16
  import { createWorkspaceTools } from '#src/tools/infrastructure/workspaceTools';
@@ -250,17 +251,21 @@ async function executorTools(provider, workspace, commands) {
250
251
  return tools;
251
252
  return [...tools, await commandToolFor(workspace, commands)];
252
253
  }
254
+ /** What an explorer finds and reads with: no edits, no changes, no commands. */
255
+ function explorerTools({ read, policy }) {
256
+ const finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile');
257
+ return [...finding, createTrackedReadFile(policy)];
258
+ }
253
259
  /**
254
- * What the planner and the reviewer read with: no edits, the current task's changes, and the
255
- * commands given to their role.
260
+ * What the planner and the reviewer read with: no edits, the current task's changes, `explore`
261
+ * with `explorer`, and the commands given to their role.
256
262
  */
257
- async function readingTools(workspace, role, commands) {
258
- const { read, policy, store } = workspace;
259
- const finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile');
263
+ async function readingTools(workspace, role, commands, explorer) {
264
+ const { policy, store } = workspace;
260
265
  const tools = [
261
- ...finding,
262
- createTrackedReadFile(policy),
266
+ ...explorerTools(workspace),
263
267
  createShowChangesTool({ store, policy }),
268
+ createExploreTool(explorer),
264
269
  ];
265
270
  const own = commands && commandsFor(commands, role);
266
271
  if (!own || Object.keys(own).length === 0)
@@ -268,21 +273,32 @@ async function readingTools(workspace, role, commands) {
268
273
  return [...tools, await commandToolFor(workspace, own)];
269
274
  }
270
275
  const batching = 'When you know you need several files, or several searches, ask for all of them in one answer rather than one at a time: each answer is a step, and steps are limited.';
276
+ const exploring = 'To learn an area of the repository, send explorers: ask `explore` the independent questions you have in one call, and read yourself only what you must see exactly.';
277
+ // Each provider's cheaper model, which only finds and reads. Haiku, which names Claude Haiku 4.5,
278
+ // takes no reasoning effort.
279
+ const explorerRoles = {
280
+ anthropic: { model: 'haiku' },
281
+ openai: { model: 'gpt-5.6-luna', reasoningEffort: 'medium' },
282
+ };
283
+ const explorerSteps = 30;
284
+ const explorerInstructions = `You explore a repository for another agent, which is planning or reviewing a change and asked you one question. Find what it asks with listFiles, searchText and readFile, reading only what the question needs. Answer with what you found: the files and line numbers, what that code does, and short excerpts where the exact text matters. Say what you looked for and could not find. Do not propose changes or a plan, and do not copy whole files. ${batching}`;
271
285
  // How each role finds its way, sent after the workspace's roots, so it stays short. Only the
272
286
  // planner learns the repository; the executor and the reviewer work from its plan, so a plan
273
287
  // that leaves them guessing is the planner's to fix, not theirs to make up for.
274
288
  const repositoryGuidance = {
275
- planner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${batching}`,
289
+ planner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${exploring} ${batching}`,
276
290
  executor: `Work from the plan: read the files it names, and only what you need to change them. Do not study the repository's architecture or decisions; the plan already applied them. ${batching}`,
277
- reviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${batching}`,
291
+ reviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${exploring} ${batching}`,
278
292
  };
279
293
  /**
280
294
  * Builds the planner → executor → reviewer workflow with every role on the model APIs, each
281
295
  * holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the
282
296
  * workspace's roots.
283
297
  *
284
- * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, and
285
- * `showChanges`, the current task's changes as far as each may read them.
298
+ * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `showChanges`,
299
+ * the current task's changes as far as each may read them, and `explore`, which sends up to 4
300
+ * read-only explorers at once on the role's provider's cheaper model, each a new agent that
301
+ * starts from its question.
286
302
  * - The executor gets its provider's file tools (see `createFileTools`), and changes files only
287
303
  * in a `write` root; `autoApprove` reaches only it.
288
304
  * - Each role has its own step limit: `maxSteps`, 80 for the executor and 65 for the others by
@@ -323,11 +339,20 @@ export async function createLLMOrchestrator({ provider, autoApprove, systemPromp
323
339
  // Every command, checked once, before any role takes its share.
324
340
  if (commands !== undefined)
325
341
  validateCommands(commands);
342
+ // A new explorer for each question, on the role's provider: it starts from the question alone.
343
+ const explorerToolset = explorerTools(opened);
344
+ const explorer = (provider) => () => buildLLMAgent(provider, {
345
+ ...explorerRoles[provider],
346
+ systemPrompt: withGuidance(explorerInstructions, guidance),
347
+ tools: explorerToolset,
348
+ maxSteps: explorerSteps,
349
+ logger,
350
+ });
326
351
  const reader = async ({ provider, model, reasoningEffort }, role, systemPrompt) => buildLLMAgent(provider, {
327
352
  model,
328
353
  reasoningEffort,
329
354
  systemPrompt,
330
- tools: await readingTools(opened, role, commands),
355
+ tools: await readingTools(opened, role, commands, explorer(provider)),
331
356
  maxSteps: steps[role],
332
357
  compactAt: compaction[role],
333
358
  ...shared,
@@ -1 +1 @@
1
- {"version":3,"file":"agentLLMFactory.js","sourceRoot":"","sources":["../../../src/factory/infrastructure/agentLLMFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EAAE,QAAQ,EAAE,MAAM,oCAAoC,CAAC;AAE9D,OAAO,EACN,eAAe,EACf,eAAe,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J,CAAC","sourcesContent":["import { resolve } from 'node:path';\nimport type { Agent } from '#src/agent/domain/agent';\nimport type { HistoryReader } from '#src/engines/domain/model/historyFollower';\nimport { LLMAgent } from '#src/engines/domain/model/llmAgent';\nimport type { LLMClient } from '#src/llm/domain/llm';\nimport {\n\tClaudeLLMClient,\n\tclaudeLLMModels,\n\tclaudeLLMReasoningEfforts,\n} from '#src/llm/infrastructure/claudeLLMClient';\nimport {\n\tOpenAILLMClient,\n\topenAIModels,\n\topenAIReasoningEfforts,\n} from '#src/llm/infrastructure/openAILLMClient';\nimport {\n\texecutorInstructions,\n\texecutorInstructionsWithoutCommands,\n\tOrchestratorAgent,\n\tplannerInstructions,\n\treviewerInstructions,\n\treviewerInstructionsWithoutCommands,\n} from '#src/orchestration/domain/model/orchestratorAgent';\nimport { ReviewerDecisionValidator } from '#src/orchestration/infrastructure/model/reviewerDecisionValidator';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport { RetryingAgent } from '#src/retry/domain/model/retryingAgent';\nimport { InvalidAgentConfigError } from '#src/shared/domain/errors';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { Logger } from '#src/shared/infrastructure/logger';\nimport type { WorkspaceRoot } from '#src/tools/domain/accessPolicy';\nimport {\n\ttype CommandRole,\n\ttype Commands,\n\tcommandsFor,\n\tvalidateCommands,\n} from '#src/tools/domain/commands';\nimport type { AgentTool } from '#src/tools/domain/preparedCall';\nimport type { Tool } from '#src/tools/domain/tool';\nimport {\n\tcommandToolFor,\n\ttype FileTool,\n\tfileToolsFor,\n\ttype OpenedWorkspace,\n\topenStore,\n\topenWorkspace,\n\tstateDirectoryOf,\n\ttype WorkspaceOptions,\n} from '#src/tools/infrastructure/fileTools';\nimport { createShowChangesTool } from '#src/tools/infrastructure/showChangesTool';\nimport { createTrackedReadFile } from '#src/tools/infrastructure/trackedReadFile';\nimport { createWorkspaceTools } from '#src/tools/infrastructure/workspaceTools';\nimport { isAgentProvider, orchestratorRolesFor, type Role } from './agentFactory.ts';\nimport {\n\tagentProviders,\n\ttype AgentModel,\n\ttype AgentProvider,\n\ttype CreateOrchestratorOptions,\n\ttype ReasoningEffort,\n} from './types.ts';\n\n/** The models each provider's model API accepts. */\nexport const llmModels = {\n\tanthropic: claudeLLMModels,\n\topenai: openAIModels,\n} as const satisfies Readonly<Record<AgentProvider, readonly AgentModel[]>>;\n\n/** The reasoning efforts each provider's model API accepts. */\nexport const llmReasoningEfforts = {\n\tanthropic: claudeLLMReasoningEfforts,\n\topenai: openAIReasoningEfforts,\n} as const satisfies Readonly<Record<AgentProvider, readonly ReasoningEffort[]>>;\n\n/** Narrows a model to one accepted by the selected provider's model API. */\nexport function isLLMModelOf<Provider extends AgentProvider>(\n\tprovider: Provider,\n\tvalue: string,\n): value is (typeof llmModels)[Provider][number] {\n\treturn isOneOf(llmModels[provider], value);\n}\n\n/** Narrows a reasoning effort to one accepted by the selected provider's model API. */\nexport function isLLMReasoningEffortOf<Provider extends AgentProvider>(\n\tprovider: Provider,\n\tvalue: string,\n): value is (typeof llmReasoningEfforts)[Provider][number] {\n\treturn isOneOf(llmReasoningEfforts[provider], value);\n}\n\nexport interface CreateLLMAgentOptions {\n\t/**\n\t * Defaults to `'sonnet'` on Anthropic and `'gpt-5.6-luna'` on OpenAI. The provider's client\n\t * rejects a model it does not support.\n\t */\n\tmodel?: AgentModel;\n\t/** Defaults to `'high'`. The provider's client rejects an effort it does not support. */\n\treasoningEffort?: ReasoningEffort;\n\t/** Sent as the model's instructions on every call. */\n\tsystemPrompt: string;\n\t/** The tools the model may call: the consumer's own, and those of `createFileTools`. Defaults to none. */\n\ttools?: (Tool | FileTool)[];\n\t/**\n\t * The folders the agent works on, the same as given to `createFileTools`. With it, the agent\n\t * follows the workspace's history: after the user undoes runs, its next run starts from the\n\t * conversation as it was, and is told what was undone. The system prompt is followed by the\n\t * roots and how to name a file in them.\n\t */\n\tworkspace?: WorkspaceOptions;\n\t/**\n\t * With `workspace`, a summary of what was undone, from the provider's cheap model, in place\n\t * of the undone prompts. That is Claude Haiku without thinking, or `gpt-5.6-luna` at high\n\t * effort, and the call is billed with the run's tokens. Defaults to `true`.\n\t */\n\tsummarizeUndone?: boolean;\n\t/**\n\t * How many calls to the model one run may make before it fails. Defaults to 65, with no upper\n\t * bound. A run that asks for exactly the same tool calls 5 times in a row fails before that.\n\t */\n\tmaxSteps?: number;\n\t/**\n\t * The input tokens at which the provider compacts the conversation on its side: it replaces\n\t * every turn before that call with its own summary, which only its model reads back. The\n\t * conversation keeps every original turn. Without it, the conversation is never compacted.\n\t * At least 50,000 on Anthropic, where Claude Haiku cannot compact.\n\t */\n\tcompactAt?: number;\n\t/**\n\t * Runs every tool call without asking, `destructive` ones included, for CI where no one can\n\t * answer. Without it, a `destructive` call goes to the run's `approve`, or is denied.\n\t */\n\tautoApprove?: boolean;\n\t/** Defaults to warnings on stderr. */\n\tlogger?: ILogger;\n}\n\n/** A limit per role of `createLLMOrchestrator`; a role left out keeps its default. */\nexport type RoleSteps = Partial<Record<OrchestratorRole, number>>;\n\n/** A number of tokens per role of `createLLMOrchestrator`; a role left out keeps its default. */\nexport type RoleTokens = Partial<Record<OrchestratorRole, number>>;\n\n// The same three roles a command can be given to.\ntype OrchestratorRole = CommandRole;\n\n// The executor reads, edits and checks, so it needs more calls than the roles that only read.\nconst defaultRoleSteps: Record<OrchestratorRole, number> = {\n\tplanner: 65,\n\texecutor: 80,\n\treviewer: 65,\n};\n\n// No role compacts unless asked to.\nconst defaultRoleCompaction: Record<OrchestratorRole, number | undefined> = {\n\tplanner: undefined,\n\texecutor: undefined,\n\treviewer: undefined,\n};\n\n/**\n * Each role's value of the option `name`, from one number for all of them or a number per role.\n * Each number is checked by whatever takes it.\n *\n * @throws {InvalidAgentConfigError} for a value that is neither, and for a role that does not\n * exist, which is a typo that would otherwise leave that role on its default without a word.\n */\nfunction perRole<T extends number | undefined>(\n\tname: string,\n\tvalue: unknown,\n\tdefaults: Record<OrchestratorRole, T>,\n\t{ unit, example }: { unit: string; example: string },\n): Record<OrchestratorRole, T | number> {\n\tif (value === undefined) return defaults;\n\tif (typeof value === 'number') return { planner: value, executor: value, reviewer: value };\n\t// Untyped input, such as the CLI's configuration file, can hold `null` or a list here.\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${name} must be a number or an object of ${unit} per role, such as ${example}`,\n\t\t);\n\t}\n\tconst unknown = Object.keys(value).filter(role => !(role in defaults));\n\tif (unknown.length > 0) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${name} names roles that do not exist: ${unknown.join(', ')}; expected planner, executor or reviewer`,\n\t\t);\n\t}\n\t// A role given as `undefined`, which untyped input can do, keeps its default.\n\tconst given = Object.entries(value as Record<string, unknown>).filter(\n\t\t([, each]) => each !== undefined,\n\t);\n\treturn { ...defaults, ...Object.fromEntries(given) };\n}\n\nexport interface CreateLLMOrchestratorOptions extends CreateOrchestratorOptions {\n\t/**\n\t * The folders the agents work on. The executor changes files only in a `write` root, every\n\t * change recorded in the workspace's history. Defaults to the current working directory,\n\t * read only.\n\t */\n\tworkspace?: WorkspaceOptions;\n\t/**\n\t * How many calls to the model one run of each role may make: one number for every role, or a\n\t * number per role. Defaults to 80 for the executor and 65 for the planner and the reviewer,\n\t * with no upper bound. A run that asks for exactly the same tool calls 5 times in a row fails\n\t * before its limit.\n\t */\n\tmaxSteps?: number | RoleSteps;\n\t/**\n\t * The input tokens at which each role's provider compacts its conversation, as\n\t * `CreateLLMAgentOptions.compactAt`: one number for every role, or a number per role. Without\n\t * it, no role compacts.\n\t */\n\tcompactAt?: number | RoleTokens;\n\t/**\n\t * Commands the roles may run, such as the project's tests, through `runCommand`. Each goes to\n\t * the roles its `roles` names, the executor by default. See `createFileTools`. Each needs a\n\t * `write` root to run in.\n\t */\n\tcommands?: Commands;\n\t/**\n\t * A summary of what the user undid, from the planner's provider's cheap model, for every\n\t * role. See `CreateLLMAgentOptions.summarizeUndone`. Defaults to `true`.\n\t */\n\tsummarizeUndone?: boolean;\n}\n\nconst defaultLLMAgentModels = {\n\tanthropic: 'sonnet',\n\topenai: 'gpt-5.6-luna',\n} as const satisfies Record<AgentProvider, AgentModel>;\n\nfunction unknownProvider(provider: never): InvalidAgentConfigError {\n\treturn new InvalidAgentConfigError(\n\t\t`\"${String(provider)}\" is not an agent provider; expected one of: ${agentProviders.join(', ')}`,\n\t);\n}\n\nfunction llmClientFor(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel?: AgentModel;\n\t\treasoningEffort?: ReasoningEffort;\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t},\n): LLMClient {\n\tswitch (provider) {\n\t\tcase 'anthropic':\n\t\t\treturn new ClaudeLLMClient({\n\t\t\t\tmodel: model ?? defaultLLMAgentModels.anthropic,\n\t\t\t\treasoningEffort,\n\t\t\t\tcompactAt,\n\t\t\t\tsystemPrompt,\n\t\t\t\tlogger,\n\t\t\t});\n\t\tcase 'openai':\n\t\t\treturn new OpenAILLMClient({\n\t\t\t\tmodel: model ?? defaultLLMAgentModels.openai,\n\t\t\t\treasoningEffort,\n\t\t\t\tcompactAt,\n\t\t\t\tsystemPrompt,\n\t\t\t\tlogger,\n\t\t\t});\n\t\tdefault:\n\t\t\t// Reachable from untyped input.\n\t\t\tthrow unknownProvider(provider);\n\t}\n}\n\n/** The provider's cheap model, for the summary of what was undone. */\nfunction summarizerFor(provider: AgentProvider, logger: ILogger): LLMClient {\n\treturn provider === 'anthropic'\n\t\t? new ClaudeLLMClient({ model: 'haiku', systemPrompt: '', logger })\n\t\t: new OpenAILLMClient({\n\t\t\t\tmodel: 'gpt-5.6-luna',\n\t\t\t\treasoningEffort: 'high',\n\t\t\t\tsystemPrompt: '',\n\t\t\t\tlogger,\n\t\t\t});\n}\n\n/**\n * The workspace's history, opened on first use, so a factory that builds an agent stays\n * synchronous. Every agent and every file tool of one workspace reads the same files on disk.\n */\nfunction historyOf(workspace: WorkspaceOptions): HistoryReader {\n\t// Checked now: an agent with no root to follow is a setup error, not a first-run one.\n\tif (workspace.roots.length === 0) {\n\t\tthrow new InvalidAgentConfigError('A workspace needs at least one root');\n\t}\n\tlet store: Promise<RecoveryStore> | undefined;\n\tconst open = () => {\n\t\tstore ??= stateDirectoryOf(workspace)\n\t\t\t.then(directory => openStore(workspace, directory))\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// Not kept: the next run tries again, as one whose disk was full for a moment.\n\t\t\t\tstore = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\treturn store;\n\t};\n\treturn {\n\t\tlistRuns: async () => (await open()).listRuns(),\n\t\tlistRevisions: async () => (await open()).listRevisions(),\n\t\treadRun: async runId => (await open()).readRun(runId),\n\t};\n}\n\n/**\n * What the model is told about the workspace after its instructions: the roots, which it may\n * change, and how to name a file. A host path in an error sends the model looking for it, so\n * the real root is given here once.\n */\nfunction workspaceGuidance(roots: WorkspaceRoot[]): string {\n\tconst [first, ...others] = roots.map(root => ({ ...root, path: resolve(root.path) }));\n\tif (!first) return '';\n\tconst described = [first, ...others].map(\n\t\t({ path, access }) => `- ${path}${access === 'write' ? '' : ' (read only)'}`,\n\t);\n\treturn [\n\t\t'The workspace:',\n\t\t...described,\n\t\t`Name a file by its path relative to ${first.path}, such as src/index.ts, and a file in another folder of the workspace by its full path. Read a file before you change it.`,\n\t].join('\\n');\n}\n\nfunction withGuidance(systemPrompt: string, guidance: string): string {\n\treturn guidance === '' ? systemPrompt : `${systemPrompt}\\n\\n${guidance}`;\n}\n\n/** An `LLMAgent` on `provider`, wrapped in the harness's retry policy. */\nfunction buildLLMAgent(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt,\n\t\ttools,\n\t\thistory,\n\t\tsummarizer,\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger,\n\t}: {\n\t\tmodel?: AgentModel;\n\t\treasoningEffort?: ReasoningEffort;\n\t\tsystemPrompt: string;\n\t\ttools: AgentTool[];\n\t\thistory?: HistoryReader;\n\t\tsummarizer?: LLMClient;\n\t\tmaxSteps?: number;\n\t\tcompactAt?: number | undefined;\n\t\tautoApprove?: boolean;\n\t\tlogger: ILogger;\n\t},\n): Agent {\n\tconst llmClient = llmClientFor(provider, {\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t});\n\t// LLMAgent records nothing from a failed call, so the original prompt is the whole story.\n\treturn new RetryingAgent({\n\t\tinner: new LLMAgent({\n\t\t\tllmClient,\n\t\t\ttools,\n\t\t\tautoApprove,\n\t\t\tlogger,\n\t\t\t...(history ? { history } : {}),\n\t\t\t...(summarizer ? { summarizer } : {}),\n\t\t\t...(maxSteps === undefined ? {} : { maxSteps }),\n\t\t}),\n\t\tlogger,\n\t\tnoteFailures: false,\n\t});\n}\n\n/**\n * Builds an agent whose conversation MiKode owns, on a provider's model API, already wrapped in\n * the harness's retry policy. It needs the provider's API key and bills per token, where\n * `createAgent` uses the Agent SDK's login. Each tool judges the risk of each call; a\n * `destructive` one runs only when the run's `approve` allows it, or with `autoApprove`.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, a model or reasoning effort its\n * client does not support, or two tools that share a name.\n * @throws {UnrecoverableError} when the client cannot be set up, for example because\n * `OPENAI_API_KEY` is missing. The Anthropic SDK resolves credentials lazily, so a missing\n * `ANTHROPIC_API_KEY` fails the first run instead, with an `UnrecoverableError`.\n */\nexport function createLLMAgent(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt,\n\t\ttools = [],\n\t\tworkspace,\n\t\tsummarizeUndone = true,\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger = new Logger(),\n\t}: CreateLLMAgentOptions,\n): Agent {\n\treturn buildLLMAgent(provider, {\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt: workspace\n\t\t\t? withGuidance(systemPrompt, workspaceGuidance(workspace.roots))\n\t\t\t: systemPrompt,\n\t\t// A file tool is a harness tool under its public name.\n\t\ttools: tools as AgentTool[],\n\t\t...(workspace ? { history: historyOf(workspace) } : {}),\n\t\t...(workspace && summarizeUndone ? { summarizer: summarizerFor(provider, logger) } : {}),\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger,\n\t});\n}\n\n/**\n * The file tools for an agent from `createLLMAgent` on `provider`, over `workspace`, in the\n * provider's own format:\n *\n * - OpenAI: `listFiles`, `searchText`, `readFile` and its native `apply_patch`;\n * - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and\n * `delete_file`.\n *\n * Every one goes through the workspace's access policy: a path outside the roots, a secret,\n * a file `.gitignore` excludes or the harness protects is refused. A change is made only in a\n * `write` root, only from a version the agent read, and is recorded in the workspace's history,\n * so it can be undone. Without a `write` root the tools only read. Give the agent the same\n * `workspace`, so it follows what the history undoes.\n *\n * With `commands`, they include `runCommand`, which runs one of them by name, with only the\n * parameters it declares and never through a shell. Each run asks the approver, showing the\n * program exactly as it will run, and gets a small environment without the provider keys. The\n * files of the `write` roots are captured before it and compared after, so what it changed is\n * in the history too. It is trusted execution, not a sandbox: a command can reach whatever\n * this user can. Not supported on Windows yet.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, a workspace with no root, or an\n * invalid command, including one whose `cwd` is not in a `write` root, or any on Windows.\n * @throws {UnrecoverableError} when no program can read the first root.\n */\nexport async function createFileTools(\n\tprovider: AgentProvider,\n\tworkspace: WorkspaceOptions,\n\t{ logger = new Logger(), commands }: { logger?: ILogger; commands?: Commands } = {},\n): Promise<FileTool[]> {\n\t// Reachable from untyped input.\n\tif (!isAgentProvider(provider)) throw unknownProvider(provider);\n\tif (commands !== undefined) validateCommands(commands);\n\tconst opened = await openWorkspace(workspace, logger);\n\treturn (await executorTools(provider, opened, commands)) as unknown as FileTool[];\n}\n\n/** The executor's file tools, and `runCommand` when there are commands. */\nasync function executorTools(\n\tprovider: AgentProvider,\n\tworkspace: OpenedWorkspace,\n\tcommands: Commands | undefined,\n): Promise<AgentTool[]> {\n\tconst tools = fileToolsFor(provider, workspace);\n\t// Every command may belong to other roles, leaving none for this one.\n\tif (commands === undefined || Object.keys(commands).length === 0) return tools;\n\treturn [...tools, await commandToolFor(workspace, commands)];\n}\n\n/**\n * What the planner and the reviewer read with: no edits, the current task's changes, and the\n * commands given to their role.\n */\nasync function readingTools(\n\tworkspace: OpenedWorkspace,\n\trole: CommandRole,\n\tcommands: Commands | undefined,\n): Promise<AgentTool[]> {\n\tconst { read, policy, store } = workspace;\n\tconst finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile');\n\tconst tools = [\n\t\t...finding,\n\t\tcreateTrackedReadFile(policy),\n\t\tcreateShowChangesTool({ store, policy }),\n\t];\n\tconst own = commands && commandsFor(commands, role);\n\tif (!own || Object.keys(own).length === 0) return tools;\n\treturn [...tools, await commandToolFor(workspace, own)];\n}\n\nconst batching =\n\t'When you know you need several files, or several searches, ask for all of them in one answer rather than one at a time: each answer is a step, and steps are limited.';\n\n// How each role finds its way, sent after the workspace's roots, so it stays short. Only the\n// planner learns the repository; the executor and the reviewer work from its plan, so a plan\n// that leaves them guessing is the planner's to fix, not theirs to make up for.\nconst repositoryGuidance: Record<CommandRole, string> = {\n\tplanner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${batching}`,\n\texecutor: `Work from the plan: read the files it names, and only what you need to change them. Do not study the repository's architecture or decisions; the plan already applied them. ${batching}`,\n\treviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${batching}`,\n};\n\n/**\n * Builds the planner → executor → reviewer workflow with every role on the model APIs, each\n * holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the\n * workspace's roots.\n *\n * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, and\n * `showChanges`, the current task's changes as far as each may read them.\n * - The executor gets its provider's file tools (see `createFileTools`), and changes files only\n * in a `write` root; `autoApprove` reaches only it.\n * - Each role has its own step limit: `maxSteps`, 80 for the executor and 65 for the others by\n * default.\n * - Each role gets `runCommand` with the `commands` whose `roles` name it, the executor by\n * default. A command asks the approver in any role, and its files are captured around it.\n * - The executor is told to finish only once the tests and checks pass, and the reviewer that\n * they passed, when the executor has a command; without one, both are told the tests were\n * not run, and the reviewer judges from the code whether they would pass.\n *\n * One run of the orchestrator is one run of the workspace's history, every round and retry\n * included, and its `AgentResponse` names it. Every role follows what the user undoes.\n * Asynchronous because opening the workspace is.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, or a workspace with no root.\n * @throws {UnrecoverableError} when a role cannot be set up, for example because\n * `OPENAI_API_KEY` is missing, or when no program can read the repository.\n */\nexport async function createLLMOrchestrator({\n\tprovider,\n\tautoApprove,\n\tsystemPrompts = {},\n\tworkspace = { roots: [{ path: process.cwd(), access: 'read' }] },\n\tmaxSteps,\n\tcompactAt,\n\tcommands,\n\tsummarizeUndone = true,\n\tlogger = new Logger(),\n}: CreateLLMOrchestratorOptions = {}): Promise<Agent> {\n\tconst roles = orchestratorRolesFor(provider);\n\tconst steps = perRole('maxSteps', maxSteps, defaultRoleSteps, {\n\t\tunit: 'steps',\n\t\texample: '{ \"executor\": 120 }',\n\t});\n\tconst compaction = perRole('compactAt', compactAt, defaultRoleCompaction, {\n\t\tunit: 'tokens',\n\t\texample: '{ \"executor\": 200000 }',\n\t});\n\tconst opened = await openWorkspace(workspace, logger);\n\tconst guidance = workspaceGuidance(workspace.roots);\n\tconst summarizer = summarizeUndone ? summarizerFor(roles.planner.provider, logger) : undefined;\n\tconst shared = { history: opened.store, ...(summarizer ? { summarizer } : {}), logger };\n\t// A caller's own prompt replaces our instructions and guidance, not the workspace: the model\n\t// needs the roots to name a file, as `createLLMAgent` gives them.\n\tconst prompt = (role: CommandRole, own: string | undefined, instructions: string) =>\n\t\town === undefined\n\t\t\t? withGuidance(instructions, `${guidance}\\n${repositoryGuidance[role]}`)\n\t\t\t: withGuidance(own, guidance);\n\t// Every command, checked once, before any role takes its share.\n\tif (commands !== undefined) validateCommands(commands);\n\tconst reader = async (\n\t\t{ provider, model, reasoningEffort }: Role,\n\t\trole: CommandRole,\n\t\tsystemPrompt: string,\n\t) =>\n\t\tbuildLLMAgent(provider, {\n\t\t\tmodel,\n\t\t\treasoningEffort,\n\t\t\tsystemPrompt,\n\t\t\ttools: await readingTools(opened, role, commands),\n\t\t\tmaxSteps: steps[role],\n\t\t\tcompactAt: compaction[role],\n\t\t\t...shared,\n\t\t});\n\tconst { executor } = roles;\n\tconst executorToolset = await executorTools(\n\t\texecutor.provider,\n\t\topened,\n\t\tcommands && commandsFor(commands, 'executor'),\n\t);\n\t// The executor and the reviewer are told whether the tests were run, which only an executor\n\t// with a command can do.\n\tconst executorRuns = executorToolset.some(tool => tool.name === 'runCommand');\n\n\treturn new OrchestratorAgent({\n\t\tplannerAgent: await reader(\n\t\t\troles.planner,\n\t\t\t'planner',\n\t\t\tprompt('planner', systemPrompts.planner, plannerInstructions),\n\t\t),\n\t\texecutorAgent: buildLLMAgent(executor.provider, {\n\t\t\tmodel: executor.model,\n\t\t\treasoningEffort: executor.reasoningEffort,\n\t\t\tsystemPrompt: prompt(\n\t\t\t\t'executor',\n\t\t\t\tsystemPrompts.executor,\n\t\t\t\texecutorRuns ? executorInstructions : executorInstructionsWithoutCommands,\n\t\t\t),\n\t\t\ttools: executorToolset,\n\t\t\tmaxSteps: steps.executor,\n\t\t\tcompactAt: compaction.executor,\n\t\t\tautoApprove,\n\t\t\t...shared,\n\t\t}),\n\t\treviewerAgent: await reader(\n\t\t\troles.reviewer,\n\t\t\t'reviewer',\n\t\t\tprompt(\n\t\t\t\t'reviewer',\n\t\t\t\tsystemPrompts.reviewer,\n\t\t\t\texecutorRuns ? reviewerInstructions : reviewerInstructionsWithoutCommands,\n\t\t\t),\n\t\t),\n\t\treviewerDecisionValidator: new ReviewerDecisionValidator(),\n\t\tlogger,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agentLLMFactory.js","sourceRoot":"","sources":["../../../src/factory/infrastructure/agentLLMFactory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,OAAO,EAAE,QAAQ,EAAE,MAAM,oCAAoC,CAAC;AAE9D,OAAO,EACN,eAAe,EACf,eAAe,EACf,yBAAyB,GACzB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACN,eAAe,EACf,YAAY,EACZ,sBAAsB,GACtB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACN,oBAAoB,EACpB,mCAAmC,EACnC,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,EACpB,mCAAmC,GACnC,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,yBAAyB,EAAE,MAAM,mEAAmE,CAAC;AAE9G,OAAO,EAAE,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAErD,OAAO,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAE3D,OAAO,EAGN,WAAW,EACX,gBAAgB,GAChB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACN,cAAc,EAEd,YAAY,EAEZ,SAAS,EACT,aAAa,EACb,gBAAgB,GAEhB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAAE,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AoB,CAAC,CAAC,CAAC,mCAAmC,CACzE,CACD;QACD,yBAAyB,EAAE,IAAI,yBAAyB,EAAE;QAC1D,MAAM;KACN,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { resolve } from 'node:path';\nimport type { Agent } from '#src/agent/domain/agent';\nimport type { HistoryReader } from '#src/engines/domain/model/historyFollower';\nimport { LLMAgent } from '#src/engines/domain/model/llmAgent';\nimport type { LLMClient } from '#src/llm/domain/llm';\nimport {\n\tClaudeLLMClient,\n\tclaudeLLMModels,\n\tclaudeLLMReasoningEfforts,\n} from '#src/llm/infrastructure/claudeLLMClient';\nimport {\n\tOpenAILLMClient,\n\topenAIModels,\n\topenAIReasoningEfforts,\n} from '#src/llm/infrastructure/openAILLMClient';\nimport {\n\texecutorInstructions,\n\texecutorInstructionsWithoutCommands,\n\tOrchestratorAgent,\n\tplannerInstructions,\n\treviewerInstructions,\n\treviewerInstructionsWithoutCommands,\n} from '#src/orchestration/domain/model/orchestratorAgent';\nimport { ReviewerDecisionValidator } from '#src/orchestration/infrastructure/model/reviewerDecisionValidator';\nimport type { RecoveryStore } from '#src/recovery/domain/recoveryStore';\nimport { RetryingAgent } from '#src/retry/domain/model/retryingAgent';\nimport { InvalidAgentConfigError } from '#src/shared/domain/errors';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { Logger } from '#src/shared/infrastructure/logger';\nimport type { WorkspaceRoot } from '#src/tools/domain/accessPolicy';\nimport {\n\ttype CommandRole,\n\ttype Commands,\n\tcommandsFor,\n\tvalidateCommands,\n} from '#src/tools/domain/commands';\nimport type { AgentTool } from '#src/tools/domain/preparedCall';\nimport type { Tool } from '#src/tools/domain/tool';\nimport {\n\tcommandToolFor,\n\ttype FileTool,\n\tfileToolsFor,\n\ttype OpenedWorkspace,\n\topenStore,\n\topenWorkspace,\n\tstateDirectoryOf,\n\ttype WorkspaceOptions,\n} from '#src/tools/infrastructure/fileTools';\nimport { createExploreTool } from '#src/tools/infrastructure/exploreTool';\nimport { createShowChangesTool } from '#src/tools/infrastructure/showChangesTool';\nimport { createTrackedReadFile } from '#src/tools/infrastructure/trackedReadFile';\nimport { createWorkspaceTools } from '#src/tools/infrastructure/workspaceTools';\nimport { isAgentProvider, orchestratorRolesFor, type Role } from './agentFactory.ts';\nimport {\n\tagentProviders,\n\ttype AgentModel,\n\ttype AgentProvider,\n\ttype CreateOrchestratorOptions,\n\ttype ReasoningEffort,\n} from './types.ts';\n\n/** The models each provider's model API accepts. */\nexport const llmModels = {\n\tanthropic: claudeLLMModels,\n\topenai: openAIModels,\n} as const satisfies Readonly<Record<AgentProvider, readonly AgentModel[]>>;\n\n/** The reasoning efforts each provider's model API accepts. */\nexport const llmReasoningEfforts = {\n\tanthropic: claudeLLMReasoningEfforts,\n\topenai: openAIReasoningEfforts,\n} as const satisfies Readonly<Record<AgentProvider, readonly ReasoningEffort[]>>;\n\n/** Narrows a model to one accepted by the selected provider's model API. */\nexport function isLLMModelOf<Provider extends AgentProvider>(\n\tprovider: Provider,\n\tvalue: string,\n): value is (typeof llmModels)[Provider][number] {\n\treturn isOneOf(llmModels[provider], value);\n}\n\n/** Narrows a reasoning effort to one accepted by the selected provider's model API. */\nexport function isLLMReasoningEffortOf<Provider extends AgentProvider>(\n\tprovider: Provider,\n\tvalue: string,\n): value is (typeof llmReasoningEfforts)[Provider][number] {\n\treturn isOneOf(llmReasoningEfforts[provider], value);\n}\n\nexport interface CreateLLMAgentOptions {\n\t/**\n\t * Defaults to `'sonnet'` on Anthropic and `'gpt-5.6-luna'` on OpenAI. The provider's client\n\t * rejects a model it does not support.\n\t */\n\tmodel?: AgentModel;\n\t/** Defaults to `'high'`. The provider's client rejects an effort it does not support. */\n\treasoningEffort?: ReasoningEffort;\n\t/** Sent as the model's instructions on every call. */\n\tsystemPrompt: string;\n\t/** The tools the model may call: the consumer's own, and those of `createFileTools`. Defaults to none. */\n\ttools?: (Tool | FileTool)[];\n\t/**\n\t * The folders the agent works on, the same as given to `createFileTools`. With it, the agent\n\t * follows the workspace's history: after the user undoes runs, its next run starts from the\n\t * conversation as it was, and is told what was undone. The system prompt is followed by the\n\t * roots and how to name a file in them.\n\t */\n\tworkspace?: WorkspaceOptions;\n\t/**\n\t * With `workspace`, a summary of what was undone, from the provider's cheap model, in place\n\t * of the undone prompts. That is Claude Haiku without thinking, or `gpt-5.6-luna` at high\n\t * effort, and the call is billed with the run's tokens. Defaults to `true`.\n\t */\n\tsummarizeUndone?: boolean;\n\t/**\n\t * How many calls to the model one run may make before it fails. Defaults to 65, with no upper\n\t * bound. A run that asks for exactly the same tool calls 5 times in a row fails before that.\n\t */\n\tmaxSteps?: number;\n\t/**\n\t * The input tokens at which the provider compacts the conversation on its side: it replaces\n\t * every turn before that call with its own summary, which only its model reads back. The\n\t * conversation keeps every original turn. Without it, the conversation is never compacted.\n\t * At least 50,000 on Anthropic, where Claude Haiku cannot compact.\n\t */\n\tcompactAt?: number;\n\t/**\n\t * Runs every tool call without asking, `destructive` ones included, for CI where no one can\n\t * answer. Without it, a `destructive` call goes to the run's `approve`, or is denied.\n\t */\n\tautoApprove?: boolean;\n\t/** Defaults to warnings on stderr. */\n\tlogger?: ILogger;\n}\n\n/** A limit per role of `createLLMOrchestrator`; a role left out keeps its default. */\nexport type RoleSteps = Partial<Record<OrchestratorRole, number>>;\n\n/** A number of tokens per role of `createLLMOrchestrator`; a role left out keeps its default. */\nexport type RoleTokens = Partial<Record<OrchestratorRole, number>>;\n\n// The same three roles a command can be given to.\ntype OrchestratorRole = CommandRole;\n\n// The executor reads, edits and checks, so it needs more calls than the roles that only read.\nconst defaultRoleSteps: Record<OrchestratorRole, number> = {\n\tplanner: 65,\n\texecutor: 80,\n\treviewer: 65,\n};\n\n// No role compacts unless asked to.\nconst defaultRoleCompaction: Record<OrchestratorRole, number | undefined> = {\n\tplanner: undefined,\n\texecutor: undefined,\n\treviewer: undefined,\n};\n\n/**\n * Each role's value of the option `name`, from one number for all of them or a number per role.\n * Each number is checked by whatever takes it.\n *\n * @throws {InvalidAgentConfigError} for a value that is neither, and for a role that does not\n * exist, which is a typo that would otherwise leave that role on its default without a word.\n */\nfunction perRole<T extends number | undefined>(\n\tname: string,\n\tvalue: unknown,\n\tdefaults: Record<OrchestratorRole, T>,\n\t{ unit, example }: { unit: string; example: string },\n): Record<OrchestratorRole, T | number> {\n\tif (value === undefined) return defaults;\n\tif (typeof value === 'number') return { planner: value, executor: value, reviewer: value };\n\t// Untyped input, such as the CLI's configuration file, can hold `null` or a list here.\n\tif (typeof value !== 'object' || value === null || Array.isArray(value)) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${name} must be a number or an object of ${unit} per role, such as ${example}`,\n\t\t);\n\t}\n\tconst unknown = Object.keys(value).filter(role => !(role in defaults));\n\tif (unknown.length > 0) {\n\t\tthrow new InvalidAgentConfigError(\n\t\t\t`${name} names roles that do not exist: ${unknown.join(', ')}; expected planner, executor or reviewer`,\n\t\t);\n\t}\n\t// A role given as `undefined`, which untyped input can do, keeps its default.\n\tconst given = Object.entries(value as Record<string, unknown>).filter(\n\t\t([, each]) => each !== undefined,\n\t);\n\treturn { ...defaults, ...Object.fromEntries(given) };\n}\n\nexport interface CreateLLMOrchestratorOptions extends CreateOrchestratorOptions {\n\t/**\n\t * The folders the agents work on. The executor changes files only in a `write` root, every\n\t * change recorded in the workspace's history. Defaults to the current working directory,\n\t * read only.\n\t */\n\tworkspace?: WorkspaceOptions;\n\t/**\n\t * How many calls to the model one run of each role may make: one number for every role, or a\n\t * number per role. Defaults to 80 for the executor and 65 for the planner and the reviewer,\n\t * with no upper bound. A run that asks for exactly the same tool calls 5 times in a row fails\n\t * before its limit.\n\t */\n\tmaxSteps?: number | RoleSteps;\n\t/**\n\t * The input tokens at which each role's provider compacts its conversation, as\n\t * `CreateLLMAgentOptions.compactAt`: one number for every role, or a number per role. Without\n\t * it, no role compacts.\n\t */\n\tcompactAt?: number | RoleTokens;\n\t/**\n\t * Commands the roles may run, such as the project's tests, through `runCommand`. Each goes to\n\t * the roles its `roles` names, the executor by default. See `createFileTools`. Each needs a\n\t * `write` root to run in.\n\t */\n\tcommands?: Commands;\n\t/**\n\t * A summary of what the user undid, from the planner's provider's cheap model, for every\n\t * role. See `CreateLLMAgentOptions.summarizeUndone`. Defaults to `true`.\n\t */\n\tsummarizeUndone?: boolean;\n}\n\nconst defaultLLMAgentModels = {\n\tanthropic: 'sonnet',\n\topenai: 'gpt-5.6-luna',\n} as const satisfies Record<AgentProvider, AgentModel>;\n\nfunction unknownProvider(provider: never): InvalidAgentConfigError {\n\treturn new InvalidAgentConfigError(\n\t\t`\"${String(provider)}\" is not an agent provider; expected one of: ${agentProviders.join(', ')}`,\n\t);\n}\n\nfunction llmClientFor(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel?: AgentModel;\n\t\treasoningEffort?: ReasoningEffort;\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t},\n): LLMClient {\n\tswitch (provider) {\n\t\tcase 'anthropic':\n\t\t\treturn new ClaudeLLMClient({\n\t\t\t\tmodel: model ?? defaultLLMAgentModels.anthropic,\n\t\t\t\treasoningEffort,\n\t\t\t\tcompactAt,\n\t\t\t\tsystemPrompt,\n\t\t\t\tlogger,\n\t\t\t});\n\t\tcase 'openai':\n\t\t\treturn new OpenAILLMClient({\n\t\t\t\tmodel: model ?? defaultLLMAgentModels.openai,\n\t\t\t\treasoningEffort,\n\t\t\t\tcompactAt,\n\t\t\t\tsystemPrompt,\n\t\t\t\tlogger,\n\t\t\t});\n\t\tdefault:\n\t\t\t// Reachable from untyped input.\n\t\t\tthrow unknownProvider(provider);\n\t}\n}\n\n/** The provider's cheap model, for the summary of what was undone. */\nfunction summarizerFor(provider: AgentProvider, logger: ILogger): LLMClient {\n\treturn provider === 'anthropic'\n\t\t? new ClaudeLLMClient({ model: 'haiku', systemPrompt: '', logger })\n\t\t: new OpenAILLMClient({\n\t\t\t\tmodel: 'gpt-5.6-luna',\n\t\t\t\treasoningEffort: 'high',\n\t\t\t\tsystemPrompt: '',\n\t\t\t\tlogger,\n\t\t\t});\n}\n\n/**\n * The workspace's history, opened on first use, so a factory that builds an agent stays\n * synchronous. Every agent and every file tool of one workspace reads the same files on disk.\n */\nfunction historyOf(workspace: WorkspaceOptions): HistoryReader {\n\t// Checked now: an agent with no root to follow is a setup error, not a first-run one.\n\tif (workspace.roots.length === 0) {\n\t\tthrow new InvalidAgentConfigError('A workspace needs at least one root');\n\t}\n\tlet store: Promise<RecoveryStore> | undefined;\n\tconst open = () => {\n\t\tstore ??= stateDirectoryOf(workspace)\n\t\t\t.then(directory => openStore(workspace, directory))\n\t\t\t.catch((error: unknown) => {\n\t\t\t\t// Not kept: the next run tries again, as one whose disk was full for a moment.\n\t\t\t\tstore = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\treturn store;\n\t};\n\treturn {\n\t\tlistRuns: async () => (await open()).listRuns(),\n\t\tlistRevisions: async () => (await open()).listRevisions(),\n\t\treadRun: async runId => (await open()).readRun(runId),\n\t};\n}\n\n/**\n * What the model is told about the workspace after its instructions: the roots, which it may\n * change, and how to name a file. A host path in an error sends the model looking for it, so\n * the real root is given here once.\n */\nfunction workspaceGuidance(roots: WorkspaceRoot[]): string {\n\tconst [first, ...others] = roots.map(root => ({ ...root, path: resolve(root.path) }));\n\tif (!first) return '';\n\tconst described = [first, ...others].map(\n\t\t({ path, access }) => `- ${path}${access === 'write' ? '' : ' (read only)'}`,\n\t);\n\treturn [\n\t\t'The workspace:',\n\t\t...described,\n\t\t`Name a file by its path relative to ${first.path}, such as src/index.ts, and a file in another folder of the workspace by its full path. Read a file before you change it.`,\n\t].join('\\n');\n}\n\nfunction withGuidance(systemPrompt: string, guidance: string): string {\n\treturn guidance === '' ? systemPrompt : `${systemPrompt}\\n\\n${guidance}`;\n}\n\n/** An `LLMAgent` on `provider`, wrapped in the harness's retry policy. */\nfunction buildLLMAgent(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt,\n\t\ttools,\n\t\thistory,\n\t\tsummarizer,\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger,\n\t}: {\n\t\tmodel?: AgentModel;\n\t\treasoningEffort?: ReasoningEffort;\n\t\tsystemPrompt: string;\n\t\ttools: AgentTool[];\n\t\thistory?: HistoryReader;\n\t\tsummarizer?: LLMClient;\n\t\tmaxSteps?: number;\n\t\tcompactAt?: number | undefined;\n\t\tautoApprove?: boolean;\n\t\tlogger: ILogger;\n\t},\n): Agent {\n\tconst llmClient = llmClientFor(provider, {\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t});\n\t// LLMAgent records nothing from a failed call, so the original prompt is the whole story.\n\treturn new RetryingAgent({\n\t\tinner: new LLMAgent({\n\t\t\tllmClient,\n\t\t\ttools,\n\t\t\tautoApprove,\n\t\t\tlogger,\n\t\t\t...(history ? { history } : {}),\n\t\t\t...(summarizer ? { summarizer } : {}),\n\t\t\t...(maxSteps === undefined ? {} : { maxSteps }),\n\t\t}),\n\t\tlogger,\n\t\tnoteFailures: false,\n\t});\n}\n\n/**\n * Builds an agent whose conversation MiKode owns, on a provider's model API, already wrapped in\n * the harness's retry policy. It needs the provider's API key and bills per token, where\n * `createAgent` uses the Agent SDK's login. Each tool judges the risk of each call; a\n * `destructive` one runs only when the run's `approve` allows it, or with `autoApprove`.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, a model or reasoning effort its\n * client does not support, or two tools that share a name.\n * @throws {UnrecoverableError} when the client cannot be set up, for example because\n * `OPENAI_API_KEY` is missing. The Anthropic SDK resolves credentials lazily, so a missing\n * `ANTHROPIC_API_KEY` fails the first run instead, with an `UnrecoverableError`.\n */\nexport function createLLMAgent(\n\tprovider: AgentProvider,\n\t{\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt,\n\t\ttools = [],\n\t\tworkspace,\n\t\tsummarizeUndone = true,\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger = new Logger(),\n\t}: CreateLLMAgentOptions,\n): Agent {\n\treturn buildLLMAgent(provider, {\n\t\tmodel,\n\t\treasoningEffort,\n\t\tsystemPrompt: workspace\n\t\t\t? withGuidance(systemPrompt, workspaceGuidance(workspace.roots))\n\t\t\t: systemPrompt,\n\t\t// A file tool is a harness tool under its public name.\n\t\ttools: tools as AgentTool[],\n\t\t...(workspace ? { history: historyOf(workspace) } : {}),\n\t\t...(workspace && summarizeUndone ? { summarizer: summarizerFor(provider, logger) } : {}),\n\t\tmaxSteps,\n\t\tcompactAt,\n\t\tautoApprove,\n\t\tlogger,\n\t});\n}\n\n/**\n * The file tools for an agent from `createLLMAgent` on `provider`, over `workspace`, in the\n * provider's own format:\n *\n * - OpenAI: `listFiles`, `searchText`, `readFile` and its native `apply_patch`;\n * - Anthropic: `listFiles`, `searchText`, its native text editor, whose `view` reads, and\n * `delete_file`.\n *\n * Every one goes through the workspace's access policy: a path outside the roots, a secret,\n * a file `.gitignore` excludes or the harness protects is refused. A change is made only in a\n * `write` root, only from a version the agent read, and is recorded in the workspace's history,\n * so it can be undone. Without a `write` root the tools only read. Give the agent the same\n * `workspace`, so it follows what the history undoes.\n *\n * With `commands`, they include `runCommand`, which runs one of them by name, with only the\n * parameters it declares and never through a shell. Each run asks the approver, showing the\n * program exactly as it will run, and gets a small environment without the provider keys. The\n * files of the `write` roots are captured before it and compared after, so what it changed is\n * in the history too. It is trusted execution, not a sandbox: a command can reach whatever\n * this user can. Not supported on Windows yet.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, a workspace with no root, or an\n * invalid command, including one whose `cwd` is not in a `write` root, or any on Windows.\n * @throws {UnrecoverableError} when no program can read the first root.\n */\nexport async function createFileTools(\n\tprovider: AgentProvider,\n\tworkspace: WorkspaceOptions,\n\t{ logger = new Logger(), commands }: { logger?: ILogger; commands?: Commands } = {},\n): Promise<FileTool[]> {\n\t// Reachable from untyped input.\n\tif (!isAgentProvider(provider)) throw unknownProvider(provider);\n\tif (commands !== undefined) validateCommands(commands);\n\tconst opened = await openWorkspace(workspace, logger);\n\treturn (await executorTools(provider, opened, commands)) as unknown as FileTool[];\n}\n\n/** The executor's file tools, and `runCommand` when there are commands. */\nasync function executorTools(\n\tprovider: AgentProvider,\n\tworkspace: OpenedWorkspace,\n\tcommands: Commands | undefined,\n): Promise<AgentTool[]> {\n\tconst tools = fileToolsFor(provider, workspace);\n\t// Every command may belong to other roles, leaving none for this one.\n\tif (commands === undefined || Object.keys(commands).length === 0) return tools;\n\treturn [...tools, await commandToolFor(workspace, commands)];\n}\n\n/** What an explorer finds and reads with: no edits, no changes, no commands. */\nfunction explorerTools({ read, policy }: OpenedWorkspace): AgentTool[] {\n\tconst finding = createWorkspaceTools(read).filter(tool => tool.name !== 'readFile');\n\treturn [...finding, createTrackedReadFile(policy)];\n}\n\n/**\n * What the planner and the reviewer read with: no edits, the current task's changes, `explore`\n * with `explorer`, and the commands given to their role.\n */\nasync function readingTools(\n\tworkspace: OpenedWorkspace,\n\trole: CommandRole,\n\tcommands: Commands | undefined,\n\texplorer: () => Agent,\n): Promise<AgentTool[]> {\n\tconst { policy, store } = workspace;\n\tconst tools = [\n\t\t...explorerTools(workspace),\n\t\tcreateShowChangesTool({ store, policy }),\n\t\tcreateExploreTool(explorer),\n\t];\n\tconst own = commands && commandsFor(commands, role);\n\tif (!own || Object.keys(own).length === 0) return tools;\n\treturn [...tools, await commandToolFor(workspace, own)];\n}\n\nconst batching =\n\t'When you know you need several files, or several searches, ask for all of them in one answer rather than one at a time: each answer is a step, and steps are limited.';\n\nconst exploring =\n\t'To learn an area of the repository, send explorers: ask `explore` the independent questions you have in one call, and read yourself only what you must see exactly.';\n\n// Each provider's cheaper model, which only finds and reads. Haiku, which names Claude Haiku 4.5,\n// takes no reasoning effort.\nconst explorerRoles = {\n\tanthropic: { model: 'haiku' },\n\topenai: { model: 'gpt-5.6-luna', reasoningEffort: 'medium' },\n} as const satisfies Record<\n\tAgentProvider,\n\t{ model: AgentModel; reasoningEffort?: ReasoningEffort }\n>;\n\nconst explorerSteps = 30;\n\nconst explorerInstructions = `You explore a repository for another agent, which is planning or reviewing a change and asked you one question. Find what it asks with listFiles, searchText and readFile, reading only what the question needs. Answer with what you found: the files and line numbers, what that code does, and short excerpts where the exact text matters. Say what you looked for and could not find. Do not propose changes or a plan, and do not copy whole files. ${batching}`;\n\n// How each role finds its way, sent after the workspace's roots, so it stays short. Only the\n// planner learns the repository; the executor and the reviewer work from its plan, so a plan\n// that leaves them guessing is the planner's to fix, not theirs to make up for.\nconst repositoryGuidance: Record<CommandRole, string> = {\n\tplanner: `Start with AGENTS.md, which says where the architecture and the decisions are, and read only the parts your task needs. Name in the plan every file to change and what to change in it, so the executor needs nothing else. ${exploring} ${batching}`,\n\texecutor: `Work from the plan: read the files it names, and only what you need to change them. Do not study the repository's architecture or decisions; the plan already applied them. ${batching}`,\n\treviewer: `Work from the plan and the changes: read what they touch, and only what you need to judge them. ${exploring} ${batching}`,\n};\n\n/**\n * Builds the planner → executor → reviewer workflow with every role on the model APIs, each\n * holding its role's instructions, or `systemPrompts`, as its system prompt, followed by the\n * workspace's roots.\n *\n * - The planner and the reviewer read: `listFiles`, `searchText`, `readFile`, `showChanges`,\n * the current task's changes as far as each may read them, and `explore`, which sends up to 4\n * read-only explorers at once on the role's provider's cheaper model, each a new agent that\n * starts from its question.\n * - The executor gets its provider's file tools (see `createFileTools`), and changes files only\n * in a `write` root; `autoApprove` reaches only it.\n * - Each role has its own step limit: `maxSteps`, 80 for the executor and 65 for the others by\n * default.\n * - Each role gets `runCommand` with the `commands` whose `roles` name it, the executor by\n * default. A command asks the approver in any role, and its files are captured around it.\n * - The executor is told to finish only once the tests and checks pass, and the reviewer that\n * they passed, when the executor has a command; without one, both are told the tests were\n * not run, and the reviewer judges from the code whether they would pass.\n *\n * One run of the orchestrator is one run of the workspace's history, every round and retry\n * included, and its `AgentResponse` names it. Every role follows what the user undoes.\n * Asynchronous because opening the workspace is.\n *\n * @throws {InvalidAgentConfigError} for an unknown provider, or a workspace with no root.\n * @throws {UnrecoverableError} when a role cannot be set up, for example because\n * `OPENAI_API_KEY` is missing, or when no program can read the repository.\n */\nexport async function createLLMOrchestrator({\n\tprovider,\n\tautoApprove,\n\tsystemPrompts = {},\n\tworkspace = { roots: [{ path: process.cwd(), access: 'read' }] },\n\tmaxSteps,\n\tcompactAt,\n\tcommands,\n\tsummarizeUndone = true,\n\tlogger = new Logger(),\n}: CreateLLMOrchestratorOptions = {}): Promise<Agent> {\n\tconst roles = orchestratorRolesFor(provider);\n\tconst steps = perRole('maxSteps', maxSteps, defaultRoleSteps, {\n\t\tunit: 'steps',\n\t\texample: '{ \"executor\": 120 }',\n\t});\n\tconst compaction = perRole('compactAt', compactAt, defaultRoleCompaction, {\n\t\tunit: 'tokens',\n\t\texample: '{ \"executor\": 200000 }',\n\t});\n\tconst opened = await openWorkspace(workspace, logger);\n\tconst guidance = workspaceGuidance(workspace.roots);\n\tconst summarizer = summarizeUndone ? summarizerFor(roles.planner.provider, logger) : undefined;\n\tconst shared = { history: opened.store, ...(summarizer ? { summarizer } : {}), logger };\n\t// A caller's own prompt replaces our instructions and guidance, not the workspace: the model\n\t// needs the roots to name a file, as `createLLMAgent` gives them.\n\tconst prompt = (role: CommandRole, own: string | undefined, instructions: string) =>\n\t\town === undefined\n\t\t\t? withGuidance(instructions, `${guidance}\\n${repositoryGuidance[role]}`)\n\t\t\t: withGuidance(own, guidance);\n\t// Every command, checked once, before any role takes its share.\n\tif (commands !== undefined) validateCommands(commands);\n\t// A new explorer for each question, on the role's provider: it starts from the question alone.\n\tconst explorerToolset = explorerTools(opened);\n\tconst explorer = (provider: AgentProvider) => () =>\n\t\tbuildLLMAgent(provider, {\n\t\t\t...explorerRoles[provider],\n\t\t\tsystemPrompt: withGuidance(explorerInstructions, guidance),\n\t\t\ttools: explorerToolset,\n\t\t\tmaxSteps: explorerSteps,\n\t\t\tlogger,\n\t\t});\n\tconst reader = async (\n\t\t{ provider, model, reasoningEffort }: Role,\n\t\trole: CommandRole,\n\t\tsystemPrompt: string,\n\t) =>\n\t\tbuildLLMAgent(provider, {\n\t\t\tmodel,\n\t\t\treasoningEffort,\n\t\t\tsystemPrompt,\n\t\t\ttools: await readingTools(opened, role, commands, explorer(provider)),\n\t\t\tmaxSteps: steps[role],\n\t\t\tcompactAt: compaction[role],\n\t\t\t...shared,\n\t\t});\n\tconst { executor } = roles;\n\tconst executorToolset = await executorTools(\n\t\texecutor.provider,\n\t\topened,\n\t\tcommands && commandsFor(commands, 'executor'),\n\t);\n\t// The executor and the reviewer are told whether the tests were run, which only an executor\n\t// with a command can do.\n\tconst executorRuns = executorToolset.some(tool => tool.name === 'runCommand');\n\n\treturn new OrchestratorAgent({\n\t\tplannerAgent: await reader(\n\t\t\troles.planner,\n\t\t\t'planner',\n\t\t\tprompt('planner', systemPrompts.planner, plannerInstructions),\n\t\t),\n\t\texecutorAgent: buildLLMAgent(executor.provider, {\n\t\t\tmodel: executor.model,\n\t\t\treasoningEffort: executor.reasoningEffort,\n\t\t\tsystemPrompt: prompt(\n\t\t\t\t'executor',\n\t\t\t\tsystemPrompts.executor,\n\t\t\t\texecutorRuns ? executorInstructions : executorInstructionsWithoutCommands,\n\t\t\t),\n\t\t\ttools: executorToolset,\n\t\t\tmaxSteps: steps.executor,\n\t\t\tcompactAt: compaction.executor,\n\t\t\tautoApprove,\n\t\t\t...shared,\n\t\t}),\n\t\treviewerAgent: await reader(\n\t\t\troles.reviewer,\n\t\t\t'reviewer',\n\t\t\tprompt(\n\t\t\t\t'reviewer',\n\t\t\t\tsystemPrompts.reviewer,\n\t\t\t\texecutorRuns ? reviewerInstructions : reviewerInstructionsWithoutCommands,\n\t\t\t),\n\t\t),\n\t\treviewerDecisionValidator: new ReviewerDecisionValidator(),\n\t\tlogger,\n\t});\n}\n"]}
@@ -1,4 +1,6 @@
1
+ import type { ProgressEvent } from '#src/agent/domain/agent';
1
2
  import type { RunContext } from '#src/agent/domain/runContext';
3
+ import type { Tokens } from '#src/shared/domain/tokens';
2
4
  /**
3
5
  * What one conversation has seen of each file: the hash of the content a read showed it, or an
4
6
  * edit of its own left. An edit is made only from that version, so the model never changes a
@@ -37,10 +39,23 @@ export declare class RunReads {
37
39
  commit(): void;
38
40
  }
39
41
  /**
40
- * What a harness-built tool gets for one call: the run it belongs to, shared by every role, and
41
- * the reads of the conversation that made the call.
42
+ * What a harness-built tool gets for one call: the run it belongs to, shared by every role, the
43
+ * reads of the conversation that made the call, and the run's narration and usage, for a call
44
+ * that does its own work on the model, such as running subagents.
42
45
  */
43
46
  export interface ToolCallContext {
44
47
  readonly run: RunContext;
45
48
  readonly reads: RunReads;
49
+ /** The id of the call, which its `tool` events carry. */
50
+ readonly callId: string;
51
+ /**
52
+ * Narrates an event in the run's progress. It never throws: a failing callback ends the run
53
+ * once the call returns.
54
+ */
55
+ readonly onProgress: (event: ProgressEvent) => void;
56
+ /**
57
+ * Adds what the call spent on the model to the run's usage. `unreported` when a call it made
58
+ * came back without usage, which leaves the run's total unknown.
59
+ */
60
+ readonly spend: (tokens: Tokens | undefined, unreported: boolean) => void;
46
61
  }
@@ -1 +1 @@
1
- {"version":3,"file":"readRegistry.js","sourceRoot":"","sources":["../../../src/tools/domain/readRegistry.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IAChB,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEzC,0FAA0F;IAC1F,KAAK;QACJ,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE;YACrC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAClB,CAAC,CAAC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,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AAC;CACD","sourcesContent":["import type { RunContext } from '#src/agent/domain/runContext';\n\n/**\n * What one conversation has seen of each file: the hash of the content a read showed it, or an\n * edit of its own left. An edit is made only from that version, so the model never changes a\n * file it has not read, or one that changed since.\n *\n * Keyed by the file's real path, so two spellings of one file are one entry. It belongs to the\n * conversation, not to the run: each role, with its own conversation, has its own.\n */\nexport class ReadRegistry {\n\tprivate seen = new Map<string, string>();\n\n\t/** The reads of one run, which count for the conversation only once the run succeeded. */\n\tbegin(): RunReads {\n\t\treturn new RunReads(this.seen, seen => {\n\t\t\tthis.seen = seen;\n\t\t});\n\t}\n\n\t/**\n\t * Forgets every file: the workspace moved through its history, so what the conversation saw\n\t * may no longer be what the files hold.\n\t */\n\tclear(): void {\n\t\tthis.seen = new Map();\n\t}\n}\n\n/**\n * The versions one run has seen, on top of what its conversation saw before it. A failed run\n * records nothing in its conversation, so the model does not remember what it read there: its\n * reads are kept only by `commit`.\n */\nexport class RunReads {\n\tprivate readonly base: ReadonlyMap<string, string>;\n\tprivate readonly own = new Map<string, string | undefined>();\n\tprivate readonly save: (seen: Map<string, string>) => void;\n\n\tconstructor(base: ReadonlyMap<string, string>, save: (seen: Map<string, string>) => void) {\n\t\tthis.base = base;\n\t\tthis.save = save;\n\t}\n\n\t/** The version of `absolute` the conversation has seen, if any. */\n\tversionOf(absolute: string): string | undefined {\n\t\treturn this.own.has(absolute) ? this.own.get(absolute) : this.base.get(absolute);\n\t}\n\n\t/** The conversation now knows `absolute` as holding the content `hash` names. */\n\trecord(absolute: string, hash: string): void {\n\t\tthis.own.set(absolute, hash);\n\t}\n\n\t/** The file is gone, as the conversation knows it. */\n\tforget(absolute: string): void {\n\t\tthis.own.set(absolute, undefined);\n\t}\n\n\t/** Keeps this run's reads for the conversation's next runs. */\n\tcommit(): void {\n\t\tconst seen = new Map(this.base);\n\t\tfor (const [path, hash] of this.own) {\n\t\t\tif (hash === undefined) seen.delete(path);\n\t\t\telse seen.set(path, hash);\n\t\t}\n\t\tthis.save(seen);\n\t}\n}\n\n/**\n * What a harness-built tool gets for one call: the run it belongs to, shared by every role, and\n * the reads of the conversation that made the call.\n */\nexport interface ToolCallContext {\n\treadonly run: RunContext;\n\treadonly reads: RunReads;\n}\n"]}
1
+ {"version":3,"file":"readRegistry.js","sourceRoot":"","sources":["../../../src/tools/domain/readRegistry.ts"],"names":[],"mappings":"AAIA;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IAChB,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEzC,0FAA0F;IAC1F,KAAK;QACJ,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE;YACrC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QAClB,CAAC,CAAC,CAAC;IACJ,CAAC;IAED;;;OAGG;IACH,KAAK;QACJ,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;IACvB,CAAC;CACD;AAED;;;;GAIG;AACH,MAAM,OAAO,QAAQ;IACH,IAAI,CAA8B;IAClC,GAAG,GAAG,IAAI,GAAG,EAA8B,CAAC;IAC5C,IAAI,CAAsC;IAE3D,YAAY,IAAiC,EAAE,IAAyC;QACvF,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED,mEAAmE;IACnE,SAAS,CAAC,QAAgB;QACzB,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAClF,CAAC;IAED,iFAAiF;IACjF,MAAM,CAAC,QAAgB,EAAE,IAAY;QACpC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,sDAAsD;IACtD,MAAM,CAAC,QAAgB;QACtB,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;IACnC,CAAC;IAED,+DAA+D;IAC/D,MAAM;QACL,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAChC,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YACrC,IAAI,IAAI,KAAK,SAAS;gBAAE,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;;gBACrC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;CACD","sourcesContent":["import type { ProgressEvent } from '#src/agent/domain/agent';\nimport type { RunContext } from '#src/agent/domain/runContext';\nimport type { Tokens } from '#src/shared/domain/tokens';\n\n/**\n * What one conversation has seen of each file: the hash of the content a read showed it, or an\n * edit of its own left. An edit is made only from that version, so the model never changes a\n * file it has not read, or one that changed since.\n *\n * Keyed by the file's real path, so two spellings of one file are one entry. It belongs to the\n * conversation, not to the run: each role, with its own conversation, has its own.\n */\nexport class ReadRegistry {\n\tprivate seen = new Map<string, string>();\n\n\t/** The reads of one run, which count for the conversation only once the run succeeded. */\n\tbegin(): RunReads {\n\t\treturn new RunReads(this.seen, seen => {\n\t\t\tthis.seen = seen;\n\t\t});\n\t}\n\n\t/**\n\t * Forgets every file: the workspace moved through its history, so what the conversation saw\n\t * may no longer be what the files hold.\n\t */\n\tclear(): void {\n\t\tthis.seen = new Map();\n\t}\n}\n\n/**\n * The versions one run has seen, on top of what its conversation saw before it. A failed run\n * records nothing in its conversation, so the model does not remember what it read there: its\n * reads are kept only by `commit`.\n */\nexport class RunReads {\n\tprivate readonly base: ReadonlyMap<string, string>;\n\tprivate readonly own = new Map<string, string | undefined>();\n\tprivate readonly save: (seen: Map<string, string>) => void;\n\n\tconstructor(base: ReadonlyMap<string, string>, save: (seen: Map<string, string>) => void) {\n\t\tthis.base = base;\n\t\tthis.save = save;\n\t}\n\n\t/** The version of `absolute` the conversation has seen, if any. */\n\tversionOf(absolute: string): string | undefined {\n\t\treturn this.own.has(absolute) ? this.own.get(absolute) : this.base.get(absolute);\n\t}\n\n\t/** The conversation now knows `absolute` as holding the content `hash` names. */\n\trecord(absolute: string, hash: string): void {\n\t\tthis.own.set(absolute, hash);\n\t}\n\n\t/** The file is gone, as the conversation knows it. */\n\tforget(absolute: string): void {\n\t\tthis.own.set(absolute, undefined);\n\t}\n\n\t/** Keeps this run's reads for the conversation's next runs. */\n\tcommit(): void {\n\t\tconst seen = new Map(this.base);\n\t\tfor (const [path, hash] of this.own) {\n\t\t\tif (hash === undefined) seen.delete(path);\n\t\t\telse seen.set(path, hash);\n\t\t}\n\t\tthis.save(seen);\n\t}\n}\n\n/**\n * What a harness-built tool gets for one call: the run it belongs to, shared by every role, the\n * reads of the conversation that made the call, and the run's narration and usage, for a call\n * that does its own work on the model, such as running subagents.\n */\nexport interface ToolCallContext {\n\treadonly run: RunContext;\n\treadonly reads: RunReads;\n\t/** The id of the call, which its `tool` events carry. */\n\treadonly callId: string;\n\t/**\n\t * Narrates an event in the run's progress. It never throws: a failing callback ends the run\n\t * once the call returns.\n\t */\n\treadonly onProgress: (event: ProgressEvent) => void;\n\t/**\n\t * Adds what the call spent on the model to the run's usage. `unreported` when a call it made\n\t * came back without usage, which leaves the run's total unknown.\n\t */\n\treadonly spend: (tokens: Tokens | undefined, unreported: boolean) => void;\n}\n"]}
@@ -0,0 +1,10 @@
1
+ import type { Agent } from '#src/agent/domain/agent';
2
+ import type { PreparingTool } from '../domain/preparedCall.ts';
3
+ /** The most explorers one call sends, so a single call cannot fan out without bound. */
4
+ export declare const maxExplorers = 4;
5
+ /**
6
+ * `explore` for the planner and the reviewer: it sends cheaper, read-only explorers, created by
7
+ * `explorer`, to find what an agent needs in the repository, so the agent that called it reads
8
+ * their reports instead of filling its own context with the files.
9
+ */
10
+ export declare function createExploreTool(explorer: () => Agent): PreparingTool;
@@ -0,0 +1,88 @@
1
+ import { z } from 'zod';
2
+ import { withRunContext } from '#src/agent/domain/runContext';
3
+ import { RecoverableError, UnrecoverableError } from '#src/shared/domain/errors';
4
+ import { definePreparingTool } from "./defineTool.js";
5
+ /** The most explorers one call sends, so a single call cannot fan out without bound. */
6
+ export const maxExplorers = 4;
7
+ // An answer is read whole, like a read, which returns at most 16 KB.
8
+ const maxAnswerCharacters = 16_000;
9
+ function cut(answer) {
10
+ if (answer.length <= maxAnswerCharacters)
11
+ return answer;
12
+ return `${answer.slice(0, maxAnswerCharacters)}\n[The answer was cut at ${String(maxAnswerCharacters)} characters.]`;
13
+ }
14
+ function failureOf(error) {
15
+ return typeof error.cause === 'string' ? `${error.message}: ${error.cause}` : error.message;
16
+ }
17
+ /**
18
+ * Runs one explorer per question, all at once, each a new agent that starts from its question
19
+ * alone. Every explorer's usage counts in the run's, whether it answered or failed; a failure
20
+ * becomes that explorer's answer, so the others' are not lost. A cancellation escapes.
21
+ */
22
+ async function explore(questions, explorer, signal, call) {
23
+ const answers = await Promise.allSettled(questions.map(async (question, index) => {
24
+ const subagent = index + 1;
25
+ const heading = `Explorer ${String(subagent)}: ${question}`;
26
+ const onProgress = (event) => {
27
+ call.onProgress({
28
+ type: 'subagent',
29
+ callId: call.callId,
30
+ subagent,
31
+ task: question,
32
+ event,
33
+ });
34
+ };
35
+ // Within the run that made the call, so the explorers' reads belong to it.
36
+ const options = withRunContext({ signal, onProgress }, call.run);
37
+ try {
38
+ const { response, tokens } = await explorer().run(question, options);
39
+ call.spend(tokens, tokens === undefined);
40
+ return `${heading}\n${cut(response || 'It found nothing to report.')}`;
41
+ }
42
+ catch (error) {
43
+ if (!(error instanceof RecoverableError || error instanceof UnrecoverableError)) {
44
+ throw error;
45
+ }
46
+ call.spend(error.tokens, error.usageUnreported);
47
+ return `${heading}\nThe explorer failed: ${failureOf(error)}`;
48
+ }
49
+ }));
50
+ // Whatever each explorer threw once the run was cancelled, the call ends as cancelled.
51
+ signal.throwIfAborted();
52
+ return answers
53
+ .map(answer => {
54
+ if (answer.status === 'rejected')
55
+ throw answer.reason;
56
+ return answer.value;
57
+ })
58
+ .join('\n\n');
59
+ }
60
+ /**
61
+ * `explore` for the planner and the reviewer: it sends cheaper, read-only explorers, created by
62
+ * `explorer`, to find what an agent needs in the repository, so the agent that called it reads
63
+ * their reports instead of filling its own context with the files.
64
+ */
65
+ export function createExploreTool(explorer) {
66
+ return definePreparingTool({
67
+ name: 'explore',
68
+ description: `Sends read-only explorers to find things in the repository for you, one for each question, all at once. Each explorer starts from nothing but its question, so make each one complete: what to find, and what to report about it, such as which files and lines implement something and how. Ask up to ${String(maxExplorers)} independent questions in one call. Each answer is an explorer's report, not the files: read a file yourself when you need its exact text.`,
69
+ input: z.object({
70
+ questions: z.array(z.string()).describe('One complete, independent question per explorer.'),
71
+ }),
72
+ summarize: ({ questions }) => questions.length === 1 ? (questions[0] ?? '') : `${String(questions.length)} questions`,
73
+ prepare: ({ questions }, _, call) => {
74
+ const asked = questions.map(question => question.trim());
75
+ if (asked.length === 0 || asked.length > maxExplorers) {
76
+ return Promise.reject(new Error(`Ask between 1 and ${String(maxExplorers)} questions in one call.`));
77
+ }
78
+ if (asked.some(question => question === '')) {
79
+ return Promise.reject(new Error('Every question needs some text.'));
80
+ }
81
+ return Promise.resolve({
82
+ risk: 'safe',
83
+ run: signal => explore(asked, explorer, signal, call),
84
+ });
85
+ },
86
+ });
87
+ }
88
+ //# sourceMappingURL=exploreTool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exploreTool.js","sourceRoot":"","sources":["../../../src/tools/infrastructure/exploreTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;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agent, ProgressEvent } from '#src/agent/domain/agent';\nimport { withRunContext } from '#src/agent/domain/runContext';\nimport { RecoverableError, UnrecoverableError } from '#src/shared/domain/errors';\nimport type { PreparingTool } from '../domain/preparedCall.ts';\nimport type { ToolCallContext } from '../domain/readRegistry.ts';\nimport { definePreparingTool } from './defineTool.ts';\n\n/** The most explorers one call sends, so a single call cannot fan out without bound. */\nexport const maxExplorers = 4;\n\n// An answer is read whole, like a read, which returns at most 16 KB.\nconst maxAnswerCharacters = 16_000;\n\nfunction cut(answer: string): string {\n\tif (answer.length <= maxAnswerCharacters) return answer;\n\treturn `${answer.slice(0, maxAnswerCharacters)}\\n[The answer was cut at ${String(maxAnswerCharacters)} characters.]`;\n}\n\nfunction failureOf(error: RecoverableError | UnrecoverableError): string {\n\treturn typeof error.cause === 'string' ? `${error.message}: ${error.cause}` : error.message;\n}\n\n/**\n * Runs one explorer per question, all at once, each a new agent that starts from its question\n * alone. Every explorer's usage counts in the run's, whether it answered or failed; a failure\n * becomes that explorer's answer, so the others' are not lost. A cancellation escapes.\n */\nasync function explore(\n\tquestions: readonly string[],\n\texplorer: () => Agent,\n\tsignal: AbortSignal,\n\tcall: ToolCallContext,\n): Promise<string> {\n\tconst answers = await Promise.allSettled(\n\t\tquestions.map(async (question, index) => {\n\t\t\tconst subagent = index + 1;\n\t\t\tconst heading = `Explorer ${String(subagent)}: ${question}`;\n\t\t\tconst onProgress = (event: ProgressEvent) => {\n\t\t\t\tcall.onProgress({\n\t\t\t\t\ttype: 'subagent',\n\t\t\t\t\tcallId: call.callId,\n\t\t\t\t\tsubagent,\n\t\t\t\t\ttask: question,\n\t\t\t\t\tevent,\n\t\t\t\t});\n\t\t\t};\n\t\t\t// Within the run that made the call, so the explorers' reads belong to it.\n\t\t\tconst options = withRunContext({ signal, onProgress }, call.run);\n\t\t\ttry {\n\t\t\t\tconst { response, tokens } = await explorer().run(question, options);\n\t\t\t\tcall.spend(tokens, tokens === undefined);\n\t\t\t\treturn `${heading}\\n${cut(response || 'It found nothing to report.')}`;\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof RecoverableError || error instanceof UnrecoverableError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tcall.spend(error.tokens, error.usageUnreported);\n\t\t\t\treturn `${heading}\\nThe explorer failed: ${failureOf(error)}`;\n\t\t\t}\n\t\t}),\n\t);\n\t// Whatever each explorer threw once the run was cancelled, the call ends as cancelled.\n\tsignal.throwIfAborted();\n\treturn answers\n\t\t.map(answer => {\n\t\t\tif (answer.status === 'rejected') throw answer.reason;\n\t\t\treturn answer.value;\n\t\t})\n\t\t.join('\\n\\n');\n}\n\n/**\n * `explore` for the planner and the reviewer: it sends cheaper, read-only explorers, created by\n * `explorer`, to find what an agent needs in the repository, so the agent that called it reads\n * their reports instead of filling its own context with the files.\n */\nexport function createExploreTool(explorer: () => Agent): PreparingTool {\n\treturn definePreparingTool({\n\t\tname: 'explore',\n\t\tdescription: `Sends read-only explorers to find things in the repository for you, one for each question, all at once. Each explorer starts from nothing but its question, so make each one complete: what to find, and what to report about it, such as which files and lines implement something and how. Ask up to ${String(maxExplorers)} independent questions in one call. Each answer is an explorer's report, not the files: read a file yourself when you need its exact text.`,\n\t\tinput: z.object({\n\t\t\tquestions: z.array(z.string()).describe('One complete, independent question per explorer.'),\n\t\t}),\n\t\tsummarize: ({ questions }) =>\n\t\t\tquestions.length === 1 ? (questions[0] ?? '') : `${String(questions.length)} questions`,\n\t\tprepare: ({ questions }, _, call) => {\n\t\t\tconst asked = questions.map(question => question.trim());\n\t\t\tif (asked.length === 0 || asked.length > maxExplorers) {\n\t\t\t\treturn Promise.reject(\n\t\t\t\t\tnew Error(`Ask between 1 and ${String(maxExplorers)} questions in one call.`),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (asked.some(question => question === '')) {\n\t\t\t\treturn Promise.reject(new Error('Every question needs some text.'));\n\t\t\t}\n\t\t\treturn Promise.resolve({\n\t\t\t\trisk: 'safe',\n\t\t\t\trun: signal => explore(asked, explorer, signal, call),\n\t\t\t});\n\t\t},\n\t});\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikode13/harness",
3
- "version": "6.0.1",
3
+ "version": "6.1.0",
4
4
  "description": "Test/agent harness utility",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",