@bitkyc08/opencodex 2.99.0 → 2.100.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 (276) 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-g3Cm2xhZ.js +59 -0
  7. package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
  8. package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
  9. package/gui/dist/assets/index-Bziu8gTy.css +2 -0
  10. package/gui/dist/assets/index-OYzhQUNP.js +94 -0
  11. package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
  12. package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
  14. package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.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-image-normalize.ts +1 -1
  38. package/src/adapters/anthropic.ts +28 -2
  39. package/src/adapters/claude-cli/adapter.ts +5 -25
  40. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  41. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  42. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  43. package/src/adapters/client-fingerprint.ts +1 -1
  44. package/src/adapters/coding-agent/protocol.ts +1 -1
  45. package/src/adapters/devin/live-models.ts +3 -0
  46. package/src/adapters/google-http.ts +3 -0
  47. package/src/adapters/google-vertex-key-project.ts +10 -2
  48. package/src/adapters/google.ts +40 -8
  49. package/src/adapters/kiro/usage.ts +3 -13
  50. package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
  51. package/src/adapters/openai-chat-images.ts +100 -0
  52. package/src/adapters/openai-chat.ts +6 -9
  53. package/src/adapters/openai-responses/passthrough.ts +5 -2
  54. package/src/adapters/openai-responses/request-strips.ts +32 -0
  55. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  56. package/src/chat/inbound.ts +1 -1
  57. package/src/claude/auth-detect.ts +26 -8
  58. package/src/claude/inbound-content-options.ts +18 -3
  59. package/src/claude/inbound.ts +5 -2
  60. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  61. package/src/cli/capabilities-agents-routing.ts +2 -2
  62. package/src/cli/capabilities-observe-system.ts +60 -0
  63. package/src/cli/combo-input.ts +6 -0
  64. package/src/cli/combo-result.ts +1 -1
  65. package/src/cli/combo.ts +4 -0
  66. package/src/cli/config-command.ts +16 -2
  67. package/src/cli/connect.ts +12 -10
  68. package/src/cli/dispatch.ts +4 -0
  69. package/src/cli/doctor.ts +11 -0
  70. package/src/cli/help.ts +1 -0
  71. package/src/cli/init.ts +4 -0
  72. package/src/cli/link-enrollment.ts +152 -25
  73. package/src/cli/link-local-control.ts +49 -0
  74. package/src/cli/link.ts +37 -10
  75. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  76. package/src/cli/registry.ts +13 -0
  77. package/src/cli/star-prompt.ts +2 -0
  78. package/src/cli/status.ts +1 -1
  79. package/src/cli/telemetry-profile.ts +206 -0
  80. package/src/cli/telemetry.ts +260 -0
  81. package/src/client/hub-relay.ts +26 -0
  82. package/src/client/machine-api.ts +3 -0
  83. package/src/clients/config-export/t3code.ts +44 -5
  84. package/src/clients/omo-role-models.ts +1 -1
  85. package/src/codex/catalog/bundled.ts +44 -2
  86. package/src/codex/runtime.ts +12 -0
  87. package/src/codex/shim-restore-lock.ts +67 -30
  88. package/src/combos/types.ts +21 -1
  89. package/src/config/atomic-write.ts +24 -1
  90. package/src/config/diagnostics.ts +15 -0
  91. package/src/config/live-reconcile.ts +17 -0
  92. package/src/config/load-degrade.ts +16 -0
  93. package/src/config/provider-validation.ts +29 -0
  94. package/src/config/schema/config-schema.ts +24 -0
  95. package/src/config/schema/leaf-validators.ts +17 -0
  96. package/src/config/telemetry-carry.ts +30 -0
  97. package/src/config.ts +13 -1
  98. package/src/generated/compatibility-version.json +422 -170
  99. package/src/generated/model-metadata.ts +3 -3
  100. package/src/integrations/aside-profiles.ts +7 -1
  101. package/src/integrations/owned-refresh.ts +9 -2
  102. package/src/lab/artifacts/secure-fs.ts +12 -11
  103. package/src/lab/fabric/scratch.ts +11 -9
  104. package/src/lab/public/community.ts +2 -3
  105. package/src/lab/public/file-safety.ts +18 -20
  106. package/src/lab/public/mutation-lock.ts +109 -337
  107. package/src/lab/public/private-file.ts +4 -3
  108. package/src/lib/bun-runtime-preflight.ts +1 -1
  109. package/src/lib/codex-catalog-read-only.ts +122 -0
  110. package/src/lib/config-ownership.ts +56 -18
  111. package/src/lib/errors.ts +11 -0
  112. package/src/lib/gcp-adc.ts +167 -48
  113. package/src/lib/jsonc.ts +4 -2
  114. package/src/lib/local-control-socket.ts +88 -0
  115. package/src/lib/privacy.ts +15 -0
  116. package/src/lib/provider-client-headers.ts +3 -0
  117. package/src/lib/token-estimate.ts +13 -2
  118. package/src/link/child-binary-source.ts +228 -0
  119. package/src/link/ephemeral-child.ts +45 -0
  120. package/src/link/remote-plant.ts +306 -0
  121. package/src/link/remote-windows.ts +59 -5
  122. package/src/link/ssh-argv.ts +71 -8
  123. package/src/link/status-projection.ts +2 -0
  124. package/src/link/store.ts +5 -1
  125. package/src/oauth/anthropic-model-quota.ts +12 -0
  126. package/src/oauth/anthropic-routing.ts +11 -4
  127. package/src/oauth/claude-keychain-read.ts +165 -0
  128. package/src/oauth/kiro-iam-identity-center.ts +4 -1
  129. package/src/oauth/local-token-detect.ts +14 -17
  130. package/src/protocols/envelope.ts +20 -2
  131. package/src/providers/api-key-selection.ts +8 -2
  132. package/src/providers/claude-cli-identity.ts +9 -3
  133. package/src/providers/claude-cli-usage-state.ts +93 -0
  134. package/src/providers/claude-cli-usage.ts +3 -2
  135. package/src/providers/github-copilot-auto.ts +25 -5
  136. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  137. package/src/providers/model-rename-fields.ts +3 -0
  138. package/src/providers/quota/anthropic-family-headers.ts +8 -1
  139. package/src/providers/quota/anthropic-usage-windows.ts +49 -2
  140. package/src/providers/quota/vendor-probes-key.ts +23 -4
  141. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  142. package/src/providers/quota/workbuddy.ts +2 -2
  143. package/src/providers/quota-types.ts +7 -0
  144. package/src/providers/quota.ts +25 -18
  145. package/src/providers/registry/entries-core.ts +7 -4
  146. package/src/providers/registry/entries-extended.ts +42 -8
  147. package/src/providers/registry/model-ids.ts +1 -0
  148. package/src/providers/registry/model-seeds.ts +10 -2
  149. package/src/providers/registry/types.ts +6 -0
  150. package/src/providers/resolved-model-policy.ts +4 -0
  151. package/src/providers/routed-config.ts +30 -3
  152. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  153. package/src/providers/vertex-environment-authority.ts +50 -0
  154. package/src/providers/workbuddy-credit-balance.ts +38 -6
  155. package/src/quota-pool/assemble.ts +14 -6
  156. package/src/responses/retained-compaction.ts +31 -5
  157. package/src/router.ts +1 -0
  158. package/src/server/adapter-resolve.ts +11 -6
  159. package/src/server/audio-dictation.ts +21 -7
  160. package/src/server/auth-cors.ts +19 -0
  161. package/src/server/background-lifecycle.ts +71 -0
  162. package/src/server/chat-completions.ts +2 -0
  163. package/src/server/claude-messages.ts +30 -3
  164. package/src/server/index/live-sideband.ts +15 -1
  165. package/src/server/index/local-control-listener.ts +515 -0
  166. package/src/server/index/optional-listeners.ts +21 -1
  167. package/src/server/index/serve-options.ts +4 -3
  168. package/src/server/index/websocket-handler.ts +2 -0
  169. package/src/server/index.ts +3 -0
  170. package/src/server/management/combo-routes.ts +6 -1
  171. package/src/server/management/context.ts +1 -0
  172. package/src/server/management/link-child-preflight.ts +74 -0
  173. package/src/server/management/link-enrollment.ts +190 -25
  174. package/src/server/management/link-route-state.ts +6 -1
  175. package/src/server/management/link-routes.ts +27 -9
  176. package/src/server/management/model-rows.ts +4 -0
  177. package/src/server/management/oauth-account-routes.ts +9 -4
  178. package/src/server/management/provider-overwrite-carry.ts +9 -2
  179. package/src/server/management/provider-routes.ts +14 -0
  180. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  181. package/src/server/management/route-registry.ts +7 -0
  182. package/src/server/management/session-routes.ts +4 -1
  183. package/src/server/management/telemetry-routes.ts +37 -0
  184. package/src/server/management/usage-aggregate-cache.ts +290 -67
  185. package/src/server/management-api.ts +11 -2
  186. package/src/server/messages-native-preflight.ts +166 -0
  187. package/src/server/messages-native.ts +143 -43
  188. package/src/server/messages-shared.ts +14 -0
  189. package/src/server/proxy-liveness.ts +99 -6
  190. package/src/server/request-log-conversation.ts +18 -2
  191. package/src/server/request-log.ts +7 -2
  192. package/src/server/responses/adapter-continuation.ts +1 -0
  193. package/src/server/responses/adapter-dispatch.ts +11 -28
  194. package/src/server/responses/adapter-failure-message.ts +68 -0
  195. package/src/server/responses/combo-stream-preflight.ts +14 -2
  196. package/src/server/responses/compact.ts +13 -1
  197. package/src/server/responses/core-auth.ts +26 -5
  198. package/src/server/responses/core-codex-account.ts +8 -1
  199. package/src/server/responses/core-combo-failure.ts +6 -1
  200. package/src/server/responses/core-combo-native.ts +150 -37
  201. package/src/server/responses/core-combo.ts +15 -9
  202. package/src/server/responses/core-normalize.ts +1 -0
  203. package/src/server/responses/core-options.ts +7 -1
  204. package/src/server/responses/core-pipeline.ts +21 -1
  205. package/src/server/responses/fetch-helpers.ts +5 -0
  206. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  207. package/src/server/responses/passthrough-delivery.ts +8 -1
  208. package/src/server/responses/passthrough-error.ts +22 -0
  209. package/src/server/responses/request-prepare.ts +7 -1
  210. package/src/server/responses/request-transport.ts +28 -5
  211. package/src/server/responses/run-turn-execution.ts +13 -0
  212. package/src/server/sse-frame-buffer.ts +5 -0
  213. package/src/server/ws-bridge.ts +10 -0
  214. package/src/service/launchd.ts +78 -4
  215. package/src/telemetry/aggregate.ts +348 -0
  216. package/src/telemetry/consent.ts +128 -0
  217. package/src/telemetry/contract.ts +403 -0
  218. package/src/telemetry/disclosure.ts +19 -0
  219. package/src/telemetry/install-id.ts +226 -0
  220. package/src/telemetry/payload.ts +129 -0
  221. package/src/telemetry/profile/client.ts +150 -0
  222. package/src/telemetry/profile/contract.ts +288 -0
  223. package/src/telemetry/profile/disclosure.ts +14 -0
  224. package/src/telemetry/profile/paths.ts +13 -0
  225. package/src/telemetry/profile/routes.ts +99 -0
  226. package/src/telemetry/profile/service.ts +234 -0
  227. package/src/telemetry/profile/state.ts +189 -0
  228. package/src/telemetry/profile/sync.ts +276 -0
  229. package/src/telemetry/routes.ts +183 -0
  230. package/src/telemetry/scheduler.ts +386 -0
  231. package/src/telemetry/sender.ts +97 -0
  232. package/src/telemetry/state.ts +334 -0
  233. package/src/types/combo-jev-effort-mode.ts +11 -0
  234. package/src/types/config.ts +3 -0
  235. package/src/types/provider.ts +11 -1
  236. package/src/types/request.ts +2 -0
  237. package/src/types/telemetry.ts +15 -0
  238. package/src/types/wire.ts +10 -0
  239. package/src/types.ts +5 -0
  240. package/src/update/index.ts +7 -1
  241. package/src/update/minisign.d.mts +17 -0
  242. package/src/update/minisign.mjs +88 -0
  243. package/src/update/signed-supply.d.mts +59 -0
  244. package/src/update/signed-supply.mjs +289 -0
  245. package/src/update/trust-root.json +38 -0
  246. package/src/update/update-bounded-json.d.mts +4 -0
  247. package/src/update/update-bounded-json.mjs +113 -0
  248. package/src/update/update-bytes.d.mts +2 -0
  249. package/src/update/update-bytes.mjs +23 -0
  250. package/src/update/update-candidate-id.d.mts +2 -0
  251. package/src/update/update-candidate-id.mjs +23 -0
  252. package/src/update/update-checkpoint-codec.d.mts +33 -0
  253. package/src/update/update-checkpoint-codec.mjs +217 -0
  254. package/src/update/update-contracts.d.mts +24 -0
  255. package/src/update/update-contracts.mjs +207 -0
  256. package/src/update/update-signature-threshold.d.mts +12 -0
  257. package/src/update/update-signature-threshold.mjs +47 -0
  258. package/src/update/update-signed-version.d.mts +5 -0
  259. package/src/update/update-signed-version.mjs +25 -0
  260. package/src/update/update-trust-anchor.d.mts +2 -0
  261. package/src/update/update-trust-anchor.mjs +2 -0
  262. package/src/usage/cache-diagnostic.ts +195 -50
  263. package/src/usage/expected-prices.ts +20 -2
  264. package/src/usage/filter-index.ts +1469 -0
  265. package/src/usage/ledger-scanner.ts +245 -4
  266. package/src/usage/source-filter.ts +10 -2
  267. package/src/usage/summary.ts +16 -0
  268. package/src/web-search/parse.ts +265 -38
  269. package/gui/dist/assets/App-BepstgEN.js +0 -59
  270. package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
  271. package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
  272. package/gui/dist/assets/index-C-9X2yaI.js +0 -94
  273. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  274. package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
  275. package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
  276. package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
@@ -20,6 +20,7 @@ import { linkChildParityRouteAllowed } from "../../link/child-parity";
20
20
  import { saveConfigPreservingClaudeCode } from "../../config/live-reconcile";
21
21
  import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
22
22
  import { startJevQuotaActivation } from "../../combos/jev-quota-activation";
23
+ import { createLocalControlListener } from "./local-control-listener";
23
24
  export { LINK_INGRESS_HOSTNAME } from "./link-listener";
24
25
  import type { ServerIngress } from "./serve-options";
25
26
 
@@ -45,6 +46,12 @@ export interface OptionalListenerSet<T> {
45
46
  linkStatus(): LinkListenerStatus;
46
47
  linkSupervisor(): LinkSupervisor;
47
48
  start(ctx: OptionalListenerStartContext<T>): void;
49
+ /**
50
+ * Synchronous rollback for a startup that failed after `start`. The local control socket holds a
51
+ * live lease, and `startServer` cannot await a teardown, so that lease is released here instead of
52
+ * being left for a successor to mistake for a running runtime.
53
+ */
54
+ abortStart(): void;
48
55
  ensureStarted(): Promise<void>;
49
56
  close(): Promise<void>;
50
57
  registerSupervisorStop(stop: () => Promise<void>): () => void;
@@ -54,6 +61,7 @@ export interface OptionalListenerSet<T> {
54
61
  export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): OptionalListenerSet<T> {
55
62
  const claudeIntercept: ClaudeInterceptLifecycle<T> = createClaudeInterceptLifecycle<T>();
56
63
  const linkListener: LinkListenerLifecycle<T> = createLinkListenerLifecycle<T>(linkDeps);
64
+ const localControl = createLocalControlListener<T>();
57
65
  let activeConfig: OcxConfig | undefined;
58
66
  let stopJevQuotaActivation: (() => void) | undefined;
59
67
  const supervisor = createLinkSupervisor({
@@ -85,6 +93,7 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
85
93
  ingressOf(server) {
86
94
  if (linkListener.ownsListener(server)) return "hub-link";
87
95
  if (claudeIntercept.ownsListener(server)) return "claude-intercept";
96
+ if (localControl.ownsListener(server)) return "local-control";
88
97
  return undefined;
89
98
  },
90
99
  // The Home's link listener admits the data plane plus the read-only management relay
@@ -102,6 +111,7 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
102
111
  linkSupervisor: () => supervisor,
103
112
  start(ctx) {
104
113
  activeConfig = ctx.config;
114
+ localControl.start({ config: ctx.config, publicPort: ctx.publicPort, dispatch: ctx.dispatch });
105
115
  linkListener.start({ dispatch: ctx.dispatch, maxRequestBodySize: ctx.maxRequestBodySize,
106
116
  connectionGeneration: linkId => supervisor.connectionGeneration?.(linkId),
107
117
  keyFingerprints: apiKeyId => {
@@ -129,6 +139,9 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
129
139
  // Last, after every listener started: JEV advisory quota follows the live config while serving.
130
140
  stopJevQuotaActivation = startJevQuotaActivation(ctx.config);
131
141
  },
142
+ abortStart() {
143
+ try { localControl.abort(); } catch { /* the startup error is the one worth reporting */ }
144
+ },
132
145
  ensureStarted: () => linkListener.ensureStarted(),
133
146
  close: () => linkListener.close(),
134
147
  registerSupervisorStop(stop) {
@@ -139,8 +152,15 @@ export function createOptionalListenerSet<T>(linkDeps: LinkListenerDeps = {}): O
139
152
  },
140
153
  async stop() {
141
154
  let failure: unknown;
155
+ // First, before any other await. The local control socket's ownership record is released
156
+ // synchronously inside this call, and the shutdown that follows can take a long time: a
157
+ // supervisor stop over SSH, a link drain, the intercept pair. The public listener is already
158
+ // closed by then, so an independent `ocx start` sees a free port and no runtime record; if
159
+ // the lease were still held by this live pid it would read as a live owner and that
160
+ // successor would refuse the port for good.
161
+ try { await localControl.stop(); } catch (error) { failure = error; }
142
162
  if (supervisorStop) {
143
- try { await supervisorStop(); } catch (error) { failure = error; }
163
+ try { await supervisorStop(); } catch (error) { failure ??= error; }
144
164
  }
145
165
  try { await linkListener.stop(); } catch (error) { failure ??= error; }
146
166
  try { await claudeIntercept.stop(); } catch (error) { failure ??= error; }
@@ -220,10 +220,10 @@ import { withCallerSessionIdentity } from "../caller-session-identity";
220
220
  import { agentAssertionUnsupportedResponse, hasAgentAssertionAuthorization } from "../../lib/authorization-scheme";
221
221
  import { runTurnStateCallerScope } from "../turn-state-handles";
222
222
 
223
- export type ServerIngress = "public" | "unauthenticated-loopback" | "hub-management" | "claude-intercept" | "hub-link";
223
+ export type ServerIngress = "public" | "unauthenticated-loopback" | "hub-management" | "claude-intercept" | "hub-link" | "local-control";
224
224
 
225
225
  export function trustedLoopbackForIngress(ingress: ServerIngress, hostname: string): boolean {
226
- return ingress === "unauthenticated-loopback"
226
+ return ingress === "unauthenticated-loopback" || ingress === "local-control"
227
227
  || (ingress === "public" && isLoopbackHostname(hostname));
228
228
  }
229
229
 
@@ -378,7 +378,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
378
378
  // Anthropic credentials, not opencodex admission tokens — so it takes the loopback view too.
379
379
  const policy: RequestPolicyView = ingress === "hub-link"
380
380
  ? linkPolicyView!
381
- : ingress === "unauthenticated-loopback" || ingress === "claude-intercept"
381
+ : ingress === "unauthenticated-loopback" || ingress === "claude-intercept" || ingress === "local-control"
382
382
  ? loopbackPolicy()
383
383
  : config;
384
384
  // Codex runtime agent assertion_only (Authorization: AgentAssertion) is refused before
@@ -1866,6 +1866,7 @@ export function createServeOptions(ctx: ServeOptionsContext) {
1866
1866
  liveUpstreamProtocols: audio?.protocols,
1867
1867
  liveValidateFrame: audio?.validateFrame,
1868
1868
  liveMaxSessionMs: audio?.maxSessionMs,
1869
+ liveFinalizationMs: audio?.finalizationMs,
1869
1870
  liveFinish: finish,
1870
1871
  liveAbortSignal: audioController?.signal,
1871
1872
  livePending: [],
@@ -10,6 +10,7 @@ import {
10
10
  MAX_WS_FRAME_BYTES,
11
11
  WEBSOCKET_IDLE_TIMEOUT_SECONDS,
12
12
  attachLiveSidebandUpstream,
13
+ beginAudioFinalization,
13
14
  clientCloseForUpstream,
14
15
  closeLiveSideband,
15
16
  closeLiveSidebandBeforeUpgrade,
@@ -157,6 +158,7 @@ export function createWebsocketHandler(
157
158
  closeLiveSideband(ws, 1008, "invalid audio event");
158
159
  return;
159
160
  }
161
+ beginAudioFinalization(ws, raw);
160
162
  const rawBytes = webSocketFrameBytes(raw);
161
163
  if (exceedsLiveSidebandFrameByteLimit(rawBytes)) {
162
164
  closeLiveSideband(ws, 1009, "message too large");
@@ -716,6 +716,9 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
716
716
  userCostOverlayReconciler?.stop();
717
717
  backgroundLifecycle?.releaseAfterFailedStart();
718
718
  void nativeMainLifecycle.release();
719
+ // A later optional listener can still throw after the local control socket started. Its lease
720
+ // is live state, so it has to go synchronously before the startup error propagates.
721
+ optionalListeners.abortStart();
719
722
  throw error;
720
723
  }
721
724
 
@@ -93,13 +93,15 @@ function sparseComboConfig<T extends {
93
93
  imageInput?: "auto" | "disabled";
94
94
  reasoningEffortMode?: "strict" | "adaptive";
95
95
  defaultEffortMode?: "fallback" | "force";
96
- }>(combo: T): Omit<T, "cooldownMs" | "waitForCooldownMs" | "cooldownWaitPolicy" | "imageInput" | "reasoningEffortMode" | "defaultEffortMode"> & {
96
+ jevEffortMode?: "decide" | "client";
97
+ }>(combo: T): Omit<T, "cooldownMs" | "waitForCooldownMs" | "cooldownWaitPolicy" | "imageInput" | "reasoningEffortMode" | "defaultEffortMode" | "jevEffortMode"> & {
97
98
  cooldownMs?: number;
98
99
  waitForCooldownMs?: number;
99
100
  cooldownWaitPolicy?: OcxComboCooldownWaitPolicy;
100
101
  imageInput?: "disabled";
101
102
  reasoningEffortMode?: "adaptive";
102
103
  defaultEffortMode?: "force";
104
+ jevEffortMode?: "client";
103
105
  } {
104
106
  const {
105
107
  cooldownMs,
@@ -108,6 +110,7 @@ function sparseComboConfig<T extends {
108
110
  imageInput,
109
111
  reasoningEffortMode,
110
112
  defaultEffortMode,
113
+ jevEffortMode,
111
114
  ...rest
112
115
  } = combo;
113
116
  return {
@@ -122,6 +125,7 @@ function sparseComboConfig<T extends {
122
125
  ...(imageInput === "disabled" ? { imageInput: "disabled" as const } : {}),
123
126
  ...(reasoningEffortMode === "adaptive" ? { reasoningEffortMode: "adaptive" as const } : {}),
124
127
  ...(defaultEffortMode === "force" ? { defaultEffortMode: "force" as const } : {}),
128
+ ...(jevEffortMode === "client" ? { jevEffortMode: "client" as const } : {}),
125
129
  };
126
130
  }
127
131
 
@@ -227,6 +231,7 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise<Respons
227
231
  ? { cooldownReprobe: previous.cooldownReprobe }
228
232
  : {}),
229
233
  ...(!Object.hasOwn(requestedCombo, "decisionQuotaSignals") && requestedCombo.strategy === "jev" && previous?.decisionQuotaSignals !== undefined ? { decisionQuotaSignals: previous.decisionQuotaSignals } : {}),
234
+ ...(!Object.hasOwn(requestedCombo, "jevEffortMode") && requestedCombo.strategy === "jev" && previous?.jevEffortMode !== undefined ? { jevEffortMode: previous.jevEffortMode } : {}),
230
235
  ...(!Object.hasOwn(requestedCombo, "decisionQuotaTiers") && requestedCombo.strategy === "jev" && previous?.decisionQuotaTiers !== undefined ? { decisionQuotaTiers: previous.decisionQuotaTiers } : {}),
231
236
  // The dashboard does not edit the session pin (#7525): an omitted field keeps it on a JEV save.
232
237
  ...(!Object.hasOwn(requestedCombo, "sessionPin") && requestedCombo.strategy === "jev" && previous?.sessionPin != null ? { sessionPin: previous.sessionPin } : {}),
@@ -167,6 +167,7 @@ export interface ManagementApiDeps {
167
167
  issueApiKey?: (config: OcxConfig, name: string) => IssuedApiKey;
168
168
  revokeApiKey?: (config: OcxConfig, id: string) => boolean;
169
169
  loadLinkCandidates?: () => Array<{ alias: string; source: "ssh_config" | "tailscale" }>;
170
+ resolveChildBinarySource?: typeof import("../../link/child-binary-source").resolveChildBinarySource;
170
171
  /** Bound public inference port, not the ingress receiving this management request. */
171
172
  liveListenPort?: () => number | undefined;
172
173
  now?: () => number;
@@ -0,0 +1,74 @@
1
+ import { SSH_MAX_OUTPUT_BYTES, boundHint, sshFailureHint } from "../../link/ssh-runner";
2
+
3
+ /**
4
+ * Home enrollment reads one Child command before it may restart that Child: `ocx config show
5
+ * --json`, for the effective `port`, `runtimeRole` and (ephemeral) `ephemeralChild` fields.
6
+ *
7
+ * There is no smaller command that answers on every Child this Home supports. Full `ocx` has
8
+ * `config get <dot.path>` since 2.66.0, but resolving only fields that happen to be persisted
9
+ * cannot tell an absent `runtimeRole` (standalone by default) from an unreadable one, and it
10
+ * fails outright for an absent key. The lightweight `ocx-child` binary answers only `config show
11
+ * --json`. A Child is therefore allowed the runner's maximum capture here: a saved configuration
12
+ * of ordinary size stays well under it, and the 64 KiB default rejected a large-but-valid one
13
+ * before preflight could read the two fields it needs (#8356).
14
+ */
15
+ export const CHILD_PREFLIGHT_MAX_OUTPUT_BYTES = SSH_MAX_OUTPUT_BYTES;
16
+
17
+ export const CHILD_CONFIG_TOO_LARGE_MESSAGE = "The Child configuration is too large for the Remote Link preflight.";
18
+
19
+ /** The operator-facing hint for a Child whose config output exceeded even the raised cap. */
20
+ export const CHILD_CONFIG_TOO_LARGE_HINT =
21
+ `ocx config show --json on the Child exceeded ${CHILD_PREFLIGHT_MAX_OUTPUT_BYTES} bytes; trim the Child's saved configuration and retry`;
22
+
23
+ /**
24
+ * Why the Child's effective configuration could not be read (#8357): a failed `config show`
25
+ * names its own last stderr line (bounded and redacted by `sshFailureHint`, e.g. an invalid
26
+ * saved configuration), and a successful one that printed no usable JSON says so.
27
+ */
28
+ export function childConfigFailureHint(result: { code: number; stderr: string }): string {
29
+ if (result.code !== 0) return sshFailureHint(result.stderr) ?? `ocx config show --json exited ${result.code} on the Child`;
30
+ return "ocx config show --json on the Child did not print a configuration with a valid port";
31
+ }
32
+
33
+ /** `ocx config validate --json` prints one small object; this bounds a misbehaving Child. */
34
+ export const CHILD_CONFIG_VALIDATE_MAX_OUTPUT_BYTES = 16 * 1024;
35
+
36
+ /**
37
+ * The validation reason a full `ocx` Child gives for its own saved configuration, or undefined.
38
+ *
39
+ * `config show` on an invalid configuration prints only a generic warning whose path can push
40
+ * the pointer past the 160-code-point hint cap, so it never names the defect (#8357). `config
41
+ * validate --json` answers `{ "ok": false, "error": "schema_invalid: <field>: <rule>" }`, naming
42
+ * fields and expected types, never configured values. Only that `error` string is read from
43
+ * stdout, and `boundHint` still redacts and caps it. A Child without the command (`ocx-child`,
44
+ * an older `ocx`) prints nothing usable and the caller keeps the `config show` reason.
45
+ */
46
+ export function childConfigValidationHint(result: { code: number; stdout: string }): string | undefined {
47
+ if (result.code === 0) return undefined;
48
+ let parsed: unknown;
49
+ try { parsed = JSON.parse(result.stdout); } catch { return undefined; }
50
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
51
+ const { ok, error } = parsed as { ok?: unknown; error?: unknown };
52
+ if (ok !== false || typeof error !== "string") return undefined;
53
+ return boundHint(`Child config is invalid: ${error}`);
54
+ }
55
+
56
+ /**
57
+ * The hint for an unreadable Child configuration: the Child's own validation reason when `config
58
+ * show` failed and `config validate` can name it, otherwise `childConfigFailureHint`. The
59
+ * extra command runs only on this failure path and is read-only on the Child.
60
+ */
61
+ export async function childConfigFailureReason(
62
+ configured: { code: number; stderr: string },
63
+ validate: () => Promise<{ code: number; stdout: string }>,
64
+ ): Promise<string> {
65
+ if (configured.code !== 0) {
66
+ try {
67
+ const reason = childConfigValidationHint(await validate());
68
+ if (reason) return reason;
69
+ } catch {
70
+ // A timeout or transport failure here must not mask the config show reason.
71
+ }
72
+ }
73
+ return childConfigFailureHint(configured);
74
+ }
@@ -2,9 +2,11 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { assertSshAlias, buildExecArgv, buildFingerprintArgv, buildProbeArgv, REMOTE_COMMAND_NOT_FOUND, remoteOcxArgv } from "../../link/ssh-argv";
5
+ import { plantUnavailableGuidance, resolveChildBinarySource } from "../../link/child-binary-source";
5
6
  import { parseFingerprintLine } from "../../link/fingerprint";
7
+ import { isDetachedEphemeralChildConfig } from "../../link/ephemeral-child";
8
+ import { classifyChildAttachConflict, classifyPlantFailure, inspectRemoteChildRuntime, remotePlantChildArgv, remotePurgePlantedChildArgv } from "../../link/remote-plant";
6
9
  import { requireRemotePlatform } from "../../link/remote-platform";
7
- import type { SshRunner } from "../../link/ssh-runner";
8
10
  import { LINK_CATALOG_MAX_BYTES, LINK_RELAY_VERIFY_MS, isChildHealth, linkCommandBudget, linkRestartBudget, parseChildHttp, remoteChildHttpArgv, REMOTE_CURL_PREFLIGHT } from "../../link/remote-probe";
9
11
  import { newLinkId, type LinkStore } from "../../link/store";
10
12
  import { SshRunnerError, boundHint, sshFailureHint, sshRunnerErrorHint, type SshRunResult } from "../../link/ssh-runner";
@@ -12,6 +14,7 @@ import { withConfigMutationLockSync } from "../../config/mutation-lock";
12
14
  import type { ManagementContext } from "./context";
13
15
  import { readManagementJsonBodyOr } from "./body";
14
16
  import { fail, exactBody, port, isRecord, runnerFor, readStoreFor, writeStoreFor, knownHostsFile, putKnownHost, issueKey, compensateNewLink, type LinkRouteState } from "./link-route-state";
17
+ import { CHILD_CONFIG_TOO_LARGE_HINT, CHILD_CONFIG_TOO_LARGE_MESSAGE, CHILD_CONFIG_VALIDATE_MAX_OUTPUT_BYTES, CHILD_PREFLIGHT_MAX_OUTPUT_BYTES, childConfigFailureReason } from "./link-child-preflight";
15
18
 
16
19
  const PROBE_TTL_MS = 5 * 60_000;
17
20
  const MIN_REMOTE_OCX = [2, 66, 0] as const;
@@ -30,12 +33,27 @@ function remoteFailure(result: SshRunResult, code: string, message: string): Res
30
33
  return result.code === 0 ? null : fail(code, message, 502, sshFailureHint(result.stderr));
31
34
  }
32
35
 
36
+ function parseVersion(stdout: string): { version: string; parts: number[] } | null {
37
+ const match = REMOTE_OCX_VERSION.exec(stdout.trim().split(/\r?\n/)[0] ?? "");
38
+ return match ? { version: match.slice(1, 4).join(".") + (match[4] ?? "") + (match[5] ?? ""), parts: match.slice(1, 4).map(Number) } : null;
39
+ }
40
+
41
+ function isOutdatedVersion(parts: readonly number[]): boolean {
42
+ const cmp = parts.findIndex((part, i) => part !== MIN_REMOTE_OCX[i]);
43
+ return cmp >= 0 && parts[cmp]! < MIN_REMOTE_OCX[cmp]!;
44
+ }
45
+
33
46
  export async function probe(ctx: ManagementContext, state: LinkRouteState): Promise<Response> {
34
47
  const value = await readManagementJsonBodyOr(ctx.req, null);
35
- const body = exactBody(value, ["alias"]) ?? exactBody(value, ["alias", "includeVersion"]);
36
- if (!body || typeof body.alias !== "string" || (body.includeVersion !== undefined && body.includeVersion !== true)) return fail("invalid_body", "alias is required.", 400);
48
+ const body = exactBody(value, ["alias"]) ?? exactBody(value, ["alias", "includeVersion"]) ?? exactBody(value, ["alias", "includeVersion", "allowMissing"]);
49
+ if (!body || typeof body.alias !== "string"
50
+ || (body.includeVersion !== undefined && body.includeVersion !== true)
51
+ || (body.allowMissing !== undefined && (typeof body.allowMissing !== "boolean" || body.includeVersion !== true))) {
52
+ return fail("invalid_body", "alias is required.", 400);
53
+ }
37
54
  const alias = body.alias;
38
55
  try { assertSshAlias(alias); } catch { return fail("invalid_alias", "alias must be a valid SSH host alias.", 400); }
56
+ const resolveBinary = ctx.deps.resolveChildBinarySource ?? resolveChildBinarySource;
39
57
  return serialized(state, alias, async () => {
40
58
  const dir = mkdtempSync(join(tmpdir(), "ocx-link-probe-"));
41
59
  const path = join(dir, "known_hosts");
@@ -52,6 +70,38 @@ export async function probe(ctx: ManagementContext, state: LinkRouteState): Prom
52
70
  const line = readFileSync(path, "utf8").trim().split(/\r?\n/).filter(Boolean).at(-1);
53
71
  if (!line) return fail("fingerprint_failed", "The SSH probe did not record a host key.", 502);
54
72
  const remotePlatform = await requireRemotePlatform(runner, alias, path);
73
+ if (body.includeVersion === true && body.allowMissing === true) {
74
+ const inspected = await inspectRemoteChildRuntime(runner, alias, path, remotePlatform);
75
+ if (!inspected) return fail("version_probe_failed", "The remote OpenCodex runtime could not be inspected.", 502);
76
+ if (inspected.runtimeKind === "missing") {
77
+ const source = resolveBinary(inspected.targetTriple);
78
+ state.pendingHosts.set(alias, { alias, fingerprint: parsed.fingerprint, keyType: parsed.keyType, knownHostLine: line, probedAt: now(), sshLatencyMs: latency, remotePlatform, runtimeKind: "missing", targetTriple: inspected.targetTriple });
79
+ state.confirmedHosts?.delete(alias);
80
+ return Response.json({
81
+ alias,
82
+ fingerprint: parsed.fingerprint,
83
+ keyType: parsed.keyType,
84
+ ocxVersion: null,
85
+ runtimeKind: "missing",
86
+ targetTriple: inspected.targetTriple,
87
+ plantable: source.ok,
88
+ ...(source.ok ? { binarySizeBytes: source.artifact.sizeBytes } : { plantUnavailableReason: source.reason }),
89
+ });
90
+ }
91
+ const parsedVersion = parseVersion(inspected.ocxVersionLine ?? "");
92
+ if (!parsedVersion) return fail("remote_ocx_unrecognized", "The remote ocx did not report an OpenCodex version.", 502);
93
+ state.pendingHosts.set(alias, { alias, fingerprint: parsed.fingerprint, keyType: parsed.keyType, knownHostLine: line, probedAt: now(), sshLatencyMs: latency, remotePlatform, runtimeKind: inspected.runtimeKind, targetTriple: inspected.targetTriple });
94
+ state.confirmedHosts?.delete(alias);
95
+ return Response.json({
96
+ alias,
97
+ fingerprint: parsed.fingerprint,
98
+ keyType: parsed.keyType,
99
+ ocxVersion: parsedVersion.version,
100
+ runtimeKind: inspected.runtimeKind,
101
+ targetTriple: inspected.targetTriple,
102
+ plantable: false,
103
+ });
104
+ }
55
105
  let ocxVersion: string | undefined;
56
106
  if (body.includeVersion === true) {
57
107
  const versionResult = await runner.run(buildExecArgv({ alias, argv: remoteOcxArgv(["--version"], remotePlatform), knownHostsFile: path }), { timeoutMs: 30_000 });
@@ -69,15 +119,14 @@ export async function probe(ctx: ManagementContext, state: LinkRouteState): Prom
69
119
  });
70
120
  }
71
121
 
72
- function parseVersion(stdout: string): { version: string; parts: number[] } | null {
73
- const match = REMOTE_OCX_VERSION.exec(stdout.trim().split(/\r?\n/)[0] ?? "");
74
- return match ? { version: match.slice(1, 4).join(".") + (match[4] ?? "") + (match[5] ?? ""), parts: match.slice(1, 4).map(Number) } : null;
75
- }
76
-
77
122
  export async function confirmHost(ctx: ManagementContext, state: LinkRouteState): Promise<Response> {
78
- const body = exactBody(await readManagementJsonBodyOr(ctx.req, null), ["alias", "fingerprint"]);
79
- if (!body || typeof body.alias !== "string" || typeof body.fingerprint !== "string") return fail("invalid_body", "alias and fingerprint are required.", 400);
123
+ const value = await readManagementJsonBodyOr(ctx.req, null);
124
+ const body = exactBody(value, ["alias", "fingerprint"]) ?? exactBody(value, ["alias", "fingerprint", "allowMissing"]);
125
+ if (!body || typeof body.alias !== "string" || typeof body.fingerprint !== "string" || (body.allowMissing !== undefined && typeof body.allowMissing !== "boolean")) {
126
+ return fail("invalid_body", "alias and fingerprint are required.", 400);
127
+ }
80
128
  const alias = body.alias;
129
+ const resolveBinary = ctx.deps.resolveChildBinarySource ?? resolveChildBinarySource;
81
130
  return serialized(state, alias, async () => {
82
131
  const pending = state.pendingHosts.get(alias), now = ctx.deps.now ?? Date.now;
83
132
  if (!pending || now() - pending.probedAt > PROBE_TTL_MS) return fail("host_confirmation_expired", "The SSH host probe has expired.", 409);
@@ -88,13 +137,58 @@ export async function confirmHost(ctx: ManagementContext, state: LinkRouteState)
88
137
  const started = now();
89
138
  const runner = runnerFor(ctx);
90
139
  const remotePlatform = pending.remotePlatform ?? await requireRemotePlatform(runner, alias, path);
140
+ if (body.allowMissing === true) {
141
+ const inspected = await inspectRemoteChildRuntime(runner, alias, path, remotePlatform);
142
+ if (!inspected) return fail("version_probe_failed", "The remote ocx version could not be confirmed.", 502);
143
+ if (inspected.runtimeKind === "missing") {
144
+ const source = resolveBinary(inspected.targetTriple);
145
+ if (state.pendingHosts.get(alias) !== pending || now() - pending.probedAt > PROBE_TTL_MS) return fail("host_confirmation_expired", "The SSH host probe changed or expired.", 409);
146
+ withConfigMutationLockSync(() => putKnownHost(knownHostsFile(ctx), alias, pending.knownHostLine));
147
+ const confirmed = {
148
+ ...pending,
149
+ remotePlatform,
150
+ sshLatencyMs: Math.max(pending.sshLatencyMs ?? 0, now() - started),
151
+ ocxVersion: null,
152
+ runtimeKind: "missing" as const,
153
+ targetTriple: inspected.targetTriple,
154
+ plantable: source.ok,
155
+ ...(source.ok ? { binarySizeBytes: source.artifact.sizeBytes } : { plantUnavailableReason: source.reason }),
156
+ };
157
+ (state.confirmedHosts ??= new Map()).set(alias, confirmed);
158
+ state.pendingHosts.delete(alias);
159
+ return Response.json({
160
+ alias,
161
+ fingerprint: pending.fingerprint,
162
+ ocxVersion: null,
163
+ runtimeKind: "missing",
164
+ targetTriple: inspected.targetTriple,
165
+ plantable: source.ok,
166
+ ...(source.ok ? { binarySizeBytes: source.artifact.sizeBytes } : { plantUnavailableReason: source.reason }),
167
+ });
168
+ }
169
+ const version = parseVersion(inspected.ocxVersionLine ?? "");
170
+ if (!version) return fail("remote_ocx_unrecognized", "The remote ocx did not report an OpenCodex version.", 502);
171
+ if (isOutdatedVersion(version.parts)) return fail("remote_ocx_outdated", "The remote OpenCodex is older than 2.66.0.", 409, boundHint("opencodex " + version.version));
172
+ if (state.pendingHosts.get(alias) !== pending || now() - pending.probedAt > PROBE_TTL_MS) return fail("host_confirmation_expired", "The SSH host probe changed or expired.", 409);
173
+ withConfigMutationLockSync(() => putKnownHost(knownHostsFile(ctx), alias, pending.knownHostLine));
174
+ const confirmed = { ...pending, remotePlatform, sshLatencyMs: Math.max(pending.sshLatencyMs ?? 0, now() - started), ocxVersion: version.version, runtimeKind: inspected.runtimeKind, targetTriple: inspected.targetTriple, plantable: false };
175
+ (state.confirmedHosts ??= new Map()).set(alias, confirmed);
176
+ state.pendingHosts.delete(alias);
177
+ return Response.json({
178
+ alias,
179
+ fingerprint: pending.fingerprint,
180
+ ocxVersion: version.version,
181
+ runtimeKind: inspected.runtimeKind,
182
+ targetTriple: inspected.targetTriple,
183
+ plantable: false,
184
+ });
185
+ }
91
186
  const result = await runner.run(buildExecArgv({ alias, argv: remoteOcxArgv(["--version"], remotePlatform), knownHostsFile: path }), { timeoutMs: 30_000 });
92
187
  const denied = remoteFailure(result, "version_probe_failed", "The remote ocx version could not be confirmed.");
93
188
  if (denied) return denied;
94
189
  const version = parseVersion(result.stdout);
95
190
  if (!version) return fail("remote_ocx_unrecognized", "The remote ocx did not report an OpenCodex version.", 502);
96
- const cmp = version.parts.findIndex((part, i) => part !== MIN_REMOTE_OCX[i]);
97
- if (cmp >= 0 && version.parts[cmp]! < MIN_REMOTE_OCX[cmp]!) return fail("remote_ocx_outdated", "The remote OpenCodex is older than 2.66.0.", 409, boundHint("opencodex " + version.version));
191
+ if (isOutdatedVersion(version.parts)) return fail("remote_ocx_outdated", "The remote OpenCodex is older than 2.66.0.", 409, boundHint("opencodex " + version.version));
98
192
  if (state.pendingHosts.get(alias) !== pending || now() - pending.probedAt > PROBE_TTL_MS) return fail("host_confirmation_expired", "The SSH host probe changed or expired.", 409);
99
193
  withConfigMutationLockSync(() => putKnownHost(knownHostsFile(ctx), alias, pending.knownHostLine));
100
194
  const confirmed = { ...pending, remotePlatform, sshLatencyMs: Math.max(pending.sshLatencyMs ?? 0, now() - started), ocxVersion: version.version };
@@ -113,15 +207,21 @@ function parsePort(stdout: string): number | null {
113
207
 
114
208
  export async function apply(ctx: ManagementContext, state: LinkRouteState): Promise<Response> {
115
209
  const value = await readManagementJsonBodyOr(ctx.req, null);
116
- const body = exactBody(value, ["alias"]) ?? exactBody(value, ["alias", "fingerprint"]);
117
- if (!body || typeof body.alias !== "string" || (body.fingerprint !== undefined && typeof body.fingerprint !== "string")) return fail("invalid_body", "alias and optional fingerprint are required.", 400);
210
+ const body = exactBody(value, ["alias"]) ?? exactBody(value, ["alias", "fingerprint"]) ?? exactBody(value, ["alias", "plant"]) ?? exactBody(value, ["alias", "fingerprint", "plant"]);
211
+ if (!body || typeof body.alias !== "string" || (body.fingerprint !== undefined && typeof body.fingerprint !== "string") || (body.plant !== undefined && typeof body.plant !== "boolean")) {
212
+ return fail("invalid_body", "alias and optional fingerprint/plant are required.", 400);
213
+ }
118
214
  const alias = body.alias;
215
+ const resolveBinary = ctx.deps.resolveChildBinarySource ?? resolveChildBinarySource;
119
216
  return serialized(state, alias, async () => {
120
217
  const confirmed = state.confirmedHosts?.get(alias), now = ctx.deps.now ?? Date.now;
121
218
  if (!confirmed) return fail("host_not_confirmed", "Confirm the SSH host before applying the link.", 409);
122
219
  if (now() - confirmed.probedAt > PROBE_TTL_MS) return fail("host_confirmation_expired", "The SSH host confirmation has expired.", 409);
123
220
  if (body.fingerprint !== undefined && body.fingerprint !== confirmed.fingerprint) return fail("host_fingerprint_mismatch", "The apply fingerprint does not match the confirmed host.", 409);
124
221
  if (readStoreFor(ctx).links.some(link => link.alias === alias && link.direction === "hub-initiated")) return fail("link_exists", "A link for this alias already exists.", 409);
222
+ if (confirmed.runtimeKind === "missing" && body.plant !== true) {
223
+ return fail("remote_ocx_missing", "ocx was not found on the remote host; confirm planting ocx-child before applying.", 409);
224
+ }
125
225
  const dir = mkdtempSync(join(tmpdir(), "ocx-link-apply-")), knownHosts = join(dir, "known_hosts");
126
226
  writeFileSync(knownHosts, confirmed.knownHostLine + "\n", { mode: 0o600 });
127
227
  const runner = runnerFor(ctx), budget = linkCommandBudget(confirmed.sshLatencyMs);
@@ -129,36 +229,86 @@ export async function apply(ctx: ManagementContext, state: LinkRouteState): Prom
129
229
  let remotePlatform: "posix" | "windows";
130
230
  const ocx = (args: readonly string[]) => remoteOcxArgv(args, remotePlatform);
131
231
  let record: LinkStore["links"][number] | undefined, input: Uint8Array | undefined;
132
- let remoteMayBeConnected = false, phase = "remote_port";
232
+ let ephemeralChild = confirmed.runtimeKind === "ephemeral", plantedFreshBinary = false, purgeRollbackFailed = false, remoteMayBeConnected = false, phase = "remote_port";
133
233
  const failed = async (response: Response): Promise<Response> => {
134
234
  const compensation = record ? await compensateNewLink(ctx, state, record) : null;
235
+ if (plantedFreshBinary) {
236
+ plantedFreshBinary = false;
237
+ try {
238
+ const purged = await run(remotePurgePlantedChildArgv(remotePlatform));
239
+ if (purged.code === 0) remoteMayBeConnected = false;
240
+ else { remoteMayBeConnected = true; purgeRollbackFailed = true; }
241
+ } catch {
242
+ remoteMayBeConnected = true;
243
+ purgeRollbackFailed = true;
244
+ }
245
+ }
135
246
  const outcome = compensation ?? response;
136
247
  if (!remoteMayBeConnected) return outcome;
137
248
  const payload = await outcome.json() as Record<string, unknown>;
138
- return Response.json({ ...payload, residual: true, recovery: "Run ocx disconnect and ocx restart on the Child before retrying." }, { status: outcome.status });
249
+ const recovery = purgeRollbackFailed
250
+ ? "Run ~/.cache/opencodex/bin/ocx-child detach --purge on the Child before retrying."
251
+ : ephemeralChild
252
+ ? "Run ocx-child detach (or ocx disconnect) on the Child before retrying."
253
+ : "Run ocx disconnect and ocx restart on the Child before retrying.";
254
+ return Response.json({ ...payload, residual: true, recovery }, { status: outcome.status });
139
255
  };
140
256
  try {
141
257
  remotePlatform = confirmed.remotePlatform ?? await requireRemotePlatform(runner, alias, knownHosts);
258
+ if (body.plant === true && confirmed.runtimeKind === "missing") {
259
+ phase = "remote_plant";
260
+ const source = resolveBinary(confirmed.targetTriple ?? null);
261
+ if (!source.ok) return fail("remote_plant_unavailable", plantUnavailableGuidance(source.reason, confirmed.targetTriple ?? null), 409, source.reason);
262
+ let planted: SshRunResult;
263
+ try {
264
+ planted = await runner.run(
265
+ buildExecArgv({ alias, argv: remotePlantChildArgv(remotePlatform, source.artifact.sizeBytes, source.artifact.sha256), knownHostsFile: knownHosts }),
266
+ { stdin: source.artifact.bytes, timeoutMs: Math.max(budget, 60_000) },
267
+ );
268
+ } catch (plantErr) {
269
+ if (plantErr instanceof SshRunnerError && plantErr.code === "timeout") {
270
+ return fail("remote_plant_timeout", "Planting ocx-child on the remote host timed out.", 502, sshRunnerErrorHint(plantErr));
271
+ }
272
+ return fail("remote_plant_failed", "Could not plant ocx-child on the remote host.", 502, sshRunnerErrorHint(plantErr));
273
+ }
274
+ if (planted.code !== 0) {
275
+ const reason = classifyPlantFailure(planted.stderr);
276
+ if (reason) return fail("remote_plant_failed", "The Child has no sha256sum, shasum, or openssl to verify the ocx-child binary, so it was not installed.", 502, reason);
277
+ return fail("remote_plant_failed", "Could not plant ocx-child on the remote host.", 502, sshFailureHint(planted.stderr));
278
+ }
279
+ plantedFreshBinary = true;
280
+ ephemeralChild = true;
281
+ }
282
+ phase = "remote_port";
142
283
  const chosen = await run(ocx(["link", "port"]));
143
284
  const denied = remoteFailure(chosen, "remote_port_failed", "The remote link port could not be determined.");
144
- if (denied) return denied;
285
+ if (denied) return await failed(denied);
145
286
  const remotePort = parsePort(chosen.stdout);
146
- if (!remotePort) return fail("remote_port_failed", "The remote link port could not be determined.", 502);
287
+ if (!remotePort) return await failed(fail("remote_port_failed", "The remote link port could not be determined.", 502));
147
288
  phase = "child_preflight";
148
- const configured = await run(ocx(["config", "show", "--json"]));
289
+ const configured = await run(ocx(["config", "show", "--json"]), budget, CHILD_PREFLIGHT_MAX_OUTPUT_BYTES);
149
290
  let childConfig: unknown = null;
150
291
  try { if (configured.code === 0) childConfig = JSON.parse(configured.stdout); } catch { /* fail closed */ }
151
- if (!isRecord(childConfig) || !port(childConfig.port)) return fail("child_preflight_failed", "The Child effective configuration could not be read.", 502);
152
- if ((childConfig.runtimeRole ?? "standalone") !== "standalone") return fail("child_restart_unsupported", "The Child must run standalone OpenCodex; an existing Hub or Child cannot be converted by Add Child.", 409);
292
+ if (!isRecord(childConfig) || !port(childConfig.port)) {
293
+ const hint = await childConfigFailureReason(configured, () => run(ocx(["config", "validate", "--json"]), budget, CHILD_CONFIG_VALIDATE_MAX_OUTPUT_BYTES));
294
+ return await failed(fail("child_preflight_failed", "The Child effective configuration could not be read.", 502, hint));
295
+ }
296
+ if ((childConfig.runtimeRole ?? "standalone") !== "standalone") return await failed(fail("child_restart_unsupported", "The Child must run standalone OpenCodex; an existing Hub or Child cannot be converted by Add Child.", 409));
153
297
  const childPort = childConfig.port;
154
- if (remotePlatform === "posix" && (await run(REMOTE_CURL_PREFLIGHT)).code !== 0) return fail("child_curl_missing", "Install curl on the Child before connecting a Remote Link.", 409);
298
+ if (remotePlatform === "posix" && (await run(REMOTE_CURL_PREFLIGHT)).code !== 0) return await failed(fail("child_curl_missing", "Install curl on the Child before connecting a Remote Link.", 409));
155
299
  const before = await run(remoteChildHttpArgv(childPort, "healthz", LINK_RELAY_VERIFY_MS, remotePlatform));
156
- const beforeHealth = before.code === 0 ? parseChildHttp(before.stdout) : null;
157
- if (!isChildHealth(beforeHealth, "standalone", childPort)) return fail("child_restart_unsupported", "The Child must run a standalone OpenCodex with bound restart support; update or disconnect it before linking.", 409);
300
+ ephemeralChild = isDetachedEphemeralChildConfig(childConfig);
301
+ if (ephemeralChild) {
302
+ if (before.code === 255) return await failed(fail("child_preflight_failed", "The Child loopback port could not be inspected.", 502, sshFailureHint(before.stderr)));
303
+ if (before.code === 0) return await failed(fail("child_port_busy", "The Child's target port is already in use; no Child files were modified.", 409));
304
+ } else {
305
+ const beforeHealth = before.code === 0 ? parseChildHttp(before.stdout) : null;
306
+ if (!isChildHealth(beforeHealth, "standalone", childPort)) return await failed(fail("child_restart_unsupported", "The Child must run a standalone OpenCodex with bound restart support; update or disconnect it before linking.", 409));
307
+ }
158
308
  state.confirmedHosts?.delete(alias);
159
309
  phase = "home_setup";
160
310
  const id = newLinkId(), issued = issueKey(ctx, "link:" + alias);
161
- record = { id, alias, direction: "hub-initiated", hostKeyFingerprint: confirmed.fingerprint, tunnelPort: remotePort, apiKeyId: issued.id, createdAt: new Date(now()).toISOString(), remotePlatform };
311
+ record = { id, alias, direction: "hub-initiated", hostKeyFingerprint: confirmed.fingerprint, tunnelPort: remotePort, apiKeyId: issued.id, createdAt: new Date(now()).toISOString(), remotePlatform, childKind: ephemeralChild ? "ephemeral" : "full" };
162
312
  withConfigMutationLockSync(() => {
163
313
  const current = readStoreFor(ctx);
164
314
  if (current.links.some(link => link.alias === alias && link.direction === "hub-initiated")) throw new Error("link exists");
@@ -172,6 +322,17 @@ export async function apply(ctx: ManagementContext, state: LinkRouteState): Prom
172
322
  input = new TextEncoder().encode(JSON.stringify({ apiKeyId: issued.id, key: issued.key }));
173
323
  remoteMayBeConnected = true;
174
324
  const connected = await runner.run(buildExecArgv({ alias, argv: ocx(["connect", "--link", "--key-stdin", "--tunnel-port", String(remotePort), "--link-id", id]), knownHostsFile: knownHosts }), { stdin: input, timeoutMs: budget });
325
+ if (connected.code !== 0) {
326
+ const conflict = classifyChildAttachConflict(connected.stderr);
327
+ if (conflict === "child_port_busy") {
328
+ remoteMayBeConnected = false;
329
+ return await failed(fail("child_port_busy", "The Child's target port is already in use; no Child files were modified.", 409, sshFailureHint(connected.stderr)));
330
+ }
331
+ if (conflict === "child_external_provider_conflict") {
332
+ remoteMayBeConnected = false;
333
+ return await failed(fail("child_external_provider_conflict", "The Child's ~/.codex/config.toml is already managed by another model provider or custom base URL; no Child files were modified.", 409, sshFailureHint(connected.stderr)));
334
+ }
335
+ }
175
336
  const connectDenied = remoteFailure(connected, "remote_connect_failed", "The Child enrollment command failed.");
176
337
  if (connectDenied) return await failed(connectDenied);
177
338
  input.fill(0);
@@ -193,7 +354,11 @@ export async function apply(ctx: ManagementContext, state: LinkRouteState): Prom
193
354
  return Response.json({ linkId: id }, { status: 202 });
194
355
  } finally { unsubscribe(); }
195
356
  } catch (error) {
357
+ if (phase === "child_preflight" && error instanceof SshRunnerError && error.code === "output_limit") {
358
+ return await failed(fail("child_preflight_output_limit", CHILD_CONFIG_TOO_LARGE_MESSAGE, 502, CHILD_CONFIG_TOO_LARGE_HINT));
359
+ }
196
360
  return await failed(fail(phase + (error instanceof SshRunnerError && error.code === "timeout" ? "_timeout" : "_failed"), "Remote Link failed during " + phase.replaceAll("_", " ") + ".", 502, sshRunnerErrorHint(error)));
197
361
  } finally { input?.fill(0); rmSync(dir, { recursive: true, force: true }); }
198
362
  });
199
363
  }
364
+
@@ -17,10 +17,15 @@ export interface PendingLinkHost {
17
17
  probedAt: number;
18
18
  sshLatencyMs?: number;
19
19
  remotePlatform?: "posix" | "windows";
20
+ runtimeKind?: "full" | "ephemeral" | "missing";
21
+ targetTriple?: import("../../link/child-binary-source").ChildTargetTriple | null;
20
22
  }
21
23
 
22
24
  export interface ConfirmedLinkHost extends PendingLinkHost {
23
- ocxVersion: string;
25
+ ocxVersion: string | null;
26
+ plantable?: boolean;
27
+ binarySizeBytes?: number;
28
+ plantUnavailableReason?: import("../../link/child-binary-source").PlantUnavailableReason;
24
29
  }
25
30
 
26
31
  export interface LinkRouteListener {