@pennixrv/trellis 0.7.2-beta.12 → 0.7.2-beta.16

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 (283) hide show
  1. package/dist/commands/init.d.ts.map +1 -1
  2. package/dist/commands/init.js +11 -13
  3. package/dist/commands/init.js.map +1 -1
  4. package/dist/commands/update.d.ts.map +1 -1
  5. package/dist/commands/update.js +23 -10
  6. package/dist/commands/update.js.map +1 -1
  7. package/dist/commands/workflow.d.ts.map +1 -1
  8. package/dist/commands/workflow.js +5 -7
  9. package/dist/commands/workflow.js.map +1 -1
  10. package/dist/configurators/codebuddy.d.ts +1 -8
  11. package/dist/configurators/codebuddy.d.ts.map +1 -1
  12. package/dist/configurators/codebuddy.js +2 -12
  13. package/dist/configurators/codebuddy.js.map +1 -1
  14. package/dist/configurators/codex.d.ts +0 -36
  15. package/dist/configurators/codex.d.ts.map +1 -1
  16. package/dist/configurators/codex.js +2 -99
  17. package/dist/configurators/codex.js.map +1 -1
  18. package/dist/configurators/copilot.d.ts +1 -12
  19. package/dist/configurators/copilot.d.ts.map +1 -1
  20. package/dist/configurators/copilot.js +2 -20
  21. package/dist/configurators/copilot.js.map +1 -1
  22. package/dist/configurators/cursor.d.ts +1 -8
  23. package/dist/configurators/cursor.d.ts.map +1 -1
  24. package/dist/configurators/cursor.js +2 -12
  25. package/dist/configurators/cursor.js.map +1 -1
  26. package/dist/configurators/droid.d.ts +1 -8
  27. package/dist/configurators/droid.d.ts.map +1 -1
  28. package/dist/configurators/droid.js +2 -12
  29. package/dist/configurators/droid.js.map +1 -1
  30. package/dist/configurators/dsh.d.ts +1 -21
  31. package/dist/configurators/dsh.d.ts.map +1 -1
  32. package/dist/configurators/dsh.js +4 -37
  33. package/dist/configurators/dsh.js.map +1 -1
  34. package/dist/configurators/gemini.d.ts +1 -16
  35. package/dist/configurators/gemini.d.ts.map +1 -1
  36. package/dist/configurators/gemini.js +3 -21
  37. package/dist/configurators/gemini.js.map +1 -1
  38. package/dist/configurators/grok.d.ts +1 -12
  39. package/dist/configurators/grok.d.ts.map +1 -1
  40. package/dist/configurators/grok.js +2 -18
  41. package/dist/configurators/grok.js.map +1 -1
  42. package/dist/configurators/kimi.d.ts +1 -21
  43. package/dist/configurators/kimi.d.ts.map +1 -1
  44. package/dist/configurators/kimi.js +2 -38
  45. package/dist/configurators/kimi.js.map +1 -1
  46. package/dist/configurators/kiro.d.ts +1 -9
  47. package/dist/configurators/kiro.d.ts.map +1 -1
  48. package/dist/configurators/kiro.js +1 -9
  49. package/dist/configurators/kiro.js.map +1 -1
  50. package/dist/configurators/omp.d.ts.map +1 -1
  51. package/dist/configurators/omp.js +1 -5
  52. package/dist/configurators/omp.js.map +1 -1
  53. package/dist/configurators/pi.d.ts.map +1 -1
  54. package/dist/configurators/pi.js +2 -5
  55. package/dist/configurators/pi.js.map +1 -1
  56. package/dist/configurators/qoder.d.ts +1 -10
  57. package/dist/configurators/qoder.d.ts.map +1 -1
  58. package/dist/configurators/qoder.js +3 -15
  59. package/dist/configurators/qoder.js.map +1 -1
  60. package/dist/configurators/reasonix.d.ts +1 -12
  61. package/dist/configurators/reasonix.d.ts.map +1 -1
  62. package/dist/configurators/reasonix.js +3 -22
  63. package/dist/configurators/reasonix.js.map +1 -1
  64. package/dist/configurators/shared.d.ts +1 -24
  65. package/dist/configurators/shared.d.ts.map +1 -1
  66. package/dist/configurators/shared.js +5 -184
  67. package/dist/configurators/shared.js.map +1 -1
  68. package/dist/configurators/snow.d.ts +1 -20
  69. package/dist/configurators/snow.d.ts.map +1 -1
  70. package/dist/configurators/snow.js +2 -25
  71. package/dist/configurators/snow.js.map +1 -1
  72. package/dist/configurators/trae.d.ts +1 -14
  73. package/dist/configurators/trae.d.ts.map +1 -1
  74. package/dist/configurators/trae.js +3 -19
  75. package/dist/configurators/trae.js.map +1 -1
  76. package/dist/configurators/zcode.d.ts +1 -13
  77. package/dist/configurators/zcode.d.ts.map +1 -1
  78. package/dist/configurators/zcode.js +2 -18
  79. package/dist/configurators/zcode.js.map +1 -1
  80. package/dist/migrations/manifests/0.5.0-beta.5.json +1 -212
  81. package/dist/migrations/manifests/0.7.2-beta.13.json +9 -0
  82. package/dist/migrations/manifests/0.7.2-beta.14.json +9 -0
  83. package/dist/migrations/manifests/0.7.2-beta.15.json +9 -0
  84. package/dist/migrations/manifests/0.7.2-beta.16.json +9 -0
  85. package/dist/migrations/retired-native-paths.d.ts +109 -0
  86. package/dist/migrations/retired-native-paths.d.ts.map +1 -0
  87. package/dist/migrations/retired-native-paths.js +263 -0
  88. package/dist/migrations/retired-native-paths.js.map +1 -0
  89. package/dist/templates/claude/index.d.ts +1 -16
  90. package/dist/templates/claude/index.d.ts.map +1 -1
  91. package/dist/templates/claude/index.js +5 -32
  92. package/dist/templates/claude/index.js.map +1 -1
  93. package/dist/templates/claude/settings.json +0 -22
  94. package/dist/templates/codebuddy/index.d.ts +2 -3
  95. package/dist/templates/codebuddy/index.d.ts.map +1 -1
  96. package/dist/templates/codebuddy/index.js +2 -3
  97. package/dist/templates/codebuddy/index.js.map +1 -1
  98. package/dist/templates/codebuddy/settings.json +0 -10
  99. package/dist/templates/codex/config.toml +2 -19
  100. package/dist/templates/codex/hooks/session-start.py +1 -1
  101. package/dist/templates/codex/hooks.json +0 -12
  102. package/dist/templates/codex/index.d.ts +0 -5
  103. package/dist/templates/codex/index.d.ts.map +1 -1
  104. package/dist/templates/codex/index.js +0 -13
  105. package/dist/templates/codex/index.js.map +1 -1
  106. package/dist/templates/common/bundled-skills/trellis-meta/SKILL.md +7 -7
  107. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-agents.md +9 -51
  108. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-context-loading.md +3 -15
  109. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-hooks.md +1 -2
  110. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/context-injection.md +4 -9
  111. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/generated-files.md +2 -2
  112. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/overview.md +1 -1
  113. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/spec-system.md +1 -1
  114. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/agents.md +9 -79
  115. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/hooks-and-settings.md +2 -4
  116. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/overview.md +3 -6
  117. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/platform-map.md +24 -103
  118. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/skills-and-commands.md +1 -1
  119. package/dist/templates/common/bundled-skills/trellis-session-insight/SKILL.md +1 -1
  120. package/dist/templates/copilot/hooks/session-start.py +1 -1
  121. package/dist/templates/cursor/hooks.json +0 -7
  122. package/dist/templates/cursor/index.d.ts +1 -11
  123. package/dist/templates/cursor/index.d.ts.map +1 -1
  124. package/dist/templates/cursor/index.js +2 -10
  125. package/dist/templates/cursor/index.js.map +1 -1
  126. package/dist/templates/droid/index.d.ts +2 -3
  127. package/dist/templates/droid/index.d.ts.map +1 -1
  128. package/dist/templates/droid/index.js +2 -3
  129. package/dist/templates/droid/index.js.map +1 -1
  130. package/dist/templates/droid/settings.json +0 -10
  131. package/dist/templates/dsh/DSH.md +2 -33
  132. package/dist/templates/dsh/index.d.ts +1 -19
  133. package/dist/templates/dsh/index.d.ts.map +1 -1
  134. package/dist/templates/dsh/index.js +2 -21
  135. package/dist/templates/dsh/index.js.map +1 -1
  136. package/dist/templates/gemini/index.d.ts +1 -11
  137. package/dist/templates/gemini/index.d.ts.map +1 -1
  138. package/dist/templates/gemini/index.js +2 -10
  139. package/dist/templates/gemini/index.js.map +1 -1
  140. package/dist/templates/kiro/index.d.ts +1 -13
  141. package/dist/templates/kiro/index.d.ts.map +1 -1
  142. package/dist/templates/kiro/index.js +1 -13
  143. package/dist/templates/kiro/index.js.map +1 -1
  144. package/dist/templates/markdown/agents.md +6 -3
  145. package/dist/templates/omp/extensions/trellis/index.ts.txt +11 -51
  146. package/dist/templates/omp/index.d.ts +0 -2
  147. package/dist/templates/omp/index.d.ts.map +1 -1
  148. package/dist/templates/omp/index.js +1 -4
  149. package/dist/templates/omp/index.js.map +1 -1
  150. package/dist/templates/opencode/lib/trellis-context.js +12 -321
  151. package/dist/templates/opencode/plugins/inject-shell-session-context.js +93 -0
  152. package/dist/templates/opencode/plugins/inject-workflow-state.js +4 -10
  153. package/dist/templates/opencode/plugins/session-start.js +2 -6
  154. package/dist/templates/pi/extensions/trellis/index.ts.txt +8 -1432
  155. package/dist/templates/pi/index.d.ts +1 -2
  156. package/dist/templates/pi/index.d.ts.map +1 -1
  157. package/dist/templates/pi/index.js +2 -5
  158. package/dist/templates/pi/index.js.map +1 -1
  159. package/dist/templates/qoder/index.d.ts +2 -3
  160. package/dist/templates/qoder/index.d.ts.map +1 -1
  161. package/dist/templates/qoder/index.js +2 -3
  162. package/dist/templates/qoder/index.js.map +1 -1
  163. package/dist/templates/shared-hooks/index.d.ts +2 -56
  164. package/dist/templates/shared-hooks/index.d.ts.map +1 -1
  165. package/dist/templates/shared-hooks/index.js +3 -70
  166. package/dist/templates/shared-hooks/index.js.map +1 -1
  167. package/dist/templates/shared-hooks/inject-spec-context.py +6 -35
  168. package/dist/templates/shared-hooks/inject-workflow-state.py +3 -77
  169. package/dist/templates/shared-hooks/session-start.py +1 -1
  170. package/dist/templates/snow/SNOW.md +6 -18
  171. package/dist/templates/snow/hooks/write-trellis-context.py +51 -133
  172. package/dist/templates/snow/index.d.ts +2 -21
  173. package/dist/templates/snow/index.d.ts.map +1 -1
  174. package/dist/templates/snow/index.js +3 -24
  175. package/dist/templates/snow/index.js.map +1 -1
  176. package/dist/templates/template-utils.d.ts +1 -2
  177. package/dist/templates/template-utils.d.ts.map +1 -1
  178. package/dist/templates/template-utils.js +1 -11
  179. package/dist/templates/template-utils.js.map +1 -1
  180. package/dist/templates/trae/index.d.ts +2 -3
  181. package/dist/templates/trae/index.d.ts.map +1 -1
  182. package/dist/templates/trae/index.js +2 -3
  183. package/dist/templates/trae/index.js.map +1 -1
  184. package/dist/templates/trellis/config.yaml +7 -36
  185. package/dist/templates/trellis/scripts/common/config.py +1 -36
  186. package/dist/templates/trellis/scripts/common/git_context.py +3 -4
  187. package/dist/templates/trellis/scripts/common/task_context.py +3 -3
  188. package/dist/templates/trellis/scripts/common/task_store.py +1 -77
  189. package/dist/templates/trellis/scripts/common/workflow_phase.py +3 -36
  190. package/dist/templates/trellis/scripts/common/workflow_selection.py +12 -2
  191. package/dist/templates/trellis/scripts/task.py +2 -2
  192. package/dist/templates/trellis/workflow.md +1 -7
  193. package/dist/templates/zcode/config.json +0 -10
  194. package/dist/templates/zcode/index.d.ts +3 -22
  195. package/dist/templates/zcode/index.d.ts.map +1 -1
  196. package/dist/templates/zcode/index.js +3 -24
  197. package/dist/templates/zcode/index.js.map +1 -1
  198. package/dist/types/ai-tools.d.ts +0 -4
  199. package/dist/types/ai-tools.d.ts.map +1 -1
  200. package/dist/types/ai-tools.js +4 -109
  201. package/dist/types/ai-tools.js.map +1 -1
  202. package/dist/utils/ablation-store.d.ts.map +1 -1
  203. package/dist/utils/ablation-store.js +24 -0
  204. package/dist/utils/ablation-store.js.map +1 -1
  205. package/dist/utils/asset-backup.d.ts.map +1 -1
  206. package/dist/utils/asset-backup.js +3 -0
  207. package/dist/utils/asset-backup.js.map +1 -1
  208. package/dist/utils/retired-native-assets.d.ts +16 -0
  209. package/dist/utils/retired-native-assets.d.ts.map +1 -0
  210. package/dist/utils/retired-native-assets.js +234 -0
  211. package/dist/utils/retired-native-assets.js.map +1 -0
  212. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -1
  213. package/dist/utils/uninstall-scrubbers.js +1 -1
  214. package/dist/utils/uninstall-scrubbers.js.map +1 -1
  215. package/package.json +2 -2
  216. package/dist/templates/claude/agents/trellis-check.md +0 -115
  217. package/dist/templates/claude/agents/trellis-implement.md +0 -110
  218. package/dist/templates/claude/agents/trellis-research.md +0 -137
  219. package/dist/templates/codebuddy/agents/trellis-check.md +0 -115
  220. package/dist/templates/codebuddy/agents/trellis-implement.md +0 -110
  221. package/dist/templates/codebuddy/agents/trellis-research.md +0 -137
  222. package/dist/templates/codex/agents/trellis-check.toml +0 -56
  223. package/dist/templates/codex/agents/trellis-implement.toml +0 -37
  224. package/dist/templates/codex/agents/trellis-research.toml +0 -78
  225. package/dist/templates/cursor/agents/trellis-check.md +0 -114
  226. package/dist/templates/cursor/agents/trellis-implement.md +0 -109
  227. package/dist/templates/cursor/agents/trellis-research.md +0 -136
  228. package/dist/templates/droid/droids/trellis-check.md +0 -107
  229. package/dist/templates/droid/droids/trellis-implement.md +0 -102
  230. package/dist/templates/droid/droids/trellis-research.md +0 -137
  231. package/dist/templates/dsh/agents/trellis-check.md +0 -99
  232. package/dist/templates/dsh/agents/trellis-implement.md +0 -106
  233. package/dist/templates/dsh/agents/trellis-research.md +0 -134
  234. package/dist/templates/gemini/agents/trellis-check.md +0 -107
  235. package/dist/templates/gemini/agents/trellis-implement.md +0 -102
  236. package/dist/templates/gemini/agents/trellis-research.md +0 -136
  237. package/dist/templates/grok/agents/trellis-check.md +0 -105
  238. package/dist/templates/grok/agents/trellis-implement.md +0 -116
  239. package/dist/templates/grok/agents/trellis-research.md +0 -146
  240. package/dist/templates/grok/index.d.ts +0 -16
  241. package/dist/templates/grok/index.d.ts.map +0 -1
  242. package/dist/templates/grok/index.js +0 -19
  243. package/dist/templates/grok/index.js.map +0 -1
  244. package/dist/templates/kimi/agents/trellis-check.md +0 -103
  245. package/dist/templates/kimi/agents/trellis-implement.md +0 -115
  246. package/dist/templates/kimi/agents/trellis-research.md +0 -144
  247. package/dist/templates/kimi/index.d.ts +0 -20
  248. package/dist/templates/kimi/index.d.ts.map +0 -1
  249. package/dist/templates/kimi/index.js +0 -23
  250. package/dist/templates/kimi/index.js.map +0 -1
  251. package/dist/templates/kiro/agents/trellis-check.json +0 -26
  252. package/dist/templates/kiro/agents/trellis-implement.json +0 -26
  253. package/dist/templates/kiro/agents/trellis-research.json +0 -30
  254. package/dist/templates/omp/agents/trellis-check.md +0 -41
  255. package/dist/templates/omp/agents/trellis-implement.md +0 -45
  256. package/dist/templates/omp/agents/trellis-research.md +0 -30
  257. package/dist/templates/opencode/agents/trellis-check.md +0 -122
  258. package/dist/templates/opencode/agents/trellis-implement.md +0 -118
  259. package/dist/templates/opencode/agents/trellis-research.md +0 -145
  260. package/dist/templates/opencode/plugins/inject-subagent-context.js +0 -569
  261. package/dist/templates/pi/agents/trellis-check.md +0 -37
  262. package/dist/templates/pi/agents/trellis-implement.md +0 -42
  263. package/dist/templates/pi/agents/trellis-research.md +0 -25
  264. package/dist/templates/qoder/agents/trellis-check.md +0 -108
  265. package/dist/templates/qoder/agents/trellis-implement.md +0 -103
  266. package/dist/templates/qoder/agents/trellis-research.md +0 -137
  267. package/dist/templates/reasonix/agents/trellis-check.md +0 -36
  268. package/dist/templates/reasonix/agents/trellis-implement.md +0 -41
  269. package/dist/templates/reasonix/index.d.ts +0 -13
  270. package/dist/templates/reasonix/index.d.ts.map +0 -1
  271. package/dist/templates/reasonix/index.js +0 -16
  272. package/dist/templates/reasonix/index.js.map +0 -1
  273. package/dist/templates/shared-hooks/inject-subagent-context.py +0 -1217
  274. package/dist/templates/snow/agents/trellis-check.md +0 -135
  275. package/dist/templates/snow/agents/trellis-implement.md +0 -153
  276. package/dist/templates/snow/agents/trellis-research.md +0 -114
  277. package/dist/templates/snow/hooks/beforeSubAgentStart.json +0 -15
  278. package/dist/templates/trae/agents/trellis-check.md +0 -108
  279. package/dist/templates/trae/agents/trellis-implement.md +0 -103
  280. package/dist/templates/trae/agents/trellis-research.md +0 -137
  281. package/dist/templates/zcode/agents/trellis-check.md +0 -109
  282. package/dist/templates/zcode/agents/trellis-implement.md +0 -111
  283. package/dist/templates/zcode/agents/trellis-research.md +0 -133
@@ -1,30 +1,12 @@
1
- import {
2
- existsSync,
3
- readFileSync,
4
- readdirSync,
5
- realpathSync,
6
- statSync,
7
- } from "node:fs";
1
+
2
+ import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
8
3
  import { createHash, randomBytes } from "node:crypto";
9
- import {
10
- delimiter,
11
- dirname,
12
- isAbsolute,
13
- join,
14
- relative,
15
- resolve,
16
- } from "node:path";
17
- import { homedir } from "node:os";
18
- import { spawn, spawnSync } from "node:child_process";
4
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
+ import { spawnSync } from "node:child_process";
19
6
  import { isUtf8 } from "node:buffer";
20
7
 
21
8
  // ── Types ──────────────────────────────────────────────────────────────
22
9
  type JsonObject = Record<string, unknown>;
23
- type TextContent = { type: "text"; text: string };
24
- interface PiToolResult {
25
- content: TextContent[];
26
- details?: unknown;
27
- }
28
10
  interface PiExtensionContext {
29
11
  cwd?: string;
30
12
  hasUI?: boolean;
@@ -40,69 +22,7 @@ interface PiExtensionContext {
40
22
  notify?: (msg: string, type?: "info" | "warning" | "error") => void;
41
23
  };
42
24
  }
43
- interface SubagentInput {
44
- agent?: string;
45
- prompt?: string;
46
- mode?: "single" | "parallel" | "chain";
47
- prompts?: string[];
48
- model?: string;
49
- thinking?: string;
50
- }
51
- interface AgentConfig {
52
- model?: string;
53
- thinking?: string;
54
- tools?: string[];
55
- fallbackModels: string[];
56
- }
57
- interface PiRunConfig {
58
- model?: string;
59
- thinking?: string;
60
- tools?: string[];
61
- }
62
-
63
- // ── Lazy-load pi-tui (avoid failing top-level imports) ─────────────────
64
- let _piTui: {
65
- visibleWidth?: (s: string) => number;
66
- truncateToWidth?: (s: string, w: number, ellipsis?: string) => string;
67
- } | null = null;
68
- function piTui() {
69
- if (!_piTui) {
70
- try {
71
- _piTui = require("@earendil-works/pi-tui");
72
- } catch {
73
- _piTui = {};
74
- }
75
- }
76
- return _piTui;
77
- }
78
- function trunc(s: string, w: number) {
79
- const t = piTui();
80
- return t.truncateToWidth
81
- ? t.truncateToWidth(s, w, "…")
82
- : s.length <= w
83
- ? s
84
- : w > 1
85
- ? s.slice(0, w - 1) + "…"
86
- : s.slice(0, w);
87
- }
88
-
89
- // ── Constants ─────────────────────────────────────────────────────────
90
- const TRELLIS_AGENT_JSONL: Record<string, string> = {
91
- "trellis-implement": "implement.jsonl",
92
- implement: "implement.jsonl",
93
- "trellis-check": "check.jsonl",
94
- check: "check.jsonl",
95
- };
96
- const MAX_STDOUT = 8 * 1024 * 1024;
97
- const MAX_STDERR = 1024 * 1024;
98
- const MAX_TAIL = 256 * 1024;
99
- const MAX_LINE_BUFFER = 1024 * 1024;
100
- const MAX_TOOL_ARG_CHARS = 2048;
101
- const MAX_TOOLS = 256;
102
- const MAX_PARALLEL_PROMPTS = 6;
103
- const ABORT_KILL_GRACE_MS = 1500;
104
25
  const SESSION_OVERVIEW_TIMEOUT_MS = 1500;
105
- const THROTTLE_MS = 500;
106
26
  const FIRST_REPLY_NOTICE = `<first-reply-notice>
107
27
  On the first visible assistant reply in this session, briefly acknowledge that Trellis SessionStart context loaded.
108
28
  Choose the acknowledgment language in this order:
@@ -114,302 +34,6 @@ The acknowledgment must not alter the language used for the remainder of the res
114
34
  This notice is one-shot: do not repeat it after the first visible assistant reply in this session.
115
35
  </first-reply-notice>`;
116
36
 
117
- // ── State types ───────────────────────────────────────────────────────
118
- type RunStatus = "pending" | "running" | "succeeded" | "failed" | "cancelled";
119
- type ToolStatus = "running" | "succeeded" | "failed";
120
-
121
- interface Usage {
122
- input: number;
123
- output: number;
124
- cacheRead: number;
125
- cacheWrite: number;
126
- cost: number;
127
- ctxTokens: number;
128
- turns: number;
129
- }
130
- interface ToolTrace {
131
- id: string;
132
- name: string;
133
- args: string;
134
- status: ToolStatus;
135
- startedAt: number;
136
- finishedAt?: number;
137
- }
138
- interface RunState {
139
- id: string;
140
- agent: string;
141
- prompt: string;
142
- step?: number;
143
- status: RunStatus;
144
- startedAt?: number;
145
- finishedAt?: number;
146
- finalText: string;
147
- textTail: string;
148
- thinkingTail: string;
149
- stderrTail: string;
150
- tools: ToolTrace[];
151
- usage: Usage;
152
- model?: string;
153
- thinking?: string;
154
- errorMessage?: string;
155
- }
156
- interface ProgressDetails {
157
- kind: "trellis-subagent-progress";
158
- agent: string;
159
- mode: "single" | "parallel" | "chain";
160
- startedAt: number;
161
- updatedAt: number;
162
- final: boolean;
163
- runs: RunState[];
164
- }
165
-
166
- // ── Native partial-update card state ──────────────────────────────────
167
- interface NativeCardHandle {
168
- state: JsonObject;
169
- invalidate: () => void;
170
- updatedAt: number;
171
- }
172
- const MAX_NATIVE_CARDS = 20;
173
- const nativeCards = new Map<string, NativeCardHandle>();
174
- let activeSubagentToolCallId: string | null = null;
175
- function rememberNativeCard(id: string, card: NativeCardHandle) {
176
- nativeCards.set(id, card);
177
- const active = activeSubagentToolCallId
178
- ? nativeCards.get(activeSubagentToolCallId)
179
- : undefined;
180
- if (!active || card.updatedAt >= active.updatedAt)
181
- activeSubagentToolCallId = id;
182
- for (const key of nativeCards.keys()) {
183
- if (nativeCards.size <= MAX_NATIVE_CARDS) break;
184
- if (key !== activeSubagentToolCallId) nativeCards.delete(key);
185
- }
186
- }
187
- function totalUsage(d: ProgressDetails): Usage {
188
- const u: Usage = {
189
- input: 0,
190
- output: 0,
191
- cacheRead: 0,
192
- cacheWrite: 0,
193
- cost: 0,
194
- ctxTokens: 0,
195
- turns: 0,
196
- };
197
- for (const r of d.runs) {
198
- u.input += r.usage.input;
199
- u.output += r.usage.output;
200
- u.cacheRead += r.usage.cacheRead;
201
- u.cacheWrite += r.usage.cacheWrite;
202
- u.cost += r.usage.cost;
203
- u.ctxTokens = Math.max(u.ctxTokens, r.usage.ctxTokens);
204
- u.turns += r.usage.turns;
205
- }
206
- return u;
207
- }
208
- function activeRun(d: ProgressDetails) {
209
- return d.runs.find((r) => r.status === "running") ?? d.runs.at(-1);
210
- }
211
- function toolArgs(t: ToolTrace) {
212
- try {
213
- return JSON.parse(t.args) as Record<string, unknown>;
214
- } catch {
215
- return {};
216
- }
217
- }
218
- function bashCommand(t: ToolTrace) {
219
- const a = toolArgs(t);
220
- return String(a.command || "").toLowerCase();
221
- }
222
- function isSearchTool(t: ToolTrace) {
223
- return t.name === "read" || t.name === "grep" || t.name === "find";
224
- }
225
- function isMutationTool(t: ToolTrace) {
226
- return t.name === "edit" || t.name === "write";
227
- }
228
- function isValidationCommand(t: ToolTrace) {
229
- const c = bashCommand(t);
230
- return /\b(test|typecheck|lint|build|gofmt|go test|npm run|pnpm|vitest|tsc)\b/.test(
231
- c,
232
- );
233
- }
234
- function isInspectionCommand(t: ToolTrace) {
235
- const c = bashCommand(t);
236
- return /\b(rg|grep|find|git diff|git status|ls|tree)\b/.test(c);
237
- }
238
- function thinkingIntent(text: string) {
239
- const s = text.toLowerCase();
240
- if (/error|failed|failure|panic|exception|报错|失败|错误|异常/.test(s))
241
- return "Analyzing failure cause";
242
- if (/test|verify|check|typecheck|lint|验证|测试|检查/.test(s))
243
- return "Planning verification steps";
244
- if (/plan|approach|design|strategy|方案|计划|思路|设计/.test(s))
245
- return "Structuring the implementation approach";
246
- if (/implement|change|edit|modify|refactor|实现|修改|重构/.test(s))
247
- return "Reasoning through code changes";
248
- if (/inspect|search|locate|read|context|定位|搜索|阅读|上下文/.test(s))
249
- return "Locating relevant context";
250
- return "";
251
- }
252
- function behaviorSummary(r: RunState) {
253
- if (r.status === "succeeded") return "Task completed and result returned";
254
- if (r.status === "failed")
255
- return "Task failed and error details were retained";
256
-
257
- const runningTool = r.tools.findLast((t) => t.status === "running");
258
- if (runningTool) {
259
- if (isMutationTool(runningTool)) return "Applying the plan to code";
260
- if (runningTool.name === "bash" && isValidationCommand(runningTool))
261
- return "Verifying whether the implementation passes";
262
- if (runningTool.name === "bash" && isInspectionCommand(runningTool))
263
- return "Inspecting current code state";
264
- if (isSearchTool(runningTool)) return "Locating relevant code and context";
265
- if (runningTool.name === "bash")
266
- return "Validating assumptions with commands";
267
- return "Using tools to advance the task";
268
- }
269
-
270
- const recent = r.tools.slice(-5);
271
- if (recent.some((t) => t.status === "failed"))
272
- return "Investigating tool or command failure";
273
- if (recent.some(isMutationTool)) return "Reviewing recent changes";
274
- if (recent.some((t) => t.name === "bash" && isValidationCommand(t)))
275
- return "Analyzing verification results";
276
- if (
277
- recent.length >= 2 &&
278
- recent.every(
279
- (t) => isSearchTool(t) || (t.name === "bash" && isInspectionCommand(t)),
280
- )
281
- )
282
- return "Mapping code structure and impact";
283
-
284
- const intent = thinkingIntent(`${r.thinkingTail}\n${r.textTail}`);
285
- if (intent) return intent;
286
- if (!r.tools.length) return "Understanding the task and planning execution";
287
- return "Advancing the task and preparing next steps";
288
- }
289
- function progressState(d: ProgressDetails) {
290
- const running = d.runs.filter((r) => r.status === "running").length;
291
- const failed = d.runs.some((r) => r.status === "failed");
292
- return failed
293
- ? "failed"
294
- : d.final
295
- ? "completed"
296
- : running
297
- ? `${running} running`
298
- : "pending";
299
- }
300
- function progressDone(d: ProgressDetails) {
301
- return d.runs.filter((r) => r.status !== "pending" && r.status !== "running")
302
- .length;
303
- }
304
- function summaryText(text: string) {
305
- return `${text.trim().replace(/[。.!?…]+$/u, "")}...`;
306
- }
307
- function splitModelThinking(model?: string, fallbackThinking?: string) {
308
- const m = model?.match(/^(.*):(off|minimal|low|medium|high|xhigh|max)$/i);
309
- return {
310
- model: m ? m[1] : model,
311
- thinking: (m?.[2] ?? fallbackThinking)?.toLowerCase(),
312
- };
313
- }
314
- function modelLabel(r: RunState) {
315
- const { model, thinking } = splitModelThinking(r.model, r.thinking);
316
- if (!model) return undefined;
317
- return thinking && thinking !== "off" ? `${model}(${thinking})` : model;
318
- }
319
- function applyRunConfig(r: RunState, cfg: PiRunConfig) {
320
- const parsed = splitModelThinking(cfg.model, cfg.thinking);
321
- r.model = parsed.model;
322
- r.thinking = parsed.thinking;
323
- }
324
- function runElapsed(d: ProgressDetails, r: RunState) {
325
- const start = r.startedAt ?? d.startedAt;
326
- const end =
327
- r.finishedAt ?? (r.status === "running" ? Date.now() : d.updatedAt);
328
- return fmtDur(Math.max(0, end - start));
329
- }
330
- function runHeader(d: ProgressDetails, r: RunState) {
331
- const usage = fmtUsage(r.usage, modelLabel(r)) || fmtUsage(totalUsage(d));
332
- return `${r.agent} · ${progressDone(d)}/${d.runs.length} done · ${progressState(d)} · ${runElapsed(d, r)}${usage ? ` · ${usage}` : ""}`;
333
- }
334
- function renderRunBlock(
335
- lines: string[],
336
- d: ProgressDetails,
337
- run: RunState,
338
- expanded: boolean,
339
- ) {
340
- const step = run.step ? `step ${run.step} · ` : "";
341
- lines.push(` - ${step}${runHeader(d, run)}`);
342
- const summary = behaviorSummary(run);
343
- if (summary) lines.push(` › ${summaryText(summary)}`);
344
- const visibleTools = expanded ? run.tools.slice(-8) : run.tools.slice(-1);
345
- for (const t of visibleTools)
346
- lines.push(` ${toolIcon(t.status)} ${toolBrief(t)}`);
347
- if (expanded && run.errorMessage) {
348
- lines.push(` ✗ ${oneLine(run.errorMessage, 120)}`);
349
- }
350
- }
351
- function renderProgressCard(
352
- d: ProgressDetails,
353
- expanded: boolean,
354
- w: number,
355
- ): string[] {
356
- const r = activeRun(d);
357
- if (!r) return [];
358
- const spinner = ["◐", "◓", "◑", "◒"][Math.floor(Date.now() / 250) % 4]!;
359
- const icon = d.final
360
- ? d.runs.some((x) => x.status === "failed")
361
- ? "✗"
362
- : "✓"
363
- : spinner;
364
- const totalElapsed = fmtDur(
365
- (d.final ? d.updatedAt : Date.now()) - d.startedAt,
366
- );
367
- const lines: string[] = [
368
- `${icon} subagent ${d.mode} · total ${totalElapsed}`,
369
- ];
370
-
371
- if (!expanded) {
372
- renderRunBlock(lines, d, r, false);
373
- lines.push(" Alt+O expand latest subagent card");
374
- return lines.map((l) => trunc(l, w));
375
- }
376
-
377
- for (const run of d.runs) renderRunBlock(lines, d, run, true);
378
- lines.push(" Alt+O collapse latest subagent card");
379
- const max = 48;
380
- const shown =
381
- lines.length > max
382
- ? [
383
- ...lines.slice(0, max - 1),
384
- ` … ${lines.length - max + 1} lines hidden`,
385
- ]
386
- : lines;
387
- return shown.map((l) => trunc(l, w));
388
- }
389
- function progressKey(d: ProgressDetails) {
390
- return d.runs
391
- .map((r) => {
392
- const t = r.tools.at(-1);
393
- return [
394
- r.id,
395
- r.status,
396
- r.tools.length,
397
- t?.id ?? "",
398
- t?.status ?? "",
399
- r.usage.turns,
400
- r.usage.input,
401
- r.usage.output,
402
- r.usage.cacheRead,
403
- r.usage.cacheWrite,
404
- r.usage.ctxTokens,
405
- r.model ?? "",
406
- r.thinking ?? "",
407
- r.errorMessage ?? "",
408
- ].join("~");
409
- })
410
- .join("|");
411
- }
412
-
413
37
  // ── Utilities ─────────────────────────────────────────────────────────
414
38
  function isObj(v: unknown): v is JsonObject {
415
39
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -417,9 +41,6 @@ function isObj(v: unknown): v is JsonObject {
417
41
  function str(v: unknown): string | null {
418
42
  return typeof v === "string" && v.trim() ? v.trim() : null;
419
43
  }
420
- function num(v: unknown): number {
421
- return typeof v === "number" && Number.isFinite(v) ? v : 0;
422
- }
423
44
  function hash(s: string) {
424
45
  return createHash("sha256").update(s).digest("hex").slice(0, 24);
425
46
  }
@@ -478,285 +99,10 @@ function cmdHasTrellisCtx(cmd: string) {
478
99
  /^env\s+.*TRELLIS_CONTEXT_ID=/.test(t)
479
100
  );
480
101
  }
481
- function fmtDur(ms: number) {
482
- if (ms < 1000) return `${ms}ms`;
483
- const s = Math.floor(ms / 1000);
484
- if (s < 60) return `${s}s`;
485
- return `${Math.floor(s / 60)}m${s % 60}s`;
486
- }
487
- function fmtNum(n: number) {
488
- if (!n) return "0";
489
- if (Math.abs(n) < 1000) return `${n}`;
490
- if (Math.abs(n) < 1000000) return `${(n / 1000).toFixed(1)}k`;
491
- return `${(n / 1000000).toFixed(1)}m`;
492
- }
493
- function fmtUsage(u: Usage, m?: string) {
494
- const p: string[] = [];
495
- if (u.turns) p.push(`${u.turns}t`);
496
- if (u.input) p.push(`↑${fmtNum(u.input)}`);
497
- if (u.output) p.push(`↓${fmtNum(u.output)}`);
498
- if (u.cost) p.push(`$${u.cost.toFixed(3)}`);
499
- if (u.ctxTokens) p.push(`ctx:${fmtNum(u.ctxTokens)}`);
500
- if (m) p.push(m);
501
- return p.join(" ");
502
- }
503
- function statusIcon(s: RunStatus) {
504
- return s === "pending"
505
- ? "○"
506
- : s === "running"
507
- ? "●"
508
- : s === "succeeded"
509
- ? "✓"
510
- : s === "failed"
511
- ? "✗"
512
- : "⊘";
513
- }
514
- function toolIcon(s: ToolStatus) {
515
- return s === "running" ? "•" : s === "succeeded" ? "✓" : "✗";
516
- }
517
- function latest(text: string, n: number) {
518
- return text
519
- .split(/\r?\n/)
520
- .map((l) => l.trimEnd())
521
- .filter((l) => l.trim())
522
- .slice(-n);
523
- }
524
- function appendTail(cur: string, next: string, max: number) {
525
- if (!next) return cur;
526
- const c = cur + next;
527
- return c.length <= max ? c : c.slice(-max);
528
- }
529
- function extractText(content: unknown): string {
530
- if (typeof content === "string") return content;
531
- if (!Array.isArray(content)) return "";
532
- return content
533
- .map((b) =>
534
- isObj(b) && b.type === "text" && typeof b.text === "string" ? b.text : "",
535
- )
536
- .join("");
537
- }
538
- function extractThinking(content: unknown): string {
539
- if (!Array.isArray(content)) return "";
540
- return content
541
- .map((b) =>
542
- isObj(b) && b.type === "thinking" && typeof b.thinking === "string"
543
- ? b.thinking
544
- : "",
545
- )
546
- .join("\n");
547
- }
548
- function newUsage(): Usage {
549
- return {
550
- input: 0,
551
- output: 0,
552
- cacheRead: 0,
553
- cacheWrite: 0,
554
- cost: 0,
555
- ctxTokens: 0,
556
- turns: 0,
557
- };
558
- }
559
- function newRun(
560
- id: string,
561
- agent: string,
562
- prompt: string,
563
- step?: number,
564
- ): RunState {
565
- return {
566
- id,
567
- agent,
568
- prompt: trunc(prompt.replace(/\s+/g, " ").trim(), 120) || "(empty)",
569
- step,
570
- status: "pending",
571
- finalText: "",
572
- textTail: "",
573
- thinkingTail: "",
574
- stderrTail: "",
575
- tools: [],
576
- usage: newUsage(),
577
- };
578
- }
579
- function cloneProgress(d: ProgressDetails): ProgressDetails {
580
- return {
581
- ...d,
582
- runs: d.runs.map((r) => ({
583
- ...r,
584
- tools: r.tools.map((t) => ({ ...t })),
585
- usage: { ...r.usage },
586
- })),
587
- };
588
- }
589
-
590
- function oneLine(v: unknown, max = 80) {
591
- return String(v || "...")
592
- .replace(/\s+/g, " ")
593
- .trim()
594
- .slice(0, max);
595
- }
596
- function summarizeToolArgs(name: string, args: unknown): string {
597
- const a = isObj(args) ? args : {};
598
- const summary: JsonObject = {};
599
- if ("path" in a) summary.path = oneLine(a.path, 240);
600
- if ("file_path" in a) summary.file_path = oneLine(a.file_path, 240);
601
- if ("command" in a) summary.command = oneLine(a.command, 240);
602
- if ("pattern" in a) summary.pattern = oneLine(a.pattern, 120);
603
- if ("limit" in a) summary.limit = a.limit;
604
- if ("offset" in a) summary.offset = a.offset;
605
- if (name === "edit" && Array.isArray(a.edits))
606
- summary.edits = `${a.edits.length} edit(s)`;
607
- if (name === "write" && "content" in a)
608
- summary.content = `<${String(a.content ?? "").length} chars>`;
609
- const json = JSON.stringify(
610
- Object.keys(summary).length ? summary : { tool: name },
611
- );
612
- return json.length <= MAX_TOOL_ARG_CHARS
613
- ? json
614
- : json.slice(0, MAX_TOOL_ARG_CHARS);
615
- }
616
- function toolBrief(t: ToolTrace): string {
617
- const a = toolArgs(t);
618
- if (t.name === "read") return `read: ${oneLine(a.path || a.file_path, 80)}`;
619
- if (t.name === "bash") return `bash: ${oneLine(a.command, 60)}`;
620
- if (t.name === "write") return `write: ${oneLine(a.path || a.file_path, 80)}`;
621
- if (t.name === "edit") return `edit: ${oneLine(a.path || a.file_path, 80)}`;
622
- if (t.name === "grep") return `grep: ${oneLine(a.pattern, 50)}`;
623
- if (t.name === "find") return `find: ${oneLine(a.pattern || "*", 50)}`;
624
- return oneLine(t.name, 50);
625
- }
626
-
627
- // ── Pi CLI path resolution ────────────────────────────────────────────
628
- const PI_CLI_SEGMENTS = [
629
- ["node_modules", "@earendil-works", "pi-coding-agent", "dist", "cli.js"],
630
- ["node_modules", "@mariozechner", "pi-coding-agent", "dist", "cli.js"],
631
- ];
632
-
633
- function resolvePiCli(): { command: string; args: string[] } {
634
- const envCli = str(process.env.TRELLIS_PI_CLI_JS);
635
- if (envCli) {
636
- const p = resolve(envCli);
637
- if (!exists(p)) throw new Error(`TRELLIS_PI_CLI_JS missing: ${p}`);
638
- return { command: process.execPath, args: [p] };
639
- }
640
- const candidates: string[] = [];
641
- for (const arg of process.argv)
642
- if (/pi-coding-agent[\\/]dist[\\/]cli\.js$/i.test(arg))
643
- candidates.push(resolve(arg));
644
- const prefix =
645
- str(process.env.npm_config_prefix) ?? str(process.env.NPM_CONFIG_PREFIX);
646
- const appData = str(process.env.APPDATA);
647
- const pathVal = process.env.PATH ?? process.env.Path ?? "";
648
- const addBase = (base: string) => {
649
- for (const seg of PI_CLI_SEGMENTS) candidates.push(join(base, ...seg));
650
- };
651
- if (prefix) {
652
- addBase(prefix);
653
- addBase(join(prefix, "lib"));
654
- }
655
- if (appData) addBase(join(appData, "npm"));
656
- for (const entry of pathVal.split(delimiter)) {
657
- const e = entry.trim();
658
- if (!e) continue;
659
- addBase(e);
660
- addBase(dirname(e));
661
- addBase(join(dirname(e), "lib"));
662
- }
663
- for (const c of [...new Set(candidates)])
664
- if (exists(c)) return { command: process.execPath, args: [c] };
665
- return { command: "pi", args: [] };
666
- }
667
-
668
- function resolveRunCfg(
669
- input: SubagentInput,
670
- agentCfg: AgentConfig,
671
- inheritedThinking?: string,
672
- inheritedModel?: string,
673
- ): PiRunConfig {
674
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
675
- const normalize = (v: unknown): string | undefined => {
676
- const s = typeof v === "string" && v.trim() ? v.trim().toLowerCase() : "";
677
- return THINKING_LEVELS.includes(s) ? s : undefined;
678
- };
679
- const suffixRe = /:(off|minimal|low|medium|high|xhigh|max)$/i;
680
- const inputModel = str(input.model);
681
- const agentModel = agentCfg.model;
682
- const rawModel = inputModel ?? agentModel ?? str(inheritedModel);
683
- const inputSuffixThinking = normalize(inputModel?.match(suffixRe)?.[1]);
684
- const agentSuffixThinking = normalize(agentModel?.match(suffixRe)?.[1]);
685
- const baseModel = rawModel?.replace(suffixRe, "");
686
- const thinking =
687
- normalize(input.thinking) ??
688
- inputSuffixThinking ??
689
- normalize(agentCfg.thinking) ??
690
- agentSuffixThinking ??
691
- normalize(inheritedThinking);
692
- if (baseModel && thinking && thinking !== "off")
693
- return { model: `${baseModel}:${thinking}`, thinking, tools: agentCfg.tools };
694
- return { model: baseModel || rawModel, thinking, tools: agentCfg.tools };
695
- }
696
-
697
- function contextModelRef(ctx?: PiExtensionContext): string | undefined {
698
- const provider = str(ctx?.model?.provider);
699
- const modelId = str(ctx?.model?.id);
700
- return provider && modelId ? `${provider}/${modelId}` : undefined;
701
- }
702
-
703
- function buildPiArgs(cfg: PiRunConfig): string[] {
704
- const args = ["--mode", "json", "-p", "--no-session"];
705
- if (cfg.model)
706
- args.push(
707
- "--model",
708
- cfg.thinking && cfg.thinking !== "off" && !cfg.model.includes(":")
709
- ? `${cfg.model}:${cfg.thinking}`
710
- : cfg.model,
711
- );
712
- else if (cfg.thinking && cfg.thinking !== "off")
713
- args.push("--thinking", cfg.thinking);
714
- if (cfg.tools && cfg.tools.length > 0)
715
- args.push("--tools", cfg.tools.join(","));
716
- return args;
717
- }
718
-
719
- // ── BoundedBufferCollector ─────────────────────────────────────────────
720
- class BBC {
721
- private c: Buffer[] = [];
722
- private len = 0;
723
- private trunc = 0;
724
- constructor(private max: number) {}
725
- append(b: Buffer) {
726
- if (b.length >= this.max) {
727
- this.trunc += this.len + b.length - this.max;
728
- this.c = [b.subarray(b.length - this.max)];
729
- this.len = this.max;
730
- return;
731
- }
732
- this.c.push(b);
733
- this.len += b.length;
734
- while (this.len > this.max) {
735
- const f = this.c[0]!;
736
- if (f.length <= this.len - this.max) {
737
- this.c.shift();
738
- this.len -= f.length;
739
- this.trunc += f.length;
740
- } else {
741
- const ov = this.len - this.max;
742
- this.c[0] = f.subarray(ov);
743
- this.len -= ov;
744
- this.trunc += ov;
745
- break;
746
- }
747
- }
748
- }
749
- toString() {
750
- const body = Buffer.concat(this.c, this.len).toString("utf-8");
751
- return this.trunc ? `[${this.trunc} bytes truncated]\n${body}` : body;
752
- }
753
- }
754
102
 
755
103
  // ── Context Injection Limits (issue #441) ───────────────────────────────
756
104
  //
757
- // Notice text and behavior mirrored byte-for-byte from the shared-hooks
758
- // Python sub-agent context injection hook. Changing wording there requires
759
- // changing it here too.
105
+ // Main-session context budgets use the shared Python configuration contract.
760
106
  interface ContextInjectionLimits {
761
107
  max_file_bytes: number;
762
108
  max_artifact_bytes: number;
@@ -1001,64 +347,6 @@ function resolveRoot(ctx?: PiExtensionContext): string {
1001
347
  function cacheKey(k: string | null, ctx?: PiExtensionContext): string {
1002
348
  return `${k ?? "default"}::${resolveRoot(ctx)}`;
1003
349
  }
1004
- function splitFM(c: string) {
1005
- const m = c.replace(/^\uFEFF/, "").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
1006
- return m
1007
- ? { fm: m[1] ?? "", body: c.slice(m[0].length) }
1008
- : { fm: "", body: c };
1009
- }
1010
- function stripFM(c: string) {
1011
- return splitFM(c).body.trimStart();
1012
- }
1013
- function parseAgentFM(c: string): AgentConfig {
1014
- const cfg: AgentConfig = { fallbackModels: [] };
1015
- const { fm } = splitFM(c);
1016
- const lines = fm.split(/\r?\n/);
1017
- for (let i = 0; i < lines.length; i++) {
1018
- const m = (lines[i] ?? "").match(/^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/);
1019
- if (!m) continue;
1020
- const k = m[1] ?? "",
1021
- v = m[2] ?? "";
1022
- if (k === "model")
1023
- cfg.model = v.trim().replace(/^["']|["']$/g, "") || undefined;
1024
- else if (k === "thinking")
1025
- cfg.thinking = (v.trim().replace(/^["']|["']$/g, "") || undefined) as
1026
- | string
1027
- | undefined;
1028
- else if (k === "fallbackModels" || k === "fallback_models") {
1029
- if (v.trim()) {
1030
- cfg.fallbackModels = v
1031
- .trim()
1032
- .replace(/^\[|\]$/g, "")
1033
- .split(",")
1034
- .map((s) => s.trim().replace(/^["']|["']$/g, ""))
1035
- .filter(Boolean);
1036
- } else {
1037
- i++;
1038
- while (i < lines.length && /^\s+-\s/.test(lines[i] ?? "")) {
1039
- const item = (lines[i] ?? "")
1040
- .trim()
1041
- .replace(/^-\s+/, "")
1042
- .replace(/^["']|["']$/g, "");
1043
- if (item) cfg.fallbackModels.push(item);
1044
- i++;
1045
- }
1046
- i--;
1047
- }
1048
- } else if (k === "tools") {
1049
- // Pi tool names are lowercase (read, bash, edit, write, grep, find, ls).
1050
- // Normalize to lowercase so mixed-case frontmatter still matches.
1051
- if (v.trim()) {
1052
- cfg.tools = v
1053
- .trim()
1054
- .split(",")
1055
- .map((s) => s.trim().replace(/^["']|["']$/g, "").toLowerCase())
1056
- .filter(Boolean);
1057
- }
1058
- }
1059
- }
1060
- return cfg;
1061
- }
1062
350
 
1063
351
  function contextKey(input?: unknown, ctx?: PiExtensionContext): string | null {
1064
352
  const sessionId =
@@ -1277,7 +565,7 @@ function buildStartupContext(
1277
565
  .join("\n\n");
1278
566
  }
1279
567
 
1280
- function buildContext(root: string, agent: string, key: string | null): string {
568
+ function buildContext(root: string, key: string | null): string {
1281
569
  const dir = readTaskDir(root, key);
1282
570
  if (!dir)
1283
571
  return "No active Trellis task found. Read .trellis/ before proceeding.";
@@ -1285,11 +573,8 @@ function buildContext(root: string, agent: string, key: string | null): string {
1285
573
  const limits = readContextInjectionLimits(root);
1286
574
  const budget = new ContextBudget(limits.max_total_bytes);
1287
575
 
1288
- // 1. Curated spec/research files from {agent}.jsonl (same order, budget
1289
- // processed first, matching Python's get_agent_context()).
1290
- const jsonlName = TRELLIS_AGENT_JSONL[agent] ?? "";
1291
576
  const specBlocks: string[] = [];
1292
- if (jsonlName) {
577
+ for (const jsonlName of ["implement.jsonl", "check.jsonl"]) {
1293
578
  for (const entry of readJsonlEntries(dir, jsonlName)) {
1294
579
  if (entry.type === "directory") continue;
1295
580
  const block = materializeFile(root, entry.file, entry.reason, limits, budget);
@@ -1338,525 +623,13 @@ function buildContext(root: string, agent: string, key: string | null): string {
1338
623
  ].join("\n");
1339
624
  }
1340
625
 
1341
- function normalizeAgent(agent: string | undefined): string {
1342
- const name = agent ?? "trellis-implement";
1343
- return name.startsWith("trellis-") ? name : `trellis-${name}`;
1344
- }
1345
-
1346
- function isTrellisAgent(root: string, agent: string): boolean {
1347
- return existsSync(join(root, ".pi", "agents", `${agent}.md`));
1348
- }
1349
-
1350
- function buildPrompt(
1351
- root: string,
1352
- input: SubagentInput,
1353
- key: string | null,
1354
- ): string {
1355
- const agent = normalizeAgent(input.agent);
1356
- const raw = readText(join(root, ".pi", "agents", `${agent}.md`));
1357
- const def = stripFM(raw);
1358
- const ctx = buildContext(root, agent, key);
1359
- return [
1360
- "## Trellis Agent Definition",
1361
- def || "(missing)",
1362
- "",
1363
- ctx,
1364
- "",
1365
- "## Delegated Task",
1366
- input.prompt ?? "",
1367
- ].join("\n");
1368
- }
1369
-
1370
- // ── Event parsing ─────────────────────────────────────────────────────
1371
- function parseJsonEvent(line: string): JsonObject | null {
1372
- const t = line.trim();
1373
- if (!t) return null;
1374
- const i = t.indexOf("{");
1375
- if (i < 0) return null;
1376
- try {
1377
- const p = JSON.parse(t.slice(i));
1378
- return isObj(p) ? p : null;
1379
- } catch {
1380
- return null;
1381
- }
1382
- }
1383
-
1384
- function applyEvent(r: RunState, evt: JsonObject): boolean {
1385
- const type = typeof evt.type === "string" ? evt.type : "";
1386
- if (!type) return false;
1387
- if (type === "agent_start" || type === "turn_start") {
1388
- r.status = "running";
1389
- r.startedAt ??= Date.now();
1390
- return true;
1391
- }
1392
- if (type === "message_update") {
1393
- const ae = isObj(evt.assistantMessageEvent)
1394
- ? evt.assistantMessageEvent
1395
- : null;
1396
- if (!ae || typeof ae.delta !== "string") return false;
1397
- if (ae.type === "thinking_delta") {
1398
- r.thinkingTail = appendTail(r.thinkingTail, ae.delta, MAX_TAIL);
1399
- return true;
1400
- }
1401
- if (ae.type === "text_delta") {
1402
- r.textTail = appendTail(r.textTail, ae.delta, MAX_TAIL);
1403
- return true;
1404
- }
1405
- return false;
1406
- }
1407
- if (type === "message_end" && isObj(evt.message)) {
1408
- const msg = evt.message;
1409
- if (msg.role !== "assistant") return false;
1410
- r.usage.turns += 1;
1411
- const u = isObj(msg.usage) ? msg.usage : null;
1412
- const cost = isObj(u?.cost) ? u.cost : null;
1413
- r.usage.input += num(u?.input);
1414
- r.usage.output += num(u?.output);
1415
- r.usage.cacheRead += num(u?.cacheRead);
1416
- r.usage.cacheWrite += num(u?.cacheWrite);
1417
- r.usage.cost += num(cost?.total);
1418
- r.usage.ctxTokens = num(u?.totalTokens);
1419
- const thinking = extractThinking(msg.content);
1420
- if (thinking) r.thinkingTail = appendTail("", thinking, MAX_TAIL);
1421
- const text = extractText(msg.content);
1422
- if (text) {
1423
- r.finalText = text;
1424
- r.textTail = appendTail("", text, MAX_TAIL);
1425
- }
1426
- if (typeof msg.model === "string") {
1427
- const parsed = splitModelThinking(msg.model, r.thinking);
1428
- r.model = parsed.model;
1429
- r.thinking = parsed.thinking;
1430
- }
1431
- if (typeof msg.errorMessage === "string") r.errorMessage = msg.errorMessage;
1432
- return true;
1433
- }
1434
- if (type === "tool_execution_start") {
1435
- const id =
1436
- typeof evt.toolCallId === "string"
1437
- ? evt.toolCallId
1438
- : hash(`${Date.now()}`);
1439
- const name = typeof evt.toolName === "string" ? evt.toolName : "tool";
1440
- const args = summarizeToolArgs(name, evt.args);
1441
- const existing = r.tools.findIndex((t) => t.id === id);
1442
- if (existing >= 0)
1443
- r.tools[existing] = { ...r.tools[existing]!, args, status: "running" };
1444
- else
1445
- r.tools.push({
1446
- id,
1447
- name,
1448
- args,
1449
- status: "running",
1450
- startedAt: Date.now(),
1451
- });
1452
- if (r.tools.length > MAX_TOOLS)
1453
- r.tools.splice(0, r.tools.length - MAX_TOOLS);
1454
- return true;
1455
- }
1456
- if (type === "tool_execution_end") {
1457
- const id = typeof evt.toolCallId === "string" ? evt.toolCallId : "";
1458
- const idx = r.tools.findIndex((t) => t.id === id);
1459
- if (idx >= 0)
1460
- r.tools[idx] = {
1461
- ...r.tools[idx]!,
1462
- status: evt.isError ? "failed" : "succeeded",
1463
- finishedAt: Date.now(),
1464
- };
1465
- return true;
1466
- }
1467
- if (type === "agent_end") {
1468
- r.finishedAt = Date.now();
1469
- if (r.status === "running" || r.status === "pending")
1470
- r.status = "succeeded";
1471
- return true;
1472
- }
1473
- return false;
1474
- }
1475
-
1476
- function finalize(r: RunState, fallback: string): string {
1477
- return r.finalText || fallback.trim() || r.stderrTail.trim();
1478
- }
1479
- function formatPiOutput(stdout: string, stderr: string): string {
1480
- let ft = "";
1481
- for (const line of stdout.split(/\r?\n/)) {
1482
- const t = line.trim();
1483
- if (!t) continue;
1484
- try {
1485
- const evt = JSON.parse(t) as JsonObject;
1486
- const msg = isObj(evt.message) ? evt.message : null;
1487
- if (msg?.role === "assistant") {
1488
- const txt = extractText(msg.content);
1489
- if (txt) ft = txt;
1490
- }
1491
- } catch {}
1492
- }
1493
- return ft || stdout || stderr;
1494
- }
1495
-
1496
- // ── Permission-forwarding parent session (issue #610) ───────────
1497
- // Headless `pi --mode json` children have no UI. `@gotgenes/pi-permission-system`
1498
- // forwards `ask` to the parent only when the child env names the *serving*
1499
- // parent session and is marked as a subagent. Three layers, all required:
1500
- // 1. PI_SUBAGENT_PARENT_SESSION — out-of-process convention
1501
- // 2. PI_SUBAGENT_CHILD=1 — stops pi-subagents overwriting that parent id
1502
- // with the child's own session id
1503
- // 3. serving heartbeat id, not stale PI_SESSION_ID (compaction can fork
1504
- // the live id while the permission extension still listens on the
1505
- // activation-time id). Drop inherited PI_SESSION_ID so the child
1506
- // mints its own instead of colliding with the parent.
1507
- let lastLiveSessionId: string | null = null;
1508
-
1509
- function currentSessionId(ctx?: PiExtensionContext): string | null {
1510
- const viaCtx = callStr(
1511
- ctx?.sessionManager?.getSessionId,
1512
- ctx?.sessionManager,
1513
- );
1514
- if (viaCtx) {
1515
- lastLiveSessionId = viaCtx;
1516
- return viaCtx;
1517
- }
1518
- return (
1519
- lastLiveSessionId ??
1520
- str(process.env.PI_SESSION_ID) ??
1521
- str(process.env.PI_SESSIONID)
1522
- );
1523
- }
1524
-
1525
- function piSessionsRoot(): string {
1526
- const sessionDir = str(process.env.PI_CODING_AGENT_SESSION_DIR);
1527
- if (sessionDir) return sessionDir;
1528
- const agentDir = str(process.env.PI_CODING_AGENT_DIR);
1529
- if (agentDir) return join(agentDir, "sessions");
1530
- return join(homedir(), ".pi", "agent", "sessions");
1531
- }
1532
-
1533
- function servingSessionId(): string | null {
1534
- try {
1535
- const dir = join(piSessionsRoot(), "permission-forwarding", "serving");
1536
- let best: { sessionId: string; updatedAt: number } | null = null;
1537
- for (const name of readdirSync(dir)) {
1538
- if (!name.endsWith(".json")) continue;
1539
- let parsed: unknown;
1540
- try {
1541
- parsed = JSON.parse(readFileSync(join(dir, name), "utf-8"));
1542
- } catch {
1543
- continue;
1544
- }
1545
- if (!isObj(parsed) || parsed.pid !== process.pid) continue;
1546
- const sessionId = str(parsed.sessionId);
1547
- const updatedAt =
1548
- typeof parsed.updatedAt === "number" && Number.isFinite(parsed.updatedAt)
1549
- ? parsed.updatedAt
1550
- : 0;
1551
- if (!sessionId) continue;
1552
- if (!best || updatedAt > best.updatedAt) best = { sessionId, updatedAt };
1553
- }
1554
- return best?.sessionId ?? null;
1555
- } catch {
1556
- return null;
1557
- }
1558
- }
1559
-
1560
- function parentSessionIdForChild(ctx?: PiExtensionContext): string | null {
1561
- return servingSessionId() ?? currentSessionId(ctx);
1562
- }
1563
-
1564
- function buildChildEnv(
1565
- key?: string | null,
1566
- parentSessionId?: string | null,
1567
- ): NodeJS.ProcessEnv {
1568
- const childEnv: NodeJS.ProcessEnv = {
1569
- ...process.env,
1570
- TRELLIS_SUBAGENT_CHILD: "1",
1571
- // Stops pi-subagents from overwriting PI_SUBAGENT_PARENT_SESSION with the
1572
- // child's own session id, and lets the permission system treat this process
1573
- // as a subagent (ParentAuthorizer forwarding) even when no parent id is known.
1574
- PI_SUBAGENT_CHILD: "1",
1575
- ...(key ? { TRELLIS_CONTEXT_ID: key } : {}),
1576
- ...(parentSessionId ? { PI_SUBAGENT_PARENT_SESSION: parentSessionId } : {}),
1577
- };
1578
- delete childEnv.PI_SESSION_ID;
1579
- delete childEnv.PI_SESSIONID;
1580
- return childEnv;
1581
- }
1582
-
1583
- // ── runPi: subprocess execution + event processing ───────────────────
1584
- function runPi(
1585
- root: string,
1586
- prompt: string,
1587
- cfg: PiRunConfig,
1588
- state: RunState,
1589
- emit: () => void,
1590
- key?: string | null,
1591
- signal?: AbortSignal,
1592
- parentSessionId?: string | null,
1593
- ): Promise<{ output: string; failed: boolean }> {
1594
- return new Promise((resolve) => {
1595
- if (signal?.aborted) {
1596
- state.status = "cancelled";
1597
- state.errorMessage = "cancelled";
1598
- state.finishedAt = Date.now();
1599
- emit();
1600
- resolve({ output: "cancelled", failed: true });
1601
- return;
1602
- }
1603
- const inv = resolvePiCli();
1604
- const childEnv = buildChildEnv(key, parentSessionId);
1605
- const cli = spawn(inv.command, [...inv.args, ...buildPiArgs(cfg)], {
1606
- cwd: root,
1607
- env: childEnv,
1608
- stdio: ["pipe", "pipe", "pipe"],
1609
- windowsHide: true,
1610
- });
1611
- const stdout = new BBC(MAX_STDOUT);
1612
- const stderr = new BBC(MAX_STDERR);
1613
- let buf = "";
1614
- let settled = false;
1615
- let aborted = false;
1616
- let killTimer: ReturnType<typeof setTimeout> | null = null;
1617
- const abort = () => {
1618
- aborted = true;
1619
- cli.kill();
1620
- killTimer = setTimeout(() => {
1621
- if (!settled && cli.exitCode === null) cli.kill("SIGKILL");
1622
- }, ABORT_KILL_GRACE_MS);
1623
- killTimer?.unref?.();
1624
- };
1625
- const done = (v: { output: string; failed: boolean }) => {
1626
- if (settled) return;
1627
- settled = true;
1628
- if (killTimer) clearTimeout(killTimer);
1629
- signal?.removeEventListener("abort", abort);
1630
- emit();
1631
- resolve(v);
1632
- };
1633
- signal?.addEventListener("abort", abort, { once: true });
1634
- state.status = "running";
1635
- state.startedAt = Date.now();
1636
- emit();
1637
- const processLine = (line: string) => {
1638
- const evt = parseJsonEvent(line);
1639
- if (evt && applyEvent(state, evt)) emit();
1640
- };
1641
- cli.stdout?.on("data", (d: Buffer) => {
1642
- stdout.append(d);
1643
- buf += d.toString("utf-8");
1644
- if (buf.length > MAX_LINE_BUFFER) buf = buf.slice(-MAX_LINE_BUFFER);
1645
- const lines = buf.split(/\r?\n/);
1646
- buf = lines.pop() ?? "";
1647
- for (const l of lines) processLine(l);
1648
- });
1649
- cli.stderr?.on("data", (d: Buffer) => {
1650
- stderr.append(d);
1651
- state.stderrTail = appendTail(
1652
- state.stderrTail,
1653
- d.toString("utf-8"),
1654
- MAX_TAIL,
1655
- );
1656
- });
1657
- cli.stdin?.on("error", (e: Error & { code?: string }) => {
1658
- if (!aborted && e.code !== "EPIPE")
1659
- done({ output: e.message, failed: true });
1660
- });
1661
- cli.on("error", (e) => {
1662
- state.status = aborted ? "cancelled" : "failed";
1663
- state.errorMessage = e instanceof Error ? e.message : String(e);
1664
- state.finishedAt = Date.now();
1665
- done({ output: finalize(state, state.errorMessage), failed: true });
1666
- });
1667
- cli.on("close", (code) => {
1668
- if (buf.trim()) processLine(buf);
1669
- const out = stdout.toString();
1670
- const err = stderr.toString();
1671
- state.stderrTail = appendTail("", err, MAX_TAIL);
1672
- state.finishedAt = Date.now();
1673
- if (aborted) {
1674
- state.status = "cancelled";
1675
- state.errorMessage = "cancelled";
1676
- done({ output: finalize(state, "cancelled"), failed: true });
1677
- return;
1678
- }
1679
- if (code === 0) {
1680
- if (state.status === "pending" || state.status === "running")
1681
- state.status = "succeeded";
1682
- done({
1683
- output: finalize(state, formatPiOutput(out, err)),
1684
- failed: false,
1685
- });
1686
- return;
1687
- }
1688
- state.status = "failed";
1689
- state.errorMessage = err || out || `exit ${code ?? "?"}`;
1690
- done({ output: finalize(state, state.errorMessage), failed: true });
1691
- });
1692
- cli.stdin?.end(prompt);
1693
- });
1694
- }
1695
-
1696
- // ── runSubagent: orchestrate single/parallel/chain via native partial updates ──
1697
- async function runSubagent(
1698
- root: string,
1699
- input: SubagentInput,
1700
- key: string | null,
1701
- signal?: AbortSignal,
1702
- onUpdate?: (r: PiToolResult) => void,
1703
- inheritedThinking?: string,
1704
- inheritedModel?: string,
1705
- ctx?: PiExtensionContext,
1706
- ): Promise<{ output: string; details: ProgressDetails; failed: boolean }> {
1707
- const parentSessionId = parentSessionIdForChild(ctx);
1708
- const agentName = normalizeAgent(input.agent);
1709
- const agentRaw = readText(join(root, ".pi", "agents", `${agentName}.md`));
1710
- const agentCfg = parseAgentFM(agentRaw);
1711
- const runCfg = resolveRunCfg(
1712
- input,
1713
- agentCfg,
1714
- inheritedThinking,
1715
- inheritedModel,
1716
- );
1717
- const mode = input.mode ?? "single";
1718
- const startedAt = Date.now();
1719
- const details: ProgressDetails = {
1720
- kind: "trellis-subagent-progress",
1721
- agent: agentName,
1722
- mode,
1723
- startedAt,
1724
- updatedAt: startedAt,
1725
- final: false,
1726
- runs: [],
1727
- };
1728
- let lastEmit = 0;
1729
- let lastPartialKey = "";
1730
- let closed = false;
1731
- const pushPartial = (force = false) => {
1732
- if (closed || !onUpdate) return;
1733
- const key = progressKey(details);
1734
- if (!force && key === lastPartialKey) return;
1735
- lastPartialKey = key;
1736
- onUpdate({
1737
- // Keep native partial content stable; renderResult owns the visible progress UI.
1738
- content: [{ type: "text", text: "subagent running" }],
1739
- details: cloneProgress(details),
1740
- });
1741
- };
1742
- const emit = (force = false) => {
1743
- const now = Date.now();
1744
- if (!force && now - lastEmit < THROTTLE_MS) return;
1745
- lastEmit = now;
1746
- details.updatedAt = now;
1747
- pushPartial(force);
1748
- };
1749
- const finish = (output: string, failed: boolean) => {
1750
- closed = true;
1751
- details.final = true;
1752
- details.updatedAt = Date.now();
1753
- return { output, details: cloneProgress(details), failed };
1754
- };
1755
-
1756
- try {
1757
- if (mode === "parallel") {
1758
- const prompts = input.prompts ?? (input.prompt ? [input.prompt] : []);
1759
- details.runs = prompts.map((p, i) => {
1760
- const r = newRun(`${agentName}-${i + 1}`, agentName, p);
1761
- applyRunConfig(r, runCfg);
1762
- return r;
1763
- });
1764
- emit(true);
1765
- const results = await Promise.all(
1766
- prompts.map((p, i) =>
1767
- runPi(
1768
- root,
1769
- buildPrompt(root, { ...input, prompt: p }, key),
1770
- runCfg,
1771
- details.runs[i]!,
1772
- emit,
1773
- key,
1774
- signal,
1775
- parentSessionId,
1776
- ),
1777
- ),
1778
- );
1779
- return finish(
1780
- results.map((r) => r.output).join("\n\n---\n\n"),
1781
- results.some((r) => r.failed),
1782
- );
1783
- }
1784
- if (mode === "chain") {
1785
- let prev = "";
1786
- let failed = false;
1787
- for (let i = 0; i < (input.prompts?.length ?? 1); i++) {
1788
- const p = input.prompts?.[i] ?? input.prompt ?? "";
1789
- const rs = newRun(`${agentName}-${i + 1}`, agentName, p, i + 1);
1790
- applyRunConfig(rs, runCfg);
1791
- details.runs.push(rs);
1792
- emit(true);
1793
- const result = await runPi(
1794
- root,
1795
- buildPrompt(
1796
- root,
1797
- {
1798
- ...input,
1799
- prompt: prev ? `${p}\n\nPrevious output:\n${prev}` : p,
1800
- },
1801
- key,
1802
- ),
1803
- runCfg,
1804
- rs,
1805
- emit,
1806
- key,
1807
- signal,
1808
- parentSessionId,
1809
- );
1810
- prev = result.output;
1811
- failed = failed || result.failed;
1812
- if (result.failed) break;
1813
- }
1814
- return finish(prev, failed);
1815
- }
1816
- const rs = newRun(`${agentName}-1`, agentName, input.prompt ?? "");
1817
- applyRunConfig(rs, runCfg);
1818
- details.runs = [rs];
1819
- emit(true);
1820
- const result = await runPi(
1821
- root,
1822
- buildPrompt(root, input, key),
1823
- runCfg,
1824
- rs,
1825
- emit,
1826
- key,
1827
- signal,
1828
- parentSessionId,
1829
- );
1830
- return finish(result.output, result.failed);
1831
- } catch (e) {
1832
- const message = e instanceof Error ? e.message : String(e);
1833
- const r = activeRun(details);
1834
- if (r) {
1835
- r.status = "failed";
1836
- r.errorMessage = message;
1837
- r.finishedAt = Date.now();
1838
- }
1839
- return finish(message, true);
1840
- }
1841
- }
1842
-
1843
626
  // ── Extension ──────────────────────────────────────────────────────────
1844
627
  export default function trellisExtension(pi: {
1845
- registerTool?: (tool: JsonObject) => void;
1846
- registerShortcut?: (
1847
- key: string,
1848
- opts: {
1849
- description?: string;
1850
- handler: (ctx: PiExtensionContext) => unknown;
1851
- },
1852
- ) => void;
1853
628
  on?: (
1854
629
  event: string,
1855
630
  handler: (event: unknown, ctx?: PiExtensionContext) => unknown,
1856
631
  ) => void;
1857
- getThinkingLevel?: () => string;
1858
632
  }): void {
1859
- if (process.env.TRELLIS_SUBAGENT_CHILD === "1") return;
1860
633
  // Process-level fallback; call sites with a session context re-resolve via
1861
634
  // resolveRoot(ctx) so the active project (session cwd) is used instead.
1862
635
  const root = resolveRoot();
@@ -1920,183 +693,6 @@ export default function trellisExtension(pi: {
1920
693
  // keeps following the previous project's instructions.
1921
694
  const lastPersistedRoot = new Map<string, string>();
1922
695
 
1923
- // Toggle only the latest subagent native card; do not use Pi global tool expansion.
1924
- const toggleDetail = (ctx: PiExtensionContext) => {
1925
- const id = activeSubagentToolCallId;
1926
- const card = id ? nativeCards.get(id) : undefined;
1927
- if (!card) {
1928
- ctx.ui?.notify?.("No subagent card to toggle yet.", "warning");
1929
- return;
1930
- }
1931
- card.state.localExpanded = card.state.localExpanded !== true;
1932
- card.invalidate();
1933
- };
1934
-
1935
- pi.registerShortcut?.("alt+o", {
1936
- description: "Toggle latest subagent card details",
1937
- handler: async (ctx: PiExtensionContext) => toggleDetail(ctx),
1938
- });
1939
-
1940
- // Tool registration
1941
- pi.registerTool?.({
1942
- name: "trellis_subagent",
1943
- label: "Trellis Subagent",
1944
- description: "Run a Trellis project sub-agent with active task context.",
1945
- promptSnippet:
1946
- 'Sub-agent dispatch protocol (Trellis): your dispatch prompt MUST start with one line "Active task: <task path from `task.py current`>" before any other instructions.',
1947
- promptGuidelines: [
1948
- 'Use subagent for task delegation. Your dispatch prompt MUST start with "Active task: <task path from `task.py current`>".',
1949
- ],
1950
- parameters: {
1951
- type: "object",
1952
- properties: {
1953
- agent: {
1954
- type: "string",
1955
- description:
1956
- "Agent name, such as trellis-implement or trellis-check.",
1957
- },
1958
- prompt: {
1959
- type: "string",
1960
- description: "Task prompt for the sub-agent.",
1961
- },
1962
- mode: { type: "string", enum: ["single", "parallel", "chain"] },
1963
- prompts: {
1964
- type: "array",
1965
- items: { type: "string" },
1966
- maxItems: MAX_PARALLEL_PROMPTS,
1967
- },
1968
- model: {
1969
- type: "string",
1970
- description:
1971
- "Optional Pi model override for the child sub-agent process.",
1972
- },
1973
- thinking: {
1974
- type: "string",
1975
- description:
1976
- "Optional Pi thinking level override for the child sub-agent process.",
1977
- enum: ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
1978
- },
1979
- },
1980
- },
1981
- execute: async (
1982
- id: string,
1983
- input: SubagentInput,
1984
- signal?: AbortSignal,
1985
- onUpdate?: (r: PiToolResult) => void,
1986
- ctx?: PiExtensionContext,
1987
- ) => {
1988
- activeSubagentToolCallId = id;
1989
- const root = resolveRoot(ctx);
1990
- const agentName = normalizeAgent(input.agent);
1991
- if (!isTrellisAgent(root, agentName)) {
1992
- return {
1993
- content: [
1994
- {
1995
- type: "text",
1996
- text:
1997
- "`trellis_subagent` is only for Trellis workflow agents with a definition file in .pi/agents/.\n\n" +
1998
- `No definition found for: ${agentName}\n\n` +
1999
- "For general-purpose sub-agents, use one of these community tools:\n" +
2000
- "- `subagent` tool from npm:pi-subagents (nicobailon/pi-subagents)\n" +
2001
- "- `Agent` tool from npm:@tintinweb/pi-subagents\n\n" +
2002
- "If neither is installed, ask the user to either:\n" +
2003
- `- Create .pi/agents/${agentName}.md for your custom Trellis agent\n` +
2004
- "- Install a community subagent package: pi install -l npm:@tintinweb/pi-subagents",
2005
- },
2006
- ],
2007
- details: { agent: agentName, error: "not a trellis workflow agent" },
2008
- };
2009
- }
2010
- const mode = input.mode ?? "single";
2011
- const prompt = input.prompt?.trim();
2012
- const prompts = input.prompts?.map((p) => p.trim()).filter(Boolean);
2013
- if (mode === "single" && !prompt)
2014
- throw new Error("subagent prompt is required for single mode");
2015
- if (
2016
- (mode === "parallel" || mode === "chain") &&
2017
- !prompt &&
2018
- !prompts?.length
2019
- )
2020
- throw new Error(
2021
- "subagent prompt or prompts are required for parallel/chain mode",
2022
- );
2023
- if (
2024
- mode === "parallel" &&
2025
- prompts &&
2026
- prompts.length > MAX_PARALLEL_PROMPTS
2027
- )
2028
- throw new Error(
2029
- `subagent parallel mode supports at most ${MAX_PARALLEL_PROMPTS} prompts`,
2030
- );
2031
- const cleanInput: SubagentInput = {
2032
- ...input,
2033
- prompt,
2034
- prompts: prompts?.length ? prompts : undefined,
2035
- };
2036
- const key = getKey(cleanInput, ctx);
2037
- const inheritedThinking = pi.getThinkingLevel?.();
2038
- const inheritedModel = contextModelRef(ctx);
2039
- const result = await runSubagent(
2040
- root,
2041
- cleanInput,
2042
- key,
2043
- signal,
2044
- onUpdate,
2045
- inheritedThinking,
2046
- inheritedModel,
2047
- ctx,
2048
- );
2049
- return {
2050
- content: [{ type: "text", text: result.output }],
2051
- details: result.details,
2052
- };
2053
- },
2054
- // Hide the call renderer so the native card only shows result/progress once.
2055
- renderCall: () => ({
2056
- render() {
2057
- return [];
2058
- },
2059
- invalidate() {},
2060
- }),
2061
- renderResult: (
2062
- result: PiToolResult,
2063
- _opts?: { expanded?: boolean; isPartial?: boolean },
2064
- _theme?: unknown,
2065
- context?: unknown,
2066
- ) => {
2067
- const ctxObj = isObj(context) ? context : null;
2068
- const toolCallId = str(ctxObj?.toolCallId);
2069
- const state = isObj(ctxObj?.state) ? (ctxObj.state as JsonObject) : null;
2070
- const invalidate =
2071
- typeof ctxObj?.invalidate === "function"
2072
- ? (ctxObj.invalidate as () => void)
2073
- : null;
2074
- const isProgress =
2075
- isObj(result.details) &&
2076
- result.details.kind === "trellis-subagent-progress";
2077
- if (toolCallId && state && invalidate) {
2078
- const updatedAt = isProgress
2079
- ? (result.details as ProgressDetails).updatedAt
2080
- : Date.now();
2081
- rememberNativeCard(toolCallId, { state, invalidate, updatedAt });
2082
- }
2083
- return {
2084
- render(w: number) {
2085
- if (isProgress) {
2086
- const expanded = state?.localExpanded === true;
2087
- return renderProgressCard(
2088
- result.details as ProgressDetails,
2089
- expanded,
2090
- w,
2091
- );
2092
- }
2093
- return [trunc(result.content?.[0]?.text ?? "(no output)", w)];
2094
- },
2095
- invalidate() {},
2096
- };
2097
- },
2098
- });
2099
-
2100
696
  // Events
2101
697
  pi.on?.("session_start", (event, ctx) => {
2102
698
  getKey(event, ctx);
@@ -2105,10 +701,6 @@ export default function trellisExtension(pi: {
2105
701
  "info",
2106
702
  );
2107
703
  });
2108
- pi.on?.("session_shutdown", () => {
2109
- nativeCards.clear();
2110
- activeSubagentToolCallId = null;
2111
- });
2112
704
  pi.on?.("tool_call", (event, ctx) => {
2113
705
  const k = getKey(event, ctx);
2114
706
  const ev = event as { toolName?: string; input?: JsonObject };
@@ -2120,22 +712,6 @@ export default function trellisExtension(pi: {
2120
712
  )
2121
713
  ev.input.command = `export TRELLIS_CONTEXT_ID=${shellQuote(k)}; ${ev.input.command}`;
2122
714
  });
2123
- // Preserve progress details from execute(); mark failed subagent results through
2124
- // the official tool_result patch hook instead of throwing away renderer details.
2125
- pi.on?.("tool_result", (event) => {
2126
- const ev = event as { toolName?: string; details?: unknown };
2127
- if (
2128
- ev.toolName === "trellis_subagent" &&
2129
- isObj(ev.details) &&
2130
- ev.details.kind === "trellis-subagent-progress" &&
2131
- Array.isArray(ev.details.runs) &&
2132
- ev.details.runs.some(
2133
- (r) => isObj(r) && (r.status === "failed" || r.status === "cancelled"),
2134
- )
2135
- )
2136
- return { isError: true };
2137
- return undefined;
2138
- });
2139
715
  pi.on?.("before_agent_start", (event, ctx) => {
2140
716
  const k = getKey(event, ctx);
2141
717
  const key = cacheKey(k, ctx);
@@ -2145,7 +721,7 @@ export default function trellisExtension(pi: {
2145
721
  const startup = getStartupCtx(k, turn, ctx);
2146
722
  // Task context is snapshotted into systemPrompt once; later on-disk
2147
723
  // changes are delivered as persisted messages so the prefix stays stable.
2148
- const freshTaskCtx = buildContext(root, "trellis-implement", k);
724
+ const freshTaskCtx = buildContext(root, k);
2149
725
  let taskCtx = taskCtxSnapshot.get(key);
2150
726
  if (taskCtx === undefined) {
2151
727
  taskCtx = freshTaskCtx;