@yolk-sdk/agent 0.1.0-canary.55 → 0.1.0-canary.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/providers/anthropic/claude-provider.d.mts.map +1 -1
- package/dist/providers/anthropic/claude-provider.mjs +111 -42
- package/dist/providers/anthropic/claude-provider.mjs.map +1 -1
- package/dist/skillset/merge.d.mts +2 -2
- package/package.json +1 -1
- package/src/providers/anthropic/claude-provider.ts +189 -73
package/README.md
CHANGED
|
@@ -129,6 +129,15 @@ configuration. Anthropic Claude forwards `low`, `medium`, `high`, and `xhigh` th
|
|
|
129
129
|
`output_config.effort`. It omits `minimal`, which Anthropic does not support. Hosts remain
|
|
130
130
|
responsible for choosing an effort accepted by the selected provider and model.
|
|
131
131
|
|
|
132
|
+
### Anthropic tool schemas
|
|
133
|
+
|
|
134
|
+
Claude subscription OAuth rejects some valid JSON Schema constructs that Effect Schema can emit
|
|
135
|
+
for unions, refinements, and tuples. The Claude adapter therefore projects tool parameters to a
|
|
136
|
+
provider-compatible object schema without `anyOf`, `oneOf`, `allOf`, or tuple-only `prefixItems`.
|
|
137
|
+
When a constraint cannot be represented faithfully, the projection widens the model-facing schema
|
|
138
|
+
rather than excluding a valid call. Tool execution remains safe because `makeTool` validates the
|
|
139
|
+
returned arguments against the original Effect Schema before invoking the executor.
|
|
140
|
+
|
|
132
141
|
## Provider failures and retries
|
|
133
142
|
|
|
134
143
|
Provider adapters classify safe failure metadata at the boundary. The loop owns bounded retry
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-provider.d.mts","names":[],"sources":["../../../src/providers/anthropic/claude-provider.ts"],"mappings":";;;;;;KAoDY,6BAAA;EAAA,SACD,KAAA,EAAO,gBAAA;EAAA,SACP,WAAA;EAAA,SACA,SAAA;EAAA,SACA,YAAA,GAAe,QAAA,CAAS,MAAA;AAAA;AAAA,KAG9B,kBAAA;EAAA,SACM,IAA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Q,aAAA,CAAc,aAAA;AAAA;AAAA,
|
|
1
|
+
{"version":3,"file":"claude-provider.d.mts","names":[],"sources":["../../../src/providers/anthropic/claude-provider.ts"],"mappings":";;;;;;KAoDY,6BAAA;EAAA,SACD,KAAA,EAAO,gBAAA;EAAA,SACP,WAAA;EAAA,SACA,SAAA;EAAA,SACA,YAAA,GAAe,QAAA,CAAS,MAAA;AAAA;AAAA,KAG9B,kBAAA;EAAA,SACM,IAAA;EAAA,SACA,IAAI;AAAA;AAAA,KAGV,oBAAA,GAAuB,kBAAkB;AAAA,KAEzC,mBAAA;EAAA,SACM,IAAA;EAAA,SACA,MAAA;IAAA,SAEM,IAAA;IAAA,SACA,UAAA;IAAA,SACA,IAAA;EAAA;IAAA,SAGA,IAAA;IAAA,SACA,GAAA;EAAA;AAAA;AAAA,KAIZ,sBAAA;EAAA,SACM,IAAA;EAAA,SACA,MAAA;IAAA,SAEM,IAAA;IAAA,SACA,UAAA;IAAA,SACA,IAAA;EAAA;IAAA,SAGA,IAAA;IAAA,SACA,GAAA;EAAA;EAAA,SAEN,KAAA;AAAA;AAAA,KAGN,qBAAA;EAAA,SACM,IAAA;EAAA,SACA,EAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;AAAA;AAAA,KAGN,+BAAA,GACD,kBAAA,GACA,mBAAA,GACA,sBAAA;AAAA,KAEC,wBAAA;EAAA,SACM,IAAA;EAAA,SACA,WAAA;EAAA,SACA,OAAA,WAAkB,aAAa,CAAC,+BAAA;EAAA,SAChC,QAAA;AAAA;AAAA,KAGN,kBAAA,GACD,kBAAA,GACA,mBAAA,GACA,sBAAA,GACA,wBAAA;AAAA,KACC,uBAAA,GAA0B,kBAAA,GAAqB,qBAAqB;AAAA,KAEpE,gBAAA;EAAA,SACU,IAAA;EAAA,SAAuB,OAAA,WAAkB,aAAA,CAAc,kBAAA;AAAA;EAAA,SACvD,IAAA;EAAA,SAA4B,OAAA,EAAS,aAAA,CAAc,uBAAA;AAAA;AAAA,KAS7D,aAAA;EAAA,SACM,IAAA;EAAA,SACA,WAAA;EAAA,SACA,YAAA;AAAA;AAAA,KAGN,oBAAA;EAAA,SACM,KAAA;EAAA,SACA,MAAA,EAAQ,aAAA,CAAc,oBAAA;EAAA,SACtB,QAAA,EAAU,aAAA,CAAc,gBAAA;EAAA,SACxB,UAAA;EAAA,SACA,aAAA;IAAA,SACE,MAAA;EAAA;EAAA,SAEF,MAAA;EAAA,SACA,KAAA,GAAQ,aAAA,CAAc,aAAA;AAAA;AAAA,cAg7BpB,4BAAA,GACX,OAAA,EAAS,UAAA,EACT,MAAA;EAAA,SAAmB,SAAA;EAAA,SAA4B,MAAA;AAAA,MAC9C,MAAA,CAAO,MAAA,CAAO,oBAAA,EAAsB,QAAA;AAAA,cAmmB1B,6BAAA,GACX,QAAA,EAAU,kBAAA,CAAmB,kBAAA,KAC5B,MAAA,CAAO,MAAA,CAAO,QAAA,EAAU,QAAA;AAAA,cAoGd,gCAAA,GAAoC,MAAA,EAAQ,6BAAA,KAA6B,KAAA,CAAA,KAAA,CAAA,WAAA,SAAA,UAAA,CAAA,UAAA"}
|
|
@@ -288,11 +288,12 @@ const topLevelJsonSchemaCombinator = (schema) => {
|
|
|
288
288
|
}
|
|
289
289
|
};
|
|
290
290
|
const withoutTopLevelJsonSchemaCombinators = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !isTopLevelJsonSchemaCombinatorKey(key)));
|
|
291
|
-
const withoutJsonSchemaCombinatorsAndTupleHints = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !isTopLevelJsonSchemaCombinatorKey(key) && key !== "prefixItems"));
|
|
292
|
-
const
|
|
293
|
-
const
|
|
294
|
-
return isJsonObject(
|
|
291
|
+
const withoutJsonSchemaCombinatorsAndTupleHints = (schema) => Object.fromEntries(Object.entries(schema).filter(([key]) => !isTopLevelJsonSchemaCombinatorKey(key) && key !== "prefixItems" && key !== "not" && key !== "if" && key !== "then" && key !== "else"));
|
|
292
|
+
const jsonSchemaMap = (schema, key) => {
|
|
293
|
+
const value = jsonObjectField(schema, key);
|
|
294
|
+
return isJsonObject(value) ? value : {};
|
|
295
295
|
};
|
|
296
|
+
const jsonSchemaProperties = (schema) => jsonSchemaMap(schema, "properties");
|
|
296
297
|
const jsonSchemaDefinitions = (schema) => {
|
|
297
298
|
const definitions = jsonObjectField(schema, "$defs");
|
|
298
299
|
return isJsonObject(definitions) ? definitions : {};
|
|
@@ -321,24 +322,21 @@ const mergeEnumPropertySchemas = (left, right) => {
|
|
|
321
322
|
const leftEnum = jsonObjectField(left, "enum");
|
|
322
323
|
const rightEnum = jsonObjectField(right, "enum");
|
|
323
324
|
if (!Array.isArray(leftEnum) || !Array.isArray(rightEnum)) return;
|
|
324
|
-
|
|
325
|
+
const leftType = jsonObjectField(left, "type");
|
|
326
|
+
if (leftType !== jsonObjectField(right, "type")) return;
|
|
327
|
+
const description = [jsonObjectField(left, "description"), jsonObjectField(right, "description")].find((value) => typeof value === "string");
|
|
325
328
|
return {
|
|
326
|
-
...
|
|
327
|
-
...
|
|
328
|
-
|
|
329
|
+
...leftType === void 0 ? {} : { type: leftType },
|
|
330
|
+
enum: uniqueUnknownArray([...leftEnum, ...rightEnum]),
|
|
331
|
+
...description === void 0 ? {} : { description }
|
|
329
332
|
};
|
|
330
333
|
};
|
|
331
|
-
const jsonSchemaAnyOfItems = (schema) => {
|
|
332
|
-
if (!isJsonObject(schema)) return [schema];
|
|
333
|
-
const anyOf = jsonObjectField(schema, "anyOf");
|
|
334
|
-
return Array.isArray(anyOf) ? anyOf : [schema];
|
|
335
|
-
};
|
|
336
334
|
const mergePropertySchemas = (left, right) => {
|
|
337
335
|
const leftKey = jsonValueKey(left);
|
|
338
336
|
if (leftKey !== void 0 && leftKey === jsonValueKey(right)) return left;
|
|
339
337
|
const mergedEnum = mergeEnumPropertySchemas(left, right);
|
|
340
338
|
if (mergedEnum !== void 0) return mergedEnum;
|
|
341
|
-
return {
|
|
339
|
+
return {};
|
|
342
340
|
};
|
|
343
341
|
const mergeJsonSchemaObjects = (objects) => {
|
|
344
342
|
const merged = /* @__PURE__ */ new Map();
|
|
@@ -346,48 +344,115 @@ const mergeJsonSchemaObjects = (objects) => {
|
|
|
346
344
|
else merged.set(key, value);
|
|
347
345
|
return Object.fromEntries(merged);
|
|
348
346
|
};
|
|
349
|
-
const
|
|
347
|
+
const mergeUnionJsonSchemaObjects = (objects, owners) => {
|
|
348
|
+
const keys = new Set(objects.flatMap((object) => Object.keys(object)));
|
|
349
|
+
return Object.fromEntries(Array.from(keys, (key) => {
|
|
350
|
+
const [first, ...rest] = objects.flatMap((object, index) => {
|
|
351
|
+
if (Object.hasOwn(object, key)) return [jsonObjectField(object, key)];
|
|
352
|
+
const additionalProperties = owners?.[index];
|
|
353
|
+
if (additionalProperties === void 0) return [];
|
|
354
|
+
const additionalPropertySchema = jsonObjectField(additionalProperties, "additionalProperties");
|
|
355
|
+
if (additionalPropertySchema === false) return [];
|
|
356
|
+
return [isJsonObject(additionalPropertySchema) ? additionalPropertySchema : {}];
|
|
357
|
+
});
|
|
358
|
+
return [key, rest.reduce(mergePropertySchemas, first)];
|
|
359
|
+
}));
|
|
360
|
+
};
|
|
361
|
+
const mergeRightBiasedJsonSchemaObjects = (objects) => Object.assign({}, ...objects);
|
|
362
|
+
const mergeAllOfSchemaObjects = (objects) => {
|
|
363
|
+
const merged = mergeRightBiasedJsonSchemaObjects(objects);
|
|
364
|
+
const properties = mergeRightBiasedJsonSchemaObjects(objects.map(jsonSchemaProperties));
|
|
365
|
+
const required = mergeJsonSchemaRequired("allOf", objects);
|
|
366
|
+
const definitions = mergeJsonSchemaObjects(objects.map(jsonSchemaDefinitions));
|
|
367
|
+
return {
|
|
368
|
+
...merged,
|
|
369
|
+
...Object.keys(properties).length === 0 ? {} : { properties },
|
|
370
|
+
...required.length === 0 ? {} : { required },
|
|
371
|
+
...Object.keys(definitions).length === 0 ? {} : { $defs: definitions }
|
|
372
|
+
};
|
|
373
|
+
};
|
|
374
|
+
const jsonSchemaMapKeywords = new Set([
|
|
375
|
+
"properties",
|
|
376
|
+
"patternProperties",
|
|
377
|
+
"$defs",
|
|
378
|
+
"definitions",
|
|
379
|
+
"dependentSchemas"
|
|
380
|
+
]);
|
|
381
|
+
const jsonSchemaDataKeywords = new Set([
|
|
382
|
+
"const",
|
|
383
|
+
"default",
|
|
384
|
+
"enum",
|
|
385
|
+
"examples"
|
|
386
|
+
]);
|
|
387
|
+
const normalizeJsonSchemaObjectFields = (schema) => {
|
|
388
|
+
const normalized = Object.fromEntries(Object.entries(withoutJsonSchemaCombinatorsAndTupleHints(schema)).map(([key, value]) => {
|
|
389
|
+
if (jsonSchemaDataKeywords.has(key)) return [key, value];
|
|
390
|
+
if (key === "dependencies" && isJsonObject(value)) return [key, Object.fromEntries(Object.entries(value).map(([name, dependency]) => [name, Array.isArray(dependency) ? dependency : normalizeAnthropicToolSchema(dependency)]))];
|
|
391
|
+
if (jsonSchemaMapKeywords.has(key) && isJsonObject(value)) return [key, Object.fromEntries(Object.entries(value).map(([name, childSchema]) => [name, normalizeAnthropicToolSchema(childSchema)]))];
|
|
392
|
+
return [key, normalizeAnthropicToolSchema(value)];
|
|
393
|
+
}));
|
|
394
|
+
if (Array.isArray(jsonObjectField(schema, "prefixItems"))) return {
|
|
395
|
+
...normalized,
|
|
396
|
+
items: {}
|
|
397
|
+
};
|
|
398
|
+
return normalized;
|
|
399
|
+
};
|
|
350
400
|
const jsonSchemaType = (schema) => {
|
|
351
401
|
const type = jsonObjectField(schema, "type");
|
|
352
402
|
return typeof type === "string" ? type : void 0;
|
|
353
403
|
};
|
|
354
|
-
const isNullJsonSchema = (schema) => jsonSchemaType(schema) === "null";
|
|
355
404
|
const firstJsonObject = (items) => items[0];
|
|
356
|
-
const
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
405
|
+
const independentCommonVariantKeys = new Set([
|
|
406
|
+
"type",
|
|
407
|
+
"enum",
|
|
408
|
+
"const",
|
|
409
|
+
"format",
|
|
410
|
+
"pattern",
|
|
411
|
+
"minLength",
|
|
412
|
+
"maxLength",
|
|
413
|
+
"minimum",
|
|
414
|
+
"maximum",
|
|
415
|
+
"exclusiveMinimum",
|
|
416
|
+
"exclusiveMaximum",
|
|
417
|
+
"multipleOf",
|
|
418
|
+
"minItems",
|
|
419
|
+
"maxItems",
|
|
420
|
+
"uniqueItems",
|
|
421
|
+
"minProperties",
|
|
422
|
+
"maxProperties",
|
|
423
|
+
"description"
|
|
424
|
+
]);
|
|
425
|
+
const commonVariantFields = (variants) => {
|
|
366
426
|
const first = firstJsonObject(variants);
|
|
367
|
-
|
|
368
|
-
if (
|
|
369
|
-
return
|
|
427
|
+
if (first === void 0) return {};
|
|
428
|
+
if (variants.length === 1) return first;
|
|
429
|
+
return Object.fromEntries(Object.entries(first).filter(([key, value]) => {
|
|
430
|
+
if (!independentCommonVariantKeys.has(key)) return false;
|
|
431
|
+
const valueKey = jsonValueKey(value);
|
|
432
|
+
return valueKey !== void 0 && variants.every((variant) => valueKey === jsonValueKey(jsonObjectField(variant, key)));
|
|
433
|
+
}));
|
|
370
434
|
};
|
|
371
435
|
const objectVariant = (variants) => {
|
|
372
|
-
if (variants.length === 0 || variants.some((variant) =>
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
})) return;
|
|
436
|
+
if (variants.length === 0 || variants.some((variant) => jsonSchemaType(variant) !== "object")) return;
|
|
437
|
+
if (variants.some((variant) => Object.keys(jsonSchemaMap(variant, "patternProperties")).length > 0)) return { type: "object" };
|
|
438
|
+
const additionalProperties = mergeAdditionalProperties(variants);
|
|
376
439
|
return {
|
|
377
440
|
type: "object",
|
|
378
|
-
properties:
|
|
441
|
+
properties: mergeUnionJsonSchemaObjects(variants.map(jsonSchemaProperties), variants),
|
|
379
442
|
required: mergeJsonSchemaRequired("oneOf", variants),
|
|
380
443
|
$defs: mergeJsonSchemaObjects(variants.map(jsonSchemaDefinitions)),
|
|
381
|
-
additionalProperties:
|
|
444
|
+
...additionalProperties === void 0 ? {} : { additionalProperties }
|
|
382
445
|
};
|
|
383
446
|
};
|
|
384
447
|
const normalizeJsonSchemaCombinator = (schema, combinator) => {
|
|
385
448
|
const base = normalizeJsonSchemaObjectFields(schema);
|
|
386
|
-
const
|
|
449
|
+
const normalizedItems = combinator.items.map(normalizeAnthropicToolSchema);
|
|
450
|
+
const variants = normalizedItems.filter(isJsonObject);
|
|
387
451
|
const first = firstJsonObject(variants);
|
|
452
|
+
if (combinator.key === "allOf") return mergeAllOfSchemaObjects([base, ...variants]);
|
|
453
|
+
if (normalizedItems.includes(true)) return base;
|
|
388
454
|
if (first === void 0) return base;
|
|
389
|
-
|
|
390
|
-
return mergeJsonSchemaObjects([base, mergeCompatibleVariants(variants) ?? samePrimitiveTypeVariant(variants) ?? objectVariant(variants) ?? first]);
|
|
455
|
+
return mergeAllOfSchemaObjects([objectVariant(variants) ?? commonVariantFields(variants), base]);
|
|
391
456
|
};
|
|
392
457
|
function normalizeAnthropicToolSchema(value) {
|
|
393
458
|
if (Array.isArray(value)) return value.map(normalizeAnthropicToolSchema);
|
|
@@ -410,22 +475,26 @@ const mergeAdditionalProperties = (objects) => {
|
|
|
410
475
|
const flattenTopLevelCombinatorToolSchema = (schema, combinator) => {
|
|
411
476
|
const base = withoutTopLevelJsonSchemaCombinators(schema);
|
|
412
477
|
const objectVariants = combinator.items.filter(isJsonObject);
|
|
478
|
+
const hasUnconstrainedUnion = combinator.key !== "allOf" && combinator.items.some((item) => item === true || !isJsonObject(item));
|
|
413
479
|
const additionalProperties = mergeAdditionalProperties(objectVariants);
|
|
414
480
|
const flattened = {
|
|
415
481
|
...base,
|
|
416
482
|
type: "object",
|
|
417
|
-
properties:
|
|
418
|
-
required: mergeJsonSchemaRequired(combinator.key, objectVariants),
|
|
483
|
+
properties: hasUnconstrainedUnion ? {} : combinator.key === "allOf" ? mergeRightBiasedJsonSchemaObjects(objectVariants.map(jsonSchemaProperties)) : mergeUnionJsonSchemaObjects(objectVariants.map(jsonSchemaProperties), objectVariants),
|
|
484
|
+
required: hasUnconstrainedUnion ? [] : mergeJsonSchemaRequired(combinator.key, objectVariants),
|
|
419
485
|
$defs: mergeJsonSchemaObjects([jsonSchemaDefinitions(schema), ...objectVariants.map(jsonSchemaDefinitions)])
|
|
420
486
|
};
|
|
421
|
-
if (additionalProperties === void 0) return flattened;
|
|
487
|
+
if (hasUnconstrainedUnion || additionalProperties === void 0) return flattened;
|
|
422
488
|
return {
|
|
423
489
|
...flattened,
|
|
424
490
|
additionalProperties
|
|
425
491
|
};
|
|
426
492
|
};
|
|
427
493
|
const anthropicToolInputSchema = (schema) => {
|
|
428
|
-
if (!isJsonObject(schema)) return {
|
|
494
|
+
if (!isJsonObject(schema)) return schema === true ? {
|
|
495
|
+
type: "object",
|
|
496
|
+
properties: {}
|
|
497
|
+
} : {
|
|
429
498
|
type: "object",
|
|
430
499
|
properties: {},
|
|
431
500
|
required: [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-provider.mjs","names":["LLMTextDelta","LLMReasoningDelta"],"sources":["../../../src/providers/anthropic/claude-provider.ts"],"sourcesContent":["import { Effect, Layer, Option, Ref, Result, Stream } from 'effect'\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentInputUsage,\n AgentOutputUsage,\n AgentUsage,\n ToolCall,\n attachmentSourceText,\n assistantContent,\n assistantHostToolCalls,\n isTextDocumentMimeType,\n messageContextText,\n replaceLoneSurrogatesDeep,\n prependMessageContextToContent,\n type AgentMessage,\n type Content,\n type ContentPart,\n type ProviderFailureKind,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport {\n LLMError,\n LLMDone,\n LLMProvider,\n LLMReasoningDelta,\n LLMTextDelta,\n LLMToolCall,\n LLMUsage,\n type LLMEvent,\n type LLMRequest\n} from '@yolk-sdk/agent/loop'\nimport {\n anthropicClaudeAuthorizationHeaders,\n anthropicClaudeCodeEntrypoint,\n anthropicClaudeCodeVersion,\n anthropicClaudeOAuthUserAgent\n} from './claude.ts'\nimport type { OAuthAccessToken } from '@yolk-sdk/agent/oauth'\nimport {\n classifyProviderFailure,\n providerErrorInfo,\n providerFailureCause,\n providerFailureRetryable\n} from '../provider-error.ts'\nimport { validateProviderTranscript } from '../transcript.ts'\n\nexport type AnthropicClaudeProviderConfig = {\n readonly token: OAuthAccessToken\n readonly messagesUrl?: string\n readonly maxTokens: number\n readonly extraHeaders?: Readonly<Record<string, string>>\n}\n\ntype AnthropicTextBlock = {\n readonly type: 'text'\n readonly text: string\n}\n\ntype AnthropicSystemBlock = AnthropicTextBlock\n\ntype AnthropicImageBlock = {\n readonly type: 'image'\n readonly source:\n | {\n readonly type: 'base64'\n readonly media_type: string\n readonly data: string\n }\n | {\n readonly type: 'url'\n readonly url: string\n }\n}\n\ntype AnthropicDocumentBlock = {\n readonly type: 'document'\n readonly source:\n | {\n readonly type: 'base64'\n readonly media_type: 'application/pdf'\n readonly data: string\n }\n | {\n readonly type: 'url'\n readonly url: string\n }\n readonly title?: string\n}\n\ntype AnthropicToolUseBlock = {\n readonly type: 'tool_use'\n readonly id: string\n readonly name: string\n readonly input: unknown\n}\n\ntype AnthropicToolResultContentBlock =\n | AnthropicTextBlock\n | AnthropicImageBlock\n | AnthropicDocumentBlock\n\ntype AnthropicToolResultBlock = {\n readonly type: 'tool_result'\n readonly tool_use_id: string\n readonly content: string | ReadonlyArray<AnthropicToolResultContentBlock>\n readonly is_error?: boolean\n}\n\ntype AnthropicUserBlock =\n | AnthropicTextBlock\n | AnthropicImageBlock\n | AnthropicDocumentBlock\n | AnthropicToolResultBlock\ntype AnthropicAssistantBlock = AnthropicTextBlock | AnthropicToolUseBlock\n\ntype AnthropicMessage =\n | { readonly role: 'user'; readonly content: string | ReadonlyArray<AnthropicUserBlock> }\n | { readonly role: 'assistant'; readonly content: ReadonlyArray<AnthropicAssistantBlock> }\n\ntype JsonObject = Readonly<Record<string, unknown>>\ntype TopLevelJsonSchemaCombinatorKey = 'anyOf' | 'oneOf' | 'allOf'\ntype TopLevelJsonSchemaCombinator = {\n readonly key: TopLevelJsonSchemaCombinatorKey\n readonly items: ReadonlyArray<unknown>\n}\n\ntype AnthropicTool = {\n readonly name: string\n readonly description: string\n readonly input_schema: unknown\n}\n\ntype AnthropicRequestBody = {\n readonly model: string\n readonly system: ReadonlyArray<AnthropicSystemBlock>\n readonly messages: ReadonlyArray<AnthropicMessage>\n readonly max_tokens: number\n readonly output_config?: {\n readonly effort: 'low' | 'medium' | 'high' | 'xhigh'\n }\n readonly stream?: true\n readonly tools?: ReadonlyArray<AnthropicTool>\n}\n\ntype AnthropicToolBlockState = {\n readonly id: string\n readonly name: string\n readonly partialJson: string\n}\n\nconst anthropicClaudeSystemIdentity = \"You are Claude Code, Anthropic's official CLI for Claude.\"\nconst anthropicClaudeBillingPrefix = 'x-anthropic-billing-header:'\nconst anthropicClaudeToolPrefix = 'mcp_'\nconst anthropicClaudeVersion = '2023-06-01'\nconst anthropicClaudeCchSalt = '59cf53e54c78'\nconst anthropicClaudeCchPositions: ReadonlyArray<number> = [4, 7, 20]\nconst anthropicClaudeEffortBeta = 'effort-2025-11-24'\nconst anthropicClaudeInterleavedThinkingBeta = 'interleaved-thinking-2025-05-14'\nconst anthropicClaudeRequiredBetas: ReadonlyArray<string> = [\n 'claude-code-20250219',\n 'oauth-2025-04-20',\n anthropicClaudeInterleavedThinkingBeta,\n 'prompt-caching-scope-2026-01-05',\n 'context-management-2025-06-27',\n 'advisor-tool-2026-03-01'\n]\nconst anthropicClaudeSystemTextReplacements: ReadonlyArray<{\n readonly match: string\n readonly replacement: string\n}> = [\n {\n match: 'if OpenCode honestly',\n replacement: 'if the assistant honestly'\n },\n {\n match: 'Here is some useful information about the environment you are running in:',\n replacement: 'Environment context you are running in:'\n }\n]\nconst anthropicClaudeStainlessPackageVersion = '0.81.0'\n\n// Claude subscription OAuth is fingerprinted against Claude Code tool names.\nconst prefixClaudeToolName = (name: string) =>\n `${anthropicClaudeToolPrefix}${name.charAt(0).toUpperCase()}${name.slice(1)}`\n\nconst unprefixClaudeToolName = (name: string) => {\n if (!name.startsWith(anthropicClaudeToolPrefix)) {\n return name\n }\n\n const unprefixed = name.slice(anthropicClaudeToolPrefix.length)\n\n if (unprefixed === 'StructuredOutput') {\n return unprefixed\n }\n\n return `${unprefixed.charAt(0).toLowerCase()}${unprefixed.slice(1)}`\n}\n\nconst anthropicClaudeMessagesUrl = 'https://api.anthropic.com/v1/messages?beta=true'\nconst anthropicClaudeIdentitySystemBlock: AnthropicSystemBlock = {\n type: 'text',\n text: anthropicClaudeSystemIdentity\n}\n\nconst randomHex = (byteLength: number) => {\n const crypto = globalThis.crypto\n const bytes = new Uint8Array(byteLength)\n\n if (crypto !== undefined && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes)\n }\n\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\nconst makeAnthropicClaudeRequestId = () => {\n const crypto = globalThis.crypto\n\n if (crypto !== undefined && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n return randomHex(16)\n}\n\nconst sha256Hex = (value: string): Effect.Effect<string, LLMError> => {\n const crypto = globalThis.crypto\n\n if (crypto === undefined || crypto.subtle === undefined) {\n return Effect.fail(\n new LLMError({\n cause: 'provider_error',\n message: 'Web Crypto SHA-256 is required for Anthropic Claude OAuth billing headers',\n retryable: false\n })\n )\n }\n\n return Effect.tryPromise({\n try: () =>\n crypto.subtle\n .digest('SHA-256', new TextEncoder().encode(value))\n .then(buffer =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n ),\n catch: error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not compute Anthropic Claude OAuth billing header: ${unknownToMessage(error)}`,\n retryable: false\n })\n })\n}\n\nconst computeAnthropicClaudeCch = (messageText: string) =>\n sha256Hex(messageText).pipe(Effect.map(hash => hash.slice(0, 5)))\n\nconst computeAnthropicClaudeVersionSuffix = (messageText: string) => {\n const chars = anthropicClaudeCchPositions.map(index => messageText[index] ?? '0').join('')\n\n return sha256Hex(`${anthropicClaudeCchSalt}${chars}${anthropicClaudeCodeVersion}`).pipe(\n Effect.map(hash => hash.slice(0, 3))\n )\n}\n\nconst firstUserMessageText = (messages: ReadonlyArray<AnthropicMessage>) => {\n for (const message of messages) {\n if (message.role !== 'user') {\n continue\n }\n\n if (typeof message.content === 'string') {\n return message.content\n }\n\n for (const block of message.content) {\n if (block.type === 'text') {\n return block.text\n }\n }\n }\n\n return ''\n}\n\nconst makeAnthropicClaudeBillingSystemBlock = (\n messages: ReadonlyArray<AnthropicMessage>\n): Effect.Effect<AnthropicSystemBlock, LLMError> => {\n const text = firstUserMessageText(messages)\n\n return Effect.all({\n cch: computeAnthropicClaudeCch(text),\n suffix: computeAnthropicClaudeVersionSuffix(text)\n }).pipe(\n Effect.map(\n ({ cch, suffix }): AnthropicSystemBlock => ({\n type: 'text',\n text:\n `${anthropicClaudeBillingPrefix} ` +\n `cc_version=${anthropicClaudeCodeVersion}.${suffix}; ` +\n `cc_entrypoint=${anthropicClaudeCodeEntrypoint}; ` +\n `cch=${cch};`\n })\n )\n )\n}\n\nconst sanitizeAnthropicClaudeSystemText = (text: string) => {\n let result = text\n\n for (const rule of anthropicClaudeSystemTextReplacements) {\n result = result.split(rule.match).join(rule.replacement)\n }\n\n return result\n}\n\nconst anthropicClaudeBetaHeader = (model: string) => {\n const lowerModel = model.toLowerCase()\n const baseBetas = lowerModel.includes('haiku')\n ? anthropicClaudeRequiredBetas.filter(beta => beta !== anthropicClaudeInterleavedThinkingBeta)\n : anthropicClaudeRequiredBetas\n\n if (\n !lowerModel.includes('haiku') &&\n (lowerModel.includes('4-6') || lowerModel.includes('4-7')) &&\n !baseBetas.includes(anthropicClaudeEffortBeta)\n ) {\n return [...baseBetas, anthropicClaudeEffortBeta].join(',')\n }\n\n return baseBetas.join(',')\n}\n\nconst makeAnthropicClaudeCompatibilityHeaders = (input: {\n readonly model: string\n readonly sessionId: string\n}) => ({\n 'anthropic-beta': anthropicClaudeBetaHeader(input.model),\n 'anthropic-dangerous-direct-browser-access': 'true',\n 'anthropic-version': anthropicClaudeVersion,\n 'user-agent': anthropicClaudeOAuthUserAgent,\n 'x-app': 'cli',\n 'x-client-request-id': makeAnthropicClaudeRequestId(),\n 'X-Claude-Code-Session-Id': input.sessionId,\n 'x-stainless-arch': 'unknown',\n 'x-stainless-lang': 'js',\n 'x-stainless-os': 'unknown',\n 'x-stainless-package-version': anthropicClaudeStainlessPackageVersion,\n 'x-stainless-retry-count': '0',\n 'x-stainless-runtime': 'node',\n 'x-stainless-runtime-version': 'unknown',\n 'x-stainless-timeout': '600'\n})\n\n// Keep app instructions out of `system[]`; Anthropic can reject/limit otherwise.\nconst prependSystemPromptToFirstUserMessage = (\n messages: ReadonlyArray<AnthropicMessage>,\n systemPrompt: string\n): ReadonlyArray<AnthropicMessage> => {\n const sanitizedSystemPrompt = sanitizeAnthropicClaudeSystemText(systemPrompt).trim()\n\n if (sanitizedSystemPrompt.length === 0) {\n return messages\n }\n\n let relocated = false\n\n return messages.map(message => {\n if (relocated || message.role !== 'user') {\n return message\n }\n\n relocated = true\n\n if (typeof message.content === 'string') {\n return { ...message, content: `${sanitizedSystemPrompt}\\n\\n${message.content}` }\n }\n\n return {\n ...message,\n content: [{ type: 'text', text: sanitizedSystemPrompt }, ...message.content]\n }\n })\n}\n\nclass AnthropicTextResponseBlock extends Schema.Class<AnthropicTextResponseBlock>(\n 'AnthropicTextResponseBlock'\n)({\n type: Schema.Literal('text'),\n text: Schema.String\n}) {}\n\nclass AnthropicThinkingResponseBlock extends Schema.Class<AnthropicThinkingResponseBlock>(\n 'AnthropicThinkingResponseBlock'\n)({\n type: Schema.Literal('thinking'),\n thinking: Schema.String\n}) {}\n\nclass AnthropicToolUseResponseBlock extends Schema.Class<AnthropicToolUseResponseBlock>(\n 'AnthropicToolUseResponseBlock'\n)({\n type: Schema.Literal('tool_use'),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown\n}) {}\n\nconst AnthropicContentResponseBlock = Schema.Union([\n AnthropicTextResponseBlock,\n AnthropicThinkingResponseBlock,\n AnthropicToolUseResponseBlock\n])\n\nclass AnthropicUsageResponse extends Schema.Class<AnthropicUsageResponse>('AnthropicUsageResponse')(\n {\n input_tokens: Schema.Number,\n output_tokens: Schema.Number,\n cache_read_input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_creation_input_tokens: Schema.optional(Schema.NullOr(Schema.Number))\n }\n) {}\n\nclass AnthropicStreamUsageResponse extends Schema.Class<AnthropicStreamUsageResponse>(\n 'AnthropicStreamUsageResponse'\n)({\n input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n output_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_read_input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_creation_input_tokens: Schema.optional(Schema.NullOr(Schema.Number))\n}) {}\n\nclass AnthropicMessageResponse extends Schema.Class<AnthropicMessageResponse>(\n 'AnthropicMessageResponse'\n)({\n content: Schema.Array(AnthropicContentResponseBlock),\n stop_reason: Schema.NullOr(Schema.String),\n usage: Schema.optional(AnthropicUsageResponse)\n}) {}\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst unsupportedContentError = (contentType: string) =>\n new LLMError({\n cause: 'provider_error',\n message: `${contentType} content is not supported by the Anthropic Claude provider yet`,\n retryable: false\n })\n\nconst imageToAnthropicBlock = (\n part: Extract<ContentPart, { readonly _tag: 'Image' }>\n): Effect.Effect<AnthropicImageBlock, LLMError> => {\n switch (part.source._tag) {\n case 'InlineBase64':\n return Effect.succeed({\n type: 'image',\n source: {\n type: 'base64',\n media_type: part.mimeType,\n data: part.source.data\n }\n })\n case 'Url':\n return Effect.succeed({\n type: 'image',\n source: {\n type: 'url',\n url: part.source.url\n }\n })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved image source'))\n }\n}\n\nconst pdfDocumentToAnthropicBlock = (\n part: Extract<ContentPart, { readonly _tag: 'Document' }>\n): Effect.Effect<AnthropicDocumentBlock, LLMError> => {\n switch (part.source._tag) {\n case 'InlineBase64':\n return Effect.succeed({\n type: 'document',\n source: {\n type: 'base64',\n media_type: 'application/pdf',\n data: part.source.data\n },\n title: part.title ?? part.filename\n })\n case 'Url':\n return Effect.succeed({\n type: 'document',\n source: {\n type: 'url',\n url: part.source.url\n },\n title: part.title ?? part.filename\n })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved document source'))\n }\n}\n\nconst textDocumentToAnthropicBlock = (part: Extract<ContentPart, { readonly _tag: 'Document' }>) =>\n attachmentSourceText(part.source).pipe(\n Effect.mapError(() => unsupportedContentError('Invalid document text')),\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(unsupportedContentError('Unresolved document source')),\n onSome: text => {\n const block: AnthropicTextBlock = {\n type: 'text',\n text: `Document: ${part.title ?? part.filename}\\n\\n${text}`\n }\n\n return Effect.succeed(block)\n }\n })\n )\n )\n\nconst contentPartToAnthropicBlock = (\n part: ContentPart\n): Effect.Effect<AnthropicToolResultContentBlock, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed({ type: 'text', text: part.text })\n case 'Image':\n return imageToAnthropicBlock(part)\n case 'Document':\n return isTextDocumentMimeType(part.mimeType)\n ? textDocumentToAnthropicBlock(part)\n : part.mimeType === 'application/pdf'\n ? pdfDocumentToAnthropicBlock(part)\n : Effect.fail(unsupportedContentError(`Document ${part.mimeType}`))\n case 'Audio':\n return Effect.fail(unsupportedContentError('Audio'))\n }\n}\n\nconst contentToAnthropicContent = (\n content: Content\n): Effect.Effect<string | ReadonlyArray<AnthropicToolResultContentBlock>, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, contentPartToAnthropicBlock)\n\nconst contentPartToText = (part: ContentPart, owner: string): Effect.Effect<string, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part.text)\n case 'Image':\n return Effect.fail(unsupportedContentError(`${owner} image`))\n case 'Document':\n return Effect.fail(unsupportedContentError(`${owner} document`))\n case 'Audio':\n return Effect.fail(unsupportedContentError(`${owner} audio`))\n }\n}\n\nconst contentToText = (content: Content, owner: string): Effect.Effect<string, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => contentPartToText(part, owner)).pipe(\n Effect.map(textParts => textParts.join('\\n'))\n )\n\nconst toolCallToAnthropicBlock = (call: ToolCall): AnthropicToolUseBlock => ({\n type: 'tool_use',\n id: call.id,\n name: prefixClaudeToolName(call.name),\n input: call.params\n})\n\nconst isJsonObject = (value: unknown): value is JsonObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst jsonObjectField = (value: JsonObject, key: string) =>\n Object.getOwnPropertyDescriptor(value, key)?.value\n\nconst topLevelJsonSchemaCombinatorKeys: ReadonlyArray<TopLevelJsonSchemaCombinatorKey> = [\n 'anyOf',\n 'oneOf',\n 'allOf'\n]\n\nconst isTopLevelJsonSchemaCombinatorKey = (key: string): key is TopLevelJsonSchemaCombinatorKey =>\n key === 'anyOf' || key === 'oneOf' || key === 'allOf'\n\nconst topLevelJsonSchemaCombinator = (\n schema: JsonObject\n): TopLevelJsonSchemaCombinator | undefined => {\n for (const key of topLevelJsonSchemaCombinatorKeys) {\n const value = jsonObjectField(schema, key)\n\n if (Array.isArray(value)) {\n return { key, items: value }\n }\n }\n\n return undefined\n}\n\nconst withoutTopLevelJsonSchemaCombinators = (schema: JsonObject): JsonObject =>\n Object.fromEntries(\n Object.entries(schema).filter(([key]) => !isTopLevelJsonSchemaCombinatorKey(key))\n )\n\nconst withoutJsonSchemaCombinatorsAndTupleHints = (schema: JsonObject): JsonObject =>\n Object.fromEntries(\n Object.entries(schema).filter(\n ([key]) => !isTopLevelJsonSchemaCombinatorKey(key) && key !== 'prefixItems'\n )\n )\n\nconst jsonSchemaProperties = (schema: JsonObject) => {\n const properties = jsonObjectField(schema, 'properties')\n\n return isJsonObject(properties) ? properties : {}\n}\n\nconst jsonSchemaDefinitions = (schema: JsonObject) => {\n const definitions = jsonObjectField(schema, '$defs')\n\n return isJsonObject(definitions) ? definitions : {}\n}\n\nconst jsonSchemaRequired = (schema: JsonObject) => {\n const required = jsonObjectField(schema, 'required')\n\n return Array.isArray(required) ? required.filter(item => typeof item === 'string') : []\n}\n\nconst jsonValueKey = (value: unknown) =>\n Result.try(() => JSON.stringify(value)).pipe(\n Result.match({\n onFailure: () => undefined,\n onSuccess: encoded => encoded\n })\n )\n\nconst uniqueUnknownArray = (items: ReadonlyArray<unknown>): ReadonlyArray<unknown> => {\n const seen = new Set<string>()\n const result: Array<unknown> = []\n\n for (const item of items) {\n const key = jsonValueKey(item)\n\n if (key === undefined || seen.has(key)) {\n continue\n }\n\n seen.add(key)\n result.push(item)\n }\n\n return result\n}\n\nconst mergeEnumPropertySchemas = (left: unknown, right: unknown): unknown | undefined => {\n if (!isJsonObject(left) || !isJsonObject(right)) {\n return undefined\n }\n\n const leftEnum = jsonObjectField(left, 'enum')\n const rightEnum = jsonObjectField(right, 'enum')\n\n if (!Array.isArray(leftEnum) || !Array.isArray(rightEnum)) {\n return undefined\n }\n\n const leftType = jsonObjectField(left, 'type')\n const rightType = jsonObjectField(right, 'type')\n\n if (leftType !== rightType) {\n return undefined\n }\n\n return { ...left, ...right, enum: uniqueUnknownArray([...leftEnum, ...rightEnum]) }\n}\n\nconst jsonSchemaAnyOfItems = (schema: unknown) => {\n if (!isJsonObject(schema)) {\n return [schema]\n }\n\n const anyOf = jsonObjectField(schema, 'anyOf')\n\n return Array.isArray(anyOf) ? anyOf : [schema]\n}\n\nconst mergePropertySchemas = (left: unknown, right: unknown): unknown => {\n const leftKey = jsonValueKey(left)\n\n if (leftKey !== undefined && leftKey === jsonValueKey(right)) {\n return left\n }\n\n const mergedEnum = mergeEnumPropertySchemas(left, right)\n\n if (mergedEnum !== undefined) {\n return mergedEnum\n }\n\n return {\n anyOf: uniqueUnknownArray([...jsonSchemaAnyOfItems(left), ...jsonSchemaAnyOfItems(right)])\n }\n}\n\nconst mergeJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject => {\n const merged = new Map<string, unknown>()\n\n for (const object of objects) {\n for (const [key, value] of Object.entries(object)) {\n if (merged.has(key)) {\n merged.set(key, mergePropertySchemas(merged.get(key), value))\n } else {\n merged.set(key, value)\n }\n }\n }\n\n return Object.fromEntries(merged)\n}\n\nconst normalizeJsonSchemaObjectFields = (schema: JsonObject): JsonObject =>\n Object.fromEntries(\n Object.entries(withoutJsonSchemaCombinatorsAndTupleHints(schema)).map(([key, value]) => [\n key,\n normalizeAnthropicToolSchema(value)\n ])\n )\n\nconst jsonSchemaType = (schema: JsonObject) => {\n const type = jsonObjectField(schema, 'type')\n\n return typeof type === 'string' ? type : undefined\n}\n\nconst isNullJsonSchema = (schema: JsonObject) => jsonSchemaType(schema) === 'null'\n\nconst firstJsonObject = (items: ReadonlyArray<JsonObject>) => items[0]\n\nconst mergeCompatibleVariants = (\n variants: ReadonlyArray<JsonObject>\n): JsonObject | undefined => {\n const first = firstJsonObject(variants)\n if (first === undefined) return undefined\n\n let merged: unknown = first\n\n for (const variant of variants.slice(1)) {\n merged = mergePropertySchemas(merged, variant)\n }\n\n if (!isJsonObject(merged)) return undefined\n\n if (Array.isArray(jsonObjectField(merged, 'anyOf'))) return undefined\n\n\n return merged\n}\n\nconst samePrimitiveTypeVariant = (variants: ReadonlyArray<JsonObject>): JsonObject | undefined => {\n const first = firstJsonObject(variants)\n const type = first === undefined ? undefined : jsonSchemaType(first)\n\n if (type === undefined || type === 'object' || type === 'array' || type === 'null') {\n return undefined\n }\n\n return variants.every(variant => jsonSchemaType(variant) === type) ? first : undefined\n}\n\nconst objectVariant = (variants: ReadonlyArray<JsonObject>): JsonObject | undefined => {\n if (\n variants.length === 0 ||\n variants.some(variant => {\n const type = jsonSchemaType(variant)\n\n return type !== undefined && type !== 'object'\n })\n ) {\n return undefined\n }\n\n return {\n type: 'object',\n properties: mergeJsonSchemaObjects(variants.map(jsonSchemaProperties)),\n required: mergeJsonSchemaRequired('oneOf', variants),\n $defs: mergeJsonSchemaObjects(variants.map(jsonSchemaDefinitions)),\n additionalProperties: mergeAdditionalProperties(variants) ?? false\n }\n}\n\nconst normalizeJsonSchemaCombinator = (\n schema: JsonObject,\n combinator: TopLevelJsonSchemaCombinator\n): JsonObject => {\n const base = normalizeJsonSchemaObjectFields(schema)\n const variants = combinator.items\n .map(normalizeAnthropicToolSchema)\n .filter(isJsonObject)\n .filter(variant => !isNullJsonSchema(variant))\n const first = firstJsonObject(variants)\n\n if (first === undefined) return base\n\n if (combinator.key === 'allOf') {\n return mergeJsonSchemaObjects([base, ...variants])\n }\n\n const merged =\n mergeCompatibleVariants(variants) ?? samePrimitiveTypeVariant(variants) ?? objectVariant(variants)\n\n return mergeJsonSchemaObjects([base, merged ?? first])\n}\n\nfunction normalizeAnthropicToolSchema(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(normalizeAnthropicToolSchema)\n if (!isJsonObject(value)) return value\n\n const combinator = topLevelJsonSchemaCombinator(value)\n if (combinator !== undefined) return normalizeJsonSchemaCombinator(value, combinator)\n\n return normalizeJsonSchemaObjectFields(value)\n}\n\nconst mergeJsonSchemaRequired = (\n combinatorKey: TopLevelJsonSchemaCombinatorKey,\n objects: ReadonlyArray<JsonObject>\n): ReadonlyArray<string> => {\n const requiredSets = objects.map(jsonSchemaRequired)\n\n if (requiredSets.length === 0) {\n return []\n }\n\n if (combinatorKey === 'allOf') {\n return Array.from(new Set(requiredSets.flat()))\n }\n\n const first = requiredSets[0] ?? []\n\n return first.filter(item => requiredSets.every(required => required.includes(item)))\n}\n\nconst mergeAdditionalProperties = (objects: ReadonlyArray<JsonObject>) => {\n const values = objects.map(object => jsonObjectField(object, 'additionalProperties'))\n\n if (values.every(value => value === false)) {\n return false\n }\n\n if (values.every(value => value === true)) {\n return true\n }\n\n return undefined\n}\n\n// Anthropic rejects root combinators. This widens provider-facing guidance only;\n// tool execution still validates calls against the original registry schema.\nconst flattenTopLevelCombinatorToolSchema = (\n schema: JsonObject,\n combinator: TopLevelJsonSchemaCombinator\n): JsonObject => {\n const base = withoutTopLevelJsonSchemaCombinators(schema)\n const objectVariants = combinator.items.filter(isJsonObject)\n const additionalProperties = mergeAdditionalProperties(objectVariants)\n const flattened = {\n ...base,\n type: 'object',\n properties: mergeJsonSchemaObjects(objectVariants.map(jsonSchemaProperties)),\n required: mergeJsonSchemaRequired(combinator.key, objectVariants),\n $defs: mergeJsonSchemaObjects([\n jsonSchemaDefinitions(schema),\n ...objectVariants.map(jsonSchemaDefinitions)\n ])\n }\n\n if (additionalProperties === undefined) {\n return flattened\n }\n\n return { ...flattened, additionalProperties }\n}\n\nconst anthropicToolInputSchema = (schema: unknown): unknown => {\n if (!isJsonObject(schema)) {\n return {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n }\n }\n\n const combinator = topLevelJsonSchemaCombinator(schema)\n\n if (combinator !== undefined) {\n return normalizeAnthropicToolSchema(flattenTopLevelCombinatorToolSchema(schema, combinator))\n }\n\n if (jsonObjectField(schema, 'type') !== undefined) {\n return normalizeAnthropicToolSchema(schema)\n }\n\n return normalizeAnthropicToolSchema({ ...schema, type: 'object' })\n}\n\nconst toAnthropicMessage = (message: AgentMessage): Effect.Effect<AnthropicMessage, LLMError> =>\n Effect.gen(function* () {\n switch (message._tag) {\n case 'User':\n return {\n role: 'user',\n content: yield* contentToAnthropicContent(\n prependMessageContextToContent(message.content, messageContextText(message))\n )\n }\n case 'Assistant': {\n const text = yield* contentToText(\n prependMessageContextToContent(assistantContent(message), messageContextText(message)),\n 'Assistant'\n )\n const textBlocks: ReadonlyArray<AnthropicTextBlock> =\n text.length === 0 ? [] : [{ type: 'text', text }]\n const toolBlocks = assistantHostToolCalls(message).map(toolCallToAnthropicBlock)\n return { role: 'assistant', content: [...textBlocks, ...toolBlocks] }\n }\n case 'ToolResult':\n return {\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: yield* contentToAnthropicContent(\n prependMessageContextToContent(message.content, messageContextText(message))\n ),\n is_error: message.isError\n }\n ]\n }\n }\n })\n\nconst toAnthropicTool = (tool: ToolDef): AnthropicTool => ({\n name: prefixClaudeToolName(tool.name),\n description: tool.description,\n input_schema: anthropicToolInputSchema(tool.parameters)\n})\n\nexport const toAnthropicClaudeRequestBody = (\n request: LLMRequest,\n config: { readonly maxTokens: number; readonly stream?: boolean }\n): Effect.Effect<AnthropicRequestBody, LLMError> =>\n Effect.gen(function* () {\n yield* validateProviderTranscript(request.messages)\n const rawMessages = yield* Effect.forEach(request.messages, toAnthropicMessage)\n const billingSystemBlock = yield* makeAnthropicClaudeBillingSystemBlock(rawMessages)\n const messages = prependSystemPromptToFirstUserMessage(rawMessages, request.systemPrompt)\n const outputConfig =\n request.reasoningEffort === undefined || request.reasoningEffort === 'minimal'\n ? undefined\n : { effort: request.reasoningEffort }\n const baseBody = {\n model: request.model,\n system: [billingSystemBlock, anthropicClaudeIdentitySystemBlock],\n messages,\n max_tokens: config.maxTokens,\n ...(outputConfig === undefined ? {} : { output_config: outputConfig })\n }\n const body: AnthropicRequestBody =\n config.stream === true ? { ...baseBody, stream: true } : baseBody\n\n if (request.tools.length === 0) {\n return body\n }\n\n return {\n ...body,\n tools: request.tools.map(toAnthropicTool)\n }\n })\n\nconst anthropicClaudeProvider = 'anthropic_claude'\n\nconst toHttpClientLlmError =\n (message: string, retryable: boolean, kind: ProviderFailureKind = 'network') =>\n (error: HttpClientError.HttpClientError) =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${error.message}`,\n retryable,\n provider: providerErrorInfo({\n provider: anthropicClaudeProvider,\n kind: retryable ? kind : 'unknown'\n })\n })\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null\n\nconst field = (value: unknown, key: string) =>\n isRecord(value) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined\n\nconst stringField = (value: unknown, key: string) => {\n const raw = field(value, key)\n return typeof raw === 'string' ? raw : undefined\n}\n\ntype AnthropicHttpErrorInfo = {\n readonly message?: string\n readonly providerCode?: string\n}\n\nconst maxAnthropicHttpErrorMessageCharacters = 1_000\n\nconst boundedAnthropicHttpErrorMessage = (message: string) =>\n message.length <= maxAnthropicHttpErrorMessageCharacters\n ? message\n : `${message.slice(0, maxAnthropicHttpErrorMessageCharacters)}…`\n\nconst decodeAnthropicHttpErrorInfo = (\n raw: string\n): Effect.Effect<AnthropicHttpErrorInfo> =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.map(parsed => {\n const error = field(parsed, 'error')\n const message = stringField(error, 'message')\n const providerCode = stringField(error, 'type') ?? stringField(error, 'code')\n\n return {\n ...(message === undefined\n ? {}\n : { message: boundedAnthropicHttpErrorMessage(message) }),\n ...(providerCode === undefined ? {} : { providerCode })\n }\n }),\n Effect.catch(() => Effect.succeed({}))\n )\n\nconst providerSignalError = (input: {\n readonly message: string\n readonly providerCode?: string\n readonly fallbackKind?: ProviderFailureKind\n}) => {\n const provider = classifyProviderFailure({\n provider: anthropicClaudeProvider,\n message: input.message,\n ...(input.providerCode === undefined ? {} : { providerCode: input.providerCode }),\n ...(input.fallbackKind === undefined ? {} : { fallbackKind: input.fallbackKind })\n })\n\n return new LLMError({\n cause: providerFailureCause(provider.kind),\n message: input.message,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n}\n\nconst numberField = (value: unknown, key: string) => {\n const raw = field(value, key)\n return typeof raw === 'number' ? raw : undefined\n}\n\nconst sseDataFromBlock = (block: string) =>\n block\n .split('\\n')\n .filter(line => line.startsWith('data:'))\n .map(line => line.slice('data:'.length).trimStart())\n .join('\\n')\n .trim()\n\nconst dataFromSseBlock = (block: string) => {\n const data = sseDataFromBlock(block)\n\n if (data.length === 0 || data === '[DONE]') {\n return undefined\n }\n\n return data\n}\n\nconst normalizeNewlines = (text: string) => text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\nconst splitCompleteSseBlocks = (buffer: string) => {\n const blocks = buffer.split('\\n\\n')\n const tail = blocks.at(-1) ?? ''\n\n return { completeBlocks: blocks.slice(0, -1), tail }\n}\n\nconst parseToolParams = (raw: string) => {\n const trimmed = raw.trim()\n\n if (trimmed.length === 0) return Effect.succeed({})\n\n return decodeJsonString(trimmed, 'Invalid Anthropic Claude tool arguments JSON')\n}\n\ntype AnthropicUsageComponents = {\n readonly inputTokens: number\n readonly outputTokens: number\n readonly cacheReadInputTokens: number\n readonly cacheCreationInputTokens: number\n}\n\nconst zeroAnthropicUsageComponents: AnthropicUsageComponents = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadInputTokens: 0,\n cacheCreationInputTokens: 0\n}\n\nconst positiveOrUndefined = (value: number) => (value > 0 ? value : undefined)\n\nconst toAgentUsageFromComponents = (usage: AnthropicUsageComponents) =>\n AgentUsage.make({\n input: AgentInputUsage.make({\n total: usage.inputTokens + usage.cacheReadInputTokens + usage.cacheCreationInputTokens,\n uncached: positiveOrUndefined(usage.inputTokens),\n cacheRead: positiveOrUndefined(usage.cacheReadInputTokens),\n cacheWrite: positiveOrUndefined(usage.cacheCreationInputTokens)\n }),\n output: AgentOutputUsage.make({\n total: usage.outputTokens,\n text: positiveOrUndefined(usage.outputTokens)\n })\n })\n\nconst toAgentUsage = (usage: AnthropicUsageResponse) =>\n toAgentUsageFromComponents({\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n cacheReadInputTokens: usage.cache_read_input_tokens ?? 0,\n cacheCreationInputTokens: usage.cache_creation_input_tokens ?? 0\n })\n\nconst nextAnthropicUsageSnapshot = (\n previous: AnthropicUsageComponents,\n usage: AnthropicStreamUsageResponse\n): AnthropicUsageComponents => ({\n inputTokens: usage.input_tokens ?? previous.inputTokens,\n outputTokens: usage.output_tokens ?? previous.outputTokens,\n cacheReadInputTokens: usage.cache_read_input_tokens ?? previous.cacheReadInputTokens,\n cacheCreationInputTokens: usage.cache_creation_input_tokens ?? previous.cacheCreationInputTokens\n})\n\nconst usageComponentDelta = (previous: number, next: number) => Math.max(0, next - previous)\n\nconst anthropicUsageDelta = (\n previous: AnthropicUsageComponents,\n next: AnthropicUsageComponents\n): AnthropicUsageComponents => ({\n inputTokens: usageComponentDelta(previous.inputTokens, next.inputTokens),\n outputTokens: usageComponentDelta(previous.outputTokens, next.outputTokens),\n cacheReadInputTokens: usageComponentDelta(\n previous.cacheReadInputTokens,\n next.cacheReadInputTokens\n ),\n cacheCreationInputTokens: usageComponentDelta(\n previous.cacheCreationInputTokens,\n next.cacheCreationInputTokens\n )\n})\n\nconst hasAnthropicUsage = (usage: AnthropicUsageComponents) =>\n usage.inputTokens > 0 ||\n usage.outputTokens > 0 ||\n usage.cacheReadInputTokens > 0 ||\n usage.cacheCreationInputTokens > 0\n\ntype AnthropicStreamUsageStep = {\n readonly snapshot: AnthropicUsageComponents\n readonly events: ReadonlyArray<LLMEvent>\n}\n\nconst usageStepFromUnknown = (\n usage: unknown,\n previous: AnthropicUsageComponents\n): AnthropicStreamUsageStep => {\n const parsed = Schema.decodeUnknownOption(AnthropicStreamUsageResponse)(usage)\n\n if (parsed._tag === 'None') {\n return { snapshot: previous, events: [] }\n }\n\n const value = parsed.value\n const snapshot = nextAnthropicUsageSnapshot(previous, value)\n const delta = anthropicUsageDelta(previous, snapshot)\n\n return {\n snapshot,\n events: hasAnthropicUsage(delta)\n ? [LLMUsage.make({ usage: toAgentUsageFromComponents(delta) })]\n : []\n }\n}\n\nconst toLlmEvents = (\n response: AnthropicMessageResponse\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n if (response.stop_reason === 'max_tokens') {\n return yield* Effect.fail(anthropicMaxTokensError())\n }\n\n const events = yield* Effect.forEach(response.content, block => {\n switch (block.type) {\n case 'text':\n return Effect.succeed<LLMEvent>(LLMTextDelta.make({ text: block.text }))\n case 'thinking':\n return Effect.succeed<LLMEvent>(LLMReasoningDelta.make({ text: block.thinking }))\n case 'tool_use':\n return Effect.succeed<LLMEvent>(\n LLMToolCall.make({\n call: ToolCall.make({\n id: block.id,\n name: unprefixClaudeToolName(block.name),\n params: block.input\n })\n })\n )\n }\n })\n const stopReason = response.stop_reason === 'tool_use' ? 'tool_use' : 'stop'\n const usageEvent =\n response.usage === undefined ? [] : [LLMUsage.make({ usage: toAgentUsage(response.usage) })]\n\n return [...events, LLMDone.make({ stopReason }), ...usageEvent]\n })\n\nconst decodeAnthropicMessageResponse = (json: unknown) =>\n Schema.decodeUnknownEffect(AnthropicMessageResponse)(json).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid Anthropic Claude response: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst parseAnthropicJsonResponse = (\n raw: string\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const json = yield* decodeJsonString(raw, 'Could not parse Anthropic Claude response JSON')\n const parsed = yield* decodeAnthropicMessageResponse(json)\n\n return yield* toLlmEvents(parsed)\n })\n\ntype AnthropicBodyFormat = 'undecided' | 'sse' | 'json'\n\ntype AnthropicSseState = {\n readonly hasToolCall: boolean\n readonly hasDone: boolean\n readonly stopReason?: string\n readonly usage: AnthropicUsageComponents\n}\n\ntype AnthropicSseStep = {\n readonly state: AnthropicSseState\n readonly events: ReadonlyArray<LLMEvent>\n}\n\ntype AnthropicBodyState = {\n readonly format: AnthropicBodyFormat\n readonly buffer: string\n readonly sse: AnthropicSseState\n}\n\nconst initialSseState: AnthropicSseState = {\n hasToolCall: false,\n hasDone: false,\n usage: zeroAnthropicUsageComponents\n}\n\nconst initialBodyState: AnthropicBodyState = {\n format: 'undecided',\n buffer: '',\n sse: initialSseState\n}\n\nconst classifyAnthropicBody = (buffer: string): AnthropicBodyFormat => {\n const trimmed = buffer.trimStart()\n\n if (trimmed.length === 0) {\n return 'undecided'\n }\n\n if (trimmed.startsWith('event:') || trimmed.startsWith('data:')) {\n return 'sse'\n }\n\n if ('event:'.startsWith(trimmed) || 'data:'.startsWith(trimmed)) {\n return 'undecided'\n }\n\n return 'json'\n}\n\nconst invalidToolUseStartError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Invalid Anthropic Claude tool_use stream block',\n retryable: false\n })\n\nconst anthropicMaxTokensError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Anthropic Claude stopped after reaching max_tokens',\n retryable: false\n })\n\nconst makeAnthropicStreamEmitter = () => {\n const toolBlocks = new Map<number, AnthropicToolBlockState>()\n\n return (state: AnthropicSseState, data: unknown): Effect.Effect<AnthropicSseStep, LLMError> => {\n const type = stringField(data, 'type')\n\n if (type === 'message_start') {\n const message = field(data, 'message')\n const step = usageStepFromUnknown(field(message, 'usage'), state.usage)\n\n return Effect.succeed({ state: { ...state, usage: step.snapshot }, events: step.events })\n }\n\n if (type === 'content_block_start') {\n const index = numberField(data, 'index')\n const block = field(data, 'content_block')\n\n if (index !== undefined && stringField(block, 'type') === 'tool_use') {\n const id = stringField(block, 'id')\n const name = stringField(block, 'name')\n\n if (id === undefined || name === undefined) {\n return Effect.fail(invalidToolUseStartError())\n }\n\n toolBlocks.set(index, {\n id,\n name: unprefixClaudeToolName(name),\n partialJson: ''\n })\n }\n\n return Effect.succeed({ state, events: [] })\n }\n\n if (type === 'content_block_delta') {\n const index = numberField(data, 'index')\n const delta = field(data, 'delta')\n const deltaType = stringField(delta, 'type')\n const text = stringField(delta, 'text')\n const thinking = stringField(delta, 'thinking')\n const partialJson = stringField(delta, 'partial_json')\n\n if (deltaType === 'text_delta' && text !== undefined) {\n return Effect.succeed({ state, events: [LLMTextDelta.make({ text })] })\n }\n\n if (deltaType === 'thinking_delta' && thinking !== undefined) {\n return Effect.succeed({ state, events: [LLMReasoningDelta.make({ text: thinking })] })\n }\n\n if (index !== undefined && deltaType === 'input_json_delta' && partialJson !== undefined) {\n const current = toolBlocks.get(index)\n if (current !== undefined) {\n toolBlocks.set(index, { ...current, partialJson: `${current.partialJson}${partialJson}` })\n }\n }\n\n return Effect.succeed({ state, events: [] })\n }\n\n if (type === 'content_block_stop') {\n const index = numberField(data, 'index')\n const toolBlock = index === undefined ? undefined : toolBlocks.get(index)\n\n if (toolBlock === undefined) return Effect.succeed({ state, events: [] })\n\n return parseToolParams(toolBlock.partialJson).pipe(\n Effect.map(params => {\n if (index !== undefined) toolBlocks.delete(index)\n\n return {\n state: { ...state, hasToolCall: true },\n events: [\n LLMToolCall.make({\n call: ToolCall.make({\n id: toolBlock.id,\n name: toolBlock.name,\n params\n })\n })\n ]\n }\n })\n )\n }\n\n if (type === 'message_delta') {\n const step = usageStepFromUnknown(field(data, 'usage'), state.usage)\n const delta = field(data, 'delta')\n const stopReason = stringField(delta, 'stop_reason')\n\n return Effect.succeed({\n state: {\n ...state,\n usage: step.snapshot,\n ...(stopReason === undefined ? {} : { stopReason })\n },\n events: step.events\n })\n }\n\n if (type === 'message_stop') {\n if (state.stopReason === 'max_tokens') return Effect.fail(anthropicMaxTokensError())\n\n return Effect.succeed({\n state: { ...state, hasDone: true },\n events: [LLMDone.make({ stopReason: state.hasToolCall ? 'tool_use' : 'stop' })]\n })\n }\n\n if (type === 'error') {\n const error = field(data, 'error')\n const providerCode = stringField(error, 'type') ?? stringField(error, 'code')\n\n return Effect.fail(\n providerSignalError({\n message: stringField(error, 'message') ?? 'Anthropic Claude stream error',\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n return Effect.succeed({ state, events: [] })\n }\n}\n\nconst processSseData = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n data: string\n): Effect.Effect<AnthropicSseStep, LLMError> =>\n decodeJsonString(data, 'Could not parse Anthropic Claude stream event JSON').pipe(\n Effect.flatMap(parsed => emitData(state, parsed))\n )\n\nconst processSseBlock = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n block: string\n): Effect.Effect<AnthropicSseStep, LLMError> => {\n const data = dataFromSseBlock(block)\n\n if (data === undefined) {\n return Effect.succeed({ state, events: [] })\n }\n\n return processSseData(emitData, state, data)\n}\n\nconst processSseBlocks = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n blocks: ReadonlyArray<string>\n): Effect.Effect<AnthropicSseStep, LLMError> =>\n Effect.gen(function* () {\n const events: Array<LLMEvent> = []\n let currentState = state\n\n for (const block of blocks) {\n const step = yield* processSseBlock(emitData, currentState, block)\n currentState = step.state\n events.push(...step.events)\n }\n\n return { state: currentState, events }\n })\n\nconst processBodyChunk = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicBodyState,\n chunk: string\n): Effect.Effect<AnthropicSseStep & { readonly bodyState: AnthropicBodyState }, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(`${state.buffer}${chunk}`)\n const format = state.format === 'undecided' ? classifyAnthropicBody(buffer) : state.format\n\n if (format !== 'sse') {\n return {\n state: state.sse,\n bodyState: { ...state, format, buffer },\n events: []\n }\n }\n\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(emitData, state.sse, split.completeBlocks)\n\n return {\n state: step.state,\n bodyState: { format, buffer: split.tail, sse: step.state },\n events: step.events\n }\n })\n\nconst finalizeBodyState = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicBodyState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(state.buffer)\n const format = state.format === 'undecided' ? classifyAnthropicBody(buffer) : state.format\n\n if (format === 'json') {\n return yield* parseAnthropicJsonResponse(buffer)\n }\n\n const events: Array<LLMEvent> = []\n let sseState = state.sse\n\n if (format === 'sse') {\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(emitData, sseState, split.completeBlocks)\n sseState = step.state\n events.push(...step.events)\n\n if (split.tail.trim().length > 0) {\n const tailStep = yield* processSseBlock(emitData, sseState, split.tail)\n sseState = tailStep.state\n events.push(...tailStep.events)\n }\n }\n\n if (sseState.stopReason === 'max_tokens') {\n return yield* Effect.fail(anthropicMaxTokensError())\n }\n\n if (!sseState.hasDone) {\n events.push(LLMDone.make({ stopReason: sseState.hasToolCall ? 'tool_use' : 'stop' }))\n }\n\n return events\n })\n\nexport const streamAnthropicClaudeResponse = (\n response: HttpClientResponse.HttpClientResponse\n): Stream.Stream<LLMEvent, LLMError> =>\n Stream.unwrap(\n Ref.make(initialBodyState).pipe(\n Effect.map(bodyStateRef => {\n const emitData = makeAnthropicStreamEmitter()\n const chunks = response.stream.pipe(\n Stream.mapError(\n toHttpClientLlmError('Could not read Anthropic Claude stream', true, 'stream')\n ),\n Stream.decodeText,\n Stream.mapEffect(chunk =>\n Effect.gen(function* () {\n const state = yield* Ref.get(bodyStateRef)\n const step = yield* processBodyChunk(emitData, state, chunk)\n yield* Ref.set(bodyStateRef, step.bodyState)\n return step.events\n })\n ),\n Stream.flatMap(events => Stream.fromIterable(events))\n )\n const finalEvents = Stream.fromEffect(\n Ref.get(bodyStateRef).pipe(Effect.flatMap(state => finalizeBodyState(emitData, state)))\n ).pipe(Stream.flatMap(events => Stream.fromIterable(events)))\n\n return chunks.pipe(Stream.concat(finalEvents))\n })\n )\n )\n\nconst sendAnthropicClaudeRequest = (\n config: AnthropicClaudeProviderConfig,\n request: LLMRequest,\n client: HttpClient.HttpClient,\n sessionId: string\n): Effect.Effect<HttpClientResponse.HttpClientResponse, LLMError> =>\n Effect.gen(function* () {\n const body = yield* toAnthropicClaudeRequestBody(request, { ...config, stream: true })\n // Replayed transcripts can carry lone surrogates; harden the lowered\n // body so one bad historical string cannot poison every model call.\n const serializedBody = yield* encodeJsonString(\n replaceLoneSurrogatesDeep(body),\n 'Could not serialize Anthropic Claude request'\n )\n const httpRequest = HttpClientRequest.post(\n config.messagesUrl ?? anthropicClaudeMessagesUrl\n ).pipe(\n HttpClientRequest.setHeaders({\n accept: 'text/event-stream',\n ...anthropicClaudeAuthorizationHeaders(config.token),\n 'content-type': 'application/json',\n ...makeAnthropicClaudeCompatibilityHeaders({ model: request.model, sessionId }),\n ...config.extraHeaders\n }),\n HttpClientRequest.bodyText(serializedBody, 'application/json')\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientLlmError('Anthropic Claude request failed', true)))\n\n if (response.status < 200 || response.status >= 300) {\n const errorText = yield* response.text.pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not read Anthropic Claude error body: ${error.message}`,\n retryable: false\n })\n )\n )\n const errorInfo = yield* decodeAnthropicHttpErrorInfo(errorText)\n\n const provider = classifyProviderFailure({\n provider: anthropicClaudeProvider,\n status: response.status,\n headers: response.headers,\n body: errorText,\n ...(errorInfo.message === undefined ? {} : { message: errorInfo.message }),\n ...(errorInfo.providerCode === undefined\n ? {}\n : { providerCode: errorInfo.providerCode })\n })\n const message =\n errorInfo.message === undefined\n ? `Anthropic Claude returned ${response.status}`\n : `Anthropic Claude returned ${response.status}: ${errorInfo.message}`\n\n return yield* Effect.fail(\n new LLMError({\n cause: providerFailureCause(provider.kind),\n message,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n )\n }\n\n return response\n }).pipe(Effect.withSpan('AnthropicClaudeProvider.stream'))\n\nexport const makeAnthropicClaudeProviderLayer = (config: AnthropicClaudeProviderConfig) =>\n Layer.effect(\n LLMProvider,\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const sessionId = makeAnthropicClaudeRequestId()\n\n return LLMProvider.of({\n stream: request =>\n Stream.fromEffect(sendAnthropicClaudeRequest(config, request, client, sessionId)).pipe(\n Stream.flatMap(streamAnthropicClaudeResponse)\n )\n })\n })\n )\n"],"mappings":";;;;;;;;;AA4JA,MAAM,gCAAgC;AACtC,MAAM,+BAA+B;AACrC,MAAM,4BAA4B;AAClC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;AAC/B,MAAM,8BAAqD;CAAC;CAAG;CAAG;AAAE;AACpE,MAAM,4BAA4B;AAClC,MAAM,yCAAyC;AAC/C,MAAM,+BAAsD;CAC1D;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,wCAGD,CACH;CACE,OAAO;CACP,aAAa;AACf,GACA;CACE,OAAO;CACP,aAAa;AACf,CACF;AACA,MAAM,yCAAyC;AAG/C,MAAM,wBAAwB,SAC5B,GAAG,4BAA4B,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC;AAE5E,MAAM,0BAA0B,SAAiB;CAC/C,IAAI,CAAC,KAAK,WAAW,yBAAyB,GAC5C,OAAO;CAGT,MAAM,aAAa,KAAK,MAAM,CAAgC;CAE9D,IAAI,eAAe,oBACjB,OAAO;CAGT,OAAO,GAAG,WAAW,OAAO,CAAC,EAAE,YAAY,IAAI,WAAW,MAAM,CAAC;AACnE;AAEA,MAAM,6BAA6B;AACnC,MAAM,qCAA2D;CAC/D,MAAM;CACN,MAAM;AACR;AAEA,MAAM,aAAa,eAAuB;CACxC,MAAM,SAAS,WAAW;CAC1B,MAAM,QAAQ,IAAI,WAAW,UAAU;CAEvC,IAAI,WAAW,KAAA,KAAa,OAAO,OAAO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QAAQ,SAAS,CAAC,EAAE,KAChF,OAAO,QAAQ,6BAA6B,CAC9C,EACJ,CAAC;AACH,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"claude-provider.mjs","names":["LLMTextDelta","LLMReasoningDelta"],"sources":["../../../src/providers/anthropic/claude-provider.ts"],"sourcesContent":["import { Effect, Layer, Option, Ref, Result, Stream } from 'effect'\nimport {\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentInputUsage,\n AgentOutputUsage,\n AgentUsage,\n ToolCall,\n attachmentSourceText,\n assistantContent,\n assistantHostToolCalls,\n isTextDocumentMimeType,\n messageContextText,\n replaceLoneSurrogatesDeep,\n prependMessageContextToContent,\n type AgentMessage,\n type Content,\n type ContentPart,\n type ProviderFailureKind,\n type ToolDef\n} from '@yolk-sdk/agent/protocol'\nimport {\n LLMError,\n LLMDone,\n LLMProvider,\n LLMReasoningDelta,\n LLMTextDelta,\n LLMToolCall,\n LLMUsage,\n type LLMEvent,\n type LLMRequest\n} from '@yolk-sdk/agent/loop'\nimport {\n anthropicClaudeAuthorizationHeaders,\n anthropicClaudeCodeEntrypoint,\n anthropicClaudeCodeVersion,\n anthropicClaudeOAuthUserAgent\n} from './claude.ts'\nimport type { OAuthAccessToken } from '@yolk-sdk/agent/oauth'\nimport {\n classifyProviderFailure,\n providerErrorInfo,\n providerFailureCause,\n providerFailureRetryable\n} from '../provider-error.ts'\nimport { validateProviderTranscript } from '../transcript.ts'\n\nexport type AnthropicClaudeProviderConfig = {\n readonly token: OAuthAccessToken\n readonly messagesUrl?: string\n readonly maxTokens: number\n readonly extraHeaders?: Readonly<Record<string, string>>\n}\n\ntype AnthropicTextBlock = {\n readonly type: 'text'\n readonly text: string\n}\n\ntype AnthropicSystemBlock = AnthropicTextBlock\n\ntype AnthropicImageBlock = {\n readonly type: 'image'\n readonly source:\n | {\n readonly type: 'base64'\n readonly media_type: string\n readonly data: string\n }\n | {\n readonly type: 'url'\n readonly url: string\n }\n}\n\ntype AnthropicDocumentBlock = {\n readonly type: 'document'\n readonly source:\n | {\n readonly type: 'base64'\n readonly media_type: 'application/pdf'\n readonly data: string\n }\n | {\n readonly type: 'url'\n readonly url: string\n }\n readonly title?: string\n}\n\ntype AnthropicToolUseBlock = {\n readonly type: 'tool_use'\n readonly id: string\n readonly name: string\n readonly input: unknown\n}\n\ntype AnthropicToolResultContentBlock =\n | AnthropicTextBlock\n | AnthropicImageBlock\n | AnthropicDocumentBlock\n\ntype AnthropicToolResultBlock = {\n readonly type: 'tool_result'\n readonly tool_use_id: string\n readonly content: string | ReadonlyArray<AnthropicToolResultContentBlock>\n readonly is_error?: boolean\n}\n\ntype AnthropicUserBlock =\n | AnthropicTextBlock\n | AnthropicImageBlock\n | AnthropicDocumentBlock\n | AnthropicToolResultBlock\ntype AnthropicAssistantBlock = AnthropicTextBlock | AnthropicToolUseBlock\n\ntype AnthropicMessage =\n | { readonly role: 'user'; readonly content: string | ReadonlyArray<AnthropicUserBlock> }\n | { readonly role: 'assistant'; readonly content: ReadonlyArray<AnthropicAssistantBlock> }\n\ntype JsonObject = Readonly<Record<string, unknown>>\ntype TopLevelJsonSchemaCombinatorKey = 'anyOf' | 'oneOf' | 'allOf'\ntype TopLevelJsonSchemaCombinator = {\n readonly key: TopLevelJsonSchemaCombinatorKey\n readonly items: ReadonlyArray<unknown>\n}\n\ntype AnthropicTool = {\n readonly name: string\n readonly description: string\n readonly input_schema: unknown\n}\n\ntype AnthropicRequestBody = {\n readonly model: string\n readonly system: ReadonlyArray<AnthropicSystemBlock>\n readonly messages: ReadonlyArray<AnthropicMessage>\n readonly max_tokens: number\n readonly output_config?: {\n readonly effort: 'low' | 'medium' | 'high' | 'xhigh'\n }\n readonly stream?: true\n readonly tools?: ReadonlyArray<AnthropicTool>\n}\n\ntype AnthropicToolBlockState = {\n readonly id: string\n readonly name: string\n readonly partialJson: string\n}\n\nconst anthropicClaudeSystemIdentity = \"You are Claude Code, Anthropic's official CLI for Claude.\"\nconst anthropicClaudeBillingPrefix = 'x-anthropic-billing-header:'\nconst anthropicClaudeToolPrefix = 'mcp_'\nconst anthropicClaudeVersion = '2023-06-01'\nconst anthropicClaudeCchSalt = '59cf53e54c78'\nconst anthropicClaudeCchPositions: ReadonlyArray<number> = [4, 7, 20]\nconst anthropicClaudeEffortBeta = 'effort-2025-11-24'\nconst anthropicClaudeInterleavedThinkingBeta = 'interleaved-thinking-2025-05-14'\nconst anthropicClaudeRequiredBetas: ReadonlyArray<string> = [\n 'claude-code-20250219',\n 'oauth-2025-04-20',\n anthropicClaudeInterleavedThinkingBeta,\n 'prompt-caching-scope-2026-01-05',\n 'context-management-2025-06-27',\n 'advisor-tool-2026-03-01'\n]\nconst anthropicClaudeSystemTextReplacements: ReadonlyArray<{\n readonly match: string\n readonly replacement: string\n}> = [\n {\n match: 'if OpenCode honestly',\n replacement: 'if the assistant honestly'\n },\n {\n match: 'Here is some useful information about the environment you are running in:',\n replacement: 'Environment context you are running in:'\n }\n]\nconst anthropicClaudeStainlessPackageVersion = '0.81.0'\n\n// Claude subscription OAuth is fingerprinted against Claude Code tool names.\nconst prefixClaudeToolName = (name: string) =>\n `${anthropicClaudeToolPrefix}${name.charAt(0).toUpperCase()}${name.slice(1)}`\n\nconst unprefixClaudeToolName = (name: string) => {\n if (!name.startsWith(anthropicClaudeToolPrefix)) {\n return name\n }\n\n const unprefixed = name.slice(anthropicClaudeToolPrefix.length)\n\n if (unprefixed === 'StructuredOutput') {\n return unprefixed\n }\n\n return `${unprefixed.charAt(0).toLowerCase()}${unprefixed.slice(1)}`\n}\n\nconst anthropicClaudeMessagesUrl = 'https://api.anthropic.com/v1/messages?beta=true'\nconst anthropicClaudeIdentitySystemBlock: AnthropicSystemBlock = {\n type: 'text',\n text: anthropicClaudeSystemIdentity\n}\n\nconst randomHex = (byteLength: number) => {\n const crypto = globalThis.crypto\n const bytes = new Uint8Array(byteLength)\n\n if (crypto !== undefined && typeof crypto.getRandomValues === 'function') {\n crypto.getRandomValues(bytes)\n }\n\n return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n}\n\nconst makeAnthropicClaudeRequestId = () => {\n const crypto = globalThis.crypto\n\n if (crypto !== undefined && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID()\n }\n\n return randomHex(16)\n}\n\nconst sha256Hex = (value: string): Effect.Effect<string, LLMError> => {\n const crypto = globalThis.crypto\n\n if (crypto === undefined || crypto.subtle === undefined) {\n return Effect.fail(\n new LLMError({\n cause: 'provider_error',\n message: 'Web Crypto SHA-256 is required for Anthropic Claude OAuth billing headers',\n retryable: false\n })\n )\n }\n\n return Effect.tryPromise({\n try: () =>\n crypto.subtle\n .digest('SHA-256', new TextEncoder().encode(value))\n .then(buffer =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n ),\n catch: error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not compute Anthropic Claude OAuth billing header: ${unknownToMessage(error)}`,\n retryable: false\n })\n })\n}\n\nconst computeAnthropicClaudeCch = (messageText: string) =>\n sha256Hex(messageText).pipe(Effect.map(hash => hash.slice(0, 5)))\n\nconst computeAnthropicClaudeVersionSuffix = (messageText: string) => {\n const chars = anthropicClaudeCchPositions.map(index => messageText[index] ?? '0').join('')\n\n return sha256Hex(`${anthropicClaudeCchSalt}${chars}${anthropicClaudeCodeVersion}`).pipe(\n Effect.map(hash => hash.slice(0, 3))\n )\n}\n\nconst firstUserMessageText = (messages: ReadonlyArray<AnthropicMessage>) => {\n for (const message of messages) {\n if (message.role !== 'user') {\n continue\n }\n\n if (typeof message.content === 'string') {\n return message.content\n }\n\n for (const block of message.content) {\n if (block.type === 'text') {\n return block.text\n }\n }\n }\n\n return ''\n}\n\nconst makeAnthropicClaudeBillingSystemBlock = (\n messages: ReadonlyArray<AnthropicMessage>\n): Effect.Effect<AnthropicSystemBlock, LLMError> => {\n const text = firstUserMessageText(messages)\n\n return Effect.all({\n cch: computeAnthropicClaudeCch(text),\n suffix: computeAnthropicClaudeVersionSuffix(text)\n }).pipe(\n Effect.map(\n ({ cch, suffix }): AnthropicSystemBlock => ({\n type: 'text',\n text:\n `${anthropicClaudeBillingPrefix} ` +\n `cc_version=${anthropicClaudeCodeVersion}.${suffix}; ` +\n `cc_entrypoint=${anthropicClaudeCodeEntrypoint}; ` +\n `cch=${cch};`\n })\n )\n )\n}\n\nconst sanitizeAnthropicClaudeSystemText = (text: string) => {\n let result = text\n\n for (const rule of anthropicClaudeSystemTextReplacements) {\n result = result.split(rule.match).join(rule.replacement)\n }\n\n return result\n}\n\nconst anthropicClaudeBetaHeader = (model: string) => {\n const lowerModel = model.toLowerCase()\n const baseBetas = lowerModel.includes('haiku')\n ? anthropicClaudeRequiredBetas.filter(beta => beta !== anthropicClaudeInterleavedThinkingBeta)\n : anthropicClaudeRequiredBetas\n\n if (\n !lowerModel.includes('haiku') &&\n (lowerModel.includes('4-6') || lowerModel.includes('4-7')) &&\n !baseBetas.includes(anthropicClaudeEffortBeta)\n ) {\n return [...baseBetas, anthropicClaudeEffortBeta].join(',')\n }\n\n return baseBetas.join(',')\n}\n\nconst makeAnthropicClaudeCompatibilityHeaders = (input: {\n readonly model: string\n readonly sessionId: string\n}) => ({\n 'anthropic-beta': anthropicClaudeBetaHeader(input.model),\n 'anthropic-dangerous-direct-browser-access': 'true',\n 'anthropic-version': anthropicClaudeVersion,\n 'user-agent': anthropicClaudeOAuthUserAgent,\n 'x-app': 'cli',\n 'x-client-request-id': makeAnthropicClaudeRequestId(),\n 'X-Claude-Code-Session-Id': input.sessionId,\n 'x-stainless-arch': 'unknown',\n 'x-stainless-lang': 'js',\n 'x-stainless-os': 'unknown',\n 'x-stainless-package-version': anthropicClaudeStainlessPackageVersion,\n 'x-stainless-retry-count': '0',\n 'x-stainless-runtime': 'node',\n 'x-stainless-runtime-version': 'unknown',\n 'x-stainless-timeout': '600'\n})\n\n// Keep app instructions out of `system[]`; Anthropic can reject/limit otherwise.\nconst prependSystemPromptToFirstUserMessage = (\n messages: ReadonlyArray<AnthropicMessage>,\n systemPrompt: string\n): ReadonlyArray<AnthropicMessage> => {\n const sanitizedSystemPrompt = sanitizeAnthropicClaudeSystemText(systemPrompt).trim()\n\n if (sanitizedSystemPrompt.length === 0) {\n return messages\n }\n\n let relocated = false\n\n return messages.map(message => {\n if (relocated || message.role !== 'user') {\n return message\n }\n\n relocated = true\n\n if (typeof message.content === 'string') {\n return { ...message, content: `${sanitizedSystemPrompt}\\n\\n${message.content}` }\n }\n\n return {\n ...message,\n content: [{ type: 'text', text: sanitizedSystemPrompt }, ...message.content]\n }\n })\n}\n\nclass AnthropicTextResponseBlock extends Schema.Class<AnthropicTextResponseBlock>(\n 'AnthropicTextResponseBlock'\n)({\n type: Schema.Literal('text'),\n text: Schema.String\n}) {}\n\nclass AnthropicThinkingResponseBlock extends Schema.Class<AnthropicThinkingResponseBlock>(\n 'AnthropicThinkingResponseBlock'\n)({\n type: Schema.Literal('thinking'),\n thinking: Schema.String\n}) {}\n\nclass AnthropicToolUseResponseBlock extends Schema.Class<AnthropicToolUseResponseBlock>(\n 'AnthropicToolUseResponseBlock'\n)({\n type: Schema.Literal('tool_use'),\n id: Schema.String,\n name: Schema.String,\n input: Schema.Unknown\n}) {}\n\nconst AnthropicContentResponseBlock = Schema.Union([\n AnthropicTextResponseBlock,\n AnthropicThinkingResponseBlock,\n AnthropicToolUseResponseBlock\n])\n\nclass AnthropicUsageResponse extends Schema.Class<AnthropicUsageResponse>('AnthropicUsageResponse')(\n {\n input_tokens: Schema.Number,\n output_tokens: Schema.Number,\n cache_read_input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_creation_input_tokens: Schema.optional(Schema.NullOr(Schema.Number))\n }\n) {}\n\nclass AnthropicStreamUsageResponse extends Schema.Class<AnthropicStreamUsageResponse>(\n 'AnthropicStreamUsageResponse'\n)({\n input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n output_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_read_input_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n cache_creation_input_tokens: Schema.optional(Schema.NullOr(Schema.Number))\n}) {}\n\nclass AnthropicMessageResponse extends Schema.Class<AnthropicMessageResponse>(\n 'AnthropicMessageResponse'\n)({\n content: Schema.Array(AnthropicContentResponseBlock),\n stop_reason: Schema.NullOr(Schema.String),\n usage: Schema.optional(AnthropicUsageResponse)\n}) {}\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst unsupportedContentError = (contentType: string) =>\n new LLMError({\n cause: 'provider_error',\n message: `${contentType} content is not supported by the Anthropic Claude provider yet`,\n retryable: false\n })\n\nconst imageToAnthropicBlock = (\n part: Extract<ContentPart, { readonly _tag: 'Image' }>\n): Effect.Effect<AnthropicImageBlock, LLMError> => {\n switch (part.source._tag) {\n case 'InlineBase64':\n return Effect.succeed({\n type: 'image',\n source: {\n type: 'base64',\n media_type: part.mimeType,\n data: part.source.data\n }\n })\n case 'Url':\n return Effect.succeed({\n type: 'image',\n source: {\n type: 'url',\n url: part.source.url\n }\n })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved image source'))\n }\n}\n\nconst pdfDocumentToAnthropicBlock = (\n part: Extract<ContentPart, { readonly _tag: 'Document' }>\n): Effect.Effect<AnthropicDocumentBlock, LLMError> => {\n switch (part.source._tag) {\n case 'InlineBase64':\n return Effect.succeed({\n type: 'document',\n source: {\n type: 'base64',\n media_type: 'application/pdf',\n data: part.source.data\n },\n title: part.title ?? part.filename\n })\n case 'Url':\n return Effect.succeed({\n type: 'document',\n source: {\n type: 'url',\n url: part.source.url\n },\n title: part.title ?? part.filename\n })\n case 'Ref':\n return Effect.fail(unsupportedContentError('Unresolved document source'))\n }\n}\n\nconst textDocumentToAnthropicBlock = (part: Extract<ContentPart, { readonly _tag: 'Document' }>) =>\n attachmentSourceText(part.source).pipe(\n Effect.mapError(() => unsupportedContentError('Invalid document text')),\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.fail(unsupportedContentError('Unresolved document source')),\n onSome: text => {\n const block: AnthropicTextBlock = {\n type: 'text',\n text: `Document: ${part.title ?? part.filename}\\n\\n${text}`\n }\n\n return Effect.succeed(block)\n }\n })\n )\n )\n\nconst contentPartToAnthropicBlock = (\n part: ContentPart\n): Effect.Effect<AnthropicToolResultContentBlock, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed({ type: 'text', text: part.text })\n case 'Image':\n return imageToAnthropicBlock(part)\n case 'Document':\n return isTextDocumentMimeType(part.mimeType)\n ? textDocumentToAnthropicBlock(part)\n : part.mimeType === 'application/pdf'\n ? pdfDocumentToAnthropicBlock(part)\n : Effect.fail(unsupportedContentError(`Document ${part.mimeType}`))\n case 'Audio':\n return Effect.fail(unsupportedContentError('Audio'))\n }\n}\n\nconst contentToAnthropicContent = (\n content: Content\n): Effect.Effect<string | ReadonlyArray<AnthropicToolResultContentBlock>, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, contentPartToAnthropicBlock)\n\nconst contentPartToText = (part: ContentPart, owner: string): Effect.Effect<string, LLMError> => {\n switch (part._tag) {\n case 'Text':\n return Effect.succeed(part.text)\n case 'Image':\n return Effect.fail(unsupportedContentError(`${owner} image`))\n case 'Document':\n return Effect.fail(unsupportedContentError(`${owner} document`))\n case 'Audio':\n return Effect.fail(unsupportedContentError(`${owner} audio`))\n }\n}\n\nconst contentToText = (content: Content, owner: string): Effect.Effect<string, LLMError> =>\n typeof content === 'string'\n ? Effect.succeed(content)\n : Effect.forEach(content, part => contentPartToText(part, owner)).pipe(\n Effect.map(textParts => textParts.join('\\n'))\n )\n\nconst toolCallToAnthropicBlock = (call: ToolCall): AnthropicToolUseBlock => ({\n type: 'tool_use',\n id: call.id,\n name: prefixClaudeToolName(call.name),\n input: call.params\n})\n\nconst isJsonObject = (value: unknown): value is JsonObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst jsonObjectField = (value: JsonObject, key: string) =>\n Object.getOwnPropertyDescriptor(value, key)?.value\n\n// Claude subscription OAuth validates tool schemas more narrowly than the regular\n// Anthropic API: combinators and tuple-only prefixItems can be rejected even when\n// they are valid JSON Schema. Effect Schema emits those constructs for unions,\n// refinements, and tuples, so the provider needs a compatibility projection.\n//\n// This projection is model guidance, not the execution validator. Whenever an\n// unsupported constraint cannot be represented faithfully, normalization must\n// widen it (usually to {}) rather than exclude an input accepted by the original\n// schema. makeTool continues to validate calls against that original Effect Schema.\nconst topLevelJsonSchemaCombinatorKeys: ReadonlyArray<TopLevelJsonSchemaCombinatorKey> = [\n 'anyOf',\n 'oneOf',\n 'allOf'\n]\n\nconst isTopLevelJsonSchemaCombinatorKey = (key: string): key is TopLevelJsonSchemaCombinatorKey =>\n key === 'anyOf' || key === 'oneOf' || key === 'allOf'\n\nconst topLevelJsonSchemaCombinator = (\n schema: JsonObject\n): TopLevelJsonSchemaCombinator | undefined => {\n for (const key of topLevelJsonSchemaCombinatorKeys) {\n const value = jsonObjectField(schema, key)\n\n if (Array.isArray(value)) {\n return { key, items: value }\n }\n }\n\n return undefined\n}\n\nconst withoutTopLevelJsonSchemaCombinators = (schema: JsonObject): JsonObject =>\n Object.fromEntries(\n Object.entries(schema).filter(([key]) => !isTopLevelJsonSchemaCombinatorKey(key))\n )\n\nconst withoutJsonSchemaCombinatorsAndTupleHints = (schema: JsonObject): JsonObject =>\n Object.fromEntries(\n Object.entries(schema).filter(\n ([key]) =>\n !isTopLevelJsonSchemaCombinatorKey(key) &&\n key !== 'prefixItems' &&\n key !== 'not' &&\n key !== 'if' &&\n key !== 'then' &&\n key !== 'else'\n )\n )\n\nconst jsonSchemaMap = (schema: JsonObject, key: string) => {\n const value = jsonObjectField(schema, key)\n\n return isJsonObject(value) ? value : {}\n}\n\nconst jsonSchemaProperties = (schema: JsonObject) => jsonSchemaMap(schema, 'properties')\n\nconst jsonSchemaDefinitions = (schema: JsonObject) => {\n const definitions = jsonObjectField(schema, '$defs')\n\n return isJsonObject(definitions) ? definitions : {}\n}\n\nconst jsonSchemaRequired = (schema: JsonObject) => {\n const required = jsonObjectField(schema, 'required')\n\n return Array.isArray(required) ? required.filter(item => typeof item === 'string') : []\n}\n\nconst jsonValueKey = (value: unknown) =>\n Result.try(() => JSON.stringify(value)).pipe(\n Result.match({\n onFailure: () => undefined,\n onSuccess: encoded => encoded\n })\n )\n\nconst uniqueUnknownArray = (items: ReadonlyArray<unknown>): ReadonlyArray<unknown> => {\n const seen = new Set<string>()\n const result: Array<unknown> = []\n\n for (const item of items) {\n const key = jsonValueKey(item)\n\n if (key === undefined || seen.has(key)) {\n continue\n }\n\n seen.add(key)\n result.push(item)\n }\n\n return result\n}\n\nconst mergeEnumPropertySchemas = (left: unknown, right: unknown): unknown | undefined => {\n if (!isJsonObject(left) || !isJsonObject(right)) {\n return undefined\n }\n\n const leftEnum = jsonObjectField(left, 'enum')\n const rightEnum = jsonObjectField(right, 'enum')\n\n if (!Array.isArray(leftEnum) || !Array.isArray(rightEnum)) {\n return undefined\n }\n\n const leftType = jsonObjectField(left, 'type')\n const rightType = jsonObjectField(right, 'type')\n\n if (leftType !== rightType) {\n return undefined\n }\n\n const descriptions = [jsonObjectField(left, 'description'), jsonObjectField(right, 'description')]\n const description = descriptions.find(value => typeof value === 'string')\n\n return {\n ...(leftType === undefined ? {} : { type: leftType }),\n enum: uniqueUnknownArray([...leftEnum, ...rightEnum]),\n ...(description === undefined ? {} : { description })\n }\n}\n\nconst mergePropertySchemas = (left: unknown, right: unknown): unknown => {\n const leftKey = jsonValueKey(left)\n\n if (leftKey !== undefined && leftKey === jsonValueKey(right)) {\n return left\n }\n\n const mergedEnum = mergeEnumPropertySchemas(left, right)\n\n if (mergedEnum !== undefined) {\n return mergedEnum\n }\n\n // Anthropic rejects combinators in tool schemas. An unconstrained schema\n // preserves every value accepted by either incompatible variant; makeTool\n // still validates calls against the complete original Effect Schema.\n return {}\n}\n\nconst mergeJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject => {\n const merged = new Map<string, unknown>()\n\n for (const object of objects) {\n for (const [key, value] of Object.entries(object)) {\n if (merged.has(key)) {\n merged.set(key, mergePropertySchemas(merged.get(key), value))\n } else {\n merged.set(key, value)\n }\n }\n }\n\n return Object.fromEntries(merged)\n}\n\nconst mergeUnionJsonSchemaObjects = (\n objects: ReadonlyArray<JsonObject>,\n owners?: ReadonlyArray<JsonObject>\n): JsonObject => {\n const keys = new Set(objects.flatMap(object => Object.keys(object)))\n\n return Object.fromEntries(\n Array.from(keys, key => {\n const values = objects.flatMap((object, index) => {\n if (Object.hasOwn(object, key)) return [jsonObjectField(object, key)]\n\n const additionalProperties = owners?.[index]\n if (additionalProperties === undefined) return []\n\n const additionalPropertySchema = jsonObjectField(additionalProperties, 'additionalProperties')\n if (additionalPropertySchema === false) return []\n\n return [isJsonObject(additionalPropertySchema) ? additionalPropertySchema : {}]\n })\n const [first, ...rest] = values\n\n return [key, rest.reduce(mergePropertySchemas, first)]\n })\n )\n}\n\nconst mergeRightBiasedJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject =>\n Object.assign({}, ...objects)\n\nconst mergeAllOfSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject => {\n const merged = mergeRightBiasedJsonSchemaObjects(objects)\n const properties = mergeRightBiasedJsonSchemaObjects(objects.map(jsonSchemaProperties))\n const required = mergeJsonSchemaRequired('allOf', objects)\n const definitions = mergeJsonSchemaObjects(objects.map(jsonSchemaDefinitions))\n\n return {\n ...merged,\n ...(Object.keys(properties).length === 0 ? {} : { properties }),\n ...(required.length === 0 ? {} : { required }),\n ...(Object.keys(definitions).length === 0 ? {} : { $defs: definitions })\n }\n}\n\n// JSON objects are not always schemas. Values under schema-map keywords are\n// schemas, while values under data keywords are literals and must remain opaque;\n// recursively normalizing enum data or property/definition names can corrupt it.\nconst jsonSchemaMapKeywords = new Set([\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas'\n])\n\nconst jsonSchemaDataKeywords = new Set(['const', 'default', 'enum', 'examples'])\n\nconst normalizeJsonSchemaObjectFields = (schema: JsonObject): JsonObject => {\n const normalized = Object.fromEntries(\n Object.entries(withoutJsonSchemaCombinatorsAndTupleHints(schema)).map(([key, value]) => {\n if (jsonSchemaDataKeywords.has(key)) return [key, value]\n\n if (key === 'dependencies' && isJsonObject(value)) {\n return [\n key,\n Object.fromEntries(\n Object.entries(value).map(([name, dependency]) => [\n name,\n Array.isArray(dependency) ? dependency : normalizeAnthropicToolSchema(dependency)\n ])\n )\n ]\n }\n\n if (jsonSchemaMapKeywords.has(key) && isJsonObject(value)) {\n return [\n key,\n Object.fromEntries(\n Object.entries(value).map(([name, childSchema]) => [\n name,\n normalizeAnthropicToolSchema(childSchema)\n ])\n )\n ]\n }\n\n return [key, normalizeAnthropicToolSchema(value)]\n })\n )\n\n if (Array.isArray(jsonObjectField(schema, 'prefixItems'))) {\n return { ...normalized, items: {} }\n }\n\n return normalized\n}\n\nconst jsonSchemaType = (schema: JsonObject) => {\n const type = jsonObjectField(schema, 'type')\n\n return typeof type === 'string' ? type : undefined\n}\n\nconst firstJsonObject = (items: ReadonlyArray<JsonObject>) => items[0]\n\nconst independentCommonVariantKeys = new Set([\n 'type',\n 'enum',\n 'const',\n 'format',\n 'pattern',\n 'minLength',\n 'maxLength',\n 'minimum',\n 'maximum',\n 'exclusiveMinimum',\n 'exclusiveMaximum',\n 'multipleOf',\n 'minItems',\n 'maxItems',\n 'uniqueItems',\n 'minProperties',\n 'maxProperties',\n 'description'\n])\n\nconst commonVariantFields = (variants: ReadonlyArray<JsonObject>): JsonObject => {\n const first = firstJsonObject(variants)\n if (first === undefined) return {}\n if (variants.length === 1) return first\n\n return Object.fromEntries(\n Object.entries(first).filter(([key, value]) => {\n if (!independentCommonVariantKeys.has(key)) return false\n\n const valueKey = jsonValueKey(value)\n return valueKey !== undefined && variants.every(variant => valueKey === jsonValueKey(jsonObjectField(variant, key)))\n })\n )\n}\n\nconst objectVariant = (variants: ReadonlyArray<JsonObject>): JsonObject | undefined => {\n if (variants.length === 0 || variants.some(variant => jsonSchemaType(variant) !== 'object')) {\n return undefined\n }\n\n if (\n variants.some(variant => Object.keys(jsonSchemaMap(variant, 'patternProperties')).length > 0)\n ) {\n return { type: 'object' }\n }\n\n const additionalProperties = mergeAdditionalProperties(variants)\n\n return {\n type: 'object',\n properties: mergeUnionJsonSchemaObjects(variants.map(jsonSchemaProperties), variants),\n required: mergeJsonSchemaRequired('oneOf', variants),\n $defs: mergeJsonSchemaObjects(variants.map(jsonSchemaDefinitions)),\n ...(additionalProperties === undefined ? {} : { additionalProperties })\n }\n}\n\nconst normalizeJsonSchemaCombinator = (\n schema: JsonObject,\n combinator: TopLevelJsonSchemaCombinator\n): JsonObject => {\n const base = normalizeJsonSchemaObjectFields(schema)\n const normalizedItems = combinator.items.map(normalizeAnthropicToolSchema)\n const variants = normalizedItems.filter(isJsonObject)\n const first = firstJsonObject(variants)\n\n if (combinator.key === 'allOf') {\n return mergeAllOfSchemaObjects([base, ...variants])\n }\n\n if (normalizedItems.includes(true)) return base\n if (first === undefined) return base\n\n const merged = objectVariant(variants) ?? commonVariantFields(variants)\n\n return mergeAllOfSchemaObjects([merged, base])\n}\n\nfunction normalizeAnthropicToolSchema(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(normalizeAnthropicToolSchema)\n if (!isJsonObject(value)) return value\n\n const combinator = topLevelJsonSchemaCombinator(value)\n if (combinator !== undefined) return normalizeJsonSchemaCombinator(value, combinator)\n\n return normalizeJsonSchemaObjectFields(value)\n}\n\nconst mergeJsonSchemaRequired = (\n combinatorKey: TopLevelJsonSchemaCombinatorKey,\n objects: ReadonlyArray<JsonObject>\n): ReadonlyArray<string> => {\n const requiredSets = objects.map(jsonSchemaRequired)\n\n if (requiredSets.length === 0) {\n return []\n }\n\n if (combinatorKey === 'allOf') {\n return Array.from(new Set(requiredSets.flat()))\n }\n\n const first = requiredSets[0] ?? []\n\n return first.filter(item => requiredSets.every(required => required.includes(item)))\n}\n\nconst mergeAdditionalProperties = (objects: ReadonlyArray<JsonObject>) => {\n const values = objects.map(object => jsonObjectField(object, 'additionalProperties'))\n\n if (values.every(value => value === false)) {\n return false\n }\n\n if (values.every(value => value === true)) {\n return true\n }\n\n return undefined\n}\n\n// Anthropic rejects root combinators. This widens provider-facing guidance only;\n// tool execution still validates calls against the original registry schema.\nconst flattenTopLevelCombinatorToolSchema = (\n schema: JsonObject,\n combinator: TopLevelJsonSchemaCombinator\n): JsonObject => {\n const base = withoutTopLevelJsonSchemaCombinators(schema)\n const objectVariants = combinator.items.filter(isJsonObject)\n const hasUnconstrainedUnion =\n combinator.key !== 'allOf' &&\n combinator.items.some(item => item === true || !isJsonObject(item))\n const additionalProperties = mergeAdditionalProperties(objectVariants)\n const flattened = {\n ...base,\n type: 'object',\n properties: hasUnconstrainedUnion\n ? {}\n : combinator.key === 'allOf'\n ? mergeRightBiasedJsonSchemaObjects(objectVariants.map(jsonSchemaProperties))\n : mergeUnionJsonSchemaObjects(objectVariants.map(jsonSchemaProperties), objectVariants),\n required: hasUnconstrainedUnion\n ? []\n : mergeJsonSchemaRequired(combinator.key, objectVariants),\n $defs: mergeJsonSchemaObjects([\n jsonSchemaDefinitions(schema),\n ...objectVariants.map(jsonSchemaDefinitions)\n ])\n }\n\n if (hasUnconstrainedUnion || additionalProperties === undefined) {\n return flattened\n }\n\n return { ...flattened, additionalProperties }\n}\n\nconst anthropicToolInputSchema = (schema: unknown): unknown => {\n if (!isJsonObject(schema)) {\n return schema === true\n ? { type: 'object', properties: {} }\n : {\n type: 'object',\n properties: {},\n required: [],\n additionalProperties: false\n }\n }\n\n const combinator = topLevelJsonSchemaCombinator(schema)\n\n if (combinator !== undefined) {\n return normalizeAnthropicToolSchema(flattenTopLevelCombinatorToolSchema(schema, combinator))\n }\n\n if (jsonObjectField(schema, 'type') !== undefined) {\n return normalizeAnthropicToolSchema(schema)\n }\n\n return normalizeAnthropicToolSchema({ ...schema, type: 'object' })\n}\n\nconst toAnthropicMessage = (message: AgentMessage): Effect.Effect<AnthropicMessage, LLMError> =>\n Effect.gen(function* () {\n switch (message._tag) {\n case 'User':\n return {\n role: 'user',\n content: yield* contentToAnthropicContent(\n prependMessageContextToContent(message.content, messageContextText(message))\n )\n }\n case 'Assistant': {\n const text = yield* contentToText(\n prependMessageContextToContent(assistantContent(message), messageContextText(message)),\n 'Assistant'\n )\n const textBlocks: ReadonlyArray<AnthropicTextBlock> =\n text.length === 0 ? [] : [{ type: 'text', text }]\n const toolBlocks = assistantHostToolCalls(message).map(toolCallToAnthropicBlock)\n return { role: 'assistant', content: [...textBlocks, ...toolBlocks] }\n }\n case 'ToolResult':\n return {\n role: 'user',\n content: [\n {\n type: 'tool_result',\n tool_use_id: message.toolCallId,\n content: yield* contentToAnthropicContent(\n prependMessageContextToContent(message.content, messageContextText(message))\n ),\n is_error: message.isError\n }\n ]\n }\n }\n })\n\nconst toAnthropicTool = (tool: ToolDef): AnthropicTool => ({\n name: prefixClaudeToolName(tool.name),\n description: tool.description,\n input_schema: anthropicToolInputSchema(tool.parameters)\n})\n\nexport const toAnthropicClaudeRequestBody = (\n request: LLMRequest,\n config: { readonly maxTokens: number; readonly stream?: boolean }\n): Effect.Effect<AnthropicRequestBody, LLMError> =>\n Effect.gen(function* () {\n yield* validateProviderTranscript(request.messages)\n const rawMessages = yield* Effect.forEach(request.messages, toAnthropicMessage)\n const billingSystemBlock = yield* makeAnthropicClaudeBillingSystemBlock(rawMessages)\n const messages = prependSystemPromptToFirstUserMessage(rawMessages, request.systemPrompt)\n const outputConfig =\n request.reasoningEffort === undefined || request.reasoningEffort === 'minimal'\n ? undefined\n : { effort: request.reasoningEffort }\n const baseBody = {\n model: request.model,\n system: [billingSystemBlock, anthropicClaudeIdentitySystemBlock],\n messages,\n max_tokens: config.maxTokens,\n ...(outputConfig === undefined ? {} : { output_config: outputConfig })\n }\n const body: AnthropicRequestBody =\n config.stream === true ? { ...baseBody, stream: true } : baseBody\n\n if (request.tools.length === 0) {\n return body\n }\n\n return {\n ...body,\n tools: request.tools.map(toAnthropicTool)\n }\n })\n\nconst anthropicClaudeProvider = 'anthropic_claude'\n\nconst toHttpClientLlmError =\n (message: string, retryable: boolean, kind: ProviderFailureKind = 'network') =>\n (error: HttpClientError.HttpClientError) =>\n new LLMError({\n cause: 'provider_error',\n message: `${message}: ${error.message}`,\n retryable,\n provider: providerErrorInfo({\n provider: anthropicClaudeProvider,\n kind: retryable ? kind : 'unknown'\n })\n })\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `${message}: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null\n\nconst field = (value: unknown, key: string) =>\n isRecord(value) ? Object.getOwnPropertyDescriptor(value, key)?.value : undefined\n\nconst stringField = (value: unknown, key: string) => {\n const raw = field(value, key)\n return typeof raw === 'string' ? raw : undefined\n}\n\ntype AnthropicHttpErrorInfo = {\n readonly message?: string\n readonly providerCode?: string\n}\n\nconst maxAnthropicHttpErrorMessageCharacters = 1_000\n\nconst boundedAnthropicHttpErrorMessage = (message: string) =>\n message.length <= maxAnthropicHttpErrorMessageCharacters\n ? message\n : `${message.slice(0, maxAnthropicHttpErrorMessageCharacters)}…`\n\nconst decodeAnthropicHttpErrorInfo = (\n raw: string\n): Effect.Effect<AnthropicHttpErrorInfo> =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.map(parsed => {\n const error = field(parsed, 'error')\n const message = stringField(error, 'message')\n const providerCode = stringField(error, 'type') ?? stringField(error, 'code')\n\n return {\n ...(message === undefined\n ? {}\n : { message: boundedAnthropicHttpErrorMessage(message) }),\n ...(providerCode === undefined ? {} : { providerCode })\n }\n }),\n Effect.catch(() => Effect.succeed({}))\n )\n\nconst providerSignalError = (input: {\n readonly message: string\n readonly providerCode?: string\n readonly fallbackKind?: ProviderFailureKind\n}) => {\n const provider = classifyProviderFailure({\n provider: anthropicClaudeProvider,\n message: input.message,\n ...(input.providerCode === undefined ? {} : { providerCode: input.providerCode }),\n ...(input.fallbackKind === undefined ? {} : { fallbackKind: input.fallbackKind })\n })\n\n return new LLMError({\n cause: providerFailureCause(provider.kind),\n message: input.message,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n}\n\nconst numberField = (value: unknown, key: string) => {\n const raw = field(value, key)\n return typeof raw === 'number' ? raw : undefined\n}\n\nconst sseDataFromBlock = (block: string) =>\n block\n .split('\\n')\n .filter(line => line.startsWith('data:'))\n .map(line => line.slice('data:'.length).trimStart())\n .join('\\n')\n .trim()\n\nconst dataFromSseBlock = (block: string) => {\n const data = sseDataFromBlock(block)\n\n if (data.length === 0 || data === '[DONE]') {\n return undefined\n }\n\n return data\n}\n\nconst normalizeNewlines = (text: string) => text.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n')\n\nconst splitCompleteSseBlocks = (buffer: string) => {\n const blocks = buffer.split('\\n\\n')\n const tail = blocks.at(-1) ?? ''\n\n return { completeBlocks: blocks.slice(0, -1), tail }\n}\n\nconst parseToolParams = (raw: string) => {\n const trimmed = raw.trim()\n\n if (trimmed.length === 0) return Effect.succeed({})\n\n return decodeJsonString(trimmed, 'Invalid Anthropic Claude tool arguments JSON')\n}\n\ntype AnthropicUsageComponents = {\n readonly inputTokens: number\n readonly outputTokens: number\n readonly cacheReadInputTokens: number\n readonly cacheCreationInputTokens: number\n}\n\nconst zeroAnthropicUsageComponents: AnthropicUsageComponents = {\n inputTokens: 0,\n outputTokens: 0,\n cacheReadInputTokens: 0,\n cacheCreationInputTokens: 0\n}\n\nconst positiveOrUndefined = (value: number) => (value > 0 ? value : undefined)\n\nconst toAgentUsageFromComponents = (usage: AnthropicUsageComponents) =>\n AgentUsage.make({\n input: AgentInputUsage.make({\n total: usage.inputTokens + usage.cacheReadInputTokens + usage.cacheCreationInputTokens,\n uncached: positiveOrUndefined(usage.inputTokens),\n cacheRead: positiveOrUndefined(usage.cacheReadInputTokens),\n cacheWrite: positiveOrUndefined(usage.cacheCreationInputTokens)\n }),\n output: AgentOutputUsage.make({\n total: usage.outputTokens,\n text: positiveOrUndefined(usage.outputTokens)\n })\n })\n\nconst toAgentUsage = (usage: AnthropicUsageResponse) =>\n toAgentUsageFromComponents({\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n cacheReadInputTokens: usage.cache_read_input_tokens ?? 0,\n cacheCreationInputTokens: usage.cache_creation_input_tokens ?? 0\n })\n\nconst nextAnthropicUsageSnapshot = (\n previous: AnthropicUsageComponents,\n usage: AnthropicStreamUsageResponse\n): AnthropicUsageComponents => ({\n inputTokens: usage.input_tokens ?? previous.inputTokens,\n outputTokens: usage.output_tokens ?? previous.outputTokens,\n cacheReadInputTokens: usage.cache_read_input_tokens ?? previous.cacheReadInputTokens,\n cacheCreationInputTokens: usage.cache_creation_input_tokens ?? previous.cacheCreationInputTokens\n})\n\nconst usageComponentDelta = (previous: number, next: number) => Math.max(0, next - previous)\n\nconst anthropicUsageDelta = (\n previous: AnthropicUsageComponents,\n next: AnthropicUsageComponents\n): AnthropicUsageComponents => ({\n inputTokens: usageComponentDelta(previous.inputTokens, next.inputTokens),\n outputTokens: usageComponentDelta(previous.outputTokens, next.outputTokens),\n cacheReadInputTokens: usageComponentDelta(\n previous.cacheReadInputTokens,\n next.cacheReadInputTokens\n ),\n cacheCreationInputTokens: usageComponentDelta(\n previous.cacheCreationInputTokens,\n next.cacheCreationInputTokens\n )\n})\n\nconst hasAnthropicUsage = (usage: AnthropicUsageComponents) =>\n usage.inputTokens > 0 ||\n usage.outputTokens > 0 ||\n usage.cacheReadInputTokens > 0 ||\n usage.cacheCreationInputTokens > 0\n\ntype AnthropicStreamUsageStep = {\n readonly snapshot: AnthropicUsageComponents\n readonly events: ReadonlyArray<LLMEvent>\n}\n\nconst usageStepFromUnknown = (\n usage: unknown,\n previous: AnthropicUsageComponents\n): AnthropicStreamUsageStep => {\n const parsed = Schema.decodeUnknownOption(AnthropicStreamUsageResponse)(usage)\n\n if (parsed._tag === 'None') {\n return { snapshot: previous, events: [] }\n }\n\n const value = parsed.value\n const snapshot = nextAnthropicUsageSnapshot(previous, value)\n const delta = anthropicUsageDelta(previous, snapshot)\n\n return {\n snapshot,\n events: hasAnthropicUsage(delta)\n ? [LLMUsage.make({ usage: toAgentUsageFromComponents(delta) })]\n : []\n }\n}\n\nconst toLlmEvents = (\n response: AnthropicMessageResponse\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n if (response.stop_reason === 'max_tokens') {\n return yield* Effect.fail(anthropicMaxTokensError())\n }\n\n const events = yield* Effect.forEach(response.content, block => {\n switch (block.type) {\n case 'text':\n return Effect.succeed<LLMEvent>(LLMTextDelta.make({ text: block.text }))\n case 'thinking':\n return Effect.succeed<LLMEvent>(LLMReasoningDelta.make({ text: block.thinking }))\n case 'tool_use':\n return Effect.succeed<LLMEvent>(\n LLMToolCall.make({\n call: ToolCall.make({\n id: block.id,\n name: unprefixClaudeToolName(block.name),\n params: block.input\n })\n })\n )\n }\n })\n const stopReason = response.stop_reason === 'tool_use' ? 'tool_use' : 'stop'\n const usageEvent =\n response.usage === undefined ? [] : [LLMUsage.make({ usage: toAgentUsage(response.usage) })]\n\n return [...events, LLMDone.make({ stopReason }), ...usageEvent]\n })\n\nconst decodeAnthropicMessageResponse = (json: unknown) =>\n Schema.decodeUnknownEffect(AnthropicMessageResponse)(json).pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'invalid_response',\n message: `Invalid Anthropic Claude response: ${unknownToMessage(error)}`,\n retryable: false\n })\n )\n )\n\nconst parseAnthropicJsonResponse = (\n raw: string\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const json = yield* decodeJsonString(raw, 'Could not parse Anthropic Claude response JSON')\n const parsed = yield* decodeAnthropicMessageResponse(json)\n\n return yield* toLlmEvents(parsed)\n })\n\ntype AnthropicBodyFormat = 'undecided' | 'sse' | 'json'\n\ntype AnthropicSseState = {\n readonly hasToolCall: boolean\n readonly hasDone: boolean\n readonly stopReason?: string\n readonly usage: AnthropicUsageComponents\n}\n\ntype AnthropicSseStep = {\n readonly state: AnthropicSseState\n readonly events: ReadonlyArray<LLMEvent>\n}\n\ntype AnthropicBodyState = {\n readonly format: AnthropicBodyFormat\n readonly buffer: string\n readonly sse: AnthropicSseState\n}\n\nconst initialSseState: AnthropicSseState = {\n hasToolCall: false,\n hasDone: false,\n usage: zeroAnthropicUsageComponents\n}\n\nconst initialBodyState: AnthropicBodyState = {\n format: 'undecided',\n buffer: '',\n sse: initialSseState\n}\n\nconst classifyAnthropicBody = (buffer: string): AnthropicBodyFormat => {\n const trimmed = buffer.trimStart()\n\n if (trimmed.length === 0) {\n return 'undecided'\n }\n\n if (trimmed.startsWith('event:') || trimmed.startsWith('data:')) {\n return 'sse'\n }\n\n if ('event:'.startsWith(trimmed) || 'data:'.startsWith(trimmed)) {\n return 'undecided'\n }\n\n return 'json'\n}\n\nconst invalidToolUseStartError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Invalid Anthropic Claude tool_use stream block',\n retryable: false\n })\n\nconst anthropicMaxTokensError = () =>\n new LLMError({\n cause: 'invalid_response',\n message: 'Anthropic Claude stopped after reaching max_tokens',\n retryable: false\n })\n\nconst makeAnthropicStreamEmitter = () => {\n const toolBlocks = new Map<number, AnthropicToolBlockState>()\n\n return (state: AnthropicSseState, data: unknown): Effect.Effect<AnthropicSseStep, LLMError> => {\n const type = stringField(data, 'type')\n\n if (type === 'message_start') {\n const message = field(data, 'message')\n const step = usageStepFromUnknown(field(message, 'usage'), state.usage)\n\n return Effect.succeed({ state: { ...state, usage: step.snapshot }, events: step.events })\n }\n\n if (type === 'content_block_start') {\n const index = numberField(data, 'index')\n const block = field(data, 'content_block')\n\n if (index !== undefined && stringField(block, 'type') === 'tool_use') {\n const id = stringField(block, 'id')\n const name = stringField(block, 'name')\n\n if (id === undefined || name === undefined) {\n return Effect.fail(invalidToolUseStartError())\n }\n\n toolBlocks.set(index, {\n id,\n name: unprefixClaudeToolName(name),\n partialJson: ''\n })\n }\n\n return Effect.succeed({ state, events: [] })\n }\n\n if (type === 'content_block_delta') {\n const index = numberField(data, 'index')\n const delta = field(data, 'delta')\n const deltaType = stringField(delta, 'type')\n const text = stringField(delta, 'text')\n const thinking = stringField(delta, 'thinking')\n const partialJson = stringField(delta, 'partial_json')\n\n if (deltaType === 'text_delta' && text !== undefined) {\n return Effect.succeed({ state, events: [LLMTextDelta.make({ text })] })\n }\n\n if (deltaType === 'thinking_delta' && thinking !== undefined) {\n return Effect.succeed({ state, events: [LLMReasoningDelta.make({ text: thinking })] })\n }\n\n if (index !== undefined && deltaType === 'input_json_delta' && partialJson !== undefined) {\n const current = toolBlocks.get(index)\n if (current !== undefined) {\n toolBlocks.set(index, { ...current, partialJson: `${current.partialJson}${partialJson}` })\n }\n }\n\n return Effect.succeed({ state, events: [] })\n }\n\n if (type === 'content_block_stop') {\n const index = numberField(data, 'index')\n const toolBlock = index === undefined ? undefined : toolBlocks.get(index)\n\n if (toolBlock === undefined) return Effect.succeed({ state, events: [] })\n\n return parseToolParams(toolBlock.partialJson).pipe(\n Effect.map(params => {\n if (index !== undefined) toolBlocks.delete(index)\n\n return {\n state: { ...state, hasToolCall: true },\n events: [\n LLMToolCall.make({\n call: ToolCall.make({\n id: toolBlock.id,\n name: toolBlock.name,\n params\n })\n })\n ]\n }\n })\n )\n }\n\n if (type === 'message_delta') {\n const step = usageStepFromUnknown(field(data, 'usage'), state.usage)\n const delta = field(data, 'delta')\n const stopReason = stringField(delta, 'stop_reason')\n\n return Effect.succeed({\n state: {\n ...state,\n usage: step.snapshot,\n ...(stopReason === undefined ? {} : { stopReason })\n },\n events: step.events\n })\n }\n\n if (type === 'message_stop') {\n if (state.stopReason === 'max_tokens') return Effect.fail(anthropicMaxTokensError())\n\n return Effect.succeed({\n state: { ...state, hasDone: true },\n events: [LLMDone.make({ stopReason: state.hasToolCall ? 'tool_use' : 'stop' })]\n })\n }\n\n if (type === 'error') {\n const error = field(data, 'error')\n const providerCode = stringField(error, 'type') ?? stringField(error, 'code')\n\n return Effect.fail(\n providerSignalError({\n message: stringField(error, 'message') ?? 'Anthropic Claude stream error',\n ...(providerCode === undefined ? {} : { providerCode })\n })\n )\n }\n\n return Effect.succeed({ state, events: [] })\n }\n}\n\nconst processSseData = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n data: string\n): Effect.Effect<AnthropicSseStep, LLMError> =>\n decodeJsonString(data, 'Could not parse Anthropic Claude stream event JSON').pipe(\n Effect.flatMap(parsed => emitData(state, parsed))\n )\n\nconst processSseBlock = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n block: string\n): Effect.Effect<AnthropicSseStep, LLMError> => {\n const data = dataFromSseBlock(block)\n\n if (data === undefined) {\n return Effect.succeed({ state, events: [] })\n }\n\n return processSseData(emitData, state, data)\n}\n\nconst processSseBlocks = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicSseState,\n blocks: ReadonlyArray<string>\n): Effect.Effect<AnthropicSseStep, LLMError> =>\n Effect.gen(function* () {\n const events: Array<LLMEvent> = []\n let currentState = state\n\n for (const block of blocks) {\n const step = yield* processSseBlock(emitData, currentState, block)\n currentState = step.state\n events.push(...step.events)\n }\n\n return { state: currentState, events }\n })\n\nconst processBodyChunk = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicBodyState,\n chunk: string\n): Effect.Effect<AnthropicSseStep & { readonly bodyState: AnthropicBodyState }, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(`${state.buffer}${chunk}`)\n const format = state.format === 'undecided' ? classifyAnthropicBody(buffer) : state.format\n\n if (format !== 'sse') {\n return {\n state: state.sse,\n bodyState: { ...state, format, buffer },\n events: []\n }\n }\n\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(emitData, state.sse, split.completeBlocks)\n\n return {\n state: step.state,\n bodyState: { format, buffer: split.tail, sse: step.state },\n events: step.events\n }\n })\n\nconst finalizeBodyState = (\n emitData: ReturnType<typeof makeAnthropicStreamEmitter>,\n state: AnthropicBodyState\n): Effect.Effect<ReadonlyArray<LLMEvent>, LLMError> =>\n Effect.gen(function* () {\n const buffer = normalizeNewlines(state.buffer)\n const format = state.format === 'undecided' ? classifyAnthropicBody(buffer) : state.format\n\n if (format === 'json') {\n return yield* parseAnthropicJsonResponse(buffer)\n }\n\n const events: Array<LLMEvent> = []\n let sseState = state.sse\n\n if (format === 'sse') {\n const split = splitCompleteSseBlocks(buffer)\n const step = yield* processSseBlocks(emitData, sseState, split.completeBlocks)\n sseState = step.state\n events.push(...step.events)\n\n if (split.tail.trim().length > 0) {\n const tailStep = yield* processSseBlock(emitData, sseState, split.tail)\n sseState = tailStep.state\n events.push(...tailStep.events)\n }\n }\n\n if (sseState.stopReason === 'max_tokens') {\n return yield* Effect.fail(anthropicMaxTokensError())\n }\n\n if (!sseState.hasDone) {\n events.push(LLMDone.make({ stopReason: sseState.hasToolCall ? 'tool_use' : 'stop' }))\n }\n\n return events\n })\n\nexport const streamAnthropicClaudeResponse = (\n response: HttpClientResponse.HttpClientResponse\n): Stream.Stream<LLMEvent, LLMError> =>\n Stream.unwrap(\n Ref.make(initialBodyState).pipe(\n Effect.map(bodyStateRef => {\n const emitData = makeAnthropicStreamEmitter()\n const chunks = response.stream.pipe(\n Stream.mapError(\n toHttpClientLlmError('Could not read Anthropic Claude stream', true, 'stream')\n ),\n Stream.decodeText,\n Stream.mapEffect(chunk =>\n Effect.gen(function* () {\n const state = yield* Ref.get(bodyStateRef)\n const step = yield* processBodyChunk(emitData, state, chunk)\n yield* Ref.set(bodyStateRef, step.bodyState)\n return step.events\n })\n ),\n Stream.flatMap(events => Stream.fromIterable(events))\n )\n const finalEvents = Stream.fromEffect(\n Ref.get(bodyStateRef).pipe(Effect.flatMap(state => finalizeBodyState(emitData, state)))\n ).pipe(Stream.flatMap(events => Stream.fromIterable(events)))\n\n return chunks.pipe(Stream.concat(finalEvents))\n })\n )\n )\n\nconst sendAnthropicClaudeRequest = (\n config: AnthropicClaudeProviderConfig,\n request: LLMRequest,\n client: HttpClient.HttpClient,\n sessionId: string\n): Effect.Effect<HttpClientResponse.HttpClientResponse, LLMError> =>\n Effect.gen(function* () {\n const body = yield* toAnthropicClaudeRequestBody(request, { ...config, stream: true })\n // Replayed transcripts can carry lone surrogates; harden the lowered\n // body so one bad historical string cannot poison every model call.\n const serializedBody = yield* encodeJsonString(\n replaceLoneSurrogatesDeep(body),\n 'Could not serialize Anthropic Claude request'\n )\n const httpRequest = HttpClientRequest.post(\n config.messagesUrl ?? anthropicClaudeMessagesUrl\n ).pipe(\n HttpClientRequest.setHeaders({\n accept: 'text/event-stream',\n ...anthropicClaudeAuthorizationHeaders(config.token),\n 'content-type': 'application/json',\n ...makeAnthropicClaudeCompatibilityHeaders({ model: request.model, sessionId }),\n ...config.extraHeaders\n }),\n HttpClientRequest.bodyText(serializedBody, 'application/json')\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientLlmError('Anthropic Claude request failed', true)))\n\n if (response.status < 200 || response.status >= 300) {\n const errorText = yield* response.text.pipe(\n Effect.mapError(\n error =>\n new LLMError({\n cause: 'provider_error',\n message: `Could not read Anthropic Claude error body: ${error.message}`,\n retryable: false\n })\n )\n )\n const errorInfo = yield* decodeAnthropicHttpErrorInfo(errorText)\n\n const provider = classifyProviderFailure({\n provider: anthropicClaudeProvider,\n status: response.status,\n headers: response.headers,\n body: errorText,\n ...(errorInfo.message === undefined ? {} : { message: errorInfo.message }),\n ...(errorInfo.providerCode === undefined\n ? {}\n : { providerCode: errorInfo.providerCode })\n })\n const message =\n errorInfo.message === undefined\n ? `Anthropic Claude returned ${response.status}`\n : `Anthropic Claude returned ${response.status}: ${errorInfo.message}`\n\n return yield* Effect.fail(\n new LLMError({\n cause: providerFailureCause(provider.kind),\n message,\n retryable: providerFailureRetryable(provider.kind),\n provider\n })\n )\n }\n\n return response\n }).pipe(Effect.withSpan('AnthropicClaudeProvider.stream'))\n\nexport const makeAnthropicClaudeProviderLayer = (config: AnthropicClaudeProviderConfig) =>\n Layer.effect(\n LLMProvider,\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const sessionId = makeAnthropicClaudeRequestId()\n\n return LLMProvider.of({\n stream: request =>\n Stream.fromEffect(sendAnthropicClaudeRequest(config, request, client, sessionId)).pipe(\n Stream.flatMap(streamAnthropicClaudeResponse)\n )\n })\n })\n )\n"],"mappings":";;;;;;;;;AA4JA,MAAM,gCAAgC;AACtC,MAAM,+BAA+B;AACrC,MAAM,4BAA4B;AAClC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;AAC/B,MAAM,8BAAqD;CAAC;CAAG;CAAG;AAAE;AACpE,MAAM,4BAA4B;AAClC,MAAM,yCAAyC;AAC/C,MAAM,+BAAsD;CAC1D;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,wCAGD,CACH;CACE,OAAO;CACP,aAAa;AACf,GACA;CACE,OAAO;CACP,aAAa;AACf,CACF;AACA,MAAM,yCAAyC;AAG/C,MAAM,wBAAwB,SAC5B,GAAG,4BAA4B,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC;AAE5E,MAAM,0BAA0B,SAAiB;CAC/C,IAAI,CAAC,KAAK,WAAW,yBAAy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;CACjC,MAAM,YAAY,6BAA6B;CAE/C,OAAO,YAAY,GAAG,EACpB,SAAQ,YACN,OAAO,WAAW,2BAA2B,QAAQ,SAAS,QAAQ,SAAS,CAAC,EAAE,KAChF,OAAO,QAAQ,6BAA6B,CAC9C,EACJ,CAAC;AACH,CAAC,CACH"}
|
|
@@ -25,8 +25,9 @@ declare const mergeSkillsets: (sources: ReadonlyArray<SkillsetSource>) => Effect
|
|
|
25
25
|
readonly name: string;
|
|
26
26
|
readonly hints: readonly string[];
|
|
27
27
|
readonly template: string;
|
|
28
|
-
readonly source?: string | undefined;
|
|
29
28
|
readonly description?: string | undefined;
|
|
29
|
+
readonly source?: string | undefined;
|
|
30
|
+
readonly location?: string | undefined;
|
|
30
31
|
readonly arguments?: readonly {
|
|
31
32
|
readonly required: boolean;
|
|
32
33
|
readonly name: string;
|
|
@@ -34,7 +35,6 @@ declare const mergeSkillsets: (sources: ReadonlyArray<SkillsetSource>) => Effect
|
|
|
34
35
|
}[] | undefined;
|
|
35
36
|
readonly access?: "read" | "write" | "destructive" | undefined;
|
|
36
37
|
readonly fileRefs?: boolean | undefined;
|
|
37
|
-
readonly location?: string | undefined;
|
|
38
38
|
}[];
|
|
39
39
|
}, SkillsetError, never>;
|
|
40
40
|
//#endregion
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk-sdk/agent",
|
|
3
|
-
"version": "0.1.0-canary.
|
|
3
|
+
"version": "0.1.0-canary.56",
|
|
4
4
|
"description": "Protocol, loop, runtime, client, compaction, tools, React, providers, OAuth, skillset, and voice primitives for building Yolk agents.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -599,6 +599,15 @@ const isJsonObject = (value: unknown): value is JsonObject =>
|
|
|
599
599
|
const jsonObjectField = (value: JsonObject, key: string) =>
|
|
600
600
|
Object.getOwnPropertyDescriptor(value, key)?.value
|
|
601
601
|
|
|
602
|
+
// Claude subscription OAuth validates tool schemas more narrowly than the regular
|
|
603
|
+
// Anthropic API: combinators and tuple-only prefixItems can be rejected even when
|
|
604
|
+
// they are valid JSON Schema. Effect Schema emits those constructs for unions,
|
|
605
|
+
// refinements, and tuples, so the provider needs a compatibility projection.
|
|
606
|
+
//
|
|
607
|
+
// This projection is model guidance, not the execution validator. Whenever an
|
|
608
|
+
// unsupported constraint cannot be represented faithfully, normalization must
|
|
609
|
+
// widen it (usually to {}) rather than exclude an input accepted by the original
|
|
610
|
+
// schema. makeTool continues to validate calls against that original Effect Schema.
|
|
602
611
|
const topLevelJsonSchemaCombinatorKeys: ReadonlyArray<TopLevelJsonSchemaCombinatorKey> = [
|
|
603
612
|
'anyOf',
|
|
604
613
|
'oneOf',
|
|
@@ -630,16 +639,24 @@ const withoutTopLevelJsonSchemaCombinators = (schema: JsonObject): JsonObject =>
|
|
|
630
639
|
const withoutJsonSchemaCombinatorsAndTupleHints = (schema: JsonObject): JsonObject =>
|
|
631
640
|
Object.fromEntries(
|
|
632
641
|
Object.entries(schema).filter(
|
|
633
|
-
([key]) =>
|
|
642
|
+
([key]) =>
|
|
643
|
+
!isTopLevelJsonSchemaCombinatorKey(key) &&
|
|
644
|
+
key !== 'prefixItems' &&
|
|
645
|
+
key !== 'not' &&
|
|
646
|
+
key !== 'if' &&
|
|
647
|
+
key !== 'then' &&
|
|
648
|
+
key !== 'else'
|
|
634
649
|
)
|
|
635
650
|
)
|
|
636
651
|
|
|
637
|
-
const
|
|
638
|
-
const
|
|
652
|
+
const jsonSchemaMap = (schema: JsonObject, key: string) => {
|
|
653
|
+
const value = jsonObjectField(schema, key)
|
|
639
654
|
|
|
640
|
-
return isJsonObject(
|
|
655
|
+
return isJsonObject(value) ? value : {}
|
|
641
656
|
}
|
|
642
657
|
|
|
658
|
+
const jsonSchemaProperties = (schema: JsonObject) => jsonSchemaMap(schema, 'properties')
|
|
659
|
+
|
|
643
660
|
const jsonSchemaDefinitions = (schema: JsonObject) => {
|
|
644
661
|
const definitions = jsonObjectField(schema, '$defs')
|
|
645
662
|
|
|
@@ -697,17 +714,14 @@ const mergeEnumPropertySchemas = (left: unknown, right: unknown): unknown | unde
|
|
|
697
714
|
return undefined
|
|
698
715
|
}
|
|
699
716
|
|
|
700
|
-
|
|
701
|
-
|
|
717
|
+
const descriptions = [jsonObjectField(left, 'description'), jsonObjectField(right, 'description')]
|
|
718
|
+
const description = descriptions.find(value => typeof value === 'string')
|
|
702
719
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
720
|
+
return {
|
|
721
|
+
...(leftType === undefined ? {} : { type: leftType }),
|
|
722
|
+
enum: uniqueUnknownArray([...leftEnum, ...rightEnum]),
|
|
723
|
+
...(description === undefined ? {} : { description })
|
|
706
724
|
}
|
|
707
|
-
|
|
708
|
-
const anyOf = jsonObjectField(schema, 'anyOf')
|
|
709
|
-
|
|
710
|
-
return Array.isArray(anyOf) ? anyOf : [schema]
|
|
711
725
|
}
|
|
712
726
|
|
|
713
727
|
const mergePropertySchemas = (left: unknown, right: unknown): unknown => {
|
|
@@ -723,9 +737,10 @@ const mergePropertySchemas = (left: unknown, right: unknown): unknown => {
|
|
|
723
737
|
return mergedEnum
|
|
724
738
|
}
|
|
725
739
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
740
|
+
// Anthropic rejects combinators in tool schemas. An unconstrained schema
|
|
741
|
+
// preserves every value accepted by either incompatible variant; makeTool
|
|
742
|
+
// still validates calls against the complete original Effect Schema.
|
|
743
|
+
return {}
|
|
729
744
|
}
|
|
730
745
|
|
|
731
746
|
const mergeJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject => {
|
|
@@ -744,73 +759,165 @@ const mergeJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject
|
|
|
744
759
|
return Object.fromEntries(merged)
|
|
745
760
|
}
|
|
746
761
|
|
|
747
|
-
const
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
762
|
+
const mergeUnionJsonSchemaObjects = (
|
|
763
|
+
objects: ReadonlyArray<JsonObject>,
|
|
764
|
+
owners?: ReadonlyArray<JsonObject>
|
|
765
|
+
): JsonObject => {
|
|
766
|
+
const keys = new Set(objects.flatMap(object => Object.keys(object)))
|
|
767
|
+
|
|
768
|
+
return Object.fromEntries(
|
|
769
|
+
Array.from(keys, key => {
|
|
770
|
+
const values = objects.flatMap((object, index) => {
|
|
771
|
+
if (Object.hasOwn(object, key)) return [jsonObjectField(object, key)]
|
|
772
|
+
|
|
773
|
+
const additionalProperties = owners?.[index]
|
|
774
|
+
if (additionalProperties === undefined) return []
|
|
775
|
+
|
|
776
|
+
const additionalPropertySchema = jsonObjectField(additionalProperties, 'additionalProperties')
|
|
777
|
+
if (additionalPropertySchema === false) return []
|
|
778
|
+
|
|
779
|
+
return [isJsonObject(additionalPropertySchema) ? additionalPropertySchema : {}]
|
|
780
|
+
})
|
|
781
|
+
const [first, ...rest] = values
|
|
782
|
+
|
|
783
|
+
return [key, rest.reduce(mergePropertySchemas, first)]
|
|
784
|
+
})
|
|
753
785
|
)
|
|
786
|
+
}
|
|
754
787
|
|
|
755
|
-
const
|
|
756
|
-
|
|
788
|
+
const mergeRightBiasedJsonSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject =>
|
|
789
|
+
Object.assign({}, ...objects)
|
|
757
790
|
|
|
758
|
-
|
|
791
|
+
const mergeAllOfSchemaObjects = (objects: ReadonlyArray<JsonObject>): JsonObject => {
|
|
792
|
+
const merged = mergeRightBiasedJsonSchemaObjects(objects)
|
|
793
|
+
const properties = mergeRightBiasedJsonSchemaObjects(objects.map(jsonSchemaProperties))
|
|
794
|
+
const required = mergeJsonSchemaRequired('allOf', objects)
|
|
795
|
+
const definitions = mergeJsonSchemaObjects(objects.map(jsonSchemaDefinitions))
|
|
796
|
+
|
|
797
|
+
return {
|
|
798
|
+
...merged,
|
|
799
|
+
...(Object.keys(properties).length === 0 ? {} : { properties }),
|
|
800
|
+
...(required.length === 0 ? {} : { required }),
|
|
801
|
+
...(Object.keys(definitions).length === 0 ? {} : { $defs: definitions })
|
|
802
|
+
}
|
|
759
803
|
}
|
|
760
804
|
|
|
761
|
-
|
|
805
|
+
// JSON objects are not always schemas. Values under schema-map keywords are
|
|
806
|
+
// schemas, while values under data keywords are literals and must remain opaque;
|
|
807
|
+
// recursively normalizing enum data or property/definition names can corrupt it.
|
|
808
|
+
const jsonSchemaMapKeywords = new Set([
|
|
809
|
+
'properties',
|
|
810
|
+
'patternProperties',
|
|
811
|
+
'$defs',
|
|
812
|
+
'definitions',
|
|
813
|
+
'dependentSchemas'
|
|
814
|
+
])
|
|
762
815
|
|
|
763
|
-
const
|
|
816
|
+
const jsonSchemaDataKeywords = new Set(['const', 'default', 'enum', 'examples'])
|
|
817
|
+
|
|
818
|
+
const normalizeJsonSchemaObjectFields = (schema: JsonObject): JsonObject => {
|
|
819
|
+
const normalized = Object.fromEntries(
|
|
820
|
+
Object.entries(withoutJsonSchemaCombinatorsAndTupleHints(schema)).map(([key, value]) => {
|
|
821
|
+
if (jsonSchemaDataKeywords.has(key)) return [key, value]
|
|
822
|
+
|
|
823
|
+
if (key === 'dependencies' && isJsonObject(value)) {
|
|
824
|
+
return [
|
|
825
|
+
key,
|
|
826
|
+
Object.fromEntries(
|
|
827
|
+
Object.entries(value).map(([name, dependency]) => [
|
|
828
|
+
name,
|
|
829
|
+
Array.isArray(dependency) ? dependency : normalizeAnthropicToolSchema(dependency)
|
|
830
|
+
])
|
|
831
|
+
)
|
|
832
|
+
]
|
|
833
|
+
}
|
|
764
834
|
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
835
|
+
if (jsonSchemaMapKeywords.has(key) && isJsonObject(value)) {
|
|
836
|
+
return [
|
|
837
|
+
key,
|
|
838
|
+
Object.fromEntries(
|
|
839
|
+
Object.entries(value).map(([name, childSchema]) => [
|
|
840
|
+
name,
|
|
841
|
+
normalizeAnthropicToolSchema(childSchema)
|
|
842
|
+
])
|
|
843
|
+
)
|
|
844
|
+
]
|
|
845
|
+
}
|
|
770
846
|
|
|
771
|
-
|
|
847
|
+
return [key, normalizeAnthropicToolSchema(value)]
|
|
848
|
+
})
|
|
849
|
+
)
|
|
772
850
|
|
|
773
|
-
|
|
774
|
-
|
|
851
|
+
if (Array.isArray(jsonObjectField(schema, 'prefixItems'))) {
|
|
852
|
+
return { ...normalized, items: {} }
|
|
775
853
|
}
|
|
776
854
|
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
if (Array.isArray(jsonObjectField(merged, 'anyOf'))) return undefined
|
|
855
|
+
return normalized
|
|
856
|
+
}
|
|
780
857
|
|
|
858
|
+
const jsonSchemaType = (schema: JsonObject) => {
|
|
859
|
+
const type = jsonObjectField(schema, 'type')
|
|
781
860
|
|
|
782
|
-
return
|
|
861
|
+
return typeof type === 'string' ? type : undefined
|
|
783
862
|
}
|
|
784
863
|
|
|
785
|
-
const
|
|
864
|
+
const firstJsonObject = (items: ReadonlyArray<JsonObject>) => items[0]
|
|
865
|
+
|
|
866
|
+
const independentCommonVariantKeys = new Set([
|
|
867
|
+
'type',
|
|
868
|
+
'enum',
|
|
869
|
+
'const',
|
|
870
|
+
'format',
|
|
871
|
+
'pattern',
|
|
872
|
+
'minLength',
|
|
873
|
+
'maxLength',
|
|
874
|
+
'minimum',
|
|
875
|
+
'maximum',
|
|
876
|
+
'exclusiveMinimum',
|
|
877
|
+
'exclusiveMaximum',
|
|
878
|
+
'multipleOf',
|
|
879
|
+
'minItems',
|
|
880
|
+
'maxItems',
|
|
881
|
+
'uniqueItems',
|
|
882
|
+
'minProperties',
|
|
883
|
+
'maxProperties',
|
|
884
|
+
'description'
|
|
885
|
+
])
|
|
886
|
+
|
|
887
|
+
const commonVariantFields = (variants: ReadonlyArray<JsonObject>): JsonObject => {
|
|
786
888
|
const first = firstJsonObject(variants)
|
|
787
|
-
|
|
889
|
+
if (first === undefined) return {}
|
|
890
|
+
if (variants.length === 1) return first
|
|
788
891
|
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
892
|
+
return Object.fromEntries(
|
|
893
|
+
Object.entries(first).filter(([key, value]) => {
|
|
894
|
+
if (!independentCommonVariantKeys.has(key)) return false
|
|
792
895
|
|
|
793
|
-
|
|
896
|
+
const valueKey = jsonValueKey(value)
|
|
897
|
+
return valueKey !== undefined && variants.every(variant => valueKey === jsonValueKey(jsonObjectField(variant, key)))
|
|
898
|
+
})
|
|
899
|
+
)
|
|
794
900
|
}
|
|
795
901
|
|
|
796
902
|
const objectVariant = (variants: ReadonlyArray<JsonObject>): JsonObject | undefined => {
|
|
797
|
-
if (
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
const type = jsonSchemaType(variant)
|
|
903
|
+
if (variants.length === 0 || variants.some(variant => jsonSchemaType(variant) !== 'object')) {
|
|
904
|
+
return undefined
|
|
905
|
+
}
|
|
801
906
|
|
|
802
|
-
|
|
803
|
-
|
|
907
|
+
if (
|
|
908
|
+
variants.some(variant => Object.keys(jsonSchemaMap(variant, 'patternProperties')).length > 0)
|
|
804
909
|
) {
|
|
805
|
-
return
|
|
910
|
+
return { type: 'object' }
|
|
806
911
|
}
|
|
807
912
|
|
|
913
|
+
const additionalProperties = mergeAdditionalProperties(variants)
|
|
914
|
+
|
|
808
915
|
return {
|
|
809
916
|
type: 'object',
|
|
810
|
-
properties:
|
|
917
|
+
properties: mergeUnionJsonSchemaObjects(variants.map(jsonSchemaProperties), variants),
|
|
811
918
|
required: mergeJsonSchemaRequired('oneOf', variants),
|
|
812
919
|
$defs: mergeJsonSchemaObjects(variants.map(jsonSchemaDefinitions)),
|
|
813
|
-
additionalProperties:
|
|
920
|
+
...(additionalProperties === undefined ? {} : { additionalProperties })
|
|
814
921
|
}
|
|
815
922
|
}
|
|
816
923
|
|
|
@@ -819,22 +926,20 @@ const normalizeJsonSchemaCombinator = (
|
|
|
819
926
|
combinator: TopLevelJsonSchemaCombinator
|
|
820
927
|
): JsonObject => {
|
|
821
928
|
const base = normalizeJsonSchemaObjectFields(schema)
|
|
822
|
-
const
|
|
823
|
-
|
|
824
|
-
.filter(isJsonObject)
|
|
825
|
-
.filter(variant => !isNullJsonSchema(variant))
|
|
929
|
+
const normalizedItems = combinator.items.map(normalizeAnthropicToolSchema)
|
|
930
|
+
const variants = normalizedItems.filter(isJsonObject)
|
|
826
931
|
const first = firstJsonObject(variants)
|
|
827
932
|
|
|
828
|
-
if (first === undefined) return base
|
|
829
|
-
|
|
830
933
|
if (combinator.key === 'allOf') {
|
|
831
|
-
return
|
|
934
|
+
return mergeAllOfSchemaObjects([base, ...variants])
|
|
832
935
|
}
|
|
833
936
|
|
|
834
|
-
|
|
835
|
-
|
|
937
|
+
if (normalizedItems.includes(true)) return base
|
|
938
|
+
if (first === undefined) return base
|
|
939
|
+
|
|
940
|
+
const merged = objectVariant(variants) ?? commonVariantFields(variants)
|
|
836
941
|
|
|
837
|
-
return
|
|
942
|
+
return mergeAllOfSchemaObjects([merged, base])
|
|
838
943
|
}
|
|
839
944
|
|
|
840
945
|
function normalizeAnthropicToolSchema(value: unknown): unknown {
|
|
@@ -888,19 +993,28 @@ const flattenTopLevelCombinatorToolSchema = (
|
|
|
888
993
|
): JsonObject => {
|
|
889
994
|
const base = withoutTopLevelJsonSchemaCombinators(schema)
|
|
890
995
|
const objectVariants = combinator.items.filter(isJsonObject)
|
|
996
|
+
const hasUnconstrainedUnion =
|
|
997
|
+
combinator.key !== 'allOf' &&
|
|
998
|
+
combinator.items.some(item => item === true || !isJsonObject(item))
|
|
891
999
|
const additionalProperties = mergeAdditionalProperties(objectVariants)
|
|
892
1000
|
const flattened = {
|
|
893
1001
|
...base,
|
|
894
1002
|
type: 'object',
|
|
895
|
-
properties:
|
|
896
|
-
|
|
1003
|
+
properties: hasUnconstrainedUnion
|
|
1004
|
+
? {}
|
|
1005
|
+
: combinator.key === 'allOf'
|
|
1006
|
+
? mergeRightBiasedJsonSchemaObjects(objectVariants.map(jsonSchemaProperties))
|
|
1007
|
+
: mergeUnionJsonSchemaObjects(objectVariants.map(jsonSchemaProperties), objectVariants),
|
|
1008
|
+
required: hasUnconstrainedUnion
|
|
1009
|
+
? []
|
|
1010
|
+
: mergeJsonSchemaRequired(combinator.key, objectVariants),
|
|
897
1011
|
$defs: mergeJsonSchemaObjects([
|
|
898
1012
|
jsonSchemaDefinitions(schema),
|
|
899
1013
|
...objectVariants.map(jsonSchemaDefinitions)
|
|
900
1014
|
])
|
|
901
1015
|
}
|
|
902
1016
|
|
|
903
|
-
if (additionalProperties === undefined) {
|
|
1017
|
+
if (hasUnconstrainedUnion || additionalProperties === undefined) {
|
|
904
1018
|
return flattened
|
|
905
1019
|
}
|
|
906
1020
|
|
|
@@ -909,12 +1023,14 @@ const flattenTopLevelCombinatorToolSchema = (
|
|
|
909
1023
|
|
|
910
1024
|
const anthropicToolInputSchema = (schema: unknown): unknown => {
|
|
911
1025
|
if (!isJsonObject(schema)) {
|
|
912
|
-
return
|
|
913
|
-
type: 'object',
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
1026
|
+
return schema === true
|
|
1027
|
+
? { type: 'object', properties: {} }
|
|
1028
|
+
: {
|
|
1029
|
+
type: 'object',
|
|
1030
|
+
properties: {},
|
|
1031
|
+
required: [],
|
|
1032
|
+
additionalProperties: false
|
|
1033
|
+
}
|
|
918
1034
|
}
|
|
919
1035
|
|
|
920
1036
|
const combinator = topLevelJsonSchemaCombinator(schema)
|