omnicell-router 0.7.0 → 0.8.2
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/backend/dist/cli/clients/activity.d.ts +35 -0
- package/backend/dist/cli/clients/activity.js +67 -0
- package/backend/dist/cli/clients/base.d.ts +13 -2
- package/backend/dist/cli/clients/claude.d.ts +2 -2
- package/backend/dist/cli/clients/codex.d.ts +2 -2
- package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
- package/backend/dist/cli/clients/core-adapters.js +3 -4
- package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
- package/backend/dist/cli/clients/cursor-proxy.js +421 -0
- package/backend/dist/cli/clients/dsh.d.ts +2 -2
- package/backend/dist/cli/clients/grok.d.ts +2 -2
- package/backend/dist/cli/clients/index.d.ts +8 -1
- package/backend/dist/cli/clients/index.js +55 -21
- package/backend/dist/cli/clients/kimi.d.ts +2 -2
- package/backend/dist/cli/clients/launcher.d.ts +8 -0
- package/backend/dist/cli/clients/model-meta.js +1 -1
- package/backend/dist/cli/clients/omp.d.ts +2 -2
- package/backend/dist/cli/clients/openclaw.d.ts +2 -2
- package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
- package/backend/dist/cli/clients/opencode-proxy.js +351 -0
- package/backend/dist/cli/clients/opencode.d.ts +2 -2
- package/backend/dist/cli/clients/pi.d.ts +2 -2
- package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
- package/backend/dist/cli/clients/plugin-adapters.js +6 -29
- package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
- package/backend/dist/cli/clients/qoder-proxy.js +497 -0
- package/backend/dist/cli/clients/reserved.d.ts +2 -6
- package/backend/dist/cli/clients/reserved.js +2 -0
- package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
- package/backend/dist/cli/index.js +60 -9
- package/backend/dist/cli/types.d.ts +29 -8
- package/backend/dist/compression/caveman-prompts.d.ts +1 -1
- package/backend/dist/config/comments-en.js +6 -12
- package/backend/dist/config/comments-zh.js +6 -12
- package/backend/dist/config/defaults.d.ts +56 -1
- package/backend/dist/config/defaults.js +68 -0
- package/backend/dist/config/index.d.ts +9 -2
- package/backend/dist/config/index.js +26 -3
- package/backend/dist/config/types.d.ts +55 -43
- package/backend/dist/forward-proxy/egress.d.ts +10 -2
- package/backend/dist/forward-proxy/egress.js +42 -4
- package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
- package/backend/dist/forward-proxy/ordered-relay.js +46 -0
- package/backend/dist/forward-proxy/rules.d.ts +66 -19
- package/backend/dist/forward-proxy/rules.js +61 -14
- package/backend/dist/forward-proxy/server.js +226 -77
- package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
- package/backend/dist/forward-proxy/system-proxy.js +199 -22
- package/backend/dist/harness/common/market.d.ts +3 -3
- package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
- package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
- package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
- package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
- package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
- package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
- package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
- package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
- package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
- package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
- package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
- package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
- package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
- package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
- package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
- package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
- package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
- package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
- package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
- package/backend/dist/harness/translation.js +64 -21
- package/backend/dist/harness/types.d.ts +1 -1
- package/backend/dist/harness/types.js +1 -1
- package/backend/dist/index.js +31 -18
- package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
- package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
- package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
- package/backend/dist/ir/adapters/anthropic.js +788 -0
- package/backend/dist/ir/adapters/chat.d.ts +15 -0
- package/backend/dist/ir/adapters/chat.js +602 -0
- package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
- package/backend/dist/ir/adapters/google-stream.js +242 -0
- package/backend/dist/ir/adapters/google.d.ts +9 -0
- package/backend/dist/ir/adapters/google.js +317 -0
- package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
- package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
- package/backend/dist/ir/adapters/openai-responses.js +26 -1
- package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
- package/backend/dist/ir/adapters/responses-output.js +348 -0
- package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
- package/backend/dist/ir/adapters/responses-stream.js +178 -0
- package/backend/dist/ir/adapters/responses.d.ts +14 -0
- package/backend/dist/ir/adapters/responses.js +646 -0
- package/backend/dist/ir/errors.d.ts +2 -2
- package/backend/dist/ir/types.d.ts +2 -1
- package/backend/dist/metrics/request-cost.d.ts +11 -2
- package/backend/dist/metrics/request-cost.js +12 -3
- package/backend/dist/observability/request-identity.d.ts +1 -1
- package/backend/dist/observability/trace-id.d.ts +40 -0
- package/backend/dist/observability/trace-id.js +134 -0
- package/backend/dist/observability/upstream-events.d.ts +82 -60
- package/backend/dist/observability/upstream-events.js +142 -67
- package/backend/dist/opencode/catalog/types.d.ts +9 -0
- package/backend/dist/opencode/credentials/types.d.ts +2 -2
- package/backend/dist/opencode/probe.d.ts +24 -1
- package/backend/dist/opencode/probe.js +28 -4
- package/backend/dist/opencode/user-config.d.ts +5 -0
- package/backend/dist/pipeline/directives.d.ts +6 -2
- package/backend/dist/pipeline/directives.js +7 -3
- package/backend/dist/pipeline/orchestrator.d.ts +28 -27
- package/backend/dist/pipeline/orchestrator.js +220 -194
- package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
- package/backend/dist/pipeline/unresolved-model.js +43 -0
- package/backend/dist/plugins/catalog-def.d.ts +143 -0
- package/backend/dist/plugins/catalog-def.js +177 -0
- package/backend/dist/plugins/gateways.d.ts +62 -3
- package/backend/dist/plugins/gateways.js +139 -2
- package/backend/dist/plugins/host.d.ts +42 -5
- package/backend/dist/plugins/host.js +454 -38
- package/backend/dist/plugins/manifest.d.ts +119 -10
- package/backend/dist/plugins/manifest.js +265 -14
- package/backend/dist/plugins/pack.js +26 -0
- package/backend/dist/plugins/types.d.ts +187 -21
- package/backend/dist/protocols/systemone/convert.d.ts +1 -0
- package/backend/dist/protocols/systemone/convert.js +6 -1
- package/backend/dist/protocols/systemone/decide.js +18 -8
- package/backend/dist/providers/anthropic-messages.d.ts +12 -0
- package/backend/dist/providers/anthropic-messages.js +53 -0
- package/backend/dist/providers/anthropic.d.ts +7 -8
- package/backend/dist/providers/anthropic.js +36 -324
- package/backend/dist/providers/base.d.ts +14 -2
- package/backend/dist/providers/boot-direct.js +68 -38
- package/backend/dist/providers/dispatch.d.ts +5 -19
- package/backend/dist/providers/dispatch.js +46 -58
- package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
- package/backend/dist/providers/executors/anthropic-messages.js +3 -0
- package/backend/dist/providers/executors/dispatch.d.ts +16 -2
- package/backend/dist/providers/executors/dispatch.js +39 -9
- package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
- package/backend/dist/providers/executors/google-gemini.js +3 -0
- package/backend/dist/providers/executors/http-stream.js +16 -3
- package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
- package/backend/dist/providers/executors/openai-chat.js +3 -0
- package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
- package/backend/dist/providers/executors/openai-responses.js +3 -0
- package/backend/dist/providers/executors/plugin-adapter.js +4 -4
- package/backend/dist/providers/google-gemini.d.ts +12 -0
- package/backend/dist/providers/google-gemini.js +50 -0
- package/backend/dist/providers/google.d.ts +7 -8
- package/backend/dist/providers/google.js +35 -308
- package/backend/dist/providers/http-json.d.ts +19 -0
- package/backend/dist/providers/http-json.js +104 -0
- package/backend/dist/providers/http-stream.d.ts +52 -0
- package/backend/dist/providers/http-stream.js +423 -0
- package/backend/dist/providers/member-match.d.ts +4 -5
- package/backend/dist/providers/member-match.js +4 -5
- package/backend/dist/providers/openai-chat.d.ts +13 -0
- package/backend/dist/providers/openai-chat.js +99 -0
- package/backend/dist/providers/openai-compatible.d.ts +7 -4
- package/backend/dist/providers/openai-compatible.js +71 -368
- package/backend/dist/providers/openai-responses.d.ts +12 -0
- package/backend/dist/providers/openai-responses.js +68 -0
- package/backend/dist/providers/opencode-proxy.d.ts +5 -5
- package/backend/dist/providers/opencode-proxy.js +49 -125
- package/backend/dist/providers/plugin-adapter.d.ts +9 -0
- package/backend/dist/providers/plugin-adapter.js +31 -0
- package/backend/dist/providers/registry.d.ts +49 -24
- package/backend/dist/providers/registry.js +97 -55
- package/backend/dist/providers/responses.d.ts +7 -28
- package/backend/dist/providers/responses.js +45 -253
- package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
- package/backend/dist/providers/tool-markup-leak.js +57 -0
- package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
- package/backend/dist/providers/tool-markup-recovery.js +786 -0
- package/backend/dist/providers/virtual-meta.d.ts +21 -2
- package/backend/dist/providers/virtual-meta.js +49 -9
- package/backend/dist/proxy/asset-download.d.ts +54 -0
- package/backend/dist/proxy/asset-download.js +420 -0
- package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
- package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
- package/backend/dist/proxy/mihomo-binary.js +62 -51
- package/backend/dist/proxy/mihomo-client.js +15 -1
- package/backend/dist/proxy/mihomo-config.js +11 -2
- package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
- package/backend/dist/proxy/mihomo-geo.js +213 -0
- package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
- package/backend/dist/proxy/mihomo-logs.js +70 -0
- package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
- package/backend/dist/proxy/mihomo-pac.js +15 -0
- package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
- package/backend/dist/proxy/mihomo-rules-import.js +7 -7
- package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
- package/backend/dist/proxy/mihomo-sidecar.js +148 -26
- package/backend/dist/quota/adapters/minimax.js +36 -13
- package/backend/dist/quota/cli-login.d.ts +8 -0
- package/backend/dist/quota/cli-login.js +18 -0
- package/backend/dist/quota/declarations.js +10 -0
- package/backend/dist/quota/dsl.js +18 -5
- package/backend/dist/quota/engine.d.ts +22 -1
- package/backend/dist/quota/engine.js +170 -29
- package/backend/dist/quota/prober.d.ts +5 -0
- package/backend/dist/quota/prober.js +11 -2
- package/backend/dist/quota/types.d.ts +87 -8
- package/backend/dist/quota/verdict.d.ts +35 -0
- package/backend/dist/quota/verdict.js +135 -0
- package/backend/dist/ratelimit/admission.d.ts +131 -0
- package/backend/dist/ratelimit/admission.js +233 -0
- package/backend/dist/ratelimit/rate-limiter.js +6 -0
- package/backend/dist/resilience/types.d.ts +2 -2
- package/backend/dist/router/layer2-decision.d.ts +1 -1
- package/backend/dist/router/layer2-decision.js +5 -8
- package/backend/dist/routes/console.js +248 -52
- package/backend/dist/routes/mihomo.d.ts +2 -0
- package/backend/dist/routes/mihomo.js +334 -29
- package/backend/dist/routes/responses.d.ts +87 -8
- package/backend/dist/routes/responses.js +314 -33
- package/backend/dist/server.js +34 -6
- package/backend/dist/session/session-manager.d.ts +6 -0
- package/backend/dist/session/session-manager.js +20 -9
- package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
- package/backend/dist/surfaces/chat-pipeline.js +17 -7
- package/backend/dist/surfaces/chat.js +15 -0
- package/backend/dist/surfaces/decision-pipeline.js +7 -10
- package/backend/dist/surfaces/direct-forward.d.ts +3 -0
- package/backend/dist/surfaces/direct-forward.js +206 -0
- package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
- package/backend/dist/surfaces/rate-limit-response.js +57 -0
- package/backend/dist/surfaces/types.d.ts +11 -0
- package/backend/dist/trace/tracker.d.ts +32 -1
- package/backend/dist/trace/tracker.js +29 -4
- package/backend/dist/types/router.d.ts +34 -12
- package/backend/dist/types/router.js +35 -6
- package/backend/dist/utils/chat-stream.d.ts +21 -8
- package/backend/dist/utils/chat-stream.js +46 -9
- package/backend/dist/utils/event-ring.d.ts +4 -0
- package/backend/dist/utils/event-ring.js +4 -0
- package/backend/dist/utils/popularity.js +29 -4
- package/backend/dist/utils/proxy.d.ts +7 -0
- package/backend/dist/utils/proxy.js +35 -10
- package/backend/dist/utils/retry-after.d.ts +21 -0
- package/backend/dist/utils/retry-after.js +36 -0
- package/bin/ocr.js +2 -2
- package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
- package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
- package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
- package/frontend/dist/index.html +2 -2
- package/package.json +1 -1
- package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { EFFORT_LADDER } from '../../types/router.js';
|
|
3
|
+
import { IrUnsupportedError } from '../errors.js';
|
|
4
|
+
import { assertCanonicalRequestSupported, assertCanonicalResponseSupported, assertCanonicalStreamEventSupported, } from '../validate.js';
|
|
5
|
+
const PROTOCOL = 'anthropic';
|
|
6
|
+
const DEFAULT_MAX_TOKENS = 4096;
|
|
7
|
+
const EFFORT_TO_BUDGET = {
|
|
8
|
+
none: 0,
|
|
9
|
+
minimal: 512,
|
|
10
|
+
low: 1024,
|
|
11
|
+
medium: 4096,
|
|
12
|
+
high: 16384,
|
|
13
|
+
xhigh: 32768,
|
|
14
|
+
max: 65536,
|
|
15
|
+
};
|
|
16
|
+
function record(value) {
|
|
17
|
+
return value && typeof value === 'object' ? value : {};
|
|
18
|
+
}
|
|
19
|
+
function fail(code, message) {
|
|
20
|
+
throw new IrUnsupportedError(code, message, PROTOCOL);
|
|
21
|
+
}
|
|
22
|
+
function cacheOf(raw) {
|
|
23
|
+
if (!raw || typeof raw !== 'object')
|
|
24
|
+
return undefined;
|
|
25
|
+
const value = record(raw);
|
|
26
|
+
return { ...(typeof value.type === 'string' ? { type: value.type } : {}), raw: value };
|
|
27
|
+
}
|
|
28
|
+
function cacheToWire(cache) {
|
|
29
|
+
if (!cache)
|
|
30
|
+
return undefined;
|
|
31
|
+
return cache.raw ?? (cache.type ? { type: cache.type } : undefined);
|
|
32
|
+
}
|
|
33
|
+
function parseObject(raw) {
|
|
34
|
+
if (raw && typeof raw === 'object' && !Array.isArray(raw))
|
|
35
|
+
return raw;
|
|
36
|
+
if (typeof raw !== 'string' || !raw.trim())
|
|
37
|
+
return {};
|
|
38
|
+
try {
|
|
39
|
+
const value = JSON.parse(raw);
|
|
40
|
+
if (value && typeof value === 'object' && !Array.isArray(value))
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// The explicit error below is the tool-call contract, not a fallback shape.
|
|
45
|
+
}
|
|
46
|
+
return fail('tool_arguments', 'Anthropic tool_use input requires a JSON object string.');
|
|
47
|
+
}
|
|
48
|
+
function sourceFromWire(raw) {
|
|
49
|
+
const source = record(raw);
|
|
50
|
+
if (source.type === 'base64' && typeof source.data === 'string' && typeof source.media_type === 'string') {
|
|
51
|
+
return {
|
|
52
|
+
type: 'image',
|
|
53
|
+
source: { kind: 'base64', mediaType: source.media_type, data: source.data },
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (source.type === 'url' && typeof source.url === 'string') {
|
|
57
|
+
return { type: 'image', source: { kind: 'url', url: source.url } };
|
|
58
|
+
}
|
|
59
|
+
if (source.type === 'file' && typeof source.file_id === 'string') {
|
|
60
|
+
return { type: 'image', source: { kind: 'file', fileId: source.file_id } };
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
function partFromWire(raw) {
|
|
65
|
+
const block = record(raw);
|
|
66
|
+
const cache = cacheOf(block.cache_control);
|
|
67
|
+
if (block.type === 'text' && typeof block.text === 'string') {
|
|
68
|
+
return {
|
|
69
|
+
type: 'text', text: block.text,
|
|
70
|
+
...(Array.isArray(block.citations) ? {
|
|
71
|
+
annotations: block.citations.map((payload) => ({ type: 'extension', protocol: PROTOCOL, payload })),
|
|
72
|
+
} : {}),
|
|
73
|
+
...(cache ? { cache } : {}),
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
if (block.type === 'image') {
|
|
77
|
+
const part = sourceFromWire(block.source);
|
|
78
|
+
if (part)
|
|
79
|
+
return { ...part, ...(cache ? { cache } : {}) };
|
|
80
|
+
}
|
|
81
|
+
if (block.type === 'document') {
|
|
82
|
+
const source = record(block.source);
|
|
83
|
+
const common = {
|
|
84
|
+
...(typeof block.title === 'string' ? { filename: block.title } : {}),
|
|
85
|
+
...(cache ? { cache } : {}),
|
|
86
|
+
};
|
|
87
|
+
if (source.type === 'base64' && typeof source.data === 'string') {
|
|
88
|
+
return {
|
|
89
|
+
type: 'file',
|
|
90
|
+
source: {
|
|
91
|
+
kind: 'base64',
|
|
92
|
+
mediaType: typeof source.media_type === 'string' ? source.media_type : 'application/pdf',
|
|
93
|
+
data: source.data,
|
|
94
|
+
},
|
|
95
|
+
...common,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (source.type === 'url' && typeof source.url === 'string') {
|
|
99
|
+
return { type: 'file', source: { kind: 'url', url: source.url }, ...common };
|
|
100
|
+
}
|
|
101
|
+
if (source.type === 'file' && typeof source.file_id === 'string') {
|
|
102
|
+
return { type: 'file', source: { kind: 'file', fileId: source.file_id }, ...common };
|
|
103
|
+
}
|
|
104
|
+
if (source.type === 'text' && typeof source.data === 'string') {
|
|
105
|
+
return {
|
|
106
|
+
type: 'file',
|
|
107
|
+
source: {
|
|
108
|
+
kind: 'base64',
|
|
109
|
+
mediaType: typeof source.media_type === 'string' ? source.media_type : 'text/plain',
|
|
110
|
+
data: Buffer.from(source.data, 'utf8').toString('base64'),
|
|
111
|
+
},
|
|
112
|
+
...common,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// Unknown blocks stay opaque. Same-carrier passthrough can replay them;
|
|
117
|
+
// cross-carrier conversion fails at the common capability gate.
|
|
118
|
+
return { type: 'extension', protocol: PROTOCOL, payload: raw };
|
|
119
|
+
}
|
|
120
|
+
function partToWire(part, output = false) {
|
|
121
|
+
if (part.type === 'extension') {
|
|
122
|
+
if (part.protocol !== PROTOCOL)
|
|
123
|
+
fail('content_part', `Cannot convert ${part.protocol} content.`);
|
|
124
|
+
return record(part.payload);
|
|
125
|
+
}
|
|
126
|
+
const cache = 'cache' in part ? cacheToWire(part.cache) : undefined;
|
|
127
|
+
if (part.type === 'text') {
|
|
128
|
+
const citations = part.annotations?.map((annotation) => {
|
|
129
|
+
if (annotation.type !== 'extension' || annotation.protocol !== PROTOCOL) {
|
|
130
|
+
fail('annotation', `Anthropic cannot convert ${annotation.type} annotations without a carrier-native mapping.`);
|
|
131
|
+
}
|
|
132
|
+
return annotation.payload;
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
type: 'text', text: part.text,
|
|
136
|
+
...(citations ? { citations } : {}),
|
|
137
|
+
...(cache ? { cache_control: cache } : {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
if (part.type === 'image') {
|
|
141
|
+
const source = part.source.kind === 'base64'
|
|
142
|
+
? { type: 'base64', media_type: part.source.mediaType, data: part.source.data }
|
|
143
|
+
: part.source.kind === 'url'
|
|
144
|
+
? { type: 'url', url: part.source.url }
|
|
145
|
+
: { type: 'file', file_id: part.source.fileId };
|
|
146
|
+
return { type: 'image', source, ...(cache ? { cache_control: cache } : {}) };
|
|
147
|
+
}
|
|
148
|
+
if (part.type === 'file') {
|
|
149
|
+
const source = part.source.kind === 'base64'
|
|
150
|
+
? { type: 'base64', media_type: part.source.mediaType, data: part.source.data }
|
|
151
|
+
: part.source.kind === 'url'
|
|
152
|
+
? { type: 'url', url: part.source.url }
|
|
153
|
+
: { type: 'file', file_id: part.source.fileId };
|
|
154
|
+
return {
|
|
155
|
+
type: 'document', source,
|
|
156
|
+
...(part.filename ? { title: part.filename } : {}),
|
|
157
|
+
...(cache ? { cache_control: cache } : {}),
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
if (part.type === 'refusal' && output)
|
|
161
|
+
return { type: 'text', text: part.text };
|
|
162
|
+
fail('content_part', `Anthropic cannot carry ${part.type} content.`);
|
|
163
|
+
}
|
|
164
|
+
function itemsFromMessage(role, rawContent) {
|
|
165
|
+
if (typeof rawContent === 'string') {
|
|
166
|
+
return [{ type: 'message', role, content: rawContent ? [{ type: 'text', text: rawContent }] : [] }];
|
|
167
|
+
}
|
|
168
|
+
const blocks = Array.isArray(rawContent) ? rawContent : [];
|
|
169
|
+
const items = [];
|
|
170
|
+
let messageParts = [];
|
|
171
|
+
const flush = () => {
|
|
172
|
+
if (!messageParts.length)
|
|
173
|
+
return;
|
|
174
|
+
items.push({ type: 'message', role, content: messageParts });
|
|
175
|
+
messageParts = [];
|
|
176
|
+
};
|
|
177
|
+
for (const raw of blocks) {
|
|
178
|
+
const block = record(raw);
|
|
179
|
+
if (block.type === 'tool_use') {
|
|
180
|
+
flush();
|
|
181
|
+
items.push({
|
|
182
|
+
type: 'tool_call',
|
|
183
|
+
id: String(block.id ?? ''),
|
|
184
|
+
callId: String(block.id ?? ''),
|
|
185
|
+
name: String(block.name ?? ''),
|
|
186
|
+
arguments: JSON.stringify(block.input ?? {}),
|
|
187
|
+
});
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (block.type === 'tool_result') {
|
|
191
|
+
flush();
|
|
192
|
+
const content = typeof block.content === 'string'
|
|
193
|
+
? [{ type: 'text', text: block.content }]
|
|
194
|
+
: (Array.isArray(block.content) ? block.content : []).map(partFromWire);
|
|
195
|
+
items.push({
|
|
196
|
+
type: 'tool_result',
|
|
197
|
+
callId: String(block.tool_use_id ?? ''),
|
|
198
|
+
content,
|
|
199
|
+
...(block.is_error === true ? { isError: true } : {}),
|
|
200
|
+
...(cacheOf(block.cache_control) ? { cache: cacheOf(block.cache_control) } : {}),
|
|
201
|
+
});
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (block.type === 'thinking' || block.type === 'redacted_thinking') {
|
|
205
|
+
flush();
|
|
206
|
+
items.push({
|
|
207
|
+
type: 'reasoning',
|
|
208
|
+
...(typeof block.thinking === 'string' ? { text: block.thinking } : {}),
|
|
209
|
+
...(typeof block.signature === 'string' ? { signature: block.signature } : {}),
|
|
210
|
+
...(typeof block.data === 'string' ? { encrypted: block.data } : {}),
|
|
211
|
+
vendor: { anthropic: { blockType: block.type } },
|
|
212
|
+
});
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
messageParts.push(partFromWire(block));
|
|
216
|
+
}
|
|
217
|
+
flush();
|
|
218
|
+
if (!items.length)
|
|
219
|
+
items.push({ type: 'message', role, content: [] });
|
|
220
|
+
return items;
|
|
221
|
+
}
|
|
222
|
+
function systemToIR(system) {
|
|
223
|
+
if (typeof system === 'string')
|
|
224
|
+
return system ? { instructions: system } : {};
|
|
225
|
+
if (!Array.isArray(system))
|
|
226
|
+
return system === undefined || system === null ? {} : fail('system', 'Anthropic system must be a string or block array.');
|
|
227
|
+
const texts = [];
|
|
228
|
+
let systemCache;
|
|
229
|
+
for (const raw of system) {
|
|
230
|
+
const block = record(raw);
|
|
231
|
+
if (block.type !== 'text' || typeof block.text !== 'string') {
|
|
232
|
+
fail('system_block', `Unsupported Anthropic system block: ${String(block.type)}.`);
|
|
233
|
+
}
|
|
234
|
+
texts.push(block.text);
|
|
235
|
+
systemCache ??= cacheOf(block.cache_control);
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
...(texts.length ? { instructions: texts.join('\n\n') } : {}),
|
|
239
|
+
...(systemCache ? { systemCache } : {}),
|
|
240
|
+
...(system.length ? { systemBlocks: system.map((block) => ({ ...record(block) })) } : {}),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/** Anthropic Messages request → Canonical IR. No Chat-shaped intermediate. */
|
|
244
|
+
export function anthropicRequestToIR(body) {
|
|
245
|
+
const req = record(body);
|
|
246
|
+
if (!Array.isArray(req.messages) || req.messages.length === 0) {
|
|
247
|
+
fail('messages', 'Invalid request: "messages" array is required.');
|
|
248
|
+
}
|
|
249
|
+
const input = [];
|
|
250
|
+
for (const raw of req.messages) {
|
|
251
|
+
const message = record(raw);
|
|
252
|
+
if (message.role !== 'user' && message.role !== 'assistant')
|
|
253
|
+
fail('role', `Invalid Anthropic role: ${String(message.role)}.`);
|
|
254
|
+
input.push(...itemsFromMessage(message.role, message.content));
|
|
255
|
+
}
|
|
256
|
+
const system = systemToIR(req.system);
|
|
257
|
+
const tools = Array.isArray(req.tools) ? req.tools.map((raw) => {
|
|
258
|
+
const tool = record(raw);
|
|
259
|
+
if (typeof tool.name !== 'string')
|
|
260
|
+
fail('tool', 'Anthropic function tools require a name.');
|
|
261
|
+
return {
|
|
262
|
+
type: 'function',
|
|
263
|
+
function: {
|
|
264
|
+
name: tool.name,
|
|
265
|
+
...(typeof tool.description === 'string' ? { description: tool.description } : {}),
|
|
266
|
+
parameters: record(tool.input_schema),
|
|
267
|
+
...(typeof tool.strict === 'boolean' ? { strict: tool.strict } : {}),
|
|
268
|
+
...(cacheOf(tool.cache_control) ? { cache: cacheOf(tool.cache_control) } : {}),
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}) : undefined;
|
|
272
|
+
if (req.tools !== undefined && !Array.isArray(req.tools))
|
|
273
|
+
fail('tools', 'Anthropic tools must be an array.');
|
|
274
|
+
const choice = record(req.tool_choice);
|
|
275
|
+
const toolChoice = choice.type === 'auto' || choice.type === 'none'
|
|
276
|
+
? { type: choice.type }
|
|
277
|
+
: choice.type === 'any'
|
|
278
|
+
? { type: 'required' }
|
|
279
|
+
: choice.type === 'tool' && typeof choice.name === 'string'
|
|
280
|
+
? { type: 'function', name: choice.name }
|
|
281
|
+
: undefined;
|
|
282
|
+
if (req.tool_choice !== undefined && !toolChoice)
|
|
283
|
+
fail('tool_choice', 'Unsupported Anthropic tool_choice.');
|
|
284
|
+
const thinking = record(req.thinking);
|
|
285
|
+
const outputConfig = record(req.output_config);
|
|
286
|
+
const configuredEffort = typeof outputConfig.effort === 'string' && EFFORT_LADDER.includes(outputConfig.effort)
|
|
287
|
+
? outputConfig.effort
|
|
288
|
+
: undefined;
|
|
289
|
+
if (outputConfig.effort !== undefined && !configuredEffort) {
|
|
290
|
+
fail('reasoning_effort', `Unsupported Anthropic output_config.effort: ${String(outputConfig.effort)}.`);
|
|
291
|
+
}
|
|
292
|
+
const metadata = record(req.metadata);
|
|
293
|
+
return {
|
|
294
|
+
model: typeof req.model === 'string' && req.model.trim() ? req.model.trim() : 'auto',
|
|
295
|
+
stream: req.stream === true,
|
|
296
|
+
...(system.instructions ? { instructions: system.instructions } : {}),
|
|
297
|
+
input,
|
|
298
|
+
...(tools?.length ? { tools } : {}),
|
|
299
|
+
...(toolChoice ? { toolChoice } : {}),
|
|
300
|
+
...(toolChoice && choice.disable_parallel_tool_use === true ? { parallelToolCalls: false } : {}),
|
|
301
|
+
generation: {
|
|
302
|
+
maxOutputTokens: typeof req.max_tokens === 'number' ? req.max_tokens : DEFAULT_MAX_TOKENS,
|
|
303
|
+
...(typeof req.temperature === 'number' ? { temperature: req.temperature } : {}),
|
|
304
|
+
...(typeof req.top_p === 'number' ? { topP: req.top_p } : {}),
|
|
305
|
+
...(typeof req.top_k === 'number' ? { topK: req.top_k } : {}),
|
|
306
|
+
...(Array.isArray(req.stop_sequences) ? { stop: req.stop_sequences } : {}),
|
|
307
|
+
},
|
|
308
|
+
...(thinking.type === 'enabled' || configuredEffort || thinking.type === 'disabled'
|
|
309
|
+
? {
|
|
310
|
+
reasoning: {
|
|
311
|
+
...(thinking.type === 'enabled' && typeof thinking.budget_tokens === 'number'
|
|
312
|
+
? { budgetTokens: thinking.budget_tokens }
|
|
313
|
+
: {}),
|
|
314
|
+
...(configuredEffort ? { effort: configuredEffort } : thinking.type === 'disabled' ? { effort: 'none' } : {}),
|
|
315
|
+
},
|
|
316
|
+
}
|
|
317
|
+
: {}),
|
|
318
|
+
...(typeof metadata.user_id === 'string' ? { user: metadata.user_id } : {}),
|
|
319
|
+
...(outputConfig.format || system.systemCache || system.systemBlocks
|
|
320
|
+
? {
|
|
321
|
+
vendor: {
|
|
322
|
+
anthropic: {
|
|
323
|
+
...(outputConfig.format ? { outputFormat: outputConfig.format } : {}),
|
|
324
|
+
...(system.systemCache ? { systemCache: system.systemCache } : {}),
|
|
325
|
+
...(system.systemBlocks ? { systemBlocks: system.systemBlocks } : {}),
|
|
326
|
+
},
|
|
327
|
+
},
|
|
328
|
+
}
|
|
329
|
+
: {}),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function appendMessage(messages, role, blocks) {
|
|
333
|
+
if (!blocks.length)
|
|
334
|
+
return;
|
|
335
|
+
const previous = messages[messages.length - 1];
|
|
336
|
+
if (previous?.role === role && Array.isArray(previous.content))
|
|
337
|
+
previous.content.push(...blocks);
|
|
338
|
+
else
|
|
339
|
+
messages.push({ role, content: blocks });
|
|
340
|
+
}
|
|
341
|
+
function reasoningToWire(item) {
|
|
342
|
+
const redacted = item.vendor?.anthropic?.blockType === 'redacted_thinking' || (!item.text && item.encrypted);
|
|
343
|
+
if (redacted) {
|
|
344
|
+
if (!item.encrypted)
|
|
345
|
+
fail('reasoning_signature', 'Redacted Anthropic thinking requires its opaque data.');
|
|
346
|
+
return { type: 'redacted_thinking', data: item.encrypted };
|
|
347
|
+
}
|
|
348
|
+
return {
|
|
349
|
+
type: 'thinking',
|
|
350
|
+
thinking: item.text ?? '',
|
|
351
|
+
...(item.signature ? { signature: item.signature } : {}),
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** Canonical IR → Anthropic Messages request. */
|
|
355
|
+
export function canonicalToAnthropicPayload(ir, model) {
|
|
356
|
+
assertCanonicalRequestSupported(ir, PROTOCOL);
|
|
357
|
+
const messages = [];
|
|
358
|
+
for (const item of ir.input) {
|
|
359
|
+
if (item.type === 'message') {
|
|
360
|
+
if (item.role === 'system' || item.role === 'developer')
|
|
361
|
+
continue;
|
|
362
|
+
const blocks = item.content.map((part) => partToWire(part));
|
|
363
|
+
if (item.cache) {
|
|
364
|
+
const last = blocks.at(-1);
|
|
365
|
+
if (!last)
|
|
366
|
+
fail('cache_item_breakpoint', 'An Anthropic message cache breakpoint requires a content block.');
|
|
367
|
+
if (last.cache_control)
|
|
368
|
+
fail('cache_item_breakpoint', 'Message and final-part cache breakpoints cannot be merged.');
|
|
369
|
+
last.cache_control = cacheToWire(item.cache);
|
|
370
|
+
}
|
|
371
|
+
appendMessage(messages, item.role, blocks);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (item.type === 'reasoning') {
|
|
375
|
+
appendMessage(messages, 'assistant', [reasoningToWire(item)]);
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (item.type === 'tool_call') {
|
|
379
|
+
appendMessage(messages, 'assistant', [{
|
|
380
|
+
type: 'tool_use', id: item.callId ?? item.id, name: item.name, input: parseObject(item.arguments),
|
|
381
|
+
}]);
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
if (item.type === 'tool_result') {
|
|
385
|
+
const content = item.content.map((part) => partToWire(part));
|
|
386
|
+
appendMessage(messages, 'user', [{
|
|
387
|
+
type: 'tool_result', tool_use_id: item.callId,
|
|
388
|
+
content: content.every((part) => part.type === 'text')
|
|
389
|
+
? content.map((part) => part.text).join('\n')
|
|
390
|
+
: content,
|
|
391
|
+
...(item.isError ? { is_error: true } : {}),
|
|
392
|
+
...(cacheToWire(item.cache) ? { cache_control: cacheToWire(item.cache) } : {}),
|
|
393
|
+
}]);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
if (item.type === 'extension' && item.protocol === PROTOCOL) {
|
|
397
|
+
const raw = record(item.payload);
|
|
398
|
+
appendMessage(messages, raw.role === 'assistant' ? 'assistant' : 'user', [raw]);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
fail('input_item', 'Anthropic cannot resolve item references or foreign extension items.');
|
|
402
|
+
}
|
|
403
|
+
const systemMessages = ir.input.filter((item) => item.type === 'message' && (item.role === 'system' || item.role === 'developer'));
|
|
404
|
+
const systemText = [ir.instructions, ...systemMessages.map((item) => item.type === 'message'
|
|
405
|
+
? item.content.map((part) => part.type === 'text' ? part.text : fail('system_part', 'Anthropic system prompts carry text only.')).join('')
|
|
406
|
+
: '')].filter(Boolean).join('\n\n');
|
|
407
|
+
const declaredCache = systemMessages.find((item) => item.type === 'message' && item.cache !== undefined)?.cache;
|
|
408
|
+
const vendorCache = ir.vendor?.anthropic?.systemCache;
|
|
409
|
+
const vendorBlocks = ir.vendor?.anthropic?.systemBlocks;
|
|
410
|
+
const originalBlocks = systemMessages.length === 0 && Array.isArray(vendorBlocks) &&
|
|
411
|
+
vendorBlocks.every((block) => record(block).type === 'text' && typeof record(block).text === 'string')
|
|
412
|
+
? vendorBlocks
|
|
413
|
+
: undefined;
|
|
414
|
+
const originalText = originalBlocks?.map((block) => String(block.text)).join('\n\n');
|
|
415
|
+
const replayOriginal = originalBlocks !== undefined && originalText === systemText && declaredCache === undefined;
|
|
416
|
+
const systemCache = declaredCache ?? (replayOriginal && vendorCache && typeof vendorCache === 'object'
|
|
417
|
+
? vendorCache
|
|
418
|
+
: undefined);
|
|
419
|
+
const system = replayOriginal
|
|
420
|
+
? originalBlocks.map((block) => ({ ...block }))
|
|
421
|
+
: systemText
|
|
422
|
+
? [{ type: 'text', text: systemText, cache_control: cacheToWire(systemCache) ?? { type: 'ephemeral' } }]
|
|
423
|
+
: undefined;
|
|
424
|
+
const maxFromRequest = ir.generation?.maxOutputTokens ?? DEFAULT_MAX_TOKENS;
|
|
425
|
+
let maxTokens = maxFromRequest;
|
|
426
|
+
let thinking;
|
|
427
|
+
const effort = ir.reasoning?.effort;
|
|
428
|
+
const explicitBudget = ir.reasoning?.budgetTokens !== undefined && ir.reasoning.budgetTokens > 0
|
|
429
|
+
? ir.reasoning.budgetTokens
|
|
430
|
+
: undefined;
|
|
431
|
+
if ((effort && effort !== 'none') || explicitBudget !== undefined) {
|
|
432
|
+
const budget = explicitBudget ?? EFFORT_TO_BUDGET[effort];
|
|
433
|
+
if (budget > 0) {
|
|
434
|
+
maxTokens = Math.max(maxTokens, budget + 1024);
|
|
435
|
+
thinking = { type: 'enabled', budget_tokens: budget };
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const tools = ir.tools?.map((tool) => {
|
|
439
|
+
if (tool.type !== 'function')
|
|
440
|
+
fail('tool_type', `Anthropic carries function tools only, not ${tool.type}.`);
|
|
441
|
+
return {
|
|
442
|
+
name: tool.function.name,
|
|
443
|
+
...(tool.function.description !== undefined ? { description: tool.function.description } : {}),
|
|
444
|
+
input_schema: tool.function.parameters ?? { type: 'object', properties: {} },
|
|
445
|
+
...(tool.function.strict !== undefined ? { strict: tool.function.strict } : {}),
|
|
446
|
+
...(cacheToWire(tool.function.cache) ? { cache_control: cacheToWire(tool.function.cache) } : {}),
|
|
447
|
+
};
|
|
448
|
+
});
|
|
449
|
+
const disableParallel = ir.parallelToolCalls === false && !!tools?.length;
|
|
450
|
+
const toolChoice = ir.toolChoice
|
|
451
|
+
? ir.toolChoice.type === 'required'
|
|
452
|
+
? { type: 'any' }
|
|
453
|
+
: ir.toolChoice.type === 'function'
|
|
454
|
+
? { type: 'tool', name: ir.toolChoice.name }
|
|
455
|
+
: ir.toolChoice.type === 'auto' || ir.toolChoice.type === 'none'
|
|
456
|
+
? { type: ir.toolChoice.type }
|
|
457
|
+
: fail('tool_choice', `Anthropic cannot express ${ir.toolChoice.type}.`)
|
|
458
|
+
: undefined;
|
|
459
|
+
if (disableParallel && toolChoice?.type !== 'none') {
|
|
460
|
+
Object.assign(toolChoice ?? {}, { disable_parallel_tool_use: true });
|
|
461
|
+
}
|
|
462
|
+
const schema = ir.text?.format?.type === 'json_schema' ? ir.text.format.schema : undefined;
|
|
463
|
+
const outputFormat = ir.vendor?.anthropic?.outputFormat;
|
|
464
|
+
return {
|
|
465
|
+
model: model.upstreamModel,
|
|
466
|
+
max_tokens: maxTokens,
|
|
467
|
+
messages,
|
|
468
|
+
...(system ? { system } : {}),
|
|
469
|
+
...(ir.generation?.temperature !== undefined && model.temperature !== false
|
|
470
|
+
? { temperature: ir.generation.temperature }
|
|
471
|
+
: {}),
|
|
472
|
+
...(ir.generation?.topP !== undefined ? { top_p: ir.generation.topP } : {}),
|
|
473
|
+
...(ir.generation?.topK !== undefined ? { top_k: ir.generation.topK } : {}),
|
|
474
|
+
...(ir.generation?.stop?.length ? { stop_sequences: ir.generation.stop } : {}),
|
|
475
|
+
...(thinking ? { thinking } : {}),
|
|
476
|
+
...(tools?.length ? { tools } : {}),
|
|
477
|
+
...(toolChoice || disableParallel
|
|
478
|
+
? { tool_choice: { ...(toolChoice ?? { type: 'auto' }), ...(disableParallel ? { disable_parallel_tool_use: true } : {}) } }
|
|
479
|
+
: {}),
|
|
480
|
+
...(schema || outputFormat
|
|
481
|
+
? { output_config: { ...(schema ? { format: { type: 'json_schema', schema } } : outputFormat ? { format: outputFormat } : {}) } }
|
|
482
|
+
: {}),
|
|
483
|
+
...(ir.user ? { metadata: { user_id: ir.user } } : {}),
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
function usageFromWire(raw) {
|
|
487
|
+
const usage = record(raw);
|
|
488
|
+
const cached = usage.cache_read_input_tokens ?? 0;
|
|
489
|
+
const write = usage.cache_creation_input_tokens ?? 0;
|
|
490
|
+
const input = (usage.input_tokens ?? 0) + cached + write;
|
|
491
|
+
const output = usage.output_tokens ?? 0;
|
|
492
|
+
return {
|
|
493
|
+
inputTokens: input,
|
|
494
|
+
outputTokens: output,
|
|
495
|
+
totalTokens: input + output,
|
|
496
|
+
cachedInputTokens: cached,
|
|
497
|
+
cacheWriteTokens: write,
|
|
498
|
+
...(usage.cache_creation?.ephemeral_5m_input_tokens !== undefined
|
|
499
|
+
? { cacheWrite5mTokens: usage.cache_creation.ephemeral_5m_input_tokens }
|
|
500
|
+
: {}),
|
|
501
|
+
...(usage.cache_creation?.ephemeral_1h_input_tokens !== undefined
|
|
502
|
+
? { cacheWrite1hTokens: usage.cache_creation.ephemeral_1h_input_tokens }
|
|
503
|
+
: {}),
|
|
504
|
+
...(usage.output_tokens_details?.thinking_tokens !== undefined
|
|
505
|
+
? { reasoningTokens: usage.output_tokens_details.thinking_tokens }
|
|
506
|
+
: {}),
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/** Anthropic Messages response → Canonical IR, including signed thinking. */
|
|
510
|
+
export function anthropicResponseToIR(data) {
|
|
511
|
+
const body = record(data);
|
|
512
|
+
const output = [];
|
|
513
|
+
for (const raw of Array.isArray(body.content) ? body.content : []) {
|
|
514
|
+
const block = record(raw);
|
|
515
|
+
if (block.type === 'tool_use') {
|
|
516
|
+
output.push({
|
|
517
|
+
type: 'tool_call', id: String(block.id ?? ''), callId: String(block.id ?? ''),
|
|
518
|
+
name: String(block.name ?? ''), arguments: JSON.stringify(block.input ?? {}),
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
else if (block.type === 'thinking' || block.type === 'redacted_thinking') {
|
|
522
|
+
output.push({
|
|
523
|
+
type: 'reasoning',
|
|
524
|
+
...(typeof block.thinking === 'string' ? { text: block.thinking } : {}),
|
|
525
|
+
...(typeof block.signature === 'string' ? { signature: block.signature } : {}),
|
|
526
|
+
...(typeof block.data === 'string' ? { encrypted: block.data } : {}),
|
|
527
|
+
vendor: { anthropic: { blockType: block.type } },
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
output.push({ type: 'message', role: 'assistant', content: [partFromWire(block)] });
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const reason = body.stop_reason === 'tool_use' ? 'tool_calls'
|
|
535
|
+
: body.stop_reason === 'max_tokens' ? 'length'
|
|
536
|
+
: body.stop_reason === 'refusal' ? 'content_filter' : 'stop';
|
|
537
|
+
return {
|
|
538
|
+
...(typeof body.id === 'string' ? { id: body.id } : {}),
|
|
539
|
+
...(typeof body.model === 'string' ? { model: body.model } : {}),
|
|
540
|
+
status: reason === 'length' || reason === 'content_filter' ? 'incomplete' : 'completed',
|
|
541
|
+
reason,
|
|
542
|
+
output,
|
|
543
|
+
usage: usageFromWire(body.usage),
|
|
544
|
+
vendor: { anthropic: { stopReason: body.stop_reason ?? null, stopSequence: body.stop_sequence ?? null } },
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
function stopReasonOf(response) {
|
|
548
|
+
const native = response.vendor?.anthropic?.stopReason;
|
|
549
|
+
if (typeof native === 'string')
|
|
550
|
+
return native;
|
|
551
|
+
if (response.reason === 'tool_calls' || response.output.some((item) => item.type === 'tool_call'))
|
|
552
|
+
return 'tool_use';
|
|
553
|
+
if (response.reason === 'length')
|
|
554
|
+
return 'max_tokens';
|
|
555
|
+
if (response.reason === 'content_filter')
|
|
556
|
+
return 'refusal';
|
|
557
|
+
return 'end_turn';
|
|
558
|
+
}
|
|
559
|
+
function usageToAnthropic(usage, opening = false) {
|
|
560
|
+
const cached = usage.cachedInputTokens ?? 0;
|
|
561
|
+
const written = usage.cacheWriteTokens ?? 0;
|
|
562
|
+
return {
|
|
563
|
+
input_tokens: Math.max(0, usage.inputTokens - cached - written),
|
|
564
|
+
output_tokens: opening ? 0 : usage.outputTokens,
|
|
565
|
+
...(usage.cachedInputTokens !== undefined ? { cache_read_input_tokens: usage.cachedInputTokens } : {}),
|
|
566
|
+
...(usage.cacheWriteTokens !== undefined ? { cache_creation_input_tokens: usage.cacheWriteTokens } : {}),
|
|
567
|
+
...((usage.cacheWrite5mTokens !== undefined || usage.cacheWrite1hTokens !== undefined)
|
|
568
|
+
? {
|
|
569
|
+
cache_creation: {
|
|
570
|
+
...(usage.cacheWrite5mTokens !== undefined ? { ephemeral_5m_input_tokens: usage.cacheWrite5mTokens } : {}),
|
|
571
|
+
...(usage.cacheWrite1hTokens !== undefined ? { ephemeral_1h_input_tokens: usage.cacheWrite1hTokens } : {}),
|
|
572
|
+
},
|
|
573
|
+
}
|
|
574
|
+
: {}),
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
function toolArgumentsToWire(raw) {
|
|
578
|
+
try {
|
|
579
|
+
const parsed = JSON.parse(raw || '{}');
|
|
580
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
581
|
+
fail('tool_arguments', 'Anthropic tool_use input must be a JSON object.');
|
|
582
|
+
}
|
|
583
|
+
return parsed;
|
|
584
|
+
}
|
|
585
|
+
catch (err) {
|
|
586
|
+
if (err instanceof IrUnsupportedError)
|
|
587
|
+
throw err;
|
|
588
|
+
fail('tool_arguments', 'Cannot emit malformed tool-call arguments as an Anthropic tool_use block.');
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/** Canonical IR → Anthropic Messages JSON, without a Chat response projection. */
|
|
592
|
+
export function canonicalToAnthropicResponse(response, model) {
|
|
593
|
+
assertCanonicalResponseSupported(response, PROTOCOL);
|
|
594
|
+
const content = [];
|
|
595
|
+
for (const item of response.output) {
|
|
596
|
+
if (item.type === 'message') {
|
|
597
|
+
for (const part of item.content)
|
|
598
|
+
content.push(partToWire(part, true));
|
|
599
|
+
}
|
|
600
|
+
else if (item.type === 'reasoning') {
|
|
601
|
+
content.push(reasoningToWire(item));
|
|
602
|
+
}
|
|
603
|
+
else if (item.type === 'tool_call') {
|
|
604
|
+
content.push({
|
|
605
|
+
type: 'tool_use',
|
|
606
|
+
id: item.callId ?? item.id,
|
|
607
|
+
name: item.name,
|
|
608
|
+
input: toolArgumentsToWire(item.arguments),
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
else if (item.protocol === PROTOCOL) {
|
|
612
|
+
content.push(record(item.payload));
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
fail('output_item', `Cannot convert ${item.protocol} output to Anthropic.`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
if (content.length === 0)
|
|
619
|
+
content.push({ type: 'text', text: '' });
|
|
620
|
+
return {
|
|
621
|
+
id: response.id ?? `msg_${crypto.randomBytes(12).toString('hex')}`,
|
|
622
|
+
type: 'message',
|
|
623
|
+
role: 'assistant',
|
|
624
|
+
model,
|
|
625
|
+
content,
|
|
626
|
+
stop_reason: stopReasonOf(response),
|
|
627
|
+
stop_sequence: response.vendor?.anthropic?.stopSequence ?? null,
|
|
628
|
+
usage: usageToAnthropic(response.usage),
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
/** Stateful IR-event → Anthropic SSE payload encoder for one client turn. */
|
|
632
|
+
export class AnthropicEventEncoder {
|
|
633
|
+
id = `msg_${crypto.randomBytes(12).toString('hex')}`;
|
|
634
|
+
model = '';
|
|
635
|
+
usage = { inputTokens: 0, outputTokens: 0 };
|
|
636
|
+
started = false;
|
|
637
|
+
terminal = false;
|
|
638
|
+
sawToolCall = false;
|
|
639
|
+
nextBlock = 0;
|
|
640
|
+
blocks = new Map();
|
|
641
|
+
encode(event, model, finalResponse) {
|
|
642
|
+
assertCanonicalStreamEventSupported(event, PROTOCOL);
|
|
643
|
+
if ((event.candidateIndex ?? 0) !== 0)
|
|
644
|
+
return [];
|
|
645
|
+
if (event.type === 'response.created') {
|
|
646
|
+
this.id = event.id ?? this.id;
|
|
647
|
+
this.model = model;
|
|
648
|
+
if (finalResponse)
|
|
649
|
+
this.usage = finalResponse.usage;
|
|
650
|
+
return this.start();
|
|
651
|
+
}
|
|
652
|
+
if (event.type === 'response.usage') {
|
|
653
|
+
this.usage = event.usage;
|
|
654
|
+
return [];
|
|
655
|
+
}
|
|
656
|
+
if (event.type === 'response.output_item.added') {
|
|
657
|
+
const opening = this.start();
|
|
658
|
+
if (event.item.type === 'tool_call') {
|
|
659
|
+
this.sawToolCall = true;
|
|
660
|
+
const block = this.blockFor(`item:${event.index}`, {
|
|
661
|
+
type: 'tool_use', id: event.item.callId ?? event.item.id, name: event.item.name, input: {},
|
|
662
|
+
});
|
|
663
|
+
opening.push(block);
|
|
664
|
+
}
|
|
665
|
+
else if (event.item.type === 'reasoning') {
|
|
666
|
+
opening.push(this.blockFor(`item:${event.index}`, reasoningStart(event.item)));
|
|
667
|
+
}
|
|
668
|
+
else if (event.item.type === 'extension') {
|
|
669
|
+
fail('output_item', `Cannot convert ${event.item.protocol} output to an Anthropic stream.`);
|
|
670
|
+
}
|
|
671
|
+
return opening;
|
|
672
|
+
}
|
|
673
|
+
if (event.type === 'response.content_part.added') {
|
|
674
|
+
const opening = this.start();
|
|
675
|
+
const part = event.part.type === 'text' ? { type: 'text', text: '' } : partToWire(event.part, true);
|
|
676
|
+
opening.push(this.blockFor(`part:${event.index}:${event.partIndex}`, part));
|
|
677
|
+
return opening;
|
|
678
|
+
}
|
|
679
|
+
if (event.type === 'response.output_text.delta') {
|
|
680
|
+
return [...this.start(), {
|
|
681
|
+
type: 'content_block_delta', index: this.blockIndex(`part:${event.index}:${event.partIndex}`),
|
|
682
|
+
delta: { type: 'text_delta', text: event.text },
|
|
683
|
+
}];
|
|
684
|
+
}
|
|
685
|
+
if (event.type === 'response.output_text.annotation.added') {
|
|
686
|
+
if (event.annotation.type !== 'extension' || event.annotation.protocol !== PROTOCOL) {
|
|
687
|
+
fail('annotation', 'Anthropic streams require carrier-native citation payloads.');
|
|
688
|
+
}
|
|
689
|
+
return [...this.start(), {
|
|
690
|
+
type: 'content_block_delta', index: this.blockIndex(`part:${event.index}:${event.partIndex}`),
|
|
691
|
+
delta: { type: 'citations_delta', citation: event.annotation.payload },
|
|
692
|
+
}];
|
|
693
|
+
}
|
|
694
|
+
if (event.type === 'response.reasoning.delta') {
|
|
695
|
+
return [...this.start(), {
|
|
696
|
+
type: 'content_block_delta', index: this.blockIndex(`item:${event.index}`),
|
|
697
|
+
delta: { type: 'thinking_delta', thinking: event.text },
|
|
698
|
+
}];
|
|
699
|
+
}
|
|
700
|
+
if (event.type === 'response.function_call.arguments.delta') {
|
|
701
|
+
return [...this.start(), {
|
|
702
|
+
type: 'content_block_delta', index: this.blockIndex(`item:${event.index}`),
|
|
703
|
+
delta: { type: 'input_json_delta', partial_json: event.argumentsDelta },
|
|
704
|
+
}];
|
|
705
|
+
}
|
|
706
|
+
if (event.type === 'response.content_part.done') {
|
|
707
|
+
return this.stopBlock(`part:${event.index}:${event.partIndex}`);
|
|
708
|
+
}
|
|
709
|
+
if (event.type === 'response.output_item.done') {
|
|
710
|
+
if (event.item.type === 'reasoning' && event.item.signature) {
|
|
711
|
+
const index = this.blockIndex(`item:${event.index}`);
|
|
712
|
+
return [
|
|
713
|
+
{ type: 'content_block_delta', index, delta: { type: 'signature_delta', signature: event.item.signature } },
|
|
714
|
+
...this.stopBlock(`item:${event.index}`),
|
|
715
|
+
];
|
|
716
|
+
}
|
|
717
|
+
return this.stopBlock(`item:${event.index}`);
|
|
718
|
+
}
|
|
719
|
+
if (event.type === 'response.completed' || event.type === 'response.incomplete' || event.type === 'response.failed') {
|
|
720
|
+
if (this.terminal)
|
|
721
|
+
return [];
|
|
722
|
+
this.terminal = true;
|
|
723
|
+
const reason = event.type === 'response.completed' ? undefined : event.reason;
|
|
724
|
+
const effectiveReason = reason ?? (this.sawToolCall ? 'tool_calls' : undefined);
|
|
725
|
+
const response = finalResponse ?? {
|
|
726
|
+
id: this.id, model: this.model || model, status: event.type === 'response.completed' ? 'completed'
|
|
727
|
+
: event.type === 'response.incomplete' ? 'incomplete' : 'failed',
|
|
728
|
+
...(effectiveReason ? { reason: effectiveReason } : {}), output: [], usage: this.usage,
|
|
729
|
+
};
|
|
730
|
+
if (event.type === 'response.failed') {
|
|
731
|
+
return [{
|
|
732
|
+
type: 'error',
|
|
733
|
+
error: { type: 'api_error', message: response.error?.message ?? response.reason ?? 'Upstream stream failed.' },
|
|
734
|
+
}];
|
|
735
|
+
}
|
|
736
|
+
return [
|
|
737
|
+
...this.start(),
|
|
738
|
+
{
|
|
739
|
+
type: 'message_delta',
|
|
740
|
+
delta: { stop_reason: stopReasonOf(response), stop_sequence: response.vendor?.anthropic?.stopSequence ?? null },
|
|
741
|
+
usage: usageToAnthropic(response.usage),
|
|
742
|
+
},
|
|
743
|
+
{ type: 'message_stop' },
|
|
744
|
+
];
|
|
745
|
+
}
|
|
746
|
+
if (event.type === 'error') {
|
|
747
|
+
return [{ type: 'error', error: { type: 'api_error', message: event.message } }];
|
|
748
|
+
}
|
|
749
|
+
return [];
|
|
750
|
+
}
|
|
751
|
+
start() {
|
|
752
|
+
if (this.started)
|
|
753
|
+
return [];
|
|
754
|
+
this.started = true;
|
|
755
|
+
return [{
|
|
756
|
+
type: 'message_start',
|
|
757
|
+
message: {
|
|
758
|
+
id: this.id, type: 'message', role: 'assistant', model: this.model,
|
|
759
|
+
content: [], stop_reason: null, stop_sequence: null, usage: usageToAnthropic(this.usage, true),
|
|
760
|
+
},
|
|
761
|
+
}];
|
|
762
|
+
}
|
|
763
|
+
blockFor(key, content) {
|
|
764
|
+
const index = this.nextBlock++;
|
|
765
|
+
this.blocks.set(key, index);
|
|
766
|
+
return { type: 'content_block_start', index, content_block: content };
|
|
767
|
+
}
|
|
768
|
+
blockIndex(key) {
|
|
769
|
+
const index = this.blocks.get(key);
|
|
770
|
+
if (index === undefined)
|
|
771
|
+
fail('stream_lifecycle', `Anthropic stream delta references an unopened block (${key}).`);
|
|
772
|
+
return index;
|
|
773
|
+
}
|
|
774
|
+
stopBlock(key) {
|
|
775
|
+
const index = this.blocks.get(key);
|
|
776
|
+
if (index === undefined)
|
|
777
|
+
return [];
|
|
778
|
+
this.blocks.delete(key);
|
|
779
|
+
return [{ type: 'content_block_stop', index }];
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
function reasoningStart(item) {
|
|
783
|
+
const redacted = item.vendor?.anthropic?.blockType === 'redacted_thinking' || (!item.text && item.encrypted);
|
|
784
|
+
return redacted
|
|
785
|
+
? { type: 'redacted_thinking', data: item.encrypted ?? '' }
|
|
786
|
+
: { type: 'thinking', thinking: '', ...(item.signature ? { signature: item.signature } : {}) };
|
|
787
|
+
}
|
|
788
|
+
export { usageFromWire as anthropicUsageFromWire };
|