@tt-a1i/openpi 0.1.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.
- package/README.md +643 -0
- package/SETUP.md +74 -0
- package/THIRD_PARTY_NOTICES.md +16 -0
- package/assets/openpi-package.png +0 -0
- package/assets/readme-hero-mobile.svg +72 -0
- package/assets/readme-hero.svg +118 -0
- package/assets/readme-runtime-mobile.svg +91 -0
- package/assets/readme-runtime.svg +111 -0
- package/extensions/ask-user/handoff.ts +205 -0
- package/extensions/ask-user/index.ts +1110 -0
- package/extensions/ask-user/limits.ts +89 -0
- package/extensions/ask-user/prompt.ts +76 -0
- package/extensions/background-terminals/index.ts +653 -0
- package/extensions/background-terminals/src/domain.ts +99 -0
- package/extensions/background-terminals/src/manager.ts +989 -0
- package/extensions/background-terminals/src/output.ts +84 -0
- package/extensions/background-terminals/src/prompt.ts +195 -0
- package/extensions/background-terminals/src/result-delivery.ts +43 -0
- package/extensions/background-terminals/src/runtime.ts +36 -0
- package/extensions/background-terminals/src/ui/output-view.ts +55 -0
- package/extensions/background-terminals/src/ui/ps.ts +642 -0
- package/extensions/background-terminals/src/ui/tool-result.ts +146 -0
- package/extensions/background-terminals/src/watch.ts +192 -0
- package/extensions/context-pivot/index.ts +222 -0
- package/extensions/copy-all/index.ts +65 -0
- package/extensions/cron/index.ts +173 -0
- package/extensions/cron/schedule.ts +127 -0
- package/extensions/file-mutation-display/index.ts +105 -0
- package/extensions/file-mutation-display/render.ts +107 -0
- package/extensions/file-search/index.ts +515 -0
- package/extensions/file-search/src/args.ts +129 -0
- package/extensions/file-search/src/binaries.ts +419 -0
- package/extensions/file-search/src/output.ts +142 -0
- package/extensions/file-search/src/process.ts +309 -0
- package/extensions/file-search/src/prompt.ts +53 -0
- package/extensions/git-info/index.ts +272 -0
- package/extensions/git-info/src/changed-files-view.ts +414 -0
- package/extensions/git-info/src/process.ts +107 -0
- package/extensions/git-info/src/refresh-coordinator.ts +13 -0
- package/extensions/git-info/src/runtime.ts +28 -0
- package/extensions/goal/controller.ts +794 -0
- package/extensions/goal/index.ts +521 -0
- package/extensions/goal/prompts.ts +122 -0
- package/extensions/goal/state.ts +763 -0
- package/extensions/goal/ui.ts +158 -0
- package/extensions/model-info/index.ts +234 -0
- package/extensions/plan-mode/bash-policy.ts +313 -0
- package/extensions/plan-mode/index.ts +539 -0
- package/extensions/post-edit/index.ts +129 -0
- package/extensions/sessions/LICENSE.upstream +21 -0
- package/extensions/sessions/git-stats.ts +226 -0
- package/extensions/sessions/index.ts +1092 -0
- package/extensions/sessions/sessions.ts +385 -0
- package/extensions/setup/index.ts +408 -0
- package/extensions/shared/activity-status.ts +65 -0
- package/extensions/shared/below-editor-navigation.ts +343 -0
- package/extensions/shared/child-session.ts +352 -0
- package/extensions/shared/context-utilization.ts +47 -0
- package/extensions/shared/dashboard-state.ts +102 -0
- package/extensions/shared/plan-mode-state.ts +65 -0
- package/extensions/shared/setup-config.ts +971 -0
- package/extensions/shared/subagent-roles.ts +22 -0
- package/extensions/shared/terminal-text.ts +38 -0
- package/extensions/shared/tool-call-timeout.ts +104 -0
- package/extensions/shared/worktree.ts +526 -0
- package/extensions/subagents/index.ts +1225 -0
- package/extensions/subagents/navigation.ts +121 -0
- package/extensions/subagents/src/agent-types.ts +543 -0
- package/extensions/subagents/src/backend.ts +63 -0
- package/extensions/subagents/src/backends/pi.ts +493 -0
- package/extensions/subagents/src/backends/stub.ts +296 -0
- package/extensions/subagents/src/by-the-way.ts +21 -0
- package/extensions/subagents/src/domain.ts +271 -0
- package/extensions/subagents/src/format.ts +48 -0
- package/extensions/subagents/src/manager.ts +769 -0
- package/extensions/subagents/src/prompt.ts +190 -0
- package/extensions/subagents/src/result-delivery.ts +20 -0
- package/extensions/subagents/src/runtime.ts +51 -0
- package/extensions/subagents/src/ui/takeover.ts +615 -0
- package/extensions/subagents/src/ui/transcript.ts +293 -0
- package/extensions/subagents/src/ui/wait-result.ts +89 -0
- package/extensions/suggestions/index.ts +172 -0
- package/extensions/suggestions/src/config.ts +12 -0
- package/extensions/suggestions/src/predictor.ts +147 -0
- package/extensions/suggestions/src/prompt.ts +20 -0
- package/extensions/suggestions/src/transcript.ts +233 -0
- package/extensions/suggestions/src/ui.ts +224 -0
- package/extensions/tasks/index.ts +512 -0
- package/extensions/tasks/tasks.ts +649 -0
- package/extensions/tasks/ui.ts +421 -0
- package/extensions/turn-time/index.ts +61 -0
- package/extensions/ui-customization/footer.ts +512 -0
- package/extensions/ui-customization/index.ts +217 -0
- package/extensions/workflows/acceptance.ts +298 -0
- package/extensions/workflows/artifacts.ts +225 -0
- package/extensions/workflows/controller.ts +210 -0
- package/extensions/workflows/dashboard.ts +1226 -0
- package/extensions/workflows/index.ts +1884 -0
- package/extensions/workflows/journal.ts +188 -0
- package/extensions/workflows/meta.ts +250 -0
- package/extensions/workflows/model.ts +423 -0
- package/extensions/workflows/navigation.ts +93 -0
- package/extensions/workflows/prompt.ts +212 -0
- package/extensions/workflows/replay-safety.ts +577 -0
- package/extensions/workflows/runner.ts +786 -0
- package/extensions/workflows/sandbox-child.cjs +402 -0
- package/extensions/workflows/sandbox.ts +397 -0
- package/extensions/workflows/serialization.ts +162 -0
- package/extensions/workflows/worktree-handoff.ts +216 -0
- package/package.json +87 -0
- package/scripts/prepare-effect-tsgo.mjs +16 -0
- package/skills/background-terminals/SKILL.md +30 -0
- package/skills/subagents/SKILL.md +15 -0
- package/themes/github-dark-default.json +89 -0
|
@@ -0,0 +1,989 @@
|
|
|
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
|
+
/** Deadline won the race and initiated termination. */
|
|
90
|
+
timedOut: boolean;
|
|
91
|
+
timeoutTimer?: ReturnType<typeof setTimeout>;
|
|
92
|
+
/** The child emitted 'error' (spawn failure etc.); settles as "failed".
|
|
93
|
+
* Kept separate from errorText, which also carries non-fatal notes
|
|
94
|
+
* (spill failures) that must not flip a clean exit to "failed". */
|
|
95
|
+
processErrored: boolean;
|
|
96
|
+
/** 'exit' event observed (code/signal recorded). */
|
|
97
|
+
exited: boolean;
|
|
98
|
+
/** 'close' event observed (stdio flushed; the settle trigger). */
|
|
99
|
+
stdioClosed: boolean;
|
|
100
|
+
/** A settle-after-spill-flush is in flight; don't start a second one. */
|
|
101
|
+
settling: boolean;
|
|
102
|
+
/** The shell exited without stdio closing; a bounded scope close is queued
|
|
103
|
+
* to reap descendants that still hold the inherited pipes open. */
|
|
104
|
+
exitCleanupStarted: boolean;
|
|
105
|
+
/** Completed exactly once when the entry settles. Kill callers and the scope
|
|
106
|
+
* finalizer can all await the same result without missing a notification. */
|
|
107
|
+
settled: Deferred.Deferred<void>;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface StartOptions {
|
|
111
|
+
readonly command: string;
|
|
112
|
+
readonly title: string;
|
|
113
|
+
readonly cwd: string;
|
|
114
|
+
/** Optional runtime limit in seconds. Omit for an indefinite server/watcher. */
|
|
115
|
+
readonly timeoutSeconds?: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface KillResult {
|
|
119
|
+
readonly id: string;
|
|
120
|
+
readonly title: string;
|
|
121
|
+
readonly status: TerminalStatus;
|
|
122
|
+
/** True when the entry was still running when this kill began. */
|
|
123
|
+
readonly wasRunning: boolean;
|
|
124
|
+
/** True when this call initiated the termination AND the entry settled as
|
|
125
|
+
* killed (a natural exit that won the race reports killed: false). */
|
|
126
|
+
readonly killed: boolean;
|
|
127
|
+
/** Final exit rendering ("exit 0", "SIGTERM", ...) captured at settle time,
|
|
128
|
+
* so reports stay accurate even if the entry is pruned afterwards. */
|
|
129
|
+
readonly exit: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// --- Read model ----------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
/** Synchronous bridge for the TUI. Snapshots are live objects; do not mutate. */
|
|
135
|
+
export interface TerminalReadModel {
|
|
136
|
+
list(): ReadonlyArray<TerminalSnapshot>;
|
|
137
|
+
get(id: string): TerminalSnapshot | undefined;
|
|
138
|
+
size(): number;
|
|
139
|
+
/** Any-change notification (widget, /ps list). */
|
|
140
|
+
subscribe(listener: () => void): () => void;
|
|
141
|
+
/** Per-terminal notification (/ps detail view). */
|
|
142
|
+
subscribeTo(id: string, listener: () => void): () => void;
|
|
143
|
+
/**
|
|
144
|
+
* Per-terminal raw output chunks, for bg_watch's mid-run matching. Separate
|
|
145
|
+
* from subscribeTo: that fires on any change and carries no payload, while a
|
|
146
|
+
* watcher needs the actual bytes as they stream.
|
|
147
|
+
*/
|
|
148
|
+
subscribeToChunks(
|
|
149
|
+
id: string,
|
|
150
|
+
listener: (chunk: string, stream: "stdout" | "stderr") => void,
|
|
151
|
+
): () => void;
|
|
152
|
+
/** Fire-and-forget kill (dashboard/detail `x`). Not marked consumed: the
|
|
153
|
+
* settle still flows back to the model as a follow-up message. */
|
|
154
|
+
requestKill(id: string): void;
|
|
155
|
+
/**
|
|
156
|
+
* Register the settle hook. `consumed` is true when an active bg_kill is
|
|
157
|
+
* collecting the result (so it must not also be delivered as a follow-up).
|
|
158
|
+
*/
|
|
159
|
+
setOnSettled(
|
|
160
|
+
hook: ((snap: TerminalSnapshot, consumed: boolean) => void) | undefined,
|
|
161
|
+
): void;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// --- Service --------------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
export interface TerminalManagerShape {
|
|
167
|
+
start(
|
|
168
|
+
options: StartOptions,
|
|
169
|
+
): Effect.Effect<TerminalSnapshot, SpawnError | ConcurrencyLimitError>;
|
|
170
|
+
status(id: string): Effect.Effect<TerminalSnapshot, UnknownTerminalError>;
|
|
171
|
+
/** Kill running terminals; resolves only after they have settled. */
|
|
172
|
+
kill(ids: ReadonlyArray<string>): Effect.Effect<ReadonlyArray<KillResult>>;
|
|
173
|
+
readonly list: Effect.Effect<ReadonlyArray<TerminalSnapshot>>;
|
|
174
|
+
readonly disposeAll: Effect.Effect<void>;
|
|
175
|
+
readonly view: TerminalReadModel;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export class TerminalManager extends Context.Service<
|
|
179
|
+
TerminalManager,
|
|
180
|
+
TerminalManagerShape
|
|
181
|
+
>()("background-terminals/TerminalManager") {}
|
|
182
|
+
|
|
183
|
+
// --- Process helpers ------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
function shellInvocation(command: string) {
|
|
186
|
+
if (process.platform === "win32") {
|
|
187
|
+
const shell = process.env.ComSpec ?? "cmd.exe";
|
|
188
|
+
return { shell, args: ["/d", "/s", "/c", command] };
|
|
189
|
+
}
|
|
190
|
+
return { shell: "/bin/sh", args: ["-c", command] };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Signal the whole process group on POSIX so descendants (servers a shell
|
|
194
|
+
* command spawned) die with it; a wedged child must not orphan its tree. */
|
|
195
|
+
function killTree(child: ChildProcess, signal: NodeJS.Signals) {
|
|
196
|
+
if (process.platform === "win32" && child.pid) {
|
|
197
|
+
try {
|
|
198
|
+
const killer = spawn(
|
|
199
|
+
"taskkill",
|
|
200
|
+
[
|
|
201
|
+
"/pid",
|
|
202
|
+
String(child.pid),
|
|
203
|
+
"/T",
|
|
204
|
+
...(signal === "SIGKILL" ? ["/F"] : []),
|
|
205
|
+
],
|
|
206
|
+
{ stdio: "ignore", windowsHide: true },
|
|
207
|
+
);
|
|
208
|
+
killer.once("error", () => {
|
|
209
|
+
try {
|
|
210
|
+
child.kill(signal);
|
|
211
|
+
} catch {
|
|
212
|
+
// Process may already be gone.
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
killer.once("exit", (code) => {
|
|
216
|
+
if (code === 0) return;
|
|
217
|
+
try {
|
|
218
|
+
child.kill(signal);
|
|
219
|
+
} catch {
|
|
220
|
+
// Process may already be gone.
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
killer.unref();
|
|
224
|
+
return;
|
|
225
|
+
} catch {
|
|
226
|
+
// Fall through to the direct signal when taskkill cannot be launched.
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (process.platform !== "win32" && child.pid) {
|
|
230
|
+
try {
|
|
231
|
+
process.kill(-child.pid, signal);
|
|
232
|
+
return;
|
|
233
|
+
} catch {
|
|
234
|
+
// Group may already be gone; fall through to the direct signal.
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
child.kill(signal);
|
|
239
|
+
} catch {
|
|
240
|
+
// Process may already be gone.
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Await stdio closure without retaining a listener after interruption. */
|
|
245
|
+
function awaitChildClose(child: ChildProcess, closed: () => boolean) {
|
|
246
|
+
return Effect.callback<void>((resume) => {
|
|
247
|
+
if (closed()) {
|
|
248
|
+
resume(Effect.void);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const onClose = () => resume(Effect.void);
|
|
252
|
+
child.once("close", onClose);
|
|
253
|
+
return Effect.sync(() => child.off("close", onClose));
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** SIGTERM → deadline → SIGKILL; waits for stdio closure rather than only the
|
|
258
|
+
* shell's exit because descendants can keep the inherited pipes and process
|
|
259
|
+
* group alive after the shell itself is gone. */
|
|
260
|
+
function terminateChild(
|
|
261
|
+
child: ChildProcess,
|
|
262
|
+
closed: () => boolean,
|
|
263
|
+
onSignal: () => void,
|
|
264
|
+
) {
|
|
265
|
+
return Effect.suspend(() => {
|
|
266
|
+
if (closed()) return Effect.void;
|
|
267
|
+
return Effect.gen(function* () {
|
|
268
|
+
yield* Effect.sync(() => {
|
|
269
|
+
onSignal();
|
|
270
|
+
killTree(child, "SIGTERM");
|
|
271
|
+
});
|
|
272
|
+
yield* awaitChildClose(child, closed).pipe(
|
|
273
|
+
Effect.timeout(FORCE_KILL_AFTER_MS),
|
|
274
|
+
Effect.ignore,
|
|
275
|
+
);
|
|
276
|
+
if (closed()) return;
|
|
277
|
+
yield* Effect.sync(() => killTree(child, "SIGKILL"));
|
|
278
|
+
yield* awaitChildClose(child, closed).pipe(
|
|
279
|
+
Effect.timeout(500),
|
|
280
|
+
Effect.ignore,
|
|
281
|
+
);
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// --- Implementation --------------------------------------------------------------
|
|
287
|
+
|
|
288
|
+
const makeManager = Effect.gen(function* () {
|
|
289
|
+
// Scoped detached forker for sync contexts (read-model kills, process-event
|
|
290
|
+
// settlement, pruning). Completed fibers remove themselves; manager scope
|
|
291
|
+
// close interrupts any work that outlives the bounded disposeAll wait.
|
|
292
|
+
const cleanupFibers = yield* FiberSet.make();
|
|
293
|
+
const runCleanup = yield* FiberSet.runtime(cleanupFibers)();
|
|
294
|
+
|
|
295
|
+
const entries = new Map<string, Entry>();
|
|
296
|
+
/** Small immutable tombstones preserve truthful kill reports if pruning
|
|
297
|
+
* races the tool boundary after an id was validated. */
|
|
298
|
+
const settledHistory = new Map<
|
|
299
|
+
string,
|
|
300
|
+
Pick<KillResult, "title" | "status" | "exit">
|
|
301
|
+
>();
|
|
302
|
+
/** ids with an in-flight kill() collecting the result (settle → consumed). */
|
|
303
|
+
const killInterest = new Map<string, number>();
|
|
304
|
+
const listeners = new Set<() => void>();
|
|
305
|
+
const idListeners = new Map<string, Set<() => void>>();
|
|
306
|
+
/** bg_watch chunk listeners, keyed by terminal id. */
|
|
307
|
+
const chunkListeners = new Map<
|
|
308
|
+
string,
|
|
309
|
+
Set<(chunk: string, stream: "stdout" | "stderr") => void>
|
|
310
|
+
>();
|
|
311
|
+
let counter = 0;
|
|
312
|
+
let reserved = 0;
|
|
313
|
+
let disposed = false;
|
|
314
|
+
let spillDir: string | undefined | null;
|
|
315
|
+
let onSettled:
|
|
316
|
+
((snap: TerminalSnapshot, consumed: boolean) => void) | undefined;
|
|
317
|
+
|
|
318
|
+
const notify = (id?: string) => {
|
|
319
|
+
for (const listener of [...listeners]) {
|
|
320
|
+
try {
|
|
321
|
+
listener();
|
|
322
|
+
} catch {
|
|
323
|
+
// A failed widget/render listener must not corrupt lifecycle state.
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
if (id) {
|
|
327
|
+
for (const listener of idListeners.get(id) ?? []) {
|
|
328
|
+
try {
|
|
329
|
+
listener();
|
|
330
|
+
} catch {
|
|
331
|
+
// Same.
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Fan out a raw output chunk to bg_watch listeners. Purely additive next to
|
|
339
|
+
* notify(): a throwing watcher must never corrupt stream/lifecycle state.
|
|
340
|
+
*/
|
|
341
|
+
const emitChunk = (
|
|
342
|
+
id: string,
|
|
343
|
+
chunk: string,
|
|
344
|
+
stream: "stdout" | "stderr",
|
|
345
|
+
) => {
|
|
346
|
+
const set = chunkListeners.get(id);
|
|
347
|
+
if (!set) return;
|
|
348
|
+
for (const listener of [...set]) {
|
|
349
|
+
try {
|
|
350
|
+
listener(chunk, stream);
|
|
351
|
+
} catch {
|
|
352
|
+
// A failed watcher must not break output capture.
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
|
|
357
|
+
const runningCount = () =>
|
|
358
|
+
[...entries.values()].filter((e) => e.snapshot.status === "running").length;
|
|
359
|
+
|
|
360
|
+
const addKillInterest = (ids: ReadonlyArray<string>) => {
|
|
361
|
+
for (const id of ids) killInterest.set(id, (killInterest.get(id) ?? 0) + 1);
|
|
362
|
+
};
|
|
363
|
+
const releaseKillInterest = (ids: ReadonlyArray<string>) => {
|
|
364
|
+
for (const id of ids) {
|
|
365
|
+
const count = (killInterest.get(id) ?? 1) - 1;
|
|
366
|
+
if (count <= 0) killInterest.delete(id);
|
|
367
|
+
else killInterest.set(id, count);
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
const closeEntryScope = (entry: Entry) =>
|
|
372
|
+
Scope.close(entry.scope, Exit.void).pipe(Effect.ignore);
|
|
373
|
+
|
|
374
|
+
const pruneSettled = () => {
|
|
375
|
+
if (entries.size <= MAX_TRACKED) return;
|
|
376
|
+
const candidates = [...entries.values()]
|
|
377
|
+
.filter(
|
|
378
|
+
(e) =>
|
|
379
|
+
e.snapshot.status !== "running" && !killInterest.has(e.snapshot.id),
|
|
380
|
+
)
|
|
381
|
+
.sort(
|
|
382
|
+
(a, b) =>
|
|
383
|
+
(a.snapshot.settledAt ?? a.snapshot.createdAt) -
|
|
384
|
+
(b.snapshot.settledAt ?? b.snapshot.createdAt),
|
|
385
|
+
);
|
|
386
|
+
for (const entry of candidates) {
|
|
387
|
+
if (entries.size <= MAX_TRACKED) break;
|
|
388
|
+
entries.delete(entry.snapshot.id);
|
|
389
|
+
runCleanup(closeEntryScope(entry));
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/** End all spill streams; resolves when their buffers are flushed to disk
|
|
394
|
+
* (bounded), so a settle notification never points at a partial file. */
|
|
395
|
+
const flushSpillStreams = (entry: Entry) => {
|
|
396
|
+
const streams = entry.spillStreams;
|
|
397
|
+
entry.spillStreams = [];
|
|
398
|
+
return Effect.forEach(
|
|
399
|
+
streams,
|
|
400
|
+
(stream) =>
|
|
401
|
+
Effect.callback<void>((resume) => {
|
|
402
|
+
const done = () => resume(Effect.void);
|
|
403
|
+
try {
|
|
404
|
+
stream.end(done);
|
|
405
|
+
} catch {
|
|
406
|
+
// Best effort; tmpdir contents are disposable.
|
|
407
|
+
done();
|
|
408
|
+
}
|
|
409
|
+
}),
|
|
410
|
+
{ concurrency: "unbounded", discard: true },
|
|
411
|
+
).pipe(
|
|
412
|
+
Effect.timeoutOrElse({
|
|
413
|
+
duration: SPILL_FLUSH_TIMEOUT_MS,
|
|
414
|
+
orElse: () =>
|
|
415
|
+
Effect.sync(() => {
|
|
416
|
+
entry.stdoutBuf.spillPath = undefined;
|
|
417
|
+
entry.stderrBuf.spillPath = undefined;
|
|
418
|
+
entry.snapshot.errorText ??=
|
|
419
|
+
"Full-log spill flush timed out; full output may be incomplete";
|
|
420
|
+
}),
|
|
421
|
+
}),
|
|
422
|
+
);
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
/** Single settle path — idempotent; kill vs natural exit vs error races are
|
|
426
|
+
* resolved by whichever lands first (the second call is a no-op). */
|
|
427
|
+
const settle = (entry: Entry) => {
|
|
428
|
+
const s = entry.snapshot;
|
|
429
|
+
if (s.status !== "running") return;
|
|
430
|
+
s.settledAt = Date.now();
|
|
431
|
+
s.status = entry.timedOut
|
|
432
|
+
? "timed_out"
|
|
433
|
+
: entry.killSignaled
|
|
434
|
+
? "killed"
|
|
435
|
+
: entry.processErrored
|
|
436
|
+
? "failed"
|
|
437
|
+
: s.exitCode === 0
|
|
438
|
+
? "done"
|
|
439
|
+
: "failed";
|
|
440
|
+
if (entry.timeoutTimer) clearTimeout(entry.timeoutTimer);
|
|
441
|
+
entry.timeoutTimer = undefined;
|
|
442
|
+
settledHistory.set(s.id, {
|
|
443
|
+
title: s.title,
|
|
444
|
+
status: s.status,
|
|
445
|
+
exit: formatExit(s),
|
|
446
|
+
});
|
|
447
|
+
while (settledHistory.size > MAX_SETTLED_HISTORY) {
|
|
448
|
+
const oldest = settledHistory.keys().next().value;
|
|
449
|
+
if (oldest === undefined) break;
|
|
450
|
+
settledHistory.delete(oldest);
|
|
451
|
+
}
|
|
452
|
+
// Completing the Deferred can immediately resume kill waiters, whose
|
|
453
|
+
// ensuring blocks release interest. Snapshot consumption first so the
|
|
454
|
+
// settle hook observes the interest that existed when settlement won.
|
|
455
|
+
const consumed = (killInterest.get(s.id) ?? 0) > 0;
|
|
456
|
+
Deferred.doneUnsafe(entry.settled, Effect.void);
|
|
457
|
+
notify(s.id);
|
|
458
|
+
try {
|
|
459
|
+
// During teardown, don't queue results into a shutting-down session.
|
|
460
|
+
if (!disposed) onSettled?.(s, consumed);
|
|
461
|
+
} catch {
|
|
462
|
+
// The parent session may be unavailable; settlement stays final.
|
|
463
|
+
}
|
|
464
|
+
pruneSettled();
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
/** Flush the spill files, then settle: the completion follow-up (and the
|
|
468
|
+
* kill() resolution) reference the spill path, so the full capture must be
|
|
469
|
+
* on disk before anyone is told about it. Idempotent via `settling`. */
|
|
470
|
+
const settleAfterFlush = (entry: Entry) => {
|
|
471
|
+
if (entry.settling || entry.snapshot.status !== "running") return;
|
|
472
|
+
entry.settling = true;
|
|
473
|
+
runCleanup(
|
|
474
|
+
flushSpillStreams(entry).pipe(
|
|
475
|
+
Effect.andThen(Effect.sync(() => settle(entry))),
|
|
476
|
+
),
|
|
477
|
+
);
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
const scheduleExitCleanup = (entry: Entry) => {
|
|
481
|
+
if (entry.exitCleanupStarted) return;
|
|
482
|
+
entry.exitCleanupStarted = true;
|
|
483
|
+
runCleanup(
|
|
484
|
+
Effect.sleep(SETTLE_GRACE_MS).pipe(
|
|
485
|
+
Effect.andThen(
|
|
486
|
+
Effect.suspend(() =>
|
|
487
|
+
entry.snapshot.status === "running" && !entry.stdioClosed
|
|
488
|
+
? closeEntryScope(entry).pipe(
|
|
489
|
+
Effect.timeout(STOP_TIMEOUT_MS),
|
|
490
|
+
Effect.ignore,
|
|
491
|
+
)
|
|
492
|
+
: Effect.void,
|
|
493
|
+
),
|
|
494
|
+
),
|
|
495
|
+
),
|
|
496
|
+
);
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
const resolveSpillDir = () => {
|
|
500
|
+
if (spillDir !== undefined) return spillDir ?? undefined;
|
|
501
|
+
try {
|
|
502
|
+
const base = path.join(os.tmpdir(), "pi-background-terminals");
|
|
503
|
+
fs.mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
504
|
+
fs.chmodSync(base, 0o700);
|
|
505
|
+
spillDir = fs.mkdtempSync(path.join(base, "session-"));
|
|
506
|
+
fs.chmodSync(spillDir, 0o700);
|
|
507
|
+
} catch {
|
|
508
|
+
spillDir = null;
|
|
509
|
+
}
|
|
510
|
+
return spillDir ?? undefined;
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
const makeSpill = (
|
|
514
|
+
entry: () => Entry | undefined,
|
|
515
|
+
id: string,
|
|
516
|
+
stream: "stdout" | "stderr",
|
|
517
|
+
resumeSource: () => void,
|
|
518
|
+
) => {
|
|
519
|
+
const dir = resolveSpillDir();
|
|
520
|
+
if (!dir) return undefined;
|
|
521
|
+
const spillPath = path.join(dir, `${id}.${stream}.log`);
|
|
522
|
+
try {
|
|
523
|
+
const file = fs.createWriteStream(spillPath, {
|
|
524
|
+
flags: "a",
|
|
525
|
+
mode: 0o600,
|
|
526
|
+
});
|
|
527
|
+
let broken = false;
|
|
528
|
+
let capped = false;
|
|
529
|
+
let writtenBytes = 0;
|
|
530
|
+
file.on("error", (error) => {
|
|
531
|
+
broken = true;
|
|
532
|
+
resumeSource();
|
|
533
|
+
const current = entry();
|
|
534
|
+
if (current) {
|
|
535
|
+
const buf =
|
|
536
|
+
stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
|
|
537
|
+
buf.spillPath = undefined;
|
|
538
|
+
current.snapshot.errorText ??= bounded(
|
|
539
|
+
`Full-log spill to ${spillPath} failed: ${boundedError(error)}`,
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
});
|
|
543
|
+
return {
|
|
544
|
+
spillPath,
|
|
545
|
+
file,
|
|
546
|
+
write: (chunk: string) => {
|
|
547
|
+
// writableEnded guard: late 'data' after the settle flush must not
|
|
548
|
+
// error the ended stream (and falsely report the spill as broken).
|
|
549
|
+
if (broken || capped || file.writableEnded) return true;
|
|
550
|
+
const chunkBytes = Buffer.byteLength(chunk, "utf8");
|
|
551
|
+
if (writtenBytes + chunkBytes > MAX_SPILL_BYTES_PER_STREAM) {
|
|
552
|
+
capped = true;
|
|
553
|
+
const current = entry();
|
|
554
|
+
if (current) {
|
|
555
|
+
const buf =
|
|
556
|
+
stream === "stdout" ? current.stdoutBuf : current.stderrBuf;
|
|
557
|
+
buf.spillPath = undefined;
|
|
558
|
+
current.snapshot.errorText ??= bounded(
|
|
559
|
+
`${stream} full-log spill reached the ${MAX_SPILL_BYTES_PER_STREAM}-byte safety limit`,
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
return true;
|
|
563
|
+
}
|
|
564
|
+
writtenBytes += chunkBytes;
|
|
565
|
+
const accepted = file.write(chunk);
|
|
566
|
+
if (!accepted) file.once("drain", resumeSource);
|
|
567
|
+
return accepted;
|
|
568
|
+
},
|
|
569
|
+
};
|
|
570
|
+
} catch {
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
const start = (options: StartOptions) =>
|
|
576
|
+
Effect.gen(function* () {
|
|
577
|
+
// Reserve synchronously (before the first yield inside doStart) so
|
|
578
|
+
// parallel tool calls cannot race past the cap.
|
|
579
|
+
yield* Effect.suspend(
|
|
580
|
+
(): Effect.Effect<void, SpawnError | ConcurrencyLimitError> => {
|
|
581
|
+
if (disposed) {
|
|
582
|
+
return new SpawnError({
|
|
583
|
+
message: "Background terminal manager is shutting down.",
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
if (runningCount() + reserved >= MAX_RUNNING) {
|
|
587
|
+
return new ConcurrencyLimitError({
|
|
588
|
+
message: `Max ${MAX_RUNNING} background terminals can run concurrently. Stop one with bg_kill before starting another.`,
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
reserved++;
|
|
592
|
+
return Effect.void;
|
|
593
|
+
},
|
|
594
|
+
);
|
|
595
|
+
|
|
596
|
+
const doStart = Effect.gen(function* () {
|
|
597
|
+
const { shell, args } = shellInvocation(options.command);
|
|
598
|
+
const child = yield* Effect.try({
|
|
599
|
+
try: () =>
|
|
600
|
+
spawn(shell, args, {
|
|
601
|
+
cwd: options.cwd,
|
|
602
|
+
env: process.env,
|
|
603
|
+
// stdin IGNORED: there is no input surface, ever. A process
|
|
604
|
+
// that reads stdin sees EOF immediately.
|
|
605
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
606
|
+
// Own process group on POSIX → group kill takes the whole tree.
|
|
607
|
+
detached: process.platform !== "win32",
|
|
608
|
+
}),
|
|
609
|
+
catch: (error) => new SpawnError({ message: boundedError(error) }),
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
const id = `bt-${++counter}`;
|
|
613
|
+
const entryRef = () => entries.get(id);
|
|
614
|
+
const stdoutSpill = makeSpill(entryRef, id, "stdout", () =>
|
|
615
|
+
child.stdout?.resume(),
|
|
616
|
+
);
|
|
617
|
+
const stderrSpill = makeSpill(entryRef, id, "stderr", () =>
|
|
618
|
+
child.stderr?.resume(),
|
|
619
|
+
);
|
|
620
|
+
const stdoutBuf = new OutputBuffer(
|
|
621
|
+
RETAINED_PER_STREAM,
|
|
622
|
+
stdoutSpill?.write,
|
|
623
|
+
);
|
|
624
|
+
const stderrBuf = new OutputBuffer(
|
|
625
|
+
RETAINED_PER_STREAM,
|
|
626
|
+
stderrSpill?.write,
|
|
627
|
+
);
|
|
628
|
+
stdoutBuf.spillPath = stdoutSpill?.spillPath;
|
|
629
|
+
stderrBuf.spillPath = stderrSpill?.spillPath;
|
|
630
|
+
|
|
631
|
+
const snapshot: MutableSnapshot = {
|
|
632
|
+
id,
|
|
633
|
+
command: options.command,
|
|
634
|
+
title: options.title,
|
|
635
|
+
cwd: options.cwd,
|
|
636
|
+
pid: child.pid,
|
|
637
|
+
status: "running",
|
|
638
|
+
createdAt: Date.now(),
|
|
639
|
+
timeoutAt:
|
|
640
|
+
options.timeoutSeconds === undefined
|
|
641
|
+
? undefined
|
|
642
|
+
: Date.now() + options.timeoutSeconds * 1_000,
|
|
643
|
+
get stdout() {
|
|
644
|
+
return stdoutBuf.view();
|
|
645
|
+
},
|
|
646
|
+
get stderr() {
|
|
647
|
+
return stderrBuf.view();
|
|
648
|
+
},
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
const scope = yield* Scope.make();
|
|
652
|
+
const settled = yield* Deferred.make<void>();
|
|
653
|
+
const entry: Entry = {
|
|
654
|
+
snapshot,
|
|
655
|
+
child,
|
|
656
|
+
scope,
|
|
657
|
+
stdoutBuf,
|
|
658
|
+
stderrBuf,
|
|
659
|
+
spillStreams: [stdoutSpill?.file, stderrSpill?.file].filter(
|
|
660
|
+
(file): file is fs.WriteStream => file !== undefined,
|
|
661
|
+
),
|
|
662
|
+
killSignaled: false,
|
|
663
|
+
timedOut: false,
|
|
664
|
+
processErrored: false,
|
|
665
|
+
exited: false,
|
|
666
|
+
stdioClosed: false,
|
|
667
|
+
settling: false,
|
|
668
|
+
exitCleanupStarted: false,
|
|
669
|
+
settled,
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
if (options.timeoutSeconds !== undefined) {
|
|
673
|
+
entry.timeoutTimer = setTimeout(() => {
|
|
674
|
+
if (entry.snapshot.status !== "running") return;
|
|
675
|
+
// If the shell exited naturally just before the deadline, preserve
|
|
676
|
+
// that result; bounded exit cleanup will reap descendants holding
|
|
677
|
+
// inherited stdio open.
|
|
678
|
+
if (entry.exited) return;
|
|
679
|
+
entry.timedOut = true;
|
|
680
|
+
runCleanup(
|
|
681
|
+
closeEntryScope(entry).pipe(
|
|
682
|
+
Effect.timeout(STOP_TIMEOUT_MS),
|
|
683
|
+
Effect.ignore,
|
|
684
|
+
),
|
|
685
|
+
);
|
|
686
|
+
}, options.timeoutSeconds * 1_000);
|
|
687
|
+
entry.timeoutTimer.unref?.();
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Plain-callback stream plumbing (the codex-backend precedent):
|
|
691
|
+
// setEncoding's internal StringDecoder is multibyte-safe across
|
|
692
|
+
// chunk boundaries.
|
|
693
|
+
child.stdout?.setEncoding("utf8");
|
|
694
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
695
|
+
if (!stdoutBuf.push(chunk)) child.stdout?.pause();
|
|
696
|
+
notify(id);
|
|
697
|
+
emitChunk(id, chunk, "stdout");
|
|
698
|
+
});
|
|
699
|
+
child.stderr?.setEncoding("utf8");
|
|
700
|
+
child.stderr?.on("data", (chunk: string) => {
|
|
701
|
+
if (!stderrBuf.push(chunk)) child.stderr?.pause();
|
|
702
|
+
notify(id);
|
|
703
|
+
emitChunk(id, chunk, "stderr");
|
|
704
|
+
});
|
|
705
|
+
// Spawn failures (ENOENT etc.) arrive via 'error', not a throw. Node
|
|
706
|
+
// still emits 'close' afterwards (with a bogus errno as code), so
|
|
707
|
+
// record the failure here and let the close path do the one settle.
|
|
708
|
+
child.once("error", (error) => {
|
|
709
|
+
entry.processErrored = true;
|
|
710
|
+
snapshot.errorText ??= boundedError(error);
|
|
711
|
+
entry.exited = true;
|
|
712
|
+
settleAfterFlush(entry);
|
|
713
|
+
});
|
|
714
|
+
// Record code/signal on 'exit'; settle on 'close' so the completion
|
|
715
|
+
// notification always carries the final flushed output.
|
|
716
|
+
child.once("exit", (code, signal) => {
|
|
717
|
+
entry.exited = true;
|
|
718
|
+
snapshot.exitCode = code ?? undefined;
|
|
719
|
+
snapshot.signal = signal ?? undefined;
|
|
720
|
+
// A descendant can keep the pipes open after the shell exits. Give
|
|
721
|
+
// close a short natural grace, then close the scope to terminate
|
|
722
|
+
// the surviving process group and force a bounded settlement.
|
|
723
|
+
scheduleExitCleanup(entry);
|
|
724
|
+
});
|
|
725
|
+
child.once("close", (code, signal) => {
|
|
726
|
+
entry.exited = true;
|
|
727
|
+
entry.stdioClosed = true;
|
|
728
|
+
// Only trust close's code/signal when 'exit' never fired (a spawn
|
|
729
|
+
// 'error' close reports the errno, e.g. -2, as its code).
|
|
730
|
+
if (!entry.processErrored) {
|
|
731
|
+
snapshot.exitCode ??= code ?? undefined;
|
|
732
|
+
snapshot.signal ??= signal ?? undefined;
|
|
733
|
+
}
|
|
734
|
+
settleAfterFlush(entry);
|
|
735
|
+
});
|
|
736
|
+
|
|
737
|
+
// One teardown path: kill(), requestKill, pruning, disposeAll, and
|
|
738
|
+
// runtime.dispose() all converge on closing this scope.
|
|
739
|
+
yield* Scope.provide(
|
|
740
|
+
Effect.addFinalizer(() =>
|
|
741
|
+
Effect.gen(function* () {
|
|
742
|
+
// Only claim "killed" when we are actually about to signal a
|
|
743
|
+
// live process; a natural exit that already happened (still
|
|
744
|
+
// waiting on 'close') keeps its truthful done/failed status.
|
|
745
|
+
yield* terminateChild(
|
|
746
|
+
child,
|
|
747
|
+
() => entry.stdioClosed,
|
|
748
|
+
() => {
|
|
749
|
+
entry.killSignaled ||=
|
|
750
|
+
!entry.timedOut &&
|
|
751
|
+
!entry.exited &&
|
|
752
|
+
entry.snapshot.status === "running";
|
|
753
|
+
},
|
|
754
|
+
);
|
|
755
|
+
// Give the natural close→flush→settle path a bounded grace,
|
|
756
|
+
// then force the settle: a grandchild holding the pipe open
|
|
757
|
+
// (detached into a new group) must not leave the entry
|
|
758
|
+
// "running" forever.
|
|
759
|
+
if (entry.snapshot.status === "running") {
|
|
760
|
+
yield* Deferred.await(entry.settled).pipe(
|
|
761
|
+
Effect.timeout(SETTLE_GRACE_MS),
|
|
762
|
+
Effect.ignore,
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
if (entry.snapshot.status === "running" && !entry.settling) {
|
|
766
|
+
// Force the settle ourselves. When `settling` is set, the
|
|
767
|
+
// close path's flush→settle is already in flight (bounded by
|
|
768
|
+
// SPILL_FLUSH_TIMEOUT_MS) — settling here first would cite a
|
|
769
|
+
// spill file that is still being flushed.
|
|
770
|
+
if (!entry.stdioClosed) {
|
|
771
|
+
entry.snapshot.errorText ??=
|
|
772
|
+
"stdio did not close after termination; output may be incomplete";
|
|
773
|
+
}
|
|
774
|
+
entry.settling = true;
|
|
775
|
+
yield* flushSpillStreams(entry);
|
|
776
|
+
settle(entry);
|
|
777
|
+
}
|
|
778
|
+
}),
|
|
779
|
+
),
|
|
780
|
+
scope,
|
|
781
|
+
);
|
|
782
|
+
|
|
783
|
+
// disposeAll may have swept the entries map while we were setting up;
|
|
784
|
+
// an entry added after the sweep would never be torn down. Close our
|
|
785
|
+
// own scope (kills the child) and fail instead (subagents precedent).
|
|
786
|
+
if (disposed) {
|
|
787
|
+
yield* closeEntryScope(entry);
|
|
788
|
+
return yield* new SpawnError({
|
|
789
|
+
message: "Background terminal manager shut down while starting.",
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
entries.set(id, entry);
|
|
793
|
+
notify(id);
|
|
794
|
+
return snapshot as TerminalSnapshot;
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
// Uninterruptible: between spawn() and entries.set there must be no
|
|
798
|
+
// window where an interrupt (tool abort, runtime dispose) leaves a
|
|
799
|
+
// live child that no scope/registry knows about. All steps are sync.
|
|
800
|
+
return yield* doStart.pipe(
|
|
801
|
+
Effect.uninterruptible,
|
|
802
|
+
Effect.ensuring(
|
|
803
|
+
Effect.sync(() => {
|
|
804
|
+
reserved--;
|
|
805
|
+
notify();
|
|
806
|
+
}),
|
|
807
|
+
),
|
|
808
|
+
);
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
const status = (id: string) =>
|
|
812
|
+
Effect.suspend(
|
|
813
|
+
(): Effect.Effect<TerminalSnapshot, UnknownTerminalError> => {
|
|
814
|
+
const entry = entries.get(id);
|
|
815
|
+
if (!entry) {
|
|
816
|
+
const known = [...entries.keys()];
|
|
817
|
+
return new UnknownTerminalError({
|
|
818
|
+
message: `Unknown terminal id "${id}". Known: ${known.join(", ") || "none"}.`,
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
return Effect.succeed(entry.snapshot as TerminalSnapshot);
|
|
822
|
+
},
|
|
823
|
+
);
|
|
824
|
+
|
|
825
|
+
/** Kill one running entry: close the scope — whose finalizer marks the kill
|
|
826
|
+
* at the signal point, terminates the tree, and force-settles —
|
|
827
|
+
* in a DETACHED fiber. Once the flag is set the termination must actually
|
|
828
|
+
* happen; a tool abort interrupting the caller cannot cancel it (this is
|
|
829
|
+
* what makes "termination continues in the background" truthful). */
|
|
830
|
+
const killEntry = (entry: Entry) =>
|
|
831
|
+
Effect.sync(() => {
|
|
832
|
+
if (entry.snapshot.status !== "running") return;
|
|
833
|
+
runCleanup(
|
|
834
|
+
closeEntryScope(entry).pipe(
|
|
835
|
+
Effect.timeout(STOP_TIMEOUT_MS),
|
|
836
|
+
Effect.ignore,
|
|
837
|
+
),
|
|
838
|
+
);
|
|
839
|
+
});
|
|
840
|
+
|
|
841
|
+
const kill = (ids: ReadonlyArray<string>) =>
|
|
842
|
+
Effect.suspend(() => {
|
|
843
|
+
const unique = [...new Set(ids)];
|
|
844
|
+
const byId = new Map(
|
|
845
|
+
unique
|
|
846
|
+
.map((id) => entries.get(id))
|
|
847
|
+
.filter((entry): entry is Entry => entry !== undefined)
|
|
848
|
+
.map((entry) => [entry.snapshot.id, entry]),
|
|
849
|
+
);
|
|
850
|
+
const running = [...byId.values()].filter(
|
|
851
|
+
(entry) => entry.snapshot.status === "running",
|
|
852
|
+
);
|
|
853
|
+
const runningIds = running.map((entry) => entry.snapshot.id);
|
|
854
|
+
// Mark consumed before signaling so this kill's settlements are not
|
|
855
|
+
// ALSO queued as automatic follow-up messages to the model.
|
|
856
|
+
addKillInterest(runningIds);
|
|
857
|
+
const work = Effect.gen(function* () {
|
|
858
|
+
yield* Effect.forEach(running, killEntry, {
|
|
859
|
+
concurrency: "unbounded",
|
|
860
|
+
});
|
|
861
|
+
// Every caller waits on the entries that were running when its kill
|
|
862
|
+
// began. Deferred completion cannot be missed and supports concurrent
|
|
863
|
+
// overlapping/multi-id kill calls.
|
|
864
|
+
yield* Effect.forEach(
|
|
865
|
+
running,
|
|
866
|
+
(entry) => Deferred.await(entry.settled),
|
|
867
|
+
{ concurrency: "unbounded", discard: true },
|
|
868
|
+
);
|
|
869
|
+
// Capture the report BEFORE the ensuring below releases interest and
|
|
870
|
+
// prunes — a just-settled entry must not vanish out from under it.
|
|
871
|
+
return unique.map((id): KillResult => {
|
|
872
|
+
const snapshot = byId.get(id)?.snapshot;
|
|
873
|
+
const history = settledHistory.get(id);
|
|
874
|
+
const status = snapshot?.status ?? history?.status ?? "killed";
|
|
875
|
+
const wasRunning = runningIds.includes(id);
|
|
876
|
+
return {
|
|
877
|
+
id,
|
|
878
|
+
title: snapshot?.title ?? history?.title ?? "?",
|
|
879
|
+
status,
|
|
880
|
+
wasRunning,
|
|
881
|
+
// A natural exit can win the race with our SIGTERM; report what
|
|
882
|
+
// actually happened rather than claiming the kill did it.
|
|
883
|
+
killed: wasRunning && status === "killed",
|
|
884
|
+
exit: snapshot
|
|
885
|
+
? formatExit(snapshot)
|
|
886
|
+
: (history?.exit ?? "unknown"),
|
|
887
|
+
};
|
|
888
|
+
});
|
|
889
|
+
});
|
|
890
|
+
return work.pipe(
|
|
891
|
+
Effect.ensuring(
|
|
892
|
+
Effect.sync(() => {
|
|
893
|
+
releaseKillInterest(runningIds);
|
|
894
|
+
pruneSettled();
|
|
895
|
+
}),
|
|
896
|
+
),
|
|
897
|
+
);
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
const disposeAll = Effect.gen(function* () {
|
|
901
|
+
disposed = true;
|
|
902
|
+
const all = [...entries.values()];
|
|
903
|
+
entries.clear();
|
|
904
|
+
yield* Effect.forEach(
|
|
905
|
+
all,
|
|
906
|
+
(entry) =>
|
|
907
|
+
closeEntryScope(entry).pipe(
|
|
908
|
+
Effect.timeout(STOP_TIMEOUT_MS),
|
|
909
|
+
Effect.ignore,
|
|
910
|
+
),
|
|
911
|
+
{ concurrency: "unbounded" },
|
|
912
|
+
);
|
|
913
|
+
// Detached kill/prune/flush work is scoped to the manager. Wait for it
|
|
914
|
+
// within the shutdown bound; the FiberSet finalizer interrupts anything
|
|
915
|
+
// still live when the manager scope closes, so cleanup cannot leak.
|
|
916
|
+
yield* FiberSet.awaitEmpty(cleanupFibers).pipe(
|
|
917
|
+
Effect.timeout(STOP_TIMEOUT_MS),
|
|
918
|
+
Effect.ignore,
|
|
919
|
+
);
|
|
920
|
+
yield* Effect.sync(() => {
|
|
921
|
+
const dir = spillDir;
|
|
922
|
+
spillDir = null;
|
|
923
|
+
if (dir) fs.rmSync(dir, { recursive: true, force: true });
|
|
924
|
+
});
|
|
925
|
+
yield* Effect.sync(() => notify());
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
const view: TerminalReadModel = {
|
|
929
|
+
list: () => [...entries.values()].map((entry) => entry.snapshot),
|
|
930
|
+
get: (id) => entries.get(id)?.snapshot,
|
|
931
|
+
size: () => entries.size,
|
|
932
|
+
subscribe: (listener) => {
|
|
933
|
+
listeners.add(listener);
|
|
934
|
+
return () => listeners.delete(listener);
|
|
935
|
+
},
|
|
936
|
+
subscribeTo: (id, listener) => {
|
|
937
|
+
let set = idListeners.get(id);
|
|
938
|
+
if (!set) {
|
|
939
|
+
set = new Set();
|
|
940
|
+
idListeners.set(id, set);
|
|
941
|
+
}
|
|
942
|
+
set.add(listener);
|
|
943
|
+
return () => {
|
|
944
|
+
set.delete(listener);
|
|
945
|
+
if (set.size === 0) idListeners.delete(id);
|
|
946
|
+
};
|
|
947
|
+
},
|
|
948
|
+
subscribeToChunks: (id, listener) => {
|
|
949
|
+
let set = chunkListeners.get(id);
|
|
950
|
+
if (!set) {
|
|
951
|
+
set = new Set();
|
|
952
|
+
chunkListeners.set(id, set);
|
|
953
|
+
}
|
|
954
|
+
set.add(listener);
|
|
955
|
+
return () => {
|
|
956
|
+
set.delete(listener);
|
|
957
|
+
if (set.size === 0) chunkListeners.delete(id);
|
|
958
|
+
};
|
|
959
|
+
},
|
|
960
|
+
requestKill: (id) => {
|
|
961
|
+
const entry = entries.get(id);
|
|
962
|
+
if (!entry) return;
|
|
963
|
+
// UI-initiated kills are not "consumed": the killed result still flows
|
|
964
|
+
// back to the model as a follow-up message (subagents precedent).
|
|
965
|
+
runCleanup(killEntry(entry).pipe(Effect.ignore));
|
|
966
|
+
},
|
|
967
|
+
setOnSettled: (hook) => {
|
|
968
|
+
onSettled = hook;
|
|
969
|
+
},
|
|
970
|
+
};
|
|
971
|
+
|
|
972
|
+
// Safety net: disposing the ManagedRuntime tears everything down even if
|
|
973
|
+
// the extension forgot to call disposeAll explicitly.
|
|
974
|
+
yield* Effect.addFinalizer(() => disposeAll);
|
|
975
|
+
|
|
976
|
+
return TerminalManager.of({
|
|
977
|
+
start,
|
|
978
|
+
status,
|
|
979
|
+
kill,
|
|
980
|
+
list: Effect.sync(() => [...entries.values()].map((e) => e.snapshot)),
|
|
981
|
+
disposeAll,
|
|
982
|
+
view,
|
|
983
|
+
});
|
|
984
|
+
});
|
|
985
|
+
|
|
986
|
+
export const TerminalManagerLive: Layer.Layer<TerminalManager> = Layer.effect(
|
|
987
|
+
TerminalManager,
|
|
988
|
+
makeManager,
|
|
989
|
+
);
|