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
@@ -9,7 +9,7 @@ import { FinOpsTracker } from './metrics/finops-tracker.js';
9
9
  import { PipelineOrchestrator } from './pipeline/orchestrator.js';
10
10
  import { catalogRepository } from './opencode/catalog/repository.js';
11
11
  import { initProxyConfig } from './utils/proxy.js';
12
- import { reconcileMihomoSidecar } from './proxy/mihomo-sidecar.js';
12
+ import { reconcileMihomoSidecar, stopSpawnedMihomoSync } from './proxy/mihomo-sidecar.js';
13
13
  import { isRestartSupervisorProcess, runRestartSupervisor, takeRestartSelfRegisterFlag, writeDaemonFiles } from './cli/daemon.js';
14
14
  import { openFinOpsStore } from './trace/persist.js';
15
15
  import { openRateLimitEventStore, getRateLimitEventLog } from './ratelimit/event-log.js';
@@ -19,6 +19,7 @@ import { RATE_LIMIT_CHECKPOINT_INTERVAL_MS } from './config/index.js';
19
19
  import { openQuotaEventStore, getQuotaEventLog } from './quota/events.js';
20
20
  import { openFailureEventStore, getFailureEventLog } from './observability/failure-events.js';
21
21
  import { QuotaProber, setQuotaProber, getQuotaProber } from './quota/prober.js';
22
+ import { providerUsesCliLogin } from './quota/cli-login.js';
22
23
  import { getQuotaStore } from './quota/store.js';
23
24
  import { keyHashPrefix } from './opencode/credentials/types.js';
24
25
  import { expandEnvTemplate, getProviderNodeById, listConfigProviders } from './opencode/user-config.js';
@@ -80,10 +81,16 @@ function pluginQuotaAdapterFor(providerId) {
80
81
  const check = plugin?.quotaCheck;
81
82
  if (!plugin || !check || !entry)
82
83
  return undefined;
84
+ // The plugin names the origins it dials for this entry; the core turns them
85
+ // into a proxy-guarded transport. Without them the adapter would inherit the
86
+ // raw global `fetch` and `proxy.includes` would silently not apply — the
87
+ // exact gap that made plugin-wire providers unreachable through a split.
88
+ const egressOrigins = plugin.egressOrigins?.bind(plugin);
83
89
  return {
84
90
  id: `plugin:${entry.view.id}`,
85
91
  providerIds: [providerId],
86
92
  probe: (ctx) => check(ctx),
93
+ ...(egressOrigins ? { egressOrigins } : {}),
87
94
  };
88
95
  }
89
96
  async function main() {
@@ -117,23 +124,24 @@ async function main() {
117
124
  upgradeConfigFile();
118
125
  const config = loadConfig();
119
126
  initProxyConfig(config.proxy);
120
- // Mihomo sidecar (ADR-0022): when outbound proxy mode is mihomo and the
121
- // master switch is on, adopt a healthy local controller or spawn mihomo.
122
- // Fire-and-forget — a missing binary is logged, never a boot failure, and
123
- // the download helper stays opt-in (POST /api/admin/proxy/mihomo/install).
124
- if (config.proxy?.enabled === true && config.proxy.mode === 'mihomo') {
125
- void reconcileMihomoSidecar(config.proxy)
126
- .then((r) => {
127
- if (r.ok)
128
- console.log(`[OCR] clash sidecar ${r.action}${r.pid ? ` (pid ${r.pid})` : ''}`);
129
- else
130
- console.warn(`[OCR] clash sidecar ${r.action} failed: ${r.error}`);
131
- })
132
- .catch((err) => {
133
- const message = err instanceof Error ? err.message : String(err);
134
- console.warn(`[OCR] mihomo sidecar auto-start threw: ${message}`);
135
- });
136
- }
127
+ // Mihomo sidecar (ADR-0022): reconcile by `autoStart` — NOT by the outbound
128
+ // mode — so "core runs while outbound is direct" (and "stopped stays
129
+ // stopped") survive a gateway restart. The reconcile adopts a healthy local
130
+ // controller, spawns when the run policy says it should exist, and stops
131
+ // only a core this gateway shape spawned. Fire-and-forget — a missing binary
132
+ // is logged, never a boot failure, and the download helper stays opt-in
133
+ // (POST /api/admin/proxy/mihomo/install).
134
+ void reconcileMihomoSidecar(config.proxy)
135
+ .then((r) => {
136
+ if (r.ok)
137
+ console.log(`[OCR] clash sidecar ${r.action}${r.pid ? ` (pid ${r.pid})` : ''}`);
138
+ else
139
+ console.warn(`[OCR] clash sidecar ${r.action} failed: ${r.error}`);
140
+ })
141
+ .catch((err) => {
142
+ const message = err instanceof Error ? err.message : String(err);
143
+ console.warn(`[OCR] mihomo sidecar auto-start threw: ${message}`);
144
+ });
137
145
  // Headroom sidecar association (opt-in compression.headroom.autoStart):
138
146
  // probe <url>/health → adopt a running instance, else detached-spawn one.
139
147
  // Fire-and-forget — never blocks or crashes boot; the compression stage
@@ -354,6 +362,7 @@ async function main() {
354
362
  // L-d origin containment anchor: a model-less provider has no registry
355
363
  // config, so fall back to its provider-defs node (the single def truth).
356
364
  getProviderBaseUrl: (name) => registry.getProviderConfig(name)?.baseUrl ?? providerDefBaseUrl(name),
365
+ credentialless: (name) => providerUsesCliLogin(name),
357
366
  listStoredCredentials: (name) => {
358
367
  if (!credentialStore)
359
368
  return [];
@@ -472,6 +481,10 @@ async function main() {
472
481
  process.on('exit', () => {
473
482
  breakerStore.flush();
474
483
  orchestrator.getSessionManager().flushPersist();
484
+ // The Clash core is OUR child (ADR-0022): a cooperative exit takes it with
485
+ // us, exactly like the console's Stop. Synchronous by necessity; an
486
+ // adopted (operator-owned) core has no in-memory pid and is left running.
487
+ stopSpawnedMihomoSync();
475
488
  });
476
489
  }
477
490
  if (!cliMode)
@@ -0,0 +1,18 @@
1
+ import type { StreamEvent } from '../types.js';
2
+ /** Anthropic Messages SSE → canonical item lifecycle decoder. */
3
+ export declare class AnthropicStreamDecoder {
4
+ private readonly blocks;
5
+ private nextItem;
6
+ private createdSent;
7
+ private nativeTerminal;
8
+ private terminalSent;
9
+ private stopReason;
10
+ private usage;
11
+ get terminated(): boolean;
12
+ push(raw: unknown): StreamEvent[];
13
+ finish(): StreamEvent[];
14
+ private closeBlock;
15
+ private mergeUsage;
16
+ private wireIndex;
17
+ private block;
18
+ }
@@ -0,0 +1,247 @@
1
+ import { IrUpstreamError } from '../errors.js';
2
+ import { anthropicUsageFromWire } from './anthropic.js';
3
+ function record(value) {
4
+ return value && typeof value === 'object' ? value : {};
5
+ }
6
+ function invalid(message) {
7
+ throw new IrUpstreamError(`Invalid Anthropic stream: ${message}`);
8
+ }
9
+ /** Anthropic Messages SSE → canonical item lifecycle decoder. */
10
+ export class AnthropicStreamDecoder {
11
+ blocks = new Map();
12
+ nextItem = 0;
13
+ createdSent = false;
14
+ nativeTerminal = false;
15
+ terminalSent = false;
16
+ stopReason;
17
+ usage = { inputTokens: 0, outputTokens: 0 };
18
+ get terminated() {
19
+ return this.nativeTerminal;
20
+ }
21
+ push(raw) {
22
+ const frame = record(raw);
23
+ const type = String(frame.type ?? '');
24
+ if (type === 'message_start') {
25
+ const message = record(frame.message);
26
+ this.usage = anthropicUsageFromWire(message.usage);
27
+ this.createdSent = true;
28
+ return [
29
+ {
30
+ type: 'response.created',
31
+ ...(typeof message.id === 'string' ? { id: message.id } : {}),
32
+ ...(typeof message.model === 'string' ? { model: message.model } : {}),
33
+ },
34
+ { type: 'response.usage', usage: this.usage },
35
+ ];
36
+ }
37
+ if (type === 'content_block_start') {
38
+ const wireIndex = this.wireIndex(frame.index);
39
+ if (this.blocks.has(wireIndex))
40
+ invalid(`content block ${wireIndex} was opened twice.`);
41
+ const block = record(frame.content_block);
42
+ const itemIndex = this.nextItem++;
43
+ let state;
44
+ const events = [];
45
+ if (block.type === 'text') {
46
+ const part = {
47
+ type: 'text', text: typeof block.text === 'string' ? block.text : '',
48
+ ...(Array.isArray(block.citations)
49
+ ? { annotations: block.citations.map((payload) => ({ type: 'extension', protocol: 'anthropic', payload })) }
50
+ : {}),
51
+ };
52
+ const item = { type: 'message', role: 'assistant', content: [part] };
53
+ state = { wireIndex, itemIndex, item, part, kind: 'text' };
54
+ events.push({ type: 'response.output_item.added', index: itemIndex, item }, { type: 'response.content_part.added', index: itemIndex, partIndex: 0, part });
55
+ if (part.text)
56
+ events.push({ type: 'response.output_text.delta', index: itemIndex, partIndex: 0, text: part.text });
57
+ }
58
+ else if (block.type === 'tool_use') {
59
+ const id = String(block.id ?? '');
60
+ const item = { type: 'tool_call', id, callId: id, name: String(block.name ?? ''), arguments: '' };
61
+ state = { wireIndex, itemIndex, item, kind: 'tool' };
62
+ events.push({ type: 'response.output_item.added', index: itemIndex, item });
63
+ const initial = block.input && typeof block.input === 'object' && Object.keys(block.input).length
64
+ ? JSON.stringify(block.input)
65
+ : '';
66
+ if (initial) {
67
+ item.arguments = initial;
68
+ events.push({ type: 'response.function_call.arguments.delta', index: itemIndex, argumentsDelta: initial });
69
+ }
70
+ }
71
+ else if (block.type === 'thinking' || block.type === 'redacted_thinking') {
72
+ const item = {
73
+ type: 'reasoning',
74
+ ...(block.type === 'thinking' ? { text: typeof block.thinking === 'string' ? block.thinking : '' } : {}),
75
+ ...(typeof block.signature === 'string' ? { signature: block.signature } : {}),
76
+ ...(typeof block.data === 'string' ? { encrypted: block.data } : {}),
77
+ vendor: { anthropic: { blockType: block.type } },
78
+ };
79
+ state = { wireIndex, itemIndex, item, kind: 'reasoning' };
80
+ events.push({ type: 'response.output_item.added', index: itemIndex, item });
81
+ if (item.text)
82
+ events.push({ type: 'response.reasoning.delta', index: itemIndex, text: item.text });
83
+ }
84
+ else {
85
+ const item = { type: 'extension', protocol: 'anthropic', payload: frame.content_block };
86
+ state = { wireIndex, itemIndex, item, kind: 'extension' };
87
+ events.push({ type: 'response.output_item.added', index: itemIndex, item });
88
+ }
89
+ this.blocks.set(wireIndex, state);
90
+ return events;
91
+ }
92
+ if (type === 'content_block_delta') {
93
+ const state = this.block(frame.index);
94
+ const delta = record(frame.delta);
95
+ if (delta.type === 'text_delta' && state.part?.type === 'text') {
96
+ if (typeof delta.text !== 'string')
97
+ invalid('text_delta requires text.');
98
+ state.part.text += delta.text;
99
+ return [{ type: 'response.output_text.delta', index: state.itemIndex, partIndex: 0, text: delta.text }];
100
+ }
101
+ if (delta.type === 'thinking_delta' && state.item.type === 'reasoning') {
102
+ if (typeof delta.thinking !== 'string')
103
+ invalid('thinking_delta requires thinking.');
104
+ state.item.text = (state.item.text ?? '') + delta.thinking;
105
+ return [{ type: 'response.reasoning.delta', index: state.itemIndex, text: delta.thinking }];
106
+ }
107
+ if (delta.type === 'signature_delta' && state.item.type === 'reasoning') {
108
+ if (typeof delta.signature !== 'string')
109
+ invalid('signature_delta requires signature.');
110
+ state.item.signature = (state.item.signature ?? '') + delta.signature;
111
+ return [];
112
+ }
113
+ if (delta.type === 'input_json_delta' && state.item.type === 'tool_call') {
114
+ if (typeof delta.partial_json !== 'string')
115
+ invalid('input_json_delta requires partial_json.');
116
+ state.item.arguments += delta.partial_json;
117
+ return [{
118
+ type: 'response.function_call.arguments.delta', index: state.itemIndex,
119
+ argumentsDelta: delta.partial_json,
120
+ }];
121
+ }
122
+ if (delta.type === 'citations_delta' && state.part?.type === 'text') {
123
+ const annotation = { type: 'extension', protocol: 'anthropic', payload: delta.citation };
124
+ state.part.annotations ??= [];
125
+ const annotationIndex = state.part.annotations.push(annotation) - 1;
126
+ return [{
127
+ type: 'response.output_text.annotation.added', index: state.itemIndex,
128
+ partIndex: 0, annotationIndex, annotation,
129
+ }];
130
+ }
131
+ return invalid(`delta "${String(delta.type)}" does not match content block ${state.wireIndex}.`);
132
+ }
133
+ if (type === 'content_block_stop')
134
+ return this.closeBlock(this.wireIndex(frame.index));
135
+ if (type === 'message_delta') {
136
+ const delta = record(frame.delta);
137
+ if (typeof delta.stop_reason === 'string')
138
+ this.stopReason = delta.stop_reason;
139
+ const events = [];
140
+ if (frame.usage && typeof frame.usage === 'object') {
141
+ this.mergeUsage(record(frame.usage));
142
+ events.push({ type: 'response.usage', usage: this.usage });
143
+ }
144
+ return events;
145
+ }
146
+ if (type === 'message_stop') {
147
+ this.nativeTerminal = true;
148
+ this.terminalSent = true;
149
+ const events = [];
150
+ if (!this.createdSent) {
151
+ this.createdSent = true;
152
+ events.push({ type: 'response.created' });
153
+ }
154
+ for (const index of [...this.blocks.keys()].sort((a, b) => a - b))
155
+ events.push(...this.closeBlock(index));
156
+ const reason = this.stopReason === 'max_tokens' ? 'length'
157
+ : this.stopReason === 'refusal' ? 'content_filter' : undefined;
158
+ events.push(reason ? { type: 'response.incomplete', reason } : { type: 'response.completed' });
159
+ return events;
160
+ }
161
+ if (type === 'error') {
162
+ this.nativeTerminal = true;
163
+ this.terminalSent = true;
164
+ const error = record(frame.error);
165
+ return [{ type: 'error', code: error.type, message: String(error.message ?? 'Anthropic stream failed.') }];
166
+ }
167
+ if (type === 'ping')
168
+ return [];
169
+ return invalid(`unsupported event "${type || 'missing type'}".`);
170
+ }
171
+ finish() {
172
+ if (this.terminalSent)
173
+ return [];
174
+ this.terminalSent = true;
175
+ const events = [];
176
+ for (const index of [...this.blocks.keys()].sort((a, b) => a - b))
177
+ events.push(...this.closeBlock(index));
178
+ events.push(this.stopReason === 'max_tokens'
179
+ ? { type: 'response.incomplete', reason: 'length' }
180
+ : this.stopReason === 'refusal'
181
+ ? { type: 'response.incomplete', reason: 'content_filter' }
182
+ : { type: 'response.completed' });
183
+ return events;
184
+ }
185
+ closeBlock(wireIndex) {
186
+ const state = this.blocks.get(wireIndex);
187
+ if (!state)
188
+ invalid(`content block ${wireIndex} was not open.`);
189
+ this.blocks.delete(wireIndex);
190
+ const index = state.itemIndex;
191
+ if (state.kind === 'text' && state.part?.type === 'text') {
192
+ return [
193
+ {
194
+ type: 'response.output_text.done', index, partIndex: 0, text: state.part.text,
195
+ ...(state.part.annotations ? { annotations: state.part.annotations } : {}),
196
+ },
197
+ { type: 'response.content_part.done', index, partIndex: 0, part: state.part },
198
+ { type: 'response.output_item.done', index, item: state.item },
199
+ ];
200
+ }
201
+ if (state.kind === 'reasoning' && state.item.type === 'reasoning') {
202
+ return [
203
+ ...(state.item.text !== undefined
204
+ ? [{ type: 'response.reasoning.done', index, text: state.item.text }]
205
+ : []),
206
+ { type: 'response.output_item.done', index, item: state.item },
207
+ ];
208
+ }
209
+ if (state.kind === 'tool' && state.item.type === 'tool_call') {
210
+ return [
211
+ { type: 'response.function_call.arguments.done', index, arguments: state.item.arguments },
212
+ { type: 'response.output_item.done', index, item: state.item },
213
+ ];
214
+ }
215
+ return [{ type: 'response.output_item.done', index, item: state.item }];
216
+ }
217
+ mergeUsage(raw) {
218
+ const next = anthropicUsageFromWire(raw);
219
+ const hasInput = raw.input_tokens !== undefined || raw.cache_read_input_tokens !== undefined ||
220
+ raw.cache_creation_input_tokens !== undefined;
221
+ this.usage = {
222
+ ...this.usage,
223
+ ...(hasInput ? {
224
+ inputTokens: next.inputTokens,
225
+ cachedInputTokens: next.cachedInputTokens,
226
+ cacheWriteTokens: next.cacheWriteTokens,
227
+ cacheWrite5mTokens: next.cacheWrite5mTokens,
228
+ cacheWrite1hTokens: next.cacheWrite1hTokens,
229
+ } : {}),
230
+ ...(raw.output_tokens !== undefined ? { outputTokens: next.outputTokens } : {}),
231
+ ...(next.reasoningTokens !== undefined ? { reasoningTokens: next.reasoningTokens } : {}),
232
+ };
233
+ this.usage.totalTokens = this.usage.inputTokens + this.usage.outputTokens;
234
+ }
235
+ wireIndex(value) {
236
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 0)
237
+ invalid('content block index must be a non-negative integer.');
238
+ return value;
239
+ }
240
+ block(value) {
241
+ const index = this.wireIndex(value);
242
+ const state = this.blocks.get(index);
243
+ if (!state)
244
+ invalid(`delta references unopened content block ${index}.`);
245
+ return state;
246
+ }
247
+ }
@@ -0,0 +1,29 @@
1
+ import type { ModelRegistration } from '../../config/types.js';
2
+ import type { CanonicalRequest, CanonicalResponse, Usage } from '../types.js';
3
+ type Wire = Record<string, any>;
4
+ /** Anthropic Messages request → Canonical IR. No Chat-shaped intermediate. */
5
+ export declare function anthropicRequestToIR(body: unknown): CanonicalRequest;
6
+ /** Canonical IR → Anthropic Messages request. */
7
+ export declare function canonicalToAnthropicPayload(ir: CanonicalRequest, model: ModelRegistration): Wire;
8
+ declare function usageFromWire(raw: unknown): Usage;
9
+ /** Anthropic Messages response → Canonical IR, including signed thinking. */
10
+ export declare function anthropicResponseToIR(data: unknown): CanonicalResponse;
11
+ /** Canonical IR → Anthropic Messages JSON, without a Chat response projection. */
12
+ export declare function canonicalToAnthropicResponse(response: CanonicalResponse, model: string): Wire;
13
+ /** Stateful IR-event → Anthropic SSE payload encoder for one client turn. */
14
+ export declare class AnthropicEventEncoder {
15
+ private id;
16
+ private model;
17
+ private usage;
18
+ private started;
19
+ private terminal;
20
+ private sawToolCall;
21
+ private nextBlock;
22
+ private readonly blocks;
23
+ encode(event: import('../types.js').StreamEvent, model: string, finalResponse?: CanonicalResponse): Wire[];
24
+ private start;
25
+ private blockFor;
26
+ private blockIndex;
27
+ private stopBlock;
28
+ }
29
+ export { usageFromWire as anthropicUsageFromWire };