omnicell-router 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/backend/dist/cli/clients/base.d.ts +13 -2
  2. package/backend/dist/cli/clients/claude.d.ts +2 -2
  3. package/backend/dist/cli/clients/codex.d.ts +2 -2
  4. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  5. package/backend/dist/cli/clients/core-adapters.js +3 -4
  6. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  7. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  8. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  9. package/backend/dist/cli/clients/grok.d.ts +2 -2
  10. package/backend/dist/cli/clients/index.d.ts +8 -1
  11. package/backend/dist/cli/clients/index.js +48 -20
  12. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  13. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  14. package/backend/dist/cli/clients/model-meta.js +1 -1
  15. package/backend/dist/cli/clients/omp.d.ts +2 -2
  16. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  17. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  18. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  19. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  20. package/backend/dist/cli/clients/pi.d.ts +2 -2
  21. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  22. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  23. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  24. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  25. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  26. package/backend/dist/cli/clients/reserved.js +2 -0
  27. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  28. package/backend/dist/cli/index.js +60 -9
  29. package/backend/dist/cli/types.d.ts +20 -8
  30. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  31. package/backend/dist/config/comments-en.js +6 -12
  32. package/backend/dist/config/comments-zh.js +6 -12
  33. package/backend/dist/config/defaults.d.ts +56 -1
  34. package/backend/dist/config/defaults.js +68 -0
  35. package/backend/dist/config/index.d.ts +9 -2
  36. package/backend/dist/config/index.js +26 -3
  37. package/backend/dist/config/types.d.ts +55 -43
  38. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  39. package/backend/dist/forward-proxy/egress.js +42 -4
  40. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  41. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  42. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  43. package/backend/dist/forward-proxy/rules.js +61 -14
  44. package/backend/dist/forward-proxy/server.js +226 -77
  45. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  46. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  47. package/backend/dist/harness/common/market.d.ts +3 -3
  48. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  49. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  50. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  55. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  57. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  66. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  67. package/backend/dist/harness/translation.js +64 -21
  68. package/backend/dist/harness/types.d.ts +1 -1
  69. package/backend/dist/harness/types.js +1 -1
  70. package/backend/dist/index.js +31 -18
  71. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  72. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  73. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  74. package/backend/dist/ir/adapters/anthropic.js +788 -0
  75. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  76. package/backend/dist/ir/adapters/chat.js +602 -0
  77. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  78. package/backend/dist/ir/adapters/google-stream.js +242 -0
  79. package/backend/dist/ir/adapters/google.d.ts +9 -0
  80. package/backend/dist/ir/adapters/google.js +317 -0
  81. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  82. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  83. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  84. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  85. package/backend/dist/ir/adapters/responses-output.js +348 -0
  86. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  87. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  88. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  89. package/backend/dist/ir/adapters/responses.js +646 -0
  90. package/backend/dist/ir/errors.d.ts +2 -2
  91. package/backend/dist/ir/types.d.ts +2 -1
  92. package/backend/dist/metrics/request-cost.d.ts +11 -2
  93. package/backend/dist/metrics/request-cost.js +12 -3
  94. package/backend/dist/observability/request-identity.d.ts +1 -1
  95. package/backend/dist/observability/trace-id.d.ts +40 -0
  96. package/backend/dist/observability/trace-id.js +134 -0
  97. package/backend/dist/observability/upstream-events.d.ts +82 -60
  98. package/backend/dist/observability/upstream-events.js +142 -67
  99. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  100. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  101. package/backend/dist/opencode/probe.d.ts +24 -1
  102. package/backend/dist/opencode/probe.js +28 -4
  103. package/backend/dist/opencode/user-config.d.ts +5 -0
  104. package/backend/dist/pipeline/directives.d.ts +6 -2
  105. package/backend/dist/pipeline/directives.js +7 -3
  106. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  107. package/backend/dist/pipeline/orchestrator.js +220 -194
  108. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  109. package/backend/dist/pipeline/unresolved-model.js +43 -0
  110. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  111. package/backend/dist/plugins/catalog-def.js +177 -0
  112. package/backend/dist/plugins/gateways.d.ts +62 -3
  113. package/backend/dist/plugins/gateways.js +139 -2
  114. package/backend/dist/plugins/host.d.ts +42 -5
  115. package/backend/dist/plugins/host.js +454 -38
  116. package/backend/dist/plugins/manifest.d.ts +119 -10
  117. package/backend/dist/plugins/manifest.js +265 -14
  118. package/backend/dist/plugins/pack.js +26 -0
  119. package/backend/dist/plugins/types.d.ts +187 -21
  120. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  121. package/backend/dist/protocols/systemone/convert.js +6 -1
  122. package/backend/dist/protocols/systemone/decide.js +18 -8
  123. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  124. package/backend/dist/providers/anthropic-messages.js +53 -0
  125. package/backend/dist/providers/anthropic.d.ts +7 -8
  126. package/backend/dist/providers/anthropic.js +36 -324
  127. package/backend/dist/providers/base.d.ts +14 -2
  128. package/backend/dist/providers/boot-direct.js +68 -38
  129. package/backend/dist/providers/dispatch.d.ts +5 -19
  130. package/backend/dist/providers/dispatch.js +46 -58
  131. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  132. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  133. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  134. package/backend/dist/providers/executors/dispatch.js +39 -9
  135. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  136. package/backend/dist/providers/executors/google-gemini.js +3 -0
  137. package/backend/dist/providers/executors/http-stream.js +16 -3
  138. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  139. package/backend/dist/providers/executors/openai-chat.js +3 -0
  140. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-responses.js +3 -0
  142. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  143. package/backend/dist/providers/google-gemini.d.ts +12 -0
  144. package/backend/dist/providers/google-gemini.js +50 -0
  145. package/backend/dist/providers/google.d.ts +7 -8
  146. package/backend/dist/providers/google.js +35 -308
  147. package/backend/dist/providers/http-json.d.ts +19 -0
  148. package/backend/dist/providers/http-json.js +104 -0
  149. package/backend/dist/providers/http-stream.d.ts +52 -0
  150. package/backend/dist/providers/http-stream.js +423 -0
  151. package/backend/dist/providers/member-match.d.ts +4 -5
  152. package/backend/dist/providers/member-match.js +4 -5
  153. package/backend/dist/providers/openai-chat.d.ts +13 -0
  154. package/backend/dist/providers/openai-chat.js +99 -0
  155. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  156. package/backend/dist/providers/openai-compatible.js +71 -368
  157. package/backend/dist/providers/openai-responses.d.ts +12 -0
  158. package/backend/dist/providers/openai-responses.js +68 -0
  159. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  160. package/backend/dist/providers/opencode-proxy.js +49 -125
  161. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  162. package/backend/dist/providers/plugin-adapter.js +31 -0
  163. package/backend/dist/providers/registry.d.ts +49 -24
  164. package/backend/dist/providers/registry.js +97 -55
  165. package/backend/dist/providers/responses.d.ts +7 -28
  166. package/backend/dist/providers/responses.js +45 -253
  167. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  168. package/backend/dist/providers/tool-markup-leak.js +57 -0
  169. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  170. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  171. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  172. package/backend/dist/providers/virtual-meta.js +49 -9
  173. package/backend/dist/proxy/asset-download.d.ts +54 -0
  174. package/backend/dist/proxy/asset-download.js +420 -0
  175. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  176. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  177. package/backend/dist/proxy/mihomo-binary.js +62 -51
  178. package/backend/dist/proxy/mihomo-client.js +15 -1
  179. package/backend/dist/proxy/mihomo-config.js +11 -2
  180. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  181. package/backend/dist/proxy/mihomo-geo.js +213 -0
  182. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  183. package/backend/dist/proxy/mihomo-logs.js +70 -0
  184. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  185. package/backend/dist/proxy/mihomo-pac.js +15 -0
  186. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  187. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  188. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  189. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  190. package/backend/dist/quota/adapters/minimax.js +36 -13
  191. package/backend/dist/quota/cli-login.d.ts +8 -0
  192. package/backend/dist/quota/cli-login.js +18 -0
  193. package/backend/dist/quota/declarations.js +10 -0
  194. package/backend/dist/quota/dsl.js +18 -5
  195. package/backend/dist/quota/engine.d.ts +22 -1
  196. package/backend/dist/quota/engine.js +170 -29
  197. package/backend/dist/quota/prober.d.ts +5 -0
  198. package/backend/dist/quota/prober.js +11 -2
  199. package/backend/dist/quota/types.d.ts +87 -8
  200. package/backend/dist/quota/verdict.d.ts +35 -0
  201. package/backend/dist/quota/verdict.js +135 -0
  202. package/backend/dist/ratelimit/admission.d.ts +131 -0
  203. package/backend/dist/ratelimit/admission.js +233 -0
  204. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  205. package/backend/dist/resilience/types.d.ts +2 -2
  206. package/backend/dist/router/layer2-decision.d.ts +1 -1
  207. package/backend/dist/router/layer2-decision.js +5 -8
  208. package/backend/dist/routes/console.js +242 -51
  209. package/backend/dist/routes/mihomo.d.ts +2 -0
  210. package/backend/dist/routes/mihomo.js +334 -29
  211. package/backend/dist/routes/responses.d.ts +87 -8
  212. package/backend/dist/routes/responses.js +314 -33
  213. package/backend/dist/server.js +26 -6
  214. package/backend/dist/session/session-manager.d.ts +6 -0
  215. package/backend/dist/session/session-manager.js +20 -9
  216. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  217. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  218. package/backend/dist/surfaces/chat.js +15 -0
  219. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  220. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  221. package/backend/dist/surfaces/direct-forward.js +206 -0
  222. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  223. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  224. package/backend/dist/surfaces/types.d.ts +11 -0
  225. package/backend/dist/trace/tracker.d.ts +32 -1
  226. package/backend/dist/trace/tracker.js +29 -4
  227. package/backend/dist/types/router.d.ts +34 -12
  228. package/backend/dist/types/router.js +35 -6
  229. package/backend/dist/utils/chat-stream.d.ts +21 -8
  230. package/backend/dist/utils/chat-stream.js +46 -9
  231. package/backend/dist/utils/event-ring.d.ts +4 -0
  232. package/backend/dist/utils/event-ring.js +4 -0
  233. package/backend/dist/utils/popularity.js +29 -4
  234. package/backend/dist/utils/proxy.d.ts +7 -0
  235. package/backend/dist/utils/proxy.js +35 -10
  236. package/backend/dist/utils/retry-after.d.ts +21 -0
  237. package/backend/dist/utils/retry-after.js +36 -0
  238. package/bin/ocr.js +2 -2
  239. package/frontend/dist/assets/index-Cn3QMOQx.js +1487 -0
  240. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  241. package/frontend/dist/index.html +2 -2
  242. package/package.json +1 -1
  243. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -0,0 +1,786 @@
1
+ /**
2
+ * Provider-layer tool-call markup recovery (ADR-0034).
3
+ *
4
+ * Endpoint/model policy (opencode.ai zen + deepseek-v4 DSML) lives HERE — on
5
+ * the southbound execution boundary — not in the vendor-neutral `ir/` core.
6
+ * `registry.execute` decides whether to enable recovery; this module owns how.
7
+ */
8
+ import { randomUUID } from 'node:crypto';
9
+ import { detectToolMarkupLeak } from './tool-markup-leak.js';
10
+ const TAG = /<(?:[|\uFF5C\s]*\/)?[|\uFF5C\s]*(?:DSML[|\uFF5C\s]*)?(?:tool_calls|invoke|parameter)\b[^>]*>/gi;
11
+ const STREAM_PENDING_MAX_CHARS = 1024 * 1024;
12
+ function callableTools(request) {
13
+ if (request.toolChoice?.type === 'none' || request.toolChoice?.type === 'custom')
14
+ return new Map();
15
+ const allowed = request.toolChoice?.type === 'function'
16
+ ? new Set([request.toolChoice.name])
17
+ : request.toolChoice?.type === 'allowed'
18
+ ? new Set(request.toolChoice.tools.filter((tool) => tool.type === 'function').map((tool) => tool.name))
19
+ : null;
20
+ return new Map((request.tools ?? []).flatMap((tool) => {
21
+ if (tool.type !== 'function' || (allowed && !allowed.has(tool.function.name)))
22
+ return [];
23
+ return [[tool.function.name, tool.function]];
24
+ }));
25
+ }
26
+ /** Endpoint + model + request scope; provider ids deliberately play no role. */
27
+ export function toolMarkupRecoveryFor(request, model, config) {
28
+ // Token, not a substring: `deepseek-v4-flash` matches; `deepseek-v40` does not.
29
+ if (!config || callableTools(request).size === 0 || !/(?:^|[^a-z0-9])deepseek-v4(?:$|[^a-z0-9])/i.test(model.upstreamModel))
30
+ return null;
31
+ try {
32
+ const url = new URL(config.baseUrl);
33
+ if (url.hostname !== 'opencode.ai' || url.pathname.replace(/\/+$/, '') !== '/zen/v1')
34
+ return null;
35
+ return 'dsml';
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function fencedSpans(text) {
42
+ const spans = [];
43
+ let offset = 0;
44
+ let open = null;
45
+ while (offset < text.length) {
46
+ const newline = text.indexOf('\n', offset);
47
+ const end = newline === -1 ? text.length : newline + 1;
48
+ const line = text.slice(offset, end);
49
+ if (!open) {
50
+ const match = line.match(/^[ \t]{0,3}(`{3,}|~{3,})/);
51
+ if (match)
52
+ open = { start: offset, marker: match[1] };
53
+ }
54
+ else {
55
+ const close = new RegExp(`^[ \\t]{0,3}${open.marker[0]}{${open.marker.length},}[ \\t]*\\r?(?:\\n|$)`);
56
+ if (close.test(line)) {
57
+ spans.push({ start: open.start, end });
58
+ open = null;
59
+ }
60
+ }
61
+ offset = end;
62
+ }
63
+ if (open)
64
+ spans.push({ start: open.start, end: text.length });
65
+ // Inline code is prose too. Mask paired (and conservatively, unterminated)
66
+ // backtick spans outside fenced blocks before looking for invoke tags.
67
+ let cursor = 0;
68
+ while (cursor < text.length) {
69
+ const fenced = spans.find((span) => cursor >= span.start && cursor < span.end);
70
+ if (fenced) {
71
+ cursor = fenced.end;
72
+ continue;
73
+ }
74
+ const start = text.indexOf('`', cursor);
75
+ if (start === -1)
76
+ break;
77
+ const containing = spans.find((span) => start >= span.start && start < span.end);
78
+ if (containing) {
79
+ cursor = containing.end;
80
+ continue;
81
+ }
82
+ const marker = text.slice(start).match(/^`+/)?.[0] ?? '`';
83
+ const close = text.indexOf(marker, start + marker.length);
84
+ const end = close === -1 ? text.length : close + marker.length;
85
+ spans.push({ start, end });
86
+ cursor = end;
87
+ }
88
+ return spans.sort((a, b) => a.start - b.start);
89
+ }
90
+ function inSpans(index, spans) {
91
+ return spans.some((span) => index >= span.start && index < span.end);
92
+ }
93
+ function tagAt(text, start) {
94
+ TAG.lastIndex = start;
95
+ const match = TAG.exec(text);
96
+ if (!match || match.index !== start)
97
+ return null;
98
+ const raw = match[0];
99
+ const kind = raw.match(/(?:tool_calls|invoke|parameter)\b/i)?.[0].toLowerCase();
100
+ if (!kind)
101
+ return null;
102
+ return {
103
+ kind,
104
+ closing: /^<[|\uFF5C\s]*\//.test(raw),
105
+ start,
106
+ end: start + raw.length,
107
+ raw,
108
+ name: raw.match(/\bname\s*=\s*"([^"]*)"/i)?.[1],
109
+ stringValue: /\bstring\s*=\s*"true"/i.test(raw) ? true : /\bstring\s*=\s*"false"/i.test(raw) ? false : undefined,
110
+ };
111
+ }
112
+ function nextTag(text, from, fences) {
113
+ TAG.lastIndex = from;
114
+ let match = TAG.exec(text);
115
+ while (match && inSpans(match.index, fences))
116
+ match = TAG.exec(text);
117
+ return match ? tagAt(text, match.index) : null;
118
+ }
119
+ function schemaType(schema) {
120
+ const type = schema?.type;
121
+ return typeof type === 'string' ? [type] : Array.isArray(type) ? type.filter((value) => typeof value === 'string') : [];
122
+ }
123
+ function valueMatchesSchema(value, schema) {
124
+ if (!schema)
125
+ return true;
126
+ if (Array.isArray(schema.anyOf)) {
127
+ return schema.anyOf.some((entry) => typeof entry === 'object' && entry && valueMatchesSchema(value, entry));
128
+ }
129
+ if (Array.isArray(schema.enum) && !schema.enum.includes(value))
130
+ return false;
131
+ const types = schemaType(schema);
132
+ if (types.includes('null') && value === null)
133
+ return true;
134
+ if (types.includes('string') && typeof value === 'string')
135
+ return true;
136
+ if (types.includes('number') && typeof value === 'number' && Number.isFinite(value))
137
+ return true;
138
+ if (types.includes('integer') && typeof value === 'number' && Number.isInteger(value))
139
+ return true;
140
+ if (types.includes('boolean') && typeof value === 'boolean')
141
+ return true;
142
+ if (types.includes('array') && Array.isArray(value)) {
143
+ const items = typeof schema.items === 'object' && schema.items ? schema.items : undefined;
144
+ return value.every((entry) => valueMatchesSchema(entry, items));
145
+ }
146
+ if ((types.includes('object') || (!types.length && (schema.properties || schema.required))) && value && typeof value === 'object' && !Array.isArray(value)) {
147
+ const record = value;
148
+ const properties = typeof schema.properties === 'object' && schema.properties
149
+ ? schema.properties
150
+ : {};
151
+ const required = Array.isArray(schema.required) ? schema.required.filter((entry) => typeof entry === 'string') : [];
152
+ if (required.some((key) => !Object.hasOwn(record, key)))
153
+ return false;
154
+ if (schema.additionalProperties === false && Object.keys(record).some((key) => !Object.hasOwn(properties, key)))
155
+ return false;
156
+ return Object.entries(record).every(([key, entry]) => !Object.hasOwn(properties, key) || valueMatchesSchema(entry, properties[key]));
157
+ }
158
+ return types.length === 0;
159
+ }
160
+ function parameterValue(raw, tag, schema) {
161
+ if (tag.stringValue === true) {
162
+ return valueMatchesSchema(raw, schema) ? { ok: true, value: raw } : { ok: false };
163
+ }
164
+ try {
165
+ const value = JSON.parse(raw);
166
+ if (valueMatchesSchema(value, schema))
167
+ return { ok: true, value };
168
+ }
169
+ catch {
170
+ // Fall through to schema-guided string acceptance below.
171
+ }
172
+ // Real DSML emissions may omit string="true" (even for numeric- or
173
+ // boolean-looking strings like "123" or "true"). The request schema, not a
174
+ // fallback cast, is what makes treating the body as a string safe.
175
+ if (tag.stringValue === undefined && schemaType(schema).includes('string') && valueMatchesSchema(raw, schema)) {
176
+ return { ok: true, value: raw };
177
+ }
178
+ return { ok: false };
179
+ }
180
+ function parseInvoke(text, open, tools, fences) {
181
+ const tool = open.name ? tools.get(open.name) : undefined;
182
+ if (!tool)
183
+ return { status: 'invalid' };
184
+ const properties = typeof tool.parameters?.properties === 'object' && tool.parameters.properties
185
+ ? tool.parameters.properties
186
+ : {};
187
+ const args = Object.create(null);
188
+ let cursor = open.end;
189
+ while (cursor <= text.length) {
190
+ const tag = nextTag(text, cursor, fences);
191
+ if (!tag)
192
+ return { status: 'incomplete' };
193
+ if (text.slice(cursor, tag.start).trim())
194
+ return { status: 'invalid' };
195
+ if (tag.closing && tag.kind === 'invoke') {
196
+ return valueMatchesSchema(args, tool.parameters)
197
+ ? { status: 'valid', end: tag.end, calls: [{ name: open.name, arguments: JSON.stringify(args) }] }
198
+ : { status: 'invalid' };
199
+ }
200
+ if (tag.closing || tag.kind !== 'parameter' || !tag.name || Object.hasOwn(args, tag.name))
201
+ return { status: 'invalid' };
202
+ const close = nextTag(text, tag.end, fences);
203
+ if (!close)
204
+ return { status: 'incomplete' };
205
+ if (!close.closing || close.kind !== 'parameter')
206
+ return { status: close.start === tag.end ? 'invalid' : 'incomplete' };
207
+ const paramSchema = Object.hasOwn(properties, tag.name) ? properties[tag.name] : undefined;
208
+ const converted = parameterValue(text.slice(tag.end, close.start), tag, paramSchema);
209
+ if (!converted.ok)
210
+ return { status: 'invalid' };
211
+ args[tag.name] = converted.value;
212
+ cursor = close.end;
213
+ }
214
+ return { status: 'incomplete' };
215
+ }
216
+ function parseWrapper(text, open, tools, fences) {
217
+ const calls = [];
218
+ let cursor = open.end;
219
+ while (cursor <= text.length) {
220
+ const tag = nextTag(text, cursor, fences);
221
+ if (!tag)
222
+ return { status: 'incomplete' };
223
+ if (text.slice(cursor, tag.start).trim())
224
+ return { status: 'invalid' };
225
+ if (tag.closing && tag.kind === 'tool_calls') {
226
+ return calls.length ? { status: 'valid', end: tag.end, calls } : { status: 'invalid' };
227
+ }
228
+ if (tag.closing || tag.kind !== 'invoke')
229
+ return { status: 'invalid' };
230
+ const parsed = parseInvoke(text, tag, tools, fences);
231
+ if (parsed.status !== 'valid')
232
+ return parsed;
233
+ calls.push(...parsed.calls);
234
+ cursor = parsed.end;
235
+ }
236
+ return { status: 'incomplete' };
237
+ }
238
+ function parsePrefix(text, tools, fences) {
239
+ const open = tagAt(text, 0);
240
+ if (!open || open.closing || inSpans(0, fences))
241
+ return { status: 'invalid' };
242
+ if (open.kind === 'invoke')
243
+ return parseInvoke(text, open, tools, fences);
244
+ if (open.kind === 'tool_calls')
245
+ return parseWrapper(text, open, tools, fences);
246
+ return { status: 'invalid' };
247
+ }
248
+ function findMatchingCloseEnd(text, from, kind, fences) {
249
+ let scan = from;
250
+ let depth = 1;
251
+ while (scan < text.length) {
252
+ const tag = nextTag(text, scan, fences);
253
+ if (!tag)
254
+ return null;
255
+ if (tag.kind === kind && !tag.closing)
256
+ depth += 1;
257
+ else if (tag.kind === kind && tag.closing) {
258
+ depth -= 1;
259
+ if (depth === 0)
260
+ return tag.end;
261
+ }
262
+ scan = tag.end;
263
+ }
264
+ return null;
265
+ }
266
+ export function recoverToolMarkupText(text, request) {
267
+ const tools = callableTools(request);
268
+ if (!text || tools.size === 0)
269
+ return { text, calls: [] };
270
+ const fences = fencedSpans(text);
271
+ const spans = [];
272
+ const calls = [];
273
+ let cursor = 0;
274
+ while (cursor < text.length) {
275
+ const open = nextTag(text, cursor, fences);
276
+ if (!open)
277
+ break;
278
+ if (open.closing || (open.kind !== 'invoke' && open.kind !== 'tool_calls')) {
279
+ cursor = open.end;
280
+ continue;
281
+ }
282
+ const parsed = open.kind === 'invoke' ? parseInvoke(text, open, tools, fences) : parseWrapper(text, open, tools, fences);
283
+ if (parsed.status === 'valid') {
284
+ spans.push({ start: open.start, end: parsed.end });
285
+ calls.push(...parsed.calls);
286
+ cursor = parsed.end;
287
+ }
288
+ else if (open.kind === 'tool_calls') {
289
+ // A malformed wrapper is indivisible: skip the entire matching wrapper
290
+ // (depth-aware) so no inner sibling is rescued while later independent
291
+ // blocks still remain recoverable.
292
+ const closeEnd = findMatchingCloseEnd(text, open.end, 'tool_calls', fences);
293
+ if (closeEnd !== null)
294
+ cursor = closeEnd;
295
+ else
296
+ break;
297
+ }
298
+ else {
299
+ // Invalid bare invoke: skip the whole body when a matching close exists
300
+ // (depth-aware) so nested markup inside stays ordinary text.
301
+ const closeEnd = findMatchingCloseEnd(text, open.end, 'invoke', fences);
302
+ if (closeEnd !== null)
303
+ cursor = closeEnd;
304
+ else
305
+ break;
306
+ }
307
+ }
308
+ if (!calls.length)
309
+ return { text, calls: [] };
310
+ let clean = '';
311
+ let copied = 0;
312
+ for (const span of spans) {
313
+ clean += text.slice(copied, span.start);
314
+ copied = span.end;
315
+ }
316
+ clean += text.slice(copied);
317
+ return { text: clean, calls };
318
+ }
319
+ function placeholder(call) {
320
+ const args = call.arguments.trim();
321
+ return !args || args === '{}';
322
+ }
323
+ function syntheticId(responseId, candidateIndex, sequence) {
324
+ const safe = responseId.replace(/[^A-Za-z0-9_-]/g, '_').slice(-64) || randomUUID();
325
+ return `call_${safe}_dsml_${candidateIndex}_${sequence}`;
326
+ }
327
+ function reconcileOutput(output, calls, responseId, candidateIndex) {
328
+ const next = output.map((item) => item.type === 'tool_call' ? { ...item } : item);
329
+ const remaining = [];
330
+ let applied = 0;
331
+ for (const call of calls) {
332
+ const native = next.find((item) => item.type === 'tool_call' && item.name === call.name && placeholder(item));
333
+ if (native) {
334
+ native.arguments = call.arguments;
335
+ applied += 1;
336
+ continue;
337
+ }
338
+ // A same-name native with real args already owns the call — never duplicate.
339
+ if (next.some((item) => item.type === 'tool_call' && item.name === call.name && !placeholder(item)))
340
+ continue;
341
+ remaining.push(call);
342
+ }
343
+ let sequence = 0;
344
+ for (const call of remaining) {
345
+ const id = syntheticId(responseId, candidateIndex, ++sequence);
346
+ next.push({ type: 'tool_call', id, callId: id, status: 'completed', name: call.name, arguments: call.arguments });
347
+ applied += 1;
348
+ }
349
+ return { output: next, applied };
350
+ }
351
+ function finishResponse(response, recovered) {
352
+ const leak = detectToolMarkupLeak(response);
353
+ return {
354
+ ...response,
355
+ ...(recovered > 0 ? {
356
+ reason: response.status === 'completed' ? 'tool_calls' : response.reason,
357
+ toolTextRecovery: { kind: 'dsml', calls: recovered },
358
+ } : {}),
359
+ ...(leak ? { toolMarkupLeak: leak } : { toolMarkupLeak: undefined }),
360
+ };
361
+ }
362
+ /** Collect verbatim user / tool_result text so echo recovery cannot upgrade it. */
363
+ function inputTextEchoSet(request) {
364
+ const out = new Set();
365
+ for (const item of request.input) {
366
+ if (item.type === 'message' && item.role === 'user') {
367
+ for (const part of item.content) {
368
+ if (part.type === 'text' && part.text.trim())
369
+ out.add(part.text.trim());
370
+ }
371
+ }
372
+ if (item.type === 'tool_result') {
373
+ for (const part of item.content) {
374
+ if (part.type === 'text' && part.text.trim())
375
+ out.add(part.text.trim());
376
+ }
377
+ }
378
+ }
379
+ return out;
380
+ }
381
+ export function recoverToolMarkupInResponse(response, request) {
382
+ if (response.status === 'failed')
383
+ return finishResponse(response, 0);
384
+ const responseId = response.id ?? randomUUID();
385
+ const echoed = inputTextEchoSet(request);
386
+ let recovered = 0;
387
+ const convert = (output, candidateIndex) => {
388
+ const calls = [];
389
+ const next = output.map((item) => {
390
+ if (item.type !== 'message')
391
+ return item;
392
+ let changed = false;
393
+ const content = [];
394
+ for (const part of item.content) {
395
+ if (part.type !== 'text') {
396
+ content.push(part);
397
+ continue;
398
+ }
399
+ // ADR-0034: never recover markup that is an exact echo of user/tool input.
400
+ if (echoed.has(part.text.trim())) {
401
+ content.push(part);
402
+ continue;
403
+ }
404
+ const result = recoverToolMarkupText(part.text, request);
405
+ if (!result.calls.length) {
406
+ content.push(part);
407
+ continue;
408
+ }
409
+ changed = true;
410
+ calls.push(...result.calls);
411
+ if (result.text)
412
+ content.push({ ...part, text: result.text });
413
+ }
414
+ return changed ? { ...item, content } : item;
415
+ });
416
+ if (!calls.length)
417
+ return next;
418
+ const reconciled = reconcileOutput(next, calls, responseId, candidateIndex);
419
+ recovered += reconciled.applied;
420
+ return reconciled.output;
421
+ };
422
+ const output = convert(response.output, 0);
423
+ const candidates = response.candidates?.map((candidate) => ({
424
+ ...candidate,
425
+ // Some accumulators mirror the primary output in candidates[0]. Convert
426
+ // that shared candidate once, not once per representation.
427
+ output: candidate.index === 0 && candidate.output === response.output
428
+ ? output
429
+ : convert(candidate.output, candidate.index),
430
+ }));
431
+ if (!recovered)
432
+ return finishResponse(response, 0);
433
+ return finishResponse({ ...response, output, ...(candidates ? { candidates } : {}) }, recovered);
434
+ }
435
+ function fenceStart(text, atLineStart) {
436
+ const match = atLineStart
437
+ ? /(?:^|\n)[ \t]{0,3}(?:`{3,}|~{3,})/.exec(text)
438
+ : /\n[ \t]{0,3}(?:`{3,}|~{3,})/.exec(text);
439
+ return match ? match.index + (match[0].startsWith('\n') ? 1 : 0) : -1;
440
+ }
441
+ function fenceEnd(text) {
442
+ const newline = text.indexOf('\n');
443
+ const first = text.slice(0, newline === -1 ? text.length : newline);
444
+ const marker = first.match(/^[ \t]{0,3}(`{3,}|~{3,})/)?.[1];
445
+ if (!marker)
446
+ return null;
447
+ let offset = newline === -1 ? text.length : newline + 1;
448
+ const close = new RegExp(`^[ \\t]{0,3}${marker[0]}{${marker.length},}[ \\t]*\\r?(?:\\n|$)`);
449
+ while (offset < text.length) {
450
+ const next = text.indexOf('\n', offset);
451
+ const end = next === -1 ? text.length : next + 1;
452
+ if (close.test(text.slice(offset, end)))
453
+ return end;
454
+ offset = end;
455
+ }
456
+ return null;
457
+ }
458
+ function couldBeTagPrefix(text) {
459
+ // Once `>` is present and tagAt() already returned null, no more bytes can
460
+ // turn this prefix into a valid DSML tag.
461
+ if (text.includes('>'))
462
+ return false;
463
+ const compact = text.toLowerCase().replace(/[|\uFF5C\s]/g, '');
464
+ const prefixes = [
465
+ '<dsmltool_calls', '</dsmltool_calls', '<dsmlinvoke', '</dsmlinvoke', '<dsmlparameter', '</dsmlparameter',
466
+ '<tool_calls', '</tool_calls', '<invoke', '</invoke', '<parameter', '</parameter',
467
+ ];
468
+ return prefixes.some((prefix) => {
469
+ if (prefix.startsWith(compact))
470
+ return true;
471
+ if (!compact.startsWith(prefix))
472
+ return false;
473
+ // After the keyword completes, the next character must be a word boundary,
474
+ // not another identifier char (so `<parameters>` or `<invoke_other>` never stall).
475
+ const kw = prefix.replace(/^<\/?(?:dsml)?/, '');
476
+ const idx = text.toLowerCase().indexOf(kw);
477
+ if (idx < 0)
478
+ return false;
479
+ const next = text[idx + kw.length];
480
+ return next === undefined || !/[a-z0-9_]/i.test(next);
481
+ });
482
+ }
483
+ function inlineCodeStart(text) {
484
+ return text.indexOf('`');
485
+ }
486
+ function inlineCodeEnd(text) {
487
+ const marker = text.match(/^`+/)?.[0];
488
+ if (!marker)
489
+ return null;
490
+ const close = text.indexOf(marker, marker.length);
491
+ return close === -1 ? null : close + marker.length;
492
+ }
493
+ /**
494
+ * Incremental IR-event rewriter. Text passes immediately unless it can still
495
+ * become a fence or tool tag. Tool items are reconciled at EOS so an upstream
496
+ * empty native placeholder and a recovered call can never both execute.
497
+ */
498
+ export function createToolMarkupStreamRecovery(request) {
499
+ const tools = callableTools(request);
500
+ const echoed = inputTextEchoSet(request);
501
+ const candidates = new Map();
502
+ let responseId = randomUUID();
503
+ let recovered = 0;
504
+ let finished = false;
505
+ const candidate = (index) => {
506
+ let state = candidates.get(index);
507
+ if (!state) {
508
+ state = { texts: new Map(), recovered: [], native: new Map(), nextIndex: 0 };
509
+ candidates.set(index, state);
510
+ }
511
+ return state;
512
+ };
513
+ const textState = (state, event) => {
514
+ const key = `${event.index}:${event.partIndex}`;
515
+ let text = state.texts.get(key);
516
+ if (!text) {
517
+ text = { pending: '', clean: '', suppressed: [], finalized: false, passthrough: false, atLineStart: true };
518
+ state.texts.set(key, text);
519
+ }
520
+ return text;
521
+ };
522
+ const drain = (state, text, final) => {
523
+ const emitted = [];
524
+ if (text.finalized)
525
+ return emitted;
526
+ const emit = (value) => {
527
+ if (!value)
528
+ return;
529
+ text.clean += value;
530
+ text.atLineStart = value.endsWith('\n');
531
+ emitted.push(value);
532
+ };
533
+ if (text.passthrough) {
534
+ emit(text.pending);
535
+ text.pending = '';
536
+ if (final)
537
+ text.finalized = true;
538
+ return emitted;
539
+ }
540
+ while (text.pending) {
541
+ if (text.pending.length > STREAM_PENDING_MAX_CHARS) {
542
+ text.passthrough = true;
543
+ emit(text.pending);
544
+ text.pending = '';
545
+ break;
546
+ }
547
+ const lessThan = text.pending.indexOf('<');
548
+ const fence = fenceStart(text.pending, text.atLineStart);
549
+ const inline = inlineCodeStart(text.pending);
550
+ const starts = [lessThan, fence, inline].filter((index) => index >= 0);
551
+ if (!starts.length) {
552
+ if (!final) {
553
+ // Hold trailing line-start indent (1-3 spaces/tabs) or partial tilde
554
+ // fence (`~` / `~~`) so split fences (e.g. ` ` + `~~~`) keep atLineStart.
555
+ const tildeTail = (text.atLineStart
556
+ ? /(?:^|\n)([ \t]{1,3}|[ \t]{0,3}~{1,2})$/
557
+ : /\n([ \t]{1,3}|[ \t]{0,3}~{1,2})$/).exec(text.pending);
558
+ if (tildeTail) {
559
+ const keepFrom = text.pending.length - tildeTail[1].length;
560
+ if (keepFrom > 0)
561
+ emit(text.pending.slice(0, keepFrom));
562
+ text.pending = text.pending.slice(keepFrom);
563
+ break;
564
+ }
565
+ }
566
+ emit(text.pending);
567
+ text.pending = '';
568
+ break;
569
+ }
570
+ const start = Math.min(...starts);
571
+ if (start > 0) {
572
+ emit(text.pending.slice(0, start));
573
+ text.pending = text.pending.slice(start);
574
+ continue;
575
+ }
576
+ if (fence === 0) {
577
+ const end = fenceEnd(text.pending);
578
+ if (end !== null) {
579
+ emit(text.pending.slice(0, end));
580
+ text.pending = text.pending.slice(end);
581
+ continue;
582
+ }
583
+ if (!final)
584
+ break;
585
+ emit(text.pending);
586
+ text.pending = '';
587
+ break;
588
+ }
589
+ if (inline === 0) {
590
+ const end = inlineCodeEnd(text.pending);
591
+ if (end !== null) {
592
+ emit(text.pending.slice(0, end));
593
+ text.pending = text.pending.slice(end);
594
+ continue;
595
+ }
596
+ if (!final)
597
+ break;
598
+ emit(text.pending);
599
+ text.pending = '';
600
+ break;
601
+ }
602
+ const open = tagAt(text.pending, 0);
603
+ if (!open && !final && couldBeTagPrefix(text.pending))
604
+ break;
605
+ const parsed = open ? parsePrefix(text.pending, tools, fencedSpans(text.pending)) : { status: 'invalid' };
606
+ if (parsed.status === 'valid') {
607
+ const chunk = text.pending.slice(0, parsed.end);
608
+ // Same echo rule as the buffered path: never upgrade verbatim user /
609
+ // tool_result text into an executable tool_call (ADR-0034).
610
+ const full = `${text.clean}${chunk}`.trim();
611
+ if (echoed.has(chunk.trim()) || echoed.has(full)) {
612
+ emit(chunk);
613
+ text.pending = text.pending.slice(parsed.end);
614
+ continue;
615
+ }
616
+ state.recovered.push(...parsed.calls);
617
+ text.suppressed.push(chunk);
618
+ text.pending = text.pending.slice(parsed.end);
619
+ continue;
620
+ }
621
+ if (parsed.status === 'incomplete' && !final)
622
+ break;
623
+ if (open && !open.closing && (open.kind === 'tool_calls' || open.kind === 'invoke')) {
624
+ // Malformed wrapper / invoke is indivisible (ADR-0034): skip the whole
625
+ // matching block as plain text instead of advancing by 1 char and
626
+ // rescuing an inner sibling invoke.
627
+ const closeEnd = findMatchingCloseEnd(text.pending, open.end, open.kind, fencedSpans(text.pending));
628
+ if (closeEnd !== null) {
629
+ emit(text.pending.slice(0, closeEnd));
630
+ text.pending = text.pending.slice(closeEnd);
631
+ continue;
632
+ }
633
+ if (!final && open.kind === 'tool_calls')
634
+ break;
635
+ }
636
+ // Invalid or truncated markup remains ordinary text. Emitting only the
637
+ // first character lets the loop find any later valid, independent block.
638
+ emit(text.pending[0]);
639
+ text.pending = text.pending.slice(1);
640
+ }
641
+ if (final) {
642
+ emit(text.pending);
643
+ text.pending = '';
644
+ text.finalized = true;
645
+ }
646
+ return emitted;
647
+ };
648
+ const emitTools = (state, candidateIndex, includeRecovered) => {
649
+ const events = [];
650
+ const native = [...state.native.entries()].sort(([a], [b]) => a - b);
651
+ const remaining = [];
652
+ let applied = 0;
653
+ for (const call of includeRecovered ? state.recovered : []) {
654
+ const placeholderEntry = native.find(([, item]) => item.name === call.name && placeholder(item));
655
+ if (placeholderEntry) {
656
+ placeholderEntry[1].arguments = call.arguments;
657
+ applied += 1;
658
+ continue;
659
+ }
660
+ if (native.some(([, item]) => item.name === call.name && !placeholder(item)))
661
+ continue;
662
+ remaining.push(call);
663
+ }
664
+ const emitCall = (index, item) => {
665
+ events.push({ type: 'response.output_item.added', candidateIndex, index, item: { ...item, arguments: '' } });
666
+ events.push({ type: 'response.function_call.arguments.delta', candidateIndex, index, argumentsDelta: item.arguments });
667
+ events.push({ type: 'response.function_call.arguments.done', candidateIndex, index, arguments: item.arguments });
668
+ events.push({ type: 'response.output_item.done', candidateIndex, index, item: { ...item } });
669
+ };
670
+ native.forEach(([index, item]) => emitCall(index, item));
671
+ let sequence = 0;
672
+ for (const call of remaining) {
673
+ const id = syntheticId(responseId, candidateIndex, ++sequence);
674
+ const index = state.nextIndex++;
675
+ emitCall(index, { type: 'tool_call', id, callId: id, status: 'completed', name: call.name, arguments: call.arguments });
676
+ applied += 1;
677
+ }
678
+ if (includeRecovered)
679
+ recovered += applied;
680
+ state.recovered = [];
681
+ return events;
682
+ };
683
+ const finish = (terminal) => {
684
+ if (finished)
685
+ return [];
686
+ finished = true;
687
+ const events = [];
688
+ const includeRecovered = !terminal || terminal.type === 'response.completed' || terminal.type === 'response.incomplete';
689
+ for (const [candidateIndex, state] of candidates) {
690
+ for (const [key, text] of state.texts) {
691
+ const [index, partIndex] = key.split(':').map(Number);
692
+ if (!includeRecovered && text.suppressed.length) {
693
+ // A failed turn must not execute a recovered call, but its source is
694
+ // still upstream output. Re-emit what was suppressed instead of
695
+ // silently deleting it; clients cannot retract deltas already sent.
696
+ const restored = text.suppressed.join('');
697
+ text.clean += restored;
698
+ if (text.finalized) {
699
+ const restoreIndex = state.nextIndex++;
700
+ events.push({ type: 'response.output_item.added', candidateIndex, index: restoreIndex, item: { type: 'message', role: 'assistant', content: [] } }, { type: 'response.content_part.added', candidateIndex, index: restoreIndex, partIndex: 0, part: { type: 'text', text: '' } }, { type: 'response.output_text.delta', candidateIndex, index: restoreIndex, partIndex: 0, text: restored }, { type: 'response.output_text.done', candidateIndex, index: restoreIndex, partIndex: 0, text: restored }, { type: 'response.content_part.done', candidateIndex, index: restoreIndex, partIndex: 0, part: { type: 'text', text: restored } }, { type: 'response.output_item.done', candidateIndex, index: restoreIndex, item: { type: 'message', role: 'assistant', content: [{ type: 'text', text: restored }] } });
701
+ }
702
+ else {
703
+ events.push({ type: 'response.output_text.delta', candidateIndex, index: index, partIndex: partIndex, text: restored });
704
+ }
705
+ }
706
+ drain(state, text, true).forEach((value) => events.push({
707
+ type: 'response.output_text.delta', candidateIndex, index: index, partIndex: partIndex, text: value,
708
+ }));
709
+ }
710
+ events.push(...emitTools(state, candidateIndex, includeRecovered));
711
+ }
712
+ if (terminal)
713
+ events.push(terminal);
714
+ return events;
715
+ };
716
+ return {
717
+ push(event) {
718
+ if (finished)
719
+ return [event];
720
+ if (event.type === 'response.created') {
721
+ if (event.id)
722
+ responseId = event.id;
723
+ return [event];
724
+ }
725
+ if (event.type === 'response.completed' || event.type === 'response.incomplete' || event.type === 'response.failed' || event.type === 'error') {
726
+ return finish(event);
727
+ }
728
+ const candidateIndex = event.candidateIndex ?? 0;
729
+ const state = candidate(candidateIndex);
730
+ if ('index' in event)
731
+ state.nextIndex = Math.max(state.nextIndex, event.index + 1);
732
+ if (event.type === 'response.output_text.delta') {
733
+ const text = textState(state, event);
734
+ text.pending += event.text;
735
+ return drain(state, text, false).map((value) => ({ ...event, text: value }));
736
+ }
737
+ if (event.type === 'response.output_text.done') {
738
+ const text = textState(state, event);
739
+ const events = drain(state, text, true).map((value) => ({
740
+ type: 'response.output_text.delta', candidateIndex, index: event.index, partIndex: event.partIndex, text: value,
741
+ }));
742
+ events.push({ ...event, text: text.clean });
743
+ return events;
744
+ }
745
+ if (event.type === 'response.content_part.done' && event.part.type === 'text') {
746
+ return [{ ...event, part: { ...event.part, text: textState(state, event).clean } }];
747
+ }
748
+ if (event.type === 'response.output_item.done' && event.item.type === 'message') {
749
+ return [{
750
+ ...event,
751
+ item: {
752
+ ...event.item,
753
+ content: event.item.content.map((part, partIndex) => part.type === 'text'
754
+ ? { ...part, text: textState(state, { index: event.index, partIndex }).clean }
755
+ : part),
756
+ },
757
+ }];
758
+ }
759
+ if (event.type === 'response.output_item.added' && event.item.type === 'tool_call') {
760
+ state.native.set(event.index, { ...event.item });
761
+ return [];
762
+ }
763
+ if (event.type === 'response.function_call.arguments.delta') {
764
+ const item = state.native.get(event.index);
765
+ if (item)
766
+ item.arguments += event.argumentsDelta;
767
+ return [];
768
+ }
769
+ if (event.type === 'response.function_call.arguments.done') {
770
+ const item = state.native.get(event.index);
771
+ if (item)
772
+ item.arguments = event.arguments;
773
+ return [];
774
+ }
775
+ if (event.type === 'response.output_item.done' && event.item.type === 'tool_call') {
776
+ state.native.set(event.index, { ...event.item });
777
+ return [];
778
+ }
779
+ return [event];
780
+ },
781
+ finish,
782
+ finishResponse(response) {
783
+ return finishResponse(response, recovered);
784
+ },
785
+ };
786
+ }