@bitkyc08/opencodex 2.99.0 → 2.100.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 (258) hide show
  1. package/AGENTS_INSTALL.md +19 -1
  2. package/README.md +37 -33
  3. package/SPONSORS.md +5 -1
  4. package/bin/ocx.mjs +1 -1
  5. package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
  6. package/gui/dist/assets/App-CitvEefy.js +59 -0
  7. package/gui/dist/assets/Tray-CeKVWQyB.js +1 -0
  8. package/gui/dist/assets/{brand-mark-wzPe3R-J.js → brand-mark-M92UnxX2.js} +1 -1
  9. package/gui/dist/assets/index-BP47do6-.js +94 -0
  10. package/gui/dist/assets/index-DmDooSAG.css +2 -0
  11. package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-CcxZBnxv.js} +1 -1
  12. package/gui/dist/classic/assets/App-aYgIQMxI.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-D8jfUXpQ.js} +1 -1
  14. package/gui/dist/classic/assets/index-CfGqHooN.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +1 -0
  16. package/gui/dist/classic/index.html +1 -1
  17. package/gui/dist/index.html +2 -2
  18. package/native/ocx-child/Cargo.lock +215 -0
  19. package/native/ocx-child/Cargo.toml +31 -0
  20. package/native/ocx-child/src/cli.rs +1901 -0
  21. package/native/ocx-child/src/codex_home.rs +429 -0
  22. package/native/ocx-child/src/codex_settings.rs +231 -0
  23. package/native/ocx-child/src/daemon.rs +363 -0
  24. package/native/ocx-child/src/http_wire.rs +619 -0
  25. package/native/ocx-child/src/journal.rs +977 -0
  26. package/native/ocx-child/src/lib.rs +22 -0
  27. package/native/ocx-child/src/main.rs +9 -0
  28. package/native/ocx-child/src/parity.rs +102 -0
  29. package/native/ocx-child/src/platform.rs +1487 -0
  30. package/native/ocx-child/src/relay.rs +1288 -0
  31. package/native/ocx-child/src/relay_auth.rs +166 -0
  32. package/native/ocx-child/src/routes.rs +236 -0
  33. package/native/ocx-child/src/state.rs +190 -0
  34. package/native/ocx-child/src/test_hooks.rs +58 -0
  35. package/native/ocx-child/src/toml_surgeon.rs +1156 -0
  36. package/package.json +8 -2
  37. package/src/adapters/anthropic.ts +28 -2
  38. package/src/adapters/claude-cli/adapter.ts +5 -25
  39. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  40. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  41. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  42. package/src/adapters/coding-agent/protocol.ts +1 -1
  43. package/src/adapters/devin/live-models.ts +3 -0
  44. package/src/adapters/google-http.ts +3 -0
  45. package/src/adapters/google-vertex-key-project.ts +10 -2
  46. package/src/adapters/google.ts +40 -8
  47. package/src/adapters/kiro/usage.ts +3 -13
  48. package/src/adapters/openai-responses/passthrough.ts +5 -2
  49. package/src/adapters/openai-responses/request-strips.ts +32 -0
  50. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  51. package/src/chat/inbound.ts +1 -1
  52. package/src/claude/auth-detect.ts +26 -8
  53. package/src/claude/inbound-content-options.ts +18 -3
  54. package/src/claude/inbound.ts +5 -2
  55. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  56. package/src/cli/capabilities-agents-routing.ts +2 -2
  57. package/src/cli/capabilities-observe-system.ts +60 -0
  58. package/src/cli/combo-input.ts +6 -0
  59. package/src/cli/combo-result.ts +1 -1
  60. package/src/cli/combo.ts +4 -0
  61. package/src/cli/config-command.ts +16 -2
  62. package/src/cli/connect.ts +12 -10
  63. package/src/cli/dispatch.ts +4 -0
  64. package/src/cli/doctor.ts +11 -0
  65. package/src/cli/help.ts +1 -0
  66. package/src/cli/init.ts +4 -0
  67. package/src/cli/link-enrollment.ts +152 -25
  68. package/src/cli/link-local-control.ts +49 -0
  69. package/src/cli/link.ts +37 -10
  70. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  71. package/src/cli/registry.ts +13 -0
  72. package/src/cli/star-prompt.ts +2 -0
  73. package/src/cli/status.ts +1 -1
  74. package/src/cli/telemetry-profile.ts +206 -0
  75. package/src/cli/telemetry.ts +260 -0
  76. package/src/client/hub-relay.ts +26 -0
  77. package/src/client/machine-api.ts +3 -0
  78. package/src/clients/config-export/t3code.ts +44 -5
  79. package/src/clients/omo-role-models.ts +1 -1
  80. package/src/codex/catalog/bundled.ts +44 -2
  81. package/src/codex/runtime.ts +12 -0
  82. package/src/codex/shim-restore-lock.ts +67 -30
  83. package/src/combos/types.ts +21 -1
  84. package/src/config/atomic-write.ts +24 -1
  85. package/src/config/diagnostics.ts +15 -0
  86. package/src/config/live-reconcile.ts +17 -0
  87. package/src/config/load-degrade.ts +16 -0
  88. package/src/config/provider-validation.ts +29 -0
  89. package/src/config/schema/config-schema.ts +24 -0
  90. package/src/config/schema/leaf-validators.ts +17 -0
  91. package/src/config/telemetry-carry.ts +30 -0
  92. package/src/config.ts +13 -1
  93. package/src/generated/compatibility-version.json +405 -153
  94. package/src/generated/model-metadata.ts +3 -3
  95. package/src/integrations/aside-profiles.ts +7 -1
  96. package/src/integrations/owned-refresh.ts +9 -2
  97. package/src/lab/artifacts/secure-fs.ts +12 -11
  98. package/src/lab/fabric/scratch.ts +11 -9
  99. package/src/lab/public/community.ts +2 -3
  100. package/src/lab/public/file-safety.ts +18 -20
  101. package/src/lab/public/mutation-lock.ts +109 -337
  102. package/src/lab/public/private-file.ts +4 -3
  103. package/src/lib/bun-runtime-preflight.ts +1 -1
  104. package/src/lib/codex-catalog-read-only.ts +122 -0
  105. package/src/lib/config-ownership.ts +49 -18
  106. package/src/lib/errors.ts +11 -0
  107. package/src/lib/gcp-adc.ts +167 -48
  108. package/src/lib/jsonc.ts +4 -2
  109. package/src/lib/local-control-socket.ts +88 -0
  110. package/src/lib/privacy.ts +15 -0
  111. package/src/lib/provider-client-headers.ts +3 -0
  112. package/src/lib/token-estimate.ts +13 -2
  113. package/src/link/child-binary-source.ts +228 -0
  114. package/src/link/ephemeral-child.ts +45 -0
  115. package/src/link/remote-plant.ts +306 -0
  116. package/src/link/remote-windows.ts +59 -5
  117. package/src/link/ssh-argv.ts +71 -8
  118. package/src/link/status-projection.ts +2 -0
  119. package/src/link/store.ts +5 -1
  120. package/src/oauth/claude-keychain-read.ts +165 -0
  121. package/src/oauth/local-token-detect.ts +14 -17
  122. package/src/protocols/envelope.ts +20 -2
  123. package/src/providers/api-key-selection.ts +8 -2
  124. package/src/providers/claude-cli-usage-state.ts +93 -0
  125. package/src/providers/github-copilot-auto.ts +25 -5
  126. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  127. package/src/providers/model-rename-fields.ts +3 -0
  128. package/src/providers/quota/vendor-probes-key.ts +23 -4
  129. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  130. package/src/providers/quota/workbuddy.ts +2 -2
  131. package/src/providers/quota.ts +25 -18
  132. package/src/providers/registry/entries-core.ts +7 -4
  133. package/src/providers/registry/entries-extended.ts +39 -7
  134. package/src/providers/registry/model-seeds.ts +10 -2
  135. package/src/providers/resolved-model-policy.ts +4 -0
  136. package/src/providers/routed-config.ts +30 -3
  137. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  138. package/src/providers/vertex-environment-authority.ts +50 -0
  139. package/src/providers/workbuddy-credit-balance.ts +38 -6
  140. package/src/quota-pool/assemble.ts +14 -6
  141. package/src/router.ts +1 -0
  142. package/src/server/adapter-resolve.ts +11 -6
  143. package/src/server/audio-dictation.ts +21 -7
  144. package/src/server/auth-cors.ts +19 -0
  145. package/src/server/background-lifecycle.ts +71 -0
  146. package/src/server/chat-completions.ts +2 -0
  147. package/src/server/claude-messages.ts +30 -3
  148. package/src/server/index/live-sideband.ts +15 -1
  149. package/src/server/index/local-control-listener.ts +515 -0
  150. package/src/server/index/optional-listeners.ts +21 -1
  151. package/src/server/index/serve-options.ts +4 -3
  152. package/src/server/index/websocket-handler.ts +2 -0
  153. package/src/server/index.ts +3 -0
  154. package/src/server/management/combo-routes.ts +6 -1
  155. package/src/server/management/context.ts +1 -0
  156. package/src/server/management/link-child-preflight.ts +74 -0
  157. package/src/server/management/link-enrollment.ts +190 -25
  158. package/src/server/management/link-route-state.ts +6 -1
  159. package/src/server/management/link-routes.ts +27 -9
  160. package/src/server/management/model-rows.ts +4 -0
  161. package/src/server/management/oauth-account-routes.ts +9 -4
  162. package/src/server/management/provider-overwrite-carry.ts +9 -2
  163. package/src/server/management/provider-routes.ts +14 -0
  164. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  165. package/src/server/management/route-registry.ts +7 -0
  166. package/src/server/management/session-routes.ts +4 -1
  167. package/src/server/management/telemetry-routes.ts +37 -0
  168. package/src/server/management/usage-aggregate-cache.ts +290 -67
  169. package/src/server/management-api.ts +11 -2
  170. package/src/server/messages-native-preflight.ts +166 -0
  171. package/src/server/messages-native.ts +143 -43
  172. package/src/server/messages-shared.ts +14 -0
  173. package/src/server/proxy-liveness.ts +99 -6
  174. package/src/server/request-log-conversation.ts +18 -2
  175. package/src/server/request-log.ts +7 -2
  176. package/src/server/responses/adapter-continuation.ts +1 -0
  177. package/src/server/responses/adapter-dispatch.ts +11 -28
  178. package/src/server/responses/adapter-failure-message.ts +68 -0
  179. package/src/server/responses/combo-stream-preflight.ts +14 -2
  180. package/src/server/responses/core-auth.ts +26 -5
  181. package/src/server/responses/core-codex-account.ts +8 -1
  182. package/src/server/responses/core-combo-failure.ts +6 -1
  183. package/src/server/responses/core-combo-native.ts +150 -37
  184. package/src/server/responses/core-combo.ts +15 -9
  185. package/src/server/responses/core-normalize.ts +1 -0
  186. package/src/server/responses/core-options.ts +7 -1
  187. package/src/server/responses/core-pipeline.ts +21 -1
  188. package/src/server/responses/fetch-helpers.ts +5 -0
  189. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  190. package/src/server/responses/passthrough-delivery.ts +8 -1
  191. package/src/server/responses/passthrough-error.ts +22 -0
  192. package/src/server/responses/request-prepare.ts +7 -1
  193. package/src/server/responses/request-transport.ts +28 -5
  194. package/src/server/responses/run-turn-execution.ts +13 -0
  195. package/src/server/sse-frame-buffer.ts +5 -0
  196. package/src/server/ws-bridge.ts +10 -0
  197. package/src/service/launchd.ts +78 -4
  198. package/src/telemetry/aggregate.ts +348 -0
  199. package/src/telemetry/consent.ts +128 -0
  200. package/src/telemetry/contract.ts +403 -0
  201. package/src/telemetry/disclosure.ts +19 -0
  202. package/src/telemetry/install-id.ts +226 -0
  203. package/src/telemetry/payload.ts +129 -0
  204. package/src/telemetry/profile/client.ts +150 -0
  205. package/src/telemetry/profile/contract.ts +288 -0
  206. package/src/telemetry/profile/disclosure.ts +14 -0
  207. package/src/telemetry/profile/paths.ts +13 -0
  208. package/src/telemetry/profile/routes.ts +99 -0
  209. package/src/telemetry/profile/service.ts +234 -0
  210. package/src/telemetry/profile/state.ts +189 -0
  211. package/src/telemetry/profile/sync.ts +276 -0
  212. package/src/telemetry/routes.ts +183 -0
  213. package/src/telemetry/scheduler.ts +386 -0
  214. package/src/telemetry/sender.ts +97 -0
  215. package/src/telemetry/state.ts +334 -0
  216. package/src/types/combo-jev-effort-mode.ts +11 -0
  217. package/src/types/config.ts +3 -0
  218. package/src/types/provider.ts +11 -1
  219. package/src/types/request.ts +2 -0
  220. package/src/types/telemetry.ts +15 -0
  221. package/src/types/wire.ts +10 -0
  222. package/src/types.ts +5 -0
  223. package/src/update/index.ts +7 -1
  224. package/src/update/minisign.d.mts +17 -0
  225. package/src/update/minisign.mjs +88 -0
  226. package/src/update/signed-supply.d.mts +59 -0
  227. package/src/update/signed-supply.mjs +289 -0
  228. package/src/update/trust-root.json +38 -0
  229. package/src/update/update-bounded-json.d.mts +4 -0
  230. package/src/update/update-bounded-json.mjs +113 -0
  231. package/src/update/update-bytes.d.mts +2 -0
  232. package/src/update/update-bytes.mjs +23 -0
  233. package/src/update/update-candidate-id.d.mts +2 -0
  234. package/src/update/update-candidate-id.mjs +23 -0
  235. package/src/update/update-checkpoint-codec.d.mts +33 -0
  236. package/src/update/update-checkpoint-codec.mjs +217 -0
  237. package/src/update/update-contracts.d.mts +24 -0
  238. package/src/update/update-contracts.mjs +207 -0
  239. package/src/update/update-signature-threshold.d.mts +12 -0
  240. package/src/update/update-signature-threshold.mjs +47 -0
  241. package/src/update/update-signed-version.d.mts +5 -0
  242. package/src/update/update-signed-version.mjs +25 -0
  243. package/src/update/update-trust-anchor.d.mts +2 -0
  244. package/src/update/update-trust-anchor.mjs +2 -0
  245. package/src/usage/cache-diagnostic.ts +195 -50
  246. package/src/usage/expected-prices.ts +20 -2
  247. package/src/usage/filter-index.ts +1469 -0
  248. package/src/usage/ledger-scanner.ts +245 -4
  249. package/src/usage/source-filter.ts +10 -2
  250. package/src/usage/summary.ts +16 -0
  251. package/src/web-search/parse.ts +244 -38
  252. package/gui/dist/assets/App-BepstgEN.js +0 -59
  253. package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
  254. package/gui/dist/assets/index-C-9X2yaI.js +0 -94
  255. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  256. package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
  257. package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
  258. package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
@@ -0,0 +1,306 @@
1
+ import { CHILD_TARGET_TRIPLES, type ChildTargetTriple } from "./child-binary-source";
2
+ import { MANAGED_PURGE_CHILD_MISSING_MARKER, windowsInspectRuntimeArgv, windowsManagedPurgeDisconnectArgv, windowsPlantChildArgv, windowsPurgePlantedChildArgv } from "./remote-windows";
3
+ import { buildExecArgv, REMOTE_SERVED_RUNTIME, remoteServedRuntimeAttempt } from "./ssh-argv";
4
+ import { sshFailureHint, sshRunnerErrorHint, type SshRunner } from "./ssh-runner";
5
+
6
+ export type RemoteRuntimeKind = "full" | "ephemeral" | "missing";
7
+ export type ChildAttachConflictCode = "child_port_busy" | "child_external_provider_conflict";
8
+
9
+ export interface ParsedRemoteRuntimeInspection {
10
+ readonly runtimeKind: RemoteRuntimeKind;
11
+ readonly targetTriple: ChildTargetTriple | null;
12
+ readonly rawArch: string;
13
+ readonly ocxVersionLine: string | null;
14
+ }
15
+
16
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
17
+
18
+ export function parseTargetTriple(platform: "posix" | "windows", rawArch: string): ChildTargetTriple | null {
19
+ const trimmed = rawArch.trim();
20
+ if (platform === "windows") {
21
+ return /^(?:AMD64|x86_64|x64)$/i.test(trimmed) ? "windows-x64" : null;
22
+ }
23
+ const sep = trimmed.indexOf(":");
24
+ if (sep <= 0) return null;
25
+ const kernel = trimmed.slice(0, sep).trim().toLowerCase();
26
+ const machine = trimmed.slice(sep + 1).trim().toLowerCase();
27
+ if (kernel === "darwin") {
28
+ if (machine === "arm64" || machine === "aarch64") return "darwin-arm64";
29
+ if (machine === "x86_64" || machine === "amd64") return "darwin-x64";
30
+ return null;
31
+ }
32
+ if (kernel === "linux") {
33
+ if (machine === "x86_64" || machine === "amd64") return "linux-x64";
34
+ if (machine === "aarch64" || machine === "arm64") return "linux-arm64";
35
+ return null;
36
+ }
37
+ return null;
38
+ }
39
+
40
+ export const POSIX_INSPECT_SCRIPT = [
41
+ "export PATH=\"$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin\"",
42
+ "case \"$(uname -s 2>/dev/null)\" in Windows*|MSYS*|MINGW*|CYGWIN*) exit 125;; esac",
43
+ "printf 'ocx-inspect:uname:%s:%s\\n' \"$(uname -s 2>/dev/null)\" \"$(uname -m 2>/dev/null)\"",
44
+ "ocx_entry=",
45
+ "try_inspect() {",
46
+ " kind=$1; candidate=$2",
47
+ " if [ -x \"$candidate\" ]; then",
48
+ " ver=$(\"$candidate\" ${ocx_entry:+\"$ocx_entry\"} --version 2>/dev/null) || return 0",
49
+ " first=$(printf '%s\\n' \"$ver\" | awk 'NR==1{print; exit}')",
50
+ " if [ -n \"$first\" ]; then",
51
+ " printf 'ocx-inspect:kind:%s\\n' \"$kind\"",
52
+ " printf 'ocx-inspect:version:%s\\n' \"$first\"",
53
+ " exit 0",
54
+ " fi",
55
+ " fi",
56
+ "}",
57
+ "inspect_ocx_child() {",
58
+ " for candidate in \"$HOME/.local/bin/ocx-child\" \"$HOME/.cache/opencodex/bin/ocx-child\"; do",
59
+ " try_inspect ephemeral \"$candidate\"",
60
+ " done",
61
+ " remaining=$PATH",
62
+ " while :; do",
63
+ " directory=${remaining%%:*}",
64
+ " try_inspect ephemeral \"${directory:-.}/ocx-child\"",
65
+ " case \"$remaining\" in *:*) remaining=${remaining#*:};; *) break;; esac",
66
+ " done",
67
+ "}",
68
+ "if [ -f \"${OPENCODEX_HOME:-$HOME/.opencodex}/child/state.json\" ]; then",
69
+ " inspect_ocx_child",
70
+ "fi",
71
+ // #8359: report the install that last started serving this home before any Desktop or PATH copy.
72
+ REMOTE_SERVED_RUNTIME.trimEnd(),
73
+ remoteServedRuntimeAttempt("try_inspect full \"$served_bin\""),
74
+ "for candidate in \"$HOME/.opencodex-desktop/bin/ocx\" \"/Applications/OpenCodex.app/Contents/MacOS/ocx\" \"/usr/bin/ocx\"; do",
75
+ " try_inspect full \"$candidate\"",
76
+ "done",
77
+ "remaining=$PATH",
78
+ "while :; do",
79
+ " directory=${remaining%%:*}",
80
+ " try_inspect full \"${directory:-.}/ocx\"",
81
+ " case \"$remaining\" in *:*) remaining=${remaining#*:};; *) break;; esac",
82
+ "done",
83
+ "inspect_ocx_child",
84
+ "printf 'ocx-inspect:kind:missing\\n'",
85
+ "exit 0",
86
+ ].join("\n");
87
+
88
+ export function remoteInspectRuntimeArgv(platform: "posix" | "windows" = "posix"): string[] {
89
+ return platform === "windows" ? windowsInspectRuntimeArgv() : ["sh", "-c", POSIX_INSPECT_SCRIPT, "ocx-inspect"];
90
+ }
91
+
92
+ export function parseRemoteRuntimeInspection(platform: "posix" | "windows", stdout: string): ParsedRemoteRuntimeInspection | null {
93
+ let rawArch: string | null = null;
94
+ let runtimeKind: RemoteRuntimeKind | null = null;
95
+ let ocxVersionLine: string | null = null;
96
+ for (const raw of stdout.split(/\r?\n/)) {
97
+ const line = raw.trim();
98
+ if (platform === "posix" && line.startsWith("ocx-inspect:uname:")) {
99
+ rawArch = line.slice("ocx-inspect:uname:".length);
100
+ } else if (platform === "windows" && line.startsWith("ocx-inspect:arch:")) {
101
+ rawArch = line.slice("ocx-inspect:arch:".length);
102
+ } else if (line.startsWith("ocx-inspect:kind:")) {
103
+ const kind = line.slice("ocx-inspect:kind:".length);
104
+ if (kind === "full" || kind === "ephemeral" || kind === "missing") runtimeKind = kind;
105
+ } else if (line.startsWith("ocx-inspect:version:")) {
106
+ ocxVersionLine = line.slice("ocx-inspect:version:".length).trim();
107
+ }
108
+ }
109
+ if (rawArch === null || runtimeKind === null) return null;
110
+ if (runtimeKind !== "missing" && !ocxVersionLine) return null;
111
+ const targetTriple = parseTargetTriple(platform, rawArch);
112
+ return { runtimeKind, targetTriple: targetTriple && CHILD_TARGET_TRIPLES.includes(targetTriple) ? targetTriple : null, rawArch, ocxVersionLine };
113
+ }
114
+
115
+ export async function inspectRemoteChildRuntime(
116
+ runner: Pick<SshRunner, "run">,
117
+ alias: string,
118
+ knownHostsFile: string,
119
+ platform: "posix" | "windows",
120
+ timeoutMs = 30_000,
121
+ ): Promise<ParsedRemoteRuntimeInspection | null> {
122
+ const res = await runner.run(buildExecArgv({ alias, argv: remoteInspectRuntimeArgv(platform), knownHostsFile }), { timeoutMs });
123
+ if (res.code !== 0) return null;
124
+ return parseRemoteRuntimeInspection(platform, res.stdout);
125
+ }
126
+
127
+ /** Printed on stderr by the POSIX plant script when no tool can verify the binary's SHA-256. */
128
+ export const PLANT_HASH_TOOL_UNAVAILABLE_MARKER = "ocx-plant-error:hash_tool_unavailable";
129
+
130
+ export const POSIX_PLANT_SCRIPT = [
131
+ "case \"$(uname -s 2>/dev/null)\" in Windows*|MSYS*|MINGW*|CYGWIN*) exit 125;; esac",
132
+ "umask 077",
133
+ "expected_bytes=$1",
134
+ "expected_sha=$2",
135
+ "for p in \"$HOME/.cache\" \"$HOME/.cache/opencodex\" \"$HOME/.cache/opencodex/bin\" \"$HOME/.cache/opencodex/bin/ocx-child\"; do",
136
+ " if [ -L \"$p\" ]; then printf 'Refusing symlink in managed plant path: %s\\n' \"$p\" >&2; exit 1; fi",
137
+ "done",
138
+ "mkdir -p \"$HOME/.cache/opencodex/bin\" || exit 1",
139
+ "chmod 0700 \"$HOME/.cache/opencodex\" \"$HOME/.cache/opencodex/bin\" 2>/dev/null || true",
140
+ "dest=\"$HOME/.cache/opencodex/bin/ocx-child\"",
141
+ "tmp=\"$HOME/.cache/opencodex/bin/.ocx-child.tmp.$$\"",
142
+ "trap 'rm -f \"$tmp\"' EXIT HUP INT TERM",
143
+ "cat > \"$tmp\" || exit 1",
144
+ "actual_bytes=$(wc -c < \"$tmp\" | awk '{print $1}') || exit 1",
145
+ "if [ \"$actual_bytes\" != \"$expected_bytes\" ]; then",
146
+ " printf 'Planted binary size mismatch: expected %s got %s\\n' \"$expected_bytes\" \"$actual_bytes\" >&2",
147
+ " exit 1",
148
+ "fi",
149
+ // The digest must be checked before the binary is ever executed; with no tool to check it the
150
+ // plant fails closed and the temporary file is removed by the EXIT trap.
151
+ "if command -v sha256sum >/dev/null 2>&1; then",
152
+ " actual_sha=$(sha256sum \"$tmp\" | awk '{print tolower($1)}')",
153
+ "elif command -v shasum >/dev/null 2>&1; then",
154
+ " actual_sha=$(shasum -a 256 \"$tmp\" | awk '{print tolower($1)}')",
155
+ "elif command -v openssl >/dev/null 2>&1; then",
156
+ " actual_sha=$(openssl dgst -sha256 \"$tmp\" | awk '{print tolower($NF)}')",
157
+ "else",
158
+ ` printf '${PLANT_HASH_TOOL_UNAVAILABLE_MARKER}\\nNo sha256sum, shasum, or openssl on this host to verify the ocx-child binary.\\n' >&2`,
159
+ " exit 3",
160
+ "fi",
161
+ "if [ \"$actual_sha\" != \"$expected_sha\" ]; then printf 'Planted binary SHA-256 mismatch\\n' >&2; exit 1; fi",
162
+ "chmod 0700 \"$tmp\" || exit 1",
163
+ "mv -f \"$tmp\" \"$dest\" || exit 1",
164
+ "trap - EXIT HUP INT TERM",
165
+ "if ! \"$dest\" --version >/dev/null 2>&1; then",
166
+ " rm -f \"$dest\"",
167
+ " printf 'Planted ocx-child failed --version verification\\n' >&2",
168
+ " exit 1",
169
+ "fi",
170
+ "exit 0",
171
+ ].join("\n");
172
+
173
+ export function remotePlantChildArgv(
174
+ platform: "posix" | "windows",
175
+ expectedBytes: number,
176
+ expectedSha256: string,
177
+ ): string[] {
178
+ if (!Number.isSafeInteger(expectedBytes) || expectedBytes <= 0 || expectedBytes > 32 * 1024 * 1024) {
179
+ throw new Error("invalid expectedBytes for ocx-child plant");
180
+ }
181
+ if (!SHA256_HEX.test(expectedSha56Safe(expectedSha256))) throw new Error("invalid expectedSha256 for ocx-child plant");
182
+ return platform === "windows"
183
+ ? windowsPlantChildArgv(expectedBytes, expectedSha256)
184
+ : ["sh", "-c", POSIX_PLANT_SCRIPT, "ocx-plant", String(expectedBytes), expectedSha256];
185
+ }
186
+
187
+ function expectedSha56Safe(v: string): string { return v; }
188
+
189
+ export const POSIX_PURGE_PLANTED_SCRIPT = [
190
+ "case \"$(uname -s 2>/dev/null)\" in Windows*|MSYS*|MINGW*|CYGWIN*) exit 125;; esac",
191
+ "for p in \"$HOME/.cache\" \"$HOME/.cache/opencodex\" \"$HOME/.cache/opencodex/bin\" \"$HOME/.cache/opencodex/bin/ocx-child\"; do",
192
+ " if [ -L \"$p\" ]; then exit 1; fi",
193
+ "done",
194
+ "dest=\"$HOME/.cache/opencodex/bin/ocx-child\"",
195
+ "child_dir=\"${OPENCODEX_HOME:-$HOME/.opencodex}/child\"",
196
+ "codex_home=\"${CODEX_HOME:-$HOME/.codex}\"",
197
+ // Any record ocx-child keeps until an attach, sync, or detach finishes means the binary is still
198
+ // the only way to recover, so it stays and the rollback reports a residual.
199
+ "recovery_pending() {",
200
+ " for f in \"$child_dir/state.json\" \"$child_dir/codex-journal.json\" \"$child_dir/attach-rollback.json\" \"$codex_home/.ocx-child-owner.json\"; do",
201
+ " if [ -e \"$f\" ] || [ -L \"$f\" ]; then printf 'ocx-child recovery record remains at %s; keeping the planted binary for detach.\\n' \"$f\" >&2; return 0; fi",
202
+ " done",
203
+ " return 1",
204
+ "}",
205
+ "if [ -f \"$dest\" ]; then",
206
+ " if [ -x \"$dest\" ]; then",
207
+ " \"$dest\" detach --purge >/dev/null || exit $?",
208
+ " rm -f \"$dest\" 2>/dev/null || true",
209
+ " elif recovery_pending; then",
210
+ " exit 1",
211
+ " else",
212
+ " rm -f \"$dest\" 2>/dev/null || true",
213
+ " fi",
214
+ "elif recovery_pending; then",
215
+ " exit 1",
216
+ "fi",
217
+ "rmdir \"$HOME/.cache/opencodex/bin\" \"$HOME/.cache/opencodex\" 2>/dev/null || true",
218
+ "exit 0",
219
+ ].join("\n");
220
+
221
+ export function remotePurgePlantedChildArgv(platform: "posix" | "windows" = "posix"): string[] {
222
+ return platform === "windows"
223
+ ? windowsPurgePlantedChildArgv()
224
+ : ["sh", "-c", POSIX_PURGE_PLANTED_SCRIPT, "ocx-purge-plant"];
225
+ }
226
+
227
+ /**
228
+ * Runs disconnect through the managed planted binary only. A PATH or ~/.local/bin candidate cannot
229
+ * purge itself (it lives outside the managed directory), so the generic resolver is never used here.
230
+ */
231
+ export const POSIX_MANAGED_PURGE_DISCONNECT_SCRIPT = [
232
+ "case \"$(uname -s 2>/dev/null)\" in Windows*|MSYS*|MINGW*|CYGWIN*) exit 125;; esac",
233
+ "for p in \"$HOME/.cache\" \"$HOME/.cache/opencodex\" \"$HOME/.cache/opencodex/bin\" \"$HOME/.cache/opencodex/bin/ocx-child\"; do",
234
+ " if [ -L \"$p\" ]; then printf 'Refusing symlink in managed plant path: %s\\n' \"$p\" >&2; exit 1; fi",
235
+ "done",
236
+ "dest=\"$HOME/.cache/opencodex/bin/ocx-child\"",
237
+ `if [ ! -f "$dest" ] || [ ! -x "$dest" ]; then printf '${MANAGED_PURGE_CHILD_MISSING_MARKER}\\n' >&2; exit 1; fi`,
238
+ "exec \"$dest\" disconnect --purge --json",
239
+ ].join("\n");
240
+
241
+ export function remoteManagedPurgeDisconnectArgv(platform: "posix" | "windows" = "posix"): string[] {
242
+ return platform === "windows"
243
+ ? windowsManagedPurgeDisconnectArgv()
244
+ : ["sh", "-c", POSIX_MANAGED_PURGE_DISCONNECT_SCRIPT, "ocx-managed-purge"];
245
+ }
246
+
247
+ /** The `purged` flag from `ocx-child disconnect --json`, or null when no such report was printed. */
248
+ export function parsePurgeDisconnectReport(stdout: string): boolean | null {
249
+ for (const raw of stdout.split(/\r?\n/).reverse()) {
250
+ const line = raw.trim();
251
+ if (!line.startsWith("{")) continue;
252
+ try {
253
+ const parsed: unknown = JSON.parse(line);
254
+ if (parsed && typeof parsed === "object" && typeof (parsed as { purged?: unknown }).purged === "boolean") return (parsed as { purged: boolean }).purged;
255
+ } catch { /* not the report line */ }
256
+ }
257
+ return null;
258
+ }
259
+
260
+ export type PurgeDisconnectOutcome =
261
+ | { readonly ok: true }
262
+ | { readonly ok: false; readonly status: number; readonly code: string; readonly message: string; readonly hint?: string };
263
+
264
+ /**
265
+ * Disconnect with --purge. A link enrolled before childKind existed is inspected first; only an
266
+ * ocx-child Child can be purged, and success requires the binary's own report that it was removed.
267
+ */
268
+ export async function purgeDisconnectRemote(
269
+ runner: Pick<SshRunner, "run">,
270
+ alias: string,
271
+ knownHostsFile: string,
272
+ platform: "posix" | "windows",
273
+ childKind: "ephemeral" | "full" | undefined,
274
+ ): Promise<PurgeDisconnectOutcome> {
275
+ const failed = (message: string, hint?: string): PurgeDisconnectOutcome => ({ ok: false, status: 502, code: "remote_disconnect_failed", message, ...(hint ? { hint } : {}) });
276
+ let kind = childKind;
277
+ if (kind === undefined) {
278
+ let inspected: ParsedRemoteRuntimeInspection | null;
279
+ try { inspected = await inspectRemoteChildRuntime(runner, alias, knownHostsFile, platform); } catch (error) { return failed("The Child runtime could not be inspected, so --purge was not attempted.", sshRunnerErrorHint(error) ?? "child_kind_unknown"); }
280
+ if (!inspected || inspected.runtimeKind === "missing") return failed("The Child runtime could not be identified, so --purge was not attempted.", "child_kind_unknown");
281
+ kind = inspected.runtimeKind;
282
+ }
283
+ if (kind !== "ephemeral") {
284
+ return { ok: false, status: 409, code: "purge_unsupported", message: "This Child runs a full OpenCodex install; --purge removes only a planted ocx-child. Disconnect without --purge." };
285
+ }
286
+ let result;
287
+ try { result = await runner.run(buildExecArgv({ alias, argv: remoteManagedPurgeDisconnectArgv(platform), knownHostsFile }), { timeoutMs: 30_000 }); } catch (error) { return failed("The remote client could not be disconnected.", sshRunnerErrorHint(error)); }
288
+ if (result.code !== 0) {
289
+ if (result.stderr.includes(MANAGED_PURGE_CHILD_MISSING_MARKER)) return failed("No planted ocx-child was found in the managed directory, so nothing was purged.", "managed_child_missing");
290
+ return failed("The remote client could not be disconnected.", sshFailureHint(result.stderr));
291
+ }
292
+ if (parsePurgeDisconnectReport(result.stdout) !== true) return failed("The Child disconnected but did not report removing the planted ocx-child binary.", "purge_incomplete");
293
+ return { ok: true };
294
+ }
295
+
296
+ /** The distinct reason a plant failed on the Child, when the plant script reported one. */
297
+ export function classifyPlantFailure(stderr: string): "hash_tool_unavailable" | null {
298
+ return stderr.includes(PLANT_HASH_TOOL_UNAVAILABLE_MARKER) ? "hash_tool_unavailable" : null;
299
+ }
300
+
301
+ export function classifyChildAttachConflict(stderr: string): ChildAttachConflictCode | null {
302
+ if (stderr.includes("ocx-child-conflict:child_port_busy:")) return "child_port_busy";
303
+ if (stderr.includes("ocx-child-conflict:child_external_provider_conflict:")) return "child_external_provider_conflict";
304
+ return null;
305
+ }
306
+
@@ -144,18 +144,72 @@ export function windowsNativeArgv(executable: string, args: readonly string[]):
144
144
  * Desktop first, then the GOAT-managed current junction, then legacy and PATH candidates. Each
145
145
  * must answer --version within ten seconds; only the selected one runs the real command.
146
146
  */
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")
148
- if($env:LOCALAPPDATA){$c+="$env:LOCALAPPDATA\Programs\OpenCodex\ocx.exe"}
149
- if($env:ProgramFiles){$c+="$env:ProgramFiles\OpenCodex\ocx.exe"}
150
- $c+=@((Get-Command ocx.exe -Type Application -EA 0).Source)
147
+ const OCX_CANDIDATES = String.raw`$u=$env:USERPROFILE;$f=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe")
148
+ if($env:LOCALAPPDATA){$f+="$env:LOCALAPPDATA\Programs\OpenCodex\ocx.exe"}
149
+ if($env:ProgramFiles){$f+="$env:ProgramFiles\OpenCodex\ocx.exe"}
150
+ $f+=@((Get-Command ocx.exe -Type Application -EA 0).Source)
151
+ $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)
152
+ $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}
151
153
  `;
152
154
  export function windowsOcxArgv(args: readonly string[]): string[] {
155
+ 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=$_}}}}}};` : "";
156
+ const run = sweep ? `try{$c=[OcxJob]::Run($x,((@($x)+$d.args|%{Quote-Native $_}) -join ' '))}catch{Fail};${sweep}exit $c` : `Invoke-Native $x @($d.args)`;
153
157
  return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + String.raw`
154
- foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){Invoke-Native $x @($d.args)}}
158
+ foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){` + run + String.raw`}}
155
159
  [Console]::Error.WriteLine('No runnable ocx.exe found; install the Windows standalone archive.');exit 127
156
160
  `);
157
161
  }
158
162
 
163
+ export function windowsInspectRuntimeArgv(): string[] {
164
+ return packedPowerShellArgv(NATIVE_PROCESS + OCX_CANDIDATES + String.raw`
165
+ [Console]::Out.WriteLine('ocx-inspect:arch:'+[string]$env:PROCESSOR_ARCHITECTURE)
166
+ 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}}
167
+ [Console]::Out.WriteLine('ocx-inspect:kind:missing');exit 0
168
+ `);
169
+ }
170
+
171
+ const WINDOWS_MANAGED_BIN = String.raw`function Resolve-PlantDir{
172
+ $r=if($env:LOCALAPPDATA){$env:LOCALAPPDATA}else{$env:USERPROFILE};$subs=if($env:LOCALAPPDATA){@('opencodex','bin')}else{@('.cache','opencodex','bin')};$cur=$r
173
+ foreach($s in $subs){$cur="$cur\$s";if([IO.Directory]::Exists($cur)-or[IO.File]::Exists($cur)){if((([IO.FileSystemInfo](Get-Item -LiteralPath $cur -Force)).Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw 'reparse'}}else{[IO.Directory]::CreateDirectory($cur)|Out-Null}}
174
+ $dst="$cur\ocx-child.exe";if([IO.File]::Exists($dst)-or[IO.Directory]::Exists($dst)){if((([IO.FileSystemInfo](Get-Item -LiteralPath $dst -Force)).Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw 'reparse'}}
175
+ return $cur}
176
+ `;
177
+
178
+ export function windowsPlantChildArgv(expectedBytes: number, expectedSha256: string): string[] {
179
+ return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: [String(expectedBytes), expectedSha256] }) + WINDOWS_MANAGED_BIN + String.raw`
180
+ $tmp=$null;try{$dir=Resolve-PlantDir;$dst="$dir\ocx-child.exe";$lim=[int]$d.args[0];$exp=$d.args[1]
181
+ $tmp="$dir\.ocx-child.tmp.$PID.$([Guid]::NewGuid().ToString('N').Substring(0,8)).exe"
182
+ $in=[Console]::OpenStandardInput();$fs=[IO.File]::Open($tmp,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None);$h=[Security.Cryptography.SHA256]::Create();$buf=New-Object byte[] 16384;$tot=0
183
+ try{while(($n=$in.Read($buf,0,$buf.Length)) -gt 0){$tot+=$n;if($tot -gt $lim){throw 'size'};$fs.Write($buf,0,$n);[void]$h.TransformBlock($buf,0,$n,$null,0)};[void]$h.TransformFinalBlock($buf,0,0)}finally{$fs.Dispose()}
184
+ $sha=([BitConverter]::ToString($h.Hash)).Replace('-','').ToLowerInvariant();$h.Dispose()
185
+ if($tot -ne $lim -or $sha -ne $exp){throw 'integrity'}
186
+ [IO.File]::Copy($tmp,$dst,$true);[IO.File]::Delete($tmp);$tmp=$null
187
+ $rc=[OcxJob]::Run($dst,('"'+$dst+'" --version'));if($rc -ne 0){[IO.File]::Delete($dst);exit 1};exit 0
188
+ }catch{if($tmp -and [IO.File]::Exists($tmp)){try{[IO.File]::Delete($tmp)}catch{$null=$_}};[Console]::Error.WriteLine('Windows ocx-child plant failed.');exit 1}
189
+ `);
190
+ }
191
+
192
+ export function windowsPurgePlantedChildArgv(): string[] {
193
+ return packedPowerShellArgv(NATIVE_PROCESS + WINDOWS_MANAGED_BIN + String.raw`
194
+ $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"}
195
+ $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.'}
196
+ 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};try{[IO.File]::Delete($dst)}catch{$null=$_}}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
197
+ `);
198
+ }
199
+
200
+ /** Printed on stderr when the managed plant directory holds no runnable ocx-child to purge. */
201
+ export const MANAGED_PURGE_CHILD_MISSING_MARKER = "ocx-purge-error:managed_child_missing";
202
+
203
+ /** Runs `disconnect --purge --json` through the planted %LOCALAPPDATA% binary, never a PATH candidate. */
204
+ export function windowsManagedPurgeDisconnectArgv(): string[] {
205
+ return packedPowerShellArgv(NATIVE_PROCESS + WINDOWS_MANAGED_BIN + String.raw`
206
+ try{$dir=Resolve-PlantDir}catch{[Console]::Error.WriteLine('Refusing a reparse point in the managed ocx-child directory.');exit 1}
207
+ $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}
208
+ try{$rc=[OcxJob]::Run($dst,('"'+$dst+'" disconnect --purge --json'))}catch{exit 1}
209
+ Get-ChildItem -LiteralPath $dir -Filter '.ocx-child.purge.*.old' -Force -EA 0|%{try{[IO.File]::Delete($_.FullName)}catch{$null=$_}};exit $rc
210
+ `);
211
+ }
212
+
159
213
  export function windowsPinnedSyncArgv(linkId: string): string[] {
160
214
  return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json"] }) + OCX_CANDIDATES + String.raw`
161
215
  foreach($x in ($c|select -Unique)){
@@ -143,10 +143,72 @@ export const REMOTE_PLATFORM_UNSUPPORTED = 125;
143
143
  /**
144
144
  * The remote sh script for every ocx call. `quoteRemote` single-quotes it, so the login shell
145
145
  * passes it through untouched and `$HOME`/`$PATH` expand in the remote `sh`; the arguments reach
146
- * ocx as `"$@"` without another round of parsing. Desktop binaries precede PATH candidates;
147
- * each candidate must run --version successfully. A missing runnable ocx exits 127.
146
+ * ocx as `"$@"` without another round of parsing. After an ephemeral ocx-child, the install that
147
+ * last started serving this home comes first (#8359): every `ocx start` that binds records its own
148
+ * relaunch argv at the front of `serving-runtimes.json` (src/config/serving-runtimes.ts), `[ocx]`
149
+ * for a compiled binary or `[bun, cli/index.ts]` for a package install. Only the first entry's
150
+ * `command`, one or two absolute paths without quotes or backslashes, is read; any other shape
151
+ * falls through. Desktop binaries then precede PATH candidates; each candidate must run --version
152
+ * successfully. A missing runnable ocx exits 127.
148
153
  */
149
- const REMOTE_OCX_CANDIDATES = `for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
154
+ /**
155
+ * Reads the first \`command\` of \`serving-runtimes.json\` (#8359): one or two absolute paths without
156
+ * quotes or backslashes, printed one per line, from a file of at most 64 KiB. Any other shape fails.
157
+ * Shared by the ocx discovery, pinned sync and runtime inspection scripts.
158
+ */
159
+ export const REMOTE_SERVED_RUNTIME = `served_runtime() {
160
+ [ -f "$1" ] || return 1
161
+ [ "$(wc -c < "$1" 2>/dev/null)" -le 65536 ] 2>/dev/null || return 1
162
+ awk '
163
+ !open { if ($0 ~ /"command": \\[$/) open = 1; next }
164
+ $0 ~ /^ *\\],?$/ { closed = 1; exit }
165
+ {
166
+ line = $0; sub(/^ +/, "", line); sub(/,$/, "", line)
167
+ if (line !~ /^"\\/[^"\\\\]*"$/ || ++count > 2) { bad = 1; exit }
168
+ print substr(line, 2, length(line) - 2)
169
+ }
170
+ END { if (bad || !closed || !count) exit 1 }
171
+ ' "$1"
172
+ }
173
+ `;
174
+
175
+ /**
176
+ * Tries the served install with \`attempt\`, which must read \`$served_bin\` and honour \`$ocx_entry\`:
177
+ * a compiled binary runs alone, and a package pair runs as \`bun <entry>\` only while the entry exists.
178
+ */
179
+ export function remoteServedRuntimeAttempt(attempt: string): string {
180
+ return `served_bin= served_entry=
181
+ if served=$(served_runtime "\${OPENCODEX_HOME:-$HOME/.opencodex}/serving-runtimes.json"); then
182
+ { IFS= read -r served_bin; IFS= read -r served_entry; } <<OCX_SERVED
183
+ $served
184
+ OCX_SERVED
185
+ if [ -z "$served_entry" ]; then
186
+ ${attempt}
187
+ elif [ -f "$served_entry" ]; then
188
+ ocx_entry=$served_entry
189
+ ${attempt}
190
+ ocx_entry=
191
+ fi
192
+ fi`;
193
+ }
194
+
195
+ const REMOTE_OCX_CANDIDATES = `ocx_entry=
196
+ ${REMOTE_SERVED_RUNTIME}run_ocx_child() {
197
+ for candidate in "$HOME/.local/bin/ocx-child" "$HOME/.cache/opencodex/bin/ocx-child"; do
198
+ try_ocx "$candidate" "$@"
199
+ done
200
+ remaining=$PATH
201
+ while :; do
202
+ directory=\${remaining%%:*}
203
+ try_ocx "\${directory:-.}/ocx-child" "$@"
204
+ case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
205
+ done
206
+ }
207
+ if [ -f "\${OPENCODEX_HOME:-$HOME/.opencodex}/child/state.json" ]; then
208
+ run_ocx_child "$@"
209
+ fi
210
+ ${remoteServedRuntimeAttempt('try_ocx "$served_bin" "$@"')}
211
+ for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do
150
212
  try_ocx "$candidate" "$@"
151
213
  done
152
214
  remaining=$PATH
@@ -154,15 +216,16 @@ while :; do
154
216
  directory=\${remaining%%:*}
155
217
  try_ocx "\${directory:-.}/ocx" "$@"
156
218
  case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac
157
- done`;
219
+ done
220
+ run_ocx_child "$@"`;
158
221
 
159
222
  export const REMOTE_OCX_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"
160
223
  case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac
161
224
  try_ocx() {
162
- if [ -x "$1" ] && "$1" --version >/dev/null 2>&1; then
225
+ if [ -x "$1" ] && "$1" \${ocx_entry:+"$ocx_entry"} --version >/dev/null 2>&1; then
163
226
  executable=$1
164
227
  shift
165
- exec "$executable" "$@"
228
+ exec "$executable" \${ocx_entry:+"$ocx_entry"} "$@"
166
229
  fi
167
230
  }
168
231
  ${REMOTE_OCX_CANDIDATES}
@@ -250,7 +313,7 @@ trap 'rm -rf "$dir"' EXIT HUP INT TERM
250
313
  try_ocx() {
251
314
  c=$1; shift
252
315
  [ -x "$c" ] || return
253
- ( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null & vp=$!
316
+ ( ulimit -c 0; ulimit -f 1; exec "$c" \${ocx_entry:+"$ocx_entry"} --version ) >"$tmp" 2>/dev/null & vp=$!
254
317
  ( 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
318
  while [ ! -f "$ready" ]; do kill -0 "$watchdog" 2>/dev/null || break; sleep 0.01 >/dev/null 2>&1; done
256
319
  { wait "$vp"; status=$?; } 2>/dev/null
@@ -283,7 +346,7 @@ try_ocx() {
283
346
  rm -rf "$dir"; trap - EXIT HUP INT TERM
284
347
  printf 'ocx-fanout:selected:%s\\n' "$version" >&2
285
348
  printf '%s\\n' 'ocx-fanout:stdout-begin'
286
- exec "$c" sync --expect-link "$1" --json
349
+ exec "$c" \${ocx_entry:+"$ocx_entry"} sync --expect-link "$1" --json
287
350
  }
288
351
  ${REMOTE_OCX_CANDIDATES}
289
352
  exit ${REMOTE_COMMAND_NOT_FOUND}`;
@@ -20,6 +20,7 @@ export interface LinkStatusDto {
20
20
  since: string;
21
21
  reason: string | null;
22
22
  tunnelPort: number;
23
+ childKind?: "full" | "ephemeral";
23
24
  /** Home only: what the link carried from this Child, and the compatibility verdict. */
24
25
  peer?: LinkPeerStatus;
25
26
  /** Home-initiated links on request (`?diagnostics=1`): retry progress and the last failure. */
@@ -140,6 +141,7 @@ export function projectLinkStatus(
140
141
  direction: record.direction,
141
142
  ...stateDetails(record, byId.get(record.id), compensation),
142
143
  tunnelPort: record.tunnelPort,
144
+ ...(record.childKind ? { childKind: record.childKind } : {}),
143
145
  ...parity(record.id),
144
146
  }));
145
147
  const childRecord = config.runtimeRole === "client"
package/src/link/store.ts CHANGED
@@ -12,6 +12,7 @@ import { assertSshAlias } from "./ssh-argv";
12
12
  * It never holds a key: keys live in the running proxy's `apiKeys`, and admission reads them there.
13
13
  */
14
14
  export type LinkDirection = "hub-initiated" | "client-initiated";
15
+ export type LinkChildKind = "full" | "ephemeral";
15
16
 
16
17
  export interface LinkRecord {
17
18
  id: string;
@@ -28,6 +29,7 @@ export interface LinkRecord {
28
29
  apiKeyId: string;
29
30
  createdAt: string;
30
31
  remotePlatform?: "posix" | "windows";
32
+ childKind?: LinkChildKind;
31
33
  }
32
34
 
33
35
  export interface LinkStore {
@@ -52,7 +54,7 @@ export function newLinkId(): string {
52
54
  return `lnk_${randomBytes(8).toString("hex")}`;
53
55
  }
54
56
 
55
- const RECORD_KEYS = new Set(["id", "alias", "direction", "hostKeyFingerprint", "tunnelPort", "apiKeyId", "createdAt", "remotePlatform"]);
57
+ const RECORD_KEYS = new Set(["id", "alias", "direction", "hostKeyFingerprint", "tunnelPort", "apiKeyId", "createdAt", "remotePlatform", "childKind"]);
56
58
  const STORE_KEYS = new Set(["version", "listenerPort", "links"]);
57
59
  const API_KEY_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/;
58
60
  const FINGERPRINT = /^[A-Z0-9]+:[A-Za-z0-9+/=]{16,128}$/;
@@ -77,6 +79,7 @@ function parseRecord(value: unknown, index: number): LinkRecord {
77
79
  try { assertSshAlias(raw.alias as string); } catch { fail("alias"); }
78
80
  if (raw.direction !== "hub-initiated" && raw.direction !== "client-initiated") fail("direction");
79
81
  if (raw.remotePlatform !== undefined && raw.remotePlatform !== "posix" && raw.remotePlatform !== "windows") fail("remotePlatform");
82
+ if (raw.childKind !== undefined && raw.childKind !== "full" && raw.childKind !== "ephemeral") fail("childKind");
80
83
  const fingerprint = raw.hostKeyFingerprint;
81
84
  if (fingerprint === null ? raw.direction !== "client-initiated"
82
85
  : typeof fingerprint !== "string" || !FINGERPRINT.test(fingerprint)) fail("hostKeyFingerprint");
@@ -92,6 +95,7 @@ function parseRecord(value: unknown, index: number): LinkRecord {
92
95
  apiKeyId: raw.apiKeyId as string,
93
96
  createdAt: raw.createdAt as string,
94
97
  ...(raw.remotePlatform === undefined ? {} : { remotePlatform: raw.remotePlatform as "posix" | "windows" }),
98
+ ...(raw.childKind === undefined ? {} : { childKind: raw.childKind as LinkChildKind }),
95
99
  };
96
100
  }
97
101