@ornexus/neocortex 4.60.67 → 4.60.68

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 (230) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.sh +1 -1
  4. package/package.json +2 -2
  5. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  6. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  7. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  8. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  9. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  10. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  11. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  12. package/packages/client/dist/adapters/index.js +22 -1
  13. package/packages/client/dist/adapters/platform-detector.js +212 -1
  14. package/packages/client/dist/adapters/target-adapter.js +12 -0
  15. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  16. package/packages/client/dist/agent/refresh-stubs.js +417 -2
  17. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  18. package/packages/client/dist/agent/update-description.js +251 -1
  19. package/packages/client/dist/cache/crypto-utils.js +78 -1
  20. package/packages/client/dist/cache/encrypted-cache.js +108 -1
  21. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  22. package/packages/client/dist/cache/index.js +13 -1
  23. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  24. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  25. package/packages/client/dist/checkpoint/index.js +11 -1
  26. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  27. package/packages/client/dist/cli.js +290 -3
  28. package/packages/client/dist/commands/activate.js +394 -8
  29. package/packages/client/dist/commands/architecture-answers.js +274 -7
  30. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  31. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  32. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  33. package/packages/client/dist/commands/cache-status.js +112 -2
  34. package/packages/client/dist/commands/config.js +88 -1
  35. package/packages/client/dist/commands/doctor.js +635 -2
  36. package/packages/client/dist/commands/invoke.js +7140 -142
  37. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  38. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  39. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  40. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  41. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  42. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  43. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  44. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  45. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  46. package/packages/client/dist/commands/mutation-qa.js +220 -1
  47. package/packages/client/dist/commands/native-agent.js +136 -2
  48. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  49. package/packages/client/dist/commands/planning-generation.js +53 -1
  50. package/packages/client/dist/commands/planning-memory.js +40 -1
  51. package/packages/client/dist/commands/planning-research.js +42 -1
  52. package/packages/client/dist/commands/private-session.js +75 -1
  53. package/packages/client/dist/commands/property-qa.js +139 -1
  54. package/packages/client/dist/commands/qa-control.js +16 -1
  55. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  56. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  57. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  58. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  59. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  60. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  61. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  63. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  64. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  65. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  66. package/packages/client/dist/commands/refactor-commit.js +399 -13
  67. package/packages/client/dist/commands/refactor-control.js +142 -3
  68. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  69. package/packages/client/dist/commands/refactor-review.js +283 -5
  70. package/packages/client/dist/commands/refactor-root.js +588 -7
  71. package/packages/client/dist/commands/refresh-memory.js +156 -3
  72. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  73. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  74. package/packages/client/dist/config/profile-directory.js +13 -1
  75. package/packages/client/dist/config/resolver-selection.js +278 -1
  76. package/packages/client/dist/config/secure-config.js +281 -12
  77. package/packages/client/dist/config.js +223 -2
  78. package/packages/client/dist/constants.js +25 -1
  79. package/packages/client/dist/context/context-collector.js +222 -2
  80. package/packages/client/dist/context/context-sanitizer.js +145 -1
  81. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  82. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  83. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  84. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  85. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  86. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  87. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  88. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  89. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  90. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  91. package/packages/client/dist/continuity/native-agent-types.js +90 -1
  92. package/packages/client/dist/continuity/outbox.js +117 -1
  93. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  94. package/packages/client/dist/continuity/sqlite-store.js +2536 -81
  95. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  96. package/packages/client/dist/errors/error-messages.js +228 -2
  97. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  98. package/packages/client/dist/evidence/collector.js +347 -1
  99. package/packages/client/dist/evidence/index.js +1 -1
  100. package/packages/client/dist/evidence/types.js +2 -0
  101. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  102. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  103. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  104. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  105. package/packages/client/dist/git/direct-yolo-checkpoint.js +1234 -4
  106. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  107. package/packages/client/dist/git/git-lifecycle-store.js +1938 -9
  108. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  109. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  110. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  111. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  112. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  113. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  114. package/packages/client/dist/i18n/first-run.js +60 -2
  115. package/packages/client/dist/index.js +47 -1
  116. package/packages/client/dist/invocation/invoke-input.js +24 -1
  117. package/packages/client/dist/license/index.js +5 -1
  118. package/packages/client/dist/license/license-client.js +304 -1
  119. package/packages/client/dist/machine/fingerprint.js +163 -2
  120. package/packages/client/dist/machine/index.js +5 -1
  121. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  122. package/packages/client/dist/memory/project-memory-writer.js +1007 -40
  123. package/packages/client/dist/memory/shared-project-memory-types.js +253 -2
  124. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  125. package/packages/client/dist/migrations/project-identity.js +493 -7
  126. package/packages/client/dist/migrations/state-json.js +344 -4
  127. package/packages/client/dist/policy/architecture-policy.js +184 -2
  128. package/packages/client/dist/policy/index.js +7 -1
  129. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  130. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  131. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  132. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  133. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  134. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  135. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  136. package/packages/client/dist/private-execution/delivery.js +410 -13
  137. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  138. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  139. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  140. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  141. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  142. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  143. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  144. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  145. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  146. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  147. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  148. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  149. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  150. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  151. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  152. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  153. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  154. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  155. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  156. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  157. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  158. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  159. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  160. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  161. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  162. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  163. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  164. package/packages/client/dist/private-execution/session-lease.js +63 -1
  165. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  166. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  167. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  168. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  169. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  170. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  171. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  172. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  173. package/packages/client/dist/resilience/index.js +8 -1
  174. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  175. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  176. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  177. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  178. package/packages/client/dist/runner/binary.js +404 -1
  179. package/packages/client/dist/runner/cli.js +1571 -17
  180. package/packages/client/dist/runner/headless/adapters.js +49 -1
  181. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  182. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  183. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  184. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +110 -2
  185. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1236 -8
  186. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +318 -2
  187. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  188. package/packages/client/dist/runner/headless/managed-profile.js +132 -1
  189. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  190. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  191. package/packages/client/dist/runner/headless/resolver.js +231 -1
  192. package/packages/client/dist/runner/headless/run-yolo.js +885 -1
  193. package/packages/client/dist/runner/headless/run-yoloop.js +2574 -2
  194. package/packages/client/dist/runner/headless/types.js +574 -2
  195. package/packages/client/dist/runner/local-console.js +396 -13
  196. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  197. package/packages/client/dist/runner/project-identity.js +106 -1
  198. package/packages/client/dist/runner/scheduler.js +995 -7
  199. package/packages/client/dist/runner-cli.js +18 -2
  200. package/packages/client/dist/state/invocation-shape.js +13 -1
  201. package/packages/client/dist/state/project-state-snapshot.js +1677 -1
  202. package/packages/client/dist/state/state-json-repair.js +785 -3
  203. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  204. package/packages/client/dist/telemetry/index.js +5 -1
  205. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  206. package/packages/client/dist/tier/index.js +5 -1
  207. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  208. package/packages/client/dist/types/index.js +38 -1
  209. package/packages/client/dist/version.js +27 -1
  210. package/packages/client/dist/yolo/change-evidence-collector.js +126 -1
  211. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  212. package/packages/client/dist/yolo/spec-envelope-collector.js +185 -5
  213. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  214. package/packages/client/dist/yoloop/index.js +8 -1
  215. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  216. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  217. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  218. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  219. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1723 -1
  220. package/targets-stubs/antigravity/gemini.md +1 -1
  221. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  222. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  223. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  224. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  225. package/targets-stubs/claude-code/neocortex.md +2 -2
  226. package/targets-stubs/codex/AGENTS.md +1 -1
  227. package/targets-stubs/cursor/agent.md +2 -2
  228. package/targets-stubs/gemini-cli/agent.md +2 -2
  229. package/targets-stubs/opencode/neocortex-root.md +1 -1
  230. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,2 +1,574 @@
1
- import{createHash as v}from"node:crypto";import{spawn as V}from"node:child_process";import{createLocalJobConsoleServer as z}from"../local-console.js";const F=Object.freeze(["fake","test","opencode","claude-code"]),l=Object.freeze({OK:"continuity-ok",RUNTIME_EXPLICIT:"headless-runtime-explicit",RUNTIME_ORIGIN:"headless-runtime-origin",RUNTIME_DEFAULT:"headless-runtime-default",RUNTIME_FALLBACK:"headless-runtime-fallback",RUNTIME_UNRESOLVED:"headless-runtime-unresolved",RUNTIME_UNTRUSTED:"headless-runtime-untrusted",MODEL_REJECTED:"headless-model-rejected",DIRECTIVE_REJECTED:"headless-directive-rejected",PROMPT_REJECTED:"headless-prompt-rejected",ADAPTER_UNAVAILABLE:"headless-adapter-unavailable",RUNTIME_AUTH_REQUIRED:"headless-runtime-auth-required",MANAGED_PROFILE_MISSING:"headless-managed-profile-missing",MANAGED_PROFILE_INVALID:"headless-managed-profile-invalid",APPROVAL_POLICY_INVALID:"headless-approval-policy-invalid",APPROVAL_POLICY_MISMATCH:"headless-approval-policy-mismatch",EXECUTION_CANCELLED:"headless-execution-cancelled",EXECUTION_TIMEOUT:"headless-execution-timeout",EXECUTION_BACKOFF:"headless-execution-backoff",EXECUTION_COMPLETED:"headless-execution-completed",EXECUTION_FAILED:"headless-execution-failed",RECEIPT_REDACTED:"headless-receipt-redacted",YOLOOP_METADATA_INVALID:"headless-yoloop-metadata-invalid",YOLOOP_ISOLATION_VIOLATION:"headless-yoloop-isolation-violation",WORKER_POOL_SERIAL_FALLBACK:"worker-pool-serial-fallback",WORKER_POOL_PARALLEL_ACTIVE:"worker-pool-parallel-active",WORKER_POOL_BACKPRESSURE_PAUSED:"worker-pool-backpressure-paused"}),$=120,O=240,X=600*1e3,U=1800*1e3,Y=/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/,G=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,J=/^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/,Z=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,w=/(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)/i,L=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/,q=new Set(["promptKind","targetKind","targetRef","storyId","epicId","runtimeId","modelId","runtimeSource","timeoutMs","receipt","publicSummary","publicSafe"]),W=new Set(["executionId","attemptId","jobId","operationId","idempotencyKey","runnerId","subagentId"]);function Q(e){return F.includes(e)}function pe(e,r){const t=[],s=[];if(!K(e))return t.push(i("input","unsafe_key","value-denied")),k(l.DIRECTIVE_REJECTED,"Headless adapter input must be a public object.",t);for(const m of Object.keys(e))q.has(m)||(s.push(m),t.push(i(m,x(m),"key-denied")));const u=e.publicSafe===!0;u||t.push(i("publicSafe","unsafe_key","value-denied"));const a=h(e.promptKind);a!=="yolo"&&a!=="yolo-branchless-preparation"&&a!=="yoloop"&&t.push(i("promptKind","unsafe_key","value-denied"));const p=h(e.targetKind);p!=="story"&&p!=="epic"&&t.push(i("targetKind","unsafe_key","value-denied"));const o=h(e.targetRef);(!o||!M(o)||L.test(o)||o.includes(".."))&&t.push(i("targetRef","prompt_body","value-denied")),(a==="yolo"||a==="yolo-branchless-preparation")&&(p!=="story"||!o||!G.test(o))&&t.push(i("targetRef","prompt_body","value-denied")),a==="yoloop"&&(p!=="epic"||!o||!J.test(o))&&t.push(i("targetRef","prompt_body","value-denied"));const d=P(e.storyId,"storyId",t),f=P(e.epicId,"epicId",t);d&&o&&(a==="yolo"||a==="yolo-branchless-preparation")&&d!==o.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")&&t.push(i("storyId","prompt_body","value-denied")),f&&o&&a==="yoloop"&&f!==o.replace(/^docs\/epics\/epic-/,"").replace(/\.md$/,"")&&t.push(i("epicId","prompt_body","value-denied"));const E=h(e.runtimeId);(!E||!Q(E)||r&&E!==r)&&t.push(i("runtimeId","unsafe_key","value-denied"));const b=te(e.modelId,t),y=re(e.runtimeSource,t),_=se(e.timeoutMs,t),T=ne(e.publicSummary,t),S=ie(e.receipt,t);if(t.length>0||s.length>0||!u||!a||!p||!o||!E){const m=t.some(n=>n.field==="modelId"),g=t.some(n=>n.reason==="prompt_body");return k(m?l.MODEL_REJECTED:g?l.PROMPT_REJECTED:l.DIRECTIVE_REJECTED,g?"Headless adapter target did not match a public prompt shape.":"Headless adapter input failed public-safety validation.",t)}const A={promptKind:a,targetKind:p,targetRef:o,...d?{storyId:d}:{},...f?{epicId:f}:{},runtimeId:E,...b?{modelId:b}:{},...y?{runtimeSource:y}:{},..._?{timeoutMs:_}:{},...S?{receipt:S}:{},...T?{publicSummary:T}:{},publicSafe:!0},R=D(A);return{ok:!0,input:A,prompt:R,promptHash:I(R),reasonCodes:[l.OK],publicSafe:!0}}function D(e){return e.promptKind==="yolo"?`*yolo @${e.targetRef}`:e.promptKind==="yolo-branchless-preparation"?`*yolo @${e.targetRef} branchless-preparation`:`*yoloop @${e.targetRef}`}function I(e){return`sha256:${v("sha256").update(e).digest("hex")}`}function fe(e,r,t,s=0){return{status:"failed",adapterId:e,runtimeId:r,reasonCode:t.reasonCode,reasonCodes:t.reasonCodes,durationMs:s,counts:{},hashes:{},publicSummary:C(t.publicSummary),redactionSummary:t.redactionSummary,relativePaths:[],publicSafe:!0}}function Ee(e,r,t,s=0){return{status:"failed",adapterId:e,runtimeId:r.runtimeId,...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},reasonCode:t.reasonCode,reasonCodes:t.reasonCodes,durationMs:s,counts:{},hashes:{prompt:I(D(r))},publicSummary:C(t.publicSummary),redactionSummary:t.redactionSummary,relativePaths:[r.targetRef],...r.receipt?{receipt:r.receipt}:{},publicSafe:!0}}function me(e,r,t){const s=D(r),u=I(t.stdout),a=I(t.stderr),p=t.timedOut||t.exitCode===0?0:de(t.stdout,t.stderr),o=t.cancelled?"failed":t.timedOut?"timed_out":t.exitCode===0?"completed":"failed",d=t.cancelled?l.EXECUTION_CANCELLED:t.timedOut?l.EXECUTION_TIMEOUT:t.exitCode===0?l.EXECUTION_COMPLETED:p>0?l.RUNTIME_AUTH_REQUIRED:l.EXECUTION_FAILED,f=[i("prompt","prompt_body",I(s))];return t.stdoutBytes>0&&f.push(i("stdout","raw_log",u)),t.stderrBytes>0&&f.push(i("stderr","raw_log",a)),{status:o,adapterId:e,runtimeId:r.runtimeId,...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},reasonCode:d,reasonCodes:[d,l.RECEIPT_REDACTED],exitCode:t.exitCode,signal:t.signal??null,durationMs:t.durationMs,counts:{stdoutBytes:t.stdoutBytes,stderrBytes:t.stderrBytes,stdoutLines:H(t.stdout),stderrLines:H(t.stderr),...p>0?{authEvidenceMatches:p}:{}},hashes:{prompt:I(s),stdout:u,stderr:a},publicSummary:o==="completed"?"Headless adapter completed with public-safe redacted output summary.":d===l.EXECUTION_CANCELLED?"Headless adapter was cancelled; raw output was redacted.":o==="timed_out"?"Headless adapter timed out; raw output was redacted.":d===l.RUNTIME_AUTH_REQUIRED?"Headless adapter requires local runtime authentication; raw output was redacted.":"Headless adapter failed; raw output was redacted.",redactionSummary:f,relativePaths:[r.targetRef],...r.receipt?{receipt:r.receipt}:{},publicSafe:!0}}async function _e(e,r,t={}){const s=Date.now(),u=oe(t.timeoutMs),a=t.maxOutputBytes??64e3;return t.signal?.aborted?{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:Date.now()-s,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}:await new Promise(p=>{const o=V(e,[...r],{cwd:t.cwd,env:t.env,shell:!1,stdio:[t.localConsole?"pipe":"ignore","pipe","pipe"]}),d=t.localConsole?.jobId?z({...t.localConsole,projectRoot:t.localConsole.projectRoot??t.cwd,writeStdin:n=>{o.stdin?.write(n)},signalProcess:n=>o.kill(n)}):void 0;d?.start();let f="",E="",b=0,y=0,_=!1,T=!1,S=!1;const A=()=>{_||(S=!0,o.kill("SIGTERM"))};t.signal?.addEventListener("abort",A,{once:!0});const R=()=>{t.signal?.removeEventListener("abort",A)},m=(n,c,B)=>{const N=B+c.length;if(n.length<a){const j=a-n.length;return{text:n+c.toString("utf8").slice(0,j),bytes:N}}return{text:n,bytes:N}};o.stdout?.on("data",n=>{const c=m(f,n,b);f=c.text,b=c.bytes,d?.broadcastStdout(n)}),o.stderr?.on("data",n=>{const c=m(E,n,y);E=c.text,y=c.bytes,d?.broadcastStderr(n)});const g=setTimeout(()=>{T=!0,o.kill("SIGTERM")},u);o.on("error",n=>{if(_)return;_=!0,clearTimeout(g),R(),d?.close({exitCode:127,signal:null});const c=n instanceof Error?n.message:String(n);p({exitCode:127,signal:null,timedOut:!1,cancelled:S,durationMs:Date.now()-s,stdout:f,stderr:c,stdoutBytes:b,stderrBytes:Buffer.byteLength(c)})}),o.on("close",(n,c)=>{_||(_=!0,clearTimeout(g),R(),d?.close({exitCode:n,signal:c}),p({exitCode:n,signal:c,timedOut:T,cancelled:S,durationMs:Date.now()-s,stdout:f,stderr:E,stdoutBytes:b,stderrBytes:y}))})})}function be(e,r,t,s,u=[]){return{ok:!1,adapterId:e,...r?{commandName:r}:{},reasonCode:t,reasonCodes:[t],publicSummary:C(s),redactionSummary:u,publicSafe:!0}}function Ie(e,r,t,s={}){const u={ok:!0,adapterId:e,commandName:r,...s.versionText?{versionHash:I(s.versionText)}:{},reasonCodes:[l.OK],publicSummary:C(t),publicSafe:!0};return s.executablePath&&Object.defineProperty(u,"executablePath",{value:s.executablePath,enumerable:!1,configurable:!1}),u}function i(e,r,t){return{field:e,reason:r,evidence:t,publicSafe:!0}}function C(e){return e.length<=O?e:`${e.slice(0,O)}\u2026[TRUNCATED:${e.length-O}]`}function ee(e){return e.length<=$&&Y.test(e)&&!w.test(e)&&!L.test(e)&&!e.includes("..")&&!e.startsWith("/")}function k(e,r,t){return{ok:!1,reasonCode:e,reasonCodes:[e],publicSummary:C(r),redactionSummary:t,publicSafe:!0}}function P(e,r,t){if(e===void 0)return;const s=h(e);if(!s||!M(s)||L.test(s)){t.push(i(r,x(r),"value-denied"));return}return s}function te(e,r){if(e===void 0)return;const t=h(e);if(!t||!ee(t)){r.push(i("modelId","unsafe_key","value-denied"));return}return t}function re(e,r){if(e!==void 0){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e;r.push(i("runtimeSource","unsafe_key","value-denied"))}}function se(e,r){if(e!==void 0){if(typeof e!="number"||!Number.isInteger(e)||e<=0||e>U){r.push(i("timeoutMs","unbounded_number","value-denied"));return}return e}}function oe(e){return!e||!Number.isInteger(e)||e<=0||e>U?X:e}function ne(e,r){if(e===void 0)return;const t=h(e);if(!t||t.length>O||!M(t)){r.push(i("publicSummary","unbounded_text","value-denied"));return}return t}function ie(e,r){if(e===void 0)return;if(!K(e)){r.push(i("receipt","unsafe_key","value-denied"));return}const t={};for(const[s,u]of Object.entries(e)){if(!W.has(s)||Z.test(s)){r.push(i(`receipt.${s}`,x(s),"key-denied"));continue}const a=P(u,`receipt.${s}`,r);a&&(t[s]=a)}return Object.keys(t).length>0?t:void 0}function x(e){return/prompt/i.test(e)?"prompt_body":/std(?:out|err)|raw|log|transcript|stack/i.test(e)?"raw_log":/url/i.test(e)?"private_url":/path|cwd|argv|args|shell|command|binary|executable/i.test(e)?"executable_path":/secret|token|password|authorization|api[_-]?key|license/i.test(e)?"secret_or_pii":"unsafe_key"}function h(e){return typeof e=="string"?e:void 0}function M(e){return e.length>0&&!w.test(e)&&!/\0/.test(e)}function H(e){return e?e.split(/\r?\n/).filter(r=>r.length>0).length:0}const ae=Object.freeze([/\bauth(?:entication|orization)?\s+(?:is\s+)?required\b/i,/\brequires?\s+authentication\b/i,/\bmust\s+(?:log\s?in|authenticate|be\s+authenticated)\b/i,/\bunauthenticated\b/i,/\b(?:not|unauthenticated)\s+(?:logged\s+in|authenticated)\b/i,/\blog\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,/\bplease\s+(?:log\s?in|authenticate|sign\s?in)\b/i,/\bsign\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,/\bsession\s+(?:expired|not\s+found|invalid)\b/i,/\bcredentials?\s+(?:missing|required|not\s+found)\b/i]);function de(...e){const r=e.filter(t=>t.length>0).map(t=>t.slice(0,8e3)).join(`
2
- `);return r?ae.reduce((t,s)=>t+(s.test(r)?1:0),0):0}function K(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}export{F as HEADLESS_ADAPTER_IDS,l as HEADLESS_REASON_CODES,be as adapterAvailabilityFailure,Ie as adapterAvailabilitySuccess,C as boundPublicSummary,fe as createRejectedExecutionResult,Ee as createUnavailableExecutionResult,I as hashPublicValue,Q as isHeadlessAdapterId,ee as isSafeHeadlessModelId,me as normalizeHeadlessCommandResult,i as redaction,D as renderHeadlessPrompt,_e as runHeadlessCommand,pe as validateHeadlessAdapterExecutionInput};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ *
5
+ * P190.04 -- public-safe headless runtime/adapter contracts.
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import { spawn } from 'node:child_process';
9
+ import { createLocalJobConsoleServer } from '../local-console.js';
10
+ export const HEADLESS_ADAPTER_IDS = Object.freeze([
11
+ 'fake',
12
+ 'test',
13
+ 'opencode',
14
+ 'claude-code',
15
+ ]);
16
+ export const HEADLESS_REASON_CODES = Object.freeze({
17
+ OK: 'continuity-ok',
18
+ RUNTIME_EXPLICIT: 'headless-runtime-explicit',
19
+ RUNTIME_ORIGIN: 'headless-runtime-origin',
20
+ RUNTIME_DEFAULT: 'headless-runtime-default',
21
+ RUNTIME_FALLBACK: 'headless-runtime-fallback',
22
+ RUNTIME_UNRESOLVED: 'headless-runtime-unresolved',
23
+ RUNTIME_UNTRUSTED: 'headless-runtime-untrusted',
24
+ MODEL_REJECTED: 'headless-model-rejected',
25
+ DIRECTIVE_REJECTED: 'headless-directive-rejected',
26
+ PROMPT_REJECTED: 'headless-prompt-rejected',
27
+ ADAPTER_UNAVAILABLE: 'headless-adapter-unavailable',
28
+ RUNTIME_AUTH_REQUIRED: 'headless-runtime-auth-required',
29
+ MANAGED_PROFILE_MISSING: 'headless-managed-profile-missing',
30
+ MANAGED_PROFILE_INVALID: 'headless-managed-profile-invalid',
31
+ APPROVAL_POLICY_INVALID: 'headless-approval-policy-invalid',
32
+ APPROVAL_POLICY_MISMATCH: 'headless-approval-policy-mismatch',
33
+ EXECUTION_CANCELLED: 'headless-execution-cancelled',
34
+ EXECUTION_TIMEOUT: 'headless-execution-timeout',
35
+ EXECUTION_BACKOFF: 'headless-execution-backoff',
36
+ EXECUTION_COMPLETED: 'headless-execution-completed',
37
+ EXECUTION_FAILED: 'headless-execution-failed',
38
+ RECEIPT_REDACTED: 'headless-receipt-redacted',
39
+ YOLOOP_METADATA_INVALID: 'headless-yoloop-metadata-invalid',
40
+ YOLOOP_ISOLATION_VIOLATION: 'headless-yoloop-isolation-violation',
41
+ WORKER_POOL_SERIAL_FALLBACK: 'worker-pool-serial-fallback',
42
+ WORKER_POOL_PARALLEL_ACTIVE: 'worker-pool-parallel-active',
43
+ WORKER_POOL_BACKPRESSURE_PAUSED: 'worker-pool-backpressure-paused',
44
+ });
45
+ const HEADLESS_MODEL_ID_MAX_CHARS = 120;
46
+ const HEADLESS_PUBLIC_SUMMARY_MAX_CHARS = 240;
47
+ const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;
48
+ const MAX_TIMEOUT_MS = 30 * 60 * 1000;
49
+ const MODEL_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/;
50
+ const STORY_REF_PATTERN = /^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/;
51
+ const EPIC_REF_PATTERN = /^docs\/epics\/epic-[A-Za-z0-9._-]+\.md$/;
52
+ const UNSAFE_KEY_PATTERN = /(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i;
53
+ const UNSAFE_VALUE_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)/i;
54
+ const SHELL_FRAGMENT_PATTERN = /(?:[;&|`$<>]|\$\(|\n|\r|\0)/;
55
+ const ADAPTER_INPUT_ALLOWED_KEYS = new Set([
56
+ 'promptKind',
57
+ 'targetKind',
58
+ 'targetRef',
59
+ 'storyId',
60
+ 'epicId',
61
+ 'runtimeId',
62
+ 'modelId',
63
+ 'runtimeSource',
64
+ 'timeoutMs',
65
+ 'receipt',
66
+ 'publicSummary',
67
+ 'publicSafe',
68
+ ]);
69
+ const RECEIPT_ALLOWED_KEYS = new Set([
70
+ 'executionId',
71
+ 'attemptId',
72
+ 'jobId',
73
+ 'operationId',
74
+ 'idempotencyKey',
75
+ 'runnerId',
76
+ 'subagentId',
77
+ ]);
78
+ export function isHeadlessAdapterId(value) {
79
+ return HEADLESS_ADAPTER_IDS.includes(value);
80
+ }
81
+ export function validateHeadlessAdapterExecutionInput(input, expectedRuntimeId) {
82
+ const redactions = [];
83
+ const rejectedKeys = [];
84
+ if (!isRecord(input)) {
85
+ redactions.push(redaction('input', 'unsafe_key', 'value-denied'));
86
+ return rejectAdapterInput(HEADLESS_REASON_CODES.DIRECTIVE_REJECTED, 'Headless adapter input must be a public object.', redactions);
87
+ }
88
+ for (const key of Object.keys(input)) {
89
+ if (!ADAPTER_INPUT_ALLOWED_KEYS.has(key)) {
90
+ rejectedKeys.push(key);
91
+ redactions.push(redaction(key, unsafeKeyReason(key), 'key-denied'));
92
+ }
93
+ }
94
+ const publicSafe = input.publicSafe === true;
95
+ if (!publicSafe)
96
+ redactions.push(redaction('publicSafe', 'unsafe_key', 'value-denied'));
97
+ const promptKind = stringValue(input.promptKind);
98
+ if (promptKind !== 'yolo' && promptKind !== 'yolo-branchless-preparation' && promptKind !== 'yoloop') {
99
+ redactions.push(redaction('promptKind', 'unsafe_key', 'value-denied'));
100
+ }
101
+ const targetKind = stringValue(input.targetKind);
102
+ if (targetKind !== 'story' && targetKind !== 'epic') {
103
+ redactions.push(redaction('targetKind', 'unsafe_key', 'value-denied'));
104
+ }
105
+ const targetRef = stringValue(input.targetRef);
106
+ if (!targetRef || !isSafePublicText(targetRef) || SHELL_FRAGMENT_PATTERN.test(targetRef) || targetRef.includes('..')) {
107
+ redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
108
+ }
109
+ if ((promptKind === 'yolo' || promptKind === 'yolo-branchless-preparation')
110
+ && (targetKind !== 'story' || !targetRef || !STORY_REF_PATTERN.test(targetRef))) {
111
+ redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
112
+ }
113
+ if (promptKind === 'yoloop' && (targetKind !== 'epic' || !targetRef || !EPIC_REF_PATTERN.test(targetRef))) {
114
+ redactions.push(redaction('targetRef', 'prompt_body', 'value-denied'));
115
+ }
116
+ const storyId = optionalSafeString(input.storyId, 'storyId', redactions);
117
+ const epicId = optionalSafeString(input.epicId, 'epicId', redactions);
118
+ if (storyId && targetRef && (promptKind === 'yolo' || promptKind === 'yolo-branchless-preparation')
119
+ && storyId !== targetRef.replace(/^docs\/stories\//, '').replace(/\.story\.md$/, '')) {
120
+ redactions.push(redaction('storyId', 'prompt_body', 'value-denied'));
121
+ }
122
+ if (epicId && targetRef && promptKind === 'yoloop' && epicId !== targetRef.replace(/^docs\/epics\/epic-/, '').replace(/\.md$/, '')) {
123
+ redactions.push(redaction('epicId', 'prompt_body', 'value-denied'));
124
+ }
125
+ const runtimeId = stringValue(input.runtimeId);
126
+ if (!runtimeId || !isHeadlessAdapterId(runtimeId) || (expectedRuntimeId && runtimeId !== expectedRuntimeId)) {
127
+ redactions.push(redaction('runtimeId', 'unsafe_key', 'value-denied'));
128
+ }
129
+ const modelId = optionalSafeModelId(input.modelId, redactions);
130
+ const runtimeSource = optionalRuntimeSource(input.runtimeSource, redactions);
131
+ const timeoutMs = normalizeTimeout(input.timeoutMs, redactions);
132
+ const publicSummary = optionalPublicSummary(input.publicSummary, redactions);
133
+ const receipt = validateReceipt(input.receipt, redactions);
134
+ if (redactions.length > 0 || rejectedKeys.length > 0 || !publicSafe || !promptKind || !targetKind || !targetRef || !runtimeId) {
135
+ const modelRejected = redactions.some((item) => item.field === 'modelId');
136
+ const promptRejected = redactions.some((item) => item.reason === 'prompt_body');
137
+ return rejectAdapterInput(modelRejected
138
+ ? HEADLESS_REASON_CODES.MODEL_REJECTED
139
+ : promptRejected
140
+ ? HEADLESS_REASON_CODES.PROMPT_REJECTED
141
+ : HEADLESS_REASON_CODES.DIRECTIVE_REJECTED, promptRejected
142
+ ? 'Headless adapter target did not match a public prompt shape.'
143
+ : 'Headless adapter input failed public-safety validation.', redactions);
144
+ }
145
+ const normalized = {
146
+ promptKind: promptKind,
147
+ targetKind: targetKind,
148
+ targetRef,
149
+ ...(storyId ? { storyId } : {}),
150
+ ...(epicId ? { epicId } : {}),
151
+ runtimeId: runtimeId,
152
+ ...(modelId ? { modelId } : {}),
153
+ ...(runtimeSource ? { runtimeSource } : {}),
154
+ ...(timeoutMs ? { timeoutMs } : {}),
155
+ ...(receipt ? { receipt } : {}),
156
+ ...(publicSummary ? { publicSummary } : {}),
157
+ publicSafe: true,
158
+ };
159
+ const prompt = renderHeadlessPrompt(normalized);
160
+ return {
161
+ ok: true,
162
+ input: normalized,
163
+ prompt,
164
+ promptHash: hashPublicValue(prompt),
165
+ reasonCodes: [HEADLESS_REASON_CODES.OK],
166
+ publicSafe: true,
167
+ };
168
+ }
169
+ export function renderHeadlessPrompt(input) {
170
+ if (input.promptKind === 'yolo')
171
+ return `*yolo @${input.targetRef}`;
172
+ if (input.promptKind === 'yolo-branchless-preparation')
173
+ return `*yolo @${input.targetRef} branchless-preparation`;
174
+ return `*yoloop @${input.targetRef}`;
175
+ }
176
+ export function hashPublicValue(value) {
177
+ return `sha256:${createHash('sha256').update(value).digest('hex')}`;
178
+ }
179
+ export function createRejectedExecutionResult(adapterId, runtimeId, rejected, durationMs = 0) {
180
+ return {
181
+ status: 'failed',
182
+ adapterId,
183
+ runtimeId,
184
+ reasonCode: rejected.reasonCode,
185
+ reasonCodes: rejected.reasonCodes,
186
+ durationMs,
187
+ counts: {},
188
+ hashes: {},
189
+ publicSummary: boundPublicSummary(rejected.publicSummary),
190
+ redactionSummary: rejected.redactionSummary,
191
+ relativePaths: [],
192
+ publicSafe: true,
193
+ };
194
+ }
195
+ export function createUnavailableExecutionResult(adapterId, input, availability, durationMs = 0) {
196
+ return {
197
+ status: 'failed',
198
+ adapterId,
199
+ runtimeId: input.runtimeId,
200
+ ...(input.modelId ? { modelId: input.modelId } : {}),
201
+ ...(input.runtimeSource ? { runtimeSource: input.runtimeSource } : {}),
202
+ reasonCode: availability.reasonCode,
203
+ reasonCodes: availability.reasonCodes,
204
+ durationMs,
205
+ counts: {},
206
+ hashes: { prompt: hashPublicValue(renderHeadlessPrompt(input)) },
207
+ publicSummary: boundPublicSummary(availability.publicSummary),
208
+ redactionSummary: availability.redactionSummary,
209
+ relativePaths: [input.targetRef],
210
+ ...(input.receipt ? { receipt: input.receipt } : {}),
211
+ publicSafe: true,
212
+ };
213
+ }
214
+ export function normalizeHeadlessCommandResult(adapterId, input, commandResult) {
215
+ const prompt = renderHeadlessPrompt(input);
216
+ const stdoutHash = hashPublicValue(commandResult.stdout);
217
+ const stderrHash = hashPublicValue(commandResult.stderr);
218
+ const authEvidenceMatches = commandResult.timedOut || commandResult.exitCode === 0
219
+ ? 0
220
+ : countHeadlessAuthEvidenceMatches(commandResult.stdout, commandResult.stderr);
221
+ const status = commandResult.cancelled
222
+ ? 'failed'
223
+ : commandResult.timedOut
224
+ ? 'timed_out'
225
+ : commandResult.exitCode === 0
226
+ ? 'completed'
227
+ : 'failed';
228
+ const reasonCode = commandResult.cancelled
229
+ ? HEADLESS_REASON_CODES.EXECUTION_CANCELLED
230
+ : commandResult.timedOut
231
+ ? HEADLESS_REASON_CODES.EXECUTION_TIMEOUT
232
+ : commandResult.exitCode === 0
233
+ ? HEADLESS_REASON_CODES.EXECUTION_COMPLETED
234
+ : authEvidenceMatches > 0
235
+ ? HEADLESS_REASON_CODES.RUNTIME_AUTH_REQUIRED
236
+ : HEADLESS_REASON_CODES.EXECUTION_FAILED;
237
+ const redactionSummary = [
238
+ redaction('prompt', 'prompt_body', hashPublicValue(prompt)),
239
+ ];
240
+ if (commandResult.stdoutBytes > 0)
241
+ redactionSummary.push(redaction('stdout', 'raw_log', stdoutHash));
242
+ if (commandResult.stderrBytes > 0)
243
+ redactionSummary.push(redaction('stderr', 'raw_log', stderrHash));
244
+ return {
245
+ status,
246
+ adapterId,
247
+ runtimeId: input.runtimeId,
248
+ ...(input.modelId ? { modelId: input.modelId } : {}),
249
+ ...(input.runtimeSource ? { runtimeSource: input.runtimeSource } : {}),
250
+ reasonCode,
251
+ reasonCodes: [reasonCode, HEADLESS_REASON_CODES.RECEIPT_REDACTED],
252
+ exitCode: commandResult.exitCode,
253
+ signal: commandResult.signal ?? null,
254
+ durationMs: commandResult.durationMs,
255
+ counts: {
256
+ stdoutBytes: commandResult.stdoutBytes,
257
+ stderrBytes: commandResult.stderrBytes,
258
+ stdoutLines: countLines(commandResult.stdout),
259
+ stderrLines: countLines(commandResult.stderr),
260
+ ...(authEvidenceMatches > 0 ? { authEvidenceMatches } : {}),
261
+ },
262
+ hashes: {
263
+ prompt: hashPublicValue(prompt),
264
+ stdout: stdoutHash,
265
+ stderr: stderrHash,
266
+ },
267
+ publicSummary: status === 'completed'
268
+ ? 'Headless adapter completed with public-safe redacted output summary.'
269
+ : reasonCode === HEADLESS_REASON_CODES.EXECUTION_CANCELLED
270
+ ? 'Headless adapter was cancelled; raw output was redacted.'
271
+ : status === 'timed_out'
272
+ ? 'Headless adapter timed out; raw output was redacted.'
273
+ : reasonCode === HEADLESS_REASON_CODES.RUNTIME_AUTH_REQUIRED
274
+ ? 'Headless adapter requires local runtime authentication; raw output was redacted.'
275
+ : 'Headless adapter failed; raw output was redacted.',
276
+ redactionSummary,
277
+ relativePaths: [input.targetRef],
278
+ ...(input.receipt ? { receipt: input.receipt } : {}),
279
+ publicSafe: true,
280
+ };
281
+ }
282
+ export async function runHeadlessCommand(command, args, options = {}) {
283
+ const startedAt = Date.now();
284
+ const timeoutMs = normalizeRunnerTimeout(options.timeoutMs);
285
+ const maxOutputBytes = options.maxOutputBytes ?? 64_000;
286
+ if (options.signal?.aborted) {
287
+ return {
288
+ exitCode: null,
289
+ signal: 'SIGTERM',
290
+ timedOut: false,
291
+ cancelled: true,
292
+ durationMs: Date.now() - startedAt,
293
+ stdout: '',
294
+ stderr: '',
295
+ stdoutBytes: 0,
296
+ stderrBytes: 0,
297
+ };
298
+ }
299
+ return await new Promise((resolve) => {
300
+ const child = spawn(command, [...args], {
301
+ cwd: options.cwd,
302
+ env: options.env,
303
+ shell: false,
304
+ stdio: [options.localConsole ? 'pipe' : 'ignore', 'pipe', 'pipe'],
305
+ });
306
+ const localConsole = options.localConsole?.jobId
307
+ ? createLocalJobConsoleServer({
308
+ ...options.localConsole,
309
+ projectRoot: options.localConsole.projectRoot ?? options.cwd,
310
+ writeStdin: (chunk) => {
311
+ child.stdin?.write(chunk);
312
+ },
313
+ signalProcess: (signal) => child.kill(signal),
314
+ })
315
+ : undefined;
316
+ void localConsole?.start();
317
+ let stdout = '';
318
+ let stderr = '';
319
+ let stdoutBytes = 0;
320
+ let stderrBytes = 0;
321
+ let settled = false;
322
+ let timedOut = false;
323
+ let cancelled = false;
324
+ const abort = () => {
325
+ if (settled)
326
+ return;
327
+ cancelled = true;
328
+ child.kill('SIGTERM');
329
+ };
330
+ options.signal?.addEventListener('abort', abort, { once: true });
331
+ const cleanup = () => {
332
+ options.signal?.removeEventListener('abort', abort);
333
+ };
334
+ const append = (current, chunk, previousBytes) => {
335
+ const bytes = previousBytes + chunk.length;
336
+ if (current.length < maxOutputBytes) {
337
+ const remaining = maxOutputBytes - current.length;
338
+ return { text: current + chunk.toString('utf8').slice(0, remaining), bytes };
339
+ }
340
+ return { text: current, bytes };
341
+ };
342
+ child.stdout?.on('data', (chunk) => {
343
+ const next = append(stdout, chunk, stdoutBytes);
344
+ stdout = next.text;
345
+ stdoutBytes = next.bytes;
346
+ localConsole?.broadcastStdout(chunk);
347
+ });
348
+ child.stderr?.on('data', (chunk) => {
349
+ const next = append(stderr, chunk, stderrBytes);
350
+ stderr = next.text;
351
+ stderrBytes = next.bytes;
352
+ localConsole?.broadcastStderr(chunk);
353
+ });
354
+ const timer = setTimeout(() => {
355
+ timedOut = true;
356
+ child.kill('SIGTERM');
357
+ }, timeoutMs);
358
+ child.on('error', (error) => {
359
+ if (settled)
360
+ return;
361
+ settled = true;
362
+ clearTimeout(timer);
363
+ cleanup();
364
+ localConsole?.close({ exitCode: 127, signal: null });
365
+ const safeMessage = error instanceof Error ? error.message : String(error);
366
+ resolve({
367
+ exitCode: 127,
368
+ signal: null,
369
+ timedOut: false,
370
+ cancelled,
371
+ durationMs: Date.now() - startedAt,
372
+ stdout,
373
+ stderr: safeMessage,
374
+ stdoutBytes,
375
+ stderrBytes: Buffer.byteLength(safeMessage),
376
+ });
377
+ });
378
+ child.on('close', (exitCode, signal) => {
379
+ if (settled)
380
+ return;
381
+ settled = true;
382
+ clearTimeout(timer);
383
+ cleanup();
384
+ localConsole?.close({ exitCode, signal });
385
+ resolve({
386
+ exitCode,
387
+ signal,
388
+ timedOut,
389
+ cancelled,
390
+ durationMs: Date.now() - startedAt,
391
+ stdout,
392
+ stderr,
393
+ stdoutBytes,
394
+ stderrBytes,
395
+ });
396
+ });
397
+ });
398
+ }
399
+ export function adapterAvailabilityFailure(adapterId, commandName, reasonCode, publicSummary, redactionSummary = []) {
400
+ return {
401
+ ok: false,
402
+ adapterId,
403
+ ...(commandName ? { commandName } : {}),
404
+ reasonCode,
405
+ reasonCodes: [reasonCode],
406
+ publicSummary: boundPublicSummary(publicSummary),
407
+ redactionSummary,
408
+ publicSafe: true,
409
+ };
410
+ }
411
+ export function adapterAvailabilitySuccess(adapterId, commandName, publicSummary, details = {}) {
412
+ const result = {
413
+ ok: true,
414
+ adapterId,
415
+ commandName,
416
+ ...(details.versionText ? { versionHash: hashPublicValue(details.versionText) } : {}),
417
+ reasonCodes: [HEADLESS_REASON_CODES.OK],
418
+ publicSummary: boundPublicSummary(publicSummary),
419
+ publicSafe: true,
420
+ };
421
+ if (details.executablePath) {
422
+ Object.defineProperty(result, 'executablePath', {
423
+ value: details.executablePath,
424
+ enumerable: false,
425
+ configurable: false,
426
+ });
427
+ }
428
+ return result;
429
+ }
430
+ export function redaction(field, reason, evidence) {
431
+ return { field, reason, evidence, publicSafe: true };
432
+ }
433
+ export function boundPublicSummary(value) {
434
+ return value.length <= HEADLESS_PUBLIC_SUMMARY_MAX_CHARS
435
+ ? value
436
+ : `${value.slice(0, HEADLESS_PUBLIC_SUMMARY_MAX_CHARS)}…[TRUNCATED:${value.length - HEADLESS_PUBLIC_SUMMARY_MAX_CHARS}]`;
437
+ }
438
+ export function isSafeHeadlessModelId(value) {
439
+ return value.length <= HEADLESS_MODEL_ID_MAX_CHARS
440
+ && MODEL_ID_PATTERN.test(value)
441
+ && !UNSAFE_VALUE_PATTERN.test(value)
442
+ && !SHELL_FRAGMENT_PATTERN.test(value)
443
+ && !value.includes('..')
444
+ && !value.startsWith('/');
445
+ }
446
+ function rejectAdapterInput(reasonCode, publicSummary, redactions) {
447
+ return {
448
+ ok: false,
449
+ reasonCode,
450
+ reasonCodes: [reasonCode],
451
+ publicSummary: boundPublicSummary(publicSummary),
452
+ redactionSummary: redactions,
453
+ publicSafe: true,
454
+ };
455
+ }
456
+ function optionalSafeString(value, field, redactions) {
457
+ if (value === undefined)
458
+ return undefined;
459
+ const text = stringValue(value);
460
+ if (!text || !isSafePublicText(text) || SHELL_FRAGMENT_PATTERN.test(text)) {
461
+ redactions.push(redaction(field, unsafeKeyReason(field), 'value-denied'));
462
+ return undefined;
463
+ }
464
+ return text;
465
+ }
466
+ function optionalSafeModelId(value, redactions) {
467
+ if (value === undefined)
468
+ return undefined;
469
+ const modelId = stringValue(value);
470
+ if (!modelId || !isSafeHeadlessModelId(modelId)) {
471
+ redactions.push(redaction('modelId', 'unsafe_key', 'value-denied'));
472
+ return undefined;
473
+ }
474
+ return modelId;
475
+ }
476
+ function optionalRuntimeSource(value, redactions) {
477
+ if (value === undefined)
478
+ return undefined;
479
+ if (value === 'explicit' || value === 'origin' || value === 'default' || value === 'fallback')
480
+ return value;
481
+ redactions.push(redaction('runtimeSource', 'unsafe_key', 'value-denied'));
482
+ return undefined;
483
+ }
484
+ function normalizeTimeout(value, redactions) {
485
+ if (value === undefined)
486
+ return undefined;
487
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0 || value > MAX_TIMEOUT_MS) {
488
+ redactions.push(redaction('timeoutMs', 'unbounded_number', 'value-denied'));
489
+ return undefined;
490
+ }
491
+ return value;
492
+ }
493
+ function normalizeRunnerTimeout(value) {
494
+ if (!value || !Number.isInteger(value) || value <= 0 || value > MAX_TIMEOUT_MS)
495
+ return DEFAULT_TIMEOUT_MS;
496
+ return value;
497
+ }
498
+ function optionalPublicSummary(value, redactions) {
499
+ if (value === undefined)
500
+ return undefined;
501
+ const text = stringValue(value);
502
+ if (!text || text.length > HEADLESS_PUBLIC_SUMMARY_MAX_CHARS || !isSafePublicText(text)) {
503
+ redactions.push(redaction('publicSummary', 'unbounded_text', 'value-denied'));
504
+ return undefined;
505
+ }
506
+ return text;
507
+ }
508
+ function validateReceipt(value, redactions) {
509
+ if (value === undefined)
510
+ return undefined;
511
+ if (!isRecord(value)) {
512
+ redactions.push(redaction('receipt', 'unsafe_key', 'value-denied'));
513
+ return undefined;
514
+ }
515
+ const receipt = {};
516
+ for (const [key, child] of Object.entries(value)) {
517
+ if (!RECEIPT_ALLOWED_KEYS.has(key) || UNSAFE_KEY_PATTERN.test(key)) {
518
+ redactions.push(redaction(`receipt.${key}`, unsafeKeyReason(key), 'key-denied'));
519
+ continue;
520
+ }
521
+ const text = optionalSafeString(child, `receipt.${key}`, redactions);
522
+ if (text)
523
+ receipt[key] = text;
524
+ }
525
+ return Object.keys(receipt).length > 0 ? receipt : undefined;
526
+ }
527
+ function unsafeKeyReason(key) {
528
+ if (/prompt/i.test(key))
529
+ return 'prompt_body';
530
+ if (/std(?:out|err)|raw|log|transcript|stack/i.test(key))
531
+ return 'raw_log';
532
+ if (/url/i.test(key))
533
+ return 'private_url';
534
+ if (/path|cwd|argv|args|shell|command|binary|executable/i.test(key))
535
+ return 'executable_path';
536
+ if (/secret|token|password|authorization|api[_-]?key|license/i.test(key))
537
+ return 'secret_or_pii';
538
+ return 'unsafe_key';
539
+ }
540
+ function stringValue(value) {
541
+ return typeof value === 'string' ? value : undefined;
542
+ }
543
+ function isSafePublicText(value) {
544
+ return value.length > 0 && !UNSAFE_VALUE_PATTERN.test(value) && !/\0/.test(value);
545
+ }
546
+ function countLines(value) {
547
+ if (!value)
548
+ return 0;
549
+ return value.split(/\r?\n/).filter((line) => line.length > 0).length;
550
+ }
551
+ const HEADLESS_AUTH_EVIDENCE_PATTERNS = Object.freeze([
552
+ /\bauth(?:entication|orization)?\s+(?:is\s+)?required\b/i,
553
+ /\brequires?\s+authentication\b/i,
554
+ /\bmust\s+(?:log\s?in|authenticate|be\s+authenticated)\b/i,
555
+ /\bunauthenticated\b/i,
556
+ /\b(?:not|unauthenticated)\s+(?:logged\s+in|authenticated)\b/i,
557
+ /\blog\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,
558
+ /\bplease\s+(?:log\s?in|authenticate|sign\s?in)\b/i,
559
+ /\bsign\s?in\s+(?:required|to\s+continue|before\s+continuing)\b/i,
560
+ /\bsession\s+(?:expired|not\s+found|invalid)\b/i,
561
+ /\bcredentials?\s+(?:missing|required|not\s+found)\b/i,
562
+ ]);
563
+ function countHeadlessAuthEvidenceMatches(...values) {
564
+ const bounded = values
565
+ .filter((value) => value.length > 0)
566
+ .map((value) => value.slice(0, 8_000))
567
+ .join('\n');
568
+ if (!bounded)
569
+ return 0;
570
+ return HEADLESS_AUTH_EVIDENCE_PATTERNS.reduce((count, pattern) => count + (pattern.test(bounded) ? 1 : 0), 0);
571
+ }
572
+ function isRecord(value) {
573
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
574
+ }