@asterxsk/kiln 0.4.0 → 0.4.2

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 (259) hide show
  1. package/README.md +155 -155
  2. package/agent/AGENTS.md +67 -67
  3. package/agent/README.md +5 -5
  4. package/agent/extensions/ask-user/index.ts +418 -418
  5. package/agent/extensions/ask-user/install.ps1 +27 -27
  6. package/agent/extensions/ask-user/install.sh +24 -24
  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/install.ps1 +27 -27
  14. package/agent/extensions/background-terminals/install.sh +24 -24
  15. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  16. package/agent/extensions/background-terminals/output.test.ts +109 -109
  17. package/agent/extensions/background-terminals/package-lock.json +769 -769
  18. package/agent/extensions/background-terminals/package.json +17 -17
  19. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  20. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  21. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  22. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  23. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  24. package/agent/extensions/background-terminals/src/output.ts +84 -84
  25. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  26. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  27. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  28. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  29. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  30. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  31. package/agent/extensions/destructive/README.md +31 -31
  32. package/agent/extensions/destructive/index.ts +88 -88
  33. package/agent/extensions/destructive/install.ps1 +27 -27
  34. package/agent/extensions/destructive/install.sh +24 -24
  35. package/agent/extensions/file-search/index.spec.ts +443 -443
  36. package/agent/extensions/file-search/index.ts +459 -459
  37. package/agent/extensions/file-search/install.ps1 +27 -27
  38. package/agent/extensions/file-search/install.sh +24 -24
  39. package/agent/extensions/file-search/package-lock.json +2253 -2253
  40. package/agent/extensions/file-search/package.json +23 -23
  41. package/agent/extensions/file-search/src/args.ts +122 -122
  42. package/agent/extensions/file-search/src/binaries.ts +422 -422
  43. package/agent/extensions/file-search/src/output.ts +126 -126
  44. package/agent/extensions/file-search/src/process.ts +146 -146
  45. package/agent/extensions/file-search/src/prompt.ts +52 -52
  46. package/agent/extensions/file-search/tsconfig.json +7 -7
  47. package/agent/extensions/goal/README.md +50 -50
  48. package/agent/extensions/goal/index.ts +155 -155
  49. package/agent/extensions/goal/install.ps1 +27 -27
  50. package/agent/extensions/goal/install.sh +24 -24
  51. package/agent/extensions/kiln-update/README.md +38 -25
  52. package/agent/extensions/kiln-update/index.ts +177 -99
  53. package/agent/extensions/modelconf/PLAN.md +915 -915
  54. package/agent/extensions/modelconf/README.md +66 -66
  55. package/agent/extensions/modelconf/index.ts +296 -296
  56. package/agent/extensions/modelconf/install.ps1 +27 -27
  57. package/agent/extensions/modelconf/install.sh +24 -24
  58. package/agent/extensions/modelconf/package-lock.json +1809 -1809
  59. package/agent/extensions/modelconf/package.json +13 -13
  60. package/agent/extensions/modelconf/src/fuzzy.ts +26 -26
  61. package/agent/extensions/modelconf/src/glob.ts +13 -13
  62. package/agent/extensions/modelconf/src/persistence.test.ts +46 -46
  63. package/agent/extensions/modelconf/src/persistence.ts +164 -164
  64. package/agent/extensions/modelconf/src/ui/ModelConfView.test.ts +75 -75
  65. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  66. package/agent/extensions/modelconf/tsconfig.json +15 -15
  67. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  68. package/agent/extensions/pi-web-access/LICENSE +21 -21
  69. package/agent/extensions/pi-web-access/README.md +470 -470
  70. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  71. package/agent/extensions/pi-web-access/activity.ts +101 -101
  72. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  73. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  74. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  75. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  76. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  77. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  78. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  79. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  80. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  81. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  82. package/agent/extensions/pi-web-access/exa.ts +526 -526
  83. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  84. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  85. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  86. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  87. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  88. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  89. package/agent/extensions/pi-web-access/gemini-search.ts +21 -21
  90. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  91. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  92. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  93. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  94. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  95. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  96. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  97. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  98. package/agent/extensions/pi-web-access/package.json +64 -64
  99. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  100. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  101. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  102. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  103. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  104. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  105. package/agent/extensions/pi-web-access/search-types.ts +20 -20
  106. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  107. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  108. package/agent/extensions/pi-web-access/storage.ts +521 -521
  109. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  110. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  111. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  112. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  113. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  114. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  115. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  116. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  117. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  118. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  119. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  120. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  121. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  122. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  123. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  124. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  125. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  126. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  127. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  128. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  129. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  130. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  131. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  132. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  133. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  134. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  135. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  136. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  137. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  138. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  139. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  140. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  141. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  142. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  143. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  144. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  145. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  146. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  147. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  148. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  149. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  150. package/agent/extensions/pi-web-access/test/summary-model-scope.test.mjs +106 -106
  151. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  152. package/agent/extensions/pi-web-access/test/web-search-answer-render.test.mjs +66 -66
  153. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  154. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  155. package/agent/extensions/pi-web-access/utils.ts +451 -451
  156. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  157. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  158. package/agent/extensions/shared/activity-status.ts +31 -31
  159. package/agent/extensions/shared/child-session.test.ts +270 -270
  160. package/agent/extensions/shared/child-session.ts +148 -148
  161. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  162. package/agent/extensions/shared/context-utilization.ts +47 -47
  163. package/agent/extensions/shared/dashboard-state.ts +99 -99
  164. package/agent/extensions/shared/install.ps1 +27 -27
  165. package/agent/extensions/shared/install.sh +24 -24
  166. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  167. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  168. package/agent/extensions/skillsconf/README.md +74 -74
  169. package/agent/extensions/skillsconf/index.ts +92 -92
  170. package/agent/extensions/skillsconf/install.ps1 +27 -27
  171. package/agent/extensions/skillsconf/install.sh +24 -24
  172. package/agent/extensions/skillsconf/package-lock.json +1809 -1809
  173. package/agent/extensions/skillsconf/package.json +18 -18
  174. package/agent/extensions/skillsconf/src/delete-skill.test.ts +64 -64
  175. package/agent/extensions/skillsconf/src/delete-skill.ts +45 -45
  176. package/agent/extensions/skillsconf/src/filter.test.ts +80 -80
  177. package/agent/extensions/skillsconf/src/filter.ts +74 -74
  178. package/agent/extensions/skillsconf/src/fuzzy.ts +26 -26
  179. package/agent/extensions/skillsconf/src/persistence.test.ts +72 -72
  180. package/agent/extensions/skillsconf/src/persistence.ts +169 -169
  181. package/agent/extensions/skillsconf/src/ui/SkillConfView.test.ts +337 -337
  182. package/agent/extensions/skillsconf/src/ui/SkillConfView.ts +758 -758
  183. package/agent/extensions/skillsconf/src/ui/text-input.ts +91 -91
  184. package/agent/extensions/skillsconf/src/ui/tui-helpers.ts +144 -144
  185. package/agent/extensions/skillsconf/tsconfig.json +15 -15
  186. package/agent/extensions/statusline/index.ts +273 -282
  187. package/agent/extensions/statusline/install.ps1 +27 -27
  188. package/agent/extensions/statusline/install.sh +24 -24
  189. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  190. package/agent/extensions/subagents/claude.test.ts +119 -119
  191. package/agent/extensions/subagents/codex.test.ts +102 -102
  192. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  193. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  194. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  195. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  196. package/agent/extensions/subagents/index.ts +779 -779
  197. package/agent/extensions/subagents/install.ps1 +27 -27
  198. package/agent/extensions/subagents/install.sh +24 -24
  199. package/agent/extensions/subagents/manager.test.ts +276 -276
  200. package/agent/extensions/subagents/package-lock.json +2244 -2244
  201. package/agent/extensions/subagents/package.json +19 -19
  202. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  203. package/agent/extensions/subagents/src/backend.ts +73 -73
  204. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  205. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  206. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  207. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  208. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  209. package/agent/extensions/subagents/src/domain.ts +253 -253
  210. package/agent/extensions/subagents/src/format.ts +74 -74
  211. package/agent/extensions/subagents/src/manager.ts +736 -736
  212. package/agent/extensions/subagents/src/prompt.ts +92 -92
  213. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  214. package/agent/extensions/subagents/src/runtime.ts +53 -53
  215. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  216. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  217. package/agent/extensions/subagents/takeover.test.ts +29 -29
  218. package/agent/extensions/subagents/tsconfig.json +7 -7
  219. package/agent/extensions/todo/AGENTS.md +38 -38
  220. package/agent/extensions/todo/LICENSE +21 -21
  221. package/agent/extensions/todo/config.ts +55 -55
  222. package/agent/extensions/todo/index.ts +151 -151
  223. package/agent/extensions/todo/install.ps1 +27 -27
  224. package/agent/extensions/todo/install.sh +24 -24
  225. package/agent/extensions/todo/locales/de.json +17 -17
  226. package/agent/extensions/todo/locales/en.json +15 -15
  227. package/agent/extensions/todo/locales/es.json +17 -17
  228. package/agent/extensions/todo/locales/fr.json +17 -17
  229. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  230. package/agent/extensions/todo/locales/pt.json +17 -17
  231. package/agent/extensions/todo/locales/ru.json +17 -17
  232. package/agent/extensions/todo/locales/uk.json +17 -17
  233. package/agent/extensions/todo/locales/zh.json +17 -17
  234. package/agent/extensions/todo/package-lock.json +3358 -3358
  235. package/agent/extensions/todo/package.json +67 -67
  236. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  237. package/agent/extensions/todo/state/invariants.ts +20 -20
  238. package/agent/extensions/todo/state/replay.ts +38 -38
  239. package/agent/extensions/todo/state/selectors.ts +107 -107
  240. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  241. package/agent/extensions/todo/state/state.ts +18 -18
  242. package/agent/extensions/todo/state/store.ts +82 -82
  243. package/agent/extensions/todo/state/task-graph.ts +57 -57
  244. package/agent/extensions/todo/todo-overlay.ts +200 -200
  245. package/agent/extensions/todo/todo.ts +155 -155
  246. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  247. package/agent/extensions/todo/tool/types.ts +206 -206
  248. package/agent/extensions/todo/view/format.ts +177 -177
  249. package/agent/extensions/trim-context/README.md +54 -54
  250. package/agent/extensions/trim-context/index.ts +487 -487
  251. package/agent/extensions/trim-context/install.ps1 +27 -27
  252. package/agent/extensions/trim-context/install.sh +24 -24
  253. package/agent/keybindings.json +7 -7
  254. package/agent/version.txt +1 -1
  255. package/bin/kiln.js +20 -13
  256. package/package.json +1 -1
  257. package/agent/extensions/taste/index.ts +0 -443
  258. package/agent/extensions/taste/install.ps1 +0 -27
  259. package/agent/extensions/taste/install.sh +0 -24
@@ -1,907 +1,907 @@
1
- /**
2
- * TerminalManager — owns the registry of running/settled background
3
- * terminals.
4
- *
5
- * Each terminal is a raw `node:child_process` spawn (own process group on
6
- * POSIX, stdin ignored) whose stdout/stderr 'data' callbacks fold into two
7
- * bounded OutputBuffers. Closing a terminal's scope kills the whole process
8
- * tree (SIGTERM → SIGKILL escalation).
9
- *
10
- * The manager also exposes a synchronous `TerminalReadModel` so the
11
- * imperative TUI components (which render synchronously) can read snapshots
12
- * and issue fire-and-forget kills without touching the Effect runtime.
13
- */
14
-
15
- import { spawn, type ChildProcess } from "node:child_process";
16
- import * as fs from "node:fs";
17
- import * as os from "node:os";
18
- import * as path from "node:path";
19
- import {
20
- Context,
21
- Deferred,
22
- Effect,
23
- Exit,
24
- FiberSet,
25
- Layer,
26
- Scope,
27
- } from "effect";
28
- import {
29
- ConcurrencyLimitError,
30
- formatExit,
31
- SpawnError,
32
- UnknownTerminalError,
33
- type TerminalSnapshot,
34
- type TerminalStatus,
35
- } from "./domain.ts";
36
- import { OutputBuffer } from "./output.ts";
37
-
38
- export const MAX_RUNNING = 8;
39
- export const MAX_TRACKED = 32;
40
- const MAX_SETTLED_HISTORY = MAX_TRACKED * 4;
41
- /** In-memory retained cap per stream. */
42
- export const RETAINED_PER_STREAM = 2 * 1024 * 1024;
43
- /** Private full-log spills are bounded so a firehose cannot fill the temp disk. */
44
- export const MAX_SPILL_BYTES_PER_STREAM = 256 * 1024 * 1024;
45
- const STOP_TIMEOUT_MS = 5_000;
46
- /** SIGTERM is normally enough; the second deadline covers a wedged process. */
47
- const FORCE_KILL_AFTER_MS = 2_000;
48
- /** After termination, how long to wait for the natural close→flush→settle
49
- * path before force-settling (a grandchild can hold the stdio pipes open). */
50
- const SETTLE_GRACE_MS = 1_000;
51
- /** Bound on waiting for spill WriteStreams to flush before settling; a hung
52
- * filesystem must not leave an exited entry "running" (and kill() waiting).
53
- * Terminate (≤2.5s) + settle grace (1s) + flush (1.5s) stays inside the 5s
54
- * scope-close bound, so teardown remains bounded end to end. */
55
- const SPILL_FLUSH_TIMEOUT_MS = 1_500;
56
- const ERROR_TEXT_MAX_LENGTH = 4_096;
57
-
58
- function bounded(text: string) {
59
- return text.slice(0, ERROR_TEXT_MAX_LENGTH);
60
- }
61
-
62
- function boundedError(error: unknown) {
63
- return bounded(error instanceof Error ? error.message : String(error));
64
- }
65
-
66
- // --- Internal state -----------------------------------------------------------
67
-
68
- /** Mutable snapshot; exposed to readers via the readonly TerminalSnapshot type.
69
- * stdout/stderr are getters over the live OutputBuffers. */
70
- interface MutableSnapshot extends TerminalSnapshot {
71
- status: TerminalStatus;
72
- pid?: number;
73
- settledAt?: number;
74
- exitCode?: number;
75
- signal?: string;
76
- errorText?: string;
77
- }
78
-
79
- interface Entry {
80
- snapshot: MutableSnapshot;
81
- child: ChildProcess;
82
- scope: Scope.Closeable;
83
- stdoutBuf: OutputBuffer;
84
- stderrBuf: OutputBuffer;
85
- spillStreams: fs.WriteStream[];
86
- /** Set in the same synchronous effect that sends SIGTERM so a natural exit
87
- * before signaling keeps its truthful status. */
88
- killSignaled: boolean;
89
- /** The child emitted 'error' (spawn failure etc.); settles as "failed".
90
- * Kept separate from errorText, which also carries non-fatal notes
91
- * (spill failures) that must not flip a clean exit to "failed". */
92
- processErrored: boolean;
93
- /** 'exit' event observed (code/signal recorded). */
94
- exited: boolean;
95
- /** 'close' event observed (stdio flushed; the settle trigger). */
96
- stdioClosed: boolean;
97
- /** A settle-after-spill-flush is in flight; don't start a second one. */
98
- settling: boolean;
99
- /** The shell exited without stdio closing; a bounded scope close is queued
100
- * to reap descendants that still hold the inherited pipes open. */
101
- exitCleanupStarted: boolean;
102
- /** Completed exactly once when the entry settles. Kill callers and the scope
103
- * finalizer can all await the same result without missing a notification. */
104
- settled: Deferred.Deferred<void>;
105
- }
106
-
107
- export interface StartOptions {
108
- readonly command: string;
109
- readonly title: string;
110
- readonly cwd: string;
111
- }
112
-
113
- export interface KillResult {
114
- readonly id: string;
115
- readonly title: string;
116
- readonly status: TerminalStatus;
117
- /** True when the entry was still running when this kill began. */
118
- readonly wasRunning: boolean;
119
- /** True when this call initiated the termination AND the entry settled as
120
- * killed (a natural exit that won the race reports killed: false). */
121
- readonly killed: boolean;
122
- /** Final exit rendering ("exit 0", "SIGTERM", ...) captured at settle time,
123
- * so reports stay accurate even if the entry is pruned afterwards. */
124
- readonly exit: string;
125
- }
126
-
127
- // --- Read model ----------------------------------------------------------------
128
-
129
- /** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
130
- export interface TerminalReadModel {
131
- list(): ReadonlyArray<TerminalSnapshot>;
132
- get(id: string): TerminalSnapshot | undefined;
133
- size(): number;
134
- /** Any-change notification (widget, /ps list). */
135
- subscribe(listener: () => void): () => void;
136
- /** Per-terminal notification (/ps detail view). */
137
- subscribeTo(id: string, listener: () => void): () => void;
138
- /** Fire-and-forget kill (dashboard/detail `x`). Not marked consumed: the
139
- * settle still flows back to the model as a follow-up message. */
140
- requestKill(id: string): void;
141
- /**
142
- * Register the settle hook. `consumed` is true when an active bg_kill is
143
- * collecting the result (so it must not also be delivered as a follow-up).
144
- */
145
- setOnSettled(
146
- hook: ((snap: TerminalSnapshot, consumed: boolean) => void) | undefined,
147
- ): void;
148
- }
149
-
150
- // --- Service --------------------------------------------------------------------
151
-
152
- export interface TerminalManagerShape {
153
- start(
154
- options: StartOptions,
155
- ): Effect.Effect<TerminalSnapshot, SpawnError | ConcurrencyLimitError>;
156
- status(id: string): Effect.Effect<TerminalSnapshot, UnknownTerminalError>;
157
- /** Kill running terminals; resolves only after they have settled. */
158
- kill(ids: ReadonlyArray<string>): Effect.Effect<ReadonlyArray<KillResult>>;
159
- readonly list: Effect.Effect<ReadonlyArray<TerminalSnapshot>>;
160
- readonly disposeAll: Effect.Effect<void>;
161
- readonly view: TerminalReadModel;
162
- }
163
-
164
- export class TerminalManager extends Context.Service<
165
- TerminalManager,
166
- TerminalManagerShape
167
- >()("background-terminals/TerminalManager") {}
168
-
169
- // --- Process helpers ------------------------------------------------------------
170
-
171
- function shellInvocation(command: string) {
172
- if (process.platform === "win32") {
173
- const shell = process.env.ComSpec ?? "cmd.exe";
174
- return { shell, args: ["/d", "/s", "/c", command] };
175
- }
176
- return { shell: "/bin/sh", args: ["-c", command] };
177
- }
178
-
179
- /** Signal the whole process group on POSIX so descendants (servers a shell
180
- * command spawned) die with it; a wedged child must not orphan its tree. */
181
- function killTree(child: ChildProcess, signal: NodeJS.Signals) {
182
- if (process.platform === "win32" && child.pid) {
183
- try {
184
- const killer = spawn(
185
- "taskkill",
186
- [
187
- "/pid",
188
- String(child.pid),
189
- "/T",
190
- ...(signal === "SIGKILL" ? ["/F"] : []),
191
- ],
192
- { stdio: "ignore", windowsHide: true },
193
- );
194
- killer.once("error", () => {
195
- try {
196
- child.kill(signal);
197
- } catch {
198
- // Process may already be gone.
199
- }
200
- });
201
- killer.once("exit", (code) => {
202
- if (code === 0) return;
203
- try {
204
- child.kill(signal);
205
- } catch {
206
- // Process may already be gone.
207
- }
208
- });
209
- killer.unref();
210
- return;
211
- } catch {
212
- // Fall through to the direct signal when taskkill cannot be launched.
213
- }
214
- }
215
- if (process.platform !== "win32" && child.pid) {
216
- try {
217
- process.kill(-child.pid, signal);
218
- return;
219
- } catch {
220
- // Group may already be gone; fall through to the direct signal.
221
- }
222
- }
223
- try {
224
- child.kill(signal);
225
- } catch {
226
- // Process may already be gone.
227
- }
228
- }
229
-
230
- /** Await stdio closure without retaining a listener after interruption. */
231
- function awaitChildClose(child: ChildProcess, closed: () => boolean) {
232
- return Effect.callback<void>((resume) => {
233
- if (closed()) {
234
- resume(Effect.void);
235
- return;
236
- }
237
- const onClose = () => resume(Effect.void);
238
- child.once("close", onClose);
239
- return Effect.sync(() => child.off("close", onClose));
240
- });
241
- }
242
-
243
- /** SIGTERM → deadline → SIGKILL; waits for stdio closure rather than only the
244
- * shell's exit because descendants can keep the inherited pipes and process
245
- * group alive after the shell itself is gone. */
246
- function terminateChild(
247
- child: ChildProcess,
248
- closed: () => boolean,
249
- onSignal: () => void,
250
- ) {
251
- return Effect.suspend(() => {
252
- if (closed()) return Effect.void;
253
- return Effect.gen(function* () {
254
- yield* Effect.sync(() => {
255
- onSignal();
256
- killTree(child, "SIGTERM");
257
- });
258
- yield* awaitChildClose(child, closed).pipe(
259
- Effect.timeout(FORCE_KILL_AFTER_MS),
260
- Effect.ignore,
261
- );
262
- if (closed()) return;
263
- yield* Effect.sync(() => killTree(child, "SIGKILL"));
264
- yield* awaitChildClose(child, closed).pipe(
265
- Effect.timeout(500),
266
- Effect.ignore,
267
- );
268
- });
269
- });
270
- }
271
-
272
- // --- Implementation --------------------------------------------------------------
273
-
274
- const makeManager = Effect.gen(function* () {
275
- // Scoped detached forker for sync contexts (read-model kills, process-event
276
- // settlement, pruning). Completed fibers remove themselves; manager scope
277
- // close interrupts any work that outlives the bounded disposeAll wait.
278
- const cleanupFibers = yield* FiberSet.make();
279
- const runCleanup = yield* FiberSet.runtime(cleanupFibers)();
280
-
281
- const entries = new Map<string, Entry>();
282
- /** Small immutable tombstones preserve truthful kill reports if pruning
283
- * races the tool boundary after an id was validated. */
284
- const settledHistory = new Map<
285
- string,
286
- Pick<KillResult, "title" | "status" | "exit">
287
- >();
288
- /** ids with an in-flight kill() collecting the result (settle → consumed). */
289
- const killInterest = new Map<string, number>();
290
- const listeners = new Set<() => void>();
291
- const idListeners = new Map<string, Set<() => void>>();
292
- let counter = 0;
293
- let reserved = 0;
294
- let disposed = false;
295
- let spillDir: string | undefined | null;
296
- let onSettled:
297
- ((snap: TerminalSnapshot, consumed: boolean) => void) | undefined;
298
-
299
- const notify = (id?: string) => {
300
- for (const listener of [...listeners]) {
301
- try {
302
- listener();
303
- } catch {
304
- // A failed widget/render listener must not corrupt lifecycle state.
305
- }
306
- }
307
- if (id) {
308
- for (const listener of idListeners.get(id) ?? []) {
309
- try {
310
- listener();
311
- } catch {
312
- // Same.
313
- }
314
- }
315
- }
316
- };
317
-
318
- const runningCount = () =>
319
- [...entries.values()].filter((e) => e.snapshot.status === "running").length;
320
-
321
- const addKillInterest = (ids: ReadonlyArray<string>) => {
322
- for (const id of ids) killInterest.set(id, (killInterest.get(id) ?? 0) + 1);
323
- };
324
- const releaseKillInterest = (ids: ReadonlyArray<string>) => {
325
- for (const id of ids) {
326
- const count = (killInterest.get(id) ?? 1) - 1;
327
- if (count <= 0) killInterest.delete(id);
328
- else killInterest.set(id, count);
329
- }
330
- };
331
-
332
- const closeEntryScope = (entry: Entry) =>
333
- Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
334
-
335
- const pruneSettled = () => {
336
- if (entries.size <= MAX_TRACKED) return;
337
- const candidates = [...entries.values()]
338
- .filter(
339
- (e) =>
340
- e.snapshot.status !== "running" && !killInterest.has(e.snapshot.id),
341
- )
342
- .sort(
343
- (a, b) =>
344
- (a.snapshot.settledAt ?? a.snapshot.createdAt) -
345
- (b.snapshot.settledAt ?? b.snapshot.createdAt),
346
- );
347
- for (const entry of candidates) {
348
- if (entries.size <= MAX_TRACKED) break;
349
- entries.delete(entry.snapshot.id);
350
- runCleanup(closeEntryScope(entry));
351
- }
352
- };
353
-
354
- /** End all spill streams; resolves when their buffers are flushed to disk
355
- * (bounded), so a settle notification never points at a partial file. */
356
- const flushSpillStreams = (entry: Entry) => {
357
- const streams = entry.spillStreams;
358
- entry.spillStreams = [];
359
- return Effect.forEach(
360
- streams,
361
- (stream) =>
362
- Effect.callback<void>((resume) => {
363
- const done = () => resume(Effect.void);
364
- try {
365
- stream.end(done);
366
- } catch {
367
- // Best effort; tmpdir contents are disposable.
368
- done();
369
- }
370
- }),
371
- { concurrency: "unbounded", discard: true },
372
- ).pipe(
373
- Effect.timeoutOrElse({
374
- duration: SPILL_FLUSH_TIMEOUT_MS,
375
- orElse: () =>
376
- Effect.sync(() => {
377
- entry.stdoutBuf.spillPath = undefined;
378
- entry.stderrBuf.spillPath = undefined;
379
- entry.snapshot.errorText ??=
380
- "Full-log spill flush timed out; full output may be incomplete";
381
- }),
382
- }),
383
- );
384
- };
385
-
386
- /** Single settle path — idempotent; kill vs natural exit vs error races are
387
- * resolved by whichever lands first (the second call is a no-op). */
388
- const settle = (entry: Entry) => {
389
- const s = entry.snapshot;
390
- if (s.status !== "running") return;
391
- s.settledAt = Date.now();
392
- s.status = entry.killSignaled
393
- ? "killed"
394
- : entry.processErrored
395
- ? "failed"
396
- : s.exitCode === 0
397
- ? "done"
398
- : "failed";
399
- settledHistory.set(s.id, {
400
- title: s.title,
401
- status: s.status,
402
- exit: formatExit(s),
403
- });
404
- while (settledHistory.size > MAX_SETTLED_HISTORY) {
405
- const oldest = settledHistory.keys().next().value;
406
- if (oldest === undefined) break;
407
- settledHistory.delete(oldest);
408
- }
409
- // Completing the Deferred can immediately resume kill waiters, whose
410
- // ensuring blocks release interest. Snapshot consumption first so the
411
- // settle hook observes the interest that existed when settlement won.
412
- const consumed = (killInterest.get(s.id) ?? 0) > 0;
413
- Deferred.doneUnsafe(entry.settled, Effect.void);
414
- notify(s.id);
415
- try {
416
- // During teardown, don't queue results into a shutting-down session.
417
- if (!disposed) onSettled?.(s, consumed);
418
- } catch {
419
- // The parent session may be unavailable; settlement stays final.
420
- }
421
- pruneSettled();
422
- };
423
-
424
- /** Flush the spill files, then settle: the completion follow-up (and the
425
- * kill() resolution) reference the spill path, so the full capture must be
426
- * on disk before anyone is told about it. Idempotent via `settling`. */
427
- const settleAfterFlush = (entry: Entry) => {
428
- if (entry.settling || entry.snapshot.status !== "running") return;
429
- entry.settling = true;
430
- runCleanup(
431
- flushSpillStreams(entry).pipe(
432
- Effect.andThen(Effect.sync(() => settle(entry))),
433
- ),
434
- );
435
- };
436
-
437
- const scheduleExitCleanup = (entry: Entry) => {
438
- if (entry.exitCleanupStarted) return;
439
- entry.exitCleanupStarted = true;
440
- runCleanup(
441
- Effect.sleep(SETTLE_GRACE_MS).pipe(
442
- Effect.andThen(
443
- Effect.suspend(() =>
444
- entry.snapshot.status === "running" && !entry.stdioClosed
445
- ? closeEntryScope(entry).pipe(
446
- Effect.timeout(STOP_TIMEOUT_MS),
447
- Effect.ignore,
448
- )
449
- : Effect.void,
450
- ),
451
- ),
452
- ),
453
- );
454
- };
455
-
456
- const resolveSpillDir = () => {
457
- if (spillDir !== undefined) return spillDir ?? undefined;
458
- try {
459
- const base = path.join(os.tmpdir(), "pi-background-terminals");
460
- fs.mkdirSync(base, { recursive: true, mode: 0o700 });
461
- fs.chmodSync(base, 0o700);
462
- spillDir = fs.mkdtempSync(path.join(base, "session-"));
463
- fs.chmodSync(spillDir, 0o700);
464
- } catch {
465
- spillDir = null;
466
- }
467
- return spillDir ?? undefined;
468
- };
469
-
470
- const makeSpill = (
471
- entry: () => Entry | undefined,
472
- id: string,
473
- stream: "stdout" | "stderr",
474
- resumeSource: () => void,
475
- ) => {
476
- const dir = resolveSpillDir();
477
- if (!dir) return undefined;
478
- const spillPath = path.join(dir, `${id}.${stream}.log`);
479
- try {
480
- const file = fs.createWriteStream(spillPath, {
481
- flags: "a",
482
- mode: 0o600,
483
- });
484
- let broken = false;
485
- let capped = false;
486
- let writtenBytes = 0;
487
- file.on("error", (error) => {
488
- broken = true;
489
- resumeSource();
490
- const current = entry();
491
- if (current) {
492
- const buf =
493
- stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
494
- buf.spillPath = undefined;
495
- current.snapshot.errorText ??= bounded(
496
- `Full-log spill to ${spillPath} failed: ${boundedError(error)}`,
497
- );
498
- }
499
- });
500
- return {
501
- spillPath,
502
- file,
503
- write: (chunk: string) => {
504
- // writableEnded guard: late 'data' after the settle flush must not
505
- // error the ended stream (and falsely report the spill as broken).
506
- if (broken || capped || file.writableEnded) return true;
507
- const chunkBytes = Buffer.byteLength(chunk, "utf8");
508
- if (writtenBytes + chunkBytes > MAX_SPILL_BYTES_PER_STREAM) {
509
- capped = true;
510
- const current = entry();
511
- if (current) {
512
- const buf =
513
- stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
514
- buf.spillPath = undefined;
515
- current.snapshot.errorText ??= bounded(
516
- `${stream} full-log spill reached the ${MAX_SPILL_BYTES_PER_STREAM}-byte safety limit`,
517
- );
518
- }
519
- return true;
520
- }
521
- writtenBytes += chunkBytes;
522
- const accepted = file.write(chunk);
523
- if (!accepted) file.once("drain", resumeSource);
524
- return accepted;
525
- },
526
- };
527
- } catch {
528
- return undefined;
529
- }
530
- };
531
-
532
- const start = (options: StartOptions) =>
533
- Effect.gen(function* () {
534
- // Reserve synchronously (before the first yield inside doStart) so
535
- // parallel tool calls cannot race past the cap.
536
- yield* Effect.suspend(
537
- (): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
538
- if (disposed) {
539
- return new SpawnError({
540
- message: "Background terminal manager is shutting down.",
541
- });
542
- }
543
- if (runningCount() + reserved >= MAX_RUNNING) {
544
- return new ConcurrencyLimitError({
545
- message: `Max ${MAX_RUNNING} background terminals can run concurrently. Stop one with bg_kill before starting another.`,
546
- });
547
- }
548
- reserved++;
549
- return Effect.void;
550
- },
551
- );
552
-
553
- const doStart = Effect.gen(function* () {
554
- const { shell, args } = shellInvocation(options.command);
555
- const child = yield* Effect.try({
556
- try: () =>
557
- spawn(shell, args, {
558
- cwd: options.cwd,
559
- env: process.env,
560
- // stdin IGNORED: there is no input surface, ever. A process
561
- // that reads stdin sees EOF immediately.
562
- stdio: ["ignore", "pipe", "pipe"],
563
- // Own process group on POSIX → group kill takes the whole tree.
564
- detached: process.platform !== "win32",
565
- }),
566
- catch: (error) => new SpawnError({ message: boundedError(error) }),
567
- });
568
-
569
- const id = `bt-${++counter}`;
570
- const entryRef = () => entries.get(id);
571
- const stdoutSpill = makeSpill(entryRef, id, "stdout", () =>
572
- child.stdout?.resume(),
573
- );
574
- const stderrSpill = makeSpill(entryRef, id, "stderr", () =>
575
- child.stderr?.resume(),
576
- );
577
- const stdoutBuf = new OutputBuffer(
578
- RETAINED_PER_STREAM,
579
- stdoutSpill?.write,
580
- );
581
- const stderrBuf = new OutputBuffer(
582
- RETAINED_PER_STREAM,
583
- stderrSpill?.write,
584
- );
585
- stdoutBuf.spillPath = stdoutSpill?.spillPath;
586
- stderrBuf.spillPath = stderrSpill?.spillPath;
587
-
588
- const snapshot: MutableSnapshot = {
589
- id,
590
- command: options.command,
591
- title: options.title,
592
- cwd: options.cwd,
593
- pid: child.pid,
594
- status: "running",
595
- createdAt: Date.now(),
596
- get stdout() {
597
- return stdoutBuf.view();
598
- },
599
- get stderr() {
600
- return stderrBuf.view();
601
- },
602
- };
603
-
604
- const scope = yield* Scope.make();
605
- const settled = yield* Deferred.make<void>();
606
- const entry: Entry = {
607
- snapshot,
608
- child,
609
- scope,
610
- stdoutBuf,
611
- stderrBuf,
612
- spillStreams: [stdoutSpill?.file, stderrSpill?.file].filter(
613
- (file): file is fs.WriteStream => file !== undefined,
614
- ),
615
- killSignaled: false,
616
- processErrored: false,
617
- exited: false,
618
- stdioClosed: false,
619
- settling: false,
620
- exitCleanupStarted: false,
621
- settled,
622
- };
623
-
624
- // Plain-callback stream plumbing (the codex-backend precedent):
625
- // setEncoding's internal StringDecoder is multibyte-safe across
626
- // chunk boundaries.
627
- child.stdout?.setEncoding("utf8");
628
- child.stdout?.on("data", (chunk: string) => {
629
- if (!stdoutBuf.push(chunk)) child.stdout?.pause();
630
- notify(id);
631
- });
632
- child.stderr?.setEncoding("utf8");
633
- child.stderr?.on("data", (chunk: string) => {
634
- if (!stderrBuf.push(chunk)) child.stderr?.pause();
635
- notify(id);
636
- });
637
- // Spawn failures (ENOENT etc.) arrive via 'error', not a throw. Node
638
- // still emits 'close' afterwards (with a bogus errno as code), so
639
- // record the failure here and let the close path do the one settle.
640
- child.once("error", (error) => {
641
- entry.processErrored = true;
642
- snapshot.errorText ??= boundedError(error);
643
- entry.exited = true;
644
- settleAfterFlush(entry);
645
- });
646
- // Record code/signal on 'exit'; settle on 'close' so the completion
647
- // notification always carries the final flushed output.
648
- child.once("exit", (code, signal) => {
649
- entry.exited = true;
650
- snapshot.exitCode = code ?? undefined;
651
- snapshot.signal = signal ?? undefined;
652
- // A descendant can keep the pipes open after the shell exits. Give
653
- // close a short natural grace, then close the scope to terminate
654
- // the surviving process group and force a bounded settlement.
655
- scheduleExitCleanup(entry);
656
- });
657
- child.once("close", (code, signal) => {
658
- entry.exited = true;
659
- entry.stdioClosed = true;
660
- // Only trust close's code/signal when 'exit' never fired (a spawn
661
- // 'error' close reports the errno, e.g. -2, as its code).
662
- if (!entry.processErrored) {
663
- snapshot.exitCode ??= code ?? undefined;
664
- snapshot.signal ??= signal ?? undefined;
665
- }
666
- settleAfterFlush(entry);
667
- });
668
-
669
- // One teardown path: kill(), requestKill, pruning, disposeAll, and
670
- // runtime.dispose() all converge on closing this scope.
671
- yield* Scope.provide(
672
- Effect.addFinalizer(() =>
673
- Effect.gen(function* () {
674
- // Only claim "killed" when we are actually about to signal a
675
- // live process; a natural exit that already happened (still
676
- // waiting on 'close') keeps its truthful done/failed status.
677
- yield* terminateChild(
678
- child,
679
- () => entry.stdioClosed,
680
- () => {
681
- entry.killSignaled ||=
682
- !entry.exited && entry.snapshot.status === "running";
683
- },
684
- );
685
- // Give the natural close→flush→settle path a bounded grace,
686
- // then force the settle: a grandchild holding the pipe open
687
- // (detached into a new group) must not leave the entry
688
- // "running" forever.
689
- if (entry.snapshot.status === "running") {
690
- yield* Deferred.await(entry.settled).pipe(
691
- Effect.timeout(SETTLE_GRACE_MS),
692
- Effect.ignore,
693
- );
694
- }
695
- if (entry.snapshot.status === "running" && !entry.settling) {
696
- // Force the settle ourselves. When `settling` is set, the
697
- // close path's flush→settle is already in flight (bounded by
698
- // SPILL_FLUSH_TIMEOUT_MS) — settling here first would cite a
699
- // spill file that is still being flushed.
700
- if (!entry.stdioClosed) {
701
- entry.snapshot.errorText ??=
702
- "stdio did not close after termination; output may be incomplete";
703
- }
704
- entry.settling = true;
705
- yield* flushSpillStreams(entry);
706
- settle(entry);
707
- }
708
- }),
709
- ),
710
- scope,
711
- );
712
-
713
- // disposeAll may have swept the entries map while we were setting up;
714
- // an entry added after the sweep would never be torn down. Close our
715
- // own scope (kills the child) and fail instead (subagents precedent).
716
- if (disposed) {
717
- yield* closeEntryScope(entry);
718
- return yield* new SpawnError({
719
- message: "Background terminal manager shut down while starting.",
720
- });
721
- }
722
- entries.set(id, entry);
723
- notify(id);
724
- return snapshot as TerminalSnapshot;
725
- });
726
-
727
- // Uninterruptible: between spawn() and entries.set there must be no
728
- // window where an interrupt (tool abort, runtime dispose) leaves a
729
- // live child that no scope/registry knows about. All steps are sync.
730
- return yield* doStart.pipe(
731
- Effect.uninterruptible,
732
- Effect.ensuring(
733
- Effect.sync(() => {
734
- reserved--;
735
- notify();
736
- }),
737
- ),
738
- );
739
- });
740
-
741
- const status = (id: string) =>
742
- Effect.suspend(
743
- (): Effect.Effect<TerminalSnapshot, UnknownTerminalError> => {
744
- const entry = entries.get(id);
745
- if (!entry) {
746
- const known = [...entries.keys()];
747
- return new UnknownTerminalError({
748
- message: `Unknown terminal id "${id}". Known: ${known.join(", ") || "none"}.`,
749
- });
750
- }
751
- return Effect.succeed(entry.snapshot as TerminalSnapshot);
752
- },
753
- );
754
-
755
- /** Kill one running entry: close the scope — whose finalizer marks the kill
756
- * at the signal point, terminates the tree, and force-settles —
757
- * in a DETACHED fiber. Once the flag is set the termination must actually
758
- * happen; a tool abort interrupting the caller cannot cancel it (this is
759
- * what makes "termination continues in the background" truthful). */
760
- const killEntry = (entry: Entry) =>
761
- Effect.sync(() => {
762
- if (entry.snapshot.status !== "running") return;
763
- runCleanup(
764
- closeEntryScope(entry).pipe(
765
- Effect.timeout(STOP_TIMEOUT_MS),
766
- Effect.ignore,
767
- ),
768
- );
769
- });
770
-
771
- const kill = (ids: ReadonlyArray<string>) =>
772
- Effect.suspend(() => {
773
- const unique = [...new Set(ids)];
774
- const byId = new Map(
775
- unique
776
- .map((id) => entries.get(id))
777
- .filter((entry): entry is Entry => entry !== undefined)
778
- .map((entry) => [entry.snapshot.id, entry]),
779
- );
780
- const running = [...byId.values()].filter(
781
- (entry) => entry.snapshot.status === "running",
782
- );
783
- const runningIds = running.map((entry) => entry.snapshot.id);
784
- // Mark consumed before signaling so this kill's settlements are not
785
- // ALSO queued as automatic follow-up messages to the model.
786
- addKillInterest(runningIds);
787
- const work = Effect.gen(function* () {
788
- yield* Effect.forEach(running, killEntry, {
789
- concurrency: "unbounded",
790
- });
791
- // Every caller waits on the entries that were running when its kill
792
- // began. Deferred completion cannot be missed and supports concurrent
793
- // overlapping/multi-id kill calls.
794
- yield* Effect.forEach(
795
- running,
796
- (entry) => Deferred.await(entry.settled),
797
- { concurrency: "unbounded", discard: true },
798
- );
799
- // Capture the report BEFORE the ensuring below releases interest and
800
- // prunes — a just-settled entry must not vanish out from under it.
801
- return unique.map((id): KillResult => {
802
- const snapshot = byId.get(id)?.snapshot;
803
- const history = settledHistory.get(id);
804
- const status = snapshot?.status ?? history?.status ?? "killed";
805
- const wasRunning = runningIds.includes(id);
806
- return {
807
- id,
808
- title: snapshot?.title ?? history?.title ?? "?",
809
- status,
810
- wasRunning,
811
- // A natural exit can win the race with our SIGTERM; report what
812
- // actually happened rather than claiming the kill did it.
813
- killed: wasRunning && status === "killed",
814
- exit: snapshot
815
- ? formatExit(snapshot)
816
- : (history?.exit ?? "unknown"),
817
- };
818
- });
819
- });
820
- return work.pipe(
821
- Effect.ensuring(
822
- Effect.sync(() => {
823
- releaseKillInterest(runningIds);
824
- pruneSettled();
825
- }),
826
- ),
827
- );
828
- });
829
-
830
- const disposeAll = Effect.gen(function* () {
831
- disposed = true;
832
- const all = [...entries.values()];
833
- entries.clear();
834
- yield* Effect.forEach(
835
- all,
836
- (entry) =>
837
- closeEntryScope(entry).pipe(
838
- Effect.timeout(STOP_TIMEOUT_MS),
839
- Effect.ignore,
840
- ),
841
- { concurrency: "unbounded" },
842
- );
843
- // Detached kill/prune/flush work is scoped to the manager. Wait for it
844
- // within the shutdown bound; the FiberSet finalizer interrupts anything
845
- // still live when the manager scope closes, so cleanup cannot leak.
846
- yield* FiberSet.awaitEmpty(cleanupFibers).pipe(
847
- Effect.timeout(STOP_TIMEOUT_MS),
848
- Effect.ignore,
849
- );
850
- yield* Effect.sync(() => {
851
- const dir = spillDir;
852
- spillDir = null;
853
- if (dir) fs.rmSync(dir, { recursive: true, force: true });
854
- });
855
- yield* Effect.sync(() => notify());
856
- });
857
-
858
- const view: TerminalReadModel = {
859
- list: () => [...entries.values()].map((entry) => entry.snapshot),
860
- get: (id) => entries.get(id)?.snapshot,
861
- size: () => entries.size,
862
- subscribe: (listener) => {
863
- listeners.add(listener);
864
- return () => listeners.delete(listener);
865
- },
866
- subscribeTo: (id, listener) => {
867
- let set = idListeners.get(id);
868
- if (!set) {
869
- set = new Set();
870
- idListeners.set(id, set);
871
- }
872
- set.add(listener);
873
- return () => {
874
- set.delete(listener);
875
- if (set.size === 0) idListeners.delete(id);
876
- };
877
- },
878
- requestKill: (id) => {
879
- const entry = entries.get(id);
880
- if (!entry) return;
881
- // UI-initiated kills are not "consumed": the killed result still flows
882
- // back to the model as a follow-up message (subagents precedent).
883
- runCleanup(killEntry(entry).pipe(Effect.ignore));
884
- },
885
- setOnSettled: (hook) => {
886
- onSettled = hook;
887
- },
888
- };
889
-
890
- // Safety net: disposing the ManagedRuntime tears everything down even if
891
- // the extension forgot to call disposeAll explicitly.
892
- yield* Effect.addFinalizer(() => disposeAll);
893
-
894
- return TerminalManager.of({
895
- start,
896
- status,
897
- kill,
898
- list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
899
- disposeAll,
900
- view,
901
- });
902
- });
903
-
904
- export const TerminalManagerLive: Layer.Layer<TerminalManager> = Layer.effect(
905
- TerminalManager,
906
- makeManager,
907
- );
1
+ /**
2
+ * TerminalManager — owns the registry of running/settled background
3
+ * terminals.
4
+ *
5
+ * Each terminal is a raw `node:child_process` spawn (own process group on
6
+ * POSIX, stdin ignored) whose stdout/stderr 'data' callbacks fold into two
7
+ * bounded OutputBuffers. Closing a terminal's scope kills the whole process
8
+ * tree (SIGTERM → SIGKILL escalation).
9
+ *
10
+ * The manager also exposes a synchronous `TerminalReadModel` so the
11
+ * imperative TUI components (which render synchronously) can read snapshots
12
+ * and issue fire-and-forget kills without touching the Effect runtime.
13
+ */
14
+
15
+ import { spawn, type ChildProcess } from "node:child_process";
16
+ import * as fs from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+ import {
20
+ Context,
21
+ Deferred,
22
+ Effect,
23
+ Exit,
24
+ FiberSet,
25
+ Layer,
26
+ Scope,
27
+ } from "effect";
28
+ import {
29
+ ConcurrencyLimitError,
30
+ formatExit,
31
+ SpawnError,
32
+ UnknownTerminalError,
33
+ type TerminalSnapshot,
34
+ type TerminalStatus,
35
+ } from "./domain.ts";
36
+ import { OutputBuffer } from "./output.ts";
37
+
38
+ export const MAX_RUNNING = 8;
39
+ export const MAX_TRACKED = 32;
40
+ const MAX_SETTLED_HISTORY = MAX_TRACKED * 4;
41
+ /** In-memory retained cap per stream. */
42
+ export const RETAINED_PER_STREAM = 2 * 1024 * 1024;
43
+ /** Private full-log spills are bounded so a firehose cannot fill the temp disk. */
44
+ export const MAX_SPILL_BYTES_PER_STREAM = 256 * 1024 * 1024;
45
+ const STOP_TIMEOUT_MS = 5_000;
46
+ /** SIGTERM is normally enough; the second deadline covers a wedged process. */
47
+ const FORCE_KILL_AFTER_MS = 2_000;
48
+ /** After termination, how long to wait for the natural close→flush→settle
49
+ * path before force-settling (a grandchild can hold the stdio pipes open). */
50
+ const SETTLE_GRACE_MS = 1_000;
51
+ /** Bound on waiting for spill WriteStreams to flush before settling; a hung
52
+ * filesystem must not leave an exited entry "running" (and kill() waiting).
53
+ * Terminate (≤2.5s) + settle grace (1s) + flush (1.5s) stays inside the 5s
54
+ * scope-close bound, so teardown remains bounded end to end. */
55
+ const SPILL_FLUSH_TIMEOUT_MS = 1_500;
56
+ const ERROR_TEXT_MAX_LENGTH = 4_096;
57
+
58
+ function bounded(text: string) {
59
+ return text.slice(0, ERROR_TEXT_MAX_LENGTH);
60
+ }
61
+
62
+ function boundedError(error: unknown) {
63
+ return bounded(error instanceof Error ? error.message : String(error));
64
+ }
65
+
66
+ // --- Internal state -----------------------------------------------------------
67
+
68
+ /** Mutable snapshot; exposed to readers via the readonly TerminalSnapshot type.
69
+ * stdout/stderr are getters over the live OutputBuffers. */
70
+ interface MutableSnapshot extends TerminalSnapshot {
71
+ status: TerminalStatus;
72
+ pid?: number;
73
+ settledAt?: number;
74
+ exitCode?: number;
75
+ signal?: string;
76
+ errorText?: string;
77
+ }
78
+
79
+ interface Entry {
80
+ snapshot: MutableSnapshot;
81
+ child: ChildProcess;
82
+ scope: Scope.Closeable;
83
+ stdoutBuf: OutputBuffer;
84
+ stderrBuf: OutputBuffer;
85
+ spillStreams: fs.WriteStream[];
86
+ /** Set in the same synchronous effect that sends SIGTERM so a natural exit
87
+ * before signaling keeps its truthful status. */
88
+ killSignaled: boolean;
89
+ /** The child emitted 'error' (spawn failure etc.); settles as "failed".
90
+ * Kept separate from errorText, which also carries non-fatal notes
91
+ * (spill failures) that must not flip a clean exit to "failed". */
92
+ processErrored: boolean;
93
+ /** 'exit' event observed (code/signal recorded). */
94
+ exited: boolean;
95
+ /** 'close' event observed (stdio flushed; the settle trigger). */
96
+ stdioClosed: boolean;
97
+ /** A settle-after-spill-flush is in flight; don't start a second one. */
98
+ settling: boolean;
99
+ /** The shell exited without stdio closing; a bounded scope close is queued
100
+ * to reap descendants that still hold the inherited pipes open. */
101
+ exitCleanupStarted: boolean;
102
+ /** Completed exactly once when the entry settles. Kill callers and the scope
103
+ * finalizer can all await the same result without missing a notification. */
104
+ settled: Deferred.Deferred<void>;
105
+ }
106
+
107
+ export interface StartOptions {
108
+ readonly command: string;
109
+ readonly title: string;
110
+ readonly cwd: string;
111
+ }
112
+
113
+ export interface KillResult {
114
+ readonly id: string;
115
+ readonly title: string;
116
+ readonly status: TerminalStatus;
117
+ /** True when the entry was still running when this kill began. */
118
+ readonly wasRunning: boolean;
119
+ /** True when this call initiated the termination AND the entry settled as
120
+ * killed (a natural exit that won the race reports killed: false). */
121
+ readonly killed: boolean;
122
+ /** Final exit rendering ("exit 0", "SIGTERM", ...) captured at settle time,
123
+ * so reports stay accurate even if the entry is pruned afterwards. */
124
+ readonly exit: string;
125
+ }
126
+
127
+ // --- Read model ----------------------------------------------------------------
128
+
129
+ /** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
130
+ export interface TerminalReadModel {
131
+ list(): ReadonlyArray<TerminalSnapshot>;
132
+ get(id: string): TerminalSnapshot | undefined;
133
+ size(): number;
134
+ /** Any-change notification (widget, /ps list). */
135
+ subscribe(listener: () => void): () => void;
136
+ /** Per-terminal notification (/ps detail view). */
137
+ subscribeTo(id: string, listener: () => void): () => void;
138
+ /** Fire-and-forget kill (dashboard/detail `x`). Not marked consumed: the
139
+ * settle still flows back to the model as a follow-up message. */
140
+ requestKill(id: string): void;
141
+ /**
142
+ * Register the settle hook. `consumed` is true when an active bg_kill is
143
+ * collecting the result (so it must not also be delivered as a follow-up).
144
+ */
145
+ setOnSettled(
146
+ hook: ((snap: TerminalSnapshot, consumed: boolean) => void) | undefined,
147
+ ): void;
148
+ }
149
+
150
+ // --- Service --------------------------------------------------------------------
151
+
152
+ export interface TerminalManagerShape {
153
+ start(
154
+ options: StartOptions,
155
+ ): Effect.Effect<TerminalSnapshot, SpawnError | ConcurrencyLimitError>;
156
+ status(id: string): Effect.Effect<TerminalSnapshot, UnknownTerminalError>;
157
+ /** Kill running terminals; resolves only after they have settled. */
158
+ kill(ids: ReadonlyArray<string>): Effect.Effect<ReadonlyArray<KillResult>>;
159
+ readonly list: Effect.Effect<ReadonlyArray<TerminalSnapshot>>;
160
+ readonly disposeAll: Effect.Effect<void>;
161
+ readonly view: TerminalReadModel;
162
+ }
163
+
164
+ export class TerminalManager extends Context.Service<
165
+ TerminalManager,
166
+ TerminalManagerShape
167
+ >()("background-terminals/TerminalManager") {}
168
+
169
+ // --- Process helpers ------------------------------------------------------------
170
+
171
+ function shellInvocation(command: string) {
172
+ if (process.platform === "win32") {
173
+ const shell = process.env.ComSpec ?? "cmd.exe";
174
+ return { shell, args: ["/d", "/s", "/c", command] };
175
+ }
176
+ return { shell: "/bin/sh", args: ["-c", command] };
177
+ }
178
+
179
+ /** Signal the whole process group on POSIX so descendants (servers a shell
180
+ * command spawned) die with it; a wedged child must not orphan its tree. */
181
+ function killTree(child: ChildProcess, signal: NodeJS.Signals) {
182
+ if (process.platform === "win32" && child.pid) {
183
+ try {
184
+ const killer = spawn(
185
+ "taskkill",
186
+ [
187
+ "/pid",
188
+ String(child.pid),
189
+ "/T",
190
+ ...(signal === "SIGKILL" ? ["/F"] : []),
191
+ ],
192
+ { stdio: "ignore", windowsHide: true },
193
+ );
194
+ killer.once("error", () => {
195
+ try {
196
+ child.kill(signal);
197
+ } catch {
198
+ // Process may already be gone.
199
+ }
200
+ });
201
+ killer.once("exit", (code) => {
202
+ if (code === 0) return;
203
+ try {
204
+ child.kill(signal);
205
+ } catch {
206
+ // Process may already be gone.
207
+ }
208
+ });
209
+ killer.unref();
210
+ return;
211
+ } catch {
212
+ // Fall through to the direct signal when taskkill cannot be launched.
213
+ }
214
+ }
215
+ if (process.platform !== "win32" && child.pid) {
216
+ try {
217
+ process.kill(-child.pid, signal);
218
+ return;
219
+ } catch {
220
+ // Group may already be gone; fall through to the direct signal.
221
+ }
222
+ }
223
+ try {
224
+ child.kill(signal);
225
+ } catch {
226
+ // Process may already be gone.
227
+ }
228
+ }
229
+
230
+ /** Await stdio closure without retaining a listener after interruption. */
231
+ function awaitChildClose(child: ChildProcess, closed: () => boolean) {
232
+ return Effect.callback<void>((resume) => {
233
+ if (closed()) {
234
+ resume(Effect.void);
235
+ return;
236
+ }
237
+ const onClose = () => resume(Effect.void);
238
+ child.once("close", onClose);
239
+ return Effect.sync(() => child.off("close", onClose));
240
+ });
241
+ }
242
+
243
+ /** SIGTERM → deadline → SIGKILL; waits for stdio closure rather than only the
244
+ * shell's exit because descendants can keep the inherited pipes and process
245
+ * group alive after the shell itself is gone. */
246
+ function terminateChild(
247
+ child: ChildProcess,
248
+ closed: () => boolean,
249
+ onSignal: () => void,
250
+ ) {
251
+ return Effect.suspend(() => {
252
+ if (closed()) return Effect.void;
253
+ return Effect.gen(function* () {
254
+ yield* Effect.sync(() => {
255
+ onSignal();
256
+ killTree(child, "SIGTERM");
257
+ });
258
+ yield* awaitChildClose(child, closed).pipe(
259
+ Effect.timeout(FORCE_KILL_AFTER_MS),
260
+ Effect.ignore,
261
+ );
262
+ if (closed()) return;
263
+ yield* Effect.sync(() => killTree(child, "SIGKILL"));
264
+ yield* awaitChildClose(child, closed).pipe(
265
+ Effect.timeout(500),
266
+ Effect.ignore,
267
+ );
268
+ });
269
+ });
270
+ }
271
+
272
+ // --- Implementation --------------------------------------------------------------
273
+
274
+ const makeManager = Effect.gen(function* () {
275
+ // Scoped detached forker for sync contexts (read-model kills, process-event
276
+ // settlement, pruning). Completed fibers remove themselves; manager scope
277
+ // close interrupts any work that outlives the bounded disposeAll wait.
278
+ const cleanupFibers = yield* FiberSet.make();
279
+ const runCleanup = yield* FiberSet.runtime(cleanupFibers)();
280
+
281
+ const entries = new Map<string, Entry>();
282
+ /** Small immutable tombstones preserve truthful kill reports if pruning
283
+ * races the tool boundary after an id was validated. */
284
+ const settledHistory = new Map<
285
+ string,
286
+ Pick<KillResult, "title" | "status" | "exit">
287
+ >();
288
+ /** ids with an in-flight kill() collecting the result (settle → consumed). */
289
+ const killInterest = new Map<string, number>();
290
+ const listeners = new Set<() => void>();
291
+ const idListeners = new Map<string, Set<() => void>>();
292
+ let counter = 0;
293
+ let reserved = 0;
294
+ let disposed = false;
295
+ let spillDir: string | undefined | null;
296
+ let onSettled:
297
+ ((snap: TerminalSnapshot, consumed: boolean) => void) | undefined;
298
+
299
+ const notify = (id?: string) => {
300
+ for (const listener of [...listeners]) {
301
+ try {
302
+ listener();
303
+ } catch {
304
+ // A failed widget/render listener must not corrupt lifecycle state.
305
+ }
306
+ }
307
+ if (id) {
308
+ for (const listener of idListeners.get(id) ?? []) {
309
+ try {
310
+ listener();
311
+ } catch {
312
+ // Same.
313
+ }
314
+ }
315
+ }
316
+ };
317
+
318
+ const runningCount = () =>
319
+ [...entries.values()].filter((e) => e.snapshot.status === "running").length;
320
+
321
+ const addKillInterest = (ids: ReadonlyArray<string>) => {
322
+ for (const id of ids) killInterest.set(id, (killInterest.get(id) ?? 0) + 1);
323
+ };
324
+ const releaseKillInterest = (ids: ReadonlyArray<string>) => {
325
+ for (const id of ids) {
326
+ const count = (killInterest.get(id) ?? 1) - 1;
327
+ if (count <= 0) killInterest.delete(id);
328
+ else killInterest.set(id, count);
329
+ }
330
+ };
331
+
332
+ const closeEntryScope = (entry: Entry) =>
333
+ Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
334
+
335
+ const pruneSettled = () => {
336
+ if (entries.size <= MAX_TRACKED) return;
337
+ const candidates = [...entries.values()]
338
+ .filter(
339
+ (e) =>
340
+ e.snapshot.status !== "running" && !killInterest.has(e.snapshot.id),
341
+ )
342
+ .sort(
343
+ (a, b) =>
344
+ (a.snapshot.settledAt ?? a.snapshot.createdAt) -
345
+ (b.snapshot.settledAt ?? b.snapshot.createdAt),
346
+ );
347
+ for (const entry of candidates) {
348
+ if (entries.size <= MAX_TRACKED) break;
349
+ entries.delete(entry.snapshot.id);
350
+ runCleanup(closeEntryScope(entry));
351
+ }
352
+ };
353
+
354
+ /** End all spill streams; resolves when their buffers are flushed to disk
355
+ * (bounded), so a settle notification never points at a partial file. */
356
+ const flushSpillStreams = (entry: Entry) => {
357
+ const streams = entry.spillStreams;
358
+ entry.spillStreams = [];
359
+ return Effect.forEach(
360
+ streams,
361
+ (stream) =>
362
+ Effect.callback<void>((resume) => {
363
+ const done = () => resume(Effect.void);
364
+ try {
365
+ stream.end(done);
366
+ } catch {
367
+ // Best effort; tmpdir contents are disposable.
368
+ done();
369
+ }
370
+ }),
371
+ { concurrency: "unbounded", discard: true },
372
+ ).pipe(
373
+ Effect.timeoutOrElse({
374
+ duration: SPILL_FLUSH_TIMEOUT_MS,
375
+ orElse: () =>
376
+ Effect.sync(() => {
377
+ entry.stdoutBuf.spillPath = undefined;
378
+ entry.stderrBuf.spillPath = undefined;
379
+ entry.snapshot.errorText ??=
380
+ "Full-log spill flush timed out; full output may be incomplete";
381
+ }),
382
+ }),
383
+ );
384
+ };
385
+
386
+ /** Single settle path — idempotent; kill vs natural exit vs error races are
387
+ * resolved by whichever lands first (the second call is a no-op). */
388
+ const settle = (entry: Entry) => {
389
+ const s = entry.snapshot;
390
+ if (s.status !== "running") return;
391
+ s.settledAt = Date.now();
392
+ s.status = entry.killSignaled
393
+ ? "killed"
394
+ : entry.processErrored
395
+ ? "failed"
396
+ : s.exitCode === 0
397
+ ? "done"
398
+ : "failed";
399
+ settledHistory.set(s.id, {
400
+ title: s.title,
401
+ status: s.status,
402
+ exit: formatExit(s),
403
+ });
404
+ while (settledHistory.size > MAX_SETTLED_HISTORY) {
405
+ const oldest = settledHistory.keys().next().value;
406
+ if (oldest === undefined) break;
407
+ settledHistory.delete(oldest);
408
+ }
409
+ // Completing the Deferred can immediately resume kill waiters, whose
410
+ // ensuring blocks release interest. Snapshot consumption first so the
411
+ // settle hook observes the interest that existed when settlement won.
412
+ const consumed = (killInterest.get(s.id) ?? 0) > 0;
413
+ Deferred.doneUnsafe(entry.settled, Effect.void);
414
+ notify(s.id);
415
+ try {
416
+ // During teardown, don't queue results into a shutting-down session.
417
+ if (!disposed) onSettled?.(s, consumed);
418
+ } catch {
419
+ // The parent session may be unavailable; settlement stays final.
420
+ }
421
+ pruneSettled();
422
+ };
423
+
424
+ /** Flush the spill files, then settle: the completion follow-up (and the
425
+ * kill() resolution) reference the spill path, so the full capture must be
426
+ * on disk before anyone is told about it. Idempotent via `settling`. */
427
+ const settleAfterFlush = (entry: Entry) => {
428
+ if (entry.settling || entry.snapshot.status !== "running") return;
429
+ entry.settling = true;
430
+ runCleanup(
431
+ flushSpillStreams(entry).pipe(
432
+ Effect.andThen(Effect.sync(() => settle(entry))),
433
+ ),
434
+ );
435
+ };
436
+
437
+ const scheduleExitCleanup = (entry: Entry) => {
438
+ if (entry.exitCleanupStarted) return;
439
+ entry.exitCleanupStarted = true;
440
+ runCleanup(
441
+ Effect.sleep(SETTLE_GRACE_MS).pipe(
442
+ Effect.andThen(
443
+ Effect.suspend(() =>
444
+ entry.snapshot.status === "running" && !entry.stdioClosed
445
+ ? closeEntryScope(entry).pipe(
446
+ Effect.timeout(STOP_TIMEOUT_MS),
447
+ Effect.ignore,
448
+ )
449
+ : Effect.void,
450
+ ),
451
+ ),
452
+ ),
453
+ );
454
+ };
455
+
456
+ const resolveSpillDir = () => {
457
+ if (spillDir !== undefined) return spillDir ?? undefined;
458
+ try {
459
+ const base = path.join(os.tmpdir(), "pi-background-terminals");
460
+ fs.mkdirSync(base, { recursive: true, mode: 0o700 });
461
+ fs.chmodSync(base, 0o700);
462
+ spillDir = fs.mkdtempSync(path.join(base, "session-"));
463
+ fs.chmodSync(spillDir, 0o700);
464
+ } catch {
465
+ spillDir = null;
466
+ }
467
+ return spillDir ?? undefined;
468
+ };
469
+
470
+ const makeSpill = (
471
+ entry: () => Entry | undefined,
472
+ id: string,
473
+ stream: "stdout" | "stderr",
474
+ resumeSource: () => void,
475
+ ) => {
476
+ const dir = resolveSpillDir();
477
+ if (!dir) return undefined;
478
+ const spillPath = path.join(dir, `${id}.${stream}.log`);
479
+ try {
480
+ const file = fs.createWriteStream(spillPath, {
481
+ flags: "a",
482
+ mode: 0o600,
483
+ });
484
+ let broken = false;
485
+ let capped = false;
486
+ let writtenBytes = 0;
487
+ file.on("error", (error) => {
488
+ broken = true;
489
+ resumeSource();
490
+ const current = entry();
491
+ if (current) {
492
+ const buf =
493
+ stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
494
+ buf.spillPath = undefined;
495
+ current.snapshot.errorText ??= bounded(
496
+ `Full-log spill to ${spillPath} failed: ${boundedError(error)}`,
497
+ );
498
+ }
499
+ });
500
+ return {
501
+ spillPath,
502
+ file,
503
+ write: (chunk: string) => {
504
+ // writableEnded guard: late 'data' after the settle flush must not
505
+ // error the ended stream (and falsely report the spill as broken).
506
+ if (broken || capped || file.writableEnded) return true;
507
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
508
+ if (writtenBytes + chunkBytes > MAX_SPILL_BYTES_PER_STREAM) {
509
+ capped = true;
510
+ const current = entry();
511
+ if (current) {
512
+ const buf =
513
+ stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
514
+ buf.spillPath = undefined;
515
+ current.snapshot.errorText ??= bounded(
516
+ `${stream} full-log spill reached the ${MAX_SPILL_BYTES_PER_STREAM}-byte safety limit`,
517
+ );
518
+ }
519
+ return true;
520
+ }
521
+ writtenBytes += chunkBytes;
522
+ const accepted = file.write(chunk);
523
+ if (!accepted) file.once("drain", resumeSource);
524
+ return accepted;
525
+ },
526
+ };
527
+ } catch {
528
+ return undefined;
529
+ }
530
+ };
531
+
532
+ const start = (options: StartOptions) =>
533
+ Effect.gen(function* () {
534
+ // Reserve synchronously (before the first yield inside doStart) so
535
+ // parallel tool calls cannot race past the cap.
536
+ yield* Effect.suspend(
537
+ (): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
538
+ if (disposed) {
539
+ return new SpawnError({
540
+ message: "Background terminal manager is shutting down.",
541
+ });
542
+ }
543
+ if (runningCount() + reserved >= MAX_RUNNING) {
544
+ return new ConcurrencyLimitError({
545
+ message: `Max ${MAX_RUNNING} background terminals can run concurrently. Stop one with bg_kill before starting another.`,
546
+ });
547
+ }
548
+ reserved++;
549
+ return Effect.void;
550
+ },
551
+ );
552
+
553
+ const doStart = Effect.gen(function* () {
554
+ const { shell, args } = shellInvocation(options.command);
555
+ const child = yield* Effect.try({
556
+ try: () =>
557
+ spawn(shell, args, {
558
+ cwd: options.cwd,
559
+ env: process.env,
560
+ // stdin IGNORED: there is no input surface, ever. A process
561
+ // that reads stdin sees EOF immediately.
562
+ stdio: ["ignore", "pipe", "pipe"],
563
+ // Own process group on POSIX → group kill takes the whole tree.
564
+ detached: process.platform !== "win32",
565
+ }),
566
+ catch: (error) => new SpawnError({ message: boundedError(error) }),
567
+ });
568
+
569
+ const id = `bt-${++counter}`;
570
+ const entryRef = () => entries.get(id);
571
+ const stdoutSpill = makeSpill(entryRef, id, "stdout", () =>
572
+ child.stdout?.resume(),
573
+ );
574
+ const stderrSpill = makeSpill(entryRef, id, "stderr", () =>
575
+ child.stderr?.resume(),
576
+ );
577
+ const stdoutBuf = new OutputBuffer(
578
+ RETAINED_PER_STREAM,
579
+ stdoutSpill?.write,
580
+ );
581
+ const stderrBuf = new OutputBuffer(
582
+ RETAINED_PER_STREAM,
583
+ stderrSpill?.write,
584
+ );
585
+ stdoutBuf.spillPath = stdoutSpill?.spillPath;
586
+ stderrBuf.spillPath = stderrSpill?.spillPath;
587
+
588
+ const snapshot: MutableSnapshot = {
589
+ id,
590
+ command: options.command,
591
+ title: options.title,
592
+ cwd: options.cwd,
593
+ pid: child.pid,
594
+ status: "running",
595
+ createdAt: Date.now(),
596
+ get stdout() {
597
+ return stdoutBuf.view();
598
+ },
599
+ get stderr() {
600
+ return stderrBuf.view();
601
+ },
602
+ };
603
+
604
+ const scope = yield* Scope.make();
605
+ const settled = yield* Deferred.make<void>();
606
+ const entry: Entry = {
607
+ snapshot,
608
+ child,
609
+ scope,
610
+ stdoutBuf,
611
+ stderrBuf,
612
+ spillStreams: [stdoutSpill?.file, stderrSpill?.file].filter(
613
+ (file): file is fs.WriteStream => file !== undefined,
614
+ ),
615
+ killSignaled: false,
616
+ processErrored: false,
617
+ exited: false,
618
+ stdioClosed: false,
619
+ settling: false,
620
+ exitCleanupStarted: false,
621
+ settled,
622
+ };
623
+
624
+ // Plain-callback stream plumbing (the codex-backend precedent):
625
+ // setEncoding's internal StringDecoder is multibyte-safe across
626
+ // chunk boundaries.
627
+ child.stdout?.setEncoding("utf8");
628
+ child.stdout?.on("data", (chunk: string) => {
629
+ if (!stdoutBuf.push(chunk)) child.stdout?.pause();
630
+ notify(id);
631
+ });
632
+ child.stderr?.setEncoding("utf8");
633
+ child.stderr?.on("data", (chunk: string) => {
634
+ if (!stderrBuf.push(chunk)) child.stderr?.pause();
635
+ notify(id);
636
+ });
637
+ // Spawn failures (ENOENT etc.) arrive via 'error', not a throw. Node
638
+ // still emits 'close' afterwards (with a bogus errno as code), so
639
+ // record the failure here and let the close path do the one settle.
640
+ child.once("error", (error) => {
641
+ entry.processErrored = true;
642
+ snapshot.errorText ??= boundedError(error);
643
+ entry.exited = true;
644
+ settleAfterFlush(entry);
645
+ });
646
+ // Record code/signal on 'exit'; settle on 'close' so the completion
647
+ // notification always carries the final flushed output.
648
+ child.once("exit", (code, signal) => {
649
+ entry.exited = true;
650
+ snapshot.exitCode = code ?? undefined;
651
+ snapshot.signal = signal ?? undefined;
652
+ // A descendant can keep the pipes open after the shell exits. Give
653
+ // close a short natural grace, then close the scope to terminate
654
+ // the surviving process group and force a bounded settlement.
655
+ scheduleExitCleanup(entry);
656
+ });
657
+ child.once("close", (code, signal) => {
658
+ entry.exited = true;
659
+ entry.stdioClosed = true;
660
+ // Only trust close's code/signal when 'exit' never fired (a spawn
661
+ // 'error' close reports the errno, e.g. -2, as its code).
662
+ if (!entry.processErrored) {
663
+ snapshot.exitCode ??= code ?? undefined;
664
+ snapshot.signal ??= signal ?? undefined;
665
+ }
666
+ settleAfterFlush(entry);
667
+ });
668
+
669
+ // One teardown path: kill(), requestKill, pruning, disposeAll, and
670
+ // runtime.dispose() all converge on closing this scope.
671
+ yield* Scope.provide(
672
+ Effect.addFinalizer(() =>
673
+ Effect.gen(function* () {
674
+ // Only claim "killed" when we are actually about to signal a
675
+ // live process; a natural exit that already happened (still
676
+ // waiting on 'close') keeps its truthful done/failed status.
677
+ yield* terminateChild(
678
+ child,
679
+ () => entry.stdioClosed,
680
+ () => {
681
+ entry.killSignaled ||=
682
+ !entry.exited && entry.snapshot.status === "running";
683
+ },
684
+ );
685
+ // Give the natural close→flush→settle path a bounded grace,
686
+ // then force the settle: a grandchild holding the pipe open
687
+ // (detached into a new group) must not leave the entry
688
+ // "running" forever.
689
+ if (entry.snapshot.status === "running") {
690
+ yield* Deferred.await(entry.settled).pipe(
691
+ Effect.timeout(SETTLE_GRACE_MS),
692
+ Effect.ignore,
693
+ );
694
+ }
695
+ if (entry.snapshot.status === "running" && !entry.settling) {
696
+ // Force the settle ourselves. When `settling` is set, the
697
+ // close path's flush→settle is already in flight (bounded by
698
+ // SPILL_FLUSH_TIMEOUT_MS) — settling here first would cite a
699
+ // spill file that is still being flushed.
700
+ if (!entry.stdioClosed) {
701
+ entry.snapshot.errorText ??=
702
+ "stdio did not close after termination; output may be incomplete";
703
+ }
704
+ entry.settling = true;
705
+ yield* flushSpillStreams(entry);
706
+ settle(entry);
707
+ }
708
+ }),
709
+ ),
710
+ scope,
711
+ );
712
+
713
+ // disposeAll may have swept the entries map while we were setting up;
714
+ // an entry added after the sweep would never be torn down. Close our
715
+ // own scope (kills the child) and fail instead (subagents precedent).
716
+ if (disposed) {
717
+ yield* closeEntryScope(entry);
718
+ return yield* new SpawnError({
719
+ message: "Background terminal manager shut down while starting.",
720
+ });
721
+ }
722
+ entries.set(id, entry);
723
+ notify(id);
724
+ return snapshot as TerminalSnapshot;
725
+ });
726
+
727
+ // Uninterruptible: between spawn() and entries.set there must be no
728
+ // window where an interrupt (tool abort, runtime dispose) leaves a
729
+ // live child that no scope/registry knows about. All steps are sync.
730
+ return yield* doStart.pipe(
731
+ Effect.uninterruptible,
732
+ Effect.ensuring(
733
+ Effect.sync(() => {
734
+ reserved--;
735
+ notify();
736
+ }),
737
+ ),
738
+ );
739
+ });
740
+
741
+ const status = (id: string) =>
742
+ Effect.suspend(
743
+ (): Effect.Effect<TerminalSnapshot, UnknownTerminalError> => {
744
+ const entry = entries.get(id);
745
+ if (!entry) {
746
+ const known = [...entries.keys()];
747
+ return new UnknownTerminalError({
748
+ message: `Unknown terminal id "${id}". Known: ${known.join(", ") || "none"}.`,
749
+ });
750
+ }
751
+ return Effect.succeed(entry.snapshot as TerminalSnapshot);
752
+ },
753
+ );
754
+
755
+ /** Kill one running entry: close the scope — whose finalizer marks the kill
756
+ * at the signal point, terminates the tree, and force-settles —
757
+ * in a DETACHED fiber. Once the flag is set the termination must actually
758
+ * happen; a tool abort interrupting the caller cannot cancel it (this is
759
+ * what makes "termination continues in the background" truthful). */
760
+ const killEntry = (entry: Entry) =>
761
+ Effect.sync(() => {
762
+ if (entry.snapshot.status !== "running") return;
763
+ runCleanup(
764
+ closeEntryScope(entry).pipe(
765
+ Effect.timeout(STOP_TIMEOUT_MS),
766
+ Effect.ignore,
767
+ ),
768
+ );
769
+ });
770
+
771
+ const kill = (ids: ReadonlyArray<string>) =>
772
+ Effect.suspend(() => {
773
+ const unique = [...new Set(ids)];
774
+ const byId = new Map(
775
+ unique
776
+ .map((id) => entries.get(id))
777
+ .filter((entry): entry is Entry => entry !== undefined)
778
+ .map((entry) => [entry.snapshot.id, entry]),
779
+ );
780
+ const running = [...byId.values()].filter(
781
+ (entry) => entry.snapshot.status === "running",
782
+ );
783
+ const runningIds = running.map((entry) => entry.snapshot.id);
784
+ // Mark consumed before signaling so this kill's settlements are not
785
+ // ALSO queued as automatic follow-up messages to the model.
786
+ addKillInterest(runningIds);
787
+ const work = Effect.gen(function* () {
788
+ yield* Effect.forEach(running, killEntry, {
789
+ concurrency: "unbounded",
790
+ });
791
+ // Every caller waits on the entries that were running when its kill
792
+ // began. Deferred completion cannot be missed and supports concurrent
793
+ // overlapping/multi-id kill calls.
794
+ yield* Effect.forEach(
795
+ running,
796
+ (entry) => Deferred.await(entry.settled),
797
+ { concurrency: "unbounded", discard: true },
798
+ );
799
+ // Capture the report BEFORE the ensuring below releases interest and
800
+ // prunes — a just-settled entry must not vanish out from under it.
801
+ return unique.map((id): KillResult => {
802
+ const snapshot = byId.get(id)?.snapshot;
803
+ const history = settledHistory.get(id);
804
+ const status = snapshot?.status ?? history?.status ?? "killed";
805
+ const wasRunning = runningIds.includes(id);
806
+ return {
807
+ id,
808
+ title: snapshot?.title ?? history?.title ?? "?",
809
+ status,
810
+ wasRunning,
811
+ // A natural exit can win the race with our SIGTERM; report what
812
+ // actually happened rather than claiming the kill did it.
813
+ killed: wasRunning && status === "killed",
814
+ exit: snapshot
815
+ ? formatExit(snapshot)
816
+ : (history?.exit ?? "unknown"),
817
+ };
818
+ });
819
+ });
820
+ return work.pipe(
821
+ Effect.ensuring(
822
+ Effect.sync(() => {
823
+ releaseKillInterest(runningIds);
824
+ pruneSettled();
825
+ }),
826
+ ),
827
+ );
828
+ });
829
+
830
+ const disposeAll = Effect.gen(function* () {
831
+ disposed = true;
832
+ const all = [...entries.values()];
833
+ entries.clear();
834
+ yield* Effect.forEach(
835
+ all,
836
+ (entry) =>
837
+ closeEntryScope(entry).pipe(
838
+ Effect.timeout(STOP_TIMEOUT_MS),
839
+ Effect.ignore,
840
+ ),
841
+ { concurrency: "unbounded" },
842
+ );
843
+ // Detached kill/prune/flush work is scoped to the manager. Wait for it
844
+ // within the shutdown bound; the FiberSet finalizer interrupts anything
845
+ // still live when the manager scope closes, so cleanup cannot leak.
846
+ yield* FiberSet.awaitEmpty(cleanupFibers).pipe(
847
+ Effect.timeout(STOP_TIMEOUT_MS),
848
+ Effect.ignore,
849
+ );
850
+ yield* Effect.sync(() => {
851
+ const dir = spillDir;
852
+ spillDir = null;
853
+ if (dir) fs.rmSync(dir, { recursive: true, force: true });
854
+ });
855
+ yield* Effect.sync(() => notify());
856
+ });
857
+
858
+ const view: TerminalReadModel = {
859
+ list: () => [...entries.values()].map((entry) => entry.snapshot),
860
+ get: (id) => entries.get(id)?.snapshot,
861
+ size: () => entries.size,
862
+ subscribe: (listener) => {
863
+ listeners.add(listener);
864
+ return () => listeners.delete(listener);
865
+ },
866
+ subscribeTo: (id, listener) => {
867
+ let set = idListeners.get(id);
868
+ if (!set) {
869
+ set = new Set();
870
+ idListeners.set(id, set);
871
+ }
872
+ set.add(listener);
873
+ return () => {
874
+ set.delete(listener);
875
+ if (set.size === 0) idListeners.delete(id);
876
+ };
877
+ },
878
+ requestKill: (id) => {
879
+ const entry = entries.get(id);
880
+ if (!entry) return;
881
+ // UI-initiated kills are not "consumed": the killed result still flows
882
+ // back to the model as a follow-up message (subagents precedent).
883
+ runCleanup(killEntry(entry).pipe(Effect.ignore));
884
+ },
885
+ setOnSettled: (hook) => {
886
+ onSettled = hook;
887
+ },
888
+ };
889
+
890
+ // Safety net: disposing the ManagedRuntime tears everything down even if
891
+ // the extension forgot to call disposeAll explicitly.
892
+ yield* Effect.addFinalizer(() => disposeAll);
893
+
894
+ return TerminalManager.of({
895
+ start,
896
+ status,
897
+ kill,
898
+ list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
899
+ disposeAll,
900
+ view,
901
+ });
902
+ });
903
+
904
+ export const TerminalManagerLive: Layer.Layer<TerminalManager> = Layer.effect(
905
+ TerminalManager,
906
+ makeManager,
907
+ );