@bitkyc08/opencodex 2.99.0-preview.20261108 → 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-DpiBmFGI.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-JcszQ18T.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-5v86r9Az.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-CWz0areF.js +0 -59
  253. package/gui/dist/assets/Tray-BosDoskm.js +0 -1
  254. package/gui/dist/assets/index-CAxjGWkm.js +0 -94
  255. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  256. package/gui/dist/classic/assets/App-BOEsFmiN.js +0 -58
  257. package/gui/dist/classic/assets/index-ClZ_zZ77.js +0 -94
  258. package/gui/dist/classic/assets/quota-summary-xwvDtvu7.js +0 -1
@@ -0,0 +1,515 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ linkSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ readdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ type BigIntStats,
13
+ } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { Server } from "bun";
16
+ import { isLoopbackHostname } from "../../codex/loopback-target";
17
+ import { withLockClaim } from "../../codex/prompt-lock-claim";
18
+ import { ownEvidence, ownerDefaults, ownerState, type OwnerEvidence } from "../../codex/prompt-lock-owner";
19
+ import { getConfigDir } from "../../config/paths";
20
+ import { ConfigOwnershipLockError, registerOwnedConfigPath } from "../../lib/config-ownership";
21
+ import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard";
22
+ import {
23
+ isPrivateSocketDir,
24
+ localControlLeasePath,
25
+ localControlPrivateSocketPath,
26
+ localControlSocketDir,
27
+ localControlSocketPath,
28
+ localControlSocketPathFits,
29
+ localControlSocketSupported,
30
+ } from "../../lib/local-control-socket";
31
+ import type { OcxConfig } from "../../types";
32
+
33
+ /**
34
+ * The one request the local control socket serves (#8184). `ocx link status` needs admin-token
35
+ * authority on trusted loopback ingress, which a hub whose public listener is not loopback cannot
36
+ * give it: the hub management listener is reached through Tailscale Serve, so it must never count
37
+ * as trusted loopback (#6913). The socket is a separate ingress with that trust, limited to this
38
+ * read and still requiring the admin token.
39
+ */
40
+ export function localControlRouteAllowed(url: URL, req: Request): boolean {
41
+ return req.method === "GET" && url.pathname === "/api/link/status" && !req.headers.has("upgrade");
42
+ }
43
+
44
+ /** A loopback public listener already gives the CLI trusted ingress; only other binds need this. */
45
+ export function localControlSocketWanted(config: Pick<OcxConfig, "hostname">): boolean {
46
+ return localControlSocketSupported() && !isLoopbackHostname(config.hostname ?? "127.0.0.1");
47
+ }
48
+
49
+ export interface LocalControlStartContext<T> {
50
+ config: OcxConfig;
51
+ publicPort: number;
52
+ dispatch: (req: Request, server: Server<T>) => Promise<Response>;
53
+ configDir?: string;
54
+ }
55
+
56
+ export interface LocalControlListener<T> {
57
+ ownsListener(server: Server<T>): boolean;
58
+ socketPath(): string | null;
59
+ start(ctx: LocalControlStartContext<T>): void;
60
+ /**
61
+ * Synchronous teardown for a startup that failed after this listener started. `startServer` is
62
+ * synchronous, so the ownership record has to go before the startup error propagates; an
63
+ * awaited `stop()` would leave a live lease nobody serves.
64
+ */
65
+ abort(): void;
66
+ stop(): Promise<void>;
67
+ }
68
+
69
+ function preparePrivateDir(dir: string): void {
70
+ assertNotRealHomeUnderTest(dirname(dir));
71
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
72
+ const stat = lstatSync(dir);
73
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid!()) {
74
+ throw new Error("socket directory is not a directory owned by this user");
75
+ }
76
+ chmodSync(dir, 0o700);
77
+ if (!isPrivateSocketDir(dir)) throw new Error("socket directory could not be made private");
78
+ }
79
+
80
+ /** Inode identity as the kernel reports it. Bigint keeps every bit of a Windows file ID. */
81
+ interface FileIdentity { dev: bigint; ino: bigint }
82
+
83
+ /**
84
+ * The per-port ownership record. `host` and `processStart` come from the shared owner evidence
85
+ * (`src/codex/prompt-lock-owner.ts`), so a record from another machine, or from a pid that has
86
+ * been reused, is never mistaken for a crashed predecessor.
87
+ */
88
+ interface LocalControlLease extends OwnerEvidence { token: string }
89
+
90
+ type LeaseRead =
91
+ | { kind: "absent" }
92
+ | { kind: "record"; lease: LocalControlLease }
93
+ | { kind: "unsafe" };
94
+
95
+ type LeaseDecision =
96
+ | { kind: "acquired" }
97
+ | { kind: "held" }
98
+ | { kind: "unsafe" }
99
+ | { kind: "contended" }
100
+ | { kind: "failed"; error: unknown };
101
+
102
+ const PUBLISH_ATTEMPTS = 4;
103
+ /** `withLockClaim` is a try-lock; a contender retries a bounded number of times and then refuses. */
104
+ const LEASE_LOCK_ATTEMPTS = 8;
105
+ const LEASE_LOCK_RETRY_MS = 2;
106
+ /** A release is on the shutdown path, so it retries longer than the acquire does. */
107
+ const RELEASE_ATTEMPTS = 12;
108
+ const RELEASE_RETRY_MS = 5;
109
+ /** Filesystems without hard links reject `link` with one of these; the socket cannot be published. */
110
+ const HARD_LINK_UNSUPPORTED = new Set(["EPERM", "EOPNOTSUPP", "ENOTSUP", "ENOSYS", "EXDEV", "EMLINK"]);
111
+ const HARD_LINK_WARNING = "[local-control] the socket directory's filesystem does not support hard links; ocx link status will use the TCP listener";
112
+
113
+ function isCode(error: unknown, code: string): boolean {
114
+ return !!error && typeof error === "object" && (error as { code?: unknown }).code === code;
115
+ }
116
+
117
+ function hardLinkUnsupported(error: unknown): boolean {
118
+ const code = (error as { code?: unknown } | null)?.code;
119
+ return typeof code === "string" && HARD_LINK_UNSUPPORTED.has(code);
120
+ }
121
+
122
+ function messageOf(error: unknown): string {
123
+ return error instanceof Error ? error.message : String(error);
124
+ }
125
+
126
+ /** A fresh identity per listener instance, so a same-pid restart never reuses a name or a record. */
127
+ function randomToken(): string {
128
+ return randomBytes(8).toString("hex");
129
+ }
130
+
131
+ /**
132
+ * Record the run directory as state uninstall may remove. Another runtime may hold the ownership
133
+ * lock for a moment, and refusing the socket over that transient would silently drop the only
134
+ * ingress `ocx link status` has on a hub, so a busy lock is retried briefly.
135
+ */
136
+ function registerRunDirectory(root: string, dir: string): void {
137
+ for (let attempt = 0; ; attempt += 1) {
138
+ try {
139
+ if (registerOwnedConfigPath(root, dir) === "full") {
140
+ console.warn("[local-control] the config ownership manifest is full; the run directory may survive uninstall");
141
+ }
142
+ return;
143
+ } catch (error) {
144
+ if (!(error instanceof ConfigOwnershipLockError) || attempt >= 2) throw error;
145
+ Bun.sleepSync(5);
146
+ }
147
+ }
148
+ }
149
+
150
+ function identityOf(path: string): FileIdentity | null {
151
+ try {
152
+ const stat = lstatSync(path, { bigint: true });
153
+ return { dev: stat.dev, ino: stat.ino };
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ function sameIdentity(path: string, identity: FileIdentity): boolean {
160
+ const current = identityOf(path);
161
+ return current !== null && current.dev === identity.dev && current.ino === identity.ino;
162
+ }
163
+
164
+ /**
165
+ * A record that exists but cannot be read is `unsafe`, never `absent`: treating a corrupt lease
166
+ * as "no owner" is how a live runtime gets displaced by a reader that could not parse it.
167
+ */
168
+ function readLease(path: string): LeaseRead {
169
+ let body: string;
170
+ try {
171
+ body = readFileSync(path, "utf8");
172
+ } catch (error) {
173
+ return isCode(error, "ENOENT") ? { kind: "absent" } : { kind: "unsafe" };
174
+ }
175
+ try {
176
+ const parsed = JSON.parse(body) as Partial<LocalControlLease>;
177
+ if (typeof parsed.token !== "string" || parsed.token.length === 0) return { kind: "unsafe" };
178
+ return { kind: "record", lease: parsed as LocalControlLease };
179
+ } catch {
180
+ return { kind: "unsafe" };
181
+ }
182
+ }
183
+
184
+ /** Replace the record in one rename, so no reader ever sees a half-written lease. */
185
+ function writeLease(path: string, lease: LocalControlLease): void {
186
+ const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
187
+ try {
188
+ writeFileSync(temp, JSON.stringify(lease), { mode: 0o600 });
189
+ renameSync(temp, path);
190
+ } finally {
191
+ try { unlinkSync(temp); } catch { /* renamed or never written */ }
192
+ }
193
+ }
194
+
195
+ /** Remove the record only when it is still this instance's; the caller holds the claim mutex. */
196
+ function removeOwnedLease(path: string, token: string): void {
197
+ const current = readLease(path);
198
+ if (current.kind !== "record" || current.lease.token !== token) return;
199
+ try { unlinkSync(path); } catch { /* already gone */ }
200
+ }
201
+
202
+ /**
203
+ * Remove a private socket left by a runtime that died before it could clean up. The lease is ours,
204
+ * so every other `.c<port>.*` socket is a crashed predecessor's; a live owner would have kept the
205
+ * lease and this code would never run.
206
+ */
207
+ function removeOrphanPrivateSockets(port: number, configDir: string | undefined): void {
208
+ const dir = localControlSocketDir(configDir);
209
+ let entries: string[];
210
+ try { entries = readdirSync(dir); } catch { return; }
211
+ const prefix = `.c${port}.`;
212
+ for (const name of entries) {
213
+ if (!name.startsWith(prefix)) continue;
214
+ const candidate = join(dir, name);
215
+ try {
216
+ const stat = lstatSync(candidate);
217
+ if (stat.isSocket() && stat.uid === process.getuid!()) unlinkSync(candidate);
218
+ } catch { /* raced with another cleanup */ }
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Publish the private socket at the public path with an atomic hard link. The caller holds the
224
+ * lease, so a same-user socket already there can only be a crashed predecessor's and is removed;
225
+ * any other file is left alone and the socket is not served.
226
+ */
227
+ function publishPublicLink(target: string, privateTarget: string): void {
228
+ for (let attempt = 0; attempt < PUBLISH_ATTEMPTS; attempt += 1) {
229
+ try {
230
+ linkSync(privateTarget, target);
231
+ return;
232
+ } catch (error) {
233
+ if (!isCode(error, "EEXIST")) throw error;
234
+ }
235
+ let existing: BigIntStats;
236
+ try {
237
+ existing = lstatSync(target, { bigint: true });
238
+ } catch (error) {
239
+ if (isCode(error, "ENOENT")) continue;
240
+ throw error;
241
+ }
242
+ if (!existing.isSocket() || existing.uid !== BigInt(process.getuid!())) throw new Error("socket path is occupied");
243
+ unlinkSync(target);
244
+ }
245
+ throw new Error("socket path is occupied");
246
+ }
247
+
248
+ /**
249
+ * Read the record, decide, and publish, all inside the shared claim mutex
250
+ * (`withLockClaim`, `src/codex/prompt-lock-claim.ts`). The mutex is what makes this a decision
251
+ * rather than a recheck: no other runtime can be between its own read and its own write, so a
252
+ * record judged stale cannot be replaced by a live one before this runtime publishes.
253
+ */
254
+ function acquireLease(leasePath: string, token: string, publish: () => void): LeaseDecision {
255
+ for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) {
256
+ const outcome = withLockClaim(leasePath, token, ownerDefaults, (): LeaseDecision => {
257
+ const current = readLease(leasePath);
258
+ if (current.kind === "unsafe") return { kind: "unsafe" };
259
+ if (current.kind === "record") {
260
+ const state = ownerState(current.lease, ownerDefaults);
261
+ if (state !== "dead") return { kind: state === "live" ? "held" : "unsafe" };
262
+ }
263
+ // Absent, or provably a crashed predecessor: this runtime owns the port now.
264
+ writeLease(leasePath, { ...ownEvidence(ownerDefaults), token });
265
+ try {
266
+ publish();
267
+ } catch (error) {
268
+ removeOwnedLease(leasePath, token);
269
+ return { kind: "failed", error };
270
+ }
271
+ return { kind: "acquired" };
272
+ });
273
+ if (outcome.ok) return outcome.value;
274
+ if (attempt + 1 < LEASE_LOCK_ATTEMPTS) Bun.sleepSync(LEASE_LOCK_RETRY_MS);
275
+ }
276
+ return { kind: "contended" };
277
+ }
278
+
279
+ /** The record and the paths one runtime published, kept until the release actually succeeds. */
280
+ interface OwnedSocket {
281
+ leasePath: string;
282
+ token: string;
283
+ publicPath: string | null;
284
+ privatePath: string | null;
285
+ identity: FileIdentity | null;
286
+ }
287
+
288
+ type ReleaseOutcome =
289
+ | { kind: "released" }
290
+ | { kind: "contended" }
291
+ | { kind: "failed"; error: unknown };
292
+
293
+ /**
294
+ * A stop that could not give the port back. The record stays on the listener, so a later stop()
295
+ * or start() retries it; this error is how the caller learns the socket may still be live.
296
+ */
297
+ export class LocalControlReleaseError extends Error {
298
+ readonly code = "LOCAL_CONTROL_RELEASE_FAILED";
299
+ constructor(readonly outcome: "contended" | "failed", cause?: unknown) {
300
+ super(outcome === "contended"
301
+ ? "another runtime held the control socket ownership record; the lease and socket were left in place"
302
+ : "the control socket ownership record could not be released", { cause });
303
+ this.name = "LocalControlReleaseError";
304
+ }
305
+ }
306
+
307
+ function releaseFailure(outcome: Exclude<ReleaseOutcome, { kind: "released" }>): string {
308
+ return outcome.kind === "contended"
309
+ ? "another runtime held the control socket ownership record"
310
+ : `the control socket ownership record could not be released: ${messageOf(outcome.error)}`;
311
+ }
312
+
313
+ /**
314
+ * Remove the published link and the lease, inside the claim mutex. The outcome is explicit: a
315
+ * lost mutex is contention the caller must retry, never a release that silently did nothing.
316
+ */
317
+ function releaseOwnedSocket(state: OwnedSocket): ReleaseOutcome {
318
+ try {
319
+ const outcome = withLockClaim(state.leasePath, state.token, ownerDefaults, () => {
320
+ if (state.publicPath && state.identity && sameIdentity(state.publicPath, state.identity)) unlinkSync(state.publicPath);
321
+ if (state.privatePath && state.identity && sameIdentity(state.privatePath, state.identity)) unlinkSync(state.privatePath);
322
+ removeOwnedLease(state.leasePath, state.token);
323
+ });
324
+ return outcome.ok ? { kind: "released" } : { kind: "contended" };
325
+ } catch (error) {
326
+ return { kind: "failed", error };
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Retry a contended release a bounded number of times. The wait is synchronous on purpose:
332
+ * stop() has to give the record up before it suspends on its own socket teardown, or a successor
333
+ * starting in the same turn reads a live lease and abandons a port nobody will serve. A
334
+ * same-process peer holds this mutex only inside a synchronous critical section, so a blocking
335
+ * wait always reaches it; a peer process makes progress on its own.
336
+ */
337
+ function releaseBlocking(state: OwnedSocket): ReleaseOutcome {
338
+ let outcome = releaseOwnedSocket(state);
339
+ for (let attempt = 1; attempt < RELEASE_ATTEMPTS && outcome.kind === "contended"; attempt += 1) {
340
+ Bun.sleepSync(RELEASE_RETRY_MS);
341
+ outcome = releaseOwnedSocket(state);
342
+ }
343
+ return outcome;
344
+ }
345
+
346
+ const notFound = () => Response.json(
347
+ { error: { code: "not_found", message: "The local control socket serves only GET /api/link/status." } },
348
+ { status: 404 },
349
+ );
350
+
351
+ export function createLocalControlListener<T>(): LocalControlListener<T> {
352
+ let server: Server<T> | null = null;
353
+ let publicPath: string | null = null;
354
+ let privatePath: string | null = null;
355
+ let identity: FileIdentity | null = null;
356
+ let leasePath: string | null = null;
357
+ let leaseToken: string | null = null;
358
+ /** A release that could not run yet. Retained so the next stop() or start() finishes it. */
359
+ let pendingRelease: OwnedSocket | null = null;
360
+
361
+ const liveState = (): OwnedSocket | null => leasePath && leaseToken
362
+ ? { leasePath, token: leaseToken, publicPath, privatePath, identity }
363
+ : null;
364
+
365
+ const clearLive = (): void => {
366
+ server = null;
367
+ publicPath = null;
368
+ privatePath = null;
369
+ identity = null;
370
+ leasePath = null;
371
+ leaseToken = null;
372
+ };
373
+
374
+ return {
375
+ ownsListener: candidate => server !== null && candidate === server,
376
+ socketPath: () => publicPath,
377
+ start(ctx) {
378
+ if (server || !localControlSocketWanted(ctx.config)) return;
379
+ // A previous stop could not give the port back; finish that before asking for it again,
380
+ // because the record it left names this pid and would read as a live owner.
381
+ if (pendingRelease) {
382
+ const previous = releaseBlocking(pendingRelease);
383
+ if (previous.kind !== "released") {
384
+ console.warn(`[local-control] ${releaseFailure(previous)}; leaving the previous record in place`);
385
+ return;
386
+ }
387
+ pendingRelease = null;
388
+ }
389
+ const target = localControlSocketPath(ctx.publicPort, ctx.configDir);
390
+ const leaseFile = localControlLeasePath(ctx.publicPort, ctx.configDir);
391
+ const token = randomToken();
392
+ const privateTarget = localControlPrivateSocketPath(ctx.publicPort, token, ctx.configDir);
393
+ if (!localControlSocketPathFits(target) || !localControlSocketPathFits(privateTarget)) {
394
+ console.warn("[local-control] socket path is too long; ocx link status will use the TCP listener");
395
+ return;
396
+ }
397
+ try {
398
+ preparePrivateDir(dirname(target));
399
+ } catch (error) {
400
+ console.warn(`[local-control] socket unavailable: ${messageOf(error)}`);
401
+ return;
402
+ }
403
+ try {
404
+ // The run directory is state this runtime creates inside the config home, so uninstall has
405
+ // to know about it. Only the directory is recorded: the sockets and the lease inside it are
406
+ // transient, and the ownership API refuses to adopt an entry it did not record.
407
+ registerRunDirectory(ctx.configDir ?? getConfigDir(), dirname(target));
408
+ } catch (error) {
409
+ console.warn(`[local-control] socket unavailable: ${messageOf(error)}`);
410
+ return;
411
+ }
412
+ let bound: Server<T> | null = null;
413
+ let published: FileIdentity | null = null;
414
+ const publish = (): void => {
415
+ removeOrphanPrivateSockets(ctx.publicPort, ctx.configDir);
416
+ // Bun binds a process-specific address, so its own stop() can only ever unlink this one.
417
+ bound = Bun.serve<T, never>({
418
+ unix: privateTarget,
419
+ maxRequestBodySize: 0,
420
+ fetch(req, requestServer) {
421
+ let url: URL;
422
+ try { url = new URL(req.url); } catch { return notFound(); }
423
+ return localControlRouteAllowed(url, req) ? ctx.dispatch(req, requestServer) : notFound();
424
+ },
425
+ });
426
+ // The private directory is the access boundary; the socket mode is a second fence.
427
+ chmodSync(privateTarget, 0o600);
428
+ const socketIdentity = identityOf(privateTarget);
429
+ if (!socketIdentity) throw new Error("socket identity unavailable");
430
+ publishPublicLink(target, privateTarget);
431
+ published = socketIdentity;
432
+ };
433
+ let decision: LeaseDecision;
434
+ try {
435
+ decision = acquireLease(leaseFile, token, publish);
436
+ } catch (error) {
437
+ if (bound) void (bound as Server<T>).stop(true).catch(() => {});
438
+ console.warn(hardLinkUnsupported(error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(error)}`);
439
+ return;
440
+ }
441
+ if (decision.kind === "failed") {
442
+ if (bound) void (bound as Server<T>).stop(true).catch(() => {});
443
+ // Publishing is where a hard-link-less filesystem actually fails, and that error is
444
+ // returned rather than thrown, so this branch is the one that has to classify it.
445
+ console.warn(hardLinkUnsupported(decision.error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(decision.error)}`);
446
+ return;
447
+ }
448
+ if (decision.kind === "held") {
449
+ console.warn("[local-control] another runtime owns this port's control socket; leaving it in place");
450
+ return;
451
+ }
452
+ if (decision.kind === "unsafe") {
453
+ console.warn("[local-control] the control socket ownership record is not this machine's; leaving it in place");
454
+ return;
455
+ }
456
+ if (decision.kind === "contended") {
457
+ console.warn("[local-control] could not take the control socket ownership record; leaving it in place");
458
+ return;
459
+ }
460
+ server = bound;
461
+ publicPath = target;
462
+ privatePath = privateTarget;
463
+ identity = published;
464
+ leasePath = leaseFile;
465
+ leaseToken = token;
466
+ },
467
+ abort() {
468
+ const running = server;
469
+ // Bun's own stop unlinks the private name, so this rollback leaves that one to it.
470
+ const live = liveState();
471
+ const state = pendingRelease ?? (live ? { ...live, privatePath: null } : null);
472
+ clearLive();
473
+ // startServer is synchronous, so this rollback cannot await. Bun begins closing the listen
474
+ // socket on the call itself and unlinks its own private name; the published link and the
475
+ // lease must go now, because a stranded live lease keeps the next runtime off a dead socket.
476
+ if (running) {
477
+ try { void running.stop(true).catch(() => {}); } catch { /* the startup error is the one to report */ }
478
+ }
479
+ if (!state) return;
480
+ const outcome = releaseBlocking(state);
481
+ if (outcome.kind === "released") { pendingRelease = null; return; }
482
+ // abort() runs inside startServer's catch, so it must not replace the startup error. The
483
+ // record is retained and reported here, and the next stop() or start() retries it.
484
+ pendingRelease = state;
485
+ console.warn(`[local-control] ${releaseFailure(outcome)}; the record is retained for the next start or stop`);
486
+ },
487
+ async stop() {
488
+ const running = server;
489
+ const state = pendingRelease ?? liveState();
490
+ clearLive();
491
+ // Give the record up BEFORE awaiting the socket teardown. A successor that starts while
492
+ // this stop is suspended must not read a live lease and abandon a port nobody will serve.
493
+ let releaseError: LocalControlReleaseError | null = null;
494
+ if (state) {
495
+ const outcome = releaseBlocking(state);
496
+ if (outcome.kind === "released") {
497
+ pendingRelease = null;
498
+ } else {
499
+ pendingRelease = state;
500
+ releaseError = new LocalControlReleaseError(outcome.kind, outcome.kind === "failed" ? outcome.error : undefined);
501
+ }
502
+ }
503
+ let failure: unknown;
504
+ try {
505
+ if (running) await running.stop(true);
506
+ } catch (error) {
507
+ failure = error;
508
+ }
509
+ // A record that could not be released is the failure worth reporting: the socket may live,
510
+ // and the caller's shutdown has to say so rather than look complete.
511
+ if (releaseError) throw releaseError;
512
+ if (failure) throw failure;
513
+ },
514
+ };
515
+ }
@@ -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