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,6 +1,9 @@
1
+ import { DEFAULT_QUOTA_PROBE_TIMEOUT_MS } from '../config/defaults.js';
1
2
  import { BUILTIN_QUOTA_DECLARATIONS, builtinAdapters } from './declarations.js';
2
3
  import { evalSuccessIf, resolveWindows, validateEntry } from './dsl.js';
4
+ import { captureBody, resolveVerdict, upstreamCode } from './verdict.js';
3
5
  import { getQuotaStore } from './store.js';
6
+ import { proxiedFetch } from '../utils/proxy.js';
4
7
  /**
5
8
  * Probe engine: merges the three knowledge layers into the
6
9
  * effective entry set, executes one GET probe per pair, and lands the result
@@ -196,7 +199,7 @@ pluginLayer) {
196
199
  }
197
200
  export async function runDslProbe(entry, opts) {
198
201
  const doFetch = opts.fetchImpl ?? fetch;
199
- const timeoutMs = opts.timeoutMs ?? 10_000;
202
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_QUOTA_PROBE_TIMEOUT_MS;
200
203
  const controller = new AbortController();
201
204
  const timer = setTimeout(() => controller.abort(), timeoutMs);
202
205
  const startedAt = (opts.now ?? Date.now)();
@@ -210,42 +213,64 @@ export async function runDslProbe(entry, opts) {
210
213
  headers.Authorization = opts.key;
211
214
  const res = await doFetch(entry.url, { method: 'GET', headers, signal: controller.signal });
212
215
  const meta = { url: entry.url, status: res.status, durationMs: Math.max(0, (opts.now ?? Date.now)() - startedAt) };
213
- if (res.status === 429)
214
- return { outcome: { ok: false, reason: 'status' }, rateLimited: true, http: { ...meta, ok: false } };
215
- if (res.status === 401 || res.status === 403)
216
- return { outcome: { ok: false, reason: 'auth' }, rateLimited: false, http: { ...meta, ok: false } };
217
- if (!res.ok)
218
- return { outcome: { ok: false, reason: 'status' }, rateLimited: false, http: { ...meta, ok: false } };
219
- const raw = await res.text().catch(() => '');
220
- let body = undefined;
216
+ // Words BEFORE the verdict. A rejection is the commonest quota failure (a
217
+ // dead key answers 401 on every declaration-table provider) and the upstream
218
+ // explains it in the body it sends with the 4xx — a capture that drops that
219
+ // body can only render a reason word, which is the silence this whole change
220
+ // exists to remove. So the text is read once, for every outcome; a body read
221
+ // that itself breaks keeps the status and says so in `detail`.
222
+ let bodyReadError;
223
+ const raw = await res.text().catch((err) => {
224
+ bodyReadError = failureCause(err);
225
+ return '';
226
+ });
227
+ // Parsed when it parses (the console pretty-prints an object), raw text
228
+ // otherwise (an HTML error page still says something), and bounded either
229
+ // way — never hold an arbitrarily large JSON object per pair.
230
+ let parsed;
221
231
  if (raw) {
222
232
  try {
223
- body = JSON.parse(raw);
233
+ parsed = JSON.parse(raw);
224
234
  }
225
235
  catch {
226
- return {
227
- outcome: { ok: false, reason: 'shape' },
228
- rateLimited: false,
229
- http: { ...meta, ok: false, body: raw.slice(0, LAST_BODY_MAX_CHARS) },
230
- };
236
+ parsed = undefined;
231
237
  }
232
238
  }
233
- // Oversized parsed bodies degrade to truncated text for the human-facing
234
- // capture (never hold an arbitrarily large JSON object in memory per pair).
235
- const captureBody = raw.length > LAST_BODY_MAX_JSON_CHARS ? raw.slice(0, LAST_BODY_MAX_CHARS) : body;
239
+ const http = {
240
+ ...meta,
241
+ ok: res.ok,
242
+ ...(raw ? { body: raw.length > LAST_BODY_MAX_JSON_CHARS ? raw.slice(0, LAST_BODY_MAX_CHARS) : (parsed ?? raw.slice(0, LAST_BODY_MAX_CHARS)) } : {}),
243
+ ...(bodyReadError ? { detail: `response body read failed: ${bodyReadError}` } : {}),
244
+ };
245
+ if (res.status === 429)
246
+ return { outcome: { ok: false, reason: 'status' }, rateLimited: true, http };
247
+ if (res.status === 401 || res.status === 403)
248
+ return { outcome: { ok: false, reason: 'auth' }, rateLimited: false, http };
249
+ if (!res.ok)
250
+ return { outcome: { ok: false, reason: 'status' }, rateLimited: false, http };
251
+ const body = parsed;
252
+ if (raw && body === undefined)
253
+ return { outcome: { ok: false, reason: 'shape' }, rateLimited: false, http };
236
254
  if (!evalSuccessIf(entry, body))
237
- return { outcome: { ok: false, reason: 'shape' }, rateLimited: false, http: { ...meta, ok: false, body: captureBody } };
255
+ return { outcome: { ok: false, reason: 'shape' }, rateLimited: false, http };
238
256
  const headerGetter = (name) => res.headers.get(name);
239
257
  const { windows, plan } = resolveWindows(entry, body, headerGetter);
240
258
  if (windows.length === 0)
241
- return { outcome: { ok: false, reason: 'shape' }, rateLimited: false, http: { ...meta, ok: false, body: captureBody } };
242
- return { outcome: { ok: true, windows, plan }, rateLimited: false, http: { ...meta, ok: true, body: captureBody } };
259
+ return { outcome: { ok: false, reason: 'shape' }, rateLimited: false, http };
260
+ return { outcome: { ok: true, windows, plan }, rateLimited: false, http };
243
261
  }
244
- catch {
262
+ catch (err) {
263
+ const reason = classifyThrownFailure(err);
245
264
  return {
246
- outcome: { ok: false, reason: 'network' },
265
+ outcome: { ok: false, reason },
247
266
  rateLimited: false,
248
- http: { url: entry.url, ok: false, error: 'network', durationMs: Math.max(0, (opts.now ?? Date.now)() - startedAt) },
267
+ http: {
268
+ url: entry.url,
269
+ ok: false,
270
+ error: reason,
271
+ detail: failureCause(err),
272
+ durationMs: Math.max(0, (opts.now ?? Date.now)() - startedAt),
273
+ },
249
274
  };
250
275
  }
251
276
  finally {
@@ -260,6 +285,57 @@ function oneLine(text) {
260
285
  const flat = text.replace(/\s+/g, ' ').trim();
261
286
  return flat.length > FAILURE_MESSAGE_MAX_CHARS ? `${flat.slice(0, FAILURE_MESSAGE_MAX_CHARS - 1)}…` : flat;
262
287
  }
288
+ /**
289
+ * A probe that THREW is either a timeout or a plain transport fault — it is
290
+ * never a credential verdict. Node/undici report a wall-clock timeout with
291
+ * `err.name === 'AbortError'`, the same name an operator cancel carries, and the
292
+ * first pass labelled every throw `network` while a status branch reserved
293
+ * 401/403 for `auth`: a gateway that hung (or an auth shim that answered 504)
294
+ * then read as "key rejected", which sends the operator to re-auth a working
295
+ * credential. An HTTP ANSWER keeps its own class (`status`) — 504 says
296
+ * "upstream refused · HTTP 504", which is honest; this rule is for legs that
297
+ * never got an answer at all.
298
+ */
299
+ export function classifyThrownFailure(err) {
300
+ const e = err;
301
+ const name = e?.name ?? '';
302
+ const code = typeof e?.cause?.code === 'string' ? e.cause.code : '';
303
+ if (name === 'HeadersTimeoutError' ||
304
+ name === 'BodyTimeoutError' ||
305
+ code === 'ETIMEDOUT' ||
306
+ code === 'UND_ERR_HEADERS_TIMEOUT' ||
307
+ code === 'UND_ERR_BODY_TIMEOUT' ||
308
+ e?.timedOut === true ||
309
+ /timed out|timeout/i.test(`${name} ${e?.message ?? ''} ${e?.cause?.message ?? ''}`)) {
310
+ return 'timeout';
311
+ }
312
+ return 'network';
313
+ }
314
+ /**
315
+ * The cause of a failure that produced NO captured body: error class, its
316
+ * message, the transport code Node/Bun park on `cause` (`ENOTFOUND`,
317
+ * `ECONNREFUSED`, `ETIMEDOUT`, an abort) and the vendor's own words when the
318
+ * thrown error carries them in `errorBody` instead. A probe that throws is only
319
+ * ever labelled `network`, so without this line the operator cannot tell a dead
320
+ * resolver from a refused connection from a rejected credential chain.
321
+ */
322
+ export function failureCause(err) {
323
+ const e = err;
324
+ const cause = e?.cause;
325
+ const parts = [
326
+ e?.name ?? 'Error',
327
+ typeof e?.message === 'string' && e.message ? e.message : String(err),
328
+ typeof cause?.code === 'string' ? cause.code : typeof cause?.message === 'string' ? cause.message : undefined,
329
+ ].filter((p) => Boolean(p));
330
+ // A rejection that answered with a body the executor wrapped INTO the error
331
+ // (host `UpstreamError.errorBody`) never reaches `http.body` — the quota plane
332
+ // only sees the throw. Without this the sentence the vendor DID send
333
+ // ("token was expired") disappears behind the transport label.
334
+ const body = typeof e?.errorBody === 'string' ? upstreamMessage(e.errorBody) : undefined;
335
+ if (body)
336
+ parts.push(`body: ${body}`);
337
+ return oneLine(parts.join(': '));
338
+ }
263
339
  /**
264
340
  * The upstream's own words when the body carries a recognizable envelope
265
341
  * (MiniMax `base_resp.status_msg`, the common `error.message` / `message` /
@@ -306,15 +382,40 @@ function upstreamMessage(body) {
306
382
  * HTTP status + the upstream's short message. Display-only evidence — it never
307
383
  * gates routing and never reaches the breaker plane.
308
384
  */
309
- export function probeFailureDetail(outcome, http, at) {
310
- const message = upstreamMessage(http?.body);
385
+ export function probeFailureDetail(outcome, http, at, entry) {
386
+ const message = upstreamMessage(http?.body) ?? http?.detail;
387
+ const body = captureBody(http);
388
+ const code = upstreamCode(body);
311
389
  return {
312
390
  reason: outcome.reason,
391
+ verdict: outcome.verdict ?? resolveVerdict({ reason: outcome.reason, status: http?.status, body, entry }),
392
+ ...(code !== undefined ? { upstreamCode: code } : {}),
313
393
  ...(http?.status !== undefined ? { statusCode: http.status } : {}),
314
394
  ...(message ? { message } : {}),
315
395
  at,
316
396
  };
317
397
  }
398
+ /**
399
+ * Normalize windows BEFORE they land in the store, for every source (DSL entry
400
+ * or adapter). A NEGATIVE cap is a vendor sentinel meaning 'no stated ceiling',
401
+ * never a credit count: passed through it rendered as `0 / -1`, a row that reads
402
+ * as an empty pool the account does not have. The wire type carries no remaining
403
+ * leg, so an absent ceiling cannot be rebuilt — say so with `unlimited` and drop
404
+ * the percent that was computed against it.
405
+ */
406
+ function sanitizeWindows(windows) {
407
+ return windows.map((w) => {
408
+ if (w.total === null || w.total >= 0)
409
+ return w;
410
+ return {
411
+ ...w,
412
+ used: w.used !== null && w.used >= 0 ? w.used : null,
413
+ total: null,
414
+ remainingPct: null,
415
+ unlimited: true,
416
+ };
417
+ });
418
+ }
318
419
  /**
319
420
  * Probe one pair through its effective entry (DSL or adapter) and land the
320
421
  * result in the store. Probe failure NEVER touches breakers — it keeps the
@@ -328,11 +429,46 @@ export async function probePair(target, opts) {
328
429
  let rateLimited = false;
329
430
  let entryId;
330
431
  let source;
432
+ // The effective entry, when the DSL executed it — its `refusalIf` is the
433
+ // declaration-table half of the verdict decision (see verdict.ts).
434
+ let probedEntry;
331
435
  if (target.kind === 'adapter') {
332
436
  entryId = `adapter:${target.adapter.id}`;
333
437
  source = 'probed';
334
- outcome = await target.adapter.probe({ providerId: opts.providerId, key: opts.key, fetchImpl: opts.fetchImpl, now, timeoutMs: opts.timeoutMs });
335
- http = outcome.http;
438
+ // An adapter is THIRD-PARTY code: it may reject instead of returning the
439
+ // failure object its contract asks for (an unwrapped transport call, its own
440
+ // defect). Letting that escape would kill the whole pair — no failure record,
441
+ // no capture, and the cycle dies with the other pairs unprobed — which is
442
+ // precisely the silent `—` this plane is meant to eliminate. The adapter's
443
+ // id stands in for a URL here: the throw happened before (or outside) any
444
+ // exchange core could see.
445
+ try {
446
+ // A plugin-mediated adapter declares the origins it dials; the transport
447
+ // they get is proxy-guarded per call site (ADR-0022), so the operator's
448
+ // split governs a plugin-wire quota read too. The url argument a caller
449
+ // passes to `fetchImpl` is the classification key.
450
+ let adapterFetch = opts.fetchImpl;
451
+ if (!adapterFetch && target.adapter.egressOrigins) {
452
+ adapterFetch = async (input, init) => {
453
+ // A Request carries its own method/headers/body. When the caller
454
+ // supplies no explicit init, preserve them — extracting only `.url`
455
+ // would silently degrade a credentialed POST quota read to a bare
456
+ // GET. Read the body as text so no stream/duplex handling is needed.
457
+ if (input instanceof Request && !init) {
458
+ const body = input.body ? await input.text() : undefined;
459
+ return proxiedFetch(input.url, { method: input.method, headers: input.headers, ...(body !== undefined ? { body } : {}) }, { provider: opts.providerId });
460
+ }
461
+ return proxiedFetch(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url, init, { provider: opts.providerId });
462
+ };
463
+ }
464
+ outcome = await target.adapter.probe({ providerId: opts.providerId, key: opts.key, fetchImpl: adapterFetch, now, timeoutMs: opts.timeoutMs });
465
+ http = outcome.http;
466
+ }
467
+ catch (err) {
468
+ const reason = classifyThrownFailure(err);
469
+ outcome = { ok: false, reason };
470
+ http = { url: entryId, ok: false, error: reason, detail: `adapter threw: ${failureCause(err)}` };
471
+ }
336
472
  // Any 429 from any probe (DSL or adapter) arms the engine-level global
337
473
  // backoff — adapters report it as a plain status failure, so lift it here.
338
474
  if (http?.status === 429)
@@ -340,6 +476,7 @@ export async function probePair(target, opts) {
340
476
  }
341
477
  else {
342
478
  const entry = target.entry;
479
+ probedEntry = entry;
343
480
  entryId = entry.id;
344
481
  source = entry.builtin ? 'probed' : 'forked';
345
482
  const run = await runDslProbe(entry, opts);
@@ -349,6 +486,10 @@ export async function probePair(target, opts) {
349
486
  }
350
487
  const store = getQuotaStore();
351
488
  if (outcome.ok) {
489
+ // Sanitize the OUTCOME, not just the stored copy: the returned windows are
490
+ // what a manual 'probe now' answers with, and the two views must not
491
+ // disagree about whether a cap exists.
492
+ outcome = { ...outcome, windows: sanitizeWindows(outcome.windows) };
352
493
  store.put({
353
494
  providerId: opts.providerId,
354
495
  keyHashPrefix: opts.prefix,
@@ -367,7 +508,7 @@ export async function probePair(target, opts) {
367
508
  // there is no "delete on failure" path — staleness is the honest
368
509
  // signal) AND records WHY, so a pair that never succeeded shows its
369
510
  // verdict instead of an eternal `unverified`.
370
- store.markFailure(opts.providerId, opts.prefix, probeFailureDetail(outcome, http, now()));
511
+ store.markFailure(opts.providerId, opts.prefix, probeFailureDetail(outcome, http, now(), probedEntry));
371
512
  }
372
513
  // The raw last exchange rides MEMORY-ONLY (never into the snapshot file) —
373
514
  // the console's "inspect last probe" surface reads it back here.
@@ -52,6 +52,11 @@ export interface QuotaRegistryView {
52
52
  keyHashPrefix: string;
53
53
  key: string;
54
54
  }[];
55
+ /**
56
+ * The plugin owns login and stores no OCR key (`authTypes: ['none']`).
57
+ * Quota still activates: one pair, the machine CLI login.
58
+ */
59
+ credentialless?(name: string): boolean;
55
60
  }
56
61
  /** Outcome of one manual refresh (the console button). */
57
62
  export interface QuotaRefreshReport {
@@ -1,4 +1,5 @@
1
1
  import { keyHashPrefix } from '../opencode/credentials/types.js';
2
+ import { CLI_LOGIN_QUOTA_PREFIX } from './cli-login.js';
2
3
  import { buildEffectivePlan, probePair, clampTtl } from './engine.js';
3
4
  import { getQuotaStore } from './store.js';
4
5
  import { clampProbeIntervalMs, DEFAULT_PROBE_INTERVAL_MS } from '../utils/probe-interval.js';
@@ -61,8 +62,12 @@ export class QuotaProber {
61
62
  if (this.timer)
62
63
  return;
63
64
  this.timer = setInterval(() => {
64
- this.tick().catch(() => {
65
- // Background probe cycles swallow scheduling errors — next tick retries.
65
+ this.tick().catch((err) => {
66
+ // Background probe cycles never arm a retry from here — the next tick
67
+ // comes on its own schedule. But a crash must not be invisible: this is
68
+ // the ONE line that proves the cycle ran, and a silently dead prober
69
+ // looks exactly like a vendor that never answers.
70
+ console.warn(`[quota] probe cycle failed: ${err instanceof Error ? `${err.name}: ${err.message}${err.cause instanceof Error ? ` (${err.cause.message})` : ''}` : String(err)}`);
66
71
  });
67
72
  }, this.intervalMs);
68
73
  this.timer.unref?.();
@@ -120,6 +125,10 @@ export class QuotaProber {
120
125
  * then the registry chain, then the config-baked inference key (chain-less
121
126
  * degeneracy). */
122
127
  pairsOf(providerId) {
128
+ // One machine login is one account. Stray OCR keys are not extra rows.
129
+ if (this.registry.credentialless?.(providerId)) {
130
+ return [{ providerId, keyHashPrefix: CLI_LOGIN_QUOTA_PREFIX, key: '' }];
131
+ }
123
132
  const stored = this.registry.listStoredCredentials?.(providerId);
124
133
  if (stored && stored.length > 0) {
125
134
  return stored.map((c) => ({ providerId, keyHashPrefix: c.keyHashPrefix, key: c.key }));
@@ -83,6 +83,36 @@ export interface QuotaSnapshot {
83
83
  * into `stale`; absent when attempts never failed since success. */
84
84
  lastFailureAt?: number;
85
85
  }
86
+ /**
87
+ * Closed failure vocabulary of the probe plane. `timeout` is a leg that never
88
+ * got an answer because the clock ran out; `network` is every other transport
89
+ * fault; `status` is an HTTP ANSWER that failed (including 504 — the upstream
90
+ * did speak); `shape` is an answer the probe could not read; `auth` is a
91
+ * credential the upstream rejected. Nothing outside these five may appear.
92
+ */
93
+ export type QuotaProbeFailureReason = 'network' | 'timeout' | 'status' | 'shape' | 'auth';
94
+ /**
95
+ * The ACCOUNT-level conclusion a failing probe reached, on a closed vocabulary.
96
+ *
97
+ * Why this is separate from `reason`: `reason` names the transport shape (a
98
+ * status arrived, a body could not be read) and is useless to an operator —
99
+ * "shape" over a plan that expired and "status" over a subscription that was
100
+ * never opened look identical. This field names WHAT TO DO instead, and it is
101
+ * assigned only from STRUCTURED signals an upstream states in machine-readable
102
+ * form (an HTTP status, an envelope field like `success: false` / MiniMax
103
+ * `base_resp.status_code`, or a declaration-table `refusalIf` predicate) —
104
+ * never from pattern-matching a human sentence, which cannot be done once
105
+ * without hardcoding prose per vendor in every language.
106
+ *
107
+ * `credential-rejected` a 401/403 (or an adapter's own key-rejected code):
108
+ * check the key. `plan-inactive` the account states it holds no active plan /
109
+ * subscription: renew or subscribe. `endpoint-gone` a 404 (or a body claiming
110
+ * the path does not exist): the probe URL is stale, the provider changed its
111
+ * API. `rate-limited` 429. `upstream-error` any other answer that failed.
112
+ * `unreadable` an answer the probe could not parse into windows. `unreachable`
113
+ * / `timeout` no answer at all. Absent when the attempt succeeded.
114
+ */
115
+ export type QuotaFailureVerdict = 'credential-rejected' | 'plan-inactive' | 'endpoint-gone' | 'rate-limited' | 'upstream-error' | 'unreadable' | 'unreachable' | 'timeout';
86
116
  /**
87
117
  * WHY the last attempt produced nothing — the honest answer to "covered, but
88
118
  * empty". Without it a pair whose upstream answers 401 (dead credential) or
@@ -96,10 +126,17 @@ export interface QuotaSnapshot {
96
126
  */
97
127
  export interface QuotaProbeFailure {
98
128
  /** Same closed vocabulary as `QuotaProbeOutcome.reason`. */
99
- reason: 'network' | 'status' | 'shape' | 'auth';
129
+ reason: QuotaProbeFailureReason;
130
+ /** Account-level conclusion, assigned from structured signals only (see
131
+ * `QuotaFailureVerdict`). Absent on records written by an older build. */
132
+ verdict?: QuotaFailureVerdict;
133
+ /** Envelope/native code the upstream stated, when it stated one (MiniMax
134
+ * `base_resp.status_code: 2062`, an `error.code` string, …). Evidence only. */
135
+ upstreamCode?: string | number;
100
136
  /** HTTP status when a response existed (absent for a transport failure). */
101
137
  statusCode?: number;
102
- /** Upstream's own words, collapsed to one line and length-bounded. */
138
+ /** Upstream's own words when a body came back, else the transport/credential
139
+ * cause (`LastProbeCapture.detail`) — collapsed to one line, length-bounded. */
103
140
  message?: string;
104
141
  /** Epoch ms of this attempt. */
105
142
  at: number;
@@ -127,15 +164,32 @@ export interface QuotaFieldSpec {
127
164
  /**
128
165
  * Presence/equality gate (construct `where`): `exists` = path must resolve to
129
166
  * a non-null value; `eq` = strict equality against one literal; `in` =
130
- * membership in a literal list. Value comparison (<, >, regex, time deltas)
131
- * is a BANNED class — the loader never accepts such keys (unrepresentable by
132
- * this shape).
167
+ * membership in a literal list; `truthy` = the resolved value is a truthy
168
+ * boolean (`false` = absent, so a gate can test `success == true`). Value
169
+ * comparison (<, >, regex, time deltas) is a BANNED class — the loader never
170
+ * accepts such keys (unrepresentable by this shape).
133
171
  */
134
172
  export interface QuotaWhereSpec {
135
173
  path: string;
136
174
  exists?: boolean;
137
175
  eq?: string | number | boolean;
138
176
  in?: (string | number)[];
177
+ truthy?: boolean;
178
+ }
179
+ /**
180
+ * How a declaration says "this answer, though it arrived, means the ACCOUNT
181
+ * has no plan" — the declarative carrier for `plan-inactive`.
182
+ *
183
+ * The predicate is the ordinary `where` shape (path equality / membership /
184
+ * presence over the parsed body), so the vendor's own structured field is the
185
+ * evidence: Zhipu answers `{ code: 500, msg: "…", success: false }` with HTTP
186
+ * 200, and `success: false` is a machine-readable refusal — no prose, no
187
+ * regex, no per-language string matching. A code adapter states the same
188
+ * conclusion directly with `verdict: 'plan-inactive'`.
189
+ */
190
+ export interface QuotaRefusalSpec {
191
+ /** Body predicate marking a plan-level refusal. */
192
+ where: QuotaWhereSpec;
139
193
  }
140
194
  /** Window/plan label resolution (construct nameTemplate + enumMap). */
141
195
  export interface QuotaNameSpec {
@@ -225,6 +279,10 @@ export interface QuotaProbeEntry {
225
279
  headers?: Record<string, string>;
226
280
  /** Single-equality success gate against a body field (e.g. code == 0). */
227
281
  successIf?: QuotaWhereSpec;
282
+ /** Plan-level refusal predicate: when it matches the (status-OK) body the
283
+ * probe fails with `verdict: 'plan-inactive'` — the account says it holds
284
+ * no active plan, which is an OPERATOR action (renew), not a code fault. */
285
+ refusalIf?: QuotaRefusalSpec;
228
286
  windows: QuotaWindowsSpec;
229
287
  /** Cache window for the snapshot; loader clamps to [60 s, 24 h]. */
230
288
  cacheTtlMs?: number;
@@ -246,8 +304,16 @@ export interface LastProbeCapture {
246
304
  status?: number;
247
305
  ok: boolean;
248
306
  durationMs?: number;
249
- /** Transport-level failure — no response at all. */
250
- error?: 'network';
307
+ /** Transport-level failure — no response at all (`timeout` = ran out of clock). */
308
+ error?: 'network' | 'timeout';
309
+ /** One display line naming the CAUSE when there is no upstream body to read:
310
+ * error class + message + the transport code parked on `cause` (`ENOTFOUND`,
311
+ * `ECONNREFUSED`, an abort, a rejected token-exchange chain). Without it a
312
+ * dead socket, a refused credential chain and a timed-out request all collapse
313
+ * into the same bare `network` verdict, which the console can only label
314
+ * "network failure" — the probe plane never discards the error text
315
+ * (ADR-0009 never-silent). */
316
+ detail?: string;
251
317
  /** Parsed JSON body, or truncated raw text when not JSON / oversized. */
252
318
  body?: unknown;
253
319
  }
@@ -259,7 +325,11 @@ export type QuotaProbeOutcome = {
259
325
  http?: LastProbeCapture;
260
326
  } | {
261
327
  ok: false;
262
- reason: 'network' | 'status' | 'shape' | 'auth';
328
+ reason: QuotaProbeFailureReason;
329
+ /** Set by a code adapter that already knows the account conclusion from a
330
+ * structured field it read itself (MiniMax `base_resp`); the DSL path
331
+ * leaves it absent and `resolveVerdict` derives it. */
332
+ verdict?: QuotaFailureVerdict;
263
333
  http?: LastProbeCapture;
264
334
  };
265
335
  /**
@@ -282,6 +352,15 @@ export interface QuotaCodeAdapter {
282
352
  id: string;
283
353
  /** Which covered providers resolve to this adapter (region-aware sets). */
284
354
  providerIds: string[];
355
+ /**
356
+ * Origins this adapter may dial for `providerId` — absent when the adapter
357
+ * has no plugin-mediated transport to describe (a core code adapter that
358
+ * already dials through `proxiedFetch`). Present: the engine hands `probe()`
359
+ * a `fetchImpl` that applies `proxy.includes` / `proxy.excludes` to whichever
360
+ * of these URLs the adapter actually requests, so a plugin-owned entry is
361
+ * proxied exactly like a built-in one.
362
+ */
363
+ egressOrigins?(providerId: string, baseURL?: string): readonly string[];
285
364
  probe(ctx: QuotaAdapterContext): Promise<QuotaProbeOutcome>;
286
365
  }
287
366
  /**
@@ -0,0 +1,35 @@
1
+ import type { LastProbeCapture, QuotaFailureVerdict, QuotaProbeEntry, QuotaProbeFailureReason } from './types.js';
2
+ /**
3
+ * The upstream's own code, when the body states one (`code`, `error.code`,
4
+ * MiniMax's `base_resp.status_code`). Evidence for the console, never a gate.
5
+ */
6
+ export declare function upstreamCode(body: unknown): string | number | undefined;
7
+ /**
8
+ * True when a status-OK body says, in a machine-readable field, that the call
9
+ * FAILED. Two shapes carry that: an explicit boolean refusal (`success: false`,
10
+ * `ok: false`) and a non-zero envelope code. Both are statements the vendor
11
+ * makes structurally — Zhipu's `{"code":500,"success":false}` on HTTP 200 is
12
+ * the motivating case: the transport succeeded and the ACCOUNT was refused.
13
+ */
14
+ export declare function bodyStatesRefusal(body: unknown): boolean;
15
+ /** What the caller knows about the attempt, beyond the raw capture. */
16
+ export interface VerdictContext {
17
+ reason: QuotaProbeFailureReason;
18
+ status?: number;
19
+ /** Parsed response body (absent when the body was not JSON). */
20
+ body: unknown;
21
+ /** The effective entry — its `refusalIf` is a declaration-table predicate. */
22
+ entry?: QuotaProbeEntry;
23
+ /** Set by a code adapter that already knows the conclusion (MiniMax envelope,
24
+ * credential-rejected codes). Wins over everything derived from the body. */
25
+ stated?: QuotaFailureVerdict;
26
+ }
27
+ /**
28
+ * Assign the closed verdict for one failed attempt. Precedence: an adapter's
29
+ * stated conclusion, then the declaration's `refusalIf`, then HTTP status, then
30
+ * the transport reason. Status before shape is deliberate: a 404 IS
31
+ * `endpoint-gone` even though the 404 body also fails to parse.
32
+ */
33
+ export declare function resolveVerdict(ctx: VerdictContext): QuotaFailureVerdict;
34
+ /** Pull the parsed body out of a memory-only capture (best effort). */
35
+ export declare function captureBody(http: LastProbeCapture | undefined): unknown;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Failure verdict assignment — the ONE place an account-level conclusion is
3
+ * derived from a failed probe.
4
+ *
5
+ * The rule this module exists to enforce: a verdict is assigned from a
6
+ * STRUCTURED signal the upstream stated in machine-readable form — an HTTP
7
+ * status, an envelope field (`success: false`, MiniMax `base_resp.status_code`),
8
+ * or a declaration-table `refusalIf` predicate over the parsed body. It is
9
+ * NEVER derived from pattern-matching a human sentence: quota endpoints answer
10
+ * in prose (and in every vendor's own language), so a wording rule would have
11
+ * to be written once per vendor per language — unmaintainable by construction,
12
+ * and it silently rots the moment a vendor rephrases.
13
+ *
14
+ * So the sentence travels as EVIDENCE (`QuotaProbeFailure.message`, rendered
15
+ * verbatim) while the verdict travels as a closed code the console translates
16
+ * once into eight languages.
17
+ */
18
+ /** Envelope keys that state a verdict as a boolean or a zero-is-success code. */
19
+ const SUCCESS_FLAGS = ['success', 'ok'];
20
+ const CODE_PATHS = [
21
+ ['code'],
22
+ ['error', 'code'],
23
+ ['base_resp', 'status_code'],
24
+ ['baseResp', 'statusCode'],
25
+ ];
26
+ function readPath(body, path) {
27
+ let cur = body;
28
+ for (const key of path) {
29
+ if (cur === null || typeof cur !== 'object')
30
+ return undefined;
31
+ cur = cur[key];
32
+ }
33
+ return cur;
34
+ }
35
+ /**
36
+ * The upstream's own code, when the body states one (`code`, `error.code`,
37
+ * MiniMax's `base_resp.status_code`). Evidence for the console, never a gate.
38
+ */
39
+ export function upstreamCode(body) {
40
+ for (const path of CODE_PATHS) {
41
+ const v = readPath(body, path);
42
+ if (typeof v === 'number' && Number.isFinite(v))
43
+ return v;
44
+ if (typeof v === 'string' && v.trim())
45
+ return v;
46
+ }
47
+ return undefined;
48
+ }
49
+ /**
50
+ * True when a status-OK body says, in a machine-readable field, that the call
51
+ * FAILED. Two shapes carry that: an explicit boolean refusal (`success: false`,
52
+ * `ok: false`) and a non-zero envelope code. Both are statements the vendor
53
+ * makes structurally — Zhipu's `{"code":500,"success":false}` on HTTP 200 is
54
+ * the motivating case: the transport succeeded and the ACCOUNT was refused.
55
+ */
56
+ export function bodyStatesRefusal(body) {
57
+ for (const flag of SUCCESS_FLAGS) {
58
+ const v = readPath(body, [flag]);
59
+ if (v === false)
60
+ return true;
61
+ }
62
+ const code = upstreamCode(body);
63
+ if (typeof code === 'number')
64
+ return code !== 0;
65
+ if (typeof code === 'string') {
66
+ // A textual code is only a refusal when it is a code, not a sentence: a
67
+ // numeric-looking string ('2062') counts, an error NAME ('invalid_key')
68
+ // also states refusal, while an arbitrary message does not.
69
+ return /^\d+$/.test(code) ? Number(code) !== 0 : true;
70
+ }
71
+ return false;
72
+ }
73
+ /**
74
+ * Assign the closed verdict for one failed attempt. Precedence: an adapter's
75
+ * stated conclusion, then the declaration's `refusalIf`, then HTTP status, then
76
+ * the transport reason. Status before shape is deliberate: a 404 IS
77
+ * `endpoint-gone` even though the 404 body also fails to parse.
78
+ */
79
+ export function resolveVerdict(ctx) {
80
+ if (ctx.stated)
81
+ return ctx.stated;
82
+ // The declaration-table half of the decision. Evaluated over the WHOLE
83
+ // document (no item binding), with exactly the predicate grammar the rest of
84
+ // the table uses — `dsl/evalWhere` binds to a window ITEM, so it cannot be
85
+ // reused here.
86
+ if (ctx.entry?.refusalIf && evalWhereOverDocument(ctx.entry.refusalIf.where, ctx.body))
87
+ return 'plan-inactive';
88
+ const status = ctx.status;
89
+ if (status === 401 || status === 403)
90
+ return 'credential-rejected';
91
+ if (status === 404)
92
+ return 'endpoint-gone';
93
+ if (status === 429)
94
+ return 'rate-limited';
95
+ if (status !== undefined && (status < 200 || status >= 300))
96
+ return 'upstream-error';
97
+ if (ctx.reason === 'timeout')
98
+ return 'timeout';
99
+ if (ctx.reason === 'network')
100
+ return 'unreachable';
101
+ if (ctx.reason === 'auth')
102
+ return 'credential-rejected';
103
+ // A status-OK answer that still failed: the body refused in a structured
104
+ // field (non-zero envelope code / `success: false`) or the probe could not
105
+ // read it into windows. A stated refusal is an account statement, not a
106
+ // parser fault, so it is `plan-inactive`; everything else is `unreadable`.
107
+ if (bodyStatesRefusal(ctx.body))
108
+ return 'plan-inactive';
109
+ return 'unreadable';
110
+ }
111
+ /** Minimal gate evaluation over a whole document (no item binding). */
112
+ function evalWhereOverDocument(where, body) {
113
+ const v = readPath(body, where.path.split('.'));
114
+ if (where.truthy)
115
+ return v === true;
116
+ if (where.exists !== undefined)
117
+ return where.exists ? v !== undefined && v !== null : v === undefined || v === null;
118
+ if (where.eq !== undefined) {
119
+ if (typeof where.eq === 'boolean')
120
+ return v === where.eq;
121
+ if (typeof where.eq === 'number')
122
+ return Number(v) === where.eq;
123
+ return String(v) === String(where.eq);
124
+ }
125
+ if (where.in !== undefined)
126
+ return where.in.some((c) => String(c) === String(v));
127
+ return false;
128
+ }
129
+ /** Pull the parsed body out of a memory-only capture (best effort). */
130
+ export function captureBody(http) {
131
+ const body = http?.body;
132
+ if (body === undefined)
133
+ return undefined;
134
+ return body;
135
+ }