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
@@ -1,7 +1,7 @@
1
1
  import type { ProviderRegistry } from './registry.js';
2
2
  import type { ComboConfig } from '../config/types.js';
3
- import type { CatalogModel, CatalogProviderRecord } from '../opencode/catalog/types.js';
4
- import { type TierLevel } from '../types/router.js';
3
+ import type { CatalogCost, CatalogModel, CatalogProviderRecord } from '../opencode/catalog/types.js';
4
+ import { type ModelPricing, type TierLevel } from '../types/router.js';
5
5
  /**
6
6
  * Capability envelope for VIRTUAL model refs (auto* aliases, tier aliases,
7
7
  * combos) — the shared math behind client-hook model records (pi models.json)
@@ -68,6 +68,17 @@ export declare const TIER_LADDER: readonly TierLevel[];
68
68
  export declare const TIER_PURPOSE: Record<TierLevel, string>;
69
69
  /** Minimal registry seam so callers can pass the live singleton (or a stub). */
70
70
  export type CatalogList = () => Promise<CatalogProviderRecord[]>;
71
+ /**
72
+ * The ONE catalog-cost → registration-pricing rule (no fabrication, ADR-0035):
73
+ * input AND output must both be known or there is no price (`undefined`, never
74
+ * a synthesized 0 — "free" is a lie the cost plane exists to remove). An absent
75
+ * cached-READ rate derives from `input` (a vendor that publishes none bills
76
+ * cache reads as input). An absent cached-WRITE rate is OMITTED, not zeroed:
77
+ * `cache_write: 0` would publish "cache writes are free", a number the vendor
78
+ * never stated. Shared by boot-direct (real models) and the virtual combo
79
+ * envelope so the two derivations can never drift apart.
80
+ */
81
+ export declare function pricingFromCost(cost: CatalogCost | undefined): ModelPricing | undefined;
71
82
  /**
72
83
  * Batch catalog lookup for member ids: full registered form `${provider}/${model}`
73
84
  * first, then bare model id (mirrors the client-hook lookup semantics). Ids with
@@ -75,10 +86,18 @@ export type CatalogList = () => Promise<CatalogProviderRecord[]>;
75
86
  * `lookup` resolves any single member id with the same precedence (used for the
76
87
  * chain-order leader, who must be found by IDENTITY even when other members
77
88
  * lack catalog records).
89
+ *
90
+ * Each pushed record's LOOKUP id is available from the `byId` map: callers
91
+ * that key by the registered id (`server.ts` catById.get(m.id)) must read that
92
+ * map, not the record's own `id` — a prefixed provider's registered id is
93
+ * `${provider}/${upstream}` while the catalog record keeps the bare upstream
94
+ * key, so indexing records by `rec.id` misses every prefixed provider.
78
95
  */
79
96
  export declare function findMemberCatalogRecords(ids: string[], listCatalog: CatalogList): Promise<{
80
97
  records: CatalogModel[];
81
98
  lookup: (id: string) => CatalogModel | undefined;
99
+ /** Resolved record keyed by the id it was looked up by (registered form). */
100
+ byId: Map<string, CatalogModel>;
82
101
  }>;
83
102
  /**
84
103
  * Envelope for a tier alias (`lite`|`plus`|`pro`|`ultra`) or `auto`. `auto`
@@ -1,4 +1,15 @@
1
1
  import { EFFORT_LADDER } from '../types/router.js';
2
+ /** Strip `none` from a published effort table when the vendor forbids
3
+ * thinking-off (ADR-0035): the public catalog must advertise exactly what
4
+ * routing will serve, never a level the gateway withholds. An effort option
5
+ * that empties under the strip is dropped, not re-published. */
6
+ function stripForbiddenNone(options, disableable) {
7
+ if (disableable !== false)
8
+ return options;
9
+ return options
10
+ .map((o) => (o.type === 'effort' && Array.isArray(o.values) ? { ...o, values: o.values.filter((v) => v !== 'none') } : o))
11
+ .filter((o) => !(o.type === 'effort' && Array.isArray(o.values) && o.values.length === 0));
12
+ }
2
13
  /**
3
14
  * models.dev-shaped capability block for ONE model record (snake_case, aligned
4
15
  * with https://models.opencode.ai/api.json). Fields absent from the record stay
@@ -8,7 +19,7 @@ export function modelsDevBlock(cat) {
8
19
  return {
9
20
  ...(cat.attachment !== undefined ? { attachment: cat.attachment } : {}),
10
21
  ...(cat.reasoning !== undefined ? { reasoning: cat.reasoning } : {}),
11
- ...(cat.reasoningOptions ? { reasoning_options: cat.reasoningOptions } : {}),
22
+ ...(cat.reasoningOptions ? { reasoning_options: stripForbiddenNone(cat.reasoningOptions, cat.reasoningDisableable) } : {}),
12
23
  ...(cat.tool_call !== undefined ? { tool_call: cat.tool_call } : {}),
13
24
  ...(cat.temperature !== undefined ? { temperature: cat.temperature } : {}),
14
25
  ...(cat.structured_output !== undefined ? { structured_output: cat.structured_output } : {}),
@@ -58,6 +69,26 @@ export const TIER_PURPOSE = {
58
69
  pro: 'implementation & review — write code, review code',
59
70
  ultra: 'the oracle second opinion — the hardest judgment calls',
60
71
  };
72
+ /**
73
+ * The ONE catalog-cost → registration-pricing rule (no fabrication, ADR-0035):
74
+ * input AND output must both be known or there is no price (`undefined`, never
75
+ * a synthesized 0 — "free" is a lie the cost plane exists to remove). An absent
76
+ * cached-READ rate derives from `input` (a vendor that publishes none bills
77
+ * cache reads as input). An absent cached-WRITE rate is OMITTED, not zeroed:
78
+ * `cache_write: 0` would publish "cache writes are free", a number the vendor
79
+ * never stated. Shared by boot-direct (real models) and the virtual combo
80
+ * envelope so the two derivations can never drift apart.
81
+ */
82
+ export function pricingFromCost(cost) {
83
+ if (!cost || cost.input === undefined || cost.output === undefined)
84
+ return undefined;
85
+ return {
86
+ input: cost.input,
87
+ output: cost.output,
88
+ cacheRead: cost.cache_read ?? cost.input,
89
+ ...(cost.cache_write !== undefined ? { cacheWrite: cost.cache_write } : {}),
90
+ };
91
+ }
61
92
  /** Common math: safe-min limits, intersection image, leader pricing/name. */
62
93
  function envelopeOf(memberCats, leaderCat, leaderPricing, fallbackCount) {
63
94
  const contexts = memberCats.map((c) => c.limit?.context).filter((n) => typeof n === 'number' && n > 0);
@@ -68,10 +99,7 @@ function envelopeOf(memberCats, leaderCat, leaderPricing, fallbackCount) {
68
99
  const all = (pick) => memberCats.length > 0 && memberCats.every((c) => pick(c) === true);
69
100
  // Cost fallback and display name bind to the true chain-order LEADER (by
70
101
  // identity), never to "the first member that happens to have a record".
71
- const cost = leaderCat?.cost;
72
- const pricing = leaderPricing ?? (cost
73
- ? { input: cost.input ?? 0, output: cost.output ?? 0, cacheRead: cost.cache_read ?? 0, cacheWrite: cost.cache_write ?? 0 }
74
- : undefined);
102
+ const pricing = leaderPricing ?? pricingFromCost(leaderCat?.cost);
75
103
  return {
76
104
  memberCount: fallbackCount,
77
105
  ...(contexts.length > 0 ? { contextWindow: Math.min(...contexts) } : {}),
@@ -91,6 +119,12 @@ function envelopeOf(memberCats, leaderCat, leaderPricing, fallbackCount) {
91
119
  * `lookup` resolves any single member id with the same precedence (used for the
92
120
  * chain-order leader, who must be found by IDENTITY even when other members
93
121
  * lack catalog records).
122
+ *
123
+ * Each pushed record's LOOKUP id is available from the `byId` map: callers
124
+ * that key by the registered id (`server.ts` catById.get(m.id)) must read that
125
+ * map, not the record's own `id` — a prefixed provider's registered id is
126
+ * `${provider}/${upstream}` while the catalog record keeps the bare upstream
127
+ * key, so indexing records by `rec.id` misses every prefixed provider.
94
128
  */
95
129
  export async function findMemberCatalogRecords(ids, listCatalog) {
96
130
  let providers;
@@ -98,7 +132,7 @@ export async function findMemberCatalogRecords(ids, listCatalog) {
98
132
  providers = await listCatalog();
99
133
  }
100
134
  catch {
101
- return { records: [], lookup: () => undefined };
135
+ return { records: [], lookup: () => undefined, byId: new Map() };
102
136
  }
103
137
  const byFull = new Map();
104
138
  const byBare = new Map();
@@ -111,12 +145,18 @@ export async function findMemberCatalogRecords(ids, listCatalog) {
111
145
  }
112
146
  const lookup = (id) => byFull.get(id) ?? byBare.get(id);
113
147
  const records = [];
148
+ const byId = new Map();
114
149
  for (const id of ids) {
115
150
  const cat = lookup(id);
116
- if (cat)
117
- records.push(cat);
151
+ if (!cat)
152
+ continue;
153
+ records.push(cat);
154
+ // First writer wins: a repeated id must not let a later bare-key hit
155
+ // overwrite the prefixed provider's record.
156
+ if (!byId.has(id))
157
+ byId.set(id, cat);
118
158
  }
119
- return { records, lookup };
159
+ return { records, lookup, byId };
120
160
  }
121
161
  /**
122
162
  * Envelope for a tier alias (`lite`|`plus`|`pro`|`ultra`) or `auto`. `auto`
@@ -0,0 +1,54 @@
1
+ export type AssetDownloadCode = 'download-failed' | 'download-incomplete' | 'download-too-large' | 'download-aborted' | 'checksum-failed' | 'write-failed';
2
+ export interface AssetSidecar {
3
+ /** The asset URL the bytes were fetched from; a different URL is a different file. */
4
+ url: string;
5
+ /** Whole-asset size in bytes as the host reported it; 0 = unknown. */
6
+ size: number;
7
+ etag?: string;
8
+ lastModified?: string;
9
+ sha256?: string;
10
+ savedAt: number;
11
+ }
12
+ export interface AssetDownloadOptions {
13
+ url: string;
14
+ /** Absolute path of the in-progress file. Its sidecar is `<path>.json`. */
15
+ partPath: string;
16
+ fetchImpl: typeof fetch;
17
+ /** Ceiling for the WHOLE asset, resumed prefix included. */
18
+ maxBytes: number;
19
+ /** Lowercase hex sha256 when the host published one (the release API does). */
20
+ sha256?: string;
21
+ /** Extra request headers (the caller's UA/Accept). */
22
+ headers?: Record<string, string>;
23
+ /** Cancels the request and the stream; the part written so far is kept. */
24
+ signal?: AbortSignal;
25
+ /** Byte progress of the WHOLE asset, so a resumed run starts off the origin. */
26
+ onProgress?: (downloaded: number, total: number) => void;
27
+ /** Ignore and delete any existing part (the console's explicit re-sync). */
28
+ discardPartial?: boolean;
29
+ }
30
+ export type AssetDownloadResult = {
31
+ ok: true;
32
+ size: number;
33
+ resumedFrom: number;
34
+ verified: boolean;
35
+ } | {
36
+ ok: false;
37
+ code: AssetDownloadCode;
38
+ error: string;
39
+ };
40
+ export declare function assetPartPaths(target: string): {
41
+ partPath: string;
42
+ metaPath: string;
43
+ };
44
+ export declare function cleanupAssetPart(partPath: string): void;
45
+ export declare function withAssetLock<T>(target: string, fn: () => Promise<T>): Promise<T>;
46
+ /** `sha256:<hex>` (the release API spelling) or a bare hex digest; else absent. */
47
+ export declare function parseAssetDigest(value: unknown): string | undefined;
48
+ /**
49
+ * Fetch one release asset into `partPath`, continuing an interrupted transfer
50
+ * when the host and the sidecar allow it. On success the verified asset bytes
51
+ * (still compressed/packed) sit at `partPath` and the CALLER owns them: unpack,
52
+ * install, then `cleanupAssetPart`.
53
+ */
54
+ export declare function downloadAssetToFile(opts: AssetDownloadOptions): Promise<AssetDownloadResult>;
@@ -0,0 +1,420 @@
1
+ /**
2
+ * Resumable release-asset downloads (ADR-0022).
3
+ *
4
+ * The Clash core binary and the two geo databases are tens of megabytes off a
5
+ * GitHub release host, and a transfer that died at 99% used to lose every byte:
6
+ * both callers buffered the whole body in memory and touched the disk only once
7
+ * the stream had ended. This module streams to a `.part` file instead, so an
8
+ * interrupted transfer keeps its progress and the next attempt asks the host for
9
+ * the missing tail.
10
+ *
11
+ * Contract:
12
+ * - ONE writer per asset. `withAssetLock` serialises concurrent calls for the
13
+ * same destination, so two console tabs cannot interleave writes into one
14
+ * file and rename a torn binary into place.
15
+ * - Resume needs a validator. The sidecar (`<part>.json`) records the host's
16
+ * `ETag`/`Last-Modified`, the expected size and the digest, and is written
17
+ * BEFORE the body streams — so a process killed mid-transfer still leaves
18
+ * enough provenance to continue. A retry sends `Range` + `If-Range`; only a
19
+ * `206` appends, a `200` means the host ignored or rejected the validator and
20
+ * the file restarts from zero, and a `416` whose `Content-Range` confirms the
21
+ * recorded size means the part is already complete.
22
+ * - A published `sha256` is verified before the caller sees success, and a
23
+ * mismatch destroys the part. Resume is never a way to install spliced bytes.
24
+ * - A failure KEEPS the part (the next click continues). The exceptions are the
25
+ * size cap, a checksum mismatch, a stale or mismatched sidecar and an explicit
26
+ * re-sync — each deletes it, so a bad part can never loop the caller. An
27
+ * archive that downloads and verifies but will not unpack is destroyed by the
28
+ * caller for the same reason.
29
+ * - `Accept-Encoding: identity` is forced: a transformed body breaks both the
30
+ * byte accounting and the digest comparison, and would make any stored prefix
31
+ * meaningless.
32
+ */
33
+ import crypto from 'node:crypto';
34
+ import fs from 'node:fs';
35
+ import path from 'node:path';
36
+ /** A part older than this is discarded, not resumed (an abandoned download is
37
+ * not a queue, and a stale prefix costs a conditional request to find out). */
38
+ const PART_TTL_MS = 24 * 60 * 60 * 1000;
39
+ const USER_AGENT = 'omnicell-router';
40
+ export function assetPartPaths(target) {
41
+ return { partPath: `${target}.part`, metaPath: `${target}.part.json` };
42
+ }
43
+ export function cleanupAssetPart(partPath) {
44
+ for (const file of [partPath, `${partPath}.json`]) {
45
+ try {
46
+ fs.rmSync(file, { force: true });
47
+ }
48
+ catch {
49
+ // Nothing to clean: a missing temp file is the finished state.
50
+ }
51
+ }
52
+ }
53
+ /**
54
+ * Serialise an operation on one asset path. The key is the FINAL destination,
55
+ * so the download, the unpack and the rename are one critical section — a
56
+ * second click waits instead of writing the same temp file underneath it.
57
+ */
58
+ const chains = new Map();
59
+ export async function withAssetLock(target, fn) {
60
+ const prev = chains.get(target) ?? Promise.resolve();
61
+ const settled = prev.then(fn, fn);
62
+ const tail = settled.catch(() => undefined);
63
+ chains.set(target, tail);
64
+ try {
65
+ return await settled;
66
+ }
67
+ finally {
68
+ if (chains.get(target) === tail)
69
+ chains.delete(target);
70
+ }
71
+ }
72
+ /** `sha256:<hex>` (the release API spelling) or a bare hex digest; else absent. */
73
+ export function parseAssetDigest(value) {
74
+ if (typeof value !== 'string')
75
+ return undefined;
76
+ const raw = value.trim().toLowerCase();
77
+ const hex = raw.startsWith('sha256:') ? raw.slice(7) : raw;
78
+ return /^[0-9a-f]{64}$/.test(hex) ? hex : undefined;
79
+ }
80
+ function isAborted(signal, err) {
81
+ if (signal?.aborted)
82
+ return true;
83
+ // Node surfaces the same cancellation as an AbortError, Bun/undici as the
84
+ // ABORT_ERR code; a caller-supplied fetch may throw either.
85
+ if (!(err instanceof Error))
86
+ return false;
87
+ return err.name === 'AbortError' || err.code === 'ABORT_ERR';
88
+ }
89
+ function contentLengthOf(res) {
90
+ return Number(res.headers.get('content-length') ?? '') || 0;
91
+ }
92
+ /** The total in a Content-Range header: `bytes 400-999/1000`, and on a 416 the
93
+ * asterisk form `bytes <star>/1000`. */
94
+ function contentRangeTotal(res) {
95
+ const match = /\/(\d+)\s*$/.exec(res.headers.get('content-range') ?? '');
96
+ return match ? Number(match[1]) : 0;
97
+ }
98
+ /** The sidecar of a part that may be resumed, or null when it may not. */
99
+ function readableSidecar(metaPath, partPath, url, sha256) {
100
+ let meta;
101
+ try {
102
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ if (typeof meta?.url !== 'string' || meta.url !== url)
108
+ return null;
109
+ // Without a validator the host cannot confirm the prefix belongs to the
110
+ // current representation, so splicing it would be a guess.
111
+ if (!meta.etag && !meta.lastModified)
112
+ return null;
113
+ if (sha256 && meta.sha256 !== sha256)
114
+ return null;
115
+ if (typeof meta.savedAt !== 'number' || Date.now() - meta.savedAt > PART_TTL_MS)
116
+ return null;
117
+ let have;
118
+ try {
119
+ const stat = fs.statSync(partPath);
120
+ if (!stat.isFile())
121
+ return null;
122
+ have = stat.size;
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ if (have === 0)
128
+ return null;
129
+ if (meta.size > 0 && have > meta.size)
130
+ return null;
131
+ return meta;
132
+ }
133
+ function sha256File(file) {
134
+ const hash = crypto.createHash('sha256');
135
+ const fd = fs.openSync(file, 'r');
136
+ try {
137
+ const buf = Buffer.alloc(1024 * 1024);
138
+ for (;;) {
139
+ const read = fs.readSync(fd, buf, 0, buf.length, null);
140
+ if (!read)
141
+ break;
142
+ hash.update(buf.subarray(0, read));
143
+ }
144
+ }
145
+ finally {
146
+ fs.closeSync(fd);
147
+ }
148
+ return hash.digest('hex');
149
+ }
150
+ /** Pump the response body into the part file with backpressure. */
151
+ async function streamBody(res, partPath, append, start, maxBytes, opts) {
152
+ const ws = fs.createWriteStream(partPath, { flags: append ? 'a' : 'w' });
153
+ let written = start;
154
+ let lastReport = 0;
155
+ let flushed = null;
156
+ /**
157
+ * Let the bytes already taken land, once. They are a valid prefix of the
158
+ * asset, so an interrupted transfer must not throw them away: destroy() here
159
+ * discards everything still buffered (measured on Bun 1.3.14: 160KB queued ->
160
+ * a 0-byte `.part`), which would force the next attempt to restart from zero
161
+ * and make the resume promise false exactly when it matters.
162
+ */
163
+ const settle = () => {
164
+ if (flushed)
165
+ return flushed;
166
+ flushed = new Promise((resolve) => {
167
+ ws.once('close', resolve);
168
+ ws.once('error', () => resolve());
169
+ ws.end();
170
+ });
171
+ return flushed;
172
+ };
173
+ const fail = async (code, error) => {
174
+ await settle();
175
+ return { ok: false, code, error };
176
+ };
177
+ const report = (total, force = false) => {
178
+ const now = Date.now();
179
+ if (!force && now - lastReport < 100)
180
+ return;
181
+ lastReport = now;
182
+ opts.onProgress?.(written, total);
183
+ };
184
+ const put = async (chunk) => {
185
+ try {
186
+ if (ws.write(chunk))
187
+ return null;
188
+ await new Promise((resolve, reject) => {
189
+ const onDrain = () => { cleanup(); resolve(); };
190
+ const onError = (err) => { cleanup(); reject(err); };
191
+ const onAbort = () => { cleanup(); reject(new DOMException('aborted', 'AbortError')); };
192
+ const cleanup = () => {
193
+ ws.off('drain', onDrain);
194
+ ws.off('error', onError);
195
+ opts.signal?.removeEventListener('abort', onAbort);
196
+ };
197
+ ws.once('drain', onDrain);
198
+ ws.once('error', onError);
199
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
200
+ });
201
+ return null;
202
+ }
203
+ catch (err) {
204
+ const message = err instanceof Error ? err.message : 'write failed';
205
+ return isAborted(opts.signal, err)
206
+ ? fail('download-aborted', 'download cancelled')
207
+ : fail('write-failed', `could not write the download file (${message})`);
208
+ }
209
+ };
210
+ const total = append ? start + contentLengthOf(res) : contentLengthOf(res);
211
+ try {
212
+ if (!res.body) {
213
+ const buf = new Uint8Array(await res.arrayBuffer());
214
+ written += buf.length;
215
+ if (written > maxBytes)
216
+ return fail('download-too-large', `download exceeded ${Math.floor(maxBytes / 1048576)}MB`);
217
+ const writeFailure = await put(buf);
218
+ if (writeFailure)
219
+ return writeFailure;
220
+ report(total || written, true);
221
+ }
222
+ else {
223
+ const reader = res.body.getReader();
224
+ opts.onProgress?.(start, total);
225
+ for (;;) {
226
+ if (opts.signal?.aborted) {
227
+ await reader.cancel().catch(() => undefined);
228
+ await settle();
229
+ return { ok: false, code: 'download-aborted', error: 'download cancelled' };
230
+ }
231
+ const { done, value } = await reader.read();
232
+ if (done)
233
+ break;
234
+ if (!value)
235
+ continue;
236
+ written += value.byteLength;
237
+ if (written > maxBytes) {
238
+ await reader.cancel().catch(() => undefined);
239
+ return fail('download-too-large', `download exceeded ${Math.floor(maxBytes / 1048576)}MB`);
240
+ }
241
+ const writeFailure = await put(value);
242
+ if (writeFailure) {
243
+ await reader.cancel().catch(() => undefined);
244
+ return writeFailure;
245
+ }
246
+ report(total);
247
+ }
248
+ report(total || written, true);
249
+ }
250
+ await new Promise((resolve, reject) => {
251
+ ws.once('error', reject);
252
+ ws.end(() => resolve());
253
+ });
254
+ return { ok: true, bytes: written };
255
+ }
256
+ catch (err) {
257
+ // The read itself threw — a network drop, or the abort signal firing while
258
+ // the body was mid-flight. The bytes already taken are a valid prefix of the
259
+ // asset either way, so flush them instead of dropping the write queue.
260
+ await settle();
261
+ const aborted = isAborted(opts.signal, err);
262
+ const message = err instanceof Error ? err.message : 'network error';
263
+ return aborted
264
+ ? { ok: false, code: 'download-aborted', error: 'download cancelled' }
265
+ : { ok: false, code: 'download-failed', error: `download failed (${message})` };
266
+ }
267
+ finally {
268
+ if (!ws.writableEnded)
269
+ ws.destroy();
270
+ }
271
+ }
272
+ /**
273
+ * Fetch one release asset into `partPath`, continuing an interrupted transfer
274
+ * when the host and the sidecar allow it. On success the verified asset bytes
275
+ * (still compressed/packed) sit at `partPath` and the CALLER owns them: unpack,
276
+ * install, then `cleanupAssetPart`.
277
+ */
278
+ export async function downloadAssetToFile(opts) {
279
+ const metaPath = `${opts.partPath}.json`;
280
+ fs.mkdirSync(path.dirname(opts.partPath), { recursive: true });
281
+ if (opts.discardPartial)
282
+ cleanupAssetPart(opts.partPath);
283
+ // Two passes: a 416 the sidecar cannot explain restarts the file from zero.
284
+ for (let pass = 0; pass < 2; pass += 1) {
285
+ let resumeFrom = 0;
286
+ let validator;
287
+ if (pass === 0 && !opts.discardPartial) {
288
+ const meta = readableSidecar(metaPath, opts.partPath, opts.url, opts.sha256);
289
+ if (meta) {
290
+ const have = fs.statSync(opts.partPath).size;
291
+ resumeFrom = meta.size > 0 ? Math.min(have, meta.size) : have;
292
+ if (resumeFrom > 0)
293
+ validator = meta.etag ?? meta.lastModified;
294
+ }
295
+ }
296
+ if (resumeFrom === 0)
297
+ cleanupAssetPart(opts.partPath);
298
+ const headers = {
299
+ 'User-Agent': USER_AGENT,
300
+ Accept: 'application/octet-stream',
301
+ 'Accept-Encoding': 'identity',
302
+ ...opts.headers,
303
+ };
304
+ if (resumeFrom > 0) {
305
+ headers.Range = `bytes=${resumeFrom}-`;
306
+ if (validator)
307
+ headers['If-Range'] = validator;
308
+ }
309
+ let res;
310
+ try {
311
+ res = await opts.fetchImpl(opts.url, { headers, signal: opts.signal });
312
+ }
313
+ catch (err) {
314
+ if (isAborted(opts.signal, err))
315
+ return { ok: false, code: 'download-aborted', error: 'download cancelled' };
316
+ const message = err instanceof Error ? err.message : 'network error';
317
+ return { ok: false, code: 'download-failed', error: `download failed (${message})` };
318
+ }
319
+ if (res.status === 416 && resumeFrom > 0) {
320
+ const total = contentRangeTotal(res);
321
+ if (total === resumeFrom) {
322
+ // The host says the representation is exactly the bytes we hold. With a
323
+ // digest that is provable; without one the If-Range match above already
324
+ // tied the part to the current representation.
325
+ return finish(opts, resumeFrom, resumeFrom);
326
+ }
327
+ cleanupAssetPart(opts.partPath);
328
+ continue;
329
+ }
330
+ if (res.status !== 200 && res.status !== 206) {
331
+ await res.body?.cancel().catch(() => undefined);
332
+ return { ok: false, code: 'download-failed', error: `download failed (${res.status})` };
333
+ }
334
+ const append = res.status === 206 && resumeFrom > 0;
335
+ if (!append && resumeFrom > 0)
336
+ cleanupAssetPart(opts.partPath);
337
+ const start = append ? resumeFrom : 0;
338
+ // A 206 reports the REMAINING bytes, so the asset total is the prefix plus
339
+ // what the host just offered; a 200 reports the whole file.
340
+ const total = contentLengthOf(res) + start;
341
+ const encoding = (res.headers.get('content-encoding') ?? 'identity').toLowerCase();
342
+ const rawBody = encoding === 'identity' || encoding === 'none';
343
+ const etag = res.headers.get('etag') ?? undefined;
344
+ const lastModified = res.headers.get('last-modified') ?? undefined;
345
+ // Recorded before the body moves: a kill at any point in the stream leaves
346
+ // the validators and the expected size behind, which is what makes the next
347
+ // attempt a continuation instead of a restart.
348
+ if (rawBody && (etag || lastModified)) {
349
+ const sidecar = {
350
+ url: opts.url,
351
+ size: total,
352
+ ...(etag ? { etag } : {}),
353
+ ...(lastModified ? { lastModified } : {}),
354
+ ...(opts.sha256 ? { sha256: opts.sha256 } : {}),
355
+ savedAt: Date.now(),
356
+ };
357
+ try {
358
+ fs.writeFileSync(metaPath, `${JSON.stringify(sidecar)}\n`);
359
+ }
360
+ catch {
361
+ // Progress continues without resume support: a sidecar is an optimisation.
362
+ }
363
+ }
364
+ else {
365
+ try {
366
+ fs.rmSync(metaPath, { force: true });
367
+ }
368
+ catch {
369
+ // Nothing to remove.
370
+ }
371
+ }
372
+ const streamed = await streamBody(res, opts.partPath, append, start, opts.maxBytes, opts);
373
+ if (!rawBody) {
374
+ // The host encoded a body we asked for raw. Whatever it decoded to is not
375
+ // the release asset, so it is refused rather than installed.
376
+ cleanupAssetPart(opts.partPath);
377
+ return { ok: false, code: 'download-failed', error: `download host encoded the asset (${encoding})` };
378
+ }
379
+ if (!streamed.ok) {
380
+ // A truncated body keeps its prefix; a cap breach cannot ever be resumed.
381
+ if (streamed.code === 'download-too-large' || streamed.code === 'write-failed')
382
+ cleanupAssetPart(opts.partPath);
383
+ else if (!fs.existsSync(opts.partPath) || fs.statSync(opts.partPath).size === 0) {
384
+ // Nothing usable landed (cancelled before a byte flushed): an orphan
385
+ // sidecar would only make the next attempt look deliberate.
386
+ cleanupAssetPart(opts.partPath);
387
+ }
388
+ return streamed;
389
+ }
390
+ if (total > 0 && streamed.bytes < total) {
391
+ return { ok: false, code: 'download-incomplete', error: `download stopped at ${streamed.bytes}/${total} bytes` };
392
+ }
393
+ return finish(opts, streamed.bytes, start);
394
+ }
395
+ return { ok: false, code: 'download-failed', error: 'download failed' };
396
+ }
397
+ /** Verify and hand the part over; a mismatch or an empty file is destroyed. */
398
+ function finish(opts, size, resumedFrom) {
399
+ if (size === 0) {
400
+ cleanupAssetPart(opts.partPath);
401
+ return { ok: false, code: 'download-failed', error: 'download was empty' };
402
+ }
403
+ if (opts.sha256) {
404
+ let actual = '';
405
+ try {
406
+ actual = sha256File(opts.partPath);
407
+ }
408
+ catch (err) {
409
+ const message = err instanceof Error ? err.message : 'read failed';
410
+ cleanupAssetPart(opts.partPath);
411
+ return { ok: false, code: 'write-failed', error: `could not read the download file (${message})` };
412
+ }
413
+ if (actual !== opts.sha256) {
414
+ cleanupAssetPart(opts.partPath);
415
+ return { ok: false, code: 'checksum-failed', error: 'download checksum did not match the published digest' };
416
+ }
417
+ return { ok: true, size, resumedFrom, verified: true };
418
+ }
419
+ return { ok: true, size, resumedFrom, verified: false };
420
+ }