@ornexus/neocortex 4.60.78 → 4.60.79

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