@bitkyc08/opencodex 2.99.0 → 2.100.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/AGENTS_INSTALL.md +19 -1
  2. package/README.md +37 -33
  3. package/SPONSORS.md +5 -1
  4. package/bin/ocx.mjs +1 -1
  5. package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
  6. package/gui/dist/assets/App-CitvEefy.js +59 -0
  7. package/gui/dist/assets/Tray-CeKVWQyB.js +1 -0
  8. package/gui/dist/assets/{brand-mark-wzPe3R-J.js → brand-mark-M92UnxX2.js} +1 -1
  9. package/gui/dist/assets/index-BP47do6-.js +94 -0
  10. package/gui/dist/assets/index-DmDooSAG.css +2 -0
  11. package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-CcxZBnxv.js} +1 -1
  12. package/gui/dist/classic/assets/App-aYgIQMxI.js +58 -0
  13. package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-D8jfUXpQ.js} +1 -1
  14. package/gui/dist/classic/assets/index-CfGqHooN.js +94 -0
  15. package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +1 -0
  16. package/gui/dist/classic/index.html +1 -1
  17. package/gui/dist/index.html +2 -2
  18. package/native/ocx-child/Cargo.lock +215 -0
  19. package/native/ocx-child/Cargo.toml +31 -0
  20. package/native/ocx-child/src/cli.rs +1901 -0
  21. package/native/ocx-child/src/codex_home.rs +429 -0
  22. package/native/ocx-child/src/codex_settings.rs +231 -0
  23. package/native/ocx-child/src/daemon.rs +363 -0
  24. package/native/ocx-child/src/http_wire.rs +619 -0
  25. package/native/ocx-child/src/journal.rs +977 -0
  26. package/native/ocx-child/src/lib.rs +22 -0
  27. package/native/ocx-child/src/main.rs +9 -0
  28. package/native/ocx-child/src/parity.rs +102 -0
  29. package/native/ocx-child/src/platform.rs +1487 -0
  30. package/native/ocx-child/src/relay.rs +1288 -0
  31. package/native/ocx-child/src/relay_auth.rs +166 -0
  32. package/native/ocx-child/src/routes.rs +236 -0
  33. package/native/ocx-child/src/state.rs +190 -0
  34. package/native/ocx-child/src/test_hooks.rs +58 -0
  35. package/native/ocx-child/src/toml_surgeon.rs +1156 -0
  36. package/package.json +8 -2
  37. package/src/adapters/anthropic.ts +28 -2
  38. package/src/adapters/claude-cli/adapter.ts +5 -25
  39. package/src/adapters/claude-cli/instruction-images.ts +31 -0
  40. package/src/adapters/claude-cli/stable-replay.ts +42 -14
  41. package/src/adapters/claude-cli/usage-admission.ts +53 -64
  42. package/src/adapters/coding-agent/protocol.ts +1 -1
  43. package/src/adapters/devin/live-models.ts +3 -0
  44. package/src/adapters/google-http.ts +3 -0
  45. package/src/adapters/google-vertex-key-project.ts +10 -2
  46. package/src/adapters/google.ts +40 -8
  47. package/src/adapters/kiro/usage.ts +3 -13
  48. package/src/adapters/openai-responses/passthrough.ts +5 -2
  49. package/src/adapters/openai-responses/request-strips.ts +32 -0
  50. package/src/adapters/openai-responses/tool-schema.ts +9 -4
  51. package/src/chat/inbound.ts +1 -1
  52. package/src/claude/auth-detect.ts +26 -8
  53. package/src/claude/inbound-content-options.ts +18 -3
  54. package/src/claude/inbound.ts +5 -2
  55. package/src/cli/bundled-bun-diagnostic.ts +91 -0
  56. package/src/cli/capabilities-agents-routing.ts +2 -2
  57. package/src/cli/capabilities-observe-system.ts +60 -0
  58. package/src/cli/combo-input.ts +6 -0
  59. package/src/cli/combo-result.ts +1 -1
  60. package/src/cli/combo.ts +4 -0
  61. package/src/cli/config-command.ts +16 -2
  62. package/src/cli/connect.ts +12 -10
  63. package/src/cli/dispatch.ts +4 -0
  64. package/src/cli/doctor.ts +11 -0
  65. package/src/cli/help.ts +1 -0
  66. package/src/cli/init.ts +4 -0
  67. package/src/cli/link-enrollment.ts +152 -25
  68. package/src/cli/link-local-control.ts +49 -0
  69. package/src/cli/link.ts +37 -10
  70. package/src/cli/provider-lifecycle-runtime.ts +4 -2
  71. package/src/cli/registry.ts +13 -0
  72. package/src/cli/star-prompt.ts +2 -0
  73. package/src/cli/status.ts +1 -1
  74. package/src/cli/telemetry-profile.ts +206 -0
  75. package/src/cli/telemetry.ts +260 -0
  76. package/src/client/hub-relay.ts +26 -0
  77. package/src/client/machine-api.ts +3 -0
  78. package/src/clients/config-export/t3code.ts +44 -5
  79. package/src/clients/omo-role-models.ts +1 -1
  80. package/src/codex/catalog/bundled.ts +44 -2
  81. package/src/codex/runtime.ts +12 -0
  82. package/src/codex/shim-restore-lock.ts +67 -30
  83. package/src/combos/types.ts +21 -1
  84. package/src/config/atomic-write.ts +24 -1
  85. package/src/config/diagnostics.ts +15 -0
  86. package/src/config/live-reconcile.ts +17 -0
  87. package/src/config/load-degrade.ts +16 -0
  88. package/src/config/provider-validation.ts +29 -0
  89. package/src/config/schema/config-schema.ts +24 -0
  90. package/src/config/schema/leaf-validators.ts +17 -0
  91. package/src/config/telemetry-carry.ts +30 -0
  92. package/src/config.ts +13 -1
  93. package/src/generated/compatibility-version.json +405 -153
  94. package/src/generated/model-metadata.ts +3 -3
  95. package/src/integrations/aside-profiles.ts +7 -1
  96. package/src/integrations/owned-refresh.ts +9 -2
  97. package/src/lab/artifacts/secure-fs.ts +12 -11
  98. package/src/lab/fabric/scratch.ts +11 -9
  99. package/src/lab/public/community.ts +2 -3
  100. package/src/lab/public/file-safety.ts +18 -20
  101. package/src/lab/public/mutation-lock.ts +109 -337
  102. package/src/lab/public/private-file.ts +4 -3
  103. package/src/lib/bun-runtime-preflight.ts +1 -1
  104. package/src/lib/codex-catalog-read-only.ts +122 -0
  105. package/src/lib/config-ownership.ts +49 -18
  106. package/src/lib/errors.ts +11 -0
  107. package/src/lib/gcp-adc.ts +167 -48
  108. package/src/lib/jsonc.ts +4 -2
  109. package/src/lib/local-control-socket.ts +88 -0
  110. package/src/lib/privacy.ts +15 -0
  111. package/src/lib/provider-client-headers.ts +3 -0
  112. package/src/lib/token-estimate.ts +13 -2
  113. package/src/link/child-binary-source.ts +228 -0
  114. package/src/link/ephemeral-child.ts +45 -0
  115. package/src/link/remote-plant.ts +306 -0
  116. package/src/link/remote-windows.ts +59 -5
  117. package/src/link/ssh-argv.ts +71 -8
  118. package/src/link/status-projection.ts +2 -0
  119. package/src/link/store.ts +5 -1
  120. package/src/oauth/claude-keychain-read.ts +165 -0
  121. package/src/oauth/local-token-detect.ts +14 -17
  122. package/src/protocols/envelope.ts +20 -2
  123. package/src/providers/api-key-selection.ts +8 -2
  124. package/src/providers/claude-cli-usage-state.ts +93 -0
  125. package/src/providers/github-copilot-auto.ts +25 -5
  126. package/src/providers/meta-muse-plan-refusal.ts +94 -0
  127. package/src/providers/model-rename-fields.ts +3 -0
  128. package/src/providers/quota/vendor-probes-key.ts +23 -4
  129. package/src/providers/quota/vendor-probes-oauth.ts +59 -0
  130. package/src/providers/quota/workbuddy.ts +2 -2
  131. package/src/providers/quota.ts +25 -18
  132. package/src/providers/registry/entries-core.ts +7 -4
  133. package/src/providers/registry/entries-extended.ts +39 -7
  134. package/src/providers/registry/model-seeds.ts +10 -2
  135. package/src/providers/resolved-model-policy.ts +4 -0
  136. package/src/providers/routed-config.ts +30 -3
  137. package/src/providers/stale-no-vision-seed-migration.ts +7 -0
  138. package/src/providers/vertex-environment-authority.ts +50 -0
  139. package/src/providers/workbuddy-credit-balance.ts +38 -6
  140. package/src/quota-pool/assemble.ts +14 -6
  141. package/src/router.ts +1 -0
  142. package/src/server/adapter-resolve.ts +11 -6
  143. package/src/server/audio-dictation.ts +21 -7
  144. package/src/server/auth-cors.ts +19 -0
  145. package/src/server/background-lifecycle.ts +71 -0
  146. package/src/server/chat-completions.ts +2 -0
  147. package/src/server/claude-messages.ts +30 -3
  148. package/src/server/index/live-sideband.ts +15 -1
  149. package/src/server/index/local-control-listener.ts +515 -0
  150. package/src/server/index/optional-listeners.ts +21 -1
  151. package/src/server/index/serve-options.ts +4 -3
  152. package/src/server/index/websocket-handler.ts +2 -0
  153. package/src/server/index.ts +3 -0
  154. package/src/server/management/combo-routes.ts +6 -1
  155. package/src/server/management/context.ts +1 -0
  156. package/src/server/management/link-child-preflight.ts +74 -0
  157. package/src/server/management/link-enrollment.ts +190 -25
  158. package/src/server/management/link-route-state.ts +6 -1
  159. package/src/server/management/link-routes.ts +27 -9
  160. package/src/server/management/model-rows.ts +4 -0
  161. package/src/server/management/oauth-account-routes.ts +9 -4
  162. package/src/server/management/provider-overwrite-carry.ts +9 -2
  163. package/src/server/management/provider-routes.ts +14 -0
  164. package/src/server/management/provider-thinking-display-patch.ts +54 -0
  165. package/src/server/management/route-registry.ts +7 -0
  166. package/src/server/management/session-routes.ts +4 -1
  167. package/src/server/management/telemetry-routes.ts +37 -0
  168. package/src/server/management/usage-aggregate-cache.ts +290 -67
  169. package/src/server/management-api.ts +11 -2
  170. package/src/server/messages-native-preflight.ts +166 -0
  171. package/src/server/messages-native.ts +143 -43
  172. package/src/server/messages-shared.ts +14 -0
  173. package/src/server/proxy-liveness.ts +99 -6
  174. package/src/server/request-log-conversation.ts +18 -2
  175. package/src/server/request-log.ts +7 -2
  176. package/src/server/responses/adapter-continuation.ts +1 -0
  177. package/src/server/responses/adapter-dispatch.ts +11 -28
  178. package/src/server/responses/adapter-failure-message.ts +68 -0
  179. package/src/server/responses/combo-stream-preflight.ts +14 -2
  180. package/src/server/responses/core-auth.ts +26 -5
  181. package/src/server/responses/core-codex-account.ts +8 -1
  182. package/src/server/responses/core-combo-failure.ts +6 -1
  183. package/src/server/responses/core-combo-native.ts +150 -37
  184. package/src/server/responses/core-combo.ts +15 -9
  185. package/src/server/responses/core-normalize.ts +1 -0
  186. package/src/server/responses/core-options.ts +7 -1
  187. package/src/server/responses/core-pipeline.ts +21 -1
  188. package/src/server/responses/fetch-helpers.ts +5 -0
  189. package/src/server/responses/opengateway-completion-guard.ts +7 -3
  190. package/src/server/responses/passthrough-delivery.ts +8 -1
  191. package/src/server/responses/passthrough-error.ts +22 -0
  192. package/src/server/responses/request-prepare.ts +7 -1
  193. package/src/server/responses/request-transport.ts +28 -5
  194. package/src/server/responses/run-turn-execution.ts +13 -0
  195. package/src/server/sse-frame-buffer.ts +5 -0
  196. package/src/server/ws-bridge.ts +10 -0
  197. package/src/service/launchd.ts +78 -4
  198. package/src/telemetry/aggregate.ts +348 -0
  199. package/src/telemetry/consent.ts +128 -0
  200. package/src/telemetry/contract.ts +403 -0
  201. package/src/telemetry/disclosure.ts +19 -0
  202. package/src/telemetry/install-id.ts +226 -0
  203. package/src/telemetry/payload.ts +129 -0
  204. package/src/telemetry/profile/client.ts +150 -0
  205. package/src/telemetry/profile/contract.ts +288 -0
  206. package/src/telemetry/profile/disclosure.ts +14 -0
  207. package/src/telemetry/profile/paths.ts +13 -0
  208. package/src/telemetry/profile/routes.ts +99 -0
  209. package/src/telemetry/profile/service.ts +234 -0
  210. package/src/telemetry/profile/state.ts +189 -0
  211. package/src/telemetry/profile/sync.ts +276 -0
  212. package/src/telemetry/routes.ts +183 -0
  213. package/src/telemetry/scheduler.ts +386 -0
  214. package/src/telemetry/sender.ts +97 -0
  215. package/src/telemetry/state.ts +334 -0
  216. package/src/types/combo-jev-effort-mode.ts +11 -0
  217. package/src/types/config.ts +3 -0
  218. package/src/types/provider.ts +11 -1
  219. package/src/types/request.ts +2 -0
  220. package/src/types/telemetry.ts +15 -0
  221. package/src/types/wire.ts +10 -0
  222. package/src/types.ts +5 -0
  223. package/src/update/index.ts +7 -1
  224. package/src/update/minisign.d.mts +17 -0
  225. package/src/update/minisign.mjs +88 -0
  226. package/src/update/signed-supply.d.mts +59 -0
  227. package/src/update/signed-supply.mjs +289 -0
  228. package/src/update/trust-root.json +38 -0
  229. package/src/update/update-bounded-json.d.mts +4 -0
  230. package/src/update/update-bounded-json.mjs +113 -0
  231. package/src/update/update-bytes.d.mts +2 -0
  232. package/src/update/update-bytes.mjs +23 -0
  233. package/src/update/update-candidate-id.d.mts +2 -0
  234. package/src/update/update-candidate-id.mjs +23 -0
  235. package/src/update/update-checkpoint-codec.d.mts +33 -0
  236. package/src/update/update-checkpoint-codec.mjs +217 -0
  237. package/src/update/update-contracts.d.mts +24 -0
  238. package/src/update/update-contracts.mjs +207 -0
  239. package/src/update/update-signature-threshold.d.mts +12 -0
  240. package/src/update/update-signature-threshold.mjs +47 -0
  241. package/src/update/update-signed-version.d.mts +5 -0
  242. package/src/update/update-signed-version.mjs +25 -0
  243. package/src/update/update-trust-anchor.d.mts +2 -0
  244. package/src/update/update-trust-anchor.mjs +2 -0
  245. package/src/usage/cache-diagnostic.ts +195 -50
  246. package/src/usage/expected-prices.ts +20 -2
  247. package/src/usage/filter-index.ts +1469 -0
  248. package/src/usage/ledger-scanner.ts +245 -4
  249. package/src/usage/source-filter.ts +10 -2
  250. package/src/usage/summary.ts +16 -0
  251. package/src/web-search/parse.ts +244 -38
  252. package/gui/dist/assets/App-BepstgEN.js +0 -59
  253. package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
  254. package/gui/dist/assets/index-C-9X2yaI.js +0 -94
  255. package/gui/dist/assets/index-bnUWypyz.css +0 -2
  256. package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
  257. package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
  258. package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
@@ -0,0 +1,429 @@
1
+ //! Serialization and ownership of the shared `CODEX_HOME`.
2
+ //!
3
+ //! The lifecycle lock and journal live under `OPENCODEX_HOME/child`, but `config.toml`, the
4
+ //! model catalog and `models_cache.json` live in `CODEX_HOME`, which two ocx-child installs
5
+ //! with different `OPENCODEX_HOME`s can share. Every command that writes those files first
6
+ //! takes a fixed lock file inside the canonical `CODEX_HOME` and checks a durable ownership
7
+ //! record there. The lock file is never deleted or replaced, so every process locks the same
8
+ //! inode. Ownership is never taken over by PID or timeout: a foreign, unreadable or corrupt
9
+ //! record refuses without mutation.
10
+ //!
11
+ //! Lock order everywhere: local lifecycle lock, then this lock, then the daemon start gate.
12
+ //! The guarantee covers ocx-child against ocx-child; a full OpenCodex install is detected
13
+ //! separately by `journal::assert_no_full_ocx_conflict`.
14
+
15
+ use std::fs;
16
+ use std::io::{self, Read};
17
+ use std::path::{Path, PathBuf};
18
+
19
+ use serde::{Deserialize, Serialize};
20
+
21
+ use crate::journal::{remove_optional_file, validate_existing_journal_paths};
22
+ use crate::platform::{
23
+ DirectoryIdentity, FileLock, LockAcquireError, constant_time_eq, directory_identity,
24
+ random_hex, reject_symlink, write_private_atomic, write_regular_atomic,
25
+ };
26
+ use crate::state::ChildPaths;
27
+
28
+ pub const CODEX_HOME_LOCK_FILE: &str = ".ocx-child.lock";
29
+ pub const CODEX_HOME_OWNER_FILE: &str = ".ocx-child-owner.json";
30
+ pub const CODEX_HOME_OWNER_SCHEMA: &str = "ocx.child.codex-home-owner/1";
31
+ const MAX_OWNER_RECORD_BYTES: u64 = 16 * 1024;
32
+
33
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34
+ #[serde(rename_all = "kebab-case")]
35
+ pub enum OwnershipPhase {
36
+ Attaching,
37
+ Attached,
38
+ Detaching,
39
+ CleanupComplete,
40
+ }
41
+
42
+ /// Durable ownership record stored in `CODEX_HOME`. Holds no credentials.
43
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
45
+ pub struct CodexHomeOwnerRecord {
46
+ pub schema: String,
47
+ pub owner_id: String,
48
+ pub opencodex_home: String,
49
+ pub opencodex_home_identity: DirectoryIdentity,
50
+ pub codex_home: String,
51
+ pub codex_home_identity: DirectoryIdentity,
52
+ pub phase: OwnershipPhase,
53
+ }
54
+
55
+ #[derive(Debug, Clone, PartialEq, Eq)]
56
+ pub enum CodexHomeError {
57
+ /// Another process holds the lock (non-blocking acquisition only).
58
+ Busy,
59
+ /// `CODEX_HOME` does not exist and the caller did not ask to create it.
60
+ Missing,
61
+ /// The home is owned by a different OpenCodex home, or the record cannot be trusted.
62
+ Refused(String),
63
+ Io(String),
64
+ }
65
+
66
+ impl CodexHomeError {
67
+ pub fn message(&self) -> String {
68
+ match self {
69
+ Self::Busy => "Codex home is locked by another ocx-child lifecycle command".to_owned(),
70
+ Self::Missing => "Codex home does not exist".to_owned(),
71
+ Self::Refused(msg) | Self::Io(msg) => msg.clone(),
72
+ }
73
+ }
74
+ }
75
+
76
+ /// Failure of one guarded restoration step.
77
+ #[derive(Debug, Clone, PartialEq, Eq)]
78
+ pub enum RestoreStepError {
79
+ /// A home no longer matches its captured identity; restoration must stop and keep every
80
+ /// recovery record.
81
+ HomeChanged(String),
82
+ /// The write or removal itself failed.
83
+ Failed(String),
84
+ }
85
+
86
+ impl RestoreStepError {
87
+ pub fn into_message(self) -> String {
88
+ match self {
89
+ Self::HomeChanged(msg) | Self::Failed(msg) => msg,
90
+ }
91
+ }
92
+ }
93
+
94
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
95
+ pub enum ClaimPolicy {
96
+ /// Claim an unowned home, or continue owning ours. Refuses while our detach is incomplete.
97
+ Attach,
98
+ /// Continue an attachment: ours in an attach phase, or adopt an unowned home whose journal
99
+ /// already belongs to this OpenCodex home.
100
+ Continue,
101
+ /// Restore and release: never claims an unowned home, refuses only a foreign owner.
102
+ Detach,
103
+ }
104
+
105
+ enum OwnerStatus {
106
+ Absent,
107
+ Ours(CodexHomeOwnerRecord),
108
+ Foreign(String),
109
+ }
110
+
111
+ /// Proof that this process holds the `CODEX_HOME` lock and that the home is unowned or owned
112
+ /// by this OpenCodex home. Journal application and restoration take it as a parameter.
113
+ pub struct CodexHomeGuard {
114
+ _lock: FileLock,
115
+ paths: ChildPaths,
116
+ opencodex_identity: DirectoryIdentity,
117
+ codex_identity: DirectoryIdentity,
118
+ owner: Option<CodexHomeOwnerRecord>,
119
+ newly_claimed: bool,
120
+ phase_before_claim: Option<OwnershipPhase>,
121
+ }
122
+
123
+ fn canonical_utf8(path: &Path, what: &str) -> Result<(PathBuf, String), CodexHomeError> {
124
+ let canonical = fs::canonicalize(path).map_err(|e| {
125
+ if e.kind() == io::ErrorKind::NotFound {
126
+ CodexHomeError::Missing
127
+ } else {
128
+ CodexHomeError::Io(format!("cannot resolve {what}: {e}"))
129
+ }
130
+ })?;
131
+ let text = canonical
132
+ .to_str()
133
+ .ok_or_else(|| CodexHomeError::Io(format!("{what} is not UTF-8")))?
134
+ .to_owned();
135
+ Ok((canonical, text))
136
+ }
137
+
138
+ fn create_codex_home(path: &Path) -> Result<(), CodexHomeError> {
139
+ let mut builder = fs::DirBuilder::new();
140
+ builder.recursive(true);
141
+ #[cfg(unix)]
142
+ {
143
+ use std::os::unix::fs::DirBuilderExt;
144
+ builder.mode(0o700);
145
+ }
146
+ builder
147
+ .create(path)
148
+ .map_err(|e| CodexHomeError::Io(format!("cannot create Codex home: {e}")))
149
+ }
150
+
151
+ impl CodexHomeGuard {
152
+ /// Lock `CODEX_HOME` and classify its owner, then apply `policy`.
153
+ pub fn acquire(
154
+ paths: &ChildPaths,
155
+ blocking: bool,
156
+ create_codex_home_if_missing: bool,
157
+ policy: ClaimPolicy,
158
+ ) -> Result<Self, CodexHomeError> {
159
+ if create_codex_home_if_missing {
160
+ create_codex_home(&paths.codex_home)?;
161
+ }
162
+ let (ocx, _) = canonical_utf8(&paths.opencodex_home, "OpenCodex home").map_err(|e| {
163
+ if e == CodexHomeError::Missing {
164
+ CodexHomeError::Io("OpenCodex home does not exist".to_owned())
165
+ } else {
166
+ e
167
+ }
168
+ })?;
169
+ let (codex, _) = canonical_utf8(&paths.codex_home, "Codex home")?;
170
+ let opencodex_identity = directory_identity(&ocx).map_err(CodexHomeError::Io)?;
171
+ let codex_identity = directory_identity(&codex).map_err(CodexHomeError::Io)?;
172
+ let canonical = ChildPaths::new(ocx, codex);
173
+ let lock = FileLock::acquire_in_existing_dir(&canonical.codex_lock_path(), blocking)
174
+ .map_err(|e| match e {
175
+ LockAcquireError::Busy => CodexHomeError::Busy,
176
+ LockAcquireError::Io => {
177
+ CodexHomeError::Io("cannot open the Codex home lock file".to_owned())
178
+ }
179
+ })?;
180
+ let mut guard = Self {
181
+ _lock: lock,
182
+ paths: canonical,
183
+ opencodex_identity,
184
+ codex_identity,
185
+ owner: None,
186
+ newly_claimed: false,
187
+ phase_before_claim: None,
188
+ };
189
+ // The directory could have been replaced between resolution and locking.
190
+ guard.verify_homes().map_err(CodexHomeError::Refused)?;
191
+ guard.apply_policy(policy)?;
192
+ Ok(guard)
193
+ }
194
+
195
+ /// Canonical paths of the locked homes; use these for every guarded file operation.
196
+ pub fn paths(&self) -> &ChildPaths {
197
+ &self.paths
198
+ }
199
+
200
+ pub fn is_owner(&self) -> bool {
201
+ self.owner.is_some()
202
+ }
203
+
204
+ /// True when this guard created the ownership record (first attach).
205
+ pub fn newly_claimed(&self) -> bool {
206
+ self.newly_claimed
207
+ }
208
+
209
+ pub fn phase(&self) -> Option<OwnershipPhase> {
210
+ self.owner.as_ref().map(|r| r.phase)
211
+ }
212
+
213
+ /// Confirm both homes are still the directories identified when the lock was taken.
214
+ pub fn verify_homes(&self) -> Result<(), String> {
215
+ let ocx = directory_identity(&self.paths.opencodex_home)
216
+ .map_err(|e| format!("OpenCodex home changed during the operation: {e}"))?;
217
+ let codex = directory_identity(&self.paths.codex_home)
218
+ .map_err(|e| format!("Codex home changed during the operation: {e}"))?;
219
+ if ocx != self.opencodex_identity || codex != self.codex_identity {
220
+ return Err(
221
+ "a home directory was replaced during the operation; recovery records were kept"
222
+ .to_owned(),
223
+ );
224
+ }
225
+ Ok(())
226
+ }
227
+
228
+ /// Run one restoration write, rename or removal, re-verifying both home identities
229
+ /// immediately before and immediately after it. Paths must come from `paths()`.
230
+ ///
231
+ /// This narrows, but cannot close, the window between the check and the system call: a
232
+ /// process running as the same user can still swap a directory in between. Such a process
233
+ /// gains nothing from that, since it can already write these files directly.
234
+ pub fn restore_step<T>(
235
+ &self,
236
+ op: impl FnOnce() -> Result<T, String>,
237
+ ) -> Result<T, RestoreStepError> {
238
+ crate::test_hooks::barrier("restore-before-write");
239
+ self.verify_homes().map_err(RestoreStepError::HomeChanged)?;
240
+ let out = op().map_err(RestoreStepError::Failed);
241
+ crate::test_hooks::barrier("restore-after-write");
242
+ self.verify_homes().map_err(RestoreStepError::HomeChanged)?;
243
+ out
244
+ }
245
+
246
+ fn read_owner(&self) -> Result<OwnerStatus, CodexHomeError> {
247
+ let record_path = self.paths.codex_owner_path();
248
+ let corrupt = |detail: String| {
249
+ CodexHomeError::Refused(format!(
250
+ "Codex home ownership record {} is unreadable ({detail}); refusing to modify this \
251
+ Codex home. Remove it only after confirming no ocx-child uses this Codex home.",
252
+ record_path.display()
253
+ ))
254
+ };
255
+ reject_symlink(&record_path).map_err(&corrupt)?;
256
+ let file = match fs::File::open(&record_path) {
257
+ Ok(f) => f,
258
+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(OwnerStatus::Absent),
259
+ Err(e) => return Err(corrupt(e.to_string())),
260
+ };
261
+ let mut bytes = Vec::new();
262
+ file.take(MAX_OWNER_RECORD_BYTES + 1)
263
+ .read_to_end(&mut bytes)
264
+ .map_err(|e| corrupt(e.to_string()))?;
265
+ if bytes.len() as u64 > MAX_OWNER_RECORD_BYTES {
266
+ return Err(corrupt("record exceeds size limit".to_owned()));
267
+ }
268
+ let record: CodexHomeOwnerRecord =
269
+ serde_json::from_slice(&bytes).map_err(|e| corrupt(e.to_string()))?;
270
+ if record.schema != CODEX_HOME_OWNER_SCHEMA {
271
+ return Err(corrupt(format!("unsupported schema {}", record.schema)));
272
+ }
273
+ let ours = record.opencodex_home == path_text(&self.paths.opencodex_home)
274
+ && record.opencodex_home_identity == self.opencodex_identity
275
+ && record.codex_home == path_text(&self.paths.codex_home)
276
+ && record.codex_home_identity == self.codex_identity
277
+ && self
278
+ .local_owner_id()
279
+ .map_err(CodexHomeError::Io)?
280
+ .is_some_and(|id| constant_time_eq(id.as_bytes(), record.owner_id.as_bytes()));
281
+ if ours {
282
+ return Ok(OwnerStatus::Ours(record));
283
+ }
284
+ Ok(OwnerStatus::Foreign(format!(
285
+ "Codex home {} is owned by another ocx-child (OPENCODEX_HOME={}); run \
286
+ `ocx-child detach` with that OPENCODEX_HOME first. If that home no longer exists, \
287
+ remove {} after confirming no ocx-child uses this Codex home.",
288
+ self.paths.codex_home.display(),
289
+ record.opencodex_home,
290
+ record_path.display()
291
+ )))
292
+ }
293
+
294
+ fn local_owner_id(&self) -> Result<Option<String>, String> {
295
+ reject_symlink(&self.paths.owner_id_file)?;
296
+ match fs::read(&self.paths.owner_id_file) {
297
+ Ok(bytes) => {
298
+ let text = String::from_utf8(bytes).unwrap_or_default();
299
+ let id = text.trim();
300
+ Ok(
301
+ (id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit()))
302
+ .then(|| id.to_owned()),
303
+ )
304
+ }
305
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
306
+ Err(e) => Err(format!("cannot read local owner id: {e}")),
307
+ }
308
+ }
309
+
310
+ fn apply_policy(&mut self, policy: ClaimPolicy) -> Result<(), CodexHomeError> {
311
+ match self.read_owner()? {
312
+ OwnerStatus::Foreign(msg) => Err(CodexHomeError::Refused(msg)),
313
+ OwnerStatus::Ours(record) => {
314
+ let phase = record.phase;
315
+ self.owner = Some(record);
316
+ match (policy, phase) {
317
+ (ClaimPolicy::Detach, _) => Ok(()),
318
+ (ClaimPolicy::Attach, OwnershipPhase::Detaching)
319
+ | (ClaimPolicy::Continue, OwnershipPhase::Detaching)
320
+ | (ClaimPolicy::Continue, OwnershipPhase::CleanupComplete) => {
321
+ Err(CodexHomeError::Refused(
322
+ "a previous ocx-child detach of this Codex home is incomplete; \
323
+ run `ocx-child detach` again"
324
+ .to_owned(),
325
+ ))
326
+ }
327
+ (ClaimPolicy::Attach, _) => {
328
+ self.phase_before_claim = Some(phase);
329
+ self.set_phase(OwnershipPhase::Attaching)
330
+ .map_err(CodexHomeError::Io)
331
+ }
332
+ (ClaimPolicy::Continue, _) => Ok(()),
333
+ }
334
+ }
335
+ OwnerStatus::Absent => match policy {
336
+ ClaimPolicy::Detach => Ok(()),
337
+ ClaimPolicy::Attach => {
338
+ // A journal of ours that targets another Codex home must not gain a
339
+ // second ownership record; journal validation reports the conflict.
340
+ validate_existing_journal_paths(&self.paths)
341
+ .map_err(CodexHomeError::Refused)?;
342
+ self.claim(OwnershipPhase::Attaching)
343
+ }
344
+ ClaimPolicy::Continue => match validate_existing_journal_paths(&self.paths) {
345
+ Ok(true) => self.claim(OwnershipPhase::Attached),
346
+ Ok(false) => Ok(()),
347
+ Err(e) => Err(CodexHomeError::Refused(e)),
348
+ },
349
+ },
350
+ }
351
+ }
352
+
353
+ fn claim(&mut self, phase: OwnershipPhase) -> Result<(), CodexHomeError> {
354
+ let owner_id = match self.local_owner_id().map_err(CodexHomeError::Io)? {
355
+ Some(id) => id,
356
+ None => {
357
+ let id = random_hex(16).map_err(CodexHomeError::Io)?;
358
+ write_private_atomic(&self.paths.owner_id_file, id.as_bytes())
359
+ .map_err(CodexHomeError::Io)?;
360
+ id
361
+ }
362
+ };
363
+ let record = CodexHomeOwnerRecord {
364
+ schema: CODEX_HOME_OWNER_SCHEMA.to_owned(),
365
+ owner_id,
366
+ opencodex_home: path_text(&self.paths.opencodex_home),
367
+ opencodex_home_identity: self.opencodex_identity.clone(),
368
+ codex_home: path_text(&self.paths.codex_home),
369
+ codex_home_identity: self.codex_identity.clone(),
370
+ phase,
371
+ };
372
+ self.write_record(&record).map_err(CodexHomeError::Io)?;
373
+ self.owner = Some(record);
374
+ self.newly_claimed = true;
375
+ Ok(())
376
+ }
377
+
378
+ fn write_record(&self, record: &CodexHomeOwnerRecord) -> Result<(), String> {
379
+ self.verify_homes()?;
380
+ let mut bytes = serde_json::to_vec_pretty(record)
381
+ .map_err(|e| format!("cannot serialize ownership record: {e}"))?;
382
+ bytes.push(b'\n');
383
+ write_regular_atomic(&self.paths.codex_owner_path(), &bytes)
384
+ }
385
+
386
+ /// Durably record a new phase. A no-op when this guard does not own the home.
387
+ pub fn set_phase(&mut self, phase: OwnershipPhase) -> Result<(), String> {
388
+ let Some(mut record) = self.owner.clone() else {
389
+ return Ok(());
390
+ };
391
+ if record.phase == phase {
392
+ return Ok(());
393
+ }
394
+ record.phase = phase;
395
+ self.write_record(&record)?;
396
+ self.owner = Some(record);
397
+ Ok(())
398
+ }
399
+
400
+ /// Undo this guard's claim after an attach failed without leaving changes behind: release
401
+ /// a record this guard created, or put back the phase an existing record had.
402
+ pub fn revert_claim(&mut self) -> Result<(), String> {
403
+ if self.newly_claimed {
404
+ return self.release();
405
+ }
406
+ match self.phase_before_claim.take() {
407
+ Some(phase) => self.set_phase(phase),
408
+ None => Ok(()),
409
+ }
410
+ }
411
+
412
+ /// Release ownership after cleanup: durably mark cleanup complete, then remove the record,
413
+ /// then the local owner id. A crash at any step leaves a record `detach` can resume from.
414
+ pub fn release(&mut self) -> Result<(), String> {
415
+ if self.owner.is_none() {
416
+ return Ok(());
417
+ }
418
+ self.set_phase(OwnershipPhase::CleanupComplete)?;
419
+ self.verify_homes()?;
420
+ remove_optional_file(&self.paths.codex_owner_path())?;
421
+ self.owner = None;
422
+ self.newly_claimed = false;
423
+ remove_optional_file(&self.paths.owner_id_file)
424
+ }
425
+ }
426
+
427
+ fn path_text(path: &Path) -> String {
428
+ path.to_str().unwrap_or_default().to_owned()
429
+ }
@@ -0,0 +1,231 @@
1
+ use serde::{Deserialize, Serialize};
2
+
3
+ use crate::platform::sha256_hex;
4
+
5
+ pub const HOME_CODEX_SETTINGS_VERSION: u32 = 1;
6
+
7
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
9
+ pub struct SubagentDefaults {
10
+ pub model: String,
11
+ pub reasoning_effort: Option<String>,
12
+ }
13
+
14
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
16
+ pub struct HomeCodexSettings {
17
+ pub fast_mode: Option<bool>,
18
+ pub multi_agent_mode: Option<String>,
19
+ pub web_search_sidecar_enabled: bool,
20
+ pub subagent_defaults: Option<SubagentDefaults>,
21
+ }
22
+
23
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
25
+ pub struct HomeIdentity {
26
+ pub name: String,
27
+ pub version: String,
28
+ }
29
+
30
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
32
+ pub struct HomeCodexSettingsDocument {
33
+ pub version: u32,
34
+ pub home: HomeIdentity,
35
+ pub settings: HomeCodexSettings,
36
+ }
37
+
38
+ fn is_ecmascript_whitespace(ch: char) -> bool {
39
+ matches!(
40
+ ch as u32,
41
+ 0x0009 | 0x000A | 0x000B | 0x000C | 0x000D | 0x0020 | 0x00A0 | 0x1680 | 0x2000
42
+ ..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 | 0xFEFF
43
+ )
44
+ }
45
+
46
+ pub fn sanitize_safe_label(value: &str, max_utf16_units: usize) -> Option<String> {
47
+ let trimmed = value.trim_matches(is_ecmascript_whitespace);
48
+ let utf16_len = trimmed.encode_utf16().count();
49
+ if trimmed.is_empty() || utf16_len > max_utf16_units {
50
+ return None;
51
+ }
52
+ for ch in trimmed.chars() {
53
+ let cp = ch as u32;
54
+ if cp < 0x20
55
+ || cp == 0x7f
56
+ || (0x202a..=0x202e).contains(&cp)
57
+ || (0x2066..=0x2069).contains(&cp)
58
+ {
59
+ return None;
60
+ }
61
+ }
62
+ Some(trimmed.to_owned())
63
+ }
64
+
65
+ pub fn is_valid_reasoning_effort_token(value: &str) -> bool {
66
+ let bytes = value.as_bytes();
67
+ if bytes.is_empty() || bytes.len() > 32 {
68
+ return false;
69
+ }
70
+ if !bytes[0].is_ascii_lowercase() {
71
+ return false;
72
+ }
73
+ bytes[1..]
74
+ .iter()
75
+ .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
76
+ }
77
+
78
+ fn exact_keys(obj: &serde_json::Map<String, serde_json::Value>, keys: &[&str]) -> bool {
79
+ obj.len() == keys.len() && keys.iter().all(|k| obj.contains_key(*k))
80
+ }
81
+
82
+ /// Strict parser matching `parseHomeCodexSettingsDocument` in `src/link/codex-settings.ts`.
83
+ pub fn parse_home_codex_settings_document(bytes: &[u8]) -> Option<HomeCodexSettingsDocument> {
84
+ let root: serde_json::Value = serde_json::from_slice(bytes).ok()?;
85
+ let root_obj = root.as_object()?;
86
+ if !exact_keys(root_obj, &["version", "home", "settings"]) {
87
+ return None;
88
+ }
89
+ let version = root_obj.get("version")?.as_u64()?;
90
+ if version != u64::from(HOME_CODEX_SETTINGS_VERSION) {
91
+ return None;
92
+ }
93
+ let home_obj = root_obj.get("home")?.as_object()?;
94
+ if !exact_keys(home_obj, &["name", "version"]) {
95
+ return None;
96
+ }
97
+ let name = sanitize_safe_label(home_obj.get("name")?.as_str()?, 255)?;
98
+ let home_version = sanitize_safe_label(home_obj.get("version")?.as_str()?, 64)?;
99
+ let s_obj = root_obj.get("settings")?.as_object()?;
100
+ if !exact_keys(
101
+ s_obj,
102
+ &[
103
+ "fastMode",
104
+ "multiAgentMode",
105
+ "webSearchSidecarEnabled",
106
+ "subagentDefaults",
107
+ ],
108
+ ) {
109
+ return None;
110
+ }
111
+ let fast_mode = match s_obj.get("fastMode")? {
112
+ serde_json::Value::Null => None,
113
+ serde_json::Value::Bool(b) => Some(*b),
114
+ _ => return None,
115
+ };
116
+ let multi_agent_mode = match s_obj.get("multiAgentMode")? {
117
+ serde_json::Value::Null => None,
118
+ serde_json::Value::String(m) if matches!(m.as_str(), "v1" | "default" | "v2") => {
119
+ Some(m.clone())
120
+ }
121
+ _ => return None,
122
+ };
123
+ let web_search_sidecar_enabled = s_obj.get("webSearchSidecarEnabled")?.as_bool()?;
124
+ let subagent_defaults = match s_obj.get("subagentDefaults")? {
125
+ serde_json::Value::Null => None,
126
+ serde_json::Value::Object(d_obj) => {
127
+ if !exact_keys(d_obj, &["model", "reasoningEffort"]) {
128
+ return None;
129
+ }
130
+ let model = sanitize_safe_label(d_obj.get("model")?.as_str()?, 256)?;
131
+ let reasoning_effort = match d_obj.get("reasoningEffort")? {
132
+ serde_json::Value::Null => None,
133
+ serde_json::Value::String(eff) if is_valid_reasoning_effort_token(eff) => {
134
+ Some(eff.clone())
135
+ }
136
+ _ => return None,
137
+ };
138
+ Some(SubagentDefaults {
139
+ model,
140
+ reasoning_effort,
141
+ })
142
+ }
143
+ _ => return None,
144
+ };
145
+ Some(HomeCodexSettingsDocument {
146
+ version: HOME_CODEX_SETTINGS_VERSION,
147
+ home: HomeIdentity {
148
+ name,
149
+ version: home_version,
150
+ },
151
+ settings: HomeCodexSettings {
152
+ fast_mode,
153
+ multi_agent_mode,
154
+ web_search_sidecar_enabled,
155
+ subagent_defaults,
156
+ },
157
+ })
158
+ }
159
+
160
+ impl HomeCodexSettings {
161
+ pub fn validate(&self) -> bool {
162
+ if let Some(mode) = &self.multi_agent_mode
163
+ && !matches!(mode.as_str(), "v1" | "default" | "v2")
164
+ {
165
+ return false;
166
+ }
167
+ if let Some(sub) = &self.subagent_defaults {
168
+ if sanitize_safe_label(&sub.model, 256).is_none() {
169
+ return false;
170
+ }
171
+ if let Some(eff) = &sub.reasoning_effort
172
+ && !is_valid_reasoning_effort_token(eff)
173
+ {
174
+ return false;
175
+ }
176
+ }
177
+ true
178
+ }
179
+ }
180
+
181
+ impl HomeCodexSettingsDocument {
182
+ pub fn validate(&self) -> bool {
183
+ self.version == HOME_CODEX_SETTINGS_VERSION
184
+ && sanitize_safe_label(&self.home.name, 255).is_some()
185
+ && sanitize_safe_label(&self.home.version, 64).is_some()
186
+ && self.settings.validate()
187
+ }
188
+ }
189
+
190
+ #[derive(Serialize)]
191
+ struct DigestEnvelope<'a> {
192
+ version: u32,
193
+ settings: DigestSettings<'a>,
194
+ }
195
+
196
+ #[derive(Serialize)]
197
+ #[serde(rename_all = "camelCase")]
198
+ struct DigestSettings<'a> {
199
+ fast_mode: Option<bool>,
200
+ multi_agent_mode: &'a Option<String>,
201
+ web_search_sidecar_enabled: bool,
202
+ subagent_defaults: Option<DigestSubagent<'a>>,
203
+ }
204
+
205
+ #[derive(Serialize)]
206
+ #[serde(rename_all = "camelCase")]
207
+ struct DigestSubagent<'a> {
208
+ model: &'a str,
209
+ reasoning_effort: &'a Option<String>,
210
+ }
211
+
212
+ /// Produces the exact OCX-6 compact JSON string hashed by `codexSettingsDigest` in `src/link/codex-settings.ts`.
213
+ pub fn codex_settings_digest_payload(settings: &HomeCodexSettings) -> String {
214
+ let env = DigestEnvelope {
215
+ version: HOME_CODEX_SETTINGS_VERSION,
216
+ settings: DigestSettings {
217
+ fast_mode: settings.fast_mode,
218
+ multi_agent_mode: &settings.multi_agent_mode,
219
+ web_search_sidecar_enabled: settings.web_search_sidecar_enabled,
220
+ subagent_defaults: settings.subagent_defaults.as_ref().map(|d| DigestSubagent {
221
+ model: &d.model,
222
+ reasoning_effort: &d.reasoning_effort,
223
+ }),
224
+ },
225
+ };
226
+ serde_json::to_string(&env).expect("DigestEnvelope serialization is infallible")
227
+ }
228
+
229
+ pub fn codex_settings_digest(settings: &HomeCodexSettings) -> String {
230
+ sha256_hex(codex_settings_digest_payload(settings).as_bytes())
231
+ }