@bitkyc08/opencodex 2.100.0 → 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 (178) 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-DU-0Vdkr.js +1 -0
  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-CcxZBnxv.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-aYgIQMxI.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-D8jfUXpQ.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/anthropic-image-normalize.ts +1 -1
  15. package/src/adapters/client-fingerprint.ts +6 -4
  16. package/src/adapters/cursor/native-exec.ts +3 -2
  17. package/src/adapters/cursor/tool-guidance.ts +3 -3
  18. package/src/adapters/cursor/tool-wording.ts +10 -1
  19. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  20. package/src/adapters/google-antigravity-wire.ts +13 -6
  21. package/src/adapters/google-truncation.ts +4 -2
  22. package/src/adapters/google.ts +8 -2
  23. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  24. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  25. package/src/adapters/openai-chat-images.ts +100 -0
  26. package/src/adapters/openai-chat.ts +6 -9
  27. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  28. package/src/adapters/run-turn-queue.ts +139 -5
  29. package/src/adapters/upstream-http-error.ts +4 -2
  30. package/src/bridge/sse.ts +8 -1
  31. package/src/claude/chat-tool-dispatch.ts +233 -0
  32. package/src/claude/inbound-tool-loading.ts +42 -17
  33. package/src/cli/account-api.ts +6 -0
  34. package/src/cli/account-extended.ts +60 -6
  35. package/src/cli/account-key-quota.ts +22 -2
  36. package/src/cli/account.ts +1 -1
  37. package/src/cli/capabilities-access-remote.ts +10 -0
  38. package/src/cli/capabilities-agents-routing.ts +2 -2
  39. package/src/cli/capabilities-base.ts +2 -2
  40. package/src/cli/claude.ts +19 -14
  41. package/src/cli/config-command.ts +24 -1
  42. package/src/cli/connect.ts +36 -3
  43. package/src/cli/gui-pair-client.ts +23 -2
  44. package/src/cli/help.ts +1 -1
  45. package/src/cli/hub.ts +18 -1
  46. package/src/cli/link-child-ops.ts +136 -0
  47. package/src/cli/link-status-child.ts +94 -0
  48. package/src/cli/link.ts +22 -9
  49. package/src/cli/registry.ts +3 -2
  50. package/src/cli/sync-command.ts +3 -1
  51. package/src/cli/sync-fanout.ts +8 -81
  52. package/src/client/link-readiness.ts +16 -6
  53. package/src/client/link-tunnel-status.ts +76 -0
  54. package/src/clients/config-export.ts +14 -1
  55. package/src/codex/account-resume-health.ts +41 -0
  56. package/src/codex/auth-api/login-flow.ts +6 -0
  57. package/src/codex/auth-api/routes.ts +35 -2
  58. package/src/codex/catalog/gather-capture.ts +2 -0
  59. package/src/codex/catalog/provider-models.ts +13 -8
  60. package/src/codex/convergence-types.ts +2 -0
  61. package/src/codex/quota.ts +111 -6
  62. package/src/combos/cooldown-store.ts +208 -0
  63. package/src/combos/failover.ts +432 -35
  64. package/src/config/salvage.ts +1 -0
  65. package/src/config/schema/config-schema.ts +6 -3
  66. package/src/config/schema/leaf-validators.ts +34 -12
  67. package/src/generated/compatibility-version.json +227 -135
  68. package/src/lib/catalog-etag.ts +10 -0
  69. package/src/lib/client-error-body.ts +15 -0
  70. package/src/lib/config-ownership.ts +9 -2
  71. package/src/lib/context-overflow-verdict.ts +266 -9
  72. package/src/lib/failure-detail.ts +72 -3
  73. package/src/lib/hard-refusal.ts +259 -0
  74. package/src/link/child-activity.ts +57 -0
  75. package/src/link/child-catalog-freshness.ts +149 -0
  76. package/src/link/child-gated-ocx.ts +117 -0
  77. package/src/link/child-observations.ts +205 -0
  78. package/src/link/child-observe.ts +121 -0
  79. package/src/link/child-ops-engine.ts +162 -0
  80. package/src/link/child-update-contract.ts +165 -0
  81. package/src/link/paths.ts +5 -0
  82. package/src/link/remote-windows.ts +42 -6
  83. package/src/link/ssh-argv.ts +126 -32
  84. package/src/link/status-projection.ts +73 -0
  85. package/src/link/sync-fanout-classify.ts +98 -0
  86. package/src/link/tunnel-state.ts +10 -4
  87. package/src/messaging/mcp-queue-rpc.ts +2 -1
  88. package/src/messaging/mcp-queue-server.ts +5 -0
  89. package/src/messaging/mcp-reply-tools.ts +24 -9
  90. package/src/messaging/mcp-reply-wait.ts +70 -0
  91. package/src/oauth/account-resume-health.ts +60 -0
  92. package/src/oauth/anthropic-model-quota.ts +12 -0
  93. package/src/oauth/anthropic-routing.ts +11 -4
  94. package/src/oauth/index.ts +1 -0
  95. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  96. package/src/oauth/store.ts +44 -1
  97. package/src/providers/api-key-pause-state.ts +23 -0
  98. package/src/providers/api-key-pause.ts +68 -10
  99. package/src/providers/api-key-selection-capture.ts +3 -1
  100. package/src/providers/api-key-selection.ts +3 -2
  101. package/src/providers/api-keys.ts +18 -5
  102. package/src/providers/claude-cli-identity.ts +9 -3
  103. package/src/providers/claude-cli-usage-state.ts +11 -6
  104. package/src/providers/claude-cli-usage.ts +27 -8
  105. package/src/providers/codex-capacity.ts +11 -2
  106. package/src/providers/key-failover.ts +13 -6
  107. package/src/providers/model-discovery-config.ts +31 -0
  108. package/src/providers/model-discovery-diagnostic.ts +34 -3
  109. package/src/providers/model-discovery.ts +43 -7
  110. package/src/providers/model-rename-fields.ts +2 -0
  111. package/src/providers/openai-sidecar.ts +15 -2
  112. package/src/providers/provider-id-rewrite.ts +3 -0
  113. package/src/providers/quota/account-cache.ts +52 -34
  114. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  115. package/src/providers/quota/anthropic-usage-windows.ts +66 -9
  116. package/src/providers/quota/report-cache.ts +53 -5
  117. package/src/providers/quota/vendor-probes-key.ts +73 -0
  118. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  119. package/src/providers/quota-key-accounts.ts +12 -5
  120. package/src/providers/quota-mistral-budget.ts +18 -0
  121. package/src/providers/quota-types.ts +32 -0
  122. package/src/providers/quota.ts +22 -22
  123. package/src/providers/reasoning-metadata.ts +1051 -12
  124. package/src/providers/registry/entries-extended.ts +3 -1
  125. package/src/providers/registry/model-ids.ts +1 -0
  126. package/src/providers/registry/types.ts +6 -0
  127. package/src/quota/reset-observer.ts +4 -2
  128. package/src/quota/reset-seen-store.ts +9 -0
  129. package/src/quota/window-mapping.ts +1 -0
  130. package/src/quota-pool/assemble.ts +4 -1
  131. package/src/responses/hosted-tool-policy.ts +56 -12
  132. package/src/responses/retained-compaction.ts +31 -5
  133. package/src/router.ts +2 -0
  134. package/src/server/auth-cors.ts +11 -8
  135. package/src/server/catalog-download.ts +3 -5
  136. package/src/server/chat-native.ts +11 -2
  137. package/src/server/claude-messages.ts +2 -1
  138. package/src/server/images.ts +41 -13
  139. package/src/server/index/link-listener.ts +16 -2
  140. package/src/server/index/link-relay-sessions.ts +43 -2
  141. package/src/server/index/optional-listeners.ts +18 -0
  142. package/src/server/management/config-routes.ts +7 -1
  143. package/src/server/management/context.ts +1 -1
  144. package/src/server/management/link-child-ops-routes.ts +116 -0
  145. package/src/server/management/link-route-state.ts +10 -0
  146. package/src/server/management/link-routes.ts +10 -0
  147. package/src/server/management/oauth-account-routes.ts +33 -4
  148. package/src/server/management/provider-overwrite-carry.ts +28 -3
  149. package/src/server/management/provider-routes.ts +16 -11
  150. package/src/server/management/route-registry.ts +3 -0
  151. package/src/server/messages-native.ts +5 -0
  152. package/src/server/request-log-failure-detail.ts +59 -1
  153. package/src/server/responses/adapter-dispatch.ts +35 -44
  154. package/src/server/responses/combo-stream-preflight.ts +146 -29
  155. package/src/server/responses/compact.ts +27 -4
  156. package/src/server/responses/context-overflow.ts +58 -2
  157. package/src/server/responses/core-combo-failure.ts +29 -4
  158. package/src/server/responses/core-combo-native.ts +3 -1
  159. package/src/server/responses/core-combo.ts +30 -3
  160. package/src/server/responses/core-errors.ts +3 -1
  161. package/src/server/responses/core-opaque-recovery.ts +45 -2
  162. package/src/server/responses/core-options.ts +12 -0
  163. package/src/server/responses/passthrough-dispatch.ts +30 -38
  164. package/src/server/responses/request-transport.ts +43 -14
  165. package/src/server/responses/reset-replay.ts +58 -2
  166. package/src/server/responses/run-turn-execution.ts +56 -30
  167. package/src/types/claude-tool-loading.ts +48 -0
  168. package/src/types/config.ts +5 -35
  169. package/src/types/provider.ts +21 -0
  170. package/src/types.ts +1 -0
  171. package/src/web-search/parse.ts +44 -4
  172. package/gui/dist/assets/App-CitvEefy.js +0 -59
  173. package/gui/dist/assets/Tray-CeKVWQyB.js +0 -1
  174. package/gui/dist/assets/brand-mark-M92UnxX2.js +0 -1
  175. package/gui/dist/assets/index-BP47do6-.js +0 -94
  176. package/gui/dist/assets/index-DmDooSAG.css +0 -2
  177. package/gui/dist/classic/assets/index-CfGqHooN.js +0 -94
  178. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +0 -1
@@ -1,10 +1,15 @@
1
1
  import type { Server } from "bun";
2
+ import { createHash } from "node:crypto";
2
3
  import {
3
4
  LINK_RELAY_AUTH_PATH, LINK_RELAY_AUTH_TIMEOUT_MS, LINK_RELAY_AUTH_VERSION, LINK_RELAY_CONNECTION_HEADER,
4
5
  LINK_RELAY_CONNECTION_PROOF_HEADER, LINK_RELAY_PROBE_HEADER, LINK_RELAY_SESSION_HEADER, linkConnectionProof,
5
6
  linkRelayProof, linkRelayProofMatches,
6
7
  } from "../../link/relay-auth";
7
8
  import { parseLinkPeerReport, type LinkPeerObservations } from "../../link/peer-report";
9
+ import { linkActivityCounts, type LinkActivity } from "../../link/child-activity";
10
+
11
+ /** A 200 `GET /v1/catalog` whose body the Child read to the end (wp2 catalog freshness). */
12
+ export interface LinkCatalogServed { linkId: string | null; keyId: string | null; etag: string }
8
13
 
9
14
  interface Session {
10
15
  peer: string;
@@ -24,6 +29,14 @@ export interface LinkRelaySessionOptions {
24
29
  peers?: LinkPeerObservations;
25
30
  /** The current tunnel connection of a Home-initiated link, announced with each proof. */
26
31
  connectionGeneration?: (linkId: string) => string | undefined;
32
+ /** Per-link model-traffic book owned by the listener lifecycle (D5); survives rebinds. */
33
+ activity?: LinkActivity;
34
+ /**
35
+ * Called after a 200 `GET /v1/catalog` body was read to the end and the stream closed. linkId comes from the relay
36
+ * session; a legacy key admission gives null and the response's `x-opencodex-key-id`. The etag is the sha256 of the
37
+ * bytes served, the same value as `catalogEtag(body)`. Cancel, abort, a read error and HEAD report nothing.
38
+ */
39
+ catalogServed?: (served: LinkCatalogServed) => void;
27
40
  }
28
41
 
29
42
  /** One book per bound listener. A pending proof reserves the bind before the data request arrives. */
@@ -102,11 +115,13 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
102
115
  }
103
116
  const nonce = req.headers.get(LINK_RELAY_SESSION_HEADER);
104
117
  let release: () => void;
118
+ let sessionLink: string | null = null;
105
119
  if (nonce !== null) {
106
120
  // A proof received on one HTTP socket never authorizes another socket, even on the same port.
107
121
  const session = consume(nonce);
108
122
  if (!session) return refuse();
109
123
  release = session.release;
124
+ sessionLink = session.linkId;
110
125
  if (session.peer !== peerOf(req, server as Server<unknown>) || Date.now() >= session.expiresAt
111
126
  || !options.fingerprints(session.keyId, session.linkId).includes(session.fingerprint)) {
112
127
  release(); return refuse();
@@ -118,6 +133,17 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
118
133
  // Older peers may still use the ordinary key admission. Its response also owns a drain lease.
119
134
  release = acquire();
120
135
  }
136
+ // Activity wraps the release every path below calls (body end, cancel, abort, HEAD, dispatch throw); both halves
137
+ // are idempotent. A relay-session request counts from session validation, so a refused proof never counts. A
138
+ // legacy key admission counts only once its response status is known and below 400: until then the key has not
139
+ // been accepted, so an unauthenticated or refused request never touches inFlight or lastDataEndAt.
140
+ const countsActivity = options.activity !== undefined && linkActivityCounts(url, req);
141
+ const beginActivity = (): void => {
142
+ const lease = release;
143
+ const end = options.activity!.begin(sessionLink);
144
+ release = () => { end(); lease(); };
145
+ };
146
+ if (countsActivity && sessionLink !== null) beginActivity();
121
147
  // Socket cancellation before headers is terminal too; an upstream handler that is
122
148
  // settling its own cleanup cannot keep a dead transport's listener lease forever.
123
149
  const beforeHeadersAbort = () => release();
@@ -126,9 +152,23 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
126
152
  try {
127
153
  const response = await dispatch(req, server);
128
154
  req.signal.removeEventListener("abort", beforeHeadersAbort);
155
+ if (countsActivity && sessionLink === null && response.status < 400 && !req.signal.aborted) beginActivity();
129
156
  if (!response.body || req.method === "HEAD") { release(); return response; }
130
157
  const reader = response.body.getReader();
158
+ const catalogHash = options.catalogServed && req.method === "GET" && url.pathname === "/v1/catalog" && url.search === ""
159
+ && response.status === 200 ? createHash("sha256") : null;
160
+ const catalogKeyId = sessionLink === null ? response.headers.get("x-opencodex-key-id") : null;
161
+ const reportCatalog = (): void => {
162
+ if (!catalogHash) return;
163
+ try {
164
+ options.catalogServed!({ linkId: sessionLink, keyId: catalogKeyId, etag: `"${catalogHash.digest("hex")}"` });
165
+ } catch (error) {
166
+ console.warn(`[link] catalog pull record failed: ${error instanceof Error ? error.name : "unknown"}`);
167
+ }
168
+ };
131
169
  let ended = false;
170
+ // A cancel resolves a pending read as done; that end is not a completed body.
171
+ let cancelled = false;
132
172
  const finish = () => {
133
173
  if (ended) return;
134
174
  ended = true;
@@ -136,6 +176,7 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
136
176
  release();
137
177
  };
138
178
  const cancel = async (reason?: unknown) => {
179
+ cancelled = true;
139
180
  try { await reader.cancel(reason); } finally { finish(); }
140
181
  };
141
182
  const aborted = () => { void cancel(req.signal.reason).catch(() => {}); };
@@ -145,8 +186,8 @@ export function createLinkRelaySessions(options: LinkRelaySessionOptions) {
145
186
  async pull(controller) {
146
187
  try {
147
188
  const next = await reader.read();
148
- if (next.done) { finish(); controller.close(); }
149
- else controller.enqueue(next.value);
189
+ if (next.done) { finish(); controller.close(); if (!cancelled) reportCatalog(); }
190
+ else { catalogHash?.update(next.value); controller.enqueue(next.value); }
150
191
  } catch (error) { finish(); controller.error(error); }
151
192
  },
152
193
  cancel,
@@ -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);