omnicell-router 0.8.2 → 0.8.4

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 (86) hide show
  1. package/backend/dist/auth/api-keys.js +11 -0
  2. package/backend/dist/auth/key-models.d.ts +36 -0
  3. package/backend/dist/auth/key-models.js +99 -0
  4. package/backend/dist/cli/clients/activity.js +2 -0
  5. package/backend/dist/cli/clients/codex.d.ts +70 -0
  6. package/backend/dist/cli/clients/codex.js +470 -57
  7. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  8. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  9. package/backend/dist/cli/clients/opencode.js +3 -2
  10. package/backend/dist/cli/clients/reserved.js +2 -0
  11. package/backend/dist/cli/types.d.ts +9 -0
  12. package/backend/dist/config/comments-en.js +5 -1
  13. package/backend/dist/config/comments-zh.js +5 -1
  14. package/backend/dist/config/defaults.d.ts +98 -1
  15. package/backend/dist/config/defaults.js +98 -1
  16. package/backend/dist/config/index.d.ts +15 -1
  17. package/backend/dist/config/index.js +35 -1
  18. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  19. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  20. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  21. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  22. package/backend/dist/config/schema.d.ts +3 -3
  23. package/backend/dist/config/schema.js +8 -4
  24. package/backend/dist/config/types.d.ts +54 -3
  25. package/backend/dist/forward-proxy/egress.js +13 -0
  26. package/backend/dist/forward-proxy/h2-forward.js +6 -5
  27. package/backend/dist/forward-proxy/index.js +5 -0
  28. package/backend/dist/forward-proxy/server.d.ts +12 -0
  29. package/backend/dist/forward-proxy/server.js +113 -15
  30. package/backend/dist/index.js +6 -1
  31. package/backend/dist/ir/adapters/openai-chat.js +5 -3
  32. package/backend/dist/ir/adapters/openai-responses-output.js +2 -2
  33. package/backend/dist/ir/adapters/openai-responses.d.ts +33 -0
  34. package/backend/dist/ir/adapters/openai-responses.js +44 -2
  35. package/backend/dist/ir/capabilities.js +4 -0
  36. package/backend/dist/ir/validate.d.ts +24 -0
  37. package/backend/dist/ir/validate.js +113 -63
  38. package/backend/dist/opencode/catalog/auto-pull.js +8 -7
  39. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  40. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  41. package/backend/dist/opencode/catalog/overrides-store.d.ts +5 -3
  42. package/backend/dist/opencode/catalog/overrides-store.js +22 -19
  43. package/backend/dist/opencode/catalog/repository.js +3 -3
  44. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  45. package/backend/dist/opencode/catalog/sources/models-dev.js +29 -11
  46. package/backend/dist/opencode/catalog/types.d.ts +7 -9
  47. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  48. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  49. package/backend/dist/opencode/migrate/engine.js +71 -0
  50. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  51. package/backend/dist/opencode/migrate/migrator.js +6 -0
  52. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  53. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  54. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  55. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  56. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  57. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  58. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  59. package/backend/dist/opencode/provider-defs.js +45 -45
  60. package/backend/dist/opencode/user-config.d.ts +23 -26
  61. package/backend/dist/opencode/user-config.js +95 -77
  62. package/backend/dist/pipeline/orchestrator.js +17 -7
  63. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  64. package/backend/dist/plugins/host.d.ts +2 -2
  65. package/backend/dist/plugins/host.js +15 -12
  66. package/backend/dist/providers/boot-direct.js +32 -8
  67. package/backend/dist/providers/dial-wire.d.ts +17 -0
  68. package/backend/dist/providers/dial-wire.js +49 -0
  69. package/backend/dist/providers/protocols-field.d.ts +24 -0
  70. package/backend/dist/providers/protocols-field.js +66 -0
  71. package/backend/dist/providers/registry.d.ts +3 -1
  72. package/backend/dist/providers/registry.js +23 -7
  73. package/backend/dist/quota/cli-login.js +3 -1
  74. package/backend/dist/routes/console.js +115 -95
  75. package/backend/dist/server.js +91 -2
  76. package/backend/dist/surfaces/anthropic.js +4 -1
  77. package/backend/dist/surfaces/body-admission.d.ts +279 -0
  78. package/backend/dist/surfaces/body-admission.js +613 -0
  79. package/backend/dist/surfaces/transport-node-http.d.ts +44 -5
  80. package/backend/dist/surfaces/transport-node-http.js +86 -13
  81. package/backend/dist/utils/server-liveness.d.ts +27 -0
  82. package/backend/dist/utils/server-liveness.js +31 -0
  83. package/frontend/dist/assets/{index-55VVwfFQ.js → index-Dk76uc7e.js} +367 -366
  84. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-KI1OW5x6.css} +1 -1
  85. package/frontend/dist/index.html +2 -2
  86. package/package.json +1 -1
@@ -10,6 +10,8 @@ import { DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, FORWARD_PROXY_HANG_TIMEOUT_MS, F
10
10
  import { describeUpstreamFailure, failureLabel, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveForwardProxy, transitEgressFor, shouldRetryOriginLeg, transitProxyFor, UPSTREAM_TIMEOUT_CODE, upstreamServernameOption, } from './egress.js';
11
11
  import { resolveUpstreamTls } from './upstream-tls.js';
12
12
  import { createAccessTap, recordProxyConnect, recordProxyTunnel } from './access-log.js';
13
+ import { applyInboundLiveness } from '../utils/server-liveness.js';
14
+ import { bodyLimitFor, settleContinuationExpectation, } from '../surfaces/body-admission.js';
13
15
  import { closeH2Pool, forwardH2 } from './h2-forward.js';
14
16
  import { createWsObserver } from './ws-frames.js';
15
17
  import { findGateway, listGatewayHosts } from '../plugins/gateways.js';
@@ -96,11 +98,51 @@ const CLIENT_TLS_ERROR_DEDUPE_MS = 5_000;
96
98
  */
97
99
  const MITM_ABORT_FLUSH_MS = 1_000;
98
100
  /**
99
- * How long a blind tunnel waits for client bytes before recording its decision
100
- * row without an identity. Never a relay delay — the tunnel is already flowing;
101
- * this only bounds the observation window for a server-speaks-first protocol.
101
+ * Framing-level refusals for the two HTTP/1 listener legs (RFC 9110 10.1.1: a
102
+ * request line or header block the parser cannot use gets a FINAL status, not a
103
+ * silent close). Mapped from the parser code so the two legs cannot drift:
104
+ * - header block overran the parser limit -> 431 (RFC 9110 15.5.21, and what
105
+ * node's own default clientError path sends when no listener exists);
106
+ * - unsupported message version -> 505 (RFC 9110 15.5.19);
107
+ * - everything else is malformed syntax -> 400.
108
+ * No body: a peer that could not frame a request is not being asked to parse
109
+ * JSON, and `Connection: close` (RFC 9110 9.6) says the connection is done —
110
+ * RFC 10.1.1's advice to state whether it will be closed.
102
111
  */
103
- const CLIENT_ERROR_RESPONSE = 'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n';
112
+ function clientErrorResponse(err) {
113
+ const code = typeof err === 'object' && err !== null && typeof err.code === 'string'
114
+ ? err.code
115
+ : '';
116
+ const [status, reason] = code === 'HPE_HEADER_OVERFLOW'
117
+ ? [431, 'Request Header Fields Too Large']
118
+ : code === 'HPE_INVALID_VERSION'
119
+ ? [505, 'HTTP Version Not Supported']
120
+ : [400, 'Bad Request'];
121
+ return `HTTP/1.1 ${status} ${reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`;
122
+ }
123
+ /**
124
+ * Answer a framing-level client error on its own socket, then close it.
125
+ *
126
+ * The write is DEFERRED one tick because bun's socket layer discards a write
127
+ * issued synchronously inside a `clientError` listener (verified on bun 1.3.14
128
+ * against node v24: bun sends nothing at all, so the client saw a bare reset and
129
+ * no status). Deferring is the portable half of the fix; the socket is still
130
+ * closed immediately after, so a stalled client cannot hold it open.
131
+ */
132
+ function answerClientError(socket, err, log, leg) {
133
+ log(`${leg} clientError ${describeClientError(err)}`);
134
+ const packet = clientErrorResponse(err);
135
+ setImmediate(() => {
136
+ try {
137
+ if (socket.destroyed || !socket.writable)
138
+ return;
139
+ socket.end(packet);
140
+ }
141
+ catch {
142
+ // The peer is already gone; nothing left to tell.
143
+ }
144
+ });
145
+ }
104
146
  /**
105
147
  * Credential-shaped header names in a raw packet head. The access log applies
106
148
  * the same policy to captured headers (`DENY_HEADER_SUBSTRINGS`), and this log
@@ -241,7 +283,7 @@ function parseUpgradeHead(head, defaultPort) {
241
283
  * any), then the live stream. With a tap, chunks tee into the access log
242
284
  * alongside the upstream writes (both consumers see every chunk).
243
285
  *
244
- * A preface can be up to 16 MB (`DEFAULT_MAX_BODY_BYTES`), so it is written
286
+ * A preface can be up to `GATEWAY_MAX_BODY_BYTES` (32 MiB, h2-forward.ts), so it is written
245
287
  * under backpressure: the old loop queued every chunk regardless of
246
288
  * `write()` returning false, spiking the outgoing buffer by the whole body. */
247
289
  function pumpRequestBody(req, upstream, tap, preface) {
@@ -656,6 +698,11 @@ function forwardPlainViaProxy(req, res, t, proxyUrl, upstreamTls) {
656
698
  }
657
699
  export async function createForwardProxyServer(deps) {
658
700
  const log = deps.log ?? (() => { });
701
+ // The surface registry seam is optional only so tests can boot the proxy
702
+ // without it; a production boot without it would silently lose the MITM-leg
703
+ // early 413/415, so say so once at startup rather than let it go quiet.
704
+ if (!deps.detectSurface)
705
+ log('inner 100-continue guard: no surface registry injected — header-decidable refusals fall through to the body gate');
659
706
  setLiveForwardProxy(deps.liveForwardProxy);
660
707
  setBootRules(deps.rules, deps.interceptPosture);
661
708
  const ca = ensureCa(deps.caDir);
@@ -664,12 +711,46 @@ export async function createForwardProxyServer(deps) {
664
711
  const inner = http.createServer((req, res) => {
665
712
  void handleInnerRequest(req, res, false);
666
713
  });
667
- inner.on('clientError', (err, socket) => {
668
- log(`inner clientError ${describeClientError(err)}`);
669
- try {
670
- socket.end(CLIENT_ERROR_RESPONSE);
714
+ // Same liveness bounds as the native leg (utils/server-liveness): an intercepted
715
+ // client is the same kind of client, and "no bound armed" was Bun's default —
716
+ // which is how a stalled request could hold a MITM socket open forever.
717
+ applyInboundLiveness(inner);
718
+ /**
719
+ * `Expect: 100-continue` admission on the MITM legs (RFC 9110 10.1.1): a body whose
720
+ * declared length already exceeds the gateway cap is refused from the HEADERS, so
721
+ * the client never pays for an upload we would discard. Only a target the surface
722
+ * registry recognizes is judged -- a forward to a third-party host is not ours to
723
+ * size-limit, and refusing one would be the proxy inventing a rule it never agreed
724
+ * to. A caller that injected no `detectSurface` gets no early refusal here: the
725
+ * expectation is honoured and the post-body gate still enforces the cap. The cap is the configured one (`bodyLimits.maxBytes`), read at call time so a
726
+ * controlled restart picks the new value up without a rebuild.
727
+ *
728
+ * Installing these listeners suppresses the server's own delivery (verified on Bun
729
+ * 1.3.14 and Node 24), so each leg re-dispatches when the guard says continue. The
730
+ * h2 inner leg needs no guard: RFC 9113 8.2.2 forbids `Expect` in HTTP/2.
731
+ */
732
+ function mitmContinuationRoute(url, res) {
733
+ const surface = deps.detectSurface?.(url);
734
+ if (!surface)
735
+ return undefined;
736
+ const abort = res[MITM_ABORT];
737
+ return {
738
+ capBytes: bodyLimitFor('gateway'),
739
+ errorBody: (err) => surface.errorBody(err.statusCode, err.message, err.code),
740
+ leg: 'mitm',
741
+ // `res.end()` alone leaves the terminated TLS socket open on Bun, so the client
742
+ // would sit waiting for the rest of a body nobody is reading: the refusal must
743
+ // retire the terminator's own connection to be real.
744
+ refuse: typeof abort === 'function' ? abort : undefined,
745
+ };
746
+ }
747
+ inner.on('checkContinue', (req, res) => {
748
+ if (!settleContinuationExpectation(req, res, (url) => mitmContinuationRoute(url, res))) {
749
+ void handleInnerRequest(req, res, false);
671
750
  }
672
- catch { }
751
+ });
752
+ inner.on('clientError', (err, socket) => {
753
+ answerClientError(socket, err, log, 'inner');
673
754
  });
674
755
  // ── h2 loopback inner (prior-knowledge h2c): the transport-complete half of
675
756
  // the MITM leg. EVERY host may reach it (see the ALPN offer below) — h2 is
@@ -679,6 +760,14 @@ export async function createForwardProxyServer(deps) {
679
760
  // compatibility API mirrors the node-http req/res shape the gateway
680
761
  // contract consumes.
681
762
  const h2Inner = http2.createServer();
763
+ // No HTTP/1-style idle clocks here on purpose: an h2 session is multiplexed and
764
+ // may legitimately sit open between streams, so `keepAliveTimeout`/
765
+ // `headersTimeout` have no meaning on this listener. What DOES bound it: every
766
+ // gateway-dispatched body is read through `readRequestBody`, which arms
767
+ // `REQUEST_BODY_IDLE_TIMEOUT_MS` per chunk on both inner legs, and the session is
768
+ // reaped by the CONNECT lifetime (`FORWARD_PROXY_KEEPALIVE_MS`). If a
769
+ // session-level bound is ever wanted it is `sessionTimeout` on this factory —
770
+ // do not reach for the HTTP/1 knobs.
682
771
  h2Inner.on('request', (req, res) => {
683
772
  void handleInnerRequest(req, res, true);
684
773
  });
@@ -1530,13 +1619,22 @@ export async function createForwardProxyServer(deps) {
1530
1619
  const proxy = http.createServer((req, res) => {
1531
1620
  void handlePlainProxyRequest(req, res);
1532
1621
  });
1622
+ // The outer leg terminates client TCP too, so it gets the same bounds. The blind
1623
+ // TUNNEL behind it is deliberately NOT timed by an HTTP idle clock — a tunneled
1624
+ // protocol may sit idle on purpose (IMAP IDLE), which is what
1625
+ // FORWARD_PROXY_KEEPALIVE_MS exists to reap instead.
1626
+ applyInboundLiveness(proxy);
1627
+ proxy.on('checkContinue', (req, res) => {
1628
+ // Absolute-form target on this leg (`http://gw.test:8443/v1/chat/completions`);
1629
+ // `detectSurface` matches on the trailing path, so the spelling needs no rewrite,
1630
+ // but a non-gateway target simply never matches and gets the continue.
1631
+ if (!settleContinuationExpectation(req, res, (url) => mitmContinuationRoute(url, res))) {
1632
+ void handlePlainProxyRequest(req, res);
1633
+ }
1634
+ });
1533
1635
  proxy.on('connect', handleConnect);
1534
1636
  proxy.on('clientError', (err, socket) => {
1535
- log(`proxy clientError ${describeClientError(err)}`);
1536
- try {
1537
- socket.end(CLIENT_ERROR_RESPONSE);
1538
- }
1539
- catch { }
1637
+ answerClientError(socket, err, log, 'proxy');
1540
1638
  });
1541
1639
  /**
1542
1640
  * The ONLY proxy credential (ADR-0017): the Basic password must resolve to
@@ -1,5 +1,6 @@
1
1
  import { loadConfig, ensureDefaultConfigFile, upgradeConfigFile, getRuntimeConfigRef } from './config/index.js';
2
2
  import { setPoolRefreshHook } from './providers/pool-refresh.js';
3
+ import { setFollowCatalogSyncRegistry } from './cli/clients/follow-catalog-sync.js';
3
4
  import { createServer } from './server.js';
4
5
  import { ProviderRegistry } from './providers/registry.js';
5
6
  import { refreshDirectPool } from './providers/boot-direct.js';
@@ -32,6 +33,7 @@ import { setForwardProxyStatus } from './forward-proxy/status.js';
32
33
  import { defaultBreakerStateStore } from './resilience/breaker-state.js';
33
34
  import { startHeadroomSidecar } from './compression/headroom-sidecar.js';
34
35
  import { wireFor } from './providers/wire.js';
36
+ import { normalizeProtocols, primaryProtocol } from './providers/protocols-field.js';
35
37
  import { getModelServicePluginEntry } from './plugins/host.js';
36
38
  // Dual entry — the desktop bundle compiles THIS file into `ocr-backend`; the
37
39
  // `--cli` flag turns the same binary into the `ocr` command surface (a packaged
@@ -75,7 +77,8 @@ function providerDefApiKey(providerId) {
75
77
  */
76
78
  function pluginQuotaAdapterFor(providerId) {
77
79
  const def = getProviderNodeById(providerId);
78
- const npm = typeof def?.npm === 'string' ? def.npm : typeof def?.package === 'string' ? def.package : undefined;
80
+ // Same resolution the boot primary uses: the normalized def's protocol head.
81
+ const npm = primaryProtocol(normalizeProtocols(def?.protocols));
79
82
  const entry = getModelServicePluginEntry(wireFor(npm, providerDefBaseUrl(providerId)));
80
83
  const plugin = entry?.plugin;
81
84
  const check = plugin?.quotaCheck;
@@ -299,6 +302,7 @@ async function main() {
299
302
  // Background producers (catalog auto-pull) resync the pool through this
300
303
  // hook — same builder, same fail-open contract, no import cycles.
301
304
  setPoolRefreshHook(() => refreshDirectPool(registry));
305
+ setFollowCatalogSyncRegistry(registry);
302
306
  const providerLevel = boot.excluded.filter((e) => !e.model);
303
307
  const modelLevel = boot.excluded.filter((e) => e.model);
304
308
  for (const ex of providerLevel)
@@ -310,6 +314,7 @@ async function main() {
310
314
  console.warn(`[OCR] Direct pool build failed, booting an EMPTY registry (no chat providers): ${err.message}`);
311
315
  registry = new ProviderRegistry(config, false);
312
316
  setPoolRefreshHook(() => refreshDirectPool(registry));
317
+ setFollowCatalogSyncRegistry(registry);
313
318
  }
314
319
  // breaker memory: attach the on-disk
315
320
  // store and resume last lifetime's cooldowns / backoff / manual trips.
@@ -1,6 +1,6 @@
1
1
  import { IrUnsupportedError } from '../errors.js';
2
2
  import { DATA_URL_RE } from '../media.js';
3
- import { assertCanonicalRequestSupported, assertCanonicalResponseSupported } from '../validate.js';
3
+ import { assertCanonicalRequestSupported, assertCanonicalResponseSupported, unsupportedToolKindMessage, } from '../validate.js';
4
4
  function unsupported(code, message) {
5
5
  throw new IrUnsupportedError(code, message, 'openai-chat');
6
6
  }
@@ -424,7 +424,7 @@ export function irToChatRequest(ir, model, options = {}) {
424
424
  const gen = ir.generation;
425
425
  const tools = ir.tools?.map((t) => {
426
426
  if (t.type !== 'function') {
427
- unsupported('tool_type', `Chat carries function tools only, not ${t.type}.`);
427
+ unsupported('tool_type', unsupportedToolKindMessage('openai-chat', t.type, false));
428
428
  }
429
429
  return {
430
430
  type: 'function',
@@ -444,7 +444,9 @@ export function irToChatRequest(ir, model, options = {}) {
444
444
  ? { type: 'function', function: { name: ir.toolChoice.name } }
445
445
  : ir.toolChoice.type === 'auto' || ir.toolChoice.type === 'none' || ir.toolChoice.type === 'required'
446
446
  ? ir.toolChoice.type
447
- : unsupported('tool_choice', `Chat cannot express tool_choice ${ir.toolChoice.type}.`)
447
+ : ir.toolChoice.type === 'custom'
448
+ ? unsupported('tool_choice', unsupportedToolKindMessage('openai-chat', 'custom', true))
449
+ : unsupported('tool_choice', unsupportedToolKindMessage('openai-chat', String(ir.toolChoice.type), true))
448
450
  : undefined;
449
451
  if (ir.text?.verbosity)
450
452
  unsupported('text_verbosity', 'Chat cannot represent text.verbosity on this execution bridge.');
@@ -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, responsesToolItemId } from './openai-responses.js';
4
+ import { responsesCallId, 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');
@@ -72,7 +72,7 @@ function outputItemToWire(item, messageId) {
72
72
  return {
73
73
  type: custom ? 'custom_tool_call' : 'function_call',
74
74
  id: responsesToolItemId(item.id || shortId(custom ? 'ctc_' : 'fc_'), custom),
75
- call_id: item.callId ?? item.id,
75
+ call_id: responsesCallId(item.callId, item.id),
76
76
  name: item.name,
77
77
  ...(custom ? { input: item.arguments } : { arguments: item.arguments }),
78
78
  status: item.status ?? 'completed',
@@ -19,6 +19,39 @@ export declare function responsesToolToWire(tool: ToolDef): Record<string, unkno
19
19
  * characters or a tail would silently merge two calls into one id.
20
20
  */
21
21
  export declare function responsesToolItemId(id: string, custom: boolean): string;
22
+ /**
23
+ * Canonical correlation id -> Responses `call_id`, carrying the same two
24
+ * invariants as `responsesToolItemId` plus the one it lacked: a FIELD BUDGET.
25
+ * Upstream Responses APIs validate this string's length, and a client id that
26
+ * arrived from another carrier (chat owns `tool_calls[].id`; the cursor-gateway
27
+ * loop re-injects the id a PREVIOUS upstream minted) would otherwise leave here
28
+ * verbatim and answer 400.
29
+ *
30
+ * Four properties, all load-bearing:
31
+ *
32
+ * - In-budget -> BYTE-IDENTICAL. Most traffic never sees a rewrite, so carriers
33
+ * that key on the `call_` / `toolu_` SHAPE keep seeing it. `call_id` carries no
34
+ * item-type prefix requirement (that is why `responsesToolItemId` adds one and
35
+ * this does not), so the hashed form stays valid where a hashed ITEM id would
36
+ * not.
37
+ * - Deterministic: the same history yields the same id on every turn, or the
38
+ * replayed prefix busts the upstream prompt cache.
39
+ * - Injective: truncating to the budget is NOT the fallback — ids that share a
40
+ * 64-char prefix would silently merge, and a merged correlation id merges two
41
+ * tool results onto one call with no error anywhere. The digest is `sha256`
42
+ * hex at its FULL 64, so nothing is sliced away.
43
+ * - A PROJECTION: `responsesCallId(responsesCallId(x)) === responsesCallId(x)`,
44
+ * because the hashed form is itself in-budget. The correlation id flows back
45
+ * through the gateway (a client replays whatever id it was handed, and an
46
+ * extension item may carry one verbatim), so a map that is not idempotent
47
+ * would name the same call differently on two turns of one session.
48
+ *
49
+ * An empty id has no faithful representation — pairing is impossible without it,
50
+ * so it is refused in the plane's own envelope rather than minted a placeholder
51
+ * (which would merge every unlabelled call onto one id) or relayed as `""` for
52
+ * the upstream to reject in a language the client cannot read.
53
+ */
54
+ export declare function responsesCallId(callId: string | undefined, fallback?: string): string;
22
55
  /** Canonical IR → OpenAI Responses request. No request-object spreading. */
23
56
  export declare function canonicalToResponsesPayload(ir: CanonicalRequest, model: ModelRegistration, stream?: boolean): Record<string, any>;
24
57
  export declare function responsesInputToIR(raw: unknown): InputItem[];
@@ -1,4 +1,5 @@
1
1
  import crypto from 'node:crypto';
2
+ import { RESPONSES_CALL_ID_MAX_LEN } from '../../config/defaults.js';
2
3
  import { IrUnsupportedError } from '../errors.js';
3
4
  import { DATA_URL_RE } from '../media.js';
4
5
  import { assertCanonicalRequestSupported } from '../validate.js';
@@ -187,6 +188,47 @@ export function responsesToolItemId(id, custom) {
187
188
  return prefix + id;
188
189
  return prefix + crypto.createHash('sha256').update(id).digest('hex').slice(0, 48);
189
190
  }
191
+ /** Charset + length budget for `call_id` (see RESPONSES_CALL_ID_MAX_LEN). */
192
+ const CALL_ID_SHAPE = new RegExp(`^[A-Za-z0-9_-]{1,${RESPONSES_CALL_ID_MAX_LEN}}$`);
193
+ /**
194
+ * Canonical correlation id -> Responses `call_id`, carrying the same two
195
+ * invariants as `responsesToolItemId` plus the one it lacked: a FIELD BUDGET.
196
+ * Upstream Responses APIs validate this string's length, and a client id that
197
+ * arrived from another carrier (chat owns `tool_calls[].id`; the cursor-gateway
198
+ * loop re-injects the id a PREVIOUS upstream minted) would otherwise leave here
199
+ * verbatim and answer 400.
200
+ *
201
+ * Four properties, all load-bearing:
202
+ *
203
+ * - In-budget -> BYTE-IDENTICAL. Most traffic never sees a rewrite, so carriers
204
+ * that key on the `call_` / `toolu_` SHAPE keep seeing it. `call_id` carries no
205
+ * item-type prefix requirement (that is why `responsesToolItemId` adds one and
206
+ * this does not), so the hashed form stays valid where a hashed ITEM id would
207
+ * not.
208
+ * - Deterministic: the same history yields the same id on every turn, or the
209
+ * replayed prefix busts the upstream prompt cache.
210
+ * - Injective: truncating to the budget is NOT the fallback — ids that share a
211
+ * 64-char prefix would silently merge, and a merged correlation id merges two
212
+ * tool results onto one call with no error anywhere. The digest is `sha256`
213
+ * hex at its FULL 64, so nothing is sliced away.
214
+ * - A PROJECTION: `responsesCallId(responsesCallId(x)) === responsesCallId(x)`,
215
+ * because the hashed form is itself in-budget. The correlation id flows back
216
+ * through the gateway (a client replays whatever id it was handed, and an
217
+ * extension item may carry one verbatim), so a map that is not idempotent
218
+ * would name the same call differently on two turns of one session.
219
+ *
220
+ * An empty id has no faithful representation — pairing is impossible without it,
221
+ * so it is refused in the plane's own envelope rather than minted a placeholder
222
+ * (which would merge every unlabelled call onto one id) or relayed as `""` for
223
+ * the upstream to reject in a language the client cannot read.
224
+ */
225
+ export function responsesCallId(callId, fallback) {
226
+ const id = (callId ?? '').trim() || (fallback ?? '').trim();
227
+ if (!id) {
228
+ throw new IrUnsupportedError('tool_call_id', 'Responses tool items require a non-empty correlation id.', PROTOCOL);
229
+ }
230
+ return CALL_ID_SHAPE.test(id) ? id : crypto.createHash('sha256').update(id).digest('hex');
231
+ }
190
232
  function itemToWire(item) {
191
233
  if (item.type === 'extension') {
192
234
  if (item.protocol !== PROTOCOL)
@@ -214,7 +256,7 @@ function itemToWire(item) {
214
256
  return {
215
257
  type: custom ? 'custom_tool_call' : 'function_call',
216
258
  id: responsesToolItemId(item.id, custom),
217
- call_id: item.callId ?? item.id,
259
+ call_id: responsesCallId(item.callId, item.id),
218
260
  name: item.name,
219
261
  ...(custom ? { input: item.arguments } : { arguments: item.arguments }),
220
262
  ...(item.status ? { status: item.status } : {}),
@@ -227,7 +269,7 @@ function itemToWire(item) {
227
269
  const textOnly = parts.every((p) => p.type === 'input_text');
228
270
  return {
229
271
  type: item.vendor?.[PROTOCOL]?.itemType === 'custom_tool_call_output' ? 'custom_tool_call_output' : 'function_call_output',
230
- call_id: item.callId,
272
+ call_id: responsesCallId(item.callId),
231
273
  output: textOnly ? parts.map((p) => String(p.text ?? '')).join('\n') : parts,
232
274
  };
233
275
  }
@@ -10,6 +10,10 @@ const CHAT_GENERATION = {
10
10
  const OPENAI_CHAT = {
11
11
  parts: { text: true, image: true, refusal: true },
12
12
  sources: { image: ['url', 'base64'] },
13
+ // function only: this id is the portable OpenAI-compatible Chat contract.
14
+ // OpenAI Platform's 2025-08 Chat `custom` tools stay off the global matrix —
15
+ // most compat upstreams reject them; enabling here would forward OpenAI-only
16
+ // payloads to Xiaomi/DeepSeek/Kimi-style endpoints. Responses keeps custom/builtin.
13
17
  toolKinds: { function: true },
14
18
  reasoningSignature: false,
15
19
  // The orchestrator translates a budget to reasoning_effort before this wire.
@@ -1,3 +1,4 @@
1
+ import { IrUnsupportedError } from './errors.js';
1
2
  import type { CanonicalRequest, CanonicalResponse, ProtocolId, StreamEvent } from './types.js';
2
3
  /** Request = southbound payload; response = northbound encoder. Same matrix,
3
4
  * but a few carriers accept a field on one leg only (Responses signatures). */
@@ -6,6 +7,29 @@ export interface RequestValidationOptions {
6
7
  /** Generic OpenAI wires deliberately strip foreign carrier cache extensions. */
7
8
  stripCarrierExtensions?: boolean;
8
9
  }
10
+ /**
11
+ * Client-visible unsupported_parameter body. One voice for the gate and adapters:
12
+ * feature + dialed protocol + actionable hint. Dial context (model / protocols[])
13
+ * is layered on by `withDialContext` in the registry.
14
+ */
15
+ export declare function formatUnsupported(protocol: ProtocolId, feature: string, hint?: string): string;
16
+ /**
17
+ * Operator-facing copy when a wire rejects non-function tools.
18
+ * OpenAI Platform Chat Completions added `type:"custom"` in 2025-08, but OCR's
19
+ * `openai-chat` id is the *portable* Chat Completions contract used by Xiaomi /
20
+ * DeepSeek / Kimi-style compat endpoints — those accept function tools, not
21
+ * OpenAI's freeform/grammar custom dialect or Responses builtins.
22
+ */
23
+ export declare function unsupportedToolKindMessage(protocol: ProtocolId, kind: string, forChoice: boolean): string;
24
+ /**
25
+ * Layer dial facts onto a gate/adapter refusal so the client sees which model
26
+ * and protocols[] were in play. Same code/protocol; message only.
27
+ */
28
+ export declare function withDialContext(err: IrUnsupportedError, opts: {
29
+ modelId: string;
30
+ dialWire: string;
31
+ protocols?: readonly string[];
32
+ }): IrUnsupportedError;
9
33
  /**
10
34
  * Fail-visible conversion gate. It is deliberately adapter-independent: every
11
35
  * southbound wire runs the SAME checks before it builds its payload, so adding