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,144 @@
|
|
|
1
|
+
// sg ops — pure arg-building / parsing / formatting over the sg CLI facts
|
|
2
|
+
// (verified against ast-grep 0.45.3):
|
|
3
|
+
// run -p PAT [-l LANG] [--globs G]… [PATHS…] --json=compact
|
|
4
|
+
// → one JSON array of matches; exit 1 + "[]" = NO MATCHES (not an error);
|
|
5
|
+
// stderr carrying "ERROR node" = the pattern failed to parse; exit 9 =
|
|
6
|
+
// bad args (bad glob). range.start.line/column are 0-BASED.
|
|
7
|
+
// run -p PAT -r REW … (no -U) → per-file diff preview (dry-run).
|
|
8
|
+
// run -p PAT -r REW … -U → writes files, prints NOTHING on success.
|
|
9
|
+
|
|
10
|
+
export interface SgMatch {
|
|
11
|
+
file: string;
|
|
12
|
+
/** 1-based (converted from sg's 0-based range). */
|
|
13
|
+
line: number;
|
|
14
|
+
column: number;
|
|
15
|
+
text: string;
|
|
16
|
+
/** Dedup key from sg's byte offsets. */
|
|
17
|
+
byteStart: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ParsedSg {
|
|
21
|
+
matches: SgMatch[];
|
|
22
|
+
noMatches: boolean;
|
|
23
|
+
patternError?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface RawSgMatch {
|
|
27
|
+
text?: string;
|
|
28
|
+
file?: string;
|
|
29
|
+
range?: { start?: { line?: number; column?: number }; end?: { line?: number; column?: number } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Build `run` args for a search (or rewrite preview when rewrite given). */
|
|
33
|
+
export function buildRunArgs(opts: {
|
|
34
|
+
pattern: string;
|
|
35
|
+
rewrite?: string;
|
|
36
|
+
language?: string;
|
|
37
|
+
globs?: string[];
|
|
38
|
+
paths?: string[];
|
|
39
|
+
update?: boolean;
|
|
40
|
+
json?: boolean;
|
|
41
|
+
}): string[] {
|
|
42
|
+
const args = ["run", "-p", opts.pattern];
|
|
43
|
+
if (opts.rewrite !== undefined) args.push("-r", opts.rewrite);
|
|
44
|
+
if (opts.language) args.push("-l", opts.language);
|
|
45
|
+
for (const g of opts.globs ?? []) args.push("--globs", g);
|
|
46
|
+
if (opts.update) args.push("-U");
|
|
47
|
+
if (opts.json) args.push("--json=compact");
|
|
48
|
+
args.push(...(opts.paths && opts.paths.length > 0 ? opts.paths : ["."]));
|
|
49
|
+
return args;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parse a `--json=compact` search result. Exit 1 with an empty array is a
|
|
53
|
+
* NO-MATCH, not an error; a pattern-parse failure ("ERROR node" stderr on
|
|
54
|
+
* older sg, exit 8 + "Cannot parse query" on ast-grep 0.4x) is a
|
|
55
|
+
* patternError — the tools render it as a hint, not a tool crash. */
|
|
56
|
+
export function parseSearch(result: { exitCode: number; stdout: string; stderr: string }, pattern: string): ParsedSg {
|
|
57
|
+
if (
|
|
58
|
+
result.stderr.includes("ERROR node") ||
|
|
59
|
+
(result.exitCode !== 0 && /Cannot parse query|Multiple AST nodes are detected/.test(result.stderr))
|
|
60
|
+
) {
|
|
61
|
+
return { matches: [], noMatches: true, patternError: `pattern failed to parse: ${pattern}${firstLine(result.stderr)}` };
|
|
62
|
+
}
|
|
63
|
+
let raw: unknown;
|
|
64
|
+
try {
|
|
65
|
+
raw = JSON.parse(result.stdout);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new Error(`sg returned non-JSON output (exit ${result.exitCode}): ${result.stdout.slice(0, 200) || result.stderr.slice(0, 200)}`);
|
|
68
|
+
}
|
|
69
|
+
if (!Array.isArray(raw)) {
|
|
70
|
+
throw new Error(`sg returned unexpected output (exit ${result.exitCode}): ${result.stdout.slice(0, 200)}`);
|
|
71
|
+
}
|
|
72
|
+
const matches = (raw as RawSgMatch[])
|
|
73
|
+
.filter((m) => typeof m.file === "string")
|
|
74
|
+
.map((m) => ({
|
|
75
|
+
file: m.file!,
|
|
76
|
+
// sg's range is 0-based — surface 1-based editor coordinates.
|
|
77
|
+
line: (m.range?.start?.line ?? 0) + 1,
|
|
78
|
+
column: (m.range?.start?.column ?? 0) + 1,
|
|
79
|
+
text: m.text ?? "",
|
|
80
|
+
byteStart: byteStartOf(m),
|
|
81
|
+
}));
|
|
82
|
+
return { matches, noMatches: matches.length === 0 };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function byteStartOf(m: RawSgMatch): number {
|
|
86
|
+
const bo = (m as { range?: { byteOffset?: { start?: number } } }).range?.byteOffset?.start;
|
|
87
|
+
if (typeof bo === "number") return bo;
|
|
88
|
+
// Older sg without byteOffset: fall back to a file+position key (deduped
|
|
89
|
+
// per-run anyway — cross-run dedupe just keeps both, harmless).
|
|
90
|
+
return -1;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function firstLine(stderr: string): string {
|
|
94
|
+
const line = stderr.split("\n").find((l) => l.trim().length > 0);
|
|
95
|
+
return line ? ` (${line.trim().slice(0, 160)})` : "";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Merge sequential-run results, deduping by file + byte offset. */
|
|
99
|
+
export function mergeMatches(runs: ParsedSg[]): ParsedSg {
|
|
100
|
+
const patternError = runs.find((r) => r.patternError)?.patternError;
|
|
101
|
+
const seen = new Set<string>();
|
|
102
|
+
const matches: SgMatch[] = [];
|
|
103
|
+
for (const run of runs) {
|
|
104
|
+
for (const m of run.matches) {
|
|
105
|
+
const key = `${m.file}:${m.byteStart}`;
|
|
106
|
+
if (m.byteStart >= 0 && seen.has(key)) continue;
|
|
107
|
+
seen.add(key);
|
|
108
|
+
matches.push(m);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { matches, noMatches: matches.length === 0 && !patternError, patternError };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Render matches: `path:line:col text`. */
|
|
115
|
+
export function formatMatches(matches: SgMatch[], pattern: string, maxMatches = 200): string {
|
|
116
|
+
if (matches.length === 0) return `no matches for ${pattern}`;
|
|
117
|
+
const shown = matches.slice(0, maxMatches);
|
|
118
|
+
const lines = shown.map((m) => {
|
|
119
|
+
const text = m.text.length > 200 ? `${m.text.slice(0, 197)}…` : m.text;
|
|
120
|
+
return `${m.file}:${m.line}:${m.column} ${text.replaceAll("\n", "\\n")}`;
|
|
121
|
+
});
|
|
122
|
+
if (matches.length > shown.length) {
|
|
123
|
+
lines.push(`… ${matches.length - shown.length} more (showing ${shown.length} of ${matches.length})`);
|
|
124
|
+
}
|
|
125
|
+
return lines.join("\n");
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Split a dry-run diff preview into per-file sections (`path\n@@ …`). */
|
|
129
|
+
export function parseDiffOutput(stdout: string): Array<{ file: string; diff: string }> {
|
|
130
|
+
const out: Array<{ file: string; diff: string }> = [];
|
|
131
|
+
const lines = stdout.split("\n");
|
|
132
|
+
let current: { file: string; lines: string[] } | undefined;
|
|
133
|
+
for (const line of lines) {
|
|
134
|
+
// File headers are bare relative paths (no @@, no gutter glyphs).
|
|
135
|
+
if (line.length > 0 && !line.startsWith("@@") && !/^\s*[0-9]+\s*[│|]/.test(line) && !/^[│\-+ ]/.test(line) && line === line.trim() && !line.includes("│")) {
|
|
136
|
+
if (current) out.push({ file: current.file, diff: current.lines.join("\n") });
|
|
137
|
+
current = { file: line, lines: [] };
|
|
138
|
+
} else if (current) {
|
|
139
|
+
current.lines.push(line);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (current) out.push({ file: current.file, diff: current.lines.join("\n") });
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// The `sg`/`ast-grep` CLI runner — the single seam every op goes through
|
|
2
|
+
// (gh-module pattern: injected fake in tests). Zero deps.
|
|
3
|
+
//
|
|
4
|
+
// Env contract: NO_COLOR/CLICOLOR/CLICOLOR_FORCE pinned OFF — the user's
|
|
5
|
+
// CLICOLOR_FORCE=1 otherwise colorizes piped JSON and breaks parsing (the
|
|
6
|
+
// live gh bug, same fix).
|
|
7
|
+
|
|
8
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
9
|
+
|
|
10
|
+
/** Deadline for one sg invocation. */
|
|
11
|
+
export const SG_TIMEOUT_MS = 30_000;
|
|
12
|
+
/** Captured-output cap per stream. */
|
|
13
|
+
export const SG_OUTPUT_LIMIT_BYTES = 2 * 1024 * 1024;
|
|
14
|
+
const TRUNCATION_MARKER = "\n[sg output truncated after 2 MiB]\n";
|
|
15
|
+
|
|
16
|
+
/** sg / ast-grep with color forced OFF. */
|
|
17
|
+
export function sgEnv(): NodeJS.ProcessEnv {
|
|
18
|
+
return {
|
|
19
|
+
...process.env,
|
|
20
|
+
NO_COLOR: "1",
|
|
21
|
+
CLICOLOR: "0",
|
|
22
|
+
CLICOLOR_FORCE: "0",
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SgCommandResult {
|
|
27
|
+
exitCode: number;
|
|
28
|
+
stdout: string;
|
|
29
|
+
stderr: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The seam every op goes through — swapped for a fake in tests. */
|
|
33
|
+
export interface SgRunner {
|
|
34
|
+
/** Run sg; does NOT throw on non-zero exit. */
|
|
35
|
+
run(cwd: string, args: string[], signal?: AbortSignal): Promise<SgCommandResult>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let availableCache: string | null | undefined;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve the sg binary: `ast-grep` first (the maintained name; `sg` prints a
|
|
42
|
+
* deprecation warning to stderr on every call), falling back to `sg`. Cached.
|
|
43
|
+
* Null when neither is installed (module registration is fail-open on this).
|
|
44
|
+
*/
|
|
45
|
+
export function sgBinary(): string | null {
|
|
46
|
+
if (availableCache !== undefined) return availableCache;
|
|
47
|
+
availableCache = null;
|
|
48
|
+
for (const bin of ["ast-grep", "sg"]) {
|
|
49
|
+
try {
|
|
50
|
+
const probe = spawnSync(bin, ["--version"], { stdio: "ignore", timeout: 10_000 });
|
|
51
|
+
if (!probe.error && probe.status === 0) {
|
|
52
|
+
availableCache = bin;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
} catch {
|
|
56
|
+
// try the next candidate
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return availableCache;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Test hook: forget the probed binary (module state outlives a test). */
|
|
63
|
+
export function resetSgBinaryCache(): void {
|
|
64
|
+
availableCache = undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** True when an sg CLI is installed (cached after the first probe). */
|
|
68
|
+
export function sgAvailable(): boolean {
|
|
69
|
+
return sgBinary() !== null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export const realSg: SgRunner = {
|
|
73
|
+
run(cwd, args, signal) {
|
|
74
|
+
const bin = sgBinary();
|
|
75
|
+
if (!bin) {
|
|
76
|
+
return Promise.reject(new Error("ast-grep CLI is not installed — install with `brew install ast-grep` or `npm i -g @ast-grep/cli`."));
|
|
77
|
+
}
|
|
78
|
+
return new Promise<SgCommandResult>((resolveP, rejectP) => {
|
|
79
|
+
const timeout = AbortSignal.timeout(SG_TIMEOUT_MS);
|
|
80
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
81
|
+
const child = spawn(bin, args, { cwd, env: sgEnv(), stdio: ["ignore", "pipe", "pipe"], signal: combined });
|
|
82
|
+
const out: Buffer[] = [];
|
|
83
|
+
const err: Buffer[] = [];
|
|
84
|
+
let outTotal = 0;
|
|
85
|
+
let errTotal = 0;
|
|
86
|
+
child.stdout!.on("data", (chunk: Buffer) => {
|
|
87
|
+
outTotal += chunk.length;
|
|
88
|
+
if (outTotal <= SG_OUTPUT_LIMIT_BYTES) out.push(chunk);
|
|
89
|
+
});
|
|
90
|
+
child.stderr!.on("data", (chunk: Buffer) => {
|
|
91
|
+
errTotal += chunk.length;
|
|
92
|
+
if (errTotal <= SG_OUTPUT_LIMIT_BYTES) err.push(chunk);
|
|
93
|
+
});
|
|
94
|
+
child.on("error", rejectP);
|
|
95
|
+
child.on("close", (code) => {
|
|
96
|
+
let stdout = Buffer.concat(out).toString("utf8");
|
|
97
|
+
if (outTotal > SG_OUTPUT_LIMIT_BYTES) stdout += TRUNCATION_MARKER;
|
|
98
|
+
let stderr = Buffer.concat(err).toString("utf8");
|
|
99
|
+
if (errTotal > SG_OUTPUT_LIMIT_BYTES) stderr += TRUNCATION_MARKER;
|
|
100
|
+
resolveP({ exitCode: code ?? -1, stdout, stderr });
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
},
|
|
104
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// sg module unit tests — fake SgRunner (scripted arg-matching, gh.test.ts
|
|
2
|
+
// pattern). No real sg spawns; the binary is not assumed present.
|
|
3
|
+
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import { sgBinary, type SgRunner } from "../lib/sg-cli.js";
|
|
7
|
+
import {
|
|
8
|
+
buildRunArgs,
|
|
9
|
+
formatMatches,
|
|
10
|
+
mergeMatches,
|
|
11
|
+
parseDiffOutput,
|
|
12
|
+
parseSearch,
|
|
13
|
+
type SgMatch,
|
|
14
|
+
} from "../lib/ops.js";
|
|
15
|
+
|
|
16
|
+
function sgMatch(over: Partial<SgMatch>): SgMatch {
|
|
17
|
+
return { file: "a.ts", line: 2, column: 3, text: "return 1;", byteStart: 26, ...over };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const SEARCH_JSON = JSON.stringify([
|
|
21
|
+
{ text: "return 1;", range: { byteOffset: { start: 26, end: 35 }, start: { line: 1, column: 2 }, end: { line: 1, column: 11 } }, file: "a.ts", lines: " return 1;" },
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
describe("buildRunArgs", () => {
|
|
25
|
+
it("search: pattern + json + default path", () => {
|
|
26
|
+
assert.deepEqual(buildRunArgs({ pattern: "return 1", json: true }), ["run", "-p", "return 1", "--json=compact", "."]);
|
|
27
|
+
});
|
|
28
|
+
it("language, globs, paths", () => {
|
|
29
|
+
const args = buildRunArgs({ pattern: "P", language: "ts", globs: ["*.ts"], paths: ["src", "lib"], json: true });
|
|
30
|
+
assert.deepEqual(args, ["run", "-p", "P", "-l", "ts", "--globs", "*.ts", "--json=compact", "src", "lib"]);
|
|
31
|
+
});
|
|
32
|
+
it("rewrite dry-run has NO -U; apply adds it", () => {
|
|
33
|
+
const dry = buildRunArgs({ pattern: "P", rewrite: "R", json: true });
|
|
34
|
+
assert.equal(dry.includes("-U"), false);
|
|
35
|
+
assert.ok(dry.includes("-r"));
|
|
36
|
+
const apply = buildRunArgs({ pattern: "P", rewrite: "R", update: true });
|
|
37
|
+
assert.equal(apply.includes("-U"), true);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe("parseSearch", () => {
|
|
42
|
+
it("converts 0-based range to 1-based display", () => {
|
|
43
|
+
const r = parseSearch({ exitCode: 0, stdout: SEARCH_JSON, stderr: "" }, "return 1");
|
|
44
|
+
assert.equal(r.matches[0]!.line, 2);
|
|
45
|
+
assert.equal(r.matches[0]!.column, 3);
|
|
46
|
+
assert.equal(r.noMatches, false);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("exit 1 + empty array = no matches, NOT an error", () => {
|
|
50
|
+
const r = parseSearch({ exitCode: 1, stdout: "[]", stderr: "" }, "zzz");
|
|
51
|
+
assert.equal(r.noMatches, true);
|
|
52
|
+
assert.deepEqual(r.matches, []);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("ERROR node stderr → pattern error with remediation text", () => {
|
|
56
|
+
const r = parseSearch({ exitCode: 0, stdout: "[]", stderr: "Warning: Pattern contains an ERROR node and may cause unexpected results." }, "((((");
|
|
57
|
+
assert.match(r.patternError!, /pattern failed to parse/);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("non-JSON stdout throws (bad args surface loudly)", () => {
|
|
61
|
+
assert.throws(() => parseSearch({ exitCode: 9, stdout: "error: unexpected argument", stderr: "" }, "x"), /non-JSON/);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("matches without byteOffset still parse (dedupe key -1)", () => {
|
|
65
|
+
const legacy = JSON.stringify([{ text: "x", file: "f.ts", range: { start: { line: 0, column: 0 } } }]);
|
|
66
|
+
const r = parseSearch({ exitCode: 0, stdout: legacy, stderr: "" }, "x");
|
|
67
|
+
assert.equal(r.matches[0]!.byteStart, -1);
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
describe("mergeMatches", () => {
|
|
72
|
+
it("dedupes by file + byteStart across sequential runs", () => {
|
|
73
|
+
const a = { matches: [sgMatch({ byteStart: 5 }), sgMatch({ file: "b.ts", byteStart: 7 })], noMatches: false };
|
|
74
|
+
const b = { matches: [sgMatch({ byteStart: 5 }), sgMatch({ byteStart: 9 })], noMatches: false };
|
|
75
|
+
const merged = mergeMatches([a, b]);
|
|
76
|
+
assert.equal(merged.matches.length, 3);
|
|
77
|
+
});
|
|
78
|
+
it("keeps -1-keyed legacy matches (no false dedupe)", () => {
|
|
79
|
+
const a = { matches: [sgMatch({ byteStart: -1, line: 1 })], noMatches: false };
|
|
80
|
+
const b = { matches: [sgMatch({ byteStart: -1, line: 5 })], noMatches: false };
|
|
81
|
+
assert.equal(mergeMatches([a, b]).matches.length, 2);
|
|
82
|
+
});
|
|
83
|
+
it("surfaces a pattern error from any run", () => {
|
|
84
|
+
const merged = mergeMatches([{ matches: [], noMatches: true }, { matches: [], noMatches: true, patternError: "bad" }]);
|
|
85
|
+
assert.equal(merged.patternError, "bad");
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
describe("formatMatches", () => {
|
|
90
|
+
it("path:line:col + text, capped with a footer", () => {
|
|
91
|
+
const matches = Array.from({ length: 250 }, (_, i) => sgMatch({ file: `f${i}.ts`, line: i + 1, column: 1, byteStart: i }));
|
|
92
|
+
const out = formatMatches(matches, "pat");
|
|
93
|
+
const lines = out.split("\n");
|
|
94
|
+
assert.match(lines[0]!, /^f0\.ts:1:1 return 1;$/);
|
|
95
|
+
assert.match(lines.at(-1)!, /showing 200 of 250/);
|
|
96
|
+
});
|
|
97
|
+
it("empty → friendly no-match line", () => {
|
|
98
|
+
assert.equal(formatMatches([], "pat"), "no matches for pat");
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe("parseDiffOutput", () => {
|
|
103
|
+
it("splits per-file sections on bare-path headers", () => {
|
|
104
|
+
const stdout = [
|
|
105
|
+
"a.ts",
|
|
106
|
+
"@@ -0,3 +0,3 @@",
|
|
107
|
+
"1 1│ export function foo() {",
|
|
108
|
+
" │- return 1;",
|
|
109
|
+
" 2│+ return 2",
|
|
110
|
+
"sub/c.ts",
|
|
111
|
+
"@@ -0,3 +0,3 @@",
|
|
112
|
+
"2 │- return 1;",
|
|
113
|
+
].join("\n");
|
|
114
|
+
const sections = parseDiffOutput(stdout);
|
|
115
|
+
assert.deepEqual(sections.map((s) => s.file), ["a.ts", "sub/c.ts"]);
|
|
116
|
+
assert.match(sections[0]!.diff, /return 2/);
|
|
117
|
+
assert.match(sections[1]!.diff, /return 1;/);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("binary probe", () => {
|
|
122
|
+
it("sgBinary returns a name or null without throwing", () => {
|
|
123
|
+
// Cached after first call; on this dev machine ast-grep IS installed,
|
|
124
|
+
// but the test only asserts the shape (CI has no binary).
|
|
125
|
+
const bin = sgBinary();
|
|
126
|
+
assert.ok(bin === null || bin === "ast-grep" || bin === "sg");
|
|
127
|
+
});
|
|
128
|
+
});
|
|
@@ -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
|
+
}
|