@mikode13/harness 6.3.0 → 6.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -132,6 +132,14 @@ function describeBlock(block, logger) {
132
132
  case 'tool_use':
133
133
  return [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];
134
134
  case 'compaction': {
135
+ // A compaction that failed, with no summary. Claude reads one sent back as if it were not
136
+ // there, so it is left out: the context goes on whole, and Claude compacts again later.
137
+ if (!block.content) {
138
+ treatErrors(() => {
139
+ logger.warn('Claude could not compact the conversation; it is sent whole until Claude compacts it');
140
+ }, classifyHostFailure, 'Claude client logger failed while mapping a response');
141
+ return [];
142
+ }
135
143
  // Claude's summary of the context before it, readable, with what it alone reads back.
136
144
  const compaction = {
137
145
  type: 'compaction',
@@ -197,7 +205,11 @@ function toTokens(usage, logger) {
197
205
  outputTokens: usage.output_tokens,
198
206
  };
199
207
  }
200
- function toLLMResponse(response, logger) {
208
+ /**
209
+ * @param summaries each compaction's summary as it was streamed, by the index of its block. The
210
+ * SDK joins a delta that carries none as the text "null", so the final message cannot tell.
211
+ */
212
+ function toLLMResponse(response, logger, summaries) {
201
213
  let usage;
202
214
  try {
203
215
  // Inside the try: it warns when the usage is missing, and that warning can throw too.
@@ -205,7 +217,12 @@ function toLLMResponse(response, logger) {
205
217
  return {
206
218
  message: {
207
219
  role: 'assistant',
208
- content: response.content.flatMap(block => describeBlock(block, logger)),
220
+ content: response.content.flatMap((block, index) => {
221
+ const summary = summaries.get(index);
222
+ return describeBlock(block.type === 'compaction' && summary !== undefined
223
+ ? { ...block, content: summary }
224
+ : block, logger);
225
+ }),
209
226
  },
210
227
  usage,
211
228
  stopReason: toStopReason(response),
@@ -317,6 +334,8 @@ export class ClaudeLLMClient {
317
334
  async send({ context, tools }, signal) {
318
335
  let response;
319
336
  let stream;
337
+ // What each compaction streamed of its summary, by block index, its missing parts left out.
338
+ const summaries = new Map();
320
339
  try {
321
340
  // Streamed only to lift the timeout: the client still answers with the whole message.
322
341
  const sent = this.client.beta.messages.stream({
@@ -354,6 +373,15 @@ export class ClaudeLLMClient {
354
373
  }),
355
374
  }, { signal });
356
375
  stream = sent;
376
+ sent.on('streamEvent', event => {
377
+ if (event.type === 'content_block_start' && event.content_block.type === 'compaction') {
378
+ summaries.set(event.index, event.content_block.content ?? '');
379
+ }
380
+ else if (event.type === 'content_block_delta' &&
381
+ event.delta.type === 'compaction_delta') {
382
+ summaries.set(event.index, (summaries.get(event.index) ?? '') + (event.delta.content ?? ''));
383
+ }
384
+ });
357
385
  response = await sent.finalMessage();
358
386
  }
359
387
  catch (error) {
@@ -365,7 +393,7 @@ export class ClaudeLLMClient {
365
393
  // never finished sending, so the run's count cannot be known.
366
394
  throw connected ? withSpentTokens(failure, undefined, true) : failure;
367
395
  }
368
- return treatErrors(() => toLLMResponse(response, this.logger), classifyLocalFailure, 'Claude response mapping failed');
396
+ return treatErrors(() => toLLMResponse(response, this.logger, summaries), classifyLocalFailure, 'Claude response mapping failed');
369
397
  }
370
398
  }
371
399
  //# sourceMappingURL=claudeLLMClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"claudeLLMClient.js","sourceRoot":"","sources":["../../../src/llm/infrastructure/claudeLLMClient.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,EAAE,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAgBxE,OAAO,EACN,uBAAuB,EACvB,kBAAkB,EAClB,eAAe,GACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACN,mBAAmB,EACnB,oBAAoB,EACpB,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,QAA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C5C,MAAM,OAAO,GAAG,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACxD,uFAAuF;YACvF,8DAA8D;YAC9D,MAAM,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,EAC1C,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku runs without thinking: it has no adaptive thinking\n// and takes no reasoning effort, and it is here for short, simple calls such as a summary.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet', 'haiku'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n\thaiku: 'claude-haiku-4-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. 64,000 is the most Haiku 4.5 writes; the\n// other models write up to 128,000, which a single answer here has not needed.\nconst maxOutputTokens = 64_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\nfunction toLLMResponse(response: AnthropicMessage, logger: ILogger): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap(block => describeBlock(block, logger)),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\t// Missing for Haiku, which runs without thinking.\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort | undefined;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which Anthropic compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (model === 'haiku' && reasoningEffort !== undefined) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t'Claude Haiku takes no reasoning effort: it runs without thinking',\n\t\t\t);\n\t\t}\n\t\tconst effort = model === 'haiku' ? undefined : (reasoningEffort ?? 'high');\n\t\tif (effort !== undefined && !isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined) {\n\t\t\t// The alias names Claude Haiku 4.5, which Anthropic does not compact.\n\t\t\tif (model === 'haiku') {\n\t\t\t\tthrow new InvalidAgentConfigError('Claude Haiku cannot compact: leave compactAt out');\n\t\t\t}\n\t\t\tif (!(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\tthis.compactAt === undefined || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\t\t\t\tmessages: sentContext(context, claudeSource).flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\t// Haiku has no adaptive thinking, and an effort is refused with a 400.\n\t\t\t\t\t...(this.reasoningEffort !== undefined && {\n\t\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t}),\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tbetas: [compactionBeta],\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: this.compactAt },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\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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AAC,KAAK,CAAC,OAAO,IAAI,EAAE,CAAC,CAChE,CAAC;gBACH,CAAC;YACF,CAAC,CAAC,CAAC;YACH,QAAQ,GAAG,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,mFAAmF;YACnF,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC5C,MAAM,OAAO,GAAG,qBAAqB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;YACxD,uFAAuF;YACvF,8DAA8D;YAC9D,MAAM,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QACvE,CAAC;QAED,OAAO,WAAW,CACjB,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EACrD,oBAAoB,EACpB,gCAAgC,CAChC,CAAC;IACH,CAAC;CACD","sourcesContent":["import Anthropic, { AnthropicError, APIError } from '@anthropic-ai/sdk';\nimport type { BetaMessageStream } from '@anthropic-ai/sdk/lib/BetaMessageStream';\n// The beta surface, for compaction: without its beta header, a request is the stable one.\nimport type {\n\tBetaCompactionBlockParam as CompactionBlockParam,\n\tBetaContentBlock as ContentBlock,\n\tBetaContentBlockParam as ContentBlockParam,\n\tBetaMessage as AnthropicMessage,\n\tBetaMessageParam as MessageParam,\n\tBetaOutputConfig as OutputConfig,\n\tBetaRedactedThinkingBlockParam as RedactedThinkingBlockParam,\n\tBetaThinkingBlockParam as ThinkingBlockParam,\n\tBetaTool as ClaudeTool,\n\tBetaToolTextEditor20250728 as ToolTextEditor20250728,\n\tBetaUsage as Usage,\n} from '@anthropic-ai/sdk/resources/beta/messages/messages';\nimport {\n\tInvalidAgentConfigError,\n\tUnrecoverableError,\n\twithSpentTokens,\n} from '#src/shared/domain/errors';\nimport {\n\tclassifyHostFailure,\n\tclassifyLocalFailure,\n\tclassifyProviderFailure,\n\tdescribeFailure,\n\ttreatErrors,\n} from '#src/shared/domain/providerFailure';\nimport { isOneOf } from '#src/shared/domain/isOneOf';\nimport type { ILogger } from '#src/shared/domain/logger';\nimport type { Tokens } from '#src/shared/domain/tokens';\nimport { MaxContextError } from '../domain/errors.ts';\nimport type { LLMClient, LLMResponse, StopReason } from '../domain/llm.ts';\nimport { type Message, type MessagePart, sentContext } from '../domain/message.ts';\nimport { type NativeTool, nativeOf, type ToolDefinition } from '../domain/tool.ts';\n\n// The Messages API takes full model IDs. Callers name a model by the Agent SDK's alias, so both\n// paths share one vocabulary; this table pins the ID each alias means here, and moves by hand\n// when Anthropic releases a newer model. Haiku runs without thinking: it has no adaptive thinking\n// and takes no reasoning effort, and it is here for short, simple calls such as a summary.\nexport const claudeLLMModels = ['opus', 'fable', 'sonnet', 'haiku'] as const;\nexport type ClaudeLLMModel = (typeof claudeLLMModels)[number];\n\nconst claudeLLMModelIds = {\n\topus: 'claude-opus-5-5',\n\tfable: 'claude-fable-5-1',\n\tsonnet: 'claude-sonnet-5',\n\thaiku: 'claude-haiku-4-5',\n} as const satisfies Record<ClaudeLLMModel, string>;\n\nexport const claudeLLMReasoningEfforts = [\n\t'low',\n\t'medium',\n\t'high',\n\t'xhigh',\n\t'max',\n] as const satisfies readonly NonNullable<OutputConfig['effort']>[];\nexport type ClaudeLLMReasoningEffort = (typeof claudeLLMReasoningEfforts)[number];\n\n// Adaptive thinking spends from this budget too, so a hard step at a high effort can need most\n// of it. The request is streamed so it is not bound by the SDK's ten-minute timeout, which made\n// it refuse more than about 21,000 without a stream. 64,000 is the most Haiku 4.5 writes; the\n// other models write up to 128,000, which a single answer here has not needed.\nconst maxOutputTokens = 64_000;\n\n// The request itself is wrong or not allowed, so sending it again cannot succeed.\nconst unrecoverableStatuses = [400, 401, 403, 404, 413, 422];\n\n// The account is out of credit, or its key cannot make the request. Resending cannot fix\n// either, whatever status the error arrives with.\nconst unrecoverableErrorTypes = ['billing_error', 'authentication_error', 'permission_error'];\n\n// This client's label on the thinking blocks it keeps for replay; see `ProviderDataPart`.\nconst claudeSource = 'claude';\n\n// Anthropic's compaction at a token threshold, and the least threshold it accepts.\nconst compactionBeta = 'compact-2026-01-12';\nconst minCompactAt = 50_000;\n\n/**\n * Anthropic rejects a `tool_use` whose input is not an object, with a 400 on every later call.\n * Another provider's call can hold anything else, such as OpenAI arguments that did not parse;\n * its result already told the model the call failed, so sending it as empty loses nothing.\n */\nfunction toClaudeInputObject(input: unknown): unknown {\n\treturn typeof input === 'object' && input !== null && !Array.isArray(input) ? input : {};\n}\n\n/** Thinking crosses back only as the signed block this client kept, never as its text. */\nfunction toClaudeBlocks(part: MessagePart): ContentBlockParam[] {\n\tswitch (part.type) {\n\t\tcase 'text':\n\t\t\t// The API rejects an empty text block.\n\t\t\treturn part.text ? [{ type: 'text', text: part.text }] : [];\n\t\tcase 'toolCall':\n\t\t\treturn [\n\t\t\t\t{ type: 'tool_use', id: part.id, name: part.name, input: toClaudeInputObject(part.input) },\n\t\t\t];\n\t\tcase 'toolResult':\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\ttype: 'tool_result',\n\t\t\t\t\ttool_use_id: part.callId,\n\t\t\t\t\tcontent: part.output,\n\t\t\t\t\tis_error: part.isError,\n\t\t\t\t},\n\t\t\t];\n\t\tcase 'providerData':\n\t\t\t// Another provider's block would be rejected; losing it only costs that provider's reasoning.\n\t\t\treturn part.source === claudeSource\n\t\t\t\t? [part.data as ThinkingBlockParam | RedactedThinkingBlockParam]\n\t\t\t\t: [];\n\t\tcase 'compaction':\n\t\t\t// Another provider's summary means nothing here; this client sends the turns it replaced.\n\t\t\treturn part.source === claudeSource ? [part.data as CompactionBlockParam] : [];\n\t\tcase 'reasoning':\n\t\t\t// Unsigned text cannot be replayed as thinking. The API accepts a turn without it.\n\t\t\treturn [];\n\t}\n}\n\n/**\n * Tool results travel in a user turn, as the API requires. A message left with no blocks is\n * left out whole; the API joins the consecutive user turns that leaves.\n */\nfunction toClaudeInput(message: Message): MessageParam[] {\n\tconst content = message.content.flatMap(toClaudeBlocks);\n\tif (content.length === 0) {\n\t\treturn [];\n\t}\n\n\treturn [{ role: message.role === 'tool' ? 'user' : message.role, content }];\n}\n\n// Anthropic fixes the text editor's name: its calls arrive under it.\nconst textEditorName = 'str_replace_based_edit_tool';\n\n/**\n * Strict: the API constrains the model to the schema, so its input always parses and matches.\n * A schema outside what strict mode supports fails the request with a 400. The native text\n * editor has Anthropic's own schema, and its calls and results are ordinary tool blocks.\n */\nfunction toClaudeTool(definition: ToolDefinition): ClaudeTool | ToolTextEditor20250728 {\n\tconst native = nativeOf(definition);\n\tif (native === 'textEditor') {\n\t\tif (definition.name !== textEditorName) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`Claude's text editor must be named \"${textEditorName}\", not \"${definition.name}\"`,\n\t\t\t);\n\t\t}\n\t\treturn { type: 'text_editor_20250728', name: textEditorName };\n\t}\n\tif (native !== undefined) {\n\t\tthrow new InvalidAgentConfigError(`Claude has no native tool \"${native}\"`);\n\t}\n\tconst { name, description, inputSchema } = definition;\n\treturn { name, description, input_schema: inputSchema, strict: true };\n}\n\nfunction describeBlock(block: ContentBlock, logger: ILogger): MessagePart[] {\n\tswitch (block.type) {\n\t\tcase 'text':\n\t\t\treturn [{ type: 'text', text: block.text }];\n\t\tcase 'thinking': {\n\t\t\t// Kept signed for replay; the summarized text is only for narration.\n\t\t\tconst signed: ThinkingBlockParam = {\n\t\t\t\ttype: 'thinking',\n\t\t\t\tthinking: block.thinking,\n\t\t\t\tsignature: block.signature,\n\t\t\t};\n\t\t\tconst replay: MessagePart = { type: 'providerData', source: claudeSource, data: signed };\n\t\t\treturn block.thinking ? [{ type: 'reasoning', text: block.thinking }, replay] : [replay];\n\t\t}\n\t\tcase 'redacted_thinking': {\n\t\t\t// Encrypted by design: nothing to narrate, but it still goes back.\n\t\t\tconst redacted: RedactedThinkingBlockParam = { type: 'redacted_thinking', data: block.data };\n\t\t\treturn [{ type: 'providerData', source: claudeSource, data: redacted }];\n\t\t}\n\t\tcase 'tool_use':\n\t\t\treturn [{ type: 'toolCall', id: block.id, name: block.name, input: block.input }];\n\t\tcase 'compaction': {\n\t\t\t// A compaction that failed, with no summary. Claude reads one sent back as if it were not\n\t\t\t// there, so it is left out: the context goes on whole, and Claude compacts again later.\n\t\t\tif (!block.content) {\n\t\t\t\ttreatErrors(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\t'Claude could not compact the conversation; it is sent whole until Claude compacts it',\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\tclassifyHostFailure,\n\t\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t\t);\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\t// Claude's summary of the context before it, readable, with what it alone reads back.\n\t\t\tconst compaction: CompactionBlockParam = {\n\t\t\t\ttype: 'compaction',\n\t\t\t\tcontent: block.content,\n\t\t\t\tencrypted_content: block.encrypted_content,\n\t\t\t};\n\t\t\treturn [{ type: 'compaction', source: claudeSource, data: compaction }];\n\t\t}\n\t\tdefault:\n\t\t\t// Server tools are never offered, so any other block is output this client does not expect.\n\t\t\ttreatErrors(\n\t\t\t\t() => {\n\t\t\t\t\tlogger.warn(block, 'Claude returned a content block the client does not map');\n\t\t\t\t},\n\t\t\t\tclassifyHostFailure,\n\t\t\t\t'Claude client logger failed while mapping a response',\n\t\t\t);\n\t\t\treturn [];\n\t}\n}\n\nfunction toStopReason(response: AnthropicMessage): StopReason {\n\tswitch (response.stop_reason) {\n\t\t// `tool_use` is a complete answer that asks for tools: running them is the agent's call.\n\t\tcase 'end_turn':\n\t\tcase 'tool_use':\n\t\t\treturn 'completed';\n\t\tcase 'max_tokens':\n\t\t\treturn 'truncated';\n\t\tcase 'refusal':\n\t\t\treturn 'refused';\n\t\tcase 'model_context_window_exceeded':\n\t\t\tthrow new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: 'The response stopped at the model context window.',\n\t\t\t});\n\t\tdefault:\n\t\t\t// `pause_turn` and `stop_sequence` need server tools or stop sequences, and this\n\t\t\t// client sends neither.\n\t\t\tthrow new UnrecoverableError('The Claude response stopped unexpectedly', {\n\t\t\t\tcause: `The response stopped with \"${response.stop_reason ?? 'unknown'}\".`,\n\t\t\t});\n\t}\n}\n\n/**\n * Unlike OpenAI, Anthropic counts cache reads and writes apart from `input_tokens`. A call that\n * compacted leaves the compaction out of its totals, so with iterations their sum is the bill.\n */\nfunction toTokens(usage: Usage | undefined, logger: ILogger): Tokens | undefined {\n\tif (!usage) {\n\t\t// Zeros would report a call that may have been billed as free.\n\t\ttreatErrors(\n\t\t\t() => {\n\t\t\t\tlogger.warn('Claude returned a response without usage; it cannot be accounted for');\n\t\t\t},\n\t\t\tclassifyHostFailure,\n\t\t\t'Claude client logger failed while reading usage',\n\t\t);\n\t\treturn undefined;\n\t}\n\n\tif (usage.iterations && usage.iterations.length > 0) {\n\t\treturn usage.iterations.reduce<Tokens>(\n\t\t\t(sum, iteration) => ({\n\t\t\t\tinputTokens: sum.inputTokens + iteration.input_tokens,\n\t\t\t\treadCacheTokens: sum.readCacheTokens + iteration.cache_read_input_tokens,\n\t\t\t\twrittenCacheTokens: sum.writtenCacheTokens + iteration.cache_creation_input_tokens,\n\t\t\t\toutputTokens: sum.outputTokens + iteration.output_tokens,\n\t\t\t}),\n\t\t\t{ inputTokens: 0, readCacheTokens: 0, writtenCacheTokens: 0, outputTokens: 0 },\n\t\t);\n\t}\n\treturn {\n\t\tinputTokens: usage.input_tokens,\n\t\treadCacheTokens: usage.cache_read_input_tokens ?? 0,\n\t\twrittenCacheTokens: usage.cache_creation_input_tokens ?? 0,\n\t\toutputTokens: usage.output_tokens,\n\t};\n}\n\n/**\n * @param summaries each compaction's summary as it was streamed, by the index of its block. The\n * SDK joins a delta that carries none as the text \"null\", so the final message cannot tell.\n */\nfunction toLLMResponse(\n\tresponse: AnthropicMessage,\n\tlogger: ILogger,\n\tsummaries: ReadonlyMap<number, string>,\n): LLMResponse {\n\tlet usage: Tokens | undefined;\n\n\ttry {\n\t\t// Inside the try: it warns when the usage is missing, and that warning can throw too.\n\t\tusage = toTokens(response.usage, logger);\n\t\treturn {\n\t\t\tmessage: {\n\t\t\t\trole: 'assistant',\n\t\t\t\tcontent: response.content.flatMap((block, index) => {\n\t\t\t\t\tconst summary = summaries.get(index);\n\t\t\t\t\treturn describeBlock(\n\t\t\t\t\t\tblock.type === 'compaction' && summary !== undefined\n\t\t\t\t\t\t\t? { ...block, content: summary }\n\t\t\t\t\t\t\t: block,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t},\n\t\t\tusage,\n\t\t\tstopReason: toStopReason(response),\n\t\t};\n\t} catch (error) {\n\t\t// The call was billed whether the response failed or a logger did while mapping it, and\n\t\t// an answer without usage leaves the run's count unknown.\n\t\tthrow withSpentTokens(error, usage, !response.usage);\n\t}\n}\n\n/**\n * The SDK resolves credentials lazily, so a missing key surfaces on the first call, as a plain\n * `Error` the SDK gives no class of its own. Before the stream connects, an `AnthropicError` that\n * is not an `APIError` never carries an answer from the API: it is the SDK refusing to make the\n * call, such as an unresolved profile. Once it connects, the stream reports any failure as one,\n * such as a connection lost halfway; see `classifyClaudeFailure`.\n */\nfunction isLocalSDKFailure(error: unknown): boolean {\n\treturn (\n\t\t(error instanceof AnthropicError && !(error instanceof APIError)) ||\n\t\t(error instanceof Error && error.message.startsWith('Could not resolve authentication method'))\n\t);\n}\n\n/** `connected` is whether the stream had its response: a failure after that broke the stream off. */\nfunction classifyClaudeFailure(error: unknown, connected: boolean): Error {\n\tif (connected && !(error instanceof APIError)) {\n\t\t// The API was answering, so a later attempt can succeed. An error event the API sends\n\t\t// mid-stream, such as an overload, arrives as an `APIError` and is classified below.\n\t\treturn classifyProviderFailure(error, 'The Claude stream broke off');\n\t}\n\tif (isLocalSDKFailure(error)) {\n\t\t// The API never answered, and calling again would fail the same way.\n\t\treturn new UnrecoverableError('The Claude client cannot send the request', {\n\t\t\tcause: describeFailure(error),\n\t\t});\n\t}\n\tif (error instanceof APIError) {\n\t\t// Anthropic gives an overlong prompt no code of its own, only a 400 with this message.\n\t\tif (error.status === 400 && error.message.includes('prompt is too long')) {\n\t\t\treturn new MaxContextError('The context no longer fits the Claude model', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t\tif (\n\t\t\tunrecoverableErrorTypes.some(type => type === error.type) ||\n\t\t\tunrecoverableStatuses.some(status => status === error.status)\n\t\t) {\n\t\t\treturn new UnrecoverableError('Claude rejected the request', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\t}\n\n\t// A rate limit, an overload (529), a 5xx or a network failure: a later attempt can succeed.\n\treturn classifyProviderFailure(error, 'The Claude request failed');\n}\n\n/**\n * A stateless `LLMClient` on the Anthropic Messages API, which keeps nothing between calls:\n * every call carries the whole context, so the conversation is MiKode's, not the provider's.\n */\nexport class ClaudeLLMClient implements LLMClient {\n\tprivate readonly client: Anthropic;\n\tprivate readonly model: (typeof claudeLLMModelIds)[ClaudeLLMModel];\n\t// Missing for Haiku, which runs without thinking.\n\tprivate readonly reasoningEffort: ClaudeLLMReasoningEffort | undefined;\n\tprivate readonly compactAt: number | undefined;\n\treadonly systemPrompt: string;\n\treadonly providerDataSource = claudeSource;\n\tprivate readonly logger: ILogger;\n\n\t// `model` and `reasoningEffort` are untyped on purpose: this adapter is the one that knows\n\t// what Claude supports.\n\tconstructor({\n\t\tmodel,\n\t\treasoningEffort,\n\t\tcompactAt,\n\t\tsystemPrompt,\n\t\tlogger,\n\t}: {\n\t\tmodel: string;\n\t\treasoningEffort?: string;\n\t\t/** The input tokens at which Anthropic compacts the context on its side. Without it, never. */\n\t\tcompactAt?: number | undefined;\n\t\tsystemPrompt: string;\n\t\tlogger: ILogger;\n\t}) {\n\t\tif (!isOneOf(claudeLLMModels, model)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${model}\" is not a Claude API model; expected one of: ${claudeLLMModels.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (model === 'haiku' && reasoningEffort !== undefined) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t'Claude Haiku takes no reasoning effort: it runs without thinking',\n\t\t\t);\n\t\t}\n\t\tconst effort = model === 'haiku' ? undefined : (reasoningEffort ?? 'high');\n\t\tif (effort !== undefined && !isOneOf(claudeLLMReasoningEfforts, effort)) {\n\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t`\"${effort}\" is not a Claude API reasoning effort; expected one of: ${claudeLLMReasoningEfforts.join(', ')}`,\n\t\t\t);\n\t\t}\n\t\tif (compactAt !== undefined) {\n\t\t\t// The alias names Claude Haiku 4.5, which Anthropic does not compact.\n\t\t\tif (model === 'haiku') {\n\t\t\t\tthrow new InvalidAgentConfigError('Claude Haiku cannot compact: leave compactAt out');\n\t\t\t}\n\t\t\tif (!(Number.isInteger(compactAt) && compactAt >= minCompactAt)) {\n\t\t\t\tthrow new InvalidAgentConfigError(\n\t\t\t\t\t`compactAt must be a whole number of tokens of at least ${String(minCompactAt)} on Claude, not ${String(compactAt)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// The SDK's default retries stay on, as OpenAI's do. See \"The provider SDKs keep their\n\t\t\t// transport retries under RetryingAgent\" in decisions.md.\n\t\t\tthis.client = new Anthropic();\n\t\t} catch (error) {\n\t\t\t// Conflicting credential options, for example: building it again cannot fix them. A\n\t\t\t// missing key does not fail here but on the first call; see `isLocalSDKFailure`.\n\t\t\tthrow new UnrecoverableError('The Claude client could not be set up', {\n\t\t\t\tcause: describeFailure(error),\n\t\t\t});\n\t\t}\n\n\t\tthis.model = claudeLLMModelIds[model];\n\t\tthis.reasoningEffort = effort;\n\t\tthis.compactAt = compactAt;\n\t\tthis.systemPrompt = systemPrompt;\n\t\tthis.logger = logger;\n\t}\n\n\tsupportsNative(tool: NativeTool): boolean {\n\t\treturn tool === 'textEditor';\n\t}\n\n\tasync send(\n\t\t{ context, tools }: { context: Message[]; tools: ToolDefinition[] },\n\t\tsignal: AbortSignal,\n\t): Promise<LLMResponse> {\n\t\tlet response: AnthropicMessage;\n\t\tlet stream: BetaMessageStream | undefined;\n\t\t// What each compaction streamed of its summary, by block index, its missing parts left out.\n\t\tconst summaries = new Map<number, string>();\n\n\t\ttry {\n\t\t\t// Streamed only to lift the timeout: the client still answers with the whole message.\n\t\t\tconst sent = this.client.beta.messages.stream(\n\t\t\t\t{\n\t\t\t\t\tmodel: this.model,\n\t\t\t\t\tmax_tokens: maxOutputTokens,\n\t\t\t\t\t// A compaction changes the conversation's first block, so the cache would otherwise\n\t\t\t\t\t// keep nothing: this keeps the system prompt cached across it. The API rejects an\n\t\t\t\t\t// empty text block, and an empty prompt has nothing to cache.\n\t\t\t\t\tsystem:\n\t\t\t\t\t\tthis.compactAt === undefined || this.systemPrompt === ''\n\t\t\t\t\t\t\t? this.systemPrompt\n\t\t\t\t\t\t\t: [{ type: 'text', text: this.systemPrompt, cache_control: { type: 'ephemeral' } }],\n\t\t\t\t\t// The latest compaction carries everything before it, which Anthropic would only ignore.\n\t\t\t\t\tmessages: sentContext(context, claudeSource).flatMap(toClaudeInput),\n\t\t\t\t\t// Left out when empty, so a request without tools stays as it always was.\n\t\t\t\t\t...(tools.length > 0 && { tools: tools.map(toClaudeTool) }),\n\t\t\t\t\t// Haiku has no adaptive thinking, and an effort is refused with a 400.\n\t\t\t\t\t...(this.reasoningEffort !== undefined && {\n\t\t\t\t\t\tthinking: { type: 'adaptive', display: 'summarized' },\n\t\t\t\t\t\toutput_config: { effort: this.reasoningEffort },\n\t\t\t\t\t}),\n\t\t\t\t\t// Anthropic caches only on request. This marks the last block, so the next call\n\t\t\t\t\t// reads everything before it from the cache instead of paying for it again.\n\t\t\t\t\tcache_control: { type: 'ephemeral' },\n\t\t\t\t\t// Anthropic compacts inside the call that passes it, and answers with the compaction first.\n\t\t\t\t\t...(this.compactAt !== undefined && {\n\t\t\t\t\t\tbetas: [compactionBeta],\n\t\t\t\t\t\tcontext_management: {\n\t\t\t\t\t\t\tedits: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: 'compact_20260112',\n\t\t\t\t\t\t\t\t\ttrigger: { type: 'input_tokens', value: this.compactAt },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\t{ signal },\n\t\t\t);\n\t\t\tstream = sent;\n\t\t\tsent.on('streamEvent', event => {\n\t\t\t\tif (event.type === 'content_block_start' && event.content_block.type === 'compaction') {\n\t\t\t\t\tsummaries.set(event.index, event.content_block.content ?? '');\n\t\t\t\t} else if (\n\t\t\t\t\tevent.type === 'content_block_delta' &&\n\t\t\t\t\tevent.delta.type === 'compaction_delta'\n\t\t\t\t) {\n\t\t\t\t\tsummaries.set(\n\t\t\t\t\t\tevent.index,\n\t\t\t\t\t\t(summaries.get(event.index) ?? '') + (event.delta.content ?? ''),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t});\n\t\t\tresponse = await sent.finalMessage();\n\t\t} catch (error) {\n\t\t\t// The SDK's abort error is named 'Error', so it would pass for a provider failure.\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst connected = Boolean(stream?.response);\n\t\t\tconst failure = classifyClaudeFailure(error, connected);\n\t\t\t// Once the stream connected, Claude may have written, and billed, part of an answer it\n\t\t\t// never finished sending, so the run's count cannot be known.\n\t\t\tthrow connected ? withSpentTokens(failure, undefined, true) : failure;\n\t\t}\n\n\t\treturn treatErrors(\n\t\t\t() => toLLMResponse(response, this.logger, summaries),\n\t\t\tclassifyLocalFailure,\n\t\t\t'Claude response mapping failed',\n\t\t);\n\t}\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mikode13/harness",
3
- "version": "6.3.0",
3
+ "version": "6.3.1",
4
4
  "description": "Test/agent harness utility",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",