sneakoscope 7.3.0 → 7.6.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 (283) hide show
  1. package/README.md +129 -10
  2. package/crates/sks-core/Cargo.lock +1 -1
  3. package/crates/sks-core/Cargo.toml +1 -1
  4. package/dist/cli/codex-app-command.js +1 -1
  5. package/dist/cli/command-manifest-lite.js +4 -1
  6. package/dist/cli/command-registry.js +2 -0
  7. package/dist/cli/install-helpers-codex-lb-chain.js +42 -0
  8. package/dist/cli/install-helpers-codex-lb-config.js +114 -9
  9. package/dist/cli/install-helpers-install-support.js +6 -16
  10. package/dist/cli/install-helpers.js +788 -600
  11. package/dist/cli/router.js +30 -2
  12. package/dist/commands/codex-app.js +37 -1
  13. package/dist/commands/codex-lb.js +491 -300
  14. package/dist/config/skills-manifest.json +57 -71
  15. package/dist/core/align/align-route.js +127 -0
  16. package/dist/core/codex-app/codex-app-fast-ui-repair.js +8 -4
  17. package/dist/core/codex-app/codex-app-restart.js +83 -0
  18. package/dist/core/codex-app/codex-app-ui-state-snapshot.js +8 -4
  19. package/dist/core/codex-app/desktop-routing-snapshot.js +1 -1
  20. package/dist/core/codex-app/menubar/constants.js +5 -0
  21. package/dist/core/codex-app/menubar/generation-transaction-journal.js +1 -3
  22. package/dist/core/codex-app/menubar/installer.js +18 -0
  23. package/dist/core/codex-app/multi-provider-router.js +22 -10
  24. package/dist/core/codex-app/openrouter-activate.js +26 -1
  25. package/dist/core/codex-app.js +118 -26
  26. package/dist/core/codex-control/codex-app-server-runtime-env.js +86 -0
  27. package/dist/core/codex-control/codex-app-server-v2-client.js +78 -8
  28. package/dist/core/codex-control/codex-task-runner.js +2 -2
  29. package/dist/core/codex-lb/capability-runner.js +204 -0
  30. package/dist/core/codex-lb/capability-types.js +1 -0
  31. package/dist/core/codex-lb/codex-lb-env.js +9 -13
  32. package/dist/core/codex-lb/codex-lb-setup.js +45 -8
  33. package/dist/core/codex-lb/codex-lb-tool-catalog.js +52 -74
  34. package/dist/core/codex-lb/codex-lb-tool-output-recovery.js +1 -1
  35. package/dist/core/codex-lb/desktop-auth-invariant.js +185 -0
  36. package/dist/core/codex-lb/desktop-bridge/client.js +34 -0
  37. package/dist/core/codex-lb/desktop-bridge/header-policy.js +106 -0
  38. package/dist/core/codex-lb/desktop-bridge/http-forward.js +101 -0
  39. package/dist/core/codex-lb/desktop-bridge/index.js +10 -0
  40. package/dist/core/codex-lb/desktop-bridge/launchd.js +81 -0
  41. package/dist/core/codex-lb/desktop-bridge/location-rewrite.js +27 -0
  42. package/dist/core/codex-lb/desktop-bridge/security.js +274 -0
  43. package/dist/core/codex-lb/desktop-bridge/server.js +179 -0
  44. package/dist/core/codex-lb/desktop-bridge/state.js +119 -0
  45. package/dist/core/codex-lb/desktop-bridge/types.js +16 -0
  46. package/dist/core/codex-lb/desktop-bridge/websocket-forward.js +151 -0
  47. package/dist/core/codex-lb/desktop-center-credentials.js +189 -0
  48. package/dist/core/codex-lb/desktop-controller.js +1410 -0
  49. package/dist/core/codex-lb/desktop-mode.js +32 -0
  50. package/dist/core/codex-lb/desktop-real-evidence.js +168 -0
  51. package/dist/core/codex-lb/desktop-service.js +613 -0
  52. package/dist/core/codex-lb/legacy-migration.js +575 -0
  53. package/dist/core/codex-lb/migration-receipt.js +246 -0
  54. package/dist/core/codex-lb/probes/auxiliary-surfaces-probe.js +60 -0
  55. package/dist/core/codex-lb/probes/bridge-probe.js +75 -0
  56. package/dist/core/codex-lb/probes/catalog-probe.js +128 -0
  57. package/dist/core/codex-lb/probes/computer-use-probe.js +50 -0
  58. package/dist/core/codex-lb/probes/image-generation-probe.js +47 -0
  59. package/dist/core/codex-lb/probes/probe-evidence.js +39 -0
  60. package/dist/core/codex-lb/probes/voice-realtime-probe.js +44 -0
  61. package/dist/core/codex-lb/trusted-deep-evidence.js +403 -0
  62. package/dist/core/codex-native/core-skill-manifest.js +22 -6
  63. package/dist/core/codex-runtime/codex-desktop-config-policy.js +2 -1
  64. package/dist/core/commands/align-command.js +220 -0
  65. package/dist/core/commands/image-ux-review-command.js +280 -68
  66. package/dist/core/commands/naruto-command.js +257 -8
  67. package/dist/core/commands/ppt-command.js +2 -2
  68. package/dist/core/commands/telegram-command.js +402 -34
  69. package/dist/core/commands/triwiki-command.js +11 -1
  70. package/dist/core/commands/triwiki-graph-command.js +160 -0
  71. package/dist/core/commands/wiki-command.js +100 -20
  72. package/dist/core/doctor/skill-legacy-surface.js +1 -3
  73. package/dist/core/errors/message.js +3 -0
  74. package/dist/core/evidence/evidence-freshness.js +14 -0
  75. package/dist/core/feature-fixtures.js +9 -1
  76. package/dist/core/feature-registry.js +5 -3
  77. package/dist/core/fsx.js +7 -3
  78. package/dist/core/hooks-runtime/codex-commit-hooks-selftest.js +82 -0
  79. package/dist/core/hooks-runtime/context-graph-freshness-preflight.js +113 -0
  80. package/dist/core/hooks-runtime/hook-context.js +15 -2
  81. package/dist/core/hooks-runtime/managed-skill-generation-heal.js +46 -0
  82. package/dist/core/hooks-runtime/naruto-terminal-finalization.js +1 -0
  83. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +1 -1
  84. package/dist/core/hooks-runtime/tool-output-quarantine.js +1 -1
  85. package/dist/core/hooks-runtime.js +33 -89
  86. package/dist/core/image-ux-review/callout-extraction.js +6 -0
  87. package/dist/core/image-ux-review/imagegen-adapter.js +64 -23
  88. package/dist/core/image-ux-review/real-callout-extractor.js +1 -0
  89. package/dist/core/image-ux-review.js +230 -12
  90. package/dist/core/imagegen/codex-lb-imagegen-target.js +21 -7
  91. package/dist/core/imagegen/imagegen-capability.js +10 -4
  92. package/dist/core/imagegen/require-imagegen.js +29 -5
  93. package/dist/core/init/skills.js +25 -13
  94. package/dist/core/init.js +1 -1
  95. package/dist/core/install/installed-package-smoke.js +157 -4
  96. package/dist/core/managed-assets/managed-assets-manifest.js +2 -1
  97. package/dist/core/managed-path-safety.js +8 -10
  98. package/dist/core/mcp-config/backup.js +2 -4
  99. package/dist/core/mcp-config/config-reader.js +2 -4
  100. package/dist/core/mcp-config/scope.js +3 -5
  101. package/dist/core/naruto/context-graph-advisor-scope.js +242 -0
  102. package/dist/core/naruto/context-graph-advisor.js +0 -0
  103. package/dist/core/perf/release-latency-slo.js +12 -6
  104. package/dist/core/pipeline-internals/runtime-core.js +78 -0
  105. package/dist/core/pipeline-internals/runtime-gates.js +5 -2
  106. package/dist/core/policy/latest-version-guidance.js +113 -0
  107. package/dist/core/ppt.js +8 -8
  108. package/dist/core/preflight/parallel-preflight-engine.js +1 -1
  109. package/dist/core/proof/auto-finalize.js +98 -6
  110. package/dist/core/proof/route-proof-gate.js +12 -1
  111. package/dist/core/proof/route-proof-policy.js +8 -8
  112. package/dist/core/release/gate-manifest.js +32 -1
  113. package/dist/core/release/npm-stage-contract.js +21 -0
  114. package/dist/core/release/package-size-budget.js +2 -2
  115. package/dist/core/release/release-gate-contract.js +5 -0
  116. package/dist/core/release/release-proof-io.js +1 -3
  117. package/dist/core/release/release-real-contract.js +5 -4
  118. package/dist/core/release/release-stamp-proof.js +1 -3
  119. package/dist/core/release/stage-publish.js +27 -0
  120. package/dist/core/remote/audit-idempotency.js +50 -18
  121. package/dist/core/remote/codex-public-activity.js +283 -0
  122. package/dist/core/remote/index.js +1 -0
  123. package/dist/core/remote/ssh-worker-client.js +4 -1
  124. package/dist/core/remote/worker.js +206 -27
  125. package/dist/core/research/research-adversarial-review.js +1 -3
  126. package/dist/core/research/research-claim-synthesizer.js +1 -3
  127. package/dist/core/research/research-falsification-runner.js +1 -3
  128. package/dist/core/research/research-source-evidence.js +1 -3
  129. package/dist/core/responses-stream.js +65 -19
  130. package/dist/core/routes/constants.js +1 -1
  131. package/dist/core/routes/design-policy.js +7 -2
  132. package/dist/core/routes/dollar-manifest-lite.js +2 -4
  133. package/dist/core/routes/evidence.js +1 -1
  134. package/dist/core/routes.js +30 -10
  135. package/dist/core/safety/command-contract/contracts.js +2 -0
  136. package/dist/core/safety/command-contract/types.js +1 -1
  137. package/dist/core/search/context-graph-seeds.js +205 -0
  138. package/dist/core/search/context.js +0 -0
  139. package/dist/core/search/provider.js +2 -2
  140. package/dist/core/secret-redaction.js +6 -0
  141. package/dist/core/subagents/naruto-help-contract.js +2 -1
  142. package/dist/core/subagents/naruto-host-credentials.js +161 -0
  143. package/dist/core/subagents/official-subagent-preparation.js +4 -1
  144. package/dist/core/subagents/official-subagent-prompt.js +44 -2
  145. package/dist/core/subagents/official-subagent-runner.js +26 -8
  146. package/dist/core/subagents/triwiki-attention.js +135 -123
  147. package/dist/core/telegram/bot-api.js +85 -10
  148. package/dist/core/telegram/center-snapshot.js +718 -0
  149. package/dist/core/telegram/config.js +158 -31
  150. package/dist/core/telegram/hub.js +288 -33
  151. package/dist/core/telegram/index.js +2 -0
  152. package/dist/core/telegram/ingress-spool.js +419 -0
  153. package/dist/core/telegram/ledgers.js +188 -29
  154. package/dist/core/telegram/messages.js +26 -6
  155. package/dist/core/telegram/owner-lock.js +10 -7
  156. package/dist/core/telegram/runtime-projection.js +38 -3
  157. package/dist/core/telegram/runtime.js +298 -63
  158. package/dist/core/telegram/service.js +137 -8
  159. package/dist/core/telegram/setup.js +291 -73
  160. package/dist/core/text/strings.js +3 -0
  161. package/dist/core/triwiki/code-pack.js +12 -120
  162. package/dist/core/triwiki/context-graph/compiler/cache-key.js +277 -0
  163. package/dist/core/triwiki/context-graph/compiler/extract.js +104 -0
  164. package/dist/core/triwiki/context-graph/compiler/freshness.js +108 -0
  165. package/dist/core/triwiki/context-graph/compiler/index.js +237 -0
  166. package/dist/core/triwiki/context-graph/compiler/merge.js +0 -0
  167. package/dist/core/triwiki/context-graph/compiler/serialize.js +115 -0
  168. package/dist/core/triwiki/context-graph/contracts.js +236 -0
  169. package/dist/core/triwiki/context-graph/extractors/code/builders.js +150 -0
  170. package/dist/core/triwiki/context-graph/extractors/code/declarations.js +161 -0
  171. package/dist/core/triwiki/context-graph/extractors/code/index.js +265 -0
  172. package/dist/core/triwiki/context-graph/extractors/code/inventory.js +237 -0
  173. package/dist/core/triwiki/context-graph/extractors/code/module-graph.js +252 -0
  174. package/dist/core/triwiki/context-graph/extractors/code/modules.js +79 -0
  175. package/dist/core/triwiki/context-graph/extractors/code/references.js +184 -0
  176. package/dist/core/triwiki/context-graph/extractors/code/selection.js +100 -0
  177. package/dist/core/triwiki/context-graph/extractors/code/ts-config.js +161 -0
  178. package/dist/core/triwiki/context-graph/extractors/code/types.js +18 -0
  179. package/dist/core/triwiki/context-graph/extractors/evidence/claims.js +289 -0
  180. package/dist/core/triwiki/context-graph/extractors/evidence/index.js +54 -0
  181. package/dist/core/triwiki/context-graph/extractors/evidence/proof-index.js +213 -0
  182. package/dist/core/triwiki/context-graph/extractors/evidence/proofs.js +266 -0
  183. package/dist/core/triwiki/context-graph/extractors/evidence/redaction.js +177 -0
  184. package/dist/core/triwiki/context-graph/extractors/evidence/shared.js +0 -0
  185. package/dist/core/triwiki/context-graph/extractors/evidence/sources.js +154 -0
  186. package/dist/core/triwiki/context-graph/extractors/index.js +7 -0
  187. package/dist/core/triwiki/context-graph/extractors/topology/commands.js +207 -0
  188. package/dist/core/triwiki/context-graph/extractors/topology/gate-edges.js +201 -0
  189. package/dist/core/triwiki/context-graph/extractors/topology/gates.js +182 -0
  190. package/dist/core/triwiki/context-graph/extractors/topology/globs.js +124 -0
  191. package/dist/core/triwiki/context-graph/extractors/topology/index.js +92 -0
  192. package/dist/core/triwiki/context-graph/extractors/topology/routes.js +135 -0
  193. package/dist/core/triwiki/context-graph/extractors/topology/shared.js +215 -0
  194. package/dist/core/triwiki/context-graph/graph-index.js +143 -0
  195. package/dist/core/triwiki/context-graph/ids.js +0 -0
  196. package/dist/core/triwiki/context-graph/lint/index.js +0 -0
  197. package/dist/core/triwiki/context-graph/lint/rules.js +232 -0
  198. package/dist/core/triwiki/context-graph/lint/warnings.js +93 -0
  199. package/dist/core/triwiki/context-graph/paths.js +116 -0
  200. package/dist/core/triwiki/context-graph/profiles.js +78 -0
  201. package/dist/core/triwiki/context-graph/projections/anchors.js +91 -0
  202. package/dist/core/triwiki/context-graph/projections/attention.js +58 -0
  203. package/dist/core/triwiki/context-graph/projections/code-pack-workspace.js +62 -0
  204. package/dist/core/triwiki/context-graph/projections/code-pack.js +144 -0
  205. package/dist/core/triwiki/context-graph/projections/index.js +7 -0
  206. package/dist/core/triwiki/context-graph/projections/module-view.js +140 -0
  207. package/dist/core/triwiki/context-graph/projections/node-summary.js +118 -0
  208. package/dist/core/triwiki/context-graph/projections/pack-contract.js +6 -0
  209. package/dist/core/triwiki/context-graph/query/explain.js +0 -0
  210. package/dist/core/triwiki/context-graph/query/index.js +178 -0
  211. package/dist/core/triwiki/context-graph/query/load.js +116 -0
  212. package/dist/core/triwiki/context-graph/query/pack.js +117 -0
  213. package/dist/core/triwiki/context-graph/query/rank.js +142 -0
  214. package/dist/core/triwiki/context-graph/query/ranking-config.js +64 -0
  215. package/dist/core/triwiki/context-graph/query/seeds.js +241 -0
  216. package/dist/core/triwiki/context-graph/query/snapshot-cache.js +72 -0
  217. package/dist/core/triwiki/context-graph/query/traverse.js +154 -0
  218. package/dist/core/triwiki/context-graph/query-types.js +29 -0
  219. package/dist/core/triwiki/context-graph/store/compile-lock.js +21 -0
  220. package/dist/core/triwiki/context-graph/store/event-log.js +48 -0
  221. package/dist/core/triwiki/context-graph/store/fragment-cache.js +85 -0
  222. package/dist/core/triwiki/context-graph/store/graph-status.js +85 -0
  223. package/dist/core/triwiki/context-graph/store/snapshot-store.js +155 -0
  224. package/dist/core/triwiki/triwiki-proof-bank-index-repair.js +115 -0
  225. package/dist/core/triwiki/triwiki-proof-bank-index-store.js +290 -0
  226. package/dist/core/triwiki/triwiki-proof-bank-index.js +126 -0
  227. package/dist/core/triwiki/triwiki-proof-bank.js +7 -1
  228. package/dist/core/verification/context-graph-affected.js +271 -0
  229. package/dist/core/version.js +1 -1
  230. package/dist/native/sks-menubar/Sources/AlertFactory.swift +11 -3
  231. package/dist/native/sks-menubar/Sources/AppDelegate.swift +9 -0
  232. package/dist/native/sks-menubar/Sources/ControlCenterWindowController.swift +25 -3
  233. package/dist/native/sks-menubar/Sources/ControlKit.swift +19 -8
  234. package/dist/native/sks-menubar/Sources/DiagnosticsViewController.swift +1 -2
  235. package/dist/native/sks-menubar/Sources/MCPServersViewController.swift +45 -17
  236. package/dist/native/sks-menubar/Sources/OverviewSummary.swift +162 -0
  237. package/dist/native/sks-menubar/Sources/OverviewViewController.swift +136 -190
  238. package/dist/native/sks-menubar/Sources/ProcessClient.swift +107 -11
  239. package/dist/native/sks-menubar/Sources/ProvidersMultiProvider.swift +5 -1
  240. package/dist/native/sks-menubar/Sources/ProvidersOpenRouter.swift +16 -4
  241. package/dist/native/sks-menubar/Sources/ProvidersRoleModels.swift +4 -1
  242. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +131 -0
  243. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +288 -341
  244. package/dist/native/sks-menubar/Sources/RemoteTelegramCenterState.swift +447 -0
  245. package/dist/native/sks-menubar/Sources/RemoteTelegramRendering.swift +484 -0
  246. package/dist/native/sks-menubar/Sources/RemoteTelegramViewController.swift +364 -115
  247. package/dist/native/sks-menubar/Sources/SettingsViewController.swift +73 -12
  248. package/dist/native/sks-menubar/Sources/SidebarItem.swift +3 -3
  249. package/dist/native/sks-menubar/Sources/StatusItemController.swift +13 -13
  250. package/dist/native/sks-menubar/Sources/TelegramHubSupervisor.swift +469 -0
  251. package/dist/native/sks-menubar/Sources/UpdatesViewController.swift +1 -6
  252. package/dist/native/sks-menubar/Tests/AppRuntimeTestSupport.swift +12 -0
  253. package/dist/native/sks-menubar/Tests/NativeTelegramRegressionRunner.swift +55 -0
  254. package/dist/native/sks-menubar/Tests/ProcessClientTests.swift +33 -0
  255. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +142 -0
  256. package/dist/native/sks-menubar/Tests/RemoteTelegramCenterStateTests.swift +56 -0
  257. package/dist/native/sks-menubar/Tests/TelegramHubSupervisorTests.swift +55 -0
  258. package/dist/scripts/codex-lb-catalog-passthrough-check.js +120 -0
  259. package/dist/scripts/codex-lb-desktop-auth-invariant-check.js +169 -0
  260. package/dist/scripts/codex-lb-desktop-bridge-check.js +394 -0
  261. package/dist/scripts/codex-lb-desktop-bridge-latency-check.js +196 -0
  262. package/dist/scripts/codex-lb-desktop-capabilities-check.js +287 -0
  263. package/dist/scripts/codex-lb-desktop-real-evidence-check.js +123 -0
  264. package/dist/scripts/codex-lb-fast-mode-truth-check.js +10 -3
  265. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +81 -40
  266. package/dist/scripts/codex-lb-gpt56-fast-profile-check.js +99 -37
  267. package/dist/scripts/context-graph-check.js +191 -0
  268. package/dist/scripts/doctor-fixes-codex-app-fast-ui-check.js +1 -1
  269. package/dist/scripts/gate-policy-audit-check.js +1 -1
  270. package/dist/scripts/helper-dedup-check.js +0 -2
  271. package/dist/scripts/installed-package-smoke-check.js +4 -1
  272. package/dist/scripts/latest-version-guidance-check.js +74 -0
  273. package/dist/scripts/release-metadata-check.js +21 -4
  274. package/dist/scripts/release-real-check.js +7 -0
  275. package/dist/scripts/ux-review-imagegen-blackbox-check.js +25 -1
  276. package/dist/scripts/ux-review-run-wires-imagegen-check.js +9 -1
  277. package/package.json +8 -3
  278. package/release-gates.v2.json +176 -1
  279. package/runtime-required-scripts.json +30 -0
  280. package/schemas/triwiki/context-graph.schema.json +119 -0
  281. package/dist/cli/install-helpers-codex-lb-selftest-chain.js +0 -112
  282. package/dist/cli/install-helpers-codex-lb-selftest.js +0 -481
  283. package/dist/core/triwiki/code-index-scanner.js +0 -309
@@ -0,0 +1,575 @@
1
+ import fsp from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { CODEX_LB_DESKTOP_BRIDGE_MARKER, CODEX_LB_MODEL_CATALOG_MARKER, upsertCodexLbCompatDesktopConfig, upsertCodexLbNativeDesktopConfig } from '../../cli/install-helpers-codex-lb-config.js';
6
+ import { codexAuthChatgptBackupPath } from '../../cli/install-helpers-codex-lb-shared.js';
7
+ import { ensureTrailingNewline, safeWriteCodexConfigToml } from '../codex-runtime/codex-desktop-config-policy.js';
8
+ import { messageOf as errorMessage } from '../errors/message.js';
9
+ import { ensureDir, readText } from '../fsx.js';
10
+ import { assertDesktopAuthUnchangedBySks, assertDesktopOAuthSemanticIdentity, captureCodexAuthSnapshot, codexAuthApiKeyMatches } from './desktop-auth-invariant.js';
11
+ import { DEFAULT_CODEX_LB_GATEWAY_AUTH_TRANSPORT, parseCodexLbGatewayAuthTransport } from './desktop-mode.js';
12
+ import { backupCodexLbMigrationFile, codexLbMigrationReceiptDir, createCodexLbMigrationReceiptId, finalizeCodexLbMigrationReceiptFiles, rollbackCodexLbMigrationReceipt, writeCodexLbMigrationReceipt } from './migration-receipt.js';
13
+ const LEGACY_OPENAI_ROUTING_MARKER = '# sks-codex-lb-managed-openai-base-url';
14
+ export async function detectLegacyCodexLbDesktopState(input = {}) {
15
+ const home = input.home || process.env.HOME || os.homedir();
16
+ const configPath = input.configPath || path.join(home, '.codex', 'config.toml');
17
+ const authPath = input.authPath || path.join(home, '.codex', 'auth.json');
18
+ const oauthBackupPath = input.oauthBackupPath || codexAuthChatgptBackupPath(home);
19
+ const receiptDir = input.receiptDir || codexLbMigrationReceiptDir(home);
20
+ const [config, auth, backup, priorReceiptPresent, backupFile, gatewayKeyMatches] = await Promise.all([
21
+ readText(configPath, ''),
22
+ captureCodexAuthSnapshot({ home, authPath }),
23
+ captureCodexAuthSnapshot({ home, authPath: oauthBackupPath }),
24
+ hasPriorReceipt(receiptDir),
25
+ inspectOAuthBackupFile(oauthBackupPath),
26
+ input.expectedGatewayApiKey
27
+ ? codexAuthApiKeyMatches({
28
+ home,
29
+ authPath,
30
+ expectedApiKey: input.expectedGatewayApiKey
31
+ })
32
+ : Promise.resolve(null)
33
+ ]);
34
+ const providerSelected = topLevelTomlString(config, 'model_provider') === 'codex-lb';
35
+ const providerBaseUrl = tomlTableString(config, 'model_providers.codex-lb', 'base_url') || null;
36
+ const legacyOpenAiRoutingMarkerPresent = hasAnyTopLevelMarker(config, [
37
+ LEGACY_OPENAI_ROUTING_MARKER
38
+ ]);
39
+ const managedOpenAiBaseUrl = hasAnyTopLevelMarker(config, [
40
+ LEGACY_OPENAI_ROUTING_MARKER,
41
+ CODEX_LB_DESKTOP_BRIDGE_MARKER
42
+ ])
43
+ ? topLevelTomlString(config, 'openai_base_url') || null
44
+ : null;
45
+ const expectedRemote = normalizeUrl(input.remoteBaseUrl || providerBaseUrl || '');
46
+ const gatewayKeyBindingChecked = Boolean(input.expectedGatewayApiKey);
47
+ const managedRemoteRouting = Boolean(managedOpenAiBaseUrl
48
+ && expectedRemote
49
+ && normalizeUrl(managedOpenAiBaseUrl) === expectedRemote
50
+ && !isLoopbackUrl(managedOpenAiBaseUrl));
51
+ const catalogPath = topLevelTomlString(config, 'model_catalog_json');
52
+ const cliProviderContract = Boolean(providerBaseUrl
53
+ && expectedRemote
54
+ && normalizeUrl(providerBaseUrl) === expectedRemote
55
+ && !isLoopbackUrl(providerBaseUrl)
56
+ && tomlTableString(config, 'model_providers.codex-lb', 'env_key') === 'CODEX_LB_API_KEY'
57
+ && tomlTableBoolean(config, 'model_providers.codex-lb', 'requires_openai_auth') === false);
58
+ const orphanedManagedRemoteRouting = Boolean(!topLevelTomlString(config, 'openai_base_url')
59
+ && cliProviderContract
60
+ && gatewayKeyMatches === true
61
+ && (legacyOpenAiRoutingMarkerPresent
62
+ || Boolean(catalogPath && isSksOwnedLegacyCatalogPath(catalogPath, home))
63
+ || backup.mode === 'chatgpt_oauth'
64
+ || backup.mode === 'mixed'));
65
+ const oauthBackupIdentityPresent = backup.semantic_fingerprint !== null;
66
+ const oauthBackupValid = ((backup.mode === 'chatgpt_oauth' || backup.mode === 'mixed')
67
+ && backupFile.owner_safe
68
+ && backupFile.mode_safe
69
+ && oauthBackupIdentityPresent);
70
+ const recoveryEvidence = oauthBackupValid || priorReceiptPresent;
71
+ const legacyDestructiveMode = auth.mode === 'openai_api_key'
72
+ && gatewayKeyMatches === true
73
+ && ((providerSelected && managedRemoteRouting) || orphanedManagedRemoteRouting);
74
+ const blockers = [];
75
+ if (auth.mode !== 'openai_api_key')
76
+ blockers.push('legacy_auth_not_api_key_only');
77
+ if (!gatewayKeyBindingChecked)
78
+ blockers.push('legacy_gateway_key_binding_unavailable');
79
+ else if (gatewayKeyMatches !== true)
80
+ blockers.push('legacy_gateway_key_mismatch');
81
+ if (!providerSelected && !orphanedManagedRemoteRouting)
82
+ blockers.push('legacy_codex_lb_provider_not_selected');
83
+ if (!managedRemoteRouting && !orphanedManagedRemoteRouting) {
84
+ blockers.push('legacy_managed_remote_openai_routing_missing');
85
+ }
86
+ if (!recoveryEvidence)
87
+ blockers.push('legacy_oauth_recovery_evidence_missing');
88
+ return {
89
+ schema: 'sks.codex-lb-legacy-desktop-detection.v1',
90
+ legacy_destructive_mode: legacyDestructiveMode,
91
+ auth_mode: auth.mode,
92
+ auth_path: authPath,
93
+ config_path: configPath,
94
+ oauth_backup_path: oauthBackupPath,
95
+ oauth_backup_valid: oauthBackupValid,
96
+ oauth_backup_sha256: backup.sha256,
97
+ oauth_backup_owner_safe: backupFile.owner_safe,
98
+ oauth_backup_mode_safe: backupFile.mode_safe,
99
+ oauth_backup_identity_present: oauthBackupIdentityPresent,
100
+ gateway_key_binding_checked: gatewayKeyBindingChecked,
101
+ gateway_key_matches: gatewayKeyMatches,
102
+ provider_selected: providerSelected,
103
+ provider_base_url: providerBaseUrl,
104
+ managed_openai_base_url: managedOpenAiBaseUrl,
105
+ managed_remote_routing: managedRemoteRouting,
106
+ recovery_evidence: recoveryEvidence,
107
+ prior_receipt_present: priorReceiptPresent,
108
+ blockers
109
+ };
110
+ }
111
+ export async function migrateLegacyCodexLbDesktop(input) {
112
+ const home = input.home || process.env.HOME || os.homedir();
113
+ const configPath = input.configPath || path.join(home, '.codex', 'config.toml');
114
+ const authPath = input.authPath || path.join(home, '.codex', 'auth.json');
115
+ const oauthBackupPath = input.oauthBackupPath || codexAuthChatgptBackupPath(home);
116
+ const receiptDir = input.receiptDir || codexLbMigrationReceiptDir(home);
117
+ const gatewayAuthTransport = parseCodexLbGatewayAuthTransport(input.gatewayAuthTransport || DEFAULT_CODEX_LB_GATEWAY_AUTH_TRANSPORT);
118
+ const targetMode = input.targetMode === 'desktop-dual-auth-compat'
119
+ ? 'desktop-dual-auth-compat'
120
+ : 'desktop-native-bridge';
121
+ if (targetMode === 'desktop-dual-auth-compat' && gatewayAuthTransport !== 'x-codex-lb-api-key') {
122
+ return {
123
+ schema: 'sks.codex-lb-legacy-migration.v1',
124
+ ok: false,
125
+ status: 'failed',
126
+ mode: targetMode,
127
+ identity_plane: 'unavailable',
128
+ routing_plane: 'unchanged',
129
+ gateway_auth_transport: gatewayAuthTransport,
130
+ oauth_preserved: false,
131
+ auth_path: authPath,
132
+ config_path: configPath,
133
+ receipt_path: null,
134
+ detection: await detectLegacyCodexLbDesktopState({
135
+ home,
136
+ configPath,
137
+ authPath,
138
+ oauthBackupPath,
139
+ receiptDir,
140
+ ...(input.remoteBaseUrl ? { remoteBaseUrl: input.remoteBaseUrl } : {}),
141
+ ...(input.gatewayApiKey ? { expectedGatewayApiKey: input.gatewayApiKey } : {})
142
+ }),
143
+ blockers: ['desktop_compat_requires_x_codex_lb_api_key_transport'],
144
+ error: 'desktop_compat_requires_x_codex_lb_api_key_transport'
145
+ };
146
+ }
147
+ const detection = await detectLegacyCodexLbDesktopState({
148
+ home,
149
+ configPath,
150
+ authPath,
151
+ oauthBackupPath,
152
+ receiptDir,
153
+ ...(input.remoteBaseUrl ? { remoteBaseUrl: input.remoteBaseUrl } : {}),
154
+ ...(input.gatewayApiKey ? { expectedGatewayApiKey: input.gatewayApiKey } : {})
155
+ });
156
+ const baseResult = {
157
+ schema: 'sks.codex-lb-legacy-migration.v1',
158
+ mode: targetMode,
159
+ gateway_auth_transport: gatewayAuthTransport,
160
+ auth_path: authPath,
161
+ config_path: configPath,
162
+ detection
163
+ };
164
+ if (!detection.legacy_destructive_mode) {
165
+ return {
166
+ ...baseResult,
167
+ ok: false,
168
+ status: 'not_legacy',
169
+ identity_plane: 'unavailable',
170
+ routing_plane: 'unchanged',
171
+ oauth_preserved: false,
172
+ receipt_path: null,
173
+ blockers: detection.blockers
174
+ };
175
+ }
176
+ if (!detection.oauth_backup_valid) {
177
+ return {
178
+ ...baseResult,
179
+ ok: false,
180
+ status: 'oauth_login_required',
181
+ identity_plane: 'unavailable',
182
+ routing_plane: 'unchanged',
183
+ oauth_preserved: false,
184
+ receipt_path: null,
185
+ blockers: ['valid_chatgpt_oauth_backup_required', 'run_codex_login']
186
+ };
187
+ }
188
+ const remoteBaseUrl = normalizeUrl(input.remoteBaseUrl || detection.provider_base_url || '');
189
+ if (!remoteBaseUrl) {
190
+ return {
191
+ ...baseResult,
192
+ ok: false,
193
+ status: 'failed',
194
+ identity_plane: 'unavailable',
195
+ routing_plane: 'unchanged',
196
+ oauth_preserved: false,
197
+ receipt_path: null,
198
+ blockers: ['missing_remote_base_url'],
199
+ error: 'missing_remote_base_url'
200
+ };
201
+ }
202
+ if (!input.restartApp) {
203
+ return {
204
+ ...baseResult,
205
+ ok: false,
206
+ status: 'restart_required',
207
+ identity_plane: 'unavailable',
208
+ routing_plane: 'unchanged',
209
+ oauth_preserved: false,
210
+ receipt_path: null,
211
+ blockers: ['codex_app_restart_required', 'rerun_with_restart_app']
212
+ };
213
+ }
214
+ if (!input.quitApp) {
215
+ return {
216
+ ...baseResult,
217
+ ok: false,
218
+ status: 'restart_required',
219
+ identity_plane: 'unavailable',
220
+ routing_plane: 'unchanged',
221
+ oauth_preserved: false,
222
+ receipt_path: null,
223
+ blockers: ['codex_app_quit_required', 'rerun_with_restart_app']
224
+ };
225
+ }
226
+ const quitApp = await input.quitApp();
227
+ if (quitApp.ok !== true || quitApp.skipped === true) {
228
+ return {
229
+ ...baseResult,
230
+ ok: false,
231
+ status: 'failed',
232
+ identity_plane: 'unavailable',
233
+ routing_plane: 'unchanged',
234
+ oauth_preserved: false,
235
+ receipt_path: null,
236
+ quit_app: quitApp,
237
+ blockers: ['codex_app_quiescence_required'],
238
+ error: `codex_app_quit_failed:${quitApp.status || 'failed'}`
239
+ };
240
+ }
241
+ const quiescedDetection = await detectLegacyCodexLbDesktopState({
242
+ home,
243
+ configPath,
244
+ authPath,
245
+ oauthBackupPath,
246
+ receiptDir,
247
+ ...(input.remoteBaseUrl ? { remoteBaseUrl: input.remoteBaseUrl } : {}),
248
+ ...(input.gatewayApiKey ? { expectedGatewayApiKey: input.gatewayApiKey } : {})
249
+ });
250
+ const stateStableAfterQuit = quiescedDetection.legacy_destructive_mode
251
+ && quiescedDetection.gateway_key_matches === true
252
+ && quiescedDetection.oauth_backup_valid
253
+ && quiescedDetection.oauth_backup_sha256 === detection.oauth_backup_sha256
254
+ && quiescedDetection.provider_base_url === detection.provider_base_url
255
+ && quiescedDetection.managed_openai_base_url === detection.managed_openai_base_url;
256
+ if (!stateStableAfterQuit) {
257
+ return {
258
+ ...baseResult,
259
+ detection: quiescedDetection,
260
+ ok: false,
261
+ status: 'failed',
262
+ identity_plane: 'unavailable',
263
+ routing_plane: 'unchanged',
264
+ oauth_preserved: false,
265
+ receipt_path: null,
266
+ quit_app: quitApp,
267
+ blockers: ['legacy_state_changed_during_quiescence', ...quiescedDetection.blockers],
268
+ error: 'legacy_state_changed_during_quiescence'
269
+ };
270
+ }
271
+ const receiptId = createCodexLbMigrationReceiptId();
272
+ const backupDir = path.join(receiptDir, receiptId, 'files');
273
+ const currentConfig = await readText(configPath, '');
274
+ const catalogPath = topLevelTomlString(currentConfig, 'model_catalog_json');
275
+ const paths = [
276
+ { path: configPath, owned: false },
277
+ { path: authPath, owned: false },
278
+ ...(catalogPath ? [{ path: catalogPath, owned: isSksOwnedLegacyCatalogPath(catalogPath, home) }] : []),
279
+ ...(input.bridgeSettingsPath ? [{ path: input.bridgeSettingsPath, owned: true }] : []),
280
+ ...(input.bridgeLaunchAgentPath ? [{ path: input.bridgeLaunchAgentPath, owned: true }] : []),
281
+ ...(input.bridgeStatePath ? [{ path: input.bridgeStatePath, owned: true }] : [])
282
+ ];
283
+ const backups = [];
284
+ let bridgeAttempted = false;
285
+ let restartAttempted = false;
286
+ try {
287
+ for (const file of uniquePaths(paths)) {
288
+ backups.push(await backupCodexLbMigrationFile(file.path, backupDir, file.owned));
289
+ }
290
+ if (!input.gatewayApiKey
291
+ || !await codexAuthApiKeyMatches({
292
+ home,
293
+ authPath,
294
+ expectedApiKey: input.gatewayApiKey
295
+ })) {
296
+ throw new Error('legacy_gateway_key_changed_before_auth_restore');
297
+ }
298
+ const oauthBytes = await fsp.readFile(oauthBackupPath);
299
+ if (sha256(oauthBytes) !== quiescedDetection.oauth_backup_sha256) {
300
+ throw new Error('oauth_backup_changed_before_restore');
301
+ }
302
+ await writeBufferAtomic(authPath, oauthBytes);
303
+ const oauthBaseline = await captureCodexAuthSnapshot({ home, authPath });
304
+ if (oauthBaseline.mode !== 'chatgpt_oauth' && oauthBaseline.mode !== 'mixed') {
305
+ throw new Error('restored_oauth_backup_invalid');
306
+ }
307
+ assertDesktopOAuthSemanticIdentity(await captureCodexAuthSnapshot({ home, authPath: oauthBackupPath }), oauthBaseline);
308
+ let configForMigration = currentConfig;
309
+ configForMigration = removeTopLevelTomlKey(configForMigration, 'model_provider');
310
+ configForMigration = removeTopLevelTomlKey(configForMigration, 'openai_base_url');
311
+ configForMigration = removeTopLevelMarker(configForMigration, LEGACY_OPENAI_ROUTING_MARKER);
312
+ if (catalogPath && isSksOwnedLegacyCatalogPath(catalogPath, home)) {
313
+ configForMigration = removeTopLevelTomlKey(configForMigration, 'model_catalog_json');
314
+ configForMigration = removeTopLevelMarker(configForMigration, CODEX_LB_MODEL_CATALOG_MARKER);
315
+ }
316
+ const nextConfig = targetMode === 'desktop-dual-auth-compat'
317
+ ? upsertCodexLbCompatDesktopConfig(configForMigration, { remoteBaseUrl })
318
+ : upsertCodexLbNativeDesktopConfig(configForMigration, {
319
+ bridgeBaseUrl: input.bridgeBaseUrl,
320
+ remoteBaseUrl
321
+ });
322
+ const configWrite = await safeWriteCodexConfigToml(configPath, currentConfig, nextConfig, 'codex-lb-legacy-desktop-migration', { verifyUnchangedBeforeWrite: true });
323
+ if (!configWrite.ok)
324
+ throw new Error(`legacy_config_write_failed:${configWrite.status}`);
325
+ const afterConfigBeforeRestart = await captureCodexAuthSnapshot({ home, authPath });
326
+ await assertDesktopAuthUnchangedBySks(oauthBaseline, afterConfigBeforeRestart);
327
+ let bridge;
328
+ if (targetMode === 'desktop-native-bridge') {
329
+ bridgeAttempted = Boolean(input.startBridge);
330
+ bridge = input.startBridge ? await input.startBridge() : undefined;
331
+ if (bridge?.ok === false)
332
+ throw new Error(`desktop_bridge_start_failed:${bridge.status || 'failed'}`);
333
+ }
334
+ else if (input.stopBridge) {
335
+ bridge = await input.stopBridge();
336
+ if (bridge?.ok === false)
337
+ throw new Error(`desktop_bridge_stop_failed:${bridge.status || 'failed'}`);
338
+ }
339
+ const beforeRestart = await captureCodexAuthSnapshot({ home, authPath });
340
+ await assertDesktopAuthUnchangedBySks(oauthBaseline, beforeRestart);
341
+ restartAttempted = true;
342
+ const restartApp = await input.restartApp();
343
+ if (restartApp.ok !== true)
344
+ throw new Error(`codex_app_restart_failed:${restartApp.status || 'failed'}`);
345
+ const afterRestart = await captureCodexAuthSnapshot({ home, authPath });
346
+ assertDesktopOAuthSemanticIdentity(oauthBaseline, afterRestart);
347
+ const capability = input.verifyCapabilities ? await input.verifyCapabilities() : undefined;
348
+ if (capability && !capability.ok) {
349
+ throw new Error(`desktop_capability_verification_failed:${(capability.blockers || []).join(',') || 'failed'}`);
350
+ }
351
+ const routingPlane = targetMode === 'desktop-dual-auth-compat'
352
+ ? 'desktop_dual_auth_compat'
353
+ : 'desktop_native_bridge';
354
+ const capabilitySummary = {
355
+ ...(input.capabilitySummary || {}),
356
+ ...(capability?.summary || {}),
357
+ gateway_auth_transport: gatewayAuthTransport,
358
+ identity_plane: 'chatgpt_oauth',
359
+ routing_plane: routingPlane,
360
+ oauth_backup_sha256: quiescedDetection.oauth_backup_sha256 || 'unavailable'
361
+ };
362
+ const receipt = {
363
+ schema: 'sks.codex-lb-migration-receipt.v1',
364
+ id: receiptId,
365
+ created_at: new Date().toISOString(),
366
+ from_mode: 'legacy-destructive-api-key-auth',
367
+ to_mode: targetMode,
368
+ files: await finalizeCodexLbMigrationReceiptFiles(backups),
369
+ bridge_state_path: input.bridgeStatePath || null,
370
+ oauth_preserved: true,
371
+ capability_summary: capabilitySummary
372
+ };
373
+ const receiptPath = await writeCodexLbMigrationReceipt(receipt, { receiptDir });
374
+ return {
375
+ ...baseResult,
376
+ detection: quiescedDetection,
377
+ ok: true,
378
+ status: 'migrated',
379
+ identity_plane: 'chatgpt_oauth',
380
+ routing_plane: routingPlane,
381
+ oauth_preserved: true,
382
+ receipt_path: receiptPath,
383
+ receipt,
384
+ ...(bridge ? { bridge } : {}),
385
+ quit_app: quitApp,
386
+ restart_app: restartApp,
387
+ capability_summary: capabilitySummary,
388
+ blockers: []
389
+ };
390
+ }
391
+ catch (error) {
392
+ const rollbackQuit = restartAttempted
393
+ ? await input.quitApp().catch((quitError) => ({
394
+ ok: false,
395
+ status: 'failed',
396
+ skipped: false,
397
+ error: errorMessage(quitError)
398
+ }))
399
+ : undefined;
400
+ if (rollbackQuit && (rollbackQuit.ok !== true || rollbackQuit.skipped === true)) {
401
+ return {
402
+ ...baseResult,
403
+ detection: quiescedDetection,
404
+ ok: false,
405
+ status: 'failed',
406
+ identity_plane: 'chatgpt_oauth',
407
+ routing_plane: 'desktop_native_bridge',
408
+ oauth_preserved: true,
409
+ receipt_path: null,
410
+ quit_app: quitApp,
411
+ rollback_quit_app: rollbackQuit,
412
+ blockers: [
413
+ 'legacy_migration_failed',
414
+ 'legacy_migration_rollback_quiescence_failed'
415
+ ],
416
+ error: errorMessage(error)
417
+ };
418
+ }
419
+ const bridgeStop = bridgeAttempted && input.stopBridge
420
+ ? await input.stopBridge().catch((stopError) => ({
421
+ ok: false,
422
+ status: 'failed',
423
+ error: errorMessage(stopError)
424
+ }))
425
+ : undefined;
426
+ if (bridgeAttempted
427
+ && (!bridgeStop
428
+ || bridgeStop.ok !== true
429
+ || bridgeStop.running === true)) {
430
+ return {
431
+ ...baseResult,
432
+ detection: quiescedDetection,
433
+ ok: false,
434
+ status: 'failed',
435
+ identity_plane: 'chatgpt_oauth',
436
+ routing_plane: 'desktop_native_bridge',
437
+ oauth_preserved: true,
438
+ receipt_path: null,
439
+ ...(bridgeStop ? { bridge_stop: bridgeStop } : {}),
440
+ quit_app: quitApp,
441
+ ...(rollbackQuit ? { rollback_quit_app: rollbackQuit } : {}),
442
+ blockers: [
443
+ 'legacy_migration_failed',
444
+ 'legacy_migration_bridge_stop_unverified',
445
+ 'legacy_migration_manual_recovery_required'
446
+ ],
447
+ error: errorMessage(error)
448
+ };
449
+ }
450
+ const provisionalReceipt = {
451
+ schema: 'sks.codex-lb-migration-receipt.v1',
452
+ id: receiptId,
453
+ created_at: new Date().toISOString(),
454
+ from_mode: 'legacy-destructive-api-key-auth',
455
+ to_mode: 'desktop-native-bridge',
456
+ files: await finalizeCodexLbMigrationReceiptFiles(backups),
457
+ bridge_state_path: input.bridgeStatePath || null,
458
+ oauth_preserved: false,
459
+ capability_summary: {}
460
+ };
461
+ const rollback = await rollbackCodexLbMigrationReceipt({ receipt: provisionalReceipt });
462
+ return {
463
+ ...baseResult,
464
+ detection: quiescedDetection,
465
+ ok: false,
466
+ status: 'failed',
467
+ identity_plane: 'unavailable',
468
+ routing_plane: 'unchanged',
469
+ oauth_preserved: false,
470
+ receipt_path: null,
471
+ ...(bridgeStop ? { bridge_stop: bridgeStop } : {}),
472
+ quit_app: quitApp,
473
+ ...(rollbackQuit ? { rollback_quit_app: rollbackQuit } : {}),
474
+ blockers: [
475
+ 'legacy_migration_failed',
476
+ ...(bridgeStop?.ok === false ? ['legacy_migration_bridge_stop_failed'] : []),
477
+ ...(rollback.ok ? [] : ['legacy_migration_rollback_failed'])
478
+ ],
479
+ rollback,
480
+ error: errorMessage(error)
481
+ };
482
+ }
483
+ }
484
+ async function hasPriorReceipt(receiptDir) {
485
+ try {
486
+ return (await fsp.readdir(receiptDir)).some((entry) => entry.endsWith('.json'));
487
+ }
488
+ catch {
489
+ return false;
490
+ }
491
+ }
492
+ async function inspectOAuthBackupFile(filePath) {
493
+ try {
494
+ const stat = await fsp.lstat(filePath);
495
+ const expectedUid = typeof process.getuid === 'function' ? process.getuid() : stat.uid;
496
+ return {
497
+ owner_safe: stat.isFile() && !stat.isSymbolicLink() && stat.uid === expectedUid,
498
+ mode_safe: (stat.mode & 0o777) === 0o600
499
+ };
500
+ }
501
+ catch {
502
+ return {
503
+ owner_safe: false,
504
+ mode_safe: false
505
+ };
506
+ }
507
+ }
508
+ function uniquePaths(paths) {
509
+ const seen = new Map();
510
+ for (const entry of paths) {
511
+ const resolved = path.resolve(entry.path);
512
+ seen.set(resolved, (seen.get(resolved) || false) || entry.owned);
513
+ }
514
+ return [...seen].map(([filePath, owned]) => ({ path: filePath, owned }));
515
+ }
516
+ function topLevelTomlString(text, key) {
517
+ const topLevel = String(text || '').split(/\n\s*\[/)[0] || '';
518
+ return topLevel.match(new RegExp(`(?:^|\\n)\\s*${escapeRegExp(key)}\\s*=\\s*"([^"]+)"\\s*(?:#.*)?(?=\\n|$)`))?.[1] || '';
519
+ }
520
+ function tomlTableString(text, table, key) {
521
+ const escapedTable = escapeRegExp(table);
522
+ const block = String(text || '').match(new RegExp(`(?:^|\\n)\\[${escapedTable}\\]([\\s\\S]*?)(?=\\n\\[[^\\]]+\\]|\\s*$)`))?.[1] || '';
523
+ return block.match(new RegExp(`(?:^|\\n)\\s*${escapeRegExp(key)}\\s*=\\s*"([^"]+)"\\s*(?:#.*)?(?=\\n|$)`))?.[1] || '';
524
+ }
525
+ function tomlTableBoolean(text, table, key) {
526
+ const escapedTable = escapeRegExp(table);
527
+ const block = String(text || '').match(new RegExp(`(?:^|\\n)\\[${escapedTable}\\]([\\s\\S]*?)(?=\\n\\[[^\\]]+\\]|\\s*$)`))?.[1] || '';
528
+ const value = block.match(new RegExp(`(?:^|\\n)\\s*${escapeRegExp(key)}\\s*=\\s*(true|false)\\s*(?:#.*)?(?=\\n|$)`))?.[1];
529
+ return value === 'true' ? true : value === 'false' ? false : null;
530
+ }
531
+ function hasAnyTopLevelMarker(text, markers) {
532
+ const topLevel = String(text || '').split(/\n\s*\[/)[0] || '';
533
+ return topLevel.split(/\r?\n/).some((line) => markers.includes(line.trim()));
534
+ }
535
+ function removeTopLevelTomlKey(text, key) {
536
+ const lines = String(text || '').split('\n');
537
+ const firstTable = lines.findIndex((line) => /^\s*\[.+\]\s*$/.test(line));
538
+ const end = firstTable === -1 ? lines.length : firstTable;
539
+ const keyPattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=`);
540
+ return ensureTrailingNewline(lines.filter((line, index) => index >= end || !keyPattern.test(line)).join('\n'));
541
+ }
542
+ function removeTopLevelMarker(text, marker) {
543
+ const lines = String(text || '').split('\n');
544
+ const firstTable = lines.findIndex((line) => /^\s*\[.+\]\s*$/.test(line));
545
+ const end = firstTable === -1 ? lines.length : firstTable;
546
+ return ensureTrailingNewline(lines.filter((line, index) => index >= end || line.trim() !== marker).join('\n'));
547
+ }
548
+ function isSksOwnedLegacyCatalogPath(catalogPath, home) {
549
+ return path.resolve(catalogPath) === path.resolve(home, '.codex', 'sks-codex-lb-tool-catalog.json');
550
+ }
551
+ function normalizeUrl(value) {
552
+ return String(value || '').trim().replace(/\/+$/, '');
553
+ }
554
+ function isLoopbackUrl(value) {
555
+ return /^https?:\/\/(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::|\/|$)/i.test(value);
556
+ }
557
+ function sha256(value) {
558
+ return createHash('sha256').update(value).digest('hex');
559
+ }
560
+ async function writeBufferAtomic(filePath, bytes) {
561
+ await ensureDir(path.dirname(filePath));
562
+ const tempPath = `${filePath}.${process.pid}.${Date.now().toString(36)}.tmp`;
563
+ try {
564
+ await fsp.writeFile(tempPath, bytes, { mode: 0o600, flag: 'wx' });
565
+ await fsp.rename(tempPath, filePath);
566
+ await fsp.chmod(filePath, 0o600);
567
+ }
568
+ catch (error) {
569
+ await fsp.rm(tempPath, { force: true }).catch(() => { });
570
+ throw error;
571
+ }
572
+ }
573
+ function escapeRegExp(value) {
574
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
575
+ }