@ornexus/neocortex 4.60.73 → 4.60.74

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 (241) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -212
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -358
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +143 -7200
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -156
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  75. package/packages/client/dist/config/profile-directory.js +1 -13
  76. package/packages/client/dist/config/resolver-selection.js +1 -278
  77. package/packages/client/dist/config/secure-config.js +12 -281
  78. package/packages/client/dist/config.js +2 -223
  79. package/packages/client/dist/constants.js +1 -25
  80. package/packages/client/dist/context/context-collector.js +2 -222
  81. package/packages/client/dist/context/context-sanitizer.js +1 -145
  82. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  83. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  84. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  85. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  86. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  87. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  88. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  89. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  90. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  91. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  92. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  93. package/packages/client/dist/continuity/outbox.js +1 -117
  94. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  95. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  96. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  97. package/packages/client/dist/errors/error-messages.js +2 -228
  98. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  99. package/packages/client/dist/evidence/collector.js +1 -347
  100. package/packages/client/dist/evidence/index.js +1 -1
  101. package/packages/client/dist/evidence/types.js +0 -2
  102. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  103. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  104. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  105. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  106. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  107. package/packages/client/dist/git/epic-operational-state.js +2 -672
  108. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  109. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  110. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  111. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  112. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  113. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  114. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  115. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  116. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  117. package/packages/client/dist/i18n/first-run.js +2 -60
  118. package/packages/client/dist/index.js +1 -47
  119. package/packages/client/dist/invocation/invoke-input.js +1 -24
  120. package/packages/client/dist/license/index.js +1 -5
  121. package/packages/client/dist/license/license-client.js +1 -304
  122. package/packages/client/dist/machine/fingerprint.js +2 -163
  123. package/packages/client/dist/machine/index.js +1 -5
  124. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  125. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  126. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  127. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  128. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  129. package/packages/client/dist/migrations/project-identity.js +7 -493
  130. package/packages/client/dist/migrations/state-json.js +4 -393
  131. package/packages/client/dist/policy/architecture-policy.js +2 -184
  132. package/packages/client/dist/policy/index.js +1 -7
  133. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  134. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  135. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  136. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  137. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  138. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  139. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  140. package/packages/client/dist/private-execution/delivery.js +13 -410
  141. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  142. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  143. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  144. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  145. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  146. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  147. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  148. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  149. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  150. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  151. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  152. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  153. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  154. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  155. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  156. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  157. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  158. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  159. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  160. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  161. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  162. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  163. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  164. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  165. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  166. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  167. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  168. package/packages/client/dist/private-execution/session-lease.js +1 -63
  169. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  170. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  171. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  172. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  173. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  174. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  175. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  176. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  177. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  178. package/packages/client/dist/resilience/index.js +1 -8
  179. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  180. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  181. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  182. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  183. package/packages/client/dist/runner/binary.js +1 -404
  184. package/packages/client/dist/runner/cli.js +17 -1571
  185. package/packages/client/dist/runner/headless/adapters.js +1 -49
  186. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  187. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  188. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  189. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  190. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  191. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  192. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  193. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +18 -2
  194. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  195. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  196. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  197. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  198. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  199. package/packages/client/dist/runner/headless/resolver.js +1 -231
  200. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  201. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  202. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  203. package/packages/client/dist/runner/headless/types.js +2 -574
  204. package/packages/client/dist/runner/local-console.js +13 -396
  205. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  206. package/packages/client/dist/runner/project-identity.js +1 -106
  207. package/packages/client/dist/runner/scheduler.js +7 -995
  208. package/packages/client/dist/runner-cli.js +2 -18
  209. package/packages/client/dist/state/invocation-shape.js +1 -13
  210. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  211. package/packages/client/dist/state/state-json-repair.js +3 -785
  212. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  213. package/packages/client/dist/telemetry/index.js +1 -5
  214. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  215. package/packages/client/dist/tier/index.js +1 -5
  216. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  217. package/packages/client/dist/types/index.js +1 -38
  218. package/packages/client/dist/version.js +1 -27
  219. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  220. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  221. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  222. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  223. package/packages/client/dist/yoloop/index.js +1 -8
  224. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  225. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  226. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  227. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  228. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  229. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  230. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  231. package/targets-stubs/antigravity/gemini.md +1 -1
  232. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  233. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  234. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  235. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  236. package/targets-stubs/claude-code/neocortex.md +2 -2
  237. package/targets-stubs/codex/AGENTS.md +1 -1
  238. package/targets-stubs/cursor/agent.md +2 -2
  239. package/targets-stubs/gemini-cli/agent.md +2 -2
  240. package/targets-stubs/opencode/neocortex-root.md +1 -1
  241. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,145 +1,2 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.04 -- trusted OpenCode headless adapter interface.
6
- */
7
- import { checkTrustedHeadlessRuntimeBinary } from '../binary.js';
8
- import { HEADLESS_REASON_CODES, adapterAvailabilityFailure, adapterAvailabilitySuccess, createRejectedExecutionResult, createUnavailableExecutionResult, hashPublicValue, normalizeHeadlessCommandResult, redaction, runHeadlessCommand, validateHeadlessAdapterExecutionInput, } from './types.js';
9
- import { governedPreflightFailureResult, preflightManagedHeadlessProfile, withGovernedHeadlessEvidence, } from './managed-profile.js';
10
- const OPENCODE_ADAPTER_ID = 'opencode';
11
- const OPENCODE_COMMAND = 'opencode';
12
- const OPENCODE_AGENT_PROFILE = 'neocortex';
13
- const VERSION_EVIDENCE_MAX_CHARS = 2_000;
14
- const VERSION_EVIDENCE_MAX_BYTES = 2_000;
15
- const UNSAFE_VERSION_EVIDENCE_PATTERN = /(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i;
16
- const CLAUDE_CODE_PRODUCT_PATTERN = /\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i;
17
- const VERSION_SEMVER_PATTERN = /\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;
18
- export function createOpenCodeHeadlessAdapter() {
19
- return {
20
- id: OPENCODE_ADAPTER_ID,
21
- displayName: 'OpenCode Headless Adapter',
22
- async checkAvailability(options = {}) {
23
- return checkRuntimeAvailability(OPENCODE_ADAPTER_ID, OPENCODE_COMMAND, options, {
24
- realpathBasenamePolicy: 'opencode-npm-native',
25
- });
26
- },
27
- buildInvocation(input) {
28
- const validation = validateHeadlessAdapterExecutionInput(input, OPENCODE_ADAPTER_ID);
29
- if (!validation.ok)
30
- return validation;
31
- return {
32
- ok: true,
33
- invocation: {
34
- adapterId: OPENCODE_ADAPTER_ID,
35
- commandName: OPENCODE_COMMAND,
36
- args: buildOpenCodeArgs(validation.prompt, validation.input.modelId),
37
- promptHash: validation.promptHash,
38
- ...(validation.input.modelId ? { modelId: validation.input.modelId } : {}),
39
- timeoutMs: validation.input.timeoutMs ?? 10 * 60 * 1000,
40
- publicSafe: true,
41
- },
42
- publicSafe: true,
43
- };
44
- },
45
- async execute(input, options = {}) {
46
- const validation = validateHeadlessAdapterExecutionInput(input, OPENCODE_ADAPTER_ID);
47
- if (!validation.ok)
48
- return createRejectedExecutionResult(OPENCODE_ADAPTER_ID, OPENCODE_ADAPTER_ID, validation);
49
- const preflight = preflightManagedHeadlessProfile(OPENCODE_ADAPTER_ID, options);
50
- if (!preflight.ok)
51
- return governedPreflightFailureResult(OPENCODE_ADAPTER_ID, validation.input, preflight);
52
- if (options.signal?.aborted) {
53
- return withGovernedHeadlessEvidence(normalizeHeadlessCommandResult(OPENCODE_ADAPTER_ID, validation.input, {
54
- exitCode: null, signal: 'SIGTERM', timedOut: false, cancelled: true, durationMs: 0,
55
- stdout: '', stderr: '', stdoutBytes: 0, stderrBytes: 0,
56
- }));
57
- }
58
- const availability = await this.checkAvailability(options);
59
- if (!availability.ok)
60
- return withGovernedHeadlessEvidence(createUnavailableExecutionResult(OPENCODE_ADAPTER_ID, validation.input, availability));
61
- const invocation = this.buildInvocation(validation.input);
62
- if (!invocation.ok)
63
- return createRejectedExecutionResult(OPENCODE_ADAPTER_ID, OPENCODE_ADAPTER_ID, invocation);
64
- const runner = options.commandRunner ?? runHeadlessCommand;
65
- const result = await runner(availability.executablePath ?? OPENCODE_COMMAND, invocation.invocation.args, {
66
- cwd: options.cwd,
67
- env: options.env,
68
- timeoutMs: invocation.invocation.timeoutMs,
69
- maxOutputBytes: options.maxOutputBytes,
70
- signal: options.signal,
71
- ...(validation.input.receipt?.jobId ? { localConsole: { projectRoot: options.cwd, jobId: validation.input.receipt.jobId, attemptId: validation.input.receipt.attemptId, executionId: validation.input.receipt.executionId, publicSafe: true } } : {}),
72
- });
73
- return withGovernedHeadlessEvidence(normalizeHeadlessCommandResult(OPENCODE_ADAPTER_ID, validation.input, result));
74
- },
75
- };
76
- }
77
- export async function checkRuntimeAvailability(adapterId, commandName, options, policy = {}) {
78
- const trust = checkTrustedHeadlessRuntimeBinary({
79
- commandName,
80
- env: options.env,
81
- platform: options.platform,
82
- commandLocator: options.commandLocator,
83
- realpathBasenamePolicy: policy.realpathBasenamePolicy,
84
- });
85
- if (!trust.ok) {
86
- return adapterAvailabilityFailure(adapterId, commandName, trust.reasonCode === HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE
87
- ? HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE
88
- : HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED, trust.publicSummary, trust.redactionSummary);
89
- }
90
- const runner = options.versionRunner ?? options.commandRunner ?? runHeadlessCommand;
91
- const version = await runner(trust.executablePath, ['--version'], {
92
- env: options.env,
93
- timeoutMs: 5_000,
94
- maxOutputBytes: 2_000,
95
- });
96
- const evidence = validateRuntimeVersionEvidence(version, policy.versionEvidence ?? 'generic-public');
97
- if (!evidence.ok) {
98
- return adapterAvailabilityFailure(adapterId, commandName, HEADLESS_REASON_CODES.ADAPTER_UNAVAILABLE, evidence.publicSummary, evidence.redactionSummary);
99
- }
100
- return adapterAvailabilitySuccess(adapterId, commandName, trustedAvailabilitySummary(commandName, policy.versionEvidence), {
101
- executablePath: trust.executablePath,
102
- versionText: evidence.versionText,
103
- });
104
- }
105
- function validateRuntimeVersionEvidence(version, requirement) {
106
- const versionText = normalizeVersionEvidenceText(`${version.stdout}\n${version.stderr}`.trim());
107
- const redactionSummary = versionText
108
- ? [redaction('runtimeVersion', 'raw_log', hashPublicValue(versionText))]
109
- : [redaction('runtimeVersion', 'missing', 'value-denied')];
110
- if (version.timedOut
111
- || version.exitCode !== 0
112
- || versionText.length === 0
113
- || versionText.length > VERSION_EVIDENCE_MAX_CHARS
114
- || version.stdoutBytes + version.stderrBytes > VERSION_EVIDENCE_MAX_BYTES
115
- || UNSAFE_VERSION_EVIDENCE_PATTERN.test(versionText)) {
116
- return {
117
- ok: false,
118
- publicSummary: 'Headless runtime version check did not return a bounded public result.',
119
- redactionSummary,
120
- };
121
- }
122
- if (requirement === 'claude-code' && (!CLAUDE_CODE_PRODUCT_PATTERN.test(versionText) || !VERSION_SEMVER_PATTERN.test(versionText))) {
123
- return {
124
- ok: false,
125
- publicSummary: 'Headless runtime version check did not return bounded Claude Code product/version evidence.',
126
- redactionSummary,
127
- };
128
- }
129
- return { ok: true, versionText };
130
- }
131
- function normalizeVersionEvidenceText(value) {
132
- return value.replace(/\s+/g, ' ').trim();
133
- }
134
- function trustedAvailabilitySummary(commandName, requirement) {
135
- if (requirement === 'claude-code')
136
- return `Trusted ${commandName} runtime is available with bounded Claude Code version evidence.`;
137
- return `Trusted ${commandName} runtime is available.`;
138
- }
139
- function buildOpenCodeArgs(prompt, modelId) {
140
- const args = ['run', '--standalone', '--agent', OPENCODE_AGENT_PROFILE, '--auto'];
141
- if (modelId)
142
- args.push('--model', modelId);
143
- args.push('--', prompt);
144
- return args;
145
- }
1
+ import{checkTrustedHeadlessRuntimeBinary as _}from"../binary.js";import{HEADLESS_REASON_CODES as s,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as R,createRejectedExecutionResult as p,createUnavailableExecutionResult as I,hashPublicValue as f,normalizeHeadlessCommandResult as E,redaction as A,runHeadlessCommand as v,validateHeadlessAdapterExecutionInput as b}from"./types.js";import{governedPreflightFailureResult as h,preflightManagedHeadlessProfile as y,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const r="opencode",d="opencode",S="neocortex",T=2e3,C=2e3,P=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,O=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,k=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function w(){return{id:r,displayName:"OpenCode Headless Adapter",async checkAvailability(n={}){return N(r,d,n,{realpathBasenamePolicy:"opencode-npm-native"})},buildInvocation(n){const e=b(n,r);return e.ok?{ok:!0,invocation:{adapterId:r,commandName:d,args:V(e.prompt,e.input.modelId),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=b(n,r);if(!t.ok)return p(r,r,t);const a=y(r,e);if(!a.ok)return h(r,t.input,a);if(e.signal?.aborted)return c(E(r,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const i=await this.checkAvailability(e);if(!i.ok)return c(I(r,t.input,i));const o=this.buildInvocation(t.input);if(!o.ok)return p(r,r,o);const u=await(e.commandRunner??v)(i.executablePath??d,o.invocation.args,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(E(r,t.input,u))}}}async function N(n,e,t,a={}){const i=_({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:a.realpathBasenamePolicy});if(!i.ok)return m(n,e,i.reasonCode===s.ADAPTER_UNAVAILABLE?s.ADAPTER_UNAVAILABLE:s.RUNTIME_UNTRUSTED,i.publicSummary,i.redactionSummary);const l=await(t.versionRunner??t.commandRunner??v)(i.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=g(l,a.versionEvidence??"generic-public");return u.ok?R(n,e,D(e,a.versionEvidence),{executablePath:i.executablePath,versionText:u.versionText}):m(n,e,s.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function g(n,e){const t=x(`${n.stdout}
2
+ ${n.stderr}`.trim()),a=t?[A("runtimeVersion","raw_log",f(t))]:[A("runtimeVersion","missing","value-denied")];return n.timedOut||n.exitCode!==0||t.length===0||t.length>T||n.stdoutBytes+n.stderrBytes>C||P.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:a}:e==="claude-code"&&(!O.test(t)||!k.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:a}:{ok:!0,versionText:t}}function x(n){return n.replace(/\s+/g," ").trim()}function D(n,e){return e==="claude-code"?`Trusted ${n} runtime is available with bounded Claude Code version evidence.`:`Trusted ${n} runtime is available.`}function V(n,e){const t=["run","--standalone","--agent",S,"--auto"];return e&&t.push("--model",e),t.push("--",n),t}export{N as checkRuntimeAvailability,w as createOpenCodeHeadlessAdapter};
@@ -1,43 +1 @@
1
- /** P208.05 -- client enforcement for phased plans and branchless bundles. */
2
- import { createHash } from 'node:crypto';
3
- import { validateYoloopPreparationBundle } from '../../../../shared/dist/yoloop/wave-decision-receipt.js';
4
- export function validatePhasedYoloopPlan(plan) {
5
- const errors = [];
6
- const phases = Array.isArray(plan.phases) ? plan.phases.filter(isRecord) : [];
7
- const budgets = isRecord(plan.budgets) ? plan.budgets : {};
8
- if (plan.version !== 2 || !isHash(plan.graphRevision))
9
- errors.push('phased-plan-invalid');
10
- if (budgets.maxWriteConcurrency !== 1)
11
- errors.push('writer-concurrency-invalid');
12
- for (const phase of phases) {
13
- if (!Number.isInteger(phase.maxConcurrency) || Number(phase.maxConcurrency) < 1)
14
- errors.push('phase-concurrency-invalid');
15
- const mutatesEpicCheckout = phase.mutatesEpicCheckout === true || phase.mutatesEpicWorktree === true;
16
- if (mutatesEpicCheckout && (phase.maxConcurrency !== 1 || !['epic-writer-lease', 'commit-range'].includes(String(phase.isolation))))
17
- errors.push('mutating-phase-not-serialized');
18
- }
19
- const required = ['read-only-analysis', 'isolated-build-test', 'patch-preparation', 'single-writer-integration', 'story-checkpoint-review'];
20
- if (required.some((kind) => !phases.some((phase) => phase.kind === kind)))
21
- errors.push('phase-missing');
22
- const receiptIds = Array.isArray(plan.decisionReceiptIds) ? plan.decisionReceiptIds : [];
23
- if (receiptIds.length === 0 || receiptIds.some((id) => !isHash(id)))
24
- errors.push('decision-receipt-invalid');
25
- const preparationConcurrency = Math.max(1, ...phases.filter((phase) => phase.mutatesEpicCheckout !== true && phase.mutatesEpicWorktree !== true).map((phase) => Number(phase.maxConcurrency) || 1));
26
- return { ok: errors.length === 0, preparationConcurrency, childExecutionConcurrency: 1, reasonCodes: [...new Set(errors)].sort() };
27
- }
28
- export function admitPreparedStoryBundle(input) {
29
- const errors = [...validateYoloopPreparationBundle(input.bundle, input.expected)];
30
- if (input.bundle.claimRevision !== input.expected.claimRevision)
31
- errors.push('bundle-claims-stale');
32
- if (!sameStrings(input.bundle.authorizedWriteSet, input.expected.authorizedWriteSet ?? []))
33
- errors.push('bundle-write-set-stale');
34
- const digest = createHash('sha256').update(input.payload).digest('hex');
35
- if (digest !== input.bundle.bundleDigest)
36
- errors.push('bundle-payload-digest-mismatch');
37
- if (!input.writerLease || input.writerLease.ownerStoryId !== input.bundle.storyId || input.writerLease.expiresAt <= input.expected.nowIso)
38
- errors.push('bundle-writer-lease-missing');
39
- return [...new Set(errors)].sort();
40
- }
41
- function isRecord(value) { return Boolean(value) && typeof value === 'object' && !Array.isArray(value); }
42
- function isHash(value) { return typeof value === 'string' && /^[a-f0-9]{40,64}$/.test(value); }
43
- function sameStrings(left, right) { return left.length === right.length && left.every((value, index) => value === right[index]); }
1
+ import{createHash as u}from"node:crypto";import{validateYoloopPreparationBundle as h}from"../../../../shared/dist/yoloop/wave-decision-receipt.js";function f(e){const r=[],s=Array.isArray(e.phases)?e.phases.filter(a):[],i=a(e.budgets)?e.budgets:{};(e.version!==2||!c(e.graphRevision))&&r.push("phased-plan-invalid"),i.maxWriteConcurrency!==1&&r.push("writer-concurrency-invalid");for(const t of s)(!Number.isInteger(t.maxConcurrency)||Number(t.maxConcurrency)<1)&&r.push("phase-concurrency-invalid"),(t.mutatesEpicCheckout===!0||t.mutatesEpicWorktree===!0)&&(t.maxConcurrency!==1||!["epic-writer-lease","commit-range"].includes(String(t.isolation)))&&r.push("mutating-phase-not-serialized");["read-only-analysis","isolated-build-test","patch-preparation","single-writer-integration","story-checkpoint-review"].some(t=>!s.some(n=>n.kind===t))&&r.push("phase-missing");const o=Array.isArray(e.decisionReceiptIds)?e.decisionReceiptIds:[];(o.length===0||o.some(t=>!c(t)))&&r.push("decision-receipt-invalid");const d=Math.max(1,...s.filter(t=>t.mutatesEpicCheckout!==!0&&t.mutatesEpicWorktree!==!0).map(t=>Number(t.maxConcurrency)||1));return{ok:r.length===0,preparationConcurrency:d,childExecutionConcurrency:1,reasonCodes:[...new Set(r)].sort()}}function g(e){const r=[...h(e.bundle,e.expected)];return e.bundle.claimRevision!==e.expected.claimRevision&&r.push("bundle-claims-stale"),l(e.bundle.authorizedWriteSet,e.expected.authorizedWriteSet??[])||r.push("bundle-write-set-stale"),u("sha256").update(e.payload).digest("hex")!==e.bundle.bundleDigest&&r.push("bundle-payload-digest-mismatch"),(!e.writerLease||e.writerLease.ownerStoryId!==e.bundle.storyId||e.writerLease.expiresAt<=e.expected.nowIso)&&r.push("bundle-writer-lease-missing"),[...new Set(r)].sort()}function a(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function c(e){return typeof e=="string"&&/^[a-f0-9]{40,64}$/.test(e)}function l(e,r){return e.length===r.length&&e.every((s,i)=>s===r[i])}export{g as admitPreparedStoryBundle,f as validatePhasedYoloopPlan};
@@ -1,231 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * P190.04 -- deterministic headless runtime/model resolver.
6
- */
7
- import { existsSync, readFileSync, statSync } from 'node:fs';
8
- import { homedir } from 'node:os';
9
- import { isAbsolute, join, resolve } from 'node:path';
10
- import { HEADLESS_REASON_CODES, boundPublicSummary, isHeadlessAdapterId, isSafeHeadlessModelId, redaction, } from './types.js';
11
- const DEFAULT_FALLBACK_HINT = Object.freeze({
12
- runtimeId: 'opencode',
13
- source: 'fallback',
14
- publicSafe: true,
15
- });
16
- const DEFAULT_CONFIG_RELATIVE_PATH = '.neocortex/headless-runtime.json';
17
- const DEFAULT_CONFIG_MAX_BYTES = 8 * 1024;
18
- const RUNTIME_HINT_ALLOWED_KEYS = new Set(['runtimeId', 'modelId', 'source', 'reasonCode', 'publicSafe']);
19
- const UNSAFE_HINT_KEY_PATTERN = /(raw|prompt|private|secret|token|password|authorization|api[_-]?key|license|argv|args|executable|binary|shell|cwd|command|path|url|vendor|stdout|stderr|transcript|workflow|step|customer|pii)/i;
20
- export function resolveHeadlessRuntime(input = {}) {
21
- const registry = input.registry ?? DEFAULT_REGISTRY_LIKE;
22
- const candidates = buildCandidateList(input);
23
- const normalized = [];
24
- const redactions = [];
25
- for (const candidate of candidates) {
26
- if (candidate.value === undefined)
27
- continue;
28
- const result = normalizeCandidate(candidate, registry);
29
- if (!result.ok)
30
- return result.resolution;
31
- redactions.push(...result.candidate.redactions);
32
- normalized.push(result.candidate);
33
- }
34
- const runtimeCandidate = normalized.find((candidate) => candidate.runtimeId);
35
- const modelCandidate = normalized.find((candidate) => candidate.modelId);
36
- if (!runtimeCandidate?.runtimeId) {
37
- return {
38
- ok: false,
39
- runtimeSource: 'unresolved',
40
- reasonCode: HEADLESS_REASON_CODES.RUNTIME_UNRESOLVED,
41
- reasonCodes: [HEADLESS_REASON_CODES.RUNTIME_UNRESOLVED],
42
- publicSummary: 'Headless runtime could not be resolved from explicit, origin, default or fallback sources.',
43
- redactionSummary: redactions,
44
- publicSafe: true,
45
- };
46
- }
47
- const reasonCode = sourceReasonCode(runtimeCandidate.source);
48
- return {
49
- ok: true,
50
- runtimeId: runtimeCandidate.runtimeId,
51
- ...(modelCandidate?.modelId ? { modelId: modelCandidate.modelId } : {}),
52
- runtimeSource: runtimeCandidate.source,
53
- ...(modelCandidate?.source ? { modelSource: modelCandidate.source } : {}),
54
- reasonCode,
55
- reasonCodes: [reasonCode],
56
- publicSummary: `Resolved headless runtime from ${runtimeCandidate.source} source.`,
57
- redactionSummary: redactions,
58
- publicSafe: true,
59
- };
60
- }
61
- export function loadHeadlessRuntimeDefaults(options = {}) {
62
- const maxBytes = options.maxBytes ?? DEFAULT_CONFIG_MAX_BYTES;
63
- const candidates = boundedDefaultPaths(options);
64
- for (const candidate of candidates) {
65
- if (!existsSync(candidate.path))
66
- continue;
67
- try {
68
- const stat = statSync(candidate.path);
69
- if (!stat.isFile() || stat.size > maxBytes) {
70
- return defaultsFailure('Default headless runtime config was not a bounded file.', 'defaultConfig', 'unbounded_file');
71
- }
72
- const parsed = JSON.parse(readFileSync(candidate.path, 'utf8'));
73
- const defaults = extractDefaults(parsed);
74
- if (!defaults)
75
- return defaultsFailure('Default headless runtime config did not contain a public object.', 'defaultConfig', 'unsafe_key');
76
- return {
77
- ok: true,
78
- defaults: { ...defaults, source: 'default', publicSafe: true },
79
- source: candidate.kind,
80
- reasonCodes: [HEADLESS_REASON_CODES.RUNTIME_DEFAULT],
81
- publicSummary: `Loaded ${candidate.kind} headless runtime defaults.`,
82
- publicSafe: true,
83
- };
84
- }
85
- catch {
86
- return defaultsFailure('Default headless runtime config could not be parsed safely.', 'defaultConfig', 'unsafe_key');
87
- }
88
- }
89
- return {
90
- ok: true,
91
- defaults: undefined,
92
- reasonCodes: [],
93
- publicSummary: 'No headless runtime defaults were found; resolver will continue without guessing.',
94
- publicSafe: true,
95
- };
96
- }
97
- function buildCandidateList(input) {
98
- const candidates = [
99
- { source: 'explicit', value: input.explicit },
100
- { source: 'origin', value: input.origin },
101
- ];
102
- for (const value of normalizeDefaults(input))
103
- candidates.push({ source: 'default', value });
104
- if (input.projectDefault !== undefined)
105
- candidates.push({ source: 'default', value: input.projectDefault });
106
- if (input.userDefault !== undefined)
107
- candidates.push({ source: 'default', value: input.userDefault });
108
- if (input.fallback !== false)
109
- candidates.push({ source: 'fallback', value: input.fallback ?? DEFAULT_FALLBACK_HINT });
110
- return candidates;
111
- }
112
- function normalizeDefaults(input) {
113
- if (input.defaults === undefined)
114
- return [];
115
- return Array.isArray(input.defaults) ? input.defaults : [input.defaults];
116
- }
117
- function normalizeCandidate(candidate, registry) {
118
- const value = unwrapDefaultLookup(candidate.value);
119
- if (value === undefined)
120
- return { ok: true, candidate: { source: candidate.source, redactions: [] } };
121
- if (!isRecord(value)) {
122
- return candidateFailure(HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED, 'Headless runtime hint must be a public object.', candidate.source, [redaction('runtime', 'unsafe_key', 'value-denied')]);
123
- }
124
- const redactions = [];
125
- for (const key of Object.keys(value)) {
126
- if (!RUNTIME_HINT_ALLOWED_KEYS.has(key) || UNSAFE_HINT_KEY_PATTERN.test(key)) {
127
- redactions.push(redaction(`runtime.${key}`, 'unsafe_key', 'key-denied'));
128
- }
129
- }
130
- if (value.publicSafe !== true)
131
- redactions.push(redaction('runtime.publicSafe', 'unsafe_key', 'value-denied'));
132
- const source = typeof value.source === 'string' ? value.source : candidate.source;
133
- if (source !== candidate.source)
134
- redactions.push(redaction('runtime.source', 'unsafe_key', 'value-denied'));
135
- const runtimeText = typeof value.runtimeId === 'string' ? value.runtimeId : undefined;
136
- const modelText = typeof value.modelId === 'string' ? value.modelId : undefined;
137
- let runtimeId;
138
- if (runtimeText !== undefined) {
139
- if (!isSafeRuntimeId(runtimeText) || !isHeadlessAdapterId(runtimeText) || !registry.hasAdapter(runtimeText)) {
140
- redactions.push(redaction('runtime.runtimeId', 'unsafe_key', 'value-denied'));
141
- return candidateFailure(HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED, 'Headless runtime was not trusted or allowlisted.', candidate.source, redactions);
142
- }
143
- runtimeId = runtimeText;
144
- }
145
- let modelId;
146
- if (modelText !== undefined) {
147
- if (!isSafeHeadlessModelId(modelText)) {
148
- redactions.push(redaction('runtime.modelId', 'unsafe_key', 'value-denied'));
149
- return candidateFailure(HEADLESS_REASON_CODES.MODEL_REJECTED, 'Headless model id failed bounded public-safety validation.', candidate.source, redactions);
150
- }
151
- modelId = modelText;
152
- }
153
- if (redactions.length > 0) {
154
- return candidateFailure(HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED, 'Headless runtime hint failed public-safety validation.', candidate.source, redactions);
155
- }
156
- return { ok: true, candidate: { source: candidate.source, ...(runtimeId ? { runtimeId } : {}), ...(modelId ? { modelId } : {}), redactions: [] } };
157
- }
158
- function unwrapDefaultLookup(value) {
159
- if (isRecord(value) && value.ok === true && 'defaults' in value)
160
- return value.defaults;
161
- return value;
162
- }
163
- function candidateFailure(reasonCode, publicSummary, source, redactions) {
164
- return {
165
- ok: false,
166
- resolution: {
167
- ok: false,
168
- runtimeSource: 'unresolved',
169
- reasonCode,
170
- reasonCodes: [reasonCode],
171
- publicSummary: boundPublicSummary(`${publicSummary} Source=${source}.`),
172
- redactionSummary: redactions,
173
- publicSafe: true,
174
- },
175
- };
176
- }
177
- function sourceReasonCode(source) {
178
- switch (source) {
179
- case 'explicit': return HEADLESS_REASON_CODES.RUNTIME_EXPLICIT;
180
- case 'origin': return HEADLESS_REASON_CODES.RUNTIME_ORIGIN;
181
- case 'default': return HEADLESS_REASON_CODES.RUNTIME_DEFAULT;
182
- case 'fallback': return HEADLESS_REASON_CODES.RUNTIME_FALLBACK;
183
- }
184
- }
185
- function boundedDefaultPaths(options) {
186
- const paths = [];
187
- const projectRoot = normalizeAbsoluteDirectory(options.projectRoot);
188
- if (projectRoot)
189
- paths.push({ kind: 'project', path: join(projectRoot, DEFAULT_CONFIG_RELATIVE_PATH) });
190
- const home = normalizeAbsoluteDirectory(options.homeDir ?? homedir());
191
- if (home)
192
- paths.push({ kind: 'user', path: join(home, DEFAULT_CONFIG_RELATIVE_PATH) });
193
- return paths;
194
- }
195
- function normalizeAbsoluteDirectory(value) {
196
- if (!value || /[\r\n\0]/.test(value))
197
- return undefined;
198
- const absolute = isAbsolute(value) ? value : resolve(value);
199
- return isAbsolute(absolute) ? absolute : undefined;
200
- }
201
- function extractDefaults(parsed) {
202
- if (!isRecord(parsed))
203
- return undefined;
204
- const candidate = isRecord(parsed.headless) ? parsed.headless : parsed;
205
- return {
206
- ...(typeof candidate.runtimeId === 'string' ? { runtimeId: candidate.runtimeId } : {}),
207
- ...(typeof candidate.modelId === 'string' ? { modelId: candidate.modelId } : {}),
208
- publicSafe: true,
209
- };
210
- }
211
- function defaultsFailure(publicSummary, field, reason) {
212
- return {
213
- ok: false,
214
- reasonCode: HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED,
215
- reasonCodes: [HEADLESS_REASON_CODES.RUNTIME_UNTRUSTED],
216
- publicSummary,
217
- redactionSummary: [redaction(field, reason, 'value-denied')],
218
- publicSafe: true,
219
- };
220
- }
221
- function isSafeRuntimeId(value) {
222
- return /^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(value) && !/[\/\s;&|`$<>]/.test(value);
223
- }
224
- function isRecord(value) {
225
- return typeof value === 'object' && value !== null && !Array.isArray(value);
226
- }
227
- const DEFAULT_REGISTRY_LIKE = Object.freeze({
228
- hasAdapter(id) {
229
- return isHeadlessAdapterId(id);
230
- },
231
- });
1
+ import{existsSync as h,readFileSync as T,statSync as _}from"node:fs";import{homedir as k}from"node:os";import{isAbsolute as I,join as S,resolve as R}from"node:path";import{HEADLESS_REASON_CODES as o,boundPublicSummary as D,isHeadlessAdapterId as b,isSafeHeadlessModelId as U,redaction as c}from"./types.js";const N=Object.freeze({runtimeId:"opencode",source:"fallback",publicSafe:!0}),E=".neocortex/headless-runtime.json",A=8*1024,C=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),g=/(raw|prompt|private|secret|token|password|authorization|api[_-]?key|license|argv|args|executable|binary|shell|cwd|command|path|url|vendor|stdout|stderr|transcript|workflow|step|customer|pii)/i;function P(e={}){const t=e.registry??O,u=L(e),r=[],d=[];for(const i of u){if(i.value===void 0)continue;const a=M(i,t);if(!a.ok)return a.resolution;d.push(...a.candidate.redactions),r.push(a.candidate)}const n=r.find(i=>i.runtimeId),s=r.find(i=>i.modelId);if(!n?.runtimeId)return{ok:!1,runtimeSource:"unresolved",reasonCode:o.RUNTIME_UNRESOLVED,reasonCodes:[o.RUNTIME_UNRESOLVED],publicSummary:"Headless runtime could not be resolved from explicit, origin, default or fallback sources.",redactionSummary:d,publicSafe:!0};const l=w(n.source);return{ok:!0,runtimeId:n.runtimeId,...s?.modelId?{modelId:s.modelId}:{},runtimeSource:n.source,...s?.source?{modelSource:s.source}:{},reasonCode:l,reasonCodes:[l],publicSummary:`Resolved headless runtime from ${n.source} source.`,redactionSummary:d,publicSafe:!0}}function G(e={}){const t=e.maxBytes??A,u=x(e);for(const r of u)if(h(r.path))try{const d=_(r.path);if(!d.isFile()||d.size>t)return p("Default headless runtime config was not a bounded file.","defaultConfig","unbounded_file");const n=JSON.parse(T(r.path,"utf8")),s=H(n);return s?{ok:!0,defaults:{...s,source:"default",publicSafe:!0},source:r.kind,reasonCodes:[o.RUNTIME_DEFAULT],publicSummary:`Loaded ${r.kind} headless runtime defaults.`,publicSafe:!0}:p("Default headless runtime config did not contain a public object.","defaultConfig","unsafe_key")}catch{return p("Default headless runtime config could not be parsed safely.","defaultConfig","unsafe_key")}return{ok:!0,defaults:void 0,reasonCodes:[],publicSummary:"No headless runtime defaults were found; resolver will continue without guessing.",publicSafe:!0}}function L(e){const t=[{source:"explicit",value:e.explicit},{source:"origin",value:e.origin}];for(const u of v(e))t.push({source:"default",value:u});return e.projectDefault!==void 0&&t.push({source:"default",value:e.projectDefault}),e.userDefault!==void 0&&t.push({source:"default",value:e.userDefault}),e.fallback!==!1&&t.push({source:"fallback",value:e.fallback??N}),t}function v(e){return e.defaults===void 0?[]:Array.isArray(e.defaults)?e.defaults:[e.defaults]}function M(e,t){const u=F(e.value);if(u===void 0)return{ok:!0,candidate:{source:e.source,redactions:[]}};if(!m(u))return f(o.RUNTIME_UNTRUSTED,"Headless runtime hint must be a public object.",e.source,[c("runtime","unsafe_key","value-denied")]);const r=[];for(const a of Object.keys(u))(!C.has(a)||g.test(a))&&r.push(c(`runtime.${a}`,"unsafe_key","key-denied"));u.publicSafe!==!0&&r.push(c("runtime.publicSafe","unsafe_key","value-denied")),(typeof u.source=="string"?u.source:e.source)!==e.source&&r.push(c("runtime.source","unsafe_key","value-denied"));const n=typeof u.runtimeId=="string"?u.runtimeId:void 0,s=typeof u.modelId=="string"?u.modelId:void 0;let l;if(n!==void 0){if(!j(n)||!b(n)||!t.hasAdapter(n))return r.push(c("runtime.runtimeId","unsafe_key","value-denied")),f(o.RUNTIME_UNTRUSTED,"Headless runtime was not trusted or allowlisted.",e.source,r);l=n}let i;if(s!==void 0){if(!U(s))return r.push(c("runtime.modelId","unsafe_key","value-denied")),f(o.MODEL_REJECTED,"Headless model id failed bounded public-safety validation.",e.source,r);i=s}return r.length>0?f(o.RUNTIME_UNTRUSTED,"Headless runtime hint failed public-safety validation.",e.source,r):{ok:!0,candidate:{source:e.source,...l?{runtimeId:l}:{},...i?{modelId:i}:{},redactions:[]}}}function F(e){return m(e)&&e.ok===!0&&"defaults"in e?e.defaults:e}function f(e,t,u,r){return{ok:!1,resolution:{ok:!1,runtimeSource:"unresolved",reasonCode:e,reasonCodes:[e],publicSummary:D(`${t} Source=${u}.`),redactionSummary:r,publicSafe:!0}}}function w(e){switch(e){case"explicit":return o.RUNTIME_EXPLICIT;case"origin":return o.RUNTIME_ORIGIN;case"default":return o.RUNTIME_DEFAULT;case"fallback":return o.RUNTIME_FALLBACK}}function x(e){const t=[],u=y(e.projectRoot);u&&t.push({kind:"project",path:S(u,E)});const r=y(e.homeDir??k());return r&&t.push({kind:"user",path:S(r,E)}),t}function y(e){if(!e||/[\r\n\0]/.test(e))return;const t=I(e)?e:R(e);return I(t)?t:void 0}function H(e){if(!m(e))return;const t=m(e.headless)?e.headless:e;return{...typeof t.runtimeId=="string"?{runtimeId:t.runtimeId}:{},...typeof t.modelId=="string"?{modelId:t.modelId}:{},publicSafe:!0}}function p(e,t,u){return{ok:!1,reasonCode:o.RUNTIME_UNTRUSTED,reasonCodes:[o.RUNTIME_UNTRUSTED],publicSummary:e,redactionSummary:[c(t,u,"value-denied")],publicSafe:!0}}function j(e){return/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(e)&&!/[\/\s;&|`$<>]/.test(e)}function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const O=Object.freeze({hasAdapter(e){return b(e)}});export{G as loadHeadlessRuntimeDefaults,P as resolveHeadlessRuntime};