dsh-pstack 0.1.0 → 0.2.0-beta.1

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 (312) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +92 -117
  3. package/assets/agents/comment-sicko.md +1 -1
  4. package/assets/agents/poteto-agent.md +2 -2
  5. package/assets/docs/guide/01-setup.md +9 -9
  6. package/assets/docs/guide/02-poteto-mode.md +4 -4
  7. package/assets/docs/guide/05-build-and-clean.md +3 -3
  8. package/assets/docs/guide/06-verify-and-ship.md +2 -2
  9. package/assets/docs/guide/07-overnight.md +10 -12
  10. package/assets/docs/guide/09-make-it-yours.md +2 -6
  11. package/assets/docs/guide/10-recipes-and-pitfalls.md +3 -3
  12. package/assets/docs/guide/README.md +1 -1
  13. package/assets/docs/guide/images/design.jpg +0 -0
  14. package/assets/docs/guide/images/overnight.jpg +0 -0
  15. package/assets/docs/guide/images/recipes.jpg +0 -0
  16. package/assets/docs/guide/images/router.jpg +0 -0
  17. package/assets/docs/guide/images/understanding.jpg +0 -0
  18. package/assets/docs/guide/images/verification.jpg +0 -0
  19. package/assets/docs/harness/dsh.md +60 -65
  20. package/assets/docs/pstack-models.example.md +40 -9
  21. package/assets/skills/architect/SKILL.md +12 -12
  22. package/assets/skills/arena/SKILL.md +11 -11
  23. package/assets/skills/automate-me/SKILL.md +15 -14
  24. package/assets/skills/benchmark-checklist/SKILL.md +0 -2
  25. package/assets/skills/blast-radius/SKILL.md +5 -5
  26. package/assets/skills/bro/SKILL.md +0 -2
  27. package/assets/skills/correct/SKILL.md +0 -2
  28. package/assets/skills/create-formal-verification-skill/SKILL.md +2 -2
  29. package/assets/skills/create-verification-skill/SKILL.md +2 -2
  30. package/assets/skills/figure-it-out/SKILL.md +13 -13
  31. package/assets/skills/how/SKILL.md +6 -6
  32. package/assets/skills/how/references/explainer-prompt.md +1 -1
  33. package/assets/skills/in-your-own-words/SKILL.md +0 -2
  34. package/assets/skills/interrogate/SKILL.md +9 -7
  35. package/assets/skills/interrogate/references/rubric.md +1 -1
  36. package/assets/skills/ketchup/SKILL.md +4 -4
  37. package/assets/skills/maintain-formal-verification-skill/SKILL.md +2 -2
  38. package/assets/skills/maintain-verification-skill/SKILL.md +3 -3
  39. package/assets/skills/no-comments/SKILL.md +7 -7
  40. package/assets/skills/poteto-help/SKILL.md +32 -31
  41. package/assets/skills/poteto-help/references/prompting.md +1 -1
  42. package/assets/skills/poteto-help/references/recipes.md +1 -1
  43. package/assets/skills/poteto-mode/SKILL.md +17 -19
  44. package/assets/skills/poteto-mode/playbooks/authoring-a-skill.md +3 -3
  45. package/assets/skills/poteto-mode/playbooks/autonomous-run.md +6 -4
  46. package/assets/skills/poteto-mode/playbooks/autopilot-full.md +6 -6
  47. package/assets/skills/poteto-mode/playbooks/autopilot-stack.md +2 -2
  48. package/assets/skills/poteto-mode/playbooks/babysit.md +3 -3
  49. package/assets/skills/poteto-mode/playbooks/bug-fix.md +7 -7
  50. package/assets/skills/poteto-mode/playbooks/eval.md +3 -3
  51. package/assets/skills/poteto-mode/playbooks/feature.md +8 -8
  52. package/assets/skills/poteto-mode/playbooks/hillclimb.md +3 -3
  53. package/assets/skills/poteto-mode/playbooks/investigation.md +2 -2
  54. package/assets/skills/poteto-mode/playbooks/multi-phase-plan.md +21 -21
  55. package/assets/skills/poteto-mode/playbooks/opening-a-pr.md +6 -6
  56. package/assets/skills/poteto-mode/playbooks/orchestrate.md +13 -13
  57. package/assets/skills/poteto-mode/playbooks/pause-safely.md +2 -2
  58. package/assets/skills/poteto-mode/playbooks/perf-issue.md +6 -6
  59. package/assets/skills/poteto-mode/playbooks/prototype.md +4 -4
  60. package/assets/skills/poteto-mode/playbooks/refactoring.md +9 -9
  61. package/assets/skills/poteto-mode/playbooks/runtime-forensics.md +3 -3
  62. package/assets/skills/poteto-mode/playbooks/session-pickup.md +2 -2
  63. package/assets/skills/poteto-mode/playbooks/shipping.md +2 -2
  64. package/assets/skills/poteto-mode/playbooks/trace-forensics.md +2 -2
  65. package/assets/skills/poteto-mode/playbooks/visual-parity.md +5 -5
  66. package/assets/skills/poteto-mode/playbooks/worktree-cleanup.md +14 -6
  67. package/assets/skills/poteto-mode/scripts/check-plan.mjs +85 -70
  68. package/assets/skills/poteto-mode/scripts/check-plan.test.mjs +343 -0
  69. package/assets/skills/poteto-mode/scripts/orch/orch.mjs +4282 -0
  70. package/assets/skills/poteto-mode/scripts/orch/orch.test.mjs +2042 -0
  71. package/assets/skills/poteto-mode/scripts/watch-pr/cli.test.mjs +5101 -0
  72. package/assets/skills/poteto-mode/scripts/watch-pr/github.test.mjs +1177 -0
  73. package/assets/skills/poteto-mode/scripts/watch-pr/policy.test.mjs +1441 -0
  74. package/assets/skills/poteto-mode/scripts/watch-pr/watch-pr.mjs +4601 -0
  75. package/assets/skills/poteto-mode/scripts/worktree-audit.mjs +675 -0
  76. package/assets/skills/principle-attack-the-premise/SKILL.md +0 -2
  77. package/assets/skills/principle-boundary-discipline/SKILL.md +0 -2
  78. package/assets/skills/principle-build-the-lever/SKILL.md +0 -3
  79. package/assets/skills/principle-encode-lessons-in-structure/SKILL.md +0 -2
  80. package/assets/skills/principle-exhaust-the-design-space/SKILL.md +0 -2
  81. package/assets/skills/principle-experience-first/SKILL.md +0 -2
  82. package/assets/skills/principle-explain-the-number/SKILL.md +0 -2
  83. package/assets/skills/principle-fix-root-causes/SKILL.md +0 -2
  84. package/assets/skills/principle-foundational-thinking/SKILL.md +0 -2
  85. package/assets/skills/principle-guard-the-context-window/SKILL.md +0 -2
  86. package/assets/skills/principle-laziness-protocol/SKILL.md +0 -2
  87. package/assets/skills/principle-make-operations-idempotent/SKILL.md +0 -2
  88. package/assets/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +0 -2
  89. package/assets/skills/principle-minimize-reader-load/SKILL.md +0 -2
  90. package/assets/skills/principle-model-the-domain/SKILL.md +0 -2
  91. package/assets/skills/principle-never-block-on-the-human/SKILL.md +0 -2
  92. package/assets/skills/principle-outcome-oriented-execution/SKILL.md +0 -2
  93. package/assets/skills/principle-prove-it-works/SKILL.md +2 -2
  94. package/assets/skills/principle-redesign-from-first-principles/SKILL.md +0 -2
  95. package/assets/skills/principle-separate-before-serializing-shared-state/SKILL.md +0 -2
  96. package/assets/skills/principle-sequence-verifiable-units/SKILL.md +0 -2
  97. package/assets/skills/principle-subtract-before-you-add/SKILL.md +0 -2
  98. package/assets/skills/principle-test-behavior-not-implementation/SKILL.md +0 -2
  99. package/assets/skills/principle-type-system-discipline/SKILL.md +0 -2
  100. package/assets/skills/recall/SKILL.md +9 -9
  101. package/assets/skills/reflect/SKILL.md +20 -21
  102. package/assets/skills/reflect/references/divergent-reviewer.md +4 -4
  103. package/assets/skills/reflect/references/judgment-reviewer.md +2 -2
  104. package/assets/skills/reflect/references/synthesizer.md +6 -6
  105. package/assets/skills/reflect/references/tooling-reviewer.md +2 -2
  106. package/assets/skills/setup-pstack/SKILL.md +28 -37
  107. package/assets/skills/sharpen/SKILL.md +0 -2
  108. package/assets/skills/show-me-your-work/SKILL.md +9 -9
  109. package/assets/skills/show-me-your-work/scripts/log.mjs +108 -0
  110. package/assets/skills/swarm/SKILL.md +8 -6
  111. package/assets/skills/tdd/SKILL.md +0 -2
  112. package/assets/skills/teach/SKILL.md +2 -2
  113. package/assets/skills/technical-writing/SKILL.md +2 -2
  114. package/assets/skills/typescript-best-practices/SKILL.md +6 -4
  115. package/assets/skills/unslop/SKILL.md +0 -2
  116. package/assets/skills/why/SKILL.md +9 -9
  117. package/cordis.patch.yml +33 -14
  118. package/dist/frontmatter-BQX3ekwP.mjs +229 -0
  119. package/dist/frontmatter-BQX3ekwP.mjs.map +1 -0
  120. package/dist/history.d.mts +429 -0
  121. package/dist/history.mjs +1129 -0
  122. package/dist/history.mjs.map +1 -0
  123. package/dist/host-contract-o47JH_r8.d.mts +527 -0
  124. package/dist/index.d.mts +273 -11
  125. package/dist/index.mjs +248 -148
  126. package/dist/index.mjs.map +1 -1
  127. package/dist/paths-D_JlVmBk.mjs +42 -0
  128. package/dist/paths-D_JlVmBk.mjs.map +1 -0
  129. package/dist/script.d.mts +193 -0
  130. package/dist/script.mjs +782 -0
  131. package/dist/script.mjs.map +1 -0
  132. package/dist/subagent.d.mts +306 -100
  133. package/dist/subagent.mjs +1309 -343
  134. package/dist/subagent.mjs.map +1 -1
  135. package/locale/en.json +6 -0
  136. package/locale/zh.json +6 -0
  137. package/package.json +55 -41
  138. package/static/icon.png +0 -0
  139. package/assets/skills/poteto-mode/scripts/bootstrap.ts +0 -62
  140. package/assets/skills/poteto-mode/scripts/bun.lock +0 -67
  141. package/assets/skills/poteto-mode/scripts/check-plan.test.ts +0 -96
  142. package/assets/skills/poteto-mode/scripts/orch/orch.test.ts +0 -761
  143. package/assets/skills/poteto-mode/scripts/orch/orch.ts +0 -590
  144. package/assets/skills/poteto-mode/scripts/orch/store.ts +0 -1677
  145. package/assets/skills/poteto-mode/scripts/package.json +0 -16
  146. package/assets/skills/poteto-mode/scripts/watch-pr/cli.test.ts +0 -224
  147. package/assets/skills/poteto-mode/scripts/watch-pr/cli.ts +0 -223
  148. package/assets/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +0 -129
  149. package/assets/skills/poteto-mode/scripts/watch-pr/github.test.ts +0 -436
  150. package/assets/skills/poteto-mode/scripts/watch-pr/github.ts +0 -718
  151. package/assets/skills/poteto-mode/scripts/watch-pr/policy.test.ts +0 -420
  152. package/assets/skills/poteto-mode/scripts/watch-pr/policy.ts +0 -836
  153. package/assets/skills/poteto-mode/scripts/watch-pr/render.ts +0 -169
  154. package/assets/skills/poteto-mode/scripts/watch-pr/tsconfig.json +0 -13
  155. package/assets/skills/poteto-mode/scripts/watch-pr/types.compile.ts +0 -93
  156. package/assets/skills/poteto-mode/scripts/watch-pr/types.ts +0 -413
  157. package/assets/skills/poteto-mode/scripts/watch-pr/watch-pr +0 -6
  158. package/assets/skills/poteto-mode/scripts/worktree-audit.sh +0 -127
  159. package/assets/skills/show-me-your-work/scripts/log.sh +0 -42
  160. package/dist/LICENSE +0 -22
  161. package/dist/README.md +0 -159
  162. package/dist/assets/agents/comment-sicko.md +0 -32
  163. package/dist/assets/agents/poteto-agent.md +0 -8
  164. package/dist/assets/docs/guide/01-setup.md +0 -64
  165. package/dist/assets/docs/guide/02-poteto-mode.md +0 -139
  166. package/dist/assets/docs/guide/03-understand.md +0 -79
  167. package/dist/assets/docs/guide/04-design.md +0 -133
  168. package/dist/assets/docs/guide/05-build-and-clean.md +0 -83
  169. package/dist/assets/docs/guide/06-verify-and-ship.md +0 -152
  170. package/dist/assets/docs/guide/07-overnight.md +0 -122
  171. package/dist/assets/docs/guide/08-principles.md +0 -72
  172. package/dist/assets/docs/guide/09-make-it-yours.md +0 -100
  173. package/dist/assets/docs/guide/10-recipes-and-pitfalls.md +0 -180
  174. package/dist/assets/docs/guide/README.md +0 -38
  175. package/dist/assets/docs/harness/dsh.md +0 -65
  176. package/dist/assets/docs/pstack-models.example.md +0 -23
  177. package/dist/assets/skills/architect/SKILL.md +0 -81
  178. package/dist/assets/skills/architect/references/design-red-flags.md +0 -57
  179. package/dist/assets/skills/architect/references/rationale-template.md +0 -35
  180. package/dist/assets/skills/architect/references/runner-prompt.md +0 -20
  181. package/dist/assets/skills/arena/SKILL.md +0 -50
  182. package/dist/assets/skills/automate-me/SKILL.md +0 -105
  183. package/dist/assets/skills/benchmark-checklist/SKILL.md +0 -41
  184. package/dist/assets/skills/blast-radius/SKILL.md +0 -52
  185. package/dist/assets/skills/bro/SKILL.md +0 -9
  186. package/dist/assets/skills/correct/SKILL.md +0 -34
  187. package/dist/assets/skills/create-formal-verification-skill/SKILL.md +0 -43
  188. package/dist/assets/skills/create-verification-skill/SKILL.md +0 -46
  189. package/dist/assets/skills/create-verification-skill/references/feature-map-example/README.md +0 -47
  190. package/dist/assets/skills/create-verification-skill/references/feature-map-example/create-note.md +0 -39
  191. package/dist/assets/skills/create-verification-skill/references/feature-map-example/search.md +0 -45
  192. package/dist/assets/skills/figure-it-out/SKILL.md +0 -54
  193. package/dist/assets/skills/how/SKILL.md +0 -38
  194. package/dist/assets/skills/how/references/explainer-prompt.md +0 -55
  195. package/dist/assets/skills/how/references/explorer-prompt.md +0 -35
  196. package/dist/assets/skills/in-your-own-words/SKILL.md +0 -9
  197. package/dist/assets/skills/interrogate/SKILL.md +0 -69
  198. package/dist/assets/skills/interrogate/references/code-quality-review.md +0 -47
  199. package/dist/assets/skills/interrogate/references/lead-judgment.md +0 -39
  200. package/dist/assets/skills/interrogate/references/reviewer-prompt.md +0 -62
  201. package/dist/assets/skills/interrogate/references/rubric.md +0 -77
  202. package/dist/assets/skills/ketchup/SKILL.md +0 -45
  203. package/dist/assets/skills/maintain-formal-verification-skill/SKILL.md +0 -60
  204. package/dist/assets/skills/maintain-verification-skill/SKILL.md +0 -41
  205. package/dist/assets/skills/no-comments/SKILL.md +0 -26
  206. package/dist/assets/skills/poteto-help/SKILL.md +0 -161
  207. package/dist/assets/skills/poteto-help/references/prompting.md +0 -51
  208. package/dist/assets/skills/poteto-help/references/recipes.md +0 -51
  209. package/dist/assets/skills/poteto-mode/SKILL.md +0 -153
  210. package/dist/assets/skills/poteto-mode/playbooks/authoring-a-skill.md +0 -12
  211. package/dist/assets/skills/poteto-mode/playbooks/autonomous-run.md +0 -13
  212. package/dist/assets/skills/poteto-mode/playbooks/autopilot-full.md +0 -25
  213. package/dist/assets/skills/poteto-mode/playbooks/autopilot-stack.md +0 -12
  214. package/dist/assets/skills/poteto-mode/playbooks/babysit.md +0 -23
  215. package/dist/assets/skills/poteto-mode/playbooks/bug-fix.md +0 -15
  216. package/dist/assets/skills/poteto-mode/playbooks/eval.md +0 -25
  217. package/dist/assets/skills/poteto-mode/playbooks/feature.md +0 -21
  218. package/dist/assets/skills/poteto-mode/playbooks/hillclimb.md +0 -21
  219. package/dist/assets/skills/poteto-mode/playbooks/investigation.md +0 -14
  220. package/dist/assets/skills/poteto-mode/playbooks/multi-phase-plan.md +0 -155
  221. package/dist/assets/skills/poteto-mode/playbooks/opening-a-pr.md +0 -34
  222. package/dist/assets/skills/poteto-mode/playbooks/orchestrate.md +0 -112
  223. package/dist/assets/skills/poteto-mode/playbooks/pause-safely.md +0 -10
  224. package/dist/assets/skills/poteto-mode/playbooks/perf-issue.md +0 -25
  225. package/dist/assets/skills/poteto-mode/playbooks/prototype.md +0 -14
  226. package/dist/assets/skills/poteto-mode/playbooks/refactoring.md +0 -16
  227. package/dist/assets/skills/poteto-mode/playbooks/runtime-forensics.md +0 -11
  228. package/dist/assets/skills/poteto-mode/playbooks/session-pickup.md +0 -11
  229. package/dist/assets/skills/poteto-mode/playbooks/shipping.md +0 -12
  230. package/dist/assets/skills/poteto-mode/playbooks/trace-forensics.md +0 -14
  231. package/dist/assets/skills/poteto-mode/playbooks/visual-parity.md +0 -11
  232. package/dist/assets/skills/poteto-mode/playbooks/worktree-cleanup.md +0 -12
  233. package/dist/assets/skills/poteto-mode/references/bugbot-triage.md +0 -142
  234. package/dist/assets/skills/poteto-mode/scripts/bootstrap.ts +0 -62
  235. package/dist/assets/skills/poteto-mode/scripts/bun.lock +0 -67
  236. package/dist/assets/skills/poteto-mode/scripts/check-plan.mjs +0 -205
  237. package/dist/assets/skills/poteto-mode/scripts/check-plan.test.ts +0 -96
  238. package/dist/assets/skills/poteto-mode/scripts/orch/orch.test.ts +0 -761
  239. package/dist/assets/skills/poteto-mode/scripts/orch/orch.ts +0 -590
  240. package/dist/assets/skills/poteto-mode/scripts/orch/store.ts +0 -1677
  241. package/dist/assets/skills/poteto-mode/scripts/package.json +0 -16
  242. package/dist/assets/skills/poteto-mode/scripts/watch-pr/cli.test.ts +0 -224
  243. package/dist/assets/skills/poteto-mode/scripts/watch-pr/cli.ts +0 -223
  244. package/dist/assets/skills/poteto-mode/scripts/watch-pr/fakes.test-helper.ts +0 -129
  245. package/dist/assets/skills/poteto-mode/scripts/watch-pr/github.test.ts +0 -436
  246. package/dist/assets/skills/poteto-mode/scripts/watch-pr/github.ts +0 -718
  247. package/dist/assets/skills/poteto-mode/scripts/watch-pr/policy.test.ts +0 -420
  248. package/dist/assets/skills/poteto-mode/scripts/watch-pr/policy.ts +0 -836
  249. package/dist/assets/skills/poteto-mode/scripts/watch-pr/render.ts +0 -169
  250. package/dist/assets/skills/poteto-mode/scripts/watch-pr/tsconfig.json +0 -13
  251. package/dist/assets/skills/poteto-mode/scripts/watch-pr/types.compile.ts +0 -93
  252. package/dist/assets/skills/poteto-mode/scripts/watch-pr/types.ts +0 -413
  253. package/dist/assets/skills/poteto-mode/scripts/watch-pr/watch-pr +0 -6
  254. package/dist/assets/skills/poteto-mode/scripts/worktree-audit.sh +0 -127
  255. package/dist/assets/skills/principle-attack-the-premise/SKILL.md +0 -23
  256. package/dist/assets/skills/principle-boundary-discipline/SKILL.md +0 -36
  257. package/dist/assets/skills/principle-build-the-lever/SKILL.md +0 -26
  258. package/dist/assets/skills/principle-encode-lessons-in-structure/SKILL.md +0 -13
  259. package/dist/assets/skills/principle-exhaust-the-design-space/SKILL.md +0 -11
  260. package/dist/assets/skills/principle-experience-first/SKILL.md +0 -21
  261. package/dist/assets/skills/principle-explain-the-number/SKILL.md +0 -19
  262. package/dist/assets/skills/principle-fix-root-causes/SKILL.md +0 -23
  263. package/dist/assets/skills/principle-foundational-thinking/SKILL.md +0 -23
  264. package/dist/assets/skills/principle-guard-the-context-window/SKILL.md +0 -14
  265. package/dist/assets/skills/principle-laziness-protocol/SKILL.md +0 -12
  266. package/dist/assets/skills/principle-make-operations-idempotent/SKILL.md +0 -24
  267. package/dist/assets/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +0 -16
  268. package/dist/assets/skills/principle-minimize-reader-load/SKILL.md +0 -20
  269. package/dist/assets/skills/principle-model-the-domain/SKILL.md +0 -26
  270. package/dist/assets/skills/principle-never-block-on-the-human/SKILL.md +0 -17
  271. package/dist/assets/skills/principle-outcome-oriented-execution/SKILL.md +0 -23
  272. package/dist/assets/skills/principle-prove-it-works/SKILL.md +0 -24
  273. package/dist/assets/skills/principle-redesign-from-first-principles/SKILL.md +0 -18
  274. package/dist/assets/skills/principle-separate-before-serializing-shared-state/SKILL.md +0 -18
  275. package/dist/assets/skills/principle-sequence-verifiable-units/SKILL.md +0 -19
  276. package/dist/assets/skills/principle-subtract-before-you-add/SKILL.md +0 -20
  277. package/dist/assets/skills/principle-test-behavior-not-implementation/SKILL.md +0 -22
  278. package/dist/assets/skills/principle-type-system-discipline/SKILL.md +0 -15
  279. package/dist/assets/skills/recall/SKILL.md +0 -37
  280. package/dist/assets/skills/reflect/SKILL.md +0 -70
  281. package/dist/assets/skills/reflect/references/divergent-reviewer.md +0 -38
  282. package/dist/assets/skills/reflect/references/judgment-reviewer.md +0 -37
  283. package/dist/assets/skills/reflect/references/synthesizer.md +0 -56
  284. package/dist/assets/skills/reflect/references/tooling-reviewer.md +0 -48
  285. package/dist/assets/skills/setup-pstack/SKILL.md +0 -76
  286. package/dist/assets/skills/sharpen/SKILL.md +0 -18
  287. package/dist/assets/skills/show-me-your-work/SKILL.md +0 -84
  288. package/dist/assets/skills/show-me-your-work/references/decision-log-template.tsv +0 -1
  289. package/dist/assets/skills/show-me-your-work/scripts/log.sh +0 -42
  290. package/dist/assets/skills/swarm/SKILL.md +0 -41
  291. package/dist/assets/skills/tdd/SKILL.md +0 -44
  292. package/dist/assets/skills/teach/SKILL.md +0 -23
  293. package/dist/assets/skills/technical-writing/SKILL.md +0 -108
  294. package/dist/assets/skills/typescript-best-practices/SKILL.md +0 -32
  295. package/dist/assets/skills/typescript-best-practices/references/patterns.md +0 -328
  296. package/dist/assets/skills/unslop/SKILL.md +0 -64
  297. package/dist/assets/skills/why/SKILL.md +0 -100
  298. package/dist/assets/skills/why/references/epistemics.md +0 -71
  299. package/dist/assets/skills/why/references/investigator-prompt.md +0 -84
  300. package/dist/assets/skills/why/references/source-playbook.md +0 -17
  301. package/dist/assets/skills/why/references/sources/code-archaeology.md +0 -51
  302. package/dist/assets/skills/why/references/sources/databricks.md +0 -70
  303. package/dist/assets/skills/why/references/sources/datadog.md +0 -97
  304. package/dist/assets/skills/why/references/sources/incident-postmortem.md +0 -5
  305. package/dist/assets/skills/why/references/sources/linear.md +0 -48
  306. package/dist/assets/skills/why/references/sources/notion.md +0 -55
  307. package/dist/assets/skills/why/references/sources/sentry.md +0 -66
  308. package/dist/assets/skills/why/references/sources/slack.md +0 -17
  309. package/dist/assets/skills/why/references/synthesizer-prompt.md +0 -129
  310. package/dist/cordis.patch.yml +0 -20
  311. package/dist/paths-Bbai4CaT.mjs +0 -16
  312. package/dist/paths-Bbai4CaT.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"subagent.mjs","names":[],"sources":["../src/roles.ts","../src/models.ts","../src/subagent.ts"],"sourcesContent":["/**\n * pstack role resolution.\n *\n * `~/.dsh/pstack-models.md` holds one role per line. The tool resolves a role\n * into a child LLM route at call time, so edits apply to the next delegation\n * without restarting the harness.\n *\n * Parsing never throws. A typo in one line must not break delegation, but it\n * must also not disappear: `parseModelConfigWithIssues` collects `issues` and\n * the parser keeps them so a caller can report the line that is wrong.\n */\n\nexport interface Route {\n readonly provider: string;\n readonly model: string;\n readonly reasoningEffort?: string;\n}\n\nexport type RoleValue = \"inherit-parent\" | Route;\nexport type RoleTable = ReadonlyMap<string, readonly RoleValue[]>;\n\n/** A problem in the role file, tied to the line that caused it. */\nexport interface RoleIssue {\n /** 1-based line number in `pstack-models.md`. */\n readonly line: number;\n readonly message: string;\n}\n\nexport interface ParsedModelConfig {\n readonly table: RoleTable;\n readonly issues: readonly RoleIssue[];\n}\n\nconst INHERIT = new Set([\"inherit-parent\", \"auto\", \"parent\"]);\n\n/**\n * Reasoning efforts DSH understands, widest first. A token outside this set is\n * reported rather than dropped: a route that silently loses `xhigh` looks\n * configured and is not.\n */\nexport const REASONING_EFFORTS = [\"max\", \"xhigh\", \"high\", \"medium\", \"low\", \"off\"] as const;\nconst EFFORTS = new Set<string>(REASONING_EFFORTS);\n\n/**\n * Register the role names on one line.\n *\n * The whole left side is always stored as one key, so\n * `reflect judgment, divergent, synthesizer` stays addressable as written.\n * When the comma list is a genuine group (`feature, refactoring`), each part is\n * stored too, so a caller can name just one of them. Both spellings therefore\n * work, and neither can shadow the other: the full key is a different string.\n */\nfunction splitRoles(left: string): string[] {\n const whole = left.trim().toLowerCase().replace(/\\s+/g, \" \");\n if (!whole) return [];\n const parts = left\n .split(\",\")\n .map((part) => part.trim().toLowerCase())\n .filter(Boolean);\n return parts.length > 1 ? [whole, ...parts] : [whole];\n}\n\nexport function parseModelConfigWithIssues(source: string): ParsedModelConfig {\n const table = new Map<string, RoleValue[]>();\n const issues: RoleIssue[] = [];\n const lines = source.replace(/\\r\\n/g, \"\\n\").split(\"\\n\");\n\n for (const [index, rawLine] of lines.entries()) {\n const line = rawLine.trim();\n if (!line || line.startsWith(\"#\") || line.startsWith(\"//\")) continue;\n const lineNumber = index + 1;\n const separator = line.indexOf(\":\");\n if (separator === -1) {\n issues.push({\n line: lineNumber,\n message: `expected \"role: value\", got ${JSON.stringify(line)}`,\n });\n continue;\n }\n const roles = splitRoles(line.slice(0, separator));\n if (roles.length === 0) {\n issues.push({ line: lineNumber, message: \"no role name before the colon\" });\n continue;\n }\n\n const values: RoleValue[] = [];\n for (const entry of line.slice(separator + 1).split(\",\")) {\n const parsed = parseValue(entry.trim(), lineNumber, issues);\n if (parsed !== undefined) values.push(parsed);\n }\n if (values.length === 0) {\n issues.push({ line: lineNumber, message: `no usable value for ${roles.join(\", \")}` });\n continue;\n }\n for (const role of roles) table.set(role, values);\n }\n\n return { table, issues };\n}\n\n/** Parse without the diagnostics. Kept for callers that only need the table. */\nexport function parseModelConfig(source: string): RoleTable {\n return parseModelConfigWithIssues(source).table;\n}\n\nexport function parseValue(\n value: string,\n line = 0,\n issues: RoleIssue[] = [],\n): RoleValue | undefined {\n if (!value) return undefined;\n if (INHERIT.has(value.toLowerCase())) return \"inherit-parent\";\n const tokens = value.split(/\\s+/).filter(Boolean);\n const [route, ...rest] = tokens;\n if (!route) return undefined;\n\n const slash = route.indexOf(\"/\");\n if (slash <= 0 || slash === route.length - 1) {\n // A bare model id with no provider cannot be routed safely; ask the harness\n // to inherit rather than guessing a provider.\n issues.push({\n line,\n message: `\"${route}\" is not <provider>/<model>, so this role inherits the parent route`,\n });\n return \"inherit-parent\";\n }\n\n let reasoningEffort: string | undefined;\n for (const token of rest) {\n if (EFFORTS.has(token.toLowerCase())) {\n reasoningEffort = token.toLowerCase();\n continue;\n }\n issues.push({\n line,\n message: `unknown effort \"${token}\"; expected one of ${REASONING_EFFORTS.join(\", \")}`,\n });\n }\n\n return {\n provider: route.slice(0, slash),\n model: route.slice(slash + 1),\n ...(reasoningEffort ? { reasoningEffort } : {}),\n };\n}\n\n/** How a role name was matched, so the caller can report a near miss. */\nexport interface RoleMatch {\n /** The key exactly as it appears in the file, after lowercasing. */\n readonly key: string;\n readonly values: readonly RoleValue[];\n /** True when the key came from a shared `a, b: value` line. */\n readonly fromList: boolean;\n}\n\n/**\n * Look a role up by name.\n *\n * The parser stores both the whole left side of a line and, when the comma list\n * is a genuine group, each part. So a direct map hit is the only match worth\n * making. Matching is exact on purpose: a near miss such as `how` against\n * `how explorer` must not resolve, because picking a route the user did not name\n * changes both cost and model without saying so. `findNearMisses` reports those\n * for a human instead.\n */\nexport function lookupRole(table: RoleTable, role: string | undefined): RoleMatch | undefined {\n if (!role) return undefined;\n const key = role.trim().toLowerCase().replace(/\\s+/g, \" \");\n if (!key) return undefined;\n\n const values = table.get(key);\n if (!values) return undefined;\n // `fromList` is informational: a key containing a comma came from a shared\n // line, which is how a panel role is spelled.\n return { key, values, fromList: key.includes(\",\") };\n}\n\n/**\n * Configured role names a caller could have meant. Used to explain a miss, not\n * to resolve one: `how` is a near miss for `how explorer`, and quietly running\n * on the explorer route would look configured while being wrong.\n */\nexport function findNearMisses(table: RoleTable, role: string): string[] {\n const key = role.trim().toLowerCase().replace(/\\s+/g, \" \");\n if (!key) return [];\n const hits: string[] = [];\n for (const candidate of table.keys()) {\n if (candidate === key) continue;\n if (candidate.includes(key) || key.includes(candidate)) {\n hits.push(candidate);\n continue;\n }\n // A shared line stores its parts separately too, so compare against those\n // as well: `how` should surface both `how explorer` and `how explainer`.\n for (const part of candidate.split(\",\").map((item) => item.trim())) {\n if (part === key) continue;\n if (part.includes(key) || key.includes(part)) {\n hits.push(candidate);\n break;\n }\n }\n }\n return [...new Set(hits)];\n}\n\n/**\n * Resolve one role to a route.\n *\n * `index` selects a panel entry and wraps, so a caller that spawns more\n * children than the list has entries still gets a deterministic route. A\n * missing role or an `inherit-parent` entry both return `undefined`, which\n * tells the caller to omit `agentOptions` and inherit.\n */\nexport function resolveRole(\n table: RoleTable,\n role: string | undefined,\n index = 0,\n): Route | undefined {\n const values = lookupRole(table, role)?.values;\n if (!values || values.length === 0) return undefined;\n const value = values[Math.abs(index) % values.length];\n return value && value !== \"inherit-parent\" ? value : undefined;\n}\n\n/** Every entry for a panel role. An empty list means the role is not configured. */\nexport function resolvePanel(table: RoleTable, role: string): readonly RoleValue[] {\n return lookupRole(table, role)?.values ?? [];\n}\n","/**\n * Read `~/.dsh/pstack-models.md`, the role file `/setup-pstack` writes.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { parseModelConfigWithIssues, type RoleIssue, type RoleTable } from \"./roles.ts\";\n\nexport function dshHome(): string {\n return process.env.DSH_HOME || join(homedir(), \".dsh\");\n}\n\nexport function modelConfigPath(): string {\n return join(dshHome(), \"pstack-models.md\");\n}\n\nexport interface LoadedRoleTable {\n readonly table: RoleTable;\n /** Parse problems, each tied to a line of the file. */\n readonly issues: readonly RoleIssue[];\n /** True when the file exists but could not be read. */\n readonly unreadable: boolean;\n}\n\n/**\n * Read the role file.\n *\n * A missing file is normal and means every role inherits the parent route. A\n * malformed line degrades only that line, and the issues travel with the table\n * so the tool can name them in its reply. A read failure keeps that distinction\n * explicit instead of collapsing into an empty table.\n */\nexport async function loadRoleTable(): Promise<LoadedRoleTable> {\n try {\n const source = await readFile(modelConfigPath(), \"utf8\");\n const { table, issues } = parseModelConfigWithIssues(source);\n return { table, issues, unreadable: false };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { table: new Map(), issues: [], unreadable: false };\n }\n return {\n table: new Map(),\n issues: [\n {\n line: 0,\n message: `could not read ${modelConfigPath()}: ${(error as Error).message}`,\n },\n ],\n unreadable: true,\n };\n }\n}\n","/**\n * `pstack_subagent`: pstack's delegation surface for DSH.\n *\n * Cursor's `Task` tool gives every spawn a `subagent_type`, a model slug, and\n * background execution. DSH splits those across `ctx.subagents` (background\n * activations), the agent preset system (composition), and the LLM adapter\n * routes (model choice). This tool joins them back into one call whose shape a\n * ported pstack skill can use unchanged.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Context } from \"@deepseek-ai/cordis\";\nimport type { Agent } from \"@deepseek-ai/dsh-agent\";\nimport type { ContentBlock } from \"@deepseek-ai/dsh-llm\";\nimport { ReasoningEffortId } from \"@deepseek-ai/dsh-llm\";\nimport type {} from \"@deepseek-ai/dsh-subagent\";\nimport { defineTool } from \"@deepseek-ai/dsh-tools\";\nimport { loadRoleTable, modelConfigPath } from \"./models.ts\";\nimport { AGENTS_ROOT, SKILLS_ROOT } from \"./paths.ts\";\nimport { findNearMisses, lookupRole, resolveRole, type Route } from \"./roles.ts\";\n\nexport const name = \"pstack-subagent\";\nexport const inject = [\"tools\", \"subagents\"];\n\nconst AGENT_KINDS = [\"poteto-agent\", \"comment-sicko\", \"general\"] as const;\nexport type AgentKind = (typeof AGENT_KINDS)[number];\n\nexport interface Config {\n /** Tool name exposed to the model. */\n readonly toolName?: string;\n /** Subagent provider registered on `ctx.subagents`. */\n readonly provider?: string;\n /** Default agent kind when the model omits `agent`. */\n readonly defaultAgent?: AgentKind;\n}\n\nconst POTETO_AGENT_PATH = `${AGENTS_ROOT}poteto-agent.md`;\nconst COMMENT_SICKO_PATH = `${AGENTS_ROOT}comment-sicko.md`;\nconst POTETO_MODE_PATH = `${SKILLS_ROOT}poteto-mode/SKILL.md`;\n\nexport function stripFrontmatter(source: string): string {\n if (!source.startsWith(\"---\")) return source;\n const end = source.indexOf(\"\\n---\", 3);\n return end === -1 ? source : source.slice(end + 4).replace(/^\\n+/, \"\");\n}\n\nexport async function readAgentInstructions(kind: AgentKind): Promise<string> {\n if (kind === \"general\") return \"\";\n const path = kind === \"poteto-agent\" ? POTETO_AGENT_PATH : COMMENT_SICKO_PATH;\n try {\n return stripFrontmatter(await readFile(path, \"utf8\"));\n } catch {\n return \"\";\n }\n}\n\n/**\n * Build the child prompt. A pstack delegate must read `poteto-mode` first, and\n * the parent normally passes its absolute path. When the parent omits it, this\n * fallback keeps the delegate from drifting into general-purpose style.\n */\nexport function composePrompt(input: {\n readonly kind: AgentKind;\n readonly description: string;\n readonly prompt: string;\n readonly agentInstructions: string;\n readonly potetoModePath?: string;\n}): string {\n if (input.kind === \"general\") return input.prompt;\n\n const path = input.potetoModePath ?? POTETO_MODE_PATH;\n const sections = [\n input.agentInstructions.trim(),\n `Parent task label: ${input.description}`,\n `Read \\`${path}\\` in full before any work, including its inline Principles index. Navigate to a leaf \\`principle-*\\` skill whenever you apply that principle.`,\n input.prompt.trim(),\n ].filter(Boolean);\n return sections.join(\"\\n\\n\");\n}\n\nexport interface RoleResolution {\n readonly route: Route | undefined;\n /** Human-readable notes to append to the tool reply: issues, near misses. */\n readonly notes: readonly string[];\n}\n\n/**\n * Resolve the `role` argument against the shipped role table, explaining a miss\n * instead of swallowing it.\n *\n * A missing file is normal. A configured-but-unmatched role is not: it means a\n * skill and `~/.dsh/pstack-models.md` disagree, and the child would silently run\n * on the parent route. The tool reply says so, so the parent can fix the file or\n * report the miss rather than believing the route applied.\n */\nexport async function resolveRoleArg(role: string | undefined): Promise<RoleResolution> {\n if (!role) return { route: undefined, notes: [] };\n\n const { table, issues, unreadable } = await loadRoleTable();\n const match = lookupRole(table, role);\n if (match) {\n const notes: string[] = [];\n for (const issue of issues) {\n if (issue.line === 0) notes.push(issue.message);\n }\n return { route: resolveRole(table, role), notes };\n }\n\n const near = findNearMisses(table, role);\n const lines: string[] = [];\n if (unreadable) {\n lines.push(\n `pstack: ${modelConfigPath()} could not be read; the child inherits the parent route.`,\n );\n } else if (table.size === 0) {\n lines.push(\n `pstack: no role table at ${modelConfigPath()}; the child inherits the parent route. Run /setup-pstack to configure roles.`,\n );\n } else {\n lines.push(\n `pstack: role \"${role}\" is not in ${modelConfigPath()}; the child inherits the parent route.`,\n );\n if (near.length > 0)\n lines.push(`pstack: did you mean ${near.map((n) => `\"${n}\"`).join(\" or \")}?`);\n }\n return { route: undefined, notes: lines };\n}\n\nexport interface PstackToolDeps {\n readonly start: (input: {\n readonly parent: Agent;\n readonly label: string;\n readonly prompt: ContentBlock[];\n readonly signal: AbortSignal;\n readonly route: Route | undefined;\n readonly cwd: string | undefined;\n }) => Promise<{ readonly childId: string }>;\n readonly loadAgent: (kind: AgentKind) => Promise<string>;\n /**\n * Resolve the `role` argument. The notes explain a miss so the reply can name\n * it; an empty list means the route applied as written, or there was no role.\n */\n readonly loadRole: (role: string | undefined) => Promise<RoleResolution>;\n readonly potetoModePath?: string;\n readonly defaultAgent?: AgentKind;\n readonly toolName?: string;\n}\n\n/**\n * Turn a resolved role into the `agentOptions` a child activation carries.\n *\n * This is the only place a `Route` becomes a provider request. Keeping it a\n * pure function lets a test assert the exact options without starting a child,\n * which is where a role-to-route bug would otherwise stay invisible until a\n * live delegation picked the wrong model.\n */\nexport function routeToAgentOptions(\n route: Route | undefined,\n): { provider: string; model: string; reasoningEffort?: ReasoningEffortId } | undefined {\n if (!route) return undefined;\n return {\n provider: route.provider,\n model: route.model,\n ...(route.reasoningEffort ? { reasoningEffort: ReasoningEffortId(route.reasoningEffort) } : {}),\n };\n}\n\n/** Tool definition over injected dependencies; `apply` supplies the runtime. */\nexport function createPstackTool(deps: PstackToolDeps) {\n return defineTool({\n name: deps.toolName ?? \"pstack_subagent\",\n description:\n 'Delegate a self-contained task to a pstack subagent. Use `agent: \"poteto-agent\"` for code-writing delegates and helper tasks spawned inside a /poteto-mode playbook step. Use `agent: \"general\"` for workflow reviewers such as how, why, arena, swarm, interrogate, and reflect. Use `agent: \"comment-sicko\"` only through /no-comments. Pass `role` to select the route configured in ~/.dsh/pstack-models.md; omit it to inherit the parent route. The call returns the child id immediately and the runtime reports the final answer in a completion notice.',\n parameters: {\n description: {\n type: \"string\",\n description: \"A short (3-5 word) description of the delegated task, for display.\",\n required: true,\n },\n prompt: {\n type: \"string\",\n description:\n \"The complete, self-contained task for the subagent. It does not share this conversation, so include context, file pointers, constraints, and the check that proves the work.\",\n required: true,\n },\n agent: {\n type: \"string\",\n enum: AGENT_KINDS,\n description:\n \"poteto-agent (default) for pstack delegates; general for workflow reviewers; comment-sicko for comment review.\",\n },\n role: {\n type: \"string\",\n description:\n 'Role line in ~/.dsh/pstack-models.md, such as \"feature, refactoring\" or \"judgment and prose\". Omit to inherit the parent route.',\n },\n cwd: {\n type: \"string\",\n description: \"Initial child working directory. Omit to inherit the parent directory.\",\n },\n },\n output: {\n schema: { type: \"string\" },\n render: (_args, value) => [{ type: \"text\", text: value }],\n },\n async execute(args, exec) {\n const parent = exec.agent;\n if (!parent) throw new Error(\"pstack_subagent requires an agent context\");\n\n const kind = (args.agent ?? deps.defaultAgent ?? \"poteto-agent\") as AgentKind;\n const agentInstructions = await deps.loadAgent(kind);\n const prompt = composePrompt({\n kind,\n description: args.description,\n prompt: args.prompt,\n agentInstructions,\n ...(deps.potetoModePath ? { potetoModePath: deps.potetoModePath } : {}),\n });\n const { route, notes } = await deps.loadRole(args.role);\n\n const activation = await deps.start({\n parent,\n label: args.description,\n prompt: [{ type: \"text\", text: prompt }],\n signal: exec.signal,\n route,\n cwd: args.cwd,\n });\n\n const started = `started subagent ${activation.childId}`;\n return notes.length > 0 ? [started, ...notes].join(\"\\n\") : started;\n },\n });\n}\n\n/**\n * Build the provider-facing activation request for one child.\n *\n * A role is resolved once, at delegation time, into concrete provider options.\n * The child inherits the parent route when the role is absent or resolves to\n * `inherit-parent`, which is why the field is omitted rather than set to a\n * placeholder.\n */\nexport function buildActivationRequest(input: {\n readonly parent: Agent;\n readonly prompt: ContentBlock[];\n readonly route: Route | undefined;\n readonly cwd: string | undefined;\n}): {\n parent: Agent;\n prompt: ContentBlock[];\n cwd?: string;\n agentOptions?: { provider: string; model: string; reasoningEffort?: ReasoningEffortId };\n} {\n const options = routeToAgentOptions(input.route);\n return {\n parent: input.parent,\n prompt: input.prompt,\n ...(input.cwd ? { cwd: input.cwd } : {}),\n ...(options ? { agentOptions: options } : {}),\n };\n}\n\n/**\n * Mount the tool. `ctx.subagents` owns child lifecycle; this row only supplies\n * the pstack-specific shape (agent preambles and role routes) on top.\n */\nexport function apply(ctx: Context, config: Config = {}): void {\n const providerName = config.provider ?? \"spawn\";\n\n const tool = createPstackTool({\n async start({ parent, label, prompt, signal, route, cwd }) {\n const activation = await ctx.subagents.startActivation({\n provider: providerName,\n label,\n signal,\n delivery: \"parent\",\n request: buildActivationRequest({ parent, prompt, route, cwd }),\n });\n return { childId: String(activation.childId) };\n },\n loadAgent: readAgentInstructions,\n loadRole: resolveRoleArg,\n potetoModePath: POTETO_MODE_PATH,\n ...(config.defaultAgent ? { defaultAgent: config.defaultAgent } : {}),\n ...(config.toolName ? { toolName: config.toolName } : {}),\n });\n ctx.tools.register(tool);\n}\n"],"mappings":";;;;;;;AAiCA,MAAM,0BAAU,IAAI,IAAI;CAAC;CAAkB;CAAQ;AAAQ,CAAC;;;;;;AAO5D,MAAa,oBAAoB;CAAC;CAAO;CAAS;CAAQ;CAAU;CAAO;AAAK;AAChF,MAAM,UAAU,IAAI,IAAY,iBAAiB;;;;;;;;;;AAWjD,SAAS,WAAW,MAAwB;CAC1C,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,QAAQ,GAAG;CAC3D,IAAI,CAA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AI,UAAU,gBAAgB;IACrD,UAAU;IACV;IACA;IACA,UAAU;IACV,SAAS,uBAAuB;KAAE;KAAQ;KAAQ;KAAO;IAAI,CAAC;GAChE,CAAC;GACD,OAAO,EAAE,SAAS,OAAO,WAAW,OAAO,EAAE;EAC/C;EACA,WAAW;EACX,UAAU;EACV,gBAAgB;EAChB,GAAI,OAAO,eAAe,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;EACnE,GAAI,OAAO,WAAW,EAAE,UAAU,OAAO,SAAS,IAAI,CAAC;CACzD,CAAC;CACD,IAAI,MAAM,SAAS,IAAI;AACzB"}
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,uCAAuC;EACnE,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,gBAAgB,sCAAsC;EAClE,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW,CAAC,oBAAoB,wCAAwC;EACxE,SAAS;CACX;CACA;EACE,KAAK;EACL,OAAO;EACP,WAAW;EACX,WAAW;GAC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,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"}
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "pstack skills",
4
+ "description": "Ships the 55 pstack workflow skills inside this package: the model can load setup-pstack, and the other skills are invoked explicitly with /name."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "pstack 技能",
4
+ "description": "在本包内提供 55 个 pstack 工作流技能:模型可加载 setup-pstack,其余技能用 /name 显式调用。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,16 +1,12 @@
1
1
  {
2
2
  "name": "dsh-pstack",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-beta.1",
4
4
  "description": "pstack for DeepSeek Harness: rigorous agent workflows ported from cursor/plugins.",
5
- "author": {
6
- "name": "leiwang",
7
- "email": "leiwang2000@foxmail.com"
8
- },
9
5
  "repository": {
10
6
  "type": "git",
11
- "url": "https://github.com/l246804/dsh-pstack"
7
+ "url": "git+https://github.com/l246804/dsh-pstack.git"
12
8
  },
13
- "homepage": "https://github.com/l246804/dsh-pstack",
9
+ "homepage": "https://github.com/l246804/dsh-pstack#readme",
14
10
  "bugs": {
15
11
  "url": "https://github.com/l246804/dsh-pstack/issues"
16
12
  },
@@ -23,15 +19,13 @@
23
19
  "pstack",
24
20
  "workflow"
25
21
  ],
22
+ "author": {
23
+ "name": "leiwang",
24
+ "email": "leiwang2000@foxmail.com"
25
+ },
26
26
  "license": "MIT",
27
- "files": [
28
- "dist",
29
- "assets",
30
- "cordis.patch.yml",
31
- "README.md",
32
- "LICENSE"
33
- ],
34
27
  "type": "module",
28
+ "icon": "./static/icon.png",
35
29
  "main": "./dist/index.mjs",
36
30
  "types": "./dist/index.d.mts",
37
31
  "exports": {
@@ -43,53 +37,73 @@
43
37
  "types": "./dist/subagent.d.mts",
44
38
  "default": "./dist/subagent.mjs"
45
39
  },
40
+ "./history": {
41
+ "types": "./dist/history.d.mts",
42
+ "default": "./dist/history.mjs"
43
+ },
44
+ "./script": {
45
+ "types": "./dist/script.d.mts",
46
+ "default": "./dist/script.mjs"
47
+ },
48
+ "./cordis.patch.yml": "./cordis.patch.yml",
49
+ "./locale/*.json": "./locale/*.json",
50
+ "./icon": "./static/icon.png",
46
51
  "./package.json": "./package.json"
47
52
  },
53
+ "files": [
54
+ "dist",
55
+ "assets",
56
+ "cordis.patch.yml",
57
+ "locale/*.json",
58
+ "static",
59
+ "README.md",
60
+ "LICENSE"
61
+ ],
62
+ "dsh": {
63
+ "manifestVersion": 1,
64
+ "bundle": {
65
+ "patch": "./cordis.patch.yml"
66
+ }
67
+ },
48
68
  "devDependencies": {
49
- "@deepseek-ai/cordis": "~4.0.5",
50
- "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
51
- "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
52
- "@deepseek-ai/dsh-skill": "0.2.1-rc.2",
53
- "@deepseek-ai/dsh-subagent": "0.2.1-rc.2",
54
- "@deepseek-ai/dsh-tools": "0.2.1-rc.2",
69
+ "@deepseek-ai/cordis-plugin-include": "~1.0.10",
70
+ "@deepseek-ai/cordis-plugin-loader": "~1.0.6",
71
+ "@deepseek-ai/dsh-tools": "0.2.1-rc.3",
72
+ "@types/js-yaml": "^4.0.9",
55
73
  "@types/node": "^26.6.5",
56
74
  "bumpp": "^12.3.0",
75
+ "js-yaml": "^4.3.2",
57
76
  "typescript": "^7.0.2",
58
77
  "vite-plus": "1.3.0"
59
78
  },
60
79
  "peerDependencies": {
61
- "@deepseek-ai/cordis": "~4.0.5",
62
- "@deepseek-ai/dsh-agent": "0.2.1-rc.2",
63
- "@deepseek-ai/dsh-llm": "0.2.1-rc.2",
64
- "@deepseek-ai/dsh-skill": "0.2.1-rc.2",
65
- "@deepseek-ai/dsh-subagent": "0.2.1-rc.2",
66
- "@deepseek-ai/dsh-tools": "0.2.1-rc.2"
80
+ "@deepseek-ai/cordis": "~4.0.5"
67
81
  },
68
82
  "devEngines": {
69
83
  "packageManager": {
70
84
  "name": "pnpm",
71
- "version": "12.14.0",
85
+ "version": "12.15.0",
72
86
  "onFail": "download"
73
87
  }
74
88
  },
75
89
  "engines": {
76
- "dsh": ">=0.2.0 <0.3.0",
77
- "node": ">=22.19"
78
- },
79
- "dsh": {
80
- "bundle": {
81
- "patch": "./cordis.patch.yml"
82
- },
83
- "manifestVersion": 1
90
+ "node": ">=22.19",
91
+ "dsh": "0.2.1-rc.3"
84
92
  },
85
93
  "scripts": {
86
- "sync": "node scripts/sync-upstream.ts",
87
- "sync:check": "node scripts/check-rewrites.ts --check && node scripts/sync-upstream.ts --check && node scripts/report-coverage.ts --check",
88
- "sync:report": "node scripts/report-coverage.ts",
89
- "build": "vp pack",
90
- "dev": "vp pack --watch",
94
+ "build:runtime": "node scripts/build-runtime.ts",
95
+ "build:assets": "pnpm run build:runtime && node scripts/sync-upstream.ts",
96
+ "build:bundle": "vp pack",
97
+ "build": "pnpm run build:assets && pnpm run build:bundle",
98
+ "dev": "pnpm run build:assets && vp pack --watch",
99
+ "check:upstream": "node scripts/check-upstream-tree.mjs",
100
+ "check:runtime": "node scripts/build-runtime.ts --check",
101
+ "check:assets": "pnpm run check:runtime && node scripts/sync-upstream.ts --check && node scripts/check-assets.ts",
102
+ "check:scripts": "node scripts/check-scripts.ts",
103
+ "check:pack": "node scripts/check-pack.ts",
104
+ "typecheck": "tsc --noEmit",
91
105
  "test": "vp test",
92
- "check": "vp check",
106
+ "check": "pnpm run check:upstream && pnpm run check:assets && pnpm run check:scripts && pnpm run typecheck && pnpm run test",
93
107
  "release": "bumpp"
94
108
  }
95
109
  }
Binary file
@@ -1,62 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
- import { join } from "node:path";
4
-
5
- const scriptsDirectory = import.meta.dir;
6
- const nodeModulesDirectory = join(scriptsDirectory, "node_modules");
7
- const commanderPackagePath = join(
8
- nodeModulesDirectory,
9
- "commander",
10
- "package.json"
11
- );
12
- const installKeyPath = join(
13
- nodeModulesDirectory,
14
- ".poteto-mode-tools-install-key"
15
- );
16
-
17
- function currentInstallKey(): string {
18
- return createHash("sha256")
19
- .update(readFileSync(join(scriptsDirectory, "package.json")))
20
- .update("\0")
21
- .update(readFileSync(join(scriptsDirectory, "bun.lock")))
22
- .digest("hex");
23
- }
24
-
25
- export function ensureDependenciesInstalled(): void {
26
- const installKey = currentInstallKey();
27
- if (
28
- existsSync(commanderPackagePath) &&
29
- existsSync(installKeyPath) &&
30
- readFileSync(installKeyPath, "utf8").trim() === installKey
31
- ) {
32
- return;
33
- }
34
-
35
- const result = Bun.spawnSync(
36
- [process.execPath, "install", "--frozen-lockfile"],
37
- { cwd: scriptsDirectory }
38
- );
39
- if (result.exitCode !== 0) {
40
- process.stdout.write(result.stdout);
41
- process.stderr.write(result.stderr);
42
- throw new Error(
43
- `bun install --frozen-lockfile exited with status ${result.exitCode}`
44
- );
45
- }
46
- if (!existsSync(commanderPackagePath)) {
47
- throw new Error(
48
- "bun install --frozen-lockfile completed without installing commander"
49
- );
50
- }
51
-
52
- writeFileSync(installKeyPath, `${installKey}\n`);
53
-
54
- const restarted = Bun.spawnSync([process.execPath, ...process.argv.slice(1)], {
55
- cwd: process.cwd(),
56
- env: process.env,
57
- stdin: "inherit",
58
- stdout: "inherit",
59
- stderr: "inherit",
60
- });
61
- process.exit(restarted.exitCode ?? 1);
62
- }