ceulen 0.11.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 +100 -1
- package/extensions/index.ts +5 -1
- package/extensions/lib/env.test.ts +147 -0
- package/extensions/lib/env.ts +180 -0
- package/extensions/lib/order.test.ts +74 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +23 -4
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/lib/config.ts +8 -3
- package/extensions/modules/a2a/test/configPanel.test.ts +7 -4
- package/extensions/modules/advisor/index.ts +6 -3
- package/extensions/modules/advisor/test/module.test.ts +31 -0
- package/extensions/modules/classifier/index.ts +55 -1
- package/extensions/modules/classifier/test/classifier.test.ts +62 -0
- 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 +158 -3
- 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/freshness.test.ts +41 -1
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- package/extensions/modules/repair/test/readers.test.ts +291 -0
- package/extensions/modules/repair/test/settings.test.ts +2 -1
- package/extensions/modules/router/configPanel.ts +4 -4
- package/extensions/modules/router/index.ts +1 -1
- package/extensions/modules/router/lib/config.ts +9 -4
- package/extensions/modules/router/lib/systemone.ts +17 -4
- package/extensions/modules/router/test/unit.test.ts +46 -1
- package/extensions/modules/rules/index.ts +13 -3
- package/extensions/modules/rules/lib/rules.ts +24 -12
- package/extensions/modules/rules/test/lib.test.ts +20 -0
- package/extensions/modules/rules/test/module.test.ts +21 -0
- 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/subagent/index.ts +11 -5
- package/extensions/modules/subagent/lib/herdr.ts +5 -0
- package/extensions/modules/subagent/lib/routing.ts +31 -8
- package/extensions/modules/subagent/lib/runner.ts +8 -2
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +34 -0
- package/extensions/modules/web/lib/pdf.ts +181 -0
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/extension.test.ts +2 -1
- package/extensions/modules/web/test/settings.test.ts +6 -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,210 @@
|
|
|
1
|
+
// shells — background shell sessions (Claude Code BashOutput/KillShell +
|
|
2
|
+
// Codex unified_exec parity). ONE `shell` tool over actions:
|
|
3
|
+
// start/list/output/stdin/kill. Sessions live for THIS pi session only —
|
|
4
|
+
// killed on session_shutdown, cleared on session_start. Plan mode blocks the
|
|
5
|
+
// tool (plan/lib/plan-tools.ts BLOCKED_TOOLS).
|
|
6
|
+
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { Type } from "typebox";
|
|
11
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
12
|
+
import {
|
|
13
|
+
createSession,
|
|
14
|
+
killSession,
|
|
15
|
+
resolveSession,
|
|
16
|
+
SessionStore,
|
|
17
|
+
type ShellSession,
|
|
18
|
+
} from "./lib/sessions.js";
|
|
19
|
+
|
|
20
|
+
const ACTION_ENUM = ["start", "list", "output", "stdin", "kill"] as const;
|
|
21
|
+
type Action = (typeof ACTION_ENUM)[number];
|
|
22
|
+
|
|
23
|
+
/** Default lines shown per output call. */
|
|
24
|
+
const OUTPUT_LINES_DEFAULT = 100;
|
|
25
|
+
/** Hard cap on lines per output call (the ring itself is the real bound). */
|
|
26
|
+
const OUTPUT_LINES_MAX = 1000;
|
|
27
|
+
|
|
28
|
+
function requireString(params: Record<string, unknown>, key: string, action: Action): string {
|
|
29
|
+
const v = params[key];
|
|
30
|
+
if (typeof v !== "string" || v.length === 0) {
|
|
31
|
+
throw new Error(`action:"${action}" requires a string "${key}" param`);
|
|
32
|
+
}
|
|
33
|
+
return v;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function requireSession(params: Record<string, unknown>, store: SessionStore, action: Action): ShellSession {
|
|
37
|
+
const idOrName = params.id ?? params.name;
|
|
38
|
+
if (typeof idOrName !== "string" || idOrName.length === 0) {
|
|
39
|
+
throw new Error(`action:"${action}" requires a session "id" (or "name") — use action:"list" to see sessions`);
|
|
40
|
+
}
|
|
41
|
+
return resolveSession(store, idOrName);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Trim one line for list output. */
|
|
45
|
+
function lastLine(buf: { lines(): string[] }): string {
|
|
46
|
+
const lines = buf.lines();
|
|
47
|
+
const last = lines.at(-1) ?? "";
|
|
48
|
+
return last.length > 80 ? `${last.slice(0, 77)}…` : last;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function renderList(store: SessionStore): string {
|
|
52
|
+
const sessions = store.list();
|
|
53
|
+
if (sessions.length === 0) return "(no sessions)";
|
|
54
|
+
const lines = sessions.map((s) => {
|
|
55
|
+
const name = s.name ? ` ${s.name}` : "";
|
|
56
|
+
const status = s.exitedAt === undefined ? "running" : `exited code ${s.exitCode ?? "signal"}`;
|
|
57
|
+
const uptime = `${Math.max(0, Math.round(((s.exitedAt ?? Date.now()) - s.startedAt) / 1000))}s`;
|
|
58
|
+
const kb = Math.round((s.stdout.totalWritten() + s.stderr.totalWritten()) / 1024);
|
|
59
|
+
return `${s.id}${name} ${status} ${uptime} ${kb}KB ${lastLine(s.stdout)}`;
|
|
60
|
+
});
|
|
61
|
+
return lines.join("\n");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function renderOutput(session: ShellSession, params: Record<string, unknown>): string {
|
|
65
|
+
const max = Math.min(Math.max(1, Number(params.lines ?? OUTPUT_LINES_DEFAULT) || OUTPUT_LINES_DEFAULT), OUTPUT_LINES_MAX);
|
|
66
|
+
const since = params.since === "last" ? "last" : "start";
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
let truncated = false;
|
|
69
|
+
for (const [label, buf] of [
|
|
70
|
+
["stdout", session.stdout],
|
|
71
|
+
["stderr", session.stderr],
|
|
72
|
+
] as const) {
|
|
73
|
+
const all = buf.lines();
|
|
74
|
+
const offset = since === "last" ? session.lastOutputOffset : 0;
|
|
75
|
+
const fresh = all.slice(Math.max(0, offset));
|
|
76
|
+
if (fresh.length === 0) continue;
|
|
77
|
+
const shown = fresh.slice(-max);
|
|
78
|
+
if (fresh.length > shown.length) truncated = true;
|
|
79
|
+
out.push(`── ${label}${since === "last" ? " (new)" : ""} ──`, ...shown);
|
|
80
|
+
}
|
|
81
|
+
// Advance the cursor ONLY on since:"last" reads.
|
|
82
|
+
if (since === "last") session.lastOutputOffset = Math.max(session.stdout.lines().length, session.lastOutputOffset);
|
|
83
|
+
if (out.length === 0) return `${session.id}: no ${since === "last" ? "new " : ""}output yet`;
|
|
84
|
+
const totalLines = session.stdout.lines().length + session.stderr.lines().length;
|
|
85
|
+
out.push(`── total ${totalLines} line(s)${truncated || session.stdout.isTruncated() || session.stderr.isTruncated() ? ", buffer truncated" : ""} ──`);
|
|
86
|
+
return out.join("\n");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export default function shellsModule(pi: ExtensionAPI): void {
|
|
90
|
+
const store = new SessionStore();
|
|
91
|
+
|
|
92
|
+
pi.on("session_start", () => {
|
|
93
|
+
// A fresh session can't reach children from a replaced one.
|
|
94
|
+
store.list().length = 0; // ponytail: killAll already ran on shutdown; plain clear
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
pi.on("session_shutdown", () => {
|
|
98
|
+
// Fire-and-forget: the session is going away regardless (advisor
|
|
99
|
+
// self-disarm precedent). Never blocks the shutdown path.
|
|
100
|
+
void store.killAll("SIGTERM").catch(() => {});
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
pi.registerTool({
|
|
104
|
+
name: "shell",
|
|
105
|
+
label: "Shell",
|
|
106
|
+
defaultActive: !readDisabledTools().has("shell"),
|
|
107
|
+
description: [
|
|
108
|
+
"Run a shell command as a PERSISTENT background session and interact with it across tool calls (dev servers, watchers, long builds). Actions:",
|
|
109
|
+
'- start: {command, name?, cwd?} — spawn in its own process group; returns an id ("s1"…).',
|
|
110
|
+
'- list: every session with id/name, status (running | exited code N), uptime, buffered KB, last line.',
|
|
111
|
+
'- output: {id, lines? (default 100), since?: "start"|"last"} — buffered stdout/stderr (separate sections); since:"last" returns only lines after the previous output call.',
|
|
112
|
+
'- stdin: {id, data, newline? (default true)} — write to the process\'s stdin.',
|
|
113
|
+
'- kill: {id, signal? ("SIGTERM"|"SIGKILL", default TERM)} — kill the process GROUP (children die too).',
|
|
114
|
+
"",
|
|
115
|
+
"Sessions live only for this pi session: killed on shutdown, not persisted. Output is ring-buffered (256 KB/stream, head+tail kept). Blocked in plan mode.",
|
|
116
|
+
].join("\n"),
|
|
117
|
+
promptSnippet: "Persistent background shell sessions: start/list/output/stdin/kill",
|
|
118
|
+
promptGuidelines: [
|
|
119
|
+
'Poll with action:"output" after starting a long process; use since:"last" to fetch only new lines.',
|
|
120
|
+
"Prefer the regular bash tool for one-shot commands — sessions are for processes that keep running.",
|
|
121
|
+
"A dev server started here stays up across tool calls; kill it when done.",
|
|
122
|
+
],
|
|
123
|
+
parameters: Type.Object({
|
|
124
|
+
action: Type.Union(
|
|
125
|
+
ACTION_ENUM.map((a) => Type.Literal(a)),
|
|
126
|
+
{ description: "Operation to perform." },
|
|
127
|
+
),
|
|
128
|
+
command: Type.Optional(Type.String({ description: 'Shell command (start), e.g. "npm run dev".' })),
|
|
129
|
+
name: Type.Optional(Type.String({ description: "Your own alias for the session (start); usable instead of id later. Must be unique among live sessions." })),
|
|
130
|
+
cwd: Type.Optional(Type.String({ description: "Working directory (start; default the session cwd)." })),
|
|
131
|
+
id: Type.Optional(Type.String({ description: "Session id (output/stdin/kill) or name — from action:\"list\"." })),
|
|
132
|
+
lines: Type.Optional(Type.Number({ description: "output: max lines per stream (default 100, cap 1000)." })),
|
|
133
|
+
since: Type.Optional(
|
|
134
|
+
Type.Union([Type.Literal("start"), Type.Literal("last")], { description: 'output: "last" returns only lines since the previous output call.' }),
|
|
135
|
+
),
|
|
136
|
+
data: Type.Optional(Type.String({ description: "stdin: bytes to write." })),
|
|
137
|
+
newline: Type.Optional(Type.Boolean({ description: "stdin: append \\n (default true)." })),
|
|
138
|
+
signal: Type.Optional(
|
|
139
|
+
Type.Union([Type.Literal("SIGTERM"), Type.Literal("SIGKILL")], { description: "kill: signal (default SIGTERM)." }),
|
|
140
|
+
),
|
|
141
|
+
}),
|
|
142
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx: ExtensionContext) {
|
|
143
|
+
const action = params.action as Action;
|
|
144
|
+
const cwd = ctx?.cwd || process.cwd();
|
|
145
|
+
try {
|
|
146
|
+
switch (action) {
|
|
147
|
+
case "start": {
|
|
148
|
+
const command = requireString(params, "command", "start");
|
|
149
|
+
const session = createSession(store, spawn, {
|
|
150
|
+
command,
|
|
151
|
+
cwd: path.resolve(cwd, (params.cwd as string | undefined) ?? "."),
|
|
152
|
+
name: typeof params.name === "string" && params.name.length > 0 ? params.name : undefined,
|
|
153
|
+
});
|
|
154
|
+
const label = session.name ? ` "${session.name}"` : "";
|
|
155
|
+
return {
|
|
156
|
+
content: [
|
|
157
|
+
{
|
|
158
|
+
type: "text",
|
|
159
|
+
text: `started ${session.id}${label} pid ${session.pid} — ${command}\npoll with shell action:"output" id:"${session.id}"; stop with action:"kill".`,
|
|
160
|
+
},
|
|
161
|
+
],
|
|
162
|
+
details: { action, id: session.id, pid: session.pid },
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
case "list": {
|
|
166
|
+
return { content: [{ type: "text", text: renderList(store) }], details: { action, count: store.list().length } };
|
|
167
|
+
}
|
|
168
|
+
case "output": {
|
|
169
|
+
const session = requireSession(params, store, "output");
|
|
170
|
+
return {
|
|
171
|
+
content: [{ type: "text", text: renderOutput(session, params) }],
|
|
172
|
+
details: { action, id: session.id },
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
case "stdin": {
|
|
176
|
+
const session = requireSession(params, store, "stdin");
|
|
177
|
+
const data = requireString(params, "data", "stdin");
|
|
178
|
+
const stdin = session.child.stdin;
|
|
179
|
+
if (!stdin || session.exitedAt !== undefined) {
|
|
180
|
+
throw new Error(`process not reading stdin (exited or stdin closed): ${session.id}`);
|
|
181
|
+
}
|
|
182
|
+
stdin.write(data + (params.newline === false ? "" : "\n"));
|
|
183
|
+
return {
|
|
184
|
+
content: [{ type: "text", text: `wrote ${data.length + (params.newline === false ? 0 : 1)} byte(s) to ${session.id}` }],
|
|
185
|
+
details: { action, id: session.id },
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
case "kill": {
|
|
189
|
+
const session = requireSession(params, store, "kill");
|
|
190
|
+
const sig = (params.signal as "SIGTERM" | "SIGKILL" | undefined) ?? "SIGTERM";
|
|
191
|
+
const result = await killSession(session, sig);
|
|
192
|
+
// Free the slot: evict exited sessions beyond the keep count.
|
|
193
|
+
store.evictOldestExited();
|
|
194
|
+
const how = result.signal ? `signal ${result.signal}` : `exit code ${result.code ?? "?"}`;
|
|
195
|
+
return {
|
|
196
|
+
content: [{ type: "text", text: `killed ${session.id} (${how})` }],
|
|
197
|
+
details: { action, id: session.id },
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
} catch (err) {
|
|
202
|
+
return {
|
|
203
|
+
content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
|
|
204
|
+
isError: true as const,
|
|
205
|
+
details: { action },
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
@@ -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
|
+
}
|