@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.1

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/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -166,7 +166,7 @@ export function carryReplayRefusal<T extends Response>(source: Response, rewrapp
166
166
  }
167
167
 
168
168
  // 1 initial + 2 retries: the pool may hold more than one stale socket.
169
- const RESET_RETRY_MAX_ATTEMPTS = 3;
169
+ export const RESET_RETRY_MAX_ATTEMPTS = 3;
170
170
  const RESET_RETRY_BASE_DELAY_MS = 150;
171
171
  const RESET_RETRY_MAX_DELAY_MS = 1_000;
172
172
 
@@ -552,6 +552,12 @@ export interface ResetRetryOptions {
552
552
  * `attempts`, exactly like every other send this leg makes.
553
553
  */
554
554
  claimAmbiguousResend?: () => boolean;
555
+ /**
556
+ * Opt-in offline wait (#7958): asked once a send failed before reaching the origin; true means
557
+ * the destination is reachable again and one resend may follow inside `attempts`. See
558
+ * `createOfflineResendWait` in offline-resend.ts, which owns the single-use and pre-connect rules.
559
+ */
560
+ offlineWait?: (error: unknown, signal?: AbortSignal) => Promise<boolean>;
555
561
  }
556
562
 
557
563
  export interface TransientRetryOptions extends ResetRetryOptions {
@@ -568,7 +574,8 @@ export interface TransientRetryOptions extends ResetRetryOptions {
568
574
  retryAfterCeilingMs?: number;
569
575
  }
570
576
 
571
- export type UpstreamSendRecovery = "connection-reset" | "transient-5xx";
577
+ /** `offline-resend` is the single send after an offline wait (#7958), never a reset retry. */
578
+ export type UpstreamSendRecovery = "connection-reset" | "transient-5xx" | "offline-resend";
572
579
  type ReplayableFetch = (recovery?: UpstreamSendRecovery) => Promise<Response>;
573
580
 
574
581
  /**
@@ -604,20 +611,25 @@ export class UpstreamRetryEvidenceError extends Error {
604
611
  }
605
612
 
606
613
  /**
607
- * Opt out of Bun's keep-alive pool after a connection-reset retry.
614
+ * Opt out of Bun's keep-alive pool after a connection-reset retry or an offline resend.
608
615
  *
609
616
  * Prefer the Bun fetch extension `keepalive: false` (transport-level) over
610
617
  * relying on the hop-by-hop `Connection: close` header alone — Bun has ignored
611
618
  * that header in past releases (oven-sh/bun#20492), so a header-only retry can
612
619
  * still reuse the same half-closed pooled socket. Still set Connection: close
613
620
  * as a belt-and-suspenders signal for intermediaries that honor it.
621
+ *
622
+ * An offline resend (#7958) follows a DNS outage, typically a sleep or a network change, so any
623
+ * socket still pooled for that origin or proxy was opened on the network that went away. Reusing
624
+ * one fails after the body may have left, which turns a provably unsent request into an ambiguous
625
+ * reset; a fresh connection is what the resend needs anyway.
614
626
  */
615
627
  export function applyUpstreamRecoveryInit<T extends RequestInit>(
616
628
  init: T,
617
629
  recovery?: UpstreamSendRecovery,
618
630
  ): T & { headers: Headers } {
619
631
  const headers = new Headers(init.headers);
620
- if (recovery !== "connection-reset") {
632
+ if (recovery !== "connection-reset" && recovery !== "offline-resend") {
621
633
  return { ...init, headers };
622
634
  }
623
635
  headers.set("connection", "close");
@@ -664,6 +676,8 @@ export async function fetchWithResetRetry(
664
676
  // settles as the refusal or an unambiguous answer: a second send of a possibly-executed turn
665
677
  // is already out, and handing the client anything it would retry compounds it.
666
678
  let spentOperatorReplacement = false;
679
+ // The recovery the next send reports: the caller's for the first, then whichever path resent it.
680
+ let recovery = firstRecovery;
667
681
  for (let attempt = 0; attempt < attempts; attempt++) {
668
682
  if (opts.abortSignal?.aborted) throw abortError(opts.abortSignal);
669
683
  // Reported before the await, one physical send at a time: a send that rejects has still
@@ -673,7 +687,7 @@ export async function fetchWithResetRetry(
673
687
  if (!opts.onSendsConsumed?.beforeSend) opts.onSendsConsumed?.(1);
674
688
  try {
675
689
  let response: Response;
676
- try { const run = () => doFetch(attempt === 0 ? firstRecovery : "connection-reset");
690
+ try { const sendRecovery = recovery; const run = () => doFetch(sendRecovery);
677
691
  response = await (opts.onSendsConsumed?.execute ? opts.onSendsConsumed.execute(run) : run()); }
678
692
  finally { if (opts.onSendsConsumed?.beforeSend) opts.onSendsConsumed(1); }
679
693
  return spentOperatorReplacement ? settleOperatorReplacement(response) : response;
@@ -688,6 +702,13 @@ export async function fetchWithResetRetry(
688
702
  // evidence: keep it attached so the terminal rejection cannot be
689
703
  // downgraded to the pre-connection neutral class (#914 review).
690
704
  if (sawReset) throw new UpstreamRetryEvidenceError([], err, true);
705
+ // Nothing reached the origin, so one resend after reachability returns cannot repeat an effect.
706
+ // A client that left during the wait gets this failure back, never the abort reason.
707
+ if (attempt + 1 < attempts && opts.offlineWait && await opts.offlineWait(err, opts.abortSignal)
708
+ && !opts.abortSignal?.aborted) {
709
+ recovery = "offline-resend";
710
+ continue;
711
+ }
691
712
  throw err;
692
713
  }
693
714
  if (opts.replaySafe === true) {
@@ -707,6 +728,7 @@ export async function fetchWithResetRetry(
707
728
  }
708
729
  sawReset = true;
709
730
  lastError = err;
731
+ recovery = "connection-reset";
710
732
  console.warn(
711
733
  `[upstream-retry] connection reset${opts.label ? ` (${opts.label})` : ""} — ${
712
734
  spentOperatorReplacement ? "replacing" : "retrying"
@@ -844,6 +866,8 @@ export async function fetchWithTransientRetry(
844
866
  ...opts,
845
867
  attempts: remaining(),
846
868
  onSendsConsumed: undefined,
869
+ // The offline wait belongs to the request's first send only (see below); later legs never wait.
870
+ offlineWait: undefined,
847
871
  });
848
872
  // Reported in `finally` rather than at each exit: this function returns from five places
849
873
  // and throws from one, and a caller sharing the budget across request legs must be told the
@@ -851,7 +875,16 @@ export async function fetchWithTransientRetry(
851
875
  try {
852
876
  if (budget === 0) throw new SendBudgetExhaustedError(opts.destination ?? (opts.label ? errorDestinationLabel(opts.label) : undefined));
853
877
  let attemptStart = Date.now();
854
- let res = await fetchWithResetRetry(countedFetch, innerResetOptions());
878
+ // Time spent waiting for the network to return is not part of the resend's own attempt.
879
+ const offlineWait = opts.offlineWait;
880
+ let res = await fetchWithResetRetry(countedFetch, {
881
+ ...innerResetOptions(),
882
+ ...(offlineWait ? { offlineWait: async (error: unknown, signal?: AbortSignal) => {
883
+ const resumed = await offlineWait(error, signal);
884
+ if (resumed) attemptStart = Date.now();
885
+ return resumed;
886
+ } } : {}),
887
+ });
855
888
  for (let attempt = 0; sent < budget; attempt++) {
856
889
  // A non-replayable gateway status was settled after the request body had already left
857
890
  // for the origin; retrying it here is the automatic resend the marker exists to forbid.
@@ -109,10 +109,10 @@ export type IdentityFileProblem = "identity_file_missing" | "identity_file_not_r
109
109
  export const IDENTITY_FILE_GUIDANCE: Readonly<Record<IdentityFileProblem, string>> = {
110
110
  identity_file_missing: "The identity file does not exist.",
111
111
  identity_file_not_regular: "The identity file must be a regular file, not a symlink or a directory.",
112
- identity_file_permissions: "The identity file must be owned by this user with no group or other permissions (chmod 600 on it). Use a key file of this user's own; never chown another user's or the system's key.",
113
- identity_file_directory: "The directory that holds the identity file must be owned by this user or root and not writable by group or others. Move the key to a path that passes; if a tool chose the path, run chmod go-w on that tool's own private folder or have it use a path that passes. Never change a shared or system directory such as /tmp, even when the Home runs as root.",
114
- identity_file_ancestor: "Every directory above the identity file must be owned by this user or root and not writable by group or others unless sticky, and every symlink on its path must be owned by this user or root; a folder made under umask 002 is group-writable. Run chmod go-w on such a private folder of this user's or of the tool that chose the path, or use a path that passes. Never change a shared or system directory or another user's symlink, even as root.",
115
- identity_file_unreadable: "This user cannot read the identity file or a directory on its path, or the path is too long or has too many symlinks. Use a shorter path without symlink loops; fix read access only on this user's own file or folder.",
112
+ identity_file_permissions: "The identity file must be owned by this user with no group or other permissions. Use a key file of this user's own and run chmod 600 on it; never chown or chmod another user's or the system's key.",
113
+ identity_file_directory: "The directory that holds the identity file must be owned by this user or root and not writable by group or others. Move the key to a path that passes, or run chmod go-w on that directory only if it is a private folder this user owns (its own, or one a tool made for it); a tool that chose the path can instead be set to use a path that passes. Never change a shared or system directory such as /tmp, even when the Home runs as root.",
114
+ identity_file_ancestor: "Every directory above the identity file must be owned by this user or root and not writable by group or others unless sticky, and every symlink on its path must be owned by this user or root; a folder made under umask 002 is group-writable. Run chmod go-w on such a folder only if it is a private folder this user owns (its own, or one a tool made for it), or use a path that passes. Never change a shared or system directory or another user's symlink, even as root.",
115
+ identity_file_unreadable: "This user cannot read the identity file or a directory on its path, or the path is too long or has too many symlinks. Use a shorter path without symlink loops; fix read access only on this user's own file or folder, with chmod u+r on the file or u+rx on a folder, and never add group or other access.",
116
116
  identity_file_unsupported_platform: "A Windows Home does not support an identity file yet.",
117
117
  };
118
118
 
@@ -28,20 +28,44 @@ export function powershellArgv(script: string): string[] {
28
28
  export const WINDOWS_CONTAINMENT_EXIT = 126;
29
29
 
30
30
  const SCRIPT_PACKED_PREFIX = "$ocxPacked='";
31
+ /** First code point of the packed alphabet: 14 bits per character land in U+3400..U+73FF. */
32
+ const PACK_BASE = 0x3400;
33
+
31
34
  /**
32
35
  * The whole script travels deflated and is inflated on the Child before anything in it exists,
33
- * including Fail. A session that cannot inflate it (Constrained Language Mode blocks the stream
36
+ * including Fail. The deflated bytes ride 14 bits per character in U+3400..U+73FF (#8359): every one
37
+ * is plain text inside a single-quoted PowerShell literal (no ASCII, no U+2018..U+201B smart quotes,
38
+ * no surrogates), and the denser alphabet leaves room under cmd.exe's command line for the
39
+ * served-runtime census in the gated scripts. The byte count rides along so padding bits never
40
+ * become a byte. A session that cannot inflate it (Constrained Language Mode blocks the stream
34
41
  * types) must still exit 126, so only the inflate is guarded: Invoke-Expression stays outside the
35
42
  * try, and the inflated script's own errors and exit status are never relabelled as containment.
36
43
  */
37
44
  export function packedPowerShellArgv(script: string): string[] {
38
45
  const bytes = deflateRawSync(Buffer.from(script, "utf8"), { level: 9 });
39
- const packed = Array.from(bytes, byte => String.fromCharCode(byte + 256)).join("");
40
- 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`);
46
+ let packed = "", bits = 0, pending = 0;
47
+ for (const byte of bytes) {
48
+ pending = (pending << 8) | byte;
49
+ bits += 8;
50
+ while (bits >= 14) { bits -= 14; packed += String.fromCharCode(PACK_BASE + ((pending >> bits) & 0x3fff)); }
51
+ pending &= (1 << bits) - 1;
52
+ }
53
+ if (bits > 0) packed += String.fromCharCode(PACK_BASE + ((pending << (14 - bits)) & 0x3fff));
54
+ return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$ErrorActionPreference='Stop';try{$m=[IO.MemoryStream]::new();$a=0;$n=0;foreach($c in $ocxPacked.ToCharArray()){$a=($a -shl 14)-bor([int]$c-13312);$n+=14;while($n -ge 8){$n-=8;$m.WriteByte(($a -shr $n)-band 255)};$a=$a-band((1 -shl $n)-1)};$m.SetLength(` + bytes.length + String.raw`);$m.Position=0;$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new($m,[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`);
41
55
  }
42
56
  function unpackPowerShell(script: string): string {
43
57
  const match = /\$ocxPacked='([^']+)'/.exec(script);
44
- return match ? inflateRawSync(Buffer.from(Array.from(match[1]!, ch => ch.charCodeAt(0) - 256))).toString("utf8") : script;
58
+ const length = /\$m\.SetLength\((\d+)\)/.exec(script);
59
+ if (!match || !length) return script;
60
+ const bytes: number[] = [];
61
+ let pending = 0, bits = 0;
62
+ for (const ch of match[1]!) {
63
+ pending = (pending << 14) | (ch.charCodeAt(0) - PACK_BASE);
64
+ bits += 14;
65
+ while (bits >= 8) { bits -= 8; bytes.push((pending >> bits) & 0xff); }
66
+ pending &= (1 << bits) - 1;
67
+ }
68
+ return inflateRawSync(Buffer.from(bytes.slice(0, Number(length[1])))).toString("utf8");
45
69
  }
46
70
 
47
71
  /**
@@ -54,13 +78,15 @@ function unpackPowerShell(script: string): string {
54
78
  * host's. One finally block releases the attribute list, its value buffer and the thread, process
55
79
  * and Job handles on every path, and terminates the child through its own handle if anything
56
80
  * fails after creation. If Add-Type or any step fails, the host exits 126; there is no
57
- * uncontained fallback. Ok is the bounded --version probe for discovery. Layouts are x64:
81
+ * uncontained fallback. V is the bounded --version probe (ten seconds, at most 256 characters of
82
+ * stdout, exit 0) and Ok is V succeeding; both take an already CRT-quoted argument prefix, empty
83
+ * for a binary and the entry of a served [bun.exe, entry] pair (#8359). Layouts are x64:
58
84
  * STARTUPINFOEXW is 112 bytes with the attribute list at byte 104, and LimitFlags sits at byte 16
59
85
  * of the 144-byte JOBOBJECT_EXTENDED_LIMIT_INFORMATION. Warnings fail Add-Type in Windows
60
86
  * PowerShell, so this source must compile without any.
61
87
  */
62
88
  export const OCX_JOB_SOURCE = [
63
- "using System;using System.Text;using System.Diagnostics;using System.Runtime.InteropServices;",
89
+ "using System;using System.Text;using System.Diagnostics;using System.Runtime.InteropServices;using System.Threading.Tasks;",
64
90
  "public static class OcxJob{",
65
91
  "[DllImport(\"kernel32\")]static extern IntPtr CreateJobObjectW(IntPtr a,IntPtr n);",
66
92
  "[DllImport(\"kernel32\")]static extern bool SetInformationJobObject(IntPtr j,int c,byte[] i,int l);",
@@ -73,15 +99,12 @@ export const OCX_JOB_SOURCE = [
73
99
  "[DllImport(\"kernel32\")]static extern bool TerminateProcess(IntPtr p,int c);",
74
100
  "[DllImport(\"kernel32\")]static extern bool CloseHandle(IntPtr h);",
75
101
  "static void F(bool k){if(!k)throw new Exception();}",
76
- "public static bool Ok(string x){try{",
77
- "var q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});",
78
- "q.StandardInput.Close();q.StandardOutput.ReadToEndAsync();q.StandardError.ReadToEndAsync();",
79
- "if(q.WaitForExit(10000))return q.ExitCode==0;q.Kill();}catch{return false;}return false;}",
80
- "public static string V(string x){Process q=null;try{",
81
- "q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});q.StandardInput.Close();",
82
- "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);});",
83
- "System.Threading.Tasks.Task.Run(()=>{var b=new char[1024];while(p.StandardError.Read(b,0,b.Length)>0){} });",
84
- "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;",
102
+ "public static bool Ok(string x,string a){return V(x,a)!=null;}",
103
+ "public static string V(string x,string a){Process q=null;try{",
104
+ "q=Process.Start(new ProcessStartInfo(x,a+\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});q.StandardInput.Close();",
105
+ "var p=q;var read=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);});",
106
+ "Task.Run(()=>{var b=new char[1024];while(p.StandardError.Read(b,0,b.Length)>0){} });",
107
+ "var clock=Stopwatch.StartNew();var done=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;",
85
108
  "}catch{try{if(q!=null&&!q.HasExited){q.Kill();q.WaitForExit();}}catch{return null;}return null;}finally{if(q!=null)q.Dispose();}}",
86
109
  "public static int Run(string x,string c){",
87
110
  "IntPtr z=IntPtr.Zero,j=z,l=z,v=z,h=z,t=z;bool listed=false,done=false;",
@@ -112,6 +135,11 @@ function Quote-Native([string]$v){'"'+[regex]::Replace([regex]::Replace($v,'(\\*
112
135
  function Invoke-Native([string]$e,[string[]]$a){try{$c=[OcxJob]::Run($e,((@($e)+$a|%{Quote-Native $_}) -join ' '))}catch{Fail};exit $c}
113
136
  `;
114
137
 
138
+ /** A script from this module with its packed payload inflated; any other text comes back unchanged. For tests. */
139
+ export function windowsInflatedScript(script: string): string {
140
+ return unpackPowerShell(script);
141
+ }
142
+
115
143
  /** The packed helper a script carries, inflated; for tests that check the transport. */
116
144
  export function windowsScriptHelperSource(script: string): string | undefined {
117
145
  script = unpackPowerShell(script);
@@ -161,19 +189,39 @@ $f+=@((Get-Command ocx.exe -Type Application -EA 0).Source)
161
189
  $k=@("$u\.local\bin\ocx-child.exe","$u\.cache\opencodex\bin\ocx-child.exe");if($env:LOCALAPPDATA){$k+="$env:LOCALAPPDATA\opencodex\bin\ocx-child.exe"};$k+=@((Get-Command ocx-child.exe -Type Application -EA 0).Source)
162
190
  $r=if($env:HOME){$env:HOME}elseif($u){$u}else{"."};$h=if($env:OPENCODEX_HOME){$env:OPENCODEX_HOME}else{"$r\.opencodex"};$c=if([IO.File]::Exists("$h\child\state.json")){$k+$f}else{$f+$k}
163
191
  `;
192
+ /**
193
+ * The install that last started serving this home (#8359), read from the first record's `command`
194
+ * in `serving-runtimes.json` (src/config/serving-runtimes.ts): `[ocx.exe]`, or `[bun.exe, cli\index.ts]`
195
+ * for an npm install. It moves ahead of every fixed candidate except ocx-child under a Child state,
196
+ * the POSIX order. Its variables ($sx, $sy) are names no other script fragment assigns: the gate loops
197
+ * reuse $a, $s and $p (#8359 review). `A` yields its entry as an argument prefix for the run and `P` the same prefix
198
+ * CRT-quoted for the helper's --version probe; any other candidate gets none. The pair runs only
199
+ * while its entry exists. A census over 64 KiB, a first record without a command, a relative or
200
+ * quoted path, a third element or any read error leaves the fixed order. The census sits where its
201
+ * writer's `getConfigDir()` puts it: a trimmed `OPENCODEX_HOME` (a leading ~ is the profile), else
202
+ * `%USERPROFILE%\.opencodex`, which is what `homedir()` answers on Windows; a Child state in that
203
+ * directory or the legacy `$h` one keeps ocx-child first. Discovery and runtime
204
+ * inspection, the pinned and overwrite syncs and the gated update plan all read it, so every Windows
205
+ * Remote Link command runs the same install the Child serves from.
206
+ */
207
+ const SERVED_CANDIDATE = String.raw`$sx=$null;$sy=@();try{$o=([string]$env:OPENCODEX_HOME).Trim();if($o -match '^~([\\/]|$)'){$o=$u+$o.Substring(1)};$g=$(if($o){$o}else{"$u\.opencodex"});$j="$g\serving-runtimes.json";if((Get-Item -LiteralPath $j -Force -EA 1).Length -le 65536){$e=@(@(([IO.File]::ReadAllText($j)|ConvertFrom-Json).runtimes)[0].command);if($e.Count -in 1,2 -and !($e|?{$_ -isnot [string] -or $_ -match '["\x00-\x1f]' -or ![IO.Path]::IsPathRooted($_)})-and($e.Count -eq 1 -or [IO.File]::Exists($e[1]))){$sx=$e[0];$sy=@($e|select -Skip 1);$c=if([IO.File]::Exists("$g\child\state.json")-or[IO.File]::Exists("$h\child\state.json")){$k+$sx+$f}else{@($sx)+$f+$k}}}}catch{$null=$_}
208
+ function A($x){if($x -eq $sx){$sy}}
209
+ function P($x){(@(A $x)|%{(Quote-Native $_)+' '}) -join ''}
210
+ `;
211
+
164
212
  export function windowsOcxArgv(args: readonly string[]): string[] {
165
213
  const sweep = args.includes("--purge") ? String.raw`foreach($r in @($env:LOCALAPPDATA,$env:USERPROFILE)){if($r){foreach($s in @("$r\opencodex\bin","$r\.cache\opencodex\bin")){if([IO.Directory]::Exists($s)){Get-ChildItem -LiteralPath $s -Filter '.ocx-child.purge.*.old' -Force -EA 0|%{try{[IO.File]::Delete($_.FullName)}catch{$null=$_}}}}}};` : "";
166
- const run = sweep ? `try{$c=[OcxJob]::Run($x,((@($x)+$d.args|%{Quote-Native $_}) -join ' '))}catch{Fail};${sweep}exit $c` : `Invoke-Native $x @($d.args)`;
167
- return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + String.raw`
168
- foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){` + run + String.raw`}}
214
+ const run = sweep ? `try{$c=[OcxJob]::Run($x,((@($x)+@(A $x)+$d.args|%{Quote-Native $_}) -join ' '))}catch{Fail};${sweep}exit $c` : `Invoke-Native $x (@(A $x)+@($d.args))`;
215
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + SERVED_CANDIDATE + String.raw`
216
+ foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x,(P $x))){` + run + String.raw`}}
169
217
  [Console]::Error.WriteLine('No runnable ocx.exe found; install the Windows standalone archive.');exit 127
170
218
  `);
171
219
  }
172
220
 
173
221
  export function windowsInspectRuntimeArgv(): string[] {
174
- return packedPowerShellArgv(NATIVE_PROCESS + OCX_CANDIDATES + String.raw`
222
+ return packedPowerShellArgv(NATIVE_PROCESS + OCX_CANDIDATES + SERVED_CANDIDATE + String.raw`
175
223
  [Console]::Out.WriteLine('ocx-inspect:arch:'+[string]$env:PROCESSOR_ARCHITECTURE)
176
- foreach($x in ($c|select -Unique)){if(![IO.File]::Exists($x)){continue};$v=[OcxJob]::V($x);if($null -ne $v){$k=if(([IO.Path]::GetFileName($x)).ToLowerInvariant().StartsWith('ocx-child')){'ephemeral'}else{'full'};[Console]::Out.WriteLine('ocx-inspect:kind:'+$k);[Console]::Out.WriteLine('ocx-inspect:version:'+$v.Trim());exit 0}}
224
+ foreach($x in ($c|select -Unique)){if(![IO.File]::Exists($x)){continue};$v=[OcxJob]::V($x,(P $x));if($null -ne $v){$k=if(([IO.Path]::GetFileName($x)).ToLowerInvariant().StartsWith('ocx-child')){'ephemeral'}else{'full'};[Console]::Out.WriteLine('ocx-inspect:kind:'+$k);[Console]::Out.WriteLine('ocx-inspect:version:'+$v.Trim());exit 0}}
177
225
  [Console]::Out.WriteLine('ocx-inspect:kind:missing');exit 0
178
226
  `);
179
227
  }
@@ -203,7 +251,7 @@ export function windowsPurgePlantedChildArgv(): string[] {
203
251
  return packedPowerShellArgv(NATIVE_PROCESS + WINDOWS_MANAGED_BIN + String.raw`
204
252
  $r=if($env:HOME){$env:HOME}elseif($env:USERPROFILE){$env:USERPROFILE}else{"."};$h=if($env:OPENCODEX_HOME){$env:OPENCODEX_HOME}else{"$r\.opencodex"};$cd="$h\child";$cx=if($env:CODEX_HOME){$env:CODEX_HOME}else{"$r\.codex"}
205
253
  $rec=@(@("$cd\state.json","$cd\codex-journal.json","$cd\attach-rollback.json","$cx\.ocx-child-owner.json")|?{[IO.File]::Exists($_)-or[IO.Directory]::Exists($_)});$pend=$rec.Count -gt 0;if($pend){$m='ocx-child recovery record remains at '+$rec[0]+'; keeping the planted binary for detach.'}
206
- try{$dir=Resolve-PlantDir;$dst="$dir\ocx-child.exe";if([IO.File]::Exists($dst)){if([OcxJob]::Ok($dst)){$rc=[OcxJob]::Run($dst,('"'+$dst+'" detach --purge'));if($rc -ne 0){exit $rc};if([IO.File]::Exists($dst)){[Console]::Error.WriteLine('ocx-child kept the planted binary: another ocx-child relay runs from it.')}}elseif($pend){[Console]::Error.WriteLine($m);exit 1}else{try{[IO.File]::Delete($dst)}catch{$null=$_}}}elseif($pend){[Console]::Error.WriteLine($m);exit 1};Get-ChildItem -LiteralPath $dir -Filter '.ocx-child.purge.*.old' -Force -EA 0|%{try{[IO.File]::Delete($_.FullName)}catch{$null=$_}}}catch{exit 1};exit 0
254
+ try{$dir=Resolve-PlantDir;$dst="$dir\ocx-child.exe";if([IO.File]::Exists($dst)){if([OcxJob]::Ok($dst,'')){$rc=[OcxJob]::Run($dst,('"'+$dst+'" detach --purge'));if($rc -ne 0){exit $rc};if([IO.File]::Exists($dst)){[Console]::Error.WriteLine('ocx-child kept the planted binary: another ocx-child relay runs from it.')}}elseif($pend){[Console]::Error.WriteLine($m);exit 1}else{try{[IO.File]::Delete($dst)}catch{$null=$_}}}elseif($pend){[Console]::Error.WriteLine($m);exit 1};Get-ChildItem -LiteralPath $dir -Filter '.ocx-child.purge.*.old' -Force -EA 0|%{try{[IO.File]::Delete($_.FullName)}catch{$null=$_}}}catch{exit 1};exit 0
207
255
  `);
208
256
  }
209
257
 
@@ -228,7 +276,7 @@ export function windowsManagedPurgeDisconnectArgv(expectLink?: string): string[]
228
276
  if (expectLink !== undefined && !/^lnk_[0-9a-f]{16}$/.test(expectLink)) throw new Error("invalid link id");
229
277
  return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: expectLink === undefined ? [] : [expectLink] }) + WINDOWS_MANAGED_BIN + String.raw`
230
278
  try{$dir=Resolve-PlantDir}catch{[Console]::Error.WriteLine('Refusing a reparse point in the managed ocx-child directory.');exit 1}
231
- $dst="$dir\ocx-child.exe";if(-not([IO.File]::Exists($dst)-and[OcxJob]::Ok($dst))){[Console]::Error.WriteLine('${MANAGED_PURGE_CHILD_MISSING_MARKER}');exit 1}
279
+ $dst="$dir\ocx-child.exe";if(-not([IO.File]::Exists($dst)-and[OcxJob]::Ok($dst,''))){[Console]::Error.WriteLine('${MANAGED_PURGE_CHILD_MISSING_MARKER}');exit 1}
232
280
  $x=@($d.args);$e=if($x.Count -gt 0){' --expect-link '+(Quote-Native ([string]$x[0]))}else{''}
233
281
  try{$rc=[OcxJob]::Run($dst,('"'+$dst+'" disconnect --purge --json'+$e))}catch{exit 1}
234
282
  Get-ChildItem -LiteralPath $dir -Filter '.ocx-child.purge.*.old' -Force -EA 0|%{try{[IO.File]::Delete($_.FullName)}catch{$null=$_}};exit $rc
@@ -247,9 +295,9 @@ export interface WindowsGatedCommand {
247
295
  /**
248
296
  * The gated Windows command: select a candidate, refuse below the minimum, optionally refuse ocx-child, then run it
249
297
  * contained. OCX_NO_DESKTOP_HANDOFF=1 makes a launcher answer --version and run the command itself. Windows never
250
- * sends a restart, so the selected-kind report is not built here. Windows reads no served-runtime census, so the
251
- * selected entry is always a binary: the script prints no entry marker and the Home infers "binary", which keeps the
252
- * plan probe inside the command-line budget for long preview Home versions.
298
+ * sends a restart, so the selected-kind report is not built here. The served install comes first (#8359), and a served
299
+ * [bun.exe, entry] pair passes its entry as an argument prefix. The script still prints no entry marker and the Home
300
+ * infers "binary": Windows never applies an update, so nothing reads the pair/binary distinction there.
253
301
  */
254
302
  export function windowsGatedOcxArgv(cmd: WindowsGatedCommand): string[] {
255
303
  if (!cmd.versionParts.every(part => /^(0|[1-9][0-9]{0,3})$/.test(part))) throw new Error("invalid gate version");
@@ -259,16 +307,16 @@ export function windowsGatedOcxArgv(cmd: WindowsGatedCommand): string[] {
259
307
  const overwriteEphemeral = cmd.lacksMarker === "child-ocx-lacks-overwrite" ? String.raw`if(([IO.Path]::GetFileName($x)).ToLowerInvariant().StartsWith('ocx-child')){[Console]::Error.WriteLine('ocx-fanout:child-ephemeral-no-overwrite');exit 121};` : "";
260
308
  const ephemeral = cmd.acceptEphemeral || overwriteEphemeral ? "" : String.raw`if($x -match '(^|[\\/])ocx-child[^\\/]*$'){[Console]::Error.WriteLine('ocx-fanout:child-ocx-ephemeral');exit 121};`;
261
309
  const clock = cmd.reportClock ? String.raw`[Console]::Error.WriteLine('ocx-fanout:child-now:'+[DateTimeOffset]::Now.ToUnixTimeMilliseconds());` : "";
262
- return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: cmd.args }) + OCX_CANDIDATES + String.raw`$env:OCX_NO_DESKTOP_HANDOFF='1'
310
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: cmd.args }) + OCX_CANDIDATES + SERVED_CANDIDATE + String.raw`$env:OCX_NO_DESKTOP_HANDOFF='1'
263
311
  foreach($x in ($c|select -Unique)){
264
- if(![IO.File]::Exists($x)){continue};` + overwriteEphemeral + String.raw`$v=[OcxJob]::V($x);if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
312
+ if(![IO.File]::Exists($x)){continue};` + overwriteEphemeral + String.raw`$v=[OcxJob]::V($x,(P $x));if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
265
313
  $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-]+)*))?$')
266
314
  $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}}}
267
315
  if($bad){[Console]::Error.WriteLine('ocx-fanout:child-ocx-version-unknown');exit 121}
268
316
  $a=@($m.Groups[1].Value,$m.Groups[2].Value,$m.Groups[3].Value);$b=@(` + b + String.raw`);$cmp=0
269
317
  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}}
270
318
  if($cmp -lt 0 -or ($cmp -eq 0 -and $m.Groups[4].Success)){[Console]::Error.WriteLine('ocx-fanout:` + cmd.lacksMarker + String.raw`');exit 121}
271
- ` + ephemeral + String.raw`[Console]::Error.WriteLine('ocx-fanout:selected:'+$v);` + clock + String.raw`[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args)
319
+ ` + ephemeral + String.raw`[Console]::Error.WriteLine('ocx-fanout:selected:'+$v);` + clock + String.raw`[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x (@(A $x)+@($d.args))
272
320
  };exit 127
273
321
  `);
274
322
  }
@@ -284,16 +332,16 @@ export function windowsOverwriteSyncArgv(linkId: string, overwriteConflict = fal
284
332
  const minimum = overwriteConflict ? ROUTE_OVERWRITE_MIN_CHILD_VERSION.split(".").map(part => `'${part}'`).join(",") : "'2','93','0'";
285
333
  const lacks = overwriteConflict ? "ocx-fanout:child-ocx-lacks-overwrite" : "ocx-fanout:child-ocx-lacks-expect-link";
286
334
  const ephemeral = overwriteConflict ? String.raw`if(([IO.Path]::GetFileName($x)).ToLowerInvariant().StartsWith('ocx-child')){[Console]::Error.WriteLine('ocx-fanout:child-ephemeral-no-overwrite');exit 121};` : "";
287
- return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json", ...(overwriteConflict ? ["--overwrite-conflict"] : []), ...(overwriteClient ? ["--overwrite-client", overwriteClient] : [])] }) + OCX_CANDIDATES + String.raw`$env:OCX_NO_DESKTOP_HANDOFF=1
335
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json", ...(overwriteConflict ? ["--overwrite-conflict"] : []), ...(overwriteClient ? ["--overwrite-client", overwriteClient] : [])] }) + OCX_CANDIDATES + SERVED_CANDIDATE + String.raw`$env:OCX_NO_DESKTOP_HANDOFF=1
288
336
  foreach($x in $c){
289
- if(![IO.File]::Exists($x)){continue};` + ephemeral + String.raw`$v=[OcxJob]::V($x);if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
337
+ if(![IO.File]::Exists($x)){continue};` + ephemeral + String.raw`$v=[OcxJob]::V($x,(P $x));if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)}
290
338
  $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-]+)*))?$')
291
339
  $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}}}
292
340
  if($bad){[Console]::Error.WriteLine('ocx-fanout:child-ocx-version-unknown');exit 121}
293
341
  $a=@($m.Groups[1].Value,$m.Groups[2].Value,$m.Groups[3].Value);$b=@(` + minimum + String.raw`);$cmp=0
294
342
  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}}
295
343
  if($cmp -lt 0 -or ($cmp -eq 0 -and $m.Groups[4].Success)){[Console]::Error.WriteLine('` + lacks + String.raw`');exit 121}
296
- [Console]::Error.WriteLine('ocx-fanout:selected:'+$v);[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args)
344
+ [Console]::Error.WriteLine('ocx-fanout:selected:'+$v);[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x (@(A $x)+@($d.args))
297
345
  };exit 127
298
346
  `);
299
347
  }
@@ -18,20 +18,32 @@ const OLDER_LIGHTWEIGHT = "An ocx-child older than that flag refuses it before i
18
18
  const olderFull = (id: string): string => "An OpenCodex older than that flag refuses it before it acts on the link; then run ocx disconnect and ocx restart only if ocx connect status --json shows " + id
19
19
  + ", right after that check (an enrollment that lands between the two commands would be removed), and otherwise leave the Child as it is.";
20
20
 
21
+ /**
22
+ * A purge path that is not found means no planted binary is there: an uncertain journalled plant can stop before it installs
23
+ * one, and a purge removes one only after every recovery record is gone. Either way no ocx-child of this attempt holds the
24
+ * Child, which the bare "not found" of the shell does not say.
25
+ */
26
+ const PLANT_NOT_FOUND = " If the command is not found there, the binary is not installed (the plant stopped before installing it, or it was purged since), so no ocx-child of this attempt holds the Child: nothing is left to undo on it, and you can retry.";
27
+
21
28
  const bound = (id: string): string => "it acts only when the Child's records name this attempt's link (" + id + ") or nothing at all, and leaves a Child that another link, a hub or another Home owns.";
22
29
 
23
30
  /**
24
31
  * The lightweight agent's detach by the paths it can have: the managed copy (not necessarily on PATH) for the Child's platform,
25
- * both Windows locations in Command Prompt, and a copy placed by hand through the path command -v (where.exe) prints.
32
+ * both Windows locations in Command Prompt, and a copy placed by hand: first in ~/.local/bin (%USERPROFILE%\.local\bin on
33
+ * Windows), the place the Home's discovery tries before any other and which need not be on PATH, then through the path
34
+ * command -v (where.exe) prints.
26
35
  */
27
36
  function lightweightDetach(id: string, platform: "posix" | "windows" | undefined): { first: string; rest: string; prompt: boolean } {
28
37
  const posix = "~/.cache/opencodex/bin/ocx-child detach --expect-link " + id;
29
38
  const windows = "\"%LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe\" detach --expect-link " + id;
30
39
  const windowsFallback = "\"%USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe\" detach --expect-link " + id;
31
- const placed = (lookup: string) => "for a copy placed by hand, the same detach --expect-link " + id + " through the path " + lookup + " prints";
32
- if (platform === "windows") return { first: windows, rest: " (or " + windowsFallback + " where LOCALAPPDATA is not set; " + placed("where.exe ocx-child") + ")", prompt: true };
33
- if (platform === "posix") return { first: posix, rest: " (" + placed("command -v ocx-child") + ")", prompt: false };
34
- return { first: posix, rest: " (on Windows, in Command Prompt, " + windows + ", or " + windowsFallback + " where LOCALAPPDATA is not set; " + placed("command -v ocx-child, or where.exe ocx-child on Windows,") + ")", prompt: false };
40
+ const placed = (where: string, lookup: string) => "for a copy placed by hand, the same detach --expect-link " + id + " through " + where
41
+ + ", which need not be on PATH, or through the path " + lookup + " prints";
42
+ const posixPlaced = "~/.local/bin/ocx-child";
43
+ const windowsPlaced = "%USERPROFILE%\\.local\\bin\\ocx-child.exe";
44
+ if (platform === "windows") return { first: windows, rest: " (or " + windowsFallback + " where LOCALAPPDATA is not set; " + placed(windowsPlaced, "where.exe ocx-child") + ")", prompt: true };
45
+ if (platform === "posix") return { first: posix, rest: " (" + placed(posixPlaced, "command -v ocx-child") + ")", prompt: false };
46
+ return { first: posix, rest: " (on Windows, in Command Prompt, " + windows + ", or " + windowsFallback + " where LOCALAPPDATA is not set; " + placed(posixPlaced + " (" + windowsPlaced + " on Windows)", "command -v ocx-child, or where.exe ocx-child on Windows,") + ")", prompt: false };
35
47
  }
36
48
 
37
49
  export function residualRecovery(kind: ResidualChild, linkId: string | undefined, platform?: "posix" | "windows"): string {
@@ -42,9 +54,9 @@ export function residualRecovery(kind: ResidualChild, linkId: string | undefined
42
54
  const posix = "~/.cache/opencodex/bin/ocx-child detach --purge --expect-link " + id;
43
55
  const windows = "\"%LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe\" detach --purge --expect-link " + id;
44
56
  const windowsFallback = "\"%USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe\" detach --purge --expect-link " + id;
45
- if (platform === "windows") return "In Command Prompt on the Child, run " + windows + " (or " + windowsFallback + " where LOCALAPPDATA is not set) before retrying: " + bound(id);
46
- if (platform === "posix") return "Run " + posix + " on the Child before retrying: " + bound(id);
47
- return "Run " + posix + " on the Child before retrying (on Windows, in Command Prompt, " + windows + ", or " + windowsFallback + " where LOCALAPPDATA is not set): " + bound(id);
57
+ if (platform === "windows") return "In Command Prompt on the Child, run " + windows + " (or " + windowsFallback + " where LOCALAPPDATA is not set) before retrying: " + bound(id) + PLANT_NOT_FOUND;
58
+ if (platform === "posix") return "Run " + posix + " on the Child before retrying: " + bound(id) + PLANT_NOT_FOUND;
59
+ return "Run " + posix + " on the Child before retrying (on Windows, in Command Prompt, " + windows + ", or " + windowsFallback + " where LOCALAPPDATA is not set): " + bound(id) + PLANT_NOT_FOUND;
48
60
  }
49
61
  const light = lightweightDetach(id, platform);
50
62
  if (kind === "ephemeral") return (light.prompt ? "In Command Prompt on the Child, run " + light.first + " before retrying" : "Run " + light.first + " on the Child before retrying") + light.rest + ": " + bound(id) + " " + OLDER_LIGHTWEIGHT;
@@ -15,17 +15,21 @@ export class MessageBudget {
15
15
  }
16
16
  this.deadline = performance.now() + timeoutMs;
17
17
  this.cancel = () => this.controller.abort(new LocalMessagingError("cancelled", "Messaging operation was cancelled."));
18
- this.timer = setTimeout(() => this.controller.abort(
19
- new LocalMessagingError("operation_timeout", "Messaging operation exceeded its deadline.")), timeoutMs);
18
+ this.timer = setTimeout(() => this.expire(), timeoutMs);
20
19
  parent?.addEventListener("abort", this.cancel, { once: true });
21
20
  if (parent?.aborted) this.cancel();
22
21
  }
23
22
 
24
- /** Reject expired/cancelled work even before the deadline timer receives an event-loop turn. */
25
- throwIfEnded(): void {
26
- if (!this.signal.aborted && performance.now() >= this.deadline) {
23
+ /** End the operation as timed out unless it already ended for another reason. */
24
+ private expire(): void {
25
+ if (!this.signal.aborted) {
27
26
  this.controller.abort(new LocalMessagingError("operation_timeout", "Messaging operation exceeded its deadline."));
28
27
  }
28
+ }
29
+
30
+ /** Reject expired/cancelled work even before the deadline timer receives an event-loop turn. */
31
+ throwIfEnded(): void {
32
+ if (performance.now() >= this.deadline) this.expire();
29
33
  if (this.signal.aborted) throw this.signal.reason;
30
34
  }
31
35
 
@@ -35,6 +39,20 @@ export class MessageBudget {
35
39
  return Math.max(1, Math.min(limit, Math.ceil(this.deadline - performance.now())));
36
40
  }
37
41
 
42
+ /**
43
+ * Arm one stage timer bounded by the remaining deadline. A timer the deadline capped, or one
44
+ * firing at or after it, ends the operation as operation_timeout (via the signal) instead of
45
+ * calling onStageTimeout, so timer ordering on a loaded event loop cannot relabel the expiry.
46
+ */
47
+ stageTimer(limit: number, onStageTimeout: () => void): ReturnType<typeof setTimeout> {
48
+ const delay = this.remainingMs(limit);
49
+ const capped = Math.ceil(this.deadline - performance.now()) <= limit;
50
+ return setTimeout(() => {
51
+ if (capped || performance.now() >= this.deadline) this.expire();
52
+ else onStageTimeout();
53
+ }, delay);
54
+ }
55
+
38
56
  /** Release timers/listeners and cancel any resources still waiting on this owned budget. */
39
57
  dispose(): void {
40
58
  clearTimeout(this.timer);
@@ -12,6 +12,8 @@ export type RemotePortAllocator = () => { port: number; stop(force?: boolean): v
12
12
  export interface RemotePortReservation { port: number; handoff(): void; release(): void }
13
13
  const pendingPorts = new Set<number>();
14
14
  const PORT_ALLOCATION_ATTEMPTS = 8;
15
+ // A listener-table row is about 150 bytes; a longer unterminated row is not a kernel table.
16
+ const PROC_ROW_BYTES = 4096;
15
17
  const allocateRemotePort: RemotePortAllocator = () => Bun.listen({ hostname: "127.0.0.1", port: 0,
16
18
  exclusive: true, socket: { data(socket) { socket.end(); } } });
17
19
 
@@ -45,7 +47,8 @@ export async function remotePortIsLoopback(port: number, budget: MessageBudget,
45
47
  budget.throwIfEnded();
46
48
  const platform = inspector.platform ?? process.platform;
47
49
  if (platform === "linux") {
48
- const found: string[] = [], hex = port.toString(16).toUpperCase().padStart(4, "0");
50
+ const hex = port.toString(16).toUpperCase().padStart(4, "0");
51
+ let loopback = false, exposed = false;
49
52
  for (const path of ["/proc/net/tcp", "/proc/net/tcp6"]) {
50
53
  let fd: RemoteProcFile;
51
54
  try { fd = await (inspector.openProc ?? (path => open(path, "r")))(path); }
@@ -54,19 +57,28 @@ export async function remotePortIsLoopback(port: number, budget: MessageBudget,
54
57
  throw error;
55
58
  }
56
59
  try {
57
- const bytes = Buffer.alloc(4 * 1024 * 1024 + 1); let size = 0;
58
- while (size < bytes.length) {
59
- budget.throwIfEnded(); const next = await fd.read(bytes, size, bytes.length - size, null);
60
- if (!next.bytesRead) break; size += next.bytesRead;
61
- }
62
- if (size >= bytes.length) return false;
63
- for (const line of bytes.subarray(0, size).toString("utf8").split("\n").slice(1)) {
60
+ // Stream every row: the table lists all of the host's sockets, including TIME_WAIT, so a
61
+ // busy machine passes any fixed size. A public listener anywhere in it must still refuse.
62
+ const chunk = Buffer.alloc(64 * 1024); let pending = "", header = true;
63
+ const row = (line: string) => {
64
+ if (header) { header = false; return; }
64
65
  const fields = line.trim().split(/\s+/), [address, fieldPort] = (fields[1] ?? "").split(":");
65
- if (fields[3] === "0A" && fieldPort === hex) found.push(address!);
66
+ if (fields[3] !== "0A" || fieldPort !== hex) return;
67
+ if (address === "0100007F" || address === "00000000000000000000000001000000") loopback = true;
68
+ else exposed = true;
69
+ };
70
+ for (;;) {
71
+ budget.throwIfEnded(); const next = await fd.read(chunk, 0, chunk.length, null);
72
+ if (!next.bytesRead) break;
73
+ const lines = (pending + chunk.toString("latin1", 0, next.bytesRead)).split("\n");
74
+ pending = lines.pop()!;
75
+ if (pending.length > PROC_ROW_BYTES) return false;
76
+ for (const line of lines) row(line);
66
77
  }
78
+ row(pending);
67
79
  } finally { await fd.close(); }
68
80
  }
69
- return found.length > 0 && found.every(address => address === "0100007F" || address === "00000000000000000000000001000000");
81
+ return loopback && !exposed;
70
82
  }
71
83
  if (platform === "darwin") {
72
84
  const output = await runRemoteHelper(["/usr/sbin/lsof", "-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fn"], budget, capacity,
@@ -53,9 +53,9 @@ export class LocalMessageRpc implements LocalMetadataClient {
53
53
  socket.onopen = socket.onerror = socket.onclose = null;
54
54
  };
55
55
  const abort = () => { cleanup(); reject(budget.signal.reason); };
56
- const timer = setTimeout(() => {
56
+ const timer = budget.stageTimer(rpcTimeoutMs, () => {
57
57
  cleanup(); reject(new LocalMessagingError("daemon_unavailable", "Local Codex connection timed out; no daemon was started."));
58
- }, budget.remainingMs(rpcTimeoutMs));
58
+ });
59
59
  budget.signal.addEventListener("abort", abort, { once: true });
60
60
  socket.onopen = () => { cleanup(); resolve(); };
61
61
  socket.onerror = socket.onclose = () => {
@@ -208,8 +208,8 @@ export class LocalMessageRpc implements LocalMetadataClient {
208
208
  if (this.pending.size >= 4) throw new LocalMessagingError("rpc_limit", "Local Codex metadata concurrency limit exceeded.");
209
209
  const id = ++this.nextId;
210
210
  return new Promise((resolve, reject) => {
211
- const timer = setTimeout(() => this.close(new LocalMessagingError("rpc_timeout", "Local Codex request timed out.")),
212
- this.budget.remainingMs(this.rpcTimeoutMs));
211
+ const timer = this.budget.stageTimer(this.rpcTimeoutMs,
212
+ () => this.close(new LocalMessagingError("rpc_timeout", "Local Codex request timed out.")));
213
213
  this.pending.set(id, { resolve, reject, timer, method });
214
214
  try { this.socket.send(JSON.stringify({ id, method, params })); onWritten?.(); } catch { this.close(); }
215
215
  });