@bitkyc08/opencodex 2.96.0 → 2.97.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 (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -10,13 +10,30 @@ export const POWERSHELL_ENCODED_MAX = 8_000;
10
10
  export function powershellArgv(script: string): string[] {
11
11
  // Module preparation otherwise writes a CLIXML progress record to stderr, which Home would see.
12
12
  const encoded = Buffer.from("$ProgressPreference='SilentlyContinue'\n" + script, "utf16le").toString("base64");
13
- if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error("Remote PowerShell command exceeds the cmd.exe-compatible command-line budget");
13
+ if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error(`Remote PowerShell command exceeds the cmd.exe-compatible command-line budget (${encoded.length})`);
14
14
  return ["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
15
15
  }
16
16
 
17
17
  /** Exit status when the remote ocx cannot be contained; nothing ran. */
18
18
  export const WINDOWS_CONTAINMENT_EXIT = 126;
19
19
 
20
+ const SCRIPT_PACKED_PREFIX = "$ocxPacked='";
21
+ /**
22
+ * The whole script travels deflated and is inflated on the Child before anything in it exists,
23
+ * including Fail. A session that cannot inflate it (Constrained Language Mode blocks the stream
24
+ * types) must still exit 126, so only the inflate is guarded: Invoke-Expression stays outside the
25
+ * try, and the inflated script's own errors and exit status are never relabelled as containment.
26
+ */
27
+ export function packedPowerShellArgv(script: string): string[] {
28
+ const bytes = deflateRawSync(Buffer.from(script, "utf8"), { level: 9 });
29
+ const packed = Array.from(bytes, byte => String.fromCharCode(byte + 256)).join("");
30
+ return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$ErrorActionPreference='Stop';try{$b=[byte[]]@($ocxPacked.ToCharArray()|%{[int]$_-256});$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new($b),[IO.Compression.CompressionMode]::Decompress));$s=$r.ReadToEnd()}catch{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit ${WINDOWS_CONTAINMENT_EXIT}};Invoke-Expression $s`);
31
+ }
32
+ function unpackPowerShell(script: string): string {
33
+ const match = /\$ocxPacked='([^']+)'/.exec(script);
34
+ return match ? inflateRawSync(Buffer.from(Array.from(match[1]!, ch => ch.charCodeAt(0) - 256))).toString("utf8") : script;
35
+ }
36
+
20
37
  /**
21
38
  * OcxJob, compiled on the Child with Add-Type, contains the remote ocx. Run creates the process
22
39
  * with PROC_THREAD_ATTRIBUTE_JOB_LIST (STARTUPINFOEX, EXTENDED_STARTUPINFO_PRESENT), so it is a
@@ -50,6 +67,12 @@ export const OCX_JOB_SOURCE = [
50
67
  "var q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});",
51
68
  "q.StandardInput.Close();q.StandardOutput.ReadToEndAsync();q.StandardError.ReadToEndAsync();",
52
69
  "if(q.WaitForExit(10000))return q.ExitCode==0;q.Kill();}catch{return false;}return false;}",
70
+ "public static string V(string x){Process q=null;try{",
71
+ "q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});q.StandardInput.Close();",
72
+ "var p=q;var read=System.Threading.Tasks.Task.Run(()=>{var b=new char[257];int n=0,k;while(n<257&&(k=p.StandardOutput.Read(b,n,257-n))>0)n+=k;return n>256?null:new string(b,0,n);});",
73
+ "System.Threading.Tasks.Task.Run(()=>{var b=new char[1024];while(p.StandardError.Read(b,0,b.Length)>0){} });",
74
+ "var clock=Stopwatch.StartNew();var done=System.Threading.Tasks.Task.Run(()=>p.WaitForExit());if(!read.Wait(10000)||read.Result==null||!done.Wait(Math.Max(0,10000-(int)clock.ElapsedMilliseconds))){q.Kill();q.WaitForExit();return null;}return q.ExitCode==0?read.Result:null;",
75
+ "}catch{try{if(q!=null&&!q.HasExited){q.Kill();q.WaitForExit();}}catch{return null;}return null;}finally{if(q!=null)q.Dispose();}}",
53
76
  "public static int Run(string x,string c){",
54
77
  "IntPtr z=IntPtr.Zero,j=z,l=z,v=z,h=z,t=z;bool listed=false,done=false;",
55
78
  "try{",
@@ -69,20 +92,21 @@ export const OCX_JOB_SOURCE = [
69
92
  ].join("\n");
70
93
 
71
94
  /**
72
- * The helper travels deflated so the whole command fits cmd.exe's line; PowerShell inflates it and
73
- * hands the text to Add-Type. It is never evaluated as PowerShell.
95
+ * The helper reaches Add-Type as a quoted literal inside the packed script; it is never evaluated
96
+ * as PowerShell.
74
97
  */
75
- const OCX_JOB_PACKED = deflateRawSync(Buffer.from(OCX_JOB_SOURCE, "utf8"), { level: 9 }).toString("base64");
76
-
77
98
  const NATIVE_PROCESS = String.raw`$ErrorActionPreference='Stop'
78
99
  function Fail{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126}
79
- try{Add-Type ([IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new([Convert]::FromBase64String('` + OCX_JOB_PACKED + String.raw`')),[IO.Compression.CompressionMode]::Decompress)).ReadToEnd())}catch{Fail}
100
+ try{Add-Type '` + OCX_JOB_SOURCE.replaceAll("'", "''") + String.raw`'}catch{Fail}
80
101
  function Quote-Native([string]$v){'"'+[regex]::Replace([regex]::Replace($v,'(\\*)"','$1$1\"'),'(\\+)$','$1$1')+'"'}
81
102
  function Invoke-Native([string]$e,[string[]]$a){try{$c=[OcxJob]::Run($e,((@($e)+$a|%{Quote-Native $_}) -join ' '))}catch{Fail};exit $c}
82
103
  `;
83
104
 
84
105
  /** The packed helper a script carries, inflated; for tests that check the transport. */
85
106
  export function windowsScriptHelperSource(script: string): string | undefined {
107
+ script = unpackPowerShell(script);
108
+ const source = /try\{Add-Type '([\s\S]*?)'\}catch\{Fail\}/.exec(script);
109
+ if (source) return source[1]!.replaceAll("''", "'");
86
110
  const match = /FromBase64String\('([A-Za-z0-9+/=]+)'\)\),\[IO\.Compression\.CompressionMode\]::Decompress\)\)\.ReadToEnd\(\)/.exec(script);
87
111
  if (!match) return undefined;
88
112
  return inflateRawSync(Buffer.from(match[1]!, "base64")).toString("utf8");
@@ -103,6 +127,7 @@ function dataLine(value: { executable?: string; args: readonly string[] }): stri
103
127
  * undefined for any other script. Test fixtures decode with this, never with their own pattern.
104
128
  */
105
129
  export function windowsScriptData(script: string): { executable?: string; args: string[] } | undefined {
130
+ script = unpackPowerShell(script);
106
131
  const start = script.indexOf(DATA_OPEN);
107
132
  const end = start < 0 ? -1 : script.indexOf(DATA_CLOSE, start + DATA_OPEN.length);
108
133
  if (end < 0) return undefined;
@@ -112,23 +137,40 @@ export function windowsScriptData(script: string): { executable?: string; args:
112
137
  }
113
138
 
114
139
  export function windowsNativeArgv(executable: string, args: readonly string[]): string[] {
115
- return powershellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n");
140
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n");
116
141
  }
117
142
 
118
143
  /**
119
144
  * Desktop first, then the GOAT-managed current junction, then legacy and PATH candidates. Each
120
145
  * must answer --version within ten seconds; only the selected one runs the real command.
121
146
  */
122
- export function windowsOcxArgv(args: readonly string[]): string[] {
123
- return powershellArgv(NATIVE_PROCESS + dataLine({ args }) + String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe")
147
+ const OCX_CANDIDATES = String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe")
124
148
  if($env:LOCALAPPDATA){$c+="$env:LOCALAPPDATA\Programs\OpenCodex\ocx.exe"}
125
149
  if($env:ProgramFiles){$c+="$env:ProgramFiles\OpenCodex\ocx.exe"}
126
150
  $c+=@((Get-Command ocx.exe -Type Application -EA 0).Source)
151
+ `;
152
+ export function windowsOcxArgv(args: readonly string[]): string[] {
153
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + String.raw`
127
154
  foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){Invoke-Native $x @($d.args)}}
128
155
  [Console]::Error.WriteLine('No runnable ocx.exe found; install the Windows standalone archive.');exit 127
129
156
  `);
130
157
  }
131
158
 
159
+ export function windowsPinnedSyncArgv(linkId: string): string[] {
160
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json"] }) + OCX_CANDIDATES + String.raw`
161
+ foreach($x in ($c|select -Unique)){
162
+ if(![IO.File]::Exists($x)){continue};$v=[OcxJob]::V($x);if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
163
+ $m=[regex]::Match($v,'^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$')
164
+ $bad=(!$m.Success -or $v.Length -gt 128);if(!$bad -and $m.Groups[4].Success){foreach($p in $m.Groups[4].Value.Split('.')){if(!$p -or ($p -match '^\d+$' -and $p.Length -gt 1 -and $p[0] -eq '0')){$bad=$true}}}
165
+ if($bad){[Console]::Error.WriteLine('ocx-fanout:child-ocx-version-unknown');exit 121}
166
+ $a=@($m.Groups[1].Value,$m.Groups[2].Value,$m.Groups[3].Value);$b=@('2','93','0');$cmp=0
167
+ for($i=0;$i -lt 3;$i++){if($a[$i].Length -ne $b[$i].Length){$cmp=$a[$i].Length-$b[$i].Length;break};$cmp=[string]::CompareOrdinal($a[$i],$b[$i]);if($cmp -ne 0){break}}
168
+ if($cmp -lt 0 -or ($cmp -eq 0 -and $m.Groups[4].Success)){[Console]::Error.WriteLine('ocx-fanout:child-ocx-lacks-expect-link');exit 121}
169
+ [Console]::Error.WriteLine('ocx-fanout:selected:'+$v);[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args)
170
+ };exit 127
171
+ `);
172
+ }
173
+
132
174
  /** Credential-free loopback probe of the Child; no proxy, no redirect, bounded body and deadline. */
133
175
  export function windowsChildHttpArgv(port: number, path: "healthz" | "v1/catalog", timeoutMs: number): string[] {
134
176
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid Child port");
@@ -19,7 +19,7 @@
19
19
  */
20
20
 
21
21
  import { isAbsolute } from "node:path";
22
- import { POWERSHELL_ENCODED_MAX, windowsOcxArgv } from "./remote-windows";
22
+ import { POWERSHELL_ENCODED_MAX, windowsOcxArgv, windowsPinnedSyncArgv } from "./remote-windows";
23
23
 
24
24
  export type TunnelDirection = "R" | "L";
25
25
 
@@ -146,6 +146,16 @@ export const REMOTE_PLATFORM_UNSUPPORTED = 125;
146
146
  * ocx as `"$@"` without another round of parsing. Desktop binaries precede PATH candidates;
147
147
  * each candidate must run --version successfully. A missing runnable ocx exits 127.
148
148
  */
149
+ const REMOTE_OCX_CANDIDATES = `for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
150
+ try_ocx "$candidate" "$@"
151
+ done
152
+ remaining=$PATH
153
+ while :; do
154
+ directory=\${remaining%%:*}
155
+ try_ocx "\${directory:-.}/ocx" "$@"
156
+ case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
157
+ done`;
158
+
149
159
  export const REMOTE_OCX_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
150
160
  case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac
151
161
  try_ocx() {
@@ -155,15 +165,7 @@ try_ocx() {
155
165
  exec "$executable" "$@"
156
166
  fi
157
167
  }
158
- for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
159
- try_ocx "$candidate" "$@"
160
- done
161
- remaining=$PATH
162
- while :; do
163
- directory=\${remaining%%:*}
164
- try_ocx "\${directory:-.}/ocx" "$@"
165
- case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
166
- done
168
+ ${REMOTE_OCX_CANDIDATES}
167
169
  exit ${REMOTE_COMMAND_NOT_FOUND}`;
168
170
 
169
171
  export function remoteOcxArgv(args: readonly string[], platform: "posix" | "windows" = "posix"): string[] {
@@ -238,3 +240,54 @@ export function quoteRemote(argv: readonly string[]): string {
238
240
  return `'${arg.replaceAll("'", `'"'"'`)}'`;
239
241
  }).join(" ");
240
242
  }
243
+
244
+ const REMOTE_PINNED_SYNC_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
245
+ case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac
246
+ umask 077
247
+ dir=$(mktemp -d "\${TMPDIR:-/tmp}/ocx-fanout.XXXXXXXX") || exit 127
248
+ tmp=$dir/version; ready=$dir/ready
249
+ trap 'rm -rf "$dir"' EXIT HUP INT TERM
250
+ try_ocx() {
251
+ c=$1; shift
252
+ [ -x "$c" ] || return
253
+ ( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null & vp=$!
254
+ ( sleep 10 & timer=$!; trap 'kill "$timer" 2>/dev/null; wait "$timer" 2>/dev/null; exit' TERM HUP INT; : > "$ready"; wait "$timer" 2>/dev/null; kill -9 "$vp" 2>/dev/null ) >/dev/null 2>&1 & watchdog=$!
255
+ while [ ! -f "$ready" ]; do kill -0 "$watchdog" 2>/dev/null || break; sleep 0.01 >/dev/null 2>&1; done
256
+ { wait "$vp"; status=$?; } 2>/dev/null
257
+ kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null; rm -f "$ready"
258
+ [ "$status" -eq 0 ] || return
259
+ bytes=$(wc -c < "$tmp" 2>/dev/null) || return
260
+ [ "$bytes" -le 256 ] 2>/dev/null || return
261
+ version=$(cat "$tmp"); version=\${version#opencodex }
262
+ printf '%s\\n' "$version" | awk '
263
+ function idlist(s,pre, n,a,i) {
264
+ n=split(s,a,/\\./); if (!n) return 0;
265
+ for(i=1;i<=n;i++) if(a[i]=="" || a[i] !~ /^[0-9A-Za-z-]+$/ || (pre && a[i] ~ /^[0-9]+$/ && length(a[i])>1 && substr(a[i],1,1)=="0")) return 0;
266
+ return 1
267
+ }
268
+ function cmp(a,b) { if(length(a)!=length(b)) return length(a)>length(b)?1:-1; return ("x" a)==("x" b)?0:(("x" a)>("x" b)?1:-1) }
269
+ NR==1 {
270
+ v=$0; if(length(v)>128) { result=2; next }
271
+ plus=index(v,"+"); if(plus) { build=substr(v,plus+1); v=substr(v,1,plus-1); if(!idlist(build,0)) {result=2; next} }
272
+ dash=index(v,"-"); if(dash) { pre=substr(v,dash+1); v=substr(v,1,dash-1); if(!idlist(pre,1)) {result=2; next} }
273
+ if(split(v,a,/\\./)!=3) { result=2; next }
274
+ for(i=1;i<=3;i++) if(a[i] !~ /^(0|[1-9][0-9]*)$/) { result=2; next }
275
+ c=cmp(a[1],"2"); if(!c)c=cmp(a[2],"93"); if(!c)c=cmp(a[3],"0"); if(c<0 || (!c && dash))result=1
276
+ }
277
+ NR>1 {result=2}
278
+ END {exit result}
279
+ ' 2>/dev/null
280
+ status=$?
281
+ if [ "$status" -eq 1 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-lacks-expect-link' >&2; exit 121; fi
282
+ if [ "$status" -ne 0 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-version-unknown' >&2; exit 121; fi
283
+ rm -rf "$dir"; trap - EXIT HUP INT TERM
284
+ printf 'ocx-fanout:selected:%s\\n' "$version" >&2
285
+ printf '%s\\n' 'ocx-fanout:stdout-begin'
286
+ exec "$c" sync --expect-link "$1" --json
287
+ }
288
+ ${REMOTE_OCX_CANDIDATES}
289
+ exit ${REMOTE_COMMAND_NOT_FOUND}`;
290
+
291
+ export function remotePinnedSyncArgv(linkId: string, platform: "posix" | "windows" = "posix"): string[] {
292
+ return platform === "windows" ? windowsPinnedSyncArgv(linkId) : ["sh", "-c", REMOTE_PINNED_SYNC_SCRIPT, "ocx", linkId];
293
+ }
@@ -1,3 +1,4 @@
1
+ import { clientFacingModelText, type ClientFacingModelLabel } from "../lib/error-destination";
1
2
  import { isBuiltinAnthropicInstanceRow } from "../providers/anthropic-instance";
2
3
  /**
3
4
  * Generic OAuth multi-account 429 failover (#2568).
@@ -293,14 +294,14 @@ export type AntigravityModelRoute =
293
294
  const KEEP_ANTIGRAVITY_ROUTE: AntigravityModelRoute = { kind: "keep" };
294
295
 
295
296
  /** Client-facing refusal when no usable account's discovery lists the model. Mirrored in docs-site. */
296
- export function antigravityModelUnlistedMessage(model: string): string {
297
- return `No usable Google Antigravity account lists the model "${model}" in its model discovery. `
297
+ export function antigravityModelUnlistedMessage(model?: ClientFacingModelLabel): string {
298
+ return `No usable Google Antigravity account lists the model "${clientFacingModelText(model)}" in its model discovery. `
298
299
  + "Choose a model your accounts list, or add an account that has access to it.";
299
300
  }
300
301
 
301
302
  /** Client-facing refusal when the chosen account omits the model but a sibling may serve it. */
302
- export function antigravitySelectedAccountUnlistedMessage(model: string): string {
303
- return `The selected Google Antigravity account does not list the model "${model}" in its model discovery. `
303
+ export function antigravitySelectedAccountUnlistedMessage(model?: ClientFacingModelLabel): string {
304
+ return `The selected Google Antigravity account does not list the model "${clientFacingModelText(model)}" in its model discovery. `
304
305
  + "Select an account that lists it, or enable oauthAccountFailover so OpenCodex can choose one.";
305
306
  }
306
307
 
@@ -325,6 +326,7 @@ export function routeAntigravityModel(
325
326
  plannedAccountId: string | null | undefined,
326
327
  model: string | null | undefined,
327
328
  now = Date.now(),
329
+ clientModel?: ClientFacingModelLabel,
328
330
  ): AntigravityModelRoute {
329
331
  if (providerName !== "google-antigravity" || !model || !plannedAccountId
330
332
  || accountListsModel(providerName, plannedAccountId, model) !== false) return KEEP_ANTIGRAVITY_ROUTE;
@@ -332,9 +334,9 @@ export function routeAntigravityModel(
332
334
  .filter(account => account.id !== plannedAccountId && account.paused !== true && account.needsReauth !== true)
333
335
  .map(account => account.id)
334
336
  .filter(id => accountListsModel(providerName, id, model) !== false);
335
- if (serving.length === 0) return { kind: "refuse", message: antigravityModelUnlistedMessage(model) };
337
+ if (serving.length === 0) return { kind: "refuse", message: antigravityModelUnlistedMessage(clientModel) };
336
338
  if (!isProactivePreferenceEnabled(config, providerName, now)) {
337
- return { kind: "refuse", message: antigravitySelectedAccountUnlistedMessage(model) };
339
+ return { kind: "refuse", message: antigravitySelectedAccountUnlistedMessage(clientModel) };
338
340
  }
339
341
  const ready = new Set(eligibleFailoverAccounts(providerName, now, classifyModelFamilyForQuota(providerName, model)));
340
342
  const rank = (id: string) => (ready.has(id) ? 0 : 2) + (accountListsModel(providerName, id, model) === true ? 0 : 1);
@@ -372,19 +374,19 @@ export function rotateAntigravityAccountOnModelNotFound(
372
374
  * Client-facing refusal when failover is on and a sibling may serve the model, but the request
373
375
  * still resolved to an omitting account (the sibling could not be resolved or admitted).
374
376
  */
375
- export function antigravityReplacementUnavailableMessage(model: string): string {
376
- return `The selected Google Antigravity account does not list the model "${model}" in its model discovery, `
377
+ export function antigravityReplacementUnavailableMessage(model?: ClientFacingModelLabel): string {
378
+ return `The selected Google Antigravity account does not list the model "${clientFacingModelText(model)}" in its model discovery, `
377
379
  + "and no account that may serve it could be used for this request. Retry the request.";
378
380
  }
379
381
 
380
382
  /** The refusal for an account that already resolved, or null when it may serve the model. */
381
383
  export function antigravityModelRefusal(
382
- config: OcxConfig, providerName: string, accountId: string, model: string | null | undefined, now = Date.now(),
384
+ config: OcxConfig, providerName: string, accountId: string, model: string | null | undefined, now = Date.now(), clientModel?: ClientFacingModelLabel,
383
385
  ): string | null {
384
- const verdict = routeAntigravityModel(config, providerName, accountId, model, now);
386
+ const verdict = routeAntigravityModel(config, providerName, accountId, model, now, clientModel);
385
387
  if (verdict.kind === "keep") return null;
386
388
  // A reroute verdict exists only with failover on, so advising to enable it would be wrong.
387
- return verdict.kind === "refuse" ? verdict.message : antigravityReplacementUnavailableMessage(model!);
389
+ return verdict.kind === "refuse" ? verdict.message : antigravityReplacementUnavailableMessage(clientModel);
388
390
  }
389
391
 
390
392
  function kiroModelListingHasRoom(config: OcxConfig, accountId: string, model: string): boolean {
@@ -144,7 +144,7 @@ export type OAuthActiveTokenObservation =
144
144
 
145
145
  const MAX_OAUTH_TOKEN_REFRESH_FLIGHTS = 32;
146
146
  const OAUTH_TOKEN_REFRESH_FLIGHT_STALE_MS = 120_000;
147
- interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean }
147
+ interface OAuthTokenRefreshFlight extends OAuthRefreshFlightEvidence { promise: Promise<OAuthAccessSnapshot>; startedAt: number; abort: AbortController; settled?: boolean; retirementDeferredLogged?: boolean; requireUsable?: boolean }
148
148
  const tokenRefreshes = new Map<string, OAuthTokenRefreshFlight>();
149
149
  export class OAuthTokenRefreshBusyError extends Error {
150
150
  readonly code = "OAUTH_TOKEN_REFRESH_BUSY";
@@ -156,6 +156,8 @@ export class OAuthTokenRefreshStaleError extends Error {
156
156
  readonly retryable = true;
157
157
  constructor() { super("OAuth token refresh owner became stale"); this.name = "OAuthTokenRefreshStaleError"; }
158
158
  }
159
+ /** Known pre-dispatch cancellation; independent waiters may acquire a new owner. */
160
+ class OAuthDiscoveryRefreshCancelledError extends OAuthTokenRefreshStaleError {}
159
161
 
160
162
  /** Focused owner-identity tests only. Synthetic owners retain no account data. */
161
163
  export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string; startedAt?: number; flightId?: string; dispatched?: boolean }>): {
@@ -187,9 +189,9 @@ export function seedOAuthTokenRefreshFlightsForTests(rows: Array<{ key: string;
187
189
  }
188
190
  const XAI_PERMANENT_FAILURE_TTL_MS=30_000;
189
191
  const permanentRefreshFailures=new Map<string,number>();
190
- interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
192
+ interface XaiRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; requireUsableAccount?: boolean }
191
193
  interface AnthropicRefreshDeps { resolveIdentity?: AnthropicIdentityResolver; intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; now?:()=>number; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; flight?: OAuthRefreshFlightEvidence; replacedStaleFlight?: OAuthRefreshFlightEvidence }
192
- interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal }
194
+ interface GenericRefreshDeps { intentLock?:ReturnType<typeof createOAuthRefreshIntentLock>; afterPrePersistRead?:()=>void|Promise<void>; signal?: AbortSignal; authorityCurrent?: () => boolean; requireUsableAccount?: boolean }
193
195
  function verdictKey(p:string,a:string,c:OAuthCredentials){return `${p}\0${a}\0${credentialGeneration(c)}`;}
194
196
  function cached(p:string,a:string,c:OAuthCredentials,now:()=>number){const k=verdictKey(p,a,c),u=permanentRefreshFailures.get(k);if(u===undefined)return false;if(u<=now()){permanentRefreshFailures.delete(k);return false;}return true;}
195
197
  export function sweepExpiredXaiPermanentFailureVerdicts(now=Date.now()):number{let removed=0;for(const[key,until]of permanentRefreshFailures){if(until>now)continue;permanentRefreshFailures.delete(key);removed+=1;}return removed;}
@@ -448,70 +450,8 @@ export function getOAuthCredentialApiBaseUrl(provider: string): string | undefin
448
450
  export function listOAuthProviders(): string[] {
449
451
  return Object.keys(OAUTH_PROVIDERS).filter(isPublicOAuthProvider);
450
452
  }
451
-
452
- export class UnsupportedOAuthProviderError extends Error {
453
- constructor(provider: string) {
454
- super(`Unsupported OAuth provider in config: ${provider}`);
455
- this.name = "UnsupportedOAuthProviderError";
456
- }
457
- }
458
-
459
- export class OAuthLoginRequiredError extends Error {
460
- readonly provider: string;
461
-
462
- constructor(provider: string) {
463
- super(`Not logged in to ${provider}. Run: ocx login ${provider}`);
464
- this.name = "OAuthLoginRequiredError";
465
- this.provider = provider;
466
- }
467
- }
468
-
469
- /** An operator-paused account is temporarily unavailable, not an invalid login. */
470
- export class OAuthAccountPausedError extends Error {
471
- constructor() {
472
- super("OAuth account is paused. Resume it in account settings and retry.");
473
- this.name = "OAuthAccountPausedError";
474
- }
475
- }
476
-
477
- export class OAuthProviderPublicationError extends Error {
478
- constructor(provider?: string, credentialWritten = true) {
479
- super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
480
- : credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
481
- : "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
482
- this.name = "OAuthProviderPublicationError";
483
- }
484
- }
485
-
486
- /** A local configuration conflict found before any credential is written; its text is fixed. */
487
- export class OAuthProviderNamespaceCollisionError extends Error {
488
- constructor(message: string) {
489
- super(message);
490
- this.name = "OAuthProviderNamespaceCollisionError";
491
- }
492
- }
493
-
494
- export class OAuthReauthIdentityMismatchError extends Error {
495
- constructor() {
496
- super("Signed-in account does not match the selected account. Sign in with the same account.");
497
- this.name = "OAuthReauthIdentityMismatchError";
498
- }
499
- }
500
-
501
- export class OAuthReauthIdentityUnverifiedError extends Error {
502
- constructor() {
503
- super("Could not verify signed-in account identity for reauth.");
504
- this.name = "OAuthReauthIdentityUnverifiedError";
505
- }
506
- }
507
-
508
- class OAuthLoginSupersededError extends Error {
509
- constructor() {
510
- super("OAuth login was superseded before credential persistence");
511
- this.name = "OAuthLoginSupersededError";
512
- }
513
- }
514
-
453
+ import { OAuthAccountUnusableError, OAuthLoginSupersededError, OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
454
+ export { OAuthAccountPausedError, OAuthLoginRequiredError, OAuthProviderNamespaceCollisionError, OAuthProviderPublicationError, OAuthReauthIdentityMismatchError, OAuthReauthIdentityUnverifiedError, UnsupportedOAuthProviderError } from "./oauth-errors";
515
455
  /** Project arbitrary OAuth failures onto the small, stable public error vocabulary. */
516
456
  export function publicOAuthAuthenticationErrorMessage(error: unknown): string {
517
457
  if (error instanceof AntigravityProjectDiscoveryError) return error.publicMessage;
@@ -632,6 +572,8 @@ async function resolveAccessSnapshotForAccount(
632
572
  rejectedGeneration?: string,
633
573
  requireUsableAccount = false,
634
574
  oauthProvider = provider,
575
+ authorityCurrent?: () => boolean,
576
+ retryCancelledDiscovery = true,
635
577
  ): Promise<OAuthAccessSnapshot> {
636
578
  const def = OAUTH_PROVIDERS[oauthProvider];
637
579
  if (!def) throw new UnsupportedOAuthProviderError(oauthProvider);
@@ -661,6 +603,7 @@ async function resolveAccessSnapshotForAccount(
661
603
  // no replacement starts until the old consumers have actually released enough capacity.
662
604
  const waiter = tokenRefreshWaiters.tryAcquire();
663
605
  if (!waiter) throw new OAuthTokenRefreshBusyError();
606
+ let unrestrictedRetry = false;
664
607
  try {
665
608
  if (existing && replacedStaleFlight) {
666
609
  // A replacement would wait for this owner's lock anyway. Keep its registry slot
@@ -675,7 +618,10 @@ async function resolveAccessSnapshotForAccount(
675
618
  }
676
619
  if (existing) {
677
620
  logOAuthEvent("OAuth refresh joined existing operation", { provider, accountId });
678
- return await existing.promise;
621
+ const joined = await existing.promise;
622
+ // The owner may not have required usability; a mark that landed meanwhile still rejects us.
623
+ if (requireUsableAccount && getAccountCredentialWithStatus(provider, accountId)?.needsReauth) throw new OAuthAccountUnusableError(provider);
624
+ return joined;
679
625
  }
680
626
  if (tokenRefreshes.size >= MAX_OAUTH_TOKEN_REFRESH_FLIGHTS) {
681
627
  for (const [staleKey, stale] of tokenRefreshes) {
@@ -691,12 +637,14 @@ async function resolveAccessSnapshotForAccount(
691
637
  abort,
692
638
  flightId: randomUUID(),
693
639
  dispatched: false,
640
+ requireUsable: requireUsableAccount,
694
641
  };
695
642
  const refresh = (async (): Promise<OAuthAccessSnapshot> => {
696
- const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight);
643
+ const accessToken = await refreshAndPersistAccessToken(provider, accountId, def, cred, abort.signal, flight, replacedStaleFlight, authorityCurrent, requireUsableAccount);
697
644
  const persistedRow = getAccountCredentialWithStatus(provider, accountId);
698
645
  if (!persistedRow) throw new OAuthLoginRequiredError(provider);
699
646
  if (persistedRow.paused === true) throw new OAuthAccountPausedError();
647
+ if (requireUsableAccount && persistedRow.needsReauth) throw new OAuthAccountUnusableError(provider);
700
648
  const persisted = persistedRow.credential;
701
649
  if (persisted.access !== accessToken) {
702
650
  throw new Error(`OAuth refresh persisted an unexpected access token for ${provider}`);
@@ -715,7 +663,13 @@ async function resolveAccessSnapshotForAccount(
715
663
  flight.promise = refresh;
716
664
  tokenRefreshes.set(key, flight);
717
665
  return await refresh;
666
+ } catch (error) {
667
+ // An unrestricted caller that joined a usable-only owner is not bound by that owner's rejection.
668
+ if (!requireUsableAccount && error instanceof OAuthAccountUnusableError) unrestrictedRetry = true;
669
+ else if (authorityCurrent || !retryCancelledDiscovery || !(error instanceof OAuthDiscoveryRefreshCancelledError)) throw error;
718
670
  } finally { waiter.release(); }
671
+ if (unrestrictedRetry) return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, false, oauthProvider, authorityCurrent, retryCancelledDiscovery);
672
+ return resolveAccessSnapshotForAccount(provider, accountId, rejectedGeneration, requireUsableAccount, oauthProvider, undefined, false);
719
673
  }
720
674
 
721
675
  export async function getValidAccessTokenSnapshot(
@@ -773,9 +727,9 @@ export async function getValidAccessTokenForAccount(provider: string, accountId:
773
727
  export async function getValidAccessSnapshotForAccount(
774
728
  provider: string,
775
729
  accountId: string,
776
- opts: { requireUsableAccount?: boolean } = {},
730
+ opts: { requireUsableAccount?: boolean; authorityCurrent?: () => boolean } = {},
777
731
  ): Promise<OAuthAccessSnapshot> {
778
- return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true);
732
+ return resolveAccessSnapshotForAccount(provider, accountId, undefined, opts.requireUsableAccount === true, provider, opts.authorityCurrent);
779
733
  }
780
734
 
781
735
  /** Terminal refresh failures (revoked/rotated-away grants) — retrying cannot succeed. */
@@ -839,7 +793,7 @@ function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCrede
839
793
  ...(fresh.kiro === undefined && previous.kiro ? { kiro: previous.kiro } : {}),
840
794
  };
841
795
  }
842
- export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
796
+ export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise<string>{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}}
843
797
 
844
798
 
845
799
  /**
@@ -1030,6 +984,9 @@ export async function refreshGenericAccountWithLock(
1030
984
  const row = getAccountCredentialWithStatus(provider, accountId);
1031
985
  if (!row) throw new OAuthLoginRequiredError(provider);
1032
986
  if (row.paused) throw new OAuthAccountPausedError();
987
+ // A usable-account caller rechecks needsReauth here: a mark committed while it waited must
988
+ // stop the refresh before the stored refresh token is sent.
989
+ if (deps.requireUsableAccount && row.needsReauth) throw new OAuthAccountUnusableError(provider);
1033
990
  const stored = row.credential;
1034
991
  if (
1035
992
  credentialGeneration(stored) !== credentialGeneration(callerCredential)
@@ -1040,11 +997,14 @@ export async function refreshGenericAccountWithLock(
1040
997
  }
1041
998
  const generation = credentialGeneration(stored);
1042
999
  try {
1000
+ if (deps.authorityCurrent && !deps.authorityCurrent()) throw new OAuthDiscoveryRefreshCancelledError();
1043
1001
  const refreshed = await def.refresh(stored.refresh, deps.signal, stored, accountId);
1044
1002
  const fresh = merged(refreshed, stored);
1045
1003
  const outcome = await mergeAccountCredential(provider, accountId, fresh, {
1046
1004
  expectedGeneration: generation,
1047
1005
  afterPrePersistRead: deps.afterPrePersistRead,
1006
+ // A mark that landed after this flight read the row is newer than the refresh: keep it.
1007
+ keepReauthMarkedAfterDispatch: !row.needsReauth,
1048
1008
  ...(provider === "devin" ? { assertOwnership: (store: AuthStore) => {
1049
1009
  if (store[provider]?.accounts.find(row => row.id === accountId)?.paused) throw new OAuthAccountPausedError();
1050
1010
  assertDevinCliAdoptionOwnership(store, provider, accountId, refreshed);
@@ -1138,10 +1098,12 @@ async function refreshAndPersistAccessToken(
1138
1098
  signal?: AbortSignal,
1139
1099
  flight?: OAuthRefreshFlightEvidence,
1140
1100
  replacedStaleFlight?: OAuthRefreshFlightEvidence,
1101
+ authorityCurrent?: () => boolean,
1102
+ requireUsableAccount = false,
1141
1103
  ): Promise<string> {
1142
- if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal });
1104
+ if (provider === "xai") return refreshXaiAccountWithLock(provider, accountId, def, cred, { signal, requireUsableAccount });
1143
1105
  if (isAnthropicOAuthInstance(provider)) return refreshAnthropicAccountWithLock(provider, accountId, def, cred, { signal, flight, replacedStaleFlight });
1144
- return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal });
1106
+ return refreshGenericAccountWithLock(provider, accountId, def, cred, { signal, authorityCurrent, requireUsableAccount });
1145
1107
  }
1146
1108
 
1147
1109
  /** Resolve discovery credentials only for the caller-owned configured OAuth row. */
@@ -0,0 +1,67 @@
1
+ import { errorDestinationText, providerErrorDestinationLabel } from "../lib/error-destination";
2
+
3
+ export class UnsupportedOAuthProviderError extends Error {
4
+ constructor(provider: string) {
5
+ super(`Unsupported OAuth provider in config: ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
6
+ this.name = "UnsupportedOAuthProviderError";
7
+ }
8
+ }
9
+
10
+ export class OAuthLoginRequiredError extends Error {
11
+ readonly provider: string;
12
+
13
+ constructor(provider: string) {
14
+ super(`Not logged in to ${errorDestinationText(providerErrorDestinationLabel(provider))}. Run: ocx login ${errorDestinationText(providerErrorDestinationLabel(provider))}`);
15
+ this.name = "OAuthLoginRequiredError";
16
+ this.provider = provider;
17
+ }
18
+ }
19
+
20
+ /** A usable-account caller found needsReauth under the refresh lock; unrestricted joiners retry alone. */
21
+ export class OAuthAccountUnusableError extends OAuthLoginRequiredError {}
22
+
23
+ /** An operator-paused account is temporarily unavailable, not an invalid login. */
24
+ export class OAuthAccountPausedError extends Error {
25
+ constructor() {
26
+ super("OAuth account is paused. Resume it in account settings and retry.");
27
+ this.name = "OAuthAccountPausedError";
28
+ }
29
+ }
30
+
31
+ export class OAuthProviderPublicationError extends Error {
32
+ constructor(provider?: string, credentialWritten = true) {
33
+ super(provider !== "anthropic2" ? "OAuth credential was saved, but the provider entry was not written. Resolve the account namespace collision, then retry login."
34
+ : credentialWritten ? "Anthropic Pool 2 credential was saved as an orphan auth row, but the provider entry was not written. Repair the persisted config or resolve the provider/account namespace collision, then retry login."
35
+ : "Anthropic Pool 2 login did not start because the config file is missing or could not be written; no credential was saved. Repair the persisted config, then retry login.");
36
+ this.name = "OAuthProviderPublicationError";
37
+ }
38
+ }
39
+
40
+ /** A local configuration conflict found before any credential is written; its text is fixed. */
41
+ export class OAuthProviderNamespaceCollisionError extends Error {
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "OAuthProviderNamespaceCollisionError";
45
+ }
46
+ }
47
+
48
+ export class OAuthReauthIdentityMismatchError extends Error {
49
+ constructor() {
50
+ super("Signed-in account does not match the selected account. Sign in with the same account.");
51
+ this.name = "OAuthReauthIdentityMismatchError";
52
+ }
53
+ }
54
+
55
+ export class OAuthReauthIdentityUnverifiedError extends Error {
56
+ constructor() {
57
+ super("Could not verify signed-in account identity for reauth.");
58
+ this.name = "OAuthReauthIdentityUnverifiedError";
59
+ }
60
+ }
61
+
62
+ export class OAuthLoginSupersededError extends Error {
63
+ constructor() {
64
+ super("OAuth login was superseded before credential persistence");
65
+ this.name = "OAuthLoginSupersededError";
66
+ }
67
+ }
@@ -1610,7 +1610,7 @@ export async function markAccountNeedsReauth(
1610
1610
  }, [provider, accountId]);
1611
1611
  }
1612
1612
 
1613
- export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
1613
+ export async function mergeAccountCredential(provider:string,accountId:string,credential:OAuthCredentials,opts:{expectedGeneration?:string;afterPrePersistRead?:()=>void|Promise<void>;assertOwnership?: (store: AuthStore) => void;keepReauthMarkedAfterDispatch?:boolean}={}):Promise<{superseded:false}|{superseded:true;stored:OAuthCredentials}>{const safe=normalizeCredential(credential);if(!safe)throw new Error("Refusing to persist invalid OAuth credential");if(isAnthropicInstanceId(provider))assertAnthropicCredentialSource(provider,safe);return await mutateStore(async store=>{await opts.afterPrePersistRead?.();const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account)throw new Error(`OAuth account disappeared before persist: ${provider}`);if(opts.expectedGeneration!==undefined&&credentialGeneration(account.credential)!==opts.expectedGeneration)return{superseded:true,stored:account.credential};opts.assertOwnership?.(store);account.credential=safe;delete account.refreshAttentionGeneration;if(account.needsReauthReason!=="verify_account"&&!(opts.keepReauthMarkedAfterDispatch&&account.needsReauth)){delete account.needsReauth;delete account.needsReauthReason;}return{superseded:false};},[provider,accountId,safe,opts.expectedGeneration]);}
1614
1614
  // A late refresh failure must not change an operator-paused account's health. Check under
1615
1615
  // the mutation lock, not before awaiting it, so a concurrent pause cannot be overwritten.
1616
1616
  export async function markAccountNeedsReauthIfGeneration(provider:string,accountId:string,generation:string,writerGeneration=captureConfigGeneration(),reason?:"verify_account",isCurrent?:(store:AuthStore)=>boolean):Promise<boolean>{const key=oauthAccountKey(provider,accountId);if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;return await mutateStore(store=>{const account=store[provider]?.accounts.find(x=>x.id===accountId);if(!account?.credential||account.paused||credentialGeneration(account.credential)!==generation)return false;if(writerGeneration<lastReconciledGeneration&&!liveOAuthAccountKeys.has(key))return false;if(isCurrent&&!isCurrent(store))return false;account.needsReauth=true;if(reason==="verify_account")account.needsReauthReason=reason;return true;},[provider,accountId,generation]);}