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.
Files changed (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -0,0 +1,242 @@
1
+ import crypto from 'node:crypto';
2
+ import { IrUpstreamError } from '../errors.js';
3
+ import { googleUsageFromWire } from './google.js';
4
+ function record(value) {
5
+ return value && typeof value === 'object' ? value : {};
6
+ }
7
+ function invalid(message) {
8
+ throw new IrUpstreamError(`Invalid Gemini stream: ${message}`);
9
+ }
10
+ /** Gemini streamGenerateContent chunks → canonical item lifecycle events. */
11
+ export class GoogleStreamDecoder {
12
+ candidates = new Map();
13
+ id = `google-${Date.now()}-${crypto.randomBytes(6).toString('hex')}`;
14
+ createdAt = Math.floor(Date.now() / 1000);
15
+ createdSent = false;
16
+ nativeTerminal = false;
17
+ terminalSent = false;
18
+ blockedReason;
19
+ get terminated() {
20
+ if (this.nativeTerminal)
21
+ return true;
22
+ return this.candidates.size > 0 && [...this.candidates.values()].every((candidate) => candidate.finishReason !== undefined);
23
+ }
24
+ push(raw) {
25
+ const body = record(raw);
26
+ const events = [];
27
+ this.ensureCreated(body, events);
28
+ if (body.usageMetadata) {
29
+ const usage = googleUsageFromWire(body.usageMetadata);
30
+ events.push({ type: 'response.usage', usage });
31
+ }
32
+ if (body.error) {
33
+ this.nativeTerminal = true;
34
+ this.terminalSent = true;
35
+ const error = record(body.error);
36
+ events.push({ type: 'error', code: error.status ?? error.code, message: String(error.message ?? 'Gemini stream failed.') });
37
+ return events;
38
+ }
39
+ const feedback = record(body.promptFeedback);
40
+ if (feedback.blockReason) {
41
+ this.blockedReason = String(feedback.blockReason);
42
+ this.nativeTerminal = true;
43
+ this.terminalSent = true;
44
+ events.push({ type: 'response.incomplete', reason: 'content_filter' });
45
+ return events;
46
+ }
47
+ const candidates = Array.isArray(body.candidates) ? body.candidates : [];
48
+ candidates.forEach((rawCandidate, position) => {
49
+ const candidate = record(rawCandidate);
50
+ const candidateIndex = typeof candidate.index === 'number' ? candidate.index : position;
51
+ const state = this.state(candidateIndex);
52
+ if (state.finishReason !== undefined)
53
+ invalid(`candidate ${candidateIndex} continued after finishReason.`);
54
+ const seenKinds = new Set();
55
+ const parts = Array.isArray(record(candidate.content).parts) ? record(candidate.content).parts : [];
56
+ for (const rawPart of parts) {
57
+ const part = record(rawPart);
58
+ if (typeof part.text === 'string') {
59
+ const kind = part.thought === true ? 'reasoning' : 'text';
60
+ if (state.active?.kind !== kind || seenKinds.has(kind))
61
+ events.push(...this.closeActive(candidateIndex, state));
62
+ seenKinds.add(kind);
63
+ if (kind === 'reasoning')
64
+ this.reasoningDelta(candidateIndex, state, part, events);
65
+ else
66
+ this.textDelta(candidateIndex, state, part, events);
67
+ continue;
68
+ }
69
+ events.push(...this.closeActive(candidateIndex, state));
70
+ if (part.functionCall) {
71
+ const call = record(part.functionCall);
72
+ const itemIndex = state.nextItem++;
73
+ const generatedId = `${this.id}:call:${candidateIndex}:${itemIndex}`;
74
+ const id = typeof call.id === 'string' && call.id ? call.id : generatedId;
75
+ const item = {
76
+ type: 'tool_call', id, callId: id,
77
+ name: String(call.name ?? ''), arguments: JSON.stringify(call.args ?? {}),
78
+ ...(typeof part.thoughtSignature === 'string' ? { signature: part.thoughtSignature } : {}),
79
+ };
80
+ events.push({ type: 'response.output_item.added', candidateIndex, index: itemIndex, item }, { type: 'response.function_call.arguments.delta', candidateIndex, index: itemIndex, argumentsDelta: item.arguments }, { type: 'response.function_call.arguments.done', candidateIndex, index: itemIndex, arguments: item.arguments }, { type: 'response.output_item.done', candidateIndex, index: itemIndex, item });
81
+ continue;
82
+ }
83
+ const inline = record(part.inlineData);
84
+ if (typeof inline.data === 'string') {
85
+ const mediaType = typeof inline.mimeType === 'string' ? inline.mimeType : 'application/octet-stream';
86
+ const kind = mediaType.startsWith('image/') ? 'image' : mediaType.startsWith('audio/') ? 'audio' : 'file';
87
+ const content = {
88
+ type: kind,
89
+ source: { kind: 'base64', mediaType, data: inline.data },
90
+ ...(typeof part.thoughtSignature === 'string' ? { signature: part.thoughtSignature } : {}),
91
+ };
92
+ this.completeMessagePart(candidateIndex, state, content, events);
93
+ continue;
94
+ }
95
+ const item = { type: 'extension', protocol: 'google', payload: rawPart };
96
+ const itemIndex = state.nextItem++;
97
+ events.push({ type: 'response.output_item.added', candidateIndex, index: itemIndex, item }, { type: 'response.output_item.done', candidateIndex, index: itemIndex, item });
98
+ }
99
+ if (candidate.groundingMetadata !== undefined || candidate.logprobsResult !== undefined) {
100
+ state.metadata = {
101
+ type: 'candidate_metadata',
102
+ ...(candidate.groundingMetadata !== undefined ? { groundingMetadata: candidate.groundingMetadata } : {}),
103
+ ...(candidate.logprobsResult !== undefined ? { logprobsResult: candidate.logprobsResult } : {}),
104
+ };
105
+ }
106
+ if (typeof candidate.finishReason === 'string') {
107
+ events.push(...this.closeActive(candidateIndex, state));
108
+ events.push(...this.emitMetadata(candidateIndex, state));
109
+ state.finishReason = candidate.finishReason;
110
+ }
111
+ });
112
+ return events;
113
+ }
114
+ finish() {
115
+ if (this.terminalSent)
116
+ return [];
117
+ this.terminalSent = true;
118
+ if (this.blockedReason)
119
+ return [{ type: 'response.incomplete', reason: 'content_filter' }];
120
+ const events = [];
121
+ for (const [candidateIndex, state] of [...this.candidates.entries()].sort(([a], [b]) => a - b)) {
122
+ events.push(...this.closeActive(candidateIndex, state));
123
+ events.push(...this.emitMetadata(candidateIndex, state));
124
+ }
125
+ const primary = this.candidates.get(0) ?? [...this.candidates.entries()].sort(([a], [b]) => a - b)[0]?.[1];
126
+ const reason = this.reason(primary?.finishReason);
127
+ events.push(reason === 'length' || reason === 'content_filter'
128
+ ? { type: 'response.incomplete', reason }
129
+ : { type: 'response.completed' });
130
+ return events;
131
+ }
132
+ textDelta(candidateIndex, state, part, events) {
133
+ let active = state.active;
134
+ if (active?.kind !== 'text') {
135
+ const itemIndex = state.nextItem++;
136
+ const content = { type: 'text', text: '' };
137
+ const item = {
138
+ type: 'message', id: `${this.id}:item:${candidateIndex}:${itemIndex}`,
139
+ role: 'assistant', content: [content],
140
+ };
141
+ active = { kind: 'text', itemIndex, item, part: content };
142
+ state.active = active;
143
+ events.push({ type: 'response.output_item.added', candidateIndex, index: itemIndex, item }, { type: 'response.content_part.added', candidateIndex, index: itemIndex, partIndex: 0, part: content });
144
+ }
145
+ const content = active.part;
146
+ content.text += part.text;
147
+ if (typeof part.thoughtSignature === 'string')
148
+ content.signature = part.thoughtSignature;
149
+ if (part.text) {
150
+ events.push({
151
+ type: 'response.output_text.delta', candidateIndex, index: active.itemIndex, partIndex: 0, text: part.text,
152
+ });
153
+ }
154
+ }
155
+ reasoningDelta(candidateIndex, state, part, events) {
156
+ let active = state.active;
157
+ if (active?.kind !== 'reasoning') {
158
+ const itemIndex = state.nextItem++;
159
+ const item = { type: 'reasoning', id: `${this.id}:reasoning:${candidateIndex}:${itemIndex}`, text: '' };
160
+ active = { kind: 'reasoning', itemIndex, item };
161
+ state.active = active;
162
+ events.push({ type: 'response.output_item.added', candidateIndex, index: itemIndex, item });
163
+ }
164
+ if (active.item.type !== 'reasoning')
165
+ invalid('internal reasoning item mismatch.');
166
+ active.item.text = (active.item.text ?? '') + part.text;
167
+ if (typeof part.thoughtSignature === 'string')
168
+ active.item.signature = part.thoughtSignature;
169
+ if (part.text) {
170
+ events.push({ type: 'response.reasoning.delta', candidateIndex, index: active.itemIndex, text: part.text });
171
+ }
172
+ }
173
+ completeMessagePart(candidateIndex, state, part, events) {
174
+ const itemIndex = state.nextItem++;
175
+ const item = {
176
+ type: 'message', id: `${this.id}:item:${candidateIndex}:${itemIndex}`,
177
+ role: 'assistant', content: [part],
178
+ };
179
+ events.push({ type: 'response.output_item.added', candidateIndex, index: itemIndex, item }, { type: 'response.content_part.added', candidateIndex, index: itemIndex, partIndex: 0, part }, { type: 'response.content_part.done', candidateIndex, index: itemIndex, partIndex: 0, part }, { type: 'response.output_item.done', candidateIndex, index: itemIndex, item });
180
+ }
181
+ closeActive(candidateIndex, state) {
182
+ const active = state.active;
183
+ if (!active)
184
+ return [];
185
+ state.active = undefined;
186
+ const index = active.itemIndex;
187
+ if (active.kind === 'reasoning' && active.item.type === 'reasoning') {
188
+ return [
189
+ { type: 'response.reasoning.done', candidateIndex, index, text: active.item.text ?? '' },
190
+ { type: 'response.output_item.done', candidateIndex, index, item: active.item },
191
+ ];
192
+ }
193
+ if (active.kind === 'text' && active.part) {
194
+ return [
195
+ {
196
+ type: 'response.output_text.done', candidateIndex, index, partIndex: 0, text: active.part.text,
197
+ ...(active.part.annotations ? { annotations: active.part.annotations } : {}),
198
+ },
199
+ { type: 'response.content_part.done', candidateIndex, index, partIndex: 0, part: active.part },
200
+ { type: 'response.output_item.done', candidateIndex, index, item: active.item },
201
+ ];
202
+ }
203
+ return [];
204
+ }
205
+ emitMetadata(candidateIndex, state) {
206
+ if (!state.metadata)
207
+ return [];
208
+ const item = { type: 'extension', protocol: 'google', payload: state.metadata };
209
+ state.metadata = undefined;
210
+ const index = state.nextItem++;
211
+ return [
212
+ { type: 'response.output_item.added', candidateIndex, index, item },
213
+ { type: 'response.output_item.done', candidateIndex, index, item },
214
+ ];
215
+ }
216
+ ensureCreated(body, events) {
217
+ if (this.createdSent)
218
+ return;
219
+ this.createdSent = true;
220
+ events.push({
221
+ type: 'response.created',
222
+ id: typeof body.responseId === 'string' ? body.responseId : this.id,
223
+ ...(typeof body.modelVersion === 'string' ? { model: body.modelVersion } : {}),
224
+ createdAt: this.createdAt,
225
+ });
226
+ }
227
+ state(index) {
228
+ let state = this.candidates.get(index);
229
+ if (!state) {
230
+ state = { nextItem: 0 };
231
+ this.candidates.set(index, state);
232
+ }
233
+ return state;
234
+ }
235
+ reason(finishReason) {
236
+ if (finishReason === 'MAX_TOKENS')
237
+ return 'length';
238
+ if (finishReason === 'SAFETY' || finishReason === 'RECITATION' || finishReason === 'PROHIBITED_CONTENT')
239
+ return 'content_filter';
240
+ return 'stop';
241
+ }
242
+ }
@@ -0,0 +1,9 @@
1
+ import type { ModelRegistration } from '../../config/types.js';
2
+ import type { CanonicalRequest, CanonicalResponse, Usage } from '../types.js';
3
+ type Wire = Record<string, any>;
4
+ /** Canonical IR → Gemini generateContent request. */
5
+ export declare function canonicalToGooglePayload(ir: CanonicalRequest, model: ModelRegistration): Wire;
6
+ declare function usageFromWire(raw: unknown): Usage;
7
+ /** Gemini generateContent response → Canonical IR. All candidates are retained. */
8
+ export declare function googleResponseToIR(data: unknown): CanonicalResponse;
9
+ export { usageFromWire as googleUsageFromWire };
@@ -0,0 +1,317 @@
1
+ import crypto from 'node:crypto';
2
+ import { IrUnsupportedError } from '../errors.js';
3
+ import { assertCanonicalRequestSupported } from '../validate.js';
4
+ const PROTOCOL = 'google';
5
+ const EFFORT_TO_BUDGET = {
6
+ none: 0,
7
+ minimal: 512,
8
+ low: 1024,
9
+ medium: 4096,
10
+ high: 16384,
11
+ xhigh: 32768,
12
+ max: 65536,
13
+ };
14
+ function record(value) {
15
+ return value && typeof value === 'object' ? value : {};
16
+ }
17
+ function fail(code, message) {
18
+ throw new IrUnsupportedError(code, message, PROTOCOL);
19
+ }
20
+ function parseObject(raw) {
21
+ if (raw && typeof raw === 'object' && !Array.isArray(raw))
22
+ return raw;
23
+ if (typeof raw !== 'string' || !raw.trim())
24
+ return {};
25
+ try {
26
+ const value = JSON.parse(raw);
27
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : { result: value };
28
+ }
29
+ catch {
30
+ return { result: raw };
31
+ }
32
+ }
33
+ function parseToolArguments(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 functionCall contract.
45
+ }
46
+ return fail('tool_arguments', 'Gemini functionCall args require a JSON object string.');
47
+ }
48
+ function wrapToolResponse(raw) {
49
+ const parsed = parseObject(raw);
50
+ return Object.keys(parsed).length ? parsed : { result: 'ok' };
51
+ }
52
+ function sourceToWire(part) {
53
+ if (part.source.kind === 'base64') {
54
+ return { inlineData: { mimeType: part.source.mediaType, data: part.source.data } };
55
+ }
56
+ if (part.source.kind === 'url') {
57
+ return { fileData: { fileUri: part.source.url } };
58
+ }
59
+ return { fileData: { fileUri: part.source.fileId } };
60
+ }
61
+ function partToWire(part) {
62
+ if (part.type === 'extension') {
63
+ if (part.protocol !== PROTOCOL)
64
+ fail('content_part', `Cannot convert ${part.protocol} content.`);
65
+ return record(part.payload);
66
+ }
67
+ if (part.type === 'text') {
68
+ return { text: part.text, ...(part.signature ? { thoughtSignature: part.signature } : {}) };
69
+ }
70
+ if (part.type === 'image' || part.type === 'file' || part.type === 'audio') {
71
+ return { ...sourceToWire(part), ...(part.signature ? { thoughtSignature: part.signature } : {}) };
72
+ }
73
+ fail('content_part', `Gemini cannot carry ${part.type} content.`);
74
+ }
75
+ function partFromWire(raw) {
76
+ const value = record(raw);
77
+ if (value.functionCall) {
78
+ const call = record(value.functionCall);
79
+ const id = `call_${crypto.randomBytes(8).toString('hex')}`;
80
+ return {
81
+ call: {
82
+ type: 'tool_call', id, callId: id,
83
+ name: String(call.name ?? ''), arguments: JSON.stringify(call.args ?? {}),
84
+ ...(typeof value.thoughtSignature === 'string' ? { signature: value.thoughtSignature } : {}),
85
+ },
86
+ };
87
+ }
88
+ if (typeof value.text === 'string') {
89
+ if (value.thought === true)
90
+ return { reasoning: value.text };
91
+ return {
92
+ part: {
93
+ type: 'text', text: value.text,
94
+ ...(typeof value.thoughtSignature === 'string' ? { signature: value.thoughtSignature } : {}),
95
+ },
96
+ };
97
+ }
98
+ const inline = record(value.inlineData);
99
+ if (typeof inline.data === 'string') {
100
+ const mediaType = typeof inline.mimeType === 'string' ? inline.mimeType : 'application/octet-stream';
101
+ const kind = mediaType.startsWith('image/') ? 'image' : mediaType.startsWith('audio/') ? 'audio' : 'file';
102
+ return {
103
+ part: {
104
+ type: kind,
105
+ source: { kind: 'base64', mediaType, data: inline.data },
106
+ ...(typeof value.thoughtSignature === 'string' ? { signature: value.thoughtSignature } : {}),
107
+ },
108
+ };
109
+ }
110
+ return { part: { type: 'extension', protocol: PROTOCOL, payload: raw } };
111
+ }
112
+ /** Canonical IR → Gemini generateContent request. */
113
+ export function canonicalToGooglePayload(ir, model) {
114
+ assertCanonicalRequestSupported(ir, PROTOCOL);
115
+ const nameByCall = new Map();
116
+ for (const item of ir.input)
117
+ if (item.type === 'tool_call')
118
+ nameByCall.set(item.callId ?? item.id, item.name);
119
+ const contents = [];
120
+ let pendingRole;
121
+ let pendingParts = [];
122
+ const flush = () => {
123
+ if (!pendingRole || !pendingParts.length) {
124
+ pendingRole = undefined;
125
+ pendingParts = [];
126
+ return;
127
+ }
128
+ contents.push({ role: pendingRole, parts: pendingParts });
129
+ pendingRole = undefined;
130
+ pendingParts = [];
131
+ };
132
+ const append = (role, parts) => {
133
+ if (!parts.length)
134
+ return;
135
+ if (pendingRole !== role)
136
+ flush();
137
+ pendingRole = role;
138
+ pendingParts.push(...parts);
139
+ };
140
+ for (const item of ir.input) {
141
+ if (item.type === 'message') {
142
+ if (item.role === 'system' || item.role === 'developer')
143
+ continue;
144
+ append(item.role === 'assistant' ? 'model' : 'user', item.content.map(partToWire));
145
+ }
146
+ else if (item.type === 'reasoning') {
147
+ if (item.signature || item.encrypted)
148
+ fail('reasoning_signature', 'Gemini reasoning replay requires carrier-native thought parts.');
149
+ if (item.text)
150
+ append('model', [{ text: item.text, thought: true }]);
151
+ }
152
+ else if (item.type === 'tool_call') {
153
+ append('model', [{
154
+ functionCall: { name: item.name, args: parseToolArguments(item.arguments) },
155
+ ...(item.signature ? { thoughtSignature: item.signature } : {}),
156
+ }]);
157
+ }
158
+ else if (item.type === 'tool_result') {
159
+ if (!item.content.every((part) => part.type === 'text')) {
160
+ fail('tool_result_content', 'Gemini functionResponse carries textual structured results only.');
161
+ }
162
+ const name = nameByCall.get(item.callId);
163
+ if (!name)
164
+ fail('tool_call_pairing', `No Gemini function call found for tool result "${item.callId}".`);
165
+ append('user', [{
166
+ functionResponse: {
167
+ name,
168
+ response: wrapToolResponse(item.content.map((part) => part.type === 'text' ? part.text : '').join('\n')),
169
+ },
170
+ }]);
171
+ }
172
+ else {
173
+ fail('input_item', 'Gemini cannot resolve item references or foreign extension items.');
174
+ }
175
+ }
176
+ flush();
177
+ const systemText = [ir.instructions, ...ir.input.flatMap((item) => item.type === 'message' && (item.role === 'system' || item.role === 'developer')
178
+ ? [item.content.map((part) => part.type === 'text' ? part.text : fail('system_part', 'Gemini system instructions carry text only.')).join('')]
179
+ : [])].filter(Boolean).join('\n\n');
180
+ const generation = {};
181
+ const params = ir.generation;
182
+ if (params?.maxOutputTokens !== undefined)
183
+ generation.maxOutputTokens = params.maxOutputTokens;
184
+ if (params?.temperature !== undefined && model.temperature !== false)
185
+ generation.temperature = params.temperature;
186
+ if (params?.topP !== undefined)
187
+ generation.topP = params.topP;
188
+ if (params?.topK !== undefined)
189
+ generation.topK = params.topK;
190
+ if (params?.stop?.length)
191
+ generation.stopSequences = params.stop;
192
+ if (params?.seed !== undefined)
193
+ generation.seed = params.seed;
194
+ if (params?.presencePenalty !== undefined)
195
+ generation.presencePenalty = params.presencePenalty;
196
+ if (params?.frequencyPenalty !== undefined)
197
+ generation.frequencyPenalty = params.frequencyPenalty;
198
+ if (ir.n !== undefined)
199
+ generation.candidateCount = ir.n;
200
+ if (ir.text?.format?.type === 'json_object')
201
+ generation.responseMimeType = 'application/json';
202
+ if (ir.text?.format?.type === 'json_schema') {
203
+ generation.responseMimeType = 'application/json';
204
+ generation.responseSchema = ir.text.format.schema;
205
+ }
206
+ const effort = ir.reasoning?.effort;
207
+ if (ir.reasoning?.budgetTokens !== undefined && ir.reasoning.budgetTokens >= 0) {
208
+ generation.thinkingConfig = { thinkingBudget: ir.reasoning.budgetTokens, includeThoughts: true };
209
+ }
210
+ else if (effort && effort !== 'none') {
211
+ generation.thinkingConfig = { thinkingBudget: EFFORT_TO_BUDGET[effort], includeThoughts: true };
212
+ }
213
+ const declarations = ir.tools?.map((tool) => {
214
+ if (tool.type !== 'function')
215
+ fail('tool_type', `Gemini carries function declarations only, not ${tool.type}.`);
216
+ return {
217
+ name: tool.function.name,
218
+ ...(tool.function.description !== undefined ? { description: tool.function.description } : {}),
219
+ parameters: tool.function.parameters ?? { type: 'object', properties: {} },
220
+ };
221
+ });
222
+ const mode = ir.toolChoice?.type === 'none' ? 'NONE'
223
+ : ir.toolChoice?.type === 'required' || ir.toolChoice?.type === 'function' ? 'ANY'
224
+ : ir.toolChoice?.type === 'auto' ? 'AUTO' : undefined;
225
+ if (ir.toolChoice && !mode)
226
+ fail('tool_choice', `Gemini cannot express ${ir.toolChoice.type}.`);
227
+ return {
228
+ contents,
229
+ ...(systemText ? { systemInstruction: { parts: [{ text: systemText }] } } : {}),
230
+ ...(Object.keys(generation).length ? { generationConfig: generation } : {}),
231
+ ...(declarations?.length ? { tools: [{ functionDeclarations: declarations }] } : {}),
232
+ ...(mode ? {
233
+ toolConfig: {
234
+ functionCallingConfig: {
235
+ mode,
236
+ ...(ir.toolChoice?.type === 'function' ? { allowedFunctionNames: [ir.toolChoice.name] } : {}),
237
+ },
238
+ },
239
+ } : {}),
240
+ };
241
+ }
242
+ function audioTokens(raw) {
243
+ if (!Array.isArray(raw))
244
+ return undefined;
245
+ const total = raw.reduce((sum, entry) => {
246
+ const detail = record(entry);
247
+ return detail.modality === 'AUDIO' && typeof detail.tokenCount === 'number' ? sum + detail.tokenCount : sum;
248
+ }, 0);
249
+ return total > 0 ? total : undefined;
250
+ }
251
+ function usageFromWire(raw) {
252
+ const usage = record(raw);
253
+ const audioInputTokens = audioTokens(usage.promptTokensDetails);
254
+ const audioOutputTokens = audioTokens(usage.candidatesTokensDetails);
255
+ return {
256
+ inputTokens: usage.promptTokenCount ?? 0,
257
+ outputTokens: usage.candidatesTokenCount ?? 0,
258
+ ...(usage.totalTokenCount !== undefined ? { totalTokens: usage.totalTokenCount } : {}),
259
+ ...(usage.cachedContentTokenCount !== undefined ? { cachedInputTokens: usage.cachedContentTokenCount } : {}),
260
+ ...(usage.thoughtsTokenCount !== undefined ? { reasoningTokens: usage.thoughtsTokenCount } : {}),
261
+ ...(audioInputTokens !== undefined ? { audioInputTokens } : {}),
262
+ ...(audioOutputTokens !== undefined ? { audioOutputTokens } : {}),
263
+ };
264
+ }
265
+ /** Gemini generateContent response → Canonical IR. All candidates are retained. */
266
+ export function googleResponseToIR(data) {
267
+ const body = record(data);
268
+ const rawCandidates = Array.isArray(body.candidates) ? body.candidates : [];
269
+ if (!rawCandidates.length) {
270
+ const blocked = record(body.promptFeedback);
271
+ return {
272
+ status: 'incomplete', reason: 'content_filter', output: [], usage: usageFromWire(body.usageMetadata),
273
+ vendor: { google: { blockReason: blocked.blockReason ?? 'EMPTY_CANDIDATES' } },
274
+ };
275
+ }
276
+ const candidates = rawCandidates.map((raw, index) => {
277
+ const candidate = record(raw);
278
+ const output = [];
279
+ for (const rawPart of record(candidate.content).parts ?? []) {
280
+ const converted = partFromWire(rawPart);
281
+ if (converted.call)
282
+ output.push(converted.call);
283
+ if (converted.reasoning !== undefined)
284
+ output.push({ type: 'reasoning', text: converted.reasoning });
285
+ if (converted.part)
286
+ output.push({ type: 'message', role: 'assistant', content: [converted.part] });
287
+ }
288
+ const metadata = {
289
+ ...(candidate.groundingMetadata !== undefined ? { groundingMetadata: candidate.groundingMetadata } : {}),
290
+ ...(candidate.logprobsResult !== undefined ? { logprobsResult: candidate.logprobsResult } : {}),
291
+ };
292
+ if (Object.keys(metadata).length) {
293
+ output.push({ type: 'extension', protocol: PROTOCOL, payload: { type: 'candidate_metadata', ...metadata } });
294
+ }
295
+ const finish = candidate.finishReason;
296
+ const reason = output.some((item) => item.type === 'tool_call') ? 'tool_calls'
297
+ : finish === 'MAX_TOKENS' ? 'length'
298
+ : finish === 'SAFETY' || finish === 'RECITATION' ? 'content_filter' : 'stop';
299
+ return {
300
+ index: typeof candidate.index === 'number' ? candidate.index : index,
301
+ status: reason === 'length' || reason === 'content_filter' ? 'incomplete' : 'completed',
302
+ reason,
303
+ output,
304
+ };
305
+ });
306
+ const primary = candidates[0];
307
+ return {
308
+ id: `google-${Date.now()}`,
309
+ createdAt: Math.floor(Date.now() / 1000),
310
+ status: primary.status,
311
+ reason: primary.reason,
312
+ output: primary.output,
313
+ ...(candidates.length > 1 ? { candidates } : {}),
314
+ usage: usageFromWire(body.usageMetadata),
315
+ };
316
+ }
317
+ export { usageFromWire as googleUsageFromWire };
@@ -1,7 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { IrUnsupportedError } from '../errors.js';
3
3
  import { assertCanonicalResponseSupported, assertCanonicalStreamEventSupported } from '../validate.js';
4
- import { responsesPartToWire } from './openai-responses.js';
4
+ import { responsesPartToWire, responsesToolItemId } from './openai-responses.js';
5
5
  const PROTOCOL = 'openai-responses';
6
6
  function shortId(prefix) {
7
7
  return prefix + crypto.randomBytes(12).toString('hex');
@@ -71,7 +71,7 @@ function outputItemToWire(item, messageId) {
71
71
  const custom = item.vendor?.[PROTOCOL]?.itemType === 'custom_tool_call';
72
72
  return {
73
73
  type: custom ? 'custom_tool_call' : 'function_call',
74
- id: item.id || shortId(custom ? 'ctc_' : 'fc_'),
74
+ id: responsesToolItemId(item.id || shortId(custom ? 'ctc_' : 'fc_'), custom),
75
75
  call_id: item.callId ?? item.id,
76
76
  name: item.name,
77
77
  ...(custom ? { input: item.arguments } : { arguments: item.arguments }),
@@ -296,9 +296,12 @@ export class OpenAIResponsesEventEncoder {
296
296
  throw new IrUnsupportedError('stream_lifecycle', `Responses stream references unopened output item ${index}.`, PROTOCOL);
297
297
  }
298
298
  const sourceId = 'id' in item && typeof item.id === 'string' ? item.id : undefined;
299
- const id = sourceId ?? (item.type === 'message' && index === 0 ? this.messageId : undefined)
300
- ?? shortId(item.type === 'message' ? 'msg_' : item.type === 'reasoning' ? 'rs_'
301
- : item.type === 'tool_call' && item.vendor?.[PROTOCOL]?.itemType === 'custom_tool_call' ? 'ctc_' : 'fc_');
299
+ const custom = item.type === 'tool_call' && item.vendor?.[PROTOCOL]?.itemType === 'custom_tool_call';
300
+ const id = item.type === 'tool_call' && sourceId !== undefined
301
+ ? responsesToolItemId(sourceId, custom)
302
+ : sourceId ?? (item.type === 'message' && index === 0 ? this.messageId : undefined)
303
+ ?? shortId(item.type === 'message' ? 'msg_' : item.type === 'reasoning' ? 'rs_'
304
+ : custom ? 'ctc_' : 'fc_');
302
305
  this.itemIds.set(index, id);
303
306
  return id;
304
307
  }
@@ -4,6 +4,21 @@ declare function annotationFromWire(raw: unknown): Annotation;
4
4
  declare function partFromWire(raw: unknown): ContentPart;
5
5
  export declare function responsesPartToWire(part: ContentPart, role: 'user' | 'assistant'): Record<string, unknown>;
6
6
  export declare function responsesToolToWire(tool: ToolDef): Record<string, unknown>;
7
+ /**
8
+ * Responses tool items carry their own item `id`, distinct from the correlation
9
+ * `call_id`, and upstreams reject an id that does not begin with the item-type
10
+ * prefix (`Invalid 'input[2].id': Expected an ID that begins with 'fc'`).
11
+ * Carriers without item ids (chat, Anthropic, Gemini) put the tool-call id in
12
+ * both slots, so the Responses adapters derive one. Two invariants:
13
+ *
14
+ * - Deterministic: the same history MUST yield the same id on every turn, or
15
+ * the replayed prompt prefix turns over and the upstream prompt cache misses.
16
+ * - Injective: distinct tool-call ids MUST NOT collapse onto one item id. The
17
+ * chat client controls `tool_calls[].id`, so an id that is not safe both in
18
+ * charset and length is hashed instead of sanitized/truncated — dropping
19
+ * characters or a tail would silently merge two calls into one id.
20
+ */
21
+ export declare function responsesToolItemId(id: string, custom: boolean): string;
7
22
  /** Canonical IR → OpenAI Responses request. No request-object spreading. */
8
23
  export declare function canonicalToResponsesPayload(ir: CanonicalRequest, model: ModelRegistration, stream?: boolean): Record<string, any>;
9
24
  export declare function responsesInputToIR(raw: unknown): InputItem[];
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto';
1
2
  import { IrUnsupportedError } from '../errors.js';
2
3
  import { DATA_URL_RE } from '../media.js';
3
4
  import { assertCanonicalRequestSupported } from '../validate.js';
@@ -164,6 +165,28 @@ export function responsesToolToWire(tool) {
164
165
  }
165
166
  return { type: tool.kind, ...record(tool.config) };
166
167
  }
168
+ /**
169
+ * Responses tool items carry their own item `id`, distinct from the correlation
170
+ * `call_id`, and upstreams reject an id that does not begin with the item-type
171
+ * prefix (`Invalid 'input[2].id': Expected an ID that begins with 'fc'`).
172
+ * Carriers without item ids (chat, Anthropic, Gemini) put the tool-call id in
173
+ * both slots, so the Responses adapters derive one. Two invariants:
174
+ *
175
+ * - Deterministic: the same history MUST yield the same id on every turn, or
176
+ * the replayed prompt prefix turns over and the upstream prompt cache misses.
177
+ * - Injective: distinct tool-call ids MUST NOT collapse onto one item id. The
178
+ * chat client controls `tool_calls[].id`, so an id that is not safe both in
179
+ * charset and length is hashed instead of sanitized/truncated — dropping
180
+ * characters or a tail would silently merge two calls into one id.
181
+ */
182
+ export function responsesToolItemId(id, custom) {
183
+ const prefix = custom ? 'ctc_' : 'fc_';
184
+ if (id.startsWith(prefix))
185
+ return id;
186
+ if (/^[A-Za-z0-9_-]{1,48}$/.test(id))
187
+ return prefix + id;
188
+ return prefix + crypto.createHash('sha256').update(id).digest('hex').slice(0, 48);
189
+ }
167
190
  function itemToWire(item) {
168
191
  if (item.type === 'extension') {
169
192
  if (item.protocol !== PROTOCOL)
@@ -189,7 +212,9 @@ function itemToWire(item) {
189
212
  throw new IrUnsupportedError('tool_call_signature', 'Responses cannot replay a foreign tool-call signature.', PROTOCOL);
190
213
  const custom = item.vendor?.[PROTOCOL]?.itemType === 'custom_tool_call';
191
214
  return {
192
- type: custom ? 'custom_tool_call' : 'function_call', id: item.id, call_id: item.callId ?? item.id,
215
+ type: custom ? 'custom_tool_call' : 'function_call',
216
+ id: responsesToolItemId(item.id, custom),
217
+ call_id: item.callId ?? item.id,
193
218
  name: item.name,
194
219
  ...(custom ? { input: item.arguments } : { arguments: item.arguments }),
195
220
  ...(item.status ? { status: item.status } : {}),