ceulen 0.12.0 → 0.13.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 +49 -0
- package/extensions/lib/registry.ts +15 -1
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/jfind/index.ts +115 -0
- package/extensions/modules/jfind/lib/cascade.ts +377 -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 +232 -0
- package/extensions/modules/jfind/lib/questions.ts +178 -0
- package/extensions/modules/jfind/lib/tree.ts +374 -0
- package/extensions/modules/jfind/test/cascade.test.ts +305 -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 +7 -1
- package/extensions/modules/repair/index.ts +132 -1
- package/extensions/modules/repair/lib/auto-generated.ts +89 -0
- package/extensions/modules/repair/lib/read-archive.ts +101 -0
- package/extensions/modules/repair/lib/read-sqlite.ts +185 -0
- package/extensions/modules/repair/lib/settings.ts +4 -1
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- 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 +210 -0
- package/extensions/modules/shells/lib/sessions.ts +344 -0
- package/extensions/modules/shells/test/sessions.test.ts +275 -0
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/extension.test.ts +2 -1
- 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,344 @@
|
|
|
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 capped = false;
|
|
43
|
+
|
|
44
|
+
push(chunk: string): void {
|
|
45
|
+
// A previous unterminated tail continues with this chunk's first line.
|
|
46
|
+
const parts = (this.partial + chunk).split("\n");
|
|
47
|
+
this.partial = "";
|
|
48
|
+
this.partial = parts.pop() ?? "";
|
|
49
|
+
for (const line of parts) this.linesArr.push(line);
|
|
50
|
+
this.totalBytes += Buffer.byteLength(chunk, "utf8");
|
|
51
|
+
this.lifetimeBytes += Buffer.byteLength(chunk, "utf8");
|
|
52
|
+
if (this.totalBytes > TOTAL_BYTES) this.enforceCap();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
private enforceCap(): void {
|
|
56
|
+
this.capped = true;
|
|
57
|
+
const lineBytes = (ls: string[]) => ls.reduce((n, l) => n + Buffer.byteLength(l, "utf8") + 1, 0);
|
|
58
|
+
const keepTail = TOTAL_BYTES - HEAD_KEEP_BYTES - Buffer.byteLength(truncationMarker(1), "utf8") - 1;
|
|
59
|
+
// Split the whole lines into HEAD (first bytes) + TAIL (last bytes),
|
|
60
|
+
// dropping the middle; the first line of each side is taken even when it
|
|
61
|
+
// alone busts its budget (one giant line must still be visible).
|
|
62
|
+
let head: string[] = [];
|
|
63
|
+
const tail: string[] = [];
|
|
64
|
+
let tailBytes = 0;
|
|
65
|
+
const rest = [...this.linesArr];
|
|
66
|
+
while (rest.length > 0) {
|
|
67
|
+
const l = rest[rest.length - 1]!;
|
|
68
|
+
const b = Buffer.byteLength(l, "utf8") + 1;
|
|
69
|
+
if (tailBytes + b > keepTail && tail.length > 0) break;
|
|
70
|
+
tail.unshift(l);
|
|
71
|
+
rest.pop();
|
|
72
|
+
tailBytes += b;
|
|
73
|
+
}
|
|
74
|
+
let headBytes = 0;
|
|
75
|
+
while (rest.length > 0) {
|
|
76
|
+
const l = rest[0]!;
|
|
77
|
+
const b = Buffer.byteLength(l, "utf8") + 1;
|
|
78
|
+
if (headBytes + b > HEAD_KEEP_BYTES && head.length > 0) break;
|
|
79
|
+
head.push(l);
|
|
80
|
+
rest.shift();
|
|
81
|
+
headBytes += b;
|
|
82
|
+
}
|
|
83
|
+
const droppedBytes = lineBytes(rest);
|
|
84
|
+
this.linesArr = [...head, truncationMarker(Math.max(droppedBytes, 1)), ...tail];
|
|
85
|
+
this.totalBytes = lineBytes(this.linesArr);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Everything visible so far: complete lines plus the unterminated tail. */
|
|
89
|
+
lines(): string[] {
|
|
90
|
+
return this.capAware();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Bytes written to this stream over its lifetime (pre-truncation). */
|
|
94
|
+
totalWritten(): number {
|
|
95
|
+
return this.lifetimeBytes;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** True once the cap has been enforced at least once. */
|
|
99
|
+
isTruncated(): boolean {
|
|
100
|
+
return this.capped;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The unterminated tail, if any (exposed for tests/debugging). */
|
|
104
|
+
peekPartial(): string {
|
|
105
|
+
return this.partial;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private capAware(): string[] {
|
|
109
|
+
if (this.capped) return [...this.linesArr];
|
|
110
|
+
const out = this.partial ? [...this.linesArr, this.partial] : [...this.linesArr];
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ShellSession {
|
|
116
|
+
id: string;
|
|
117
|
+
name?: string;
|
|
118
|
+
pid: number;
|
|
119
|
+
child: ChildProcess;
|
|
120
|
+
cwd: string;
|
|
121
|
+
command: string;
|
|
122
|
+
startedAt: number;
|
|
123
|
+
exitedAt?: number;
|
|
124
|
+
exitCode?: number | null;
|
|
125
|
+
stdout: RingBuffer;
|
|
126
|
+
stderr: RingBuffer;
|
|
127
|
+
/** Output cursor for `since: "last"` — lines already returned by an output call. */
|
|
128
|
+
lastOutputOffset: number;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// ID resolution + store
|
|
133
|
+
|
|
134
|
+
/** `nextId()` → "s1", "s2", … Monotonic module counter (never resets). */
|
|
135
|
+
let counter = 0;
|
|
136
|
+
export function nextId(): string {
|
|
137
|
+
counter += 1;
|
|
138
|
+
return `s${counter}`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Test/multi-store hook: reset the id counter to n (default 0). */
|
|
142
|
+
export function resetIdCounter(n = 0): void {
|
|
143
|
+
counter = n;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function fmtStatus(s: ShellSession): string {
|
|
147
|
+
return s.exitedAt === undefined ? "running" : `exited code ${s.exitCode ?? "signal"}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** One `id name status uptime` summary line used in listings and errors. */
|
|
151
|
+
export function summarizeSession(s: ShellSession): string {
|
|
152
|
+
const name = s.name ? ` ${s.name}` : "";
|
|
153
|
+
return `${s.id}${name} ${fmtStatus(s)} ${s.command}`;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** One `id name status` listing entry (no command). */
|
|
157
|
+
export function listSessionsLine(s: ShellSession): string {
|
|
158
|
+
const name = s.name ? ` ${s.name}` : "";
|
|
159
|
+
return `${s.id}${name} ${fmtStatus(s)}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Resolve idOrName: exact session id first, then a UNIQUE name match.
|
|
164
|
+
* Throws (with the session list) on no match or an ambiguous name.
|
|
165
|
+
*/
|
|
166
|
+
export function resolveSession(store: SessionStore, idOrName: string): ShellSession {
|
|
167
|
+
const byId = store.get(idOrName);
|
|
168
|
+
if (byId) return byId;
|
|
169
|
+
const byName = store.list().filter((s) => s.name === idOrName);
|
|
170
|
+
if (byName.length === 1) return byName[0]!;
|
|
171
|
+
const listing = store.list().map(listSessionsLine).join("\n") || "(no sessions)";
|
|
172
|
+
if (byName.length > 1) {
|
|
173
|
+
throw new Error(`session name '${idOrName}' is ambiguous (${byName.length} sessions):\n${listing}`);
|
|
174
|
+
}
|
|
175
|
+
throw new Error(`no session '${idOrName}'. Active sessions:\n${listing}`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const MAX_LIVE_SESSIONS = 10;
|
|
179
|
+
const MAX_EXITED_SESSIONS = 5;
|
|
180
|
+
const EXIT_WAIT_MS = 2_000;
|
|
181
|
+
|
|
182
|
+
export class SessionStore {
|
|
183
|
+
private map = new Map<string, ShellSession>();
|
|
184
|
+
|
|
185
|
+
/** Register a session. Throws (listing live sessions) when 10 are already LIVE. */
|
|
186
|
+
add(session: ShellSession): void {
|
|
187
|
+
const live = this.list().filter((s) => s.exitedAt === undefined);
|
|
188
|
+
if (live.length >= MAX_LIVE_SESSIONS && session.exitedAt === undefined) {
|
|
189
|
+
const listing = live.map(listSessionsLine).join("\n");
|
|
190
|
+
throw new Error(
|
|
191
|
+
`refusing to start an 11th live shell session — kill one first (shell action:"kill"):\n${listing}`,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
this.map.set(session.id, session);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
get(id: string): ShellSession | undefined {
|
|
198
|
+
return this.map.get(id);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** All sessions, oldest first (insertion order). */
|
|
202
|
+
list(): ShellSession[] {
|
|
203
|
+
return [...this.map.values()];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Replace a placeholder registration with the real session. */
|
|
207
|
+
replace(id: string, session: ShellSession): void {
|
|
208
|
+
this.map.delete(id);
|
|
209
|
+
this.map.set(session.id, session);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Drop a session (spawn-failure cleanup, tests). */
|
|
213
|
+
remove(id: string): void {
|
|
214
|
+
this.map.delete(id);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Remove the OLDEST exited session if more than 5 have accumulated. */
|
|
218
|
+
evictOldestExited(): ShellSession | undefined {
|
|
219
|
+
const exited = this.list().filter((s) => s.exitedAt !== undefined);
|
|
220
|
+
if (exited.length <= MAX_EXITED_SESSIONS) return undefined;
|
|
221
|
+
const oldest = exited[0]!;
|
|
222
|
+
this.map.delete(oldest.id);
|
|
223
|
+
return oldest;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Kill every live session's process GROUP (negative pid), falling back to
|
|
228
|
+
* child.kill, then wait for exit (2s) and escalate to SIGKILL. Resolves
|
|
229
|
+
* when all processes are gone (or unkillable — never rejects).
|
|
230
|
+
*/
|
|
231
|
+
async killAll(signal: NodeJS.Signals = "SIGTERM"): Promise<void> {
|
|
232
|
+
await Promise.all(this.list().filter((s) => s.exitedAt === undefined).map((s) => killSession(s, signal)));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Kill one session's process group, await exit, escalate to SIGKILL. */
|
|
237
|
+
export async function killSession(s: ShellSession, signal: NodeJS.Signals = "SIGTERM", waitMs = EXIT_WAIT_MS): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
|
|
238
|
+
if (s.exitedAt !== undefined) {
|
|
239
|
+
return { code: s.exitCode ?? null, signal: null };
|
|
240
|
+
}
|
|
241
|
+
signalProcessGroup(s, signal);
|
|
242
|
+
return await awaitExit(s, waitMs);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function signalProcessGroup(s: ShellSession, signal: NodeJS.Signals): void {
|
|
246
|
+
// detached: true → the child leads its own process group; -pid signals the
|
|
247
|
+
// whole group (the shell AND any grandchildren). Fall back to child.kill
|
|
248
|
+
// when the group is gone (already reaped) or the call fails (Windows).
|
|
249
|
+
try {
|
|
250
|
+
process.kill(-s.pid, signal);
|
|
251
|
+
} catch {
|
|
252
|
+
try {
|
|
253
|
+
s.child.kill(signal);
|
|
254
|
+
} catch {
|
|
255
|
+
// already dead — exit handling below deals with it
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Await child exit; escalate to SIGKILL after waitMs. Never rejects. */
|
|
261
|
+
export function awaitExit(s: ShellSession, waitMs = EXIT_WAIT_MS): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
|
|
262
|
+
return new Promise((resolveP) => {
|
|
263
|
+
const child = s.child;
|
|
264
|
+
let done = false;
|
|
265
|
+
const finish = (code: number | null, sig: NodeJS.Signals | null) => {
|
|
266
|
+
if (done) return;
|
|
267
|
+
done = true;
|
|
268
|
+
clearTimeout(timer);
|
|
269
|
+
resolveP({ code, signal: sig });
|
|
270
|
+
};
|
|
271
|
+
const timer = setTimeout(() => {
|
|
272
|
+
signalProcessGroup(s, "SIGKILL");
|
|
273
|
+
// Belt and braces: if even SIGKILL's exit event never lands, stop waiting.
|
|
274
|
+
setTimeout(() => finish(null, "SIGKILL"), waitMs).unref?.();
|
|
275
|
+
}, waitMs);
|
|
276
|
+
timer.unref?.();
|
|
277
|
+
child.once("exit", (code, sig) => finish(code, sig));
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ---------------------------------------------------------------------------
|
|
282
|
+
// Session creation (the spawn seam — tests inject their own spawn fn)
|
|
283
|
+
|
|
284
|
+
export type SpawnFn = (command: string, options: { shell: boolean; cwd: string; env: NodeJS.ProcessEnv; stdio: ["pipe", "pipe", "pipe"]; detached: boolean }) => ChildProcess;
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* Spawn `command` in its own process group, wire both streams into
|
|
288
|
+
* RingBuffers, and register the session in `store`. Returns the session.
|
|
289
|
+
* Throws a clean error when the spawn itself fails (bad cwd, etc.).
|
|
290
|
+
*/
|
|
291
|
+
export function createSession(
|
|
292
|
+
store: SessionStore,
|
|
293
|
+
spawnFn: SpawnFn,
|
|
294
|
+
opts: { command: string; cwd: string; name?: string; env?: NodeJS.ProcessEnv },
|
|
295
|
+
): ShellSession {
|
|
296
|
+
if (opts.name && store.list().some((s) => s.name === opts.name && s.exitedAt === undefined)) {
|
|
297
|
+
const listing = store.list().map(listSessionsLine).join("\n");
|
|
298
|
+
throw new Error(`a live session named '${opts.name}' already exists:\n${listing}`);
|
|
299
|
+
}
|
|
300
|
+
store.add({
|
|
301
|
+
id: "",
|
|
302
|
+
name: opts.name,
|
|
303
|
+
pid: 0,
|
|
304
|
+
child: {} as ChildProcess,
|
|
305
|
+
cwd: opts.cwd,
|
|
306
|
+
command: opts.command,
|
|
307
|
+
startedAt: Date.now(),
|
|
308
|
+
stdout: new RingBuffer(),
|
|
309
|
+
stderr: new RingBuffer(),
|
|
310
|
+
lastOutputOffset: 0,
|
|
311
|
+
} as ShellSession); // placeholder so the live-cap check sees THIS session too
|
|
312
|
+
const placeholder = store.list().at(-1)!;
|
|
313
|
+
let child: ChildProcess;
|
|
314
|
+
try {
|
|
315
|
+
child = spawnFn(opts.command, {
|
|
316
|
+
shell: true,
|
|
317
|
+
cwd: opts.cwd,
|
|
318
|
+
env: opts.env ?? process.env,
|
|
319
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
320
|
+
detached: true,
|
|
321
|
+
});
|
|
322
|
+
} catch (err) {
|
|
323
|
+
// Never leave a half-registered placeholder behind.
|
|
324
|
+
store.remove(placeholder.id);
|
|
325
|
+
throw new Error(`failed to start '${opts.command}': ${err instanceof Error ? err.message : String(err)}`);
|
|
326
|
+
}
|
|
327
|
+
const session: ShellSession = {
|
|
328
|
+
...placeholder,
|
|
329
|
+
id: nextId(),
|
|
330
|
+
pid: child.pid ?? 0,
|
|
331
|
+
child,
|
|
332
|
+
};
|
|
333
|
+
store.replace(placeholder.id, session);
|
|
334
|
+
child.stdout?.on("data", (d: Buffer) => session.stdout.push(d.toString()));
|
|
335
|
+
child.stderr?.on("data", (d: Buffer) => session.stderr.push(d.toString()));
|
|
336
|
+
child.on("exit", (code) => {
|
|
337
|
+
session.exitedAt = Date.now();
|
|
338
|
+
session.exitCode = code;
|
|
339
|
+
});
|
|
340
|
+
child.on("error", (err: Error) => {
|
|
341
|
+
session.stderr.push(`[shells] spawn error: ${err.message}`);
|
|
342
|
+
});
|
|
343
|
+
return session;
|
|
344
|
+
}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// shells unit tests — fake-child logic tests + a couple of REAL spawn
|
|
2
|
+
// integration tests (posix only). No network, no sleeps beyond ms timers.
|
|
3
|
+
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { spawn as realSpawn } from "node:child_process";
|
|
6
|
+
import { EventEmitter } from "node:events";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { after, describe, it } from "node:test";
|
|
10
|
+
import {
|
|
11
|
+
RingBuffer,
|
|
12
|
+
SessionStore,
|
|
13
|
+
createSession,
|
|
14
|
+
killSession,
|
|
15
|
+
nextId,
|
|
16
|
+
resetIdCounter,
|
|
17
|
+
resolveSession,
|
|
18
|
+
TOTAL_BYTES,
|
|
19
|
+
truncationMarker,
|
|
20
|
+
type ShellSession,
|
|
21
|
+
type SpawnFn,
|
|
22
|
+
} from "../lib/sessions.js";
|
|
23
|
+
|
|
24
|
+
/** A fake child: EventEmitter surface used by createSession, capture mode. */
|
|
25
|
+
function fakeChild(): { child: any; writes: string[]; killCalls: string[]; emitExit: (code: number | null, signal?: NodeJS.Signals | null) => void } {
|
|
26
|
+
const child = new EventEmitter() as any;
|
|
27
|
+
child.pid = 42_424;
|
|
28
|
+
child.stdin = { write: (d: string) => child.__writes.push(d), get writable() { return !child.__closed; } };
|
|
29
|
+
child.stdout = new EventEmitter();
|
|
30
|
+
child.stderr = new EventEmitter();
|
|
31
|
+
child.kill = (sig: NodeJS.Signals = "SIGTERM") => {
|
|
32
|
+
child.__kills.push(sig);
|
|
33
|
+
return true;
|
|
34
|
+
};
|
|
35
|
+
child.__writes = [] as string[];
|
|
36
|
+
child.__kills = [] as string[];
|
|
37
|
+
child.__closed = false;
|
|
38
|
+
child.__emitExit = (code: number | null, signal?: NodeJS.Signals | null) => {
|
|
39
|
+
child.__closed = true;
|
|
40
|
+
child.emit("exit", code, signal ?? null);
|
|
41
|
+
};
|
|
42
|
+
return { child, writes: child.__writes, killCalls: child.__kills, emitExit: child.__emitExit };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const noopSpawn: SpawnFn = () => fakeChild().child as never;
|
|
46
|
+
|
|
47
|
+
// ── RingBuffer ──────────────────────────────────────────────────────────────
|
|
48
|
+
|
|
49
|
+
describe("RingBuffer", () => {
|
|
50
|
+
it("buffers lines including the unterminated tail", () => {
|
|
51
|
+
const rb = new RingBuffer();
|
|
52
|
+
rb.push("one\ntwo\nthr");
|
|
53
|
+
assert.deepEqual(rb.lines(), ["one", "two", "thr"]); // tail visible
|
|
54
|
+
assert.equal(rb.peekPartial(), "thr");
|
|
55
|
+
rb.push("ee\nfour\n");
|
|
56
|
+
assert.deepEqual(rb.lines(), ["one", "two", "three", "four"]);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("reports totalWritten and truncation state", () => {
|
|
60
|
+
const rb = new RingBuffer();
|
|
61
|
+
rb.push("a\n");
|
|
62
|
+
assert.equal(rb.totalWritten(), 2);
|
|
63
|
+
assert.equal(rb.isTruncated(), false);
|
|
64
|
+
rb.push("x".repeat(TOTAL_BYTES + 10));
|
|
65
|
+
assert.equal(rb.isTruncated(), true);
|
|
66
|
+
assert.ok(rb.totalWritten() > TOTAL_BYTES); // lifetime count is pre-truncation
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("keeps head + tail with a marker when the cap trips", () => {
|
|
70
|
+
const rb = new RingBuffer();
|
|
71
|
+
rb.push("HEAD-LINE\n");
|
|
72
|
+
rb.push("x".repeat(TOTAL_BYTES) + "\n");
|
|
73
|
+
rb.push("TAIL-LINE\n");
|
|
74
|
+
const lines = rb.lines();
|
|
75
|
+
assert.equal(lines[0], "HEAD-LINE");
|
|
76
|
+
assert.equal(lines.at(-1), "TAIL-LINE");
|
|
77
|
+
const marker = lines.find((l) => l.startsWith("[…"));
|
|
78
|
+
assert.ok(marker, "has a truncation marker line");
|
|
79
|
+
assert.match(marker!, /^\[… \d+(?:\.\d+)? (Ki?B|bytes) truncated …\]$/);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("truncationMarker formats", () => {
|
|
83
|
+
assert.equal(truncationMarker(5), "[… 5 bytes truncated …]");
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// ── ids + resolution ────────────────────────────────────────────────────────
|
|
88
|
+
|
|
89
|
+
describe("ids and resolveSession", () => {
|
|
90
|
+
it("nextId is monotonic; resetIdCounter resets", () => {
|
|
91
|
+
resetIdCounter(0);
|
|
92
|
+
assert.equal(nextId(), "s1");
|
|
93
|
+
assert.equal(nextId(), "s2");
|
|
94
|
+
resetIdCounter(9);
|
|
95
|
+
assert.equal(nextId(), "s10");
|
|
96
|
+
resetIdCounter();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
function session(over: Partial<ShellSession>): ShellSession {
|
|
100
|
+
return {
|
|
101
|
+
id: "s1",
|
|
102
|
+
pid: 1,
|
|
103
|
+
child: {} as never,
|
|
104
|
+
cwd: "/",
|
|
105
|
+
command: "true",
|
|
106
|
+
startedAt: Date.now(),
|
|
107
|
+
stdout: new RingBuffer(),
|
|
108
|
+
stderr: new RingBuffer(),
|
|
109
|
+
lastOutputOffset: 0,
|
|
110
|
+
...over,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
it("resolves by id first, then unique name", () => {
|
|
115
|
+
const store = new SessionStore();
|
|
116
|
+
const a = session({ id: "s1", name: "dev" });
|
|
117
|
+
const b = session({ id: "s2" });
|
|
118
|
+
store.add(a);
|
|
119
|
+
store.add(b);
|
|
120
|
+
assert.equal(resolveSession(store, "s2"), b);
|
|
121
|
+
assert.equal(resolveSession(store, "dev"), a);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("ambiguous name errors with the listing; unknown errors too", () => {
|
|
125
|
+
const store = new SessionStore();
|
|
126
|
+
store.add(session({ id: "s1", name: "dev" }));
|
|
127
|
+
store.add(session({ id: "s2", name: "dev" }));
|
|
128
|
+
assert.throws(() => resolveSession(store, "dev"), /ambiguous.*dev/s);
|
|
129
|
+
assert.throws(() => resolveSession(store, "nope"), /no session 'nope'/);
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
// ── SessionStore ────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
describe("SessionStore", () => {
|
|
136
|
+
function live(over: Partial<ShellSession>): ShellSession {
|
|
137
|
+
return {
|
|
138
|
+
id: `s${Math.random()}`,
|
|
139
|
+
pid: 1,
|
|
140
|
+
child: {} as never,
|
|
141
|
+
cwd: "/",
|
|
142
|
+
command: "true",
|
|
143
|
+
startedAt: Date.now(),
|
|
144
|
+
stdout: new RingBuffer(),
|
|
145
|
+
stderr: new RingBuffer(),
|
|
146
|
+
lastOutputOffset: 0,
|
|
147
|
+
...over,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
it("refuses an 11th live session, listing them", () => {
|
|
152
|
+
const store = new SessionStore();
|
|
153
|
+
for (let i = 0; i < 10; i++) store.add(live({ id: `s${i}` }));
|
|
154
|
+
assert.throws(() => store.add(live({ id: "s11" })), /refusing to start an 11th live shell session[\s\S]*s9/);
|
|
155
|
+
// Exited sessions don't count toward the live cap.
|
|
156
|
+
const dead = live({ id: "sx", exitedAt: Date.now(), exitCode: 0 });
|
|
157
|
+
store.add(dead);
|
|
158
|
+
assert.equal(store.list().length, 11);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("evictOldestExited keeps at most 5 exited", () => {
|
|
162
|
+
const store = new SessionStore();
|
|
163
|
+
for (let i = 0; i < 7; i++) store.add(live({ id: `d${i}`, exitedAt: 1_000 + i, exitCode: 0 }));
|
|
164
|
+
let evicted = 0;
|
|
165
|
+
while (store.evictOldestExited()) evicted++;
|
|
166
|
+
assert.equal(evicted, 2);
|
|
167
|
+
assert.equal(store.list().length, 5);
|
|
168
|
+
assert.equal(store.list()[0]!.id, "d2"); // oldest two gone
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("killAll skips exited sessions and escalates for live ones", { timeout: 10_000 }, async () => {
|
|
172
|
+
const store = new SessionStore();
|
|
173
|
+
const fc = fakeChild();
|
|
174
|
+
const s = store.list().length; // 0
|
|
175
|
+
store.add({
|
|
176
|
+
id: "s1", pid: fc.child.pid, child: fc.child, cwd: "/", command: "x",
|
|
177
|
+
startedAt: Date.now(), stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
|
|
178
|
+
});
|
|
179
|
+
store.add({
|
|
180
|
+
id: "s2", pid: 1, child: fakeChild().child, cwd: "/", command: "x",
|
|
181
|
+
startedAt: Date.now(), exitedAt: Date.now(), exitCode: 0,
|
|
182
|
+
stdout: new RingBuffer(), stderr: new RingBuffer(), lastOutputOffset: 0,
|
|
183
|
+
});
|
|
184
|
+
await store.killAll("SIGTERM");
|
|
185
|
+
// Group signal fails (bogus pid) → falls back to child.kill; escalation
|
|
186
|
+
// to SIGKILL after the 2s wait hits the live session only.
|
|
187
|
+
assert.ok(fc.killCalls.includes("SIGTERM"));
|
|
188
|
+
assert.ok(fc.killCalls.includes("SIGKILL"));
|
|
189
|
+
assert.equal(s, 0);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// ── createSession ───────────────────────────────────────────────────────────
|
|
194
|
+
|
|
195
|
+
describe("createSession", () => {
|
|
196
|
+
it("wires streams, exit, stdin; rejects duplicate live names", () => {
|
|
197
|
+
const store = new SessionStore();
|
|
198
|
+
resetIdCounter(0);
|
|
199
|
+
const fc = fakeChild();
|
|
200
|
+
const s = createSession(store, () => fc.child as never, { command: "npm run dev", cwd: "/", name: "dev" });
|
|
201
|
+
assert.equal(s.id, "s1");
|
|
202
|
+
assert.equal(s.pid, 42_424);
|
|
203
|
+
fc.child.stdout.emit("data", Buffer.from("hello\n"));
|
|
204
|
+
fc.child.stderr.emit("data", Buffer.from("oops\n"));
|
|
205
|
+
assert.deepEqual(s.stdout.lines(), ["hello"]);
|
|
206
|
+
assert.deepEqual(s.stderr.lines(), ["oops"]);
|
|
207
|
+
assert.throws(() => createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" }), /already exists/);
|
|
208
|
+
// Exit marks the session and frees the name.
|
|
209
|
+
fc.emitExit(0);
|
|
210
|
+
assert.equal(s.exitedAt !== undefined, true);
|
|
211
|
+
const again = createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" });
|
|
212
|
+
assert.equal(again.id, "s2");
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
it("spawn failure cleans up the placeholder", () => {
|
|
216
|
+
const store = new SessionStore();
|
|
217
|
+
assert.throws(() => createSession(store, () => { throw new Error("bad cwd"); }, { command: "x", cwd: "/" }), /failed to start 'x': bad cwd/);
|
|
218
|
+
assert.equal(store.list().length, 0);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("killSession escalates to SIGKILL after the wait", async () => {
|
|
222
|
+
const store = new SessionStore();
|
|
223
|
+
const fc = fakeChild(); // never emits exit on its own
|
|
224
|
+
const s = createSession(store, () => fc.child as never, { command: "sleep 30", cwd: "/" });
|
|
225
|
+
const started = Date.now();
|
|
226
|
+
const r = await killSession(s, "SIGTERM", 60);
|
|
227
|
+
assert.ok(Date.now() - started >= 50);
|
|
228
|
+
assert.equal(r.signal, "SIGKILL");
|
|
229
|
+
assert.ok(fc.killCalls.length >= 1);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
it("killSession returns early for already-exited sessions", async () => {
|
|
233
|
+
const store = new SessionStore();
|
|
234
|
+
const fc = fakeChild();
|
|
235
|
+
const s = createSession(store, () => fc.child as never, { command: "x", cwd: "/" });
|
|
236
|
+
fc.emitExit(3);
|
|
237
|
+
const r = await killSession(s);
|
|
238
|
+
assert.equal(r.code, 3);
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
// ── REAL spawn integration (posix) ──────────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
const posixIt = process.platform === "win32" ? it.skip : it;
|
|
245
|
+
|
|
246
|
+
describe("real spawns", () => {
|
|
247
|
+
const tmp = os.tmpdir();
|
|
248
|
+
|
|
249
|
+
posixIt("echo lands in the buffer via createSession", async () => {
|
|
250
|
+
const store = new SessionStore();
|
|
251
|
+
const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "echo real-hello", cwd: tmp });
|
|
252
|
+
assert.notEqual(s.pid, 0);
|
|
253
|
+
// Wait for exit + buffer flush (event-driven, capped).
|
|
254
|
+
await new Promise<void>((r) => {
|
|
255
|
+
const t = setInterval(() => {
|
|
256
|
+
if (s.exitedAt !== undefined && s.stdout.lines().length > 0) {
|
|
257
|
+
clearInterval(t);
|
|
258
|
+
r();
|
|
259
|
+
}
|
|
260
|
+
}, 25);
|
|
261
|
+
setTimeout(() => { clearInterval(t); r(); }, 5_000);
|
|
262
|
+
});
|
|
263
|
+
assert.deepEqual(s.stdout.lines(), ["real-hello"]);
|
|
264
|
+
await killSession(s, "SIGKILL", 500).catch(() => {});
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
posixIt("killAll reaps a sleep child (process group)", async () => {
|
|
268
|
+
const store = new SessionStore();
|
|
269
|
+
const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "sleep 30", cwd: tmp });
|
|
270
|
+
await store.killAll("SIGKILL");
|
|
271
|
+
assert.ok(s.exitedAt !== undefined || s.exitCode !== null || s.child.killed);
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
after(() => resetIdCounter());
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
import fs from "node:fs";
|
|
12
12
|
import os from "node:os";
|
|
13
13
|
import path from "node:path";
|
|
14
|
+
import { existsSync } from "node:fs";
|
|
15
|
+
import { resolve as resolvePath } from "node:path";
|
|
14
16
|
|
|
15
17
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
16
18
|
import { Type } from "typebox";
|
|
@@ -19,6 +21,7 @@ import { readDisabledTools } from "../../lib/tools.js";
|
|
|
19
21
|
import { skillsRoot } from "../../lib/skill-path.js";
|
|
20
22
|
|
|
21
23
|
import { formatA11ySummary, runA11yAudit } from "./lib/a11y";
|
|
24
|
+
import { formatPdfText, parsePagesParam, readPdfText } from "./lib/pdf";
|
|
22
25
|
|
|
23
26
|
import {
|
|
24
27
|
findEnvValue,
|
|
@@ -971,6 +974,37 @@ export default function piWebExtension(pi: ExtensionAPI) {
|
|
|
971
974
|
},
|
|
972
975
|
});
|
|
973
976
|
|
|
977
|
+
// ── read_pdf ─────────────────────────────────────────────────
|
|
978
|
+
pi.registerTool({
|
|
979
|
+
name: "read_pdf",
|
|
980
|
+
label: "Read PDF",
|
|
981
|
+
description:
|
|
982
|
+
"Read a local PDF file's text (vendored pdf.js engine — no external binaries, no Chrome). Params: path, pages ('3', '1-5', '2,4,6-8'; default first 5, cap 10/call). Text-only: scanned/image pages return a 'no extractable text' notice.",
|
|
983
|
+
promptSnippet: "Extract text from a local PDF",
|
|
984
|
+
promptGuidelines: [
|
|
985
|
+
"Text extraction only — scanned/image PDFs yield a notice; OCR is out of scope.",
|
|
986
|
+
"Request specific pages for big documents (cap 10 pages per call).",
|
|
987
|
+
],
|
|
988
|
+
parameters: Type.Object({
|
|
989
|
+
path: Type.String({ description: "Path to the PDF (absolute or cwd-relative)." }),
|
|
990
|
+
pages: Type.Optional(
|
|
991
|
+
Type.String({ description: 'Pages to extract: "3", "1-5", or "2,4,6-8". Default: first 5 pages (cap 10/call).' }),
|
|
992
|
+
),
|
|
993
|
+
}),
|
|
994
|
+
async execute(_id: string, params: Record<string, unknown>, signal: AbortSignal, _onUpdate: unknown, ctx: any) {
|
|
995
|
+
const cwd = cwdFromContext(ctx);
|
|
996
|
+
const rawPath = params.path as string;
|
|
997
|
+
const abs = resolvePath(cwd, rawPath);
|
|
998
|
+
if (!existsSync(abs)) throw new Error(`PDF not found: ${rawPath}`);
|
|
999
|
+
if (!/\.pdf$/i.test(abs)) throw new Error(`not a PDF (extension check): ${rawPath}`);
|
|
1000
|
+
// First parse page 1 to learn numPages cheaply, then the real slice.
|
|
1001
|
+
const probe = await readPdfText({ path: abs, pages: [1], signal });
|
|
1002
|
+
const wanted = parsePagesParam(params.pages as string | undefined, probe.totalPages);
|
|
1003
|
+
const result = wanted.length === 1 && wanted[0] === 1 ? probe : await readPdfText({ path: abs, pages: wanted, signal });
|
|
1004
|
+
return { content: [{ type: "text" as const, text: formatPdfText(result) }], details: result };
|
|
1005
|
+
},
|
|
1006
|
+
});
|
|
1007
|
+
|
|
974
1008
|
// ── web_a11y ─────────────────────────────────────────────────
|
|
975
1009
|
pi.registerTool({
|
|
976
1010
|
name: "web_a11y",
|