@bitkyc08/opencodex 2.94.0 → 2.96.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 (289) hide show
  1. package/gui/dist/assets/App-B4j-Txmb.css +1 -0
  2. package/gui/dist/assets/App-bwugJRKn.js +58 -0
  3. package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-BOPQyDbH.js} +1 -1
  4. package/gui/dist/assets/index-ebuVUtB7.js +94 -0
  5. package/gui/dist/assets/quota-summary-6HsrHQAy.js +1 -0
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/anthropic.ts +10 -3
  9. package/src/adapters/command-code-project-context.ts +3 -3
  10. package/src/adapters/kiro/adapter.ts +4 -1
  11. package/src/adapters/kiro/stream.ts +1 -0
  12. package/src/adapters/kiro-events.ts +1 -0
  13. package/src/adapters/ollama-native.ts +10 -6
  14. package/src/adapters/openai-chat/messages.ts +20 -7
  15. package/src/adapters/openai-chat/passthrough.ts +4 -2
  16. package/src/adapters/openai-chat/single-system.ts +24 -0
  17. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  18. package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
  19. package/src/adapters/openai-responses/passthrough.ts +45 -11
  20. package/src/adapters/openai-responses/prompt-cache.ts +3 -1
  21. package/src/adapters/openai-responses/request-strips.ts +23 -4
  22. package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
  23. package/src/adapters/openai-responses/tool-schema.ts +20 -8
  24. package/src/adapters/openai-responses/transport.ts +17 -26
  25. package/src/adapters/opencode-go-additional-tools.ts +39 -6
  26. package/src/adapters/qoder/adapter.ts +1 -1
  27. package/src/adapters/qoder/image-input.ts +5 -2
  28. package/src/adapters/routed-agent-messages.ts +3 -0
  29. package/src/adapters/xai-web-search.ts +6 -3
  30. package/src/adapters/zed-additional-tools.ts +7 -7
  31. package/src/adapters/zed.ts +1 -6
  32. package/src/advisor/consult.ts +22 -10
  33. package/src/advisor/runtime.ts +10 -4
  34. package/src/bridge/max-output-completion.ts +41 -0
  35. package/src/bridge/response-json.ts +9 -4
  36. package/src/bridge/sse.ts +13 -2
  37. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
  38. package/src/chatgpt/app-server-shim/launcher.ts +40 -6
  39. package/src/claude/compatibility.ts +5 -1
  40. package/src/claude/desktop-3p.ts +27 -6
  41. package/src/claude/desktop-model-visibility.ts +141 -0
  42. package/src/claude/desktop-remote-store-io.ts +8 -8
  43. package/src/claude/inbound-content-options.ts +11 -1
  44. package/src/claude/intercept/proxy-auth.ts +16 -16
  45. package/src/cli/account-main.ts +3 -2
  46. package/src/cli/agent.ts +44 -15
  47. package/src/cli/capabilities-agents-routing.ts +9 -0
  48. package/src/cli/capabilities-provider-models.ts +7 -0
  49. package/src/cli/chatgpt-command.ts +1 -1
  50. package/src/cli/codex-launcher.ts +20 -8
  51. package/src/cli/codex-shim-autorestore.ts +19 -1
  52. package/src/cli/dispatch.ts +6 -6
  53. package/src/cli/doctor.ts +5 -5
  54. package/src/cli/ensure-desired-integrations.ts +4 -3
  55. package/src/cli/index.ts +8 -10
  56. package/src/cli/init.ts +2 -2
  57. package/src/cli/internal-command.ts +29 -2
  58. package/src/cli/message-command.ts +2 -1
  59. package/src/cli/message-mcp-command.ts +29 -0
  60. package/src/cli/provider-cc-switch-import.ts +185 -0
  61. package/src/cli/provider.ts +5 -0
  62. package/src/cli/registry.ts +2 -1
  63. package/src/cli/restart-scope.ts +2 -2
  64. package/src/cli/root.ts +6 -6
  65. package/src/cli/stop-approval.ts +15 -1
  66. package/src/cli/v2.ts +69 -19
  67. package/src/client/machine-api.ts +2 -2
  68. package/src/clients/config-export.ts +14 -3
  69. package/src/codex/account-cooldown-response.ts +18 -0
  70. package/src/codex/account-store.ts +1 -0
  71. package/src/codex/app-server-restart-service.ts +2 -2
  72. package/src/codex/auth-api/login-flow.ts +2 -2
  73. package/src/codex/auth-api/pool-quota-probe.ts +2 -2
  74. package/src/codex/auth-context-provider.ts +15 -0
  75. package/src/codex/auth-context.ts +14 -23
  76. package/src/codex/catalog/bundled.ts +10 -3
  77. package/src/codex/catalog/metadata.ts +4 -5
  78. package/src/codex/catalog/native-omission.ts +28 -0
  79. package/src/codex/catalog/native-template.ts +58 -0
  80. package/src/codex/catalog/parsing.ts +3 -29
  81. package/src/codex/catalog/provider-models.ts +2 -1
  82. package/src/codex/catalog/retained-sync.ts +15 -5
  83. package/src/codex/catalog/write-audit.ts +18 -18
  84. package/src/codex/cli-install-provenance.ts +46 -45
  85. package/src/codex/cli-update-artifacts.ts +8 -6
  86. package/src/codex/cli-update-job-store-windows.ts +99 -27
  87. package/src/codex/cli-update-job-worker.ts +3 -11
  88. package/src/codex/cli-update-recovery.ts +54 -8
  89. package/src/codex/cli-update-selection-gate.ts +74 -4
  90. package/src/codex/cli-windows-plan-provenance.ts +37 -19
  91. package/src/codex/codex-home-owner.ts +9 -8
  92. package/src/codex/convergence.ts +13 -3
  93. package/src/codex/coordinator-doctor.ts +14 -8
  94. package/src/codex/desktop-app/handoff.ts +1 -1
  95. package/src/codex/desktop-app-restart.ts +11 -1
  96. package/src/codex/exec-boundary.ts +26 -5
  97. package/src/codex/forward-transport-headers.ts +33 -33
  98. package/src/codex/history-provider.ts +11 -10
  99. package/src/codex/inject/bounded-config-reader.ts +14 -13
  100. package/src/codex/installation-id.ts +72 -0
  101. package/src/codex/main-account.ts +6 -6
  102. package/src/codex/native-main-lock-file.ts +13 -12
  103. package/src/codex/native-residue.ts +18 -14
  104. package/src/codex/orca-auth-source.ts +8 -7
  105. package/src/codex/quota-types.ts +5 -0
  106. package/src/codex/quota.ts +49 -7
  107. package/src/codex/role-auto-assign.ts +50 -26
  108. package/src/codex/role-capability.ts +160 -0
  109. package/src/codex/role-sizing.ts +24 -6
  110. package/src/codex/routing/cooldown-math.ts +3 -2
  111. package/src/codex/runtime.ts +43 -3
  112. package/src/codex/shim-fingerprint.ts +11 -9
  113. package/src/codex/shim-inspect.ts +3 -2
  114. package/src/codex/shim-restore-lock.ts +11 -14
  115. package/src/codex/shim-state-file.ts +22 -14
  116. package/src/codex/shim-wrapper-write.ts +7 -6
  117. package/src/codex/shim.ts +25 -2
  118. package/src/codex/transition-state.ts +5 -4
  119. package/src/combos/failover.ts +43 -4
  120. package/src/config/atomic-write.ts +38 -7
  121. package/src/config/diagnostics.ts +3 -0
  122. package/src/config/initialize.ts +6 -6
  123. package/src/config/load-degrade.ts +2 -0
  124. package/src/config/process-state.ts +23 -5
  125. package/src/config/salvage.ts +1 -0
  126. package/src/config/schema/config-schema.ts +29 -1
  127. package/src/config/schema/leaf-validators.ts +7 -0
  128. package/src/config/schema/workflow-budget.ts +43 -0
  129. package/src/config/tracked-runtime-inspection.ts +188 -0
  130. package/src/generated/compatibility-version.json +380 -244
  131. package/src/grok/sync.ts +10 -1
  132. package/src/integrations/aside-profile-context.ts +1 -1
  133. package/src/integrations/droid-settings.ts +4 -4
  134. package/src/integrations/hermes-profiles.ts +3 -3
  135. package/src/lib/bounded-file-read.ts +3 -9
  136. package/src/lib/bun-runtime-preflight.ts +9 -8
  137. package/src/lib/file-identity.ts +15 -0
  138. package/src/lib/local-chat-completion.ts +8 -6
  139. package/src/lib/local-destinations.ts +32 -3
  140. package/src/lib/redact-folding.ts +9 -0
  141. package/src/lib/spend-pool-alias-validation.ts +6 -6
  142. package/src/lib/state-store-registrations.ts +2 -0
  143. package/src/lib/test-home-guard.ts +37 -9
  144. package/src/lib/windows-secret-acl.ts +49 -31
  145. package/src/lib/workflow-budget-config.ts +39 -0
  146. package/src/local-credentials/generation.ts +6 -2
  147. package/src/local-credentials/inventory.ts +132 -8
  148. package/src/messaging/mcp-queue-rpc.ts +102 -0
  149. package/src/messaging/mcp-queue-server.ts +42 -0
  150. package/src/messaging/mcp-queue-tools.ts +39 -0
  151. package/src/messaging/remote-forward-failure.ts +35 -0
  152. package/src/messaging/remote-ports.ts +27 -5
  153. package/src/messaging/remote-process.ts +30 -4
  154. package/src/messaging/remote-tunnels.ts +80 -15
  155. package/src/oauth/anthropic-identity.ts +2 -6
  156. package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
  157. package/src/oauth/google-antigravity.ts +23 -10
  158. package/src/oauth/index.ts +7 -0
  159. package/src/oauth/kiro-device-login.ts +87 -30
  160. package/src/oauth/kiro-iam-identity-center.ts +107 -0
  161. package/src/oauth/store.ts +9 -7
  162. package/src/providers/account-quota-disk.ts +18 -4
  163. package/src/providers/anthropic-subscription.ts +25 -0
  164. package/src/providers/cc-switch-import-bytes.ts +991 -0
  165. package/src/providers/cc-switch-import-source.ts +1083 -0
  166. package/src/providers/cc-switch-import.ts +942 -0
  167. package/src/providers/claude-cli-usage.ts +15 -67
  168. package/src/providers/derive.ts +6 -0
  169. package/src/providers/model-discovery-diagnostic.ts +4 -0
  170. package/src/providers/model-discovery.ts +4 -4
  171. package/src/providers/model-rename-fields.ts +2 -0
  172. package/src/providers/model-rename-migration.ts +41 -6
  173. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  174. package/src/providers/quota/anthropic-usage-windows.ts +55 -0
  175. package/src/providers/quota/report-cache.ts +17 -4
  176. package/src/providers/quota.ts +2 -2
  177. package/src/providers/reasoning-metadata.ts +31 -15
  178. package/src/providers/registry/entries-core.ts +1 -1
  179. package/src/providers/registry/entries-extended.ts +1 -1
  180. package/src/providers/registry/model-ids.ts +1 -0
  181. package/src/providers/registry/model-seeds.ts +2 -1
  182. package/src/providers/registry/types.ts +3 -1
  183. package/src/providers/resolved-model-policy.ts +2 -2
  184. package/src/providers/routed-config.ts +2 -0
  185. package/src/providers/stale-model-roster-migration.ts +5 -1
  186. package/src/providers/xai-transport.ts +4 -4
  187. package/src/remote-control/workspace-codex-runtime.ts +2 -2
  188. package/src/remote-control/workspace-executor.ts +14 -13
  189. package/src/responses/custom-tool-compat.ts +2 -1
  190. package/src/responses/item-provenance.ts +79 -0
  191. package/src/responses/namespace-tool-compat.ts +21 -3
  192. package/src/responses/parser-tools.ts +1 -0
  193. package/src/responses/schema.ts +5 -2
  194. package/src/router.ts +21 -2
  195. package/src/routing/analytics.ts +3 -5
  196. package/src/routing/fallback-policy.ts +7 -3
  197. package/src/routing/health.ts +5 -3
  198. package/src/routing/history/build-file.ts +6 -0
  199. package/src/routing/history/indexer.ts +158 -31
  200. package/src/routing/history/ingest.ts +1 -1
  201. package/src/routing/history/integrity.ts +208 -0
  202. package/src/routing/history/rebuild-job.ts +20 -6
  203. package/src/routing/history/rebuild-protocol.ts +2 -1
  204. package/src/routing/history/rebuild-worker.ts +18 -0
  205. package/src/routing/history/sqlite-errors.ts +9 -0
  206. package/src/server/admission-model-scope.ts +21 -4
  207. package/src/server/advisor-admission-scope.ts +29 -0
  208. package/src/server/audio-dictation.ts +3 -0
  209. package/src/server/audio-live.ts +8 -2
  210. package/src/server/audio-upstream.ts +2 -0
  211. package/src/server/auth-cors.ts +5 -2
  212. package/src/server/capture-admission-policy.ts +91 -0
  213. package/src/server/chat-completions.ts +33 -7
  214. package/src/server/claude-messages.ts +93 -2
  215. package/src/server/codex-model-list.ts +2 -1
  216. package/src/server/configured-credentials.ts +5 -0
  217. package/src/server/context-history.ts +9 -6
  218. package/src/server/images.ts +14 -5
  219. package/src/server/index/live-sideband.ts +16 -2
  220. package/src/server/index/serve-options.ts +13 -2
  221. package/src/server/index/websocket-handler.ts +4 -1
  222. package/src/server/live.ts +30 -5
  223. package/src/server/management/agent-settings-routes.ts +34 -9
  224. package/src/server/management/codex-agent-role-routes.ts +1 -0
  225. package/src/server/management/codex-role-auto-assign.ts +50 -6
  226. package/src/server/management/config-routes.ts +15 -4
  227. package/src/server/management/context.ts +3 -0
  228. package/src/server/management/native-integration-routes.ts +22 -0
  229. package/src/server/management/oauth-account-routes.ts +20 -4
  230. package/src/server/management/provider-overwrite-carry.ts +21 -0
  231. package/src/server/management/provider-routes.ts +3 -1
  232. package/src/server/management/route-registry.ts +2 -0
  233. package/src/server/management/shared.ts +17 -1
  234. package/src/server/management/workflow-budget-routes.ts +70 -3
  235. package/src/server/messages-native-eligibility.ts +6 -5
  236. package/src/server/messages-native-scope.ts +6 -1
  237. package/src/server/messages-shared.ts +57 -17
  238. package/src/server/persistent-gui-session.ts +4 -4
  239. package/src/server/request-log.ts +30 -2
  240. package/src/server/responses/adapter-delivery.ts +4 -0
  241. package/src/server/responses/adapter-dispatch.ts +5 -0
  242. package/src/server/responses/advisor-plan-slot.ts +4 -0
  243. package/src/server/responses/advisor-slot.ts +73 -46
  244. package/src/server/responses/codex-auth-error.ts +9 -1
  245. package/src/server/responses/combo-required-tool-contract.ts +39 -0
  246. package/src/server/responses/compact.ts +41 -20
  247. package/src/server/responses/core-codex-account.ts +17 -6
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +70 -5
  250. package/src/server/responses/core-lifetime.ts +4 -0
  251. package/src/server/responses/core-normalize.ts +7 -1
  252. package/src/server/responses/core-options.ts +9 -0
  253. package/src/server/responses/core.ts +2 -0
  254. package/src/server/responses/jev-model-invoke.ts +4 -2
  255. package/src/server/responses/passthrough-build-error.ts +36 -0
  256. package/src/server/responses/passthrough-dispatch.ts +10 -24
  257. package/src/server/responses/policy-fallback.ts +2 -0
  258. package/src/server/responses/request-prepare.ts +4 -5
  259. package/src/server/responses/request-send-budget.ts +2 -1
  260. package/src/server/responses/request-sidecar-auth.ts +4 -1
  261. package/src/server/responses/request-transport.ts +2 -3
  262. package/src/server/responses/run-turn-execution.ts +4 -0
  263. package/src/server/responses/sidecar-execution.ts +21 -5
  264. package/src/server/responses-snapshot-repair.ts +18 -4
  265. package/src/server/responses-undeclared-tool-guard.ts +4 -0
  266. package/src/server/search.ts +13 -4
  267. package/src/server/workflow-refusal.ts +2 -1
  268. package/src/server/ws-bridge.ts +5 -2
  269. package/src/service/state-lock.ts +12 -11
  270. package/src/service-manager-probe.ts +53 -8
  271. package/src/types/admission-policy.ts +13 -0
  272. package/src/types/config.ts +25 -0
  273. package/src/types/provider.ts +10 -0
  274. package/src/types/request.ts +7 -0
  275. package/src/types.ts +1 -0
  276. package/src/update/job.ts +20 -0
  277. package/src/update/worker-launch.ts +71 -1
  278. package/src/usage/log.ts +25 -4
  279. package/src/vision/describe.ts +4 -7
  280. package/src/vision/index.ts +2 -0
  281. package/src/vision/plan.ts +4 -0
  282. package/src/vision/routed-describe.ts +38 -23
  283. package/src/web-search/executor.ts +4 -7
  284. package/src/web-search/loop.ts +104 -9
  285. package/src/web-search/parse.ts +10 -2
  286. package/gui/dist/assets/App-DMps4OLk.css +0 -1
  287. package/gui/dist/assets/App-DmvwlhQq.js +0 -58
  288. package/gui/dist/assets/index-3EPO_KbX.js +0 -94
  289. package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
@@ -0,0 +1,942 @@
1
+ /**
2
+ * Keyless CC-Switch provider configuration importer (preview, selective apply, and journaled restore).
3
+ *
4
+ * Security & privacy boundary:
5
+ * - Structural non-secret projection: projects values ONLY from an explicit allowlist of non-secret
6
+ * metadata fields (id, app_type, baseUrl, wire adapter, defaultModel); source bytes are scanned
7
+ * transiently while secret fields, free-text names, and TOML comments are skipped at the byte
8
+ * level (never decoded into strings, written, or logged) and transient buffers are zeroed in finally.
9
+ * - Enforces a narrow URL path grammar and identifier/model syntax checks as defense in depth.
10
+ * - Source files are opened read-only with O_NOFOLLOW | O_NONBLOCK, descriptor-verified, and
11
+ * refused if an active SQLite -wal/-journal sidecar is non-empty.
12
+ * - Apply and restore run only while the proxy is stopped, under the service ownership lease and
13
+ * the shared config mutation lock, with a durable streaming journal for rollback.
14
+ */
15
+ import { createHash, randomUUID } from "node:crypto";
16
+ import {
17
+ closeSync,
18
+ constants,
19
+ fstatSync,
20
+ fsyncSync,
21
+ openSync,
22
+ readFileSync,
23
+ readSync,
24
+ unlinkSync,
25
+ writeFileSync,
26
+ } from "node:fs";
27
+ import { dirname, join } from "node:path";
28
+ import {
29
+ getConfigDir,
30
+ getConfigPath,
31
+ hasOwnProvider,
32
+ isValidProviderName,
33
+ mutatePersistedConfig,
34
+ readConfigDiagnostics,
35
+ validateConfigCandidate,
36
+ withConfigMutationLockSync,
37
+ } from "../config";
38
+ import { atomicWriteFileStreamed } from "../config/atomic-write";
39
+ import { readConfigFileSnapshot } from "../config/diagnostics";
40
+ import { withConfigDirHardeningSettled } from "../config/paths";
41
+ import { readAlivePid, readRuntimePort } from "../config/process-state";
42
+ import { providerBaseUrlConfigError } from "../config/provider-validation";
43
+ import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";
44
+ import { providerDestinationConfigError } from "../lib/destination-policy";
45
+ import { getAuthStorePath } from "../oauth/store";
46
+ import { rewriteProviderReferences } from "./provider-id-rewrite";
47
+ import { acquireOwnershipMutationLease } from "../service/ownership-mutation-lease.mjs";
48
+ import { serviceStatePaths } from "../service/state";
49
+ import type { OcxConfig, OcxProviderConfig } from "../types";
50
+ import {
51
+ CcSwitchImportError,
52
+ MAX_JSON_BYTES,
53
+ METADATA_REFUSED_SENTINEL,
54
+ URL_SYNTAX_REFUSED_SENTINEL,
55
+ equalsAsciiBytes,
56
+ isAllowedMetadataBytes,
57
+ isDisallowedMetadataValue,
58
+ parseCodexTomlBytes,
59
+ readSourceRows,
60
+ readSqliteRows,
61
+ resolveCodexProjection,
62
+ scanCcSwitchJsonBytes,
63
+ setCcSwitchSourceOpenHookForTests,
64
+ unescapeJsonStringBytesBounded,
65
+ validateJsonPrimitiveBytes,
66
+ validateUtf8AndJsonStringBounds,
67
+ type CcSwitchInvalidReason,
68
+ type CodexTomlProjection,
69
+ type MetadataFieldKind,
70
+ type RawExtractedRow,
71
+ } from "./cc-switch-import-source";
72
+
73
+ export {
74
+ CcSwitchImportError,
75
+ METADATA_REFUSED_SENTINEL,
76
+ URL_SYNTAX_REFUSED_SENTINEL,
77
+ isAllowedMetadataBytes,
78
+ parseCodexTomlBytes,
79
+ readSqliteRows,
80
+ scanCcSwitchJsonBytes,
81
+ setCcSwitchSourceOpenHookForTests,
82
+ type CcSwitchInvalidReason,
83
+ type CodexTomlProjection,
84
+ type MetadataFieldKind,
85
+ };
86
+
87
+ export interface CcSwitchCandidateProvider {
88
+ name: string;
89
+ sourceId: string;
90
+ appType: string;
91
+ adapter: string;
92
+ baseUrl: string;
93
+ defaultModel?: string;
94
+ allowPrivateNetwork?: boolean;
95
+ }
96
+
97
+ export interface CcSwitchImportPreviewOrApplyResult {
98
+ mode: "preview" | "apply";
99
+ discovered: number;
100
+ eligible: number;
101
+ imported: number;
102
+ conflicts: number;
103
+ conflictNames: string[];
104
+ invalid: number;
105
+ invalidReasons: Partial<Record<CcSwitchInvalidReason, number>>;
106
+ providers: CcSwitchCandidateProvider[];
107
+ }
108
+
109
+ export interface CcSwitchImportRestoreResult {
110
+ mode: "restore";
111
+ restored: number;
112
+ restoredNames: string[];
113
+ alreadyAbsent: number;
114
+ retainedEdited: number;
115
+ retainedNames: string[];
116
+ }
117
+
118
+ export type CcSwitchImportResult = CcSwitchImportPreviewOrApplyResult | CcSwitchImportRestoreResult;
119
+
120
+ export const CC_SWITCH_IMPORT_JOURNAL_FILENAME = "cc-switch-provider-import-journal.json";
121
+ const JOURNAL_SCHEMA_VERSION = 1;
122
+
123
+ interface JournalEntry {
124
+ name: string;
125
+ sourceId: string;
126
+ appType: string;
127
+ note: string;
128
+ fingerprint: string;
129
+ }
130
+
131
+ interface ImportJournal {
132
+ schemaVersion: 1;
133
+ state: "prepared" | "committed";
134
+ importId: string;
135
+ createdAt: number;
136
+ entries: JournalEntry[];
137
+ }
138
+
139
+ function normalizeProviderSlug(raw: string): string {
140
+ return raw
141
+ .trim()
142
+ .toLowerCase()
143
+ .replace(/[^a-z0-9._-]+/g, "-")
144
+ .replace(/^-+|-+$/g, "");
145
+ }
146
+
147
+ function canonicalProviderJson(provider: OcxProviderConfig): string {
148
+ const keys = Object.keys(provider).sort();
149
+ const ordered: Record<string, unknown> = {};
150
+ for (const key of keys) {
151
+ const val = (provider as unknown as Record<string, unknown>)[key];
152
+ if (val !== undefined) ordered[key] = val;
153
+ }
154
+ return JSON.stringify(ordered);
155
+ }
156
+
157
+ export function canonicalProviderFingerprint(provider: OcxProviderConfig): string {
158
+ return createHash("sha256").update(canonicalProviderJson(provider), "utf8").digest("hex");
159
+ }
160
+
161
+ function syncDirectoryBestEffort(dirPath: string): void {
162
+ if (process.platform === "win32") return;
163
+ let fd: number | undefined;
164
+ try {
165
+ fd = openSync(dirPath, "r");
166
+ fsyncSync(fd);
167
+ } catch {
168
+ // Best-effort directory sync after unlink on POSIX.
169
+ } finally {
170
+ if (fd !== undefined) {
171
+ try { closeSync(fd); } catch { /* ignore */ }
172
+ }
173
+ }
174
+ }
175
+
176
+ function writeJournalDurably(journalPath: string, journal: ImportJournal): void {
177
+ const bytes = Buffer.from(JSON.stringify(journal, null, 2) + "\n", "utf8");
178
+ atomicWriteFileStreamed(journalPath, (fd: number) => {
179
+ writeFileSync(fd, bytes);
180
+ });
181
+ }
182
+
183
+ function unlinkJournalDurably(journalPath: string): void {
184
+ try {
185
+ unlinkSync(journalPath);
186
+ } catch (error) {
187
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
188
+ }
189
+ syncDirectoryBestEffort(dirname(journalPath));
190
+ }
191
+
192
+ function readJournal(journalPath: string): ImportJournal | null {
193
+ let raw: string;
194
+ try {
195
+ raw = readFileSync(journalPath, "utf8");
196
+ } catch (error) {
197
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
198
+ throw new CcSwitchImportError("Existing CC-Switch import journal is unreadable; inspect or restore before importing.");
199
+ }
200
+ let parsed: unknown;
201
+ try {
202
+ parsed = JSON.parse(raw);
203
+ } catch {
204
+ throw new CcSwitchImportError("Existing CC-Switch import journal is corrupt; inspect or restore before importing.");
205
+ }
206
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
207
+ throw new CcSwitchImportError("Existing CC-Switch import journal is corrupt; inspect or restore before importing.");
208
+ }
209
+ const obj = parsed as Record<string, unknown>;
210
+ if (
211
+ obj.schemaVersion !== JOURNAL_SCHEMA_VERSION
212
+ || (obj.state !== "prepared" && obj.state !== "committed")
213
+ || typeof obj.importId !== "string"
214
+ || !obj.importId.trim()
215
+ || typeof obj.createdAt !== "number"
216
+ || !Array.isArray(obj.entries)
217
+ || obj.entries.length === 0
218
+ ) {
219
+ throw new CcSwitchImportError("Existing CC-Switch import journal is corrupt; inspect or restore before importing.");
220
+ }
221
+ const entries: JournalEntry[] = [];
222
+ const seenNames = new Set<string>();
223
+ for (const item of obj.entries) {
224
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
225
+ throw new CcSwitchImportError("Existing CC-Switch import journal is corrupt; inspect or restore before importing.");
226
+ }
227
+ const rec = item as Record<string, unknown>;
228
+ if (
229
+ typeof rec.name !== "string" || !isValidProviderName(rec.name)
230
+ || typeof rec.sourceId !== "string" || !rec.sourceId
231
+ || typeof rec.appType !== "string" || !rec.appType
232
+ || typeof rec.note !== "string" || !rec.note.startsWith(`imported:cc-switch:${obj.importId}:`)
233
+ || typeof rec.fingerprint !== "string" || !/^[0-9a-f]{64}$/.test(rec.fingerprint)
234
+ || seenNames.has(rec.name)
235
+ ) {
236
+ throw new CcSwitchImportError("Existing CC-Switch import journal is corrupt; inspect or restore before importing.");
237
+ }
238
+ seenNames.add(rec.name);
239
+ entries.push({
240
+ name: rec.name,
241
+ sourceId: rec.sourceId,
242
+ appType: rec.appType,
243
+ note: rec.note,
244
+ fingerprint: rec.fingerprint,
245
+ });
246
+ }
247
+ return {
248
+ schemaVersion: 1,
249
+ state: obj.state,
250
+ importId: obj.importId,
251
+ createdAt: obj.createdAt,
252
+ entries,
253
+ };
254
+ }
255
+
256
+ function evaluateExtractedRow(
257
+ row: RawExtractedRow,
258
+ targetName: string,
259
+ allowPrivateNetwork: boolean,
260
+ ): { ok: true; candidate: CcSwitchCandidateProvider } | { ok: false; reason: CcSwitchInvalidReason } {
261
+ const sourceId = (row.id ?? "").trim();
262
+ const appType = (row.appType || "").trim().toLowerCase();
263
+ if (!sourceId) return { ok: false, reason: "malformed_entry" };
264
+ if (isDisallowedMetadataValue(sourceId, "id") || (appType !== "" && isDisallowedMetadataValue(appType, "app"))) {
265
+ return { ok: false, reason: "disallowed_metadata" };
266
+ }
267
+ if (!isValidProviderName(targetName)) return { ok: false, reason: "invalid_provider_name" };
268
+ if (row.settingsType !== "object") return { ok: false, reason: "malformed_entry" };
269
+
270
+ let adapter: string;
271
+ let baseUrl: string | undefined;
272
+ let defaultModel: string | undefined;
273
+
274
+ if (appType === "claude") {
275
+ adapter = "anthropic";
276
+ baseUrl = (row.claudeBaseUrl ?? row.genericBaseUrl ?? "").trim() || undefined;
277
+ defaultModel = (row.claudeModel ?? row.genericModel ?? "").trim() || undefined;
278
+ } else if (appType === "codex") {
279
+ if (row.codexProjection !== undefined) {
280
+ if (!row.codexProjection.ok) return row.codexProjection;
281
+ const resolved = resolveCodexProjection(row.codexProjection.value);
282
+ if (!resolved.ok) return resolved;
283
+ baseUrl = resolved.baseUrl.trim();
284
+ defaultModel = resolved.defaultModel?.trim() || (row.genericModel ?? "").trim() || undefined;
285
+ const wire = resolved.wireApi.trim().toLowerCase();
286
+ if (wire === METADATA_REFUSED_SENTINEL.toLowerCase()) return { ok: false, reason: "disallowed_metadata" };
287
+ if (wire === "responses" || wire === "openai-responses") adapter = "openai-responses";
288
+ else if (wire === "chat" || wire === "chat_completions" || wire === "openai-completions" || wire === "openai-chat") adapter = "openai-chat";
289
+ else return { ok: false, reason: "malformed_entry" };
290
+ } else if (row.codexTomlLines !== null) {
291
+ const encoder = new TextEncoder();
292
+ const tomlBytes = encoder.encode(row.codexTomlLines);
293
+ try {
294
+ const parsed = parseCodexTomlBytes(tomlBytes);
295
+ if (!parsed.ok) return parsed;
296
+ const resolved = resolveCodexProjection(parsed.value);
297
+ if (!resolved.ok) return resolved;
298
+ baseUrl = resolved.baseUrl.trim();
299
+ defaultModel = resolved.defaultModel?.trim() || (row.genericModel ?? "").trim() || undefined;
300
+ const wire = resolved.wireApi.trim().toLowerCase();
301
+ if (wire === METADATA_REFUSED_SENTINEL.toLowerCase()) return { ok: false, reason: "disallowed_metadata" };
302
+ if (wire === "responses" || wire === "openai-responses") adapter = "openai-responses";
303
+ else if (wire === "chat" || wire === "chat_completions" || wire === "openai-completions" || wire === "openai-chat") adapter = "openai-chat";
304
+ else return { ok: false, reason: "malformed_entry" };
305
+ } finally {
306
+ tomlBytes.fill(0);
307
+ }
308
+ } else if (row.genericBaseUrl) {
309
+ baseUrl = row.genericBaseUrl.trim();
310
+ defaultModel = (row.genericModel ?? "").trim() || undefined;
311
+ const wire = (row.genericWireApi ?? "responses").trim().toLowerCase();
312
+ if (wire === METADATA_REFUSED_SENTINEL.toLowerCase()) return { ok: false, reason: "disallowed_metadata" };
313
+ if (wire === "responses" || wire === "openai-responses") adapter = "openai-responses";
314
+ else if (wire === "chat" || wire === "chat_completions" || wire === "openai-completions" || wire === "openai-chat") adapter = "openai-chat";
315
+ else return { ok: false, reason: "malformed_entry" };
316
+ } else {
317
+ return { ok: false, reason: "missing_base_url" };
318
+ }
319
+ } else if (appType === "openai" || appType === "opencode") {
320
+ adapter = "openai-chat";
321
+ baseUrl = (row.genericBaseUrl ?? "").trim() || undefined;
322
+ defaultModel = (row.genericModel ?? "").trim() || undefined;
323
+ } else if (appType === "gemini") {
324
+ adapter = "google";
325
+ baseUrl = (row.genericBaseUrl ?? "").trim() || undefined;
326
+ defaultModel = (row.genericModel ?? "").trim() || undefined;
327
+ } else {
328
+ return { ok: false, reason: "unsupported_app_type" };
329
+ }
330
+
331
+ if (!baseUrl) return { ok: false, reason: "missing_base_url" };
332
+ if (defaultModel !== undefined && isDisallowedMetadataValue(defaultModel, "model")) {
333
+ return { ok: false, reason: "disallowed_metadata" };
334
+ }
335
+ if (baseUrl === URL_SYNTAX_REFUSED_SENTINEL || isDisallowedMetadataValue(baseUrl, "url")) {
336
+ return { ok: false, reason: "invalid_base_url" };
337
+ }
338
+ if (providerBaseUrlConfigError(baseUrl) !== null) {
339
+ return { ok: false, reason: "invalid_base_url" };
340
+ }
341
+ // Classify against a synthetic non-registry name so local registry names (like "ollama")
342
+ // still require explicit --allow-private-network opt-in when imported from CC-Switch.
343
+ const strictDestErr = providerDestinationConfigError("__cc_switch_imported__", { baseUrl, allowPrivateNetwork: false });
344
+ if (strictDestErr !== null) {
345
+ const permissiveDestErr = providerDestinationConfigError("__cc_switch_imported__", { baseUrl, allowPrivateNetwork: true });
346
+ if (permissiveDestErr !== null || providerDestinationConfigError(targetName, { baseUrl, allowPrivateNetwork: true }) !== null) {
347
+ return { ok: false, reason: "invalid_base_url" };
348
+ }
349
+ if (!allowPrivateNetwork) {
350
+ return { ok: false, reason: "private_network_refused" };
351
+ }
352
+ return {
353
+ ok: true,
354
+ candidate: {
355
+ name: targetName,
356
+ sourceId,
357
+ appType,
358
+ adapter,
359
+ baseUrl,
360
+ ...(defaultModel ? { defaultModel } : {}),
361
+ allowPrivateNetwork: true,
362
+ },
363
+ };
364
+ }
365
+
366
+ return {
367
+ ok: true,
368
+ candidate: {
369
+ name: targetName,
370
+ sourceId,
371
+ appType,
372
+ adapter,
373
+ baseUrl,
374
+ ...(defaultModel ? { defaultModel } : {}),
375
+ },
376
+ };
377
+ }
378
+
379
+ function buildImportedProviderConfig(candidate: CcSwitchCandidateProvider, importId: string): OcxProviderConfig {
380
+ return {
381
+ adapter: candidate.adapter,
382
+ baseUrl: candidate.baseUrl,
383
+ ...(candidate.defaultModel ? { defaultModel: candidate.defaultModel } : {}),
384
+ ...(candidate.allowPrivateNetwork ? { allowPrivateNetwork: true } : {}),
385
+ note: `imported:cc-switch:${importId}:${candidate.sourceId}:${candidate.appType}`,
386
+ };
387
+ }
388
+
389
+ function assertStopped(): void {
390
+ let running = readAlivePid() !== null;
391
+ const runtime = readRuntimePort();
392
+ if (runtime) {
393
+ try {
394
+ process.kill(runtime.pid, 0);
395
+ running = true;
396
+ } catch (error) {
397
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") running = true;
398
+ }
399
+ }
400
+ if (running) {
401
+ throw new CcSwitchImportError("Stop the opencodex proxy before applying or restoring a CC-Switch provider import.");
402
+ }
403
+ }
404
+
405
+ /**
406
+ * Read-only byte-level inspection of ~/.opencodex/auth.json to determine whether `name` has stored
407
+ * OAuth accounts (or whether auth.json is unreadable/malformed) without decoding any OAuth tokens.
408
+ */
409
+ export function hasOrCannotVerifyOAuthAccounts(name: string): boolean {
410
+ const authPath = getAuthStorePath();
411
+ const nameBytes = Buffer.from(name, "utf8");
412
+ let fd: number | undefined;
413
+ let buf: Buffer | undefined;
414
+ try {
415
+ try {
416
+ fd = openSync(
417
+ authPath,
418
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0),
419
+ );
420
+ const st = fstatSync(fd);
421
+ if (!st.isFile() || st.size > MAX_JSON_BYTES) return true;
422
+ if (st.size === 0) return true;
423
+ buf = Buffer.alloc(st.size);
424
+ let off = 0;
425
+ while (off < st.size) {
426
+ const got = readSync(fd, buf, off, st.size - off, off);
427
+ if (got <= 0) break;
428
+ off += got;
429
+ }
430
+ if (off !== st.size) return true;
431
+ } catch (error) {
432
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
433
+ return true;
434
+ } finally {
435
+ if (fd !== undefined) {
436
+ try { closeSync(fd); } catch { /* ignore */ }
437
+ }
438
+ }
439
+ const bytes = buf!;
440
+ let pos = 0;
441
+ if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) pos = 3;
442
+ const skipWs = () => {
443
+ while (pos < bytes.length && (bytes[pos] === 0x20 || bytes[pos] === 0x09 || bytes[pos] === 0x0a || bytes[pos] === 0x0d)) pos++;
444
+ };
445
+ const scanStr = (): { start: number; end: number; hasEsc: boolean } => {
446
+ const res = validateUtf8AndJsonStringBounds(bytes, pos);
447
+ if (!res) throw new Error("malformed");
448
+ pos = res.nextPos;
449
+ return { start: res.start, end: res.end, hasEsc: res.hasEscapes };
450
+ };
451
+ const keyEqualsBytes = (b: { start: number; end: number; hasEsc: boolean }, target: Uint8Array): boolean => {
452
+ if (!b.hasEsc) {
453
+ const raw = bytes.subarray(b.start, b.end);
454
+ if (raw.length !== target.length) return false;
455
+ for (let i = 0; i < raw.length; i++) if (raw[i] !== target[i]) return false;
456
+ return true;
457
+ }
458
+ const unesc = unescapeJsonStringBytesBounded(bytes, { start: b.start, end: b.end, hasEscapes: true }, 128);
459
+ if (!unesc) throw new Error("malformed");
460
+ try {
461
+ if (unesc.length !== target.length) return false;
462
+ for (let i = 0; i < unesc.length; i++) if (unesc[i] !== target[i]) return false;
463
+ return true;
464
+ } finally {
465
+ unesc.fill(0);
466
+ }
467
+ };
468
+ const keyEqualsAscii = (b: { start: number; end: number; hasEsc: boolean }, target: string): boolean => {
469
+ if (!b.hasEsc) return equalsAsciiBytes(bytes.subarray(b.start, b.end), target);
470
+ const unesc = unescapeJsonStringBytesBounded(bytes, { start: b.start, end: b.end, hasEscapes: true }, 128);
471
+ if (!unesc) throw new Error("malformed");
472
+ try {
473
+ return equalsAsciiBytes(unesc, target);
474
+ } finally {
475
+ unesc.fill(0);
476
+ }
477
+ };
478
+ const skipPrim = () => {
479
+ const s = pos;
480
+ while (pos < bytes.length && ![0x20, 0x09, 0x0a, 0x0d, 0x2c, 0x7d, 0x5d].includes(bytes[pos]!)) pos++;
481
+ if (!validateJsonPrimitiveBytes(bytes, s, pos)) {
482
+ throw new Error("malformed");
483
+ }
484
+ };
485
+ const skipVal = (depth = 0): void => {
486
+ if (depth > 32) throw new Error("malformed");
487
+ skipWs();
488
+ const b = bytes[pos];
489
+ if (b === 0x22) { scanStr(); return; }
490
+ if (b === 0x7b) {
491
+ pos++; skipWs();
492
+ if (bytes[pos] === 0x7d) { pos++; return; }
493
+ for (;;) {
494
+ skipWs(); scanStr(); skipWs();
495
+ if (bytes[pos] !== 0x3a) throw new Error("malformed");
496
+ pos++; skipVal(depth + 1); skipWs();
497
+ if (bytes[pos] === 0x2c) { pos++; continue; }
498
+ if (bytes[pos] === 0x7d) { pos++; return; }
499
+ throw new Error("malformed");
500
+ }
501
+ }
502
+ if (b === 0x5b) {
503
+ pos++; skipWs();
504
+ if (bytes[pos] === 0x5d) { pos++; return; }
505
+ for (;;) {
506
+ skipVal(depth + 1); skipWs();
507
+ if (bytes[pos] === 0x2c) { pos++; continue; }
508
+ if (bytes[pos] === 0x5d) { pos++; return; }
509
+ throw new Error("malformed");
510
+ }
511
+ }
512
+ skipPrim();
513
+ };
514
+ skipWs();
515
+ if (bytes[pos] !== 0x7b) return true;
516
+ pos++; skipWs();
517
+ let foundAccounts = false;
518
+ if (bytes[pos] === 0x7d) {
519
+ pos++;
520
+ } else {
521
+ for (;;) {
522
+ skipWs();
523
+ const provKeyBounds = scanStr();
524
+ skipWs();
525
+ if (bytes[pos] !== 0x3a) return true;
526
+ pos++; skipWs();
527
+ if (!keyEqualsBytes(provKeyBounds, nameBytes)) {
528
+ skipVal();
529
+ } else {
530
+ // Inspect the provider entry without decoding any token strings.
531
+ if (bytes[pos] !== 0x7b) return true;
532
+ pos++; skipWs();
533
+ if (bytes[pos] === 0x7d) { pos++; }
534
+ else {
535
+ let sawAccountsArray = false;
536
+ for (;;) {
537
+ skipWs();
538
+ const fieldKeyBounds = scanStr();
539
+ skipWs();
540
+ if (bytes[pos] !== 0x3a) return true;
541
+ pos++; skipWs();
542
+ if (keyEqualsAscii(fieldKeyBounds, "accounts")) {
543
+ if (bytes[pos] !== 0x5b) return true;
544
+ sawAccountsArray = true;
545
+ pos++; skipWs();
546
+ if (bytes[pos] === 0x5d) {
547
+ pos++;
548
+ } else {
549
+ foundAccounts = true;
550
+ for (;;) {
551
+ skipVal(1); skipWs();
552
+ if (bytes[pos] === 0x2c) { pos++; continue; }
553
+ if (bytes[pos] === 0x5d) { pos++; break; }
554
+ return true;
555
+ }
556
+ }
557
+ } else if (keyEqualsAscii(fieldKeyBounds, "activeAccountId") || keyEqualsAscii(fieldKeyBounds, "selectionRevision")) {
558
+ skipVal(1);
559
+ } else {
560
+ // Legacy single-credential shape or unknown field -> retain provider.
561
+ foundAccounts = true;
562
+ skipVal(1);
563
+ }
564
+ skipWs();
565
+ if (bytes[pos] === 0x2c) { pos++; continue; }
566
+ if (bytes[pos] === 0x7d) { pos++; break; }
567
+ return true;
568
+ }
569
+ if (!sawAccountsArray) foundAccounts = true;
570
+ }
571
+ }
572
+ skipWs();
573
+ if (bytes[pos] === 0x2c) { pos++; continue; }
574
+ if (bytes[pos] === 0x7d) { pos++; break; }
575
+ return true;
576
+ }
577
+ }
578
+ skipWs();
579
+ if (pos !== bytes.length) return true;
580
+ return foundAccounts;
581
+ } catch {
582
+ return true;
583
+ } finally {
584
+ nameBytes.fill(0);
585
+ buf?.fill(0);
586
+ }
587
+ }
588
+
589
+ /**
590
+ * Exhaustive check that no setting in OcxConfig references the given provider name before
591
+ * --restore deletes it. Runs inside the mutatePersistedConfig callback on every rebase attempt.
592
+ */
593
+ export function isProviderReferencedInConfig(config: OcxConfig, name: string): boolean {
594
+ if (config.defaultProvider === name) return true;
595
+ if (Object.keys(config.providers ?? {}).length <= 1) return true;
596
+ if (hasOrCannotVerifyOAuthAccounts(name)) return true;
597
+ const prefix = `${name}/`;
598
+ const rewriteProbe = rewriteProviderReferences(structuredClone(config), name, "__cc_switch_probe__");
599
+ if (rewriteProbe.changed > 0 || rewriteProbe.collisions.length > 0) return true;
600
+
601
+ if (config.fallback?.providers && Object.hasOwn(config.fallback.providers, name)) return true;
602
+ if (config.fallback?.routes && Object.keys(config.fallback.routes).some(k => k === name || k.startsWith(prefix))) return true;
603
+
604
+ const startsWithPrefix = (v: unknown): boolean => typeof v === "string" && v.trim().startsWith(prefix);
605
+ if (startsWithPrefix(config.claudeCode?.classifierModel)) return true;
606
+ if ((config.claudeCode?.classifierFallbacks ?? []).some(startsWithPrefix)) return true;
607
+ if (config.subagentModelFallbackByModel) {
608
+ for (const [k, list] of Object.entries(config.subagentModelFallbackByModel)) {
609
+ if (k.startsWith(prefix) || (Array.isArray(list) && list.some(startsWithPrefix))) return true;
610
+ }
611
+ }
612
+ for (const tierList of [config.codexRoleTiers?.fast, config.codexRoleTiers?.standard, config.codexRoleTiers?.frontier]) {
613
+ if ((tierList ?? []).some(startsWithPrefix)) return true;
614
+ }
615
+ if ((config.modelPickerOrder ?? []).some(startsWithPrefix)) return true;
616
+ if (config.modelPinnedEfforts && Object.keys(config.modelPinnedEfforts).some(k => k.startsWith(prefix))) return true;
617
+ if (startsWithPrefix(config.compactionRouting?.model)) return true;
618
+ if ((config.compactionRouting?.sourceModels ?? []).some(startsWithPrefix)) return true;
619
+ if (startsWithPrefix(config.compactionRecovery?.model)) return true;
620
+ if (startsWithPrefix(config.memoryModels?.extract?.model) || startsWithPrefix(config.memoryModels?.consolidation?.model)) return true;
621
+ if (startsWithPrefix(config.autoReviewOverride?.model)) return true;
622
+ if (startsWithPrefix(config.codexMainAccountHardLockFallback?.model)) return true;
623
+ if (startsWithPrefix(config.agentTaskRecovery?.model)) return true;
624
+ if (startsWithPrefix(config.advisor?.model)) return true;
625
+ if (config.blockedModelRedirects) {
626
+ for (const [k, v] of Object.entries(config.blockedModelRedirects)) {
627
+ if (k.startsWith(prefix) || startsWithPrefix(v)) return true;
628
+ }
629
+ }
630
+ for (const keyEntry of config.apiKeys ?? []) {
631
+ if ((keyEntry.allowedProviders ?? []).includes(name)) return true;
632
+ if ((keyEntry.allowedModels ?? []).some(startsWithPrefix)) return true;
633
+ }
634
+ if (config.spendPoolAliases && Object.values(config.spendPoolAliases).some(v => v === name)) return true;
635
+ for (const group of config.pool?.credentialGroups ?? []) {
636
+ if ((group.credentials ?? []).some(c => typeof c === "string" && c.toLowerCase().startsWith(`${name.toLowerCase()}:`))) {
637
+ return true;
638
+ }
639
+ }
640
+ return false;
641
+ }
642
+
643
+ function requireValidPersistedConfig(): OcxConfig {
644
+ const diag = readConfigDiagnostics();
645
+ if (diag.source !== "file" || diag.error !== null) {
646
+ throw new CcSwitchImportError("Initialize a valid opencodex configuration before importing or restoring providers.");
647
+ }
648
+ return diag.config;
649
+ }
650
+
651
+ function assignTargetNames(rows: RawExtractedRow[]): string[] {
652
+ const slugCounts = new Map<string, number>();
653
+ const rawSlugs = rows.map(r => normalizeProviderSlug(r.id));
654
+ for (const s of rawSlugs) {
655
+ slugCounts.set(s, (slugCounts.get(s) ?? 0) + 1);
656
+ }
657
+ const used = new Set<string>();
658
+ return rows.map((r, i) => {
659
+ const base = rawSlugs[i]!;
660
+ const appSlug = normalizeProviderSlug(r.appType);
661
+ let candidate = (slugCounts.get(base) ?? 0) > 1 && appSlug ? `${base}-${appSlug}` : base;
662
+ if (used.has(candidate)) {
663
+ let suffix = 2;
664
+ while (used.has(`${candidate}-${suffix}`)) suffix++;
665
+ candidate = `${candidate}-${suffix}`;
666
+ }
667
+ used.add(candidate);
668
+ return candidate;
669
+ });
670
+ }
671
+
672
+ function prepareCandidates(options: {
673
+ sourcePath: string;
674
+ selectedProviders?: readonly string[];
675
+ allowPrivateNetwork?: boolean;
676
+ config: OcxConfig;
677
+ }): CcSwitchImportPreviewOrApplyResult {
678
+ const rows = readSourceRows(options.sourcePath);
679
+ const targetNames = assignTargetNames(rows);
680
+ const filterSet = options.selectedProviders && options.selectedProviders.length > 0
681
+ ? new Set(options.selectedProviders.map(s => s.trim()).filter(Boolean))
682
+ : null;
683
+
684
+ if (filterSet) {
685
+ for (const wanted of filterSet) {
686
+ const matchesAny = rows.some((r, idx) => r.id === wanted || targetNames[idx] === wanted);
687
+ if (!matchesAny) {
688
+ throw new CcSwitchImportError("CC-Switch source does not contain one or more requested --provider IDs.");
689
+ }
690
+ }
691
+ }
692
+
693
+ const result: CcSwitchImportPreviewOrApplyResult = {
694
+ mode: "preview",
695
+ discovered: 0,
696
+ eligible: 0,
697
+ imported: 0,
698
+ conflicts: 0,
699
+ conflictNames: [],
700
+ invalid: 0,
701
+ invalidReasons: {},
702
+ providers: [],
703
+ };
704
+
705
+ rows.forEach((row, idx) => {
706
+ const targetName = targetNames[idx]!;
707
+ if (filterSet && !filterSet.has(row.id) && !filterSet.has(targetName)) return;
708
+ result.discovered++;
709
+ const evaluated = evaluateExtractedRow(row, targetName, options.allowPrivateNetwork === true);
710
+ if (!evaluated.ok) {
711
+ result.invalid++;
712
+ result.invalidReasons[evaluated.reason] = (result.invalidReasons[evaluated.reason] ?? 0) + 1;
713
+ return;
714
+ }
715
+ const { candidate } = evaluated;
716
+ if (
717
+ hasOwnProvider(options.config.providers, candidate.name)
718
+ || Boolean(codexAccountNamespaceProviderCollisionError(options.config.codexAccountNamespaces, candidate.name))
719
+ ) {
720
+ result.conflicts++;
721
+ result.conflictNames.push(candidate.name);
722
+ return;
723
+ }
724
+ result.eligible++;
725
+ result.providers.push(candidate);
726
+ });
727
+
728
+ return result;
729
+ }
730
+
731
+ function reconcileJournalForApply(config: OcxConfig, journalPath: string): void {
732
+ const existing = readJournal(journalPath);
733
+ if (!existing) return;
734
+ const anyPublished = existing.entries.some(e => {
735
+ const current = config.providers?.[e.name];
736
+ return current !== undefined && current.note === e.note;
737
+ });
738
+ if (existing.state === "committed" || anyPublished) {
739
+ throw new CcSwitchImportError(
740
+ "An active CC-Switch import journal already exists; run 'ocx provider import-cc-switch --restore' before applying another import.",
741
+ );
742
+ }
743
+ // Stale prepared journal where zero entries carry this journal's importId note.
744
+ unlinkJournalDurably(journalPath);
745
+ }
746
+
747
+ export async function runCcSwitchProviderImport(options: {
748
+ mode: "preview" | "apply" | "restore";
749
+ sourcePath?: string;
750
+ selectedProviders?: readonly string[];
751
+ allowPrivateNetwork?: boolean;
752
+ onBeforeApplyWrite?: (providers: readonly CcSwitchCandidateProvider[]) => void;
753
+ }): Promise<CcSwitchImportResult> {
754
+ if (options.mode === "preview") {
755
+ if (!options.sourcePath) throw new CcSwitchImportError("--source is required for preview and apply.");
756
+ const config = requireValidPersistedConfig();
757
+ return prepareCandidates({
758
+ sourcePath: options.sourcePath,
759
+ selectedProviders: options.selectedProviders,
760
+ allowPrivateNetwork: options.allowPrivateNetwork,
761
+ config,
762
+ });
763
+ }
764
+
765
+ assertStopped();
766
+ return await withConfigDirHardeningSettled(getConfigDir(), () => {
767
+ const lease = acquireOwnershipMutationLease(serviceStatePaths());
768
+ try {
769
+ assertStopped();
770
+ return withConfigMutationLockSync(() => {
771
+ assertStopped();
772
+ const journalPath = join(getConfigDir(), CC_SWITCH_IMPORT_JOURNAL_FILENAME);
773
+
774
+ if (options.mode === "apply") {
775
+ if (!options.sourcePath) throw new CcSwitchImportError("--source is required for preview and apply.");
776
+ const initialConfig = requireValidPersistedConfig();
777
+ reconcileJournalForApply(initialConfig, journalPath);
778
+
779
+ const prepared = prepareCandidates({
780
+ sourcePath: options.sourcePath,
781
+ selectedProviders: options.selectedProviders,
782
+ allowPrivateNetwork: options.allowPrivateNetwork,
783
+ config: initialConfig,
784
+ });
785
+ prepared.mode = "apply";
786
+ if (prepared.providers.length === 0) return prepared;
787
+ options.onBeforeApplyWrite?.(prepared.providers);
788
+
789
+ const importId = randomUUID();
790
+ const builtEntries = prepared.providers.map(candidate => {
791
+ const providerConfig = buildImportedProviderConfig(candidate, importId);
792
+ const fingerprint = canonicalProviderFingerprint(providerConfig);
793
+ return {
794
+ candidate,
795
+ providerConfig,
796
+ journalEntry: {
797
+ name: candidate.name,
798
+ sourceId: candidate.sourceId,
799
+ appType: candidate.appType,
800
+ note: providerConfig.note!,
801
+ fingerprint,
802
+ },
803
+ };
804
+ });
805
+
806
+ const journal: ImportJournal = {
807
+ schemaVersion: 1,
808
+ state: "prepared",
809
+ importId,
810
+ createdAt: Date.now(),
811
+ entries: builtEntries.map(b => b.journalEntry),
812
+ };
813
+ writeJournalDurably(journalPath, journal);
814
+
815
+ try {
816
+ const outcome = mutatePersistedConfig(config => {
817
+ assertStopped();
818
+ for (const { candidate, providerConfig } of builtEntries) {
819
+ if (
820
+ hasOwnProvider(config.providers, candidate.name)
821
+ || Boolean(codexAccountNamespaceProviderCollisionError(config.codexAccountNamespaces, candidate.name))
822
+ ) {
823
+ throw new CcSwitchImportError("Target configuration changed and now conflicts with imported provider names; retry.");
824
+ }
825
+ config.providers[candidate.name] = structuredClone(providerConfig);
826
+ }
827
+ const validation = validateConfigCandidate(config);
828
+ if (!validation.ok) {
829
+ throw new CcSwitchImportError("CC-Switch imported provider configuration failed schema validation.");
830
+ }
831
+ return { changed: true, value: builtEntries.length };
832
+ });
833
+ if (outcome.status !== "committed") {
834
+ throw new CcSwitchImportError("Target configuration could not be committed.");
835
+ }
836
+ writeJournalDurably(journalPath, { ...journal, state: "committed" });
837
+ prepared.imported = builtEntries.length;
838
+ return prepared;
839
+ } catch (error) {
840
+ // Never blindly unlink the prepared journal if the config write actually published!
841
+ const snap = readConfigFileSnapshot();
842
+ if (snap.diagnostics.source === "file" && snap.diagnostics.error === null) {
843
+ const landed = journal.entries.filter(e => snap.diagnostics.config.providers?.[e.name]?.note === e.note);
844
+ if (landed.length === 0) {
845
+ unlinkJournalDurably(journalPath);
846
+ } else {
847
+ writeJournalDurably(journalPath, { ...journal, state: "committed", entries: landed });
848
+ }
849
+ }
850
+ if (error instanceof CcSwitchImportError) throw error;
851
+ throw new CcSwitchImportError("CC-Switch provider import could not be committed.");
852
+ }
853
+ }
854
+
855
+ // mode === "restore"
856
+ requireValidPersistedConfig();
857
+ const journal = readJournal(journalPath);
858
+ if (!journal) {
859
+ throw new CcSwitchImportError("No CC-Switch provider import journal found to restore.");
860
+ }
861
+
862
+ try {
863
+ const outcome = mutatePersistedConfig(config => {
864
+ assertStopped();
865
+ const restoredNames: string[] = [];
866
+ let alreadyAbsent = 0;
867
+ const retainedEntries: JournalEntry[] = [];
868
+
869
+ for (const entry of journal.entries) {
870
+ if (!hasOwnProvider(config.providers, entry.name)) {
871
+ alreadyAbsent++;
872
+ continue;
873
+ }
874
+ const current = config.providers[entry.name]!;
875
+ if (
876
+ current.note !== entry.note
877
+ || canonicalProviderFingerprint(current) !== entry.fingerprint
878
+ || isProviderReferencedInConfig(config, entry.name)
879
+ ) {
880
+ retainedEntries.push(entry);
881
+ continue;
882
+ }
883
+ const probe = structuredClone(config);
884
+ delete probe.providers[entry.name];
885
+ if (!validateConfigCandidate(probe).ok) {
886
+ retainedEntries.push(entry);
887
+ continue;
888
+ }
889
+ delete config.providers[entry.name];
890
+ restoredNames.push(entry.name);
891
+ }
892
+
893
+ if (restoredNames.length > 0) {
894
+ const validation = validateConfigCandidate(config);
895
+ if (!validation.ok) {
896
+ throw new CcSwitchImportError("Configuration after restoring CC-Switch providers failed validation.");
897
+ }
898
+ }
899
+ return {
900
+ changed: restoredNames.length > 0,
901
+ value: { restoredNames, alreadyAbsent, retainedEntries },
902
+ };
903
+ });
904
+
905
+ if (outcome.status === "unavailable") {
906
+ throw new CcSwitchImportError("Target configuration could not be committed during restore.");
907
+ }
908
+ const { restoredNames, alreadyAbsent, retainedEntries } = outcome.value;
909
+ if (retainedEntries.length === 0) {
910
+ unlinkJournalDurably(journalPath);
911
+ } else {
912
+ writeJournalDurably(journalPath, {
913
+ ...journal,
914
+ state: "committed",
915
+ entries: retainedEntries,
916
+ });
917
+ }
918
+ return {
919
+ mode: "restore",
920
+ restored: restoredNames.length,
921
+ restoredNames,
922
+ alreadyAbsent,
923
+ retainedEdited: retainedEntries.length,
924
+ retainedNames: retainedEntries.map(e => e.name),
925
+ };
926
+ } catch (error) {
927
+ const snap = readConfigFileSnapshot();
928
+ if (snap.diagnostics.source === "file" && snap.diagnostics.error === null) {
929
+ const remaining = journal.entries.filter(e => hasOwnProvider(snap.diagnostics.config.providers, e.name));
930
+ if (remaining.length > 0) {
931
+ writeJournalDurably(journalPath, { ...journal, state: "committed", entries: remaining });
932
+ }
933
+ }
934
+ if (error instanceof CcSwitchImportError) throw error;
935
+ throw new CcSwitchImportError("CC-Switch provider restore could not complete.");
936
+ }
937
+ });
938
+ } finally {
939
+ lease.release();
940
+ }
941
+ });
942
+ }