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,397 @@
|
|
|
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
|
+
// stdin must be an EventEmitter: createSession registers an 'error'
|
|
29
|
+
// listener on it (EPIPE containment).
|
|
30
|
+
child.stdin = Object.assign(new EventEmitter(), { write: (d: string) => child.__writes.push(d) });
|
|
31
|
+
child.stdout = new EventEmitter();
|
|
32
|
+
child.stderr = new EventEmitter();
|
|
33
|
+
child.kill = (sig: NodeJS.Signals = "SIGTERM") => {
|
|
34
|
+
child.__kills.push(sig);
|
|
35
|
+
return true;
|
|
36
|
+
};
|
|
37
|
+
child.__writes = [] as string[];
|
|
38
|
+
child.__kills = [] as string[];
|
|
39
|
+
child.__closed = false;
|
|
40
|
+
child.__emitExit = (code: number | null, signal?: NodeJS.Signals | null) => {
|
|
41
|
+
child.__closed = true;
|
|
42
|
+
child.emit("exit", code, signal ?? null);
|
|
43
|
+
};
|
|
44
|
+
return { child, writes: child.__writes, killCalls: child.__kills, emitExit: child.__emitExit };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const noopSpawn: SpawnFn = () => fakeChild().child as never;
|
|
48
|
+
|
|
49
|
+
// ── RingBuffer ──────────────────────────────────────────────────────────────
|
|
50
|
+
|
|
51
|
+
describe("RingBuffer", () => {
|
|
52
|
+
it("buffers lines including the unterminated tail", () => {
|
|
53
|
+
const rb = new RingBuffer();
|
|
54
|
+
rb.push("one\ntwo\nthr");
|
|
55
|
+
assert.deepEqual(rb.lines(), ["one", "two", "thr"]); // tail visible
|
|
56
|
+
assert.equal(rb.peekPartial(), "thr");
|
|
57
|
+
rb.push("ee\nfour\n");
|
|
58
|
+
assert.deepEqual(rb.lines(), ["one", "two", "three", "four"]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("reports totalWritten and truncation state", () => {
|
|
62
|
+
const rb = new RingBuffer();
|
|
63
|
+
rb.push("a\n");
|
|
64
|
+
assert.equal(rb.totalWritten(), 2);
|
|
65
|
+
assert.equal(rb.isTruncated(), false);
|
|
66
|
+
rb.push("x".repeat(TOTAL_BYTES + 10));
|
|
67
|
+
assert.equal(rb.isTruncated(), true);
|
|
68
|
+
assert.ok(rb.totalWritten() > TOTAL_BYTES); // lifetime count is pre-truncation
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("keeps head + tail with a marker when the cap trips", () => {
|
|
72
|
+
const rb = new RingBuffer();
|
|
73
|
+
rb.push("HEAD-LINE\n");
|
|
74
|
+
rb.push("x".repeat(TOTAL_BYTES) + "\n");
|
|
75
|
+
rb.push("TAIL-LINE\n");
|
|
76
|
+
const lines = rb.lines();
|
|
77
|
+
assert.equal(lines[0], "HEAD-LINE");
|
|
78
|
+
assert.equal(lines.at(-1), "TAIL-LINE");
|
|
79
|
+
const marker = lines.find((l) => l.startsWith("[…"));
|
|
80
|
+
assert.ok(marker, "has a truncation marker line");
|
|
81
|
+
assert.match(marker!, /^\[… \d+(?:\.\d+)? (Ki?B|bytes) truncated …\]$/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("truncationMarker formats", () => {
|
|
85
|
+
assert.equal(truncationMarker(5), "[… 5 bytes truncated …]");
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("keeps the unterminated partial line after the cap trips", () => {
|
|
89
|
+
const rb = new RingBuffer();
|
|
90
|
+
rb.push("HEAD-LINE\n");
|
|
91
|
+
rb.push("x".repeat(TOTAL_BYTES) + "\n"); // cap trips
|
|
92
|
+
rb.push("spinner…"); // no trailing newline, arrives after capping
|
|
93
|
+
assert.equal(rb.isTruncated(), true);
|
|
94
|
+
assert.match(rb.lines().at(-1)!, /^spinner…/);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// ── ids + resolution ────────────────────────────────────────────────────────
|
|
99
|
+
|
|
100
|
+
describe("ids and resolveSession", () => {
|
|
101
|
+
it("nextId is monotonic; resetIdCounter resets", () => {
|
|
102
|
+
resetIdCounter(0);
|
|
103
|
+
assert.equal(nextId(), "s1");
|
|
104
|
+
assert.equal(nextId(), "s2");
|
|
105
|
+
resetIdCounter(9);
|
|
106
|
+
assert.equal(nextId(), "s10");
|
|
107
|
+
resetIdCounter();
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
function session(over: Partial<ShellSession>): ShellSession {
|
|
111
|
+
return {
|
|
112
|
+
id: "s1",
|
|
113
|
+
pid: 1,
|
|
114
|
+
child: {} as never,
|
|
115
|
+
cwd: "/",
|
|
116
|
+
command: "true",
|
|
117
|
+
startedAt: Date.now(),
|
|
118
|
+
stdout: new RingBuffer(),
|
|
119
|
+
stderr: new RingBuffer(),
|
|
120
|
+
lastStdoutOffset: 0, lastStderrOffset: 0,
|
|
121
|
+
...over,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
it("resolves by id first, then unique name", () => {
|
|
126
|
+
const store = new SessionStore();
|
|
127
|
+
const a = session({ id: "s1", name: "dev" });
|
|
128
|
+
const b = session({ id: "s2" });
|
|
129
|
+
store.add(a);
|
|
130
|
+
store.add(b);
|
|
131
|
+
assert.equal(resolveSession(store, "s2"), b);
|
|
132
|
+
assert.equal(resolveSession(store, "dev"), a);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("ambiguous name errors with the listing; unknown errors too", () => {
|
|
136
|
+
const store = new SessionStore();
|
|
137
|
+
store.add(session({ id: "s1", name: "dev" }));
|
|
138
|
+
store.add(session({ id: "s2", name: "dev" }));
|
|
139
|
+
assert.throws(() => resolveSession(store, "dev"), /ambiguous.*dev/s);
|
|
140
|
+
assert.throws(() => resolveSession(store, "nope"), /no session 'nope'/);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("prefers a live match over an exited one with the same name", () => {
|
|
144
|
+
const store = new SessionStore();
|
|
145
|
+
const dead = session({ id: "s1", name: "dev", exitedAt: Date.now(), exitCode: 0 });
|
|
146
|
+
const live = session({ id: "s2", name: "dev" });
|
|
147
|
+
store.add(dead);
|
|
148
|
+
store.add(live);
|
|
149
|
+
assert.equal(resolveSession(store, "dev"), live);
|
|
150
|
+
// Ambiguity is judged among LIVE sessions only.
|
|
151
|
+
const live2 = session({ id: "s3", name: "dev" });
|
|
152
|
+
store.add(live2);
|
|
153
|
+
assert.throws(() => resolveSession(store, "dev"), /ambiguous \(2 sessions\)/);
|
|
154
|
+
// All matches exited → fall back to the FULL list (original semantics:
|
|
155
|
+
// ambiguity is decided over the fallback set).
|
|
156
|
+
live.exitedAt = Date.now();
|
|
157
|
+
live2.exitedAt = Date.now();
|
|
158
|
+
assert.throws(() => resolveSession(store, "dev"), /ambiguous \(3 sessions\)/);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
// ── SessionStore ────────────────────────────────────────────────────────────
|
|
163
|
+
|
|
164
|
+
describe("SessionStore", () => {
|
|
165
|
+
function live(over: Partial<ShellSession>): ShellSession {
|
|
166
|
+
return {
|
|
167
|
+
id: `s${Math.random()}`,
|
|
168
|
+
pid: 1,
|
|
169
|
+
child: {} as never,
|
|
170
|
+
cwd: "/",
|
|
171
|
+
command: "true",
|
|
172
|
+
startedAt: Date.now(),
|
|
173
|
+
stdout: new RingBuffer(),
|
|
174
|
+
stderr: new RingBuffer(),
|
|
175
|
+
lastStdoutOffset: 0, lastStderrOffset: 0,
|
|
176
|
+
...over,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
it("refuses an 11th live session, listing them", () => {
|
|
181
|
+
const store = new SessionStore();
|
|
182
|
+
for (let i = 0; i < 10; i++) store.add(live({ id: `s${i}` }));
|
|
183
|
+
assert.throws(() => store.add(live({ id: "s11" })), /refusing to start an 11th live shell session[\s\S]*s9/);
|
|
184
|
+
// Exited sessions don't count toward the live cap.
|
|
185
|
+
const dead = live({ id: "sx", exitedAt: Date.now(), exitCode: 0 });
|
|
186
|
+
store.add(dead);
|
|
187
|
+
assert.equal(store.list().length, 11);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("evictOldestExited keeps at most 5 exited", () => {
|
|
191
|
+
const store = new SessionStore();
|
|
192
|
+
for (let i = 0; i < 7; i++) store.add(live({ id: `d${i}`, exitedAt: 1_000 + i, exitCode: 0 }));
|
|
193
|
+
let evicted = 0;
|
|
194
|
+
while (store.evictOldestExited()) evicted++;
|
|
195
|
+
assert.equal(evicted, 2);
|
|
196
|
+
assert.equal(store.list().length, 5);
|
|
197
|
+
assert.equal(store.list()[0]!.id, "d2"); // oldest two gone
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
it("clear drops every session", () => {
|
|
201
|
+
const store = new SessionStore();
|
|
202
|
+
store.add(live({ id: "s1" }));
|
|
203
|
+
store.add(live({ id: "s2" }));
|
|
204
|
+
store.clear();
|
|
205
|
+
assert.equal(store.list().length, 0);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("killAll skips exited sessions and escalates for live ones", { timeout: 10_000 }, async () => {
|
|
209
|
+
const store = new SessionStore();
|
|
210
|
+
const fc = fakeChild();
|
|
211
|
+
const s = store.list().length; // 0
|
|
212
|
+
store.add({
|
|
213
|
+
id: "s1", pid: fc.child.pid, child: fc.child, cwd: "/", command: "x",
|
|
214
|
+
startedAt: Date.now(), stdout: new RingBuffer(), stderr: new RingBuffer(), lastStdoutOffset: 0, lastStderrOffset: 0,
|
|
215
|
+
});
|
|
216
|
+
store.add({
|
|
217
|
+
id: "s2", pid: 1, child: fakeChild().child, cwd: "/", command: "x",
|
|
218
|
+
startedAt: Date.now(), exitedAt: Date.now(), exitCode: 0,
|
|
219
|
+
stdout: new RingBuffer(), stderr: new RingBuffer(), lastStdoutOffset: 0, lastStderrOffset: 0,
|
|
220
|
+
});
|
|
221
|
+
await store.killAll("SIGTERM");
|
|
222
|
+
// Group signal fails (bogus pid) → falls back to child.kill; escalation
|
|
223
|
+
// to SIGKILL after the 2s wait hits the live session only.
|
|
224
|
+
assert.ok(fc.killCalls.includes("SIGTERM"));
|
|
225
|
+
assert.ok(fc.killCalls.includes("SIGKILL"));
|
|
226
|
+
assert.equal(s, 0);
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
// ── createSession ───────────────────────────────────────────────────────────
|
|
231
|
+
|
|
232
|
+
describe("createSession", () => {
|
|
233
|
+
it("wires streams, exit, stdin; rejects duplicate live names", () => {
|
|
234
|
+
const store = new SessionStore();
|
|
235
|
+
resetIdCounter(0);
|
|
236
|
+
const fc = fakeChild();
|
|
237
|
+
const s = createSession(store, () => fc.child as never, { command: "npm run dev", cwd: "/", name: "dev" });
|
|
238
|
+
assert.equal(s.id, "s1");
|
|
239
|
+
assert.equal(s.pid, 42_424);
|
|
240
|
+
fc.child.stdout.emit("data", Buffer.from("hello\n"));
|
|
241
|
+
fc.child.stderr.emit("data", Buffer.from("oops\n"));
|
|
242
|
+
assert.deepEqual(s.stdout.lines(), ["hello"]);
|
|
243
|
+
assert.deepEqual(s.stderr.lines(), ["oops"]);
|
|
244
|
+
assert.throws(() => createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" }), /already exists/);
|
|
245
|
+
// Exit marks the session and frees the name.
|
|
246
|
+
fc.emitExit(0);
|
|
247
|
+
assert.equal(s.exitedAt !== undefined, true);
|
|
248
|
+
const again = createSession(store, noopSpawn, { command: "x", cwd: "/", name: "dev" });
|
|
249
|
+
assert.equal(again.id, "s2");
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("spawn failure cleans up the placeholder", () => {
|
|
253
|
+
const store = new SessionStore();
|
|
254
|
+
assert.throws(() => createSession(store, () => { throw new Error("bad cwd"); }, { command: "x", cwd: "/" }), /failed to start 'x': bad cwd/);
|
|
255
|
+
assert.equal(store.list().length, 0);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
it("marks an async spawn failure exited and never signals pi's own group", async () => {
|
|
259
|
+
const store = new SessionStore();
|
|
260
|
+
resetIdCounter(0);
|
|
261
|
+
// Async failure: child emits 'error' with pid undefined (bad cwd etc.).
|
|
262
|
+
const fc = fakeChild();
|
|
263
|
+
fc.child.pid = undefined;
|
|
264
|
+
const s = createSession(store, () => {
|
|
265
|
+
queueMicrotask(() => fc.child.emit("error", new Error("ENOENT: spawn bad-cwd")));
|
|
266
|
+
return fc.child as never;
|
|
267
|
+
}, { command: "x", cwd: "/nonexistent-cwd" });
|
|
268
|
+
assert.equal(s.pid, 0);
|
|
269
|
+
await new Promise<void>((r) => setImmediate(r));
|
|
270
|
+
assert.ok(s.exitedAt !== undefined, "spawn failure marks the session exited");
|
|
271
|
+
assert.equal(s.exitCode, null);
|
|
272
|
+
|
|
273
|
+
// kill on the zombie resolves early — nothing to signal, and never
|
|
274
|
+
// process.kill(-0) (== kill(0) == SIGTERM for every process in pi's
|
|
275
|
+
// own group).
|
|
276
|
+
const origKill = process.kill;
|
|
277
|
+
const groupCalls: [number | undefined, NodeJS.Signals][] = [];
|
|
278
|
+
(process as any).kill = (pid: number | undefined, sig?: NodeJS.Signals) => {
|
|
279
|
+
if (typeof pid === "number" && pid <= 0) groupCalls.push([pid, sig as NodeJS.Signals]);
|
|
280
|
+
return true;
|
|
281
|
+
};
|
|
282
|
+
try {
|
|
283
|
+
const r = await killSession(s, "SIGKILL", 50);
|
|
284
|
+
assert.deepEqual(r, { code: null, signal: null }); // early exit, no signal
|
|
285
|
+
assert.deepEqual(groupCalls, [], "no negative/zero-pid group signal may be issued");
|
|
286
|
+
} finally {
|
|
287
|
+
(process as any).kill = origKill;
|
|
288
|
+
}
|
|
289
|
+
assert.deepEqual(fc.killCalls, [] as string[], "exited session is not signalled");
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("kill on a live pid-0 session falls back to child.kill, not the host group", async () => {
|
|
293
|
+
const store = new SessionStore();
|
|
294
|
+
// Race window: session registered, spawn 'error' not yet fired → still
|
|
295
|
+
// live with pid 0. killSession must reach for child.kill only.
|
|
296
|
+
const fc = fakeChild();
|
|
297
|
+
fc.child.pid = undefined;
|
|
298
|
+
const s = createSession(store, () => fc.child as never, { command: "x", cwd: "/" });
|
|
299
|
+
assert.equal(s.pid, 0);
|
|
300
|
+
const origKill = process.kill;
|
|
301
|
+
const groupCalls: [number | undefined, NodeJS.Signals][] = [];
|
|
302
|
+
(process as any).kill = (pid: number | undefined, sig?: NodeJS.Signals) => {
|
|
303
|
+
if (typeof pid === "number" && pid <= 0) groupCalls.push([pid, sig as NodeJS.Signals]);
|
|
304
|
+
return true;
|
|
305
|
+
};
|
|
306
|
+
try {
|
|
307
|
+
const r = await killSession(s, "SIGTERM", 50);
|
|
308
|
+
assert.equal(r.signal, "SIGKILL"); // escalated: fake never exits
|
|
309
|
+
assert.deepEqual(groupCalls, [], "no negative/zero-pid group signal may be issued");
|
|
310
|
+
} finally {
|
|
311
|
+
(process as any).kill = origKill;
|
|
312
|
+
}
|
|
313
|
+
assert.ok(fc.killCalls.includes("SIGTERM"));
|
|
314
|
+
assert.ok(fc.killCalls.includes("SIGKILL"), "falls back to child.kill");
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
it("frees the name after an async spawn failure", async () => {
|
|
318
|
+
const store = new SessionStore();
|
|
319
|
+
const fc = fakeChild();
|
|
320
|
+
fc.child.pid = undefined;
|
|
321
|
+
createSession(store, () => {
|
|
322
|
+
queueMicrotask(() => fc.child.emit("error", new Error("ENOENT")));
|
|
323
|
+
return fc.child as never;
|
|
324
|
+
}, { command: "x", cwd: "/", name: "dev" });
|
|
325
|
+
await new Promise<void>((r) => setImmediate(r));
|
|
326
|
+
const again = createSession(store, noopSpawn, { command: "y", cwd: "/", name: "dev" });
|
|
327
|
+
assert.ok(again.id.length > 0);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
it("killSession escalates to SIGKILL after the wait", async () => {
|
|
331
|
+
const store = new SessionStore();
|
|
332
|
+
const fc = fakeChild(); // never emits exit on its own
|
|
333
|
+
const s = createSession(store, () => fc.child as never, { command: "sleep 30", cwd: "/" });
|
|
334
|
+
const started = Date.now();
|
|
335
|
+
const r = await killSession(s, "SIGTERM", 60);
|
|
336
|
+
assert.ok(Date.now() - started >= 50);
|
|
337
|
+
assert.equal(r.signal, "SIGKILL");
|
|
338
|
+
assert.ok(fc.killCalls.length >= 1);
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
it("killSession returns early for already-exited sessions", async () => {
|
|
342
|
+
const store = new SessionStore();
|
|
343
|
+
const fc = fakeChild();
|
|
344
|
+
const s = createSession(store, () => fc.child as never, { command: "x", cwd: "/" });
|
|
345
|
+
fc.emitExit(3);
|
|
346
|
+
const r = await killSession(s);
|
|
347
|
+
assert.equal(r.code, 3);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
it("contains a stdin EPIPE that races child exit (no uncaught error)", () => {
|
|
351
|
+
const store = new SessionStore();
|
|
352
|
+
const fc = fakeChild();
|
|
353
|
+
const s = createSession(store, () => fc.child as never, { command: "sh -c 'exit 0'", cwd: "/" });
|
|
354
|
+
fc.emitExit(0);
|
|
355
|
+
// A write that raced the exit already EPIPEd: the 'error' event lands on
|
|
356
|
+
// stdin with no writer left. On a real child that would be an
|
|
357
|
+
// uncaughtException killing pi; on an EventEmitter, emitting 'error'
|
|
358
|
+
// with no listener THROWS — so doesNotThrow is the no-crash assertion.
|
|
359
|
+
assert.doesNotThrow(() => fc.child.stdin.emit("error", new Error("EPIPE")));
|
|
360
|
+
assert.deepEqual(s.stderr.lines(), ["[shells] stdin write failed (process exited)"]);
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// ── REAL spawn integration (posix) ──────────────────────────────────────────
|
|
365
|
+
|
|
366
|
+
const posixIt = process.platform === "win32" ? it.skip : it;
|
|
367
|
+
|
|
368
|
+
describe("real spawns", () => {
|
|
369
|
+
const tmp = os.tmpdir();
|
|
370
|
+
|
|
371
|
+
posixIt("echo lands in the buffer via createSession", async () => {
|
|
372
|
+
const store = new SessionStore();
|
|
373
|
+
const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "echo real-hello", cwd: tmp });
|
|
374
|
+
assert.notEqual(s.pid, 0);
|
|
375
|
+
// Wait for exit + buffer flush (event-driven, capped).
|
|
376
|
+
await new Promise<void>((r) => {
|
|
377
|
+
const t = setInterval(() => {
|
|
378
|
+
if (s.exitedAt !== undefined && s.stdout.lines().length > 0) {
|
|
379
|
+
clearInterval(t);
|
|
380
|
+
r();
|
|
381
|
+
}
|
|
382
|
+
}, 25);
|
|
383
|
+
setTimeout(() => { clearInterval(t); r(); }, 5_000);
|
|
384
|
+
});
|
|
385
|
+
assert.deepEqual(s.stdout.lines(), ["real-hello"]);
|
|
386
|
+
await killSession(s, "SIGKILL", 500).catch(() => {});
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
posixIt("killAll reaps a sleep child (process group)", async () => {
|
|
390
|
+
const store = new SessionStore();
|
|
391
|
+
const s = createSession(store, realSpawn as unknown as SpawnFn, { command: "sleep 30", cwd: tmp });
|
|
392
|
+
await store.killAll("SIGKILL");
|
|
393
|
+
assert.ok(s.exitedAt !== undefined || s.exitCode !== null || s.child.killed);
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
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",
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// read_pdf — local PDF text extraction via the vendored pdf.js build.
|
|
2
|
+
//
|
|
3
|
+
// ponytail: the plan's CDP-viewer path was live-probed and is DEAD — headless
|
|
4
|
+
// Chrome renders file:// PDFs as a blank frame (out-of-process viewer never
|
|
5
|
+
// paints) and --virtual-time-budget hangs outright (2026-10-06). The honest
|
|
6
|
+
// text-only shape is the vendored pdf.js engine (vendor/pdfjs/README): zero
|
|
7
|
+
// deps, zero external binaries, workerless. Page IMAGES are out of scope —
|
|
8
|
+
// scanned PDFs come back as "no extractable text" with that explanation.
|
|
9
|
+
|
|
10
|
+
import { readFileSync } from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
|
|
14
|
+
// ── Shapes ──────────────────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
export interface PdfPageText {
|
|
17
|
+
page: number;
|
|
18
|
+
lines: string[];
|
|
19
|
+
chars: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PdfReadResult {
|
|
23
|
+
path: string;
|
|
24
|
+
totalPages: number;
|
|
25
|
+
pages: PdfPageText[];
|
|
26
|
+
/** Pages where text extraction found nothing (scanned/image PDFs). */
|
|
27
|
+
emptyPages: number[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ReadPdfOpts {
|
|
31
|
+
path: string;
|
|
32
|
+
/** 1-based pages to extract, pre-validated by the caller. */
|
|
33
|
+
pages: number[];
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
/** Test seam — swap the vendored engine. */
|
|
36
|
+
engine?: PdfEngine;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The slice of the pdf.js API the tool uses. */
|
|
40
|
+
export interface PdfEngine {
|
|
41
|
+
getDocument(src: { data: Uint8Array; verbosity?: number }): { promise: Promise<PdfDocument> };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PdfDocument {
|
|
45
|
+
numPages: number;
|
|
46
|
+
getPage(n: number): Promise<PdfPage>;
|
|
47
|
+
destroy?(): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PdfPage {
|
|
51
|
+
getTextContent(): Promise<{ items: Array<{ str?: string; transform?: number[] }> }>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ── Engine load (lazy — never on the entry import graph, vendor/axe rule) ──
|
|
55
|
+
|
|
56
|
+
let cachedEngine: PdfEngine | undefined;
|
|
57
|
+
|
|
58
|
+
export async function loadPdfEngine(): Promise<PdfEngine> {
|
|
59
|
+
if (cachedEngine) return cachedEngine;
|
|
60
|
+
// fileURLToPath(import.meta.url) → lib/pdf.ts; vendor sits at ../vendor.
|
|
61
|
+
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), "../vendor/pdfjs/pdf.min.mjs");
|
|
62
|
+
// Lazily dynamic-import the vendored module by FILE URL so the bundler /
|
|
63
|
+
// typechecker never sees a static dependency.
|
|
64
|
+
// pathToFileURL (not string concat): spaces/`#` in the install path must
|
|
65
|
+
// be %-encoded or the lazy pdf.js import resolves a broken URL.
|
|
66
|
+
const mod = (await import(pathToFileURL(file).href)) as PdfEngine & Record<string, unknown>;
|
|
67
|
+
cachedEngine = mod;
|
|
68
|
+
return mod;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Test hook: forget the cached engine (module state outlives a test). */
|
|
72
|
+
export function resetPdfEngineCache(): void {
|
|
73
|
+
cachedEngine = undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ── Page text ───────────────────────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Reconstruct reading-order lines from pdf.js text items: group by rounded
|
|
80
|
+
* baseline y (desc order — PDF y grows upward), then sort runs by x within a
|
|
81
|
+
* line. Exported for tests.
|
|
82
|
+
*/
|
|
83
|
+
export function itemsToLines(items: Array<{ str?: string; transform?: number[] }>): string[] {
|
|
84
|
+
const lines = new Map<number, Array<{ x: number; s: string }>>();
|
|
85
|
+
for (const item of items) {
|
|
86
|
+
if (!item.str) continue;
|
|
87
|
+
const t = item.transform;
|
|
88
|
+
if (!t) continue;
|
|
89
|
+
const y = Math.round(t[5]!);
|
|
90
|
+
if (!lines.has(y)) lines.set(y, []);
|
|
91
|
+
lines.get(y)!.push({ x: t[4]!, s: item.str });
|
|
92
|
+
}
|
|
93
|
+
return [...lines.entries()]
|
|
94
|
+
.sort((a, b) => b[0] - a[0])
|
|
95
|
+
.map(([, parts]) =>
|
|
96
|
+
parts
|
|
97
|
+
.sort((p, q) => p.x - q.x)
|
|
98
|
+
.map((p) => p.s)
|
|
99
|
+
.join(" ")
|
|
100
|
+
.replace(/ +/g, " ")
|
|
101
|
+
.trim(),
|
|
102
|
+
)
|
|
103
|
+
.filter((l) => l.length > 0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Extract text for the requested pages. One engine instantiation per call. */
|
|
107
|
+
export async function readPdfText(opts: ReadPdfOpts): Promise<PdfReadResult> {
|
|
108
|
+
const engine = opts.engine ?? (await loadPdfEngine());
|
|
109
|
+
const data = new Uint8Array(readFileSync(opts.path));
|
|
110
|
+
// verbosity 0 (ERRORS) silences the benign canvas/DOMMatrix polyfill
|
|
111
|
+
// warnings the legacy build prints on Node (text extraction needs none of
|
|
112
|
+
// them — those gates only matter for page RENDERING, which we don't do).
|
|
113
|
+
const doc = await engine.getDocument({ data, verbosity: 0 }).promise;
|
|
114
|
+
try {
|
|
115
|
+
const pages: PdfPageText[] = [];
|
|
116
|
+
const emptyPages: number[] = [];
|
|
117
|
+
for (const n of opts.pages) {
|
|
118
|
+
if (n < 1 || n > doc.numPages) throw new Error(`page ${n} out of range (1-${doc.numPages})`);
|
|
119
|
+
if (opts.signal?.aborted) throw new Error("read_pdf aborted");
|
|
120
|
+
const page = await doc.getPage(n);
|
|
121
|
+
const tc = await page.getTextContent();
|
|
122
|
+
const lines = itemsToLines(tc.items);
|
|
123
|
+
const chars = lines.reduce((a, l) => a + l.length, 0);
|
|
124
|
+
pages.push({ page: n, lines, chars });
|
|
125
|
+
if (chars === 0) emptyPages.push(n);
|
|
126
|
+
}
|
|
127
|
+
return { path: opts.path, totalPages: doc.numPages, pages, emptyPages };
|
|
128
|
+
} finally {
|
|
129
|
+
await doc.destroy?.().catch(() => {});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ── Formatting ──────────────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
const MAX_CHARS_PER_PAGE = 16_000;
|
|
136
|
+
|
|
137
|
+
/** Model-facing text. Exported for tests. */
|
|
138
|
+
export function formatPdfText(result: PdfReadResult): string {
|
|
139
|
+
const lines = [`${result.path} — ${result.totalPages} page(s), showing ${result.pages.length}`];
|
|
140
|
+
for (const page of result.pages) {
|
|
141
|
+
lines.push("", `── page ${page.page} ──`);
|
|
142
|
+
let budget = MAX_CHARS_PER_PAGE;
|
|
143
|
+
for (const l of page.lines) {
|
|
144
|
+
if (budget <= 0) {
|
|
145
|
+
lines.push(`[… page ${page.page} truncated at ${MAX_CHARS_PER_PAGE} chars …]`);
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
const slice = l.length > budget ? l.slice(0, budget) : l;
|
|
149
|
+
lines.push(slice);
|
|
150
|
+
budget -= slice.length + 1;
|
|
151
|
+
}
|
|
152
|
+
if (page.chars === 0) lines.push("(no extractable text — likely a scanned/image page)");
|
|
153
|
+
}
|
|
154
|
+
if (result.emptyPages.length > 0) {
|
|
155
|
+
lines.push(`[empty pages: ${result.emptyPages.join(", ")}]`);
|
|
156
|
+
}
|
|
157
|
+
return lines.join("\n");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Parse a `pages` param: "3" | "1-5" | "2,4,6-8" → 1-based list (cap 10,
|
|
161
|
+
* caller-enforced). Exported for tests. */
|
|
162
|
+
export function parsePagesParam(raw: string | undefined, totalPages: number): number[] {
|
|
163
|
+
if (!raw || !raw.trim()) {
|
|
164
|
+
return Array.from({ length: Math.min(5, totalPages) }, (_, i) => i + 1);
|
|
165
|
+
}
|
|
166
|
+
const out: number[] = [];
|
|
167
|
+
for (const part of raw.split(",")) {
|
|
168
|
+
const p = part.trim();
|
|
169
|
+
const range = /^(\d+)-(\d+)$/.exec(p);
|
|
170
|
+
if (range) {
|
|
171
|
+
const a = Number(range[1]);
|
|
172
|
+
const b = Number(range[2]);
|
|
173
|
+
for (let n = a; n <= b; n++) out.push(n);
|
|
174
|
+
} else if (/^\d+$/.test(p)) {
|
|
175
|
+
out.push(Number(p));
|
|
176
|
+
} else {
|
|
177
|
+
throw new Error(`invalid pages spec "${part}" — use "3", "1-5", or "2,4,6-8"`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const unique = [...new Set(out)].filter((n) => n >= 1 && n <= totalPages);
|
|
181
|
+
if (unique.length === 0) throw new Error(`no valid pages in "${raw}" (document has ${totalPages} page(s))`);
|
|
182
|
+
return unique.slice(0, 10);
|
|
183
|
+
}
|
|
@@ -13,6 +13,7 @@ import webExtension from "../index";
|
|
|
13
13
|
const ALL_TOOLS = [
|
|
14
14
|
"web_search", "web_extract", "web_map", "web_crawl", "web_screenshot", "web_pdf",
|
|
15
15
|
"web_interact", "web_research", "web_image", "web_chat", "web_status", "web_a11y",
|
|
16
|
+
"read_pdf",
|
|
16
17
|
];
|
|
17
18
|
|
|
18
19
|
function harness(opts: { disabledTools?: string[]; activeTools?: string[] } = {}) {
|
|
@@ -71,7 +72,7 @@ describe("web module ceulen contract", () => {
|
|
|
71
72
|
else process.env.PI_CODING_AGENT_DIR = oldAgentDir;
|
|
72
73
|
});
|
|
73
74
|
|
|
74
|
-
it("registers exactly the
|
|
75
|
+
it("registers exactly the thirteen web tools (12 web_* + read_pdf)", () => {
|
|
75
76
|
const { tools } = harness();
|
|
76
77
|
assert.deepEqual(Object.keys(tools).sort(), [...ALL_TOOLS].sort());
|
|
77
78
|
});
|