ceulen 0.12.0 → 0.14.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/CHANGELOG.md +91 -0
- package/extensions/lib/registry.ts +15 -1
- package/extensions/modules/a2a/lib/config.ts +15 -1
- package/extensions/modules/a2a/test/config.test.ts +27 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/fff/index.ts +19 -0
- package/extensions/modules/fff/test/index.test.ts +31 -4
- package/extensions/modules/gh/configPanel.ts +9 -6
- package/extensions/modules/gh/test/gh.test.ts +61 -0
- package/extensions/modules/jfind/index.ts +124 -0
- package/extensions/modules/jfind/lib/cascade.ts +391 -0
- package/extensions/modules/jfind/lib/format.ts +12 -0
- package/extensions/modules/jfind/lib/judge.ts +74 -0
- package/extensions/modules/jfind/lib/lexical.ts +244 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +404 -0
- package/extensions/modules/jfind/test/cascade.test.ts +360 -0
- package/extensions/modules/notify/index.ts +33 -0
- package/extensions/modules/notify/lib/notify.ts +99 -0
- package/extensions/modules/notify/test/notify.test.ts +95 -0
- package/extensions/modules/plan/lib/plan-tools.ts +13 -0
- package/extensions/modules/repair/configPanel.ts +18 -9
- package/extensions/modules/repair/index.ts +173 -9
- package/extensions/modules/repair/lib/auto-bg.ts +45 -2
- package/extensions/modules/repair/lib/auto-generated.ts +99 -0
- package/extensions/modules/repair/lib/read-archive.ts +115 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +191 -0
- package/extensions/modules/repair/lib/settings.ts +23 -9
- package/extensions/modules/repair/test/auto-bg.test.ts +66 -0
- package/extensions/modules/repair/test/hardening.test.ts +214 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +54 -14
- package/extensions/modules/sg/index.ts +129 -0
- package/extensions/modules/sg/lib/ops.ts +144 -0
- package/extensions/modules/sg/lib/sg-cli.ts +104 -0
- package/extensions/modules/sg/test/sg.test.ts +128 -0
- package/extensions/modules/shells/index.ts +227 -0
- package/extensions/modules/shells/lib/sessions.ts +412 -0
- package/extensions/modules/shells/test/output.test.ts +130 -0
- package/extensions/modules/shells/test/sessions.test.ts +397 -0
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +183 -0
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/pdf.test.ts +84 -0
- package/extensions/modules/web/vendor/pdfjs/LICENSE +177 -0
- package/extensions/modules/web/vendor/pdfjs/README.md +16 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.min.mjs +21 -0
- package/extensions/modules/web/vendor/pdfjs/pdf.worker.mjs +21 -0
- package/package.json +3 -3
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
// shells — background shell sessions (Claude Code BashOutput/KillShell parity).
|
|
2
|
+
//
|
|
3
|
+
// ALL pure logic lives here and is exported for tests: RingBuffer (line
|
|
4
|
+
// buffering + hard byte cap with head+tail split), ShellSession, SessionStore
|
|
5
|
+
// (live-session cap, killAll with escalation, evict-oldest-exited), the
|
|
6
|
+
// monotonic id counter, name-aware id resolution, and createSession — the
|
|
7
|
+
// spawn seam (takes a spawn fn so tests inject fakes or `node -e` commands).
|
|
8
|
+
|
|
9
|
+
import type { ChildProcess } from "node:child_process";
|
|
10
|
+
import type { EventEmitter } from "node:events";
|
|
11
|
+
|
|
12
|
+
/** Hard cap per stream buffer. Beyond it: keep head + tail, drop the middle. */
|
|
13
|
+
export const TOTAL_BYTES = 262_144;
|
|
14
|
+
/** Bytes kept from the START of the stream when the cap is exceeded. */
|
|
15
|
+
export const HEAD_KEEP_BYTES = 4096;
|
|
16
|
+
|
|
17
|
+
/** The `[… N bytes truncated …]` divider inserted where the middle was dropped. */
|
|
18
|
+
export function truncationMarker(bytes: number): string {
|
|
19
|
+
return `[… ${bytes} bytes truncated …]`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function trimPartialHead(lines: string[], total: number, keep: number): { lines: string[]; total: number } {
|
|
23
|
+
let dropped = 0;
|
|
24
|
+
while (lines.length > 0 && total - dropped > keep) {
|
|
25
|
+
dropped += Buffer.byteLength(lines[0], "utf8") + 1;
|
|
26
|
+
lines.shift();
|
|
27
|
+
}
|
|
28
|
+
return { lines, total: total - dropped };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Line-buffered ring for one output stream. `push` splits on \n and keeps the
|
|
33
|
+
* partial tail until its newline arrives. When total bytes exceed TOTAL_BYTES
|
|
34
|
+
* the stored lines become: first bytes + marker + last bytes (bash-tool
|
|
35
|
+
* truncation semantics), re-checked after every push.
|
|
36
|
+
*/
|
|
37
|
+
export class RingBuffer {
|
|
38
|
+
private linesArr: string[] = [];
|
|
39
|
+
private partial = ""; // unterminated tail not yet a line
|
|
40
|
+
private totalBytes = 0;
|
|
41
|
+
private lifetimeBytes = 0;
|
|
42
|
+
private lifetimeLineCount = 0; // complete lines ever pushed — never shrinks
|
|
43
|
+
private tailStart = 0; // once capped: index of the first tail line (the marker sits at tailStart - 1)
|
|
44
|
+
private capped = false;
|
|
45
|
+
|
|
46
|
+
push(chunk: string): void {
|
|
47
|
+
// A previous unterminated tail continues with this chunk's first line.
|
|
48
|
+
const parts = (this.partial + chunk).split("\n");
|
|
49
|
+
this.partial = "";
|
|
50
|
+
this.partial = parts.pop() ?? "";
|
|
51
|
+
for (const line of parts) this.linesArr.push(line);
|
|
52
|
+
this.lifetimeLineCount += parts.length;
|
|
53
|
+
this.totalBytes += Buffer.byteLength(chunk, "utf8");
|
|
54
|
+
this.lifetimeBytes += Buffer.byteLength(chunk, "utf8");
|
|
55
|
+
if (this.totalBytes > TOTAL_BYTES) this.enforceCap();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
private enforceCap(): void {
|
|
59
|
+
this.capped = true;
|
|
60
|
+
const lineBytes = (ls: string[]) => ls.reduce((n, l) => n + Buffer.byteLength(l, "utf8") + 1, 0);
|
|
61
|
+
const keepTail = TOTAL_BYTES - HEAD_KEEP_BYTES - Buffer.byteLength(truncationMarker(1), "utf8") - 1;
|
|
62
|
+
// Split the whole lines into HEAD (first bytes) + TAIL (last bytes),
|
|
63
|
+
// dropping the middle; the first line of each side is taken even when it
|
|
64
|
+
// alone busts its budget (one giant line must still be visible).
|
|
65
|
+
let head: string[] = [];
|
|
66
|
+
const tail: string[] = [];
|
|
67
|
+
let tailBytes = 0;
|
|
68
|
+
const rest = [...this.linesArr];
|
|
69
|
+
while (rest.length > 0) {
|
|
70
|
+
const l = rest[rest.length - 1]!;
|
|
71
|
+
const b = Buffer.byteLength(l, "utf8") + 1;
|
|
72
|
+
if (tailBytes + b > keepTail && tail.length > 0) break;
|
|
73
|
+
tail.unshift(l);
|
|
74
|
+
rest.pop();
|
|
75
|
+
tailBytes += b;
|
|
76
|
+
}
|
|
77
|
+
let headBytes = 0;
|
|
78
|
+
while (rest.length > 0) {
|
|
79
|
+
const l = rest[0]!;
|
|
80
|
+
const b = Buffer.byteLength(l, "utf8") + 1;
|
|
81
|
+
if (headBytes + b > HEAD_KEEP_BYTES && head.length > 0) break;
|
|
82
|
+
head.push(l);
|
|
83
|
+
rest.shift();
|
|
84
|
+
headBytes += b;
|
|
85
|
+
}
|
|
86
|
+
const droppedBytes = lineBytes(rest);
|
|
87
|
+
this.linesArr = [...head, truncationMarker(Math.max(droppedBytes, 1)), ...tail];
|
|
88
|
+
this.tailStart = head.length + 1;
|
|
89
|
+
this.totalBytes = lineBytes(this.linesArr);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Everything visible so far: complete lines plus the unterminated tail. */
|
|
93
|
+
lines(): string[] {
|
|
94
|
+
return this.capAware();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Complete lines ever pushed (lifetime — immune to cap shrinks). */
|
|
98
|
+
lifetimeLines(): number {
|
|
99
|
+
return this.lifetimeLineCount;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Visible lines pushed after lifetime line `seen` — the since:"last"
|
|
104
|
+
* cursor read. The cursor lives in lifetime space, so a cap shrink can
|
|
105
|
+
* never strand it above the window: unseen lines are the NEWEST ones,
|
|
106
|
+
* which the tail region (after the marker) always holds. When more lines
|
|
107
|
+
* arrived than the window kept, the whole recent region + marker returns
|
|
108
|
+
* instead of nothing; lines the cap dropped are simply gone.
|
|
109
|
+
*/
|
|
110
|
+
linesSince(seen: number): string[] {
|
|
111
|
+
const behind = this.lifetimeLineCount - Math.max(0, seen);
|
|
112
|
+
if (behind <= 0) return [];
|
|
113
|
+
const all = this.capAware();
|
|
114
|
+
const hasPartial = this.partial !== "";
|
|
115
|
+
const completeCount = all.length - (hasPartial ? 1 : 0);
|
|
116
|
+
const floor = this.capped ? this.tailStart - 1 : 0; // never re-show the dropped middle / marker
|
|
117
|
+
const start = Math.max(floor, completeCount - behind);
|
|
118
|
+
const fresh = all.slice(start, completeCount);
|
|
119
|
+
return hasPartial ? [...fresh, this.partial] : fresh;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Bytes written to this stream over its lifetime (pre-truncation). */
|
|
123
|
+
totalWritten(): number {
|
|
124
|
+
return this.lifetimeBytes;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** True once the cap has been enforced at least once. */
|
|
128
|
+
isTruncated(): boolean {
|
|
129
|
+
return this.capped;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The unterminated tail, if any (exposed for tests/debugging). */
|
|
133
|
+
peekPartial(): string {
|
|
134
|
+
return this.partial;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private capAware(): string[] {
|
|
138
|
+
// The partial survives capping too: spinner/progress output that hasn't
|
|
139
|
+
// got its newline yet must stay visible once the head+tail split is on.
|
|
140
|
+
if (this.capped) return this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
|
|
141
|
+
const out = this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface ShellSession {
|
|
147
|
+
id: string;
|
|
148
|
+
name?: string;
|
|
149
|
+
pid: number;
|
|
150
|
+
child: ChildProcess;
|
|
151
|
+
cwd: string;
|
|
152
|
+
command: string;
|
|
153
|
+
startedAt: number;
|
|
154
|
+
exitedAt?: number;
|
|
155
|
+
exitCode?: number | null;
|
|
156
|
+
stdout: RingBuffer;
|
|
157
|
+
stderr: RingBuffer;
|
|
158
|
+
/** Per-stream output cursors for `since: "last"` — lines already returned by an output call. */
|
|
159
|
+
lastStdoutOffset: number;
|
|
160
|
+
lastStderrOffset: number;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
// ID resolution + store
|
|
165
|
+
|
|
166
|
+
/** `nextId()` → "s1", "s2", … Monotonic module counter (never resets). */
|
|
167
|
+
let counter = 0;
|
|
168
|
+
export function nextId(): string {
|
|
169
|
+
counter += 1;
|
|
170
|
+
return `s${counter}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Test/multi-store hook: reset the id counter to n (default 0). */
|
|
174
|
+
export function resetIdCounter(n = 0): void {
|
|
175
|
+
counter = n;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function fmtStatus(s: ShellSession): string {
|
|
179
|
+
return s.exitedAt === undefined ? "running" : `exited code ${s.exitCode ?? "signal"}`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** One `id name status uptime` summary line used in listings and errors. */
|
|
183
|
+
export function summarizeSession(s: ShellSession): string {
|
|
184
|
+
const name = s.name ? ` ${s.name}` : "";
|
|
185
|
+
return `${s.id}${name} ${fmtStatus(s)} ${s.command}`;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** One `id name status` listing entry (no command). */
|
|
189
|
+
export function listSessionsLine(s: ShellSession): string {
|
|
190
|
+
const name = s.name ? ` ${s.name}` : "";
|
|
191
|
+
return `${s.id}${name} ${fmtStatus(s)}`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Resolve idOrName: exact session id first, then a UNIQUE name match.
|
|
196
|
+
* Throws (with the session list) on no match or an ambiguous name.
|
|
197
|
+
*/
|
|
198
|
+
export function resolveSession(store: SessionStore, idOrName: string): ShellSession {
|
|
199
|
+
const byId = store.get(idOrName);
|
|
200
|
+
if (byId) return byId;
|
|
201
|
+
// Prefer LIVE matches: restarting a session under the same name must not
|
|
202
|
+
// make the name ambiguous just because an old exited one lingers. Only
|
|
203
|
+
// when NO live match exists fall back to the full match list (original
|
|
204
|
+
// ambiguity semantics over exited sessions).
|
|
205
|
+
const all = store.list().filter((s) => s.name === idOrName);
|
|
206
|
+
const live = all.filter((s) => s.exitedAt === undefined);
|
|
207
|
+
const candidates = live.length > 0 ? live : all;
|
|
208
|
+
if (candidates.length === 1) return candidates[0]!;
|
|
209
|
+
const listing = store.list().map(listSessionsLine).join("\n") || "(no sessions)";
|
|
210
|
+
if (candidates.length > 1) {
|
|
211
|
+
throw new Error(`session name '${idOrName}' is ambiguous (${candidates.length} sessions):\n${listing}`);
|
|
212
|
+
}
|
|
213
|
+
throw new Error(`no session '${idOrName}'. Active sessions:\n${listing}`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const MAX_LIVE_SESSIONS = 10;
|
|
217
|
+
const MAX_EXITED_SESSIONS = 5;
|
|
218
|
+
const EXIT_WAIT_MS = 2_000;
|
|
219
|
+
|
|
220
|
+
export class SessionStore {
|
|
221
|
+
private map = new Map<string, ShellSession>();
|
|
222
|
+
|
|
223
|
+
/** Register a session. Throws (listing live sessions) when 10 are already LIVE. */
|
|
224
|
+
add(session: ShellSession): void {
|
|
225
|
+
const live = this.list().filter((s) => s.exitedAt === undefined);
|
|
226
|
+
if (live.length >= MAX_LIVE_SESSIONS && session.exitedAt === undefined) {
|
|
227
|
+
const listing = live.map(listSessionsLine).join("\n");
|
|
228
|
+
throw new Error(
|
|
229
|
+
`refusing to start an 11th live shell session — kill one first (shell action:"kill"):\n${listing}`,
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
this.map.set(session.id, session);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
get(id: string): ShellSession | undefined {
|
|
236
|
+
return this.map.get(id);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** All sessions, oldest first (insertion order). */
|
|
240
|
+
list(): ShellSession[] {
|
|
241
|
+
return [...this.map.values()];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Replace a placeholder registration with the real session. */
|
|
245
|
+
replace(id: string, session: ShellSession): void {
|
|
246
|
+
this.map.delete(id);
|
|
247
|
+
this.map.set(session.id, session);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Drop a session (spawn-failure cleanup, tests). */
|
|
251
|
+
remove(id: string): void {
|
|
252
|
+
this.map.delete(id);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Drop every session (session_start: a fresh session can't reach old children). */
|
|
256
|
+
clear(): void {
|
|
257
|
+
this.map.clear();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Remove the OLDEST exited session if more than 5 have accumulated. */
|
|
261
|
+
evictOldestExited(): ShellSession | undefined {
|
|
262
|
+
const exited = this.list().filter((s) => s.exitedAt !== undefined);
|
|
263
|
+
if (exited.length <= MAX_EXITED_SESSIONS) return undefined;
|
|
264
|
+
const oldest = exited[0]!;
|
|
265
|
+
this.map.delete(oldest.id);
|
|
266
|
+
return oldest;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Kill every live session's process GROUP (negative pid), falling back to
|
|
271
|
+
* child.kill, then wait for exit (2s) and escalate to SIGKILL. Resolves
|
|
272
|
+
* when all processes are gone (or unkillable — never rejects).
|
|
273
|
+
*/
|
|
274
|
+
async killAll(signal: NodeJS.Signals = "SIGTERM"): Promise<void> {
|
|
275
|
+
await Promise.all(this.list().filter((s) => s.exitedAt === undefined).map((s) => killSession(s, signal)));
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Kill one session's process group, await exit, escalate to SIGKILL. */
|
|
280
|
+
export async function killSession(s: ShellSession, signal: NodeJS.Signals = "SIGTERM", waitMs = EXIT_WAIT_MS): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
|
|
281
|
+
if (s.exitedAt !== undefined) {
|
|
282
|
+
return { code: s.exitCode ?? null, signal: null };
|
|
283
|
+
}
|
|
284
|
+
signalProcessGroup(s, signal);
|
|
285
|
+
return await awaitExit(s, waitMs);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function signalProcessGroup(s: ShellSession, signal: NodeJS.Signals): void {
|
|
289
|
+
// detached: true → the child leads its own process group; -pid signals the
|
|
290
|
+
// whole group (the shell AND any grandchildren). Fall back to child.kill
|
|
291
|
+
// when the group is gone (already reaped) or the call fails (Windows).
|
|
292
|
+
// pid 0 (spawn never succeeded) MUST NOT reach process.kill: kill(-0) ==
|
|
293
|
+
// kill(0) == SIGTERM for every process in pi's OWN group — host death.
|
|
294
|
+
if (s.pid <= 0) {
|
|
295
|
+
try {
|
|
296
|
+
s.child.kill(signal);
|
|
297
|
+
} catch {
|
|
298
|
+
// spawn never succeeded / already dead — exit handling deals with it
|
|
299
|
+
}
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
process.kill(-s.pid, signal);
|
|
304
|
+
} catch {
|
|
305
|
+
try {
|
|
306
|
+
s.child.kill(signal);
|
|
307
|
+
} catch {
|
|
308
|
+
// already dead — exit handling below deals with it
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Await child exit; escalate to SIGKILL after waitMs. Never rejects. */
|
|
314
|
+
export function awaitExit(s: ShellSession, waitMs = EXIT_WAIT_MS): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
|
|
315
|
+
return new Promise((resolveP) => {
|
|
316
|
+
const child = s.child;
|
|
317
|
+
let done = false;
|
|
318
|
+
const finish = (code: number | null, sig: NodeJS.Signals | null) => {
|
|
319
|
+
if (done) return;
|
|
320
|
+
done = true;
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
resolveP({ code, signal: sig });
|
|
323
|
+
};
|
|
324
|
+
const timer = setTimeout(() => {
|
|
325
|
+
signalProcessGroup(s, "SIGKILL");
|
|
326
|
+
// Belt and braces: if even SIGKILL's exit event never lands, stop waiting.
|
|
327
|
+
setTimeout(() => finish(null, "SIGKILL"), waitMs).unref?.();
|
|
328
|
+
}, waitMs);
|
|
329
|
+
timer.unref?.();
|
|
330
|
+
child.once("exit", (code, sig) => finish(code, sig));
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------------------------------------------------------------------------
|
|
335
|
+
// Session creation (the spawn seam — tests inject their own spawn fn)
|
|
336
|
+
|
|
337
|
+
export type SpawnFn = (command: string, options: { shell: boolean; cwd: string; env: NodeJS.ProcessEnv; stdio: ["pipe", "pipe", "pipe"]; detached: boolean }) => ChildProcess;
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Spawn `command` in its own process group, wire both streams into
|
|
341
|
+
* RingBuffers, and register the session in `store`. Returns the session.
|
|
342
|
+
* Throws a clean error when the spawn itself fails (bad cwd, etc.).
|
|
343
|
+
*/
|
|
344
|
+
export function createSession(
|
|
345
|
+
store: SessionStore,
|
|
346
|
+
spawnFn: SpawnFn,
|
|
347
|
+
opts: { command: string; cwd: string; name?: string; env?: NodeJS.ProcessEnv },
|
|
348
|
+
): ShellSession {
|
|
349
|
+
if (opts.name && store.list().some((s) => s.name === opts.name && s.exitedAt === undefined)) {
|
|
350
|
+
const listing = store.list().map(listSessionsLine).join("\n");
|
|
351
|
+
throw new Error(`a live session named '${opts.name}' already exists:\n${listing}`);
|
|
352
|
+
}
|
|
353
|
+
store.add({
|
|
354
|
+
id: "",
|
|
355
|
+
name: opts.name,
|
|
356
|
+
pid: 0,
|
|
357
|
+
child: {} as ChildProcess,
|
|
358
|
+
cwd: opts.cwd,
|
|
359
|
+
command: opts.command,
|
|
360
|
+
startedAt: Date.now(),
|
|
361
|
+
stdout: new RingBuffer(),
|
|
362
|
+
stderr: new RingBuffer(),
|
|
363
|
+
lastStdoutOffset: 0,
|
|
364
|
+
lastStderrOffset: 0,
|
|
365
|
+
} as ShellSession); // placeholder so the live-cap check sees THIS session too
|
|
366
|
+
const placeholder = store.list().at(-1)!;
|
|
367
|
+
let child: ChildProcess;
|
|
368
|
+
try {
|
|
369
|
+
child = spawnFn(opts.command, {
|
|
370
|
+
shell: true,
|
|
371
|
+
cwd: opts.cwd,
|
|
372
|
+
env: opts.env ?? process.env,
|
|
373
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
374
|
+
detached: true,
|
|
375
|
+
});
|
|
376
|
+
} catch (err) {
|
|
377
|
+
// Never leave a half-registered placeholder behind.
|
|
378
|
+
store.remove(placeholder.id);
|
|
379
|
+
throw new Error(`failed to start '${opts.command}': ${err instanceof Error ? err.message : String(err)}`);
|
|
380
|
+
}
|
|
381
|
+
const session: ShellSession = {
|
|
382
|
+
...placeholder,
|
|
383
|
+
id: nextId(),
|
|
384
|
+
pid: child.pid ?? 0,
|
|
385
|
+
child,
|
|
386
|
+
};
|
|
387
|
+
store.replace(placeholder.id, session);
|
|
388
|
+
child.stdout?.on("data", (d: Buffer) => session.stdout.push(d.toString()));
|
|
389
|
+
child.stderr?.on("data", (d: Buffer) => session.stderr.push(d.toString()));
|
|
390
|
+
// A stdin write that races child exit EPIPEs; with no listener Node turns
|
|
391
|
+
// that into an uncaughtException killing pi. Contain and record instead.
|
|
392
|
+
child.stdin?.on("error", () => {
|
|
393
|
+
session.stderr.push("[shells] stdin write failed (process exited)");
|
|
394
|
+
});
|
|
395
|
+
child.on("exit", (code) => {
|
|
396
|
+
session.exitedAt = Date.now();
|
|
397
|
+
session.exitCode = code;
|
|
398
|
+
});
|
|
399
|
+
child.on("error", (err: Error) => {
|
|
400
|
+
// Spawn failure (ENOENT cwd/binary) arrives as 'error' with pid undefined
|
|
401
|
+
// and NO 'exit'. Mark it exited so kill/killAll never signal a pid-0
|
|
402
|
+
// "process group" — which would hit pi's own group. Windows quirk:
|
|
403
|
+
// 'error' can also fire on a LIVE pid-carrying process (kill-EPIPE),
|
|
404
|
+
// so only the never-spawned case (no pid) counts as exit.
|
|
405
|
+
if (child.pid === undefined) {
|
|
406
|
+
session.exitedAt = Date.now();
|
|
407
|
+
session.exitCode = null;
|
|
408
|
+
}
|
|
409
|
+
session.stderr.push(`[shells] spawn error: ${err.message}`);
|
|
410
|
+
});
|
|
411
|
+
return session;
|
|
412
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Unit tests for the tool's output rendering + store lifecycle wiring
|
|
2
|
+
// (index.ts): per-stream `since:"last"` cursors and the session_start clear.
|
|
3
|
+
// index.ts is loaded through a stub ExtensionAPI; spawn is not touched.
|
|
4
|
+
|
|
5
|
+
import assert from "node:assert/strict";
|
|
6
|
+
import { describe, it } from "node:test";
|
|
7
|
+
import { RingBuffer, SessionStore, type ShellSession } from "../lib/sessions.js";
|
|
8
|
+
import mod, { getStoreForTests } from "../index.js";
|
|
9
|
+
|
|
10
|
+
/** Drive the module against a stub pi and return the registered tool + handlers. */
|
|
11
|
+
function load(): { tool: any; handlers: Record<string, Function>; store: SessionStore } {
|
|
12
|
+
const handlers: Record<string, Function> = {};
|
|
13
|
+
let tool: any;
|
|
14
|
+
const fakePi: any = {
|
|
15
|
+
on: (ev: string, fn: Function) => { handlers[ev] = fn; },
|
|
16
|
+
registerTool: (t: any) => { tool = t; },
|
|
17
|
+
};
|
|
18
|
+
mod(fakePi);
|
|
19
|
+
// Reach the store for cursor/clear assertions (module closes over it).
|
|
20
|
+
return { tool, handlers, store: getStoreForTests()! };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function session(over: Partial<ShellSession>): ShellSession {
|
|
24
|
+
return {
|
|
25
|
+
id: "s1",
|
|
26
|
+
pid: 1,
|
|
27
|
+
child: {} as never,
|
|
28
|
+
cwd: "/",
|
|
29
|
+
command: "true",
|
|
30
|
+
startedAt: Date.now(),
|
|
31
|
+
stdout: new RingBuffer(),
|
|
32
|
+
stderr: new RingBuffer(),
|
|
33
|
+
lastStdoutOffset: 0,
|
|
34
|
+
lastStderrOffset: 0,
|
|
35
|
+
...over,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe("output cursors (since:\"last\")", () => {
|
|
40
|
+
it("advances per-stream, independently", async () => {
|
|
41
|
+
const { tool, store } = load();
|
|
42
|
+
const s = session({ id: "s1" });
|
|
43
|
+
s.stdout.push("out-1\n");
|
|
44
|
+
s.stderr.push("err-1\n");
|
|
45
|
+
store.add(s);
|
|
46
|
+
|
|
47
|
+
const read = async () => {
|
|
48
|
+
const r = await tool.execute("t", { action: "output", id: "s1", since: "last" }, undefined as never, undefined as never, { cwd: "/" } as never);
|
|
49
|
+
return (r.content[0] as { text: string }).text;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
let text = await read();
|
|
53
|
+
assert.match(text, /out-1/);
|
|
54
|
+
assert.match(text, /err-1/);
|
|
55
|
+
assert.equal(s.lastStdoutOffset, 1);
|
|
56
|
+
assert.equal(s.lastStderrOffset, 1);
|
|
57
|
+
|
|
58
|
+
// Only stderr advances now: stdout cursor must stay put.
|
|
59
|
+
s.stderr.push("err-2\n");
|
|
60
|
+
text = await read();
|
|
61
|
+
assert.doesNotMatch(text, /out-1/);
|
|
62
|
+
assert.match(text, /err-2/);
|
|
63
|
+
assert.equal(s.lastStdoutOffset, 1, "stdout cursor unchanged when only stderr grew");
|
|
64
|
+
assert.equal(s.lastStderrOffset, 2);
|
|
65
|
+
|
|
66
|
+
// Only stdout grows past stderr — stderr must not repeat (the old
|
|
67
|
+
// single-cursor bug showed stderr again whenever stdout was longer).
|
|
68
|
+
s.stdout.push("out-2\n");
|
|
69
|
+
text = await read();
|
|
70
|
+
assert.match(text, /out-2/);
|
|
71
|
+
assert.doesNotMatch(text, /err-1/);
|
|
72
|
+
assert.doesNotMatch(text, /err-2/);
|
|
73
|
+
assert.equal(s.lastStdoutOffset, 2);
|
|
74
|
+
assert.equal(s.lastStderrOffset, 2);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("since:\"start\" never moves the cursors", async () => {
|
|
78
|
+
const { tool, store } = load();
|
|
79
|
+
const s = session({ id: "s1" });
|
|
80
|
+
s.stdout.push("a\nb\n");
|
|
81
|
+
store.add(s);
|
|
82
|
+
await tool.execute("t", { action: "output", id: "s1" }, undefined as never, undefined as never, { cwd: "/" } as never);
|
|
83
|
+
assert.equal(s.lastStdoutOffset, 0);
|
|
84
|
+
assert.equal(s.lastStderrOffset, 0);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("re-clamps a cursor left above a ring-cap-shrunk array and recovers", async () => {
|
|
88
|
+
const { tool, store } = load();
|
|
89
|
+
const s = session({ id: "s1" });
|
|
90
|
+
store.add(s);
|
|
91
|
+
const read = async () => {
|
|
92
|
+
const r = await tool.execute("t", { action: "output", id: "s1", since: "last" }, undefined as never, undefined as never, { cwd: "/" } as never);
|
|
93
|
+
return (r.content[0] as { text: string }).text;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// Fill the ring PAST its cap (1KB lines, two big chunks): enforceCap()
|
|
97
|
+
// rebuilds the array to head + marker + tail (~260 lines). The drain
|
|
98
|
+
// poll reports the truncation and records that line count as the cursor.
|
|
99
|
+
s.stdout.push("HEAD-LINE\n");
|
|
100
|
+
const kbLine = `${"A".repeat(999)}\n`.repeat(420); // ~420KB per chunk
|
|
101
|
+
s.stdout.push(kbLine);
|
|
102
|
+
s.stdout.push(kbLine);
|
|
103
|
+
const text1 = await read();
|
|
104
|
+
assert.match(text1, /truncated/);
|
|
105
|
+
assert.equal(s.lastStdoutOffset, s.stdout.lifetimeLines(), "drain records the lifetime cursor");
|
|
106
|
+
|
|
107
|
+
// Two huge lines re-cap and SHRINK the window far below the recorded
|
|
108
|
+
// index-space position. A window-index cursor (the old design) strands
|
|
109
|
+
// above the shrunk array forever — the lifetime cursor cannot.
|
|
110
|
+
s.stdout.push(`${"x".repeat(99_999)}\n${"y".repeat(99_999)}\n`);
|
|
111
|
+
await read();
|
|
112
|
+
assert.ok(s.lastStdoutOffset > s.stdout.lines().length, "cursor is lifetime space, above the shrunk window (previously the blackout)");
|
|
113
|
+
assert.equal(s.lastStdoutOffset, s.stdout.lifetimeLines(), "cursor stays synced to lifetime lines after the shrink");
|
|
114
|
+
|
|
115
|
+
// Recovery: new pushes must surface again, not "no new output yet".
|
|
116
|
+
for (let i = 0; i < 12; i++) s.stdout.push(`${"NEW-".padEnd(4999, "N")}\n`.repeat(60));
|
|
117
|
+
const text2 = await read();
|
|
118
|
+
assert.match(text2, /NEW-/);
|
|
119
|
+
assert.doesNotMatch(text2, /no new output yet/);
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe("session_start wiring", () => {
|
|
124
|
+
it("clears the store (no-op bug regression)", async () => {
|
|
125
|
+
const { handlers, store } = load();
|
|
126
|
+
store.add(session({ id: "s1" }));
|
|
127
|
+
(handlers.session_start as (e: unknown, ctx: unknown) => void)({}, {});
|
|
128
|
+
assert.equal(store.list().length, 0);
|
|
129
|
+
});
|
|
130
|
+
});
|