@mikode13/harness 3.0.0 → 4.0.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.
Files changed (59) hide show
  1. package/README.md +109 -9
  2. package/dist/agent/domain/agent.d.ts +23 -3
  3. package/dist/agent/domain/agent.js +2 -1
  4. package/dist/agent/domain/agent.js.map +1 -1
  5. package/dist/agent/domain/approval.d.ts +44 -0
  6. package/dist/agent/domain/approval.js +23 -0
  7. package/dist/agent/domain/approval.js.map +1 -0
  8. package/dist/engines/claude/infrastructure/model/claudeAgent.d.ts +2 -2
  9. package/dist/engines/claude/infrastructure/model/claudeAgent.js +4 -3
  10. package/dist/engines/claude/infrastructure/model/claudeAgent.js.map +1 -1
  11. package/dist/engines/codex/infrastructure/model/codexAgent.d.ts +2 -2
  12. package/dist/engines/codex/infrastructure/model/codexAgent.js +4 -4
  13. package/dist/engines/codex/infrastructure/model/codexAgent.js.map +1 -1
  14. package/dist/engines/domain/model/llmAgent.d.ts +15 -5
  15. package/dist/engines/domain/model/llmAgent.js +109 -26
  16. package/dist/engines/domain/model/llmAgent.js.map +1 -1
  17. package/dist/factory/infrastructure/agentFactory.js +1 -1
  18. package/dist/factory/infrastructure/agentFactory.js.map +1 -1
  19. package/dist/factory/infrastructure/agentLLMFactory.d.ts +14 -7
  20. package/dist/factory/infrastructure/agentLLMFactory.js +11 -9
  21. package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
  22. package/dist/index.d.ts +10 -2
  23. package/dist/index.js +6 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/llm/domain/errors.d.ts +1 -1
  26. package/dist/llm/domain/errors.js +1 -1
  27. package/dist/llm/domain/errors.js.map +1 -1
  28. package/dist/llm/infrastructure/claudeLLMClient.js +2 -2
  29. package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
  30. package/dist/llm/infrastructure/openAILLMClient.js +2 -2
  31. package/dist/llm/infrastructure/openAILLMClient.js.map +1 -1
  32. package/dist/orchestration/domain/model/instructedAgent.d.ts +2 -2
  33. package/dist/orchestration/domain/model/instructedAgent.js +2 -2
  34. package/dist/orchestration/domain/model/instructedAgent.js.map +1 -1
  35. package/dist/orchestration/domain/model/orchestratorAgent.d.ts +2 -2
  36. package/dist/orchestration/domain/model/orchestratorAgent.js +10 -10
  37. package/dist/orchestration/domain/model/orchestratorAgent.js.map +1 -1
  38. package/dist/retry/domain/model/retryingAgent.d.ts +2 -2
  39. package/dist/retry/domain/model/retryingAgent.js +4 -4
  40. package/dist/retry/domain/model/retryingAgent.js.map +1 -1
  41. package/dist/shared/domain/errors.js.map +1 -0
  42. package/dist/shared/domain/providerFailure.js.map +1 -0
  43. package/dist/tools/domain/tool.d.ts +6 -0
  44. package/dist/tools/domain/tool.js.map +1 -1
  45. package/dist/tools/infrastructure/createWorkspace.d.ts +2 -1
  46. package/dist/tools/infrastructure/createWorkspace.js +4 -3
  47. package/dist/tools/infrastructure/createWorkspace.js.map +1 -1
  48. package/dist/tools/infrastructure/defineTool.d.ts +7 -1
  49. package/dist/tools/infrastructure/defineTool.js +12 -2
  50. package/dist/tools/infrastructure/defineTool.js.map +1 -1
  51. package/dist/tools/infrastructure/workspaceTools.js +3 -0
  52. package/dist/tools/infrastructure/workspaceTools.js.map +1 -1
  53. package/package.json +7 -4
  54. package/dist/agent/domain/errors.js.map +0 -1
  55. package/dist/agent/domain/providerFailure.js.map +0 -1
  56. /package/dist/{agent → shared}/domain/errors.d.ts +0 -0
  57. /package/dist/{agent → shared}/domain/errors.js +0 -0
  58. /package/dist/{agent → shared}/domain/providerFailure.d.ts +0 -0
  59. /package/dist/{agent → shared}/domain/providerFailure.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/llm/domain/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAE9D,kGAAkG;AAClG,MAAM,OAAO,eAAgB,SAAQ,kBAAkB;CAAG","sourcesContent":["import { UnrecoverableError } from '#src/agent/domain/errors';\n\n/** The context no longer fits the model's window; the agent must compact before sending again. */\nexport class MaxContextError extends UnrecoverableError {}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../src/llm/domain/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAE/D,kGAAkG;AAClG,MAAM,OAAO,eAAgB,SAAQ,kBAAkB;CAAG","sourcesContent":["import { UnrecoverableError } from '#src/shared/domain/errors';\n\n/** The context no longer fits the model's window; the agent must compact before sending again. */\nexport class MaxContextError extends UnrecoverableError {}\n"]}
@@ -1,6 +1,6 @@
1
1
  import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';
2
- import { InvalidAgentConfigError, UnrecoverableError, withSpentTokens, } from '#src/agent/domain/errors';
3
- import { classifyHostFailure, classifyLocalFailure, classifyProviderFailure, describeFailure, treatErrors, } from '#src/agent/domain/providerFailure';
2
+ import { InvalidAgentConfigError, UnrecoverableError, withSpentTokens, } from '#src/shared/domain/errors';
3
+ import { classifyHostFailure, classifyLocalFailure, classifyProviderFailure, describeFailure, treatErrors, } from '#src/shared/domain/providerFailure';
4
4
  import { isOneOf } from '#src/shared/domain/isOneOf';
5
5
  import { MaxContextError } from "../domain/errors.js";
6
6
  // The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both
@@ -1 +1 @@
1
- {"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAYxE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,GACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,WAAW,GACX,MAAM,mCAAm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AM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,qBAAqB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type {\n\tContentBlock,\n\tContentBlockParam,\n\tMessage as AnthropicMessage,\n\tMessageParam,\n\tOutputConfig,\n\tRedactedThinkingBlockParam,\n\tThinkingBlockParam,\n\tTool as ClaudeTool,\n\tUsage,\n} from '@anthropic-ai/sdk/resources/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/agent/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/agent/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport type { Message, MessagePart } from '../domain/message.ts';\nimport type { ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku is left out: it has no adaptive thinking.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too. Above roughly 21,000 the SDK refuses a request\n// that is not streamed, because it could outlast its ten-minute timeout.\nconst maxOutputTokens = 16_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400.\n */\nfunction toClaudeTool({ name, description, inputSchema }: ToolDefinition): ClaudeTool {\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/** Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: AnthropicMessage, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap(block => describeBlock(block, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. An `AnthropicError` that is not an `APIError` never\n * carries an answer from the API: on this client's path it is the SDK refusing to make the\n * call, such as an unresolved profile or a request too large to send without streaming.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\nfunction classifyClaudeFailure(error: unknown): Error {\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort;\n\tprivate readonly systemPrompt: string;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(claudeLLMReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\n\t\ttry {\n\t\t\tresponse = await this.client.messages.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\tsystem: this.systemPrompt,\n\t\t\t\t\tmessages: context.flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyClaudeFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAYxE,OAAO,EACN,uBAAuB,EACvB,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,OAAO,EAAE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,qBAAqB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type {\n\tContentBlock,\n\tContentBlockParam,\n\tMessage as AnthropicMessage,\n\tMessageParam,\n\tOutputConfig,\n\tRedactedThinkingBlockParam,\n\tThinkingBlockParam,\n\tTool as ClaudeTool,\n\tUsage,\n} from '@anthropic-ai/sdk/resources/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport type { Message, MessagePart } from '../domain/message.ts';\nimport type { ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku is left out: it has no adaptive thinking.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too. Above roughly 21,000 the SDK refuses a request\n// that is not streamed, because it could outlast its ten-minute timeout.\nconst maxOutputTokens = 16_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400.\n */\nfunction toClaudeTool({ name, description, inputSchema }: ToolDefinition): ClaudeTool {\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/** Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: AnthropicMessage, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap(block => describeBlock(block, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. An `AnthropicError` that is not an `APIError` never\n * carries an answer from the API: on this client's path it is the SDK refusing to make the\n * call, such as an unresolved profile or a request too large to send without streaming.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\nfunction classifyClaudeFailure(error: unknown): Error {\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort;\n\tprivate readonly systemPrompt: string;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(claudeLLMReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\n\t\ttry {\n\t\t\tresponse = await this.client.messages.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\tsystem: this.systemPrompt,\n\t\t\t\t\tmessages: context.flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyClaudeFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import OpenAI, { APIError } from 'openai';
2
- import { InvalidAgentConfigError, RecoverableError, UnrecoverableError, withSpentTokens, } from '#src/agent/domain/errors';
3
- import { classifyHostFailure, classifyLocalFailure, classifyProviderFailure, describeFailure, treatErrors, } from '#src/agent/domain/providerFailure';
2
+ import { InvalidAgentConfigError, RecoverableError, UnrecoverableError, withSpentTokens, } from '#src/shared/domain/errors';
3
+ import { classifyHostFailure, classifyLocalFailure, classifyProviderFailure, describeFailure, treatErrors, } from '#src/shared/domain/providerFailure';
4
4
  import { isOneOf } from '#src/shared/domain/isOneOf';
5
5
  import { MaxContextError } from "../domain/errors.js";
6
6
  // The SDK types `model` as a plain string, so this list is maintained by hand.
@@ -1 +1 @@
1
- {"version":3,"file":"openAILLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/openAILLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAU1C,OAAO,EACN,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,eAAe,EACf,WAAW,GACX,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,YAAY,GAAG;IAC3B,aAAa;IACb,aAAa;IACb,cAAc;IACd,eAAe;CACN,CAAC;AAGX,0FAA0F;AAC1F,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACrC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CACsD,CAAC;AAG7D,kFAAkF;AAClF,MAAM,qBAAqB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAExD,gGAAgG;AAChG,mDAAmD;AACnD,MAAM,mBAAmB,GAAG;IAC3B,oBAAoB;IACpB,0BAA0B;IAC1B,8BAA8B;CAC9B,CAAC;AAEF,gFAAgF;AAChF,MAAM,2BAA2B,GAAG,CAAC,cAAc,EAAE,qBAAqB,CAAC,CAAC;AAE5E,0FAA0F;AAC1F,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B,yFAAyF;AACzF,MAAM,gBAAgB,GAAG,wBAAwB,CAAC;AAElD;;;;GAIG;AACH,SAAS,aAAa,CAAC,IAAiB,EAAE,IAA0B;IACnE,QAAQ,IAAI,CAAC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gBAC1E,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC3D,KAAK,EAAE,KAAK;gBACZ,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE;gBAC5D,uEAAuE;gBACvE,OAAO,EAAE,CAAC,6BAA6B,CAAC;aACxC,EACD,EAAE,MAAM,EAAE,CACV,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,mFAAmF;YACnF,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,qBAAqB,CAAC,KAAK,CAAC,CAAC;QACpC,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tFunctionTool,\n\tResponse,\n\tResponseInputItem,\n\tResponseOutputItem,\n\tResponseReasoningItem,\n\tResponseUsage,\n} from 'openai/resources/responses/responses';\nimport {\n\tInvalidAgentConfigError,\n\tRecoverableError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/agent/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/agent/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport type { Message, MessagePart } from '../domain/message.ts';\nimport type { ToolDefinition } from '../domain/tool.ts';\n\n// The SDK types `model` as a plain string, so this list is maintained by hand.\nexport const openAIModels = [\n\t'gpt-6-astra',\n\t'gpt-5.6-sol',\n\t'gpt-5.6-luna',\n\t'gpt-5.6-terra',\n] as const;\nexport type OpenAIModel = (typeof openAIModels)[number];\n\n// The efforts both the Responses API and Codex's model catalog list for the models above.\nexport const openAIReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<ReasoningEffort>[];\nexport type OpenAIReasoningEffort = (typeof openAIReasoningEfforts)[number];\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 422];\n\n// Out of credit or over a spend limit. These arrive as a 429 like a rate limit, but the account\n// stays blocked however often the request is sent.\nconst exhaustedQuotaCodes = [\n\t'insufficient_quota',\n\t'credit_balance_exhausted',\n\t'project_spend_limit_exceeded',\n];\n\n// The codes OpenAI gives a failed response that a new attempt can succeed past.\nconst transientResponseErrorCodes = ['server_error', 'rate_limit_exceeded'];\n\n// This client's label on the reasoning items it keeps for replay; see `ProviderDataPart`.\nconst openAISource = 'openai';\n\n// Marks a failed call's output, which would otherwise read the same as a successful one.\nconst failedToolPrefix = 'The tool call failed: ';\n\n/**\n * OpenAI takes a flat list of items, so every part becomes its own, in order. Reasoning crosses\n * back only as the encrypted item this client kept, which OpenAI requires beside the tool calls\n * that followed it; a reasoning part is its summary, kept for narration.\n */\nfunction toOpenAIItems(part: MessagePart, role: 'user' | 'assistant'): ResponseInputItem[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn part.text ? [{ role, content: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call',\n\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\t// A string is arguments that did not parse, sent back as the model wrote them.\n\t\t\t\t\targuments: typeof part.input === 'string' ? part.input : JSON.stringify(part.input),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call_output',\n\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t// OpenAI has no error flag, so the text says it; the conversation keeps the output as it was.\n\t\t\t\t\toutput: part.isError ? `${failedToolPrefix}${part.output}` : part.output,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's item would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseReasoningItem] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message): ResponseInputItem[] {\n\t// A tool message holds only results, which carry no role.\n\tconst role = message.role === 'assistant' ? 'assistant' : 'user';\n\treturn message.content.flatMap(part => toOpenAIItems(part, role));\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its arguments always parse and match.\n * A schema outside what strict mode supports fails the request with a 400.\n */\nfunction toOpenAITool({ name, description, inputSchema }: ToolDefinition): FunctionTool {\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/**\n * Strict mode makes arguments that do not parse rare: a response cut short mid-call ends as\n * `truncated` before any tool runs. Should one arrive, the tool gets the raw string and its\n * rejection lets the model correct itself, instead of the run failing.\n */\nfunction parseArguments(serialized: string): unknown {\n\ttry {\n\t\treturn JSON.parse(serialized);\n\t} catch {\n\t\treturn serialized;\n\t}\n}\n\nfunction describeItem(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\tswitch (item.type) {\n\t\tcase 'message':\n\t\t\t// A refusal is not an answer: it only sets the stop reason.\n\t\t\treturn item.content.flatMap(content =>\n\t\t\t\tcontent.type === 'output_text' ? [{ type: 'text' as const, text: content.text }] : [],\n\t\t\t);\n\t\tcase 'reasoning': {\n\t\t\t// The summary is the readable part; the encrypted item is what OpenAI reads back.\n\t\t\tconst text = item.summary.map(summary => summary.text).join('\\n');\n\t\t\tconst parts: MessagePart[] = text ? [{ type: 'reasoning', text }] : [];\n\t\t\t// Without its encrypted content the item cannot be replayed: OpenAI stores nothing.\n\t\t\tif (item.encrypted_content) {\n\t\t\t\tconst encrypted: ResponseReasoningItem = {\n\t\t\t\t\ttype: 'reasoning',\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tsummary: item.summary,\n\t\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t\t};\n\t\t\t\tparts.push({ type: 'providerData', source: openAISource, data: encrypted });\n\t\t\t}\n\t\t\treturn parts;\n\t\t}\n\t\tcase 'function_call':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\tid: item.call_id,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\tinput: parseArguments(item.arguments),\n\t\t\t\t},\n\t\t\t];\n\t\tdefault:\n\t\t\t// No built-in tools are offered, so any other item is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'OpenAI client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: Response): StopReason {\n\tif (response.status === 'incomplete') {\n\t\treturn response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';\n\t}\n\tif (response.status !== 'completed') {\n\t\tconst cause =\n\t\t\tresponse.error?.message ??\n\t\t\t`The response ended with status \"${response.status ?? 'unknown'}\".`;\n\t\t// The same failure is retried when it arrives as an SDK error, so it must be here too.\n\t\tif (response.error && transientResponseErrorCodes.includes(response.error.code)) {\n\t\t\tthrow new RecoverableError('The OpenAI response failed', { cause });\n\t\t}\n\t\tthrow new UnrecoverableError('The OpenAI response did not complete', { cause });\n\t}\n\n\tconst refused = response.output.some(\n\t\titem => item.type === 'message' && item.content.some(content => content.type === 'refusal'),\n\t);\n\treturn refused ? 'refused' : 'completed';\n}\n\n/** OpenAI counts both cache reads and cache writes inside `input_tokens`. */\nfunction toTokens(usage: ResponseUsage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('OpenAI returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'OpenAI client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst { cached_tokens, cache_write_tokens } = usage.input_tokens_details;\n\treturn {\n\t\tinputTokens: usage.input_tokens - cached_tokens - cache_write_tokens,\n\t\treadCacheTokens: cached_tokens,\n\t\twrittenCacheTokens: cache_write_tokens,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: Response, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\nfunction classifyOpenAIFailure(error: unknown): Error {\n\tif (error instanceof APIError) {\n\t\tif (error.code === 'context_length_exceeded') {\n\t\t\treturn new MaxContextError('The context no longer fits the OpenAI model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\texhaustedQuotaCodes.some(code => code === error.code) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('OpenAI rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn classifyProviderFailure(error, 'The OpenAI request failed');\n}\n\n/**\n * A stateless `LLMClient` on the OpenAI Responses API. With `store: false` OpenAI keeps\n * nothing between calls, so every call carries the whole context: the conversation is\n * MiKode's, not the provider's.\n */\nexport class OpenAILLMClient implements LLMClient {\n\tprivate readonly client: OpenAI;\n\tprivate readonly model: OpenAIModel;\n\tprivate readonly reasoningEffort: OpenAIReasoningEffort;\n\tprivate readonly systemPrompt: string;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what OpenAI supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(openAIModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on: they back off and honour `Retry-After`, which\n\t\t\t// `RetryingAgent` does not. See \"The provider SDKs keep their transport retries\" in decisions.md.\n\t\t\tthis.client = new OpenAI();\n\t\t} catch (error) {\n\t\t\t// A missing API key, for example: building the client again cannot fix it.\n\t\t\tthrow new UnrecoverableError('The OpenAI client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = model;\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.client.responses.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tinstructions: this.systemPrompt,\n\t\t\t\t\tinput: context.flatMap(toOpenAIInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'auto' },\n\t\t\t\t\t// With `store: false` this is the only way to send the reasoning back.\n\t\t\t\t\tinclude: ['reasoning.encrypted_content'],\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyOpenAIFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'OpenAI response mapping failed',\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"openAILLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/openAILLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAU1C,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,OAAO,EAAE,MAAM,4BAA4B,CAAC;AAGrD,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAKtD,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G,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tFunctionTool,\n\tResponse,\n\tResponseInputItem,\n\tResponseOutputItem,\n\tResponseReasoningItem,\n\tResponseUsage,\n} from 'openai/resources/responses/responses';\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 { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport type { Message, MessagePart } from '../domain/message.ts';\nimport type { ToolDefinition } from '../domain/tool.ts';\n\n// The SDK types `model` as a plain string, so this list is maintained by hand.\nexport const openAIModels = [\n\t'gpt-6-astra',\n\t'gpt-5.6-sol',\n\t'gpt-5.6-luna',\n\t'gpt-5.6-terra',\n] as const;\nexport type OpenAIModel = (typeof openAIModels)[number];\n\n// The efforts both the Responses API and Codex's model catalog list for the models above.\nexport const openAIReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<ReasoningEffort>[];\nexport type OpenAIReasoningEffort = (typeof openAIReasoningEfforts)[number];\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 422];\n\n// Out of credit or over a spend limit. These arrive as a 429 like a rate limit, but the account\n// stays blocked however often the request is sent.\nconst exhaustedQuotaCodes = [\n\t'insufficient_quota',\n\t'credit_balance_exhausted',\n\t'project_spend_limit_exceeded',\n];\n\n// The codes OpenAI gives a failed response that a new attempt can succeed past.\nconst transientResponseErrorCodes = ['server_error', 'rate_limit_exceeded'];\n\n// This client's label on the reasoning items it keeps for replay; see `ProviderDataPart`.\nconst openAISource = 'openai';\n\n// Marks a failed call's output, which would otherwise read the same as a successful one.\nconst failedToolPrefix = 'The tool call failed: ';\n\n/**\n * OpenAI takes a flat list of items, so every part becomes its own, in order. Reasoning crosses\n * back only as the encrypted item this client kept, which OpenAI requires beside the tool calls\n * that followed it; a reasoning part is its summary, kept for narration.\n */\nfunction toOpenAIItems(part: MessagePart, role: 'user' | 'assistant'): ResponseInputItem[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\treturn part.text ? [{ role, content: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call',\n\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\tname: part.name,\n\t\t\t\t\t// A string is arguments that did not parse, sent back as the model wrote them.\n\t\t\t\t\targuments: typeof part.input === 'string' ? part.input : JSON.stringify(part.input),\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'function_call_output',\n\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t// OpenAI has no error flag, so the text says it; the conversation keeps the output as it was.\n\t\t\t\t\toutput: part.isError ? `${failedToolPrefix}${part.output}` : part.output,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's item would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseReasoningItem] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message): ResponseInputItem[] {\n\t// A tool message holds only results, which carry no role.\n\tconst role = message.role === 'assistant' ? 'assistant' : 'user';\n\treturn message.content.flatMap(part => toOpenAIItems(part, role));\n}\n\n/**\n * Strict: the API constrains the model to the schema, so its arguments always parse and match.\n * A schema outside what strict mode supports fails the request with a 400.\n */\nfunction toOpenAITool({ name, description, inputSchema }: ToolDefinition): FunctionTool {\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/**\n * Strict mode makes arguments that do not parse rare: a response cut short mid-call ends as\n * `truncated` before any tool runs. Should one arrive, the tool gets the raw string and its\n * rejection lets the model correct itself, instead of the run failing.\n */\nfunction parseArguments(serialized: string): unknown {\n\ttry {\n\t\treturn JSON.parse(serialized);\n\t} catch {\n\t\treturn serialized;\n\t}\n}\n\nfunction describeItem(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\tswitch (item.type) {\n\t\tcase 'message':\n\t\t\t// A refusal is not an answer: it only sets the stop reason.\n\t\t\treturn item.content.flatMap(content =>\n\t\t\t\tcontent.type === 'output_text' ? [{ type: 'text' as const, text: content.text }] : [],\n\t\t\t);\n\t\tcase 'reasoning': {\n\t\t\t// The summary is the readable part; the encrypted item is what OpenAI reads back.\n\t\t\tconst text = item.summary.map(summary => summary.text).join('\\n');\n\t\t\tconst parts: MessagePart[] = text ? [{ type: 'reasoning', text }] : [];\n\t\t\t// Without its encrypted content the item cannot be replayed: OpenAI stores nothing.\n\t\t\tif (item.encrypted_content) {\n\t\t\t\tconst encrypted: ResponseReasoningItem = {\n\t\t\t\t\ttype: 'reasoning',\n\t\t\t\t\tid: item.id,\n\t\t\t\t\tsummary: item.summary,\n\t\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t\t};\n\t\t\t\tparts.push({ type: 'providerData', source: openAISource, data: encrypted });\n\t\t\t}\n\t\t\treturn parts;\n\t\t}\n\t\tcase 'function_call':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'toolCall',\n\t\t\t\t\tid: item.call_id,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\tinput: parseArguments(item.arguments),\n\t\t\t\t},\n\t\t\t];\n\t\tdefault:\n\t\t\t// No built-in tools are offered, so any other item is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'OpenAI client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: Response): StopReason {\n\tif (response.status === 'incomplete') {\n\t\treturn response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';\n\t}\n\tif (response.status !== 'completed') {\n\t\tconst cause =\n\t\t\tresponse.error?.message ??\n\t\t\t`The response ended with status \"${response.status ?? 'unknown'}\".`;\n\t\t// The same failure is retried when it arrives as an SDK error, so it must be here too.\n\t\tif (response.error && transientResponseErrorCodes.includes(response.error.code)) {\n\t\t\tthrow new RecoverableError('The OpenAI response failed', { cause });\n\t\t}\n\t\tthrow new UnrecoverableError('The OpenAI response did not complete', { cause });\n\t}\n\n\tconst refused = response.output.some(\n\t\titem => item.type === 'message' && item.content.some(content => content.type === 'refusal'),\n\t);\n\treturn refused ? 'refused' : 'completed';\n}\n\n/** OpenAI counts both cache reads and cache writes inside `input_tokens`. */\nfunction toTokens(usage: ResponseUsage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('OpenAI returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'OpenAI client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tconst { cached_tokens, cache_write_tokens } = usage.input_tokens_details;\n\treturn {\n\t\tinputTokens: usage.input_tokens - cached_tokens - cache_write_tokens,\n\t\treadCacheTokens: cached_tokens,\n\t\twrittenCacheTokens: cache_write_tokens,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: Response, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\nfunction classifyOpenAIFailure(error: unknown): Error {\n\tif (error instanceof APIError) {\n\t\tif (error.code === 'context_length_exceeded') {\n\t\t\treturn new MaxContextError('The context no longer fits the OpenAI model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\texhaustedQuotaCodes.some(code => code === error.code) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('OpenAI rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\treturn classifyProviderFailure(error, 'The OpenAI request failed');\n}\n\n/**\n * A stateless `LLMClient` on the OpenAI Responses API. With `store: false` OpenAI keeps\n * nothing between calls, so every call carries the whole context: the conversation is\n * MiKode's, not the provider's.\n */\nexport class OpenAILLMClient implements LLMClient {\n\tprivate readonly client: OpenAI;\n\tprivate readonly model: OpenAIModel;\n\tprivate readonly reasoningEffort: OpenAIReasoningEffort;\n\tprivate readonly systemPrompt: string;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what OpenAI supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort = 'high',\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(openAIModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${reasoningEffort}\" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on: they back off and honour `Retry-After`, which\n\t\t\t// `RetryingAgent` does not. See \"The provider SDKs keep their transport retries\" in decisions.md.\n\t\t\tthis.client = new OpenAI();\n\t\t} catch (error) {\n\t\t\t// A missing API key, for example: building the client again cannot fix it.\n\t\t\tthrow new UnrecoverableError('The OpenAI client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = model;\n\t\tthis.reasoningEffort = reasoningEffort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: Response;\n\n\t\ttry {\n\t\t\tresponse = await this.client.responses.create(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tinstructions: this.systemPrompt,\n\t\t\t\t\tinput: context.flatMap(toOpenAIInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'auto' },\n\t\t\t\t\t// With `store: false` this is the only way to send the reasoning back.\n\t\t\t\t\tinclude: ['reasoning.encrypted_content'],\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tthrow classifyOpenAIFailure(error);\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'OpenAI response mapping failed',\n\t\t);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';
1
+ import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';
2
2
  /**
3
3
  * Gives an agent without a system prompt its role's instructions at the head of every prompt.
4
4
  * An agent with one, such as `LLMAgent`, holds them there instead, so they are not resent
@@ -11,5 +11,5 @@ export declare class InstructedAgent implements Agent {
11
11
  inner: Agent;
12
12
  instructions: string;
13
13
  });
14
- run(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse>;
14
+ run(prompt: string, options: RunOptions): Promise<AgentResponse>;
15
15
  }
@@ -10,8 +10,8 @@ export class InstructedAgent {
10
10
  this.inner = inner;
11
11
  this.instructions = instructions;
12
12
  }
13
- run(prompt, signal, callback) {
14
- return this.inner.run(`${this.instructions}\n\n${prompt}`, signal, callback);
13
+ run(prompt, options) {
14
+ return this.inner.run(`${this.instructions}\n\n${prompt}`, options);
15
15
  }
16
16
  }
17
17
  //# sourceMappingURL=instructedAgent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"instructedAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/instructedAgent.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,OAAO,eAAe;IACV,KAAK,CAAQ;IACb,YAAY,CAAS;IAEtC,YAAY,EAAE,KAAK,EAAE,YAAY,EAA0C;QAC1E,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IAClC,CAAC;IAED,GAAG,CAAC,MAAc,EAAE,MAAmB,EAAE,QAAkB;QAC1D,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,YAAY,OAAO,MAAM,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC9E,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';\n\n/**\n * Gives an agent without a system prompt its role's instructions at the head of every prompt.\n * An agent with one, such as `LLMAgent`, holds them there instead, so they are not resent\n * inside each prompt.\n */\nexport class InstructedAgent implements Agent {\n\tprivate readonly inner: Agent;\n\tprivate readonly instructions: string;\n\n\tconstructor({ inner, instructions }: { inner: Agent; instructions: string }) {\n\t\tthis.inner = inner;\n\t\tthis.instructions = instructions;\n\t}\n\n\trun(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse> {\n\t\treturn this.inner.run(`${this.instructions}\\n\\n${prompt}`, signal, callback);\n\t}\n}\n"]}
1
+ {"version":3,"file":"instructedAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/instructedAgent.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,OAAO,eAAe;IACV,KAAK,CAAQ;IACb,YAAY,CAAS;IAEtC,YAAY,EAAE,KAAK,EAAE,YAAY,EAA0C;QAC1E,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IAClC,CAAC;IAED,GAAG,CAAC,MAAc,EAAE,OAAmB;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,YAAY,OAAO,MAAM,EAAE,EAAE,OAAO,CAAC,CAAC;IACrE,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';\n\n/**\n * Gives an agent without a system prompt its role's instructions at the head of every prompt.\n * An agent with one, such as `LLMAgent`, holds them there instead, so they are not resent\n * inside each prompt.\n */\nexport class InstructedAgent implements Agent {\n\tprivate readonly inner: Agent;\n\tprivate readonly instructions: string;\n\n\tconstructor({ inner, instructions }: { inner: Agent; instructions: string }) {\n\t\tthis.inner = inner;\n\t\tthis.instructions = instructions;\n\t}\n\n\trun(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\treturn this.inner.run(`${this.instructions}\\n\\n${prompt}`, options);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';
1
+ import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';
2
2
  import type { ReviewerDecision } from './reviewerDecision.ts';
3
3
  import type { Validator } from '../interface/validator.ts';
4
4
  import type { ILogger } from '#src/shared/domain/logger';
@@ -20,7 +20,7 @@ export declare class OrchestratorAgent implements Agent {
20
20
  maxAttempts?: number;
21
21
  logger: ILogger;
22
22
  });
23
- run(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse>;
23
+ run(prompt: string, options: RunOptions): Promise<AgentResponse>;
24
24
  private runRounds;
25
25
  private getReviewerDecision;
26
26
  private warn;
@@ -1,6 +1,6 @@
1
1
  import { addTokens } from '#src/shared/domain/tokens';
2
- import { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/agent/domain/errors';
3
- import { classifyHostFailure, treatErrors } from '#src/agent/domain/providerFailure';
2
+ import { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';
3
+ import { classifyHostFailure, treatErrors } from '#src/shared/domain/providerFailure';
4
4
  // Each role's standing instructions, kept apart from the data of a round so an agent with a
5
5
  // system prompt can hold them there instead of receiving them again in every prompt. An agent
6
6
  // without one gets them at the head of each prompt; see `InstructedAgent`.
@@ -99,12 +99,12 @@ export class OrchestratorAgent {
99
99
  this.maxAttempts = maxAttempts;
100
100
  this.logger = logger;
101
101
  }
102
- async run(prompt, signal, callback) {
102
+ async run(prompt, options) {
103
103
  const start = Date.now();
104
104
  // Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.
105
105
  const totals = { tokens: undefined, unreported: false };
106
106
  try {
107
- await this.runRounds(prompt, signal, callback, totals);
107
+ await this.runRounds(prompt, options, totals);
108
108
  }
109
109
  catch (error) {
110
110
  // A failing role carries its own tokens; the roles before it are in the totals.
@@ -117,11 +117,11 @@ export class OrchestratorAgent {
117
117
  duration: (Date.now() - start) / 1000,
118
118
  };
119
119
  }
120
- async runRounds(prompt, signal, callback, totals) {
120
+ async runRounds(prompt, options, totals) {
121
121
  let lastFailureReason;
122
122
  for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
123
123
  const isLastAttempt = attempt === this.maxAttempts;
124
- const plannerResponse = await this.plannerAgent.run(getPlannerPrompt(prompt, lastFailureReason), signal, callback);
124
+ const plannerResponse = await this.plannerAgent.run(getPlannerPrompt(prompt, lastFailureReason), options);
125
125
  addToTotals(totals, plannerResponse);
126
126
  if (!plannerResponse.response) {
127
127
  lastFailureReason = 'The planner produced no response.';
@@ -131,7 +131,7 @@ export class OrchestratorAgent {
131
131
  this.warn(`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the planner produced no response; starting another round`);
132
132
  continue;
133
133
  }
134
- const executorResponse = await this.executorAgent.run(getExecutorPrompt(prompt, plannerResponse.response), signal, callback);
134
+ const executorResponse = await this.executorAgent.run(getExecutorPrompt(prompt, plannerResponse.response), options);
135
135
  addToTotals(totals, executorResponse);
136
136
  if (!executorResponse.response) {
137
137
  lastFailureReason = 'The executor produced no response.';
@@ -141,7 +141,7 @@ export class OrchestratorAgent {
141
141
  this.warn(`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the executor produced no response; starting another round`);
142
142
  continue;
143
143
  }
144
- const reviewerDecision = await this.getReviewerDecision(prompt, plannerResponse.response, executorResponse.response, signal, callback, totals);
144
+ const reviewerDecision = await this.getReviewerDecision(prompt, plannerResponse.response, executorResponse.response, options, totals);
145
145
  if (reviewerDecision.decision === 'approved')
146
146
  return;
147
147
  lastFailureReason = reviewerDecision.feedback;
@@ -157,10 +157,10 @@ export class OrchestratorAgent {
157
157
  // Retries only the reviewer call on a malformed decision, instead of redoing
158
158
  // planning/execution — a bad or unparsable reviewer response is not evidence
159
159
  // the plan or the implementation were wrong.
160
- async getReviewerDecision(userPrompt, plannerPrompt, executorResult, signal, callback, totals) {
160
+ async getReviewerDecision(userPrompt, plannerPrompt, executorResult, options, totals) {
161
161
  let parseFailureReason;
162
162
  for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
163
- const reviewerResponse = await this.reviewerAgent.run(getReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason), signal, callback);
163
+ const reviewerResponse = await this.reviewerAgent.run(getReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason), options);
164
164
  addToTotals(totals, reviewerResponse);
165
165
  try {
166
166
  return parseReviewerDecision(reviewerResponse, this.reviewerDecisionValidator);
@@ -1 +1 @@
1
- {"version":3,"file":"orchestratorAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/orchestratorAgent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAIjG,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAErF,4FAA4F;AAC5F,8FAA8F;AAC9F,2EAA2E;AAC3E,MAAM,CAAC,MAAM,mBAAmB,GAC/B,qXAAqX,CAAC;AAEvX,MAAM,CAAC,MAAM,oBAAoB,GAChC,yVAAyV,CAAC;AAE3V,MAAM,CAAC,MAAM,oBAAoB,GAChC,yvBAAyvB,CAAC;AAE3vB,MAAM,gBAAgB,GAAG,CAAC,UAAkB,EAAE,qBAA8B,EAAE,EAAE;IAC/E,MAAM,QAAQ,GAAG,qBAAqB;QACrC,CAAC,CAAC,iDAAiD,qBAAqB,OAAO;QAC/E,CAAC,CAAC,EAAE,CAAC;IAEN,OAAO;;EAEN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AO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,0CAA0C,EAC1G,kBAAkB,CAClB,CAAC;YACH,CAAC;QACF,CAAC;QAED,MAAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE;YACtD,KAAK,EAAE,kBAAkB,IAAI,kBAAkB;SAC/C,CAAC,CAAC;IACJ,CAAC;IAEO,IAAI,CAAC,GAAG,IAAe;QAC9B,WAAW,CACV,GAAG,EAAE;YACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,CAAC,EACD,mBAAmB,EACnB,oDAAoD,CACpD,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/agent/domain/errors';\nimport type { ReviewerDecision } from './reviewerDecision.ts';\nimport type { Validator } from '../interface/validator.ts';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { classifyHostFailure, treatErrors } from '#src/agent/domain/providerFailure';\n\n// Each role's standing instructions, kept apart from the data of a round so an agent with a\n// system prompt can hold them there instead of receiving them again in every prompt. An agent\n// without one gets them at the head of each prompt; see `InstructedAgent`.\nexport const plannerInstructions =\n\t'You are the planner agent. Read the relevant repository code and create a concise, engineering-grade plan for the executor. Cover the requested behaviour, structural issues, affected files or symbols, API contracts and boundaries, important failure paths, and meaningful tests. Keep the plan focused on the current request and do not require an architecture redesign yet.';\n\nexport const executorInstructions =\n\t\"You are the executor agent. Read the relevant repository code and implement the original user request according to the planner's current plan. Preserve contracts and boundaries, handle important failure paths, keep the change focused, and add or update meaningful tests. Inspect and change the code; do not merely describe what should be done.\";\n\nexport const reviewerInstructions =\n\t'You are the reviewer agent. Independently inspect the repository, the current diff, and relevant surrounding code; do not rely on the executor\\'s narrative. Evaluate the original request first; plan compliance is secondary and provides supporting context. Check correctness and logic errors, important failure paths, unused or artificial abstractions, races or shared state, API contract breaks, boundary violations, regressions, scope, and test quality. If it is correct, respond with JSON only: {\"decision\":\"approved\"}. If it is not correct, respond with JSON only: {\"decision\":\"rejected\",\"feedback\":\"list concrete, prioritized findings and the required direction for each\"}. The feedback must contain actionable engineering findings, not a general summary.';\n\nconst getPlannerPrompt = (userPrompt: string, previousFailureReason?: string) => {\n\tconst feedback = previousFailureReason\n\t\t? `\\n\\nFeedback from the previous attempt:\\n---\\n${previousFailureReason}\\n---`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---${feedback}`;\n};\n\nconst getExecutorPrompt = (userPrompt: string, plannerPrompt: string) =>\n\t`Original user request:\n---\n${userPrompt}\n---\n\nCurrent implementation plan:\n---\n${plannerPrompt}\n---`;\n\nconst getReviewerPrompt = (\n\tuserPrompt: string,\n\tplannerPrompt: string,\n\texecutorResult: string,\n\tparseFailureReason?: string,\n) => {\n\tconst retryNotice = parseFailureReason\n\t\t? `\\n\\nYour previous response could not be used: ${parseFailureReason} Respond with JSON only, matching the schema exactly, with no surrounding text and no markdown code fences.`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---\n\nPlanner's current plan:\n---\n${plannerPrompt}\n---\n\nExecutor response (context only; verify it independently):\n---\n${executorResult}\n---${retryNotice}`;\n};\n\ninterface RunTotals {\n\ttokens: Tokens | undefined;\n\t/** A role answered without usage, so the run's total cannot be known. */\n\tunreported: boolean;\n}\n\n// Every role's response counts, even an empty one that starts another round: it was billed.\nfunction addToTotals(totals: RunTotals, response: AgentResponse): void {\n\tif (!response.tokens) totals.unreported = true;\n\ttotals.tokens = addTokens(totals.tokens, response.tokens);\n}\n\n/** Unknown rather than partial: a sum missing a billed call must not look complete. */\nfunction runTokens(totals: RunTotals): Tokens | undefined {\n\treturn totals.unreported ? undefined : totals.tokens;\n}\n\nfunction stripCodeFence(text: string): string {\n\tconst match = /^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/.exec(text.trim());\n\treturn match?.[1] ?? text;\n}\n\nfunction parseReviewerDecision(\n\tresponse: AgentResponse,\n\treviewerDecisionValidator: Validator<ReviewerDecision>,\n): ReviewerDecision {\n\tif (!response.response) {\n\t\tthrow new RecoverableError(\"There's no decision from the reviewer, something went wrong\", {\n\t\t\tcause: 'Reviewer decision is missing.',\n\t\t});\n\t}\n\n\tlet parsedResponse: unknown;\n\ttry {\n\t\tparsedResponse = JSON.parse(stripCodeFence(response.response));\n\t} catch {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response must be valid JSON.',\n\t\t});\n\t}\n\n\tconst decision = reviewerDecisionValidator.validate(parsedResponse);\n\tif (!decision) {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response did not match the decision schema.',\n\t\t});\n\t}\n\n\treturn decision;\n}\n\nexport class OrchestratorAgent implements Agent {\n\tprivate plannerAgent: Agent;\n\tprivate executorAgent: Agent;\n\tprivate reviewerAgent: Agent;\n\tprivate reviewerDecisionValidator: Validator<ReviewerDecision>;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\n\tconstructor({\n\t\tplannerAgent,\n\t\texecutorAgent,\n\t\treviewerAgent,\n\t\treviewerDecisionValidator,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t}: {\n\t\tplannerAgent: Agent;\n\t\texecutorAgent: Agent;\n\t\treviewerAgent: Agent;\n\t\treviewerDecisionValidator: Validator<ReviewerDecision>;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.plannerAgent = plannerAgent;\n\t\tthis.executorAgent = executorAgent;\n\t\tthis.reviewerAgent = reviewerAgent;\n\t\tthis.reviewerDecisionValidator = reviewerDecisionValidator;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t}\n\n\tasync run(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\t// Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.\n\t\tconst totals: RunTotals = { tokens: undefined, unreported: false };\n\n\t\ttry {\n\t\t\tawait this.runRounds(prompt, signal, callback, totals);\n\t\t} catch (error) {\n\t\t\t// A failing role carries its own tokens; the roles before it are in the totals.\n\t\t\tthrow withSpentTokens(error, totals.tokens, totals.unreported);\n\t\t}\n\n\t\treturn {\n\t\t\tresponse: 'All job has finished',\n\t\t\ttokens: runTokens(totals),\n\t\t\t// The whole run's wall clock, so it matches what the consumer waited.\n\t\t\tduration: (Date.now() - start) / 1000,\n\t\t};\n\t}\n\n\tprivate async runRounds(\n\t\tprompt: string,\n\t\tsignal: AbortSignal,\n\t\tcallback: Callback,\n\t\ttotals: RunTotals,\n\t): Promise<void> {\n\t\tlet lastFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst isLastAttempt = attempt === this.maxAttempts;\n\n\t\t\tconst plannerResponse = await this.plannerAgent.run(\n\t\t\t\tgetPlannerPrompt(prompt, lastFailureReason),\n\t\t\t\tsignal,\n\t\t\t\tcallback,\n\t\t\t);\n\t\t\taddToTotals(totals, plannerResponse);\n\n\t\t\tif (!plannerResponse.response) {\n\t\t\t\tlastFailureReason = 'The planner produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the planner produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst executorResponse = await this.executorAgent.run(\n\t\t\t\tgetExecutorPrompt(prompt, plannerResponse.response),\n\t\t\t\tsignal,\n\t\t\t\tcallback,\n\t\t\t);\n\t\t\taddToTotals(totals, executorResponse);\n\n\t\t\tif (!executorResponse.response) {\n\t\t\t\tlastFailureReason = 'The executor produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the executor produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reviewerDecision = await this.getReviewerDecision(\n\t\t\t\tprompt,\n\t\t\t\tplannerResponse.response,\n\t\t\t\texecutorResponse.response,\n\t\t\t\tsignal,\n\t\t\t\tcallback,\n\t\t\t\ttotals,\n\t\t\t);\n\n\t\t\tif (reviewerDecision.decision === 'approved') return;\n\n\t\t\tlastFailureReason = reviewerDecision.feedback;\n\t\t\tif (isLastAttempt) {\n\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t}\n\n\t\t\tthis.warn(\n\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the reviewer rejected the round; starting another with its feedback`,\n\t\t\t\tlastFailureReason,\n\t\t\t);\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: lastFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\t// Retries only the reviewer call on a malformed decision, instead of redoing\n\t// planning/execution — a bad or unparsable reviewer response is not evidence\n\t// the plan or the implementation were wrong.\n\tprivate async getReviewerDecision(\n\t\tuserPrompt: string,\n\t\tplannerPrompt: string,\n\t\texecutorResult: string,\n\t\tsignal: AbortSignal,\n\t\tcallback: Callback,\n\t\ttotals: RunTotals,\n\t): Promise<ReviewerDecision> {\n\t\tlet parseFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst reviewerResponse = await this.reviewerAgent.run(\n\t\t\t\tgetReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason),\n\t\t\t\tsignal,\n\t\t\t\tcallback,\n\t\t\t);\n\n\t\t\taddToTotals(totals, reviewerResponse);\n\n\t\t\ttry {\n\t\t\t\treturn parseReviewerDecision(reviewerResponse, this.reviewerDecisionValidator);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof RecoverableError)) throw error;\n\n\t\t\t\tparseFailureReason = error.cause;\n\t\t\t\tif (attempt === this.maxAttempts) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: parseFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Reviewer decision ${String(attempt)}/${String(this.maxAttempts)} was unusable; asking the reviewer again`,\n\t\t\t\t\tparseFailureReason,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: parseFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\tprivate warn(...args: unknown[]): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger.warn(...args);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Orchestrator logger failed while reporting a retry',\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"orchestratorAgent.js","sourceRoot":"","sources":["../../../../src/orchestration/domain/model/orchestratorAgent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAIlG,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAC;AAEtF,4FAA4F;AAC5F,8FAA8F;AAC9F,2EAA2E;AAC3E,MAAM,CAAC,MAAM,mBAAmB,GAC/B,qXAAqX,CAAC;AAEvX,MAAM,CAAC,MAAM,oBAAoB,GAChC,yVAAyV,CAAC;AAE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AAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE,EAAE,KAAK,EAAE,kBAAkB,EAAE,CAAC,CAAC;gBACvF,CAAC;gBAED,IAAI,CAAC,IAAI,CACR,qBAAqB,MAAM,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,0CAA0C,EAC1G,kBAAkB,CAClB,CAAC;YACH,CAAC;QACF,CAAC;QAED,MAAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE;YACtD,KAAK,EAAE,kBAAkB,IAAI,kBAAkB;SAC/C,CAAC,CAAC;IACJ,CAAC;IAEO,IAAI,CAAC,GAAG,IAAe;QAC9B,WAAW,CACV,GAAG,EAAE;YACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QAC3B,CAAC,EACD,mBAAmB,EACnB,oDAAoD,CACpD,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';\nimport type { ReviewerDecision } from './reviewerDecision.ts';\nimport type { Validator } from '../interface/validator.ts';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { classifyHostFailure, treatErrors } from '#src/shared/domain/providerFailure';\n\n// Each role's standing instructions, kept apart from the data of a round so an agent with a\n// system prompt can hold them there instead of receiving them again in every prompt. An agent\n// without one gets them at the head of each prompt; see `InstructedAgent`.\nexport const plannerInstructions =\n\t'You are the planner agent. Read the relevant repository code and create a concise, engineering-grade plan for the executor. Cover the requested behaviour, structural issues, affected files or symbols, API contracts and boundaries, important failure paths, and meaningful tests. Keep the plan focused on the current request and do not require an architecture redesign yet.';\n\nexport const executorInstructions =\n\t\"You are the executor agent. Read the relevant repository code and implement the original user request according to the planner's current plan. Preserve contracts and boundaries, handle important failure paths, keep the change focused, and add or update meaningful tests. Inspect and change the code; do not merely describe what should be done.\";\n\nexport const reviewerInstructions =\n\t'You are the reviewer agent. Independently inspect the repository, the current diff, and relevant surrounding code; do not rely on the executor\\'s narrative. Evaluate the original request first; plan compliance is secondary and provides supporting context. Check correctness and logic errors, important failure paths, unused or artificial abstractions, races or shared state, API contract breaks, boundary violations, regressions, scope, and test quality. If it is correct, respond with JSON only: {\"decision\":\"approved\"}. If it is not correct, respond with JSON only: {\"decision\":\"rejected\",\"feedback\":\"list concrete, prioritized findings and the required direction for each\"}. The feedback must contain actionable engineering findings, not a general summary.';\n\nconst getPlannerPrompt = (userPrompt: string, previousFailureReason?: string) => {\n\tconst feedback = previousFailureReason\n\t\t? `\\n\\nFeedback from the previous attempt:\\n---\\n${previousFailureReason}\\n---`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---${feedback}`;\n};\n\nconst getExecutorPrompt = (userPrompt: string, plannerPrompt: string) =>\n\t`Original user request:\n---\n${userPrompt}\n---\n\nCurrent implementation plan:\n---\n${plannerPrompt}\n---`;\n\nconst getReviewerPrompt = (\n\tuserPrompt: string,\n\tplannerPrompt: string,\n\texecutorResult: string,\n\tparseFailureReason?: string,\n) => {\n\tconst retryNotice = parseFailureReason\n\t\t? `\\n\\nYour previous response could not be used: ${parseFailureReason} Respond with JSON only, matching the schema exactly, with no surrounding text and no markdown code fences.`\n\t\t: '';\n\n\treturn `Original user request:\n---\n${userPrompt}\n---\n\nPlanner's current plan:\n---\n${plannerPrompt}\n---\n\nExecutor response (context only; verify it independently):\n---\n${executorResult}\n---${retryNotice}`;\n};\n\ninterface RunTotals {\n\ttokens: Tokens | undefined;\n\t/** A role answered without usage, so the run's total cannot be known. */\n\tunreported: boolean;\n}\n\n// Every role's response counts, even an empty one that starts another round: it was billed.\nfunction addToTotals(totals: RunTotals, response: AgentResponse): void {\n\tif (!response.tokens) totals.unreported = true;\n\ttotals.tokens = addTokens(totals.tokens, response.tokens);\n}\n\n/** Unknown rather than partial: a sum missing a billed call must not look complete. */\nfunction runTokens(totals: RunTotals): Tokens | undefined {\n\treturn totals.unreported ? undefined : totals.tokens;\n}\n\nfunction stripCodeFence(text: string): string {\n\tconst match = /^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/.exec(text.trim());\n\treturn match?.[1] ?? text;\n}\n\nfunction parseReviewerDecision(\n\tresponse: AgentResponse,\n\treviewerDecisionValidator: Validator<ReviewerDecision>,\n): ReviewerDecision {\n\tif (!response.response) {\n\t\tthrow new RecoverableError(\"There's no decision from the reviewer, something went wrong\", {\n\t\t\tcause: 'Reviewer decision is missing.',\n\t\t});\n\t}\n\n\tlet parsedResponse: unknown;\n\ttry {\n\t\tparsedResponse = JSON.parse(stripCodeFence(response.response));\n\t} catch {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response must be valid JSON.',\n\t\t});\n\t}\n\n\tconst decision = reviewerDecisionValidator.validate(parsedResponse);\n\tif (!decision) {\n\t\tthrow new RecoverableError('Reviewer returned an invalid decision', {\n\t\t\tcause: 'Reviewer response did not match the decision schema.',\n\t\t});\n\t}\n\n\treturn decision;\n}\n\nexport class OrchestratorAgent implements Agent {\n\tprivate plannerAgent: Agent;\n\tprivate executorAgent: Agent;\n\tprivate reviewerAgent: Agent;\n\tprivate reviewerDecisionValidator: Validator<ReviewerDecision>;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\n\tconstructor({\n\t\tplannerAgent,\n\t\texecutorAgent,\n\t\treviewerAgent,\n\t\treviewerDecisionValidator,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t}: {\n\t\tplannerAgent: Agent;\n\t\texecutorAgent: Agent;\n\t\treviewerAgent: Agent;\n\t\treviewerDecisionValidator: Validator<ReviewerDecision>;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.plannerAgent = plannerAgent;\n\t\tthis.executorAgent = executorAgent;\n\t\tthis.reviewerAgent = reviewerAgent;\n\t\tthis.reviewerDecisionValidator = reviewerDecisionValidator;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t}\n\n\tasync run(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\t// Per invocation, not per instance: the CLI keeps one orchestrator for a whole session.\n\t\tconst totals: RunTotals = { tokens: undefined, unreported: false };\n\n\t\ttry {\n\t\t\tawait this.runRounds(prompt, options, totals);\n\t\t} catch (error) {\n\t\t\t// A failing role carries its own tokens; the roles before it are in the totals.\n\t\t\tthrow withSpentTokens(error, totals.tokens, totals.unreported);\n\t\t}\n\n\t\treturn {\n\t\t\tresponse: 'All job has finished',\n\t\t\ttokens: runTokens(totals),\n\t\t\t// The whole run's wall clock, so it matches what the consumer waited.\n\t\t\tduration: (Date.now() - start) / 1000,\n\t\t};\n\t}\n\n\tprivate async runRounds(prompt: string, options: RunOptions, totals: RunTotals): Promise<void> {\n\t\tlet lastFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst isLastAttempt = attempt === this.maxAttempts;\n\n\t\t\tconst plannerResponse = await this.plannerAgent.run(\n\t\t\t\tgetPlannerPrompt(prompt, lastFailureReason),\n\t\t\t\toptions,\n\t\t\t);\n\t\t\taddToTotals(totals, plannerResponse);\n\n\t\t\tif (!plannerResponse.response) {\n\t\t\t\tlastFailureReason = 'The planner produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the planner produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst executorResponse = await this.executorAgent.run(\n\t\t\t\tgetExecutorPrompt(prompt, plannerResponse.response),\n\t\t\t\toptions,\n\t\t\t);\n\t\t\taddToTotals(totals, executorResponse);\n\n\t\t\tif (!executorResponse.response) {\n\t\t\t\tlastFailureReason = 'The executor produced no response.';\n\t\t\t\tif (isLastAttempt) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the executor produced no response; starting another round`,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst reviewerDecision = await this.getReviewerDecision(\n\t\t\t\tprompt,\n\t\t\t\tplannerResponse.response,\n\t\t\t\texecutorResponse.response,\n\t\t\t\toptions,\n\t\t\t\ttotals,\n\t\t\t);\n\n\t\t\tif (reviewerDecision.decision === 'approved') return;\n\n\t\t\tlastFailureReason = reviewerDecision.feedback;\n\t\t\tif (isLastAttempt) {\n\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: lastFailureReason });\n\t\t\t}\n\n\t\t\tthis.warn(\n\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)}: the reviewer rejected the round; starting another with its feedback`,\n\t\t\t\tlastFailureReason,\n\t\t\t);\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: lastFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\t// Retries only the reviewer call on a malformed decision, instead of redoing\n\t// planning/execution — a bad or unparsable reviewer response is not evidence\n\t// the plan or the implementation were wrong.\n\tprivate async getReviewerDecision(\n\t\tuserPrompt: string,\n\t\tplannerPrompt: string,\n\t\texecutorResult: string,\n\t\toptions: RunOptions,\n\t\ttotals: RunTotals,\n\t): Promise<ReviewerDecision> {\n\t\tlet parseFailureReason: string | undefined;\n\n\t\tfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {\n\t\t\tconst reviewerResponse = await this.reviewerAgent.run(\n\t\t\t\tgetReviewerPrompt(userPrompt, plannerPrompt, executorResult, parseFailureReason),\n\t\t\t\toptions,\n\t\t\t);\n\n\t\t\taddToTotals(totals, reviewerResponse);\n\n\t\t\ttry {\n\t\t\t\treturn parseReviewerDecision(reviewerResponse, this.reviewerDecisionValidator);\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof RecoverableError)) throw error;\n\n\t\t\t\tparseFailureReason = error.cause;\n\t\t\t\tif (attempt === this.maxAttempts) {\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', { cause: parseFailureReason });\n\t\t\t\t}\n\n\t\t\t\tthis.warn(\n\t\t\t\t\t`Reviewer decision ${String(attempt)}/${String(this.maxAttempts)} was unusable; asking the reviewer again`,\n\t\t\t\t\tparseFailureReason,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\tcause: parseFailureReason ?? 'Unknown failure.',\n\t\t});\n\t}\n\n\tprivate warn(...args: unknown[]): void {\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tthis.logger.warn(...args);\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Orchestrator logger failed while reporting a retry',\n\t\t);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';
1
+ import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';
2
2
  import type { ILogger } from '#src/shared/domain/logger';
3
3
  export declare class RetryingAgent implements Agent {
4
4
  private inner;
@@ -17,5 +17,5 @@ export declare class RetryingAgent implements Agent {
17
17
  */
18
18
  noteFailures?: boolean;
19
19
  });
20
- run(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse>;
20
+ run(prompt: string, options: RunOptions): Promise<AgentResponse>;
21
21
  }
@@ -1,5 +1,5 @@
1
- import { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/agent/domain/errors';
2
- import { classifyHostFailure, describeFailure, treatErrors, } from '#src/agent/domain/providerFailure';
1
+ import { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';
2
+ import { classifyHostFailure, describeFailure, treatErrors, } from '#src/shared/domain/providerFailure';
3
3
  import { isAbortError } from '#src/shared/domain/isAbortError';
4
4
  import { addTokens } from '#src/shared/domain/tokens';
5
5
  export class RetryingAgent {
@@ -16,7 +16,7 @@ export class RetryingAgent {
16
16
  this.logger = logger;
17
17
  this.noteFailures = noteFailures;
18
18
  }
19
- async run(prompt, signal, callback) {
19
+ async run(prompt, options) {
20
20
  const start = Date.now();
21
21
  let lastPrompt = null;
22
22
  // Failed attempts were billed too, so they travel with whichever way the run ends.
@@ -26,7 +26,7 @@ export class RetryingAgent {
26
26
  for (let attempt = 1;; attempt++) {
27
27
  try {
28
28
  const promptToSend = lastPrompt ?? prompt;
29
- const response = await this.inner.run(promptToSend, signal, callback);
29
+ const response = await this.inner.run(promptToSend, options);
30
30
  return {
31
31
  ...response,
32
32
  // Any call answered without usage makes the whole count unknown, not partial.
@@ -1 +1 @@
1
- {"version":3,"file":"retryingAgent.js","sourceRoot":"","sources":["../../../../src/retry/domain/model/retryingAgent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AACjG,OAAO,EACN,mBAAmB,EACnB,eAAe,EACf,WAAW,GACX,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AAEnE,MAAM,OAAO,aAAa;IACjB,KAAK,CAAQ;IACb,WAAW,CAAS;IACpB,MAAM,CAAU;IAChB,YAAY,CAAU;IAE9B,YAAY,EACX,KAAK,EACL,WAAW,GAAG,CAAC,EACf,MAAM,EACN,YAAY,GAAG,IAAI,GAYnB;QACA,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW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D,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, Callback } from '#src/agent/domain/agent';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/agent/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/agent/domain/providerFailure';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\n\nexport class RetryingAgent implements Agent {\n\tprivate inner: Agent;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\tprivate noteFailures: boolean;\n\n\tconstructor({\n\t\tinner,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t\tnoteFailures = true,\n\t}: {\n\t\tinner: Agent;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t\t/**\n\t\t * Appends the previous failure to the retried prompt, so a provider session that may\n\t\t * remember the failed turn is told what happened. Off for an agent that records nothing\n\t\t * from a failed call, such as `LLMAgent`: there the note would become a permanent user\n\t\t * message resent on every later turn.\n\t\t */\n\t\tnoteFailures?: boolean;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.inner = inner;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t\tthis.noteFailures = noteFailures;\n\t}\n\n\tasync run(prompt: string, signal: AbortSignal, callback: Callback): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\tlet lastPrompt: string | null = null;\n\t\t// Failed attempts were billed too, so they travel with whichever way the run ends.\n\t\tlet spent: Tokens | undefined;\n\t\t// An attempt was answered without usage, so `spent` is only a subtotal.\n\t\tlet unreported = false;\n\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst promptToSend = lastPrompt ?? prompt;\n\t\t\t\tconst response = await this.inner.run(promptToSend, signal, callback);\n\t\t\t\treturn {\n\t\t\t\t\t...response,\n\t\t\t\t\t// Any call answered without usage makes the whole count unknown, not partial.\n\t\t\t\t\ttokens: unreported ? undefined : response.tokens && addTokens(spent, response.tokens),\n\t\t\t\t\t// Every attempt was waited for, not only the last one.\n\t\t\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t\t};\n\t\t\t} catch (e) {\n\t\t\t\tif (isAbortError(e)) throw e;\n\t\t\t\tif (e instanceof UnrecoverableError) throw withSpentTokens(e, spent, unreported);\n\n\t\t\t\t// Only a failure the agent classified as recoverable earns another call. An\n\t\t\t\t// unclassified one breaks the `Agent` contract, so nothing here knows whether\n\t\t\t\t// replaying it is safe — it may already have written files or run commands.\n\t\t\t\tif (!(e instanceof RecoverableError))\n\t\t\t\t\tthrow new UnrecoverableError('The agent failed without classifying the failure', {\n\t\t\t\t\t\tcause: describeFailure(e),\n\t\t\t\t\t\ttokens: spent,\n\t\t\t\t\t\tusageUnreported: unreported,\n\t\t\t\t\t});\n\n\t\t\t\tspent = addTokens(spent, e.tokens);\n\t\t\t\tunreported ||= e.usageUnreported;\n\n\t\t\t\tif (attempt === this.maxAttempts)\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\t\t\t\tcause: `Gave up after ${String(this.maxAttempts)} attempts. Last failure: ${e.cause}`,\n\t\t\t\t\t\ttokens: spent,\n\t\t\t\t\t\tusageUnreported: unreported,\n\t\t\t\t\t});\n\n\t\t\t\t// Keeps the original request: an attempt that failed before the provider registered\n\t\t\t\t// the turn left no session that remembers it.\n\t\t\t\tif (this.noteFailures) {\n\t\t\t\t\tlastPrompt = `${prompt}\\n\\nThe previous attempt failed for the following reason: ${e.cause}`;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\ttreatErrors(\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)} failed; retrying`,\n\t\t\t\t\t\t\t\te,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t\t'RetryingAgent logger failed while reporting a retry',\n\t\t\t\t\t);\n\t\t\t\t} catch (logFailure) {\n\t\t\t\t\t// The attempts already spent their tokens, whatever the logger did.\n\t\t\t\t\tthrow withSpentTokens(logFailure, spent, unreported);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"retryingAgent.js","sourceRoot":"","sources":["../../../../src/retry/domain/model/retryingAgent.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAClG,OAAO,EACN,mBAAmB,EACnB,eAAe,EACf,WAAW,GACX,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAe,MAAM,2BAA2B,CAAC;AAEnE,MAAM,OAAO,aAAa;IACjB,KAAK,CAAQ;IACb,WAAW,CAAS;IACpB,MAAM,CAAU;IAChB,YAAY,CAAU;IAE9B,YAAY,EACX,KAAK,EACL,WAAW,GAAG,CAAC,EACf,MAAM,EACN,YAAY,GAAG,IAAI,GAYnB;QACA,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE,CAAC;YACvD,MAAM,IAAI,UAAU,CAAC,wCAAwC,CAAC,CAAC;QAChE,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IAClC,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,MAAc,EAAE,OAAmB;QA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CAAC,CAAC,MAAM,CAAC,CAAC;gBACnC,UAAU,KAAK,CAAC,CAAC,eAAe,CAAC;gBAEjC,IAAI,OAAO,KAAK,IAAI,CAAC,WAAW;oBAC/B,MAAM,IAAI,kBAAkB,CAAC,wBAAwB,EAAE;wBACtD,KAAK,EAAE,iBAAiB,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,4BAA4B,CAAC,CAAC,KAAK,EAAE;wBACrF,MAAM,EAAE,KAAK;wBACb,eAAe,EAAE,UAAU;qBAC3B,CAAC,CAAC;gBAEJ,oFAAoF;gBACpF,8CAA8C;gBAC9C,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;oBACvB,UAAU,GAAG,GAAG,MAAM,6DAA6D,CAAC,CAAC,KAAK,EAAE,CAAC;gBAC9F,CAAC;gBACD,IAAI,CAAC;oBACJ,WAAW,CACV,GAAG,EAAE;wBACJ,IAAI,CAAC,MAAM,CAAC,IAAI,CACf,WAAW,MAAM,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,mBAAmB,EACzE,CAAC,CACD,CAAC;oBACH,CAAC,EACD,mBAAmB,EACnB,qDAAqD,CACrD,CAAC;gBACH,CAAC;gBAAC,OAAO,UAAU,EAAE,CAAC;oBACrB,oEAAoE;oBACpE,MAAM,eAAe,CAAC,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC;gBACtD,CAAC;YACF,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["import type { Agent, AgentResponse, RunOptions } from '#src/agent/domain/agent';\nimport { RecoverableError, UnrecoverableError, withSpentTokens } from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isAbortError } from '#src/shared/domain/isAbortError';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport { addTokens, type Tokens } from '#src/shared/domain/tokens';\n\nexport class RetryingAgent implements Agent {\n\tprivate inner: Agent;\n\tprivate maxAttempts: number;\n\tprivate logger: ILogger;\n\tprivate noteFailures: boolean;\n\n\tconstructor({\n\t\tinner,\n\t\tmaxAttempts = 3,\n\t\tlogger,\n\t\tnoteFailures = true,\n\t}: {\n\t\tinner: Agent;\n\t\tmaxAttempts?: number;\n\t\tlogger: ILogger;\n\t\t/**\n\t\t * Appends the previous failure to the retried prompt, so a provider session that may\n\t\t * remember the failed turn is told what happened. Off for an agent that records nothing\n\t\t * from a failed call, such as `LLMAgent`: there the note would become a permanent user\n\t\t * message resent on every later turn.\n\t\t */\n\t\tnoteFailures?: boolean;\n\t}) {\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n\t\t\tthrow new RangeError('maxAttempts must be a positive integer');\n\t\t}\n\n\t\tthis.inner = inner;\n\t\tthis.maxAttempts = maxAttempts;\n\t\tthis.logger = logger;\n\t\tthis.noteFailures = noteFailures;\n\t}\n\n\tasync run(prompt: string, options: RunOptions): Promise<AgentResponse> {\n\t\tconst start = Date.now();\n\t\tlet lastPrompt: string | null = null;\n\t\t// Failed attempts were billed too, so they travel with whichever way the run ends.\n\t\tlet spent: Tokens | undefined;\n\t\t// An attempt was answered without usage, so `spent` is only a subtotal.\n\t\tlet unreported = false;\n\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\ttry {\n\t\t\t\tconst promptToSend = lastPrompt ?? prompt;\n\t\t\t\tconst response = await this.inner.run(promptToSend, options);\n\t\t\t\treturn {\n\t\t\t\t\t...response,\n\t\t\t\t\t// Any call answered without usage makes the whole count unknown, not partial.\n\t\t\t\t\ttokens: unreported ? undefined : response.tokens && addTokens(spent, response.tokens),\n\t\t\t\t\t// Every attempt was waited for, not only the last one.\n\t\t\t\t\tduration: (Date.now() - start) / 1000,\n\t\t\t\t};\n\t\t\t} catch (e) {\n\t\t\t\tif (isAbortError(e)) throw e;\n\t\t\t\tif (e instanceof UnrecoverableError) throw withSpentTokens(e, spent, unreported);\n\n\t\t\t\t// Only a failure the agent classified as recoverable earns another call. An\n\t\t\t\t// unclassified one breaks the `Agent` contract, so nothing here knows whether\n\t\t\t\t// replaying it is safe — it may already have written files or run commands.\n\t\t\t\tif (!(e instanceof RecoverableError))\n\t\t\t\t\tthrow new UnrecoverableError('The agent failed without classifying the failure', {\n\t\t\t\t\t\tcause: describeFailure(e),\n\t\t\t\t\t\ttokens: spent,\n\t\t\t\t\t\tusageUnreported: unreported,\n\t\t\t\t\t});\n\n\t\t\t\tspent = addTokens(spent, e.tokens);\n\t\t\t\tunreported ||= e.usageUnreported;\n\n\t\t\t\tif (attempt === this.maxAttempts)\n\t\t\t\t\tthrow new UnrecoverableError('Max attempts exhausted', {\n\t\t\t\t\t\tcause: `Gave up after ${String(this.maxAttempts)} attempts. Last failure: ${e.cause}`,\n\t\t\t\t\t\ttokens: spent,\n\t\t\t\t\t\tusageUnreported: unreported,\n\t\t\t\t\t});\n\n\t\t\t\t// Keeps the original request: an attempt that failed before the provider registered\n\t\t\t\t// the turn left no session that remembers it.\n\t\t\t\tif (this.noteFailures) {\n\t\t\t\t\tlastPrompt = `${prompt}\\n\\nThe previous attempt failed for the following reason: ${e.cause}`;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\ttreatErrors(\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\t\t\t`Attempt ${String(attempt)}/${String(this.maxAttempts)} failed; retrying`,\n\t\t\t\t\t\t\t\te,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t\t'RetryingAgent logger failed while reporting a retry',\n\t\t\t\t\t);\n\t\t\t\t} catch (logFailure) {\n\t\t\t\t\t// The attempts already spent their tokens, whatever the logger did.\n\t\t\t\t\tthrow withSpentTokens(logFailure, spent, unreported);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","s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,UAAU;QAAE,OAAO,KAAK,CAAC;IAExC,MAAM,UAAU,GAAG,KAAK,CAAC,WAGiB,CAAC;IAC3C,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,OAAO,EAAE;QAC1C,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,MAAM,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC;QACtC,eAAe,EAAE,KAAK,CAAC,eAAe,IAAI,UAAU;KACpD,CAAC,CAAC;IACH,0FAA0F;IAC1F,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACzB,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;CAAG","sourcesContent":["import { addTokens, type Tokens } from '#src/shared/domain/tokens';\n\ninterface ClassifiedErrorOptions {\n\tcause: string;\n\t/** What the run spent before it failed, as far as it was reported. */\n\ttokens?: Tokens | undefined;\n\t/**\n\t * A provider answered at least one call of the run without reporting its usage, so\n\t * `tokens` would be a subtotal. A failure that never got an answer, such as a dropped\n\t * connection, leaves it unset: it adds nothing that could be missing.\n\t */\n\tusageUnreported?: boolean | undefined;\n}\n\nexport class RecoverableError extends Error {\n\toverride cause: string;\n\t/** Missing when nothing was reported, and always missing when `usageUnreported` is set. */\n\treadonly tokens: Tokens | undefined;\n\treadonly usageUnreported: boolean;\n\n\tconstructor(message: string, options: ClassifiedErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.cause = options.cause;\n\t\tthis.usageUnreported = options.usageUnreported ?? false;\n\t\t// A subtotal must not pass for the run's total.\n\t\tthis.tokens = this.usageUnreported ? undefined : options.tokens;\n\t}\n}\nexport class UnrecoverableError extends Error {\n\toverride cause: string;\n\t/** Missing when nothing was reported, and always missing when `usageUnreported` is set. */\n\treadonly tokens: Tokens | undefined;\n\treadonly usageUnreported: boolean;\n\n\tconstructor(message: string, options: ClassifiedErrorOptions) {\n\t\tsuper(message, options);\n\t\tthis.cause = options.cause;\n\t\tthis.usageUnreported = options.usageUnreported ?? false;\n\t\t// A subtotal must not pass for the run's total.\n\t\tthis.tokens = this.usageUnreported ? undefined : options.tokens;\n\t}\n}\n\n/**\n * The same failure, also carrying what an outer layer spent before the failure reached it,\n * such as earlier attempts or earlier roles, or the call the failure came from. `unreported`\n * says that some of it was answered without usage. It is a new instance of the same class, so\n * a subclass such as `MaxContextError` keeps its meaning. A cancellation or an unclassified\n * failure is returned unchanged: neither can carry tokens.\n */\nexport function withSpentTokens(\n\terror: unknown,\n\tspent: Tokens | undefined,\n\tunreported = false,\n): unknown {\n\tif (!(error instanceof RecoverableError || error instanceof UnrecoverableError)) return error;\n\tif (!spent && !unreported) return error;\n\n\tconst ErrorClass = error.constructor as new (\n\t\tmessage: string,\n\t\toptions: ClassifiedErrorOptions,\n\t) => RecoverableError | UnrecoverableError;\n\tconst copy = new ErrorClass(error.message, {\n\t\tcause: error.cause,\n\t\ttokens: addTokens(error.tokens, spent),\n\t\tusageUnreported: error.usageUnreported || unreported,\n\t});\n\t// The trace should point at where the failure happened, not at the layer that counted it.\n\tcopy.stack = error.stack;\n\treturn copy;\n}\n\n/**\n * An agent was requested with something its provider does not support, such as another\n * provider's model. Thrown while the agent is built, never by `run()`.\n */\nexport class InvalidAgentConfigError extends Error {}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providerFailure.js","sourceRoot":"","sources":["../../../src/shared/domain/providerFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEnE;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,KAAc,EAAE,OAAe;IACtE,IAAI,YAAY,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,KAAK,YAAY,gBAAgB,IAAI,KAAK,YAAY,kBAAkB;QAA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,OAAO,CAAC;IAClE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IAErD,OAAO,4CAA4C,CAAC;AACrD,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,wBAAwB,CAC9C,MAAwB,EACxB,OAAe;IAEf,IAAI,MAAwB,CAAC;IAE7B,IAAI,CAAC;QACJ,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,uBAAuB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IAED,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,IAAI,CAAC;QACJ,SAAS,CAAC;YACT,IAAI,IAAuB,CAAC;YAE5B,IAAI,CAAC;gBACJ,IAAI,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAC5B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,uBAAuB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;YAED,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;gBACf,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO;YACR,CAAC;YAED,MAAM,IAAI,CAAC,KAAK,CAAC;QAClB,CAAC;IACF,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,SAAS,EAAE,CAAC;YAChB,IAAI,CAAC;gBACJ,MAAM,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;YACzB,CAAC;YAAC,MAAM,CAAC;gBACR,4EAA4E;gBAC5E,4EAA4E;YAC7E,CAAC;QACF,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { isAbortError } from '#src/shared/domain/isAbortError';\nimport { RecoverableError, UnrecoverableError } from './errors.ts';\n\n/**\n * Unclassified failures are transport-shaped, so recoverable is the useful default:\n * `RetryingAgent` turns a persistent one into an `UnrecoverableError` on exhaustion, while\n * the opposite default would make every transient blip fatal.\n */\nexport function classifyProviderFailure(error: unknown, context: string): Error {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof RecoverableError || error instanceof UnrecoverableError) return error;\n\n\treturn new RecoverableError(context, { cause: describeFailure(error) });\n}\n\n/** A host failure cannot be retried safely because the provider turn may already have side effects. */\nexport function classifyHostFailure(error: unknown, context: string): Error {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof UnrecoverableError) return error;\n\n\treturn new UnrecoverableError(context, { cause: describeFailure(error) });\n}\n\n/**\n * Runs host code — a logger, for example — and classifies whatever it throws with the\n * classifier the caller chooses. The host code stays unaware of classification, and the\n * failure cannot escape the `Agent` unclassified.\n */\nexport function treatErrors<T>(\n\toperation: () => T,\n\tclassify: (error: unknown, context: string) => Error,\n\tcontext: string,\n): T {\n\ttry {\n\t\treturn operation();\n\t} catch (error) {\n\t\tthrow classify(error, context);\n\t}\n}\n\n/** Preserves deliberate domain errors while making unexpected local failures fatal. */\nexport function classifyLocalFailure(error: unknown, context: string): Error {\n\tif (isAbortError(error)) return error;\n\tif (error instanceof RecoverableError || error instanceof UnrecoverableError) return error;\n\n\treturn new UnrecoverableError(context, { cause: describeFailure(error) });\n}\n\n/** The message alone: a stack or serialized object could expose unstable implementation details. */\nexport function describeFailure(error: unknown): string {\n\tif (error instanceof RecoverableError || error instanceof UnrecoverableError) return error.cause;\n\tif (error instanceof Error && error.message) return error.message;\n\tif (typeof error === 'string' && error) return error;\n\n\treturn 'The provider failed without a description.';\n}\n\n/**\n * Classifies the stream itself and nothing else. Consuming an SDK stream inside a\n * `try/catch` puts the loop body — item mapping, logging, the consumer callback — inside\n * the provider boundary too, so a host failure gets reported as a recoverable provider\n * failure and `RetryingAgent` replays a turn that already ran its side effects.\n */\nexport async function* classifiedProviderStream<T>(\n\tstream: AsyncIterable<T>,\n\tcontext: string,\n): AsyncGenerator<T> {\n\tlet events: AsyncIterator<T>;\n\n\ttry {\n\t\tevents = stream[Symbol.asyncIterator]();\n\t} catch (error) {\n\t\tthrow classifyProviderFailure(error, context);\n\t}\n\n\tlet completed = false;\n\n\ttry {\n\t\tfor (;;) {\n\t\t\tlet next: IteratorResult<T>;\n\n\t\t\ttry {\n\t\t\t\tnext = await events.next();\n\t\t\t} catch (error) {\n\t\t\t\tthrow classifyProviderFailure(error, context);\n\t\t\t}\n\n\t\t\tif (next.done) {\n\t\t\t\tcompleted = true;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tyield next.value;\n\t\t}\n\t} finally {\n\t\tif (!completed) {\n\t\t\ttry {\n\t\t\t\tawait events.return?.();\n\t\t\t} catch {\n\t\t\t\t// Cleanup is secondary to the failure that interrupted consumption. It must\n\t\t\t\t// never replace a classified provider error or an unrecoverable host error.\n\t\t\t}\n\t\t}\n\t}\n}\n"]}
@@ -1,5 +1,11 @@
1
+ import type { ToolRisk } from '#src/agent/domain/approval';
1
2
  import type { ToolDefinition } from '#src/llm/domain/tool';
2
3
  export interface Tool extends ToolDefinition {
4
+ /**
5
+ * Judges this call from its input before it runs, so the agent can ask before a
6
+ * `destructive` one. Input the tool would reject cannot do harm, so it may count as `safe`.
7
+ */
8
+ risk(input: unknown): ToolRisk;
3
9
  /**
4
10
  * Runs the tool on the input the model sent. The input is unknown because the model can
5
11
  * send anything: validating it is the tool's job, and a rejection returns to the model as
@@ -1 +1 @@
1
- {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/tools/domain/tool.ts"],"names":[],"mappings":"","sourcesContent":["import type { ToolDefinition } from '#src/llm/domain/tool';\n\nexport interface Tool extends ToolDefinition {\n\t/**\n\t * Runs the tool on the input the model sent. The input is unknown because the model can\n\t * send anything: validating it is the tool's job, and a rejection returns to the model as\n\t * an error result.\n\t */\n\texecute(input: unknown, signal: AbortSignal): Promise<string>;\n}\n"]}
1
+ {"version":3,"file":"tool.js","sourceRoot":"","sources":["../../../src/tools/domain/tool.ts"],"names":[],"mappings":"","sourcesContent":["import type { ToolRisk } from '#src/agent/domain/approval';\nimport type { ToolDefinition } from '#src/llm/domain/tool';\n\nexport interface Tool extends ToolDefinition {\n\t/**\n\t * Judges this call from its input before it runs, so the agent can ask before a\n\t * `destructive` one. Input the tool would reject cannot do harm, so it may count as `safe`.\n\t */\n\trisk(input: unknown): ToolRisk;\n\t/**\n\t * Runs the tool on the input the model sent. The input is unknown because the model can\n\t * send anything: validating it is the tool's job, and a rejection returns to the model as\n\t * an error result.\n\t */\n\texecute(input: unknown, signal: AbortSignal): Promise<string>;\n}\n"]}
@@ -10,5 +10,6 @@ import type { Workspace } from '../domain/workspace.ts';
10
10
  */
11
11
  export declare function createWorkspace({ root, logger, }: {
12
12
  root: string;
13
- logger: ILogger;
13
+ /** Defaults to warnings on stderr. */
14
+ logger?: ILogger;
14
15
  }): Promise<Workspace>;