@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
@@ -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 {
@@ -2,6 +2,7 @@ import { probe, confirmHost, apply } from "./link-enrollment";
2
2
  import { fail, pairedSession, auth, port, isRecord, exactBody, runnerFor, readStoreFor, writeStoreFor, knownHostsFile, issueKey, revokeKeyIdempotent, compensateNewLink, type LinkRouteState } from "./link-route-state";
3
3
  export type { LinkRouteState, PendingLinkHost, ConfirmedLinkHost, LinkRouteListener } from "./link-route-state";
4
4
  import { requireRemotePlatform } from "../../link/remote-platform";
5
+ import { purgeDisconnectRemote } from "../../link/remote-plant";
5
6
  import { assertSshAlias, buildExecArgv, remoteOcxArgv } from "../../link/ssh-argv";
6
7
  import { clearCompensationFailed, compensationPath, readCompensation } from "../../link/compensation";
7
8
  import { loadHostCandidates } from "../../link/ssh-config";
@@ -9,6 +10,7 @@ import { newLinkId, type LinkStore } from "../../link/store";
9
10
  import { sshFailureHint, sshRunnerErrorHint } from "../../link/ssh-runner";
10
11
  import { attachLinkPeers, attachLinkTunnelDiagnostics, projectLinkStatus, type LinkStatusDto } from "../../link/status-projection";
11
12
  import { homeLinkChildParity } from "../../link/child-parity";
13
+ import { codexSettingsDigest, projectHomeCodexSettings } from "../../link/codex-settings";
12
14
  import { localLinkPeer } from "../../link/compatibility";
13
15
  import { packageVersion } from "../../lib/package-version";
14
16
  import { buildPeerFeatures } from "../../remote/features";
@@ -161,7 +163,7 @@ async function handleJoin(ctx: ManagementContext, state: LinkRouteState): Promis
161
163
  runner: runnerFor(ctx),
162
164
  knownHostsFile: knownHostsFile(ctx),
163
165
  scheduleRestart: () => { acceptSystemRestart(); },
164
- ...(confirmed ? { confirmedHost: confirmed } : {}),
166
+ ...(confirmed && confirmed.runtimeKind !== "missing" && confirmed.ocxVersion !== null ? { confirmedHost: confirmed } : {}),
165
167
  };
166
168
  const result = await (overrides.joinHome ?? joinHome)(deps, { alias: body.alias });
167
169
  return Response.json({ linkId: result.linkId, alias: body.alias, restarting: true }, { status: 202 });
@@ -202,8 +204,16 @@ async function remove(ctx: ManagementContext, state: LinkRouteState, id: string)
202
204
  const record = current.links.find(link => link.id === id);
203
205
  if (!record) return fail("link_not_found", "The link was not found.", 404);
204
206
  const body = await readManagementJsonBodyOr(ctx.req, {});
205
- if (!isRecord(body) || Object.keys(body).some(key => key !== "force") || (body.force !== undefined && typeof body.force !== "boolean")) return fail("invalid_body", "force must be a boolean.", 400);
206
- const force = body.force === true;
207
+ const payload = body === null ? {} : body;
208
+ if (!isRecord(payload)
209
+ || Object.keys(payload).some(key => key !== "force" && key !== "purge")
210
+ || (payload.force !== undefined && typeof payload.force !== "boolean")
211
+ || (payload.purge !== undefined && typeof payload.purge !== "boolean")
212
+ || (payload.force === true && payload.purge === true)) {
213
+ return fail("invalid_body", "force and purge must be booleans and cannot both be true.", 400);
214
+ }
215
+ const force = payload.force === true;
216
+ const purge = payload.purge === true;
207
217
  const release = state.supervisor.holdLink?.(id);
208
218
  try {
209
219
  await state.supervisor.stopLink(id);
@@ -220,10 +230,18 @@ async function remove(ctx: ManagementContext, state: LinkRouteState, id: string)
220
230
  try {
221
231
  const runner = runnerFor(ctx);
222
232
  const platform = record.remotePlatform ?? await requireRemotePlatform(runner, record.alias, knownHostsFile(ctx));
223
- const result = await runner.run(buildExecArgv({ alias: record.alias, argv: remoteOcxArgv(["disconnect"], platform), knownHostsFile: knownHostsFile(ctx) }), { timeoutMs: 30_000 });
224
- if (result.code !== 0) {
225
- await restartTunnel();
226
- return fail("remote_disconnect_failed", "The remote client could not be disconnected.", 502, sshFailureHint(result.stderr));
233
+ if (purge) {
234
+ const purged = await purgeDisconnectRemote(runner, record.alias, knownHostsFile(ctx), platform, record.childKind);
235
+ if (!purged.ok) {
236
+ await restartTunnel();
237
+ return fail(purged.code, purged.message, purged.status, purged.hint);
238
+ }
239
+ } else {
240
+ const result = await runner.run(buildExecArgv({ alias: record.alias, argv: remoteOcxArgv(["disconnect"], platform), knownHostsFile: knownHostsFile(ctx) }), { timeoutMs: 30_000 });
241
+ if (result.code !== 0) {
242
+ await restartTunnel();
243
+ return fail("remote_disconnect_failed", "The remote client could not be disconnected.", 502, sshFailureHint(result.stderr));
244
+ }
227
245
  }
228
246
  } catch (error) {
229
247
  await restartTunnel();
@@ -297,8 +315,8 @@ export async function handleLinkRoutes(ctx: ManagementContext, suppliedState?: L
297
315
  // A dashboard session also learns why it cannot join as a Child. The admin-token answer stays
298
316
  // the exact K16 document that `ocx link status` validates key by key.
299
317
  const denial = ctx.principal === "gui-session" ? joinDenied(ctx) : null;
300
- const body: LinkStatusDto & { joinAvailable?: boolean; joinDenied?: LinkJoinDenied | null } = ctx.principal === "gui-session"
301
- ? { ...dto, joinAvailable: denial === null, joinDenied: denial } : dto;
318
+ const body: LinkStatusDto & { joinAvailable?: boolean; joinDenied?: LinkJoinDenied | null; homeCodexSettingsDigest?: string } = ctx.principal === "gui-session"
319
+ ? { ...dto, joinAvailable: denial === null, joinDenied: denial, homeCodexSettingsDigest: codexSettingsDigest(projectHomeCodexSettings(ctx.config, packageVersion("0.0.0")).settings) } : dto;
302
320
  return Response.json(body, { headers: { "cache-control": "no-store" } });
303
321
  }
304
322
  if (url.pathname === "/api/link/candidates" && req.method === "GET") {
@@ -348,12 +348,16 @@ export async function listManagementModelRows(
348
348
  const native: ManagementModelRow[] = [...nativeRows, ...accountNativeRows].map(row => {
349
349
  const reasoningEfforts = nativeReasoningEfforts(row.metadataSlug).filter(isVisionReasoningEffort);
350
350
  const defaultReasoningEffort = nativeDefaultReasoningEffort(row.metadataSlug);
351
+ const labels = config.providers.openai?.modelDisplayNames;
352
+ const displayName = row.slug === row.metadataSlug && labels && Object.hasOwn(labels, row.slug)
353
+ ? labels[row.slug]?.trim() : undefined;
351
354
  return {
352
355
  provider: "openai",
353
356
  id: row.slug,
354
357
  namespaced: row.slug,
355
358
  disabled: row.disabled,
356
359
  native: true,
360
+ ...(displayName ? { displayName, displayNameOverride: displayName, displayNameSource: "operator" as const } : {}),
357
361
  reasoningEfforts,
358
362
  ...(defaultReasoningEffort ? { defaultReasoningEffort } : {}),
359
363
  inputModalities: nativeInputModalities(row.slug),
@@ -40,7 +40,7 @@ import { OAuthMutationBusyError, removeCredential } from "../../oauth/store";
40
40
  import { cancelKiroDeviceLogin, kiroDeviceConfigBaseline, selectKiroDeviceProfile, startKiroDeviceLogin, statusKiroDeviceLogin, type KiroDeviceMethod } from "../../oauth/kiro-device-login";
41
41
  import { parseKiroIamOptions } from "../../oauth/kiro-iam-identity-center";
42
42
  import { providerDestinationResolvedError } from "../../lib/destination-policy";
43
- import { emailMaskingEnabled, maskedAccountLabel } from "../../lib/privacy";
43
+ import { accountDisplayLabel, emailMaskingEnabled, maskedAccountLabel } from "../../lib/privacy";
44
44
  import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
45
45
  import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
46
46
  import { deriveProviderPresets } from "../../providers/derive";
@@ -497,7 +497,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
497
497
  }
498
498
 
499
499
  // Multiauth account management: list a provider's logged-in accounts, switch the active
500
- // one, or remove one. Emails are masked; tokens never leave the store.
500
+ // one, or remove one. Emails and accountLabel follow privacy.maskEmails, maskedLabel is always
501
+ // masked, and tokens never leave the store.
501
502
  if (url.pathname === "/api/oauth/accounts" && req.method === "GET") {
502
503
  const provider = (url.searchParams.get("provider") ?? "").trim().toLowerCase();
503
504
  if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400);
@@ -516,7 +517,8 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
516
517
  } = await import("../../oauth/health");
517
518
  const projectAccounts = () => {
518
519
  const set = getAccountSet(provider);
519
- const current = getLoginStatus(provider, emailMaskingEnabled(config));
520
+ const maskEmails = emailMaskingEnabled(config);
521
+ const current = getLoginStatus(provider, maskEmails);
520
522
  return {
521
523
  ...(provider === "anthropic2" ? { provider } : {}), activeAccountId: current.activeAccountId ?? null,
522
524
  accounts: (current.accounts ?? []).map(summary => {
@@ -528,7 +530,10 @@ export async function handleOauthAccountRoutes(ctx: ManagementContext): Promise<
528
530
  reauthReason: summary.needsReauth === true ? "refresh_failed" : undefined,
529
531
  });
530
532
  const maskedLabel = maskedAccountLabel(full?.credential.email);
531
- return { ...summary, ...(maskedLabel ? { maskedLabel } : {}), ...oauthAccountHealthFields(provider, summary.id, health), quotaMode,
533
+ // `maskedLabel` stays masked for tray surfaces; `accountLabel` follows privacy.maskEmails.
534
+ const accountLabel = accountDisplayLabel(full?.credential.email, maskEmails);
535
+ return { ...summary, ...(maskedLabel ? { maskedLabel } : {}), ...(accountLabel ? { accountLabel } : {}),
536
+ ...oauthAccountHealthFields(provider, summary.id, health), quotaMode,
532
537
  ...(supportsPause ? { paused: full?.paused === true, ...(full?.pauseDetails ? { pauseDetails: full.pauseDetails } : {}) } : {}),
533
538
  ...(isAnthropicOAuthInstance(provider) && supportsPause ? { autoSwitchThresholdOverride: full?.autoSwitchThresholdOverride ?? null,
534
539
  effectiveAutoSwitchThreshold: effectiveAnthropicAccountThresholdForInstance(provider as AnthropicInstanceId, config, full),