@bitkyc08/opencodex 2.94.0 → 2.95.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 (249) hide show
  1. package/gui/dist/assets/App-8yedBkhm.js +58 -0
  2. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-erSMzxPG.js} +1 -1
  4. package/gui/dist/assets/index-D7DCm5eQ.js +94 -0
  5. package/gui/dist/assets/quota-summary-BK4VuQNc.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/openai-chat/messages.ts +20 -7
  14. package/src/adapters/openai-chat/passthrough.ts +4 -2
  15. package/src/adapters/openai-chat/single-system.ts +24 -0
  16. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  17. package/src/adapters/openai-responses/passthrough.ts +42 -7
  18. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  19. package/src/adapters/openai-responses/request-strips.ts +23 -4
  20. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  21. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  22. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  23. package/src/adapters/routed-agent-messages.ts +3 -0
  24. package/src/adapters/xai-web-search.ts +6 -3
  25. package/src/adapters/zed-additional-tools.ts +7 -7
  26. package/src/adapters/zed.ts +1 -6
  27. package/src/advisor/consult.ts +22 -10
  28. package/src/advisor/runtime.ts +10 -4
  29. package/src/bridge/max-output-completion.ts +41 -0
  30. package/src/bridge/response-json.ts +9 -4
  31. package/src/bridge/sse.ts +13 -2
  32. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  33. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  34. package/src/claude/compatibility.ts +5 -1
  35. package/src/claude/desktop-3p.ts +27 -6
  36. package/src/claude/desktop-model-visibility.ts +141 -0
  37. package/src/claude/desktop-remote-store-io.ts +8 -8
  38. package/src/claude/inbound-content-options.ts +11 -1
  39. package/src/claude/intercept/proxy-auth.ts +16 -16
  40. package/src/cli/account-main.ts +3 -2
  41. package/src/cli/capabilities-provider-models.ts +7 -0
  42. package/src/cli/chatgpt-command.ts +1 -1
  43. package/src/cli/codex-launcher.ts +20 -8
  44. package/src/cli/codex-shim-autorestore.ts +19 -1
  45. package/src/cli/dispatch.ts +6 -6
  46. package/src/cli/doctor.ts +5 -5
  47. package/src/cli/index.ts +4 -9
  48. package/src/cli/init.ts +2 -2
  49. package/src/cli/internal-command.ts +29 -2
  50. package/src/cli/provider-cc-switch-import.ts +185 -0
  51. package/src/cli/provider.ts +5 -0
  52. package/src/cli/registry.ts +1 -0
  53. package/src/cli/restart-scope.ts +2 -2
  54. package/src/cli/root.ts +6 -6
  55. package/src/cli/stop-approval.ts +15 -1
  56. package/src/cli/v2.ts +69 -19
  57. package/src/client/machine-api.ts +2 -2
  58. package/src/clients/config-export.ts +14 -3
  59. package/src/codex/account-cooldown-response.ts +18 -0
  60. package/src/codex/app-server-restart-service.ts +2 -2
  61. package/src/codex/auth-api/login-flow.ts +2 -2
  62. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  63. package/src/codex/auth-context.ts +4 -4
  64. package/src/codex/catalog/bundled.ts +10 -3
  65. package/src/codex/catalog/metadata.ts +4 -5
  66. package/src/codex/catalog/native-omission.ts +28 -0
  67. package/src/codex/catalog/native-template.ts +58 -0
  68. package/src/codex/catalog/parsing.ts +3 -29
  69. package/src/codex/catalog/provider-models.ts +2 -1
  70. package/src/codex/catalog/retained-sync.ts +15 -5
  71. package/src/codex/catalog/write-audit.ts +18 -18
  72. package/src/codex/cli-install-provenance.ts +46 -45
  73. package/src/codex/cli-update-artifacts.ts +8 -6
  74. package/src/codex/cli-update-job-store-windows.ts +99 -27
  75. package/src/codex/cli-update-job-worker.ts +3 -11
  76. package/src/codex/cli-update-recovery.ts +54 -8
  77. package/src/codex/cli-update-selection-gate.ts +74 -4
  78. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  79. package/src/codex/codex-home-owner.ts +9 -8
  80. package/src/codex/convergence.ts +13 -3
  81. package/src/codex/coordinator-doctor.ts +14 -8
  82. package/src/codex/desktop-app/handoff.ts +1 -1
  83. package/src/codex/desktop-app-restart.ts +11 -1
  84. package/src/codex/exec-boundary.ts +26 -5
  85. package/src/codex/history-provider.ts +11 -10
  86. package/src/codex/inject/bounded-config-reader.ts +14 -13
  87. package/src/codex/main-account.ts +6 -6
  88. package/src/codex/native-main-lock-file.ts +13 -12
  89. package/src/codex/native-residue.ts +18 -14
  90. package/src/codex/orca-auth-source.ts +8 -7
  91. package/src/codex/quota-types.ts +5 -0
  92. package/src/codex/quota.ts +49 -7
  93. package/src/codex/role-auto-assign.ts +50 -26
  94. package/src/codex/role-capability.ts +160 -0
  95. package/src/codex/role-sizing.ts +24 -6
  96. package/src/codex/routing/cooldown-math.ts +3 -2
  97. package/src/codex/runtime.ts +43 -3
  98. package/src/codex/shim-fingerprint.ts +11 -9
  99. package/src/codex/shim-inspect.ts +3 -2
  100. package/src/codex/shim-restore-lock.ts +11 -14
  101. package/src/codex/shim-state-file.ts +22 -14
  102. package/src/codex/shim-wrapper-write.ts +7 -6
  103. package/src/codex/shim.ts +25 -2
  104. package/src/codex/transition-state.ts +5 -4
  105. package/src/combos/failover.ts +43 -4
  106. package/src/config/atomic-write.ts +38 -7
  107. package/src/config/diagnostics.ts +3 -0
  108. package/src/config/initialize.ts +6 -6
  109. package/src/config/load-degrade.ts +2 -0
  110. package/src/config/process-state.ts +23 -5
  111. package/src/config/salvage.ts +1 -0
  112. package/src/config/schema/config-schema.ts +29 -1
  113. package/src/config/schema/leaf-validators.ts +7 -0
  114. package/src/config/schema/workflow-budget.ts +43 -0
  115. package/src/config/tracked-runtime-inspection.ts +188 -0
  116. package/src/generated/compatibility-version.json +313 -213
  117. package/src/integrations/aside-profile-context.ts +1 -1
  118. package/src/integrations/droid-settings.ts +4 -4
  119. package/src/integrations/hermes-profiles.ts +3 -3
  120. package/src/lib/bounded-file-read.ts +3 -9
  121. package/src/lib/bun-runtime-preflight.ts +9 -8
  122. package/src/lib/file-identity.ts +15 -0
  123. package/src/lib/local-chat-completion.ts +8 -6
  124. package/src/lib/local-destinations.ts +32 -3
  125. package/src/lib/redact-folding.ts +9 -0
  126. package/src/lib/spend-pool-alias-validation.ts +6 -6
  127. package/src/lib/state-store-registrations.ts +2 -0
  128. package/src/lib/test-home-guard.ts +37 -9
  129. package/src/lib/windows-secret-acl.ts +47 -29
  130. package/src/lib/workflow-budget-config.ts +39 -0
  131. package/src/local-credentials/generation.ts +6 -2
  132. package/src/local-credentials/inventory.ts +132 -8
  133. package/src/messaging/remote-forward-failure.ts +35 -0
  134. package/src/messaging/remote-ports.ts +27 -5
  135. package/src/messaging/remote-process.ts +30 -4
  136. package/src/messaging/remote-tunnels.ts +80 -15
  137. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  138. package/src/oauth/google-antigravity.ts +23 -10
  139. package/src/oauth/index.ts +2 -0
  140. package/src/oauth/kiro-device-login.ts +87 -30
  141. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  142. package/src/oauth/store.ts +9 -7
  143. package/src/providers/account-quota-disk.ts +18 -4
  144. package/src/providers/cc-switch-import-bytes.ts +991 -0
  145. package/src/providers/cc-switch-import-source.ts +1083 -0
  146. package/src/providers/cc-switch-import.ts +942 -0
  147. package/src/providers/derive.ts +6 -0
  148. package/src/providers/model-discovery-diagnostic.ts +4 -0
  149. package/src/providers/model-discovery.ts +4 -4
  150. package/src/providers/model-rename-fields.ts +2 -0
  151. package/src/providers/model-rename-migration.ts +41 -6
  152. package/src/providers/quota/report-cache.ts +17 -4
  153. package/src/providers/quota.ts +2 -2
  154. package/src/providers/reasoning-metadata.ts +31 -15
  155. package/src/providers/registry/entries-core.ts +1 -1
  156. package/src/providers/registry/entries-extended.ts +1 -1
  157. package/src/providers/registry/model-ids.ts +1 -0
  158. package/src/providers/registry/model-seeds.ts +2 -1
  159. package/src/providers/registry/types.ts +3 -1
  160. package/src/providers/resolved-model-policy.ts +2 -2
  161. package/src/providers/routed-config.ts +2 -0
  162. package/src/providers/stale-model-roster-migration.ts +5 -1
  163. package/src/providers/xai-transport.ts +4 -4
  164. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  165. package/src/remote-control/workspace-executor.ts +14 -13
  166. package/src/responses/custom-tool-compat.ts +2 -1
  167. package/src/responses/item-provenance.ts +79 -0
  168. package/src/responses/namespace-tool-compat.ts +21 -3
  169. package/src/router.ts +21 -2
  170. package/src/routing/analytics.ts +3 -5
  171. package/src/routing/fallback-policy.ts +7 -3
  172. package/src/routing/health.ts +5 -3
  173. package/src/routing/history/build-file.ts +6 -0
  174. package/src/routing/history/indexer.ts +158 -31
  175. package/src/routing/history/ingest.ts +1 -1
  176. package/src/routing/history/integrity.ts +208 -0
  177. package/src/routing/history/rebuild-job.ts +20 -6
  178. package/src/routing/history/rebuild-protocol.ts +2 -1
  179. package/src/routing/history/rebuild-worker.ts +18 -0
  180. package/src/routing/history/sqlite-errors.ts +9 -0
  181. package/src/server/admission-model-scope.ts +21 -4
  182. package/src/server/advisor-admission-scope.ts +29 -0
  183. package/src/server/auth-cors.ts +5 -2
  184. package/src/server/capture-admission-policy.ts +91 -0
  185. package/src/server/chat-completions.ts +33 -7
  186. package/src/server/claude-messages.ts +90 -2
  187. package/src/server/codex-model-list.ts +2 -1
  188. package/src/server/configured-credentials.ts +5 -0
  189. package/src/server/index/serve-options.ts +12 -2
  190. package/src/server/index/websocket-handler.ts +3 -0
  191. package/src/server/management/agent-settings-routes.ts +34 -9
  192. package/src/server/management/codex-agent-role-routes.ts +1 -0
  193. package/src/server/management/codex-role-auto-assign.ts +50 -6
  194. package/src/server/management/config-routes.ts +15 -4
  195. package/src/server/management/context.ts +3 -0
  196. package/src/server/management/native-integration-routes.ts +22 -0
  197. package/src/server/management/oauth-account-routes.ts +20 -4
  198. package/src/server/management/provider-overwrite-carry.ts +21 -0
  199. package/src/server/management/provider-routes.ts +3 -1
  200. package/src/server/management/route-registry.ts +2 -0
  201. package/src/server/management/shared.ts +17 -1
  202. package/src/server/management/workflow-budget-routes.ts +70 -3
  203. package/src/server/messages-native-eligibility.ts +6 -5
  204. package/src/server/messages-native-scope.ts +6 -1
  205. package/src/server/messages-shared.ts +57 -17
  206. package/src/server/persistent-gui-session.ts +4 -4
  207. package/src/server/request-log.ts +30 -2
  208. package/src/server/responses/adapter-delivery.ts +4 -0
  209. package/src/server/responses/advisor-plan-slot.ts +4 -0
  210. package/src/server/responses/advisor-slot.ts +73 -46
  211. package/src/server/responses/codex-auth-error.ts +5 -1
  212. package/src/server/responses/combo-required-tool-contract.ts +27 -0
  213. package/src/server/responses/compact.ts +4 -1
  214. package/src/server/responses/core-combo-failure.ts +2 -0
  215. package/src/server/responses/core-combo.ts +66 -5
  216. package/src/server/responses/core-lifetime.ts +4 -0
  217. package/src/server/responses/core-options.ts +9 -0
  218. package/src/server/responses/core.ts +2 -0
  219. package/src/server/responses/jev-model-invoke.ts +4 -2
  220. package/src/server/responses/passthrough-dispatch.ts +5 -4
  221. package/src/server/responses/policy-fallback.ts +2 -0
  222. package/src/server/responses/request-prepare.ts +4 -5
  223. package/src/server/responses/request-send-budget.ts +2 -1
  224. package/src/server/responses/request-sidecar-auth.ts +1 -0
  225. package/src/server/responses/request-transport.ts +2 -3
  226. package/src/server/responses/run-turn-execution.ts +4 -0
  227. package/src/server/responses/sidecar-execution.ts +21 -5
  228. package/src/server/responses-snapshot-repair.ts +18 -4
  229. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/service/state-lock.ts +12 -11
  232. package/src/service-manager-probe.ts +53 -8
  233. package/src/types/admission-policy.ts +13 -0
  234. package/src/types/config.ts +25 -0
  235. package/src/types/provider.ts +10 -0
  236. package/src/types/request.ts +7 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/job.ts +20 -0
  239. package/src/update/worker-launch.ts +71 -1
  240. package/src/usage/log.ts +25 -4
  241. package/src/vision/index.ts +2 -0
  242. package/src/vision/plan.ts +4 -0
  243. package/src/vision/routed-describe.ts +38 -23
  244. package/src/web-search/loop.ts +104 -9
  245. package/src/web-search/parse.ts +10 -2
  246. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  247. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  248. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  249. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
@@ -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
  }
@@ -269,6 +269,8 @@ export async function deliverAdapterResponse(
269
269
  toolParameterSchemas,
270
270
  ...(options.onFirstOutput ? { onFirstOutput: options.onFirstOutput } : {}),
271
271
  ...(routedCompaction ? { compaction: true, compactionRetention: parsed._compactionRetention } : {}),
272
+ completeOnMaxOutputTokens: config.completeOnMaxOutputTokens === true && options.inboundWire !== "chat" && options.inboundWire !== "anthropic",
273
+ textFormat: parsed.options.textFormat,
272
274
  // Same grok-surface split as the runTurn branch above.
273
275
  ...(logCtx.surface === "grok" ? { heartbeatStyle: "comment" as const } : {}),
274
276
  onUsage: usage => {
@@ -378,6 +380,8 @@ export async function deliverAdapterResponse(
378
380
  freeformToolNames,
379
381
  toolSearchToolNames,
380
382
  ...(routedCompaction ? { compaction: true, compactionRetention: parsed._compactionRetention } : {}),
383
+ completeOnMaxOutputTokens: config.completeOnMaxOutputTokens === true && options.inboundWire !== "chat" && options.inboundWire !== "anthropic",
384
+ textFormat: parsed.options.textFormat,
381
385
  onProviderState: state => { providerState = state; },
382
386
  onUsage: usage => {
383
387
  transportState.bindKeyUsageFromBridge(usage);
@@ -1,6 +1,7 @@
1
1
  /** Core-owned, config-scoped registration. An inactive install has no Advisor factory. */
2
2
  import type { OcxConfig, OcxParsedRequest, OcxTool } from "../../types";
3
3
  import type { AdmissionModelScope } from "../admission-model-scope";
4
+ import type { AdvisorPlan } from "./advisor-slot";
4
5
 
5
6
  export interface AdvisorPlanInput {
6
7
  config: OcxConfig;
@@ -8,11 +9,14 @@ export interface AdvisorPlanInput {
8
9
  workerModelId: string;
9
10
  /** Immutable scope captured from the request that is paying for this sidecar. */
10
11
  admissionScope?: AdmissionModelScope;
12
+ admissionPolicy?: import("../../types/admission-policy").CapturedAdmissionPolicy;
11
13
  abortSignal?: AbortSignal;
12
14
  }
13
15
 
14
16
  export interface RegisteredAdvisorPlan {
15
17
  tool: OcxTool;
18
+ consult?: AdvisorPlan["consult"];
19
+ formatUnavailable?: AdvisorPlan["formatUnavailable"];
16
20
  preflightInject(parsed: OcxParsedRequest): Promise<boolean>;
17
21
  attachGuard(parsed: OcxParsedRequest): void;
18
22
  }
@@ -69,6 +69,7 @@ export interface AdvisorPlan {
69
69
  parsed: OcxParsedRequest,
70
70
  reason: "manual",
71
71
  question: string | undefined,
72
+ abortSignal?: AbortSignal,
72
73
  ): Promise<AdvisorConsultOutcome>;
73
74
  /**
74
75
  * Runtime-owned text for a failed or limited consultation. The guard never composes failure
@@ -78,6 +79,68 @@ export interface AdvisorPlan {
78
79
  formatUnavailable(kind: "manual" | "limit", error: string): string;
79
80
  }
80
81
 
82
+ export interface AdvisorSidecarCall {
83
+ id: string;
84
+ name: string;
85
+ question?: string;
86
+ providerMetadata?: import("../../types").OcxProviderOpaqueToolCallMetadata;
87
+ }
88
+
89
+ /**
90
+ * Shares continuation/consultation bounds between the normal guard and fetch sidecar loops.
91
+ * Each leg is reserved before any expert await, while repeated calls receive one bounded limit
92
+ * result instead of starting another consultation. The tool result preserves the worker call id.
93
+ */
94
+ export function createAdvisorSidecarStep(plan: AdvisorPlan) {
95
+ let consultations = 0;
96
+ let continuations = 0;
97
+ let finalContinuationUsed = false;
98
+ return {
99
+ beginLeg(): Extract<AdapterEvent, { type: "error" }> | undefined {
100
+ const final = consultations >= MAX_ADVISOR_CONSULTATIONS_PER_REQUEST;
101
+ if (continuations >= MAX_ADVISOR_CONTINUATIONS_PER_REQUEST || finalContinuationUsed) {
102
+ return {
103
+ type: "error",
104
+ status: 502,
105
+ errorType: "advisor_continuation_limit",
106
+ message: "Advisor worker continuation limit reached; no further worker calls were sent.",
107
+ };
108
+ }
109
+ continuations += 1;
110
+ finalContinuationUsed ||= final;
111
+ return undefined;
112
+ },
113
+ async consultCall(parsed: OcxParsedRequest, call: AdvisorSidecarCall, abortSignal?: AbortSignal) {
114
+ let outcome: AdvisorConsultOutcome;
115
+ if (consultations >= MAX_ADVISOR_CONSULTATIONS_PER_REQUEST) {
116
+ outcome = {
117
+ ok: false,
118
+ isError: true,
119
+ content: plan.formatUnavailable("limit", "consultation limit reached for this request"),
120
+ };
121
+ } else {
122
+ consultations += 1;
123
+ try {
124
+ outcome = await plan.consult(parsed, "manual", call.question, abortSignal);
125
+ } catch (error) {
126
+ if (isTranslatorBudgetExceededError(error)) throw error;
127
+ outcome = {
128
+ ok: false,
129
+ isError: true,
130
+ content: plan.formatUnavailable("manual", error instanceof Error ? error.message : String(error)),
131
+ };
132
+ }
133
+ }
134
+ return { outcome, message: advisorToolResult(call, outcome, Date.now()) };
135
+ },
136
+ exhausted(): boolean {
137
+ return consultations >= MAX_ADVISOR_CONSULTATIONS_PER_REQUEST;
138
+ },
139
+ };
140
+ }
141
+
142
+ export type AdvisorSidecarStep = ReturnType<typeof createAdvisorSidecarStep>;
143
+
81
144
  interface HeldAdvisorCall {
82
145
  id: string;
83
146
  name: string;
@@ -90,10 +153,10 @@ interface HeldAdvisorCall {
90
153
 
91
154
  function parseAdvisorArgs(call: HeldAdvisorCall, retention: AdvisorRetention): { question?: string } {
92
155
  // Reserve both the joined input and parsed JSON before either is materialized.
93
- return retention.copy(call.argumentBytes * 2 + 4, () => parseArgs(call.args.join("")));
156
+ return retention.copy(call.argumentBytes * 2 + 4, () => parseAdvisorQuestionArgs(call.args.join("")));
94
157
  }
95
158
 
96
- function parseArgs(argsBuf: string): { question?: string } {
159
+ export function parseAdvisorQuestionArgs(argsBuf: string): { question?: string } {
97
160
  if (argsBuf.trim() === "") return {};
98
161
  try {
99
162
  const parsed: unknown = JSON.parse(argsBuf);
@@ -129,7 +192,7 @@ function assistantMessageFromLeg(
129
192
  }
130
193
 
131
194
  function advisorToolResult(
132
- call: HeldAdvisorCall,
195
+ call: AdvisorSidecarCall,
133
196
  outcome: AdvisorConsultOutcome,
134
197
  timestamp: number,
135
198
  ): OcxToolResultMessage {
@@ -163,11 +226,8 @@ export function createAdvisorStreamGuard(options: AdvisorGuardOptions): AsyncGen
163
226
  }
164
227
  export function createAdvisorGuard(plan: AdvisorPlan): NonNullable<OcxParsedRequest["_advisorGuard"]> {
165
228
  // Shared across invocations of this request's guard, including an empty-completion retry.
166
- let consultations = 0;
167
- let continuations = 0;
168
- let finalContinuationUsed = false;
229
+ const sidecar = createAdvisorSidecarStep(plan);
169
230
  return async function* guardAdvisorStream(options: Omit<AdvisorGuardOptions, "plan">): AsyncGenerator<AdapterEvent> {
170
- const maxConsultations = MAX_ADVISOR_CONSULTATIONS_PER_REQUEST;
171
231
  let parsed = options.parsed;
172
232
  let accumulatedUsage: OcxUsage | undefined;
173
233
  let source: AsyncIterable<AdapterEvent> = options.firstEvents;
@@ -275,61 +335,28 @@ export function createAdvisorGuard(plan: AdvisorPlan): NonNullable<OcxParsedRequ
275
335
 
276
336
  // Consume this leg's done — the continuation replaces it.
277
337
  accumulatedUsage = retention.usage(accumulatedUsage, terminalEvent?.usage);
278
- if (continuations >= MAX_ADVISOR_CONTINUATIONS_PER_REQUEST || finalContinuationUsed) {
279
- yield {
280
- type: "error",
281
- status: 502,
282
- errorType: "advisor_continuation_limit",
283
- message: "Advisor worker continuation limit reached; no further worker calls were sent.",
284
- ...(accumulatedUsage ? { usage: accumulatedUsage } : {}),
285
- };
338
+ const continuationError = sidecar.beginLeg();
339
+ if (continuationError) {
340
+ yield accumulatedUsage ? { ...continuationError, usage: accumulatedUsage } : continuationError;
286
341
  return;
287
342
  }
288
- // A repeated call after tool removal gets one last paired limit result, never a loop.
289
- const isFinalContinuation = consultations >= maxConsultations;
290
- // Reserve before any consultation await, so simultaneous guard entries share the bound.
291
- continuations += 1;
292
- finalContinuationUsed ||= isFinalContinuation;
293
343
  const timestamp = Date.now();
294
344
  const assistant = retention.history(retention.replayReservation(), () => assistantMessageFromLeg(legEvents, advisorCalls, timestamp, retention));
295
345
  const messages: OcxMessage[] = [...parsed.context.messages];
296
346
  if (assistant) messages.push(assistant);
297
347
 
298
348
  for (const call of advisorCalls) {
299
- if (consultations >= maxConsultations) {
300
- // Runtime-owned limit text: not advice, and never a genuine advice wrapper.
301
- const outcome = {
302
- ok: false,
303
- isError: true,
304
- content: plan.formatUnavailable("limit", "consultation limit reached for this request"),
305
- };
306
- messages.push(retention.history(jsonUtf8Bytes(outcome) + jsonUtf8Bytes(call.id) + 256, () => advisorToolResult(call, outcome, timestamp))!);
307
- continue;
308
- }
309
- consultations += 1;
310
349
  // Later calls in the same leg must see what came before them: the rebuilt worker turn
311
350
  // and every earlier advisor result in this leg's accumulated messages.
312
351
  const consultParsed: OcxParsedRequest = {
313
352
  ...parsed,
314
353
  context: { ...parsed.context, messages },
315
354
  };
316
- let outcome: AdvisorConsultOutcome;
317
- try {
318
- outcome = await plan.consult(consultParsed, "manual", call.question);
319
- } catch (error) {
320
- if (isTranslatorBudgetExceededError(error)) throw error;
321
- // Runtime-owned failure text only: the implementation neutralizes untrusted exception
322
- // text so it can never forge a genuine advice wrapper.
323
- outcome = {
324
- ok: false,
325
- isError: true,
326
- content: plan.formatUnavailable("manual", error instanceof Error ? error.message : String(error)),
327
- };
328
- }
329
- messages.push(retention.history(jsonUtf8Bytes(outcome) + jsonUtf8Bytes(call.id) + 256, () => advisorToolResult(call, outcome, timestamp))!);
355
+ const consulted = await sidecar.consultCall(consultParsed, call);
356
+ messages.push(retention.history(jsonUtf8Bytes(consulted.outcome) + jsonUtf8Bytes(call.id) + 256, () => consulted.message)!);
330
357
  }
331
358
 
332
- const exhausted = consultations >= maxConsultations;
359
+ const exhausted = sidecar.exhausted();
333
360
  const tools = exhausted
334
361
  ? parsed.context.tools?.filter(tool => !tool.advisor && tool.name !== ADVISOR_TOOL_NAME)
335
362
  : parsed.context.tools;
@@ -17,6 +17,7 @@ import {
17
17
  MainAuthJsonChangedDuringRefreshError,
18
18
  } from "../../codex/main-account";
19
19
  import { NativeProfileError } from "../../codex/native-profile-types";
20
+ import { markCodexAccountCooldownResponse } from "../../codex/account-cooldown-response";
20
21
 
21
22
  export interface CodexAuthContextErrorResponseOptions {
22
23
  accountSelector?: string;
@@ -78,7 +79,10 @@ export function mapCodexAuthContextErrorToResponse(
78
79
  options: CodexAuthContextErrorResponseOptions,
79
80
  ): Response | undefined {
80
81
  if (error instanceof CodexAccountCooldownError) {
81
- return cooldownErrorResponse(error, options.now, options.accountSelector);
82
+ const response = cooldownErrorResponse(error, options.now, options.accountSelector);
83
+ // Exact class only (#7850): main hard-lock, credit, Reserve, recovery-withheld and future
84
+ // policy subclasses keep their own retry semantics, including in combo target cooldowns.
85
+ return error.constructor === CodexAccountCooldownError ? markCodexAccountCooldownResponse(response) : response;
82
86
  }
83
87
  if (error instanceof CodexMainProfileDrainingError) {
84
88
  return codexMainProfileDrainingResponse();