sneakoscope 8.0.2 → 8.0.3

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 (122) hide show
  1. package/README.md +47 -23
  2. package/config/skills-hash-ledger.v1.json +1 -1
  3. package/crates/sks-core/Cargo.lock +1 -1
  4. package/crates/sks-core/Cargo.toml +1 -1
  5. package/dist/bin/fast-inline.js +55 -13
  6. package/dist/bin/sks-dispatch.js +1 -1
  7. package/dist/cli/command-manifest-lite.js +4 -0
  8. package/dist/cli/command-registry.js +4 -0
  9. package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
  10. package/dist/cli/install-helpers-codex-lb-config.js +74 -8
  11. package/dist/cli/install-helpers.js +89 -44
  12. package/dist/commands/codex-lb.js +117 -19
  13. package/dist/commands/doctor.js +697 -37
  14. package/dist/config/skills-manifest.json +3 -2
  15. package/dist/core/agents/agent-runner-codex-exec.js +5 -3
  16. package/dist/core/codex/codex-config-guard.js +238 -52
  17. package/dist/core/codex-adapter.js +5 -3
  18. package/dist/core/codex-app/menubar/constants.js +10 -1
  19. package/dist/core/codex-app/menubar/global-install.js +288 -0
  20. package/dist/core/codex-app/menubar/installer.js +79 -14
  21. package/dist/core/codex-app/menubar/launch-agent.js +267 -45
  22. package/dist/core/codex-app/menubar/paths.js +3 -0
  23. package/dist/core/codex-app/menubar/rollback.js +55 -7
  24. package/dist/core/codex-app/menubar/status.js +75 -4
  25. package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
  26. package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
  27. package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
  28. package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
  29. package/dist/core/codex-exec-output-schema.js +4 -1
  30. package/dist/core/codex-lb/codex-lb-env.js +63 -72
  31. package/dist/core/codex-lb/codex-lb-setup.js +15 -2
  32. package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
  33. package/dist/core/codex-lb/desktop-controller.js +153 -24
  34. package/dist/core/codex-lb/routing-truth.js +327 -0
  35. package/dist/core/codex-native/core-skill-manifest.js +1 -1
  36. package/dist/core/commands/basic-cli.js +7 -1
  37. package/dist/core/commands/qa-loop-command.js +3 -1
  38. package/dist/core/commands/telegram-command.js +241 -0
  39. package/dist/core/config-adopt/config-adopt-command.js +35 -0
  40. package/dist/core/config-adopt/config-adopt.js +346 -0
  41. package/dist/core/config-adopt/index.js +3 -0
  42. package/dist/core/doctor/command-alias-cleanup.js +4 -1
  43. package/dist/core/doctor/current-project-guidance-nested.js +37 -6
  44. package/dist/core/doctor/current-project-guidance.js +11 -6
  45. package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
  46. package/dist/core/doctor/retired-managed-residue-private.js +1 -1
  47. package/dist/core/doctor/sks-menubar-doctor.js +4 -0
  48. package/dist/core/feature-fixtures.js +8 -0
  49. package/dist/core/hooks-runtime/hook-context.js +9 -0
  50. package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
  51. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
  52. package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
  53. package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
  54. package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
  55. package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
  56. package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
  57. package/dist/core/hooks-runtime.js +148 -4
  58. package/dist/core/imagegen/imagegen-capability.js +46 -0
  59. package/dist/core/imagegen/require-imagegen.js +2 -2
  60. package/dist/core/init/skills.js +17 -3
  61. package/dist/core/install/installed-package-smoke.js +8 -2
  62. package/dist/core/naruto/hardware-capacity-probe.js +9 -3
  63. package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
  64. package/dist/core/perf/import-graph-budget.js +0 -1
  65. package/dist/core/product-design-app-server.js +13 -1
  66. package/dist/core/release/package-size-budget.js +2 -2
  67. package/dist/core/release/release-pack-receipt.js +1 -2
  68. package/dist/core/routes/dollar-manifest-lite.js +1 -1
  69. package/dist/core/routes.js +1 -1
  70. package/dist/core/security/private-credential-file.js +209 -0
  71. package/dist/core/subagents/agent-catalog.js +17 -32
  72. package/dist/core/subagents/naruto-help-contract.js +5 -5
  73. package/dist/core/subagents/official-subagent-config.js +16 -6
  74. package/dist/core/subagents/official-subagent-preparation.js +34 -15
  75. package/dist/core/subagents/official-subagent-prompt.js +4 -4
  76. package/dist/core/subagents/official-subagent-runner.js +27 -4
  77. package/dist/core/subagents/thread-budget.js +19 -12
  78. package/dist/core/subagents/wave-lifecycle.js +18 -6
  79. package/dist/core/telegram/access.js +54 -0
  80. package/dist/core/telegram/client.js +144 -0
  81. package/dist/core/telegram/confirmation.js +37 -0
  82. package/dist/core/telegram/doctor.js +151 -0
  83. package/dist/core/telegram/index.js +9 -0
  84. package/dist/core/telegram/keychain.js +265 -0
  85. package/dist/core/telegram/liveness.js +109 -0
  86. package/dist/core/telegram/poller.js +90 -0
  87. package/dist/core/telegram/redaction.js +15 -0
  88. package/dist/core/telegram/types.js +1 -0
  89. package/dist/core/update/update-diagnostics.js +52 -0
  90. package/dist/core/update/update-migration-state.js +5 -1
  91. package/dist/core/update/update-operation.js +2 -1
  92. package/dist/core/update/update-stage-diagnostics.js +38 -0
  93. package/dist/core/update/update-status.js +2 -9
  94. package/dist/core/update-check.js +147 -31
  95. package/dist/core/version.js +1 -1
  96. package/dist/core/zellij/zellij-launcher.js +23 -4
  97. package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
  98. package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
  99. package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
  100. package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
  101. package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
  102. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
  103. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
  104. package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
  105. package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
  106. package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
  107. package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
  108. package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
  109. package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
  110. package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
  111. package/dist/native/sks-menubar/Sources/main.swift +15 -1
  112. package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
  113. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
  114. package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
  115. package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
  116. package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
  117. package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
  118. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
  119. package/dist/scripts/current-command-surface-check.js +2 -4
  120. package/dist/scripts/official-subagent-workflow-check.js +1 -1
  121. package/dist/scripts/packlist-performance-check.js +1 -2
  122. package/package.json +1 -1
@@ -5,18 +5,27 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { exists, runProcess } from '../fsx.js';
7
7
  import { ensureConfinedDirectory, inspectConfinedPath, isLexicallyConfined, publicPathError } from '../managed-path-safety.js';
8
- import { CODEX_LB_LEGACY_KEYCHAIN_SERVICE, CODEX_LB_SECURE_KEYCHAIN_SERVICE, codexLbEnvPath, codexLbMetadataPath, loadCodexLbEnv, normalizeCodexLbBaseUrl, parseShellEnvValue } from './codex-lb-env.js';
8
+ import { CODEX_LB_LEGACY_KEYCHAIN_SERVICE, CODEX_LB_SECURE_KEYCHAIN_SERVICE, codexLbBaseUrlSecurityBlocker, codexLbEnvPath, codexLbMetadataPath, loadCodexLbEnv, normalizeCodexLbBaseUrl, parseShellEnvValue } from './codex-lb-env.js';
9
+ import { PrivateCredentialFileError, createPrivateTextExclusive, hardenPrivateCredentialFileMode, readPrivateCredentialFile, writePrivateTextAtomic } from '../security/private-credential-file.js';
9
10
  export const CODEX_LB_STALE_ENV_TWINS = ['codex-lb.env', 'sks.env'];
10
11
  export const CODEX_LB_STALE_KEYCHAIN_SERVICES = [CODEX_LB_LEGACY_KEYCHAIN_SERVICE];
11
12
  export const CODEX_LB_OFFICIAL_KEYCHAIN_SERVICE = CODEX_LB_SECURE_KEYCHAIN_SERVICE;
12
13
  export const CODEX_LB_STALE_TWIN_PROVENANCE_MARKER = '# sks-codex-lb-managed-credential-twin';
13
14
  export const CODEX_LB_KEYCHAIN_MIGRATION_RECEIPT_SCHEMA = 'sks.codex-lb-keychain-migration.v2';
15
+ export const CODEX_LB_KEYCHAIN_MIGRATION_STAMP_SCHEMA = 'sks.codex-lb-keychain-migration-stamp.v1';
14
16
  function credentialToolEnvironment(env = process.env) {
15
17
  const sanitized = { ...env };
16
18
  delete sanitized.CODEX_LB_API_KEY;
17
19
  delete sanitized.OPENROUTER_API_KEY;
18
20
  return sanitized;
19
21
  }
22
+ function codexLbCredentialStorageActions(home) {
23
+ return [
24
+ `Store the key in ${codexLbEnvPath(home)} (owner-only mode 0600).`,
25
+ 'Run: sks codex-lb setup --host <domain> --api-key-stdin --yes',
26
+ 'Alternatively, provide CODEX_LB_API_KEY in the launching environment.'
27
+ ];
28
+ }
20
29
  export async function loadOfficialCodexLbCredentials(opts = {}) {
21
30
  const home = opts.home || process.env.HOME || os.homedir();
22
31
  const load = opts.loadCodexLbEnvImpl || loadCodexLbEnv;
@@ -27,6 +36,404 @@ export async function loadOfficialCodexLbCredentials(opts = {}) {
27
36
  ...(opts.metadataPath ? { metadataPath: opts.metadataPath } : {})
28
37
  });
29
38
  }
39
+ export function codexLbLegacyKeychainMigrationStampPath(home = process.env.HOME || os.homedir()) {
40
+ return path.join(String(home || os.homedir()), '.codex', 'sks-codex-lb-keychain-migration.json');
41
+ }
42
+ export async function inspectCodexLbLegacyKeychainMigration(opts = {}) {
43
+ return reconcileCodexLbLegacyKeychainMigration('inspect', opts);
44
+ }
45
+ export async function repairCodexLbLegacyKeychainMigration(opts = {}) {
46
+ return reconcileCodexLbLegacyKeychainMigration('repair', opts);
47
+ }
48
+ async function reconcileCodexLbLegacyKeychainMigration(mode, opts) {
49
+ const home = path.resolve(opts.home || process.env.HOME || os.homedir());
50
+ const codexHome = path.join(home, '.codex');
51
+ const envPath = path.resolve(opts.envPath || codexLbEnvPath(home));
52
+ const metadataPath = path.resolve(opts.metadataPath || codexLbMetadataPath(home));
53
+ const stampPath = codexLbLegacyKeychainMigrationStampPath(home);
54
+ const account = String(opts.account || opts.env?.USER || opts.processEnv?.USER || process.env.USER || 'sks').trim();
55
+ const result = (fields) => ({
56
+ schema: 'sks.codex-lb-legacy-keychain-reconciliation.v1',
57
+ ok: false,
58
+ status: 'blocked',
59
+ mode,
60
+ env_key_valid: false,
61
+ keychain_item_present: null,
62
+ prompt_risk: 'none',
63
+ attempted: false,
64
+ stamp_path: stampPath,
65
+ stamp_outcome: null,
66
+ keychain_deleted: false,
67
+ keychain_cleared: [],
68
+ blockers: [],
69
+ ...fields
70
+ });
71
+ if ((opts.platform || process.platform) !== 'darwin') {
72
+ return result({ ok: true, status: 'not_macos' });
73
+ }
74
+ if (!isLexicallyConfined(codexHome, envPath) || !isLexicallyConfined(codexHome, metadataPath)) {
75
+ return result({
76
+ status: 'credential_path_outside_codex_home',
77
+ blockers: ['codex_lb_credential_path_outside_codex_home']
78
+ });
79
+ }
80
+ let loaded = await loadOfficialCodexLbCredentials({ home, envPath, metadataPath });
81
+ if (mode === 'repair' && loaded.blockers?.includes('codex_lb_env_file_mode_not_0600')) {
82
+ try {
83
+ await hardenPrivateCredentialFileMode(codexHome, envPath, 'codex_lb_env_file');
84
+ loaded = await loadOfficialCodexLbCredentials({ home, envPath, metadataPath });
85
+ }
86
+ catch (error) {
87
+ return result({
88
+ status: 'env_file_mode_repair_failed',
89
+ blockers: [publicPathError(error, envPath)]
90
+ });
91
+ }
92
+ }
93
+ const envKeyValid = loaded.api_key.usable && loaded.api_key.source === 'env-file';
94
+ const unsafeEnvBlockers = (loaded.blockers || []).filter((blocker) => blocker.startsWith('codex_lb_env_file_'));
95
+ if (unsafeEnvBlockers.length > 0) {
96
+ return result({
97
+ status: 'env_file_unsafe',
98
+ env_key_valid: false,
99
+ blockers: unsafeEnvBlockers
100
+ });
101
+ }
102
+ const stampRead = await readCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath);
103
+ if (stampRead.blocker) {
104
+ return result({
105
+ status: 'migration_stamp_invalid',
106
+ env_key_valid: envKeyValid,
107
+ blockers: [stampRead.blocker]
108
+ });
109
+ }
110
+ const retryAttempt = mode === 'repair'
111
+ && (opts.forceRetry === true || opts.retryAttempt === true || opts.force === true);
112
+ const completedTransfer = stampRead.stamp?.outcome === 'migrated';
113
+ if (stampRead.stamp && !retryAttempt && (!envKeyValid || completedTransfer)) {
114
+ return result({
115
+ ok: stampRead.stamp.outcome === 'migrated',
116
+ status: 'already_attempted',
117
+ env_key_valid: envKeyValid,
118
+ attempted: true,
119
+ stamp_outcome: stampRead.stamp.outcome,
120
+ blockers: stampRead.stamp.outcome === 'migrated'
121
+ ? []
122
+ : [`legacy_keychain_migration_already_attempted:${stampRead.stamp.outcome}`]
123
+ });
124
+ }
125
+ const security = opts.securityBin || (await exists('/usr/bin/security') ? '/usr/bin/security' : null);
126
+ if (!security) {
127
+ return result({
128
+ status: 'security_unavailable',
129
+ env_key_valid: envKeyValid,
130
+ blockers: ['legacy_keychain_security_unavailable']
131
+ });
132
+ }
133
+ const run = opts.runProcessImpl || runProcess;
134
+ const toolEnv = credentialToolEnvironment(opts.env || opts.processEnv || process.env);
135
+ if (mode === 'repair' && envKeyValid) {
136
+ const replacement = await verifyCodexLbLegacyKeychainReplacementStore({
137
+ home,
138
+ envPath,
139
+ metadataPath,
140
+ account,
141
+ ...(opts.expectedApiKeySha256 ? { expectedApiKeySha256: opts.expectedApiKeySha256 } : {})
142
+ });
143
+ if (!replacement.ok || !replacement.receipt) {
144
+ return result({
145
+ status: 'replacement_store_unverified',
146
+ env_key_valid: true,
147
+ blockers: replacement.blockers.length
148
+ ? replacement.blockers
149
+ : ['legacy_keychain_replacement_store_unverified']
150
+ });
151
+ }
152
+ const cleanup = await purgeStaleCodexLbCredentialTwins({
153
+ home,
154
+ account,
155
+ platform: 'darwin',
156
+ securityBin: security,
157
+ runProcessImpl: run,
158
+ env: toolEnv,
159
+ skipStaleEnvTwins: true,
160
+ legacyKeychainMigrationReceipt: replacement.receipt
161
+ });
162
+ const keychainDeleted = cleanup.keychain_cleared.includes(CODEX_LB_LEGACY_KEYCHAIN_SERVICE);
163
+ return result({
164
+ ok: cleanup.blockers.length === 0,
165
+ status: cleanup.blockers.length > 0
166
+ ? 'legacy_keychain_cleanup_failed'
167
+ : keychainDeleted ? 'legacy_keychain_removed' : 'legacy_keychain_absent',
168
+ env_key_valid: true,
169
+ keychain_deleted: keychainDeleted,
170
+ keychain_cleared: cleanup.keychain_cleared,
171
+ blockers: cleanup.blockers
172
+ });
173
+ }
174
+ const attributeProbe = await run(security, [
175
+ 'find-generic-password',
176
+ '-a',
177
+ account,
178
+ '-s',
179
+ CODEX_LB_LEGACY_KEYCHAIN_SERVICE
180
+ ], {
181
+ timeoutMs: 5000,
182
+ maxOutputBytes: 8192,
183
+ env: toolEnv,
184
+ envMode: 'replace'
185
+ }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
186
+ const keychainItemPresent = attributeProbe.code === 0;
187
+ if (!keychainItemPresent && !keychainItemMissing(attributeProbe)) {
188
+ return result({
189
+ status: 'legacy_keychain_probe_failed',
190
+ env_key_valid: envKeyValid,
191
+ blockers: ['legacy_keychain_attribute_probe_failed']
192
+ });
193
+ }
194
+ if (!keychainItemPresent) {
195
+ return result({
196
+ ok: true,
197
+ status: 'legacy_keychain_absent',
198
+ env_key_valid: envKeyValid,
199
+ keychain_item_present: false
200
+ });
201
+ }
202
+ if (mode === 'inspect') {
203
+ return result({
204
+ ok: true,
205
+ status: envKeyValid ? 'legacy_keychain_cleanup_available' : 'legacy_keychain_migration_available',
206
+ env_key_valid: envKeyValid,
207
+ keychain_item_present: true,
208
+ prompt_risk: envKeyValid ? 'none' : 'one_time_on_repair'
209
+ });
210
+ }
211
+ const migrationBaseUrl = normalizeCodexLbBaseUrl(opts.baseUrl || loaded.base_url || '');
212
+ const migrationBaseUrlBlocker = migrationBaseUrl ? codexLbBaseUrlSecurityBlocker(migrationBaseUrl) : null;
213
+ if (!migrationBaseUrl || migrationBaseUrlBlocker) {
214
+ return result({
215
+ status: 'base_url_missing',
216
+ env_key_valid: false,
217
+ keychain_item_present: true,
218
+ prompt_risk: 'one_time_on_repair',
219
+ blockers: [migrationBaseUrlBlocker || 'codex_lb_base_url_missing_for_keychain_migration']
220
+ });
221
+ }
222
+ const attemptedAt = new Date().toISOString();
223
+ const pendingStamp = {
224
+ schema: CODEX_LB_KEYCHAIN_MIGRATION_STAMP_SCHEMA,
225
+ attempted: true,
226
+ attempted_at: attemptedAt,
227
+ updated_at: attemptedAt,
228
+ outcome: 'pending',
229
+ legacy_service: CODEX_LB_LEGACY_KEYCHAIN_SERVICE,
230
+ legacy_account: account
231
+ };
232
+ try {
233
+ const claimed = retryAttempt
234
+ ? await writeCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath, pendingStamp).then(() => true)
235
+ : await createPrivateTextExclusive(codexHome, stampPath, `${JSON.stringify(pendingStamp, null, 2)}\n`, 'legacy_keychain_migration_stamp', opts.testHooks?.beforeStampPublish
236
+ ? { beforePublish: opts.testHooks.beforeStampPublish }
237
+ : {});
238
+ if (!claimed) {
239
+ return result({
240
+ status: 'already_attempted',
241
+ env_key_valid: false,
242
+ keychain_item_present: true,
243
+ attempted: true,
244
+ stamp_outcome: 'pending',
245
+ blockers: ['legacy_keychain_migration_already_attempted:pending']
246
+ });
247
+ }
248
+ }
249
+ catch (error) {
250
+ return result({
251
+ status: 'migration_stamp_write_failed',
252
+ env_key_valid: false,
253
+ keychain_item_present: true,
254
+ blockers: [publicPathError(error, stampPath)]
255
+ });
256
+ }
257
+ const secretRead = await run(security, [
258
+ 'find-generic-password',
259
+ '-w',
260
+ '-a',
261
+ account,
262
+ '-s',
263
+ CODEX_LB_LEGACY_KEYCHAIN_SERVICE
264
+ ], {
265
+ timeoutMs: 30_000,
266
+ maxOutputBytes: 65_536,
267
+ env: toolEnv,
268
+ envMode: 'replace'
269
+ }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
270
+ const apiKey = secretRead.code === 0 ? String(secretRead.stdout || '').trim() : '';
271
+ if (!apiKey) {
272
+ const outcome = secretRead.code === 0 ? 'keychain_value_empty' : 'keychain_read_failed_or_cancelled';
273
+ const outcomePersisted = await persistCodexLbLegacyKeychainMigrationOutcome(codexHome, stampPath, pendingStamp, outcome, opts);
274
+ if (!outcomePersisted) {
275
+ return result({
276
+ status: 'migration_stamp_outcome_write_failed',
277
+ env_key_valid: false,
278
+ keychain_item_present: true,
279
+ attempted: true,
280
+ stamp_outcome: 'pending',
281
+ blockers: ['migration_stamp_outcome_write_failed']
282
+ });
283
+ }
284
+ return result({
285
+ status: outcome,
286
+ env_key_valid: false,
287
+ keychain_item_present: true,
288
+ attempted: true,
289
+ stamp_outcome: outcome,
290
+ blockers: [`legacy_keychain_migration_${outcome}`]
291
+ });
292
+ }
293
+ const apiKeySha256 = sha256Bytes(Buffer.from(apiKey));
294
+ const envText = [
295
+ `export CODEX_LB_BASE_URL=${shellSingleQuote(migrationBaseUrl)}`,
296
+ `export CODEX_LB_API_KEY=${shellSingleQuote(apiKey)}`,
297
+ ''
298
+ ].join('\n');
299
+ const metadataText = `${JSON.stringify({
300
+ schema: 'sks.codex-lb-metadata.v1',
301
+ base_url: migrationBaseUrl,
302
+ updated_at: new Date().toISOString(),
303
+ source: 'legacy_keychain_migration',
304
+ api_key: {
305
+ redacted: true,
306
+ sha256: apiKeySha256,
307
+ preview: previewCredential(apiKey)
308
+ }
309
+ }, null, 2)}\n`;
310
+ try {
311
+ await writePrivateTextAtomic(codexHome, envPath, envText, 'codex_lb_env_file');
312
+ await writePrivateTextAtomic(codexHome, metadataPath, metadataText, 'codex_lb_metadata');
313
+ }
314
+ catch (error) {
315
+ const outcome = 'credential_write_failed';
316
+ const outcomePersisted = await persistCodexLbLegacyKeychainMigrationOutcome(codexHome, stampPath, pendingStamp, outcome, opts);
317
+ if (!outcomePersisted) {
318
+ return result({
319
+ status: 'migration_stamp_outcome_write_failed',
320
+ env_key_valid: false,
321
+ keychain_item_present: true,
322
+ attempted: true,
323
+ stamp_outcome: 'pending',
324
+ blockers: ['migration_stamp_outcome_write_failed', publicPathError(error, envPath)]
325
+ });
326
+ }
327
+ return result({
328
+ status: outcome,
329
+ env_key_valid: false,
330
+ keychain_item_present: true,
331
+ attempted: true,
332
+ stamp_outcome: outcome,
333
+ blockers: [publicPathError(error, envPath)]
334
+ });
335
+ }
336
+ const replacement = await verifyCodexLbLegacyKeychainReplacementStore({
337
+ home,
338
+ envPath,
339
+ metadataPath,
340
+ account,
341
+ expectedApiKeySha256: apiKeySha256
342
+ });
343
+ const cleanup = replacement.receipt
344
+ ? await purgeStaleCodexLbCredentialTwins({
345
+ home,
346
+ account,
347
+ platform: 'darwin',
348
+ securityBin: security,
349
+ runProcessImpl: run,
350
+ env: toolEnv,
351
+ skipStaleEnvTwins: true,
352
+ legacyKeychainMigrationReceipt: replacement.receipt
353
+ })
354
+ : { keychain_cleared: [], blockers: replacement.blockers };
355
+ const keychainDeleted = cleanup.keychain_cleared.includes(CODEX_LB_LEGACY_KEYCHAIN_SERVICE);
356
+ const outcome = replacement.ok && cleanup.blockers.length === 0
357
+ ? 'migrated'
358
+ : keychainDeleted ? 'post_write_verification_failed' : 'keychain_delete_failed';
359
+ const outcomePersisted = await persistCodexLbLegacyKeychainMigrationOutcome(codexHome, stampPath, pendingStamp, outcome, opts);
360
+ if (!outcomePersisted) {
361
+ return result({
362
+ status: 'migration_stamp_outcome_write_failed',
363
+ env_key_valid: replacement.ok,
364
+ keychain_item_present: true,
365
+ attempted: true,
366
+ stamp_outcome: 'pending',
367
+ keychain_deleted: keychainDeleted,
368
+ keychain_cleared: cleanup.keychain_cleared,
369
+ blockers: ['migration_stamp_outcome_write_failed']
370
+ });
371
+ }
372
+ return result({
373
+ ok: outcome === 'migrated',
374
+ status: outcome,
375
+ env_key_valid: replacement.ok,
376
+ keychain_item_present: true,
377
+ attempted: true,
378
+ stamp_outcome: outcome,
379
+ keychain_deleted: keychainDeleted,
380
+ keychain_cleared: cleanup.keychain_cleared,
381
+ blockers: outcome === 'migrated'
382
+ ? []
383
+ : [...new Set([...replacement.blockers, ...cleanup.blockers])]
384
+ });
385
+ }
386
+ async function readCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath) {
387
+ let snapshot;
388
+ try {
389
+ snapshot = await readPrivateCredentialFile(codexHome, stampPath, 'legacy_keychain_migration_stamp');
390
+ }
391
+ catch (error) {
392
+ if (error instanceof PrivateCredentialFileError && error.code === 'missing') {
393
+ return { stamp: null, blocker: null };
394
+ }
395
+ return { stamp: null, blocker: publicPathError(error, stampPath) };
396
+ }
397
+ try {
398
+ const value = JSON.parse(snapshot.bytes.toString('utf8'));
399
+ if (value.schema !== CODEX_LB_KEYCHAIN_MIGRATION_STAMP_SCHEMA
400
+ || value.attempted !== true
401
+ || !value.outcome
402
+ || value.legacy_service !== CODEX_LB_LEGACY_KEYCHAIN_SERVICE) {
403
+ return { stamp: null, blocker: 'legacy_keychain_migration_stamp_invalid' };
404
+ }
405
+ return { stamp: value, blocker: null };
406
+ }
407
+ catch {
408
+ return { stamp: null, blocker: 'legacy_keychain_migration_stamp_invalid' };
409
+ }
410
+ }
411
+ async function writeCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath, stamp) {
412
+ await writePrivateTextAtomic(codexHome, stampPath, `${JSON.stringify(stamp, null, 2)}\n`, 'legacy_keychain_migration_stamp');
413
+ }
414
+ async function updateCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath, stamp, outcome) {
415
+ await writeCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath, {
416
+ ...stamp,
417
+ updated_at: new Date().toISOString(),
418
+ outcome
419
+ });
420
+ }
421
+ async function persistCodexLbLegacyKeychainMigrationOutcome(codexHome, stampPath, stamp, outcome, opts) {
422
+ try {
423
+ await opts.testHooks?.beforeStampOutcomeWrite?.(outcome);
424
+ await updateCodexLbLegacyKeychainMigrationStamp(codexHome, stampPath, stamp, outcome);
425
+ return true;
426
+ }
427
+ catch {
428
+ return false;
429
+ }
430
+ }
431
+ function shellSingleQuote(value) {
432
+ return `'${value.replace(/'/g, `'\\''`)}'`;
433
+ }
434
+ function previewCredential(value) {
435
+ return value.length <= 8 ? '***' : `${value.slice(0, 4)}...${value.slice(-4)}`;
436
+ }
30
437
  export async function verifyCodexLbLegacyKeychainReplacementStore(opts = {}) {
31
438
  const home = path.resolve(opts.home || process.env.HOME || os.homedir());
32
439
  const codexHome = path.join(home, '.codex');
@@ -172,6 +579,7 @@ export async function purgeStaleCodexLbCredentialTwins(opts = {}) {
172
579
  || (await exists('/usr/bin/security') ? '/usr/bin/security' : null);
173
580
  const account = opts.account || process.env.USER || 'sks';
174
581
  const run = opts.runProcessImpl || runProcess;
582
+ const toolEnv = credentialToolEnvironment(opts.env || process.env);
175
583
  if (security) {
176
584
  for (const service of CODEX_LB_STALE_KEYCHAIN_SERVICES) {
177
585
  const command = legacyDeletionProven ? 'delete-generic-password' : 'find-generic-password';
@@ -184,7 +592,7 @@ export async function purgeStaleCodexLbCredentialTwins(opts = {}) {
184
592
  ], {
185
593
  timeoutMs: 5000,
186
594
  maxOutputBytes: 8192,
187
- env: credentialToolEnvironment(),
595
+ env: toolEnv,
188
596
  envMode: 'replace'
189
597
  }).catch((error) => ({
190
598
  code: 1,
@@ -206,7 +614,7 @@ export async function purgeStaleCodexLbCredentialTwins(opts = {}) {
206
614
  ], {
207
615
  timeoutMs: 5000,
208
616
  maxOutputBytes: 8192,
209
- env: credentialToolEnvironment(),
617
+ env: toolEnv,
210
618
  envMode: 'replace'
211
619
  }).catch((error) => ({
212
620
  code: 1,
@@ -231,51 +639,6 @@ export async function purgeStaleCodexLbCredentialTwins(opts = {}) {
231
639
  }
232
640
  return { removed, quarantined, keychain_cleared: keychainCleared, blockers };
233
641
  }
234
- async function readPrivateCredentialFile(boundary, file, label) {
235
- const inspected = await inspectConfinedPath(boundary, file);
236
- if (!inspected.exists)
237
- throw new Error(`${label}_missing:${file}`);
238
- if (inspected.leafSymlink || !inspected.stat?.isFile()) {
239
- throw new Error(`${label}_not_regular:${file}`);
240
- }
241
- if ((inspected.stat.mode & 0o777) !== 0o600) {
242
- throw new Error(`${label}_mode_not_0600:${file}`);
243
- }
244
- const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
245
- if (expectedUid !== null && inspected.stat.uid !== expectedUid) {
246
- throw new Error(`${label}_owner_mismatch:${file}`);
247
- }
248
- let handle = null;
249
- try {
250
- handle = await fsp.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
251
- const before = await handle.stat();
252
- if (!before.isFile()
253
- || before.dev !== inspected.stat.dev
254
- || before.ino !== inspected.stat.ino
255
- || (before.mode & 0o777) !== 0o600
256
- || (expectedUid !== null && before.uid !== expectedUid)) {
257
- throw new Error(`${label}_identity_mismatch:${file}`);
258
- }
259
- const bytes = await handle.readFile();
260
- const after = await handle.stat();
261
- const pathAfter = await inspectConfinedPath(boundary, file);
262
- if (!pathAfter.exists
263
- || pathAfter.leafSymlink
264
- || !pathAfter.stat?.isFile()
265
- || before.dev !== after.dev
266
- || before.ino !== after.ino
267
- || before.size !== after.size
268
- || before.mtimeMs !== after.mtimeMs
269
- || after.dev !== pathAfter.stat.dev
270
- || after.ino !== pathAfter.stat.ino) {
271
- throw new Error(`${label}_changed_during_verification:${file}`);
272
- }
273
- return { bytes, sha256: sha256Bytes(bytes) };
274
- }
275
- finally {
276
- await handle?.close().catch(() => undefined);
277
- }
278
- }
279
642
  async function validateLegacyKeychainMigrationReceipt(input) {
280
643
  const receipt = input.receipt;
281
644
  if (!receipt)
@@ -466,6 +829,74 @@ async function restoreStaleTwinClaimIfAbsent(quarantinePath, target, claimed) {
466
829
  return false;
467
830
  }
468
831
  }
832
+ export async function inspectDesktopCenterLaunchCredentials(opts = { mode: 'disabled' }) {
833
+ const home = opts.home || process.env.HOME || os.homedir();
834
+ const mode = String(opts.mode || 'disabled');
835
+ const platform = opts.platform || process.platform;
836
+ const actions = codexLbCredentialStorageActions(home);
837
+ if (platform !== 'darwin' && !opts.force) {
838
+ return {
839
+ schema: 'sks.codex-lb-desktop-center-credential-inspection.v1',
840
+ ok: true,
841
+ status: 'not_macos',
842
+ mode,
843
+ expected_api_key_sha256: null,
844
+ launch_api_key_sha256: null,
845
+ launch_api_key_present: false,
846
+ blockers: [],
847
+ operator_actions: []
848
+ };
849
+ }
850
+ const launchctl = opts.launchctlBin
851
+ || (await exists('/bin/launchctl') ? '/bin/launchctl' : null);
852
+ if (!launchctl) {
853
+ return {
854
+ schema: 'sks.codex-lb-desktop-center-credential-inspection.v1',
855
+ ok: false,
856
+ status: 'launchctl_missing',
857
+ mode,
858
+ expected_api_key_sha256: null,
859
+ launch_api_key_sha256: null,
860
+ launch_api_key_present: false,
861
+ blockers: ['launchctl_missing'],
862
+ operator_actions: []
863
+ };
864
+ }
865
+ const loaded = opts.loadedEnv || await loadOfficialCodexLbCredentials({
866
+ home,
867
+ ...(opts.loadCodexLbEnvImpl ? { loadCodexLbEnvImpl: opts.loadCodexLbEnvImpl } : {})
868
+ });
869
+ const run = opts.runProcessImpl || runProcess;
870
+ const observed = await run(launchctl, ['getenv', 'CODEX_LB_API_KEY'], {
871
+ timeoutMs: 5000,
872
+ maxOutputBytes: 8192,
873
+ env: credentialToolEnvironment(),
874
+ envMode: 'replace'
875
+ }).catch(() => ({ code: 1, stdout: '', stderr: '' }));
876
+ const launchKey = observed.code === 0 ? String(observed.stdout || '').trim() : '';
877
+ const expectedKey = mode === 'cli-provider' ? String(loaded.secret_api_key || '').trim() : '';
878
+ const launchHash = launchKey ? sha256Bytes(Buffer.from(launchKey)) : null;
879
+ const expectedHash = expectedKey ? sha256Bytes(Buffer.from(expectedKey)) : null;
880
+ const blockers = [];
881
+ if (mode === 'cli-provider' && !expectedKey)
882
+ blockers.push('codex_lb_launchd_canonical_key_unavailable');
883
+ if (mode === 'cli-provider' && expectedHash && launchHash !== expectedHash) {
884
+ blockers.push('codex_lb_launchd_key_mismatch');
885
+ }
886
+ if (mode !== 'cli-provider' && launchKey)
887
+ blockers.push('codex_lb_launchd_key_present_while_unselected');
888
+ return {
889
+ schema: 'sks.codex-lb-desktop-center-credential-inspection.v1',
890
+ ok: blockers.length === 0,
891
+ status: blockers.length === 0 ? 'launchd_selection_state_matched' : 'launchd_selection_state_mismatch',
892
+ mode,
893
+ expected_api_key_sha256: expectedHash,
894
+ launch_api_key_sha256: launchHash,
895
+ launch_api_key_present: Boolean(launchKey),
896
+ blockers,
897
+ operator_actions: blockers.includes('codex_lb_launchd_canonical_key_unavailable') ? actions : []
898
+ };
899
+ }
469
900
  export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disabled' }) {
470
901
  const home = opts.home || process.env.HOME || os.homedir();
471
902
  const mode = String(opts.mode || 'disabled');
@@ -498,7 +929,8 @@ export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disable
498
929
  stale_twins_removed: purge.removed,
499
930
  stale_twins_quarantined: purge.quarantined,
500
931
  stale_keychain_cleared: purge.keychain_cleared,
501
- blockers: purge.blockers
932
+ blockers: purge.blockers,
933
+ operator_actions: []
502
934
  };
503
935
  }
504
936
  const launchctl = opts.launchctlBin
@@ -515,7 +947,8 @@ export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disable
515
947
  stale_twins_removed: purge.removed,
516
948
  stale_twins_quarantined: purge.quarantined,
517
949
  stale_keychain_cleared: purge.keychain_cleared,
518
- blockers: ['launchctl_missing', ...purge.blockers]
950
+ blockers: ['launchctl_missing', ...purge.blockers],
951
+ operator_actions: []
519
952
  };
520
953
  }
521
954
  const run = opts.runProcessImpl || runProcess;
@@ -562,7 +995,8 @@ export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disable
562
995
  ...(baseOk ? [] : ['launchctl_unsetenv_CODEX_LB_BASE_URL_failed']),
563
996
  ...(openRouterOk ? [] : ['launchctl_unsetenv_OPENROUTER_API_KEY_failed']),
564
997
  ...purge.blockers
565
- ]
998
+ ],
999
+ operator_actions: codexLbCredentialStorageActions(home)
566
1000
  };
567
1001
  }
568
1002
  return {
@@ -587,10 +1021,16 @@ export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disable
587
1021
  ...(baseOk ? [] : ['launchctl_unsetenv_CODEX_LB_BASE_URL_failed']),
588
1022
  ...(openRouterOk ? [] : ['launchctl_unsetenv_OPENROUTER_API_KEY_failed']),
589
1023
  ...purge.blockers
590
- ]
1024
+ ],
1025
+ operator_actions: []
591
1026
  };
592
1027
  }
593
- const keyUnset = await unsetEnv('CODEX_LB_API_KEY');
1028
+ const cliProviderSelected = mode === 'cli-provider';
1029
+ const apiKeyStatus = cliProviderSelected
1030
+ ? loaded.secret_api_key
1031
+ ? await setEnv('CODEX_LB_API_KEY', loaded.secret_api_key) ? 'set' : 'failed'
1032
+ : await unsetEnv('CODEX_LB_API_KEY') ? 'unset' : 'failed'
1033
+ : await unsetEnv('CODEX_LB_API_KEY') ? 'unset' : 'failed';
594
1034
  const openRouterUnset = await unsetEnv('OPENROUTER_API_KEY');
595
1035
  let baseStatus = 'skipped';
596
1036
  if (loaded.base_url && (mode === 'desktop-native-bridge' || mode === 'cli-provider')) {
@@ -599,26 +1039,45 @@ export async function syncDesktopCenterLaunchCredentials(opts = { mode: 'disable
599
1039
  else if (mode === 'disabled') {
600
1040
  baseStatus = await unsetEnv('CODEX_LB_BASE_URL') ? 'unset' : 'failed';
601
1041
  }
602
- const ok = keyUnset && openRouterUnset && baseStatus !== 'failed' && purge.blockers.length === 0;
1042
+ const credentialsAvailable = !cliProviderSelected || Boolean(loaded.secret_api_key && loaded.base_url);
1043
+ const ok = credentialsAvailable
1044
+ && apiKeyStatus !== 'failed'
1045
+ && openRouterUnset
1046
+ && baseStatus !== 'failed'
1047
+ && purge.blockers.length === 0;
603
1048
  return {
604
1049
  schema: 'sks.codex-lb-desktop-center-credentials.v1',
605
1050
  ok,
606
- status: ok ? 'desktop_secret_launch_env_cleared' : 'desktop_launch_env_cleanup_failed',
1051
+ status: ok
1052
+ ? cliProviderSelected ? 'cli_provider_launch_credentials_set' : 'desktop_secret_launch_env_cleared'
1053
+ : cliProviderSelected && !credentialsAvailable
1054
+ ? 'center_credentials_unavailable'
1055
+ : 'desktop_launch_env_cleanup_failed',
607
1056
  mode,
608
1057
  api_key_fingerprint: fingerprint,
609
1058
  base_url_present: basePresent,
610
1059
  launch_env: {
611
- api_key: keyUnset ? 'unset' : 'failed',
1060
+ api_key: apiKeyStatus,
612
1061
  base_url: baseStatus
613
1062
  },
614
1063
  stale_twins_removed: purge.removed,
615
1064
  stale_twins_quarantined: purge.quarantined,
616
1065
  stale_keychain_cleared: purge.keychain_cleared,
617
1066
  blockers: [
618
- ...(keyUnset ? [] : ['launchctl_unsetenv_CODEX_LB_API_KEY_failed']),
1067
+ ...(!credentialsAvailable
1068
+ ? (loaded.missing.length
1069
+ ? loaded.missing.map((item) => `codex_lb_missing:${item}`)
1070
+ : ['codex_lb_not_configured'])
1071
+ : []),
1072
+ ...(apiKeyStatus === 'failed'
1073
+ ? [cliProviderSelected
1074
+ ? 'launchctl_setenv_CODEX_LB_API_KEY_failed'
1075
+ : 'launchctl_unsetenv_CODEX_LB_API_KEY_failed']
1076
+ : []),
619
1077
  ...(openRouterUnset ? [] : ['launchctl_unsetenv_OPENROUTER_API_KEY_failed']),
620
1078
  ...(baseStatus === 'failed' ? ['launchctl_base_url_sync_failed'] : []),
621
1079
  ...purge.blockers
622
- ]
1080
+ ],
1081
+ operator_actions: credentialsAvailable ? [] : codexLbCredentialStorageActions(home)
623
1082
  };
624
1083
  }