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
@@ -255,11 +255,99 @@ export const DEFAULT_HEADROOM_URL = `http://127.0.0.1:${DEFAULT_HEADROOM_PORT}`;
255
255
  /** Headroom call timeout when `compression.headroom.timeoutMs` is unset. */
256
256
  export const DEFAULT_HEADROOM_TIMEOUT_MS = 3000;
257
257
  /** Per-body capture cap when `requestCapture.maxBodyBytes` is unset (16 MB —
258
- * sized for a fully-loaded 2M-token context). */
258
+ * sized for a fully-loaded 2M-token context). This bounds what the ARCHIVE
259
+ * stores, never what the gateway ACCEPTS — see GATEWAY_MAX_BODY_BYTES. */
259
260
  export const DEFAULT_MAX_BODY_BYTES = 16_777_216;
261
+ /**
262
+ * Field budget for the outbound OpenAI Responses `call_id` (`ir/adapters/openai-responses.ts`
263
+ * `responsesCallId`). The value arriving here is NOT ours: a chat client owns
264
+ * `tool_calls[].id`, and the cursor-gateway agent loop re-injects the id the
265
+ * PREVIOUS upstream minted (`plugins/cursor-gateway/protocols/agent-v1-run.ts`
266
+ * `tc.id`), so a cascade that starts on a verbose provider and lands on a
267
+ * Responses-compatible one replays an id the new upstream never issued. Such
268
+ * upstreams field-validate this string and answer 400 — a breach is silent to
269
+ * the client (it sees an opaque failure of its own agent loop) and unfixable
270
+ * from the client side, because nothing about the payload is wrong.
271
+ *
272
+ * 64 is the strictest bound of that family we have evidence for. The digest
273
+ * written in its place is EXACTLY this wide (`sha256` hex is 64 chars), so the
274
+ * rewrite never truncates the digest and injectivity rests on the hash, not on
275
+ * a hand-picked slice length. Ids already inside the budget are passed through
276
+ * byte-identical — see the projection invariant on `responsesCallId`.
277
+ */
278
+ export const RESPONSES_CALL_ID_MAX_LEN = 64;
279
+ /**
280
+ * Request-body admission cap for inference traffic, ONE value for BOTH legs:
281
+ * the native Fastify routes (route `bodyLimit`) and the MITM/node-http leg
282
+ * (`surfaces/transport-node-http.ts` reads it, `forward-proxy/h2-forward.ts`
283
+ * bounds its h2 preface buffer with it). 32 MiB — the value ADR-0008 documents
284
+ * for the proxy, and the ceiling a 2M-token context plus base64 attachments
285
+ * needs (an agent upload of several MB is normal traffic here, and the capture
286
+ * plane is already sized for 16 MB bodies untruncated).
287
+ *
288
+ * WHY IT IS NOT `DEFAULT_MAX_BODY_BYTES`: that constant is the capture
289
+ * truncation window and is operator-tunable (`requestCapture.maxBodyBytes`).
290
+ * Wiring an admission gate to a storage cap means raising what the operator is
291
+ * willing to RECORD silently changes what the gateway is willing to SERVE —
292
+ * two independent policies that must never share a number.
293
+ */
294
+ export const GATEWAY_MAX_BODY_BYTES = 32 * 1024 * 1024;
295
+ /**
296
+ * Request-body admission cap for the ADMIN plane (console/API routes), applied as
297
+ * the Fastify INSTANCE default in `server.ts` — that placement is the point:
298
+ * Fastify's own instance default is 1 MiB, and a route that forgets to declare a
299
+ * limit silently inherits it. `POST /api/admin/config/raw` is exactly such a
300
+ * route: its body is the WHOLE `config.yaml` as a string, so an operator with a
301
+ * large config got `413 "Payload Too Large"` from the framework, in an envelope the
302
+ * console could not even name.
303
+ *
304
+ * 8 MiB, deliberately NOT `GATEWAY_MAX_BODY_BYTES`: a config, preset, rule set or
305
+ * harness manifest is kilobytes-to-low-megabytes, and the ceiling a client can
306
+ * push at the model plane has no business applying to the control plane. Keeping
307
+ * the tiers separate is what makes the answer to "why did that request get 413?"
308
+ * explainable. Bodies that really are big already declare their own cap per route
309
+ * (`IMPORT_BODY_LIMIT_BYTES`, `PLUGIN_PACKAGE_MAX_BYTES`).
310
+ */
311
+ export const ADMIN_MAX_BODY_BYTES = 8 * 1024 * 1024;
312
+ /**
313
+ * Bounds for the operator-tunable admission caps (`client.bodyLimits`), enforced by
314
+ * the config cleaner so a typo cannot turn the gateway into a memory sponge or
315
+ * make it refuse traffic it can no longer serve.
316
+ *
317
+ * 64 KiB floor: below that even a modest chat request with a short system prompt is
318
+ * rejected, so a smaller number is always a mistake rather than a policy.
319
+ * 512 MiB ceiling: 16x the shipped inference default. The cap is what a request may
320
+ * hold IN MEMORY while it is admitted, so the ceiling is a durability limit on the
321
+ * gateway itself, not a statement about models; an operator who genuinely needs
322
+ * more than this is describing a different product (streaming spooling), not a
323
+ * config value.
324
+ */
325
+ export const BODY_LIMIT_MIN_BYTES = 64 * 1024;
326
+ export const BODY_LIMIT_MAX_BYTES = 512 * 1024 * 1024;
260
327
  /** Forward-proxy hang protection: upstream socket timeout applied until
261
328
  * response headers arrive (blackholed-peer guard). */
262
329
  export const FORWARD_PROXY_HANG_TIMEOUT_MS = 60_000;
330
+ /**
331
+ * INBOUND liveness bounds, declared once and SET EXPLICITLY on every listener the
332
+ * gateway owns. Leaving them to the runtime is not a neutral choice: Node ships
333
+ * `requestTimeout` 300s / `headersTimeout` 60s / `keepAliveTimeout` 5s, Bun ships
334
+ * none of them, so the same slow or half-open client holds a socket forever on one
335
+ * runtime and is reaped on the other. That is the same class of bug as the original
336
+ * 413 — an invisible runtime default deciding gateway policy (here: which clients
337
+ * get served) — so the values are named, and they match Node's shipped numbers
338
+ * deliberately: on Node this changes nothing, it makes the behavior on Bun the
339
+ * behavior on Node instead of undefined.
340
+ *
341
+ * `REQUEST_BODY_IDLE_TIMEOUT_MS` is the bound the server-level timeouts cannot
342
+ * express: `requestTimeout` measures the WHOLE request, so a client that trickles
343
+ * one byte per minute never trips it on either runtime. This one is armed per chunk
344
+ * in `readRequestBody`, so a stalled upload is refused with 408 while the ceiling
345
+ * still guards the size axis.
346
+ */
347
+ export const SERVER_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
348
+ export const SERVER_HEADERS_TIMEOUT_MS = 60_000;
349
+ export const SERVER_KEEP_ALIVE_TIMEOUT_MS = 5_000;
350
+ export const REQUEST_BODY_IDLE_TIMEOUT_MS = 60_000;
263
351
  /** Forward-proxy tunnel keepalive: TCP probe interval armed on both sides of
264
352
  * every relayed connection (blind tunnels and `Upgrade:` relays). There is no
265
353
  * application-level idle timeout — a tunnel may legitimately carry a silent
@@ -293,3 +381,12 @@ export const CREDENTIAL_WEIGHT_MAX = 100;
293
381
  /** Plugin package (.zip) upload cap — route bodyLimit and the handler's
294
382
  * 413 check both read this so they can never desync. */
295
383
  export const PLUGIN_PACKAGE_MAX_BYTES = 64 * 1024 * 1024;
384
+ /**
385
+ * Follow-catalog auto-resync debounce (event-driven, not a poll).
386
+ * Key-policy edits coalesce quickly; pool rebuilds (catalog auto-pull storms)
387
+ * wait longer so one rewrite covers a burst of defs/credential mutations.
388
+ */
389
+ export const FOLLOW_CATALOG_KEY_DEBOUNCE_MS = 300;
390
+ export const FOLLOW_CATALOG_POOL_DEBOUNCE_MS = 2_000;
391
+ /** Default for `client.autoResyncFollowCatalogs` — lazy-operator default ON. */
392
+ export const DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS = true;
@@ -1,4 +1,4 @@
1
- import type { ProxyConfig, RateLimitConfig, RouterConfig, WebAuthConfig } from './types.js';
1
+ import type { BodyLimitsConfig, ProxyConfig, RateLimitConfig, RouterConfig, WebAuthConfig } from './types.js';
2
2
  import { getRuntimeConfigRef, registerRuntimeConfigRef } from './runtime.js';
3
3
  export { getRuntimeConfigRef, registerRuntimeConfigRef };
4
4
  /**
@@ -44,6 +44,20 @@ export declare function sanitizeWebAuthInput(input: unknown): WebAuthConfig | un
44
44
  * doctrine as resolveRequestCapture). `persist.enabled` defaults to true —
45
45
  * only an explicit `false` disables the ledger store. Exported for tests.
46
46
  */
47
+ /**
48
+ * Resolve the `client.bodyLimits` tree (ADR-0008) — the two request-body
49
+ * admission caps. `clampRange` is the same trust-boundary cleaner the grace
50
+ * window uses: a cap is a MEMORY promise the gateway makes for every in-flight
51
+ * request, so junk (string, NaN, negative) falls back to the shipped default and
52
+ * an absurd number is clamped to `BODY_LIMIT_MIN_BYTES`..`BODY_LIMIT_MAX_BYTES`
53
+ * instead of being honoured. Both bounds and the two defaults come from
54
+ * defaults.ts -- never re-declared here.
55
+ *
56
+ * Both members are always present on the resolved object: a partial file must not
57
+ * turn the other plane's cap undefined, and the boot-time installer
58
+ * (`surfaces/body-admission.ts`) treats undefined as "use the default" anyway.
59
+ */
60
+ export declare function resolveBodyLimits(parsed: any): BodyLimitsConfig;
47
61
  export declare function resolveRateLimit(parsed: any): RateLimitConfig;
48
62
  /** The one rule-type whitelist: the sanitizer validates against it, the
49
63
  * subscription importer maps against it, and the console offers exactly it.
@@ -8,7 +8,7 @@ import { EFFORT_LADDER } from '../types/router.js';
8
8
  import { resolveDirectivePrefix } from '../pipeline/directives.js';
9
9
  import { missingNodeCredential, sanitizeTypedNode } from '../proxy/manual-node-spec.js';
10
10
  import { ensureEnvScaffold, getEnvPaths, resolveEnvName } from './env.js';
11
- import { DEFAULT_FORWARD_PROXY_PORT, DEFAULT_FORWARD_PROXY_HOST, DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, DEFAULT_FORWARD_PROXY_RULES, DEFAULT_FORWARD_PROXY_INTERCEPT, FORWARD_PROXY_MAX_CONNECTIONS_MIN, FORWARD_PROXY_MAX_CONNECTIONS_MAX, DEFAULT_PROXY_ACCESS_LOG_PERSIST_DAYS, PROXY_ACCESS_LOG_PERSIST_DAYS_MIN, PROXY_ACCESS_LOG_PERSIST_DAYS_MAX, DEFAULT_HEADROOM_TIMEOUT_MS, DEFAULT_DIRECTIVE_PREFIX, DEFAULT_HEADROOM_URL, DEFAULT_LAYER2_EFFORT_FLOOR, DEFAULT_LAYER2_TIMEOUT_MS, DEFAULT_MAX_BODY_BYTES, DEFAULT_ROUTE_ENTRIES_MAX, DEFAULT_GATEWAY_PORT, DEFAULT_MIHOMO_CONTROLLER_PORT, DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MIXED_PORT, DEFAULT_MIHOMO_SUB_INTERVAL_SEC, MIHOMO_SUB_INTERVAL_MAX_SEC, MIHOMO_SUB_INTERVAL_MIN_SEC, MIHOMO_GROUP_INTERVAL_MAX_SEC, MIHOMO_GROUP_INTERVAL_MIN_SEC, DEFAULT_MIHOMO_GROUP_TOLERANCE_MS, MIHOMO_GROUP_TOLERANCE_MAX_MS, DEFAULT_MIHOMO_TEST_URL, MIHOMO_LAN_DIRECT_RULES, } from './defaults.js';
11
+ import { DEFAULT_FORWARD_PROXY_PORT, DEFAULT_FORWARD_PROXY_HOST, DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, DEFAULT_FORWARD_PROXY_RULES, DEFAULT_FORWARD_PROXY_INTERCEPT, FORWARD_PROXY_MAX_CONNECTIONS_MIN, FORWARD_PROXY_MAX_CONNECTIONS_MAX, DEFAULT_PROXY_ACCESS_LOG_PERSIST_DAYS, PROXY_ACCESS_LOG_PERSIST_DAYS_MIN, PROXY_ACCESS_LOG_PERSIST_DAYS_MAX, DEFAULT_HEADROOM_TIMEOUT_MS, DEFAULT_DIRECTIVE_PREFIX, DEFAULT_HEADROOM_URL, DEFAULT_LAYER2_EFFORT_FLOOR, DEFAULT_LAYER2_TIMEOUT_MS, DEFAULT_MAX_BODY_BYTES, GATEWAY_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES, BODY_LIMIT_MIN_BYTES, BODY_LIMIT_MAX_BYTES, DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS, DEFAULT_ROUTE_ENTRIES_MAX, DEFAULT_GATEWAY_PORT, DEFAULT_MIHOMO_CONTROLLER_PORT, DEFAULT_MIHOMO_GROUP, DEFAULT_MIHOMO_MIXED_PORT, DEFAULT_MIHOMO_SUB_INTERVAL_SEC, MIHOMO_SUB_INTERVAL_MAX_SEC, MIHOMO_SUB_INTERVAL_MIN_SEC, MIHOMO_GROUP_INTERVAL_MAX_SEC, MIHOMO_GROUP_INTERVAL_MIN_SEC, DEFAULT_MIHOMO_GROUP_TOLERANCE_MS, MIHOMO_GROUP_TOLERANCE_MAX_MS, DEFAULT_MIHOMO_TEST_URL, MIHOMO_LAN_DIRECT_RULES, } from './defaults.js';
12
12
  import { getRateLimiter } from '../ratelimit/rate-limiter.js';
13
13
  import { getQuotaProber } from '../quota/prober.js';
14
14
  import { migrateConfig, toDiskConfig, toRuntimeConfig, SCHEMA_VERSION } from './schema.js';
@@ -201,6 +201,16 @@ const DEFAULT_CONFIG = {
201
201
  inboundGraceMs: DEFAULT_INBOUND_GRACE_MS,
202
202
  persist: { enabled: true },
203
203
  },
204
+ // The shipped admission caps live in defaults.ts as the single source; this is
205
+ // the config face of the same two numbers (ADR-0008). A file with no
206
+ // `client.bodyLimits` therefore keeps exactly the pre-knob behavior.
207
+ bodyLimits: {
208
+ maxBytes: GATEWAY_MAX_BODY_BYTES,
209
+ adminMaxBytes: ADMIN_MAX_BODY_BYTES,
210
+ },
211
+ // Follow-catalog auto-resync: default ON (lazy-operator default). Hot-read
212
+ // by the sync module — unlike bodyLimits, no restart required.
213
+ autoResyncFollowCatalogs: DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS,
204
214
  // Two axes (ADR-0008 §1): `allow` streams only when the caller asks;
205
215
  // `stream` keeps the provider leg on the upstream SSE reader even for JSON
206
216
  // callers — TTFT/stall measurement on by default, client timing unchanged.
@@ -575,6 +585,27 @@ function resolveCircuitBreaker(parsed) {
575
585
  * doctrine as resolveRequestCapture). `persist.enabled` defaults to true —
576
586
  * only an explicit `false` disables the ledger store. Exported for tests.
577
587
  */
588
+ /**
589
+ * Resolve the `client.bodyLimits` tree (ADR-0008) — the two request-body
590
+ * admission caps. `clampRange` is the same trust-boundary cleaner the grace
591
+ * window uses: a cap is a MEMORY promise the gateway makes for every in-flight
592
+ * request, so junk (string, NaN, negative) falls back to the shipped default and
593
+ * an absurd number is clamped to `BODY_LIMIT_MIN_BYTES`..`BODY_LIMIT_MAX_BYTES`
594
+ * instead of being honoured. Both bounds and the two defaults come from
595
+ * defaults.ts -- never re-declared here.
596
+ *
597
+ * Both members are always present on the resolved object: a partial file must not
598
+ * turn the other plane's cap undefined, and the boot-time installer
599
+ * (`surfaces/body-admission.ts`) treats undefined as "use the default" anyway.
600
+ */
601
+ export function resolveBodyLimits(parsed) {
602
+ const raw = (parsed?.bodyLimits ?? {});
603
+ const base = DEFAULT_CONFIG.bodyLimits;
604
+ return {
605
+ maxBytes: clampRange(raw.maxBytes, BODY_LIMIT_MIN_BYTES, BODY_LIMIT_MAX_BYTES, base.maxBytes),
606
+ adminMaxBytes: clampRange(raw.adminMaxBytes, BODY_LIMIT_MIN_BYTES, BODY_LIMIT_MAX_BYTES, base.adminMaxBytes),
607
+ };
608
+ }
578
609
  export function resolveRateLimit(parsed) {
579
610
  const raw = (parsed?.rateLimit ?? {});
580
611
  const v = raw.inboundGraceMs;
@@ -1106,6 +1137,9 @@ export function loadConfig(configPath) {
1106
1137
  tracePersist: { ...DEFAULT_CONFIG.tracePersist, ...flat.tracePersist },
1107
1138
  circuitBreaker: resolveCircuitBreaker(flat),
1108
1139
  rateLimit: resolveRateLimit(flat),
1140
+ bodyLimits: resolveBodyLimits(flat),
1141
+ // Explicit false disables; absent / junk / true → shipped default ON.
1142
+ autoResyncFollowCatalogs: flat.autoResyncFollowCatalogs === false ? false : DEFAULT_AUTO_RESYNC_FOLLOW_CATALOGS,
1109
1143
  retry: {
1110
1144
  enabled: flat.retry?.enabled ?? DEFAULT_CONFIG.retry?.enabled,
1111
1145
  inplace: { ...DEFAULT_CONFIG.retry?.inplace, ...flat.retry?.inplace },
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Migration v4 → v5 (ADR-0008) — body admission becomes operator-tunable.
3
+ *
4
+ * schemaVersion 4 hard-wired the request-body ceilings to the constants in
5
+ * `config/defaults.ts`: nothing on either HTTP plane read config for admission,
6
+ * so an operator who needed a bigger cap (a 40 MB agent upload) or a smaller one
7
+ * (a memory-constrained box) had no lever — and, worse, no way to *see* the
8
+ * number the gateway would answer with short of triggering a 413. v5 adds
9
+ * `client.bodyLimits`, the disk home for the two per-plane caps.
10
+ *
11
+ * The step MOVES NOTHING and RENAMES NOTHING: `migrate` is the identity, exactly
12
+ * like the v3→v4 layout row. It exists because the layout tables are frozen
13
+ * per version and `toDiskConfigWith` / `toRuntimeConfigWith` iterate ONLY the
14
+ * rows of the bound table — a new disk path that is not a row is silently dropped
15
+ * in both directions (never persisted, never loaded, and therefore never able to
16
+ * re-persist). Appending the row here is what makes the knob real; bumping
17
+ * `SCHEMA_VERSION` is what makes a saved file declare the layout it was written
18
+ * under. No v4 key disappears, so a v4 file keeps every value it had.
19
+ *
20
+ * FROZEN after release: later schema versions MUST NOT edit this file — the chain
21
+ * v0→…→v4→v5→… only appends. schema.ts binds `SECTION_MOVES_V5` as the CURRENT
22
+ * layout (see LATEST_LAYOUT there) — bump that pointer when v6 ships.
23
+ */
24
+ import { type DiskConfigV4 } from './v3-to-v4.js';
25
+ import type { BodyLimitsConfig } from '../types.js';
26
+ import type { SectionMove } from '../layout.js';
27
+ import type { Migration } from '../schema.js';
28
+ /** THE v5 layout: the v4 moves plus the new admission-cap section. */
29
+ export declare const SECTION_MOVES_V5: ReadonlyArray<SectionMove>;
30
+ /** Disk format of schemaVersion 5: v4 with `client.bodyLimits` available. */
31
+ export type DiskConfigV5 = DiskConfigV4 & {
32
+ client?: DiskConfigV4['client'] & {
33
+ bodyLimits?: BodyLimitsConfig;
34
+ };
35
+ };
36
+ export declare const migrationV4ToV5: Migration;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Migration v4 → v5 (ADR-0008) — body admission becomes operator-tunable.
3
+ *
4
+ * schemaVersion 4 hard-wired the request-body ceilings to the constants in
5
+ * `config/defaults.ts`: nothing on either HTTP plane read config for admission,
6
+ * so an operator who needed a bigger cap (a 40 MB agent upload) or a smaller one
7
+ * (a memory-constrained box) had no lever — and, worse, no way to *see* the
8
+ * number the gateway would answer with short of triggering a 413. v5 adds
9
+ * `client.bodyLimits`, the disk home for the two per-plane caps.
10
+ *
11
+ * The step MOVES NOTHING and RENAMES NOTHING: `migrate` is the identity, exactly
12
+ * like the v3→v4 layout row. It exists because the layout tables are frozen
13
+ * per version and `toDiskConfigWith` / `toRuntimeConfigWith` iterate ONLY the
14
+ * rows of the bound table — a new disk path that is not a row is silently dropped
15
+ * in both directions (never persisted, never loaded, and therefore never able to
16
+ * re-persist). Appending the row here is what makes the knob real; bumping
17
+ * `SCHEMA_VERSION` is what makes a saved file declare the layout it was written
18
+ * under. No v4 key disappears, so a v4 file keeps every value it had.
19
+ *
20
+ * FROZEN after release: later schema versions MUST NOT edit this file — the chain
21
+ * v0→…→v4→v5→… only appends. schema.ts binds `SECTION_MOVES_V5` as the CURRENT
22
+ * layout (see LATEST_LAYOUT there) — bump that pointer when v6 ships.
23
+ */
24
+ import { SECTION_MOVES_V4 } from './v3-to-v4.js';
25
+ /** THE v5 layout: the v4 moves plus the new admission-cap section. */
26
+ export const SECTION_MOVES_V5 = [
27
+ ...SECTION_MOVES_V4,
28
+ ['client.bodyLimits', 'bodyLimits'],
29
+ ];
30
+ export const migrationV4ToV5 = {
31
+ from: 4,
32
+ to: 5,
33
+ warn: [
34
+ 'schemaVersion 5 adds client.bodyLimits (maxBytes | adminMaxBytes): the request-body admission caps per HTTP plane, previously fixed constants (ADR-0008)',
35
+ ],
36
+ // Nothing moved, so nothing to rewrite. The identity is deliberate: reading the
37
+ // tree to "helpfully" materialise `client: {}` on files that never had a
38
+ // `client` section would add noise the writer does not need (the section is
39
+ // created on the first real save) and break the migrate-idempotence contract
40
+ // the migration tests pin.
41
+ migrate: (raw) => ({ ...raw }),
42
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Migration v5 → v6 — follow-catalog auto-resync kill switch.
3
+ *
4
+ * schemaVersion 5 had no operator lever for whether Key/pool mutations rewrite
5
+ * follow-mode client catalogs. v6 adds `client.autoResyncFollowCatalogs` (default
6
+ * ON): an event-driven N-setup service keyed by clientProfileMemory.modelMode
7
+ * and gateway modelListMode=follow — not a profile write-through (ADR-0031).
8
+ *
9
+ * The step MOVES NOTHING and RENAMES NOTHING: `migrate` is the identity. The
10
+ * layout row is what makes the knob persist; bumping SCHEMA_VERSION declares
11
+ * the layout the file was written under.
12
+ *
13
+ * FROZEN after release: later schema versions MUST NOT edit this file — the
14
+ * chain only appends. schema.ts binds SECTION_MOVES_V6 as the CURRENT layout.
15
+ */
16
+ import { type DiskConfigV5 } from './v4-to-v5.js';
17
+ import type { SectionMove } from '../layout.js';
18
+ import type { Migration } from '../schema.js';
19
+ /** THE v6 layout: the v5 moves plus the follow-catalog auto-resync switch. */
20
+ export declare const SECTION_MOVES_V6: ReadonlyArray<SectionMove>;
21
+ /** Disk format of schemaVersion 6: v5 with the auto-resync switch available. */
22
+ export type DiskConfigV6 = DiskConfigV5 & {
23
+ client?: DiskConfigV5['client'] & {
24
+ autoResyncFollowCatalogs?: boolean;
25
+ };
26
+ };
27
+ export declare const migrationV5ToV6: Migration;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Migration v5 → v6 — follow-catalog auto-resync kill switch.
3
+ *
4
+ * schemaVersion 5 had no operator lever for whether Key/pool mutations rewrite
5
+ * follow-mode client catalogs. v6 adds `client.autoResyncFollowCatalogs` (default
6
+ * ON): an event-driven N-setup service keyed by clientProfileMemory.modelMode
7
+ * and gateway modelListMode=follow — not a profile write-through (ADR-0031).
8
+ *
9
+ * The step MOVES NOTHING and RENAMES NOTHING: `migrate` is the identity. The
10
+ * layout row is what makes the knob persist; bumping SCHEMA_VERSION declares
11
+ * the layout the file was written under.
12
+ *
13
+ * FROZEN after release: later schema versions MUST NOT edit this file — the
14
+ * chain only appends. schema.ts binds SECTION_MOVES_V6 as the CURRENT layout.
15
+ */
16
+ import { SECTION_MOVES_V5 } from './v4-to-v5.js';
17
+ /** THE v6 layout: the v5 moves plus the follow-catalog auto-resync switch. */
18
+ export const SECTION_MOVES_V6 = [
19
+ ...SECTION_MOVES_V5,
20
+ ['client.autoResyncFollowCatalogs', 'autoResyncFollowCatalogs'],
21
+ ];
22
+ export const migrationV5ToV6 = {
23
+ from: 5,
24
+ to: 6,
25
+ warn: [
26
+ 'schemaVersion 6 adds client.autoResyncFollowCatalogs (default true): event-driven rewrite of follow-mode client/gateway catalogs after Key modelAccess or model-pool changes',
27
+ ],
28
+ migrate: (raw) => ({ ...raw }),
29
+ };
@@ -1,8 +1,8 @@
1
- import { type DiskConfigV4 } from './migrations/v3-to-v4.js';
1
+ import { type DiskConfigV6 } from './migrations/v5-to-v6.js';
2
2
  import type { RouterConfig } from './types.js';
3
- export declare const SCHEMA_VERSION = 4;
3
+ export declare const SCHEMA_VERSION = 6;
4
4
  /** The current disk type — re-exported from the LATEST version's file. */
5
- export type DiskConfig = DiskConfigV4;
5
+ export type DiskConfig = DiskConfigV6;
6
6
  export interface Migration {
7
7
  from: number;
8
8
  to: number;
@@ -31,14 +31,16 @@
31
31
  import { legacySurfaceWarnings, migrationV0ToV1 } from './migrations/v0-to-v1.js';
32
32
  import { migrationV1ToV2 } from './migrations/v1-to-v2.js';
33
33
  import { migrationV2ToV3 } from './migrations/v2-to-v3.js';
34
- import { migrationV3ToV4, SECTION_MOVES_V4 } from './migrations/v3-to-v4.js';
34
+ import { migrationV3ToV4 } from './migrations/v3-to-v4.js';
35
+ import { migrationV4ToV5 } from './migrations/v4-to-v5.js';
36
+ import { migrationV5ToV6, SECTION_MOVES_V6 } from './migrations/v5-to-v6.js';
35
37
  import { toDiskConfigWith, toRuntimeConfigWith, toRuntimePathWith, } from './layout.js';
36
- export const SCHEMA_VERSION = 4;
38
+ export const SCHEMA_VERSION = 6;
37
39
  /**
38
- * The CURRENT layout pointer. Bump to `SECTION_MOVES_V4` (etc.) when the
40
+ * The CURRENT layout pointer. Bump to `SECTION_MOVES_V6` (etc.) when the
39
41
  * newest migration file ships — the single edit a new version makes here.
40
42
  */
41
- const LATEST_LAYOUT = SECTION_MOVES_V4;
43
+ const LATEST_LAYOUT = SECTION_MOVES_V6;
42
44
  /**
43
45
  * The evolution chain — assembled IN ORDER from the per-version files.
44
46
  * v0 = a config.yaml without `schemaVersion` (every file authored before
@@ -49,6 +51,8 @@ const MIGRATIONS = [
49
51
  migrationV1ToV2,
50
52
  migrationV2ToV3,
51
53
  migrationV3ToV4,
54
+ migrationV4ToV5,
55
+ migrationV5ToV6,
52
56
  ];
53
57
  /** Runtime flat config → current-version disk shape. */
54
58
  export function toDiskConfig(flat) {
@@ -71,9 +71,16 @@ export interface ModelRegistration {
71
71
  * `tiers[t].members` list claims, full stop.
72
72
  */
73
73
  pricing?: ModelPricing;
74
- /** Resolved wire for direct execution (model-level npm beats provider npm).
75
- * Core shapes plus PLUGIN-owned wire ids — the plugin half is open-ended,
76
- * filled from the loaded plugin manifests (`providers/plugin-wires.ts`). */
74
+ /**
75
+ * Ordered outbound protocol set (ADR-0033 prefer-native dial). Boot resolves
76
+ * model override → catalog model → def → catalog provider into this list; the
77
+ * per-attempt dialer (`providers/dial-wire.ts`) picks ONE id from it, and
78
+ * `wire` below is the boot primary (first entry) it falls back to.
79
+ * Core shapes plus PLUGIN-owned ids — the plugin half is open-ended, filled
80
+ * from the loaded plugin manifests (`providers/plugin-wires.ts`). */
81
+ protocols?: string[];
82
+ /** Resolved boot-primary wire for direct execution (`protocols[0]`; model
83
+ * declaration beats provider declaration). */
77
84
  wire?: WireKind;
78
85
  priority?: number;
79
86
  isDefaultInTier?: boolean;
@@ -1113,6 +1120,37 @@ export interface RateLimitPersistConfig {
1113
1120
  */
1114
1121
  enabled?: boolean;
1115
1122
  }
1123
+ /**
1124
+ * Body-admission caps for the two HTTP planes, operator-tunable (disk
1125
+ * `client.bodyLimits`). Boot-frozen: Fastify reads a route's `bodyLimit` at
1126
+ * REGISTRATION time, so a new value applies on the next controlled restart
1127
+ * (ADR-0007), never mid-flight — which is also what makes an in-flight request
1128
+ * impossible to police twice under two different numbers.
1129
+ *
1130
+ * These are the ceilings the gateway AGREES TO HOLD IN MEMORY for one request,
1131
+ * measured on the DECOMPRESSED body (an `gzip` bomb is admission-sized by what it
1132
+ * inflates to, not by what it arrived as). Not the capture archive's truncation
1133
+ * window (`requestCapture.maxBodyBytes` — what is RECORDED), and not a statement
1134
+ * about what a model can read: a request that fits the cap can still exceed a
1135
+ * model's context, and that is the model's error to return.
1136
+ */
1137
+ export interface BodyLimitsConfig {
1138
+ /**
1139
+ * Inference plane (`/v1/*` — chat, responses, anthropic, systemone + the MITM
1140
+ * and h2 forward legs, which share the one number). Default
1141
+ * `GATEWAY_MAX_BODY_BYTES`; sized for a multi-million-token context plus base64
1142
+ * attachments. Every admin upload route keeps its own declared cap and is never
1143
+ * lowered by this value.
1144
+ */
1145
+ maxBytes?: number;
1146
+ /**
1147
+ * Control plane (every other `/api/*` route, as the Fastify INSTANCE default —
1148
+ * the placement that stops a route which forgets to declare a limit from
1149
+ * silently inheriting framework default). Default `ADMIN_MAX_BODY_BYTES`, the
1150
+ * number `POST /api/admin/config/raw` needs to send a whole `config.yaml`.
1151
+ */
1152
+ adminMaxBytes?: number;
1153
+ }
1116
1154
  export interface RateLimitConfig {
1117
1155
  /**
1118
1156
  * Bounded grace wait in ms: when an inbound denial reopens its window
@@ -1189,6 +1227,19 @@ export interface RouterConfig {
1189
1227
  retry?: RetryConfig;
1190
1228
  /** Rate-limit policy (see RateLimitConfig); the windows themselves live in `apiKeys[].limits` / `credentials:`. */
1191
1229
  rateLimit?: RateLimitConfig;
1230
+ /**
1231
+ * Body-admission caps for both planes (see BodyLimitsConfig; disk
1232
+ * `client.bodyLimits`). Absent = the shipped defaults in `config/defaults.ts`.
1233
+ * Boot-frozen — applied when the routes are registered.
1234
+ */
1235
+ bodyLimits?: BodyLimitsConfig;
1236
+ /**
1237
+ * When true (default), Key `modelAccess` / model-pool mutations event-drive a
1238
+ * rewrite of every hooked follow-mode client catalog and every gateway
1239
+ * plugin with `modelListMode=follow` (disk `client.autoResyncFollowCatalogs`).
1240
+ * Hot-readable — no restart. Not a profile write-through (ADR-0031).
1241
+ */
1242
+ autoResyncFollowCatalogs?: boolean;
1192
1243
  models?: ModelRegistration[];
1193
1244
  combos?: ComboConfig[];
1194
1245
  /**
@@ -86,6 +86,11 @@ const HOP_BY_HOP = {
86
86
  trailer: true,
87
87
  'transfer-encoding': true,
88
88
  upgrade: true,
89
+ // RFC 9110 7.6.1 lists `Expect` as hop-by-hop, and 10.1 makes it a demand on
90
+ // THIS recipient: the gateway has already consumed (or refused) the body, so a
91
+ // live `Expect: 100-continue` reaching the origin would make it wait for bytes
92
+ // that will never arrive. Node's own http agent strips the same field.
93
+ expect: true,
89
94
  };
90
95
  export function filterHeaders(headers) {
91
96
  const out = {};
@@ -99,6 +104,14 @@ export function filterHeaders(headers) {
99
104
  continue;
100
105
  if (HOP_BY_HOP[k.toLowerCase()])
101
106
  continue;
107
+ // An AMBIGUOUS `Content-Length` is never relayed (RFC 9112 6.3: a proxy must
108
+ // not forward a message whose framing it cannot determine). Bun accepts a
109
+ // duplicated CL and hands the app an array, so the value that reached us is
110
+ // already unrepresentable on the wire — dropping it lets the outbound client
111
+ // re-frame from the bytes it actually writes. A single well-formed value is
112
+ // kept: it is end-to-end, not hop-by-hop.
113
+ if (k.toLowerCase() === 'content-length' && (Array.isArray(v) || !/^\d+$/.test(v)))
114
+ continue;
102
115
  out[k] = v;
103
116
  }
104
117
  return out;
@@ -1,6 +1,7 @@
1
1
  import http2 from 'node:http2';
2
2
  import tls from 'node:tls';
3
- import { DEFAULT_MAX_BODY_BYTES, FORWARD_PROXY_HANG_TIMEOUT_MS, FORWARD_PROXY_KEEPALIVE_MS } from '../config/defaults.js';
3
+ import { FORWARD_PROXY_HANG_TIMEOUT_MS, FORWARD_PROXY_KEEPALIVE_MS } from '../config/defaults.js';
4
+ import { bodyTooLargeMessage, bodyLimitFor } from '../surfaces/body-admission.js';
4
5
  import { describeUpstreamFailure, openViaProxy, transitEgressFor, transitProxyFor, upstreamServernameOption, } from './egress.js';
5
6
  /**
6
7
  * Hop-by-hop headers that must never cross a proxy hop. `te` and `trailer` are
@@ -347,7 +348,7 @@ export async function forwardH2(req, res, t, upstreamTls) {
347
348
  const onBody = (chunk) => {
348
349
  if (!upstreamStream || pumping || queueHead < queue.length) {
349
350
  queuedBytes += chunk.length;
350
- if (queuedBytes > DEFAULT_MAX_BODY_BYTES) {
351
+ if (queuedBytes > bodyLimitFor('gateway')) {
351
352
  overflow = true;
352
353
  req.destroy();
353
354
  return;
@@ -391,7 +392,7 @@ export async function forwardH2(req, res, t, upstreamTls) {
391
392
  if (!session) {
392
393
  // h1 upstreams cannot carry bidi: drain the bounded body, then hand a
393
394
  // complete preface to the h1 leg. The timeout is the proxy's hang guard;
394
- // the 16 MB cap prevents buffering an unbounded upload.
395
+ // the gateway body cap prevents buffering an unbounded upload.
395
396
  if (!heldEnd && !overflow) {
396
397
  let timer;
397
398
  await Promise.race([
@@ -406,7 +407,7 @@ export async function forwardH2(req, res, t, upstreamTls) {
406
407
  req.removeListener('end', onBodyEnd);
407
408
  req.removeListener('close', resolveEnd);
408
409
  if (overflow) {
409
- failPlain(res, 413, `Forward proxy: request body exceeds ${DEFAULT_MAX_BODY_BYTES} bytes on an h1 upstream`);
410
+ failPlain(res, 413, bodyTooLargeMessage(bodyLimitFor('gateway')) + ' (h1 upstream)');
410
411
  return { owned: true };
411
412
  }
412
413
  if (!heldEnd) {
@@ -416,7 +417,7 @@ export async function forwardH2(req, res, t, upstreamTls) {
416
417
  return { owned: false, ...(queue.length ? { preface: { chunks: queue, ended: true } } : {}) };
417
418
  }
418
419
  if (overflow) {
419
- failPlain(res, 413, `Forward proxy: request body exceeds ${DEFAULT_MAX_BODY_BYTES} bytes`);
420
+ failPlain(res, 413, bodyTooLargeMessage(bodyLimitFor('gateway')));
420
421
  return { owned: true };
421
422
  }
422
423
  const entry = pool.get(key);
@@ -8,6 +8,7 @@ import { isApiKeyUsable } from '../auth/api-keys.js';
8
8
  import { createForwardProxyServer } from './server.js';
9
9
  import { createProxyInterceptor } from './interceptor.js';
10
10
  import { setGatewayChatServices, buildGatewayChatServices } from '../surfaces/gateway-chat.js';
11
+ import { detectSurface } from '../surfaces/table.js';
11
12
  import { setProxyAccessLogSettingsReader, setProxyAccessLogPersistDir, initProxyAccessLogPersistence } from './access-log.js';
12
13
  import { listGatewayHosts, WILDCARD_HOST_CLAIM } from '../plugins/gateways.js';
13
14
  import { setUpstreamTlsReader } from './upstream-tls.js';
@@ -136,6 +137,10 @@ export async function startForwardProxy(cfg, orchestrator) {
136
137
  // Hot-apply seam: rules / intercept re-read the runtime ref per
137
138
  // request, so console saves need no restart.
138
139
  liveForwardProxy: () => getRuntimeConfigRef()?.forwardProxy,
140
+ // The MITM Expect: 100-continue guard answers in the served surface's own
141
+ // envelope, so it needs the registry — passed in, not imported by server.ts
142
+ // (that import closes a load-time cycle; see ForwardProxyDeps.detectSurface).
143
+ detectSurface,
139
144
  intercept,
140
145
  log: (m) => console.log(`[ForwardProxy] ${m}`),
141
146
  });
@@ -3,6 +3,7 @@ import type { ForwardProxyConfig } from '../config/types.js';
3
3
  import { type UpstreamTlsOptions } from './upstream-tls.js';
4
4
  import type { ForwardProxyRule, InterceptPosture } from '../config/types.js';
5
5
  import { type AccessTap } from './access-log.js';
6
+ import type { ProtocolSurface } from '../surfaces/types.js';
6
7
  import { type H2UpstreamTls } from './h2-forward.js';
7
8
  export interface ForwardProxyDeps {
8
9
  port: number;
@@ -65,6 +66,17 @@ export interface ForwardProxyDeps {
65
66
  * is observable in a few connections); default MAX_HOST_TERMINATORS.
66
67
  */
67
68
  maxHostTerminators?: number;
69
+ /**
70
+ * Map a request path to the protocol surface that serves it
71
+ * (`detectSurface` from `surfaces/table.ts`). INJECTED rather than imported:
72
+ * the registry pulls the surface modules, and those reach `config/index.ts`
73
+ * → the plugin host → THIS module, so a static import here closes a load-time
74
+ * cycle — with a surface module as the entry, `table.ts` then reads
75
+ * `responsesSurface` before its own module body finished (TDZ crash). The MITM
76
+ * `Expect: 100-continue` refusal needs it only to answer in the surface's own
77
+ * envelope; unset, the expectation is honoured and the body gate decides.
78
+ */
79
+ detectSurface?: (url: string) => ProtocolSurface | null | undefined;
68
80
  }
69
81
  export interface ForwardProxyHandle {
70
82
  port: number;