dsh-pstack 0.2.0-beta.1 → 0.2.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. package/LICENSE +2 -3
  2. package/README.md +135 -84
  3. package/README.zh.md +185 -0
  4. package/cordis.patch.yml +97 -27
  5. package/dist/host-contract-CUPSpeNk.d.mts +22 -0
  6. package/dist/index.d.mts +49 -238
  7. package/dist/index.mjs +250 -123
  8. package/dist/models.d.mts +44 -0
  9. package/dist/models.mjs +201 -0
  10. package/dist/paths-BT77khwm.mjs +48 -0
  11. package/dist/pstack/LICENSE +21 -0
  12. package/dist/pstack/README.md +291 -0
  13. package/dist/pstack/agents/poteto-agent.md +9 -0
  14. package/{assets → dist/pstack}/docs/guide/01-setup.md +13 -11
  15. package/{assets → dist/pstack}/docs/guide/02-poteto-mode.md +4 -4
  16. package/{assets → dist/pstack}/docs/guide/04-design.md +4 -4
  17. package/{assets → dist/pstack}/docs/guide/05-build-and-clean.md +2 -2
  18. package/{assets → dist/pstack}/docs/guide/06-verify-and-ship.md +13 -3
  19. package/{assets → dist/pstack}/docs/guide/07-overnight.md +15 -13
  20. package/{assets → dist/pstack}/docs/guide/09-make-it-yours.md +6 -2
  21. package/{assets → dist/pstack}/docs/guide/10-recipes-and-pitfalls.md +7 -5
  22. package/{assets → dist/pstack}/docs/guide/README.md +1 -1
  23. package/dist/pstack/docs/harness/dsh.md +98 -0
  24. package/{assets → dist/pstack}/skills/architect/SKILL.md +12 -12
  25. package/dist/pstack/skills/arena/SKILL.md +50 -0
  26. package/{assets → dist/pstack}/skills/automate-me/SKILL.md +14 -14
  27. package/{assets → dist/pstack}/skills/benchmark-checklist/SKILL.md +1 -1
  28. package/{assets → dist/pstack}/skills/blast-radius/SKILL.md +4 -6
  29. package/{assets → dist/pstack}/skills/correct/SKILL.md +1 -1
  30. package/{assets → dist/pstack}/skills/create-formal-verification-skill/SKILL.md +4 -2
  31. package/{assets → dist/pstack}/skills/create-verification-skill/SKILL.md +5 -5
  32. package/dist/pstack/skills/figure-it-out/SKILL.md +54 -0
  33. package/dist/pstack/skills/how/SKILL.md +38 -0
  34. package/{assets → dist/pstack}/skills/in-your-own-words/SKILL.md +1 -1
  35. package/dist/pstack/skills/interrogate/SKILL.md +33 -0
  36. package/{assets → dist/pstack}/skills/ketchup/SKILL.md +3 -5
  37. package/dist/pstack/skills/ketchup-video/SKILL.md +29 -0
  38. package/{assets → dist/pstack}/skills/maintain-formal-verification-skill/SKILL.md +1 -1
  39. package/{assets → dist/pstack}/skills/maintain-verification-skill/SKILL.md +3 -3
  40. package/dist/pstack/skills/make-bot-ui/SKILL.md +117 -0
  41. package/dist/pstack/skills/no-comments/SKILL.md +26 -0
  42. package/{assets → dist/pstack}/skills/poteto-help/SKILL.md +34 -31
  43. package/{assets → dist/pstack}/skills/poteto-help/references/prompting.md +1 -1
  44. package/{assets → dist/pstack}/skills/poteto-help/references/recipes.md +3 -3
  45. package/{assets → dist/pstack}/skills/poteto-mode/SKILL.md +20 -19
  46. package/dist/pstack/skills/poteto-mode/playbooks/authoring-a-skill.md +12 -0
  47. package/dist/pstack/skills/poteto-mode/playbooks/autonomous-run.md +13 -0
  48. package/dist/pstack/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  49. package/dist/pstack/skills/poteto-mode/playbooks/autopilot-stack.md +8 -0
  50. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/babysit.md +4 -4
  51. package/dist/pstack/skills/poteto-mode/playbooks/bug-fix.md +15 -0
  52. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/eval.md +3 -3
  53. package/dist/pstack/skills/poteto-mode/playbooks/feature.md +21 -0
  54. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/hillclimb.md +3 -3
  55. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/investigation.md +2 -2
  56. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/multi-phase-plan.md +23 -23
  57. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/opening-a-pr.md +6 -6
  58. package/dist/pstack/skills/poteto-mode/playbooks/orchestrate.md +25 -0
  59. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/pause-safely.md +2 -2
  60. package/dist/pstack/skills/poteto-mode/playbooks/perf-issue.md +25 -0
  61. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/prototype.md +4 -4
  62. package/dist/pstack/skills/poteto-mode/playbooks/refactoring.md +16 -0
  63. package/dist/pstack/skills/poteto-mode/playbooks/runtime-forensics.md +11 -0
  64. package/dist/pstack/skills/poteto-mode/playbooks/session-pickup.md +11 -0
  65. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/shipping.md +2 -2
  66. package/{assets → dist/pstack}/skills/poteto-mode/playbooks/trace-forensics.md +2 -2
  67. package/dist/pstack/skills/poteto-mode/playbooks/visual-parity.md +11 -0
  68. package/dist/pstack/skills/poteto-mode/playbooks/worktree-cleanup.md +12 -0
  69. package/{assets → dist/pstack}/skills/poteto-mode/scripts/check-plan.mjs +6 -8
  70. package/dist/pstack/skills/poteto-mode/scripts/check-plan.test.mjs +128 -0
  71. package/{assets/skills/poteto-mode/scripts/check-plan.test.mjs → dist/pstack/skills/poteto-mode/scripts/expect.mjs} +12 -101
  72. package/dist/pstack/skills/poteto-mode/scripts/support.mjs +93 -0
  73. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/cli.mjs +123 -0
  74. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +217 -0
  75. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.mjs +119 -0
  76. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/github.mjs +626 -0
  77. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/github.test.mjs +521 -0
  78. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/policy.mjs +657 -0
  79. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +523 -0
  80. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/render.mjs +106 -0
  81. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/types.mjs +9 -0
  82. package/dist/pstack/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +5 -0
  83. package/{assets → dist/pstack}/skills/poteto-mode/scripts/worktree-audit.mjs +15 -22
  84. package/dist/pstack/skills/poteto-mode/scripts/worktree-audit.test.mjs +134 -0
  85. package/{assets → dist/pstack}/skills/principle-attack-the-premise/SKILL.md +1 -1
  86. package/{assets → dist/pstack}/skills/principle-boundary-discipline/SKILL.md +1 -1
  87. package/{assets → dist/pstack}/skills/principle-encode-lessons-in-structure/SKILL.md +1 -1
  88. package/{assets → dist/pstack}/skills/principle-exhaust-the-design-space/SKILL.md +1 -1
  89. package/{assets → dist/pstack}/skills/principle-experience-first/SKILL.md +1 -1
  90. package/{assets → dist/pstack}/skills/principle-explain-the-number/SKILL.md +3 -2
  91. package/{assets → dist/pstack}/skills/principle-fix-root-causes/SKILL.md +1 -1
  92. package/{assets → dist/pstack}/skills/principle-laziness-protocol/SKILL.md +1 -1
  93. package/{assets → dist/pstack}/skills/principle-make-operations-idempotent/SKILL.md +1 -1
  94. package/{assets → dist/pstack}/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +1 -1
  95. package/{assets → dist/pstack}/skills/principle-minimize-reader-load/SKILL.md +1 -1
  96. package/{assets → dist/pstack}/skills/principle-model-the-domain/SKILL.md +1 -1
  97. package/{assets → dist/pstack}/skills/principle-never-block-on-the-human/SKILL.md +1 -1
  98. package/{assets → dist/pstack}/skills/principle-outcome-oriented-execution/SKILL.md +1 -1
  99. package/{assets → dist/pstack}/skills/principle-prove-it-works/SKILL.md +2 -2
  100. package/{assets → dist/pstack}/skills/principle-redesign-from-first-principles/SKILL.md +1 -1
  101. package/{assets → dist/pstack}/skills/principle-separate-before-serializing-shared-state/SKILL.md +1 -1
  102. package/{assets → dist/pstack}/skills/principle-sequence-verifiable-units/SKILL.md +1 -1
  103. package/{assets → dist/pstack}/skills/principle-subtract-before-you-add/SKILL.md +1 -1
  104. package/{assets → dist/pstack}/skills/principle-test-behavior-not-implementation/SKILL.md +1 -1
  105. package/{assets → dist/pstack}/skills/principle-type-system-discipline/SKILL.md +1 -1
  106. package/dist/pstack/skills/recall/SKILL.md +37 -0
  107. package/dist/pstack/skills/reflect/SKILL.md +71 -0
  108. package/{assets → dist/pstack}/skills/reflect/references/divergent-reviewer.md +4 -4
  109. package/{assets → dist/pstack}/skills/reflect/references/judgment-reviewer.md +2 -2
  110. package/{assets → dist/pstack}/skills/reflect/references/synthesizer.md +5 -5
  111. package/{assets → dist/pstack}/skills/reflect/references/tooling-reviewer.md +2 -2
  112. package/dist/pstack/skills/setup-pstack/SKILL.md +80 -0
  113. package/{assets → dist/pstack}/skills/sharpen/SKILL.md +1 -1
  114. package/{assets → dist/pstack}/skills/show-me-your-work/SKILL.md +8 -8
  115. package/{assets → dist/pstack}/skills/show-me-your-work/scripts/log.mjs +1 -3
  116. package/dist/pstack/skills/show-me-your-work/scripts/log.test.mjs +56 -0
  117. package/dist/pstack/skills/statechart/SKILL.md +82 -0
  118. package/dist/pstack/skills/statechart/references/render.md +93 -0
  119. package/dist/pstack/skills/statechart/scripts/backends/cfg.mjs +31 -0
  120. package/dist/pstack/skills/statechart/scripts/backends/mermaid.mjs +186 -0
  121. package/dist/pstack/skills/statechart/scripts/backends/plain-text.mjs +62 -0
  122. package/dist/pstack/skills/statechart/scripts/backends/report.mjs +84 -0
  123. package/dist/pstack/skills/statechart/scripts/frontends/config.mjs +268 -0
  124. package/dist/pstack/skills/statechart/scripts/frontends/dot.mjs +67 -0
  125. package/dist/pstack/skills/statechart/scripts/frontends/marks.mjs +94 -0
  126. package/dist/pstack/skills/statechart/scripts/frontends/messages.mjs +48 -0
  127. package/dist/pstack/skills/statechart/scripts/frontends/spec.mjs +101 -0
  128. package/dist/pstack/skills/statechart/scripts/frontends/trace.mjs +39 -0
  129. package/dist/pstack/skills/statechart/scripts/frontends/value.mjs +180 -0
  130. package/dist/pstack/skills/statechart/scripts/frontends/verdict.mjs +40 -0
  131. package/dist/pstack/skills/statechart/scripts/frontends/view.mjs +99 -0
  132. package/dist/pstack/skills/statechart/scripts/ir.mjs +277 -0
  133. package/dist/pstack/skills/statechart/scripts/passes/annotate.mjs +92 -0
  134. package/dist/pstack/skills/statechart/scripts/passes/label.mjs +210 -0
  135. package/dist/pstack/skills/statechart/scripts/passes/lift.mjs +84 -0
  136. package/dist/pstack/skills/statechart/scripts/passes/loop-check.mjs +47 -0
  137. package/dist/pstack/skills/statechart/scripts/passes/paths.mjs +72 -0
  138. package/dist/pstack/skills/statechart/scripts/passes/reach.mjs +135 -0
  139. package/dist/pstack/skills/statechart/scripts/passes/region-check.mjs +82 -0
  140. package/dist/pstack/skills/statechart/scripts/passes/regions.mjs +268 -0
  141. package/dist/pstack/skills/statechart/scripts/pipeline.mjs +72 -0
  142. package/dist/pstack/skills/statechart/scripts/run.mjs +440 -0
  143. package/dist/pstack/skills/statechart/scripts/statechart.mjs +155 -0
  144. package/dist/pstack/skills/statechart/scripts/statechart.test.mjs +198 -0
  145. package/dist/pstack/skills/statechart/scripts/worker.mjs +31 -0
  146. package/dist/pstack/skills/swarm/SKILL.md +43 -0
  147. package/{assets → dist/pstack}/skills/tdd/SKILL.md +1 -1
  148. package/{assets → dist/pstack}/skills/teach/SKILL.md +2 -2
  149. package/{assets → dist/pstack}/skills/technical-writing/SKILL.md +1 -1
  150. package/{assets → dist/pstack}/skills/typescript-best-practices/SKILL.md +3 -6
  151. package/{assets → dist/pstack}/skills/why/SKILL.md +8 -8
  152. package/dist/script.d.mts +9 -111
  153. package/dist/script.mjs +32 -329
  154. package/dist/skill.d.mts +38 -0
  155. package/dist/skill.mjs +183 -0
  156. package/dist/skills/authored/decision-audit/SKILL.md +99 -0
  157. package/dist/skills/authored/decision-audit/SKILL.zh.md +99 -0
  158. package/dist/skills/authored/decision-audit/references/recover-commit.md +17 -0
  159. package/dist/skills/authored/decision-audit/references/recover-commit.zh.md +17 -0
  160. package/dist/skills/authored/decision-write/SKILL.md +131 -0
  161. package/dist/skills/authored/decision-write/SKILL.zh.md +131 -0
  162. package/dist/skills/authored/decision-write/references/land.md +48 -0
  163. package/dist/skills/authored/decision-write/references/land.zh.md +48 -0
  164. package/dist/skills/authored/setup-project-docs/SKILL.md +58 -0
  165. package/dist/skills/authored/setup-project-docs/SKILL.zh.md +58 -0
  166. package/dist/skills/authored/setup-project-docs/references/decision-conventions.md +11 -0
  167. package/dist/skills/authored/setup-project-docs/references/decision-conventions.zh.md +11 -0
  168. package/dist/skills/vendored/retro/SKILL.md +44 -0
  169. package/dist/skills/vendored/retro/agents/openai.yaml +5 -0
  170. package/dist/skills/vendored/writing-for-agents/SKILL-MECHANICS.md +22 -0
  171. package/dist/skills/vendored/writing-for-agents/SKILL.md +81 -0
  172. package/dist/skills/vendored/writing-for-agents/agents/openai.yaml +3 -0
  173. package/dist/subagent.d.mts +56 -193
  174. package/dist/subagent.mjs +443 -741
  175. package/locale/en.json +3 -2
  176. package/locale/zh.json +3 -2
  177. package/package.json +63 -66
  178. package/assets/agents/poteto-agent.md +0 -8
  179. package/assets/docs/harness/dsh.md +0 -60
  180. package/assets/docs/pstack-models.example.md +0 -54
  181. package/assets/skills/arena/SKILL.md +0 -50
  182. package/assets/skills/figure-it-out/SKILL.md +0 -54
  183. package/assets/skills/how/SKILL.md +0 -38
  184. package/assets/skills/interrogate/SKILL.md +0 -71
  185. package/assets/skills/interrogate/references/code-quality-review.md +0 -47
  186. package/assets/skills/interrogate/references/lead-judgment.md +0 -39
  187. package/assets/skills/interrogate/references/reviewer-prompt.md +0 -62
  188. package/assets/skills/interrogate/references/rubric.md +0 -77
  189. package/assets/skills/no-comments/SKILL.md +0 -26
  190. package/assets/skills/poteto-mode/playbooks/authoring-a-skill.md +0 -12
  191. package/assets/skills/poteto-mode/playbooks/autonomous-run.md +0 -15
  192. package/assets/skills/poteto-mode/playbooks/autopilot-full.md +0 -25
  193. package/assets/skills/poteto-mode/playbooks/autopilot-stack.md +0 -12
  194. package/assets/skills/poteto-mode/playbooks/bug-fix.md +0 -15
  195. package/assets/skills/poteto-mode/playbooks/feature.md +0 -21
  196. package/assets/skills/poteto-mode/playbooks/orchestrate.md +0 -112
  197. package/assets/skills/poteto-mode/playbooks/perf-issue.md +0 -25
  198. package/assets/skills/poteto-mode/playbooks/refactoring.md +0 -16
  199. package/assets/skills/poteto-mode/playbooks/runtime-forensics.md +0 -11
  200. package/assets/skills/poteto-mode/playbooks/session-pickup.md +0 -11
  201. package/assets/skills/poteto-mode/playbooks/visual-parity.md +0 -11
  202. package/assets/skills/poteto-mode/playbooks/worktree-cleanup.md +0 -20
  203. package/assets/skills/poteto-mode/scripts/orch/orch.mjs +0 -4282
  204. package/assets/skills/poteto-mode/scripts/orch/orch.test.mjs +0 -2042
  205. package/assets/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +0 -5101
  206. package/assets/skills/poteto-mode/scripts/watch-pr/github.test.mjs +0 -1177
  207. package/assets/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +0 -1441
  208. package/assets/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +0 -4601
  209. package/assets/skills/recall/SKILL.md +0 -37
  210. package/assets/skills/reflect/SKILL.md +0 -69
  211. package/assets/skills/setup-pstack/SKILL.md +0 -67
  212. package/assets/skills/swarm/SKILL.md +0 -43
  213. package/dist/frontmatter-BQX3ekwP.mjs +0 -229
  214. package/dist/frontmatter-BQX3ekwP.mjs.map +0 -1
  215. package/dist/history.d.mts +0 -429
  216. package/dist/history.mjs +0 -1129
  217. package/dist/history.mjs.map +0 -1
  218. package/dist/host-contract-o47JH_r8.d.mts +0 -527
  219. package/dist/index.mjs.map +0 -1
  220. package/dist/paths-D_JlVmBk.mjs +0 -42
  221. package/dist/paths-D_JlVmBk.mjs.map +0 -1
  222. package/dist/script.mjs.map +0 -1
  223. package/dist/subagent.mjs.map +0 -1
  224. /package/{static/icon.png → assets/logo.png} +0 -0
  225. /package/{assets → dist/pstack}/agents/comment-sicko.md +0 -0
  226. /package/{assets → dist/pstack}/docs/guide/03-understand.md +0 -0
  227. /package/{assets → dist/pstack}/docs/guide/08-principles.md +0 -0
  228. /package/{assets → dist/pstack}/docs/guide/images/design.jpg +0 -0
  229. /package/{assets → dist/pstack}/docs/guide/images/overnight.jpg +0 -0
  230. /package/{assets → dist/pstack}/docs/guide/images/recipes.jpg +0 -0
  231. /package/{assets → dist/pstack}/docs/guide/images/router.jpg +0 -0
  232. /package/{assets → dist/pstack}/docs/guide/images/understanding.jpg +0 -0
  233. /package/{assets → dist/pstack}/docs/guide/images/verification.jpg +0 -0
  234. /package/{assets → dist/pstack}/skills/architect/references/design-red-flags.md +0 -0
  235. /package/{assets → dist/pstack}/skills/architect/references/rationale-template.md +0 -0
  236. /package/{assets → dist/pstack}/skills/architect/references/runner-prompt.md +0 -0
  237. /package/{assets → dist/pstack}/skills/bro/SKILL.md +0 -0
  238. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/README.md +0 -0
  239. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/create-note.md +0 -0
  240. /package/{assets → dist/pstack}/skills/create-verification-skill/references/feature-map-example/search.md +0 -0
  241. /package/{assets → dist/pstack}/skills/how/references/explainer-prompt.md +0 -0
  242. /package/{assets → dist/pstack}/skills/how/references/explorer-prompt.md +0 -0
  243. /package/{assets → dist/pstack}/skills/poteto-mode/references/bugbot-triage.md +0 -0
  244. /package/{assets → dist/pstack}/skills/principle-build-the-lever/SKILL.md +0 -0
  245. /package/{assets → dist/pstack}/skills/principle-foundational-thinking/SKILL.md +0 -0
  246. /package/{assets → dist/pstack}/skills/principle-guard-the-context-window/SKILL.md +0 -0
  247. /package/{assets → dist/pstack}/skills/show-me-your-work/references/decision-log-template.tsv +0 -0
  248. /package/{assets → dist/pstack}/skills/typescript-best-practices/references/patterns.md +0 -0
  249. /package/{assets → dist/pstack}/skills/unslop/SKILL.md +0 -0
  250. /package/{assets → dist/pstack}/skills/why/references/epistemics.md +0 -0
  251. /package/{assets → dist/pstack}/skills/why/references/investigator-prompt.md +0 -0
  252. /package/{assets → dist/pstack}/skills/why/references/source-playbook.md +0 -0
  253. /package/{assets → dist/pstack}/skills/why/references/sources/code-archaeology.md +0 -0
  254. /package/{assets → dist/pstack}/skills/why/references/sources/databricks.md +0 -0
  255. /package/{assets → dist/pstack}/skills/why/references/sources/datadog.md +0 -0
  256. /package/{assets → dist/pstack}/skills/why/references/sources/incident-postmortem.md +0 -0
  257. /package/{assets → dist/pstack}/skills/why/references/sources/linear.md +0 -0
  258. /package/{assets → dist/pstack}/skills/why/references/sources/notion.md +0 -0
  259. /package/{assets → dist/pstack}/skills/why/references/sources/sentry.md +0 -0
  260. /package/{assets → dist/pstack}/skills/why/references/sources/slack.md +0 -0
  261. /package/{assets → dist/pstack}/skills/why/references/synthesizer-prompt.md +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"script.mjs","names":["spawnChild"],"sources":["../scripts/runtime-manifest.ts","../src/script.ts"],"sourcesContent":["/**\n * The shipped script runtime, as one table.\n *\n * pstack ships five CLIs and five test bundles. None of them may require Bun,\n * bash, a `node_modules` tree beside them, or an install step: the npm package\n * installs into a profile whose workspace resolves no peer dependencies, and the\n * Desktop build runs the same package under Electron, where `node` is not on\n * `PATH`.\n *\n * So every shipped script is a single-file Node bundle produced by\n * `scripts/build-runtime.ts` and copied into `assets/` by `scripts/build-assets.ts`.\n * This module is the one place that says what ships and where it lands; the\n * bundler, the asset generator, and the checks read it instead of keeping their\n * own copy.\n *\n * Two source origins:\n *\n * - `upstream` — the pinned upstream TypeScript, rewritten by\n * `RUNTIME_SOURCE_PATCHES` before it is bundled. `orch`, `watch-pr`,\n * `check-plan` and their tests stay upstream sources so they keep tracking their\n * original instead of becoming a fork of it.\n * - `authored` — this repository's own Node implementation under\n * `scripts/runtime/`. `log` and `worktree-audit` are here because their upstream\n * form is a shell script; their behaviour is specified by that script and\n * re-implemented.\n */\n\n/** Where a shipped artifact's source text comes from. */\nexport type RuntimeSourceKind = \"authored\" | \"upstream\";\n\nexport interface RuntimeSource {\n readonly kind: RuntimeSourceKind;\n /** Repository-relative POSIX path. */\n readonly path: string;\n}\n\nexport interface RuntimeEntry {\n /** Stable id, used in logs and by the Host tool's `id` enum. */\n readonly id: string;\n /** A runnable CLI, or a test bundle run by `node --test`. */\n readonly kind: \"cli\" | \"test\";\n /** Bundler entry file. */\n readonly entry: RuntimeSource;\n /** Output path relative to `runtime/`. */\n readonly out: string;\n /** The same path below `assets/`. */\n readonly assetPath: string;\n /** Whether the artifact is meant to be executed directly. */\n readonly executable: boolean;\n /**\n * Every source the build touches, entry first.\n *\n * The bundler follows imports itself, so this is not a module list: it is the\n * set staged before the build and the set whose patches must all land. A file\n * missing here would either fail to resolve or silently skip its rewrite.\n */\n readonly sources: readonly RuntimeSource[];\n /** One line for `build-runtime` output. */\n readonly summary: string;\n}\n\n/** Upstream script directories whose contents the built artifacts replace. */\nexport const REPLACED_SCRIPT_DIRECTORIES: readonly string[] = [\n \"skills/poteto-mode/scripts/\",\n \"skills/show-me-your-work/scripts/\",\n];\n\n/** The directory holding the authored runtime sources. */\nexport const AUTHORED_ROOT = \"scripts/runtime/\";\n\n/** Support modules the ported tests import instead of `bun:test`. */\nexport const TEST_SUPPORT: readonly RuntimeSource[] = [\n { kind: \"authored\", path: `${AUTHORED_ROOT}tests/expect.ts` },\n { kind: \"authored\", path: `${AUTHORED_ROOT}tests/support.ts` },\n];\n\n/**\n * Where the support modules land inside the staged source tree.\n *\n * `support.ts` re-exports from `./expect.ts`, so the pair has to stay adjacent.\n * Staging them at the root of `poteto-mode/scripts` lets `orch/` and `watch-pr/`\n * both reach them through `../support.ts` with one copy, instead of one copy per\n * test directory.\n */\nexport const TEST_SUPPORT_STAGED_PREFIX = \"skills/poteto-mode/scripts/\";\n\n/** `TEST_SUPPORT` as entry sources, so a test entry declares what it imports. */\nconst TEST_SUPPORT_ROOTS: readonly RuntimeSource[] = TEST_SUPPORT;\n\nconst upstreamScript = (path: string): RuntimeSource => ({\n kind: \"upstream\",\n path: `skills/poteto-mode/scripts/${path}`,\n});\n\n/** CLI artifacts, in the order the reviews and the prose name them. */\nexport const RUNTIME_CLIS: readonly RuntimeEntry[] = [\n {\n id: \"check-plan\",\n kind: \"cli\",\n entry: upstreamScript(\"check-plan.mjs\"),\n out: \"check-plan.mjs\",\n assetPath: \"skills/poteto-mode/scripts/check-plan.mjs\",\n executable: true,\n sources: [upstreamScript(\"check-plan.mjs\")],\n summary: \"plan-shape checker\",\n },\n {\n id: \"orch\",\n kind: \"cli\",\n entry: upstreamScript(\"orch/orch.ts\"),\n out: \"orch/orch.mjs\",\n assetPath: \"skills/poteto-mode/scripts/orch/orch.mjs\",\n executable: true,\n sources: [upstreamScript(\"orch/orch.ts\"), upstreamScript(\"orch/store.ts\")],\n summary: \"orchestration bookkeeping store\",\n },\n {\n id: \"watch-pr\",\n kind: \"cli\",\n entry: upstreamScript(\"watch-pr/watch-pr\"),\n out: \"watch-pr/watch-pr.mjs\",\n assetPath: \"skills/poteto-mode/scripts/watch-pr/watch-pr.mjs\",\n executable: true,\n sources: [\n upstreamScript(\"watch-pr/watch-pr\"),\n upstreamScript(\"watch-pr/cli.ts\"),\n upstreamScript(\"watch-pr/github.ts\"),\n upstreamScript(\"watch-pr/policy.ts\"),\n upstreamScript(\"watch-pr/render.ts\"),\n upstreamScript(\"watch-pr/types.ts\"),\n ],\n summary: \"pull-request watcher\",\n },\n {\n id: \"worktree-audit\",\n kind: \"cli\",\n entry: { kind: \"authored\", path: `${AUTHORED_ROOT}worktree-audit.ts` },\n out: \"worktree-audit.mjs\",\n assetPath: \"skills/poteto-mode/scripts/worktree-audit.mjs\",\n executable: true,\n sources: [{ kind: \"authored\", path: `${AUTHORED_ROOT}worktree-audit.ts` }],\n summary: \"read-only worktree audit\",\n },\n {\n id: \"log\",\n kind: \"cli\",\n entry: { kind: \"authored\", path: `${AUTHORED_ROOT}log.ts` },\n out: \"log.mjs\",\n assetPath: \"skills/show-me-your-work/scripts/log.mjs\",\n executable: true,\n sources: [{ kind: \"authored\", path: `${AUTHORED_ROOT}log.ts` }],\n summary: \"decision-log row appender\",\n },\n];\n\n/** Test bundles, run by `node --test` from a copy with no install step. */\nexport const RUNTIME_TESTS: readonly RuntimeEntry[] = [\n {\n id: \"check-plan-test\",\n kind: \"test\",\n entry: upstreamScript(\"check-plan.test.ts\"),\n out: \"check-plan.test.mjs\",\n assetPath: \"skills/poteto-mode/scripts/check-plan.test.mjs\",\n executable: false,\n sources: [upstreamScript(\"check-plan.test.ts\")],\n summary: \"check-plan tests\",\n },\n {\n id: \"orch-test\",\n kind: \"test\",\n entry: upstreamScript(\"orch/orch.test.ts\"),\n out: \"orch/orch.test.mjs\",\n assetPath: \"skills/poteto-mode/scripts/orch/orch.test.mjs\",\n executable: false,\n sources: [\n upstreamScript(\"orch/orch.test.ts\"),\n upstreamScript(\"orch/store.ts\"),\n ...TEST_SUPPORT_ROOTS,\n ],\n summary: \"orch tests\",\n },\n {\n id: \"watch-pr-cli-test\",\n kind: \"test\",\n entry: upstreamScript(\"watch-pr/cli.test.ts\"),\n out: \"watch-pr/cli.test.mjs\",\n assetPath: \"skills/poteto-mode/scripts/watch-pr/cli.test.mjs\",\n executable: false,\n sources: [\n upstreamScript(\"watch-pr/cli.test.ts\"),\n upstreamScript(\"watch-pr/cli.ts\"),\n upstreamScript(\"watch-pr/github.ts\"),\n upstreamScript(\"watch-pr/policy.ts\"),\n upstreamScript(\"watch-pr/render.ts\"),\n upstreamScript(\"watch-pr/types.ts\"),\n upstreamScript(\"watch-pr/fakes.test-helper.ts\"),\n ...TEST_SUPPORT_ROOTS,\n ],\n summary: \"watch-pr argument and rendering tests\",\n },\n {\n id: \"watch-pr-github-test\",\n kind: \"test\",\n entry: upstreamScript(\"watch-pr/github.test.ts\"),\n out: \"watch-pr/github.test.mjs\",\n assetPath: \"skills/poteto-mode/scripts/watch-pr/github.test.mjs\",\n executable: false,\n sources: [\n upstreamScript(\"watch-pr/github.test.ts\"),\n upstreamScript(\"watch-pr/github.ts\"),\n upstreamScript(\"watch-pr/types.ts\"),\n upstreamScript(\"watch-pr/fakes.test-helper.ts\"),\n ...TEST_SUPPORT_ROOTS,\n ],\n summary: \"watch-pr GitHub reader tests\",\n },\n {\n id: \"watch-pr-policy-test\",\n kind: \"test\",\n entry: upstreamScript(\"watch-pr/policy.test.ts\"),\n out: \"watch-pr/policy.test.mjs\",\n assetPath: \"skills/poteto-mode/scripts/watch-pr/policy.test.mjs\",\n executable: false,\n sources: [\n upstreamScript(\"watch-pr/policy.test.ts\"),\n upstreamScript(\"watch-pr/policy.ts\"),\n upstreamScript(\"watch-pr/github.ts\"),\n upstreamScript(\"watch-pr/types.ts\"),\n upstreamScript(\"watch-pr/fakes.test-helper.ts\"),\n ...TEST_SUPPORT_ROOTS,\n ],\n summary: \"watch-pr policy and queue tests\",\n },\n];\n\n/** Every artifact, CLIs first. */\nexport const RUNTIME_ENTRIES: readonly RuntimeEntry[] = [...RUNTIME_CLIS, ...RUNTIME_TESTS];\n\n/** The shebang every emitted artifact starts with. */\nexport const SHEBANG = \"#!/usr/bin/env node\\n\";\n\n/** True when a repository-relative upstream path is replaced by a built artifact. */\nexport function isReplacedUpstreamScript(upstreamRelativePath: string): boolean {\n return REPLACED_SCRIPT_DIRECTORIES.some((prefix) => upstreamRelativePath.startsWith(prefix));\n}\n\n/** Look up one entry by id. */\nexport function runtimeEntry(id: string): RuntimeEntry {\n const entry = RUNTIME_ENTRIES.find((candidate) => candidate.id === id);\n if (entry === undefined) throw new Error(`unknown runtime entry \"${id}\"`);\n return entry;\n}\n","/**\n * `pstack_script`: run a bundled pstack script through the Host's own runtime.\n *\n * Every shipped CLI is a Node artefact inside this package. A model could always\n * write `node <path> …` into a shell, and that is exactly what breaks in the\n * Desktop build: Electron runs the same CLI, so `node` is not on `PATH` there.\n *\n * So the entry point is a tool, not a command. The tool spawns the artefact with\n * `process.execPath` — whichever binary is already running this Host, Node or\n * Electron — and passes `ELECTRON_RUN_AS_NODE=1` only when it is Electron. That is\n * what makes the npm CLI and the Desktop build behave the same without depending on\n * anything in `PATH`.\n *\n * The tool never accepts a path or a command string. `id` is a closed enum over the\n * shipped artefacts, resolved from this package, so a call cannot reach a script the\n * package does not contain. It is not a general shell: there is no `sh -c`, no glob\n * expansion by a shell, and no way to name another executable.\n */\n\nimport { spawn as spawnChild, type ChildProcess } from \"node:child_process\";\n\nimport type {\n JobId,\n JobsHost,\n JsonSchemaNode,\n SessionId,\n ToolDefinition,\n ToolRunContext,\n ToolsHost,\n WorkingDirectoryHost,\n} from \"./host-contract.ts\";\nimport { RUNTIME_CLIS } from \"../scripts/runtime-manifest.ts\";\nimport { ASSETS_ROOT } from \"./paths.ts\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\n/** Model-facing tool name. */\nexport const TOOL_NAME = \"pstack_script\";\n\n/** The shipped scripts this tool may run, in display order. */\nexport const SCRIPT_IDS = RUNTIME_CLIS.map((entry) => entry.id);\n\nexport type ScriptId = (typeof SCRIPT_IDS)[number];\n\n/** Default wall-clock limit for a foreground run. */\nexport const DEFAULT_TIMEOUT_MS = 120_000;\n\n/** Bounds a caller may set for one foreground run. */\nexport const MAX_TIMEOUT_MS = 600_000;\n\n/** Default cap on captured bytes per stream. */\nexport const DEFAULT_OUTPUT_LIMIT_BYTES = 64 * 1024;\n\n/** Raised for an argument problem, before anything is spawned. */\nexport class ScriptInputError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScriptInputError\";\n }\n}\n\n/** Raised when a shipped artefact is missing from this install. */\nexport class ScriptMissingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ScriptMissingError\";\n }\n}\n\n/** One parsed call. */\nexport interface ScriptArgs {\n readonly id: ScriptId;\n readonly args: readonly string[];\n readonly cwd?: string;\n readonly background: boolean;\n readonly timeoutMs?: number;\n readonly outputLimitBytes?: number;\n}\n\n/** What a foreground run produced. */\nexport interface ScriptResult {\n readonly kind: \"foreground\";\n readonly id: ScriptId;\n readonly exitCode: number;\n readonly signal: NodeJS.Signals | null;\n readonly timedOut: boolean;\n readonly stdout: string;\n readonly stderr: string;\n /** True when a stream was cut off at the limit. */\n readonly stdoutTruncated: boolean;\n readonly stderrTruncated: boolean;\n readonly durationMs: number;\n}\n\n/** What a background run produced. */\nexport interface ScriptJobResult {\n readonly kind: \"background\";\n readonly id: ScriptId;\n readonly jobId: JobId;\n readonly status: string;\n}\n\n/** Either outcome, as the model sees it. */\nexport type ScriptOutcome = ScriptResult | ScriptJobResult;\n\n/** Absolute path of one shipped artefact. */\nexport function scriptPath(id: ScriptId): string {\n const entry = RUNTIME_CLIS.find((candidate) => candidate.id === id);\n if (entry === undefined) throw new ScriptInputError(`unknown script id \"${String(id)}\"`);\n // `assetPath` is relative to the generated tree, e.g.\n // `skills/poteto-mode/scripts/orch/orch.mjs`, which is exactly what `ASSETS_ROOT`\n // is the parent of.\n return join(ASSETS_ROOT, ...entry.assetPath.split(\"/\"));\n}\n\n/**\n * The environment a child gets.\n *\n * The one rule is the Electron selector. Under Electron, `process.execPath` is the\n * Desktop binary, which starts a browser window unless `ELECTRON_RUN_AS_NODE=1` tells\n * it to behave as Node. Under plain Node the variable is inert — Node ignores it —\n * so setting it unconditionally would also work; it is conditional here so the\n * environment of a normal run stays exactly the caller's, and the one code path that\n * needs it is visible.\n */\nexport function scriptEnvironment(\n base: NodeJS.ProcessEnv = process.env,\n // Only the field this decision reads is named, so a test can pass the two shapes\n // that matter without fabricating a full `process.versions`. The cast is because\n // `ProcessVersions` types `electron` as an optional literal this file does not own.\n versions: { readonly electron?: string } = process.versions as { readonly electron?: string },\n): NodeJS.ProcessEnv {\n if (versions.electron === undefined) return { ...base };\n return { ...base, ELECTRON_RUN_AS_NODE: \"1\" };\n}\n\n/** Validate the raw tool arguments. */\nexport function parseScriptArgs(raw: unknown): ScriptArgs {\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new ScriptInputError(\"arguments must be an object\");\n }\n const record = raw as Record<string, unknown>;\n\n for (const key of Object.keys(record)) {\n if (![\"id\", \"args\", \"cwd\", \"background\", \"timeoutMs\", \"outputLimitBytes\"].includes(key)) {\n throw new ScriptInputError(`unknown argument \"${key}\"`);\n }\n }\n\n const id = record[\"id\"];\n if (typeof id !== \"string\") throw new ScriptInputError('\"id\" must be a string');\n if (!(SCRIPT_IDS as readonly string[]).includes(id)) {\n throw new ScriptInputError(\n `\"id\" must be one of ${SCRIPT_IDS.join(\", \")}; this tool runs bundled scripts only`,\n );\n }\n\n const rawArgs = record[\"args\"];\n if (rawArgs !== undefined && !Array.isArray(rawArgs)) {\n throw new ScriptInputError('\"args\" must be an array of strings');\n }\n const args: string[] = [];\n for (const value of (rawArgs ?? []) as readonly unknown[]) {\n if (typeof value !== \"string\") throw new ScriptInputError('\"args\" must contain only strings');\n args.push(value);\n }\n\n const cwd = record[\"cwd\"];\n if (cwd !== undefined && (typeof cwd !== \"string\" || cwd.trim() === \"\")) {\n throw new ScriptInputError('\"cwd\" must be a non-empty string when present');\n }\n\n const background = record[\"background\"] ?? false;\n if (typeof background !== \"boolean\") throw new ScriptInputError('\"background\" must be a boolean');\n\n const timeoutMs = record[\"timeoutMs\"];\n if (timeoutMs !== undefined) {\n if (typeof timeoutMs !== \"number\" || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {\n throw new ScriptInputError('\"timeoutMs\" must be a positive integer');\n }\n if (timeoutMs > MAX_TIMEOUT_MS) {\n throw new ScriptInputError(`\"timeoutMs\" must be at most ${MAX_TIMEOUT_MS}`);\n }\n }\n\n const outputLimitBytes = record[\"outputLimitBytes\"];\n if (outputLimitBytes !== undefined) {\n if (\n typeof outputLimitBytes !== \"number\" ||\n !Number.isInteger(outputLimitBytes) ||\n outputLimitBytes <= 0\n ) {\n throw new ScriptInputError('\"outputLimitBytes\" must be a positive integer');\n }\n }\n\n return {\n id: id as ScriptId,\n args,\n ...(cwd === undefined ? {} : { cwd: cwd as string }),\n background,\n ...(timeoutMs === undefined ? {} : { timeoutMs: timeoutMs as number }),\n ...(outputLimitBytes === undefined\n ? {}\n : { outputLimitBytes: outputLimitBytes as number }),\n };\n}\n\n/**\n * Resolve the directory the child runs in.\n *\n * The tool's `cwd` argument is documented as resolving against \"this session's\n * directory\", so `sessionCwd` — the value `ctx.workingDirectory.ensure()` returns —\n * is the base, not the Host process's working directory.\n *\n * - omitted -> the session directory\n * - relative -> joined onto the session directory\n * - absolute -> used as-is\n *\n * With no Session (a call outside an Agent) there is no session directory to\n * anchor to; the argument is then passed through and `resolve` normalises it\n * against the Host process, which is the only directory that exists.\n */\nexport function resolveWorkingDirectory(\n requested: string | undefined,\n sessionCwd: string | undefined,\n): string | undefined {\n if (requested === undefined) return sessionCwd;\n if (isAbsolute(requested)) return resolve(requested);\n return sessionCwd === undefined ? resolve(requested) : resolve(join(sessionCwd, requested));\n}\n\n/**\n * Run one script in the foreground.\n *\n * A nonzero exit, a signal, a timeout, and truncated output are all returned rather\n * than raised: the caller needs to see what the script said before it failed, and an\n * exception would discard the captured output.\n */\nexport async function runForeground(\n args: ScriptArgs,\n options: {\n readonly execPath?: string;\n readonly environment?: NodeJS.ProcessEnv;\n /** Already resolved by the caller; see `resolveWorkingDirectory`. */\n readonly cwd?: string;\n readonly signal?: AbortSignal;\n } = {},\n): Promise<ScriptResult> {\n const path = scriptPath(args.id);\n const started = Date.now();\n const timeoutMs = args.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const limit = args.outputLimitBytes ?? DEFAULT_OUTPUT_LIMIT_BYTES;\n\n return await new Promise<ScriptResult>((resolve, reject) => {\n const child = spawnChild(options.execPath ?? process.execPath, [path, ...args.args], {\n cwd: args.cwd ?? options.cwd,\n env: options.environment ?? scriptEnvironment(),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n signal: options.signal,\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let stdoutTruncated = false;\n let stderrTruncated = false;\n let timedOut = false;\n\n const collect = (chunk: Buffer, to: \"out\" | \"err\"): void => {\n const text = chunk.toString(\"utf8\");\n if (to === \"out\") {\n if (stdout.length >= limit) {\n stdoutTruncated = true;\n return;\n }\n stdout += text.slice(0, limit - stdout.length);\n if (stdout.length >= limit) stdoutTruncated = true;\n return;\n }\n if (stderr.length >= limit) {\n stderrTruncated = true;\n return;\n }\n stderr += text.slice(0, limit - stderr.length);\n if (stderr.length >= limit) stderrTruncated = true;\n };\n\n child.stdout?.on(\"data\", (chunk: Buffer) => collect(chunk, \"out\"));\n child.stderr?.on(\"data\", (chunk: Buffer) => collect(chunk, \"err\"));\n\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n\n child.once(\"error\", (error) => {\n clearTimeout(timer);\n reject(error);\n });\n\n child.once(\"close\", (code, signal) => {\n clearTimeout(timer);\n resolve({\n kind: \"foreground\",\n id: args.id,\n exitCode: code ?? (signal === null ? 1 : 1),\n signal,\n timedOut,\n stdout,\n stderr,\n stdoutTruncated,\n stderrTruncated,\n durationMs: Date.now() - started,\n });\n });\n });\n}\n\n/**\n * Start a script as a background job.\n *\n * `jobs` is required and passing nothing is a refusal with a reason. A job whose\n * output nobody can read would be worse than a failed call: the model would report a\n * task as started and no notice would ever arrive.\n */\nexport async function runBackground(\n args: ScriptArgs,\n options: {\n readonly jobs?: JobsHost | undefined;\n readonly caller?: SessionId;\n readonly execPath?: string;\n readonly environment?: NodeJS.ProcessEnv;\n readonly cwd?: string;\n },\n): Promise<ScriptJobResult> {\n const jobs = options.jobs;\n if (jobs === undefined) {\n throw new ScriptInputError(\n \"background: true needs the Host jobs service, and this composition has none. \" +\n \"Run the call in the foreground (omit background), or ask the operator to mount a job controller.\",\n );\n }\n\n const path = scriptPath(args.id);\n const execPath = options.execPath ?? process.execPath;\n const environment = options.environment ?? scriptEnvironment();\n // Already resolved by the caller; see `resolveWorkingDirectory`.\n const cwd = options.cwd;\n\n /**\n * Settles when the child either started or failed to start, or when the registry\n * never invoked the producer at all.\n *\n * `run` fills this in, so the caller can await the real startup outcome instead of\n * guessing at one with a timer. `child_process` emits exactly one of `spawn` or\n * `error`:\n *\n * - `spawn` fires once the child has been created, before any stdio or exit event.\n * - `error` fires instead when creation failed (ENOENT, EACCES, EMFILE), and no\n * `spawn` ever follows.\n *\n * So these two events are mutually exclusive and jointly exhaustive for \"did it\n * start\", which is exactly the question the tool has to answer. Measured on this\n * Node: a missing binary reports ENOENT through `error`, while a real binary —\n * including one that exits immediately or runs slowly — reports `spawn` with no\n * error.\n *\n * `state` exists because the promise must never be able to hang. Two cases would\n * otherwise leave it pending forever:\n *\n * - a registry that registers a job without calling `run` (a stub, or a future\n * controller with a different contract). `dsh-jobs-local` does call it\n * synchronously (`hooks = spec.run(handle)`), but the tool cannot assume which\n * implementation it is talking to — and hanging is far worse than reporting\n * \"started\", because the model never gets an answer at all.\n * - `run` throwing synchronously, which would skip both event handlers.\n *\n * Both are treated as \"started\" only in the sense of \"do not claim a failure we did\n * not observe\": a genuinely failed job still settles as `failed` through `done`, and\n * the Host's job tools report that.\n */\n let reportStarted: ((failure: string | null) => void) | undefined;\n const state: { settled: boolean; ran: boolean } = { settled: false, ran: false };\n const started = new Promise<string | null>((settle) => {\n reportStarted = (failure) => {\n if (state.settled) return;\n state.settled = true;\n settle(failure);\n };\n });\n\n const jobId = jobs.start({\n kind: \"bash\",\n label: `pstack_script ${args.id}`,\n ...(options.caller === undefined ? {} : { owner: options.caller }),\n outputLimitBytes: args.outputLimitBytes ?? DEFAULT_OUTPUT_LIMIT_BYTES,\n run: (job) => {\n state.ran = true;\n const settleStarted = reportStarted as (failure: string | null) => void;\n let child: ChildProcess;\n try {\n child = spawnChild(execPath, [path, ...args.args], {\n cwd,\n env: environment,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n } catch (error) {\n // A synchronous throw from `spawn` (an invalid argument, or a platform\n // failure that does not become an event) would otherwise leave the caller\n // waiting forever, because no listener was ever attached.\n settleStarted((error as NodeJS.ErrnoException).code ?? \"spawn-threw\");\n throw error;\n }\n\n child.stdout?.on(\"data\", (chunk: Buffer) => job.append(chunk.toString(\"utf8\"), { channel: \"stdout\" }));\n child.stderr?.on(\"data\", (chunk: Buffer) => job.append(chunk.toString(\"utf8\"), { channel: \"stderr\" }));\n\n // Report the startup outcome to the caller waiting above. `once` on both, and\n // the promise settles on whichever arrives first, so a late `error` after a\n // successful `spawn` cannot overwrite the answer.\n child.once(\"spawn\", () => settleStarted(null));\n child.once(\"error\", (error) => {\n // Only the error code. `child_process`'s `error.message` embeds the host's\n // absolute path to the artefact, and the model has no business seeing the\n // host layout.\n settleStarted((error as NodeJS.ErrnoException).code ?? \"spawn-failed\");\n });\n\n const done = new Promise<{ status: \"completed\" | \"killed\" | \"failed\"; detail?: string }>(\n (settle) => {\n child.once(\"error\", (error) => {\n settle({\n status: \"failed\",\n detail: (error as NodeJS.ErrnoException).code ?? \"spawn-failed\",\n });\n });\n child.once(\"close\", (code, signal) => {\n if (signal !== null) settle({ status: \"killed\", detail: `signal ${signal}` });\n else if (code === 0) settle({ status: \"completed\" });\n else settle({ status: \"failed\", detail: `exit code ${code ?? \"unknown\"}` });\n });\n },\n );\n\n return {\n cancel: (reason?: string) => {\n child.kill(\"SIGTERM\");\n if (reason !== undefined) job.updateProgress(`cancelling: ${reason}`);\n },\n done,\n };\n },\n });\n\n // Wait for the real startup outcome, not a guess.\n //\n // Three attempts preceded this, and each failed differently:\n //\n // 1. A fixed 250 ms wait. Failures before it were caught, failures after it were\n // reported to the model as \"started\" and never corrected.\n // 2. One microtask (`await Promise.resolve()`). `spawn` reports ENOENT\n // asynchronously, so this caught nothing at all — measured: after one microtask\n // the error had not fired yet, and it appeared ~100 ms later. That made the tool\n // report `running` for a job that never started, which is worse than the timer.\n // 3. This: race `spawn` against `error`, which are mutually exclusive and jointly\n // exhaustive for \"did the child start\". No duration is involved, so no\n // latency assumption can be wrong.\n //\n // If the registry never invoked the producer, the promise would never settle, so\n // that case is answered up front rather than awaited. `dsh-jobs-local` calls\n // `spec.run` synchronously, but a stub registry need not, and hanging is the one\n // outcome the model can do nothing with.\n /**\n * Turn a reported start failure into the tool error.\n *\n * The code only. A foreground run is how the caller sees the actual error, and\n * naming the code keeps host paths out of the model's context.\n */\n const failStart = (reason: string): never => {\n throw new ScriptMissingError(\n `background job ${jobId} failed to start (${reason}). ` +\n \"Run the same script in the foreground to see its error.\",\n );\n };\n\n if (!state.ran) {\n // The registry registered a job without invoking the producer, so there is no\n // child to observe. Report what the registry itself says, and refuse to present a\n // terminal failure as a started job.\n const view = jobs.get(jobId, options.caller);\n if (view.status === \"failed\") failStart(\"the job controller reported a failed start\");\n return { kind: \"background\", id: args.id, jobId, status: view.status };\n }\n\n const startFailure = await started;\n if (startFailure !== null) failStart(startFailure);\n\n // A controller may also settle the job as failed after `spawn` but before this\n // call returns. That is still a start failure from the model's point of view: it\n // has been told nothing it could act on yet.\n const view = jobs.get(jobId, options.caller);\n if (view.status === \"failed\") failStart(\"the job controller reported a failed start\");\n return { kind: \"background\", id: args.id, jobId, status: view.status };\n}\n\n/**\n * Render one captured stream as a fenced block, byte for byte.\n *\n * `trimEnd` used to run here, which is wrong for two reasons:\n *\n * - A stream of only whitespace passed the `!== \"\"` test and then rendered as an\n * empty-looking `stdout:` line, so a reader concluded the script printed nothing.\n * - `check-plan`'s contract includes exact line counts and blank-line separators, so\n * a trimmed block is a different document — and the model reads this text as the\n * script's output.\n *\n * A fence keeps every byte visible, including trailing blank lines. The fence is\n * lengthened past the longest backtick run in the content so it can never be closed\n * early by the content itself. Nothing inside is escaped or reinterpreted.\n */\nexport function renderCapturedStream(text: string): readonly string[] {\n if (text === \"\") return [];\n const longestRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));\n const fence = \"`\".repeat(Math.max(3, longestRun + 1));\n // Strip exactly one final newline: `join(\"\\n\")` puts it back, and keeping it would\n // add a visible blank line that the script did not print.\n const body = text.endsWith(\"\\n\") ? text.slice(0, -1) : text;\n return [fence, body, fence];\n}\n\n/** Render one outcome for the model. */\nexport function renderScriptOutcome(outcome: ScriptOutcome): string {\n if (outcome.kind === \"background\") {\n return [\n `started ${outcome.id} as background job ${outcome.jobId} (status: ${outcome.status}).`,\n \"Read or stop it through the Host's job tools; this tool does not poll.\",\n ].join(\"\\n\");\n }\n\n const lines = [\n `${outcome.id} exited with code ${outcome.exitCode}` +\n `${outcome.signal === null ? \"\" : ` (signal ${outcome.signal})`}` +\n `${outcome.timedOut ? ` after the timeout` : \"\"} in ${outcome.durationMs}ms`,\n ];\n // Omitted only when the stream is genuinely empty; a stream of blank lines is\n // shown, so \"printed nothing\" and \"printed newlines\" stay distinguishable.\n if (outcome.stdout !== \"\") lines.push(\"\", \"stdout (exact bytes):\", ...renderCapturedStream(outcome.stdout));\n if (outcome.stderr !== \"\") lines.push(\"\", \"stderr (exact bytes):\", ...renderCapturedStream(outcome.stderr));\n if (outcome.stdoutTruncated) lines.push(\"\", \"stdout was truncated at the output limit.\");\n if (outcome.stderrTruncated) lines.push(\"\", \"stderr was truncated at the output limit.\");\n if (outcome.exitCode !== 0 || outcome.signal !== null || outcome.timedOut) {\n lines.push(\"\", \"This run failed. Read the output above; do not report success.\");\n }\n return lines.join(\"\\n\");\n}\n\nconst TOOL_DESCRIPTION = [\n \"Run one of the scripts bundled with pstack, using the Host's own Node runtime.\",\n \"\",\n \"Use this instead of a shell for the pstack scripts. It works in both deployments: the npm CLI and\",\n \"the Desktop app, where `node` is not on PATH because the Desktop process is Electron.\",\n \"\",\n \"`id` selects a bundled script by name; only those names are accepted, so this is not a general\",\n \"shell and takes no path or command string. `args` are passed to the script verbatim.\",\n \"\",\n \"The run starts in this session's directory, so a relative path in `args` lands inside the\",\n \"workspace or worktree the session is using.\",\n \"\",\n \"**This tool does not go through command approval, and the Host's sandbox policy does not apply**\",\n \"to it. It spawns a Node process directly instead of asking `ctx.shell` to run a command, which is\",\n \"what keeps it working where no `node` is on PATH. The scripts are this package's own audited\",\n \"artefacts and `id` cannot name anything else, but the consequence is real: unlike a bash call, no\",\n \"approval prompt is shown and no filesystem policy is enforced on what the script writes. Say so\",\n \"when a task depends on that difference.\",\n \"\",\n \"A nonzero exit, a signal, a timeout, and truncated output all come back in the result with the\",\n \"captured output, so a failed run is visible rather than silent.\",\n \"\",\n \"Set `background: true` for a long run. That needs the Host jobs service; without it the call is\",\n \"refused with a reason instead of hanging. Background runs return a job id and a settlement notice\",\n \"arrives later — do not poll.\",\n].join(\"\\n\");\n\n/** The model-facing JSON Schema for `parameters`. */\nexport function buildScriptParameters(): Record<string, unknown> {\n const properties: Record<string, unknown> = {\n id: {\n type: \"string\",\n enum: [...SCRIPT_IDS],\n description: \"Which bundled pstack script to run. Not a path: only these names are accepted.\",\n },\n args: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Arguments passed to the script verbatim, one array entry per argument.\",\n },\n cwd: {\n type: \"string\",\n description:\n \"Working directory for the script. Relative paths resolve against this session's directory; an absolute path is used as-is. Omitted runs in this session's directory.\",\n },\n background: {\n type: \"boolean\",\n description:\n \"Run as a Host background job and return its id. Requires the jobs service; a composition without it refuses the call.\",\n },\n timeoutMs: {\n type: \"integer\",\n description: `Foreground wall-clock limit; 1 or greater, and values below 1 are rejected. Defaults to ${DEFAULT_TIMEOUT_MS}; values above ${MAX_TIMEOUT_MS} are rejected.`,\n },\n outputLimitBytes: {\n type: \"integer\",\n description: `Per-stream capture limit; 1 or greater, and values below 1 are rejected. Defaults to ${DEFAULT_OUTPUT_LIMIT_BYTES}.`,\n },\n };\n\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n required: [\"id\"],\n };\n}\n\n/**\n * The declared shape of one outcome, exported so tests can validate real results.\n *\n * Split by `kind` instead of one flat object. The flat form could only require\n * `kind` and `id`, so a foreground result that omitted `exitCode` was still\n * \"valid\" and the schema proved nothing about the fields the model reads.\n *\n * `signal` is nullable because `child_process` reports `null` whenever the child\n * exited on its own — that is every successful run. Declaring it `string` made\n * the registry reject the tool's own normal output: `createSuccessResult()`\n * validates before rendering, so **every** clean exit surfaced to the model as\n * `tool \"pstack_script\" returned invalid output`.\n */\nexport const OUTPUT_SCHEMA: JsonSchemaNode = {\n oneOf: [\n {\n type: \"object\",\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", const: \"foreground\" },\n id: { type: \"string\", description: \"Which bundled script ran.\" },\n exitCode: { type: \"integer\", description: \"The child's exit code.\" },\n signal: {\n oneOf: [{ type: \"string\" }, { type: \"null\" }],\n description: \"Terminating signal, or null when the script exited on its own.\",\n },\n timedOut: {\n type: \"boolean\",\n description: \"True when this tool's own timeout killed the run.\",\n },\n stdout: { type: \"string\" },\n stderr: { type: \"string\" },\n stdoutTruncated: { type: \"boolean\" },\n stderrTruncated: { type: \"boolean\" },\n durationMs: { type: \"integer\" },\n },\n required: [\n \"kind\",\n \"id\",\n \"exitCode\",\n \"signal\",\n \"timedOut\",\n \"stdout\",\n \"stderr\",\n \"stdoutTruncated\",\n \"stderrTruncated\",\n \"durationMs\",\n ],\n },\n {\n type: \"object\",\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", const: \"background\" },\n id: { type: \"string\", description: \"Which bundled script started.\" },\n jobId: { type: \"string\", description: \"The Host job id to read or stop.\" },\n status: { type: \"string\", description: \"Job status when the call returned.\" },\n },\n required: [\"kind\", \"id\", \"jobId\", \"status\"],\n },\n ],\n};\n\n/** The slices of the Cordis context this tool needs. */\nexport interface PstackScriptHost {\n readonly tools: ToolsHost;\n /** Resolves the Session's current directory; see `WorkingDirectoryHost`. */\n readonly workingDirectory: WorkingDirectoryHost;\n /**\n * Optional, and read per call rather than snapshotted.\n *\n * A profile may mount a job controller after this row, so a value read once in\n * `apply` would stay `undefined` forever. `ctx.get(\"jobs\")` is rc.3's\n * optional-service read: it returns `undefined` instead of throwing when the\n * service is absent, which is why `jobs` is not declared in `inject`.\n */\n readonly getJobs?: () => JobsHost | undefined;\n}\n\n/** Build the tool for one row. */\nexport function createPstackScriptTool(host: PstackScriptHost): ToolDefinition {\n return {\n name: TOOL_NAME,\n description: TOOL_DESCRIPTION,\n parameters: buildScriptParameters(),\n output: {\n schema: OUTPUT_SCHEMA,\n render: (_args, value) => [{ type: \"text\", text: renderScriptOutcome(value as ScriptOutcome) }],\n },\n // Two runs of the same script may write the same store, so this is not marked\n // concurrency-safe; the Host then serializes them the way it serializes any tool.\n isConcurrencySafe: () => false,\n /**\n * The Host's last-resort budget for one call.\n *\n * `DEFAULT_TIMEOUT_MS` is the tool's own timer for a foreground run, and it fires\n * first in every normal case: it kills the child and returns a `timedOut` result the\n * model can read. This budget is larger on purpose, so it only ever wins when the\n * tool's own machinery failed to return at all — a hung `await`, a timer that never\n * ran — and the alternative would be a session blocked with no answer.\n *\n * `MAX_TIMEOUT_MS` rather than a new number: it is already the ceiling the tool\n * accepts for a caller-supplied `timeoutMs`, so the Host budget can never be the\n * thing that cuts short a run the caller was allowed to request.\n *\n * It does not bound a background job. The wrapper disposes its timer when `execute`\n * settles, which is milliseconds after `jobs.start` returns.\n */\n timeoutMs: MAX_TIMEOUT_MS,\n async execute(rawArgs, exec: ToolRunContext) {\n const args = parseScriptArgs(rawArgs);\n // Ask the Host where this Session currently is, rather than inheriting the\n // Host process's directory. `ensure` is the same seam `dsh-tool-bash` uses.\n const sessionCwd =\n exec.agent === undefined\n ? undefined\n : await host.workingDirectory.ensure(exec.agent, exec.signal);\n const cwd = resolveWorkingDirectory(args.cwd, sessionCwd);\n if (args.background) {\n return await runBackground(args, {\n jobs: host.getJobs?.(),\n ...(cwd === undefined ? {} : { cwd }),\n ...(exec.agent === undefined ? {} : { caller: exec.agent.id }),\n });\n }\n return await runForeground(args, {\n signal: exec.signal,\n ...(cwd === undefined ? {} : { cwd }),\n });\n },\n };\n}\n\n/** Cordis row name, used by Loader diagnostics. */\nexport const name = \"pstack-script\";\n\n/**\n * The hard dependencies.\n *\n * `tools` is the registry this row registers into; `workingDirectory` is what\n * turns the tool's `cwd` argument and its omitted case into the Session's\n * directory. Both are always present in a profile that has an Agent at all.\n *\n * `jobs` is deliberately absent: a composition without a job controller still\n * registers the tool, and only `background: true` is refused. Declaring `jobs`\n * here would keep the whole fiber inactive in every profile that has no job\n * controller, which is most of them.\n */\nexport const inject = [\"tools\", \"workingDirectory\"];\n\n/**\n * Register `pstack_script` for this row.\n *\n * `inject` is what makes `ctx.tools` readable at all: without it Cordis runs\n * `apply` immediately and the service proxy throws\n * `cannot get property \"tools\" without inject`, so the row would register nothing\n * in any profile.\n */\nexport function apply(ctx: PstackScriptHost & { get?: (name: string) => JobsHost | undefined }): void {\n ctx.tools.register(\n createPstackScriptTool({\n tools: ctx.tools,\n workingDirectory: ctx.workingDirectory,\n // Optional-service read, so a controller mounted later is still seen.\n getJobs: () => ctx.get?.(\"jobs\"),\n }),\n );\n}\n"],"mappings":";;;;;AAoEA,MAAa,gBAAgB;;AAmB7B,MAAM,qBAA+C,CAfnD;CAAE,MAAM;CAAY,MAAM,GAAG,cAAc;AAAiB,GAC5D;CAAE,MAAM;CAAY,MAAM,GAAG,cAAc;AAAkB,CAcV;AAErD,MAAM,kBAAkB,UAAiC;CACvD,MAAM;CACN,MAAM,8BAA8B;AACtC;;AAGA,MAAa,eAAwC;CACnD;EACE,IAAI;EACJ,MAAM;EACN,OAAO,eAAe,gBAAgB;EACtC,KAAK;EACL,WAAW;EACX,YAAY;EACZ,SAAS,CAAC,eAAe,gBAAgB,CAAC;EAC1C,SAAS;CACX;CACA;EACE,IAAI;EACJ,MAAM;EACN,OAAO,eAAe,cAAc;EACpC,KAAK;EACL,WAAW;EACX,YAAY;EACZ,SAAS,CAAC,eAAe,cAAc,GAAG,eAAe,eAAe,CAAC;EACzE,SAAS;CACX;CACA;EACE,IAAI;EACJ,MAAM;EACN,OAAO,eAAe,mBAAmB;EACzC,KAAK;EACL,WAAW;EACX,YAAY;EACZ,SAAS;GACP,eAAe,mBAAmB;GAClC,eAAe,iBAAiB;GAChC,eAAe,oBAA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AwB,KAAK,KAAK,UAAU;GACxD,IAAI,KAAK,YACP,OAAO,MAAM,cAAc,MAAM;IAC/B,MAAM,KAAK,UAAU;IACrB,GAAI,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI;IACnC,GAAI,KAAK,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,KAAK,MAAM,GAAG;GAC9D,CAAC;GAEH,OAAO,MAAM,cAAc,MAAM;IAC/B,QAAQ,KAAK;IACb,GAAI,QAAQ,KAAA,IAAY,CAAC,IAAI,EAAE,IAAI;GACrC,CAAC;EACH;CACF;AACF;;AAGA,MAAa,OAAO;;;;;;;;;;;;;AAcpB,MAAa,SAAS,CAAC,SAAS,kBAAkB;;;;;;;;;AAUlD,SAAgB,MAAM,KAAgF;CACpG,IAAI,MAAM,SACR,uBAAuB;EACrB,OAAO,IAAI;EACX,kBAAkB,IAAI;EAEtB,eAAe,IAAI,MAAM,MAAM;CACjC,CAAC,CACH;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"subagent.mjs","names":["describeError","describeError"],"sources":["../scripts/role-manifest.ts","../src/effort.ts","../src/roles.ts","../src/models.ts","../src/subagent.ts"],"sourcesContent":["/**\n * The one pstack role manifest.\n *\n * Every consumer of the role vocabulary reads this module: `src/roles.ts` for\n * exact lookup and panel classification, `src/models.ts` for value shapes,\n * `scripts/build-assets.ts` for the generated example file, and the\n * `setup-pstack` skill text, which points at that example instead of listing the\n * roles again. A second literal role list anywhere is a bug.\n *\n * Keys are matched exactly after normalization. Commas are part of some keys\n * (`feature, refactoring`), so nothing here may be split on a comma.\n *\n * This module has no Node imports: the Host bundle imports it directly.\n */\n\n/** Whether a role holds one route or a comma-separated list of routes. */\nexport type RoleValueShape = \"single\" | \"list\";\n\nexport interface RoleSpec {\n /** Exact key as written in the role file. Commas belong to the key. */\n readonly key: string;\n readonly shape: RoleValueShape;\n /**\n * A list role that automatically starts one child per entry. Only the three\n * panel roles set this; every other list role selects one entry.\n */\n readonly autoPanel: boolean;\n /** Skills and playbooks that read this role. */\n readonly consumers: readonly string[];\n readonly summary: string;\n}\n\n/** File name the role policy lives under inside `$DSH_HOME`. */\nexport const PSTACK_MODELS_FILENAME = \"pstack-models.md\";\n\n/** Asset path, relative to `assets/`, of the generated shape reference. */\nexport const PSTACK_MODELS_EXAMPLE_PATH = \"docs/pstack-models.example.md\";\n\n/** Values that resolve to \"send no `agentOptions` and inherit the parent route\". */\nexport const INHERIT_PARENT_ALIASES: readonly string[] = [\"inherit-parent\", \"auto\"];\n\nexport const ROLE_MANIFEST: readonly RoleSpec[] = [\n {\n key: \"feature, refactoring\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/playbooks/feature.md\", \"poteto-mode/playbooks/refactoring.md\"],\n summary:\n \"One route for both code playbooks. The comma joins two playbook names into a single key.\",\n },\n {\n key: \"bug-fix\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/playbooks/bug-fix.md\"],\n summary: \"Implementation route for the bug-fix playbook.\",\n },\n {\n key: \"perf-issue\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/playbooks/perf-issue.md\"],\n summary: \"Implementation route for the perf-issue playbook.\",\n },\n {\n key: \"hillclimb\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/playbooks/hillclimb.md\"],\n summary: \"Implementation route for the hillclimb playbook.\",\n },\n {\n key: \"judgment and prose\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/SKILL.md\", \"unslop\", \"technical-writing\"],\n summary: \"Route for prose work and vague-instruction judgment calls.\",\n },\n {\n key: \"hardest tasks\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"poteto-mode/SKILL.md\"],\n summary: \"Route for the strongest judgment model on cross-cutting or subtle work.\",\n },\n {\n key: \"how explorer\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"how/SKILL.md\", \"how/references/explorer-prompt.md\"],\n summary: \"Route for each how explorer child.\",\n },\n {\n key: \"how explainer\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"how/SKILL.md\", \"how/references/explainer-prompt.md\"],\n summary: \"Route for the single how explainer child.\",\n },\n {\n key: \"why investigators\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"why/SKILL.md\", \"why/references/investigator-prompt.md\"],\n summary: \"Route for each why investigator child.\",\n },\n {\n key: \"why synthesizer\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"why/SKILL.md\", \"why/references/synthesizer-prompt.md\"],\n summary: \"Route for the why synthesis child.\",\n },\n {\n key: \"reflect tooling\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\"reflect/SKILL.md\", \"reflect/references/tooling-reviewer.md\"],\n summary: \"Route for the reflect tooling reviewer.\",\n },\n {\n key: \"reflect judgment, divergent, synthesizer\",\n shape: \"single\",\n autoPanel: false,\n consumers: [\n \"reflect/SKILL.md\",\n \"reflect/references/judgment-reviewer.md\",\n \"reflect/references/divergent-reviewer.md\",\n \"reflect/references/synthesizer.md\",\n ],\n summary:\n \"One shared route for the judgment reviewer, the divergent reviewer, and the synthesizer. The commas belong to the key.\",\n },\n {\n key: \"arena runners\",\n shape: \"list\",\n autoPanel: true,\n consumers: [\"arena/SKILL.md\"],\n summary: \"Panel: one arena child per entry, all started together.\",\n },\n {\n key: \"arena cross-judge pool\",\n shape: \"list\",\n autoPanel: false,\n consumers: [\"arena/SKILL.md\"],\n summary:\n \"A pool arena picks one entry from, preferring a model family unlike the parent's. Not fanned out automatically.\",\n },\n {\n key: \"swarm workers\",\n shape: \"list\",\n autoPanel: false,\n consumers: [\"swarm/SKILL.md\", \"poteto-mode/playbooks/multi-phase-plan.md\"],\n summary:\n \"One default route for every worker. A race gives each arm another entry through `roleIndex`, and the caller still starts one worker per call.\",\n },\n {\n key: \"architect runners\",\n shape: \"list\",\n autoPanel: true,\n consumers: [\"architect/SKILL.md\"],\n summary: \"Panel: one architect child per entry, all started together.\",\n },\n {\n key: \"interrogate reviewers\",\n shape: \"list\",\n autoPanel: true,\n consumers: [\"interrogate/SKILL.md\"],\n summary: \"Panel: one interrogate reviewer per entry, all started together.\",\n },\n];\n\n/** Every exact role key, in manifest order. */\nexport const ROLE_KEYS: readonly string[] = ROLE_MANIFEST.map((role) => role.key);\n\n/** Keys whose list value expands to one child per entry automatically. */\nexport const AUTO_PANEL_ROLE_KEYS: readonly string[] = ROLE_MANIFEST.filter(\n (role) => role.autoPanel,\n).map((role) => role.key);\n\n/** The four setup-pstack budget tiers and the effort each one targets. */\nexport interface BudgetTier {\n readonly label: string;\n /** Target effort token; the model's supported list decides whether it applies. */\n readonly effort: string;\n readonly description: string;\n}\n\nexport const BUDGET_TIERS: readonly BudgetTier[] = [\n { label: \"unlimited\", effort: \"max\", description: \"max reasoning\" },\n { label: \"large\", effort: \"xhigh\", description: \"xhigh reasoning\" },\n { label: \"medium\", effort: \"high\", description: \"high reasoning\" },\n { label: \"small\", effort: \"medium\", description: \"medium reasoning\" },\n];\n\n/** Exact manifest lookup. Callers normalize the key first. */\nexport function findRoleSpec(key: string): RoleSpec | undefined {\n return ROLE_MANIFEST.find((role) => role.key === key);\n}\n\n/**\n * Render the role-file shape reference shipped as a generated asset.\n *\n * The output is itself a valid role file: every explanatory line is a `#` comment,\n * so copying it verbatim yields a working policy where every role inherits the\n * parent route. That is what makes `/setup-pstack` safe to re-run and makes the\n * example a convergence baseline rather than prose that happens to look like one.\n *\n * The defaults are `inherit-parent` for every role because this package cannot\n * know which routes a deployment serves. `setup-pstack` replaces them with routes\n * the user confirmed, never with a model id guessed here.\n */\nexport function renderPstackModelsExample(): string {\n const roles = ROLE_MANIFEST.map((role) => `${role.key}: inherit-parent`);\n return [\n \"# pstack per-role model configuration\",\n \"#\",\n \"# `/setup-pstack` writes this file to `$DSH_HOME/pstack-models.md`. `pstack_subagent`\",\n \"# re-reads it on every delegation, so an edit reaches the next child and never a child\",\n \"# that already started.\",\n \"#\",\n \"# One line per role. The key must match a role in the manifest exactly, commas\",\n \"# included. Delete a line to inherit the parent route for that role.\",\n \"#\",\n \"# Value forms:\",\n \"#\",\n \"# - `inherit-parent` or `auto` sends no `agentOptions`, so the child runs on the parent\",\n \"# route.\",\n \"# - `<provider>/<model>` is an exact route. It splits at the first `/`: the\",\n \"# provider is the text before it and the model is everything after it, so\",\n \"# `gateway/vendor-a/model-x` is provider `gateway` with model\",\n \"# `vendor-a/model-x`. No segment may be empty.\",\n \"# - `<provider>/<model> [effort]` sets the starting level for that role. A caller\",\n \"# raises or lowers it per delegation with `reasoningEffort`, and a running child\",\n \"# can change its own with `set_reasoning_effort`. The effort must appear in that\",\n \"# model's supported effort list. This package assumes no ladder of its own, so it\",\n \"# never invents a token and reports the real ones whenever it refuses one.\",\n \"#\",\n \"# `arena runners`, `architect runners`, and `interrogate reviewers` are panels: the\",\n \"# value is a comma-separated list and one child starts per entry. Two entries on the\",\n \"# same route are not a cross-model review, and `pstack_subagent` says so in its\",\n \"# result.\",\n \"#\",\n \"# `arena cross-judge pool` is a list too, but it is not fanned out; pass `roleIndex` to\",\n \"# choose the entry. `swarm workers` is a list as well: its first entry is the default\",\n \"# route for every worker, `roleIndex` gives one race arm a different entry, and the\",\n \"# caller still starts each worker itself.\",\n \"#\",\n \"# The defaults below are `inherit-parent` because no route is confirmed yet. Replace\",\n \"# them with routes your own deployment serves.\",\n \"#\",\n \"# budget: none (unset)\",\n ...roles,\n \"\",\n ].join(\"\\n\");\n}\n","/**\n * Reasoning-effort control, at both ends of one delegation.\n *\n * A role line names the effort a child *starts* at. That value is a baseline, not a\n * verdict:\n *\n * 1. the caller may override it for one delegation with `reasoningEffort`\n * (validated in `src/subagent.ts` before the first child starts);\n * 2. a running child may raise or lower it with `set_reasoning_effort`, which this\n * module installs on that child's own scope.\n *\n * Both halves exist because the two people who know the right level are not the same\n * person: only the caller knows the job, and only the child knows what it found once\n * it started reading the code.\n *\n * **The effort vocabulary belongs to the adapter.** This module never carries a\n * ladder of its own. A token is accepted only when the model the child will actually\n * request advertises it in `reasoning.efforts`, and a rejection lists that model's\n * real values. A hardcoded list (`max`/`xhigh`/…) would both invent a universal\n * ladder and reject a deployment that names its efforts differently, which is why\n * `docs/decisions/2026-10-26-dynamic-reasoning-effort.md` records that shape as the\n * rejected alternative.\n *\n * @module\n */\n\nimport type {\n Agent,\n AgentOptions,\n JsonSchemaNode,\n LlmCallConfig,\n LlmHost,\n ToolDefinition,\n} from \"./host-contract.ts\";\nimport type { ChildRoute } from \"./models.ts\";\n\n/** Model-facing name of the child's own control. */\nexport const SET_EFFORT_TOOL = \"set_reasoning_effort\";\n\n/** One exact route an effort applies to. */\nexport interface EffortTarget {\n readonly provider: string;\n readonly model: string;\n}\n\n/**\n * Resolve the route a child's effort will actually apply to.\n *\n * The session's latest request header is the live route after a model switch, and\n * `Agent.options` is the creation-time fallback. DSH's own delegation code resolves\n * `inherit-parent` the same way, so reading `options` alone would validate a\n * different model than the child really inherits.\n *\n * An explicit route wins over both, because it is what the delegation will request.\n */\nexport function resolveEffortTarget(\n agent: Agent | undefined,\n route?: ChildRoute,\n): EffortTarget | undefined {\n const explicit = route?.kind === \"route\" ? route : undefined;\n const header = agent?.session.requestHeader()?.config;\n\n const provider = explicit?.provider ?? header?.provider ?? agent?.options.provider;\n const model = explicit?.model ?? header?.model ?? agent?.options.model;\n return provider !== undefined && model !== undefined ? { provider, model } : undefined;\n}\n\n/** The efforts one route advertises, in the adapter's own order. */\nasync function advertisedEfforts(\n llm: LlmHost,\n target: EffortTarget,\n signal: AbortSignal | undefined,\n): Promise<readonly string[]> {\n const info = await llm.resolveModelInfo(target.provider, target.model, signal);\n return info.reasoning?.efforts.map((entry) => entry.id) ?? [];\n}\n\n/**\n * Validate one effort against the route a child will actually request.\n *\n * Rejects with the target's real effort list rather than a generic message, because\n * \"max is not supported\" leaves the caller guessing while \"supports xhigh, high,\n * medium\" is actionable. A model that advertises no efforts at all is reported\n * separately: that is a route incapable of the control, not a wrong token.\n */\nexport async function validateEffortFor(\n llm: LlmHost,\n route: ChildRoute | undefined,\n effort: string,\n parent: Agent | undefined,\n signal?: AbortSignal,\n): Promise<void> {\n const target = resolveEffortTarget(parent, route);\n if (target === undefined) {\n throw new Error(\n \"cannot resolve the child provider/model route for reasoningEffort. Pass `role` with an exact route, or run the delegation from a session that has already made a request.\",\n );\n }\n\n let efforts: readonly string[];\n try {\n efforts = await advertisedEfforts(llm, target, signal);\n } catch (error) {\n throw new Error(\n `route ${target.provider}/${target.model} could not be resolved for reasoningEffort: ${describeError(error)}`,\n { cause: error },\n );\n }\n\n if (efforts.length === 0) {\n throw new Error(\n `${target.provider}/${target.model} advertises no reasoning efforts, so it cannot take reasoningEffort \"${effort}\". Omit the argument and let the adapter use its own default.`,\n );\n }\n if (!efforts.includes(effort)) {\n throw new Error(\n `${target.provider}/${target.model} does not support reasoning effort \"${effort}\". It supports: ${efforts.join(\", \")}.`,\n );\n }\n}\n\n/**\n * Install the effort control on one live child.\n *\n * Registration is child-scoped, so the waterfall and the tool dispose with the\n * child: a sibling delegation never sees them, and a later child cannot inherit a\n * stale value.\n *\n * The waterfall re-states the starting effort on every request and applies a\n * change from the next request onward. It never rewrites a request already in\n * flight, because `next()` has already been called and its result is the request\n * the machine built.\n *\n * A missing route is not fatal here. The child still runs on whatever the adapter\n * chose; the tool reports the missing route when the child tries to change effort.\n *\n * @param child - the live child agent, already started.\n * @param llm - the adapter host used to validate a requested change.\n * @param initialEffort - the effort the delegation started the child at, if any.\n * @returns a disposer that unwinds this contribution early, or does nothing when\n * the child context is already gone.\n */\nexport function installEffortControl(\n child: Agent,\n llm: LlmHost,\n initialEffort: string | undefined,\n): () => void {\n let current = initialEffort;\n\n const disposeListener = child.ctx.on(\"agent/request\", async (_payload, next) => {\n const config = await next();\n return current === undefined\n ? config\n : ({ ...config, reasoningEffort: current } satisfies LlmCallConfig);\n });\n\n const disposeTool = child.ctx.tools.register(\n defineSetEffortTool(child, llm, (effort) => {\n current = effort;\n }),\n );\n\n return () => {\n disposeTool();\n disposeListener();\n };\n}\n\n/** The child's own view of its effort, for the tool body. */\nfunction defineSetEffortTool(\n child: Agent,\n llm: LlmHost,\n apply: (effort: string) => void,\n): ToolDefinition {\n const parameters: Record<string, unknown> = {\n effort: {\n type: \"string\",\n description:\n \"The reasoning effort to use from your next step onward. Use one of the values this model advertises; the call rejects an unknown one and lists the real values.\",\n },\n };\n\n const outputSchema: JsonSchemaNode = { type: \"string\" };\n\n return {\n name: SET_EFFORT_TOOL,\n description: [\n \"Change your reasoning effort for future model requests.\",\n \"Use it when the task turns out harder or more routine than the role line assumed: raise it for subtle design, concurrency, or algorithm work, lower it once the remaining work is mechanical.\",\n \"The change applies from your next step; a request already in flight is unaffected, and it lasts for the rest of this child's life.\",\n \"This tool may not be visible until your second step. The effort you were started with applies to the first step, so a slow first step is expected when that level is high.\",\n ].join(\" \"),\n parameters,\n output: {\n schema: outputSchema,\n render: (_args, value) => [{ type: \"text\", text: String(value) }],\n },\n isConcurrencySafe: () => false,\n async execute(rawArgs, exec) {\n const args = rawArgs as { effort?: unknown };\n const value = typeof args.effort === \"string\" ? args.effort.trim() : \"\";\n if (value === \"\") {\n throw new Error(\n \"set_reasoning_effort needs a non-empty `effort`. Pass the exact token this model advertises; an empty value would silently re-enable the adapter default.\",\n );\n }\n\n const target = resolveEffortTarget(exec.agent ?? child);\n if (target === undefined) {\n throw new Error(\n \"this child has no resolved provider/model route, so reasoning effort cannot be validated against the live adapter metadata\",\n );\n }\n\n let efforts: readonly string[];\n try {\n efforts = await advertisedEfforts(llm, target, exec.signal);\n } catch (error) {\n throw new Error(\n `${target.provider}/${target.model} could not be resolved for reasoning effort: ${describeError(error)}`,\n { cause: error },\n );\n }\n if (efforts.length === 0) {\n throw new Error(\n `${target.provider}/${target.model} advertises no reasoning efforts, so this child has none to change. Your current effort stays as it is.`,\n );\n }\n if (!efforts.includes(value)) {\n throw new Error(\n `${target.provider}/${target.model} does not support reasoning effort \"${value}\", so nothing changed. It supports: ${efforts.join(\", \")}.`,\n );\n }\n\n apply(value);\n return `reasoning effort set to \"${value}\". It applies from your next step; the request already in flight is unaffected.`;\n },\n };\n}\n\n/**\n * The `agentOptions` one (route, effort override) pair contributes.\n *\n * The two independent halves are easy to get wrong in opposite directions:\n *\n * - an inherit-parent route with an override must still send `reasoningEffort`,\n * which means `{ reasoningEffort }` on its own is a real `agentOptions` value and\n * the backend still has to support the capability;\n * - an override always wins over the role line, because the caller asked for this\n * delegation specifically.\n */\nexport function agentOptionsFor(\n route: ChildRoute,\n effortOverride?: string,\n): AgentOptions | undefined {\n const effort = effortOverride ?? (route.kind === \"route\" ? route.effort : undefined);\n if (route.kind === \"inherit\") {\n return effort === undefined ? undefined : { reasoningEffort: effort };\n }\n return {\n provider: route.provider,\n model: route.model,\n ...(effort === undefined ? {} : { reasoningEffort: effort }),\n };\n}\n\n/** The effort a plan entry will actually run at, override included. */\nexport function effectiveEffort(route: ChildRoute, effortOverride?: string): string | undefined {\n return effortOverride ?? (route.kind === \"route\" ? route.effort : undefined);\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error) {\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" ? `${error.message} (${code})` : error.message;\n }\n return String(error);\n}\n","/**\n * Role lookup over the single manifest in `scripts/role-manifest.ts`.\n *\n * A role name is matched exactly after normalization. A near miss is reported as\n * a hint and never guessed, because silently running a role on the wrong route is\n * worse than refusing the delegation.\n *\n * Commas belong to some keys (`feature, refactoring`), so nothing here splits a\n * key on a comma. Only a role file *value* is a comma-separated list.\n */\n\nimport {\n AUTO_PANEL_ROLE_KEYS,\n ROLE_MANIFEST,\n findRoleSpec,\n type RoleSpec,\n type RoleValueShape,\n} from \"../scripts/role-manifest.ts\";\n\nexport { AUTO_PANEL_ROLE_KEYS, ROLE_MANIFEST, findRoleSpec, type RoleSpec, type RoleValueShape };\n\n/** Raised when a role name does not match the manifest. */\nexport class RoleNameError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RoleNameError\";\n }\n}\n\n/**\n * Normalize a role name for lookup.\n *\n * Case, surrounding whitespace, runs of whitespace, spacing around a comma, and a\n * trailing colon are formatting, not naming. Nothing else is normalized: a\n * different word is a different role.\n */\nexport function normalizeRoleName(raw: string): string {\n return raw\n .normalize(\"NFC\")\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \", \")\n .replace(/:+$/, \"\")\n .trim();\n}\n\n/** Every exact role key in manifest order. */\nexport function roleKeys(): readonly string[] {\n return ROLE_MANIFEST.map((role) => role.key);\n}\n\n/** Look a role up by its exact normalized key. */\nexport function lookupRole(raw: string): RoleSpec | undefined {\n return findRoleSpec(normalizeRoleName(raw));\n}\n\n/**\n * Near-miss hints for a role name that did not match.\n *\n * Only used to build a diagnostic. A suggestion is never turned into a selection.\n */\nexport function suggestRoles(raw: string, limit = 3): readonly string[] {\n const target = normalizeRoleName(raw);\n if (target === \"\") return [];\n\n const scored = ROLE_MANIFEST.map((role) => {\n const shared = sharedTokenCount(target, role.key);\n const distance = editDistance(target, role.key);\n const contains = role.key.includes(target) || target.includes(role.key);\n const score =\n (contains ? 1000 : 0) + shared * 100 - distance + Math.min(role.key.length, target.length);\n return { key: role.key, score, distance, shared, contains };\n }).filter((candidate) => candidate.contains || candidate.shared > 0 || candidate.distance <= 4);\n\n return scored\n .sort((left, right) => right.score - left.score)\n .slice(0, limit)\n .map((candidate) => candidate.key);\n}\n\n/**\n * Resolve a role name, or throw a diagnostic that names the near misses.\n */\nexport function requireRole(raw: string): RoleSpec {\n const spec = lookupRole(raw);\n if (spec !== undefined) return spec;\n\n const suggestions = suggestRoles(raw);\n const hint =\n suggestions.length === 0\n ? \"No role key is close to it.\"\n : `Closest role keys: ${suggestions.map((key) => `\"${key}\"`).join(\", \")}.`;\n throw new RoleNameError(\n `unknown pstack role ${JSON.stringify(raw)}. ${hint} Role names come from the role manifest, not from free text: pass the exact key, or omit \\`role\\` to inherit the parent route.`,\n );\n}\n\nfunction sharedTokenCount(left: string, right: string): number {\n const rightTokens = new Set(tokenize(right));\n return [...new Set(tokenize(left))].filter((token) => rightTokens.has(token)).length;\n}\n\nfunction tokenize(value: string): readonly string[] {\n return value.split(/[^a-z0-9]+/).filter((token) => token !== \"\");\n}\n\n/** Levenshtein distance, iterative with one row of state. */\nfunction editDistance(left: string, right: string): number {\n if (left === right) return 0;\n if (left === \"\") return right.length;\n if (right === \"\") return left.length;\n\n let previous = Array.from({ length: right.length + 1 }, (_, index) => index);\n for (let row = 1; row <= left.length; row += 1) {\n const current: number[] = [row];\n for (let column = 1; column <= right.length; column += 1) {\n const substitution = (previous[column - 1] as number) + (left[row - 1] === right[column - 1] ? 0 : 1);\n const deletion = (previous[column] as number) + 1;\n const insertion = (current[column - 1] as number) + 1;\n current.push(Math.min(substitution, deletion, insertion));\n }\n previous = current;\n }\n return previous[right.length] as number;\n}\n","/**\n * The pstack role file: `$DSH_HOME/pstack-models.md`.\n *\n * `pstack_subagent` reads this file again on every delegation, so a change reaches\n * the next child and never a child that already started.\n *\n * Three states are kept apart on purpose, because they need different fixes:\n *\n * - the file does not exist: no policy is configured, so every role inherits the\n * parent route;\n * - the file exists but cannot be read: a broken installation or permission\n * problem, reported as an error and never treated as \"no configuration\";\n * - the file loads but a line is wrong: a typo in a key, an unknown retired role,\n * or a malformed value is reported with the line number and the near misses.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n INHERIT_PARENT_ALIASES,\n PSTACK_MODELS_FILENAME,\n ROLE_MANIFEST,\n type RoleSpec,\n} from \"../scripts/role-manifest.ts\";\nimport { normalizeRoleName, suggestRoles } from \"./roles.ts\";\n\n/** One resolved child route. */\nexport type ChildRoute =\n | { readonly kind: \"inherit\" }\n | {\n readonly kind: \"route\";\n readonly provider: string;\n readonly model: string;\n readonly effort?: string;\n };\n\n/** A syntactically valid line for a role the manifest knows. */\nexport interface RoleFileEntry {\n readonly line: number;\n /** Verbatim key text from the file. */\n readonly rawKey: string;\n /** Normalized key that matched the manifest. */\n readonly key: string;\n readonly spec: RoleSpec;\n /** Verbatim value text from the file. */\n readonly rawValue: string;\n readonly routes: readonly ChildRoute[];\n}\n\n/** A recoverable problem found while reading the file. */\nexport interface RoleFileIssue {\n /** 1-based line number, when the issue belongs to one line. */\n readonly line?: number;\n readonly message: string;\n}\n\nexport type RoleFileRead =\n | { readonly status: \"missing\"; readonly path: string }\n | { readonly status: \"unreadable\"; readonly path: string; readonly reason: string }\n | {\n readonly status: \"loaded\";\n readonly path: string;\n /** The `# budget:` label the file records, when it has one. */\n readonly budget?: string;\n readonly roles: ReadonlyMap<string, RoleFileEntry>;\n readonly issues: readonly RoleFileIssue[];\n };\n\n/** Absolute path of the role file for one DSH home. */\nexport function modelsFilePath(dshHome: string): string {\n return join(dshHome, PSTACK_MODELS_FILENAME);\n}\n\n/**\n * Resolve `$DSH_HOME` the way the Host does: the environment when set, else\n * `~/.dsh`.\n */\nexport function resolveDshHome(\n env: Readonly<Record<string, string | undefined>> = process.env,\n home: string = homedir(),\n): string {\n const configured = env[\"DSH_HOME\"];\n if (configured !== undefined && configured.trim() !== \"\") return configured;\n return join(home, \".dsh\");\n}\n\n/** Read the role file. Never throws for a missing or unreadable file. */\nexport function readRoleFile(path: string): RoleFileRead {\n let text: string;\n try {\n text = readFileSync(path, \"utf8\");\n } catch (error) {\n if (isMissingFile(error)) return { status: \"missing\", path };\n return { status: \"unreadable\", path, reason: describeError(error) };\n }\n return parseRoleFile(text, path);\n}\n\n/** Parse role-file text. Pure: no file system access. */\nexport function parseRoleFile(text: string, path: string): RoleFileRead {\n const issues: RoleFileIssue[] = [];\n const roles = new Map<string, RoleFileEntry>();\n const lines = stripFrontmatter(text).split(\"\\n\");\n let budget: string | undefined;\n\n lines.forEach((rawLine, index) => {\n const line = index + 1;\n const trimmed = rawLine.trim();\n if (trimmed === \"\") return;\n\n if (trimmed.startsWith(\"#\")) {\n const match = /^#\\s*budget:\\s*(.+)$/i.exec(trimmed);\n if (match !== null) budget = (match[1] as string).trim();\n return;\n }\n\n const separator = trimmed.indexOf(\":\");\n if (separator === -1) {\n issues.push({\n line,\n message: `expected \\`<role>: <value>\\`, found ${JSON.stringify(trimmed)}`,\n });\n return;\n }\n\n const rawKey = trimmed.slice(0, separator).trim();\n const rawValue = trimmed.slice(separator + 1).trim();\n const key = normalizeRoleName(rawKey);\n if (key === \"\") {\n issues.push({ line, message: \"the role key is empty\" });\n return;\n }\n\n const spec = findSpec(key);\n if (spec === undefined) {\n issues.push({\n line,\n message: unknownRoleMessage(rawKey, key),\n });\n return;\n }\n\n const parsed = parseRouteValue(rawValue);\n for (const issue of parsed.issues) issues.push({ line, message: `${rawKey}: ${issue}` });\n if (parsed.routes.length === 0) return;\n\n const previous = roles.get(spec.key);\n if (previous !== undefined) {\n issues.push({\n line,\n message: `role \"${spec.key}\" is already configured on line ${previous.line}; line ${line} wins`,\n });\n }\n roles.set(spec.key, { line, rawKey, key: spec.key, spec, rawValue, routes: parsed.routes });\n });\n\n return budget === undefined\n ? { status: \"loaded\", path, roles, issues }\n : { status: \"loaded\", path, budget, roles, issues };\n}\n\nexport interface RouteParseResult {\n readonly routes: readonly ChildRoute[];\n readonly issues: readonly string[];\n}\n\n/** Parse a role value: one route, or a comma-separated list of routes. */\nexport function parseRouteValue(raw: string): RouteParseResult {\n const routes: ChildRoute[] = [];\n const issues: string[] = [];\n const segments = raw.split(\",\");\n\n segments.forEach((segment, index) => {\n const trimmed = segment.trim();\n if (trimmed === \"\") {\n // A single trailing comma is harmless; a hole in the middle is a typo.\n if (index !== segments.length - 1) {\n issues.push(`entry ${index + 1} of the list is empty`);\n }\n return;\n }\n const parsed = parseRoute(trimmed);\n if (parsed.route === undefined) {\n issues.push(parsed.issue as string);\n return;\n }\n routes.push(parsed.route);\n });\n\n if (routes.length === 0 && issues.length === 0) {\n issues.push(\n \"the value is empty; use `inherit-parent`, `auto`, or `<provider>/<model> [effort]`\",\n );\n }\n return { routes, issues };\n}\n\nexport interface SingleRouteParse {\n readonly route?: ChildRoute;\n readonly issue?: string;\n}\n\n/** Parse one entry of a role value. */\nexport function parseRoute(raw: string): SingleRouteParse {\n const value = raw.trim();\n if (value === \"\") {\n return { issue: \"the value is empty\" };\n }\n\n if (INHERIT_PARENT_ALIASES.includes(value.toLowerCase())) {\n return { route: { kind: \"inherit\" } };\n }\n\n // The provider is the text before the first `/`, and the model is everything\n // after it, so a model id that carries its own vendor prefix stays one value.\n // A deployment can name models as `gateway/vendor-a/model-x`, and a grammar\n // that forbids `/` inside a model cannot route to any of them.\n //\n // The model is written as one or more non-empty `/`-separated segments rather\n // than \"anything but whitespace, comma, or bracket\", because the wider class\n // also accepts `provider//model`, `provider/vendor/`, and `provider//`. Those\n // are not routes any adapter serves, and taking them would move the failure\n // from this line, where it is reported with the line number, to a preflight\n // error on the first delegation.\n const match = /^([^\\s/,[]+)\\/([^\\s/,[\\]]+(?:\\/[^\\s/,[\\]]+)*)(?:\\s+\\[([^[\\]]*)\\])?$/.exec(value);\n if (match === null) {\n return {\n issue: `${JSON.stringify(value)} is not a route; use \\`inherit-parent\\`, \\`auto\\`, or \\`<provider>/<model> [effort]\\``,\n };\n }\n\n const provider = match[1] as string;\n const model = match[2] as string;\n const effort = match[3];\n\n if (effort === undefined) {\n return { route: { kind: \"route\", provider, model } };\n }\n const trimmedEffort = effort.trim();\n if (trimmedEffort === \"\") {\n return {\n issue: `${JSON.stringify(value)} has empty brackets; write \\`<provider>/<model> [effort]\\` or drop the brackets`,\n };\n }\n if (/\\s/.test(trimmedEffort)) {\n return {\n issue: `${JSON.stringify(value)} has a multi-word effort; an effort is one adapter-owned token`,\n };\n }\n return { route: { kind: \"route\", provider, model, effort: trimmedEffort } };\n}\n\n/** How one role's value expands into children. */\nexport type RouteSelectionMode = \"single\" | \"panel\" | \"selected\";\n\nexport interface RouteSelection {\n readonly role: RoleSpec;\n readonly mode: RouteSelectionMode;\n /** Whether the role came from the file or from the inherit-parent fallback. */\n readonly configured: boolean;\n readonly routes: readonly ChildRoute[];\n /** How many entries the role holds, before selection. */\n readonly total: number;\n readonly roleIndex?: number;\n readonly issues: readonly string[];\n}\n\n/** Raised when a role's configured list cannot be selected from. */\nexport class RouteSelectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RouteSelectionError\";\n }\n}\n\n/**\n * Expand one role into the routes this call starts.\n *\n * The three auto-panel roles start one child per entry. Another list role selects\n * one entry, the first by default, and `roleIndex` chooses which. A single role\n * holds exactly one route and rejects `roleIndex`.\n */\nexport function selectRoleRoutes(\n spec: RoleSpec,\n entry: RoleFileEntry | undefined,\n roleIndex: number | undefined,\n): RouteSelection {\n if (spec.shape === \"single\" && roleIndex !== undefined) {\n throw new RouteSelectionError(\n `role \"${spec.key}\" holds a single route, so \\`roleIndex\\` does not apply; drop \\`roleIndex\\` or use a list-valued role (${listRoleKeys().join(\", \")})`,\n );\n }\n if (spec.autoPanel && roleIndex !== undefined) {\n throw new RouteSelectionError(\n `role \"${spec.key}\" is an automatic panel: it starts one child per entry, so \\`roleIndex\\` does not apply; configure the entries you want in ${PSTACK_MODELS_FILENAME}`,\n );\n }\n\n if (entry === undefined) {\n return {\n role: spec,\n mode: spec.autoPanel ? \"panel\" : \"single\",\n configured: false,\n routes: [{ kind: \"inherit\" }],\n total: 1,\n issues: [],\n };\n }\n\n if (spec.autoPanel) {\n return {\n role: spec,\n mode: \"panel\",\n configured: true,\n routes: entry.routes,\n total: entry.routes.length,\n issues: [],\n };\n }\n\n if (spec.shape === \"list\") {\n const index = roleIndex ?? 0;\n if (index >= entry.routes.length) {\n throw new RouteSelectionError(\n `role \"${spec.key}\" has ${entry.routes.length} entr${entry.routes.length === 1 ? \"y\" : \"ies\"}, so \\`roleIndex\\` ${index} is out of range; valid indexes are ${entry.routes\n .map((_route, position) => position)\n .join(\", \")}`,\n );\n }\n return {\n role: spec,\n mode: \"selected\",\n configured: true,\n routes: [entry.routes[index] as ChildRoute],\n total: entry.routes.length,\n roleIndex: index,\n issues: [],\n };\n }\n\n return {\n role: spec,\n mode: \"single\",\n configured: true,\n routes: [entry.routes[0] as ChildRoute],\n total: entry.routes.length,\n issues: [],\n };\n}\n\n/** Keys of the list-valued roles, including the automatic panels. */\nexport function listRoleKeys(): readonly string[] {\n return ROLE_MANIFEST.filter((role) => role.shape === \"list\").map((role) => role.key);\n}\n\nfunction findSpec(key: string): RoleSpec | undefined {\n return ROLE_MANIFEST.find((role) => role.key === key);\n}\n\nfunction unknownRoleMessage(rawKey: string, key: string): string {\n const suggestions = suggestRoles(key);\n const hint =\n suggestions.length === 0\n ? \"no role key is close to it\"\n : `closest role keys: ${suggestions.map((candidate) => `\"${candidate}\"`).join(\", \")}`;\n return `unknown role ${JSON.stringify(rawKey)} (${hint}). A line for a retired or misspelled role would otherwise be ignored, so it is reported instead.`;\n}\n\nfunction stripFrontmatter(text: string): string {\n const normalized = text.replaceAll(\"\\r\\n\", \"\\n\");\n if (!normalized.startsWith(\"---\\n\")) return normalized;\n const end = normalized.indexOf(\"\\n---\", 3);\n if (end === -1) return normalized;\n const after = normalized.indexOf(\"\\n\", end + 1);\n return after === -1 ? \"\" : normalized.slice(after + 1);\n}\n\nfunction isMissingFile(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { code?: unknown }).code === \"ENOENT\"\n );\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error) {\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" ? `${code}: ${error.message}` : error.message;\n }\n return String(error);\n}\n","/**\n * `pstack_subagent`: pstack's delegation entry point.\n *\n * One call plans one or more fresh children, validates everything before the first\n * start, then starts them through `ctx.subagents.startActivation` with parent\n * delivery. Results arrive as completion notices; this module never polls.\n *\n * Validation order follows the design's delegation flow, and every check that can\n * reject a call happens before the first child starts, except a start failure in\n * the middle of a panel, which keeps the children already running and names them.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { PSTACK_MODELS_FILENAME } from \"../scripts/role-manifest.ts\";\nimport { parseFrontmatter } from \"./frontmatter.ts\";\nimport type {\n Agent,\n AgentOptions,\n AgentsHost,\n JsonSchemaNode,\n LlmHost,\n SubagentCapabilities,\n SubagentsHost,\n TextBlock,\n ToolDefinition,\n ToolRunContext,\n ToolsHost,\n} from \"./host-contract.ts\";\nimport {\n SET_EFFORT_TOOL,\n agentOptionsFor,\n effectiveEffort,\n installEffortControl,\n validateEffortFor,\n} from \"./effort.ts\";\nimport {\n modelsFilePath,\n readRoleFile,\n resolveDshHome,\n selectRoleRoutes,\n type ChildRoute,\n type RouteSelection,\n} from \"./models.ts\";\nimport { ASSETS_ROOT, POTETO_MODE_SKILL_PATH, agentPreamblePath } from \"./paths.ts\";\nimport { requireRole, type RoleSpec } from \"./roles.ts\";\n\n/** Cordis row name, used by Loader diagnostics. */\nexport const name = \"pstack-subagent\";\n\n/**\n * Delegation needs the tool registry, the subagent registry, and the LLM adapters.\n *\n * `agents` is deliberately **not** here. It is used only to reach a child this tool\n * has just started, and a composition without it still delegates: the children keep\n * the effort their request carried and cannot change it afterwards. Declaring it as\n * a hard dependency would make the whole row inert in such a profile, so the tool\n * would not exist at all — the failure `pstack-history` already paid for once with\n * `sessionQuery`. It is read per call through `ctx.get(\"agents\")` instead, which is\n * why a controller mounted after this row is still seen.\n */\nexport const inject = [\"tools\", \"subagents\", \"llm\"];\n\n/** Model-facing tool name. */\nexport const TOOL_NAME = \"pstack_subagent\";\n\n/** Backend used when the row does not name one. */\nexport const DEFAULT_SUBAGENT_PROVIDER = \"spawn\";\n\n/** Agent type used when the call does not name one. */\nexport const DEFAULT_AGENT_KIND = \"poteto-agent\";\n\n/** The child kinds this tool knows how to brief. */\nexport const AGENT_KINDS = [\"poteto-agent\", \"comment-sicko\", \"general\"] as const;\n\nexport type AgentKind = (typeof AGENT_KINDS)[number];\n\n/** One exact route a row may authorize for explicit child selection. */\nexport interface AllowedModelRoute {\n readonly provider: string;\n readonly model: string;\n}\n\n/** Row configuration. */\nexport interface PstackSubagentConfig {\n /** `ctx.subagents` provider to start children on. */\n readonly provider: string;\n /**\n * This row's delegation-depth cap. A call may lower it and may never exceed it.\n * Omitted means the Host setting decides.\n */\n readonly maxDepth?: number;\n /**\n * Exact routes this row authorizes. Empty means no explicit route limit. This is\n * pstack's own check and is unrelated to the native session `allowedModels`\n * policy, which this plugin does not read.\n */\n readonly allowedModels: readonly AllowedModelRoute[];\n /** Non-empty allowlist; also what makes `agentPreset` appear in the schema. */\n readonly allowedAgentPresets: readonly string[];\n}\n\nconst DEFAULT_CONFIG: PstackSubagentConfig = {\n provider: DEFAULT_SUBAGENT_PROVIDER,\n allowedModels: [],\n allowedAgentPresets: [],\n};\n\n/** What a call asked for, after argument validation. */\nexport interface DelegationArgs {\n readonly description: string;\n readonly prompt: string;\n readonly agent: AgentKind;\n readonly role?: string;\n readonly cwd?: string;\n readonly agentPreset?: string;\n readonly maxDepth?: number;\n readonly roleIndex?: number;\n /**\n * Effort for every child this call starts, overriding each role line's value.\n *\n * Validated per entry against the model that entry will actually request, so a\n * panel with one incompatible entry starts nothing rather than half its children.\n */\n readonly reasoningEffort?: string;\n}\n\n/** One child this call started. */\nexport interface ChildRecord {\n readonly childId: string;\n readonly label: string;\n readonly agent: string;\n readonly role: string;\n readonly route: string;\n /** The effort this child runs at, when any applies. */\n readonly effort?: string;\n readonly maxDepth?: number;\n}\n\nexport interface DelegationResult {\n readonly kind: \"activation\" | \"activations\";\n readonly children: readonly ChildRecord[];\n readonly diagnostics: readonly string[];\n}\n\n/** Raised for a configuration or argument problem, before any child starts. */\nexport class DelegationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"DelegationError\";\n }\n}\n\n/** Raised when a child starts but a later entry in the same call fails. */\nexport class PartialDelegationError extends DelegationError {\n readonly startedChildren: readonly ChildRecord[];\n\n constructor(message: string, startedChildren: readonly ChildRecord[]) {\n super(message);\n this.name = \"PartialDelegationError\";\n this.startedChildren = startedChildren;\n }\n}\n\n/** Raised when a required agent preamble is missing or unusable. */\nexport class PreambleError extends DelegationError {\n constructor(message: string) {\n super(message);\n this.name = \"PreambleError\";\n }\n}\n\n/** The live services and locations one delegation reads. */\nexport interface SubagentRuntime {\n readonly subagents: SubagentsHost;\n readonly llm: LlmHost;\n /**\n * The Agent registry, used to reach a child this tool just started.\n *\n * Optional because a row can be composed without the `agents` service and a\n * delegation still works there: the children then keep the effort their request\n * carried and simply cannot change it afterwards. Making it required would turn a\n * missing service into a row that registers no tool at all.\n */\n readonly agents?: AgentsHost;\n /** `$DSH_HOME`, home of the role file. */\n readonly dshHome: string;\n /** Absolute package assets root, home of the agent preambles. */\n readonly assetsRoot: string;\n}\n\n// ---------------------------------------------------------------------------\n// Row config\n// ---------------------------------------------------------------------------\n\ninterface StandardSchemaIssue {\n readonly message: string;\n readonly path?: readonly (string | number)[];\n}\n\ntype StandardSchemaResult =\n | { readonly value: PstackSubagentConfig; readonly issues?: undefined }\n | { readonly issues: readonly StandardSchemaIssue[] };\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim() !== \"\";\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/**\n * Minimal Standard Schema for this row, so an omitted `config` is valid and a\n * typo fails at load instead of at the first delegation.\n */\nexport const Config = {\n \"~standard\": {\n version: 1,\n vendor: \"dsh-pstack\",\n validate(value: unknown): StandardSchemaResult {\n if (value === undefined || value === null) return { value: DEFAULT_CONFIG };\n if (typeof value !== \"object\" || Array.isArray(value)) {\n return { issues: [{ message: \"config must be a mapping\" }] };\n }\n\n const record = value as Record<string, unknown>;\n const issues: StandardSchemaIssue[] = [];\n const allowedKeys = new Set([\n \"provider\",\n \"maxDepth\",\n \"allowedModels\",\n \"allowedAgentPresets\",\n ]);\n for (const key of Object.keys(record)) {\n if (!allowedKeys.has(key)) issues.push({ message: `unknown field \"${key}\"`, path: [key] });\n }\n\n const provider = record[\"provider\"];\n if (provider !== undefined && !isNonEmptyString(provider)) {\n issues.push({ message: \"provider must be a non-empty string\", path: [\"provider\"] });\n }\n\n const maxDepth = record[\"maxDepth\"];\n if (maxDepth !== undefined && !isNonNegativeSafeInteger(maxDepth)) {\n issues.push({\n message: \"maxDepth must be a non-negative safe integer\",\n path: [\"maxDepth\"],\n });\n }\n\n const allowedModels = record[\"allowedModels\"];\n const models: AllowedModelRoute[] = [];\n if (allowedModels !== undefined) {\n if (!Array.isArray(allowedModels)) {\n issues.push({ message: \"allowedModels must be an array\", path: [\"allowedModels\"] });\n } else {\n allowedModels.forEach((entry, index) => {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n issues.push({\n message: \"each allowedModels entry must be a { provider, model } object\",\n path: [\"allowedModels\", index],\n });\n return;\n }\n const route = entry as Record<string, unknown>;\n const routeProvider = route[\"provider\"];\n const routeModel = route[\"model\"];\n if (!isNonEmptyString(routeProvider) || !isNonEmptyString(routeModel)) {\n issues.push({\n message: \"each allowedModels entry needs a non-empty provider and model\",\n path: [\"allowedModels\", index],\n });\n return;\n }\n if (models.some((known) => known.provider === routeProvider && known.model === routeModel)) {\n issues.push({\n message: `duplicate allowedModels route \"${routeProvider}/${routeModel}\"`,\n path: [\"allowedModels\", index],\n });\n return;\n }\n models.push({ provider: routeProvider, model: routeModel });\n });\n }\n }\n\n const allowedPresets = record[\"allowedAgentPresets\"];\n const presets: string[] = [];\n if (allowedPresets !== undefined) {\n if (!Array.isArray(allowedPresets)) {\n issues.push({\n message: \"allowedAgentPresets must be an array\",\n path: [\"allowedAgentPresets\"],\n });\n } else {\n allowedPresets.forEach((entry, index) => {\n if (!isNonEmptyString(entry)) {\n issues.push({\n message: \"each allowedAgentPresets entry must be a non-empty string\",\n path: [\"allowedAgentPresets\", index],\n });\n return;\n }\n if (presets.includes(entry)) {\n issues.push({\n message: `duplicate allowedAgentPresets entry \"${entry}\"`,\n path: [\"allowedAgentPresets\", index],\n });\n return;\n }\n presets.push(entry);\n });\n }\n }\n\n if (issues.length > 0) return { issues };\n return {\n value: {\n provider: isNonEmptyString(provider) ? provider : DEFAULT_SUBAGENT_PROVIDER,\n ...(isNonNegativeSafeInteger(maxDepth) ? { maxDepth } : {}),\n allowedModels: models,\n allowedAgentPresets: presets,\n },\n };\n },\n },\n};\n\n// ---------------------------------------------------------------------------\n// Preamble\n// ---------------------------------------------------------------------------\n\n/**\n * Read one agent preamble from the package assets by absolute path.\n *\n * A missing or empty preamble blocks that agent type. It never degrades into a\n * plain child, because a `comment-sicko` or `poteto-agent` child without its\n * instructions is a different agent wearing the name.\n */\nexport function loadAgentPreamble(agent: AgentKind, assetsRoot: string): string | undefined {\n const path = agentPreamblePath(agent);\n if (path === undefined) return undefined;\n\n const absolute = join(assetsRoot, \"agents\", `${agent}.md`);\n let text: string;\n try {\n text = readFileSync(absolute, \"utf8\");\n } catch (error) {\n const code = (error as { code?: unknown }).code;\n const detail = typeof code === \"string\" ? code : String(error);\n throw new PreambleError(\n `the ${agent} preamble cannot be read at ${absolute} (${detail}). This agent type does not start without its preamble; reinstall dsh-pstack so the packaged assets are present, or pass agent: \"general\" for a plain child that gets no preamble.`,\n );\n }\n\n const body = parseFrontmatter(text).body.trim();\n if (body === \"\") {\n throw new PreambleError(\n `the ${agent} preamble at ${absolute} is empty. This agent type does not start without its instructions; repair the packaged asset or pass agent: \"general\".`,\n );\n }\n return body;\n}\n\n/** One absolute path the Host injects into a child brief. */\nexport interface InjectedPath {\n readonly label: string;\n readonly path: string;\n}\n\n/**\n * Compose the self-contained prompt one child receives.\n *\n * The preambles used to locate things themselves; the Host injects the absolute\n * paths instead, so a child never scans a plugin directory or guesses a version.\n */\nexport function composeChildPrompt(input: {\n readonly preamble?: string;\n readonly injectedPaths?: readonly InjectedPath[];\n readonly task: string;\n}): string {\n const sections: string[] = [];\n if (input.preamble !== undefined) sections.push(input.preamble);\n\n const injected = input.injectedPaths ?? [];\n if (injected.length > 0) {\n sections.push(\n [\n \"Absolute paths injected by `pstack_subagent`. Read them directly; do not search a plugin directory.\",\n \"\",\n ...injected.map((entry) => `- ${entry.label}: \\`${entry.path}\\``),\n ].join(\"\\n\"),\n );\n }\n\n if (sections.length === 0) return input.task;\n sections.push(`Task:\\n\\n${input.task}`);\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\n/** One planned child, before any Host call. */\nexport interface ChildPlan {\n readonly index: number;\n readonly total: number;\n readonly label: string;\n readonly agent: AgentKind;\n readonly role: string;\n readonly route: ChildRoute;\n readonly routeLabel: string;\n /** The effort this child will actually run at: the override when present, else the role line's. */\n readonly effort?: string;\n readonly agentOptions?: AgentOptions;\n readonly agentPreset?: string;\n readonly cwd?: string;\n readonly maxDepth?: number;\n}\n\n/** The decided plan for one call. */\nexport interface DelegationPlan {\n readonly agent: AgentKind;\n readonly prompt: string;\n readonly provider: string;\n readonly role: string;\n readonly mode: RouteSelection[\"mode\"];\n readonly roleIndex?: number;\n readonly roleTotal: number;\n /** The call-wide effort override, when it supplied one. */\n readonly reasoningEffort?: string;\n readonly children: readonly ChildPlan[];\n readonly diagnostics: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// Route and depth helpers\n// ---------------------------------------------------------------------------\n\n/** The text form of one route, as reported back to the model. */\nexport function routeLabel(route: ChildRoute): string {\n if (route.kind === \"inherit\") return \"inherit-parent\";\n return route.effort === undefined\n ? `${route.provider}/${route.model}`\n : `${route.provider}/${route.model} [${route.effort}]`;\n}\n\n/**\n * The route text a caller sees when an effort override wins.\n *\n * `routeLabel` describes the role file, which stops being the whole truth once the\n * caller overrode the effort. Reporting the file's value there would tell the model\n * its override had been ignored.\n */\nexport function plannedRouteLabel(route: ChildRoute, effortOverride?: string): string {\n const effort = effectiveEffort(route, effortOverride);\n const base = route.kind === \"inherit\" ? \"inherit-parent\" : `${route.provider}/${route.model}`;\n return effort === undefined ? base : `${base} [${effort}]`;\n}\n\nexport { agentOptionsFor };\n\n/**\n * Take the smallest of the requested depth, this row's cap, and the Host setting.\n *\n * A request above the row cap is an error rather than a silent clamp, so a caller\n * cannot believe it asked for two levels when the row allows one.\n */\nexport function resolveDelegationDepth(\n configured: number | undefined,\n requested: number | undefined,\n hostLimit: number | undefined,\n): number | undefined {\n if (requested !== undefined && !isNonNegativeSafeInteger(requested)) {\n throw new DelegationError(\"maxDepth must be a non-negative safe integer\");\n }\n if (configured !== undefined && requested !== undefined && requested > configured) {\n throw new DelegationError(\n `maxDepth ${requested} exceeds this row's configured cap of ${configured}. Lower the request or raise \\`pstack-subagent\\` config.maxDepth; this tool never forwards a depth above its own row.`,\n );\n }\n\n const candidates = [configured, requested, hostLimit].filter(\n (value): value is number => value !== undefined,\n );\n return candidates.length === 0 ? undefined : Math.min(...candidates);\n}\n\n// ---------------------------------------------------------------------------\n// Arguments\n// ---------------------------------------------------------------------------\n\n/**\n * Validate the model-facing arguments.\n *\n * The tool schema is advisory at the model boundary, so every constraint is\n * re-checked here and reported with the reason.\n */\nexport function parseDelegationArgs(\n raw: unknown,\n config: PstackSubagentConfig = DEFAULT_CONFIG,\n): DelegationArgs {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n throw new DelegationError(\"arguments must be an object\");\n }\n const record = raw as Record<string, unknown>;\n\n const known = new Set([\n \"description\",\n \"prompt\",\n \"agent\",\n \"role\",\n \"cwd\",\n ...(config.allowedAgentPresets.length > 0 ? [\"agentPreset\"] : []),\n \"maxDepth\",\n \"roleIndex\",\n \"reasoningEffort\",\n ]);\n for (const key of Object.keys(record)) {\n if (!known.has(key)) {\n const hint =\n key === \"agentPreset\"\n ? \"agentPreset is only available when this row configures allowedAgentPresets\"\n : `accepted arguments are ${[...known].join(\", \")}`;\n throw new DelegationError(`unknown argument \"${key}\": ${hint}`);\n }\n }\n\n const description = record[\"description\"];\n if (!isNonEmptyString(description)) {\n throw new DelegationError(\"description must be a non-empty string: it becomes the child label\");\n }\n const prompt = record[\"prompt\"];\n if (!isNonEmptyString(prompt)) {\n throw new DelegationError(\"prompt must be a non-empty string\");\n }\n\n const agentRaw = record[\"agent\"];\n if (agentRaw !== undefined && typeof agentRaw !== \"string\") {\n throw new DelegationError(`agent must be a string: ${AGENT_KINDS.join(\", \")}`);\n }\n const agent = (agentRaw ?? DEFAULT_AGENT_KIND) as string;\n if (!(AGENT_KINDS as readonly string[]).includes(agent)) {\n throw new DelegationError(\n `unknown agent \"${agent}\". Accepted kinds are ${AGENT_KINDS.join(\", \")}; a pstack agent type is not a DSH agent preset, so \\`agent\\` never accepts a preset id.`,\n );\n }\n\n const role = record[\"role\"];\n if (role !== undefined && !isNonEmptyString(role)) {\n throw new DelegationError(\"role must be a non-empty string when present\");\n }\n\n const cwd = record[\"cwd\"];\n if (cwd !== undefined && !isNonEmptyString(cwd)) {\n throw new DelegationError(\"cwd must be a non-empty string when present\");\n }\n\n const agentPreset = record[\"agentPreset\"];\n if (agentPreset !== undefined) {\n if (config.allowedAgentPresets.length === 0) {\n throw new DelegationError(\n \"agentPreset is not available: this pstack-subagent row configures no allowedAgentPresets\",\n );\n }\n if (!isNonEmptyString(agentPreset) || !config.allowedAgentPresets.includes(agentPreset)) {\n throw new DelegationError(\n `agentPreset ${JSON.stringify(agentPreset)} is not in this row's allowlist (${config.allowedAgentPresets.join(\", \")})`,\n );\n }\n }\n\n const maxDepth = record[\"maxDepth\"];\n if (maxDepth !== undefined && !isNonNegativeSafeInteger(maxDepth)) {\n throw new DelegationError(\"maxDepth must be a non-negative safe integer\");\n }\n\n const roleIndex = record[\"roleIndex\"];\n if (roleIndex !== undefined) {\n if (!isNonNegativeSafeInteger(roleIndex)) {\n throw new DelegationError(\"roleIndex must be a non-negative safe integer\");\n }\n if (role === undefined) {\n throw new DelegationError(\n \"roleIndex requires role: it selects one entry of a list-valued role, and without a role there is no list\",\n );\n }\n }\n\n const requestedEffort = record[\"reasoningEffort\"];\n if (requestedEffort !== undefined && !isNonEmptyString(requestedEffort)) {\n throw new DelegationError(\n \"reasoningEffort must be a non-empty string when present. It is one adapter-owned token, validated against the model this call will actually request; an empty value would silently re-enable the adapter default.\",\n );\n }\n if (typeof requestedEffort === \"string\" && /\\s/.test(requestedEffort.trim())) {\n throw new DelegationError(\n `reasoningEffort ${JSON.stringify(requestedEffort)} contains whitespace. An effort is one token, exactly as the model advertises it.`,\n );\n }\n\n return {\n description,\n prompt,\n agent: agent as AgentKind,\n ...(role === undefined ? {} : { role }),\n ...(cwd === undefined ? {} : { cwd }),\n ...(agentPreset === undefined ? {} : { agentPreset }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(roleIndex === undefined ? {} : { roleIndex }),\n ...(requestedEffort === undefined ? {} : { reasoningEffort: requestedEffort.trim() }),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Planning\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the role file, the routes, the prompt, and the depth into one plan.\n *\n * Pure with respect to the Host: it reads the role file and the packaged preamble,\n * and it makes no service call.\n */\nexport function planDelegation(\n args: DelegationArgs,\n runtime: SubagentRuntime,\n config: PstackSubagentConfig = DEFAULT_CONFIG,\n): DelegationPlan {\n const preamble = loadAgentPreamble(args.agent, runtime.assetsRoot);\n\n const rolePath = modelsFilePath(runtime.dshHome);\n const roleFile = readRoleFile(rolePath);\n if (roleFile.status === \"unreadable\") {\n throw new DelegationError(\n `the pstack role file at ${rolePath} exists but cannot be read (${roleFile.reason}). This is a broken configuration, not \"no configuration\": fix its permissions or delete the file, which makes every role inherit the parent route.`,\n );\n }\n const diagnostics: string[] = [];\n if (roleFile.status === \"loaded\") {\n for (const issue of roleFile.issues) {\n diagnostics.push(\n `${rolePath}${issue.line === undefined ? \"\" : `:${issue.line}`}: ${issue.message}`,\n );\n }\n }\n\n let selection: RouteSelection | undefined;\n let roleSpec: RoleSpec | undefined;\n if (args.role !== undefined) {\n roleSpec = requireRole(args.role);\n const entry = roleFile.status === \"loaded\" ? roleFile.roles.get(roleSpec.key) : undefined;\n selection = selectRoleRoutes(roleSpec, entry, args.roleIndex);\n }\n\n const routes: readonly ChildRoute[] = selection?.routes ?? [{ kind: \"inherit\" }];\n const roleName = roleSpec?.key ?? \"(none)\";\n\n if (selection !== undefined) {\n if (!selection.configured) {\n diagnostics.push(\n `role \"${selection.role.key}\" has no line in ${rolePath}, so it inherits the parent route. Add a line to route it explicitly.`,\n );\n }\n if (selection.mode === \"selected\") {\n diagnostics.push(\n `role \"${selection.role.key}\" holds ${selection.total} entries and is not an automatic panel; entry ${(selection.roleIndex ?? 0) + 1} was selected. Pass \\`roleIndex\\` to choose another.`,\n );\n }\n if (selection.role.key === \"swarm workers\") {\n diagnostics.push(\n 'role \"swarm workers\" is a list, not a panel: its first entry is the default route for every worker, and `roleIndex` gives one race arm another entry. Each worker still needs its own pstack_subagent call, because this tool cannot compare separate calls.',\n );\n }\n }\n\n assertAllowedModels(routes, config, roleName);\n\n const injected: InjectedPath[] =\n args.agent === \"poteto-agent\"\n ? [{ label: \"`poteto-mode` SKILL.md\", path: POTETO_MODE_SKILL_PATH }]\n : [];\n const prompt = composeChildPrompt({\n ...(preamble === undefined ? {} : { preamble }),\n injectedPaths: injected,\n task: args.prompt,\n });\n\n // The Host setting is applied at start time; the plan records the row's own cap.\n const depth = resolveDelegationDepth(config.maxDepth, args.maxDepth, undefined);\n\n const total = routes.length;\n const children: ChildPlan[] = routes.map((route, index) => {\n const agentOptions = agentOptionsFor(route, args.reasoningEffort);\n const effort = effectiveEffort(route, args.reasoningEffort);\n return {\n index,\n total,\n label:\n total > 1 ? `${args.description} [${roleName} ${index + 1}/${total}]` : args.description,\n agent: args.agent,\n role: roleName,\n route,\n routeLabel: plannedRouteLabel(route, args.reasoningEffort),\n ...(effort === undefined ? {} : { effort }),\n ...(agentOptions === undefined ? {} : { agentOptions }),\n ...(args.agentPreset === undefined ? {} : { agentPreset: args.agentPreset }),\n ...(args.cwd === undefined ? {} : { cwd: args.cwd }),\n ...(depth === undefined ? {} : { maxDepth: depth }),\n };\n });\n\n if (args.reasoningEffort !== undefined) {\n const overwritten = routes.filter(\n (route) => route.kind === \"route\" && route.effort !== undefined && route.effort !== args.reasoningEffort,\n );\n if (overwritten.length > 0) {\n diagnostics.push(\n `reasoningEffort \"${args.reasoningEffort}\" overrides the effort this call's role line names (${overwritten\n .map((route) => routeLabel(route))\n .join(\", \")}). The role line is a starting baseline, so this is allowed; pass no reasoningEffort to keep it.`,\n );\n }\n }\n\n addPanelDiagnostics(children, roleName, selection, rolePath, diagnostics);\n\n return {\n agent: args.agent,\n prompt,\n provider: config.provider,\n role: roleName,\n mode: selection?.mode ?? \"single\",\n ...(selection?.roleIndex === undefined ? {} : { roleIndex: selection.roleIndex }),\n roleTotal: selection?.total ?? 1,\n ...(args.reasoningEffort === undefined ? {} : { reasoningEffort: args.reasoningEffort }),\n children,\n diagnostics,\n };\n}\n\nfunction assertAllowedModels(\n routes: readonly ChildRoute[],\n config: PstackSubagentConfig,\n roleName: string,\n): void {\n if (config.allowedModels.length === 0) return;\n const unauthorized = routes.filter(\n (route) =>\n route.kind === \"route\" &&\n !config.allowedModels.some(\n (allowed) => allowed.provider === route.provider && allowed.model === route.model,\n ),\n );\n if (unauthorized.length === 0) return;\n\n const allowed = config.allowedModels\n .map((route) => `${route.provider}/${route.model}`)\n .join(\", \");\n throw new DelegationError(\n `role ${roleName} resolves to ${unauthorized.map(routeLabel).join(\", \")}, which this row's allowedModels does not authorize. Authorized routes: ${allowed}. This is pstack's own row limit and is unrelated to the native session allowedModels policy.`,\n );\n}\n\nfunction addPanelDiagnostics(\n children: readonly ChildPlan[],\n roleName: string,\n selection: RouteSelection | undefined,\n rolePath: string,\n diagnostics: string[],\n): void {\n if (selection === undefined || selection.mode !== \"panel\") return;\n\n if (children.length === 1) {\n diagnostics.push(\n `panel \"${roleName}\" has one configured entry, so this call started one child and claims no model diversity. Add entries to ${rolePath} for a real panel.`,\n );\n return;\n }\n\n const distinct = new Set(children.map((child) => child.routeLabel));\n if (distinct.size > 1) return;\n diagnostics.push(\n `all ${children.length} entries of panel \"${roleName}\" resolve to the same route (${[...distinct][0]}), so these children are not a cross-model review. Configure distinct routes in ${rolePath} for a real panel.`,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Host calls\n// ---------------------------------------------------------------------------\n\n/**\n * Validate every route, and every requested effort, before anything starts.\n *\n * `resolveCallConfig` rejects an unsupported effort and any route the owning\n * adapter does not serve. An inherit-parent entry has no provider/model of its own,\n * so its effort is validated against the parent's live route instead. This does not\n * prove credentials, quota, or a successful model call; only a real child request\n * does.\n *\n * Every entry is checked before the first child starts. A panel whose second entry\n * cannot take the effort therefore starts none of them, which is the only outcome\n * that leaves no half-applied override behind.\n */\nasync function preflightRoutes(\n llm: LlmHost,\n parent: Agent,\n children: readonly ChildPlan[],\n roleName: string,\n effortOverride: string | undefined,\n signal: AbortSignal,\n): Promise<void> {\n for (const child of children) {\n if (child.agentOptions === undefined) continue;\n\n if (child.route.kind === \"inherit\") {\n // Only reachable with an override: an inherit route with no effort carries no\n // agentOptions at all and is skipped above.\n const effort = effortOverride as string;\n try {\n await validateEffortFor(llm, undefined, effort, parent, signal);\n } catch (error) {\n throw new DelegationError(\n `role ${roleName} inherits the parent route, and reasoningEffort \"${effort}\" failed preflight there: ${describeError(error)} Omit \\`reasoningEffort\\`, or name a role whose line holds an exact route.`,\n );\n }\n continue;\n }\n\n const route = child.route;\n const callConfig = {\n provider: route.provider,\n model: route.model,\n ...(child.effort === undefined ? {} : { reasoningEffort: child.effort }),\n };\n try {\n await llm.resolveCallConfig(callConfig, signal);\n } catch (error) {\n throw new DelegationError(\n `role ${roleName} resolves to ${child.routeLabel}, which failed route preflight: ${describeError(error)}. ${await effortHint(llm, route, child.effort, signal)}`,\n );\n }\n }\n}\n\nasync function effortHint(\n llm: LlmHost,\n route: Extract<ChildRoute, { kind: \"route\" }>,\n effort: string | undefined,\n signal: AbortSignal,\n): Promise<string> {\n if (effort !== undefined) {\n try {\n const info = await llm.resolveModelInfo(route.provider, route.model, signal);\n const efforts = info.reasoning?.efforts.map((entry) => entry.id) ?? [];\n if (efforts.length > 0) {\n return `Model ${route.provider}/${route.model} supports these efforts: ${efforts.join(\", \")}.`;\n }\n return `Model ${route.provider}/${route.model} advertises no reasoning efforts.`;\n } catch {\n return `Fix the route or the effort in ${PSTACK_MODELS_FILENAME}; the configured provider/model pair may not be served by this deployment.`;\n }\n }\n return `Check the route in ${PSTACK_MODELS_FILENAME} against the providers this deployment registers.`;\n}\n\n/** Check the backend can enforce what this call asks for. */\nexport function assertProviderCapabilities(\n capabilities: SubagentCapabilities,\n providerName: string,\n asks: { readonly agentOptions: boolean; readonly agentPreset: boolean; readonly maxDepth: boolean },\n): void {\n const missing: string[] = [];\n if (asks.agentOptions && !capabilities.agentOptions) missing.push(\"agentOptions\");\n if (asks.agentPreset && !capabilities.agentPreset) missing.push(\"agentPreset\");\n if (asks.maxDepth && !capabilities.depthLimit) missing.push(\"maxDepth\");\n if (missing.length === 0) return;\n throw new DelegationError(\n `subagent provider \"${providerName}\" does not support ${missing.join(\", \")}, so this call cannot be honored. Change the route to \\`inherit-parent\\`, drop the unsupported argument, or configure a backend that supports it; this tool never silently ignores it.`,\n );\n}\n\n/**\n * Start the planned children.\n *\n * Everything that can be rejected has already been rejected. A failure at entry N\n * keeps children 1..N-1 running and reports their ids, because the runtime owns\n * those activations and this tool cannot roll them back.\n */\nexport async function startPlannedChildren(\n parent: Agent,\n plan: DelegationPlan,\n runtime: SubagentRuntime,\n config: PstackSubagentConfig,\n signal: AbortSignal,\n): Promise<DelegationResult> {\n const provider = runtime.subagents.getProvider(plan.provider);\n if (provider === undefined) {\n const available = runtime.subagents.list();\n throw new DelegationError(\n `subagent provider \"${plan.provider}\" is not registered; registered providers: ${available.length === 0 ? \"(none)\" : available.join(\", \")}. This pstack-subagent row delegates to \"${plan.provider}\"; compose that backend or change the row's provider.`,\n );\n }\n\n const hostLimit = runtime.subagents.resolveMaxDepth(config.maxDepth);\n const effectiveDepth = resolveDelegationDepth(\n config.maxDepth,\n plan.children[0]?.maxDepth,\n hostLimit,\n );\n\n assertProviderCapabilities(provider.capabilities, plan.provider, {\n agentOptions: plan.children.some((child) => child.agentOptions !== undefined),\n agentPreset: plan.children.some((child) => child.agentPreset !== undefined),\n maxDepth: effectiveDepth !== undefined,\n });\n const children = plan.children.map((child) => ({\n ...child,\n ...(effectiveDepth === undefined ? {} : { maxDepth: effectiveDepth }),\n }));\n\n await preflightRoutes(runtime.llm, parent, children, plan.role, plan.reasoningEffort, signal);\n if (runtime.subagents.getProvider(plan.provider) !== provider) {\n throw new DelegationError(\n `subagent provider \"${plan.provider}\" changed while the child routes were being resolved; retry the delegation`,\n );\n }\n\n const started: ChildRecord[] = [];\n const diagnostics = [...plan.diagnostics];\n for (const child of children) {\n signal.throwIfAborted();\n try {\n const activation = await runtime.subagents.startActivation({\n provider: plan.provider,\n label: child.label,\n request: {\n prompt: [{ type: \"text\", text: plan.prompt }] satisfies TextBlock[],\n parent,\n ...(child.cwd === undefined ? {} : { cwd: child.cwd }),\n ...(child.agentPreset === undefined ? {} : { agentPreset: child.agentPreset }),\n ...(child.agentOptions === undefined ? {} : { agentOptions: child.agentOptions }),\n ...(child.maxDepth === undefined ? {} : { maxDepth: child.maxDepth }),\n },\n signal,\n delivery: \"parent\",\n });\n\n // The child can raise or lower its own effort from here on. Registration is on\n // the child's own scope, which disposes it with the child, so this call site\n // keeps no handle: a tool call that returns is not the owner of a child that\n // keeps running.\n //\n // A missing handle is not a failed delegation. The child then runs at the\n // effort the request carried and cannot change it, which is what a backend\n // without a live local Agent offers; saying so is better than implying a control\n // that is not there.\n const target =\n runtime.agents === undefined ? undefined : runtime.agents.get(activation.childId);\n if (target === undefined) {\n diagnostics.push(\n `child ${activation.childId} has no live local Agent handle, so it cannot change its own reasoning effort with \\`${SET_EFFORT_TOOL}\\`. It runs at ${child.effort === undefined ? \"the adapter default\" : `\"${child.effort}\"`} for its whole life.`,\n );\n } else {\n installEffortControl(target, runtime.llm, child.effort);\n }\n\n started.push({\n childId: activation.childId,\n label: child.label,\n agent: child.agent,\n role: child.role,\n route: child.routeLabel,\n ...(child.effort === undefined ? {} : { effort: child.effort }),\n ...(child.maxDepth === undefined ? {} : { maxDepth: child.maxDepth }),\n });\n } catch (error) {\n if (started.length === 0) {\n throw new DelegationError(\n `starting the ${plan.role === \"(none)\" ? \"child\" : `\"${plan.role}\" child`} \"${child.label}\" (${child.routeLabel}) failed: ${describeError(error)}`,\n );\n }\n throw new PartialDelegationError(\n `starting entry ${child.index + 1} of ${child.total} for role \"${plan.role}\" (${child.label}, ${child.routeLabel}) failed: ${describeError(error)}. The ${started.length} already started: ${started\n .map((record) => `${record.childId} (${record.label})`)\n .join(\", \")}. Those children are still running and are not rolled back; do not start them again, and use list_agents or send_message to reach them.`,\n started,\n );\n }\n }\n\n return {\n kind: started.length === 1 ? \"activation\" : \"activations\",\n children: started,\n diagnostics,\n };\n}\n\n/** Full delegation: plan, validate, start. */\nexport async function delegate(\n parent: Agent,\n args: DelegationArgs,\n runtime: SubagentRuntime,\n config: PstackSubagentConfig = DEFAULT_CONFIG,\n signal: AbortSignal = new AbortController().signal,\n): Promise<DelegationResult> {\n const plan = planDelegation(args, runtime, config);\n return startPlannedChildren(parent, plan, runtime, config, signal);\n}\n\n// ---------------------------------------------------------------------------\n// Tool\n// ---------------------------------------------------------------------------\n\nconst TOOL_DESCRIPTION = [\n \"Delegate self-contained work to one or more fresh child agents.\",\n \"\",\n \"Returns the id of every child it started plus the route each one resolved. The children run\",\n \"in the background: their results arrive later as completion notices in this conversation.\",\n \"Never wait or poll for them, and keep working on something useful meanwhile.\",\n \"\",\n \"`agent` picks the brief: `poteto-agent` (default) injects the poteto subagent preamble and\",\n \"the absolute path of the poteto-mode instructions; `comment-sicko` injects the comment\",\n \"reviewer persona and must be briefed read-only; `general` is a plain child with no preamble.\",\n \"\",\n \"`role` selects a configured pstack role and therefore the child's model route and reasoning\",\n \"effort. The role names and the meaning of each are in the pstack role manifest, not here.\",\n \"Omit `role` to inherit the parent route. Panel roles start one child per configured entry.\",\n \"\",\n \"`reasoningEffort` raises or lowers the effort for this delegation alone. The role line is a\",\n \"starting baseline, not a verdict: start from it, raise it for hard work and lower it for\",\n \"routine work. The value must be one the target model advertises, and this package does not\",\n \"assume a ladder, so read the effort list the role's model reports rather than guessing. An\",\n \"unsupported value fails the call before any child starts, including every entry of a panel.\",\n \"\",\n \"A running child can also change its own effort with `set_reasoning_effort`, which applies\",\n \"from its next step. You do not have to predict the level up front.\",\n \"\",\n \"Every prompt is a fresh child that does not see this conversation, so include everything it\",\n \"needs. A child's own summary is not evidence: review its diff or artifacts yourself.\",\n].join(\"\\n\");\n\nfunction buildParameters(config: PstackSubagentConfig): Record<string, unknown> {\n const properties: Record<string, unknown> = {\n description: {\n type: \"string\",\n description: \"A short 3-5 word label for the child, shown in list_agents and its notices.\",\n },\n prompt: {\n type: \"string\",\n description:\n \"The complete, self-contained brief. The child does not see this conversation, so include the task, every prior directive, and the paths or branches it needs.\",\n },\n agent: {\n type: \"string\",\n enum: [...AGENT_KINDS],\n description:\n 'Child brief type: \"poteto-agent\" (default) for pstack implementation delegates, \"comment-sicko\" for the read-only comment reviewer, \"general\" for a plain child with no preamble.',\n },\n role: {\n type: \"string\",\n description:\n \"A pstack role key, matched exactly. It selects the child's model route and effort. Omit it to inherit the parent route.\",\n },\n cwd: {\n type: \"string\",\n description:\n \"The child's initial working directory. Relative paths resolve against this session's directory. Omitted inherits it.\",\n },\n maxDepth: {\n type: \"integer\",\n description:\n \"How many further delegation levels the child may use; 0 or greater, and negative values are rejected. It can only lower this row's configured cap, never raise it.\",\n },\n roleIndex: {\n type: \"integer\",\n description:\n \"Selects one entry of a list-valued role that is not an automatic panel; 0 or greater, and negative values are rejected. Requires `role`.\",\n },\n reasoningEffort: {\n type: \"string\",\n description: [\n \"Reasoning effort for every child this call starts, overriding the role line's value for this delegation.\",\n \"Start from the role's level, raise it for hard work, lower it for routine work.\",\n \"The value must be one the target model advertises: this package assumes no ladder and rejects an unknown token with that model's real effort list.\",\n \"It is validated for every panel entry before any child starts, so one incompatible entry fails the whole call instead of half-starting it.\",\n \"Omit it to use the role line's effort.\",\n ].join(\" \"),\n },\n };\n\n if (config.allowedAgentPresets.length > 0) {\n properties[\"agentPreset\"] = {\n type: \"string\",\n enum: [...config.allowedAgentPresets],\n description: \"An independent child preset from this row's allowlist.\",\n };\n }\n\n return {\n type: \"object\",\n additionalProperties: false,\n properties,\n required: [\"description\", \"prompt\"],\n };\n}\n\nexport const OUTPUT_SCHEMA: JsonSchemaNode = {\n type: \"object\",\n additionalProperties: false,\n properties: {\n kind: {\n type: \"string\",\n enum: [\"activation\", \"activations\"],\n description: \"How many children this call started.\",\n },\n children: {\n type: \"array\",\n description: \"One record per started child, in start order.\",\n items: {\n type: \"object\",\n additionalProperties: false,\n properties: {\n childId: { type: \"string\", description: \"The child session id.\" },\n label: { type: \"string\", description: \"The label this call gave the child.\" },\n agent: { type: \"string\", description: \"The child brief type.\" },\n role: { type: \"string\", description: \"The role key, or `(none)`.\" },\n route: {\n type: \"string\",\n description: \"`inherit-parent` or `<provider>/<model> [effort]`.\",\n },\n effort: {\n type: \"string\",\n description:\n \"The reasoning effort this child runs at, when one applies. Equal to the call's `reasoningEffort` when that was passed.\",\n },\n maxDepth: {\n type: \"integer\",\n description: \"The delegation-depth cap the child received.\",\n },\n },\n required: [\"childId\", \"label\", \"agent\", \"role\", \"route\"],\n },\n },\n diagnostics: {\n type: \"array\",\n description:\n \"Configuration notes, including a panel whose entries share one route. Empty when nothing needs reporting.\",\n items: { type: \"string\" },\n },\n },\n required: [\"kind\", \"children\", \"diagnostics\"],\n};\n\n/** Render one delegation result for the model. */\nexport function renderDelegationResult(result: DelegationResult): string {\n const lines = [\n result.kind === \"activation\"\n ? `started 1 child: ${result.children[0]?.childId ?? \"(none)\"}`\n : `started ${result.children.length} children:`,\n ...result.children.map(\n (child) =>\n `- ${child.childId} (${child.label}) agent=${child.agent} role=${child.role} route=${child.route}${child.effort === undefined ? \"\" : ` effort=${child.effort}`}${child.maxDepth === undefined ? \"\" : ` maxDepth=${child.maxDepth}`}`,\n ),\n \"Results arrive as completion notices; do not poll for them. Each child can change its own\",\n \"effort from its next step with `set_reasoning_effort`; you do not need to predict it up front.\",\n ];\n if (result.diagnostics.length > 0) {\n lines.push(\n \"\",\n \"Diagnostics:\",\n ...result.diagnostics.map((diagnostic) => `- ${diagnostic}`),\n );\n }\n return lines.join(\"\\n\");\n}\n\n/** Build the model-facing tool for one row. */\nexport function createPstackSubagentTool(\n runtime: SubagentRuntime,\n config: PstackSubagentConfig = DEFAULT_CONFIG,\n): ToolDefinition {\n return {\n name: TOOL_NAME,\n description: TOOL_DESCRIPTION,\n parameters: buildParameters(config),\n output: {\n schema: OUTPUT_SCHEMA,\n render: (_args, value) => [\n { type: \"text\", text: renderDelegationResult(value as DelegationResult) },\n ],\n },\n isConcurrencySafe: () => true,\n async execute(rawArgs, exec: ToolRunContext) {\n const parent = exec.agent;\n if (parent === undefined) {\n throw new DelegationError(\n \"pstack_subagent needs a calling Agent, and exec.agent was undefined. This tool runs inside a conversation; it cannot start a child from a context that has no parent Agent.\",\n );\n }\n const args = parseDelegationArgs(rawArgs, config);\n const result = await delegate(parent, args, runtime, config, exec.signal);\n return result;\n },\n };\n}\n\n/**\n * The slices of the Cordis context this row uses.\n *\n * `agents` is optional in both directions: it is absent from `inject` and read per\n * call below, so a profile that mounts no agent registry still registers this tool.\n * See the `inject` comment for why a hard dependency is the wrong shape here.\n */\nexport interface PstackSubagentHost {\n readonly tools: ToolsHost;\n readonly subagents: SubagentsHost;\n readonly llm: LlmHost;\n}\n\n/** Build the runtime a real Host call reads. */\nexport function hostRuntime(\n ctx: PstackSubagentHost,\n getAgentRegistry: () => AgentsHost | undefined = () => undefined,\n): SubagentRuntime {\n return {\n subagents: ctx.subagents,\n llm: ctx.llm,\n // Resolved per delegation, not snapshotted: `agents` may mount after this row.\n get agents() {\n return getAgentRegistry();\n },\n dshHome: resolveDshHome(),\n assetsRoot: ASSETS_ROOT,\n };\n}\n\n/**\n * Register `pstack_subagent` for this row.\n *\n * @param ctx - context providing the tool registry, the subagent registry, the LLM\n * adapters, and optionally `ctx.get` for the agent registry.\n * @param config - validated row config.\n */\nexport function apply(\n ctx: PstackSubagentHost & { get?: (name: string) => AgentsHost | undefined },\n config: PstackSubagentConfig = DEFAULT_CONFIG,\n): void {\n const runtime = hostRuntime(ctx, () => ctx.get?.(\"agents\"));\n const tool = createPstackSubagentTool(runtime, config);\n ctx.tools.register(tool);\n}\n\nfunction describeError(error: unknown): string {\n if (error instanceof Error) {\n const code = (error as { code?: unknown }).code;\n const suffix = typeof code === \"string\" ? ` (${code})` : \"\";\n return `${error.message}${suffix}`;\n }\n return String(error);\n}\n"],"mappings":";;;;;;;AAiCA,MAAa,yBAAyB;;AAMtC,MAAa,yBAA4C,CAAC,kBAAkB,MAAM;AAElF,MAAa,gBAAqC;CAChD;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,oCAAoC,sCAAsC;EACtF,SACE;CACJ;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,kCAAkC;EAC9C,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,qCAAqC;EACjD,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,oCAAoC;EAChD,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW;GAAC;GAAwB;GAAU;EAAmB;EACjE,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,sBAAsB;EAClC,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,gBAAgB,mCAAmC;EAC/D,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,gBAAgB,oCAAoC;EAChE,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,gBAAgB,uCAAu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AM;EAClC,QAAQ;GACN,QAAQ;GACR,SAAS,OAAO,UAAU,CACxB;IAAE,MAAM;IAAQ,MAAM,uBAAuB,KAAyB;GAAE,CAC1E;EACF;EACA,yBAAyB;EACzB,MAAM,QAAQ,SAAS,MAAsB;GAC3C,MAAM,SAAS,KAAK;GACpB,IAAI,WAAW,KAAA,GACb,MAAM,IAAI,gBACR,6KACF;GAIF,OAAO,MADc,SAAS,QADjB,oBAAoB,SAAS,MACD,GAAG,SAAS,QAAQ,KAAK,MAAM;EAE1E;CACF;AACF;;AAgBA,SAAgB,YACd,KACA,yBAAuD,KAAA,GACtC;CACjB,OAAO;EACL,WAAW,IAAI;EACf,KAAK,IAAI;EAET,IAAI,SAAS;GACX,OAAO,iBAAiB;EAC1B;EACA,SAAS,eAAe;EACxB,YAAY;CACd;AACF;;;;;;;;AASA,SAAgB,MACd,KACA,SAA+B,gBACzB;CAEN,MAAM,OAAO,yBADG,YAAY,WAAW,IAAI,MAAM,QAAQ,CACb,GAAG,MAAM;CACrD,IAAI,MAAM,SAAS,IAAI;AACzB;AAEA,SAAS,cAAc,OAAwB;CAC7C,IAAI,iBAAiB,OAAO;EAC1B,MAAM,OAAQ,MAA6B;EAC3C,MAAM,SAAS,OAAO,SAAS,WAAW,KAAK,KAAK,KAAK;EACzD,OAAO,GAAG,MAAM,UAAU;CAC5B;CACA,OAAO,OAAO,KAAK;AACrB"}
File without changes
File without changes
File without changes
File without changes