omnicell-router 0.7.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -0,0 +1,33 @@
1
+ import type { ForwardProxyConfig, UnresolvedModelConfig } from '../config/types.js';
2
+ /**
3
+ * forwardProxy.unresolvedModel policy (ADR-0003): on the MITM forward-proxy
4
+ * leg, what happens when the client's `model` name matches NO registered
5
+ * model, combo, variant or tier alias — after the full bare-name resolution
6
+ * chain (exact id → variant → host-pinned upstream name → combo) has run
7
+ * and missed. The native /v1 leg NEVER consults this: a client dialing the
8
+ * gateway directly keeps the historical classifier behavior unconditionally.
9
+ *
10
+ * - `fail` : loud 404 — no invisible model drift.
11
+ * - `direct` : forward the request to the ORIGINAL destination the client
12
+ * dialed — the turn RUNS THROUGH the pipeline (normalization, zero-header
13
+ * session id, capture, compression: rtk + headroom + caveman, fail-open)
14
+ * but every model-bound stage is skipped (routing, ratchet, route-entry
15
+ * experience, breaker, failover, FinOps, turn registration) and the turn
16
+ * ends as a `DirectForwardPlan`: the transport relays the response from
17
+ * the ORIGINAL destination, original model id and the client's own
18
+ * Authorization header riding along (surfaces/direct-forward.ts).
19
+ * Loopback targets are refused (recursion guard) and degrade to `auto`.
20
+ * - any modelRef : the miss resolves to that ref — `auto`/tier alias/
21
+ * combo id/registered model id — exactly as if the client had sent it.
22
+ * `auto` IS the default: leaving `onMiss` unset and naming `auto`
23
+ * explicitly both resolve to the default cascade.
24
+ */
25
+ export type UnresolvedModelAction = 'auto' | 'fail' | 'direct' | {
26
+ ref: string;
27
+ };
28
+ /** Normalize the operator's raw YAML: trim values, lowercase host keys,
29
+ * drop empty entries. */
30
+ export declare function normalizeUnresolvedModelConfig(raw: UnresolvedModelConfig | undefined): UnresolvedModelConfig | undefined;
31
+ /** Evaluate the policy for one MITM-leg request. A `hosts` override for the
32
+ * original-dial host wins over the global `onMiss`. */
33
+ export declare function resolveUnresolvedModelAction(forwardProxy: ForwardProxyConfig | undefined, upstreamHost: string | undefined): UnresolvedModelAction;
@@ -0,0 +1,43 @@
1
+ /** Normalize the operator's raw YAML: trim values, lowercase host keys,
2
+ * drop empty entries. */
3
+ export function normalizeUnresolvedModelConfig(raw) {
4
+ if (!raw)
5
+ return undefined;
6
+ const onMiss = typeof raw.onMiss === 'string' ? raw.onMiss.trim() : undefined;
7
+ const hosts = {};
8
+ for (const [k, v] of Object.entries(raw.hosts ?? {})) {
9
+ const key = k.trim().toLowerCase();
10
+ const val = typeof v === 'string' ? v.trim() : '';
11
+ if (key && val)
12
+ hosts[key] = val;
13
+ }
14
+ return {
15
+ ...(onMiss ? { onMiss } : {}),
16
+ ...(Object.keys(hosts).length > 0 ? { hosts } : {}),
17
+ };
18
+ }
19
+ /** Evaluate the policy for one MITM-leg request. A `hosts` override for the
20
+ * original-dial host wins over the global `onMiss`. */
21
+ export function resolveUnresolvedModelAction(forwardProxy, upstreamHost) {
22
+ const cfg = forwardProxy?.unresolvedModel;
23
+ if (cfg && upstreamHost) {
24
+ // The Host header may carry a non-default port (`api.example.com:8443`);
25
+ // operator overrides are keyed by bare hostname (same normalization the
26
+ // loopback guard applies below), so strip the port suffix first.
27
+ const host = upstreamHost.trim().toLowerCase().replace(/:\d+$/, '');
28
+ const override = cfg.hosts?.[host];
29
+ if (override)
30
+ return toAction(override);
31
+ }
32
+ if (cfg?.onMiss)
33
+ return toAction(cfg.onMiss);
34
+ return 'auto';
35
+ }
36
+ function toAction(v) {
37
+ const t = v.trim();
38
+ // `auto` names the default cascade — the same value the function returns
39
+ // when no policy is configured.
40
+ if (t === 'auto' || t === 'fail' || t === 'direct')
41
+ return t;
42
+ return { ref: t };
43
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The ONE mapping from a vendor model row to the models.dev-shaped def the pull
3
+ * engine writes. Every model-service plugin feeds {@link VendorCapabilities} in
4
+ * here; none of them builds an OCR def by hand (ADR-0035).
5
+ *
6
+ * Why it exists: `qoder-models` and `workbuddy-models` each grew their own
7
+ * `xxxCatalogToDef`, and the two drifted on exactly the field that decides
8
+ * money and behaviour — `reasoningOptions`. qoder wrote a bare
9
+ * `[{type:'toggle'}]` for every reasoning model ("the catalog publishes no tier
10
+ * table"), `effortLadderFor` resolves `toggle` to `[]`, and `[]` makes
11
+ * `downgradeReasoning` collapse every requested level to `'none'` — so a
12
+ * client asking for `high` on GLM-5.4 silently got the cheapest level. The
13
+ * vendor had in fact declared `thinking_config.enabled.efforts` all along; the
14
+ * plugin just never read it. One mapper means one place to be wrong, one place
15
+ * to test, and no plugin able to re-derive the rule "wrong" on its own.
16
+ *
17
+ * Iron rules (each of them a silent, expensive bug in production):
18
+ *
19
+ * 1. An effort TABLE is the only thing that may become
20
+ * `{type:'effort',values}`. `{type:'toggle'}` is allowed ONLY when the
21
+ * vendor itself says "on/off, no levels" — a level-less toggle resolves to
22
+ * `[]` and erases the client's requested level.
23
+ * 2. Nothing is invented. `undefined` means "the vendor did not say", and the
24
+ * field is omitted. Never write `tool_call: true` / `temperature: true`
25
+ * because "probably fine": a wrong `true` makes the gateway send a
26
+ * parameter the upstream rejects.
27
+ * 3. `attachment` (models.dev boolean) and `modalities.input` (v2 spelling)
28
+ * are ONE fact and are always emitted together, driven by the same
29
+ * {@link ModalityInput} list — a vision model must never read as text-only
30
+ * in the console while the wire sends an image.
31
+ * 4. `limit.input` is the prompt-side cap (models.dev `limit.input`), distinct
32
+ * from `limit.context` (the window). Vendors that publish only a window
33
+ * leave `input` unset rather than having it inferred.
34
+ * 5. A vendor's "disabled" flag becomes `disabled: true`, so the model leaves
35
+ * the routing pool instead of being offered and failing per request.
36
+ */
37
+ import { type ReasoningEffort } from '../types/router.js';
38
+ /** models.dev `modalities.input` vocabulary — the only values the capability
39
+ * plane understands. `image|audio|video|pdf` are independent facts, so a
40
+ * vendor that documents PDF input says so here instead of being folded into
41
+ * `attachment` (which is vision only). */
42
+ export type ModalityInput = 'text' | 'image' | 'audio' | 'video' | 'pdf';
43
+ /** models.dev `modalities.output` vocabulary. */
44
+ export type ModalityOutput = 'text' | 'image' | 'audio';
45
+ /**
46
+ * One vendor row, normalized: what the vendor DECLARED, nothing else.
47
+ *
48
+ * Every capability is tri-state where the vendor's own schema is tri-state:
49
+ * `true` = declared supported, `false` = declared unsupported, `undefined` =
50
+ * the vendor said nothing (and the field is omitted from the def).
51
+ */
52
+ export interface VendorCapabilities {
53
+ /** Wire model id (qoder `key`, workbuddy `id`). */
54
+ id: string;
55
+ /** Human label. Omitted when the vendor has none — the console then renders
56
+ * the id, which is what the old `name ?? id` fallbacks did anyway. */
57
+ name?: string;
58
+ /**
59
+ * Reasoning, as the vendor declares it. Omitted entirely for a model the
60
+ * vendor does not mark as reasoning.
61
+ */
62
+ reasoning?: VendorReasoning;
63
+ /** Input modalities the vendor declared. `undefined` = no declaration, and
64
+ * the def carries no `attachment`/`modalities` at all.
65
+ *
66
+ * A vendor that only knows "can it see images" passes
67
+ * `['text','image']`; one that documents audio/pdf passes the full list. */
68
+ inputModalities?: ModalityInput[];
69
+ /** Output modalities. Omitted = text-only is NOT assumed to be declared;
70
+ * callers that know it is text pass `['text']`. */
71
+ outputModalities?: ModalityOutput[];
72
+ /** Tool calling, when the vendor declares it. */
73
+ toolCall?: boolean;
74
+ /** Temperature support, when the vendor declares it. Vendors rarely do —
75
+ * leave undefined rather than guessing. */
76
+ temperature?: boolean;
77
+ /** Structured/JSON output support (models.dev `structured_output`). */
78
+ structuredOutput?: boolean;
79
+ /** Token budgets. `context` = window, `input` = prompt cap (often absent),
80
+ * `output` = max completion. */
81
+ limit?: {
82
+ context?: number;
83
+ input?: number;
84
+ output?: number;
85
+ };
86
+ /** models.dev `cost`, USD per 1M tokens. A vendor that bills in CREDIT
87
+ * multipliers (qoder `price_factor`) must DERIVE this — factor × a measured
88
+ * base rate × the official credit→USD ratio (see
89
+ * `plugins/qoder-models/pricing.ts`) — and never write the raw factor here:
90
+ * a bare multiplier is not a dollar price and would corrupt every price
91
+ * band. Leave it absent when no dollar price can honestly be derived. */
92
+ cost?: {
93
+ input?: number;
94
+ output?: number;
95
+ cacheRead?: number;
96
+ cacheWrite?: number;
97
+ };
98
+ /** Vendor marks the row disabled/retired. */
99
+ disabled?: boolean;
100
+ /** A pinned thinking level for a model with ONE gear (see
101
+ * {@link VendorReasoning.fixedEffort}). */
102
+ interleavedField?: string;
103
+ /** Anything the vendor publishes that OCR has no vocabulary for yet, kept
104
+ * verbatim under `vendor` so a later field can be promoted without
105
+ * re-pulling. Never read by routing. */
106
+ vendor?: Record<string, unknown>;
107
+ }
108
+ /**
109
+ * The vendor's reasoning declaration, in the vocabulary vendors actually use.
110
+ *
111
+ * Three real shapes, each with a different honest answer:
112
+ * - a TABLE (`efforts`) → that exact table, plus `defaultEffort`;
113
+ * - a FIXED GEAR (one `effort`, no table) → a one-value table, so the router
114
+ * clamps to it and clients still see a thinking model;
115
+ * - ON/OFF ONLY (`disableable: true` and no efforts) → the one case a bare
116
+ * `{type:'toggle'}` is the truth;
117
+ * - THINKS ALWAYS (efforts but `disableable: false`) → the table with NO
118
+ * `none` member, which is exactly what makes `downgradeReasoning` refuse to
119
+ * emit `'none'` and what makes the wire stop sending "turn thinking off".
120
+ */
121
+ export interface VendorReasoning {
122
+ /** The vendor's level table. Values are normalized by {@link EFFORT_VALUES}. */
123
+ efforts?: string[];
124
+ /** The vendor's default level (`is_default` on an effort entry, or a pinned
125
+ * `reasoning.effort`). */
126
+ defaultEffort?: string;
127
+ /** `true` = the vendor lets thinking be turned OFF; `false` = it always
128
+ * thinks (GLM-5.4, MiniMax-M3.1); `undefined` = not stated. */
129
+ disableable?: boolean;
130
+ /** A single pinned gear for a model with no table. */
131
+ fixedEffort?: string;
132
+ }
133
+ /** Normalize a vendor level list: keep the known levels, dedupe, preserve the
134
+ * vendor's order (toOcrDef restores ladder order before publishing). */
135
+ export declare function normalizeEfforts(values: readonly string[] | undefined): ReasoningEffort[];
136
+ /**
137
+ * Build the OCR models.dev-shaped def from normalized vendor capabilities.
138
+ *
139
+ * The output feeds `host.pull.catalogToDef` (via `upsertModel`) and the defs
140
+ * file, so every field here is a real OCR vocabulary member — see
141
+ * `backend/src/opencode/catalog/types.ts` `CatalogModel`.
142
+ */
143
+ export declare function toOcrDef(caps: VendorCapabilities): Record<string, unknown>;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The ONE mapping from a vendor model row to the models.dev-shaped def the pull
3
+ * engine writes. Every model-service plugin feeds {@link VendorCapabilities} in
4
+ * here; none of them builds an OCR def by hand (ADR-0035).
5
+ *
6
+ * Why it exists: `qoder-models` and `workbuddy-models` each grew their own
7
+ * `xxxCatalogToDef`, and the two drifted on exactly the field that decides
8
+ * money and behaviour — `reasoningOptions`. qoder wrote a bare
9
+ * `[{type:'toggle'}]` for every reasoning model ("the catalog publishes no tier
10
+ * table"), `effortLadderFor` resolves `toggle` to `[]`, and `[]` makes
11
+ * `downgradeReasoning` collapse every requested level to `'none'` — so a
12
+ * client asking for `high` on GLM-5.4 silently got the cheapest level. The
13
+ * vendor had in fact declared `thinking_config.enabled.efforts` all along; the
14
+ * plugin just never read it. One mapper means one place to be wrong, one place
15
+ * to test, and no plugin able to re-derive the rule "wrong" on its own.
16
+ *
17
+ * Iron rules (each of them a silent, expensive bug in production):
18
+ *
19
+ * 1. An effort TABLE is the only thing that may become
20
+ * `{type:'effort',values}`. `{type:'toggle'}` is allowed ONLY when the
21
+ * vendor itself says "on/off, no levels" — a level-less toggle resolves to
22
+ * `[]` and erases the client's requested level.
23
+ * 2. Nothing is invented. `undefined` means "the vendor did not say", and the
24
+ * field is omitted. Never write `tool_call: true` / `temperature: true`
25
+ * because "probably fine": a wrong `true` makes the gateway send a
26
+ * parameter the upstream rejects.
27
+ * 3. `attachment` (models.dev boolean) and `modalities.input` (v2 spelling)
28
+ * are ONE fact and are always emitted together, driven by the same
29
+ * {@link ModalityInput} list — a vision model must never read as text-only
30
+ * in the console while the wire sends an image.
31
+ * 4. `limit.input` is the prompt-side cap (models.dev `limit.input`), distinct
32
+ * from `limit.context` (the window). Vendors that publish only a window
33
+ * leave `input` unset rather than having it inferred.
34
+ * 5. A vendor's "disabled" flag becomes `disabled: true`, so the model leaves
35
+ * the routing pool instead of being offered and failing per request.
36
+ */
37
+ import { EFFORT_LADDER } from '../types/router.js';
38
+ /** The wire vocabulary, in increasing order — the gateway's OWN ladder, never a
39
+ * local copy. A vendor level it cannot name is dropped rather than leaked into
40
+ * `supportedReasoningEfforts` as an unroutable string. */
41
+ const EFFORT_VALUES = EFFORT_LADDER;
42
+ /** Normalize a vendor level list: keep the known levels, dedupe, preserve the
43
+ * vendor's order (toOcrDef restores ladder order before publishing). */
44
+ export function normalizeEfforts(values) {
45
+ if (!Array.isArray(values))
46
+ return [];
47
+ const out = [];
48
+ for (const raw of values) {
49
+ const level = String(raw).trim().toLowerCase();
50
+ if (EFFORT_VALUES.includes(level) && !out.includes(level))
51
+ out.push(level);
52
+ }
53
+ return out;
54
+ }
55
+ /**
56
+ * Build the OCR models.dev-shaped def from normalized vendor capabilities.
57
+ *
58
+ * The output feeds `host.pull.catalogToDef` (via `upsertModel`) and the defs
59
+ * file, so every field here is a real OCR vocabulary member — see
60
+ * `backend/src/opencode/catalog/types.ts` `CatalogModel`.
61
+ */
62
+ export function toOcrDef(caps) {
63
+ const def = { id: caps.id };
64
+ if (caps.name !== undefined)
65
+ def.name = caps.name;
66
+ const reasoning = caps.reasoning;
67
+ // The on/off fact travels with the def: the boot ladder expands a bare
68
+ // reasoning boolean into the full EFFORT_LADDER, which INCLUDES `none`.
69
+ // Without this field an always-think model with no table would be told it
70
+ // serves thinking-off, and the router would reproduce the 1210 refusal the
71
+ // table stripping exists to prevent (ADR-0035 rule 2 — the withholding must
72
+ // hold at the ROUTING plane, not only on the published table).
73
+ if (reasoning?.disableable === false)
74
+ def.reasoningDisableable = false;
75
+ if (reasoning) {
76
+ // Iron rule 1: a table is a table; a bare toggle only when the vendor said
77
+ // on/off and nothing more. `[]` (= toggle) is what erased the level.
78
+ const efforts = normalizeEfforts(reasoning.efforts);
79
+ const fixed = normalizeEfforts(reasoning.fixedEffort ? [reasoning.fixedEffort] : []);
80
+ if (efforts.length > 0) {
81
+ // Vendors publish efforts as an unordered OBJECT (`{high, low, max}`), so
82
+ // the level order must be restored from the gateway's own ladder —
83
+ // otherwise the console renders `xhigh` before `low` and a `defaultEffort`
84
+ // reads as if it sat at the wrong end of the list.
85
+ efforts.sort((a, b) => EFFORT_VALUES.indexOf(a) - EFFORT_VALUES.indexOf(b));
86
+ // A model that always thinks must NOT advertise `none`: the router picks
87
+ // the ladder's max ≤ request, and with no `none` member it can never
88
+ // emit "thinking off", which is the 1210 refusal's whole cause.
89
+ const table = reasoning.disableable === false ? efforts.filter((e) => e !== 'none') : efforts;
90
+ def.reasoning = true;
91
+ // An always-think model NEVER advertises `none`, not even as a fallback:
92
+ // a contradictory vendor table (`['none']` + disableable:false) must not
93
+ // resurrect the level its own on/off fact forbids — the router would
94
+ // then send thinking-off and eat the 1210 refusal this rule exists to
95
+ // prevent. When stripping empties the table, the boolean alone is the
96
+ // honest minimum (no invented ladder, no forbidden `none`).
97
+ if (table.length > 0) {
98
+ def.reasoningOptions = [{ type: 'effort', values: table }];
99
+ const defaultEffort = normalizeEfforts(reasoning.defaultEffort ? [reasoning.defaultEffort] : [])[0];
100
+ if (defaultEffort && table.includes(defaultEffort))
101
+ def.defaultEffort = defaultEffort;
102
+ }
103
+ }
104
+ else if (fixed.length > 0) {
105
+ // One gear, no table: a one-value table keeps clients showing a thinking
106
+ // model while the router clamps to the only level the vendor honours.
107
+ def.reasoning = true;
108
+ def.reasoningOptions = [{ type: 'effort', values: fixed }];
109
+ def.defaultEffort = fixed[0];
110
+ }
111
+ else if (reasoning.disableable === true) {
112
+ // The ONE honest toggle: on/off with no levels declared.
113
+ def.reasoning = true;
114
+ def.reasoningOptions = [{ type: 'toggle' }];
115
+ }
116
+ else {
117
+ // The vendor says it reasons but declares neither a table nor on/off.
118
+ // Claiming a ladder would be invention; claiming a toggle would be a
119
+ // lie that erases every level. The boolean alone is the honest minimum —
120
+ // and `effortLadderFor` expands it, which the caller opts into knowingly.
121
+ def.reasoning = true;
122
+ }
123
+ }
124
+ // Iron rule 3: `attachment` and `modalities.input` are one fact.
125
+ //
126
+ // `modalities` is a MULTIMODALITY declaration, not a restatement that text
127
+ // works — every model does text. Emitting `{input:['text']}` for a text-only
128
+ // row would claim a capability ledger the vendor never published (and the
129
+ // console renders it as a badge). So the block appears only for a row with a
130
+ // non-text input modality or a non-text output modality; a text-only row
131
+ // carries NEITHER `attachment` nor `modalities`.
132
+ const input = caps.inputModalities?.length ? [...new Set(caps.inputModalities)] : undefined;
133
+ const output = caps.outputModalities?.length ? [...new Set(caps.outputModalities)] : undefined;
134
+ const multiInput = input?.filter((m) => m !== 'text');
135
+ const multiOutput = output?.filter((m) => m !== 'text');
136
+ if (multiInput?.length || multiOutput?.length) {
137
+ def.modalities = { ...(input ? { input } : {}), ...(output ? { output } : {}) };
138
+ }
139
+ if (multiInput?.includes('image'))
140
+ def.attachment = true;
141
+ // Iron rule 2: only what the vendor declared.
142
+ if (caps.toolCall !== undefined)
143
+ def.tool_call = caps.toolCall;
144
+ if (caps.temperature !== undefined)
145
+ def.temperature = caps.temperature;
146
+ if (caps.structuredOutput !== undefined)
147
+ def.structured_output = caps.structuredOutput;
148
+ if (caps.interleavedField)
149
+ def.interleaved = { field: caps.interleavedField };
150
+ // Iron rule 4: `input` is the prompt cap, never invented from `context`.
151
+ if (caps.limit) {
152
+ const limit = {};
153
+ if (typeof caps.limit.context === 'number' && caps.limit.context > 0)
154
+ limit.context = caps.limit.context;
155
+ if (typeof caps.limit.input === 'number' && caps.limit.input > 0)
156
+ limit.input = caps.limit.input;
157
+ if (typeof caps.limit.output === 'number' && caps.limit.output > 0)
158
+ limit.output = caps.limit.output;
159
+ if (Object.keys(limit).length > 0)
160
+ def.limit = limit;
161
+ }
162
+ if (caps.cost) {
163
+ const cost = {};
164
+ for (const k of ['input', 'output', 'cacheRead', 'cacheWrite']) {
165
+ const v = caps.cost[k];
166
+ if (typeof v === 'number' && v >= 0)
167
+ cost[k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)] = v;
168
+ }
169
+ if (Object.keys(cost).length > 0)
170
+ def.cost = cost;
171
+ }
172
+ if (caps.disabled === true)
173
+ def.disabled = true;
174
+ if (caps.vendor && Object.keys(caps.vendor).length > 0)
175
+ def.vendor = caps.vendor;
176
+ return def;
177
+ }
@@ -1,5 +1,5 @@
1
1
  import type http from 'node:http';
2
- import type { ClientGatewayPlugin } from './types.js';
2
+ import type { ClientGatewayPlugin, PluginClaimEgress } from './types.js';
3
3
  /**
4
4
  * Registry of client-gateway plugins (the second plugin type, ADR-0017).
5
5
  *
@@ -42,6 +42,19 @@ import type { ClientGatewayPlugin } from './types.js';
42
42
  */
43
43
  /** The one wildcard claim spelling. */
44
44
  export declare const WILDCARD_HOST_CLAIM = "*";
45
+ /** What the non-code tiers said about this gateway's hosts. `operator` is the
46
+ * value stored in `plugins/config/<id>.json`; it outranks the code. */
47
+ export interface ClaimEgressSources {
48
+ manifest?: PluginClaimEgress;
49
+ operator?: PluginClaimEgress;
50
+ }
51
+ /** The three tiers, RUNTIME data so the console mirror can be parity-checked
52
+ * instead of drifting silently (the drawer translates each one by name). */
53
+ export declare const CLAIM_EGRESS_SOURCES: readonly ["operator", "code", "manifest"];
54
+ /** Which tier of the claim answered for a host (ADR-0018 Revision 5). The console
55
+ * prints this, because "the plugin routes it" and "the operator told it to"
56
+ * are different things an operator is entitled to tell apart. */
57
+ export type ClaimEgressSource = (typeof CLAIM_EGRESS_SOURCES)[number];
45
58
  /** Decrypted-request shape both proxy legs can provide (h1 native, h2 compat layer). */
46
59
  export interface GatewayRequestInfo {
47
60
  method?: string;
@@ -49,8 +62,22 @@ export interface GatewayRequestInfo {
49
62
  url?: string;
50
63
  headers: http.IncomingHttpHeaders;
51
64
  }
52
- /** Register one gateway under its plugin id (staging side of the swap). */
53
- export declare function stageGateway(id: string, gateway: ClientGatewayPlugin): void;
65
+ /** Register one gateway under its plugin id (staging side of the swap).
66
+ * `egress` holds what the two NON-CODE tiers said about this gateway's hosts:
67
+ * the manifest's default leg and the operator's plugin-level switch. An
68
+ * `inherit` or absent tier stores nothing, so a host with no opinion from that
69
+ * tier is simply not represented rather than present with a no-op value. */
70
+ export declare function stageGateway(id: string, gateway: ClientGatewayPlugin, egress?: ClaimEgressSources): void;
71
+ /** Replace only the OPERATOR tier for a live gateway (config hot-apply).
72
+ *
73
+ * A config save must take effect on the next request, and the full
74
+ * stage/commit cycle is the wrong tool: it rebuilds every gateway from the
75
+ * packages on disk, which drags in unrelated load failures and re-runs each
76
+ * plugin's activation hooks for a value that lives in a JSON file. The instance
77
+ * is left alone — the switch is a vote about the transport under it, not a
78
+ * reason to hand the plugin a new one. The staging side needs no write because
79
+ * the rebuild re-reads the stored config, which this call runs after. */
80
+ export declare function setGatewayOperatorEgress(id: string, egress?: PluginClaimEgress): void;
54
81
  /** Drop staged gateways for ids that did NOT load (fail-closed at the commit
55
82
  * point). The loader stages a gateway as part of loading a package; if the
56
83
  * load then throws, the staging entry must not survive into the live map —
@@ -67,6 +94,38 @@ export declare function claimsWildcard(gw: ClientGatewayPlugin): boolean;
67
94
  * Consumers that want concrete hosts only must filter `'*'` themselves —
68
95
  * the set is the truthful claim vocabulary, not a resolved host list. */
69
96
  export declare function listGatewayHosts(): Set<string>;
97
+ /**
98
+ * Who decides the outbound leg of a host a client gateway claims, and in what
99
+ * order (ADR-0018 Revision 5). Once a package claims a host, the leg under that host
100
+ * is the package's business:
101
+ *
102
+ * 1. the OPERATOR's plugin-level switch (`plugins/config/<id>.json`), when it
103
+ * explicitly picked a leg — the operator outranks the code they installed;
104
+ * 2. the gateway's own CODE (`egressFor`), which may answer host by host and
105
+ * change its mind per request;
106
+ * 3. the MANIFEST's declared default leg.
107
+ *
108
+ * `undefined` means the claim has no opinion, which is the only way the rule
109
+ * table's `egress` reaches a claimed host.
110
+ *
111
+ * Two refusals keep the blast radius equal to the claim:
112
+ * - a WILDCARD claim never votes. `'*'` is a read permission over every host
113
+ * the machine reaches, not a statement about any one of them;
114
+ * - a host two gateways answer OPPOSITELY yields no opinion, not a winner.
115
+ * Order between two installed packages is a load artifact, and a silent pick
116
+ * is how one plugin ends up routing another vendor's traffic.
117
+ */
118
+ export declare function claimEgressFor(host: string): {
119
+ action: 'proxy' | 'direct';
120
+ source: ClaimEgressSource;
121
+ } | undefined;
122
+ /**
123
+ * Every concretely claimed host whose claim currently speaks about the leg.
124
+ * A snapshot, so the table LINT can ask "is this row's `egress` reachable?"
125
+ * without treating plugin code as a lint input; routing itself asks
126
+ * `claimEgressFor()` per request.
127
+ */
128
+ export declare function listClaimedEgress(): Map<string, 'proxy' | 'direct'>;
70
129
  /** Live gateway instance by plugin id (config-change hot-apply hook). */
71
130
  export declare function getGatewayById(id: string): ClientGatewayPlugin | undefined;
72
131
  /** All live gateways (id → instance) — read-only snapshot. The generic
@@ -41,11 +41,51 @@
41
41
  /** The one wildcard claim spelling. */
42
42
  export const WILDCARD_HOST_CLAIM = '*';
43
43
  const gateways = new Map();
44
+ /**
45
+ * The outbound-leg opinions each live gateway holds for its claimed hosts,
46
+ * keyed by plugin id. It rides the SAME staging/commit/prune cycle as
47
+ * `gateways`, so it can never outlive a claim: an uninstalled or disabled
48
+ * plugin stops declaring on the same swap that stops it intercepting. A
49
+ * parallel map is deliberate — the two tiers in here are what the MANIFEST and
50
+ * the OPERATOR said, and a gateway's own code must not be able to rewrite them.
51
+ */
52
+ const claimEgress = new Map();
53
+ /** The three tiers, RUNTIME data so the console mirror can be parity-checked
54
+ * instead of drifting silently (the drawer translates each one by name). */
55
+ export const CLAIM_EGRESS_SOURCES = ['operator', 'code', 'manifest'];
44
56
  /** Atomic-rebuild staging map (plugins/host.ts owns the rebuild cycle). */
45
57
  const nextGateways = new Map();
46
- /** Register one gateway under its plugin id (staging side of the swap). */
47
- export function stageGateway(id, gateway) {
58
+ const nextClaimEgress = new Map();
59
+ /** Register one gateway under its plugin id (staging side of the swap).
60
+ * `egress` holds what the two NON-CODE tiers said about this gateway's hosts:
61
+ * the manifest's default leg and the operator's plugin-level switch. An
62
+ * `inherit` or absent tier stores nothing, so a host with no opinion from that
63
+ * tier is simply not represented rather than present with a no-op value. */
64
+ export function stageGateway(id, gateway, egress) {
48
65
  nextGateways.set(id, gateway);
66
+ const manifest = egress?.manifest && egress.manifest !== 'inherit' ? egress.manifest : undefined;
67
+ const operator = egress?.operator && egress.operator !== 'inherit' ? egress.operator : undefined;
68
+ if (manifest || operator)
69
+ nextClaimEgress.set(id, { manifest, operator });
70
+ else
71
+ nextClaimEgress.delete(id);
72
+ }
73
+ /** Replace only the OPERATOR tier for a live gateway (config hot-apply).
74
+ *
75
+ * A config save must take effect on the next request, and the full
76
+ * stage/commit cycle is the wrong tool: it rebuilds every gateway from the
77
+ * packages on disk, which drags in unrelated load failures and re-runs each
78
+ * plugin's activation hooks for a value that lives in a JSON file. The instance
79
+ * is left alone — the switch is a vote about the transport under it, not a
80
+ * reason to hand the plugin a new one. The staging side needs no write because
81
+ * the rebuild re-reads the stored config, which this call runs after. */
82
+ export function setGatewayOperatorEgress(id, egress) {
83
+ const value = egress && egress !== 'inherit' ? egress : undefined;
84
+ const manifest = claimEgress.get(id)?.manifest;
85
+ if (!value && !manifest)
86
+ claimEgress.delete(id);
87
+ else
88
+ claimEgress.set(id, { manifest, operator: value });
49
89
  }
50
90
  /** Drop staged gateways for ids that did NOT load (fail-closed at the commit
51
91
  * point). The loader stages a gateway as part of loading a package; if the
@@ -57,18 +97,28 @@ export function retainStagedGateways(loadedIds) {
57
97
  if (!loadedIds.has(id))
58
98
  nextGateways.delete(id);
59
99
  }
100
+ for (const id of [...nextClaimEgress.keys()]) {
101
+ if (!loadedIds.has(id))
102
+ nextClaimEgress.delete(id);
103
+ }
60
104
  }
61
105
  /** Swap the staged set into the live registry (end of a host rebuild). */
62
106
  export function commitGateways() {
63
107
  gateways.clear();
108
+ claimEgress.clear();
64
109
  for (const [k, v] of nextGateways)
65
110
  gateways.set(k, v);
111
+ for (const [k, v] of nextClaimEgress)
112
+ claimEgress.set(k, v);
66
113
  nextGateways.clear();
114
+ nextClaimEgress.clear();
67
115
  }
68
116
  /** Drop one gateway immediately (disable/uninstall hot-unplug half). */
69
117
  export function removeGateway(id) {
70
118
  gateways.delete(id);
119
+ claimEgress.delete(id);
71
120
  nextGateways.delete(id);
121
+ nextClaimEgress.delete(id);
72
122
  }
73
123
  /** A plugin claims the wildcard — it answers where no exact claim did. */
74
124
  export function claimsWildcard(gw) {
@@ -84,6 +134,93 @@ export function listGatewayHosts() {
84
134
  hosts.add(h);
85
135
  return hosts;
86
136
  }
137
+ /**
138
+ * Who decides the outbound leg of a host a client gateway claims, and in what
139
+ * order (ADR-0018 Revision 5). Once a package claims a host, the leg under that host
140
+ * is the package's business:
141
+ *
142
+ * 1. the OPERATOR's plugin-level switch (`plugins/config/<id>.json`), when it
143
+ * explicitly picked a leg — the operator outranks the code they installed;
144
+ * 2. the gateway's own CODE (`egressFor`), which may answer host by host and
145
+ * change its mind per request;
146
+ * 3. the MANIFEST's declared default leg.
147
+ *
148
+ * `undefined` means the claim has no opinion, which is the only way the rule
149
+ * table's `egress` reaches a claimed host.
150
+ *
151
+ * Two refusals keep the blast radius equal to the claim:
152
+ * - a WILDCARD claim never votes. `'*'` is a read permission over every host
153
+ * the machine reaches, not a statement about any one of them;
154
+ * - a host two gateways answer OPPOSITELY yields no opinion, not a winner.
155
+ * Order between two installed packages is a load artifact, and a silent pick
156
+ * is how one plugin ends up routing another vendor's traffic.
157
+ */
158
+ export function claimEgressFor(host) {
159
+ const h = String(host || '').toLowerCase();
160
+ if (!h || h === WILDCARD_HOST_CLAIM)
161
+ return undefined;
162
+ const votes = [];
163
+ for (const [id, gw] of gateways) {
164
+ if (claimsWildcard(gw))
165
+ continue;
166
+ if (!gw.hosts.some((x) => String(x).toLowerCase() === h))
167
+ continue;
168
+ const tiered = claimEgress.get(id);
169
+ const byOperator = tiered?.operator;
170
+ const byCode = byOperator ? undefined : codeEgress(gw, h);
171
+ const action = byOperator ?? byCode ?? tiered?.manifest;
172
+ if (action !== 'proxy' && action !== 'direct')
173
+ continue;
174
+ votes.push({ action, source: byOperator ? 'operator' : byCode ? 'code' : 'manifest' });
175
+ }
176
+ if (votes.length === 0)
177
+ return undefined;
178
+ if (votes.some((v) => v.action !== votes[0].action))
179
+ return undefined;
180
+ // When several gateways agree, the console says who SPOKE, and an explicit
181
+ // operator switch outranks a package's code the same way it does within one
182
+ // package — otherwise the row would credit a manifest default the operator
183
+ // actually overrode.
184
+ const byTier = ['operator', 'code', 'manifest'];
185
+ const speaker = byTier.find((t) => votes.some((v) => v.source === t));
186
+ return { action: votes[0].action, source: speaker };
187
+ }
188
+ /** The gateway's own per-host answer. A throwing hook is silence, not a
189
+ * routing decision: a plugin bug must not strand the transport of the host it
190
+ * claims (same contract as `match()` declining in `accepts()`). */
191
+ function codeEgress(gw, host) {
192
+ if (!gw.egressFor)
193
+ return undefined;
194
+ try {
195
+ const v = gw.egressFor({ host });
196
+ return v === 'proxy' || v === 'direct' ? v : undefined;
197
+ }
198
+ catch {
199
+ return undefined;
200
+ }
201
+ }
202
+ /**
203
+ * Every concretely claimed host whose claim currently speaks about the leg.
204
+ * A snapshot, so the table LINT can ask "is this row's `egress` reachable?"
205
+ * without treating plugin code as a lint input; routing itself asks
206
+ * `claimEgressFor()` per request.
207
+ */
208
+ export function listClaimedEgress() {
209
+ const out = new Map();
210
+ for (const gw of gateways.values()) {
211
+ if (claimsWildcard(gw))
212
+ continue;
213
+ for (const host of gw.hosts) {
214
+ const h = String(host).toLowerCase();
215
+ if (h === WILDCARD_HOST_CLAIM || out.has(h))
216
+ continue;
217
+ const claim = claimEgressFor(h);
218
+ if (claim)
219
+ out.set(h, claim.action);
220
+ }
221
+ }
222
+ return out;
223
+ }
87
224
  /** Live gateway instance by plugin id (config-change hot-apply hook). */
88
225
  export function getGatewayById(id) {
89
226
  return gateways.get(id);