sneakoscope 8.1.2 → 8.2.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 (261) hide show
  1. package/README.md +96 -58
  2. package/crates/sks-core/Cargo.lock +1 -1
  3. package/crates/sks-core/Cargo.toml +1 -1
  4. package/dist/bin/fast-inline.js +5 -51
  5. package/dist/cli/command-manifest-lite.js +2 -1
  6. package/dist/cli/command-registry.js +2 -1
  7. package/dist/cli/global-mode-router.js +1 -1
  8. package/dist/cli/install-helpers-codex-lb-config.js +112 -914
  9. package/dist/cli/install-helpers-codex-lb-shared.js +3 -44
  10. package/dist/cli/install-helpers-install-support.js +4 -20
  11. package/dist/cli/install-helpers.js +36 -2716
  12. package/dist/cli/router.js +9 -9
  13. package/dist/commands/bridge-command-output.js +111 -0
  14. package/dist/commands/bridge.js +320 -0
  15. package/dist/commands/codex-app.js +39 -123
  16. package/dist/commands/doctor-helpers.js +380 -0
  17. package/dist/commands/doctor-profile.js +3 -0
  18. package/dist/commands/doctor.js +114 -873
  19. package/dist/commands/mad-sks.js +0 -4
  20. package/dist/config/skills-manifest.json +1 -1
  21. package/dist/core/agents/agent-effort-policy.js +11 -21
  22. package/dist/core/agents/agent-recursion-guard.js +26 -0
  23. package/dist/core/agents/agent-runner-codex-exec.js +7 -9
  24. package/dist/core/architecture-hardening/contracts/contracts.js +225 -161
  25. package/dist/core/architecture-hardening/state/state-service.js +49 -13
  26. package/dist/core/auto-review.js +15 -9
  27. package/dist/core/codex/codex-config-guard.js +8 -0
  28. package/dist/core/codex-adapter.js +8 -10
  29. package/dist/core/codex-app/codex-app-fast-ui-repair.js +7 -29
  30. package/dist/core/codex-app/codex-app-launcher.js +10 -12
  31. package/dist/core/codex-app/codex-app-restart.js +10 -12
  32. package/dist/core/codex-app/menubar/constants.js +2 -5
  33. package/dist/core/codex-app/menubar/global-install.js +3 -2
  34. package/dist/core/codex-app/menubar/installer/result.js +23 -0
  35. package/dist/core/codex-app/menubar/installer/runtime.js +28 -0
  36. package/dist/core/codex-app/menubar/installer.js +5 -96
  37. package/dist/core/codex-app/menubar/migration.js +1 -42
  38. package/dist/core/codex-app/openrouter-provider.js +0 -78
  39. package/dist/core/codex-app.js +97 -360
  40. package/dist/core/codex-control/codex-app-server-runtime-env.js +8 -28
  41. package/dist/core/codex-control/codex-current-image-path-real-probe.js +2 -3
  42. package/dist/core/codex-control/codex-current-web-search-probe.js +2 -3
  43. package/dist/core/codex-control/codex-sdk-adapter.js +5 -48
  44. package/dist/core/codex-control/codex-task-runner.js +16 -60
  45. package/dist/core/codex-control/desktop-bridge-launch-guard.js +227 -0
  46. package/dist/core/codex-exec-output-schema.js +11 -13
  47. package/dist/core/codex-lb/bridge-contracts.js +2 -0
  48. package/dist/core/codex-lb/bridge-runtime-validation/capability.js +104 -0
  49. package/dist/core/codex-lb/bridge-runtime-validation/catalog.js +52 -0
  50. package/dist/core/codex-lb/bridge-runtime-validation/shared.js +109 -0
  51. package/dist/core/codex-lb/bridge-runtime-validation/status.js +250 -0
  52. package/dist/core/codex-lb/bridge-runtime-validation.js +106 -0
  53. package/dist/core/codex-lb/capability-runner.js +505 -201
  54. package/dist/core/codex-lb/codex-lb-env.js +179 -12
  55. package/dist/core/codex-lb/combined-catalog/builder.js +86 -0
  56. package/dist/core/codex-lb/combined-catalog/contracts.js +5 -0
  57. package/dist/core/codex-lb/combined-catalog/normalize.js +170 -0
  58. package/dist/core/codex-lb/combined-catalog/persistence.js +207 -0
  59. package/dist/core/codex-lb/combined-catalog/shared.js +12 -0
  60. package/dist/core/codex-lb/combined-catalog/storage.js +171 -0
  61. package/dist/core/codex-lb/combined-catalog.js +12 -0
  62. package/dist/core/codex-lb/desktop-bridge/client.js +4 -1
  63. package/dist/core/codex-lb/desktop-bridge/header-policy.js +48 -63
  64. package/dist/core/codex-lb/desktop-bridge/http-forward.js +115 -83
  65. package/dist/core/codex-lb/desktop-bridge/launchd.js +20 -13
  66. package/dist/core/codex-lb/desktop-bridge/location-rewrite.js +4 -1
  67. package/dist/core/codex-lb/desktop-bridge/security.js +381 -267
  68. package/dist/core/codex-lb/desktop-bridge/server.js +148 -19
  69. package/dist/core/codex-lb/desktop-bridge/state.js +56 -70
  70. package/dist/core/codex-lb/desktop-bridge/types.js +6 -1
  71. package/dist/core/codex-lb/desktop-bridge/websocket-forward.js +281 -106
  72. package/dist/core/codex-lb/desktop-bridge-migration/historical-config.js +245 -0
  73. package/dist/core/codex-lb/desktop-bridge-migration/historical-toml.js +56 -0
  74. package/dist/core/codex-lb/desktop-bridge-migration/metadata.js +73 -0
  75. package/dist/core/codex-lb/desktop-bridge-migration/receipt.js +52 -0
  76. package/dist/core/codex-lb/desktop-bridge-migration/retired-runtime-cleanup.js +106 -0
  77. package/dist/core/codex-lb/desktop-bridge-migration/types.js +1 -0
  78. package/dist/core/codex-lb/desktop-bridge-migration.js +238 -0
  79. package/dist/core/codex-lb/desktop-controller-v3/catalog.js +257 -0
  80. package/dist/core/codex-lb/desktop-controller-v3/diagnostics.js +62 -0
  81. package/dist/core/codex-lb/desktop-controller-v3/lifecycle-commands.js +203 -0
  82. package/dist/core/codex-lb/desktop-controller-v3/live-probes.js +293 -0
  83. package/dist/core/codex-lb/desktop-controller-v3/preflight-probes.js +144 -0
  84. package/dist/core/codex-lb/desktop-controller-v3/provider-commands.js +182 -0
  85. package/dist/core/codex-lb/desktop-controller-v3/shared.js +279 -0
  86. package/dist/core/codex-lb/desktop-controller-v3/status.js +269 -0
  87. package/dist/core/codex-lb/desktop-controller-v3/types.js +1 -0
  88. package/dist/core/codex-lb/desktop-controller-v3/verification.js +89 -0
  89. package/dist/core/codex-lb/desktop-controller-v3.js +67 -0
  90. package/dist/core/codex-lb/desktop-controller.js +2 -1730
  91. package/dist/core/codex-lb/desktop-service.js +462 -627
  92. package/dist/core/codex-lb/migration-receipt.js +560 -118
  93. package/dist/core/codex-lb/probes/auxiliary-surfaces-probe.js +37 -53
  94. package/dist/core/codex-lb/probes/bridge-probe.js +125 -64
  95. package/dist/core/codex-lb/probes/catalog-probe.js +36 -136
  96. package/dist/core/codex-lb/probes/computer-use-probe.js +63 -39
  97. package/dist/core/codex-lb/probes/image-generation-probe.js +98 -41
  98. package/dist/core/codex-lb/probes/probe-evidence.js +32 -33
  99. package/dist/core/codex-lb/probes/voice-realtime-probe.js +69 -43
  100. package/dist/core/codex-lb/provider-credentials/configuration.js +127 -0
  101. package/dist/core/codex-lb/provider-credentials/locks.js +11 -0
  102. package/dist/core/codex-lb/provider-credentials/private-snapshot.js +28 -0
  103. package/dist/core/codex-lb/provider-credentials/removal.js +33 -0
  104. package/dist/core/codex-lb/provider-credentials/resolution.js +59 -0
  105. package/dist/core/codex-lb/provider-credentials/runtime.js +55 -0
  106. package/dist/core/codex-lb/provider-credentials/types.js +1 -0
  107. package/dist/core/codex-lb/provider-credentials/validation-store.js +137 -0
  108. package/dist/core/codex-lb/provider-credentials.js +5 -0
  109. package/dist/core/codex-lb/provider-registry.js +323 -0
  110. package/dist/core/codex-lb/provider-route-policy.js +118 -0
  111. package/dist/core/codex-lb/request-route-resolver.js +172 -0
  112. package/dist/core/codex-lb/route-index.js +148 -0
  113. package/dist/core/codex-lb/trusted-deep-evidence.js +158 -286
  114. package/dist/core/commands/basic-cli.js +1 -1
  115. package/dist/core/commands/check-command.js +3 -10
  116. package/dist/core/commands/gate-result-contract.js +10 -14
  117. package/dist/core/commands/intent-normalization/normalizer.js +1 -1
  118. package/dist/core/commands/mad-sks-command.js +2 -6
  119. package/dist/core/commands/release-command.js +11 -1
  120. package/dist/core/commands/telegram-command.js +46 -6
  121. package/dist/core/doctor/doctor-readiness-matrix.js +9 -7
  122. package/dist/core/doctor/skill-legacy-surface.js +5 -5
  123. package/dist/core/evidence/v2/evidence-key.js +30 -3
  124. package/dist/core/feature-fixtures.js +8 -1
  125. package/dist/core/feature-registry.js +3 -2
  126. package/dist/core/hooks-runtime/stop-finalization.js +11 -1
  127. package/dist/core/hooks-runtime/subagent-context.js +15 -1
  128. package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +1 -1
  129. package/dist/core/hooks-runtime/tool-output-quarantine.js +1 -1
  130. package/dist/core/hooks-runtime.js +73 -87
  131. package/dist/core/image-ux-review/imagegen-adapter.js +108 -94
  132. package/dist/core/image-ux-review/real-callout-extractor.js +144 -14
  133. package/dist/core/imagegen/desktop-bridge-imagegen-target.js +77 -0
  134. package/dist/core/imagegen/imagegen-capability.js +43 -151
  135. package/dist/core/init/skills/filesystem.js +89 -0
  136. package/dist/core/init/skills/inventory.js +97 -0
  137. package/dist/core/init/skills/manifest.js +151 -0
  138. package/dist/core/init/skills.js +5 -325
  139. package/dist/core/init.js +0 -63
  140. package/dist/core/install/installed-package-smoke.js +1 -1
  141. package/dist/core/managed-assets/managed-assets-manifest.js +0 -1
  142. package/dist/core/policy/latest-version-guidance.js +15 -2
  143. package/dist/core/preflight/parallel-preflight-engine.js +27 -51
  144. package/dist/core/provider/provider-badge.js +9 -4
  145. package/dist/core/provider/provider-context.js +57 -107
  146. package/dist/core/providers/openrouter/openrouter-account.js +3 -1
  147. package/dist/core/providers/openrouter/openrouter-secret-store.js +91 -22
  148. package/dist/core/release/desktop-bridge-release-evidence.js +457 -0
  149. package/dist/core/release/gate-manifest.js +0 -1
  150. package/dist/core/release/main-push-guard.js +13 -0
  151. package/dist/core/release/main-push-receipt.js +11 -0
  152. package/dist/core/release/physical-release-gates.js +664 -61
  153. package/dist/core/release/publish-preflight.js +3 -3
  154. package/dist/core/release/release-gate-batch-runner.js +19 -6
  155. package/dist/core/release/release-gate-dag.js +33 -6
  156. package/dist/core/release/release-gate-node.js +1 -3
  157. package/dist/core/release/release-gate-output-contract.js +55 -0
  158. package/dist/core/release/release-pack-contract.js +1 -1
  159. package/dist/core/release/release-pack-receipt.js +209 -8
  160. package/dist/core/release/release-real-contract.js +1 -1
  161. package/dist/core/release/stage-publish.js +106 -28
  162. package/dist/core/retention/temp-lease.js +204 -0
  163. package/dist/core/retention.js +18 -195
  164. package/dist/core/routes.js +1 -2
  165. package/dist/core/safety/intent-contract/intent-contract.js +3 -3
  166. package/dist/core/subagents/naruto-host-credentials.js +6 -1
  167. package/dist/core/subagents/official-subagent-config.js +27 -9
  168. package/dist/core/subagents/official-subagent-runner.js +14 -31
  169. package/dist/core/subagents/wave-lifecycle.js +36 -8
  170. package/dist/core/subagents/wave-parent-guidance.js +2 -1
  171. package/dist/core/telegram/doctor.js +2 -2
  172. package/dist/core/telegram/liveness.js +10 -4
  173. package/dist/core/triwiki/context-graph/compiler/index.js +18 -18
  174. package/dist/core/update/update-migration-state/fast-mode-config.js +172 -0
  175. package/dist/core/update/update-migration-state/session-state-split.js +247 -0
  176. package/dist/core/update/update-migration-state/simple-stages.js +46 -0
  177. package/dist/core/update/update-migration-state.js +4 -481
  178. package/dist/core/version.js +1 -1
  179. package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +28 -4
  180. package/dist/native/sks-menubar/Sources/OperationModels.swift +112 -2
  181. package/dist/native/sks-menubar/Sources/ProviderRouteExplanation.swift +21 -0
  182. package/dist/native/sks-menubar/Sources/ProvidersBridgeCatalog.swift +140 -0
  183. package/dist/native/sks-menubar/Sources/ProvidersOpenRouter.swift +107 -470
  184. package/dist/native/sks-menubar/Sources/ProvidersReliability.swift +27 -197
  185. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +335 -269
  186. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +233 -437
  187. package/dist/native/sks-menubar/Sources/RemoteCodingViewController.swift +16 -7
  188. package/dist/native/sks-menubar/Sources/SecureProcessEnvelope.swift +39 -9
  189. package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
  190. package/dist/scripts/canonical-test-runner.js +7 -1
  191. package/dist/scripts/check-runtime-schemas.js +7 -2
  192. package/dist/scripts/codex-sdk-real-smoke-check.js +3 -1
  193. package/dist/scripts/desktop-bridge-capabilities-check.js +123 -0
  194. package/dist/scripts/{codex-lb-desktop-bridge-latency-check.js → desktop-bridge-latency-check.js} +61 -16
  195. package/dist/scripts/desktop-bridge-real-evidence-check.js +64 -0
  196. package/dist/scripts/{codex-lb-desktop-bridge-check.js → desktop-bridge-transport-check.js} +92 -155
  197. package/dist/scripts/desktop-bridge-transport-client.js +116 -0
  198. package/dist/scripts/desktop-bridge-unification-check.js +276 -0
  199. package/dist/scripts/doctor-fixes-codex-app-fast-ui-check.js +12 -8
  200. package/dist/scripts/gate-policy-audit-check.js +52 -2
  201. package/dist/scripts/provider-badge-context-check.js +55 -12
  202. package/dist/scripts/publish-preflight.js +1 -2
  203. package/dist/scripts/release-affected-selector-check.js +1 -2
  204. package/dist/scripts/release-aggressive-resource-governor-check.js +1 -1
  205. package/dist/scripts/release-cache-glob-hashing-check.js +1 -0
  206. package/dist/scripts/release-cache-version-neutral-fixture-check.js +1 -0
  207. package/dist/scripts/release-full-parallelism-blackbox.js +1 -1
  208. package/dist/scripts/release-gate-batch-runner-check.js +9 -0
  209. package/dist/scripts/release-gate-dag-runner-check.js +6 -0
  210. package/dist/scripts/release-gate-dag-runner.js +4 -2
  211. package/dist/scripts/release-metadata-check.js +16 -3
  212. package/dist/scripts/release-pack-receipt.js +29 -6
  213. package/dist/scripts/release-physical-gates-check.js +39 -0
  214. package/dist/scripts/release-real-check.js +7 -5
  215. package/package.json +6 -8
  216. package/release-gates.v2.json +156 -157
  217. package/runtime-required-scripts.json +11 -11
  218. package/schemas/codex/desktop-bridge-status-v3.schema.json +286 -0
  219. package/schemas/codex/desktop-capabilities-v3.schema.json +198 -0
  220. package/schemas/release/release-gate-node.schema.json +2 -3
  221. package/dist/cli/codex-lb-setup-warning-output.js +0 -17
  222. package/dist/cli/install-helpers-codex-lb-chain.js +0 -529
  223. package/dist/commands/codex-lb.js +0 -1232
  224. package/dist/core/architecture-hardening/migration/migration.js +0 -111
  225. package/dist/core/codex-app/auxiliary-oauth-policy.js +0 -36
  226. package/dist/core/codex-app/catalog-compat/catalog-service.js +0 -104
  227. package/dist/core/codex-app/child-policy/child-policy.js +0 -35
  228. package/dist/core/codex-app/desktop-routing-snapshot.js +0 -233
  229. package/dist/core/codex-app/glm-model-profile.js +0 -1
  230. package/dist/core/codex-app/glm-profile-installer.js +0 -191
  231. package/dist/core/codex-app/glm-profile-schema.js +0 -42
  232. package/dist/core/codex-app/multi-provider-router.js +0 -391
  233. package/dist/core/codex-app/openrouter-activate.js +0 -405
  234. package/dist/core/codex-app/openrouter-model-catalog.js +0 -217
  235. package/dist/core/codex-app/provider-child-policy.js +0 -64
  236. package/dist/core/codex-app/provider-mode.js +0 -91
  237. package/dist/core/codex-app/provider-session-policy.js +0 -85
  238. package/dist/core/codex-app/session-policy/session-pinning.js +0 -68
  239. package/dist/core/codex-control/codex-lb-launch-recovery.js +0 -319
  240. package/dist/core/codex-lb/codex-lb-setup.js +0 -293
  241. package/dist/core/codex-lb/codex-lb-tool-catalog.js +0 -456
  242. package/dist/core/codex-lb/codex-lb-tool-output-recovery.js +0 -290
  243. package/dist/core/codex-lb/desktop-center-credentials.js +0 -1083
  244. package/dist/core/codex-lb/desktop-mode.js +0 -32
  245. package/dist/core/codex-lb/desktop-real-evidence.js +0 -168
  246. package/dist/core/codex-lb/legacy-migration.js +0 -576
  247. package/dist/core/codex-lb/native-openai-transport/transport.js +0 -68
  248. package/dist/core/codex-lb/provider-routing/provider-router.js +0 -58
  249. package/dist/core/codex-lb/routing-truth.js +0 -327
  250. package/dist/core/imagegen/codex-lb-imagegen-target.js +0 -92
  251. package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +0 -118
  252. package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +0 -17
  253. package/dist/native/sks-menubar/Sources/ProvidersMultiProvider.swift +0 -331
  254. package/dist/native/sks-menubar/Sources/ProvidersRoleModels.swift +0 -260
  255. package/dist/scripts/codex-lb-catalog-passthrough-check.js +0 -120
  256. package/dist/scripts/codex-lb-desktop-auth-invariant-check.js +0 -169
  257. package/dist/scripts/codex-lb-desktop-capabilities-check.js +0 -287
  258. package/dist/scripts/codex-lb-desktop-real-evidence-check.js +0 -123
  259. package/dist/scripts/codex-lb-fast-mode-truth-check.js +0 -114
  260. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +0 -152
  261. package/dist/scripts/codex-lb-gpt56-fast-profile-check.js +0 -231
@@ -1,529 +0,0 @@
1
- import path from 'node:path';
2
- import os from 'node:os';
3
- import fsp from 'node:fs/promises';
4
- import { ensureDir, packageRoot, readText, writeTextAtomic } from '../core/fsx.js';
5
- import { recordCodexLbHealthEvent } from '../core/codex-lb-circuit.js';
6
- import { codexLbBaseUrlSecurityBlocker } from '../core/codex-lb/codex-lb-env.js';
7
- import { probeEvidence } from '../core/codex-lb/probes/probe-evidence.js';
8
- import { CODEX_LB_CANONICAL_FAST_SERVICE_TIER, codexLbEnvPath, parseCodexLbEnvKey, redactSecretText } from './install-helpers-codex-lb-shared.js';
9
- function codexLbResponsesEndpoint(baseUrl = '') {
10
- const base = String(baseUrl || '').trim().replace(/\/+$/, '');
11
- if (!base)
12
- return '';
13
- return /\/responses$/i.test(base) ? base : `${base}/responses`;
14
- }
15
- function codexLbChainCheckEnabled(env = process.env) {
16
- return env.SKS_CODEX_LB_CHAIN_CHECK !== '0' && env.SKS_SKIP_CODEX_LB_CHAIN_CHECK !== '1';
17
- }
18
- function codexLbChainCachePath(home = process.env.HOME || os.homedir()) {
19
- return path.join(home, '.codex', 'sks-codex-lb-chain-health.json');
20
- }
21
- function codexLbChainCacheTtlMs(status = '', env = process.env) {
22
- const hardFailure = Boolean(status && !['chain_ok', 'previous_response_not_found'].includes(status));
23
- const key = hardFailure ? 'SKS_CODEX_LB_CHAIN_CHECK_FAILURE_CACHE_TTL_MS' : 'SKS_CODEX_LB_CHAIN_CHECK_CACHE_TTL_MS';
24
- const fallback = hardFailure ? 30 * 1000 : 5 * 60 * 1000;
25
- const raw = env[key] ?? env.SKS_CODEX_LB_CHAIN_CHECK_CACHE_TTL_MS;
26
- if (raw === undefined || raw === '')
27
- return fallback;
28
- const parsed = Number(raw);
29
- return Number.isFinite(parsed) ? Math.max(0, parsed) : fallback;
30
- }
31
- function codexLbChainCacheEnabled(opts = {}, env = process.env) {
32
- if (opts.force || opts.cache === false)
33
- return false;
34
- if (opts.fetch)
35
- return false;
36
- if (env.SKS_CODEX_LB_CHAIN_CHECK_CACHE === '0')
37
- return false;
38
- return true;
39
- }
40
- async function readCodexLbChainCache({ endpoint, home, opts = {}, env = process.env } = {}) {
41
- if (!endpoint || !codexLbChainCacheEnabled(opts, env))
42
- return null;
43
- const cachePath = opts.cachePath || codexLbChainCachePath(home || env.HOME || os.homedir());
44
- const text = await readText(cachePath, '');
45
- if (!text.trim())
46
- return null;
47
- try {
48
- const parsed = JSON.parse(text);
49
- if (parsed?.schema !== 'sks.codex-lb-chain-health.v1' || parsed.endpoint !== endpoint || !parsed.result?.status)
50
- return null;
51
- const now = typeof opts.now === 'function' ? opts.now() : Date.now();
52
- const checkedAt = Number(parsed.checked_at_ms || 0);
53
- const ttlMs = codexLbChainCacheTtlMs(parsed.result.status, env);
54
- if (!checkedAt || ttlMs <= 0 || now - checkedAt > ttlMs)
55
- return null;
56
- return {
57
- ...parsed.result,
58
- endpoint,
59
- cached: true,
60
- cache_path: cachePath,
61
- cache_age_ms: Math.max(0, now - checkedAt)
62
- };
63
- }
64
- catch {
65
- return null;
66
- }
67
- }
68
- async function writeCodexLbChainCache(result = {}, { endpoint, home, opts = {}, env = process.env } = {}) {
69
- if (!endpoint || !result.status || !codexLbChainCacheEnabled(opts, env))
70
- return result;
71
- const cachePath = opts.cachePath || codexLbChainCachePath(home || env.HOME || os.homedir());
72
- const now = typeof opts.now === 'function' ? opts.now() : Date.now();
73
- const cacheResult = {
74
- ok: Boolean(result.ok),
75
- status: result.status,
76
- chain_unhealthy: result.chain_unhealthy === true,
77
- http_status: result.http_status || null,
78
- error: result.error || null
79
- };
80
- try {
81
- await ensureDir(path.dirname(cachePath));
82
- await writeTextAtomic(cachePath, `${JSON.stringify({
83
- schema: 'sks.codex-lb-chain-health.v1',
84
- endpoint,
85
- checked_at_ms: now,
86
- result: cacheResult
87
- }, null, 2)}\n`);
88
- await fsp.chmod(cachePath, 0o600).catch(() => { });
89
- }
90
- catch {
91
- }
92
- return result;
93
- }
94
- function isPreviousResponseNotFound(payload = {}) {
95
- const error = payload?.error || payload?.response?.error || payload;
96
- const text = typeof error === 'string'
97
- ? error
98
- : [error?.type, error?.code, error?.message, error?.param, JSON.stringify(error || {})].filter(Boolean).join(' ');
99
- return /previous_response_not_found|previous_response_id.*not found|previous_response_id/i.test(text);
100
- }
101
- function parseCodexLbSseEvents(text = '') {
102
- const events = [];
103
- for (const line of String(text || '').split(/\r?\n/)) {
104
- if (!line.startsWith('data:'))
105
- continue;
106
- const data = line.slice(5).trim();
107
- if (!data || data === '[DONE]')
108
- continue;
109
- try {
110
- events.push(JSON.parse(data));
111
- }
112
- catch { }
113
- }
114
- return events;
115
- }
116
- function codexLbResponseId(payload = {}) {
117
- if (typeof payload?.id === 'string' && payload.id)
118
- return payload.id;
119
- if (typeof payload?.response?.id === 'string' && payload.response.id)
120
- return payload.response.id;
121
- if (typeof payload?.data?.id === 'string' && payload.data.id)
122
- return payload.data.id;
123
- if (typeof payload?.data?.response?.id === 'string' && payload.data.response.id)
124
- return payload.data.response.id;
125
- return null;
126
- }
127
- function codexLbResponseError(json, events = []) {
128
- if (json?.error)
129
- return json;
130
- for (const event of events) {
131
- if (event?.error || event?.response?.error || event?.type === 'response.failed' || event?.type === 'error')
132
- return event;
133
- }
134
- return null;
135
- }
136
- function codexLbServiceTierEvidence(...responses) {
137
- const values = [];
138
- const visit = (value) => {
139
- if (!value || typeof value !== 'object')
140
- return;
141
- values.push(value);
142
- if (Array.isArray(value)) {
143
- for (const item of value)
144
- visit(item);
145
- return;
146
- }
147
- for (const child of Object.values(value))
148
- visit(child);
149
- };
150
- for (const response of responses) {
151
- visit(response?.json);
152
- visit(response?.events);
153
- }
154
- const firstString = (...keys) => {
155
- for (const row of values) {
156
- for (const key of keys) {
157
- const value = row?.[key];
158
- if (typeof value === 'string' && value.trim())
159
- return value.trim().toLowerCase();
160
- }
161
- }
162
- return null;
163
- };
164
- const requested = firstString('requestedServiceTier', 'requested_service_tier', 'requested_serviceTier');
165
- const actual = firstString('actualServiceTier', 'actual_service_tier', 'actual_serviceTier');
166
- const effective = firstString('serviceTier', 'service_tier');
167
- return {
168
- requested_service_tier: requested,
169
- actual_service_tier: actual,
170
- effective_service_tier: effective,
171
- fast_requested: requested === CODEX_LB_CANONICAL_FAST_SERVICE_TIER || effective === CODEX_LB_CANONICAL_FAST_SERVICE_TIER,
172
- fast_actual: actual === CODEX_LB_CANONICAL_FAST_SERVICE_TIER || effective === CODEX_LB_CANONICAL_FAST_SERVICE_TIER
173
- };
174
- }
175
- function codexLbGatewayHeaders(apiKey, authTransport = 'authorization-bearer-compat') {
176
- const credentialHeader = authTransport === 'x-codex-lb-api-key'
177
- ? { 'X-Codex-LB-API-Key': String(apiKey) }
178
- : { authorization: `Bearer ${String(apiKey)}` };
179
- return { ...credentialHeader, 'content-type': 'application/json' };
180
- }
181
- async function fetchCodexLbResponse(fetchImpl, endpoint, apiKey, body, timeoutMs, authTransport = 'authorization-bearer-compat') {
182
- const controller = new AbortController();
183
- const timer = setTimeout(() => controller.abort(), timeoutMs).unref?.();
184
- try {
185
- const response = await fetchImpl(endpoint, {
186
- method: 'POST',
187
- headers: codexLbGatewayHeaders(apiKey, authTransport),
188
- body: JSON.stringify(body),
189
- redirect: 'error',
190
- signal: controller.signal
191
- });
192
- const text = await response.text();
193
- let json = null;
194
- try {
195
- json = text ? JSON.parse(text) : null;
196
- }
197
- catch { }
198
- const events = json ? [] : parseCodexLbSseEvents(text);
199
- const responseId = codexLbResponseId(json) || events.map((event) => codexLbResponseId(event)).find(Boolean) || null;
200
- const errorPayload = codexLbResponseError(json, events);
201
- return { ok: response.ok && !errorPayload, status: response.status, json, text, events, response_id: responseId, error_payload: errorPayload };
202
- }
203
- catch (err) {
204
- return { ok: false, status: 0, json: null, text: err.name === 'AbortError' ? 'request timed out' : err.message, events: [], response_id: null, error_payload: null };
205
- }
206
- finally {
207
- clearTimeout(timer);
208
- }
209
- }
210
- const CODEX_LB_CONNECT_TEST_MAX_OUTPUT_TOKENS = 32;
211
- const CODEX_LB_CONNECT_TEST_MAX_RESULT_CHARS = 256;
212
- const CODEX_LB_CONNECT_TEST_MAX_ERROR_CHARS = 512;
213
- const CODEX_LB_CONNECT_TEST_TIMEOUT_MS = 15_000;
214
- function boundedText(value, maxChars) {
215
- const text = String(value || '').trim();
216
- return text.length <= maxChars ? text : text.slice(0, maxChars);
217
- }
218
- function codexLbCompletedResponse(json, events = []) {
219
- if (json?.response && typeof json.response === 'object')
220
- return json.response;
221
- if (json?.data?.response && typeof json.data.response === 'object')
222
- return json.data.response;
223
- if (json?.data && typeof json.data === 'object')
224
- return json.data;
225
- if (json && typeof json === 'object')
226
- return json;
227
- for (let index = events.length - 1; index >= 0; index -= 1) {
228
- const event = events[index];
229
- if (event?.type === 'response.completed' && event?.response && typeof event.response === 'object') {
230
- return event.response;
231
- }
232
- }
233
- return null;
234
- }
235
- function codexLbOutputText(response, events = []) {
236
- const parts = [];
237
- for (const output of Array.isArray(response?.output) ? response.output : []) {
238
- for (const content of Array.isArray(output?.content) ? output.content : []) {
239
- if (content?.type === 'output_text' && typeof content.text === 'string' && content.text.trim()) {
240
- parts.push(content.text.trim());
241
- }
242
- }
243
- }
244
- if (parts.length === 0) {
245
- for (const event of events) {
246
- if (event?.type === 'response.output_text.done' && typeof event.text === 'string' && event.text.trim()) {
247
- parts.push(event.text.trim());
248
- }
249
- }
250
- }
251
- return parts.join('\n').trim();
252
- }
253
- function boundedCodexLbUsage(usage) {
254
- const tokenCount = (value) => Number.isSafeInteger(value) && value >= 0 ? value : null;
255
- return {
256
- input_tokens: tokenCount(usage?.input_tokens),
257
- output_tokens: tokenCount(usage?.output_tokens),
258
- total_tokens: tokenCount(usage?.total_tokens),
259
- reasoning_tokens: tokenCount(usage?.output_tokens_details?.reasoning_tokens)
260
- };
261
- }
262
- function codexLbConnectTestFailure(status, extra = {}) {
263
- return {
264
- schema: 'sks.codex-lb-connect-test.v1',
265
- ok: false,
266
- status,
267
- response_id: null,
268
- model: extra.model || null,
269
- latency_ms: extra.latency_ms ?? null,
270
- usage: extra.usage || null,
271
- result: null,
272
- result_truncated: false,
273
- http_status: extra.http_status ?? null,
274
- blockers: Array.isArray(extra.blockers) ? extra.blockers : [status],
275
- ...(extra.error ? { error: extra.error } : {})
276
- };
277
- }
278
- export async function testCodexLbConnection(status = {}, opts = {}) {
279
- const providerSelected = status?.selected === true || status?.provider?.selected === true;
280
- if (opts.requireSelected === true && !providerSelected) {
281
- return codexLbConnectTestFailure('provider_unselected', {
282
- blockers: ['codex_lb_provider_not_selected']
283
- });
284
- }
285
- const credentialBindingBlockers = Array.isArray(opts.credentialBindingBlockers)
286
- ? opts.credentialBindingBlockers.map((value) => boundedText(value, 128)).filter(Boolean)
287
- : [];
288
- if (credentialBindingBlockers.length > 0) {
289
- return codexLbConnectTestFailure('credential_binding_drift', { blockers: credentialBindingBlockers });
290
- }
291
- if (status.provider_base_url_matches_credential !== true) {
292
- return codexLbConnectTestFailure('provider_base_url_mismatch', {
293
- blockers: ['codex_lb_provider_base_url_mismatch']
294
- });
295
- }
296
- if (status.provider_contract_ok !== true) {
297
- return codexLbConnectTestFailure('provider_contract_drift', {
298
- blockers: ['codex_lb_provider_contract_drift']
299
- });
300
- }
301
- const baseUrl = opts.baseUrl || status.base_url;
302
- const endpoint = codexLbResponsesEndpoint(baseUrl);
303
- if (!endpoint)
304
- return codexLbConnectTestFailure('missing_base_url');
305
- const transportBlocker = codexLbBaseUrlSecurityBlocker(baseUrl);
306
- if (transportBlocker)
307
- return codexLbConnectTestFailure('transport_blocked', { blockers: [transportBlocker] });
308
- const env = opts.env || process.env;
309
- const home = opts.home || env.HOME || os.homedir();
310
- const apiKey = opts.apiKey || parseCodexLbEnvKey(await readText(opts.envPath || status.env_path || codexLbEnvPath(home), ''));
311
- if (!apiKey)
312
- return codexLbConnectTestFailure('missing_env_key');
313
- const model = String(opts.model || env.SKS_CODEX_MODEL || env.CODEX_MODEL || '').trim();
314
- if (!model)
315
- return codexLbConnectTestFailure('model_unselected');
316
- if (model.length > 128)
317
- return codexLbConnectTestFailure('model_invalid');
318
- const fetchImpl = opts.fetch || globalThis.fetch;
319
- if (typeof fetchImpl !== 'function')
320
- return codexLbConnectTestFailure('fetch_unavailable', { model });
321
- const timeoutMs = Number(opts.timeoutMs || env.SKS_CODEX_LB_CONNECT_TEST_TIMEOUT_MS || CODEX_LB_CONNECT_TEST_TIMEOUT_MS);
322
- const body = {
323
- model,
324
- input: 'Reply OK.',
325
- store: false,
326
- reasoning: { effort: 'low' },
327
- max_output_tokens: CODEX_LB_CONNECT_TEST_MAX_OUTPUT_TOKENS
328
- };
329
- const nowMs = typeof opts.nowMs === 'function' ? opts.nowMs : Date.now;
330
- const startedAt = nowMs();
331
- const fetched = await fetchCodexLbResponse(fetchImpl, endpoint, apiKey, body, timeoutMs, opts.gatewayAuthTransport);
332
- const latencyMs = Math.max(0, Math.round(nowMs() - startedAt));
333
- if (!fetched.ok) {
334
- const error = redactSecretText(fetched.error_payload?.error?.message
335
- || fetched.error_payload?.response?.error?.message
336
- || fetched.text
337
- || 'codex-lb Responses request failed', [apiKey]);
338
- return codexLbConnectTestFailure('request_failed', {
339
- model,
340
- latency_ms: latencyMs,
341
- http_status: fetched.status,
342
- error: boundedText(error, CODEX_LB_CONNECT_TEST_MAX_ERROR_CHARS)
343
- });
344
- }
345
- const response = codexLbCompletedResponse(fetched.json, fetched.events);
346
- const responseId = boundedText(codexLbResponseId(response), 128);
347
- const responseModel = boundedText(response?.model || model, 128);
348
- const usage = boundedCodexLbUsage(response?.usage);
349
- if (!responseId) {
350
- return codexLbConnectTestFailure('missing_response_id', {
351
- model: responseModel,
352
- latency_ms: latencyMs,
353
- http_status: fetched.status,
354
- usage
355
- });
356
- }
357
- if (response?.error) {
358
- return codexLbConnectTestFailure('response_error', {
359
- model: responseModel,
360
- latency_ms: latencyMs,
361
- http_status: fetched.status,
362
- usage,
363
- error: boundedText(redactSecretText(response.error?.message || response.error, [apiKey]), CODEX_LB_CONNECT_TEST_MAX_ERROR_CHARS)
364
- });
365
- }
366
- if (response?.status !== 'completed') {
367
- return codexLbConnectTestFailure('response_not_completed', {
368
- model: responseModel,
369
- latency_ms: latencyMs,
370
- http_status: fetched.status,
371
- usage
372
- });
373
- }
374
- const outputText = codexLbOutputText(response, fetched.events);
375
- if (!outputText) {
376
- return codexLbConnectTestFailure('empty_result', {
377
- model: responseModel,
378
- latency_ms: latencyMs,
379
- http_status: fetched.status,
380
- usage
381
- });
382
- }
383
- return {
384
- schema: 'sks.codex-lb-connect-test.v1',
385
- ok: true,
386
- status: 'connected',
387
- response_id: responseId,
388
- model: responseModel,
389
- latency_ms: latencyMs,
390
- usage,
391
- result: boundedText(outputText, CODEX_LB_CONNECT_TEST_MAX_RESULT_CHARS),
392
- result_truncated: outputText.length > CODEX_LB_CONNECT_TEST_MAX_RESULT_CHARS,
393
- http_status: fetched.status,
394
- blockers: []
395
- };
396
- }
397
- export async function checkCodexLbResponseChain(status = {}, opts = {}) {
398
- const env = opts.env || process.env;
399
- if (!codexLbChainCheckEnabled(env) && !opts.force)
400
- return { ok: true, status: 'skipped', skipped: true, reason: 'SKS_CODEX_LB_CHAIN_CHECK=0' };
401
- if (status.provider_base_url_matches_credential === false) {
402
- return recordCodexLbChainHealth({
403
- ok: false,
404
- status: 'provider_base_url_mismatch',
405
- chain_unhealthy: true,
406
- blockers: ['codex_lb_provider_base_url_mismatch'],
407
- error: 'codex_lb_provider_base_url_mismatch'
408
- }, opts);
409
- }
410
- const baseUrl = opts.baseUrl || status.base_url;
411
- const endpoint = codexLbResponsesEndpoint(baseUrl);
412
- if (!endpoint)
413
- return recordCodexLbChainHealth({ ok: false, status: 'missing_base_url', chain_unhealthy: true }, opts);
414
- const transportBlocker = codexLbBaseUrlSecurityBlocker(baseUrl);
415
- if (transportBlocker) {
416
- return recordCodexLbChainHealth({
417
- ok: false,
418
- status: 'transport_blocked',
419
- chain_unhealthy: true,
420
- endpoint,
421
- blockers: [transportBlocker],
422
- error: transportBlocker
423
- }, opts);
424
- }
425
- const home = opts.home || env.HOME || os.homedir();
426
- const apiKey = opts.apiKey || parseCodexLbEnvKey(await readText(opts.envPath || status.env_path || codexLbEnvPath(home), ''));
427
- if (!apiKey)
428
- return recordCodexLbChainHealth({ ok: false, status: 'missing_env_key', chain_unhealthy: true }, opts);
429
- const cached = await readCodexLbChainCache({ endpoint, home, opts, env });
430
- if (cached)
431
- return cached;
432
- const fetchImpl = opts.fetch || globalThis.fetch;
433
- if (typeof fetchImpl !== 'function')
434
- return { ok: true, status: 'skipped', skipped: true, reason: 'fetch unavailable' };
435
- const model = String(opts.model || env.SKS_CODEX_MODEL || env.CODEX_MODEL || '').trim();
436
- if (!model)
437
- return { ok: true, status: 'skipped', skipped: true, reason: 'model_unselected_use_explicit_model_or_codex_catalog' };
438
- const timeoutMs = Number(opts.timeoutMs || env.SKS_CODEX_LB_CHAIN_CHECK_TIMEOUT_MS || 8000);
439
- const gatewayAuthTransport = opts.gatewayAuthTransport || 'authorization-bearer-compat';
440
- const serviceTier = opts.fastMode === true || opts.serviceTier === 'fast' || opts.serviceTier === CODEX_LB_CANONICAL_FAST_SERVICE_TIER
441
- ? CODEX_LB_CANONICAL_FAST_SERVICE_TIER
442
- : null;
443
- const baseBody = {
444
- model,
445
- instructions: 'You are running a short SKS codex-lb response-chain health check.',
446
- input: 'SKS codex-lb response-chain health check. Reply with OK.',
447
- ...(serviceTier ? { service_tier: serviceTier } : {}),
448
- stream: true,
449
- store: true,
450
- parallel_tool_calls: false,
451
- tool_choice: 'auto',
452
- reasoning: { effort: 'low' }
453
- };
454
- const first = await fetchCodexLbResponse(fetchImpl, endpoint, apiKey, baseBody, timeoutMs, gatewayAuthTransport);
455
- if (!first.ok || !first.response_id) {
456
- return recordCodexLbChainHealth(await writeCodexLbChainCache({
457
- ok: false,
458
- status: first.ok ? 'missing_response_id' : 'first_request_failed',
459
- chain_unhealthy: true,
460
- endpoint,
461
- http_status: first.status,
462
- requested_service_tier: serviceTier,
463
- service_tier_evidence: codexLbServiceTierEvidence(first),
464
- error: redactSecretText(first.error_payload?.error?.message || first.error_payload?.response?.error?.message || first.text || 'codex-lb first Responses request failed', [apiKey])
465
- }, { endpoint, home, opts, env }), opts);
466
- }
467
- const second = await fetchCodexLbResponse(fetchImpl, endpoint, apiKey, { ...baseBody, previous_response_id: first.response_id }, timeoutMs, gatewayAuthTransport);
468
- if (second.ok)
469
- return recordCodexLbChainHealth(await writeCodexLbChainCache({ ok: true, status: 'chain_ok', endpoint, response_id: first.response_id, chained_response_id: second.response_id || null, http_status: second.status, requested_service_tier: serviceTier, service_tier_evidence: codexLbServiceTierEvidence(first, second) }, { endpoint, home, opts, env }), opts);
470
- const previousMissing = isPreviousResponseNotFound(second.error_payload || second.json || second.text);
471
- return recordCodexLbChainHealth(await writeCodexLbChainCache({
472
- ok: false,
473
- status: previousMissing ? 'previous_response_not_found' : 'second_request_failed',
474
- chain_unhealthy: true,
475
- endpoint,
476
- response_id: first.response_id,
477
- http_status: second.status,
478
- requested_service_tier: serviceTier,
479
- service_tier_evidence: codexLbServiceTierEvidence(first, second),
480
- error: redactSecretText(second.error_payload?.error?.message || second.error_payload?.response?.error?.message || second.text || 'codex-lb chained Responses request failed', [apiKey])
481
- }, { endpoint, home, opts, env }), opts);
482
- }
483
- export async function runCodexLbTextResponsesProbe(status = {}, opts = {}) {
484
- const result = await checkCodexLbResponseChain(status, opts);
485
- return codexLbResponseChainCapabilityEvidence(result, {
486
- checkedAt: typeof opts.nowIso === 'function' ? opts.nowIso() : new Date().toISOString()
487
- });
488
- }
489
- export function codexLbResponseChainCapabilityEvidence(result = {}, opts = {}) {
490
- const checkedAt = opts.checkedAt || new Date().toISOString();
491
- if (result?.skipped === true || result?.status === 'skipped') {
492
- return probeEvidence({
493
- skipped: true,
494
- source: 'config',
495
- evidence: {
496
- probe: 'text_responses',
497
- status: result?.status || 'skipped',
498
- reason: result?.reason || null
499
- }
500
- }, checkedAt);
501
- }
502
- const verified = result?.ok === true && result?.status === 'chain_ok';
503
- const blockers = verified
504
- ? []
505
- : [
506
- ...(Array.isArray(result?.blockers) ? result.blockers : []),
507
- `text_responses_${String(result?.status || 'probe_failed')}`
508
- ];
509
- return probeEvidence({
510
- attempted: true,
511
- verified,
512
- source: 'transport',
513
- blockers,
514
- evidence: {
515
- probe: 'text_responses',
516
- status: result?.status || null,
517
- cached: result?.cached === true,
518
- http_status: result?.http_status || null,
519
- response_chain_completed: verified,
520
- service_tier: result?.service_tier_evidence || null
521
- }
522
- }, checkedAt);
523
- }
524
- async function recordCodexLbChainHealth(result, opts = {}) {
525
- if (!result || result.skipped || opts.recordCircuit === false)
526
- return result;
527
- await recordCodexLbHealthEvent(opts.root || packageRoot(), result).catch(() => null);
528
- return result;
529
- }