@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,1156 @@
1
+ use serde::{Deserialize, Serialize};
2
+
3
+ use crate::codex_settings::HomeCodexSettings;
4
+
5
+ pub const OCX_SECTION_MARKER: &str = "# Auto-injected by opencodex";
6
+ pub const OCX_ROUTING_MARKER_LINE: &str = "# Auto-injected by opencodex (undo: ocx restore)";
7
+ pub const MANAGED_SUBAGENT_DEFAULT_MARKER: &str = "# Managed by opencodex: native subagent default";
8
+ pub const MANAGED_AGENTS_TABLE_MARKER: &str =
9
+ "# Managed by opencodex: native subagent defaults table";
10
+
11
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
12
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
13
+ pub struct WrittenSubagentDefaults {
14
+ pub default_subagent_model: String,
15
+ pub default_subagent_reasoning_effort: Option<String>,
16
+ }
17
+
18
+ #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
19
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
20
+ pub struct ChildInjectedLedger {
21
+ pub openai_base_url: Option<String>,
22
+ pub experimental_realtime_ws_base_url: Option<String>,
23
+ pub model_catalog_json: Option<String>,
24
+ pub injected_web_search: Option<String>,
25
+ pub replaced_user_web_search_line: Option<String>,
26
+ pub wrote_fast_mode: Option<bool>,
27
+ #[serde(default)]
28
+ pub prior_user_fast_mode_line: Option<String>,
29
+ pub wrote_multi_agent_v2: Option<bool>,
30
+ #[serde(default)]
31
+ pub prior_user_multi_agent_v2_line: Option<String>,
32
+ pub wrote_subagent_defaults: Option<WrittenSubagentDefaults>,
33
+ }
34
+
35
+ pub fn dominant_eol(content: &str) -> &'static str {
36
+ let crlf = content.matches("\r\n").count();
37
+ if crlf == 0 {
38
+ return "\n";
39
+ }
40
+ let total_lf = content.matches('\n').count();
41
+ let bare_lf = total_lf.saturating_sub(crlf);
42
+ if crlf >= bare_lf { "\r\n" } else { "\n" }
43
+ }
44
+
45
+ pub fn apply_eol(content: &str, eol: &str) -> String {
46
+ let lf = content.replace("\r\n", "\n");
47
+ if eol == "\n" {
48
+ lf
49
+ } else {
50
+ lf.replace('\n', "\r\n")
51
+ }
52
+ }
53
+
54
+ pub fn is_ocx_routing_marker_line(line: &str) -> bool {
55
+ let t = line.trim();
56
+ t == OCX_SECTION_MARKER || t == OCX_ROUTING_MARKER_LINE
57
+ }
58
+
59
+ pub fn toml_escape_basic_string(value: &str) -> String {
60
+ let mut out = String::with_capacity(value.len() + 2);
61
+ out.push('"');
62
+ for ch in value.chars() {
63
+ match ch {
64
+ '\\' => out.push_str("\\\\"),
65
+ '"' => out.push_str("\\\""),
66
+ '\u{0008}' => out.push_str("\\b"),
67
+ '\u{000c}' => out.push_str("\\f"),
68
+ '\n' => out.push_str("\\n"),
69
+ '\r' => out.push_str("\\r"),
70
+ '\t' => out.push_str("\\t"),
71
+ c if (c as u32) < 0x20 || c == '\u{007f}' => {
72
+ out.push_str(&format!("\\u{:04X}", c as u32));
73
+ }
74
+ c => out.push(c),
75
+ }
76
+ }
77
+ out.push('"');
78
+ out
79
+ }
80
+
81
+ fn parse_toml_quoted_string(raw_val: &str) -> Option<String> {
82
+ let trimmed = strip_inline_comment(raw_val).trim();
83
+ if trimmed.len() >= 2 && trimmed.starts_with('\'') && trimmed.ends_with('\'') {
84
+ let inner = &trimmed[1..trimmed.len() - 1];
85
+ if inner.contains('\'') {
86
+ return None;
87
+ }
88
+ return Some(inner.to_owned());
89
+ }
90
+ if trimmed.len() >= 2 && trimmed.starts_with('"') && trimmed.ends_with('"') {
91
+ let inner = &trimmed[1..trimmed.len() - 1];
92
+ let mut out = String::with_capacity(inner.len());
93
+ let mut chars = inner.chars();
94
+ while let Some(ch) = chars.next() {
95
+ if ch == '\\' {
96
+ match chars.next()? {
97
+ '\\' => out.push('\\'),
98
+ '"' => out.push('"'),
99
+ 'b' => out.push('\u{0008}'),
100
+ 'f' => out.push('\u{000c}'),
101
+ 'n' => out.push('\n'),
102
+ 'r' => out.push('\r'),
103
+ 't' => out.push('\t'),
104
+ 'u' => {
105
+ let mut hex = String::with_capacity(4);
106
+ for _ in 0..4 {
107
+ hex.push(chars.next()?);
108
+ }
109
+ let cp = u32::from_str_radix(&hex, 16).ok()?;
110
+ out.push(char::from_u32(cp)?);
111
+ }
112
+ 'U' => {
113
+ let mut hex = String::with_capacity(8);
114
+ for _ in 0..8 {
115
+ hex.push(chars.next()?);
116
+ }
117
+ let cp = u32::from_str_radix(&hex, 16).ok()?;
118
+ out.push(char::from_u32(cp)?);
119
+ }
120
+ _ => return None,
121
+ }
122
+ } else if ch == '"' {
123
+ return None;
124
+ } else {
125
+ out.push(ch);
126
+ }
127
+ }
128
+ return Some(out);
129
+ }
130
+ None
131
+ }
132
+
133
+ fn strip_inline_comment(val: &str) -> &str {
134
+ let mut in_basic = false;
135
+ let mut in_literal = false;
136
+ let mut escaped = false;
137
+ for (idx, ch) in val.char_indices() {
138
+ if escaped {
139
+ escaped = false;
140
+ continue;
141
+ }
142
+ if in_basic {
143
+ if ch == '\\' {
144
+ escaped = true;
145
+ } else if ch == '"' {
146
+ in_basic = false;
147
+ }
148
+ } else if in_literal {
149
+ if ch == '\'' {
150
+ in_literal = false;
151
+ }
152
+ } else {
153
+ match ch {
154
+ '"' => in_basic = true,
155
+ '\'' => in_literal = true,
156
+ '#' => return &val[..idx],
157
+ _ => {}
158
+ }
159
+ }
160
+ }
161
+ val
162
+ }
163
+
164
+ pub fn parse_key_value_line(line: &str) -> Option<(String, &str)> {
165
+ let trimmed = line.trim();
166
+ if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
167
+ return None;
168
+ }
169
+ let (raw_key, rhs) = trimmed.split_once('=')?;
170
+ let key_trim = raw_key.trim();
171
+ let key = if (key_trim.starts_with('"') && key_trim.ends_with('"'))
172
+ || (key_trim.starts_with('\'') && key_trim.ends_with('\''))
173
+ {
174
+ parse_toml_quoted_string(key_trim)?
175
+ } else if !key_trim.is_empty()
176
+ && key_trim
177
+ .bytes()
178
+ .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
179
+ {
180
+ key_trim.to_owned()
181
+ } else {
182
+ return None;
183
+ };
184
+ Some((key, rhs.trim()))
185
+ }
186
+
187
+ pub fn parse_single_line_string_assignment(
188
+ line: &str,
189
+ expected_key: &str,
190
+ ) -> Result<Option<String>, String> {
191
+ let Some((key, rhs)) = parse_key_value_line(line) else {
192
+ return Ok(None);
193
+ };
194
+ if key != expected_key {
195
+ return Ok(None);
196
+ }
197
+ parse_toml_quoted_string(rhs)
198
+ .map(Some)
199
+ .ok_or_else(|| format!("corrupt or multiline string assignment for {expected_key}"))
200
+ }
201
+
202
+ fn is_table_header(line: &str) -> bool {
203
+ let t = line.trim();
204
+ t.starts_with('[') && !t.starts_with('#')
205
+ }
206
+
207
+ fn parse_simple_table_name(line: &str) -> Option<String> {
208
+ let t = strip_inline_comment(line).trim();
209
+ if !t.starts_with('[') || t.starts_with("[") && t.starts_with("[[") || !t.ends_with(']') {
210
+ return None;
211
+ }
212
+ let inner = t[1..t.len() - 1].trim();
213
+ if (inner.starts_with('"') && inner.ends_with('"'))
214
+ || (inner.starts_with('\'') && inner.ends_with('\''))
215
+ {
216
+ parse_toml_quoted_string(inner)
217
+ } else {
218
+ Some(inner.to_owned())
219
+ }
220
+ }
221
+
222
+ #[derive(Clone, Copy, PartialEq, Eq)]
223
+ enum MultilineQuote {
224
+ Basic,
225
+ Literal,
226
+ }
227
+
228
+ fn quote_run_length(bytes: &[u8], start: usize, quote: u8) -> usize {
229
+ let mut end = start;
230
+ while end < bytes.len() && bytes[end] == quote && end - start < 5 {
231
+ end += 1;
232
+ }
233
+ end - start
234
+ }
235
+
236
+ /// Ports `markStructuralLines` (`src/codex/toml-source-lines.ts:158-223`) so lines beginning
237
+ /// inside multiline strings (`"""`/`'''`) or multiline arrays/inline tables are never treated
238
+ /// as table headers, root keys, or ownership markers. Returns `(structural_flags, unclosed_multiline)`.
239
+ pub fn mark_structural_lines<S: AsRef<str>>(lines: &[S]) -> (Vec<bool>, bool) {
240
+ let mut multiline: Option<MultilineQuote> = None;
241
+ let mut square_depth: usize = 0;
242
+ let mut curly_depth: usize = 0;
243
+ let mut flags = Vec::with_capacity(lines.len());
244
+
245
+ for raw in lines {
246
+ let text = raw.as_ref();
247
+ flags.push(multiline.is_none() && square_depth == 0 && curly_depth == 0);
248
+ let mut single: Option<MultilineQuote> = None;
249
+ let bytes = text.as_bytes();
250
+ let mut idx = 0usize;
251
+ while idx < bytes.len() {
252
+ if let Some(MultilineQuote::Basic) = multiline {
253
+ if bytes[idx..].starts_with(b"\"\"\"") {
254
+ multiline = None;
255
+ idx += quote_run_length(bytes, idx, b'"');
256
+ } else if bytes[idx] == b'\\' {
257
+ idx = (idx + 2).min(bytes.len());
258
+ } else {
259
+ idx += 1;
260
+ }
261
+ continue;
262
+ }
263
+ if let Some(MultilineQuote::Literal) = multiline {
264
+ if bytes[idx..].starts_with(b"'''") {
265
+ multiline = None;
266
+ idx += quote_run_length(bytes, idx, b'\'');
267
+ } else {
268
+ idx += 1;
269
+ }
270
+ continue;
271
+ }
272
+ if let Some(MultilineQuote::Basic) = single {
273
+ if bytes[idx] == b'\\' {
274
+ idx = (idx + 2).min(bytes.len());
275
+ } else if bytes[idx] == b'"' {
276
+ single = None;
277
+ idx += 1;
278
+ } else {
279
+ idx += 1;
280
+ }
281
+ continue;
282
+ }
283
+ if let Some(MultilineQuote::Literal) = single {
284
+ if bytes[idx] == b'\'' {
285
+ single = None;
286
+ }
287
+ idx += 1;
288
+ continue;
289
+ }
290
+ if bytes[idx] == b'#' {
291
+ break;
292
+ }
293
+ if bytes[idx..].starts_with(b"\"\"\"") {
294
+ multiline = Some(MultilineQuote::Basic);
295
+ idx += 3;
296
+ } else if bytes[idx..].starts_with(b"'''") {
297
+ multiline = Some(MultilineQuote::Literal);
298
+ idx += 3;
299
+ } else if bytes[idx] == b'"' {
300
+ single = Some(MultilineQuote::Basic);
301
+ idx += 1;
302
+ } else if bytes[idx] == b'\'' {
303
+ single = Some(MultilineQuote::Literal);
304
+ idx += 1;
305
+ } else if bytes[idx] == b'[' {
306
+ square_depth += 1;
307
+ idx += 1;
308
+ } else if bytes[idx] == b']' {
309
+ square_depth = square_depth.saturating_sub(1);
310
+ idx += 1;
311
+ } else if bytes[idx] == b'{' {
312
+ curly_depth += 1;
313
+ idx += 1;
314
+ } else if bytes[idx] == b'}' {
315
+ curly_depth = curly_depth.saturating_sub(1);
316
+ idx += 1;
317
+ } else {
318
+ idx += 1;
319
+ }
320
+ }
321
+ }
322
+ (flags, multiline.is_some())
323
+ }
324
+
325
+ fn root_end_index<S: AsRef<str>>(lines: &[S], structural: &[bool]) -> usize {
326
+ lines
327
+ .iter()
328
+ .enumerate()
329
+ .position(|(i, l)| structural[i] && is_table_header(l.as_ref()))
330
+ .unwrap_or(lines.len())
331
+ }
332
+
333
+ fn is_opencodex_catalog_path(path: &str) -> bool {
334
+ let norm = path.replace('\\', "/");
335
+ norm.rsplit('/').next() == Some("opencodex-catalog.json")
336
+ }
337
+
338
+ /// Mirrors `externalCodexModelProvider` (`src/codex/inject/config-toml.ts:30-45`).
339
+ pub fn external_codex_model_provider(content: &str) -> Option<String> {
340
+ let lf = apply_eol(content, "\n");
341
+ let lines: Vec<&str> = lf.split('\n').collect();
342
+ let (structural, _) = mark_structural_lines(&lines);
343
+ let root_end = root_end_index(&lines, &structural);
344
+ let mut provider: Option<String> = None;
345
+ for i in 0..root_end {
346
+ if !structural[i] {
347
+ continue;
348
+ }
349
+ let line = lines[i];
350
+ if let Ok(Some(val)) = parse_single_line_string_assignment(line, "model_provider") {
351
+ provider = Some(val);
352
+ break;
353
+ }
354
+ }
355
+ let prov = provider?;
356
+ if prov.is_empty() || prov == "openai" || prov == "opencodex" {
357
+ return None;
358
+ }
359
+ // Check `[model_providers.<prov>]`: if present without `base_url`, treat as Codex App 26.924 placeholder.
360
+ let target_table_1 = format!("model_providers.{prov}");
361
+ let target_table_2 = format!("model_providers.\"{prov}\"");
362
+ let mut table_start: Option<usize> = None;
363
+ for (idx, &line) in lines.iter().enumerate() {
364
+ if !structural[idx] {
365
+ continue;
366
+ }
367
+ if let Some(tname) = parse_simple_table_name(line) {
368
+ let normalized = tname.replace(' ', "");
369
+ if normalized == target_table_1 || normalized == target_table_2 {
370
+ table_start = Some(idx);
371
+ break;
372
+ }
373
+ }
374
+ }
375
+ if let Some(start) = table_start {
376
+ let mut has_base_url = false;
377
+ for idx in (start + 1)..lines.len() {
378
+ if !structural[idx] {
379
+ continue;
380
+ }
381
+ if is_table_header(lines[idx]) {
382
+ break;
383
+ }
384
+ if let Ok(Some(_)) = parse_single_line_string_assignment(lines[idx], "base_url") {
385
+ has_base_url = true;
386
+ break;
387
+ }
388
+ }
389
+ if !has_base_url {
390
+ return None;
391
+ }
392
+ }
393
+ Some(prov)
394
+ }
395
+
396
+ /// Checks for user-owned unmarked root routing keys before first attach so `ocx-child` fails closed.
397
+ pub fn detect_unowned_root_routing_conflict(content: &str) -> Result<(), String> {
398
+ if let Some(ext) = external_codex_model_provider(content) {
399
+ return Err(format!(
400
+ "ocx-child-conflict:child_external_provider_conflict: attach refused: an external Codex model_provider ({ext}) owns config.toml"
401
+ ));
402
+ }
403
+ let lf = apply_eol(content, "\n");
404
+ let lines: Vec<&str> = lf.split('\n').collect();
405
+ let (structural, unclosed) = mark_structural_lines(&lines);
406
+ if unclosed {
407
+ return Err("attach refused: config.toml contains an unclosed multiline string".to_owned());
408
+ }
409
+ let root_end = root_end_index(&lines, &structural);
410
+ for i in 0..root_end {
411
+ if !structural[i] {
412
+ continue;
413
+ }
414
+ let line = lines[i];
415
+ for key in ["openai_base_url", "experimental_realtime_ws_base_url"] {
416
+ match parse_single_line_string_assignment(line, key) {
417
+ Ok(Some(_)) => {
418
+ let marked =
419
+ i > 0 && structural[i - 1] && is_ocx_routing_marker_line(lines[i - 1]);
420
+ if !marked {
421
+ return Err(format!(
422
+ "ocx-child-conflict:child_external_provider_conflict: attach refused: user-owned root {key} already exists in config.toml"
423
+ ));
424
+ }
425
+ }
426
+ Ok(None) => {}
427
+ Err(e) => return Err(format!("attach refused: {e}")),
428
+ }
429
+ }
430
+ match parse_single_line_string_assignment(line, "model_catalog_json") {
431
+ Ok(Some(existing_path)) => {
432
+ if !is_opencodex_catalog_path(&existing_path) {
433
+ return Err(
434
+ "ocx-child-conflict:child_external_provider_conflict: attach refused: user-owned model_catalog_json already exists in config.toml"
435
+ .to_owned(),
436
+ );
437
+ }
438
+ }
439
+ Ok(None) => {}
440
+ Err(e) => return Err(format!("attach refused: {e}")),
441
+ }
442
+ }
443
+ Ok(())
444
+ }
445
+
446
+ fn insert_root_lines(content_lf: &str, added: &[String]) -> String {
447
+ if added.is_empty() {
448
+ return content_lf.to_owned();
449
+ }
450
+ let mut lines: Vec<String> = if content_lf.is_empty() {
451
+ Vec::new()
452
+ } else {
453
+ content_lf.split('\n').map(str::to_owned).collect()
454
+ };
455
+ // Drop trailing empty split element if content ended with \n
456
+ let had_trailing_nl = content_lf.ends_with('\n');
457
+ if had_trailing_nl && lines.last().is_some_and(String::is_empty) {
458
+ lines.pop();
459
+ }
460
+ let (structural, _) = mark_structural_lines(&lines);
461
+ let root_end = root_end_index(&lines, &structural);
462
+ if root_end == lines.len() {
463
+ while !lines.is_empty()
464
+ && structural[lines.len() - 1]
465
+ && lines.last().is_some_and(|l| l.trim().is_empty())
466
+ {
467
+ lines.pop();
468
+ }
469
+ lines.extend(added.iter().cloned());
470
+ let mut out = lines.join("\n");
471
+ out.push('\n');
472
+ return out;
473
+ }
474
+ let mut at = root_end;
475
+ while at > 0 && structural[at - 1] && lines[at - 1].trim().is_empty() {
476
+ at -= 1;
477
+ }
478
+ for (offset, item) in added.iter().enumerate() {
479
+ lines.insert(at + offset, item.clone());
480
+ }
481
+ let mut out = lines.join("\n");
482
+ if had_trailing_nl || !out.ends_with('\n') {
483
+ out.push('\n');
484
+ }
485
+ out
486
+ }
487
+
488
+ fn strip_owned_root_urls(
489
+ content_lf: &str,
490
+ journaled_base: Option<&str>,
491
+ journaled_ws: Option<&str>,
492
+ ) -> String {
493
+ let lines: Vec<&str> = content_lf.split('\n').collect();
494
+ let (structural, _) = mark_structural_lines(&lines);
495
+ let root_end = root_end_index(&lines, &structural);
496
+ let mut drop = vec![false; lines.len()];
497
+ for i in 0..root_end {
498
+ if !structural[i] {
499
+ continue;
500
+ }
501
+ if let Ok(Some(val)) = parse_single_line_string_assignment(lines[i], "openai_base_url") {
502
+ let marker_above =
503
+ i > 0 && structural[i - 1] && is_ocx_routing_marker_line(lines[i - 1]);
504
+ let value_match = journaled_base == Some(val.as_str());
505
+ if marker_above || value_match {
506
+ drop[i] = true;
507
+ if marker_above {
508
+ drop[i - 1] = true;
509
+ }
510
+ } else if marker_above {
511
+ drop[i - 1] = true;
512
+ }
513
+ } else if let Ok(Some(val)) =
514
+ parse_single_line_string_assignment(lines[i], "experimental_realtime_ws_base_url")
515
+ {
516
+ let marker_above =
517
+ i > 0 && structural[i - 1] && is_ocx_routing_marker_line(lines[i - 1]);
518
+ let value_match = journaled_ws == Some(val.as_str());
519
+ if marker_above || value_match {
520
+ drop[i] = true;
521
+ if marker_above {
522
+ drop[i - 1] = true;
523
+ }
524
+ }
525
+ }
526
+ }
527
+ let kept: Vec<&str> = lines
528
+ .into_iter()
529
+ .enumerate()
530
+ .filter_map(|(i, l)| (!drop[i]).then_some(l))
531
+ .collect();
532
+ kept.join("\n")
533
+ }
534
+
535
+ fn strip_owned_web_search(content_lf: &str, injected_val: Option<&str>) -> String {
536
+ let lines: Vec<&str> = content_lf.split('\n').collect();
537
+ let (structural, _) = mark_structural_lines(&lines);
538
+ let root_end = root_end_index(&lines, &structural);
539
+ let mut drop = vec![false; lines.len()];
540
+ for i in 0..root_end {
541
+ if !structural[i] {
542
+ continue;
543
+ }
544
+ if let Ok(Some(val)) = parse_single_line_string_assignment(lines[i], "web_search") {
545
+ let marker_above =
546
+ i > 0 && structural[i - 1] && is_ocx_routing_marker_line(lines[i - 1]);
547
+ let value_match = injected_val == Some(val.as_str());
548
+ if value_match {
549
+ drop[i] = true;
550
+ if marker_above {
551
+ drop[i - 1] = true;
552
+ }
553
+ } else if marker_above && injected_val.is_some() {
554
+ drop[i - 1] = true;
555
+ }
556
+ }
557
+ }
558
+ lines
559
+ .into_iter()
560
+ .enumerate()
561
+ .filter_map(|(i, l)| (!drop[i]).then_some(l))
562
+ .collect::<Vec<_>>()
563
+ .join("\n")
564
+ }
565
+
566
+ fn ensure_root_web_search(
567
+ content_lf: &str,
568
+ disable: bool,
569
+ prior_injected: Option<&str>,
570
+ prior_replaced_user_line: Option<&str>,
571
+ ) -> Result<(String, Option<String>, Option<String>), String> {
572
+ let stripped = strip_owned_web_search(content_lf, prior_injected);
573
+ let lines: Vec<&str> = stripped.split('\n').collect();
574
+ let (structural, _) = mark_structural_lines(&lines);
575
+ let root_end = root_end_index(&lines, &structural);
576
+ if !disable {
577
+ let mut has_user_ws = false;
578
+ for i in 0..root_end {
579
+ if !structural[i] {
580
+ continue;
581
+ }
582
+ if parse_single_line_string_assignment(lines[i], "web_search")?.is_some() {
583
+ has_user_ws = true;
584
+ break;
585
+ }
586
+ }
587
+ if let Some(restore) = prior_replaced_user_line
588
+ && !restore.trim().is_empty()
589
+ && !has_user_ws
590
+ {
591
+ let clean_restore = restore.trim_end_matches(['\r', '\n']).to_owned();
592
+ return Ok((insert_root_lines(&stripped, &[clean_restore]), None, None));
593
+ }
594
+ return Ok((stripped, None, None));
595
+ }
596
+ let mut drop = vec![false; lines.len()];
597
+ let mut replaced = prior_replaced_user_line.map(str::to_owned);
598
+ let mut saw_user = false;
599
+ for i in 0..root_end {
600
+ if !structural[i] {
601
+ continue;
602
+ }
603
+ if parse_single_line_string_assignment(lines[i], "web_search")?.is_some() {
604
+ if !saw_user {
605
+ replaced = Some(lines[i].to_owned());
606
+ saw_user = true;
607
+ }
608
+ drop[i] = true;
609
+ }
610
+ }
611
+ let filtered = lines
612
+ .into_iter()
613
+ .enumerate()
614
+ .filter_map(|(i, l)| (!drop[i]).then_some(l))
615
+ .collect::<Vec<_>>()
616
+ .join("\n");
617
+ let next = insert_root_lines(
618
+ &filtered,
619
+ &[
620
+ OCX_ROUTING_MARKER_LINE.to_owned(),
621
+ "web_search = \"disabled\"".to_owned(),
622
+ ],
623
+ );
624
+ Ok((next, Some("disabled".to_owned()), replaced))
625
+ }
626
+
627
+ fn set_root_catalog_path(content_lf: &str, catalog_path: &str) -> String {
628
+ let key_line = format!(
629
+ "model_catalog_json = {}",
630
+ toml_escape_basic_string(catalog_path)
631
+ );
632
+ let mut lines: Vec<String> = content_lf.split('\n').map(str::to_owned).collect();
633
+ let (structural, _) = mark_structural_lines(&lines);
634
+ let root_end = root_end_index(&lines, &structural);
635
+ let mut owned_indices = Vec::new();
636
+ for (i, line) in lines[..root_end].iter().enumerate() {
637
+ if !structural[i] {
638
+ continue;
639
+ }
640
+ if let Ok(Some(existing)) = parse_single_line_string_assignment(line, "model_catalog_json")
641
+ && is_opencodex_catalog_path(&existing)
642
+ {
643
+ owned_indices.push(i);
644
+ }
645
+ }
646
+ if let Some(&first) = owned_indices.first() {
647
+ lines[first] = key_line;
648
+ let dup: std::collections::HashSet<usize> = owned_indices.into_iter().skip(1).collect();
649
+ return lines
650
+ .into_iter()
651
+ .enumerate()
652
+ .filter_map(|(i, l)| (!dup.contains(&i)).then_some(l))
653
+ .collect::<Vec<_>>()
654
+ .join("\n");
655
+ }
656
+ insert_root_lines(content_lf, &[key_line])
657
+ }
658
+
659
+ fn strip_opencodex_catalog_path(content_lf: &str) -> String {
660
+ let lines: Vec<&str> = content_lf.split('\n').collect();
661
+ let (structural, _) = mark_structural_lines(&lines);
662
+ let root_end = root_end_index(&lines, &structural);
663
+ lines
664
+ .into_iter()
665
+ .enumerate()
666
+ .filter_map(|(i, l)| {
667
+ if i < root_end
668
+ && structural[i]
669
+ && let Ok(Some(p)) = parse_single_line_string_assignment(l, "model_catalog_json")
670
+ && is_opencodex_catalog_path(&p)
671
+ {
672
+ return None;
673
+ }
674
+ Some(l)
675
+ })
676
+ .collect::<Vec<_>>()
677
+ .join("\n")
678
+ }
679
+
680
+ fn upsert_table_bool(
681
+ content_lf: &str,
682
+ table_name: &str,
683
+ key: &str,
684
+ val: bool,
685
+ ) -> (String, Option<String>) {
686
+ let mut lines: Vec<String> = content_lf.split('\n').map(str::to_owned).collect();
687
+ let had_trailing_nl = content_lf.ends_with('\n');
688
+ if had_trailing_nl && lines.last().is_some_and(String::is_empty) {
689
+ lines.pop();
690
+ }
691
+ let (structural, _) = mark_structural_lines(&lines);
692
+ let table_idx = lines.iter().enumerate().position(|(i, l)| {
693
+ structural[i] && parse_simple_table_name(l).as_deref() == Some(table_name)
694
+ });
695
+ let assign_line = format!("{key} = {val}");
696
+ if let Some(start) = table_idx {
697
+ let end = lines[start + 1..]
698
+ .iter()
699
+ .enumerate()
700
+ .position(|(rel, l)| structural[start + 1 + rel] && is_table_header(l))
701
+ .map(|rel| start + 1 + rel)
702
+ .unwrap_or(lines.len());
703
+ for idx in (start + 1)..end {
704
+ if !structural[idx] {
705
+ continue;
706
+ }
707
+ let line = &mut lines[idx];
708
+ if let Some((k, _)) = parse_key_value_line(line)
709
+ && k == key
710
+ {
711
+ let prior_line = line.clone();
712
+ let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
713
+ *line = format!("{indent}{assign_line}");
714
+ let mut out = lines.join("\n");
715
+ out.push('\n');
716
+ return (out, Some(prior_line));
717
+ }
718
+ }
719
+ let mut insert_at = end;
720
+ while insert_at > start + 1
721
+ && structural[insert_at - 1]
722
+ && lines[insert_at - 1].trim().is_empty()
723
+ {
724
+ insert_at -= 1;
725
+ }
726
+ lines.insert(insert_at, assign_line);
727
+ let mut out = lines.join("\n");
728
+ out.push('\n');
729
+ return (out, None);
730
+ }
731
+ let trimmed = content_lf.trim_end_matches('\n');
732
+ let out = if trimmed.is_empty() {
733
+ format!("[{table_name}]\n{assign_line}\n")
734
+ } else {
735
+ format!("{trimmed}\n\n[{table_name}]\n{assign_line}\n")
736
+ };
737
+ (out, None)
738
+ }
739
+
740
+ fn apply_subagent_defaults(
741
+ content_lf: &str,
742
+ desired: Option<&crate::codex_settings::SubagentDefaults>,
743
+ prior_written: Option<&WrittenSubagentDefaults>,
744
+ ) -> (String, Option<WrittenSubagentDefaults>) {
745
+ let stripped = strip_subagent_defaults(content_lf, prior_written);
746
+ let Some(sub) = desired else {
747
+ return (stripped, None);
748
+ };
749
+ let mut lines: Vec<String> = stripped.split('\n').map(str::to_owned).collect();
750
+ if stripped.ends_with('\n') && lines.last().is_some_and(String::is_empty) {
751
+ lines.pop();
752
+ }
753
+ let (structural, _) = mark_structural_lines(&lines);
754
+ let ag_idx = lines.iter().enumerate().position(|(i, l)| {
755
+ structural[i] && parse_simple_table_name(l).as_deref() == Some("agents")
756
+ });
757
+ let mut to_add = vec![
758
+ MANAGED_SUBAGENT_DEFAULT_MARKER.to_owned(),
759
+ format!(
760
+ "default_subagent_model = {}",
761
+ toml_escape_basic_string(&sub.model)
762
+ ),
763
+ ];
764
+ if let Some(eff) = &sub.reasoning_effort {
765
+ to_add.push(MANAGED_SUBAGENT_DEFAULT_MARKER.to_owned());
766
+ to_add.push(format!(
767
+ "default_subagent_reasoning_effort = {}",
768
+ toml_escape_basic_string(eff)
769
+ ));
770
+ }
771
+ let written = WrittenSubagentDefaults {
772
+ default_subagent_model: sub.model.clone(),
773
+ default_subagent_reasoning_effort: sub.reasoning_effort.clone(),
774
+ };
775
+ if let Some(start) = ag_idx {
776
+ let end = lines[start + 1..]
777
+ .iter()
778
+ .enumerate()
779
+ .position(|(rel, l)| structural[start + 1 + rel] && is_table_header(l))
780
+ .map(|rel| start + 1 + rel)
781
+ .unwrap_or(lines.len());
782
+ // Respect user-owned existing keys in [agents]
783
+ for idx in (start + 1)..end {
784
+ if !structural[idx] {
785
+ continue;
786
+ }
787
+ let line = &lines[idx];
788
+ if let Some((k, _)) = parse_key_value_line(line)
789
+ && (k == "default_subagent_model" || k == "default_subagent_reasoning_effort")
790
+ {
791
+ return (stripped, None);
792
+ }
793
+ }
794
+ let mut insert_at = end;
795
+ while insert_at > start + 1
796
+ && structural[insert_at - 1]
797
+ && lines[insert_at - 1].trim().is_empty()
798
+ {
799
+ insert_at -= 1;
800
+ }
801
+ for (off, item) in to_add.into_iter().enumerate() {
802
+ lines.insert(insert_at + off, item);
803
+ }
804
+ let mut out = lines.join("\n");
805
+ out.push('\n');
806
+ return (out, Some(written));
807
+ }
808
+ let trimmed = stripped.trim_end_matches('\n');
809
+ let block = format!(
810
+ "{}\n[agents]\n{}\n",
811
+ MANAGED_AGENTS_TABLE_MARKER,
812
+ to_add.join("\n")
813
+ );
814
+ let out = if trimmed.is_empty() {
815
+ block
816
+ } else {
817
+ format!("{trimmed}\n\n{block}")
818
+ };
819
+ (out, Some(written))
820
+ }
821
+
822
+ fn strip_subagent_defaults(content_lf: &str, written: Option<&WrittenSubagentDefaults>) -> String {
823
+ let lines: Vec<&str> = content_lf.split('\n').collect();
824
+ let (structural, _) = mark_structural_lines(&lines);
825
+ let Some(ag_idx) = lines.iter().enumerate().position(|(i, l)| {
826
+ structural[i] && parse_simple_table_name(l).as_deref() == Some("agents")
827
+ }) else {
828
+ return content_lf.to_owned();
829
+ };
830
+ let end_idx = lines[ag_idx + 1..]
831
+ .iter()
832
+ .enumerate()
833
+ .position(|(rel, l)| structural[ag_idx + 1 + rel] && is_table_header(l))
834
+ .map(|rel| ag_idx + 1 + rel)
835
+ .unwrap_or(lines.len());
836
+ let mut drop = vec![false; lines.len()];
837
+ for i in (ag_idx + 1)..end_idx {
838
+ if !structural[i] {
839
+ continue;
840
+ }
841
+ let trimmed = lines[i].trim();
842
+ if trimmed == MANAGED_SUBAGENT_DEFAULT_MARKER {
843
+ drop[i] = true;
844
+ continue;
845
+ }
846
+ if let Ok(Some(val)) =
847
+ parse_single_line_string_assignment(lines[i], "default_subagent_model")
848
+ {
849
+ let marked = i > ag_idx + 1 && lines[i - 1].trim() == MANAGED_SUBAGENT_DEFAULT_MARKER;
850
+ let matched = written.is_some_and(|w| w.default_subagent_model == val);
851
+ if (marked && written.is_none()) || matched {
852
+ drop[i] = true;
853
+ }
854
+ } else if let Ok(Some(val)) =
855
+ parse_single_line_string_assignment(lines[i], "default_subagent_reasoning_effort")
856
+ {
857
+ let marked = i > ag_idx + 1 && lines[i - 1].trim() == MANAGED_SUBAGENT_DEFAULT_MARKER;
858
+ let matched = written.and_then(|w| w.default_subagent_reasoning_effort.as_deref())
859
+ == Some(val.as_str());
860
+ if (marked && written.is_none()) || matched {
861
+ drop[i] = true;
862
+ }
863
+ }
864
+ }
865
+ let remaining_body_has_content = (ag_idx + 1..end_idx)
866
+ .filter(|&i| !drop[i])
867
+ .any(|i| !structural[i] || !lines[i].trim().is_empty());
868
+ if !remaining_body_has_content {
869
+ for d in &mut drop[ag_idx..end_idx] {
870
+ *d = true;
871
+ }
872
+ }
873
+ if ag_idx > 0
874
+ && structural[ag_idx - 1]
875
+ && lines[ag_idx - 1].trim() == MANAGED_AGENTS_TABLE_MARKER
876
+ {
877
+ drop[ag_idx - 1] = true;
878
+ }
879
+ lines
880
+ .into_iter()
881
+ .enumerate()
882
+ .filter_map(|(i, l)| (!drop[i]).then_some(l))
883
+ .collect::<Vec<_>>()
884
+ .join("\n")
885
+ }
886
+
887
+ fn strip_features_ledger(
888
+ content_lf: &str,
889
+ wrote_fast_mode: Option<bool>,
890
+ prior_user_fast_mode_line: Option<&str>,
891
+ wrote_multi_agent_v2: Option<bool>,
892
+ prior_user_multi_agent_v2_line: Option<&str>,
893
+ ) -> String {
894
+ if wrote_fast_mode.is_none() && wrote_multi_agent_v2.is_none() {
895
+ return content_lf.to_owned();
896
+ }
897
+ let mut lines: Vec<String> = content_lf.split('\n').map(str::to_owned).collect();
898
+ let (structural, _) = mark_structural_lines(&lines);
899
+ let Some(feat_idx) = lines.iter().enumerate().position(|(i, l)| {
900
+ structural[i] && parse_simple_table_name(l).as_deref() == Some("features")
901
+ }) else {
902
+ return content_lf.to_owned();
903
+ };
904
+ let end_idx = lines[feat_idx + 1..]
905
+ .iter()
906
+ .enumerate()
907
+ .position(|(rel, l)| structural[feat_idx + 1 + rel] && is_table_header(l))
908
+ .map(|rel| feat_idx + 1 + rel)
909
+ .unwrap_or(lines.len());
910
+ let mut drop = vec![false; lines.len()];
911
+ for i in (feat_idx + 1)..end_idx {
912
+ if !structural[i] {
913
+ continue;
914
+ }
915
+ if let Some((k, rhs)) = parse_key_value_line(&lines[i]) {
916
+ let val_clean = strip_inline_comment(rhs).trim();
917
+ if let Some(fm) = wrote_fast_mode
918
+ && k == "fast_mode"
919
+ && val_clean == (if fm { "true" } else { "false" })
920
+ {
921
+ if let Some(prior) = prior_user_fast_mode_line {
922
+ lines[i] = prior.to_owned();
923
+ } else {
924
+ drop[i] = true;
925
+ }
926
+ continue;
927
+ }
928
+ if let Some(v2) = wrote_multi_agent_v2
929
+ && k == "multi_agent_v2"
930
+ && val_clean == (if v2 { "true" } else { "false" })
931
+ {
932
+ if let Some(prior) = prior_user_multi_agent_v2_line {
933
+ lines[i] = prior.to_owned();
934
+ } else {
935
+ drop[i] = true;
936
+ }
937
+ }
938
+ }
939
+ }
940
+ let remaining_has_keys = (feat_idx + 1..end_idx)
941
+ .filter(|&i| !drop[i])
942
+ .any(|i| !structural[i] || !lines[i].trim().is_empty());
943
+ if !remaining_has_keys {
944
+ for d in &mut drop[feat_idx..end_idx] {
945
+ *d = true;
946
+ }
947
+ }
948
+ lines
949
+ .into_iter()
950
+ .enumerate()
951
+ .filter_map(|(i, l)| (!drop[i]).then_some(l))
952
+ .collect::<Vec<_>>()
953
+ .join("\n")
954
+ }
955
+
956
+ /// Applies Design B loopback keys + Home Codex settings onto `raw_input`.
957
+ pub fn apply_design_b_config(
958
+ raw_input: &str,
959
+ listen_port: u16,
960
+ catalog_path: &str,
961
+ settings: &HomeCodexSettings,
962
+ prior_ledger: Option<&ChildInjectedLedger>,
963
+ ) -> Result<(String, ChildInjectedLedger), String> {
964
+ if let Some(ext) = external_codex_model_provider(raw_input) {
965
+ return Err(format!("external model_provider ({ext}) owns config.toml"));
966
+ }
967
+ let eol = if raw_input.is_empty() {
968
+ "\n"
969
+ } else {
970
+ dominant_eol(raw_input)
971
+ };
972
+ let base_url = format!("http://127.0.0.1:{listen_port}/v1");
973
+ let mut lf = apply_eol(raw_input, "\n");
974
+ lf = strip_owned_root_urls(
975
+ &lf,
976
+ prior_ledger
977
+ .and_then(|l| l.openai_base_url.as_deref())
978
+ .or(Some(base_url.as_str())),
979
+ prior_ledger
980
+ .and_then(|l| l.experimental_realtime_ws_base_url.as_deref())
981
+ .or(Some(base_url.as_str())),
982
+ );
983
+ let (ws_lf, wrote_ws, replaced_ws) = ensure_root_web_search(
984
+ &lf,
985
+ !settings.web_search_sidecar_enabled,
986
+ prior_ledger.and_then(|l| l.injected_web_search.as_deref()),
987
+ prior_ledger.and_then(|l| l.replaced_user_web_search_line.as_deref()),
988
+ )?;
989
+ lf = ws_lf;
990
+ lf = set_root_catalog_path(&lf, catalog_path);
991
+ lf = insert_root_lines(
992
+ &lf,
993
+ &[
994
+ OCX_ROUTING_MARKER_LINE.to_owned(),
995
+ format!("openai_base_url = {}", toml_escape_basic_string(&base_url)),
996
+ OCX_ROUTING_MARKER_LINE.to_owned(),
997
+ format!(
998
+ "experimental_realtime_ws_base_url = {}",
999
+ toml_escape_basic_string(&base_url)
1000
+ ),
1001
+ ],
1002
+ );
1003
+ let mut wrote_fast = prior_ledger.and_then(|l| l.wrote_fast_mode);
1004
+ let mut prior_fast_line = prior_ledger.and_then(|l| l.prior_user_fast_mode_line.clone());
1005
+ if let Some(fm) = settings.fast_mode {
1006
+ let (next_lf, overwritten) = upsert_table_bool(&lf, "features", "fast_mode", fm);
1007
+ if wrote_fast.is_none() {
1008
+ prior_fast_line = overwritten;
1009
+ }
1010
+ lf = next_lf;
1011
+ wrote_fast = Some(fm);
1012
+ }
1013
+ let mut wrote_v2 = prior_ledger.and_then(|l| l.wrote_multi_agent_v2);
1014
+ let mut prior_v2_line = prior_ledger.and_then(|l| l.prior_user_multi_agent_v2_line.clone());
1015
+ if let Some(mode) = &settings.multi_agent_mode {
1016
+ let v2_bool = mode == "v2";
1017
+ let (next_lf, overwritten) = upsert_table_bool(&lf, "features", "multi_agent_v2", v2_bool);
1018
+ if wrote_v2.is_none() {
1019
+ prior_v2_line = overwritten;
1020
+ }
1021
+ lf = next_lf;
1022
+ wrote_v2 = Some(v2_bool);
1023
+ }
1024
+ let (sub_lf, wrote_sub) = apply_subagent_defaults(
1025
+ &lf,
1026
+ settings.subagent_defaults.as_ref(),
1027
+ prior_ledger.and_then(|l| l.wrote_subagent_defaults.as_ref()),
1028
+ );
1029
+ lf = sub_lf;
1030
+ let ledger = ChildInjectedLedger {
1031
+ openai_base_url: Some(base_url.clone()),
1032
+ experimental_realtime_ws_base_url: Some(base_url),
1033
+ model_catalog_json: Some(catalog_path.to_owned()),
1034
+ injected_web_search: wrote_ws,
1035
+ replaced_user_web_search_line: replaced_ws,
1036
+ wrote_fast_mode: wrote_fast,
1037
+ prior_user_fast_mode_line: prior_fast_line,
1038
+ wrote_multi_agent_v2: wrote_v2,
1039
+ prior_user_multi_agent_v2_line: prior_v2_line,
1040
+ wrote_subagent_defaults: wrote_sub,
1041
+ };
1042
+ Ok((apply_eol(&lf, eol), ledger))
1043
+ }
1044
+
1045
+ /// Tier-2 surgical value-matched strip surviving `#1798` comment-stripping rewrites.
1046
+ pub fn surgical_detach_config(
1047
+ raw_current: &str,
1048
+ ledger: &ChildInjectedLedger,
1049
+ ) -> Result<Option<String>, String> {
1050
+ let eol = dominant_eol(raw_current);
1051
+ let lf = apply_eol(raw_current, "\n");
1052
+ // Validate every root managed key line parses cleanly; fail closed on corrupt spans.
1053
+ let lines: Vec<&str> = lf.split('\n').collect();
1054
+ let (structural, unclosed) = mark_structural_lines(&lines);
1055
+ if unclosed {
1056
+ return Err("config.toml contains an unclosed multiline string".to_owned());
1057
+ }
1058
+ let root_end = root_end_index(&lines, &structural);
1059
+ for i in 0..root_end {
1060
+ if !structural[i] {
1061
+ continue;
1062
+ }
1063
+ let line = lines[i];
1064
+ for managed_key in [
1065
+ "openai_base_url",
1066
+ "experimental_realtime_ws_base_url",
1067
+ "model_catalog_json",
1068
+ "web_search",
1069
+ ] {
1070
+ if let Some((k, _)) = parse_key_value_line(line)
1071
+ && k == managed_key
1072
+ {
1073
+ parse_single_line_string_assignment(line, managed_key)?;
1074
+ }
1075
+ }
1076
+ }
1077
+ // Also drop orphaned marker above user-edited openai_base_url
1078
+ let mut drop_orphan = vec![false; lines.len()];
1079
+ for i in 1..root_end {
1080
+ if structural[i]
1081
+ && structural[i - 1]
1082
+ && is_ocx_routing_marker_line(lines[i - 1])
1083
+ && let Some((k, _)) = parse_key_value_line(lines[i])
1084
+ && (k == "openai_base_url" || k == "experimental_realtime_ws_base_url")
1085
+ {
1086
+ drop_orphan[i - 1] = true;
1087
+ }
1088
+ }
1089
+ let mut work = lines
1090
+ .into_iter()
1091
+ .enumerate()
1092
+ .filter_map(|(i, l)| (!drop_orphan[i]).then_some(l))
1093
+ .collect::<Vec<_>>()
1094
+ .join("\n");
1095
+ work = strip_owned_root_urls(
1096
+ &work,
1097
+ ledger.openai_base_url.as_deref(),
1098
+ ledger.experimental_realtime_ws_base_url.as_deref(),
1099
+ );
1100
+ work = strip_opencodex_catalog_path(&work);
1101
+ let (ws_restored, _, _) = ensure_root_web_search(
1102
+ &work,
1103
+ false,
1104
+ ledger.injected_web_search.as_deref(),
1105
+ ledger.replaced_user_web_search_line.as_deref(),
1106
+ )?;
1107
+ work = ws_restored;
1108
+ work = strip_features_ledger(
1109
+ &work,
1110
+ ledger.wrote_fast_mode,
1111
+ ledger.prior_user_fast_mode_line.as_deref(),
1112
+ ledger.wrote_multi_agent_v2,
1113
+ ledger.prior_user_multi_agent_v2_line.as_deref(),
1114
+ );
1115
+ work = strip_subagent_defaults(&work, ledger.wrote_subagent_defaults.as_ref());
1116
+ work = collapse_excess_blank_lines(&work);
1117
+ if work.trim().is_empty() {
1118
+ Ok(None)
1119
+ } else {
1120
+ if !work.ends_with('\n') {
1121
+ work.push('\n');
1122
+ }
1123
+ Ok(Some(apply_eol(&work, eol)))
1124
+ }
1125
+ }
1126
+
1127
+ fn collapse_excess_blank_lines(lf: &str) -> String {
1128
+ let lines: Vec<&str> = lf.split('\n').collect();
1129
+ let (structural, _) = mark_structural_lines(&lines);
1130
+ let mut out_lines: Vec<&str> = Vec::with_capacity(lines.len());
1131
+ let mut blank_run = 0usize;
1132
+ let mut started = false;
1133
+ for (i, &line) in lines.iter().enumerate() {
1134
+ let is_struct_blank = structural[i] && line.is_empty();
1135
+ if !started && is_struct_blank {
1136
+ continue;
1137
+ }
1138
+ started = true;
1139
+ if is_struct_blank {
1140
+ blank_run += 1;
1141
+ if blank_run > 1 {
1142
+ continue;
1143
+ }
1144
+ } else {
1145
+ blank_run = 0;
1146
+ }
1147
+ out_lines.push(line);
1148
+ }
1149
+ while out_lines.len() > 1
1150
+ && out_lines.last() == Some(&"")
1151
+ && out_lines[out_lines.len() - 2].is_empty()
1152
+ {
1153
+ out_lines.pop();
1154
+ }
1155
+ out_lines.join("\n")
1156
+ }