@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,736 +1,736 @@
1
- /**
2
- * SubagentManager — owns the registry of running/finished subagents.
3
- *
4
- * Each subagent is a scoped `SubagentSession` from a `SubagentBackend` plus a
5
- * pump fiber that folds its normalized event stream into a mutable
6
- * `SubagentSnapshot`. Closing a subagent's scope kills the underlying
7
- * session/process and stops the pump.
8
- *
9
- * The manager also exposes a synchronous `SubagentReadModel` so the
10
- * imperative TUI components (which render synchronously) can read snapshots
11
- * and issue fire-and-forget commands without touching the Effect runtime.
12
- */
13
-
14
- import {
15
- Context,
16
- Effect,
17
- Exit,
18
- Fiber,
19
- Layer,
20
- Result,
21
- Scope,
22
- Stream,
23
- } from "effect";
24
- import type { SubagentBackend, SubagentSession } from "./backend.ts";
25
- import { BackendRegistry } from "./backend.ts";
26
- import type {
27
- BackendName,
28
- LiveToolState,
29
- RunOutcome,
30
- SpawnTask,
31
- SubagentEvent,
32
- SubagentOrigin,
33
- SubagentMeta,
34
- SubagentSnapshot,
35
- SubagentStatus,
36
- TranscriptItem,
37
- } from "./domain.ts";
38
- import {
39
- BackendUnavailableError,
40
- ConcurrencyLimitError,
41
- SendError,
42
- SpawnError,
43
- } from "./domain.ts";
44
-
45
- export const MAX_RUNNING = 4;
46
- export const MAX_TRACKED = 64;
47
- const STOP_TIMEOUT_MS = 5_000;
48
- const ERROR_TEXT_MAX_LENGTH = 4_096;
49
- const TRANSCRIPT_TEXT_MAX_LENGTH = 64 * 1_024;
50
- const LIVE_ASSISTANT_MAX_LENGTH = 128 * 1_024;
51
- const FINAL_TEXT_MAX_LENGTH = 1_024 * 1_024;
52
- const MAX_TRANSCRIPT_ITEMS = 512;
53
-
54
- function bounded(text: string) {
55
- return text.slice(0, ERROR_TEXT_MAX_LENGTH);
56
- }
57
-
58
- function boundedTranscriptText(text: string) {
59
- return text.slice(0, TRANSCRIPT_TEXT_MAX_LENGTH);
60
- }
61
-
62
- function appendTranscript(snapshot: MutableSnapshot, item: TranscriptItem) {
63
- snapshot.transcript.push(item);
64
- if (snapshot.transcript.length > MAX_TRANSCRIPT_ITEMS) {
65
- snapshot.transcript.splice(
66
- 0,
67
- snapshot.transcript.length - MAX_TRANSCRIPT_ITEMS,
68
- );
69
- }
70
- }
71
-
72
- // --- Internal state -----------------------------------------------------------
73
-
74
- /** Mutable snapshot; exposed to readers via the readonly SubagentSnapshot type. */
75
- interface MutableSnapshot {
76
- id: string;
77
- origin: SubagentOrigin;
78
- backend: BackendName;
79
- title: string;
80
- prompt: string;
81
- cwd: string;
82
- status: SubagentStatus;
83
- createdAt: number;
84
- settledAt?: number;
85
- errorText?: string;
86
- meta: SubagentMeta;
87
- usage: { tokens?: number; contextWindow?: number };
88
- transcript: TranscriptItem[];
89
- liveAssistant?: { text: string; thinking: string };
90
- liveTools: LiveToolState[];
91
- queued: SubagentSnapshot["queued"];
92
- finalText: string;
93
- turns: number;
94
- }
95
-
96
- interface Entry {
97
- snapshot: MutableSnapshot;
98
- session: SubagentSession;
99
- scope: Scope.Closeable;
100
- pump?: Fiber.Fiber<void>;
101
- liveToolMap: Map<string, LiveToolState>;
102
- /** Idle restart dispatched but RunStarted not folded yet; counts as running
103
- * so concurrent restarts cannot race past the cap. */
104
- restarting?: boolean;
105
- }
106
-
107
- // --- Read model ----------------------------------------------------------------
108
-
109
- /** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
110
- export interface SubagentReadModel {
111
- list(): ReadonlyArray<SubagentSnapshot>;
112
- get(id: string): SubagentSnapshot | undefined;
113
- size(): number;
114
- /** Any-change notification (footer status, dashboard). */
115
- subscribe(listener: () => void): () => void;
116
- /** Per-subagent notification (takeover view). */
117
- subscribeTo(id: string, listener: () => void): () => void;
118
- /** Fire-and-forget: steer/continue a subagent (takeover input). */
119
- requestSend(id: string, text: string): void;
120
- /** Fire-and-forget: abort a running subagent (dashboard `x`, takeover). */
121
- requestAbort(id: string): void;
122
- /**
123
- * Register the settle hook. `consumed` is true when an active
124
- * subagent_wait/cancel is collecting the result (so it must not also be
125
- * delivered as a follow-up message).
126
- */
127
- setOnSettled(
128
- hook: ((snap: SubagentSnapshot, consumed: boolean) => void) | undefined,
129
- ): void;
130
- }
131
-
132
- // --- Service --------------------------------------------------------------------
133
-
134
- export interface CancelResult {
135
- readonly id: string;
136
- readonly title: string;
137
- readonly status: SubagentStatus;
138
- readonly cancelled: boolean;
139
- }
140
-
141
- export interface SubagentManagerShape {
142
- spawn(
143
- backend: BackendName,
144
- task: SpawnTask,
145
- ): Effect.Effect<
146
- SubagentSnapshot,
147
- SpawnError | ConcurrencyLimitError | BackendUnavailableError
148
- >;
149
- /**
150
- * Wait until all listed subagents are settled. Unknown ids are treated as
151
- * settled (the tool layer validates ids first). While waiting, settles for
152
- * these ids are marked "consumed". Interruption (tool abort) releases the
153
- * interest and leaves the subagents running.
154
- */
155
- waitFor(
156
- ids: ReadonlyArray<string>,
157
- onPending?: (pending: string[]) => void,
158
- ): Effect.Effect<void>;
159
- /** Cancel running subagents; resolves when they have settled. */
160
- cancel(
161
- ids: ReadonlyArray<string>,
162
- ): Effect.Effect<ReadonlyArray<CancelResult>>;
163
- send(id: string, text: string): Effect.Effect<void, SendError>;
164
- get(id: string): Effect.Effect<SubagentSnapshot | undefined>;
165
- readonly list: Effect.Effect<ReadonlyArray<SubagentSnapshot>>;
166
- readonly disposeAll: Effect.Effect<void>;
167
- readonly view: SubagentReadModel;
168
- }
169
-
170
- export class SubagentManager extends Context.Service<
171
- SubagentManager,
172
- SubagentManagerShape
173
- >()("subagents/SubagentManager") {}
174
-
175
- // --- Implementation --------------------------------------------------------------
176
-
177
- const makeManager = Effect.gen(function* () {
178
- const registry = yield* BackendRegistry;
179
- // Detached forker for sync contexts (read-model commands, pruning) that
180
- // preserves the manager's services instead of using the global runtime.
181
- const runDetached = Effect.runForkWith(yield* Effect.context());
182
-
183
- const entries = new Map<string, Entry>();
184
- const waitInterest = new Map<string, number>();
185
- const listeners = new Set<() => void>();
186
- /** One-shot nextChange waiters, swapped out before invocation so waiters
187
- * re-registering during notification are not visited in the same sweep. */
188
- let changeWaiters: Array<() => void> = [];
189
- const idListeners = new Map<string, Set<() => void>>();
190
- const cleanups = new Set<Fiber.Fiber<unknown>>();
191
- let modelCounter = 0;
192
- let btwCounter = 0;
193
- let reserved = 0;
194
- let disposed = false;
195
- let onSettled:
196
- ((snap: SubagentSnapshot, consumed: boolean) => void) | undefined;
197
-
198
- const notify = (id?: string) => {
199
- const waiters = changeWaiters;
200
- changeWaiters = [];
201
- for (const waiter of waiters) waiter();
202
- for (const listener of [...listeners]) {
203
- try {
204
- listener();
205
- } catch {
206
- // A failed status/render listener must not corrupt lifecycle state.
207
- }
208
- }
209
- if (id) {
210
- for (const listener of idListeners.get(id) ?? []) {
211
- try {
212
- listener();
213
- } catch {
214
- // Same.
215
- }
216
- }
217
- }
218
- };
219
-
220
- /** Resolves on the next state change. Interruption unregisters the waiter. */
221
- const nextChange = Effect.callback<void>((resume) => {
222
- const waiter = () => resume(Effect.void);
223
- changeWaiters.push(waiter);
224
- return Effect.sync(() => {
225
- const index = changeWaiters.indexOf(waiter);
226
- if (index >= 0) changeWaiters.splice(index, 1);
227
- });
228
- });
229
-
230
- const runningCount = () =>
231
- [...entries.values()].filter(
232
- (e) => e.snapshot.status === "running" || e.restarting === true,
233
- ).length;
234
-
235
- const addInterest = (ids: ReadonlyArray<string>) => {
236
- for (const id of ids) waitInterest.set(id, (waitInterest.get(id) ?? 0) + 1);
237
- };
238
- const releaseInterest = (ids: ReadonlyArray<string>) => {
239
- for (const id of ids) {
240
- const count = (waitInterest.get(id) ?? 1) - 1;
241
- if (count <= 0) waitInterest.delete(id);
242
- else waitInterest.set(id, count);
243
- }
244
- };
245
-
246
- const closeEntryScope = (entry: Entry) =>
247
- Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
248
-
249
- const pruneSettled = () => {
250
- if (entries.size <= MAX_TRACKED) return;
251
- const candidates = [...entries.values()]
252
- .filter(
253
- (e) =>
254
- e.snapshot.status !== "running" && !waitInterest.has(e.snapshot.id),
255
- )
256
- .sort(
257
- (a, b) =>
258
- (a.snapshot.settledAt ?? a.snapshot.createdAt) -
259
- (b.snapshot.settledAt ?? b.snapshot.createdAt),
260
- );
261
- for (const entry of candidates) {
262
- if (entries.size <= MAX_TRACKED) break;
263
- entries.delete(entry.snapshot.id);
264
- const fiber = runDetached(closeEntryScope(entry));
265
- cleanups.add(fiber);
266
- fiber.addObserver(() => cleanups.delete(fiber));
267
- }
268
- };
269
-
270
- const settle = (entry: Entry, outcome: RunOutcome) => {
271
- const s = entry.snapshot;
272
- entry.restarting = false;
273
- if (s.status !== "running") return;
274
- s.settledAt = Date.now();
275
- switch (outcome._tag) {
276
- case "Completed":
277
- s.status = "done";
278
- s.errorText = undefined;
279
- s.finalText = outcome.finalText.slice(0, FINAL_TEXT_MAX_LENGTH);
280
- break;
281
- case "Failed":
282
- s.status = "error";
283
- s.errorText = bounded(outcome.errorText);
284
- // Never let a failed run report the previous run's successful output.
285
- s.finalText = (outcome.partialText ?? "").slice(
286
- 0,
287
- FINAL_TEXT_MAX_LENGTH,
288
- );
289
- break;
290
- case "Interrupted":
291
- s.status = "error";
292
- s.errorText = "Run was aborted";
293
- s.finalText = (outcome.partialText ?? "").slice(
294
- 0,
295
- FINAL_TEXT_MAX_LENGTH,
296
- );
297
- break;
298
- }
299
- s.liveAssistant = undefined;
300
- entry.liveToolMap.clear();
301
- s.liveTools = [];
302
- s.queued = [];
303
- const consumed = (waitInterest.get(s.id) ?? 0) > 0;
304
- notify(s.id);
305
- try {
306
- // During teardown, don't queue results into a shutting-down session.
307
- if (!disposed) onSettled?.(s, consumed);
308
- } catch {
309
- // The parent session may be unavailable; settlement stays final.
310
- }
311
- pruneSettled();
312
- };
313
-
314
- const foldEvent = (entry: Entry, event: SubagentEvent) => {
315
- const s = entry.snapshot;
316
- switch (event._tag) {
317
- case "RunStarted":
318
- entry.restarting = false;
319
- s.status = "running";
320
- s.settledAt = undefined;
321
- s.errorText = undefined;
322
- break;
323
- case "RunSettled":
324
- settle(entry, event.outcome);
325
- return; // settle() already notified
326
- case "UserMessage":
327
- appendTranscript(s, {
328
- kind: "user",
329
- text: boundedTranscriptText(event.text),
330
- });
331
- break;
332
- case "AssistantDelta": {
333
- const live = s.liveAssistant ?? { text: "", thinking: "" };
334
- s.liveAssistant =
335
- event.kind === "text"
336
- ? {
337
- ...live,
338
- text: (live.text + event.delta).slice(
339
- -LIVE_ASSISTANT_MAX_LENGTH,
340
- ),
341
- }
342
- : {
343
- ...live,
344
- thinking: (live.thinking + event.delta).slice(
345
- -LIVE_ASSISTANT_MAX_LENGTH,
346
- ),
347
- };
348
- break;
349
- }
350
- case "AssistantMessage":
351
- appendTranscript(s, {
352
- kind: "assistant",
353
- parts: event.parts.map((part) =>
354
- part.type === "toolCall"
355
- ? {
356
- ...part,
357
- argsPreview: part.argsPreview
358
- ? boundedTranscriptText(part.argsPreview)
359
- : undefined,
360
- }
361
- : { ...part, text: boundedTranscriptText(part.text) },
362
- ),
363
- });
364
- s.liveAssistant = undefined;
365
- s.turns++;
366
- break;
367
- case "ToolStart":
368
- entry.liveToolMap.set(event.toolId, {
369
- toolId: event.toolId,
370
- name: event.name,
371
- argsPreview: event.argsPreview
372
- ? boundedTranscriptText(event.argsPreview)
373
- : undefined,
374
- });
375
- s.liveTools = [...entry.liveToolMap.values()];
376
- break;
377
- case "ToolUpdate": {
378
- const current = entry.liveToolMap.get(event.toolId);
379
- if (current) {
380
- entry.liveToolMap.set(event.toolId, {
381
- ...current,
382
- outputPreview: event.outputPreview
383
- ? boundedTranscriptText(event.outputPreview)
384
- : current.outputPreview,
385
- });
386
- s.liveTools = [...entry.liveToolMap.values()];
387
- }
388
- break;
389
- }
390
- case "ToolEnd":
391
- entry.liveToolMap.delete(event.toolId);
392
- s.liveTools = [...entry.liveToolMap.values()];
393
- appendTranscript(s, {
394
- kind: "toolResult",
395
- toolId: event.toolId,
396
- name: event.name,
397
- isError: event.isError,
398
- outputPreview: event.outputPreview
399
- ? boundedTranscriptText(event.outputPreview)
400
- : undefined,
401
- });
402
- break;
403
- case "QueueChanged":
404
- s.queued = event.queued;
405
- break;
406
- case "UsageChanged":
407
- s.usage = {
408
- tokens: event.tokens ?? s.usage.tokens,
409
- contextWindow: event.contextWindow ?? s.usage.contextWindow,
410
- };
411
- break;
412
- case "MetaChanged":
413
- s.meta = { ...s.meta, ...event.meta };
414
- break;
415
- case "BackendError":
416
- s.errorText = bounded(event.message);
417
- break;
418
- }
419
- notify(s.id);
420
- };
421
-
422
- const spawn = (backendName: BackendName, task: SpawnTask) =>
423
- Effect.gen(function* () {
424
- // Reserve synchronously (before the first yield inside doSpawn) so
425
- // parallel tool calls cannot race past the global cap.
426
- yield* Effect.suspend(
427
- (): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
428
- if (disposed) {
429
- return new SpawnError({
430
- message: "Subagent manager is shutting down.",
431
- });
432
- }
433
- if (runningCount() + reserved >= MAX_RUNNING) {
434
- return new ConcurrencyLimitError({
435
- message: `Max ${MAX_RUNNING} subagents can run concurrently. Wait for one to finish before spawning another.`,
436
- });
437
- }
438
- reserved++;
439
- return Effect.void;
440
- },
441
- );
442
-
443
- const doSpawn = Effect.gen(function* () {
444
- const backend: SubagentBackend | undefined = registry.get(backendName);
445
- if (!backend) {
446
- return yield* new BackendUnavailableError({
447
- message: `Unknown backend "${backendName}".`,
448
- });
449
- }
450
- const available = yield* backend.available;
451
- if (!available) {
452
- return yield* new BackendUnavailableError({
453
- message: `Backend "${backendName}" is not available on this machine (binary/SDK/credentials missing).`,
454
- });
455
- }
456
-
457
- const scope = yield* Scope.make();
458
- const session = yield* Scope.provide(backend.spawn(task), scope).pipe(
459
- Effect.onError(() => Scope.close(scope, Exit.void)),
460
- );
461
- if (disposed) {
462
- yield* Scope.close(scope, Exit.void);
463
- return yield* new SpawnError({
464
- message: "Subagent manager shut down while spawning.",
465
- });
466
- }
467
-
468
- const origin = task.origin ?? "model";
469
- const id =
470
- origin === "btw" ? `btw-${++btwCounter}` : `sa-${++modelCounter}`;
471
- const meta = yield* session.meta;
472
- const entry: Entry = {
473
- snapshot: {
474
- id,
475
- origin,
476
- backend: backendName,
477
- title: task.title,
478
- prompt: task.prompt,
479
- cwd: task.cwd,
480
- status: "running",
481
- createdAt: Date.now(),
482
- meta,
483
- usage: { contextWindow: meta.contextWindow },
484
- transcript: [],
485
- liveTools: [],
486
- queued: [],
487
- finalText: "",
488
- turns: 0,
489
- },
490
- session,
491
- scope,
492
- liveToolMap: new Map(),
493
- };
494
- entries.set(id, entry);
495
-
496
- // Pump: fold the event stream into the snapshot. Tied to the entry
497
- // scope, so closing the scope stops it. If the stream ends while the
498
- // subagent still looks running, the backend died out from under us.
499
- const pump = Stream.runForEach(session.events, (event) =>
500
- Effect.sync(() => foldEvent(entry, event)),
501
- ).pipe(
502
- Effect.ensuring(
503
- Effect.sync(() => {
504
- if (entry.snapshot.status === "running") {
505
- settle(entry, {
506
- _tag: "Failed",
507
- errorText: "Backend event stream ended unexpectedly",
508
- });
509
- }
510
- }),
511
- ),
512
- );
513
- entry.pump = yield* Scope.provide(Effect.forkScoped(pump), scope);
514
-
515
- notify(id);
516
- return entry.snapshot as SubagentSnapshot;
517
- });
518
-
519
- return yield* doSpawn.pipe(
520
- Effect.ensuring(
521
- Effect.sync(() => {
522
- reserved--;
523
- notify();
524
- }),
525
- ),
526
- );
527
- });
528
-
529
- const waitFor = (
530
- ids: ReadonlyArray<string>,
531
- onPending?: (pending: string[]) => void,
532
- ) =>
533
- Effect.suspend(() => {
534
- const unique = [...new Set(ids)];
535
- addInterest(unique);
536
- const loop = Effect.gen(function* () {
537
- while (true) {
538
- const pending = unique.filter(
539
- (id) => entries.get(id)?.snapshot.status === "running",
540
- );
541
- if (pending.length === 0) return;
542
- onPending?.(pending);
543
- yield* nextChange;
544
- }
545
- });
546
- return loop.pipe(
547
- Effect.ensuring(
548
- Effect.sync(() => {
549
- releaseInterest(unique);
550
- pruneSettled();
551
- }),
552
- ),
553
- );
554
- });
555
-
556
- /** Interrupt one running entry, force-closing its scope after 5s. */
557
- const abortEntry = (entry: Entry) =>
558
- Effect.gen(function* () {
559
- if (entry.snapshot.status !== "running") return;
560
- const graceful = yield* entry.session.interrupt.pipe(
561
- Effect.timeout(STOP_TIMEOUT_MS),
562
- Effect.result,
563
- );
564
- if (Result.isFailure(graceful)) {
565
- // Settle before closing the scope so the pump's stream-ended
566
- // fallback ("Backend event stream ended unexpectedly") cannot win
567
- // the race and report the wrong terminal reason.
568
- yield* Effect.sync(() => {
569
- settle(entry, { _tag: "Interrupted" });
570
- entry.snapshot.errorText =
571
- "Abort deadline exceeded; session was force-disposed";
572
- notify(entry.snapshot.id);
573
- });
574
- // Bound the close like disposeAll does: a stuck backend finalizer
575
- // must not hang cancel after the run is already settled.
576
- yield* closeEntryScope(entry).pipe(
577
- Effect.timeout(STOP_TIMEOUT_MS),
578
- Effect.ignore,
579
- );
580
- }
581
- });
582
-
583
- const cancel = (ids: ReadonlyArray<string>) =>
584
- Effect.suspend(() => {
585
- const unique = [...new Set(ids)];
586
- const running = unique
587
- .map((id) => entries.get(id))
588
- .filter(
589
- (entry): entry is Entry => entry?.snapshot.status === "running",
590
- );
591
- const runningIds = running.map((entry) => entry.snapshot.id);
592
- // Mark consumed before interrupting so cancellation does not also
593
- // enqueue duplicate automatic result messages into the parent.
594
- addInterest(runningIds);
595
- const work = Effect.gen(function* () {
596
- yield* Effect.forEach(running, abortEntry, {
597
- concurrency: "unbounded",
598
- });
599
- while (running.some((entry) => entry.snapshot.status === "running")) {
600
- yield* nextChange;
601
- }
602
- });
603
- return work.pipe(
604
- Effect.ensuring(
605
- Effect.sync(() => {
606
- releaseInterest(runningIds);
607
- pruneSettled();
608
- }),
609
- ),
610
- Effect.map((): ReadonlyArray<CancelResult> =>
611
- unique.map((id) => {
612
- const snapshot = entries.get(id)?.snapshot;
613
- return {
614
- id,
615
- title: snapshot?.title ?? "?",
616
- status: snapshot?.status ?? "error",
617
- cancelled: runningIds.includes(id),
618
- };
619
- }),
620
- ),
621
- );
622
- });
623
-
624
- const send = (id: string, text: string) =>
625
- Effect.suspend((): Effect.Effect<void, SendError> => {
626
- const entry = entries.get(id);
627
- if (!entry || disposed) {
628
- return new SendError({
629
- message: `Subagent "${id}" is no longer tracked.`,
630
- });
631
- }
632
- // Restarting a settled subagent occupies a running slot again, so it
633
- // must respect the same cap as spawn. Steering an already-running one
634
- // does not consume additional capacity.
635
- if (entry.snapshot.status !== "running") {
636
- if (runningCount() + reserved >= MAX_RUNNING) {
637
- return new SendError({
638
- message: `Max ${MAX_RUNNING} subagents can run concurrently; restarting "${id}" would exceed that.`,
639
- });
640
- }
641
- // Occupy the slot synchronously: the RunStarted that flips status
642
- // arrives via the async pump, and two concurrent restarts must not
643
- // both pass the check in that window. Cleared by RunStarted/settle,
644
- // or here when the backend rejects the send.
645
- entry.restarting = true;
646
- return entry.session.send(text).pipe(
647
- Effect.onError(() =>
648
- Effect.sync(() => {
649
- entry.restarting = false;
650
- }),
651
- ),
652
- );
653
- }
654
- return entry.session.send(text);
655
- });
656
-
657
- const disposeAll = Effect.gen(function* () {
658
- disposed = true;
659
- const all = [...entries.values()];
660
- entries.clear();
661
- yield* Effect.forEach(
662
- all,
663
- (entry) =>
664
- closeEntryScope(entry).pipe(
665
- Effect.timeout(STOP_TIMEOUT_MS),
666
- Effect.ignore,
667
- ),
668
- { concurrency: "unbounded" },
669
- );
670
- // Pruning cleanups are detached; bound them like everything else so a
671
- // stuck backend finalizer cannot block runtime shutdown indefinitely.
672
- yield* Effect.forEach(
673
- [...cleanups],
674
- (fiber) =>
675
- Fiber.await(fiber).pipe(Effect.timeout(STOP_TIMEOUT_MS), Effect.ignore),
676
- { concurrency: "unbounded" },
677
- ).pipe(Effect.ignore);
678
- yield* Effect.sync(() => notify());
679
- });
680
-
681
- const view: SubagentReadModel = {
682
- list: () => [...entries.values()].map((entry) => entry.snapshot),
683
- get: (id) => entries.get(id)?.snapshot,
684
- size: () => entries.size,
685
- subscribe: (listener) => {
686
- listeners.add(listener);
687
- return () => listeners.delete(listener);
688
- },
689
- subscribeTo: (id, listener) => {
690
- let set = idListeners.get(id);
691
- if (!set) {
692
- set = new Set();
693
- idListeners.set(id, set);
694
- }
695
- set.add(listener);
696
- return () => {
697
- set.delete(listener);
698
- if (set.size === 0) idListeners.delete(id);
699
- };
700
- },
701
- requestSend: (id, text) => {
702
- runDetached(send(id, text).pipe(Effect.ignore));
703
- },
704
- requestAbort: (id) => {
705
- const entry = entries.get(id);
706
- if (!entry) return;
707
- // UI-initiated aborts are not "consumed": the failed result still
708
- // flows back to the parent as a follow-up message, matching v1.
709
- runDetached(abortEntry(entry).pipe(Effect.ignore));
710
- },
711
- setOnSettled: (hook) => {
712
- onSettled = hook;
713
- },
714
- };
715
-
716
- // Safety net: disposing the ManagedRuntime tears everything down even if
717
- // the extension forgot to call disposeAll explicitly.
718
- yield* Effect.addFinalizer(() => disposeAll);
719
-
720
- return SubagentManager.of({
721
- spawn,
722
- waitFor,
723
- cancel,
724
- send,
725
- get: (id) => Effect.sync(() => entries.get(id)?.snapshot),
726
- list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
727
- disposeAll,
728
- view,
729
- });
730
- });
731
-
732
- export const SubagentManagerLive: Layer.Layer<
733
- SubagentManager,
734
- never,
735
- BackendRegistry
736
- > = Layer.effect(SubagentManager, makeManager);
1
+ /**
2
+ * SubagentManager — owns the registry of running/finished subagents.
3
+ *
4
+ * Each subagent is a scoped `SubagentSession` from a `SubagentBackend` plus a
5
+ * pump fiber that folds its normalized event stream into a mutable
6
+ * `SubagentSnapshot`. Closing a subagent's scope kills the underlying
7
+ * session/process and stops the pump.
8
+ *
9
+ * The manager also exposes a synchronous `SubagentReadModel` so the
10
+ * imperative TUI components (which render synchronously) can read snapshots
11
+ * and issue fire-and-forget commands without touching the Effect runtime.
12
+ */
13
+
14
+ import {
15
+ Context,
16
+ Effect,
17
+ Exit,
18
+ Fiber,
19
+ Layer,
20
+ Result,
21
+ Scope,
22
+ Stream,
23
+ } from "effect";
24
+ import type { SubagentBackend, SubagentSession } from "./backend.ts";
25
+ import { BackendRegistry } from "./backend.ts";
26
+ import type {
27
+ BackendName,
28
+ LiveToolState,
29
+ RunOutcome,
30
+ SpawnTask,
31
+ SubagentEvent,
32
+ SubagentOrigin,
33
+ SubagentMeta,
34
+ SubagentSnapshot,
35
+ SubagentStatus,
36
+ TranscriptItem,
37
+ } from "./domain.ts";
38
+ import {
39
+ BackendUnavailableError,
40
+ ConcurrencyLimitError,
41
+ SendError,
42
+ SpawnError,
43
+ } from "./domain.ts";
44
+
45
+ export const MAX_RUNNING = 4;
46
+ export const MAX_TRACKED = 64;
47
+ const STOP_TIMEOUT_MS = 5_000;
48
+ const ERROR_TEXT_MAX_LENGTH = 4_096;
49
+ const TRANSCRIPT_TEXT_MAX_LENGTH = 64 * 1_024;
50
+ const LIVE_ASSISTANT_MAX_LENGTH = 128 * 1_024;
51
+ const FINAL_TEXT_MAX_LENGTH = 1_024 * 1_024;
52
+ const MAX_TRANSCRIPT_ITEMS = 512;
53
+
54
+ function bounded(text: string) {
55
+ return text.slice(0, ERROR_TEXT_MAX_LENGTH);
56
+ }
57
+
58
+ function boundedTranscriptText(text: string) {
59
+ return text.slice(0, TRANSCRIPT_TEXT_MAX_LENGTH);
60
+ }
61
+
62
+ function appendTranscript(snapshot: MutableSnapshot, item: TranscriptItem) {
63
+ snapshot.transcript.push(item);
64
+ if (snapshot.transcript.length > MAX_TRANSCRIPT_ITEMS) {
65
+ snapshot.transcript.splice(
66
+ 0,
67
+ snapshot.transcript.length - MAX_TRANSCRIPT_ITEMS,
68
+ );
69
+ }
70
+ }
71
+
72
+ // --- Internal state -----------------------------------------------------------
73
+
74
+ /** Mutable snapshot; exposed to readers via the readonly SubagentSnapshot type. */
75
+ interface MutableSnapshot {
76
+ id: string;
77
+ origin: SubagentOrigin;
78
+ backend: BackendName;
79
+ title: string;
80
+ prompt: string;
81
+ cwd: string;
82
+ status: SubagentStatus;
83
+ createdAt: number;
84
+ settledAt?: number;
85
+ errorText?: string;
86
+ meta: SubagentMeta;
87
+ usage: { tokens?: number; contextWindow?: number };
88
+ transcript: TranscriptItem[];
89
+ liveAssistant?: { text: string; thinking: string };
90
+ liveTools: LiveToolState[];
91
+ queued: SubagentSnapshot["queued"];
92
+ finalText: string;
93
+ turns: number;
94
+ }
95
+
96
+ interface Entry {
97
+ snapshot: MutableSnapshot;
98
+ session: SubagentSession;
99
+ scope: Scope.Closeable;
100
+ pump?: Fiber.Fiber<void>;
101
+ liveToolMap: Map<string, LiveToolState>;
102
+ /** Idle restart dispatched but RunStarted not folded yet; counts as running
103
+ * so concurrent restarts cannot race past the cap. */
104
+ restarting?: boolean;
105
+ }
106
+
107
+ // --- Read model ----------------------------------------------------------------
108
+
109
+ /** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
110
+ export interface SubagentReadModel {
111
+ list(): ReadonlyArray<SubagentSnapshot>;
112
+ get(id: string): SubagentSnapshot | undefined;
113
+ size(): number;
114
+ /** Any-change notification (footer status, dashboard). */
115
+ subscribe(listener: () => void): () => void;
116
+ /** Per-subagent notification (takeover view). */
117
+ subscribeTo(id: string, listener: () => void): () => void;
118
+ /** Fire-and-forget: steer/continue a subagent (takeover input). */
119
+ requestSend(id: string, text: string): void;
120
+ /** Fire-and-forget: abort a running subagent (dashboard `x`, takeover). */
121
+ requestAbort(id: string): void;
122
+ /**
123
+ * Register the settle hook. `consumed` is true when an active
124
+ * subagent_wait/cancel is collecting the result (so it must not also be
125
+ * delivered as a follow-up message).
126
+ */
127
+ setOnSettled(
128
+ hook: ((snap: SubagentSnapshot, consumed: boolean) => void) | undefined,
129
+ ): void;
130
+ }
131
+
132
+ // --- Service --------------------------------------------------------------------
133
+
134
+ export interface CancelResult {
135
+ readonly id: string;
136
+ readonly title: string;
137
+ readonly status: SubagentStatus;
138
+ readonly cancelled: boolean;
139
+ }
140
+
141
+ export interface SubagentManagerShape {
142
+ spawn(
143
+ backend: BackendName,
144
+ task: SpawnTask,
145
+ ): Effect.Effect<
146
+ SubagentSnapshot,
147
+ SpawnError | ConcurrencyLimitError | BackendUnavailableError
148
+ >;
149
+ /**
150
+ * Wait until all listed subagents are settled. Unknown ids are treated as
151
+ * settled (the tool layer validates ids first). While waiting, settles for
152
+ * these ids are marked "consumed". Interruption (tool abort) releases the
153
+ * interest and leaves the subagents running.
154
+ */
155
+ waitFor(
156
+ ids: ReadonlyArray<string>,
157
+ onPending?: (pending: string[]) => void,
158
+ ): Effect.Effect<void>;
159
+ /** Cancel running subagents; resolves when they have settled. */
160
+ cancel(
161
+ ids: ReadonlyArray<string>,
162
+ ): Effect.Effect<ReadonlyArray<CancelResult>>;
163
+ send(id: string, text: string): Effect.Effect<void, SendError>;
164
+ get(id: string): Effect.Effect<SubagentSnapshot | undefined>;
165
+ readonly list: Effect.Effect<ReadonlyArray<SubagentSnapshot>>;
166
+ readonly disposeAll: Effect.Effect<void>;
167
+ readonly view: SubagentReadModel;
168
+ }
169
+
170
+ export class SubagentManager extends Context.Service<
171
+ SubagentManager,
172
+ SubagentManagerShape
173
+ >()("subagents/SubagentManager") {}
174
+
175
+ // --- Implementation --------------------------------------------------------------
176
+
177
+ const makeManager = Effect.gen(function* () {
178
+ const registry = yield* BackendRegistry;
179
+ // Detached forker for sync contexts (read-model commands, pruning) that
180
+ // preserves the manager's services instead of using the global runtime.
181
+ const runDetached = Effect.runForkWith(yield* Effect.context());
182
+
183
+ const entries = new Map<string, Entry>();
184
+ const waitInterest = new Map<string, number>();
185
+ const listeners = new Set<() => void>();
186
+ /** One-shot nextChange waiters, swapped out before invocation so waiters
187
+ * re-registering during notification are not visited in the same sweep. */
188
+ let changeWaiters: Array<() => void> = [];
189
+ const idListeners = new Map<string, Set<() => void>>();
190
+ const cleanups = new Set<Fiber.Fiber<unknown>>();
191
+ let modelCounter = 0;
192
+ let btwCounter = 0;
193
+ let reserved = 0;
194
+ let disposed = false;
195
+ let onSettled:
196
+ ((snap: SubagentSnapshot, consumed: boolean) => void) | undefined;
197
+
198
+ const notify = (id?: string) => {
199
+ const waiters = changeWaiters;
200
+ changeWaiters = [];
201
+ for (const waiter of waiters) waiter();
202
+ for (const listener of [...listeners]) {
203
+ try {
204
+ listener();
205
+ } catch {
206
+ // A failed status/render listener must not corrupt lifecycle state.
207
+ }
208
+ }
209
+ if (id) {
210
+ for (const listener of idListeners.get(id) ?? []) {
211
+ try {
212
+ listener();
213
+ } catch {
214
+ // Same.
215
+ }
216
+ }
217
+ }
218
+ };
219
+
220
+ /** Resolves on the next state change. Interruption unregisters the waiter. */
221
+ const nextChange = Effect.callback<void>((resume) => {
222
+ const waiter = () => resume(Effect.void);
223
+ changeWaiters.push(waiter);
224
+ return Effect.sync(() => {
225
+ const index = changeWaiters.indexOf(waiter);
226
+ if (index >= 0) changeWaiters.splice(index, 1);
227
+ });
228
+ });
229
+
230
+ const runningCount = () =>
231
+ [...entries.values()].filter(
232
+ (e) => e.snapshot.status === "running" || e.restarting === true,
233
+ ).length;
234
+
235
+ const addInterest = (ids: ReadonlyArray<string>) => {
236
+ for (const id of ids) waitInterest.set(id, (waitInterest.get(id) ?? 0) + 1);
237
+ };
238
+ const releaseInterest = (ids: ReadonlyArray<string>) => {
239
+ for (const id of ids) {
240
+ const count = (waitInterest.get(id) ?? 1) - 1;
241
+ if (count <= 0) waitInterest.delete(id);
242
+ else waitInterest.set(id, count);
243
+ }
244
+ };
245
+
246
+ const closeEntryScope = (entry: Entry) =>
247
+ Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
248
+
249
+ const pruneSettled = () => {
250
+ if (entries.size <= MAX_TRACKED) return;
251
+ const candidates = [...entries.values()]
252
+ .filter(
253
+ (e) =>
254
+ e.snapshot.status !== "running" && !waitInterest.has(e.snapshot.id),
255
+ )
256
+ .sort(
257
+ (a, b) =>
258
+ (a.snapshot.settledAt ?? a.snapshot.createdAt) -
259
+ (b.snapshot.settledAt ?? b.snapshot.createdAt),
260
+ );
261
+ for (const entry of candidates) {
262
+ if (entries.size <= MAX_TRACKED) break;
263
+ entries.delete(entry.snapshot.id);
264
+ const fiber = runDetached(closeEntryScope(entry));
265
+ cleanups.add(fiber);
266
+ fiber.addObserver(() => cleanups.delete(fiber));
267
+ }
268
+ };
269
+
270
+ const settle = (entry: Entry, outcome: RunOutcome) => {
271
+ const s = entry.snapshot;
272
+ entry.restarting = false;
273
+ if (s.status !== "running") return;
274
+ s.settledAt = Date.now();
275
+ switch (outcome._tag) {
276
+ case "Completed":
277
+ s.status = "done";
278
+ s.errorText = undefined;
279
+ s.finalText = outcome.finalText.slice(0, FINAL_TEXT_MAX_LENGTH);
280
+ break;
281
+ case "Failed":
282
+ s.status = "error";
283
+ s.errorText = bounded(outcome.errorText);
284
+ // Never let a failed run report the previous run's successful output.
285
+ s.finalText = (outcome.partialText ?? "").slice(
286
+ 0,
287
+ FINAL_TEXT_MAX_LENGTH,
288
+ );
289
+ break;
290
+ case "Interrupted":
291
+ s.status = "error";
292
+ s.errorText = "Run was aborted";
293
+ s.finalText = (outcome.partialText ?? "").slice(
294
+ 0,
295
+ FINAL_TEXT_MAX_LENGTH,
296
+ );
297
+ break;
298
+ }
299
+ s.liveAssistant = undefined;
300
+ entry.liveToolMap.clear();
301
+ s.liveTools = [];
302
+ s.queued = [];
303
+ const consumed = (waitInterest.get(s.id) ?? 0) > 0;
304
+ notify(s.id);
305
+ try {
306
+ // During teardown, don't queue results into a shutting-down session.
307
+ if (!disposed) onSettled?.(s, consumed);
308
+ } catch {
309
+ // The parent session may be unavailable; settlement stays final.
310
+ }
311
+ pruneSettled();
312
+ };
313
+
314
+ const foldEvent = (entry: Entry, event: SubagentEvent) => {
315
+ const s = entry.snapshot;
316
+ switch (event._tag) {
317
+ case "RunStarted":
318
+ entry.restarting = false;
319
+ s.status = "running";
320
+ s.settledAt = undefined;
321
+ s.errorText = undefined;
322
+ break;
323
+ case "RunSettled":
324
+ settle(entry, event.outcome);
325
+ return; // settle() already notified
326
+ case "UserMessage":
327
+ appendTranscript(s, {
328
+ kind: "user",
329
+ text: boundedTranscriptText(event.text),
330
+ });
331
+ break;
332
+ case "AssistantDelta": {
333
+ const live = s.liveAssistant ?? { text: "", thinking: "" };
334
+ s.liveAssistant =
335
+ event.kind === "text"
336
+ ? {
337
+ ...live,
338
+ text: (live.text + event.delta).slice(
339
+ -LIVE_ASSISTANT_MAX_LENGTH,
340
+ ),
341
+ }
342
+ : {
343
+ ...live,
344
+ thinking: (live.thinking + event.delta).slice(
345
+ -LIVE_ASSISTANT_MAX_LENGTH,
346
+ ),
347
+ };
348
+ break;
349
+ }
350
+ case "AssistantMessage":
351
+ appendTranscript(s, {
352
+ kind: "assistant",
353
+ parts: event.parts.map((part) =>
354
+ part.type === "toolCall"
355
+ ? {
356
+ ...part,
357
+ argsPreview: part.argsPreview
358
+ ? boundedTranscriptText(part.argsPreview)
359
+ : undefined,
360
+ }
361
+ : { ...part, text: boundedTranscriptText(part.text) },
362
+ ),
363
+ });
364
+ s.liveAssistant = undefined;
365
+ s.turns++;
366
+ break;
367
+ case "ToolStart":
368
+ entry.liveToolMap.set(event.toolId, {
369
+ toolId: event.toolId,
370
+ name: event.name,
371
+ argsPreview: event.argsPreview
372
+ ? boundedTranscriptText(event.argsPreview)
373
+ : undefined,
374
+ });
375
+ s.liveTools = [...entry.liveToolMap.values()];
376
+ break;
377
+ case "ToolUpdate": {
378
+ const current = entry.liveToolMap.get(event.toolId);
379
+ if (current) {
380
+ entry.liveToolMap.set(event.toolId, {
381
+ ...current,
382
+ outputPreview: event.outputPreview
383
+ ? boundedTranscriptText(event.outputPreview)
384
+ : current.outputPreview,
385
+ });
386
+ s.liveTools = [...entry.liveToolMap.values()];
387
+ }
388
+ break;
389
+ }
390
+ case "ToolEnd":
391
+ entry.liveToolMap.delete(event.toolId);
392
+ s.liveTools = [...entry.liveToolMap.values()];
393
+ appendTranscript(s, {
394
+ kind: "toolResult",
395
+ toolId: event.toolId,
396
+ name: event.name,
397
+ isError: event.isError,
398
+ outputPreview: event.outputPreview
399
+ ? boundedTranscriptText(event.outputPreview)
400
+ : undefined,
401
+ });
402
+ break;
403
+ case "QueueChanged":
404
+ s.queued = event.queued;
405
+ break;
406
+ case "UsageChanged":
407
+ s.usage = {
408
+ tokens: event.tokens ?? s.usage.tokens,
409
+ contextWindow: event.contextWindow ?? s.usage.contextWindow,
410
+ };
411
+ break;
412
+ case "MetaChanged":
413
+ s.meta = { ...s.meta, ...event.meta };
414
+ break;
415
+ case "BackendError":
416
+ s.errorText = bounded(event.message);
417
+ break;
418
+ }
419
+ notify(s.id);
420
+ };
421
+
422
+ const spawn = (backendName: BackendName, task: SpawnTask) =>
423
+ Effect.gen(function* () {
424
+ // Reserve synchronously (before the first yield inside doSpawn) so
425
+ // parallel tool calls cannot race past the global cap.
426
+ yield* Effect.suspend(
427
+ (): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
428
+ if (disposed) {
429
+ return new SpawnError({
430
+ message: "Subagent manager is shutting down.",
431
+ });
432
+ }
433
+ if (runningCount() + reserved >= MAX_RUNNING) {
434
+ return new ConcurrencyLimitError({
435
+ message: `Max ${MAX_RUNNING} subagents can run concurrently. Wait for one to finish before spawning another.`,
436
+ });
437
+ }
438
+ reserved++;
439
+ return Effect.void;
440
+ },
441
+ );
442
+
443
+ const doSpawn = Effect.gen(function* () {
444
+ const backend: SubagentBackend | undefined = registry.get(backendName);
445
+ if (!backend) {
446
+ return yield* new BackendUnavailableError({
447
+ message: `Unknown backend "${backendName}".`,
448
+ });
449
+ }
450
+ const available = yield* backend.available;
451
+ if (!available) {
452
+ return yield* new BackendUnavailableError({
453
+ message: `Backend "${backendName}" is not available on this machine (binary/SDK/credentials missing).`,
454
+ });
455
+ }
456
+
457
+ const scope = yield* Scope.make();
458
+ const session = yield* Scope.provide(backend.spawn(task), scope).pipe(
459
+ Effect.onError(() => Scope.close(scope, Exit.void)),
460
+ );
461
+ if (disposed) {
462
+ yield* Scope.close(scope, Exit.void);
463
+ return yield* new SpawnError({
464
+ message: "Subagent manager shut down while spawning.",
465
+ });
466
+ }
467
+
468
+ const origin = task.origin ?? "model";
469
+ const id =
470
+ origin === "btw" ? `btw-${++btwCounter}` : `sa-${++modelCounter}`;
471
+ const meta = yield* session.meta;
472
+ const entry: Entry = {
473
+ snapshot: {
474
+ id,
475
+ origin,
476
+ backend: backendName,
477
+ title: task.title,
478
+ prompt: task.prompt,
479
+ cwd: task.cwd,
480
+ status: "running",
481
+ createdAt: Date.now(),
482
+ meta,
483
+ usage: { contextWindow: meta.contextWindow },
484
+ transcript: [],
485
+ liveTools: [],
486
+ queued: [],
487
+ finalText: "",
488
+ turns: 0,
489
+ },
490
+ session,
491
+ scope,
492
+ liveToolMap: new Map(),
493
+ };
494
+ entries.set(id, entry);
495
+
496
+ // Pump: fold the event stream into the snapshot. Tied to the entry
497
+ // scope, so closing the scope stops it. If the stream ends while the
498
+ // subagent still looks running, the backend died out from under us.
499
+ const pump = Stream.runForEach(session.events, (event) =>
500
+ Effect.sync(() => foldEvent(entry, event)),
501
+ ).pipe(
502
+ Effect.ensuring(
503
+ Effect.sync(() => {
504
+ if (entry.snapshot.status === "running") {
505
+ settle(entry, {
506
+ _tag: "Failed",
507
+ errorText: "Backend event stream ended unexpectedly",
508
+ });
509
+ }
510
+ }),
511
+ ),
512
+ );
513
+ entry.pump = yield* Scope.provide(Effect.forkScoped(pump), scope);
514
+
515
+ notify(id);
516
+ return entry.snapshot as SubagentSnapshot;
517
+ });
518
+
519
+ return yield* doSpawn.pipe(
520
+ Effect.ensuring(
521
+ Effect.sync(() => {
522
+ reserved--;
523
+ notify();
524
+ }),
525
+ ),
526
+ );
527
+ });
528
+
529
+ const waitFor = (
530
+ ids: ReadonlyArray<string>,
531
+ onPending?: (pending: string[]) => void,
532
+ ) =>
533
+ Effect.suspend(() => {
534
+ const unique = [...new Set(ids)];
535
+ addInterest(unique);
536
+ const loop = Effect.gen(function* () {
537
+ while (true) {
538
+ const pending = unique.filter(
539
+ (id) => entries.get(id)?.snapshot.status === "running",
540
+ );
541
+ if (pending.length === 0) return;
542
+ onPending?.(pending);
543
+ yield* nextChange;
544
+ }
545
+ });
546
+ return loop.pipe(
547
+ Effect.ensuring(
548
+ Effect.sync(() => {
549
+ releaseInterest(unique);
550
+ pruneSettled();
551
+ }),
552
+ ),
553
+ );
554
+ });
555
+
556
+ /** Interrupt one running entry, force-closing its scope after 5s. */
557
+ const abortEntry = (entry: Entry) =>
558
+ Effect.gen(function* () {
559
+ if (entry.snapshot.status !== "running") return;
560
+ const graceful = yield* entry.session.interrupt.pipe(
561
+ Effect.timeout(STOP_TIMEOUT_MS),
562
+ Effect.result,
563
+ );
564
+ if (Result.isFailure(graceful)) {
565
+ // Settle before closing the scope so the pump's stream-ended
566
+ // fallback ("Backend event stream ended unexpectedly") cannot win
567
+ // the race and report the wrong terminal reason.
568
+ yield* Effect.sync(() => {
569
+ settle(entry, { _tag: "Interrupted" });
570
+ entry.snapshot.errorText =
571
+ "Abort deadline exceeded; session was force-disposed";
572
+ notify(entry.snapshot.id);
573
+ });
574
+ // Bound the close like disposeAll does: a stuck backend finalizer
575
+ // must not hang cancel after the run is already settled.
576
+ yield* closeEntryScope(entry).pipe(
577
+ Effect.timeout(STOP_TIMEOUT_MS),
578
+ Effect.ignore,
579
+ );
580
+ }
581
+ });
582
+
583
+ const cancel = (ids: ReadonlyArray<string>) =>
584
+ Effect.suspend(() => {
585
+ const unique = [...new Set(ids)];
586
+ const running = unique
587
+ .map((id) => entries.get(id))
588
+ .filter(
589
+ (entry): entry is Entry => entry?.snapshot.status === "running",
590
+ );
591
+ const runningIds = running.map((entry) => entry.snapshot.id);
592
+ // Mark consumed before interrupting so cancellation does not also
593
+ // enqueue duplicate automatic result messages into the parent.
594
+ addInterest(runningIds);
595
+ const work = Effect.gen(function* () {
596
+ yield* Effect.forEach(running, abortEntry, {
597
+ concurrency: "unbounded",
598
+ });
599
+ while (running.some((entry) => entry.snapshot.status === "running")) {
600
+ yield* nextChange;
601
+ }
602
+ });
603
+ return work.pipe(
604
+ Effect.ensuring(
605
+ Effect.sync(() => {
606
+ releaseInterest(runningIds);
607
+ pruneSettled();
608
+ }),
609
+ ),
610
+ Effect.map((): ReadonlyArray<CancelResult> =>
611
+ unique.map((id) => {
612
+ const snapshot = entries.get(id)?.snapshot;
613
+ return {
614
+ id,
615
+ title: snapshot?.title ?? "?",
616
+ status: snapshot?.status ?? "error",
617
+ cancelled: runningIds.includes(id),
618
+ };
619
+ }),
620
+ ),
621
+ );
622
+ });
623
+
624
+ const send = (id: string, text: string) =>
625
+ Effect.suspend((): Effect.Effect<void, SendError> => {
626
+ const entry = entries.get(id);
627
+ if (!entry || disposed) {
628
+ return new SendError({
629
+ message: `Subagent "${id}" is no longer tracked.`,
630
+ });
631
+ }
632
+ // Restarting a settled subagent occupies a running slot again, so it
633
+ // must respect the same cap as spawn. Steering an already-running one
634
+ // does not consume additional capacity.
635
+ if (entry.snapshot.status !== "running") {
636
+ if (runningCount() + reserved >= MAX_RUNNING) {
637
+ return new SendError({
638
+ message: `Max ${MAX_RUNNING} subagents can run concurrently; restarting "${id}" would exceed that.`,
639
+ });
640
+ }
641
+ // Occupy the slot synchronously: the RunStarted that flips status
642
+ // arrives via the async pump, and two concurrent restarts must not
643
+ // both pass the check in that window. Cleared by RunStarted/settle,
644
+ // or here when the backend rejects the send.
645
+ entry.restarting = true;
646
+ return entry.session.send(text).pipe(
647
+ Effect.onError(() =>
648
+ Effect.sync(() => {
649
+ entry.restarting = false;
650
+ }),
651
+ ),
652
+ );
653
+ }
654
+ return entry.session.send(text);
655
+ });
656
+
657
+ const disposeAll = Effect.gen(function* () {
658
+ disposed = true;
659
+ const all = [...entries.values()];
660
+ entries.clear();
661
+ yield* Effect.forEach(
662
+ all,
663
+ (entry) =>
664
+ closeEntryScope(entry).pipe(
665
+ Effect.timeout(STOP_TIMEOUT_MS),
666
+ Effect.ignore,
667
+ ),
668
+ { concurrency: "unbounded" },
669
+ );
670
+ // Pruning cleanups are detached; bound them like everything else so a
671
+ // stuck backend finalizer cannot block runtime shutdown indefinitely.
672
+ yield* Effect.forEach(
673
+ [...cleanups],
674
+ (fiber) =>
675
+ Fiber.await(fiber).pipe(Effect.timeout(STOP_TIMEOUT_MS), Effect.ignore),
676
+ { concurrency: "unbounded" },
677
+ ).pipe(Effect.ignore);
678
+ yield* Effect.sync(() => notify());
679
+ });
680
+
681
+ const view: SubagentReadModel = {
682
+ list: () => [...entries.values()].map((entry) => entry.snapshot),
683
+ get: (id) => entries.get(id)?.snapshot,
684
+ size: () => entries.size,
685
+ subscribe: (listener) => {
686
+ listeners.add(listener);
687
+ return () => listeners.delete(listener);
688
+ },
689
+ subscribeTo: (id, listener) => {
690
+ let set = idListeners.get(id);
691
+ if (!set) {
692
+ set = new Set();
693
+ idListeners.set(id, set);
694
+ }
695
+ set.add(listener);
696
+ return () => {
697
+ set.delete(listener);
698
+ if (set.size === 0) idListeners.delete(id);
699
+ };
700
+ },
701
+ requestSend: (id, text) => {
702
+ runDetached(send(id, text).pipe(Effect.ignore));
703
+ },
704
+ requestAbort: (id) => {
705
+ const entry = entries.get(id);
706
+ if (!entry) return;
707
+ // UI-initiated aborts are not "consumed": the failed result still
708
+ // flows back to the parent as a follow-up message, matching v1.
709
+ runDetached(abortEntry(entry).pipe(Effect.ignore));
710
+ },
711
+ setOnSettled: (hook) => {
712
+ onSettled = hook;
713
+ },
714
+ };
715
+
716
+ // Safety net: disposing the ManagedRuntime tears everything down even if
717
+ // the extension forgot to call disposeAll explicitly.
718
+ yield* Effect.addFinalizer(() => disposeAll);
719
+
720
+ return SubagentManager.of({
721
+ spawn,
722
+ waitFor,
723
+ cancel,
724
+ send,
725
+ get: (id) => Effect.sync(() => entries.get(id)?.snapshot),
726
+ list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
727
+ disposeAll,
728
+ view,
729
+ });
730
+ });
731
+
732
+ export const SubagentManagerLive: Layer.Layer<
733
+ SubagentManager,
734
+ never,
735
+ BackendRegistry
736
+ > = Layer.effect(SubagentManager, makeManager);