@asterxsk/kiln 0.1.0 → 0.2.0

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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,779 +1,779 @@
1
- /**
2
- * Subagents — spawn background subagents on one of three backends
3
- * (pi, Claude Code, Codex) unified behind a single Effect service interface.
4
- *
5
- * Tools (for the parent LLM):
6
- * - subagent_spawn: fire-and-forget spawn (prompt, title, agent, working_dir,
7
- * model, reasoning_effort). Max 4 running at once across all backends.
8
- * - subagent_wait: block until the listed subagents settle, return results.
9
- * - subagent_cancel: stop one or more running subagents.
10
- * - subagent_check: peek at a subagent's status and recent activity.
11
- * - subagent_list: list all subagents.
12
- *
13
- * Unawaited subagents queue their result as a follow-up message when they
14
- * settle. `/subagents` opens a picker + full interactive takeover view.
15
- *
16
- * Architecture: Effect v4 generators throughout (backends -> manager ->
17
- * runtime); this file is the async boundary where tool handlers run effects
18
- * against one shared ManagedRuntime. All three backends are real: pi runs
19
- * in-process SDK sessions, claude drives the Claude Agent SDK, codex speaks
20
- * JSON-RPC to a scoped `codex app-server` process.
21
- */
22
-
23
- import * as fs from "node:fs";
24
- import * as path from "node:path";
25
- import { StringEnum } from "@earendil-works/pi-ai";
26
- import type {
27
- ExtensionAPI,
28
- ExtensionCommandContext,
29
- ExtensionContext,
30
- ExtensionUIContext,
31
- } from "@earendil-works/pi-coding-agent";
32
- import {
33
- DEFAULT_MAX_BYTES,
34
- DEFAULT_MAX_LINES,
35
- formatSize,
36
- getAgentDir,
37
- getMarkdownTheme,
38
- ProjectTrustStore,
39
- truncateHead,
40
- } from "@earendil-works/pi-coding-agent";
41
- import { Markdown, Text } from "@earendil-works/pi-tui";
42
- import { Type } from "typebox";
43
- import { deriveBtwTitle, isModelVisible } from "./src/by-the-way.ts";
44
- import {
45
- BACKEND_NAMES,
46
- formatElapsed,
47
- latestText,
48
- REASONING_EFFORTS,
49
- type SubagentSnapshot,
50
- } from "./src/domain.ts";
51
- import {
52
- formatActivityStatus,
53
- formatContextUtilization,
54
- } from "./src/format.ts";
55
- import { SubagentManager, type SubagentManagerShape } from "./src/manager.ts";
56
- import {
57
- buildSubagentResultMessage,
58
- buildSubagentSpawnResult,
59
- SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS,
60
- SUBAGENT_CANCEL_TOOL_DESCRIPTION,
61
- SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS,
62
- SUBAGENT_CHECK_TOOL_DESCRIPTION,
63
- SUBAGENT_LIST_TOOL_DESCRIPTION,
64
- SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS,
65
- SUBAGENT_SPAWN_PROMPT_GUIDELINES,
66
- SUBAGENT_SPAWN_PROMPT_SNIPPET,
67
- SUBAGENT_SPAWN_TOOL_DESCRIPTION,
68
- SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS,
69
- SUBAGENT_WAIT_TOOL_DESCRIPTION,
70
- } from "./src/prompt.ts";
71
- import { createDeferredResultDelivery } from "./src/result-delivery.ts";
72
- import {
73
- createSubagentRuntime,
74
- runTool,
75
- type SubagentRuntime,
76
- } from "./src/runtime.ts";
77
- import { openSubagentPicker, openSubagentTakeover } from "./src/ui/takeover.ts";
78
-
79
- const SUBAGENT_OUTPUT_MAX_BYTES = 24 * 1024;
80
- const WAIT_OUTPUT_MAX_BYTES = 48 * 1024;
81
- const WAIT_PER_AGENT_MAX_BYTES = 16 * 1024;
82
-
83
- interface BtwResultData {
84
- readonly id: string;
85
- readonly title: string;
86
- readonly status: SubagentSnapshot["status"];
87
- readonly errorText?: string;
88
- readonly prompt: string;
89
- readonly answer: string;
90
- readonly sessionFilePath?: string;
91
- }
92
-
93
- function describeSubagent(snap: SubagentSnapshot) {
94
- const details = [
95
- `${snap.backend}: ${snap.meta.modelLabel ?? "?"}`,
96
- formatContextUtilization(snap.usage),
97
- formatElapsed(snap),
98
- snap.cwd,
99
- ].filter(Boolean);
100
- return `${snap.id} [${snap.status}] "${snap.title}" (${details.join(", ")})`;
101
- }
102
-
103
- function truncatedOutput(
104
- snap: SubagentSnapshot,
105
- maxBytes = SUBAGENT_OUTPUT_MAX_BYTES,
106
- ): string {
107
- const output = snap.finalText || "(no output)";
108
- const truncation = truncateHead(output, {
109
- maxBytes: Math.min(maxBytes, DEFAULT_MAX_BYTES),
110
- maxLines: Math.min(600, DEFAULT_MAX_LINES),
111
- });
112
- let text = truncation.content;
113
- if (truncation.truncated) {
114
- text += `\n\n[Output truncated: ${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)} shown. Full transcript in session file: ${snap.meta.sessionFilePath ?? "?"}]`;
115
- }
116
- return text;
117
- }
118
-
119
- /**
120
- * Same-directory children inherit the live parent decision. An alternate cwd
121
- * is trusted only when pi's persisted trust store explicitly trusts it (or a
122
- * containing directory); unreadable/invalid trust data fails closed.
123
- */
124
- function resolveChildProjectTrust(options: {
125
- parentCwd: string;
126
- childCwd: string;
127
- parentTrusted: boolean;
128
- }) {
129
- if (path.resolve(options.childCwd) === path.resolve(options.parentCwd)) {
130
- return options.parentTrusted;
131
- }
132
- try {
133
- const trustStore = new ProjectTrustStore(getAgentDir());
134
- return trustStore.get(options.childCwd) === true;
135
- } catch {
136
- return false;
137
- }
138
- }
139
-
140
- const RESULT_PREVIEW_LINES = 10;
141
-
142
- /** Tool call line: bold-white tool name, 2-space indent (Box adds 1 + Text 1). */
143
- function renderToolCall(name: string, theme: any): Text {
144
- return new Text(theme.fg("toolTitle", theme.bold(name)), 1, 0);
145
- }
146
-
147
- /** Tool result: grey text at 2-space indent, collapsed to a short preview. */
148
- function renderToolResult(result: any, theme: any): Text {
149
- const text = (result?.content ?? [])
150
- .filter((c: any) => c?.type === "text" && typeof c?.text === "string")
151
- .map((c: any) => c.text)
152
- .join("\n");
153
- if (!text) return new Text("", 1, 0);
154
- const lines = text.split("\n");
155
- const preview = lines.slice(0, RESULT_PREVIEW_LINES);
156
- let out = theme.fg("toolOutput", preview.join("\n"));
157
- if (lines.length > RESULT_PREVIEW_LINES) {
158
- out += theme.fg("dim", `\n... (${lines.length - RESULT_PREVIEW_LINES} more lines)`);
159
- }
160
- return new Text(out, 1, 0);
161
- }
162
-
163
- export default function (pi: ExtensionAPI) {
164
- let runtime: SubagentRuntime | undefined;
165
- let managerPromise: Promise<SubagentManagerShape> | undefined;
166
- let sessionContext: ExtensionContext | undefined;
167
- let ui: ExtensionUIContext | undefined;
168
- let unsubStatus: (() => void) | undefined;
169
- const resultDelivery = createDeferredResultDelivery<SubagentSnapshot>();
170
-
171
- const getRuntime = () => (runtime ??= createSubagentRuntime());
172
-
173
- /** Resolve the manager service once per runtime and wire the extension hooks. */
174
- const getManager = () => {
175
- managerPromise ??= getRuntime()
176
- .runPromise(SubagentManager)
177
- .then((manager) => {
178
- manager.view.setOnSettled(onSettled);
179
- unsubStatus?.();
180
- unsubStatus = manager.view.subscribe(() => updateStatus(manager));
181
- updateStatus(manager);
182
- return manager;
183
- });
184
- return managerPromise;
185
- };
186
-
187
- const updateStatus = (manager: SubagentManagerShape) => {
188
- if (!ui) return;
189
- const subs = manager.view.list();
190
- if (subs.length === 0) {
191
- ui.setStatus("subagents", undefined);
192
- return;
193
- }
194
- const running = subs.filter((snap) => snap.status === "running").length;
195
- const failed = subs.filter((snap) => snap.status === "error").length;
196
- const done = subs.length - running - failed;
197
- ui.setStatus(
198
- "subagents",
199
- formatActivityStatus(ui.theme, { running, done, failed }),
200
- );
201
- };
202
-
203
- const deliverResult = (snap: SubagentSnapshot) => {
204
- pi.sendMessage(
205
- {
206
- customType: "subagent-result",
207
- content: buildSubagentResultMessage({
208
- id: snap.id,
209
- title: snap.title,
210
- status: snap.status,
211
- errorText: snap.errorText,
212
- output: truncatedOutput(snap),
213
- }),
214
- display: true,
215
- details: { id: snap.id, title: snap.title, status: snap.status },
216
- },
217
- { deliverAs: "followUp", triggerTurn: true },
218
- );
219
- };
220
-
221
- const flushResults = () => {
222
- for (const snap of resultDelivery.drain()) deliverResult(snap);
223
- };
224
-
225
- const deliverBtwResult = (snap: SubagentSnapshot) => {
226
- // appendEntry is a synchronous SessionManager operation and emits an
227
- // entry_appended event, so it is safe while the parent is streaming and
228
- // never enters the model's context or follow-up queue.
229
- pi.appendEntry<BtwResultData>("btw-result", {
230
- id: snap.id,
231
- title: snap.title,
232
- status: snap.status,
233
- errorText: snap.errorText,
234
- prompt: snap.prompt,
235
- answer: truncatedOutput(snap),
236
- sessionFilePath: snap.meta.sessionFilePath,
237
- });
238
- ui?.notify(
239
- snap.status === "error"
240
- ? `by the way “${snap.title}” failed — reopen it with /subagents`
241
- : `by the way “${snap.title}” answered — reopen it with /subagents`,
242
- snap.status === "error" ? "error" : "info",
243
- );
244
- };
245
-
246
- const onSettled = (snap: SubagentSnapshot, consumed: boolean) => {
247
- // A shutdown can settle children while disposing their scopes. Never
248
- // append into a session whose extension runtime is already closing.
249
- if (!sessionContext) return;
250
- if (snap.origin === "btw") {
251
- deliverBtwResult({ ...snap, meta: { ...snap.meta } });
252
- return;
253
- }
254
- if (consumed) {
255
- resultDelivery.consume([snap.id]);
256
- return;
257
- }
258
- // Keep the result retractable while the parent is working. A later
259
- // subagent_wait can consume it before agent_settled flushes follow-ups.
260
- // Defer a copy: the live snapshot keeps mutating if the subagent is
261
- // restarted before the deferred result flushes.
262
- resultDelivery.defer({ ...snap, meta: { ...snap.meta } });
263
- if (sessionContext?.isIdle()) flushResults();
264
- };
265
-
266
- pi.on("session_start", (_event, ctx) => {
267
- sessionContext = ctx;
268
- if (ctx.hasUI) ui = ctx.ui;
269
- });
270
-
271
- pi.on("agent_settled", flushResults);
272
-
273
- pi.on("session_shutdown", async () => {
274
- sessionContext = undefined;
275
- resultDelivery.clear();
276
- unsubStatus?.();
277
- unsubStatus = undefined;
278
- ui?.setStatus("subagents", undefined);
279
- ui = undefined;
280
- const closing = runtime;
281
- runtime = undefined;
282
- managerPromise = undefined;
283
- // Disposing the runtime runs the manager finalizer, which tears down all
284
- // subagent scopes (and, later, their real child processes).
285
- await closing?.dispose();
286
- });
287
-
288
- // --- Tools -------------------------------------------------------------
289
-
290
- pi.registerTool({
291
- name: "subagent_spawn",
292
- label: "Spawn Subagent",
293
- renderCall: (_args: any, theme: any) => renderToolCall("subagent_spawn", theme),
294
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
295
- description: SUBAGENT_SPAWN_TOOL_DESCRIPTION,
296
- promptSnippet: SUBAGENT_SPAWN_PROMPT_SNIPPET,
297
- promptGuidelines: SUBAGENT_SPAWN_PROMPT_GUIDELINES,
298
- parameters: Type.Object({
299
- prompt: Type.String({
300
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.prompt,
301
- }),
302
- name: Type.String({
303
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.name,
304
- }),
305
- harness: StringEnum(BACKEND_NAMES, {
306
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.harness,
307
- }),
308
- working_dir: Type.Optional(
309
- Type.String({
310
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.workingDir,
311
- }),
312
- ),
313
- model: Type.Optional(
314
- Type.String({
315
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.model,
316
- }),
317
- ),
318
- reasoning_effort: Type.Optional(
319
- StringEnum(REASONING_EFFORTS, {
320
- description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.reasoningEffort,
321
- }),
322
- ),
323
- }),
324
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
325
- const manager = await getManager();
326
- const harness = params.harness;
327
-
328
- const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
329
- if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
330
- throw new Error(`working_dir is not a directory: ${cwd}`);
331
- }
332
-
333
- const title = params.name.trim().slice(0, 160) || "subagent";
334
- const snap = await runTool(
335
- getRuntime(),
336
- manager.spawn(harness, {
337
- prompt: params.prompt,
338
- title,
339
- cwd,
340
- model: params.model,
341
- reasoningEffort: params.reasoning_effort,
342
- parent: {
343
- parentCwd: ctx.cwd,
344
- projectTrusted: resolveChildProjectTrust({
345
- parentCwd: ctx.cwd,
346
- childCwd: cwd,
347
- parentTrusted: ctx.isProjectTrusted(),
348
- }),
349
- inheritedModel: ctx.model
350
- ? { provider: ctx.model.provider, id: ctx.model.id }
351
- : undefined,
352
- inheritedThinkingLevel: pi.getThinkingLevel(),
353
- modelRegistry: ctx.modelRegistry,
354
- },
355
- }),
356
- { signal, interruptMessage: "Subagent spawn aborted." },
357
- );
358
-
359
- return {
360
- content: [
361
- {
362
- type: "text",
363
- text: buildSubagentSpawnResult({
364
- id: snap.id,
365
- title: snap.title,
366
- harness,
367
- modelLabel: snap.meta.modelLabel ?? "?",
368
- cwd,
369
- }),
370
- },
371
- ],
372
- details: {
373
- id: snap.id,
374
- title: snap.title,
375
- cwd,
376
- harness,
377
- model: snap.meta.modelLabel,
378
- },
379
- };
380
- },
381
- });
382
-
383
- pi.registerTool({
384
- name: "subagent_wait",
385
- label: "Wait for Subagents",
386
- renderCall: (_args: any, theme: any) => renderToolCall("subagent_wait", theme),
387
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
388
- description: SUBAGENT_WAIT_TOOL_DESCRIPTION,
389
- parameters: Type.Object({
390
- ids: Type.Array(Type.String(), {
391
- maxItems: 64,
392
- description: SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS.ids,
393
- }),
394
- }),
395
- async execute(_toolCallId, params, signal, onUpdate) {
396
- const manager = await getManager();
397
- const ids = [...new Set(params.ids)];
398
- if (ids.length === 0)
399
- throw new Error("Provide at least one subagent id.");
400
- const known = manager.view
401
- .list()
402
- .filter(isModelVisible)
403
- .map((snap) => snap.id);
404
- const unknown = ids.filter((id) => {
405
- const snap = manager.view.get(id);
406
- return !snap || !isModelVisible(snap);
407
- });
408
- if (unknown.length > 0) {
409
- throw new Error(
410
- `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
411
- );
412
- }
413
-
414
- await runTool(
415
- getRuntime(),
416
- manager.waitFor(ids, (pending) => {
417
- onUpdate?.({
418
- content: [
419
- { type: "text", text: `Waiting for ${pending.join(", ")}...` },
420
- ],
421
- details: { pending },
422
- });
423
- }),
424
- { signal, interruptMessage: "Wait aborted. Subagents keep running." },
425
- );
426
-
427
- // Settlement may have happened before this wait began. Remove any
428
- // deferred automatic delivery now that the tool is returning the result.
429
- resultDelivery.consume(ids);
430
-
431
- const sections: string[] = [];
432
- let remainingBytes = WAIT_OUTPUT_MAX_BYTES;
433
- for (const id of ids) {
434
- const snap = manager.view.get(id);
435
- if (!snap) {
436
- sections.push(`## ${id}\n\n(no longer tracked)`);
437
- continue;
438
- }
439
- const verb = snap.status === "error" ? "failed" : "finished";
440
- let section = `## ${snap.id} "${snap.title}" ${verb}`;
441
- if (snap.errorText) section += `\nError: ${snap.errorText}`;
442
- const headerBytes = Buffer.byteLength(section, "utf8") + 2;
443
- const outputBudget = Math.max(
444
- 512,
445
- Math.min(WAIT_PER_AGENT_MAX_BYTES, remainingBytes - headerBytes),
446
- );
447
- section += `\n\n${truncatedOutput(snap, outputBudget)}`;
448
- const sectionBytes = Buffer.byteLength(section, "utf8");
449
- if (sectionBytes > remainingBytes) {
450
- sections.push(
451
- `## ${snap.id} "${snap.title}"\n\n[omitted: total wait output limit reached]`,
452
- );
453
- break;
454
- }
455
- sections.push(section);
456
- remainingBytes -= sectionBytes;
457
- }
458
-
459
- const combined = sections.join("\n\n---\n\n");
460
- const bounded = truncateHead(combined, {
461
- maxBytes: WAIT_OUTPUT_MAX_BYTES - 128,
462
- maxLines: DEFAULT_MAX_LINES,
463
- });
464
- const text = bounded.truncated
465
- ? `${bounded.content}\n\n[wait output truncated at the total output limit]`
466
- : bounded.content;
467
- return {
468
- content: [{ type: "text", text }],
469
- details: {
470
- results: ids.map((id) => {
471
- const snap = manager.view.get(id);
472
- return { id, title: snap?.title, status: snap?.status };
473
- }),
474
- },
475
- };
476
- },
477
- });
478
-
479
- pi.registerTool({
480
- name: "subagent_cancel",
481
- label: "Cancel Subagents",
482
- renderCall: (_args: any, theme: any) => renderToolCall("subagent_cancel", theme),
483
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
484
- description: SUBAGENT_CANCEL_TOOL_DESCRIPTION,
485
- parameters: Type.Object({
486
- ids: Type.Array(Type.String(), {
487
- description: SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS.ids,
488
- }),
489
- }),
490
- async execute(_toolCallId, params, signal) {
491
- const manager = await getManager();
492
- const ids = [...new Set(params.ids)];
493
- if (ids.length === 0)
494
- throw new Error("Provide at least one subagent id.");
495
-
496
- const known = manager.view
497
- .list()
498
- .filter(isModelVisible)
499
- .map((snap) => snap.id);
500
- const unknown = ids.filter((id) => {
501
- const snap = manager.view.get(id);
502
- return !snap || !isModelVisible(snap);
503
- });
504
- if (unknown.length > 0) {
505
- throw new Error(
506
- `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
507
- );
508
- }
509
-
510
- const report = await runTool(getRuntime(), manager.cancel(ids), {
511
- signal,
512
- interruptMessage: "Subagent cancellation aborted.",
513
- });
514
-
515
- const lines = report.map((entry) =>
516
- entry.cancelled
517
- ? `Cancelled ${entry.id} "${entry.title}".`
518
- : `${entry.id} "${entry.title}" was already ${entry.status}.`,
519
- );
520
-
521
- return {
522
- content: [{ type: "text", text: lines.join("\n") }],
523
- details: {
524
- results: report.map((entry) => ({
525
- id: entry.id,
526
- title: entry.title,
527
- status: entry.status,
528
- })),
529
- },
530
- };
531
- },
532
- });
533
-
534
- pi.registerTool({
535
- name: "subagent_check",
536
- label: "Check Subagent",
537
- renderCall: (_args: any, theme: any) => renderToolCall("subagent_check", theme),
538
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
539
- description: SUBAGENT_CHECK_TOOL_DESCRIPTION,
540
- parameters: Type.Object({
541
- id: Type.String({
542
- description: SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS.id,
543
- }),
544
- }),
545
- async execute(_toolCallId, params) {
546
- const manager = await getManager();
547
- const snap = manager.view.get(params.id);
548
- if (!snap || !isModelVisible(snap)) {
549
- const known = manager.view
550
- .list()
551
- .filter(isModelVisible)
552
- .map((s) => s.id);
553
- throw new Error(
554
- `Unknown subagent id "${params.id}". Known: ${known.join(", ") || "none"}.`,
555
- );
556
- }
557
-
558
- let text = `${describeSubagent(snap)}\nTurns: ${snap.turns}`;
559
- if (snap.errorText) text += `\nError: ${snap.errorText}`;
560
-
561
- const output = latestText(snap);
562
- if (output) {
563
- const preview = truncateHead(output, { maxBytes: 2048, maxLines: 20 });
564
- text += `\n\nLatest output:\n${preview.content}`;
565
- if (preview.truncated) text += "\n[...]";
566
- } else if (snap.status === "running") {
567
- text += "\n\n(no text output yet)";
568
- }
569
-
570
- return {
571
- content: [{ type: "text", text }],
572
- details: { id: snap.id, status: snap.status, turns: snap.turns },
573
- };
574
- },
575
- });
576
-
577
- pi.registerTool({
578
- name: "subagent_list",
579
- label: "List Subagents",
580
- renderCall: (_args: any, theme: any) => renderToolCall("subagent_list", theme),
581
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
582
- description: SUBAGENT_LIST_TOOL_DESCRIPTION,
583
- parameters: Type.Object({}),
584
- async execute() {
585
- const manager = await getManager();
586
- const subs = manager.view.list().filter(isModelVisible);
587
- const text =
588
- subs.length === 0
589
- ? "No subagents."
590
- : subs.map((snap) => describeSubagent(snap)).join("\n");
591
- return {
592
- content: [{ type: "text", text }],
593
- details: {
594
- subagents: subs.map((snap) => ({
595
- id: snap.id,
596
- title: snap.title,
597
- harness: snap.backend,
598
- status: snap.status,
599
- })),
600
- },
601
- };
602
- },
603
- });
604
-
605
- // --- Result message rendering ------------------------------------------
606
-
607
- pi.registerMessageRenderer(
608
- "subagent-result",
609
- (message, { expanded }, theme) => {
610
- const details = (message.details ?? {}) as {
611
- id?: string;
612
- title?: string;
613
- status?: string;
614
- };
615
- const failed = details.status === "error";
616
- const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
617
- const header =
618
- `${icon} ` +
619
- theme.fg("accent", theme.bold(`subagent ${details.id ?? "?"}`)) +
620
- theme.fg(
621
- "muted",
622
- ` · ${details.title ?? ""} · ${failed ? "failed" : "finished"}`,
623
- );
624
-
625
- const content =
626
- typeof message.content === "string" ? message.content : "";
627
- // Remove only the summary line. The following Error line (when present)
628
- // is part of the actual result and must remain visible.
629
- const body = content.split("\n").slice(1).join("\n").trim();
630
-
631
- if (expanded) {
632
- const md = new Markdown(`${body}`, 0, 0, getMarkdownTheme());
633
- const container = new Text(header, 0, 0);
634
- return {
635
- render: (width: number) => [
636
- ...container.render(width),
637
- ...md.render(width),
638
- ],
639
- invalidate: () => {
640
- container.invalidate();
641
- md.invalidate();
642
- },
643
- };
644
- }
645
-
646
- const previewLines = body.split("\n").slice(0, 8);
647
- let text = ` ${header}`;
648
- for (const line of previewLines)
649
- text += `\n ${theme.fg("toolOutput", line)}`;
650
- if (body.split("\n").length > 8)
651
- text += `\n ${theme.fg("dim", "... (ctrl+o to expand)")}`;
652
- return new Text(text, 0, 0);
653
- },
654
- );
655
-
656
- pi.registerEntryRenderer<BtwResultData>(
657
- "btw-result",
658
- (entry, { expanded }, theme) => {
659
- const data = entry.data;
660
- const failed = data?.status === "error";
661
- const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
662
- const header =
663
- `${icon} ` +
664
- theme.fg("accent", theme.bold(`by the way · ${data?.title ?? "?"}`)) +
665
- theme.fg(
666
- "muted",
667
- ` · ${failed ? "failed" : "answered"} · ${data?.id ?? "?"}`,
668
- );
669
- const body = [
670
- data?.errorText ? `Error: ${data.errorText}` : "",
671
- data?.answer ?? "(no answer)",
672
- ]
673
- .filter(Boolean)
674
- .join("\n\n");
675
-
676
- if (expanded) {
677
- const md = new Markdown(body, 0, 0, getMarkdownTheme());
678
- const container = new Text(header, 0, 0);
679
- return {
680
- render: (width: number) => [
681
- ...container.render(width),
682
- ...md.render(width),
683
- ],
684
- invalidate: () => {
685
- container.invalidate();
686
- md.invalidate();
687
- },
688
- };
689
- }
690
-
691
- const lines = body.split("\n");
692
- let text = ` ${header}`;
693
- for (const line of lines.slice(0, 8))
694
- text += `\n ${theme.fg("toolOutput", line)}`;
695
- if (lines.length > 8)
696
- text += `\n ${theme.fg("dim", "... (ctrl+o to expand)")}`;
697
- return new Text(text, 0, 0);
698
- },
699
- );
700
-
701
- // --- Commands -----------------------------------------------------------
702
-
703
- const runByTheWay = async (rawArgs: string, ctx: ExtensionCommandContext) => {
704
- if (ctx.mode !== "tui") {
705
- if (ctx.hasUI)
706
- ctx.ui.notify("by the way is only available in the TUI", "error");
707
- return;
708
- }
709
-
710
- let prompt = rawArgs.trim();
711
- if (!prompt) {
712
- const input = await ctx.ui.input("by the way", "Ask a one-off question…");
713
- prompt = input?.trim() ?? "";
714
- if (!prompt) return;
715
- }
716
-
717
- const manager = await getManager();
718
- let snap: SubagentSnapshot;
719
- try {
720
- snap = await runTool(
721
- getRuntime(),
722
- manager.spawn("pi", {
723
- origin: "btw",
724
- prompt,
725
- title: deriveBtwTitle(prompt),
726
- cwd: ctx.cwd,
727
- parent: {
728
- parentCwd: ctx.cwd,
729
- projectTrusted: ctx.isProjectTrusted(),
730
- inheritedModel: ctx.model
731
- ? { provider: ctx.model.provider, id: ctx.model.id }
732
- : undefined,
733
- inheritedThinkingLevel: pi.getThinkingLevel(),
734
- modelRegistry: ctx.modelRegistry,
735
- },
736
- }),
737
- );
738
- } catch (error) {
739
- ctx.ui.notify(
740
- error instanceof Error ? error.message : String(error),
741
- "error",
742
- );
743
- return;
744
- }
745
-
746
- await openSubagentTakeover(ctx, manager.view, snap.id, {
747
- badge: "by the way",
748
- });
749
- };
750
-
751
- pi.registerCommand("btw", {
752
- description:
753
- "Ask a one-off side question while the main agent keeps working",
754
- handler: runByTheWay,
755
- });
756
-
757
- pi.registerCommand("subagents", {
758
- description: "List, inspect, and take over subagents",
759
- handler: async (_args, ctx) => {
760
- if (ctx.mode !== "tui") {
761
- if (ctx.hasUI)
762
- ctx.ui.notify(
763
- "Subagent takeover is only available in the TUI",
764
- "error",
765
- );
766
- return;
767
- }
768
- const manager = await getManager();
769
- if (manager.view.size() === 0) {
770
- ctx.ui.notify(
771
- "No subagents yet. The agent spawns them with subagent_spawn.",
772
- "info",
773
- );
774
- return;
775
- }
776
- await openSubagentPicker(ctx, manager.view);
777
- },
778
- });
779
- }
1
+ /**
2
+ * Subagents — spawn background subagents on one of three backends
3
+ * (pi, Claude Code, Codex) unified behind a single Effect service interface.
4
+ *
5
+ * Tools (for the parent LLM):
6
+ * - subagent_spawn: fire-and-forget spawn (prompt, title, agent, working_dir,
7
+ * model, reasoning_effort). Max 4 running at once across all backends.
8
+ * - subagent_wait: block until the listed subagents settle, return results.
9
+ * - subagent_cancel: stop one or more running subagents.
10
+ * - subagent_check: peek at a subagent's status and recent activity.
11
+ * - subagent_list: list all subagents.
12
+ *
13
+ * Unawaited subagents queue their result as a follow-up message when they
14
+ * settle. `/subagents` opens a picker + full interactive takeover view.
15
+ *
16
+ * Architecture: Effect v4 generators throughout (backends -> manager ->
17
+ * runtime); this file is the async boundary where tool handlers run effects
18
+ * against one shared ManagedRuntime. All three backends are real: pi runs
19
+ * in-process SDK sessions, claude drives the Claude Agent SDK, codex speaks
20
+ * JSON-RPC to a scoped `codex app-server` process.
21
+ */
22
+
23
+ import * as fs from "node:fs";
24
+ import * as path from "node:path";
25
+ import { StringEnum } from "@earendil-works/pi-ai";
26
+ import type {
27
+ ExtensionAPI,
28
+ ExtensionCommandContext,
29
+ ExtensionContext,
30
+ ExtensionUIContext,
31
+ } from "@earendil-works/pi-coding-agent";
32
+ import {
33
+ DEFAULT_MAX_BYTES,
34
+ DEFAULT_MAX_LINES,
35
+ formatSize,
36
+ getAgentDir,
37
+ getMarkdownTheme,
38
+ ProjectTrustStore,
39
+ truncateHead,
40
+ } from "@earendil-works/pi-coding-agent";
41
+ import { Markdown, Text } from "@earendil-works/pi-tui";
42
+ import { Type } from "typebox";
43
+ import { deriveBtwTitle, isModelVisible } from "./src/by-the-way.ts";
44
+ import {
45
+ BACKEND_NAMES,
46
+ formatElapsed,
47
+ latestText,
48
+ REASONING_EFFORTS,
49
+ type SubagentSnapshot,
50
+ } from "./src/domain.ts";
51
+ import {
52
+ formatActivityStatus,
53
+ formatContextUtilization,
54
+ } from "./src/format.ts";
55
+ import { SubagentManager, type SubagentManagerShape } from "./src/manager.ts";
56
+ import {
57
+ buildSubagentResultMessage,
58
+ buildSubagentSpawnResult,
59
+ SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS,
60
+ SUBAGENT_CANCEL_TOOL_DESCRIPTION,
61
+ SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS,
62
+ SUBAGENT_CHECK_TOOL_DESCRIPTION,
63
+ SUBAGENT_LIST_TOOL_DESCRIPTION,
64
+ SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS,
65
+ SUBAGENT_SPAWN_PROMPT_GUIDELINES,
66
+ SUBAGENT_SPAWN_PROMPT_SNIPPET,
67
+ SUBAGENT_SPAWN_TOOL_DESCRIPTION,
68
+ SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS,
69
+ SUBAGENT_WAIT_TOOL_DESCRIPTION,
70
+ } from "./src/prompt.ts";
71
+ import { createDeferredResultDelivery } from "./src/result-delivery.ts";
72
+ import {
73
+ createSubagentRuntime,
74
+ runTool,
75
+ type SubagentRuntime,
76
+ } from "./src/runtime.ts";
77
+ import { openSubagentPicker, openSubagentTakeover } from "./src/ui/takeover.ts";
78
+
79
+ const SUBAGENT_OUTPUT_MAX_BYTES = 24 * 1024;
80
+ const WAIT_OUTPUT_MAX_BYTES = 48 * 1024;
81
+ const WAIT_PER_AGENT_MAX_BYTES = 16 * 1024;
82
+
83
+ interface BtwResultData {
84
+ readonly id: string;
85
+ readonly title: string;
86
+ readonly status: SubagentSnapshot["status"];
87
+ readonly errorText?: string;
88
+ readonly prompt: string;
89
+ readonly answer: string;
90
+ readonly sessionFilePath?: string;
91
+ }
92
+
93
+ function describeSubagent(snap: SubagentSnapshot) {
94
+ const details = [
95
+ `${snap.backend}: ${snap.meta.modelLabel ?? "?"}`,
96
+ formatContextUtilization(snap.usage),
97
+ formatElapsed(snap),
98
+ snap.cwd,
99
+ ].filter(Boolean);
100
+ return `${snap.id} [${snap.status}] "${snap.title}" (${details.join(", ")})`;
101
+ }
102
+
103
+ function truncatedOutput(
104
+ snap: SubagentSnapshot,
105
+ maxBytes = SUBAGENT_OUTPUT_MAX_BYTES,
106
+ ): string {
107
+ const output = snap.finalText || "(no output)";
108
+ const truncation = truncateHead(output, {
109
+ maxBytes: Math.min(maxBytes, DEFAULT_MAX_BYTES),
110
+ maxLines: Math.min(600, DEFAULT_MAX_LINES),
111
+ });
112
+ let text = truncation.content;
113
+ if (truncation.truncated) {
114
+ text += `\n\n[Output truncated: ${formatSize(truncation.outputBytes)} of ${formatSize(truncation.totalBytes)} shown. Full transcript in session file: ${snap.meta.sessionFilePath ?? "?"}]`;
115
+ }
116
+ return text;
117
+ }
118
+
119
+ /**
120
+ * Same-directory children inherit the live parent decision. An alternate cwd
121
+ * is trusted only when pi's persisted trust store explicitly trusts it (or a
122
+ * containing directory); unreadable/invalid trust data fails closed.
123
+ */
124
+ function resolveChildProjectTrust(options: {
125
+ parentCwd: string;
126
+ childCwd: string;
127
+ parentTrusted: boolean;
128
+ }) {
129
+ if (path.resolve(options.childCwd) === path.resolve(options.parentCwd)) {
130
+ return options.parentTrusted;
131
+ }
132
+ try {
133
+ const trustStore = new ProjectTrustStore(getAgentDir());
134
+ return trustStore.get(options.childCwd) === true;
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ const RESULT_PREVIEW_LINES = 10;
141
+
142
+ /** Tool call line: bold-white tool name, 2-space indent (Box adds 1 + Text 1). */
143
+ function renderToolCall(name: string, theme: any): Text {
144
+ return new Text(theme.fg("toolTitle", theme.bold(name)), 1, 0);
145
+ }
146
+
147
+ /** Tool result: grey text at 2-space indent, collapsed to a short preview. */
148
+ function renderToolResult(result: any, theme: any): Text {
149
+ const text = (result?.content ?? [])
150
+ .filter((c: any) => c?.type === "text" && typeof c?.text === "string")
151
+ .map((c: any) => c.text)
152
+ .join("\n");
153
+ if (!text) return new Text("", 1, 0);
154
+ const lines = text.split("\n");
155
+ const preview = lines.slice(0, RESULT_PREVIEW_LINES);
156
+ let out = theme.fg("toolOutput", preview.join("\n"));
157
+ if (lines.length > RESULT_PREVIEW_LINES) {
158
+ out += theme.fg("dim", `\n... (${lines.length - RESULT_PREVIEW_LINES} more lines)`);
159
+ }
160
+ return new Text(out, 1, 0);
161
+ }
162
+
163
+ export default function (pi: ExtensionAPI) {
164
+ let runtime: SubagentRuntime | undefined;
165
+ let managerPromise: Promise<SubagentManagerShape> | undefined;
166
+ let sessionContext: ExtensionContext | undefined;
167
+ let ui: ExtensionUIContext | undefined;
168
+ let unsubStatus: (() => void) | undefined;
169
+ const resultDelivery = createDeferredResultDelivery<SubagentSnapshot>();
170
+
171
+ const getRuntime = () => (runtime ??= createSubagentRuntime());
172
+
173
+ /** Resolve the manager service once per runtime and wire the extension hooks. */
174
+ const getManager = () => {
175
+ managerPromise ??= getRuntime()
176
+ .runPromise(SubagentManager)
177
+ .then((manager) => {
178
+ manager.view.setOnSettled(onSettled);
179
+ unsubStatus?.();
180
+ unsubStatus = manager.view.subscribe(() => updateStatus(manager));
181
+ updateStatus(manager);
182
+ return manager;
183
+ });
184
+ return managerPromise;
185
+ };
186
+
187
+ const updateStatus = (manager: SubagentManagerShape) => {
188
+ if (!ui) return;
189
+ const subs = manager.view.list();
190
+ if (subs.length === 0) {
191
+ ui.setStatus("subagents", undefined);
192
+ return;
193
+ }
194
+ const running = subs.filter((snap) => snap.status === "running").length;
195
+ const failed = subs.filter((snap) => snap.status === "error").length;
196
+ const done = subs.length - running - failed;
197
+ ui.setStatus(
198
+ "subagents",
199
+ formatActivityStatus(ui.theme, { running, done, failed }),
200
+ );
201
+ };
202
+
203
+ const deliverResult = (snap: SubagentSnapshot) => {
204
+ pi.sendMessage(
205
+ {
206
+ customType: "subagent-result",
207
+ content: buildSubagentResultMessage({
208
+ id: snap.id,
209
+ title: snap.title,
210
+ status: snap.status,
211
+ errorText: snap.errorText,
212
+ output: truncatedOutput(snap),
213
+ }),
214
+ display: true,
215
+ details: { id: snap.id, title: snap.title, status: snap.status },
216
+ },
217
+ { deliverAs: "followUp", triggerTurn: true },
218
+ );
219
+ };
220
+
221
+ const flushResults = () => {
222
+ for (const snap of resultDelivery.drain()) deliverResult(snap);
223
+ };
224
+
225
+ const deliverBtwResult = (snap: SubagentSnapshot) => {
226
+ // appendEntry is a synchronous SessionManager operation and emits an
227
+ // entry_appended event, so it is safe while the parent is streaming and
228
+ // never enters the model's context or follow-up queue.
229
+ pi.appendEntry<BtwResultData>("btw-result", {
230
+ id: snap.id,
231
+ title: snap.title,
232
+ status: snap.status,
233
+ errorText: snap.errorText,
234
+ prompt: snap.prompt,
235
+ answer: truncatedOutput(snap),
236
+ sessionFilePath: snap.meta.sessionFilePath,
237
+ });
238
+ ui?.notify(
239
+ snap.status === "error"
240
+ ? `by the way “${snap.title}” failed — reopen it with /subagents`
241
+ : `by the way “${snap.title}” answered — reopen it with /subagents`,
242
+ snap.status === "error" ? "error" : "info",
243
+ );
244
+ };
245
+
246
+ const onSettled = (snap: SubagentSnapshot, consumed: boolean) => {
247
+ // A shutdown can settle children while disposing their scopes. Never
248
+ // append into a session whose extension runtime is already closing.
249
+ if (!sessionContext) return;
250
+ if (snap.origin === "btw") {
251
+ deliverBtwResult({ ...snap, meta: { ...snap.meta } });
252
+ return;
253
+ }
254
+ if (consumed) {
255
+ resultDelivery.consume([snap.id]);
256
+ return;
257
+ }
258
+ // Keep the result retractable while the parent is working. A later
259
+ // subagent_wait can consume it before agent_settled flushes follow-ups.
260
+ // Defer a copy: the live snapshot keeps mutating if the subagent is
261
+ // restarted before the deferred result flushes.
262
+ resultDelivery.defer({ ...snap, meta: { ...snap.meta } });
263
+ if (sessionContext?.isIdle()) flushResults();
264
+ };
265
+
266
+ pi.on("session_start", (_event, ctx) => {
267
+ sessionContext = ctx;
268
+ if (ctx.hasUI) ui = ctx.ui;
269
+ });
270
+
271
+ pi.on("agent_settled", flushResults);
272
+
273
+ pi.on("session_shutdown", async () => {
274
+ sessionContext = undefined;
275
+ resultDelivery.clear();
276
+ unsubStatus?.();
277
+ unsubStatus = undefined;
278
+ ui?.setStatus("subagents", undefined);
279
+ ui = undefined;
280
+ const closing = runtime;
281
+ runtime = undefined;
282
+ managerPromise = undefined;
283
+ // Disposing the runtime runs the manager finalizer, which tears down all
284
+ // subagent scopes (and, later, their real child processes).
285
+ await closing?.dispose();
286
+ });
287
+
288
+ // --- Tools -------------------------------------------------------------
289
+
290
+ pi.registerTool({
291
+ name: "subagent_spawn",
292
+ label: "Spawn Subagent",
293
+ renderCall: (_args: any, theme: any) => renderToolCall("subagent_spawn", theme),
294
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
295
+ description: SUBAGENT_SPAWN_TOOL_DESCRIPTION,
296
+ promptSnippet: SUBAGENT_SPAWN_PROMPT_SNIPPET,
297
+ promptGuidelines: SUBAGENT_SPAWN_PROMPT_GUIDELINES,
298
+ parameters: Type.Object({
299
+ prompt: Type.String({
300
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.prompt,
301
+ }),
302
+ name: Type.String({
303
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.name,
304
+ }),
305
+ harness: StringEnum(BACKEND_NAMES, {
306
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.harness,
307
+ }),
308
+ working_dir: Type.Optional(
309
+ Type.String({
310
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.workingDir,
311
+ }),
312
+ ),
313
+ model: Type.Optional(
314
+ Type.String({
315
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.model,
316
+ }),
317
+ ),
318
+ reasoning_effort: Type.Optional(
319
+ StringEnum(REASONING_EFFORTS, {
320
+ description: SUBAGENT_SPAWN_PARAMETER_DESCRIPTIONS.reasoningEffort,
321
+ }),
322
+ ),
323
+ }),
324
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
325
+ const manager = await getManager();
326
+ const harness = params.harness;
327
+
328
+ const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
329
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
330
+ throw new Error(`working_dir is not a directory: ${cwd}`);
331
+ }
332
+
333
+ const title = params.name.trim().slice(0, 160) || "subagent";
334
+ const snap = await runTool(
335
+ getRuntime(),
336
+ manager.spawn(harness, {
337
+ prompt: params.prompt,
338
+ title,
339
+ cwd,
340
+ model: params.model,
341
+ reasoningEffort: params.reasoning_effort,
342
+ parent: {
343
+ parentCwd: ctx.cwd,
344
+ projectTrusted: resolveChildProjectTrust({
345
+ parentCwd: ctx.cwd,
346
+ childCwd: cwd,
347
+ parentTrusted: ctx.isProjectTrusted(),
348
+ }),
349
+ inheritedModel: ctx.model
350
+ ? { provider: ctx.model.provider, id: ctx.model.id }
351
+ : undefined,
352
+ inheritedThinkingLevel: pi.getThinkingLevel(),
353
+ modelRegistry: ctx.modelRegistry,
354
+ },
355
+ }),
356
+ { signal, interruptMessage: "Subagent spawn aborted." },
357
+ );
358
+
359
+ return {
360
+ content: [
361
+ {
362
+ type: "text",
363
+ text: buildSubagentSpawnResult({
364
+ id: snap.id,
365
+ title: snap.title,
366
+ harness,
367
+ modelLabel: snap.meta.modelLabel ?? "?",
368
+ cwd,
369
+ }),
370
+ },
371
+ ],
372
+ details: {
373
+ id: snap.id,
374
+ title: snap.title,
375
+ cwd,
376
+ harness,
377
+ model: snap.meta.modelLabel,
378
+ },
379
+ };
380
+ },
381
+ });
382
+
383
+ pi.registerTool({
384
+ name: "subagent_wait",
385
+ label: "Wait for Subagents",
386
+ renderCall: (_args: any, theme: any) => renderToolCall("subagent_wait", theme),
387
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
388
+ description: SUBAGENT_WAIT_TOOL_DESCRIPTION,
389
+ parameters: Type.Object({
390
+ ids: Type.Array(Type.String(), {
391
+ maxItems: 64,
392
+ description: SUBAGENT_WAIT_PARAMETER_DESCRIPTIONS.ids,
393
+ }),
394
+ }),
395
+ async execute(_toolCallId, params, signal, onUpdate) {
396
+ const manager = await getManager();
397
+ const ids = [...new Set(params.ids)];
398
+ if (ids.length === 0)
399
+ throw new Error("Provide at least one subagent id.");
400
+ const known = manager.view
401
+ .list()
402
+ .filter(isModelVisible)
403
+ .map((snap) => snap.id);
404
+ const unknown = ids.filter((id) => {
405
+ const snap = manager.view.get(id);
406
+ return !snap || !isModelVisible(snap);
407
+ });
408
+ if (unknown.length > 0) {
409
+ throw new Error(
410
+ `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
411
+ );
412
+ }
413
+
414
+ await runTool(
415
+ getRuntime(),
416
+ manager.waitFor(ids, (pending) => {
417
+ onUpdate?.({
418
+ content: [
419
+ { type: "text", text: `Waiting for ${pending.join(", ")}...` },
420
+ ],
421
+ details: { pending },
422
+ });
423
+ }),
424
+ { signal, interruptMessage: "Wait aborted. Subagents keep running." },
425
+ );
426
+
427
+ // Settlement may have happened before this wait began. Remove any
428
+ // deferred automatic delivery now that the tool is returning the result.
429
+ resultDelivery.consume(ids);
430
+
431
+ const sections: string[] = [];
432
+ let remainingBytes = WAIT_OUTPUT_MAX_BYTES;
433
+ for (const id of ids) {
434
+ const snap = manager.view.get(id);
435
+ if (!snap) {
436
+ sections.push(`## ${id}\n\n(no longer tracked)`);
437
+ continue;
438
+ }
439
+ const verb = snap.status === "error" ? "failed" : "finished";
440
+ let section = `## ${snap.id} "${snap.title}" ${verb}`;
441
+ if (snap.errorText) section += `\nError: ${snap.errorText}`;
442
+ const headerBytes = Buffer.byteLength(section, "utf8") + 2;
443
+ const outputBudget = Math.max(
444
+ 512,
445
+ Math.min(WAIT_PER_AGENT_MAX_BYTES, remainingBytes - headerBytes),
446
+ );
447
+ section += `\n\n${truncatedOutput(snap, outputBudget)}`;
448
+ const sectionBytes = Buffer.byteLength(section, "utf8");
449
+ if (sectionBytes > remainingBytes) {
450
+ sections.push(
451
+ `## ${snap.id} "${snap.title}"\n\n[omitted: total wait output limit reached]`,
452
+ );
453
+ break;
454
+ }
455
+ sections.push(section);
456
+ remainingBytes -= sectionBytes;
457
+ }
458
+
459
+ const combined = sections.join("\n\n---\n\n");
460
+ const bounded = truncateHead(combined, {
461
+ maxBytes: WAIT_OUTPUT_MAX_BYTES - 128,
462
+ maxLines: DEFAULT_MAX_LINES,
463
+ });
464
+ const text = bounded.truncated
465
+ ? `${bounded.content}\n\n[wait output truncated at the total output limit]`
466
+ : bounded.content;
467
+ return {
468
+ content: [{ type: "text", text }],
469
+ details: {
470
+ results: ids.map((id) => {
471
+ const snap = manager.view.get(id);
472
+ return { id, title: snap?.title, status: snap?.status };
473
+ }),
474
+ },
475
+ };
476
+ },
477
+ });
478
+
479
+ pi.registerTool({
480
+ name: "subagent_cancel",
481
+ label: "Cancel Subagents",
482
+ renderCall: (_args: any, theme: any) => renderToolCall("subagent_cancel", theme),
483
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
484
+ description: SUBAGENT_CANCEL_TOOL_DESCRIPTION,
485
+ parameters: Type.Object({
486
+ ids: Type.Array(Type.String(), {
487
+ description: SUBAGENT_CANCEL_PARAMETER_DESCRIPTIONS.ids,
488
+ }),
489
+ }),
490
+ async execute(_toolCallId, params, signal) {
491
+ const manager = await getManager();
492
+ const ids = [...new Set(params.ids)];
493
+ if (ids.length === 0)
494
+ throw new Error("Provide at least one subagent id.");
495
+
496
+ const known = manager.view
497
+ .list()
498
+ .filter(isModelVisible)
499
+ .map((snap) => snap.id);
500
+ const unknown = ids.filter((id) => {
501
+ const snap = manager.view.get(id);
502
+ return !snap || !isModelVisible(snap);
503
+ });
504
+ if (unknown.length > 0) {
505
+ throw new Error(
506
+ `Unknown subagent id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
507
+ );
508
+ }
509
+
510
+ const report = await runTool(getRuntime(), manager.cancel(ids), {
511
+ signal,
512
+ interruptMessage: "Subagent cancellation aborted.",
513
+ });
514
+
515
+ const lines = report.map((entry) =>
516
+ entry.cancelled
517
+ ? `Cancelled ${entry.id} "${entry.title}".`
518
+ : `${entry.id} "${entry.title}" was already ${entry.status}.`,
519
+ );
520
+
521
+ return {
522
+ content: [{ type: "text", text: lines.join("\n") }],
523
+ details: {
524
+ results: report.map((entry) => ({
525
+ id: entry.id,
526
+ title: entry.title,
527
+ status: entry.status,
528
+ })),
529
+ },
530
+ };
531
+ },
532
+ });
533
+
534
+ pi.registerTool({
535
+ name: "subagent_check",
536
+ label: "Check Subagent",
537
+ renderCall: (_args: any, theme: any) => renderToolCall("subagent_check", theme),
538
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
539
+ description: SUBAGENT_CHECK_TOOL_DESCRIPTION,
540
+ parameters: Type.Object({
541
+ id: Type.String({
542
+ description: SUBAGENT_CHECK_PARAMETER_DESCRIPTIONS.id,
543
+ }),
544
+ }),
545
+ async execute(_toolCallId, params) {
546
+ const manager = await getManager();
547
+ const snap = manager.view.get(params.id);
548
+ if (!snap || !isModelVisible(snap)) {
549
+ const known = manager.view
550
+ .list()
551
+ .filter(isModelVisible)
552
+ .map((s) => s.id);
553
+ throw new Error(
554
+ `Unknown subagent id "${params.id}". Known: ${known.join(", ") || "none"}.`,
555
+ );
556
+ }
557
+
558
+ let text = `${describeSubagent(snap)}\nTurns: ${snap.turns}`;
559
+ if (snap.errorText) text += `\nError: ${snap.errorText}`;
560
+
561
+ const output = latestText(snap);
562
+ if (output) {
563
+ const preview = truncateHead(output, { maxBytes: 2048, maxLines: 20 });
564
+ text += `\n\nLatest output:\n${preview.content}`;
565
+ if (preview.truncated) text += "\n[...]";
566
+ } else if (snap.status === "running") {
567
+ text += "\n\n(no text output yet)";
568
+ }
569
+
570
+ return {
571
+ content: [{ type: "text", text }],
572
+ details: { id: snap.id, status: snap.status, turns: snap.turns },
573
+ };
574
+ },
575
+ });
576
+
577
+ pi.registerTool({
578
+ name: "subagent_list",
579
+ label: "List Subagents",
580
+ renderCall: (_args: any, theme: any) => renderToolCall("subagent_list", theme),
581
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
582
+ description: SUBAGENT_LIST_TOOL_DESCRIPTION,
583
+ parameters: Type.Object({}),
584
+ async execute() {
585
+ const manager = await getManager();
586
+ const subs = manager.view.list().filter(isModelVisible);
587
+ const text =
588
+ subs.length === 0
589
+ ? "No subagents."
590
+ : subs.map((snap) => describeSubagent(snap)).join("\n");
591
+ return {
592
+ content: [{ type: "text", text }],
593
+ details: {
594
+ subagents: subs.map((snap) => ({
595
+ id: snap.id,
596
+ title: snap.title,
597
+ harness: snap.backend,
598
+ status: snap.status,
599
+ })),
600
+ },
601
+ };
602
+ },
603
+ });
604
+
605
+ // --- Result message rendering ------------------------------------------
606
+
607
+ pi.registerMessageRenderer(
608
+ "subagent-result",
609
+ (message, { expanded }, theme) => {
610
+ const details = (message.details ?? {}) as {
611
+ id?: string;
612
+ title?: string;
613
+ status?: string;
614
+ };
615
+ const failed = details.status === "error";
616
+ const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
617
+ const header =
618
+ `${icon} ` +
619
+ theme.fg("accent", theme.bold(`subagent ${details.id ?? "?"}`)) +
620
+ theme.fg(
621
+ "muted",
622
+ ` · ${details.title ?? ""} · ${failed ? "failed" : "finished"}`,
623
+ );
624
+
625
+ const content =
626
+ typeof message.content === "string" ? message.content : "";
627
+ // Remove only the summary line. The following Error line (when present)
628
+ // is part of the actual result and must remain visible.
629
+ const body = content.split("\n").slice(1).join("\n").trim();
630
+
631
+ if (expanded) {
632
+ const md = new Markdown(`${body}`, 0, 0, getMarkdownTheme());
633
+ const container = new Text(header, 0, 0);
634
+ return {
635
+ render: (width: number) => [
636
+ ...container.render(width),
637
+ ...md.render(width),
638
+ ],
639
+ invalidate: () => {
640
+ container.invalidate();
641
+ md.invalidate();
642
+ },
643
+ };
644
+ }
645
+
646
+ const previewLines = body.split("\n").slice(0, 8);
647
+ let text = ` ${header}`;
648
+ for (const line of previewLines)
649
+ text += `\n ${theme.fg("toolOutput", line)}`;
650
+ if (body.split("\n").length > 8)
651
+ text += `\n ${theme.fg("dim", "... (ctrl+o to expand)")}`;
652
+ return new Text(text, 0, 0);
653
+ },
654
+ );
655
+
656
+ pi.registerEntryRenderer<BtwResultData>(
657
+ "btw-result",
658
+ (entry, { expanded }, theme) => {
659
+ const data = entry.data;
660
+ const failed = data?.status === "error";
661
+ const icon = failed ? theme.fg("error", "x") : theme.fg("success", "■");
662
+ const header =
663
+ `${icon} ` +
664
+ theme.fg("accent", theme.bold(`by the way · ${data?.title ?? "?"}`)) +
665
+ theme.fg(
666
+ "muted",
667
+ ` · ${failed ? "failed" : "answered"} · ${data?.id ?? "?"}`,
668
+ );
669
+ const body = [
670
+ data?.errorText ? `Error: ${data.errorText}` : "",
671
+ data?.answer ?? "(no answer)",
672
+ ]
673
+ .filter(Boolean)
674
+ .join("\n\n");
675
+
676
+ if (expanded) {
677
+ const md = new Markdown(body, 0, 0, getMarkdownTheme());
678
+ const container = new Text(header, 0, 0);
679
+ return {
680
+ render: (width: number) => [
681
+ ...container.render(width),
682
+ ...md.render(width),
683
+ ],
684
+ invalidate: () => {
685
+ container.invalidate();
686
+ md.invalidate();
687
+ },
688
+ };
689
+ }
690
+
691
+ const lines = body.split("\n");
692
+ let text = ` ${header}`;
693
+ for (const line of lines.slice(0, 8))
694
+ text += `\n ${theme.fg("toolOutput", line)}`;
695
+ if (lines.length > 8)
696
+ text += `\n ${theme.fg("dim", "... (ctrl+o to expand)")}`;
697
+ return new Text(text, 0, 0);
698
+ },
699
+ );
700
+
701
+ // --- Commands -----------------------------------------------------------
702
+
703
+ const runByTheWay = async (rawArgs: string, ctx: ExtensionCommandContext) => {
704
+ if (ctx.mode !== "tui") {
705
+ if (ctx.hasUI)
706
+ ctx.ui.notify("by the way is only available in the TUI", "error");
707
+ return;
708
+ }
709
+
710
+ let prompt = rawArgs.trim();
711
+ if (!prompt) {
712
+ const input = await ctx.ui.input("by the way", "Ask a one-off question…");
713
+ prompt = input?.trim() ?? "";
714
+ if (!prompt) return;
715
+ }
716
+
717
+ const manager = await getManager();
718
+ let snap: SubagentSnapshot;
719
+ try {
720
+ snap = await runTool(
721
+ getRuntime(),
722
+ manager.spawn("pi", {
723
+ origin: "btw",
724
+ prompt,
725
+ title: deriveBtwTitle(prompt),
726
+ cwd: ctx.cwd,
727
+ parent: {
728
+ parentCwd: ctx.cwd,
729
+ projectTrusted: ctx.isProjectTrusted(),
730
+ inheritedModel: ctx.model
731
+ ? { provider: ctx.model.provider, id: ctx.model.id }
732
+ : undefined,
733
+ inheritedThinkingLevel: pi.getThinkingLevel(),
734
+ modelRegistry: ctx.modelRegistry,
735
+ },
736
+ }),
737
+ );
738
+ } catch (error) {
739
+ ctx.ui.notify(
740
+ error instanceof Error ? error.message : String(error),
741
+ "error",
742
+ );
743
+ return;
744
+ }
745
+
746
+ await openSubagentTakeover(ctx, manager.view, snap.id, {
747
+ badge: "by the way",
748
+ });
749
+ };
750
+
751
+ pi.registerCommand("btw", {
752
+ description:
753
+ "Ask a one-off side question while the main agent keeps working",
754
+ handler: runByTheWay,
755
+ });
756
+
757
+ pi.registerCommand("subagents", {
758
+ description: "List, inspect, and take over subagents",
759
+ handler: async (_args, ctx) => {
760
+ if (ctx.mode !== "tui") {
761
+ if (ctx.hasUI)
762
+ ctx.ui.notify(
763
+ "Subagent takeover is only available in the TUI",
764
+ "error",
765
+ );
766
+ return;
767
+ }
768
+ const manager = await getManager();
769
+ if (manager.view.size() === 0) {
770
+ ctx.ui.notify(
771
+ "No subagents yet. The agent spawns them with subagent_spawn.",
772
+ "info",
773
+ );
774
+ return;
775
+ }
776
+ await openSubagentPicker(ctx, manager.view);
777
+ },
778
+ });
779
+ }