@bitkyc08/opencodex 2.100.1 → 2.100.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 (163) hide show
  1. package/gui/dist/assets/App-BpJOzw4F.js +59 -0
  2. package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
  3. package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
  4. package/gui/dist/assets/index-Bbor_y80.js +94 -0
  5. package/gui/dist/assets/index-DJEkIDAi.css +2 -0
  6. package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
  9. package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
  10. package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
  11. package/gui/dist/classic/index.html +1 -1
  12. package/gui/dist/index.html +2 -2
  13. package/package.json +2 -2
  14. package/src/adapters/client-fingerprint.ts +5 -3
  15. package/src/adapters/cursor/native-exec.ts +3 -2
  16. package/src/adapters/cursor/tool-guidance.ts +3 -3
  17. package/src/adapters/cursor/tool-wording.ts +10 -1
  18. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  19. package/src/adapters/google-antigravity-wire.ts +13 -6
  20. package/src/adapters/google-truncation.ts +4 -2
  21. package/src/adapters/google.ts +8 -2
  22. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  23. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  24. package/src/adapters/run-turn-queue.ts +139 -5
  25. package/src/adapters/upstream-http-error.ts +4 -2
  26. package/src/bridge/sse.ts +8 -1
  27. package/src/claude/chat-tool-dispatch.ts +233 -0
  28. package/src/claude/inbound-tool-loading.ts +42 -17
  29. package/src/cli/account-api.ts +6 -0
  30. package/src/cli/account-extended.ts +60 -6
  31. package/src/cli/account-key-quota.ts +22 -2
  32. package/src/cli/account.ts +1 -1
  33. package/src/cli/capabilities-access-remote.ts +10 -0
  34. package/src/cli/capabilities-agents-routing.ts +2 -2
  35. package/src/cli/capabilities-base.ts +2 -2
  36. package/src/cli/claude.ts +19 -14
  37. package/src/cli/config-command.ts +24 -1
  38. package/src/cli/connect.ts +36 -3
  39. package/src/cli/gui-pair-client.ts +23 -2
  40. package/src/cli/help.ts +1 -1
  41. package/src/cli/hub.ts +18 -1
  42. package/src/cli/link-child-ops.ts +136 -0
  43. package/src/cli/link-status-child.ts +94 -0
  44. package/src/cli/link.ts +22 -9
  45. package/src/cli/registry.ts +3 -2
  46. package/src/cli/sync-command.ts +3 -1
  47. package/src/cli/sync-fanout.ts +8 -81
  48. package/src/client/link-readiness.ts +16 -6
  49. package/src/client/link-tunnel-status.ts +76 -0
  50. package/src/clients/config-export.ts +14 -1
  51. package/src/codex/account-resume-health.ts +41 -0
  52. package/src/codex/auth-api/login-flow.ts +6 -0
  53. package/src/codex/auth-api/routes.ts +35 -2
  54. package/src/codex/catalog/gather-capture.ts +2 -0
  55. package/src/codex/catalog/provider-models.ts +13 -8
  56. package/src/codex/convergence-types.ts +2 -0
  57. package/src/codex/quota.ts +111 -6
  58. package/src/combos/cooldown-store.ts +208 -0
  59. package/src/combos/failover.ts +432 -35
  60. package/src/config/salvage.ts +1 -0
  61. package/src/config/schema/config-schema.ts +6 -3
  62. package/src/config/schema/leaf-validators.ts +34 -12
  63. package/src/generated/compatibility-version.json +213 -121
  64. package/src/lib/catalog-etag.ts +10 -0
  65. package/src/lib/client-error-body.ts +15 -0
  66. package/src/lib/context-overflow-verdict.ts +266 -9
  67. package/src/lib/failure-detail.ts +72 -3
  68. package/src/lib/hard-refusal.ts +259 -0
  69. package/src/link/child-activity.ts +57 -0
  70. package/src/link/child-catalog-freshness.ts +149 -0
  71. package/src/link/child-gated-ocx.ts +117 -0
  72. package/src/link/child-observations.ts +205 -0
  73. package/src/link/child-observe.ts +121 -0
  74. package/src/link/child-ops-engine.ts +162 -0
  75. package/src/link/child-update-contract.ts +165 -0
  76. package/src/link/paths.ts +5 -0
  77. package/src/link/remote-windows.ts +42 -6
  78. package/src/link/ssh-argv.ts +126 -32
  79. package/src/link/status-projection.ts +73 -0
  80. package/src/link/sync-fanout-classify.ts +98 -0
  81. package/src/link/tunnel-state.ts +10 -4
  82. package/src/messaging/mcp-queue-rpc.ts +2 -1
  83. package/src/messaging/mcp-queue-server.ts +5 -0
  84. package/src/messaging/mcp-reply-tools.ts +24 -9
  85. package/src/messaging/mcp-reply-wait.ts +70 -0
  86. package/src/oauth/account-resume-health.ts +60 -0
  87. package/src/oauth/index.ts +1 -0
  88. package/src/oauth/store.ts +44 -1
  89. package/src/providers/api-key-pause-state.ts +23 -0
  90. package/src/providers/api-key-pause.ts +68 -10
  91. package/src/providers/api-key-selection-capture.ts +3 -1
  92. package/src/providers/api-key-selection.ts +3 -2
  93. package/src/providers/api-keys.ts +18 -5
  94. package/src/providers/claude-cli-usage-state.ts +11 -6
  95. package/src/providers/claude-cli-usage.ts +27 -9
  96. package/src/providers/codex-capacity.ts +11 -2
  97. package/src/providers/key-failover.ts +13 -6
  98. package/src/providers/model-discovery-config.ts +31 -0
  99. package/src/providers/model-discovery-diagnostic.ts +34 -3
  100. package/src/providers/model-discovery.ts +43 -7
  101. package/src/providers/model-rename-fields.ts +2 -0
  102. package/src/providers/openai-sidecar.ts +15 -2
  103. package/src/providers/provider-id-rewrite.ts +3 -0
  104. package/src/providers/quota/account-cache.ts +52 -34
  105. package/src/providers/quota/anthropic-usage-windows.ts +19 -9
  106. package/src/providers/quota/report-cache.ts +53 -5
  107. package/src/providers/quota/vendor-probes-key.ts +73 -0
  108. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  109. package/src/providers/quota-key-accounts.ts +12 -5
  110. package/src/providers/quota-mistral-budget.ts +18 -0
  111. package/src/providers/quota-types.ts +25 -0
  112. package/src/providers/quota.ts +22 -22
  113. package/src/providers/reasoning-metadata.ts +1051 -12
  114. package/src/quota/reset-observer.ts +4 -2
  115. package/src/quota/reset-seen-store.ts +9 -0
  116. package/src/quota/window-mapping.ts +1 -0
  117. package/src/quota-pool/assemble.ts +4 -1
  118. package/src/responses/hosted-tool-policy.ts +56 -12
  119. package/src/router.ts +2 -0
  120. package/src/server/auth-cors.ts +11 -8
  121. package/src/server/catalog-download.ts +3 -5
  122. package/src/server/chat-native.ts +11 -2
  123. package/src/server/claude-messages.ts +2 -1
  124. package/src/server/images.ts +41 -13
  125. package/src/server/index/link-listener.ts +16 -2
  126. package/src/server/index/link-relay-sessions.ts +43 -2
  127. package/src/server/index/optional-listeners.ts +18 -0
  128. package/src/server/management/config-routes.ts +7 -1
  129. package/src/server/management/context.ts +1 -1
  130. package/src/server/management/link-child-ops-routes.ts +116 -0
  131. package/src/server/management/link-route-state.ts +10 -0
  132. package/src/server/management/link-routes.ts +10 -0
  133. package/src/server/management/oauth-account-routes.ts +33 -4
  134. package/src/server/management/provider-overwrite-carry.ts +28 -3
  135. package/src/server/management/provider-routes.ts +16 -11
  136. package/src/server/management/route-registry.ts +3 -0
  137. package/src/server/messages-native.ts +5 -0
  138. package/src/server/request-log-failure-detail.ts +59 -1
  139. package/src/server/responses/adapter-dispatch.ts +35 -44
  140. package/src/server/responses/combo-stream-preflight.ts +146 -29
  141. package/src/server/responses/compact.ts +16 -5
  142. package/src/server/responses/context-overflow.ts +58 -2
  143. package/src/server/responses/core-combo-failure.ts +29 -4
  144. package/src/server/responses/core-combo-native.ts +3 -1
  145. package/src/server/responses/core-combo.ts +30 -3
  146. package/src/server/responses/core-errors.ts +3 -1
  147. package/src/server/responses/core-opaque-recovery.ts +45 -2
  148. package/src/server/responses/core-options.ts +12 -0
  149. package/src/server/responses/passthrough-dispatch.ts +30 -38
  150. package/src/server/responses/request-transport.ts +43 -14
  151. package/src/server/responses/reset-replay.ts +58 -2
  152. package/src/server/responses/run-turn-execution.ts +56 -30
  153. package/src/types/claude-tool-loading.ts +48 -0
  154. package/src/types/config.ts +5 -35
  155. package/src/types/provider.ts +21 -0
  156. package/src/types.ts +1 -0
  157. package/src/web-search/parse.ts +21 -2
  158. package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
  159. package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
  160. package/gui/dist/assets/index-Bziu8gTy.css +0 -2
  161. package/gui/dist/assets/index-OYzhQUNP.js +0 -94
  162. package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
  163. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
@@ -21,6 +21,8 @@ import { saveConfigPreservingClaudeCode } from "../../config/live-reconcile";
21
21
  import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
22
22
  import { startJevQuotaActivation } from "../../combos/jev-quota-activation";
23
23
  import { createLocalControlListener } from "./local-control-listener";
24
+ import { createCatalogPullRecorder, type CatalogPull, type CatalogPullRecorder } from "../../link/child-catalog-freshness";
25
+ import type { LinkActivitySnapshot } from "../../link/child-activity";
24
26
  export { LINK_INGRESS_HOSTNAME } from "./link-listener";
25
27
  import type { ServerIngress } from "./serve-options";
26
28
 
@@ -42,6 +44,11 @@ export interface OptionalListenerSet<T> {
42
44
  onAuthenticatedCatalog(listener: (apiKeyId: string) => void): () => void;
43
45
  notifyAuthenticatedCatalog(apiKeyId: string): void;
44
46
  peerObservation(linkId: string): import("../../link/peer-report").LinkPeerEntry;
47
+ linkActivity(linkId: string, now: number): LinkActivitySnapshot;
48
+ /** The last relayed catalog pull of a link in this process; null before start or before any pull. */
49
+ catalogPull(linkId: string): CatalogPull | null;
50
+ /** Write every catalog pull still held in memory; a failed write is logged and kept for the next attempt. */
51
+ flushCatalogPulls(): void;
45
52
  status(): LinkListenerStatus;
46
53
  linkStatus(): LinkListenerStatus;
47
54
  linkSupervisor(): LinkSupervisor;
@@ -86,6 +93,8 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
86
93
  });
87
94
  let unregisterSupervisorAdmission: (() => void) | undefined;
88
95
  let supervisorStop: (() => Promise<void>) | undefined;
96
+ let catalogPulls: CatalogPullRecorder | undefined;
97
+ let unregisterCatalogPulls: (() => void) | undefined;
89
98
 
90
99
  return {
91
100
  ensureClaudeIntercept: () => claudeIntercept.ensure(),
@@ -106,6 +115,9 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
106
115
  onAuthenticatedCatalog: listener => linkListener.onAuthenticatedCatalog(listener),
107
116
  notifyAuthenticatedCatalog: apiKeyId => linkListener.notifyAuthenticatedCatalog(apiKeyId),
108
117
  peerObservation: linkId => linkListener.peerObservation(linkId),
118
+ linkActivity: (linkId, now) => linkListener.linkActivity(linkId, now),
119
+ catalogPull: linkId => catalogPulls?.pulled(linkId) ?? null,
120
+ flushCatalogPulls: () => { catalogPulls?.flush(); },
109
121
  status: () => linkListener.status(),
110
122
  linkStatus: () => linkListener.status(),
111
123
  linkSupervisor: () => supervisor,
@@ -124,6 +136,9 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
124
136
  },
125
137
  });
126
138
  unregisterSupervisorAdmission ??= linkListener.onAuthenticatedCatalog(apiKeyId => supervisor.notifyAuthenticatedRequest?.(apiKeyId));
139
+ // Only the hub-link relay fires this, so a Home without links records nothing.
140
+ catalogPulls ??= createCatalogPullRecorder({ storePath: linkDeps.storePath });
141
+ unregisterCatalogPulls ??= linkListener.onCatalogServed(served => catalogPulls!.record(served));
127
142
  if (linkListenerOwnsTarget(linkListener.status())) {
128
143
  supervisor.start();
129
144
  }
@@ -166,6 +181,9 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
166
181
  try { await claudeIntercept.stop(); } catch (error) { failure ??= error; }
167
182
  unregisterSupervisorAdmission?.();
168
183
  unregisterSupervisorAdmission = undefined;
184
+ unregisterCatalogPulls?.();
185
+ unregisterCatalogPulls = undefined;
186
+ catalogPulls?.flush();
169
187
  stopJevQuotaActivation?.();
170
188
  stopJevQuotaActivation = undefined;
171
189
  if (failure) throw failure;
@@ -89,6 +89,7 @@ import { getUsageDebugLogEntries } from "../../usage/debug";
89
89
  import { parseRange, parseUsageSurface, summarizeUsage } from "../../usage/summary";
90
90
  import { stripCodexRuntimeProviderFields } from "../../codex/auth-context";
91
91
  import { getProviderRegistryEntry } from "../../providers/registry";
92
+ import { providerHasStoredApiKey } from "../../providers/api-keys";
92
93
  import { VISION_REASONING_EFFORTS, isVisionReasoningEffort } from "../../reasoning-effort";
93
94
  import { normalizeVisionReasoningForModel } from "../../vision/reasoning";
94
95
  import {
@@ -390,7 +391,12 @@ async function handleConfigRoutesImpl(ctx: ManagementContext): Promise<Response
390
391
  // for up to 15s, including the admin-token check. An injected reader stays authoritative.
391
392
  const readStartupHealthSnapshot = deps.getCachedStartupHealth ?? getStartupHealthSnapshot;
392
393
  if (url.pathname === "/api/config" && req.method === "GET") {
393
- return jsonResponse(withProviderCatalogCapabilityDTO(safeConfigDTO(config), config));
394
+ const dto = safeConfigDTO(config) as { providers: Record<string, Record<string, unknown>> };
395
+ for (const [name, provider] of Object.entries(config.providers)) {
396
+ const publicProvider = dto.providers[name];
397
+ if (publicProvider) publicProvider.hasApiKey = providerHasStoredApiKey(provider);
398
+ }
399
+ return jsonResponse(withProviderCatalogCapabilityDTO(dto, config));
394
400
  }
395
401
 
396
402
  if (url.pathname === "/api/config" && req.method === "PUT") {
@@ -159,7 +159,7 @@ export interface ManagementApiDeps {
159
159
  codexPromptPaths?: CodexPromptPaths;
160
160
  /** Link seams are getters so the optional listener and supervisor are singletons. */
161
161
  linkSupervisor?: () => LinkSupervisor;
162
- linkListener?: () => Pick<LinkListenerLifecycle<unknown>, "ensureStarted" | "status" | "close" | "onAuthenticatedCatalog"> & Partial<Pick<LinkListenerLifecycle<unknown>, "peerObservation">> & Partial<Pick<import("../index/optional-listeners").OptionalListenerSet<unknown>, "ensureClaudeIntercept" | "claudeInterceptOutcome">>;
162
+ linkListener?: () => Pick<LinkListenerLifecycle<unknown>, "ensureStarted" | "status" | "close" | "onAuthenticatedCatalog"> & Partial<Pick<LinkListenerLifecycle<unknown>, "peerObservation">> & Partial<Pick<import("../index/optional-listeners").OptionalListenerSet<unknown>, "ensureClaudeIntercept" | "claudeInterceptOutcome" | "linkActivity" | "catalogPull" | "flushCatalogPulls">>;
163
163
  readLinkStore?: () => LinkStore;
164
164
  writeLinkStore?: (store: LinkStore) => void;
165
165
  linkKnownHostsPath?: () => string;
@@ -0,0 +1,116 @@
1
+ import { DEFAULT_IDLE_AFTER_MS } from "../../link/child-activity";
2
+ import { createCatalogRevisionMonitor, type CatalogRevisionMonitor } from "../../link/child-catalog-freshness";
3
+ import { observeChild } from "../../link/child-observe";
4
+ import { patchChildObservation, readChildObservations, updateChildObservations } from "../../link/child-observations";
5
+ import { createChildOpsEngine, type ChildOpsEngine } from "../../link/child-ops-engine";
6
+ import { requireRemotePlatform } from "../../link/remote-platform";
7
+ import { inspectRemoteChildRuntime } from "../../link/remote-plant";
8
+ import { attachLinkChildOps, type LinkStatusDto } from "../../link/status-projection";
9
+ import type { LinkStore } from "../../link/store";
10
+ import { packageVersion } from "../../lib/package-version";
11
+ import { readCatalog, readCodexCatalogPath } from "../../codex/catalog";
12
+ import type { ManagementContext } from "./context";
13
+ import { readManagementJsonBodyOr } from "./body";
14
+ import { auth, exactBody, fail, knownHostsFile, readStoreFor, runnerFor, type LinkRouteState } from "./link-route-state";
15
+
16
+ const LINK_ID = /^lnk_[0-9a-f]{16}$/;
17
+ const JOB_ID = /^ljob_[0-9a-f]{16}$/;
18
+ const MAX_LINK_IDS = 64;
19
+ const JOB_PATH = /^\/api\/link\/children\/jobs\/([^/]+)$/;
20
+
21
+ let revisionMonitor: CatalogRevisionMonitor | undefined;
22
+
23
+ /**
24
+ * The production Home catalog revision: the exact bytes `/v1/catalog` serves, hashed like its etag, with the
25
+ * revision persisted as `homeCatalog` in child-observations.json. Created lazily on the first `?children=1` read.
26
+ */
27
+ export function catalogRevisionForRoutes(): CatalogRevisionMonitor {
28
+ return revisionMonitor ??= createCatalogRevisionMonitor({
29
+ catalogPath: () => readCodexCatalogPath(),
30
+ read: path => {
31
+ const catalog = readCatalog(path);
32
+ return catalog ? JSON.stringify(catalog) : null;
33
+ },
34
+ load: () => readChildObservations().homeCatalog,
35
+ persist: revision => { updateChildObservations(file => { file.homeCatalog = revision; }); },
36
+ });
37
+ }
38
+
39
+ /** Exactly {op:"observe", linkIds: "all" | 1..64 distinct link ids}; wp2 admits no other op or key. */
40
+ export function parseOperation(body: unknown): { op: "observe"; linkIds: readonly string[] | "all" } | null {
41
+ const value = exactBody(body, ["op", "linkIds"]);
42
+ if (!value || value.op !== "observe") return null;
43
+ if (value.linkIds === "all") return { op: "observe", linkIds: "all" };
44
+ if (!Array.isArray(value.linkIds) || value.linkIds.length === 0 || value.linkIds.length > MAX_LINK_IDS) return null;
45
+ if (!value.linkIds.every(id => typeof id === "string" && LINK_ID.test(id))) return null;
46
+ if (new Set(value.linkIds).size !== value.linkIds.length) return null;
47
+ return { op: "observe", linkIds: value.linkIds as string[] };
48
+ }
49
+
50
+ /** One engine per route state: the per-link lock and the job registry are this Home process's. */
51
+ export function childOpsEngineFor(ctx: ManagementContext, state: LinkRouteState): ChildOpsEngine {
52
+ const now = () => new Date((ctx.deps.now ?? Date.now)());
53
+ return state.childOps ??= createChildOpsEngine({
54
+ readStore: () => readStoreFor(ctx),
55
+ observe: record => {
56
+ const runner = runnerFor(ctx);
57
+ const hosts = knownHostsFile(ctx);
58
+ return observeChild(record, {
59
+ runner, knownHostsFile: hosts, homeVersion: packageVersion("0.0.0"),
60
+ peer: linkId => state.listener.peerObservation?.(linkId) ?? { observed: null, refused: null },
61
+ platformOf: link => requireRemotePlatform(runner, link.alias, hosts),
62
+ inspect: inspectRemoteChildRuntime, now,
63
+ });
64
+ },
65
+ writeObservation: (linkId, patch) => { updateChildObservations(file => patchChildObservation(file, linkId, patch, now())); },
66
+ now,
67
+ });
68
+ }
69
+
70
+ /** `?children=1` on a Home: attach every row's `child` block. Never fails on the cache or the revision save. */
71
+ export function attachLinkChildOpsForState(dto: LinkStatusDto, state: LinkRouteState, store: LinkStore, now: number = Date.now()): LinkStatusDto {
72
+ // A pull inside the recorder's write window would otherwise reach the file only at the next pull or at shutdown.
73
+ // Best effort: a lock failure is logged by the recorder and retried later; the status read never fails on it.
74
+ state.listener.flushCatalogPulls?.();
75
+ const revision = (state.catalogRevision ??= catalogRevisionForRoutes()).current();
76
+ const observations = readChildObservations();
77
+ const known = new Set(store.links.map(link => link.id));
78
+ return attachLinkChildOps(dto, {
79
+ homeVersion: packageVersion("0.0.0"), now, idleAfterMs: DEFAULT_IDLE_AFTER_MS, revision,
80
+ peerVersion: linkId => state.listener.peerObservation?.(linkId).observed?.version ?? null,
81
+ observation: linkId => known.has(linkId) ? observations.children[linkId] ?? null : null,
82
+ activity: linkId => state.listener.linkActivity?.(linkId, now) ?? null,
83
+ catalogPull: linkId => state.listener.catalogPull?.(linkId) ?? null,
84
+ activeJob: linkId => state.childOps?.activeJob(linkId) ?? null,
85
+ });
86
+ }
87
+
88
+ export async function handleLinkChildOpsRoutes(ctx: ManagementContext, state: LinkRouteState): Promise<Response | null> {
89
+ const { url, req } = ctx;
90
+ const path = url.pathname;
91
+ const denied = auth(ctx, "either");
92
+ if (denied) return denied;
93
+ if (url.pathname === "/api/link/children/operations" && req.method === "POST") {
94
+ if (ctx.config.runtimeRole === "client") return fail("runtime_role_client", "A Child runtime does not operate other Children.", 409);
95
+ const operation = parseOperation(await readManagementJsonBodyOr(req, null));
96
+ if (!operation) return fail("invalid_body", "The body must be exactly {op:\"observe\", linkIds}.", 400);
97
+ let result: ReturnType<ChildOpsEngine["submit"]>;
98
+ try {
99
+ result = childOpsEngineFor(ctx, state).submit({ ...operation, trigger: "manual" });
100
+ } catch { return fail("link_unavailable", "The link store could not be read.", 503); }
101
+ if (result.ok) return Response.json({ job: result.job }, { status: 202, headers: { "cache-control": "no-store" } });
102
+ if (result.code === "link_not_found") return fail("link_not_found", "The link was not found.", 404);
103
+ if (result.code === "link_operation_in_progress") return fail("link_operation_in_progress", "Another operation is running on this link.", 409);
104
+ return fail("no_eligible_links", "There is no link to operate on.", 409);
105
+ }
106
+ const jobPath = req.method === "GET" ? JOB_PATH.exec(path) : null;
107
+ if (jobPath) {
108
+ let jobId: string;
109
+ try { jobId = decodeURIComponent(jobPath[1]!); } catch { return fail("invalid_job_id", "The job id is invalid.", 400); }
110
+ if (!JOB_ID.test(jobId)) return fail("invalid_job_id", "The job id is invalid.", 400);
111
+ const job = state.childOps?.job(jobId);
112
+ if (!job) return fail("job_not_found", "The job was not found.", 404);
113
+ return Response.json({ job }, { headers: { "cache-control": "no-store" } });
114
+ }
115
+ return fail("not_found", "Not found.", 404);
116
+ }
@@ -35,6 +35,12 @@ export interface LinkRouteListener {
35
35
  onAuthenticatedCatalog(listener: (apiKeyId: string) => void): () => void;
36
36
  /** Optional so route fakes stay small; without it every link reports an unknown peer. */
37
37
  peerObservation?(linkId: string): import("../../link/peer-report").LinkPeerEntry;
38
+ /** Optional: without it every link's activity reads unknown (never idle). */
39
+ linkActivity?(linkId: string, now: number): import("../../link/child-activity").LinkActivitySnapshot;
40
+ /** Optional: without it only the cached pull in child-observations.json is known. */
41
+ catalogPull?(linkId: string): import("../../link/child-catalog-freshness").CatalogPull | null;
42
+ /** Optional: persist pulls held inside the recorder's 30 s write window (best effort). */
43
+ flushCatalogPulls?(): void;
38
44
  }
39
45
 
40
46
  export interface LinkRouteState {
@@ -44,6 +50,10 @@ export interface LinkRouteState {
44
50
  compensationFailures?: Map<string, { since: string; reason: "compensation_failed" }>;
45
51
  supervisor: import("../../link/supervisor").LinkSupervisor;
46
52
  listener: LinkRouteListener;
53
+ /** Created on the first Child-operations request (link-child-ops-routes.ts). */
54
+ childOps?: import("../../link/child-ops-engine").ChildOpsEngine;
55
+ /** The Home catalog revision read on `?children=1`; defaults to the shared production monitor. */
56
+ catalogRevision?: import("../../link/child-catalog-freshness").CatalogRevisionMonitor;
47
57
  }
48
58
 
49
59
  export function fail(code: string, message: string, status: number, hint?: string): Response {
@@ -312,6 +312,11 @@ export async function handleLinkRoutes(ctx: ManagementContext, suppliedState?: L
312
312
  }
313
313
  // The same opt-in for each Home-initiated tunnel's retry progress and last failure cause.
314
314
  if (url.searchParams.get("diagnostics") === "1") attachLinkTunnelDiagnostics(dto, supervisorStates);
315
+ // The same opt-in for each Home row's Child versions, catalog freshness, activity and operations.
316
+ if (url.searchParams.get("children") === "1" && dto.role === "home") {
317
+ const { attachLinkChildOpsForState } = await import("./link-child-ops-routes");
318
+ attachLinkChildOpsForState(dto, state, store, (ctx.deps.now ?? Date.now)());
319
+ }
315
320
  // A dashboard session also learns why it cannot join as a Child. The admin-token answer stays
316
321
  // the exact K16 document that `ocx link status` validates key by key.
317
322
  const denial = ctx.principal === "gui-session" ? joinDenied(ctx) : null;
@@ -344,6 +349,11 @@ export async function handleLinkRoutes(ctx: ManagementContext, suppliedState?: L
344
349
  if (denied) return denied;
345
350
  return issue(ctx);
346
351
  }
352
+ // Before the reconnect and DELETE matchers, which would read "children" as a link id.
353
+ if (path.startsWith("/api/link/children/")) {
354
+ const { handleLinkChildOpsRoutes } = await import("./link-child-ops-routes");
355
+ return handleLinkChildOpsRoutes(ctx, state);
356
+ }
347
357
  const reconnectPath = req.method === "POST" ? /^\/api\/link\/([^/]+)\/reconnect$/.exec(path) : null;
348
358
  if (reconnectPath) {
349
359
  const denied = auth(ctx, "either");
@@ -644,6 +644,12 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
644
644
  if (body.retryAffinityReset !== undefined && typeof body.retryAffinityReset !== "boolean") {
645
645
  return jsonResponse({ error: "retryAffinityReset must be a boolean" }, 400);
646
646
  }
647
+ if (body.ifHealthy !== undefined && typeof body.ifHealthy !== "boolean") {
648
+ return jsonResponse({ error: "ifHealthy must be a boolean" }, 400);
649
+ }
650
+ if (body.ifHealthy === true && body.paused !== false) {
651
+ return jsonResponse({ error: "ifHealthy applies only to a resume (paused: false)" }, 400);
652
+ }
647
653
 
648
654
  const { isGenericFailoverProvider } = await import("../../oauth/generic-account-failover");
649
655
  const effectiveProvider = genericOAuthProviderConfig(provider, config);
@@ -653,8 +659,31 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
653
659
  }
654
660
 
655
661
  const { setAccountPaused } = await import("../../oauth/store");
656
- const result = await setAccountPaused(provider, body.accountId, body.paused);
662
+ let resumeGuard: { generation: string; pauseRevision: string | undefined } | undefined;
663
+ if (body.ifHealthy === true) {
664
+ // Explicit resume gated on an account-bound health read (#8398); an unpaused account needs none.
665
+ const { checkOAuthResumeHealth } = await import("../../oauth/account-resume-health");
666
+ const verdict = await checkOAuthResumeHealth(provider, body.accountId);
667
+ if (verdict && !verdict.ok) {
668
+ return jsonResponse({ error: `account was not resumed: ${verdict.reason}`, code: "resume_refused", reason: verdict.reason,
669
+ provider, accountId: body.accountId }, 409);
670
+ }
671
+ if (!verdict) {
672
+ // Not paused when checked: write nothing, so a pause that lands meanwhile is never cleared unchecked.
673
+ const { getAccountSet } = await import("../../oauth/store");
674
+ const set = getAccountSet(provider);
675
+ if (!set?.accounts.some(account => account.id === body.accountId)) return jsonResponse({ error: "account not found" }, 404);
676
+ return jsonResponse({ ok: true, provider, accountId: body.accountId, paused: false, unchanged: true,
677
+ activeAccountId: set.activeAccountId, activeAccountChanged: false });
678
+ }
679
+ resumeGuard = { generation: verdict.generation, pauseRevision: verdict.pauseRevision };
680
+ }
681
+ const result = await setAccountPaused(provider, body.accountId, body.paused, undefined, resumeGuard);
657
682
  if (result.status === "not-found") return jsonResponse({ error: "account not found" }, 404);
683
+ if (result.status === "changed") {
684
+ return jsonResponse({ error: "account was not resumed: account_changed", code: "resume_refused", reason: "account_changed",
685
+ provider, accountId: body.accountId }, 409);
686
+ }
658
687
 
659
688
  const anthropicRouting = isAnthropicOAuthInstance(provider)
660
689
  ? (await import("../../oauth/anthropic-routing")).anthropicRoutingFor(provider) : undefined;
@@ -1196,9 +1225,9 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
1196
1225
  if (!isPlainRecord(body)) return jsonResponse({ error: "body must be an object" }, 400);
1197
1226
  if (typeof body.name !== "string" || typeof body.id !== "string" || typeof body.paused !== "boolean") return jsonResponse({ error: "name, id and paused required" }, 400);
1198
1227
  if (!isValidProviderName(body.name) || !hasOwnProvider(config.providers, body.name)) return jsonResponse({ error: "unknown provider" }, 404);
1199
- const { setProviderApiKeyPaused } = await import("../../providers/api-key-pause");
1200
- return setProviderApiKeyPaused(config, body.name, body.id, body.paused)
1201
- ? jsonResponse({ ok: true }) : jsonResponse({ error: "key not found" }, 404);
1228
+ const { setProviderApiKeyPausedWithResult } = await import("../../providers/api-key-pause");
1229
+ const result = setProviderApiKeyPausedWithResult(config, body.name, body.id, body.paused);
1230
+ return result.ok ? jsonResponse(result) : jsonResponse({ error: "key not found" }, 404);
1202
1231
  }
1203
1232
  if (url.pathname === "/api/providers/keys/active" && req.method === "PUT") {
1204
1233
  const body = await readManagementJsonBodyOr(req, {}) as { name?: string; id?: string };
@@ -5,6 +5,7 @@ import {
5
5
  transientRetryOn5xxPolicyConfigError,
6
6
  } from "../../config/load-degrade";
7
7
  import type { OcxProviderConfig } from "../../types";
8
+ import { providerModelDiscoveryConfigError } from "../../providers/model-discovery-config";
8
9
 
9
10
  /**
10
11
  * The retry policies. They are the one carried group the PATCH field mask did not know, and they
@@ -57,6 +58,11 @@ export const PROVIDER_COMPAT_CARRY_FIELDS = [
57
58
  "singleLeadingSystemMessage",
58
59
  "reasoningWireFormat",
59
60
  "omitReasoningEffortWithToolsModels",
61
+ // Hosted-tool denials describe the same upstream, and the form sends neither. They travel
62
+ // together: carrying only the conditional list (#8204) would let a hosted-only request
63
+ // forward a tool the dropped unconditional list had denied.
64
+ "unsupportedHostedTools",
65
+ "unsupportedHostedToolsWithClientTools",
60
66
  ...RETRY_POLICY_FIELDS,
61
67
  ] as const satisfies readonly (keyof OcxProviderConfig)[];
62
68
 
@@ -71,6 +77,15 @@ export const PROVIDER_DISPLAY_CARRY_FIELDS = [
71
77
  export type ProviderCompatCarryField = typeof PROVIDER_COMPAT_CARRY_FIELDS[number];
72
78
  type ProviderDisplayCarryField = typeof PROVIDER_DISPLAY_CARRY_FIELDS[number];
73
79
 
80
+ /**
81
+ * Discovery compatibility (#7910). `modelDiscovery.skipInvalidRows` records that one gateway
82
+ * publishes invalid `/models` rows, so it follows the compatibility settings' destination rule:
83
+ * kept on a same-destination overwrite that omits it, dropped when the provider moves. It is a
84
+ * separate group because it changes discovery, not the request the compatibility cases probe.
85
+ */
86
+ export const PROVIDER_DISCOVERY_CARRY_FIELDS = ["modelDiscovery"] as const satisfies readonly (keyof OcxProviderConfig)[];
87
+ type ProviderDiscoveryCarryField = typeof PROVIDER_DISCOVERY_CARRY_FIELDS[number];
88
+
74
89
  /** The only `reasoningWireFormat` value the adapters understand. */
75
90
  export const PROVIDER_REASONING_WIRE_FORMATS: readonly NonNullable<OcxProviderConfig["reasoningWireFormat"]>[] = [
76
91
  "gateway-object",
@@ -81,13 +96,14 @@ export const PROVIDER_REASONING_WIRE_FORMATS: readonly NonNullable<OcxProviderCo
81
96
  * omitted this" and "the registry supplied it" look the same.
82
97
  */
83
98
  export interface ProviderOverwriteSample {
84
- readonly submitted: ReadonlySet<ProviderCompatCarryField | ProviderDisplayCarryField>;
99
+ readonly submitted: ReadonlySet<ProviderCompatCarryField | ProviderDisplayCarryField | ProviderDiscoveryCarryField>;
85
100
  readonly namesAuthMode: boolean;
86
101
  }
87
102
 
88
103
  export function sampleProviderOverwrite(provider: object): ProviderOverwriteSample {
89
104
  return {
90
- submitted: new Set([...PROVIDER_COMPAT_CARRY_FIELDS, ...PROVIDER_DISPLAY_CARRY_FIELDS].filter(field => Object.hasOwn(provider, field))),
105
+ submitted: new Set([...PROVIDER_COMPAT_CARRY_FIELDS, ...PROVIDER_DISPLAY_CARRY_FIELDS, ...PROVIDER_DISCOVERY_CARRY_FIELDS]
106
+ .filter(field => Object.hasOwn(provider, field))),
91
107
  namesAuthMode: Object.hasOwn(provider, "authMode"),
92
108
  };
93
109
  }
@@ -141,7 +157,7 @@ export function carryProviderCompatFields(
141
157
  if (stored !== undefined) target[field] = stored !== null && typeof stored === "object" ? structuredClone(stored) : stored;
142
158
  }
143
159
  if (!providerOverwriteKeepsDestination(candidate, live, sample)) return;
144
- for (const field of PROVIDER_COMPAT_CARRY_FIELDS) {
160
+ for (const field of [...PROVIDER_COMPAT_CARRY_FIELDS, ...PROVIDER_DISCOVERY_CARRY_FIELDS]) {
145
161
  if (sample.submitted.has(field)) continue;
146
162
  const stored = live[field];
147
163
  if (stored === undefined) continue;
@@ -278,5 +294,14 @@ export function applyProviderCompatPatchFields(
278
294
  }
279
295
  touched = true;
280
296
  }
297
+ // `null` or `{}` clears the block; anything else must pass the same check POST applies.
298
+ if (Object.hasOwn(rawBody, "modelDiscovery")) {
299
+ const value = rawBody.modelDiscovery;
300
+ const error = value === null ? null : providerModelDiscoveryConfigError(value);
301
+ if (error) return { error };
302
+ if (value === null || Object.keys(value as object).length === 0) delete next.modelDiscovery;
303
+ else next.modelDiscovery = structuredClone(value) as NonNullable<OcxProviderConfig["modelDiscovery"]>;
304
+ touched = true;
305
+ }
281
306
  return { touched };
282
307
  }
@@ -2,6 +2,7 @@ import { contextTierRecordConfigError, modelCapabilitiesConfigError, mergeModelC
2
2
  import { DECLARABLE_HOSTED_TOOL_TYPES } from "../../responses/hosted-tool-policy";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { cleanupRemovedGcpCredentials, providerGcpCredentialMarkers, snapshotProviderGcpCredentialMarkers } from "../../providers/gcp-credential-cleanup";
5
+ import { providerHasStoredApiKey } from "../../providers/api-keys";
5
6
  import { providerGcpCredentialInputResponse, removeProviderWithGcpCredentials } from "./provider-gcp-credential-routes";
6
7
  import { readFileSync } from "node:fs";
7
8
  import { isDeepStrictEqual } from "node:util";
@@ -720,23 +721,25 @@ function applyProviderPatchFields(
720
721
  }
721
722
  touched = true;
722
723
  }
723
- if (Object.hasOwn(rawBody, "unsupportedHostedTools")) {
724
- const value = rawBody.unsupportedHostedTools;
724
+ // The conditional list (#8204) shares the unconditional list's vocabulary and clearing rules.
725
+ for (const field of ["unsupportedHostedTools", "unsupportedHostedToolsWithClientTools"] as const) {
726
+ if (!Object.hasOwn(rawBody, field)) continue;
727
+ const value = rawBody[field];
725
728
  if (value === null) {
726
- delete next.unsupportedHostedTools;
729
+ delete next[field];
727
730
  } else {
728
- const error = nonBlankStringArrayConfigError(value, "unsupportedHostedTools");
731
+ const error = nonBlankStringArrayConfigError(value, field);
729
732
  if (error) return { error };
730
733
  const tools = normalizeNonBlankStringArray(value as string[]);
731
734
  const unknownTool = tools.find(tool => !DECLARABLE_HOSTED_TOOL_TYPES.has(tool));
732
735
  if (unknownTool !== undefined) {
733
736
  return {
734
- error: `unsupportedHostedTools must name only hosted tool types: `
737
+ error: `${field} must name only hosted tool types: `
735
738
  + `${[...DECLARABLE_HOSTED_TOOL_TYPES].join(", ")}`,
736
739
  };
737
740
  }
738
- if (tools.length > 0) next.unsupportedHostedTools = tools;
739
- else delete next.unsupportedHostedTools;
741
+ if (tools.length > 0) next[field] = tools;
742
+ else delete next[field];
740
743
  }
741
744
  touched = true;
742
745
  }
@@ -915,7 +918,8 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
915
918
 
916
919
  if (url.pathname === "/api/providers" && req.method === "GET") {
917
920
  return jsonResponse(Object.entries(config.providers).map(([name, p]) => ({
918
- name, adapter: p.adapter, baseUrl: publicProviderBaseUrl(p.baseUrl), defaultModel: p.defaultModel, hasApiKey: !!p.apiKey,
921
+ name, adapter: p.adapter, baseUrl: publicProviderBaseUrl(p.baseUrl), defaultModel: p.defaultModel,
922
+ hasApiKey: providerHasStoredApiKey(p),
919
923
  // Presence only (#959 review): header names and values never leave the process.
920
924
  hasHeaders: !!p.headers && Object.keys(p.headers).length > 0,
921
925
  allowPrivateNetwork: p.allowPrivateNetwork === true,
@@ -937,6 +941,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
937
941
  noStructuredOutputModels: p.noStructuredOutputModels,
938
942
  noJsonSchemaModels: p.noJsonSchemaModels,
939
943
  unsupportedHostedTools: p.unsupportedHostedTools,
944
+ unsupportedHostedToolsWithClientTools: p.unsupportedHostedToolsWithClientTools,
940
945
  retainModels: p.retainModels,
941
946
  omitReasoningEffortWithToolsModels: p.omitReasoningEffortWithToolsModels,
942
947
  upstreamHttpVersion: p.upstreamHttpVersion,
@@ -1613,7 +1618,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1613
1618
  success: true,
1614
1619
  name,
1615
1620
  disabled: config.providers[name]!.disabled === true,
1616
- hasApiKey: !!config.providers[name]!.apiKey,
1621
+ hasApiKey: providerHasStoredApiKey(config.providers[name]!),
1617
1622
  ...(shadowDependency ? { dependentShadowIntercept: shadowDependency } : {}),
1618
1623
  ...(name === "xai"
1619
1624
  ? { xaiResponsesOptInState: xaiResponsesOptInState(config.providers[name]!) }
@@ -1798,7 +1803,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1798
1803
  latencyMs,
1799
1804
  error: extracted.reason === "too_many_models"
1800
1805
  ? `upstream /models exceeded the ${discovery.maxModels}-row model limit`
1801
- : `upstream /models returned an unexpected shape${invalidModelDiscoveryHint("diagnostic" in extracted && typeof extracted.diagnostic === "string" ? extracted.diagnostic : undefined)}`,
1806
+ : `upstream /models returned an unexpected shape${invalidModelDiscoveryHint("diagnostic" in extracted && typeof extracted.diagnostic === "string" ? extracted.diagnostic : undefined, discovery.skipInvalidRows === true)}`,
1802
1807
  });
1803
1808
  }
1804
1809
  const models = ccaModels?.length ?? ("items" in extracted! ? extracted!.items.length : extracted!.rows.length);
@@ -1806,7 +1811,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1806
1811
  ok: true,
1807
1812
  latencyMs,
1808
1813
  models,
1809
- message: `Connected — ${models} model${models === 1 ? "" : "s"} available.`,
1814
+ message: `Connected — ${models} model${models === 1 ? "" : "s"} available${extracted && "skippedInvalidRows" in extracted && extracted.skippedInvalidRows ? ` (${extracted.skippedInvalidRows} invalid row${extracted.skippedInvalidRows === 1 ? "" : "s"} skipped)` : ""}.`,
1810
1815
  });
1811
1816
  } catch (err) {
1812
1817
  return jsonResponse({
@@ -437,6 +437,9 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [
437
437
  { method: "DELETE", path: "/api/link/{id}", module: "server/management/link-routes", mutates: true, mechanism: "regex" },
438
438
  { method: "POST", path: "/api/link/{id}/reconnect", module: "server/management/link-routes", mutates: true, mechanism: "regex" },
439
439
  { method: "POST", path: "/api/link/issue", module: "server/management/link-routes", mutates: true },
440
+ // server/management/link-child-ops-routes (reached through link-routes)
441
+ { method: "POST", path: "/api/link/children/operations", module: "server/management/link-child-ops-routes", mutates: true },
442
+ { method: "GET", path: "/api/link/children/jobs/{jobId}", module: "server/management/link-child-ops-routes", mutates: false, mechanism: "regex" },
440
443
  // server/management/remote-workspace-routes
441
444
  { method: "GET", path: "/api/remote-workspace", module: "server/management/remote-workspace-routes", mutates: false },
442
445
  { method: "GET", path: "/api/remote-workspace/runtimes", module: "server/management/remote-workspace-routes", mutates: false },
@@ -72,6 +72,7 @@ import {
72
72
  UPSTREAM_RESET_REPLAY_REFUSED_CODE,
73
73
  } from "../lib/upstream-retry";
74
74
  import { distributedKeyPhysicalFetch, distributedKeyResponseOwner, recordDistributedResponseFailure } from "../providers/api-key-response-ownership";
75
+ import { isProviderApiKeyPaused, ProviderApiKeyPausedError } from "../providers/api-key-pause";
75
76
  import { providerApiKeySelectionIsCurrent, resolveCurrentProviderApiKeyTransport } from "../providers/api-key-selection";
76
77
  import { RequestPacingQueueOverloadError } from "../providers/request-pacing";
77
78
  import {
@@ -539,8 +540,11 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
539
540
  try {
540
541
  const proactiveKeyProvider = selectProactiveApiKeyTransport(config, route.providerName, route.provider);
541
542
  if (proactiveKeyProvider) route.provider = proactiveKeyProvider;
543
+ if (isProviderApiKeyPaused(route.provider)) throw new ProviderApiKeyPausedError();
542
544
  } catch (error) {
543
545
  cleanupAbort(); upstream.abort();
546
+ const localRefusal = localOAuthFailure(error);
547
+ if (localRefusal) return localRefusal;
544
548
  if (!(error instanceof RequestPacingQueueOverloadError)) throw error;
545
549
  const refusal = markProxyError(fail(429, error.message, "rate_limit_error"), error.reason === "keys_exhausted" ? undefined : "pacing");
546
550
  const advice = formatClientRetryAfter(error.retryAfterSeconds);
@@ -699,6 +703,7 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp
699
703
  if (fresh) current = selectProactiveApiKeyTransport(config, route.providerName, fresh) ?? fresh;
700
704
  }
701
705
  if (!current || nativeMessagesDeclineReason({ ...route, provider: current }, body, config, selector) !== undefined) {
706
+ if (!current && isProviderApiKeyPaused(config.providers[route.providerName])) throw new ProviderApiKeyPausedError();
702
707
  throw markProxyError(new Error("Provider key selection is no longer available for native Messages"));
703
708
  }
704
709
  rebuildFor(current);
@@ -10,7 +10,7 @@ import { knownModelIdentity } from "../lib/model-identity";
10
10
  * upstreamError, which internal classifiers and status heuristics read and which never reaches a row.
11
11
  * Only proxy-composed text may be passed here.
12
12
  */
13
- import { boundedFailureDetail, type FailureDetail, type FailureDetailCode } from "../lib/failure-detail";
13
+ import { boundedFailureDetail, providerErrorTypeOf, providerFailureDetailOf, type FailureDetail, type FailureDetailCode } from "../lib/failure-detail";
14
14
 
15
15
  export type { FailureDetail };
16
16
 
@@ -95,3 +95,61 @@ export function recordUpstreamValidationDetail(logCtx: { failureDetail?: Failure
95
95
  ? record.error as Record<string, unknown> : undefined;
96
96
  logCtx.failureDetail = boundedFailureDetail({ code: "provider_error", type: nested?.type ?? record.type, validation });
97
97
  }
98
+
99
+ /**
100
+ * Capture the closed provider error class from a raw upstream error body (#8446): the envelope
101
+ * `type` (Anthropic/OpenAI) or Google's `error.status`, the latter also as the first element of a
102
+ * streamed JSON array. Validation pairs keep their existing capture and win when present. Only
103
+ * callers holding the provider's own body may use this; a body this proxy formatted is not evidence.
104
+ * An adapter transport that rewrote the body (normalizeUpstreamHttpErrorResponse) attached the class
105
+ * it read from the original to `response`, which is preferred.
106
+ */
107
+ export function recordUpstreamProviderErrorDetail(
108
+ logCtx: { failureDetail?: FailureDetail },
109
+ status: number,
110
+ payload: unknown,
111
+ response?: object,
112
+ ): void {
113
+ if (status < 400 || status >= 600) return;
114
+ const before = logCtx.failureDetail;
115
+ recordUpstreamValidationDetail(logCtx, status, payload);
116
+ if (logCtx.failureDetail !== before) { providerDetails.set(logCtx, logCtx.failureDetail!); return; }
117
+ let type = response ? providerFailureDetailOf(response)?.type : undefined;
118
+ if (type === undefined) {
119
+ let parsed = payload;
120
+ if (typeof payload === "string") {
121
+ if (payload.length > 256 * 1024) return;
122
+ try { parsed = JSON.parse(payload); } catch { return; }
123
+ }
124
+ type = providerErrorTypeOf(parsed);
125
+ }
126
+ if (type === undefined) return;
127
+ const detail: FailureDetail = { code: "provider_error", type };
128
+ logCtx.failureDetail = detail;
129
+ providerDetails.set(logCtx, detail);
130
+ }
131
+
132
+ /** The provider detail each context last recorded, so a later success can retract exactly that one. */
133
+ const providerDetails = new WeakMap<object, FailureDetail>();
134
+
135
+ /**
136
+ * Request-log side of every adapter event (the parse seam in request-transport.ts). An error event an
137
+ * adapter tagged with closed provider facts records them as a provider_error detail; a later `done` on
138
+ * the same request (a retry or replay that succeeded) retracts a detail this path recorded, so a
139
+ * successful row never names a provider failure it recovered from.
140
+ */
141
+ export function observeProviderFailureEvent(logCtx: { failureDetail?: FailureDetail }, event: { type: string }): void {
142
+ if (event.type === "done") {
143
+ const recorded = providerDetails.get(logCtx);
144
+ if (recorded !== undefined && logCtx.failureDetail === recorded) delete logCtx.failureDetail;
145
+ providerDetails.delete(logCtx);
146
+ return;
147
+ }
148
+ if (event.type !== "error") return;
149
+ const facts = providerFailureDetailOf(event);
150
+ if (!facts) return;
151
+ const detail = boundedFailureDetail({ code: "provider_error", ...facts });
152
+ if (!detail) return;
153
+ logCtx.failureDetail = detail;
154
+ providerDetails.set(logCtx, detail);
155
+ }