@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,627 +1,627 @@
1
- /**
2
- * Background terminals — start long-running shell processes the model can
3
- * inspect and stop, but never write to (stdin is ignored at the OS level).
4
- *
5
- * Tools (for the LLM):
6
- * - bg_start: fire-and-forget spawn (command, title, working_dir). Max 8
7
- * running at once. The model is notified exactly once when a process exits.
8
- * - bg_status: peek at one terminal's status + tail-truncated output.
9
- * - bg_list: list all tracked terminals (running and settled).
10
- * - bg_kill: SIGTERM→SIGKILL the whole process tree; returns final state.
11
- *
12
- * While ≥1 process runs, a one-line widget above the editor shows
13
- * "N background terminal(s) running • /ps to view". `/ps` opens a two-stage
14
- * full-screen overlay (list → read-only detail with stdout/stderr toggle).
15
- *
16
- * Architecture: Effect v4 core (manager service behind one ManagedRuntime);
17
- * this file is the async boundary where tool handlers run effects via
18
- * runTool. Node stream plumbing inside the manager is plain callbacks.
19
- */
20
-
21
- import * as fs from "node:fs";
22
- import * as path from "node:path";
23
- import type {
24
- ExtensionAPI,
25
- ExtensionContext,
26
- ExtensionUIContext,
27
- } from "@earendil-works/pi-coding-agent";
28
- import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
29
- import { Markdown, Text } from "@earendil-works/pi-tui";
30
- import { Type } from "typebox";
31
- import type { TerminalSnapshot } from "./src/domain.ts";
32
- import { TerminalManager, type TerminalManagerShape } from "./src/manager.ts";
33
- import {
34
- BG_KILL_PARAMETER_DESCRIPTIONS,
35
- BG_KILL_TOOL_DESCRIPTION,
36
- BG_LIST_TOOL_DESCRIPTION,
37
- BG_START_PARAMETER_DESCRIPTIONS,
38
- BG_START_PROMPT_GUIDELINES,
39
- BG_START_PROMPT_SNIPPET,
40
- BG_START_TOOL_DESCRIPTION,
41
- BG_STATUS_PARAMETER_DESCRIPTIONS,
42
- BG_STATUS_TOOL_DESCRIPTION,
43
- buildKillReport,
44
- buildStartResult,
45
- buildStatusResult,
46
- buildTerminalResultMessage,
47
- describeTerminal,
48
- } from "./src/prompt.ts";
49
- import { createDeferredResultDelivery } from "./src/result-delivery.ts";
50
- import {
51
- createTerminalRuntime,
52
- runTool,
53
- type TerminalRuntime,
54
- } from "./src/runtime.ts";
55
- import { sanitizeText } from "./src/ui/output-view.ts";
56
- import { openTerminalPicker } from "./src/ui/ps.ts";
57
- import { createBashTool } from "@earendil-works/pi-coding-agent";
58
-
59
- const WIDGET_KEY = "background-terminals";
60
-
61
- const AUTO_PROMOTE_MS = 50_000;
62
- const AUTO_PROMOTE_SEC = AUTO_PROMOTE_MS / 1000;
63
-
64
- const RESULT_PREVIEW_LINES = 10;
65
-
66
- /** Tool call line: bold-white tool name, 2-space indent (Box adds 1 + Text 1). */
67
- function renderToolCall(name: string, theme: any): Text {
68
- return new Text(theme.fg("toolTitle", theme.bold(name)), 1, 0);
69
- }
70
-
71
- /** Tool result: grey text at 2-space indent, collapsed to a short preview. */
72
- function renderToolResult(result: any, theme: any): Text {
73
- const text = (result?.content ?? [])
74
- .filter((c: any) => c?.type === "text" && typeof c?.text === "string")
75
- .map((c: any) => c.text)
76
- .join("\n");
77
- if (!text) return new Text("", 1, 0);
78
- const lines = text.split("\n");
79
- const preview = lines.slice(0, RESULT_PREVIEW_LINES);
80
- let out = theme.fg("toolOutput", preview.join("\n"));
81
- if (lines.length > RESULT_PREVIEW_LINES) {
82
- out += theme.fg("dim", `\n... (${lines.length - RESULT_PREVIEW_LINES} more lines)`);
83
- }
84
- return new Text(out, 1, 0);
85
- }
86
-
87
- export default function (pi: ExtensionAPI) {
88
- let runtime: TerminalRuntime | undefined;
89
- let managerPromise: Promise<TerminalManagerShape> | undefined;
90
- let sessionContext: ExtensionContext | undefined;
91
- let ui: ExtensionUIContext | undefined;
92
- let unsubStatus: (() => void) | undefined;
93
- const resultDelivery = createDeferredResultDelivery<TerminalSnapshot>();
94
-
95
- const getRuntime = () => (runtime ??= createTerminalRuntime());
96
-
97
- /** Resolve the manager service once per runtime and wire the extension hooks. */
98
- const getManager = () => {
99
- managerPromise ??= getRuntime()
100
- .runPromise(TerminalManager)
101
- .then((manager) => {
102
- manager.view.setOnSettled(onSettled);
103
- unsubStatus?.();
104
- unsubStatus = manager.view.subscribe(() => updateWidget(manager));
105
- updateWidget(manager);
106
- return manager;
107
- });
108
- return managerPromise;
109
- };
110
-
111
- /** One-line widget directly above the editor, only while ≥1 is running.
112
- * Called on every manager notification (including per-output-chunk), so it
113
- * only touches setWidget when the running count actually changes —
114
- * replacing the widget factory hundreds of times a second would churn
115
- * component creation for no visible difference. */
116
- let widgetRunning = 0;
117
- const updateWidget = (manager: TerminalManagerShape) => {
118
- if (!ui) return;
119
- try {
120
- const running = manager.view
121
- .list()
122
- .filter((snap) => snap.status === "running").length;
123
- if (running === widgetRunning) return;
124
- widgetRunning = running;
125
- if (running === 0) {
126
- ui.setWidget(WIDGET_KEY, undefined);
127
- return;
128
- }
129
- ui.setWidget(WIDGET_KEY, (_tui, theme) => {
130
- const line =
131
- theme.fg("warning", "■ ") +
132
- theme.fg(
133
- "text",
134
- `${running} background terminal${running === 1 ? "" : "s"} running`,
135
- ) +
136
- theme.fg("dim", " • ") +
137
- theme.fg("accent", "/ps") +
138
- theme.fg("dim", " to view");
139
- return { render: () => [line], invalidate: () => {} };
140
- });
141
- } catch {
142
- // UI may be unavailable (print/RPC modes or teardown).
143
- }
144
- };
145
-
146
- const deliverResult = (snap: TerminalSnapshot) => {
147
- try {
148
- pi.sendMessage(
149
- {
150
- customType: "background-terminal-result",
151
- content: buildTerminalResultMessage(snap),
152
- display: true,
153
- details: {
154
- id: snap.id,
155
- title: snap.title,
156
- status: snap.status,
157
- exitCode: snap.exitCode,
158
- signal: snap.signal,
159
- },
160
- },
161
- // followUp: queued until the agent has no more tool calls — never
162
- // interrupts a mid-turn stream. triggerTurn: wakes the model
163
- // immediately iff idle; if busy, the queued follow-up is delivered
164
- // when the current run settles. Either way exactly one delivery.
165
- { deliverAs: "followUp", triggerTurn: true },
166
- );
167
- return true;
168
- } catch (error) {
169
- // Session may be shutting down, but retain the snapshot so any later
170
- // agent-settled flush can retry instead of silently dropping it.
171
- console.error("background-terminals: failed to deliver result", error);
172
- return false;
173
- }
174
- };
175
-
176
- const flushResults = () => {
177
- for (const snap of resultDelivery.drain()) {
178
- if (!deliverResult(snap)) resultDelivery.defer(snap);
179
- }
180
- };
181
-
182
- const onSettled = (snap: TerminalSnapshot, consumed: boolean) => {
183
- if (consumed) {
184
- // An in-flight bg_kill is returning this settlement itself.
185
- resultDelivery.consume([snap.id]);
186
- return;
187
- }
188
- // Defer a deep-enough copy: the live snapshot's output views keep
189
- // mutating (late flushes) after settle.
190
- resultDelivery.defer({
191
- ...snap,
192
- stdout: { ...snap.stdout },
193
- stderr: { ...snap.stderr },
194
- });
195
- if (sessionContext?.isIdle()) flushResults();
196
- };
197
-
198
- pi.on("session_start", (_event, ctx) => {
199
- sessionContext = ctx;
200
- if (ctx.hasUI) ui = ctx.ui;
201
- });
202
-
203
- // Drain deferred results when the agent settles: together with the
204
- // isIdle() fast path above and the Map-keyed delivery (drain clears),
205
- // double delivery is structurally impossible — whoever drains first wins.
206
- pi.on("agent_settled", flushResults);
207
-
208
- // /new, /resume, /fork, /reload, and quit all emit session_shutdown for
209
- // the old extension instance. Processes never survive a session
210
- // transition: disposing the runtime runs the manager finalizer →
211
- // disposeAll → every entry scope → SIGTERM→SIGKILL tree kill, each close
212
- // bounded so a wedged process cannot hang shutdown.
213
- pi.on("session_shutdown", async () => {
214
- sessionContext = undefined;
215
- resultDelivery.clear();
216
- unsubStatus?.();
217
- unsubStatus = undefined;
218
- try {
219
- ui?.setWidget(WIDGET_KEY, undefined);
220
- } catch {
221
- // UI may already be gone.
222
- }
223
- widgetRunning = 0;
224
- ui = undefined;
225
- const closing = runtime;
226
- runtime = undefined;
227
- managerPromise = undefined;
228
- await closing?.dispose();
229
- });
230
-
231
- // --- Tools -------------------------------------------------------------
232
-
233
- pi.registerTool({
234
- name: "bg_start",
235
- label: "Start Background Terminal",
236
- renderCall: (_args: any, theme: any) => renderToolCall("bg_start", theme),
237
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
238
- description: BG_START_TOOL_DESCRIPTION,
239
- promptSnippet: BG_START_PROMPT_SNIPPET,
240
- promptGuidelines: BG_START_PROMPT_GUIDELINES,
241
- parameters: Type.Object({
242
- command: Type.String({
243
- description: BG_START_PARAMETER_DESCRIPTIONS.command,
244
- }),
245
- title: Type.String({
246
- description: BG_START_PARAMETER_DESCRIPTIONS.title,
247
- }),
248
- working_dir: Type.Optional(
249
- Type.String({
250
- description: BG_START_PARAMETER_DESCRIPTIONS.workingDir,
251
- }),
252
- ),
253
- }),
254
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
255
- const manager = await getManager();
256
-
257
- const command = params.command.trim();
258
- if (!command) throw new Error("command must not be empty.");
259
-
260
- const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
261
- if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
262
- throw new Error(`working_dir is not a directory: ${cwd}`);
263
- }
264
-
265
- // Collapse whitespace (a newline inside a one-line UI row desyncs the
266
- // TUI renderer) before bounding the length.
267
- const title =
268
- params.title.replace(/\s+/g, " ").trim().slice(0, 80) || "terminal";
269
- const snap = await runTool(
270
- getRuntime(),
271
- manager.start({ command, title, cwd }),
272
- );
273
-
274
- return {
275
- content: [{ type: "text", text: buildStartResult(snap) }],
276
- details: { id: snap.id, title: snap.title, cwd, pid: snap.pid },
277
- };
278
- },
279
- });
280
-
281
- pi.registerTool({
282
- name: "bg_status",
283
- label: "Check Background Terminal",
284
- renderCall: (_args: any, theme: any) => renderToolCall("bg_status", theme),
285
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
286
- description: BG_STATUS_TOOL_DESCRIPTION,
287
- parameters: Type.Object({
288
- id: Type.String({ description: BG_STATUS_PARAMETER_DESCRIPTIONS.id }),
289
- }),
290
- async execute(_toolCallId, params) {
291
- const manager = await getManager();
292
- const snap = manager.view.get(params.id);
293
- if (!snap) {
294
- const known = manager.view.list().map((s) => s.id);
295
- throw new Error(
296
- `Unknown terminal id "${params.id}". Known: ${known.join(", ") || "none"}.`,
297
- );
298
- }
299
-
300
- // This status is returning the settlement itself; a pending automatic
301
- // follow-up for the same settle would be a duplicate.
302
- if (snap.status !== "running") resultDelivery.consume([snap.id]);
303
-
304
- return {
305
- content: [{ type: "text", text: buildStatusResult(snap) }],
306
- details: {
307
- id: snap.id,
308
- status: snap.status,
309
- pid: snap.pid,
310
- exitCode: snap.exitCode,
311
- signal: snap.signal,
312
- },
313
- };
314
- },
315
- });
316
-
317
- pi.registerTool({
318
- name: "bg_list",
319
- label: "List Background Terminals",
320
- renderCall: (_args: any, theme: any) => renderToolCall("bg_list", theme),
321
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
322
- description: BG_LIST_TOOL_DESCRIPTION,
323
- parameters: Type.Object({}),
324
- async execute() {
325
- const manager = await getManager();
326
- const terminals = manager.view.list();
327
- const text =
328
- terminals.length === 0
329
- ? "No background terminals."
330
- : terminals.map((snap) => describeTerminal(snap)).join("\n");
331
- return {
332
- content: [{ type: "text", text }],
333
- details: {
334
- terminals: terminals.map((snap) => ({
335
- id: snap.id,
336
- title: snap.title,
337
- status: snap.status,
338
- pid: snap.pid,
339
- })),
340
- },
341
- };
342
- },
343
- });
344
-
345
- pi.registerTool({
346
- name: "bg_kill",
347
- label: "Kill Background Terminals",
348
- renderCall: (_args: any, theme: any) => renderToolCall("bg_kill", theme),
349
- renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
350
- description: BG_KILL_TOOL_DESCRIPTION,
351
- parameters: Type.Object({
352
- ids: Type.Array(Type.String(), {
353
- description: BG_KILL_PARAMETER_DESCRIPTIONS.ids,
354
- }),
355
- }),
356
- async execute(_toolCallId, params, signal) {
357
- const manager = await getManager();
358
- const ids = [...new Set(params.ids)];
359
- if (ids.length === 0)
360
- throw new Error("Provide at least one terminal id.");
361
-
362
- const known = manager.view.list().map((snap) => snap.id);
363
- const unknown = ids.filter((id) => !manager.view.get(id));
364
- if (unknown.length > 0) {
365
- throw new Error(
366
- `Unknown terminal id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
367
- );
368
- }
369
-
370
- const report = await runTool(getRuntime(), manager.kill(ids), {
371
- signal,
372
- interruptMessage:
373
- "Kill wait aborted; termination continues in the background.",
374
- });
375
-
376
- // Settlement may have happened before this kill began (or during it,
377
- // via the killInterest consumed flag). Remove any deferred automatic
378
- // delivery now that this tool returns the final state itself.
379
- resultDelivery.consume(ids);
380
-
381
- return {
382
- content: [{ type: "text", text: buildKillReport(report) }],
383
- details: {
384
- results: report.map((entry) => ({
385
- id: entry.id,
386
- title: entry.title,
387
- status: entry.status,
388
- killed: entry.killed,
389
- })),
390
- },
391
- };
392
- },
393
- });
394
-
395
- // --- Result message rendering ------------------------------------------
396
-
397
- pi.registerMessageRenderer(
398
- "background-terminal-result",
399
- (message, { expanded }, theme) => {
400
- const details = (message.details ?? {}) as {
401
- id?: string;
402
- title?: string;
403
- status?: string;
404
- exitCode?: number;
405
- signal?: string;
406
- };
407
- const failed = details.status === "failed";
408
- const killed = details.status === "killed";
409
- const icon = failed
410
- ? theme.fg("error", "x")
411
- : killed
412
- ? theme.fg("muted", "■")
413
- : theme.fg("success", "■");
414
- const how = killed
415
- ? "killed"
416
- : (details.signal ?? `exit ${details.exitCode ?? "?"}`);
417
- const header =
418
- `${icon} ` +
419
- theme.fg("accent", theme.bold(`terminal ${details.id ?? "?"}`)) +
420
- theme.fg("muted", ` · ${details.title ?? ""} · ${how}`);
421
-
422
- const content =
423
- typeof message.content === "string" ? message.content : "";
424
- // Remove only the summary line; the Error line (when present) is part
425
- // of the actual result and must remain visible. The body carries raw
426
- // process output — sanitize ANSI/control chars or the transcript smears.
427
- const body = sanitizeText(content.split("\n").slice(1).join("\n").trim());
428
-
429
- if (expanded) {
430
- const md = new Markdown(`${body}`, 0, 0, getMarkdownTheme());
431
- const container = new Text(header, 0, 0);
432
- return {
433
- render: (width: number) => [
434
- ...container.render(width),
435
- ...md.render(width),
436
- ],
437
- invalidate: () => {
438
- container.invalidate();
439
- md.invalidate();
440
- },
441
- };
442
- }
443
-
444
- const previewLines = body.split("\n").slice(0, 8);
445
- let text = header;
446
- for (const line of previewLines)
447
- text += `\n${theme.fg("toolOutput", line)}`;
448
- if (body.split("\n").length > 8)
449
- text += `\n${theme.fg("dim", "... (ctrl+o to expand)")}`;
450
- return new Text(text, 0, 0);
451
- },
452
- );
453
-
454
- // --- Auto-promote long bash to background ---------------------------------
455
- // If a bash tool call exceeds 50s, abort the blocking call, restart it
456
- // as a background terminal, and alert the agent + UI. The background
457
- // result is still delivered as a follow-up when it settles.
458
- const baseBashTool: any = createBashTool(process.cwd());
459
- pi.registerTool({
460
- ...baseBashTool,
461
- description: `${baseBashTool.description} If execution exceeds ${AUTO_PROMOTE_SEC}s it is automatically promoted to a background terminal (check with bg_status/bg_list or /ps; result arrives as follow-up).`,
462
- async execute(
463
- toolCallId: string,
464
- params: any,
465
- signal: AbortSignal | undefined,
466
- onUpdate: any,
467
- ctx: ExtensionContext,
468
- ) {
469
- const command: string = params.command;
470
- const cwd = (ctx as any).cwd ?? process.cwd();
471
- const title = command.replace(/\s+/g, " ").trim().slice(0, 80) || "bash auto-promoted";
472
-
473
- // Delegate tool bound to the current cwd so built-in bash semantics
474
- // (shell, env, truncation) stay identical for the fast path.
475
- const delegateTool: any = createBashTool(cwd);
476
-
477
- let lastPartial = "";
478
- const wrappedOnUpdate = (update: any) => {
479
- try {
480
- const text = update?.content?.[0]?.text;
481
- if (typeof text === "string") lastPartial = text;
482
- } catch {}
483
- if (onUpdate) try { onUpdate(update); } catch {}
484
- };
485
-
486
- const execAbortController = new AbortController();
487
- const onIncomingAbort = () => execAbortController.abort();
488
- if (signal) {
489
- if (signal.aborted) execAbortController.abort();
490
- else signal.addEventListener("abort", onIncomingAbort, { once: true });
491
- }
492
-
493
- const execPromise: Promise<{ kind: "done"; res: any } | { kind: "error"; err: unknown }> = delegateTool
494
- .execute(toolCallId, params, execAbortController.signal, wrappedOnUpdate, ctx as any)
495
- .then(
496
- (res: any) => ({ kind: "done" as const, res }),
497
- (err: unknown) => ({ kind: "error" as const, err }),
498
- );
499
-
500
- let timerId: ReturnType<typeof setTimeout> | undefined;
501
- const timerPromise = new Promise<{ kind: "promote" }>((resolve) => {
502
- timerId = setTimeout(() => resolve({ kind: "promote" }), AUTO_PROMOTE_MS);
503
- });
504
-
505
- const race = (await Promise.race([execPromise, timerPromise])) as
506
- | { kind: "done"; res: any }
507
- | { kind: "error"; err: unknown }
508
- | { kind: "promote" };
509
-
510
- if (race.kind !== "promote") {
511
- if (timerId) clearTimeout(timerId);
512
- if (signal) signal.removeEventListener("abort", onIncomingAbort);
513
- if (race.kind === "done") return race.res;
514
- throw race.err;
515
- }
516
-
517
- // Timer won — promote to background terminal.
518
- // Abort the original blocking execution (kills its process tree).
519
- execAbortController.abort();
520
- if (signal) signal.removeEventListener("abort", onIncomingAbort);
521
-
522
- // If the caller already aborted (Esc), don't promote — just propagate.
523
- if (signal?.aborted) {
524
- try {
525
- const settled = await execPromise;
526
- if (settled.kind === "error") throw settled.err;
527
- return (settled as any).res;
528
- } catch (e) {
529
- throw e;
530
- }
531
- }
532
-
533
- // Let the aborted exec settle (or timeout after 2s if it hangs).
534
- try {
535
- await Promise.race([
536
- execPromise.catch(() => {}),
537
- new Promise((r) => setTimeout(r, 2000)),
538
- ]);
539
- } catch {}
540
-
541
- let snap: TerminalSnapshot | undefined;
542
- let spawnError: unknown;
543
- try {
544
- const manager = await getManager();
545
- snap = await runTool(getRuntime(), manager.start({ command, title, cwd }));
546
- } catch (e) {
547
- spawnError = e;
548
- }
549
-
550
- if (!snap || spawnError) {
551
- const msg = spawnError instanceof Error ? spawnError.message : String(spawnError ?? "unknown error");
552
- const text = [
553
- `⚠️ Bash command exceeded ${AUTO_PROMOTE_SEC}s but could not be promoted to a background terminal: ${msg}`,
554
- "",
555
- `Command: ${command}`,
556
- "",
557
- lastPartial ? `Partial output (first ${AUTO_PROMOTE_SEC}s, truncated):\n${lastPartial.slice(-3000)}` : "No output captured before promotion attempt.",
558
- "",
559
- "The original blocking command was aborted. Retry with bg_start directly or free a slot with bg_kill (/ps).",
560
- ].join("\n");
561
- if ((ctx as any).hasUI) {
562
- try { (ctx as any).ui.notify(`Bash auto-promote failed: ${msg}`, "warning"); } catch {}
563
- }
564
- return {
565
- content: [{ type: "text", text }],
566
- details: { promoted: false, error: msg, command, cwd, partialOutput: lastPartial },
567
- };
568
- }
569
-
570
- const partialPreview = lastPartial ? lastPartial.slice(-3000) : "(no output yet)";
571
- const text = [
572
- `⏳ Bash command exceeded ${AUTO_PROMOTE_SEC}s and was automatically moved to a background terminal.`,
573
- "",
574
- `• Terminal ID: ${snap.id}`,
575
- `• Title: ${snap.title}`,
576
- `• Command: ${command}`,
577
- `• CWD: ${cwd}`,
578
- `• PID: ${snap.pid ?? "pending"}`,
579
- "",
580
- "The original blocking bash call was aborted and the command was restarted as a background terminal. It continues running in the background.",
581
- `Use bg_status with id "${snap.id}" or bg_list or /ps to inspect output. Its result will be delivered automatically when it finishes.`,
582
- "",
583
- lastPartial ? `Partial output captured in first ${AUTO_PROMOTE_SEC}s (truncated):\n${partialPreview}` : "",
584
- ]
585
- .filter(Boolean)
586
- .join("\n");
587
-
588
- if ((ctx as any).hasUI) {
589
- try { (ctx as any).ui.notify(`Bash auto-promoted to background terminal ${snap.id} (${snap.title})`, "info"); } catch {}
590
- }
591
-
592
- return {
593
- content: [{ type: "text", text }],
594
- details: { promoted: true, id: snap.id, title: snap.title, pid: snap.pid, cwd, command },
595
- };
596
- },
597
- });
598
-
599
- // --- Command ------------------------------------------------------------
600
-
601
- pi.registerCommand("ps", {
602
- description: "List and inspect background terminals",
603
- handler: async (_args, ctx) => {
604
- const manager = await getManager();
605
- if (ctx.mode !== "tui") {
606
- if (ctx.hasUI) {
607
- const terminals = manager.view.list();
608
- ctx.ui.notify(
609
- terminals.length === 0
610
- ? "No background terminals."
611
- : terminals.map((snap) => describeTerminal(snap)).join("\n"),
612
- "info",
613
- );
614
- }
615
- return;
616
- }
617
- if (manager.view.size() === 0) {
618
- ctx.ui.notify(
619
- "No background terminals yet. The agent starts them with bg_start.",
620
- "info",
621
- );
622
- return;
623
- }
624
- await openTerminalPicker(ctx, manager.view);
625
- },
626
- });
627
- }
1
+ /**
2
+ * Background terminals — start long-running shell processes the model can
3
+ * inspect and stop, but never write to (stdin is ignored at the OS level).
4
+ *
5
+ * Tools (for the LLM):
6
+ * - bg_start: fire-and-forget spawn (command, title, working_dir). Max 8
7
+ * running at once. The model is notified exactly once when a process exits.
8
+ * - bg_status: peek at one terminal's status + tail-truncated output.
9
+ * - bg_list: list all tracked terminals (running and settled).
10
+ * - bg_kill: SIGTERM→SIGKILL the whole process tree; returns final state.
11
+ *
12
+ * While ≥1 process runs, a one-line widget above the editor shows
13
+ * "N background terminal(s) running • /ps to view". `/ps` opens a two-stage
14
+ * full-screen overlay (list → read-only detail with stdout/stderr toggle).
15
+ *
16
+ * Architecture: Effect v4 core (manager service behind one ManagedRuntime);
17
+ * this file is the async boundary where tool handlers run effects via
18
+ * runTool. Node stream plumbing inside the manager is plain callbacks.
19
+ */
20
+
21
+ import * as fs from "node:fs";
22
+ import * as path from "node:path";
23
+ import type {
24
+ ExtensionAPI,
25
+ ExtensionContext,
26
+ ExtensionUIContext,
27
+ } from "@earendil-works/pi-coding-agent";
28
+ import { getMarkdownTheme } from "@earendil-works/pi-coding-agent";
29
+ import { Markdown, Text } from "@earendil-works/pi-tui";
30
+ import { Type } from "typebox";
31
+ import type { TerminalSnapshot } from "./src/domain.ts";
32
+ import { TerminalManager, type TerminalManagerShape } from "./src/manager.ts";
33
+ import {
34
+ BG_KILL_PARAMETER_DESCRIPTIONS,
35
+ BG_KILL_TOOL_DESCRIPTION,
36
+ BG_LIST_TOOL_DESCRIPTION,
37
+ BG_START_PARAMETER_DESCRIPTIONS,
38
+ BG_START_PROMPT_GUIDELINES,
39
+ BG_START_PROMPT_SNIPPET,
40
+ BG_START_TOOL_DESCRIPTION,
41
+ BG_STATUS_PARAMETER_DESCRIPTIONS,
42
+ BG_STATUS_TOOL_DESCRIPTION,
43
+ buildKillReport,
44
+ buildStartResult,
45
+ buildStatusResult,
46
+ buildTerminalResultMessage,
47
+ describeTerminal,
48
+ } from "./src/prompt.ts";
49
+ import { createDeferredResultDelivery } from "./src/result-delivery.ts";
50
+ import {
51
+ createTerminalRuntime,
52
+ runTool,
53
+ type TerminalRuntime,
54
+ } from "./src/runtime.ts";
55
+ import { sanitizeText } from "./src/ui/output-view.ts";
56
+ import { openTerminalPicker } from "./src/ui/ps.ts";
57
+ import { createBashTool } from "@earendil-works/pi-coding-agent";
58
+
59
+ const WIDGET_KEY = "background-terminals";
60
+
61
+ const AUTO_PROMOTE_MS = 50_000;
62
+ const AUTO_PROMOTE_SEC = AUTO_PROMOTE_MS / 1000;
63
+
64
+ const RESULT_PREVIEW_LINES = 10;
65
+
66
+ /** Tool call line: bold-white tool name, 2-space indent (Box adds 1 + Text 1). */
67
+ function renderToolCall(name: string, theme: any): Text {
68
+ return new Text(theme.fg("toolTitle", theme.bold(name)), 1, 0);
69
+ }
70
+
71
+ /** Tool result: grey text at 2-space indent, collapsed to a short preview. */
72
+ function renderToolResult(result: any, theme: any): Text {
73
+ const text = (result?.content ?? [])
74
+ .filter((c: any) => c?.type === "text" && typeof c?.text === "string")
75
+ .map((c: any) => c.text)
76
+ .join("\n");
77
+ if (!text) return new Text("", 1, 0);
78
+ const lines = text.split("\n");
79
+ const preview = lines.slice(0, RESULT_PREVIEW_LINES);
80
+ let out = theme.fg("toolOutput", preview.join("\n"));
81
+ if (lines.length > RESULT_PREVIEW_LINES) {
82
+ out += theme.fg("dim", `\n... (${lines.length - RESULT_PREVIEW_LINES} more lines)`);
83
+ }
84
+ return new Text(out, 1, 0);
85
+ }
86
+
87
+ export default function (pi: ExtensionAPI) {
88
+ let runtime: TerminalRuntime | undefined;
89
+ let managerPromise: Promise<TerminalManagerShape> | undefined;
90
+ let sessionContext: ExtensionContext | undefined;
91
+ let ui: ExtensionUIContext | undefined;
92
+ let unsubStatus: (() => void) | undefined;
93
+ const resultDelivery = createDeferredResultDelivery<TerminalSnapshot>();
94
+
95
+ const getRuntime = () => (runtime ??= createTerminalRuntime());
96
+
97
+ /** Resolve the manager service once per runtime and wire the extension hooks. */
98
+ const getManager = () => {
99
+ managerPromise ??= getRuntime()
100
+ .runPromise(TerminalManager)
101
+ .then((manager) => {
102
+ manager.view.setOnSettled(onSettled);
103
+ unsubStatus?.();
104
+ unsubStatus = manager.view.subscribe(() => updateWidget(manager));
105
+ updateWidget(manager);
106
+ return manager;
107
+ });
108
+ return managerPromise;
109
+ };
110
+
111
+ /** One-line widget directly above the editor, only while ≥1 is running.
112
+ * Called on every manager notification (including per-output-chunk), so it
113
+ * only touches setWidget when the running count actually changes —
114
+ * replacing the widget factory hundreds of times a second would churn
115
+ * component creation for no visible difference. */
116
+ let widgetRunning = 0;
117
+ const updateWidget = (manager: TerminalManagerShape) => {
118
+ if (!ui) return;
119
+ try {
120
+ const running = manager.view
121
+ .list()
122
+ .filter((snap) => snap.status === "running").length;
123
+ if (running === widgetRunning) return;
124
+ widgetRunning = running;
125
+ if (running === 0) {
126
+ ui.setWidget(WIDGET_KEY, undefined);
127
+ return;
128
+ }
129
+ ui.setWidget(WIDGET_KEY, (_tui, theme) => {
130
+ const line =
131
+ theme.fg("warning", "■ ") +
132
+ theme.fg(
133
+ "text",
134
+ `${running} background terminal${running === 1 ? "" : "s"} running`,
135
+ ) +
136
+ theme.fg("dim", " • ") +
137
+ theme.fg("accent", "/ps") +
138
+ theme.fg("dim", " to view");
139
+ return { render: () => [line], invalidate: () => {} };
140
+ });
141
+ } catch {
142
+ // UI may be unavailable (print/RPC modes or teardown).
143
+ }
144
+ };
145
+
146
+ const deliverResult = (snap: TerminalSnapshot) => {
147
+ try {
148
+ pi.sendMessage(
149
+ {
150
+ customType: "background-terminal-result",
151
+ content: buildTerminalResultMessage(snap),
152
+ display: true,
153
+ details: {
154
+ id: snap.id,
155
+ title: snap.title,
156
+ status: snap.status,
157
+ exitCode: snap.exitCode,
158
+ signal: snap.signal,
159
+ },
160
+ },
161
+ // followUp: queued until the agent has no more tool calls — never
162
+ // interrupts a mid-turn stream. triggerTurn: wakes the model
163
+ // immediately iff idle; if busy, the queued follow-up is delivered
164
+ // when the current run settles. Either way exactly one delivery.
165
+ { deliverAs: "followUp", triggerTurn: true },
166
+ );
167
+ return true;
168
+ } catch (error) {
169
+ // Session may be shutting down, but retain the snapshot so any later
170
+ // agent-settled flush can retry instead of silently dropping it.
171
+ console.error("background-terminals: failed to deliver result", error);
172
+ return false;
173
+ }
174
+ };
175
+
176
+ const flushResults = () => {
177
+ for (const snap of resultDelivery.drain()) {
178
+ if (!deliverResult(snap)) resultDelivery.defer(snap);
179
+ }
180
+ };
181
+
182
+ const onSettled = (snap: TerminalSnapshot, consumed: boolean) => {
183
+ if (consumed) {
184
+ // An in-flight bg_kill is returning this settlement itself.
185
+ resultDelivery.consume([snap.id]);
186
+ return;
187
+ }
188
+ // Defer a deep-enough copy: the live snapshot's output views keep
189
+ // mutating (late flushes) after settle.
190
+ resultDelivery.defer({
191
+ ...snap,
192
+ stdout: { ...snap.stdout },
193
+ stderr: { ...snap.stderr },
194
+ });
195
+ if (sessionContext?.isIdle()) flushResults();
196
+ };
197
+
198
+ pi.on("session_start", (_event, ctx) => {
199
+ sessionContext = ctx;
200
+ if (ctx.hasUI) ui = ctx.ui;
201
+ });
202
+
203
+ // Drain deferred results when the agent settles: together with the
204
+ // isIdle() fast path above and the Map-keyed delivery (drain clears),
205
+ // double delivery is structurally impossible — whoever drains first wins.
206
+ pi.on("agent_settled", flushResults);
207
+
208
+ // /new, /resume, /fork, /reload, and quit all emit session_shutdown for
209
+ // the old extension instance. Processes never survive a session
210
+ // transition: disposing the runtime runs the manager finalizer →
211
+ // disposeAll → every entry scope → SIGTERM→SIGKILL tree kill, each close
212
+ // bounded so a wedged process cannot hang shutdown.
213
+ pi.on("session_shutdown", async () => {
214
+ sessionContext = undefined;
215
+ resultDelivery.clear();
216
+ unsubStatus?.();
217
+ unsubStatus = undefined;
218
+ try {
219
+ ui?.setWidget(WIDGET_KEY, undefined);
220
+ } catch {
221
+ // UI may already be gone.
222
+ }
223
+ widgetRunning = 0;
224
+ ui = undefined;
225
+ const closing = runtime;
226
+ runtime = undefined;
227
+ managerPromise = undefined;
228
+ await closing?.dispose();
229
+ });
230
+
231
+ // --- Tools -------------------------------------------------------------
232
+
233
+ pi.registerTool({
234
+ name: "bg_start",
235
+ label: "Start Background Terminal",
236
+ renderCall: (_args: any, theme: any) => renderToolCall("bg_start", theme),
237
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
238
+ description: BG_START_TOOL_DESCRIPTION,
239
+ promptSnippet: BG_START_PROMPT_SNIPPET,
240
+ promptGuidelines: BG_START_PROMPT_GUIDELINES,
241
+ parameters: Type.Object({
242
+ command: Type.String({
243
+ description: BG_START_PARAMETER_DESCRIPTIONS.command,
244
+ }),
245
+ title: Type.String({
246
+ description: BG_START_PARAMETER_DESCRIPTIONS.title,
247
+ }),
248
+ working_dir: Type.Optional(
249
+ Type.String({
250
+ description: BG_START_PARAMETER_DESCRIPTIONS.workingDir,
251
+ }),
252
+ ),
253
+ }),
254
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
255
+ const manager = await getManager();
256
+
257
+ const command = params.command.trim();
258
+ if (!command) throw new Error("command must not be empty.");
259
+
260
+ const cwd = path.resolve(ctx.cwd, params.working_dir ?? ".");
261
+ if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) {
262
+ throw new Error(`working_dir is not a directory: ${cwd}`);
263
+ }
264
+
265
+ // Collapse whitespace (a newline inside a one-line UI row desyncs the
266
+ // TUI renderer) before bounding the length.
267
+ const title =
268
+ params.title.replace(/\s+/g, " ").trim().slice(0, 80) || "terminal";
269
+ const snap = await runTool(
270
+ getRuntime(),
271
+ manager.start({ command, title, cwd }),
272
+ );
273
+
274
+ return {
275
+ content: [{ type: "text", text: buildStartResult(snap) }],
276
+ details: { id: snap.id, title: snap.title, cwd, pid: snap.pid },
277
+ };
278
+ },
279
+ });
280
+
281
+ pi.registerTool({
282
+ name: "bg_status",
283
+ label: "Check Background Terminal",
284
+ renderCall: (_args: any, theme: any) => renderToolCall("bg_status", theme),
285
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
286
+ description: BG_STATUS_TOOL_DESCRIPTION,
287
+ parameters: Type.Object({
288
+ id: Type.String({ description: BG_STATUS_PARAMETER_DESCRIPTIONS.id }),
289
+ }),
290
+ async execute(_toolCallId, params) {
291
+ const manager = await getManager();
292
+ const snap = manager.view.get(params.id);
293
+ if (!snap) {
294
+ const known = manager.view.list().map((s) => s.id);
295
+ throw new Error(
296
+ `Unknown terminal id "${params.id}". Known: ${known.join(", ") || "none"}.`,
297
+ );
298
+ }
299
+
300
+ // This status is returning the settlement itself; a pending automatic
301
+ // follow-up for the same settle would be a duplicate.
302
+ if (snap.status !== "running") resultDelivery.consume([snap.id]);
303
+
304
+ return {
305
+ content: [{ type: "text", text: buildStatusResult(snap) }],
306
+ details: {
307
+ id: snap.id,
308
+ status: snap.status,
309
+ pid: snap.pid,
310
+ exitCode: snap.exitCode,
311
+ signal: snap.signal,
312
+ },
313
+ };
314
+ },
315
+ });
316
+
317
+ pi.registerTool({
318
+ name: "bg_list",
319
+ label: "List Background Terminals",
320
+ renderCall: (_args: any, theme: any) => renderToolCall("bg_list", theme),
321
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
322
+ description: BG_LIST_TOOL_DESCRIPTION,
323
+ parameters: Type.Object({}),
324
+ async execute() {
325
+ const manager = await getManager();
326
+ const terminals = manager.view.list();
327
+ const text =
328
+ terminals.length === 0
329
+ ? "No background terminals."
330
+ : terminals.map((snap) => describeTerminal(snap)).join("\n");
331
+ return {
332
+ content: [{ type: "text", text }],
333
+ details: {
334
+ terminals: terminals.map((snap) => ({
335
+ id: snap.id,
336
+ title: snap.title,
337
+ status: snap.status,
338
+ pid: snap.pid,
339
+ })),
340
+ },
341
+ };
342
+ },
343
+ });
344
+
345
+ pi.registerTool({
346
+ name: "bg_kill",
347
+ label: "Kill Background Terminals",
348
+ renderCall: (_args: any, theme: any) => renderToolCall("bg_kill", theme),
349
+ renderResult: (result: any, _options: any, theme: any) => renderToolResult(result, theme),
350
+ description: BG_KILL_TOOL_DESCRIPTION,
351
+ parameters: Type.Object({
352
+ ids: Type.Array(Type.String(), {
353
+ description: BG_KILL_PARAMETER_DESCRIPTIONS.ids,
354
+ }),
355
+ }),
356
+ async execute(_toolCallId, params, signal) {
357
+ const manager = await getManager();
358
+ const ids = [...new Set(params.ids)];
359
+ if (ids.length === 0)
360
+ throw new Error("Provide at least one terminal id.");
361
+
362
+ const known = manager.view.list().map((snap) => snap.id);
363
+ const unknown = ids.filter((id) => !manager.view.get(id));
364
+ if (unknown.length > 0) {
365
+ throw new Error(
366
+ `Unknown terminal id(s): ${unknown.join(", ")}. Known: ${known.join(", ") || "none"}.`,
367
+ );
368
+ }
369
+
370
+ const report = await runTool(getRuntime(), manager.kill(ids), {
371
+ signal,
372
+ interruptMessage:
373
+ "Kill wait aborted; termination continues in the background.",
374
+ });
375
+
376
+ // Settlement may have happened before this kill began (or during it,
377
+ // via the killInterest consumed flag). Remove any deferred automatic
378
+ // delivery now that this tool returns the final state itself.
379
+ resultDelivery.consume(ids);
380
+
381
+ return {
382
+ content: [{ type: "text", text: buildKillReport(report) }],
383
+ details: {
384
+ results: report.map((entry) => ({
385
+ id: entry.id,
386
+ title: entry.title,
387
+ status: entry.status,
388
+ killed: entry.killed,
389
+ })),
390
+ },
391
+ };
392
+ },
393
+ });
394
+
395
+ // --- Result message rendering ------------------------------------------
396
+
397
+ pi.registerMessageRenderer(
398
+ "background-terminal-result",
399
+ (message, { expanded }, theme) => {
400
+ const details = (message.details ?? {}) as {
401
+ id?: string;
402
+ title?: string;
403
+ status?: string;
404
+ exitCode?: number;
405
+ signal?: string;
406
+ };
407
+ const failed = details.status === "failed";
408
+ const killed = details.status === "killed";
409
+ const icon = failed
410
+ ? theme.fg("error", "x")
411
+ : killed
412
+ ? theme.fg("muted", "■")
413
+ : theme.fg("success", "■");
414
+ const how = killed
415
+ ? "killed"
416
+ : (details.signal ?? `exit ${details.exitCode ?? "?"}`);
417
+ const header =
418
+ `${icon} ` +
419
+ theme.fg("accent", theme.bold(`terminal ${details.id ?? "?"}`)) +
420
+ theme.fg("muted", ` · ${details.title ?? ""} · ${how}`);
421
+
422
+ const content =
423
+ typeof message.content === "string" ? message.content : "";
424
+ // Remove only the summary line; the Error line (when present) is part
425
+ // of the actual result and must remain visible. The body carries raw
426
+ // process output — sanitize ANSI/control chars or the transcript smears.
427
+ const body = sanitizeText(content.split("\n").slice(1).join("\n").trim());
428
+
429
+ if (expanded) {
430
+ const md = new Markdown(`${body}`, 0, 0, getMarkdownTheme());
431
+ const container = new Text(header, 0, 0);
432
+ return {
433
+ render: (width: number) => [
434
+ ...container.render(width),
435
+ ...md.render(width),
436
+ ],
437
+ invalidate: () => {
438
+ container.invalidate();
439
+ md.invalidate();
440
+ },
441
+ };
442
+ }
443
+
444
+ const previewLines = body.split("\n").slice(0, 8);
445
+ let text = header;
446
+ for (const line of previewLines)
447
+ text += `\n${theme.fg("toolOutput", line)}`;
448
+ if (body.split("\n").length > 8)
449
+ text += `\n${theme.fg("dim", "... (ctrl+o to expand)")}`;
450
+ return new Text(text, 0, 0);
451
+ },
452
+ );
453
+
454
+ // --- Auto-promote long bash to background ---------------------------------
455
+ // If a bash tool call exceeds 50s, abort the blocking call, restart it
456
+ // as a background terminal, and alert the agent + UI. The background
457
+ // result is still delivered as a follow-up when it settles.
458
+ const baseBashTool: any = createBashTool(process.cwd());
459
+ pi.registerTool({
460
+ ...baseBashTool,
461
+ description: `${baseBashTool.description} If execution exceeds ${AUTO_PROMOTE_SEC}s it is automatically promoted to a background terminal (check with bg_status/bg_list or /ps; result arrives as follow-up).`,
462
+ async execute(
463
+ toolCallId: string,
464
+ params: any,
465
+ signal: AbortSignal | undefined,
466
+ onUpdate: any,
467
+ ctx: ExtensionContext,
468
+ ) {
469
+ const command: string = params.command;
470
+ const cwd = (ctx as any).cwd ?? process.cwd();
471
+ const title = command.replace(/\s+/g, " ").trim().slice(0, 80) || "bash auto-promoted";
472
+
473
+ // Delegate tool bound to the current cwd so built-in bash semantics
474
+ // (shell, env, truncation) stay identical for the fast path.
475
+ const delegateTool: any = createBashTool(cwd);
476
+
477
+ let lastPartial = "";
478
+ const wrappedOnUpdate = (update: any) => {
479
+ try {
480
+ const text = update?.content?.[0]?.text;
481
+ if (typeof text === "string") lastPartial = text;
482
+ } catch {}
483
+ if (onUpdate) try { onUpdate(update); } catch {}
484
+ };
485
+
486
+ const execAbortController = new AbortController();
487
+ const onIncomingAbort = () => execAbortController.abort();
488
+ if (signal) {
489
+ if (signal.aborted) execAbortController.abort();
490
+ else signal.addEventListener("abort", onIncomingAbort, { once: true });
491
+ }
492
+
493
+ const execPromise: Promise<{ kind: "done"; res: any } | { kind: "error"; err: unknown }> = delegateTool
494
+ .execute(toolCallId, params, execAbortController.signal, wrappedOnUpdate, ctx as any)
495
+ .then(
496
+ (res: any) => ({ kind: "done" as const, res }),
497
+ (err: unknown) => ({ kind: "error" as const, err }),
498
+ );
499
+
500
+ let timerId: ReturnType<typeof setTimeout> | undefined;
501
+ const timerPromise = new Promise<{ kind: "promote" }>((resolve) => {
502
+ timerId = setTimeout(() => resolve({ kind: "promote" }), AUTO_PROMOTE_MS);
503
+ });
504
+
505
+ const race = (await Promise.race([execPromise, timerPromise])) as
506
+ | { kind: "done"; res: any }
507
+ | { kind: "error"; err: unknown }
508
+ | { kind: "promote" };
509
+
510
+ if (race.kind !== "promote") {
511
+ if (timerId) clearTimeout(timerId);
512
+ if (signal) signal.removeEventListener("abort", onIncomingAbort);
513
+ if (race.kind === "done") return race.res;
514
+ throw race.err;
515
+ }
516
+
517
+ // Timer won — promote to background terminal.
518
+ // Abort the original blocking execution (kills its process tree).
519
+ execAbortController.abort();
520
+ if (signal) signal.removeEventListener("abort", onIncomingAbort);
521
+
522
+ // If the caller already aborted (Esc), don't promote — just propagate.
523
+ if (signal?.aborted) {
524
+ try {
525
+ const settled = await execPromise;
526
+ if (settled.kind === "error") throw settled.err;
527
+ return (settled as any).res;
528
+ } catch (e) {
529
+ throw e;
530
+ }
531
+ }
532
+
533
+ // Let the aborted exec settle (or timeout after 2s if it hangs).
534
+ try {
535
+ await Promise.race([
536
+ execPromise.catch(() => {}),
537
+ new Promise((r) => setTimeout(r, 2000)),
538
+ ]);
539
+ } catch {}
540
+
541
+ let snap: TerminalSnapshot | undefined;
542
+ let spawnError: unknown;
543
+ try {
544
+ const manager = await getManager();
545
+ snap = await runTool(getRuntime(), manager.start({ command, title, cwd }));
546
+ } catch (e) {
547
+ spawnError = e;
548
+ }
549
+
550
+ if (!snap || spawnError) {
551
+ const msg = spawnError instanceof Error ? spawnError.message : String(spawnError ?? "unknown error");
552
+ const text = [
553
+ `⚠️ Bash command exceeded ${AUTO_PROMOTE_SEC}s but could not be promoted to a background terminal: ${msg}`,
554
+ "",
555
+ `Command: ${command}`,
556
+ "",
557
+ lastPartial ? `Partial output (first ${AUTO_PROMOTE_SEC}s, truncated):\n${lastPartial.slice(-3000)}` : "No output captured before promotion attempt.",
558
+ "",
559
+ "The original blocking command was aborted. Retry with bg_start directly or free a slot with bg_kill (/ps).",
560
+ ].join("\n");
561
+ if ((ctx as any).hasUI) {
562
+ try { (ctx as any).ui.notify(`Bash auto-promote failed: ${msg}`, "warning"); } catch {}
563
+ }
564
+ return {
565
+ content: [{ type: "text", text }],
566
+ details: { promoted: false, error: msg, command, cwd, partialOutput: lastPartial },
567
+ };
568
+ }
569
+
570
+ const partialPreview = lastPartial ? lastPartial.slice(-3000) : "(no output yet)";
571
+ const text = [
572
+ `⏳ Bash command exceeded ${AUTO_PROMOTE_SEC}s and was automatically moved to a background terminal.`,
573
+ "",
574
+ `• Terminal ID: ${snap.id}`,
575
+ `• Title: ${snap.title}`,
576
+ `• Command: ${command}`,
577
+ `• CWD: ${cwd}`,
578
+ `• PID: ${snap.pid ?? "pending"}`,
579
+ "",
580
+ "The original blocking bash call was aborted and the command was restarted as a background terminal. It continues running in the background.",
581
+ `Use bg_status with id "${snap.id}" or bg_list or /ps to inspect output. Its result will be delivered automatically when it finishes.`,
582
+ "",
583
+ lastPartial ? `Partial output captured in first ${AUTO_PROMOTE_SEC}s (truncated):\n${partialPreview}` : "",
584
+ ]
585
+ .filter(Boolean)
586
+ .join("\n");
587
+
588
+ if ((ctx as any).hasUI) {
589
+ try { (ctx as any).ui.notify(`Bash auto-promoted to background terminal ${snap.id} (${snap.title})`, "info"); } catch {}
590
+ }
591
+
592
+ return {
593
+ content: [{ type: "text", text }],
594
+ details: { promoted: true, id: snap.id, title: snap.title, pid: snap.pid, cwd, command },
595
+ };
596
+ },
597
+ });
598
+
599
+ // --- Command ------------------------------------------------------------
600
+
601
+ pi.registerCommand("ps", {
602
+ description: "List and inspect background terminals",
603
+ handler: async (_args, ctx) => {
604
+ const manager = await getManager();
605
+ if (ctx.mode !== "tui") {
606
+ if (ctx.hasUI) {
607
+ const terminals = manager.view.list();
608
+ ctx.ui.notify(
609
+ terminals.length === 0
610
+ ? "No background terminals."
611
+ : terminals.map((snap) => describeTerminal(snap)).join("\n"),
612
+ "info",
613
+ );
614
+ }
615
+ return;
616
+ }
617
+ if (manager.view.size() === 0) {
618
+ ctx.ui.notify(
619
+ "No background terminals yet. The agent starts them with bg_start.",
620
+ "info",
621
+ );
622
+ return;
623
+ }
624
+ await openTerminalPicker(ctx, manager.view);
625
+ },
626
+ });
627
+ }