@mikode13/harness 11.1.0 → 11.2.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 (69) hide show
  1. package/README.md +48 -10
  2. package/dist/agent/domain/agent.d.ts +17 -0
  3. package/dist/agent/domain/agent.js.map +1 -1
  4. package/dist/agent/domain/runContext.d.ts +5 -0
  5. package/dist/agent/domain/runContext.js.map +1 -1
  6. package/dist/engines/domain/model/compactor.d.ts +40 -0
  7. package/dist/engines/domain/model/compactor.js +5 -0
  8. package/dist/engines/domain/model/compactor.js.map +1 -0
  9. package/dist/engines/domain/model/llmAgent.d.ts +48 -2
  10. package/dist/engines/domain/model/llmAgent.js +351 -14
  11. package/dist/engines/domain/model/llmAgent.js.map +1 -1
  12. package/dist/engines/domain/model/recentCompaction.d.ts +39 -0
  13. package/dist/engines/domain/model/recentCompaction.js +119 -0
  14. package/dist/engines/domain/model/recentCompaction.js.map +1 -0
  15. package/dist/engines/domain/model/stepContext.js +3 -0
  16. package/dist/engines/domain/model/stepContext.js.map +1 -1
  17. package/dist/engines/domain/model/triagedCompaction.d.ts +27 -0
  18. package/dist/engines/domain/model/triagedCompaction.js +60 -0
  19. package/dist/engines/domain/model/triagedCompaction.js.map +1 -0
  20. package/dist/factory/infrastructure/agentLLMFactory.d.ts +40 -12
  21. package/dist/factory/infrastructure/agentLLMFactory.js +114 -18
  22. package/dist/factory/infrastructure/agentLLMFactory.js.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/llm/domain/contextTriage.d.ts +26 -0
  26. package/dist/llm/domain/contextTriage.js +3 -0
  27. package/dist/llm/domain/contextTriage.js.map +1 -0
  28. package/dist/llm/domain/llm.d.ts +18 -1
  29. package/dist/llm/domain/llm.js.map +1 -1
  30. package/dist/llm/domain/message.d.ts +18 -1
  31. package/dist/llm/domain/message.js +20 -0
  32. package/dist/llm/domain/message.js.map +1 -1
  33. package/dist/llm/infrastructure/claudeLLMClient.d.ts +4 -5
  34. package/dist/llm/infrastructure/claudeLLMClient.js +39 -13
  35. package/dist/llm/infrastructure/claudeLLMClient.js.map +1 -1
  36. package/dist/llm/infrastructure/jevContextTriage.d.ts +18 -0
  37. package/dist/llm/infrastructure/jevContextTriage.js +92 -0
  38. package/dist/llm/infrastructure/jevContextTriage.js.map +1 -0
  39. package/dist/llm/infrastructure/openAILLMClient.d.ts +4 -5
  40. package/dist/llm/infrastructure/openAILLMClient.js +20 -9
  41. package/dist/llm/infrastructure/openAILLMClient.js.map +1 -1
  42. package/dist/tools/domain/preparedCall.d.ts +2 -1
  43. package/dist/tools/domain/preparedCall.js +7 -1
  44. package/dist/tools/domain/preparedCall.js.map +1 -1
  45. package/dist/tools/domain/readRegistry.d.ts +11 -0
  46. package/dist/tools/domain/readRegistry.js.map +1 -1
  47. package/dist/tools/infrastructure/agentAsTool.d.ts +6 -0
  48. package/dist/tools/infrastructure/agentAsTool.js +9 -0
  49. package/dist/tools/infrastructure/agentAsTool.js.map +1 -1
  50. package/dist/tools/infrastructure/commandTool.js +4 -1
  51. package/dist/tools/infrastructure/commandTool.js.map +1 -1
  52. package/dist/tools/infrastructure/exploreTool.js +2 -0
  53. package/dist/tools/infrastructure/exploreTool.js.map +1 -1
  54. package/dist/tools/infrastructure/fileTools.js +1 -0
  55. package/dist/tools/infrastructure/fileTools.js.map +1 -1
  56. package/dist/tools/infrastructure/removeWorktreeTool.js +7 -1
  57. package/dist/tools/infrastructure/removeWorktreeTool.js.map +1 -1
  58. package/dist/tools/infrastructure/subagents.d.ts +3 -1
  59. package/dist/tools/infrastructure/subagents.js +2 -1
  60. package/dist/tools/infrastructure/subagents.js.map +1 -1
  61. package/dist/tools/infrastructure/trackedEdits.js +1 -0
  62. package/dist/tools/infrastructure/trackedEdits.js.map +1 -1
  63. package/dist/tools/infrastructure/workspaceWrites.d.ts +13 -1
  64. package/dist/tools/infrastructure/workspaceWrites.js +18 -1
  65. package/dist/tools/infrastructure/workspaceWrites.js.map +1 -1
  66. package/dist/tools/infrastructure/writeCeiling.d.ts +16 -0
  67. package/dist/tools/infrastructure/writeCeiling.js +49 -0
  68. package/dist/tools/infrastructure/writeCeiling.js.map +1 -0
  69. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAgBxE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,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;AAEtD,OAAO,EAAkC,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAmB,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,yFAAyF;AACzF,MAAM,CAAC,MAAM,eAAe,GAAG;IAC9B,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;CACqD,CAAC;AAG9D,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CAC6D,CAAC;AAGpE,+FAA+F;AAC/F,gGAAgG;AAChG,+FAA+F;AAC/F,iEAAiE;AACjE,MAAM,eAAe,GAAG,OAAO,CAAC;AAEhC,kFAAkF;AAClF,MAAM,qBAAqB,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAE7D,yFA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M,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC5C,MAAM,OAAO,GAAG,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACxD,uFAAuF;YACvF,8DAA8D;YAC9D,MAAM,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EACrD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\nimport { claudeModelIds } from './claudeModelIds.ts';\n\n// The Messages API takes full model IDs; `claudeModelIds` pins the one each alias names.\nexport const claudeLLMModels = [\n\t'opus',\n\t'fable',\n\t'sonnet',\n\t'haiku',\n] as const satisfies readonly (keyof typeof claudeModelIds)[];\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. Every model the aliases name writes up to\n// 128,000; Haiku 5.5 at `xhigh` once spent 64,000 on one answer.\nconst maxOutputTokens = 128_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// A compaction that failed, with no summary. Claude reads one sent back as if it were not\n\t\t\t// there, so it is left out: the context goes on whole, and Claude compacts again later.\n\t\t\tif (!block.content) {\n\t\t\t\ttreatErrors(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'Claude could not compact the conversation; it is sent whole until Claude compacts it',\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t\t);\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\n/**\n * @param summaries each compaction's summary as it was streamed, by the index of its block. The\n * SDK joins a delta that carries none as the text \"null\", so the final message cannot tell.\n */\nfunction toLLMResponse(\n\tresponse: AnthropicMessage,\n\tlogger: ILogger,\n\tsummaries: ReadonlyMap<number, string>,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap((block, index) => {\n\t\t\t\t\tconst summary = summaries.get(index);\n\t\t\t\t\treturn describeBlock(\n\t\t\t\t\t\tblock.type === 'compaction' && summary !== undefined\n\t\t\t\t\t\t\t? { ...block, content: summary }\n\t\t\t\t\t\t\t: block,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeModelIds)[ClaudeLLMModel];\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which Anthropic compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tconst effort = reasoningEffort ?? 'high';\n\t\tif (!isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined && !(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t);\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 = claudeModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\t\t// What each compaction streamed of its summary, by block index, its missing parts left out.\n\t\tconst summaries = new Map<number, string>();\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\tthis.compactAt === undefined || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\t\t\t\tmessages: sentContext(context, claudeSource).flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\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\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tbetas: [compactionBeta],\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: this.compactAt },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tsent.on('streamEvent', event => {\n\t\t\t\tif (event.type === 'content_block_start' && event.content_block.type === 'compaction') {\n\t\t\t\t\tsummaries.set(event.index, event.content_block.content ?? '');\n\t\t\t\t} else if (\n\t\t\t\t\tevent.type === 'content_block_delta' &&\n\t\t\t\t\tevent.delta.type === 'compaction_delta'\n\t\t\t\t) {\n\t\t\t\t\tsummaries.set(\n\t\t\t\t\t\tevent.index,\n\t\t\t\t\t\t(summaries.get(event.index) ?? '') + (event.delta.content ?? ''),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, summaries),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAgBxE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,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;AAEtD,OAAO,EAAkC,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAmB,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,yFAAyF;AACzF,MAAM,CAAC,MAAM,eAAe,GAAG;IAC9B,MAAM;IACN,OAAO;IACP,QAAQ;IACR,OAAO;CACqD,CAAC;AAG9D,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,KAAK;IACL,QAAQ;IACR,MAAM;IACN,OAAO;IACP,KAAK;CAC6D,CAAC;AAGpE,+FAA+F;AAC/F,gGAAgG;AAChG,+FAA+F;AAC/F,iEAAiE;AACjE,MAAM,eAAe,GAAG,OAAO,CA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QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EACrD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\nimport { claudeModelIds } from './claudeModelIds.ts';\n\n// The Messages API takes full model IDs; `claudeModelIds` pins the one each alias names.\nexport const claudeLLMModels = [\n\t'opus',\n\t'fable',\n\t'sonnet',\n\t'haiku',\n] as const satisfies readonly (keyof typeof claudeModelIds)[];\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. Every model the aliases name writes up to\n// 128,000; Haiku 5.5 at `xhigh` once spent 64,000 on one answer.\nconst maxOutputTokens = 128_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t\tcase 'contextSummary':\n\t\t\t// Never sent: the agent sends the context derived from it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// A compaction that failed, with no summary. Claude reads one sent back as if it were not\n\t\t\t// there, so it is left out: the context goes on whole, and Claude compacts again later.\n\t\t\tif (!block.content) {\n\t\t\t\ttreatErrors(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'Claude could not compact the conversation; it is sent whole until Claude compacts it',\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t\t);\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\n/**\n * How many tokens of context the call compacted, when it did: what its compaction iteration read,\n * since Anthropic bills a compaction as a call of its own over the context before it.\n */\nfunction compactedContext(usage: Usage | undefined): { compactedContextTokens?: number } {\n\tconst compaction = usage?.iterations?.find(iteration => iteration.type === 'compaction');\n\tif (!compaction) return {};\n\treturn {\n\t\tcompactedContextTokens:\n\t\t\tcompaction.input_tokens +\n\t\t\tcompaction.cache_read_input_tokens +\n\t\t\tcompaction.cache_creation_input_tokens,\n\t};\n}\n\n/**\n * @param summaries each compaction's summary as it was streamed, by the index of its block. The\n * SDK joins a delta that carries none as the text \"null\", so the final message cannot tell.\n */\nfunction toLLMResponse(\n\tresponse: AnthropicMessage,\n\tlogger: ILogger,\n\tsummaries: ReadonlyMap<number, string>,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap((block, index) => {\n\t\t\t\t\tconst summary = summaries.get(index);\n\t\t\t\t\treturn describeBlock(\n\t\t\t\t\t\tblock.type === 'compaction' && summary !== undefined\n\t\t\t\t\t\t\t? { ...block, content: summary }\n\t\t\t\t\t\t\t: block,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t\t...compactedContext(response.usage),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeModelIds)[ClaudeLLMModel];\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\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\tconst effort = reasoningEffort ?? 'high';\n\t\tif (!isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\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 = claudeModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tcheckCompactAt(compactAt: number): void {\n\t\tif (!(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync send(\n\t\t{\n\t\t\tcontext,\n\t\t\ttools,\n\t\t\tcompactAt,\n\t\t}: { context: Message[]; tools: ToolDefinition[]; compactAt?: number | 'now' | undefined },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\t// Compacting now is compacting at the least threshold Anthropic takes, which a context\n\t\t// too large for the model has long passed.\n\t\tconst trigger = compactAt === 'now' ? minCompactAt : compactAt;\n\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\tconst messages = sentContext(context, claudeSource);\n\t\t// A compaction sent back needs the beta as much as one asked for, even with compaction off,\n\t\t// as after a context that no longer fit was compacted once.\n\t\tconst first = messages[0]?.content[0];\n\t\tconst compacted =\n\t\t\ttrigger !== undefined || (first?.type === 'compaction' && first.source === claudeSource);\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\t\t// What each compaction streamed of its summary, by block index, its missing parts left out.\n\t\tconst summaries = new Map<number, string>();\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\t!compacted || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\tmessages: messages.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\t...(compacted && { betas: [compactionBeta] }),\n\t\t\t\t\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(trigger !== undefined && {\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: trigger },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tsent.on('streamEvent', event => {\n\t\t\t\tif (event.type === 'content_block_start' && event.content_block.type === 'compaction') {\n\t\t\t\t\tsummaries.set(event.index, event.content_block.content ?? '');\n\t\t\t\t} else if (\n\t\t\t\t\tevent.type === 'content_block_delta' &&\n\t\t\t\t\tevent.delta.type === 'compaction_delta'\n\t\t\t\t) {\n\t\t\t\t\tsummaries.set(\n\t\t\t\t\t\tevent.index,\n\t\t\t\t\t\t(summaries.get(event.index) ?? '') + (event.delta.content ?? ''),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, summaries),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import { type TypeSafeClientConfig } from '@typesafe-ai/sdk';
2
+ import type { ContextTriage, TriagedResult } from '#src/llm/domain/contextTriage';
3
+ /**
4
+ * Jev's triage of the context, one request per tool result. The client is created on the first
5
+ * triage, so a missing `TYPESAFE_API_KEY` fails that triage, never the agent's construction.
6
+ */
7
+ export declare class JevContextTriage implements ContextTriage {
8
+ private client;
9
+ private readonly config;
10
+ /** @param config for the tests: the SDK's `apiKey`, `fetch`, `retry` and `compression`. */
11
+ constructor(config?: Pick<TypeSafeClientConfig, 'apiKey' | 'fetch' | 'retry' | 'compression'>);
12
+ score({ task, latestAnswer, results, }: {
13
+ task: string;
14
+ latestAnswer: string;
15
+ results: TriagedResult[];
16
+ }, signal: AbortSignal): Promise<number[]>;
17
+ private connect;
18
+ }
@@ -0,0 +1,92 @@
1
+ import { score, TypeSafeClient } from '@typesafe-ai/sdk';
2
+ import { UnrecoverableError } from '#src/shared/domain/errors';
3
+ import { classifyProviderFailure, describeFailure } from '#src/shared/domain/providerFailure';
4
+ /** Pinned, so a new Jev release does not change what the compactor keeps unannounced. */
5
+ const jevModel = 'jev-1.14.0';
6
+ // Each question is judged with the state alone, which Jev bounds at 32k tokens without its
7
+ // slower, less accurate long context: a result is cut well within it.
8
+ const outputCharacters = 60_000;
9
+ const textCharacters = 8_000;
10
+ const inputCharacters = 4_000;
11
+ // The public endpoint limits the rate: a context of hundreds of results is triaged a few at once.
12
+ const concurrency = 8;
13
+ const instructions = 'An agent works on the task. Its context is being compacted. How much does it need this tool result word for word to go on from its latest answer?';
14
+ const criteria = [
15
+ 'Not needed again: the work has moved past it.',
16
+ 'Its gist is enough: a short summary keeps what matters.',
17
+ 'Some exact details matter: names, numbers, paths or lines the agent will reuse.',
18
+ 'Needed word for word: the agent is still working on exactly this content.',
19
+ ];
20
+ /**
21
+ * Jev's triage of the context, one request per tool result. The client is created on the first
22
+ * triage, so a missing `TYPESAFE_API_KEY` fails that triage, never the agent's construction.
23
+ */
24
+ export class JevContextTriage {
25
+ client;
26
+ config;
27
+ /** @param config for the tests: the SDK's `apiKey`, `fetch`, `retry` and `compression`. */
28
+ constructor(config = {}) {
29
+ this.config = config;
30
+ }
31
+ async score({ task, latestAnswer, results, }, signal) {
32
+ const client = this.connect();
33
+ // The first failure stops the requests still to go: the whole triage has failed.
34
+ const failed = new AbortController();
35
+ const requestSignal = AbortSignal.any([signal, failed.signal]);
36
+ const request = async (result) => {
37
+ try {
38
+ return await client.systemOne({
39
+ model: jevModel,
40
+ state: {
41
+ task: shorten(task, textCharacters),
42
+ latestAnswer: shorten(latestAnswer, textCharacters),
43
+ toolCall: {
44
+ tool: result.tool,
45
+ input: shorten(JSON.stringify(result.input), inputCharacters),
46
+ },
47
+ result: shorten(result.output, outputCharacters),
48
+ },
49
+ questions: { needed: score(instructions, criteria) },
50
+ }, { signal: requestSignal });
51
+ }
52
+ catch (error) {
53
+ failed.abort();
54
+ // The SDK's abort error is not named 'AbortError', so it would pass for a provider failure.
55
+ signal.throwIfAborted();
56
+ throw classifyProviderFailure(error, 'Jev could not triage the context');
57
+ }
58
+ };
59
+ return inPool(results, concurrency, async (result) => {
60
+ const response = await request(result);
61
+ return response.answers.needed.score;
62
+ });
63
+ }
64
+ connect() {
65
+ try {
66
+ // Its logger writes to the console, which belongs to the consumer.
67
+ this.client ??= new TypeSafeClient({ ...this.config, logLevel: 'off' });
68
+ }
69
+ catch (error) {
70
+ throw new UnrecoverableError('Jev is not configured', { cause: describeFailure(error) });
71
+ }
72
+ return this.client;
73
+ }
74
+ }
75
+ /** `map` over `items`, at most `limit` at once, the results in their order. */
76
+ async function inPool(items, limit, map) {
77
+ const results = [];
78
+ let next = 0;
79
+ const worker = async () => {
80
+ for (let index = next++; index < items.length; index = next++) {
81
+ const item = items[index];
82
+ if (item !== undefined)
83
+ results[index] = await map(item);
84
+ }
85
+ };
86
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
87
+ return results;
88
+ }
89
+ function shorten(text, max) {
90
+ return text.length <= max ? text : `${text.slice(0, max)}…`;
91
+ }
92
+ //# sourceMappingURL=jevContextTriage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jevContextTriage.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/jevContextTriage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAA6B,MAAM,kBAAkB,CAAC;AAEpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAE9F,yFAAyF;AACzF,MAAM,QAAQ,GAAG,YAAY,CAAC;AAE9B,2FAA2F;AAC3F,sEAAsE;AACtE,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,cAAc,GAAG,KAAK,CAAC;AAC7B,MAAM,eAAe,GAAG,KAAK,CAAC;AAE9B,kGAAkG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GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;YAC1B,IAAI,IAAI,KAAK,SAAS;gBAAE,OAAO,CAAC,KAAK,CAAC,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC,CAAC;IACF,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,CAAC;IACjF,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,SAAS,OAAO,CAAC,IAAY,EAAE,GAAW;IACzC,OAAO,IAAI,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC;AAC7D,CAAC","sourcesContent":["import { score, TypeSafeClient, type TypeSafeClientConfig } from '@typesafe-ai/sdk';\nimport type { ContextTriage, TriagedResult } from '#src/llm/domain/contextTriage';\nimport { UnrecoverableError } from '#src/shared/domain/errors';\nimport { classifyProviderFailure, describeFailure } from '#src/shared/domain/providerFailure';\n\n/** Pinned, so a new Jev release does not change what the compactor keeps unannounced. */\nconst jevModel = 'jev-1.14.0';\n\n// Each question is judged with the state alone, which Jev bounds at 32k tokens without its\n// slower, less accurate long context: a result is cut well within it.\nconst outputCharacters = 60_000;\nconst textCharacters = 8_000;\nconst inputCharacters = 4_000;\n\n// The public endpoint limits the rate: a context of hundreds of results is triaged a few at once.\nconst concurrency = 8;\n\nconst instructions =\n\t'An agent works on the task. Its context is being compacted. How much does it need this tool result word for word to go on from its latest answer?';\nconst criteria = [\n\t'Not needed again: the work has moved past it.',\n\t'Its gist is enough: a short summary keeps what matters.',\n\t'Some exact details matter: names, numbers, paths or lines the agent will reuse.',\n\t'Needed word for word: the agent is still working on exactly this content.',\n] as const;\n\n/**\n * Jev's triage of the context, one request per tool result. The client is created on the first\n * triage, so a missing `TYPESAFE_API_KEY` fails that triage, never the agent's construction.\n */\nexport class JevContextTriage implements ContextTriage {\n\tprivate client: TypeSafeClient | undefined;\n\tprivate readonly config: Pick<TypeSafeClientConfig, 'apiKey' | 'fetch' | 'retry' | 'compression'>;\n\n\t/** @param config for the tests: the SDK's `apiKey`, `fetch`, `retry` and `compression`. */\n\tconstructor(\n\t\tconfig: Pick<TypeSafeClientConfig, 'apiKey' | 'fetch' | 'retry' | 'compression'> = {},\n\t) {\n\t\tthis.config = config;\n\t}\n\n\tasync score(\n\t\t{\n\t\t\ttask,\n\t\t\tlatestAnswer,\n\t\t\tresults,\n\t\t}: { task: string; latestAnswer: string; results: TriagedResult[] },\n\t\tsignal: AbortSignal,\n\t): Promise<number[]> {\n\t\tconst client = this.connect();\n\t\t// The first failure stops the requests still to go: the whole triage has failed.\n\t\tconst failed = new AbortController();\n\t\tconst requestSignal = AbortSignal.any([signal, failed.signal]);\n\t\tconst request = async (result: TriagedResult) => {\n\t\t\ttry {\n\t\t\t\treturn await client.systemOne(\n\t\t\t\t\t{\n\t\t\t\t\t\tmodel: jevModel,\n\t\t\t\t\t\tstate: {\n\t\t\t\t\t\t\ttask: shorten(task, textCharacters),\n\t\t\t\t\t\t\tlatestAnswer: shorten(latestAnswer, textCharacters),\n\t\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\t\ttool: result.tool,\n\t\t\t\t\t\t\t\tinput: shorten(JSON.stringify(result.input), inputCharacters),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tresult: shorten(result.output, outputCharacters),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tquestions: { needed: score(instructions, criteria) },\n\t\t\t\t\t},\n\t\t\t\t\t{ signal: requestSignal },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tfailed.abort();\n\t\t\t\t// The SDK's abort error is not named 'AbortError', so it would pass for a provider failure.\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tthrow classifyProviderFailure(error, 'Jev could not triage the context');\n\t\t\t}\n\t\t};\n\t\treturn inPool(results, concurrency, async result => {\n\t\t\tconst response = await request(result);\n\t\t\treturn response.answers.needed.score;\n\t\t});\n\t}\n\n\tprivate connect(): TypeSafeClient {\n\t\ttry {\n\t\t\t// Its logger writes to the console, which belongs to the consumer.\n\t\t\tthis.client ??= new TypeSafeClient({ ...this.config, logLevel: 'off' });\n\t\t} catch (error) {\n\t\t\tthrow new UnrecoverableError('Jev is not configured', { cause: describeFailure(error) });\n\t\t}\n\t\treturn this.client;\n\t}\n}\n\n/** `map` over `items`, at most `limit` at once, the results in their order. */\nasync function inPool<T, R>(items: T[], limit: number, map: (item: T) => Promise<R>): Promise<R[]> {\n\tconst results: R[] = [];\n\tlet next = 0;\n\tconst worker = async () => {\n\t\tfor (let index = next++; index < items.length; index = next++) {\n\t\t\tconst item = items[index];\n\t\t\tif (item !== undefined) results[index] = await map(item);\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n\treturn results;\n}\n\nfunction shorten(text: string, max: number): string {\n\treturn text.length <= max ? text : `${text.slice(0, max)}…`;\n}\n"]}
@@ -15,21 +15,20 @@ export declare class OpenAILLMClient implements LLMClient {
15
15
  private readonly client;
16
16
  private readonly model;
17
17
  private readonly reasoningEffort;
18
- private readonly compactAt;
19
18
  readonly systemPrompt: string;
20
19
  readonly providerDataSource = "openai";
21
20
  private readonly logger;
22
- constructor({ model, reasoningEffort, compactAt, systemPrompt, logger, }: {
21
+ constructor({ model, reasoningEffort, systemPrompt, logger, }: {
23
22
  model: string;
24
23
  reasoningEffort?: string;
25
- /** The input tokens at which OpenAI compacts the context on its side. Without it, never. */
26
- compactAt?: number | undefined;
27
24
  systemPrompt: string;
28
25
  logger: ILogger;
29
26
  });
30
27
  supportsNative(tool: NativeTool): boolean;
31
- send({ context, tools }: {
28
+ checkCompactAt(compactAt: number): void;
29
+ send({ context, tools, compactAt, }: {
32
30
  context: Message[];
33
31
  tools: ToolDefinition[];
32
+ compactAt?: number | 'now' | undefined;
34
33
  }, signal: AbortSignal): Promise<LLMResponse>;
35
34
  }
@@ -94,6 +94,9 @@ function toOpenAIItems(part, role, applyPatch) {
94
94
  return part.source === openAISource ? [part.data] : [];
95
95
  case 'reasoning':
96
96
  return [];
97
+ case 'contextSummary':
98
+ // Never sent: the agent sends the context derived from it.
99
+ return [];
97
100
  }
98
101
  }
99
102
  function toOpenAIInput(message, applyPatch) {
@@ -190,6 +193,9 @@ function unmapped(item, logger) {
190
193
  }, classifyHostFailure, 'OpenAI client logger failed while mapping a response');
191
194
  return [];
192
195
  }
196
+ // The threshold that compacts a context now: far below what any of its models holds, so a
197
+ // context that no longer fits has long passed it.
198
+ const compactNowAt = 50_000;
193
199
  function toStopReason(response) {
194
200
  if (response.status === 'incomplete') {
195
201
  return response.incomplete_details?.reason === 'content_filter' ? 'refused' : 'truncated';
@@ -235,6 +241,10 @@ function toLLMResponse(response, logger, applyPatch) {
235
241
  },
236
242
  usage,
237
243
  stopReason: toStopReason(response),
244
+ // OpenAI reports the call that compacted with its whole input, the context before it.
245
+ ...(response.usage && response.output.some(item => item.type === 'compaction')
246
+ ? { compactedContextTokens: response.usage.input_tokens }
247
+ : {}),
238
248
  };
239
249
  }
240
250
  catch (error) {
@@ -268,22 +278,18 @@ export class OpenAILLMClient {
268
278
  client;
269
279
  model;
270
280
  reasoningEffort;
271
- compactAt;
272
281
  systemPrompt;
273
282
  providerDataSource = openAISource;
274
283
  logger;
275
284
  // `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows
276
285
  // what OpenAI supports.
277
- constructor({ model, reasoningEffort = 'high', compactAt, systemPrompt, logger, }) {
286
+ constructor({ model, reasoningEffort = 'high', systemPrompt, logger, }) {
278
287
  if (!isOneOf(openAIModels, model)) {
279
288
  throw new InvalidAgentConfigError(`"${model}" is not an OpenAI model; expected one of: ${openAIModels.join(', ')}`);
280
289
  }
281
290
  if (!isOneOf(openAIReasoningEfforts, reasoningEffort)) {
282
291
  throw new InvalidAgentConfigError(`"${reasoningEffort}" is not an OpenAI reasoning effort; expected one of: ${openAIReasoningEfforts.join(', ')}`);
283
292
  }
284
- if (compactAt !== undefined && !(Number.isInteger(compactAt) && compactAt > 0)) {
285
- throw new InvalidAgentConfigError(`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`);
286
- }
287
293
  try {
288
294
  // The SDK's default retries stay on: they back off and honour `Retry-After`, which
289
295
  // `RetryingAgent` does not. See "The provider SDKs keep their transport retries" in decisions.md.
@@ -297,14 +303,19 @@ export class OpenAILLMClient {
297
303
  }
298
304
  this.model = model;
299
305
  this.reasoningEffort = reasoningEffort;
300
- this.compactAt = compactAt;
301
306
  this.systemPrompt = systemPrompt;
302
307
  this.logger = logger;
303
308
  }
304
309
  supportsNative(tool) {
305
310
  return tool === 'applyPatch';
306
311
  }
307
- async send({ context, tools }, signal) {
312
+ checkCompactAt(compactAt) {
313
+ if (!(Number.isInteger(compactAt) && compactAt > 0)) {
314
+ throw new InvalidAgentConfigError(`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`);
315
+ }
316
+ }
317
+ async send({ context, tools, compactAt, }, signal) {
318
+ const threshold = compactAt === 'now' ? compactNowAt : compactAt;
308
319
  let response;
309
320
  const applyPatch = applyPatchName(tools);
310
321
  try {
@@ -316,8 +327,8 @@ export class OpenAILLMClient {
316
327
  // Left out when empty, so a request without tools stays as it always was.
317
328
  ...(tools.length > 0 && { tools: tools.map(toOpenAITool) }),
318
329
  // OpenAI compacts inside the call that passes it, and answers with the compaction first.
319
- ...(this.compactAt !== undefined && {
320
- context_management: [{ type: 'compaction', compact_threshold: this.compactAt }],
330
+ ...(threshold !== undefined && {
331
+ context_management: [{ type: 'compaction', compact_threshold: threshold }],
321
332
  }),
322
333
  store: false,
323
334
  reasoning: { effort: this.reasoningEffort, summary: 'concise' },
@@ -1 +1 @@
1
- {"version":3,"file":"openAILLMClient.js","sourceRoot":"","s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C,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAC3D,aAAa,CAAC,OAAO,EAAE,UAAU,CAAC,CAClC;gBACD,0EAA0E;gBAC1E,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC3D,yFAAyF;gBACzF,GAAG,CAAC,IAAI,CAAC,SAAS,KAAK,SAAS,IAAI;oBACnC,kBAAkB,EAAE,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,iBAAiB,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;iBAC/E,CAAC;gBACF,KAAK,EAAE,KAAK;gBACZ,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE;gBAC/D,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,EAAE,UAAU,CAAC,EACtD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tApplyPatchTool,\n\tFunctionTool,\n\tResponse,\n\tResponseApplyPatchToolCall,\n\tResponseCompactionItemParam,\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, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, 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. A call to the tool\n * offered as `apply_patch`, named `applyPatch` here, and its result go back as that tool's own\n * items.\n */\nfunction toOpenAIItems(\n\tpart: MessagePart,\n\trole: 'user' | 'assistant',\n\tapplyPatch: string | undefined,\n): 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\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call',\n\t\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\t\t// Kept as OpenAI sent it: the conversation holds the operation unchanged.\n\t\t\t\t\t\toperation: part.input as ResponseApplyPatchToolCall['operation'],\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\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\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call_output',\n\t\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t\tstatus: part.isError ? 'failed' : 'completed',\n\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\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 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseCompactionItemParam] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message, applyPatch: string | undefined): 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, applyPatch));\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. The native\n * `apply_patch` has OpenAI's own schema.\n */\nfunction toOpenAITool(definition: ToolDefinition): FunctionTool | ApplyPatchTool {\n\tconst native = nativeOf(definition);\n\tif (native === 'applyPatch') return { type: 'apply_patch' };\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`OpenAI has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/** The name the tool offered as `apply_patch` has in the conversation, if one is offered. */\nfunction applyPatchName(tools: ToolDefinition[]): string | undefined {\n\treturn tools.find(tool => nativeOf(tool) === 'applyPatch')?.name;\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(\n\titem: ResponseOutputItem,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): 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 'compaction': {\n\t\t\t// Encrypted: OpenAI's summary of the context before it, which it alone reads back.\n\t\t\tconst compaction: ResponseCompactionItemParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tid: item.id,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: openAISource, data: compaction }];\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\tcase 'apply_patch_call':\n\t\t\t// Only when `apply_patch` was offered; otherwise it is unexpected, as below.\n\t\t\tif (applyPatch !== undefined) {\n\t\t\t\treturn [{ type: 'toolCall', id: item.call_id, name: applyPatch, input: item.operation }];\n\t\t\t}\n\t\t\treturn unmapped(item, logger);\n\t\tdefault:\n\t\t\treturn unmapped(item, logger);\n\t}\n}\n\n/** An item this client does not map, which it reports and leaves out. */\nfunction unmapped(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\t// No other built-in tool is offered, so any other item is output this client does not expect.\n\ttreatErrors(\n\t\t() => {\n\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'OpenAI client logger failed while mapping a response',\n\t);\n\treturn [];\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(\n\tresponse: Response,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger, applyPatch)),\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 compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = openAISource;\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\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which OpenAI compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(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\t\tif (compactAt !== undefined && !(Number.isInteger(compactAt) && compactAt > 0)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`,\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.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'applyPatch';\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\t\tconst applyPatch = applyPatchName(tools);\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\t// The latest compaction carries everything before it, which OpenAI would only ignore.\n\t\t\t\t\tinput: sentContext(context, openAISource).flatMap(message =>\n\t\t\t\t\t\ttoOpenAIInput(message, applyPatch),\n\t\t\t\t\t),\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\t// OpenAI compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tcontext_management: [{ type: 'compaction', compact_threshold: this.compactAt }],\n\t\t\t\t\t}),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'concise' },\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, applyPatch),\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;AAa1C,OAAO,EACN,uBAAuB,EACvB,gBAAgB,EAChB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,uBAAu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MAAM,CAAC,SAAS,CAAC,MAAM,CAC5C;gBACC,KAAK,EAAE,IAAI,CAAC,KAAK;gBACjB,YAAY,EAAE,IAAI,CAAC,YAAY;gBAC/B,sFAAsF;gBACtF,KAAK,EAAE,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAC3D,aAAa,CAAC,OAAO,EAAE,UAAU,CAAC,CAClC;gBACD,0EAA0E;gBAC1E,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;gBAC3D,yFAAyF;gBACzF,GAAG,CAAC,SAAS,KAAK,SAAS,IAAI;oBAC9B,kBAAkB,EAAE,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,iBAAiB,EAAE,SAAS,EAAE,CAAC;iBAC1E,CAAC;gBACF,KAAK,EAAE,KAAK;gBACZ,SAAS,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE;gBAC/D,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,EAAE,UAAU,CAAC,EACtD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import OpenAI, { APIError } from 'openai';\nimport type { ReasoningEffort } from 'openai/resources/shared';\nimport type {\n\tApplyPatchTool,\n\tFunctionTool,\n\tResponse,\n\tResponseApplyPatchToolCall,\n\tResponseCompactionItemParam,\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, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, 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. A call to the tool\n * offered as `apply_patch`, named `applyPatch` here, and its result go back as that tool's own\n * items.\n */\nfunction toOpenAIItems(\n\tpart: MessagePart,\n\trole: 'user' | 'assistant',\n\tapplyPatch: string | undefined,\n): 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\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call',\n\t\t\t\t\t\tcall_id: part.id,\n\t\t\t\t\t\t// Kept as OpenAI sent it: the conversation holds the operation unchanged.\n\t\t\t\t\t\toperation: part.input as ResponseApplyPatchToolCall['operation'],\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\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\tif (part.name === applyPatch) {\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: 'apply_patch_call_output',\n\t\t\t\t\t\tcall_id: part.callId,\n\t\t\t\t\t\tstatus: part.isError ? 'failed' : 'completed',\n\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t}\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 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === openAISource ? [part.data as ResponseCompactionItemParam] : [];\n\t\tcase 'reasoning':\n\t\t\treturn [];\n\t\tcase 'contextSummary':\n\t\t\t// Never sent: the agent sends the context derived from it.\n\t\t\treturn [];\n\t}\n}\n\nfunction toOpenAIInput(message: Message, applyPatch: string | undefined): 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, applyPatch));\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. The native\n * `apply_patch` has OpenAI's own schema.\n */\nfunction toOpenAITool(definition: ToolDefinition): FunctionTool | ApplyPatchTool {\n\tconst native = nativeOf(definition);\n\tif (native === 'applyPatch') return { type: 'apply_patch' };\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`OpenAI has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { type: 'function', name, description, parameters: inputSchema, strict: true };\n}\n\n/** The name the tool offered as `apply_patch` has in the conversation, if one is offered. */\nfunction applyPatchName(tools: ToolDefinition[]): string | undefined {\n\treturn tools.find(tool => nativeOf(tool) === 'applyPatch')?.name;\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(\n\titem: ResponseOutputItem,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): 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 'compaction': {\n\t\t\t// Encrypted: OpenAI's summary of the context before it, which it alone reads back.\n\t\t\tconst compaction: ResponseCompactionItemParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tid: item.id,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: openAISource, data: compaction }];\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\tcase 'apply_patch_call':\n\t\t\t// Only when `apply_patch` was offered; otherwise it is unexpected, as below.\n\t\t\tif (applyPatch !== undefined) {\n\t\t\t\treturn [{ type: 'toolCall', id: item.call_id, name: applyPatch, input: item.operation }];\n\t\t\t}\n\t\t\treturn unmapped(item, logger);\n\t\tdefault:\n\t\t\treturn unmapped(item, logger);\n\t}\n}\n\n/** An item this client does not map, which it reports and leaves out. */\nfunction unmapped(item: ResponseOutputItem, logger: ILogger): MessagePart[] {\n\t// No other built-in tool is offered, so any other item is output this client does not expect.\n\ttreatErrors(\n\t\t() => {\n\t\t\tlogger.warn(item, 'OpenAI returned an output item the client does not map');\n\t\t},\n\t\tclassifyHostFailure,\n\t\t'OpenAI client logger failed while mapping a response',\n\t);\n\treturn [];\n}\n\n// The threshold that compacts a context now: far below what any of its models holds, so a\n// context that no longer fits has long passed it.\nconst compactNowAt = 50_000;\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(\n\tresponse: Response,\n\tlogger: ILogger,\n\tapplyPatch: string | undefined,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.output.flatMap(item => describeItem(item, logger, applyPatch)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t\t// OpenAI reports the call that compacted with its whole input, the context before it.\n\t\t\t...(response.usage && response.output.some(item => item.type === 'compaction')\n\t\t\t\t? { compactedContextTokens: response.usage.input_tokens }\n\t\t\t\t: {}),\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\treadonly systemPrompt: string;\n\treadonly providerDataSource = openAISource;\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\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\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'applyPatch';\n\t}\n\n\tcheckCompactAt(compactAt: number): void {\n\t\tif (!(Number.isInteger(compactAt) && compactAt > 0)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`compactAt must be a positive whole number of tokens, not ${String(compactAt)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync send(\n\t\t{\n\t\t\tcontext,\n\t\t\ttools,\n\t\t\tcompactAt,\n\t\t}: { context: Message[]; tools: ToolDefinition[]; compactAt?: number | 'now' | undefined },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tconst threshold = compactAt === 'now' ? compactNowAt : compactAt;\n\t\tlet response: Response;\n\t\tconst applyPatch = applyPatchName(tools);\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\t// The latest compaction carries everything before it, which OpenAI would only ignore.\n\t\t\t\t\tinput: sentContext(context, openAISource).flatMap(message =>\n\t\t\t\t\t\ttoOpenAIInput(message, applyPatch),\n\t\t\t\t\t),\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\t// OpenAI compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(threshold !== undefined && {\n\t\t\t\t\t\tcontext_management: [{ type: 'compaction', compact_threshold: threshold }],\n\t\t\t\t\t}),\n\t\t\t\t\tstore: false,\n\t\t\t\t\treasoning: { effort: this.reasoningEffort, summary: 'concise' },\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, applyPatch),\n\t\t\tclassifyLocalFailure,\n\t\t\t'OpenAI response mapping failed',\n\t\t);\n\t}\n}\n"]}
@@ -119,6 +119,7 @@ export type AgentTool = Tool | PreparingTool | DelegatingTool;
119
119
  export declare function isDelegating(tool: AgentTool): tool is DelegatingTool;
120
120
  /**
121
121
  * Brings any tool into the one lifecycle of prepare, approve, run. A consumer's `Tool` has its
122
- * risk judged now, and later runs on the input as the model sent it.
122
+ * risk judged now, and later runs on the input as the model sent it; one that is not `safe` is
123
+ * refused for an agent started by an agent that only reads.
123
124
  */
124
125
  export declare function prepareCall(tool: Tool | PreparingTool, input: unknown, signal: AbortSignal, call: ToolCallContext): Promise<PreparedCall>;
@@ -30,12 +30,18 @@ function isPreparing(tool) {
30
30
  }
31
31
  /**
32
32
  * Brings any tool into the one lifecycle of prepare, approve, run. A consumer's `Tool` has its
33
- * risk judged now, and later runs on the input as the model sent it.
33
+ * risk judged now, and later runs on the input as the model sent it; one that is not `safe` is
34
+ * refused for an agent started by an agent that only reads.
34
35
  */
35
36
  export async function prepareCall(tool, input, signal, call) {
36
37
  if (isPreparing(tool))
37
38
  return tool.prepare(input, signal, call);
38
39
  const risk = tool.risk(input);
40
+ // Where a consumer's tool writes is unknown, so under an agent that only reads, one that may
41
+ // write is refused whole. Under one that writes, it writes where the consumer let it.
42
+ if (risk !== 'safe' && call.writeCeiling?.length === 0) {
43
+ throw new Error(`Nothing was changed: the agent that handed you this task only reads, and ${tool.name} may change things. An agent another agent started never writes more than that agent may. Answer with what you found, and say what you would have changed.`);
44
+ }
39
45
  return { risk, unrecorded: true, run: runSignal => tool.execute(input, runSignal) };
40
46
  }
41
47
  //# sourceMappingURL=preparedCall.js.map