@bitkyc08/opencodex 2.94.0 → 2.96.0

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 (289) hide show
  1. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  2. package/gui/dist/assets/App-bwugJRKn.js +58 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-BOPQyDbH.js} +1 -1
  4. package/gui/dist/assets/index-ebuVUtB7.js +94 -0
  5. package/gui/dist/assets/quota-summary-6HsrHQAy.js +1 -0
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/anthropic.ts +10 -3
  9. package/src/adapters/command-code-project-context.ts +3 -3
  10. package/src/adapters/kiro/adapter.ts +4 -1
  11. package/src/adapters/kiro/stream.ts +1 -0
  12. package/src/adapters/kiro-events.ts +1 -0
  13. package/src/adapters/ollama-native.ts +10 -6
  14. package/src/adapters/openai-chat/messages.ts +20 -7
  15. package/src/adapters/openai-chat/passthrough.ts +4 -2
  16. package/src/adapters/openai-chat/single-system.ts +24 -0
  17. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  18. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  19. package/src/adapters/openai-responses/passthrough.ts +45 -11
  20. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  21. package/src/adapters/openai-responses/request-strips.ts +23 -4
  22. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  23. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  24. package/src/adapters/openai-responses/transport.ts +17 -26
  25. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  26. package/src/adapters/qoder/adapter.ts +1 -1
  27. package/src/adapters/qoder/image-input.ts +5 -2
  28. package/src/adapters/routed-agent-messages.ts +3 -0
  29. package/src/adapters/xai-web-search.ts +6 -3
  30. package/src/adapters/zed-additional-tools.ts +7 -7
  31. package/src/adapters/zed.ts +1 -6
  32. package/src/advisor/consult.ts +22 -10
  33. package/src/advisor/runtime.ts +10 -4
  34. package/src/bridge/max-output-completion.ts +41 -0
  35. package/src/bridge/response-json.ts +9 -4
  36. package/src/bridge/sse.ts +13 -2
  37. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  38. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  39. package/src/claude/compatibility.ts +5 -1
  40. package/src/claude/desktop-3p.ts +27 -6
  41. package/src/claude/desktop-model-visibility.ts +141 -0
  42. package/src/claude/desktop-remote-store-io.ts +8 -8
  43. package/src/claude/inbound-content-options.ts +11 -1
  44. package/src/claude/intercept/proxy-auth.ts +16 -16
  45. package/src/cli/account-main.ts +3 -2
  46. package/src/cli/agent.ts +44 -15
  47. package/src/cli/capabilities-agents-routing.ts +9 -0
  48. package/src/cli/capabilities-provider-models.ts +7 -0
  49. package/src/cli/chatgpt-command.ts +1 -1
  50. package/src/cli/codex-launcher.ts +20 -8
  51. package/src/cli/codex-shim-autorestore.ts +19 -1
  52. package/src/cli/dispatch.ts +6 -6
  53. package/src/cli/doctor.ts +5 -5
  54. package/src/cli/ensure-desired-integrations.ts +4 -3
  55. package/src/cli/index.ts +8 -10
  56. package/src/cli/init.ts +2 -2
  57. package/src/cli/internal-command.ts +29 -2
  58. package/src/cli/message-command.ts +2 -1
  59. package/src/cli/message-mcp-command.ts +29 -0
  60. package/src/cli/provider-cc-switch-import.ts +185 -0
  61. package/src/cli/provider.ts +5 -0
  62. package/src/cli/registry.ts +2 -1
  63. package/src/cli/restart-scope.ts +2 -2
  64. package/src/cli/root.ts +6 -6
  65. package/src/cli/stop-approval.ts +15 -1
  66. package/src/cli/v2.ts +69 -19
  67. package/src/client/machine-api.ts +2 -2
  68. package/src/clients/config-export.ts +14 -3
  69. package/src/codex/account-cooldown-response.ts +18 -0
  70. package/src/codex/account-store.ts +1 -0
  71. package/src/codex/app-server-restart-service.ts +2 -2
  72. package/src/codex/auth-api/login-flow.ts +2 -2
  73. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  74. package/src/codex/auth-context-provider.ts +15 -0
  75. package/src/codex/auth-context.ts +14 -23
  76. package/src/codex/catalog/bundled.ts +10 -3
  77. package/src/codex/catalog/metadata.ts +4 -5
  78. package/src/codex/catalog/native-omission.ts +28 -0
  79. package/src/codex/catalog/native-template.ts +58 -0
  80. package/src/codex/catalog/parsing.ts +3 -29
  81. package/src/codex/catalog/provider-models.ts +2 -1
  82. package/src/codex/catalog/retained-sync.ts +15 -5
  83. package/src/codex/catalog/write-audit.ts +18 -18
  84. package/src/codex/cli-install-provenance.ts +46 -45
  85. package/src/codex/cli-update-artifacts.ts +8 -6
  86. package/src/codex/cli-update-job-store-windows.ts +99 -27
  87. package/src/codex/cli-update-job-worker.ts +3 -11
  88. package/src/codex/cli-update-recovery.ts +54 -8
  89. package/src/codex/cli-update-selection-gate.ts +74 -4
  90. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  91. package/src/codex/codex-home-owner.ts +9 -8
  92. package/src/codex/convergence.ts +13 -3
  93. package/src/codex/coordinator-doctor.ts +14 -8
  94. package/src/codex/desktop-app/handoff.ts +1 -1
  95. package/src/codex/desktop-app-restart.ts +11 -1
  96. package/src/codex/exec-boundary.ts +26 -5
  97. package/src/codex/forward-transport-headers.ts +33 -33
  98. package/src/codex/history-provider.ts +11 -10
  99. package/src/codex/inject/bounded-config-reader.ts +14 -13
  100. package/src/codex/installation-id.ts +72 -0
  101. package/src/codex/main-account.ts +6 -6
  102. package/src/codex/native-main-lock-file.ts +13 -12
  103. package/src/codex/native-residue.ts +18 -14
  104. package/src/codex/orca-auth-source.ts +8 -7
  105. package/src/codex/quota-types.ts +5 -0
  106. package/src/codex/quota.ts +49 -7
  107. package/src/codex/role-auto-assign.ts +50 -26
  108. package/src/codex/role-capability.ts +160 -0
  109. package/src/codex/role-sizing.ts +24 -6
  110. package/src/codex/routing/cooldown-math.ts +3 -2
  111. package/src/codex/runtime.ts +43 -3
  112. package/src/codex/shim-fingerprint.ts +11 -9
  113. package/src/codex/shim-inspect.ts +3 -2
  114. package/src/codex/shim-restore-lock.ts +11 -14
  115. package/src/codex/shim-state-file.ts +22 -14
  116. package/src/codex/shim-wrapper-write.ts +7 -6
  117. package/src/codex/shim.ts +25 -2
  118. package/src/codex/transition-state.ts +5 -4
  119. package/src/combos/failover.ts +43 -4
  120. package/src/config/atomic-write.ts +38 -7
  121. package/src/config/diagnostics.ts +3 -0
  122. package/src/config/initialize.ts +6 -6
  123. package/src/config/load-degrade.ts +2 -0
  124. package/src/config/process-state.ts +23 -5
  125. package/src/config/salvage.ts +1 -0
  126. package/src/config/schema/config-schema.ts +29 -1
  127. package/src/config/schema/leaf-validators.ts +7 -0
  128. package/src/config/schema/workflow-budget.ts +43 -0
  129. package/src/config/tracked-runtime-inspection.ts +188 -0
  130. package/src/generated/compatibility-version.json +380 -244
  131. package/src/grok/sync.ts +10 -1
  132. package/src/integrations/aside-profile-context.ts +1 -1
  133. package/src/integrations/droid-settings.ts +4 -4
  134. package/src/integrations/hermes-profiles.ts +3 -3
  135. package/src/lib/bounded-file-read.ts +3 -9
  136. package/src/lib/bun-runtime-preflight.ts +9 -8
  137. package/src/lib/file-identity.ts +15 -0
  138. package/src/lib/local-chat-completion.ts +8 -6
  139. package/src/lib/local-destinations.ts +32 -3
  140. package/src/lib/redact-folding.ts +9 -0
  141. package/src/lib/spend-pool-alias-validation.ts +6 -6
  142. package/src/lib/state-store-registrations.ts +2 -0
  143. package/src/lib/test-home-guard.ts +37 -9
  144. package/src/lib/windows-secret-acl.ts +49 -31
  145. package/src/lib/workflow-budget-config.ts +39 -0
  146. package/src/local-credentials/generation.ts +6 -2
  147. package/src/local-credentials/inventory.ts +132 -8
  148. package/src/messaging/mcp-queue-rpc.ts +102 -0
  149. package/src/messaging/mcp-queue-server.ts +42 -0
  150. package/src/messaging/mcp-queue-tools.ts +39 -0
  151. package/src/messaging/remote-forward-failure.ts +35 -0
  152. package/src/messaging/remote-ports.ts +27 -5
  153. package/src/messaging/remote-process.ts +30 -4
  154. package/src/messaging/remote-tunnels.ts +80 -15
  155. package/src/oauth/anthropic-identity.ts +2 -6
  156. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  157. package/src/oauth/google-antigravity.ts +23 -10
  158. package/src/oauth/index.ts +7 -0
  159. package/src/oauth/kiro-device-login.ts +87 -30
  160. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  161. package/src/oauth/store.ts +9 -7
  162. package/src/providers/account-quota-disk.ts +18 -4
  163. package/src/providers/anthropic-subscription.ts +25 -0
  164. package/src/providers/cc-switch-import-bytes.ts +991 -0
  165. package/src/providers/cc-switch-import-source.ts +1083 -0
  166. package/src/providers/cc-switch-import.ts +942 -0
  167. package/src/providers/claude-cli-usage.ts +15 -67
  168. package/src/providers/derive.ts +6 -0
  169. package/src/providers/model-discovery-diagnostic.ts +4 -0
  170. package/src/providers/model-discovery.ts +4 -4
  171. package/src/providers/model-rename-fields.ts +2 -0
  172. package/src/providers/model-rename-migration.ts +41 -6
  173. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  174. package/src/providers/quota/anthropic-usage-windows.ts +55 -0
  175. package/src/providers/quota/report-cache.ts +17 -4
  176. package/src/providers/quota.ts +2 -2
  177. package/src/providers/reasoning-metadata.ts +31 -15
  178. package/src/providers/registry/entries-core.ts +1 -1
  179. package/src/providers/registry/entries-extended.ts +1 -1
  180. package/src/providers/registry/model-ids.ts +1 -0
  181. package/src/providers/registry/model-seeds.ts +2 -1
  182. package/src/providers/registry/types.ts +3 -1
  183. package/src/providers/resolved-model-policy.ts +2 -2
  184. package/src/providers/routed-config.ts +2 -0
  185. package/src/providers/stale-model-roster-migration.ts +5 -1
  186. package/src/providers/xai-transport.ts +4 -4
  187. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  188. package/src/remote-control/workspace-executor.ts +14 -13
  189. package/src/responses/custom-tool-compat.ts +2 -1
  190. package/src/responses/item-provenance.ts +79 -0
  191. package/src/responses/namespace-tool-compat.ts +21 -3
  192. package/src/responses/parser-tools.ts +1 -0
  193. package/src/responses/schema.ts +5 -2
  194. package/src/router.ts +21 -2
  195. package/src/routing/analytics.ts +3 -5
  196. package/src/routing/fallback-policy.ts +7 -3
  197. package/src/routing/health.ts +5 -3
  198. package/src/routing/history/build-file.ts +6 -0
  199. package/src/routing/history/indexer.ts +158 -31
  200. package/src/routing/history/ingest.ts +1 -1
  201. package/src/routing/history/integrity.ts +208 -0
  202. package/src/routing/history/rebuild-job.ts +20 -6
  203. package/src/routing/history/rebuild-protocol.ts +2 -1
  204. package/src/routing/history/rebuild-worker.ts +18 -0
  205. package/src/routing/history/sqlite-errors.ts +9 -0
  206. package/src/server/admission-model-scope.ts +21 -4
  207. package/src/server/advisor-admission-scope.ts +29 -0
  208. package/src/server/audio-dictation.ts +3 -0
  209. package/src/server/audio-live.ts +8 -2
  210. package/src/server/audio-upstream.ts +2 -0
  211. package/src/server/auth-cors.ts +5 -2
  212. package/src/server/capture-admission-policy.ts +91 -0
  213. package/src/server/chat-completions.ts +33 -7
  214. package/src/server/claude-messages.ts +93 -2
  215. package/src/server/codex-model-list.ts +2 -1
  216. package/src/server/configured-credentials.ts +5 -0
  217. package/src/server/context-history.ts +9 -6
  218. package/src/server/images.ts +14 -5
  219. package/src/server/index/live-sideband.ts +16 -2
  220. package/src/server/index/serve-options.ts +13 -2
  221. package/src/server/index/websocket-handler.ts +4 -1
  222. package/src/server/live.ts +30 -5
  223. package/src/server/management/agent-settings-routes.ts +34 -9
  224. package/src/server/management/codex-agent-role-routes.ts +1 -0
  225. package/src/server/management/codex-role-auto-assign.ts +50 -6
  226. package/src/server/management/config-routes.ts +15 -4
  227. package/src/server/management/context.ts +3 -0
  228. package/src/server/management/native-integration-routes.ts +22 -0
  229. package/src/server/management/oauth-account-routes.ts +20 -4
  230. package/src/server/management/provider-overwrite-carry.ts +21 -0
  231. package/src/server/management/provider-routes.ts +3 -1
  232. package/src/server/management/route-registry.ts +2 -0
  233. package/src/server/management/shared.ts +17 -1
  234. package/src/server/management/workflow-budget-routes.ts +70 -3
  235. package/src/server/messages-native-eligibility.ts +6 -5
  236. package/src/server/messages-native-scope.ts +6 -1
  237. package/src/server/messages-shared.ts +57 -17
  238. package/src/server/persistent-gui-session.ts +4 -4
  239. package/src/server/request-log.ts +30 -2
  240. package/src/server/responses/adapter-delivery.ts +4 -0
  241. package/src/server/responses/adapter-dispatch.ts +5 -0
  242. package/src/server/responses/advisor-plan-slot.ts +4 -0
  243. package/src/server/responses/advisor-slot.ts +73 -46
  244. package/src/server/responses/codex-auth-error.ts +9 -1
  245. package/src/server/responses/combo-required-tool-contract.ts +39 -0
  246. package/src/server/responses/compact.ts +41 -20
  247. package/src/server/responses/core-codex-account.ts +17 -6
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +70 -5
  250. package/src/server/responses/core-lifetime.ts +4 -0
  251. package/src/server/responses/core-normalize.ts +7 -1
  252. package/src/server/responses/core-options.ts +9 -0
  253. package/src/server/responses/core.ts +2 -0
  254. package/src/server/responses/jev-model-invoke.ts +4 -2
  255. package/src/server/responses/passthrough-build-error.ts +36 -0
  256. package/src/server/responses/passthrough-dispatch.ts +10 -24
  257. package/src/server/responses/policy-fallback.ts +2 -0
  258. package/src/server/responses/request-prepare.ts +4 -5
  259. package/src/server/responses/request-send-budget.ts +2 -1
  260. package/src/server/responses/request-sidecar-auth.ts +4 -1
  261. package/src/server/responses/request-transport.ts +2 -3
  262. package/src/server/responses/run-turn-execution.ts +4 -0
  263. package/src/server/responses/sidecar-execution.ts +21 -5
  264. package/src/server/responses-snapshot-repair.ts +18 -4
  265. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  266. package/src/server/search.ts +13 -4
  267. package/src/server/workflow-refusal.ts +2 -1
  268. package/src/server/ws-bridge.ts +5 -2
  269. package/src/service/state-lock.ts +12 -11
  270. package/src/service-manager-probe.ts +53 -8
  271. package/src/types/admission-policy.ts +13 -0
  272. package/src/types/config.ts +25 -0
  273. package/src/types/provider.ts +10 -0
  274. package/src/types/request.ts +7 -0
  275. package/src/types.ts +1 -0
  276. package/src/update/job.ts +20 -0
  277. package/src/update/worker-launch.ts +71 -1
  278. package/src/usage/log.ts +25 -4
  279. package/src/vision/describe.ts +4 -7
  280. package/src/vision/index.ts +2 -0
  281. package/src/vision/plan.ts +4 -0
  282. package/src/vision/routed-describe.ts +38 -23
  283. package/src/web-search/executor.ts +4 -7
  284. package/src/web-search/loop.ts +104 -9
  285. package/src/web-search/parse.ts +10 -2
  286. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  287. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  288. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  289. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
@@ -1,4 +1,5 @@
1
1
  import { readConfigForAdmittedMutation } from "../../config/persisted-mutation";
2
+ import { ConfigWritePublishedError } from "../../config/persist-unlocked";
2
3
  import { getConfigDir as configRoot, withConfigDirHardeningSettled as settleConfigRoot } from "../../config/paths";
3
4
  import { WindowsSecretAclSettleTimeoutError } from "../../lib/windows-secret-acl";
4
5
  import { mirrorDesiredEnabledOntoSnapshot } from "./claude-desktop-config-writers";
@@ -949,6 +950,9 @@ export async function handleNativeIntegrationRoutes(ctx: ManagementContext): Pro
949
950
 
950
951
  const enabled = body.enabled;
951
952
  if (claudeCodeEnabled(config) === enabled) {
953
+ // Re-run the same reconcile on a repeated OFF: definitions left behind by an older
954
+ // version that never pruned on disable are removed the next time the user says off.
955
+ if (!enabled) await ctx.syncClaudeAgentDefsBestEffort?.();
952
956
  return jsonResponse({
953
957
  ok: true, clientId: "claude", changed: false,
954
958
  state: enabled ? "current" : "absent",
@@ -963,6 +967,10 @@ export async function handleNativeIntegrationRoutes(ctx: ManagementContext): Pro
963
967
  * sentinel the next startServer would silently convert a user's Auto auth mode into
964
968
  * a sticky manual subscription — a failure that surfaces nowhere near this route.
965
969
  */
970
+ // Kept so a failed save leaves the shared in-memory config matching disk: otherwise a
971
+ // retry on the same object would read the unsaved value, take the repeated-OFF branch
972
+ // and prune agents while the persisted integration is still on.
973
+ const previousBlock = config.claudeCode === undefined ? undefined : structuredClone(config.claudeCode);
966
974
  commitClaudeCodeBlock(config, { ...(config.claudeCode ?? {}), enabled });
967
975
 
968
976
  /*
@@ -973,6 +981,11 @@ export async function handleNativeIntegrationRoutes(ctx: ManagementContext): Pro
973
981
  try {
974
982
  persist(config);
975
983
  } catch (error) {
984
+ // A published write already put the new value on disk; only an unpublished one rolls back.
985
+ if (!(error instanceof ConfigWritePublishedError)) {
986
+ if (previousBlock === undefined) delete config.claudeCode;
987
+ else config.claudeCode = previousBlock;
988
+ }
976
989
  if (isConfigLockError(error)) {
977
990
  return isLockContention(error)
978
991
  ? refusal(409, "claude", "config_busy",
@@ -983,6 +996,15 @@ export async function handleNativeIntegrationRoutes(ctx: ManagementContext): Pro
983
996
  throw error;
984
997
  }
985
998
 
999
+ /*
1000
+ * The generated ~/.claude/agents/ocx-*.md definitions route through this proxy; a
1001
+ * native Claude Code session that still loads them after OFF follows their
1002
+ * placeholder model (issue #7968). Prune them now instead of waiting for a later
1003
+ * launch or startup sync; the disabled reconcile removes only marker-owned regular
1004
+ * files and needs no model discovery. ON keeps its existing launch/startup sync.
1005
+ */
1006
+ if (!enabled) await ctx.syncClaudeAgentDefsBestEffort?.();
1007
+
986
1008
  let interceptReason = enabled && interceptStartRefusal(ctx) ? "intercept_start_forbidden" : null;
987
1009
  if (enabled && !interceptReason) {
988
1010
  const outcome = await ensureManagementClaudeIntercept(ctx);
@@ -37,7 +37,8 @@ import {
37
37
  waitForLoginSettled,
38
38
  } from "../../oauth";
39
39
  import { OAuthMutationBusyError, removeCredential } from "../../oauth/store";
40
- import { cancelKiroDeviceLogin, kiroDeviceConfigBaseline, startKiroDeviceLogin, statusKiroDeviceLogin, type KiroDeviceMethod } from "../../oauth/kiro-device-login";
40
+ import { cancelKiroDeviceLogin, kiroDeviceConfigBaseline, selectKiroDeviceProfile, startKiroDeviceLogin, statusKiroDeviceLogin, type KiroDeviceMethod } from "../../oauth/kiro-device-login";
41
+ import { parseKiroIamOptions } from "../../oauth/kiro-iam-identity-center";
41
42
  import { providerDestinationResolvedError } from "../../lib/destination-policy";
42
43
  import { emailMaskingEnabled } from "../../lib/privacy";
43
44
  import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
@@ -259,7 +260,7 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
259
260
  // the provider's loopback callback server (inside this process) captures the redirect in the
260
261
  // background, then the credential is persisted. The GUI opens the URL and polls /api/oauth/status.
261
262
  if (url.pathname === "/api/oauth/login" && req.method === "POST") {
262
- const body = await readManagementJsonBodyOr(req, {}) as { provider?: string; addAccount?: boolean; accountId?: string; reauth?: boolean; openBrowser?: unknown; method?: unknown; mode?: unknown };
263
+ const body = await readManagementJsonBodyOr(req, {}) as { provider?: string; addAccount?: boolean; accountId?: string; reauth?: boolean; openBrowser?: unknown; method?: unknown; mode?: unknown; startUrl?: unknown; region?: unknown; flowId?: unknown; profileArn?: unknown };
263
264
  const provider = (body.provider ?? "").trim().toLowerCase();
264
265
  if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
265
266
  // Omitted mode is the localhost-callback flow this route has always run.
@@ -282,13 +283,28 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
282
283
  const reauth = body.reauth === true || Boolean(accountId);
283
284
  if (provider === "kiro") {
284
285
  if (reauth && !accountId) return jsonResponse({ error: "Kiro reauth requires an accountId" }, 400);
286
+ if (body.flowId !== undefined) {
287
+ if (reauth || body.method !== undefined || typeof body.flowId !== "string" || body.flowId.length > 128
288
+ || typeof body.profileArn !== "string" || body.profileArn.length > 256) return jsonResponse({ error: "invalid Kiro profile selection" }, 400);
289
+ const owner = principal ?? "admin-token";
290
+ const baseline = kiroDeviceConfigBaseline(body.flowId, owner);
291
+ const status = await selectKiroDeviceProfile(body.flowId, owner, body.profileArn);
292
+ if (!status) return jsonResponse({ error: "unknown Kiro profile selection" }, 404);
293
+ if (status.state === "done") {
294
+ reconcileLiveConfigFromDisk(config, baseline ?? structuredClone(config));
295
+ reconcileLiveStateStores();
296
+ }
297
+ return jsonResponse(status);
298
+ }
285
299
  if (body.method !== undefined) {
286
- if (body.method !== "builder-id" && body.method !== "google" && body.method !== "github") {
300
+ if (body.method !== "builder-id" && body.method !== "google" && body.method !== "github" && body.method !== "iam-identity-center") {
287
301
  return jsonResponse({ error: "invalid Kiro device method" }, 400);
288
302
  }
289
303
  if (reauth) return jsonResponse({ error: "native_login_is_add_only" }, 400);
304
+ const iam = body.method === "iam-identity-center" ? parseKiroIamOptions(body) : undefined;
305
+ if (body.method === "iam-identity-center" && !iam) return jsonResponse({ error: "invalid Kiro IAM portal or region" }, 400);
290
306
  try {
291
- return jsonResponse(await startKiroDeviceLogin(body.method as KiroDeviceMethod, principal ?? "admin-token", readConfigDiagnostics().config));
307
+ return jsonResponse(await startKiroDeviceLogin(body.method as KiroDeviceMethod, principal ?? "admin-token", readConfigDiagnostics().config, iam));
292
308
  } catch {
293
309
  return jsonResponse({ error: "Kiro device login could not start" }, 409);
294
310
  }
@@ -51,8 +51,10 @@ const RETRY_POLICY_VALIDATORS = {
51
51
  export const PROVIDER_COMPAT_CARRY_FIELDS = [
52
52
  "preserveReasoningContentModels",
53
53
  "preserveResponsesReasoningContent",
54
+ "promoteAdditionalTools",
54
55
  "requiresReasoningPlaceholderModels",
55
56
  "foldDeveloperRoleToSystem",
57
+ "singleLeadingSystemMessage",
56
58
  "reasoningWireFormat",
57
59
  "omitReasoningEffortWithToolsModels",
58
60
  ...RETRY_POLICY_FIELDS,
@@ -159,10 +161,15 @@ export function providerCompatFieldConfigError(provider: Record<string, unknown>
159
161
  }
160
162
  const fold = provider.foldDeveloperRoleToSystem;
161
163
  if (fold !== undefined && typeof fold !== "boolean") return "foldDeveloperRoleToSystem must be a boolean";
164
+ if (provider.singleLeadingSystemMessage !== undefined && typeof provider.singleLeadingSystemMessage !== "boolean") {
165
+ return "singleLeadingSystemMessage must be a boolean";
166
+ }
162
167
  const hideRawReasoning = provider.hideRawReasoning;
163
168
  if (hideRawReasoning !== undefined && typeof hideRawReasoning !== "boolean") return "hideRawReasoning must be a boolean";
164
169
  const preserveResponses = provider.preserveResponsesReasoningContent;
165
170
  if (preserveResponses !== undefined && typeof preserveResponses !== "boolean") return "preserveResponsesReasoningContent must be a boolean";
171
+ const promoteAdditionalTools = provider.promoteAdditionalTools;
172
+ if (promoteAdditionalTools !== undefined && typeof promoteAdditionalTools !== "boolean") return "promoteAdditionalTools must be a boolean";
166
173
  const wire = provider.reasoningWireFormat;
167
174
  if (wire !== undefined && !PROVIDER_REASONING_WIRE_FORMATS.includes(wire as never)) {
168
175
  return `reasoningWireFormat must be one of: ${PROVIDER_REASONING_WIRE_FORMATS.join(", ")}`;
@@ -200,6 +207,13 @@ export function applyProviderCompatPatchFields(
200
207
  else return { error: "foldDeveloperRoleToSystem must be a boolean" };
201
208
  touched = true;
202
209
  }
210
+ if (Object.hasOwn(rawBody, "singleLeadingSystemMessage")) {
211
+ const value = rawBody.singleLeadingSystemMessage;
212
+ if (value === null) delete next.singleLeadingSystemMessage;
213
+ else if (typeof value === "boolean") next.singleLeadingSystemMessage = value;
214
+ else return { error: "singleLeadingSystemMessage must be a boolean" };
215
+ touched = true;
216
+ }
203
217
  if (Object.hasOwn(rawBody, "hideRawReasoning")) {
204
218
  const value = rawBody.hideRawReasoning;
205
219
  if (value === null) delete next.hideRawReasoning;
@@ -214,6 +228,13 @@ export function applyProviderCompatPatchFields(
214
228
  else return { error: "preserveResponsesReasoningContent must be a boolean" };
215
229
  touched = true;
216
230
  }
231
+ if (Object.hasOwn(rawBody, "promoteAdditionalTools")) {
232
+ const value = rawBody.promoteAdditionalTools;
233
+ if (value === null) delete next.promoteAdditionalTools;
234
+ else if (typeof value === "boolean") next.promoteAdditionalTools = value;
235
+ else return { error: "promoteAdditionalTools must be a boolean" };
236
+ touched = true;
237
+ }
217
238
  if (Object.hasOwn(rawBody, "inferContextWindow")) {
218
239
  const value = rawBody.inferContextWindow;
219
240
  if (value === null) delete next.inferContextWindow;
@@ -63,6 +63,7 @@ import {
63
63
  import { shadowInterceptProviderDependency } from "./shadow-call-validation";
64
64
  import { deriveProviderPresets, providerConfigSeed } from "../../providers/derive";
65
65
  import { initializeProviderModelSelection } from "../../providers/initial-model-selection";
66
+ import { invalidModelDiscoveryHint } from "../../providers/model-discovery-diagnostic";
66
67
  import { effectiveGoogleMode, providerCodexAccountMode, providerMatchesRegistryTransport } from "../../providers/registry";
67
68
  import {
68
69
  extractModelEnvelopeRows,
@@ -907,6 +908,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
907
908
  hasHeaders: !!p.headers && Object.keys(p.headers).length > 0,
908
909
  allowPrivateNetwork: p.allowPrivateNetwork === true,
909
910
  preserveResponsesReasoningContent: p.preserveResponsesReasoningContent,
911
+ promoteAdditionalTools: p.promoteAdditionalTools,
910
912
  liveModels: p.liveModels !== false,
911
913
  requestPacing: p.requestPacing,
912
914
  models: p.models ?? [],
@@ -1802,7 +1804,7 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
1802
1804
  latencyMs,
1803
1805
  error: extracted.reason === "too_many_models"
1804
1806
  ? `upstream /models exceeded the ${discovery.maxModels}-row model limit`
1805
- : "upstream /models returned an unexpected shape",
1807
+ : `upstream /models returned an unexpected shape${invalidModelDiscoveryHint("diagnostic" in extracted && typeof extracted.diagnostic === "string" ? extracted.diagnostic : undefined)}`,
1806
1808
  });
1807
1809
  }
1808
1810
  const models = ccaModels?.length ?? ("items" in extracted! ? extracted!.items.length : extracted!.rows.length);
@@ -396,6 +396,8 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [
396
396
  { method: "PATCH", path: "/api/protocols/settings", module: "server/management/protocol-routes", mutates: true },
397
397
  { method: "GET", path: "/api/workflow-budget", module: "server/management/workflow-budget-routes", mutates: false, exempt: { reason: "deferred-verb", why: "Reading a root's live budget is owed a CLI verb -- an operator staring at a 429 is usually already in a terminal -- but the ledger is process memory with no local transport to read it through, so the verb has to be an HTTP call the CLI does not yet make.", owner: "260915_workflow_budget_window wfc", ownerDoc: "devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md" } },
398
398
  { method: "POST", path: "/api/workflow-budget/clear", module: "server/management/workflow-budget-routes", mutates: true, exempt: { reason: "deferred-verb", why: "Clearing one root is owed the same verb as the read above and for the same reason. It is deliberately not shipped as a verb in this work-phase: the read comes first, because an operator who cannot see which ceiling fired has no basis for deciding to forgive it.", owner: "260915_workflow_budget_window wfc", ownerDoc: "devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md" } },
399
+ { method: "GET", path: "/api/workflow-budget/settings", module: "server/management/workflow-budget-routes", mutates: false, exempt: { reason: "local-transport", why: "The CLI reads the same workflowBudget block through ocx config get; the route only adds the built-in defaults and bounds the dashboard draws." } },
400
+ { method: "PUT", path: "/api/workflow-budget/settings", module: "server/management/workflow-budget-routes", mutates: true, exempt: { reason: "deferred-verb", why: "A dedicated live CLI verb for the ceilings is deferred with the other workflow-budget verbs; ocx config set/unset edits the same block on disk and the running proxy picks it up on restart.", owner: "260915_workflow_budget_window wfc", ownerDoc: "devlog/_fin/260915_workflow_budget_window/030_wfc_diff_plan.md" } },
399
401
  // server/management/request-history-routes
400
402
  { method: "GET", path: "/api/request-history", module: "server/management/request-history-routes", mutates: false },
401
403
  // server/management/routing-analytics-routes
@@ -254,6 +254,7 @@ export function requestLogDto(
254
254
  ): Record<string, unknown> {
255
255
  return {
256
256
  ...entry,
257
+ ...(entry.attemptNormalizationDropped === true ? { attemptNormalizationDropped: true } : {}),
257
258
  ...resendVerdict(entry),
258
259
  displayMetrics: {
259
260
  tokPerSecond: tokPerSecondResult(entry),
@@ -409,10 +410,14 @@ export async function buildClaudeDesktopState(config: OcxConfig, stored?: OcxCla
409
410
  for (const id of desktopVisibleNativeSlugs(config)) {
410
411
  effortByRoute.set(`native/${id}`, true);
411
412
  }
413
+ const { desktopRouteVisible, filterDesktopModelsByVisibility, readDesktopModelVisibility } = await import("../../claude/desktop-model-visibility");
414
+ const visibility = readDesktopModelVisibility(config.claudeCode);
412
415
  const models = Object.keys(profile.assignments).sort().map(route => ({
413
416
  route,
414
417
  label: modelByRoute.get(route)?.label ?? route,
415
418
  available: available.has(route),
419
+ // Desktop list membership (#7702), separate from the tier assignment below.
420
+ visible: desktopRouteVisible(visibility, route),
416
421
  ...(modelByRoute.get(route)?.contextWindow ? { contextWindow: modelByRoute.get(route)!.contextWindow } : {}),
417
422
  effortSupported: effortByRoute.get(route) ?? false,
418
423
  // Read-only view of the 1M capability the written Desktop config already emits,
@@ -420,10 +425,21 @@ export async function buildClaudeDesktopState(config: OcxConfig, stored?: OcxCla
420
425
  supports1m: routeSupportsOneMillion(route, modelByRoute.get(route)?.contextWindow),
421
426
  assignment: profile.assignments[route]!,
422
427
  }));
428
+ const rendered = renderDesktopProfile(profile, profileModels);
429
+ const selected = filterDesktopModelsByVisibility(
430
+ rendered.map(model => ({ ...model, anthropicFamilyTier: model.family })),
431
+ rendered.map(model => model.route),
432
+ visibility,
433
+ );
434
+ // Match the writer's empty-selection fallback without changing the saved intent.
435
+ const listed = selected.length > 0 ? selected : rendered;
423
436
  return {
424
437
  profile,
425
438
  models,
426
- rendered: renderDesktopProfile(profile, profileModels),
439
+ rendered,
440
+ visibility: visibility ?? null,
441
+ // What the next apply writes, including generateDesktop3pModels' empty-selection fallback.
442
+ listed: listed.map(({ route, name, label, family, isFamilyDefault }) => ({ route, name, label, family, isFamilyDefault: !!isFamilyDefault })),
427
443
  port: config.port,
428
444
  };
429
445
  }
@@ -10,14 +10,27 @@
10
10
  * chain runs, so these handlers add no auth code of their own. The GET spends no user identity.
11
11
  * The POST clears one root's windowed count ceilings; it does not spend identity, and the
12
12
  * underlying ledger leaves in-flight concurrency and the token spend record untouched.
13
+ *
14
+ * `/api/workflow-budget/settings` reads and writes the per-install count ceilings. A write
15
+ * mutates the live config object, which the request path reads per decision, so it applies to
16
+ * the next admission without a restart and never resets what a root has already used.
13
17
  */
14
18
 
15
19
  import { jsonResponse } from "../auth-cors";
16
20
  import type { OcxConfig } from "../../types";
17
21
  import type { ManagementContext } from "./context";
18
22
  import { readManagementJsonBodyOr } from "./body";
23
+ import { captureConfigTopLevelRollback, deleteConfigTopLevelKey } from "../../config/rebase-provenance";
24
+ import { ConfigWritePublishedError } from "../../config/persist-unlocked";
25
+ import {
26
+ WORKFLOW_BUDGET_BOUNDS,
27
+ WORKFLOW_BUDGET_SHAPE_HINT,
28
+ workflowBudgetSchema,
29
+ } from "../../config/schema/workflow-budget";
30
+ import { resolveWorkflowBudgetPolicy } from "../../lib/workflow-budget-config";
19
31
  import {
20
32
  clearWorkflowBudgetForRoot,
33
+ DEFAULT_WORKFLOW_BUDGET_POLICY,
21
34
  listTrackedWorkflowRoots,
22
35
  listWorkflowBudgetEvents,
23
36
  workflowBudgetSnapshot,
@@ -27,6 +40,54 @@ import {
27
40
  const DEFAULT_LIMIT = 20;
28
41
  const MAX_LIMIT = WORKFLOW_EVENT_CAPACITY;
29
42
  const MAX_ROOT_ID_LENGTH = 200;
43
+ const INVALID_BODY = Symbol("invalid-body");
44
+
45
+ /** Effective ceilings plus what the dashboard needs to draw them: defaults, bounds, the fixed window. */
46
+ function workflowBudgetSettings(config: OcxConfig) {
47
+ const policy = resolveWorkflowBudgetPolicy(config);
48
+ return {
49
+ maxConcurrentChildren: policy.maxConcurrentChildren,
50
+ maxPhysicalSends: policy.maxPhysicalSends,
51
+ maxDistinctChildren: policy.maxDistinctChildren,
52
+ interactiveReserve: policy.interactiveReserve,
53
+ windowMs: DEFAULT_WORKFLOW_BUDGET_POLICY.windowMs,
54
+ defaults: {
55
+ maxConcurrentChildren: DEFAULT_WORKFLOW_BUDGET_POLICY.maxConcurrentChildren,
56
+ maxPhysicalSends: DEFAULT_WORKFLOW_BUDGET_POLICY.maxPhysicalSends,
57
+ maxDistinctChildren: DEFAULT_WORKFLOW_BUDGET_POLICY.maxDistinctChildren,
58
+ },
59
+ bounds: WORKFLOW_BUDGET_BOUNDS,
60
+ };
61
+ }
62
+
63
+ /** Partial PUTs preserve omitted ceilings; JSON null removes the block and restores the defaults. */
64
+ async function putWorkflowBudgetSettings(ctx: ManagementContext): Promise<Response> {
65
+ const { req, config } = ctx;
66
+ const body = await readManagementJsonBodyOr(req, INVALID_BODY);
67
+ const parsed = body === null ? null : workflowBudgetSchema.safeParse(body);
68
+ if (parsed !== null && !parsed.success) {
69
+ return jsonResponse(
70
+ { error: { code: "invalid_workflow_budget", message: "body must be null or an object that " + WORKFLOW_BUDGET_SHAPE_HINT } },
71
+ 400,
72
+ req,
73
+ config,
74
+ );
75
+ }
76
+ // Resolve the saver before changing the live object: no await may interleave mutation/save.
77
+ const persist = ctx.deps.saveConfigPreservingClaudeCode
78
+ ?? (await import("../../config")).saveConfigPreservingClaudeCode;
79
+ const restore = captureConfigTopLevelRollback(config, ["workflowBudget"]);
80
+ try {
81
+ if (parsed === null) deleteConfigTopLevelKey(config, "workflowBudget");
82
+ else config.workflowBudget = { ...config.workflowBudget, ...parsed.data };
83
+ persist(config);
84
+ } catch (error) {
85
+ // Published bytes remain authoritative even if later bookkeeping failed.
86
+ if (!(error instanceof ConfigWritePublishedError)) restore();
87
+ throw error;
88
+ }
89
+ return jsonResponse(workflowBudgetSettings(config), 200, req, config);
90
+ }
30
91
 
31
92
  /**
32
93
  * A root id is an opaque caller-thread token, not a path. Without a length cap a client
@@ -60,6 +121,12 @@ function parseLimitParam(rawLimit: string | null): { ok: true; limit: number } |
60
121
  export async function handleWorkflowBudgetRoutes(ctx: ManagementContext): Promise<Response | null> {
61
122
  const { url, req, config } = ctx;
62
123
 
124
+ if (url.pathname === "/api/workflow-budget/settings" && req.method === "GET") {
125
+ return jsonResponse(workflowBudgetSettings(config), 200, req, config);
126
+ }
127
+ if (url.pathname === "/api/workflow-budget/settings" && req.method === "PUT") return putWorkflowBudgetSettings(ctx);
128
+ const policy = resolveWorkflowBudgetPolicy(config);
129
+
63
130
  if (url.pathname === "/api/workflow-budget") {
64
131
  if (req.method !== "GET") return null;
65
132
 
@@ -78,7 +145,7 @@ export async function handleWorkflowBudgetRoutes(ctx: ManagementContext): Promis
78
145
  if (rawRoot !== null) {
79
146
  const rootId = parseRootId(rawRoot);
80
147
  if (rootId === null) return invalidRootResponse(req, config);
81
- const snapshot = workflowBudgetSnapshot(rootId);
148
+ const snapshot = workflowBudgetSnapshot(rootId, policy);
82
149
  // An unknown id is a 200 with `root: null`, not a 404: the operator asked what this
83
150
  // process currently holds for that token, and "nothing" is a legitimate answer. POST
84
151
  // /clear is the opposite — claiming to forgive a ceiling that was never tracked would
@@ -98,7 +165,7 @@ export async function handleWorkflowBudgetRoutes(ctx: ManagementContext): Promis
98
165
 
99
166
  return jsonResponse(
100
167
  {
101
- roots: listTrackedWorkflowRoots(limit),
168
+ roots: listTrackedWorkflowRoots(limit, policy),
102
169
  events: listWorkflowBudgetEvents(limit),
103
170
  },
104
171
  200,
@@ -117,7 +184,7 @@ export async function handleWorkflowBudgetRoutes(ctx: ManagementContext): Promis
117
184
  const rootId = parseRootId(rawRoot);
118
185
  if (rootId === null) return invalidRootResponse(req, config);
119
186
 
120
- const before = clearWorkflowBudgetForRoot(rootId);
187
+ const before = clearWorkflowBudgetForRoot(rootId, policy);
121
188
  if (!before) {
122
189
  return jsonResponse(
123
190
  { error: { code: "unknown_root", message: "root is not currently tracked" } },
@@ -2,8 +2,8 @@
2
2
  * Whether a settled Messages route may take the managed native Messages lane (PF-08).
3
3
  *
4
4
  * PURE: reads the route, the body's structure and config, and nothing else. The Messages ingress,
5
- * `count_tokens` and the protocol planner (`src/protocols/plan-snapshot.ts`) all ask here, so a
6
- * preview, a count and the real send cannot disagree about the lane.
5
+ * `count_tokens` and the protocol planner (`src/protocols/plan-snapshot.ts`) all ask here;
6
+ * previews and counts remain conservative when runtime availability is unknown.
7
7
  */
8
8
  import { anthropicBodyElidesBlockedSkill } from "../claude/inbound";
9
9
  import { isClaudeWebSearchToolName } from "../claude/outbound";
@@ -48,6 +48,8 @@ export interface NativeMessagesSelector {
48
48
  * and judges OAuth from config alone.
49
49
  */
50
50
  oauthFailoverQuorum?: boolean;
51
+ /** Runtime sidecar plan availability; absent for config-only callers. */
52
+ webSearchBackendAvailable?: boolean;
51
53
  }
52
54
 
53
55
  type Rec = Record<string, unknown>;
@@ -59,8 +61,7 @@ function isRec(value: unknown): value is Rec {
59
61
  * Whether the bridge could hand this request to the web-search sidecar: a `web_search*` server
60
62
  * tool the tool choice does not exclude, with the sidecar not disabled in the Claude replay config
61
63
  * (`buildClaudeReplayConfig` merges `claudeCode.webSearchSidecar` over the global block). Whether
62
- * a backend credential then exists is decided at dispatch and is not read here, so this errs
63
- * toward the bridge, which is today's behavior for every such request.
64
+ * a backend credential exists is supplied separately by the sending ingress.
64
65
  */
65
66
  function webSearchSidecarMayEngage(body: Readonly<Rec>, config: OcxConfig): boolean {
66
67
  const sidecar = { ...config.webSearchSidecar, ...config.claudeCode?.webSearchSidecar };
@@ -89,7 +90,7 @@ function bridgeOnlyPolicyApplies(
89
90
  ): boolean {
90
91
  if (resolvePinnedEffort(route, selector.routeSelector, config) !== undefined) return true;
91
92
  if (anthropicBodyElidesBlockedSkill(body, selector.claudeCode ?? config.claudeCode)) return true;
92
- return webSearchSidecarMayEngage(body, config);
93
+ return selector.webSearchBackendAvailable !== false && webSearchSidecarMayEngage(body, config);
93
94
  }
94
95
 
95
96
  /**
@@ -13,7 +13,12 @@ export function nativeMessagesToolScopeDenial(
13
13
  requestedModel: string,
14
14
  body: Readonly<Rec>,
15
15
  ): AdmissionModelDeniedError | undefined {
16
- if (!scope || scope.models.length === 0) return undefined;
16
+ if (!scope) return undefined;
17
+ for (const part of scope.allOf ?? []) {
18
+ const denial = nativeMessagesToolScopeDenial(part, providerName, requestedModel, body);
19
+ if (denial) return denial;
20
+ }
21
+ if (scope.models.length === 0) return undefined;
17
22
  const definitions = new Map<string, Rec[]>();
18
23
  const withdrawn = new Set<string>();
19
24
  const anonymous: Rec[] = [];
@@ -112,7 +112,31 @@ export function tapAnthropicSseForLog(
112
112
  ): ReadableStream<Uint8Array> {
113
113
  const decoder = new TextDecoder();
114
114
  const encoder = new TextEncoder();
115
- let buffer = "";
115
+ let frameParts: string[] = [];
116
+ let pendingParts: string[] = [];
117
+ let pendingChars = 0;
118
+ let heldCr = false;
119
+ let heldLf = false;
120
+ const appendPart = (part: string) => {
121
+ if (!part) return;
122
+ pendingParts.push(part);
123
+ pendingChars += part.length;
124
+ // Coalesce tiny transport fragments: a one-byte feed must not retain one array
125
+ // entry per byte for the entire event. Each character is joined at most twice.
126
+ if (pendingChars >= 4096) {
127
+ frameParts.push(pendingParts.join(""));
128
+ pendingParts = [];
129
+ pendingChars = 0;
130
+ }
131
+ };
132
+ const takeFrame = () => {
133
+ if (pendingParts.length) frameParts.push(pendingParts.join(""));
134
+ const frame = frameParts.join("");
135
+ frameParts = [];
136
+ pendingParts = [];
137
+ pendingChars = 0;
138
+ return frame;
139
+ };
116
140
  let usageAcc: Rec = {};
117
141
  // message_stop or an upstream error event: the turn's own terminal already went through.
118
142
  let terminalSeen = false;
@@ -156,17 +180,29 @@ export function tapAnthropicSseForLog(
156
180
  }
157
181
  };
158
182
  const inspect = (chunk: Uint8Array) => {
159
- buffer += decoder.decode(chunk, { stream: true });
160
- // SSE lines may end in CRLF, LF or CR. Normalize the inspection copy to LF (the forwarded
161
- // bytes are untouched), holding a trailing CR until the next chunk shows whether an LF
162
- // follows it, so a CRLF split across chunks stays one line ending.
163
- const heldCr = buffer.endsWith("\r");
164
- buffer = (heldCr ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, "\n") + (heldCr ? "\r" : "");
183
+ // Normalize and scan only new text. Keep an unfinished frame in fragments so a long
184
+ // SSE event arriving in small chunks is never flattened or rescanned on each read.
185
+ let text = (heldCr ? "\r" : "") + decoder.decode(chunk, { stream: true });
186
+ heldCr = text.endsWith("\r");
187
+ text = (heldCr ? text.slice(0, -1) : text).replace(/\r\n?/g, "\n");
188
+ let start = 0;
189
+ if (text && heldLf) {
190
+ heldLf = false;
191
+ if (text[0] === "\n") {
192
+ inspectFrame(takeFrame());
193
+ start = 1;
194
+ } else appendPart("\n");
195
+ }
165
196
  let sep: number;
166
- while ((sep = buffer.indexOf("\n\n")) !== -1) {
167
- const frame = buffer.slice(0, sep);
168
- buffer = buffer.slice(sep + 2);
169
- inspectFrame(frame);
197
+ while ((sep = text.indexOf("\n\n", start)) !== -1) {
198
+ appendPart(text.slice(start, sep));
199
+ inspectFrame(takeFrame());
200
+ start = sep + 2;
201
+ }
202
+ if (start < text.length) {
203
+ heldLf = text.endsWith("\n");
204
+ const end = text.length - (heldLf ? 1 : 0);
205
+ appendPart(text.slice(start, end));
170
206
  }
171
207
  };
172
208
  // The last block can sit in the buffer without its blank line: an upstream that stopped after
@@ -175,14 +211,18 @@ export function tapAnthropicSseForLog(
175
211
  // client has not seen a blank line after, so the caller restores one. tailClean: nothing but
176
212
  // comments or a ping is left undelimited, so no message event was cut off.
177
213
  const flushTail = (): { terminalInTail: boolean; tailClean: boolean } => {
178
- // At EOF a held CR is a line ending, so it can complete a frame the client already has.
179
- let tail = (buffer + decoder.decode()).replace(/\r\n?/g, "\n");
180
- buffer = "";
214
+ // Rebuild the unscanned text in wire order (fragments, held LF, held CR). At EOF a held CR is
215
+ // a line ending, so it can complete a frame the client already has.
216
+ const rest = (takeFrame() + (heldLf ? "\n" : "") + (heldCr ? "\r" : "") + decoder.decode()).replace(/\r\n?/g, "\n");
217
+ heldCr = false;
218
+ heldLf = false;
219
+ let start = 0;
181
220
  let sep: number;
182
- while ((sep = tail.indexOf("\n\n")) !== -1) {
183
- inspectFrame(tail.slice(0, sep));
184
- tail = tail.slice(sep + 2);
221
+ while ((sep = rest.indexOf("\n\n", start)) !== -1) {
222
+ inspectFrame(rest.slice(start, sep));
223
+ start = sep + 2;
185
224
  }
225
+ const tail = rest.slice(start);
186
226
  const terminalBefore = terminalSeen;
187
227
  if (tail) inspectFrame(tail, false);
188
228
  return {
@@ -60,13 +60,13 @@ function readRecords(): DeviceRecord[] {
60
60
  try { fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK)); }
61
61
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
62
62
  try {
63
- const stat = fstatSync(fd);
64
- const entry = lstatSync(path);
65
- if (!stat.isFile() || stat.nlink !== 1 || stat.size > STORE_LIMIT || entry.isSymbolicLink()
63
+ const stat = fstatSync(fd, { bigint: true });
64
+ const entry = lstatSync(path, { bigint: true });
65
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size > STORE_LIMIT || entry.isSymbolicLink()
66
66
  || stat.dev !== entry.dev || stat.ino !== entry.ino) throw new Error("unsafe dashboard session store");
67
67
  // Size the read from the stat we validated: a store that grows mid-read overflows
68
68
  // the +1 sentinel byte and is rejected instead of silently truncated at a fixed limit.
69
- const bytes = Buffer.alloc(stat.size + 1);
69
+ const bytes = Buffer.alloc(Number(stat.size) + 1);
70
70
  let length = 0;
71
71
  while (length < bytes.length) { const count = readSync(fd, bytes, length, bytes.length - length, null); if (!count) break; length += count; }
72
72
  if (length > stat.size) throw new Error("dashboard session store changed during read");
@@ -19,6 +19,7 @@ import {
19
19
  } from "../lib/errors";
20
20
  import { CODEX_CONFIG_PATH, readRootTomlString } from "../codex/paths";
21
21
  import type { CodexAffinityMove, CodexAffinityReason } from "../codex/routing";
22
+ import type { CodexAuthContext } from "../codex/auth-context";
22
23
  import { readCodexCatalogPath } from "../codex/catalog";
23
24
  import type { AttemptTierOutcome, OcxProviderConfig, OcxUsage } from "../types";
24
25
  import { normalizeRouteDecisionTrace, type RouteDecisionTraceV1 } from "../routing/trace";
@@ -46,6 +47,7 @@ import {
46
47
  normalizeClaudeCompatibilityUsageLog,
47
48
  normalizeRequestFailureAttribution,
48
49
  normalizeRequestSpend,
50
+ normalizedAttempts,
49
51
  readRecentUsageEntries,
50
52
  modelIdentityLogFields, recordObservedServedModel,
51
53
  usageForFinalLog,
@@ -357,6 +359,8 @@ export interface RequestLogEntry extends UpstreamErrorDiagnostics {
357
359
  usage?: OcxUsage;
358
360
  totalTokens?: number;
359
361
  attempts?: PersistedUsageAttempt[];
362
+ /** True when persistence normalization drops any attempt. */
363
+ attemptNormalizationDropped?: boolean;
360
364
  /**
361
365
  * Upstream spend for the whole logical request: sends aggregated across attempts and combo
362
366
  * children, split into settled and unresolved, with the budget state and move reasons that
@@ -513,6 +517,8 @@ export function requestLogEntryFromPersistedUsage(entry: PersistedUsageEntry): R
513
517
  ...(entry.usage ? { usage: entry.usage } : {}),
514
518
  ...(entry.totalTokens !== undefined ? { totalTokens: entry.totalTokens } : {}),
515
519
  ...(entry.attempts !== undefined ? { attempts: entry.attempts } : {}),
520
+ ...(entry.attemptNormalizationDropped === true
521
+ ? { attemptNormalizationDropped: true } : {}),
516
522
  ...(spend ? { spend } : {}),
517
523
  ...(isKnownCacheTelemetryProvenance(entry.cacheProvenance)
518
524
  ? { cacheProvenance: entry.cacheProvenance }
@@ -619,12 +625,16 @@ export function addRequestLog(entry: RequestLogEntry) {
619
625
  const servedModel = modelIdentityLogFields(entry).servedModel;
620
626
  const claudeCompatibility = normalizeClaudeCompatibilityUsageLog(entry.claudeCompatibility);
621
627
  const jevDecision = normalizePersistedJevDecision(entry.jevDecision);
628
+ const attempts = normalizedAttempts(entry.attempts);
629
+ const attemptsDropped = Array.isArray(entry.attempts) && attempts.length < entry.attempts.length;
622
630
  const retained: RequestLogEntry = shadowCallRewrittenFrom === entry.shadowCallRewrittenFrom
623
631
  && servedModel === entry.servedModel
624
632
  && entry.claudeCompatibility === undefined
625
633
  && entry.jevDecision === undefined
634
+ && !attemptsDropped
626
635
  ? entry
627
- : { ...entry, ...(shadowCallRewrittenFrom ? { shadowCallRewrittenFrom } : {}) };
636
+ : { ...entry, ...(entry.attemptNormalizationDropped === true || attemptsDropped ? { attemptNormalizationDropped: true } : {}),
637
+ ...(shadowCallRewrittenFrom ? { shadowCallRewrittenFrom } : {}) };
628
638
  if (!shadowCallRewrittenFrom && retained !== entry) delete retained.shadowCallRewrittenFrom;
629
639
  if (!servedModel && retained !== entry) {
630
640
  delete retained.servedModel;
@@ -699,6 +709,8 @@ export function addRequestLog(entry: RequestLogEntry) {
699
709
  ...(entry.usage ? { usage: entry.usage } : {}),
700
710
  ...(entry.totalTokens !== undefined ? { totalTokens: entry.totalTokens } : {}),
701
711
  ...(entry.attempts !== undefined ? { attempts: entry.attempts } : {}),
712
+ ...(entry.attemptNormalizationDropped === true
713
+ ? { attemptNormalizationDropped: true } : {}),
702
714
  ...(entry.spend ? { spend: entry.spend } : {}),
703
715
  ...(isKnownCacheTelemetryProvenance(entry.cacheProvenance)
704
716
  ? { cacheProvenance: entry.cacheProvenance }
@@ -1263,6 +1275,18 @@ export function noteAffinityMove(
1263
1275
  (logCtx.affinityMoveReasons ??= []).push(reason);
1264
1276
  }
1265
1277
 
1278
+ /**
1279
+ * Copy the selection's own affinity decision onto the request log. Both Pool-served kinds carry
1280
+ * one: a stored Pool account and the main login rotating as `main-pool` (#4546, #7799). A move
1281
+ * then reads as an event with its cause instead of something inferred from account labels.
1282
+ */
1283
+ export function noteCodexSelectionAffinity(logCtx: RequestLogContext, authCtx: CodexAuthContext): void {
1284
+ const decision = authCtx.kind === "pool" || authCtx.kind === "main-pool" ? authCtx.affinityDecision : undefined;
1285
+ if (!decision) return;
1286
+ logCtx.affinity = decision.move;
1287
+ logCtx.affinityReason = decision.reason;
1288
+ }
1289
+
1266
1290
  /**
1267
1291
  * The affinity scope a released binding belonged to: one thread, one model lane.
1268
1292
  *
@@ -1625,7 +1649,10 @@ function finalizedUsage(
1625
1649
  const usageFallback = !finalUsage && estimate !== undefined
1626
1650
  ? { inputTokens: estimate, outputTokens: 0, estimated: true }
1627
1651
  : undefined;
1628
- const combinedInputTokens = finalUsage && estimate !== undefined
1652
+ // The estimate is a floor under a count the adapter could only guess. A count the adapter read
1653
+ // off the upstream's own usage frame stays exact: max() against a larger local estimate would
1654
+ // replace it and mark it estimated.
1655
+ const combinedInputTokens = finalUsage && !finalUsage.upstreamReported && estimate !== undefined
1629
1656
  ? Math.max(finalUsage.inputTokens, estimate)
1630
1657
  : undefined;
1631
1658
  const loggedUsage = finalUsage && combinedInputTokens !== undefined
@@ -1907,6 +1934,7 @@ export function aggregateAttemptUsage(
1907
1934
  ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
1908
1935
  ...(providerCredits !== undefined ? { providerCredits } : {}),
1909
1936
  ...(status === "estimated" ? { estimated: true } : {}),
1937
+ ...(usages.every(usage => usage.upstreamReported) ? { upstreamReported: true as const } : {}),
1910
1938
  };
1911
1939
  return { usage: aggregate, status, totalTokens };
1912
1940
  }