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,33 @@
|
|
|
1
|
+
// notify module — one `notify` tool: desktop notification for long-running
|
|
2
|
+
// work / when input is needed (herdr multi-pane ergonomics). Harmless:
|
|
3
|
+
// no fs, no network; spawn failures fall back to the terminal bell, so the
|
|
4
|
+
// tool always succeeds.
|
|
5
|
+
|
|
6
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { Type } from "typebox";
|
|
8
|
+
import { readDisabledTools } from "../../lib/tools.js";
|
|
9
|
+
import { notify } from "./lib/notify.js";
|
|
10
|
+
|
|
11
|
+
export default function notifyModule(pi: ExtensionAPI): void {
|
|
12
|
+
const disabled = readDisabledTools();
|
|
13
|
+
pi.registerTool({
|
|
14
|
+
name: "notify",
|
|
15
|
+
label: "Notify",
|
|
16
|
+
description:
|
|
17
|
+
"Send a desktop notification — for long-running work (announce completion) or when you need user input while the user is away. macOS uses osascript, Linux notify-send, else the terminal bell. Harmless: no fs/network access, and delivery failures fall back to a bell.",
|
|
18
|
+
promptSnippet: "Send a desktop notification",
|
|
19
|
+
parameters: Type.Object({
|
|
20
|
+
message: Type.String({ description: "Notification body." }),
|
|
21
|
+
title: Type.Optional(Type.String({ description: 'Notification title (default "pi").' })),
|
|
22
|
+
sound: Type.Optional(Type.Boolean({ description: "Play a sound with the notification (macOS only, default false)." })),
|
|
23
|
+
}),
|
|
24
|
+
async execute(_toolCallId, params) {
|
|
25
|
+
const p = params as { message: string; title?: string; sound?: boolean };
|
|
26
|
+
const r = await notify(p);
|
|
27
|
+
let text = `notified (via ${r.via}): ${p.title ?? "pi"} — ${p.message}`;
|
|
28
|
+
if (r.note) text += `\n${r.note}`;
|
|
29
|
+
return { content: [{ type: "text", text }], details: { via: r.via } };
|
|
30
|
+
},
|
|
31
|
+
defaultActive: !disabled.has("notify"),
|
|
32
|
+
});
|
|
33
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// notify module — desktop notifications via osascript (macOS) / notify-send
|
|
2
|
+
// (Linux), terminal bell fallback everywhere else. Zero deps: everything
|
|
3
|
+
// spawns or writes "\x07". Always resolves; note carries the fallback reason.
|
|
4
|
+
|
|
5
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
/** AppleScript string literal: wrap in "…", escape \ and ". */
|
|
8
|
+
export function appleQuote(s: string): string {
|
|
9
|
+
return `"${s.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** AppleScript args for osascript: display notification <msg> with title <t>.
|
|
13
|
+
* AppleScript string literals need DOUBLE quotes — single quotes are a
|
|
14
|
+
* syntax error (live-probed: 'x' → -2741, "x" → exit 0). */
|
|
15
|
+
export function buildDarwinArgs(title: string, message: string, sound: boolean): string[] {
|
|
16
|
+
return [
|
|
17
|
+
"-e",
|
|
18
|
+
`display notification ${appleQuote(message)} with title ${appleQuote(title)}${sound ? ` sound name "Glass"` : ""}`,
|
|
19
|
+
];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** notify-send args; app name "Pi" so the desktop shows a sane sender.
|
|
23
|
+
* ponytail: sound flag dropped — notify-send has no portable sound story. */
|
|
24
|
+
export function buildNotifySendArgs(title: string, message: string, _sound: boolean): string[] {
|
|
25
|
+
return ["-a", "Pi", title, message];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Injectable seam — resolves when the notifier exits 0, rejects otherwise. */
|
|
29
|
+
export type SpawnFn = (cmd: string, args: string[]) => Promise<void>;
|
|
30
|
+
|
|
31
|
+
function defaultSpawn(cmd: string, args: string[]): Promise<void> {
|
|
32
|
+
return new Promise((resolveP, rejectP) => {
|
|
33
|
+
const child = spawn(cmd, args, { stdio: "ignore" });
|
|
34
|
+
child.on("error", rejectP);
|
|
35
|
+
child.on("close", (code) => {
|
|
36
|
+
if (code === 0) resolveP();
|
|
37
|
+
else rejectP(new Error(`${cmd} exited with code ${code}`));
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** PATH probe for the notifier binary (spawnSync --version, like ghAvailable). */
|
|
43
|
+
function defaultProbe(cmd: string): boolean {
|
|
44
|
+
try {
|
|
45
|
+
const probe = spawnSync(cmd, ["--version"], { stdio: "ignore", timeout: 5_000 });
|
|
46
|
+
return !probe.error && probe.status === 0;
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function bell(): void {
|
|
53
|
+
process.stdout.write("\x07");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface NotifyOptions {
|
|
57
|
+
title?: string;
|
|
58
|
+
message: string;
|
|
59
|
+
sound?: boolean;
|
|
60
|
+
spawnFn?: SpawnFn;
|
|
61
|
+
probeFn?: (cmd: string) => boolean;
|
|
62
|
+
/** ponytail: injectable so the linux branches are testable on macOS. */
|
|
63
|
+
platform?: NodeJS.Platform;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface NotifyResult {
|
|
67
|
+
ok: boolean;
|
|
68
|
+
via: "osascript" | "notify-send" | "bell";
|
|
69
|
+
/** Set when we fell back — carries the failure / fallback text. */
|
|
70
|
+
note?: string;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Send a desktop notification; never throws. Spawn or probe failure → bell. */
|
|
74
|
+
export async function notify(opts: NotifyOptions): Promise<NotifyResult> {
|
|
75
|
+
const title = opts.title ?? "pi";
|
|
76
|
+
const sound = opts.sound ?? false;
|
|
77
|
+
const spawnFn = opts.spawnFn ?? defaultSpawn;
|
|
78
|
+
const probeFn = opts.probeFn ?? defaultProbe;
|
|
79
|
+
const platform = opts.platform ?? process.platform;
|
|
80
|
+
try {
|
|
81
|
+
if (platform === "darwin") {
|
|
82
|
+
await spawnFn("osascript", buildDarwinArgs(title, opts.message, sound));
|
|
83
|
+
return { ok: true, via: "osascript" };
|
|
84
|
+
}
|
|
85
|
+
if (platform === "linux") {
|
|
86
|
+
if (!probeFn("notify-send")) {
|
|
87
|
+
bell();
|
|
88
|
+
return { ok: true, via: "bell", note: "notify-send not found on PATH — rang the terminal bell instead" };
|
|
89
|
+
}
|
|
90
|
+
await spawnFn("notify-send", buildNotifySendArgs(title, opts.message, sound));
|
|
91
|
+
return { ok: true, via: "notify-send" };
|
|
92
|
+
}
|
|
93
|
+
bell();
|
|
94
|
+
return { ok: true, via: "bell", note: `no desktop notifier on ${platform} — rang the terminal bell instead` };
|
|
95
|
+
} catch (err) {
|
|
96
|
+
bell();
|
|
97
|
+
return { ok: true, via: "bell", note: err instanceof Error ? err.message : String(err) };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// notify module unit tests — pure lib functions plus notify() with injected
|
|
2
|
+
// fakes. No real spawns, no PATH probes, no desktop notifications.
|
|
3
|
+
|
|
4
|
+
import assert from "node:assert/strict";
|
|
5
|
+
import { describe, it } from "node:test";
|
|
6
|
+
import { appleQuote, buildDarwinArgs, buildNotifySendArgs, notify } from "../lib/notify.js";
|
|
7
|
+
|
|
8
|
+
describe("appleQuote", () => {
|
|
9
|
+
it("wraps in double quotes", () => {
|
|
10
|
+
assert.equal(appleQuote("hello"), '"hello"');
|
|
11
|
+
});
|
|
12
|
+
it("escapes internal double quotes and backslashes", () => {
|
|
13
|
+
assert.equal(appleQuote('say "hi"'), '"say \\"hi\\""');
|
|
14
|
+
assert.equal(appleQuote("back\\slash"), '"back\\\\slash"');
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("buildDarwinArgs", () => {
|
|
19
|
+
it("builds the display notification script", () => {
|
|
20
|
+
assert.deepEqual(buildDarwinArgs("pi", "done", false), ["-e", `display notification "done" with title "pi"`]);
|
|
21
|
+
});
|
|
22
|
+
it("appends the Glass sound when sound=true", () => {
|
|
23
|
+
assert.deepEqual(buildDarwinArgs("pi", "done", true), ["-e", `display notification "done" with title "pi" sound name "Glass"`]);
|
|
24
|
+
});
|
|
25
|
+
it("quotes the title safely", () => {
|
|
26
|
+
const [, script] = buildDarwinArgs("Bob's", "hi", false);
|
|
27
|
+
assert.ok(script.includes('"Bob\'s"'));
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe("buildNotifySendArgs", () => {
|
|
32
|
+
it("uses -a Pi and passes title then message", () => {
|
|
33
|
+
assert.deepEqual(buildNotifySendArgs("pi", "done", false), ["-a", "Pi", "pi", "done"]);
|
|
34
|
+
});
|
|
35
|
+
it("ignores sound (no portable flag)", () => {
|
|
36
|
+
assert.deepEqual(buildNotifySendArgs("pi", "done", true), ["-a", "Pi", "pi", "done"]);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe("notify", () => {
|
|
41
|
+
it("darwin: resolves via osascript when spawnFn succeeds", async () => {
|
|
42
|
+
const calls: Array<{ cmd: string; args: string[] }> = [];
|
|
43
|
+
const r = await notify({
|
|
44
|
+
title: "pi",
|
|
45
|
+
message: "done",
|
|
46
|
+
sound: true,
|
|
47
|
+
platform: "darwin",
|
|
48
|
+
spawnFn: async (cmd, args) => {
|
|
49
|
+
calls.push({ cmd, args });
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
assert.deepEqual(r, { ok: true, via: "osascript" });
|
|
53
|
+
assert.deepEqual(calls, [{ cmd: "osascript", args: buildDarwinArgs("pi", "done", true) }]);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it("darwin: falls back to bell when spawnFn errors, note carries the failure", async () => {
|
|
57
|
+
const r = await notify({
|
|
58
|
+
message: "done",
|
|
59
|
+
platform: "darwin",
|
|
60
|
+
spawnFn: async () => {
|
|
61
|
+
throw new Error("osascript: not allowed");
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
assert.equal(r.ok, true);
|
|
65
|
+
assert.equal(r.via, "bell");
|
|
66
|
+
assert.match(r.note ?? "", /osascript: not allowed/);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("linux: probe miss → bell fallback with note", async () => {
|
|
70
|
+
const r = await notify({
|
|
71
|
+
message: "done",
|
|
72
|
+
platform: "linux",
|
|
73
|
+
probeFn: () => false,
|
|
74
|
+
spawnFn: async () => {
|
|
75
|
+
throw new Error("fakeGh: must not spawn when the probe misses");
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
assert.deepEqual(r, { ok: true, via: "bell", note: "notify-send not found on PATH — rang the terminal bell instead" });
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("linux: probe hit → notify-send path", async () => {
|
|
82
|
+
const calls: string[][] = [];
|
|
83
|
+
const r = await notify({
|
|
84
|
+
title: "pi",
|
|
85
|
+
message: "done",
|
|
86
|
+
platform: "linux",
|
|
87
|
+
probeFn: () => true,
|
|
88
|
+
spawnFn: async (_cmd, args) => {
|
|
89
|
+
calls.push(args);
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
assert.deepEqual(r, { ok: true, via: "notify-send" });
|
|
93
|
+
assert.deepEqual(calls, [buildNotifySendArgs("pi", "done", false)]);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
@@ -33,6 +33,13 @@ export const READ_ONLY_TOOLS = new Set([
|
|
|
33
33
|
// Rendered-page accessibility audit — reads the page in a local headless
|
|
34
34
|
// Chrome, mutates nothing.
|
|
35
35
|
"web_a11y",
|
|
36
|
+
// PDF text extraction (vendored pdf.js, in-process) — reads a local file.
|
|
37
|
+
"read_pdf",
|
|
38
|
+
// Semantic find — read-only judging over the workspace; costs model calls
|
|
39
|
+
// but mutates nothing.
|
|
40
|
+
"jfind",
|
|
41
|
+
// ast-grep search is read-only; the REWRITE tool (ast_edit) is NOT here.
|
|
42
|
+
"ast_grep",
|
|
36
43
|
// NOTE: herdr is deliberately NOT here — its prompt action can drive a
|
|
37
44
|
// write-capable child, so every herdr call takes the confirm tier.
|
|
38
45
|
]);
|
|
@@ -43,6 +50,12 @@ export const BLOCKED_TOOLS = new Set([
|
|
|
43
50
|
"edit", "write",
|
|
44
51
|
// Diff-style file mutation — same treatment as edit/write.
|
|
45
52
|
"apply_patch",
|
|
53
|
+
// ast-grep rewrite with write:true mutates files; dry-run default keeps it
|
|
54
|
+
// a mutator (the schema carries write, so the tool is gated as a whole).
|
|
55
|
+
"ast_edit",
|
|
56
|
+
// Background shell sessions are an arbitrary-execution escape hatch —
|
|
57
|
+
// hard-blocked like bash writers, not confirm-tier.
|
|
58
|
+
"shell",
|
|
46
59
|
// File editor (create/str_replace/insert) — a direct source mutator like edit/write.
|
|
47
60
|
"str_replace_editor",
|
|
48
61
|
// Serena file mutation (restart/onboarding tools are state-changing but no
|
|
@@ -47,6 +47,12 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
|
|
|
47
47
|
defaultValue: DEFAULT_REPAIR_SETTINGS.guards,
|
|
48
48
|
description: "Block destructive bash (rm -rf /, dd writes) and read-on-guessed-path.",
|
|
49
49
|
}),
|
|
50
|
+
row("repair.autoGenGuard", "Auto-generated write guard", "toggle", cfg.autoGenGuard, (v) => {
|
|
51
|
+
cfg.autoGenGuard = v === true;
|
|
52
|
+
}, {
|
|
53
|
+
defaultValue: DEFAULT_REPAIR_SETTINGS.autoGenGuard,
|
|
54
|
+
description: "Refuse write/edit on generated files (lockfiles, dist/, *.min.js) — regenerate from source instead; bash is the override hatch.",
|
|
55
|
+
}),
|
|
50
56
|
row("repair.autoBg", "Auto-background bash", "toggle", cfg.autoBg, (v) => {
|
|
51
57
|
cfg.autoBg = v === true;
|
|
52
58
|
}, {
|
|
@@ -66,7 +72,7 @@ export function buildRepairGroups(cfg: RepairSettings): PanelGroup[] {
|
|
|
66
72
|
}
|
|
67
73
|
|
|
68
74
|
const OWNED_PREFIX = "repair.";
|
|
69
|
-
const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoBg"] as const;
|
|
75
|
+
const BOOL_KEYS = ["arguments", "editRetry", "guards", "autoGenGuard", "autoBg"] as const;
|
|
70
76
|
|
|
71
77
|
/** repair's ModuleConfig for the central /config panel. The factory receives
|
|
72
78
|
* the module's guarded pi but needs nothing from it — settings live in the
|
|
@@ -53,6 +53,9 @@ import {
|
|
|
53
53
|
stripReadContamination,
|
|
54
54
|
} from "./lib/edit-repair.js";
|
|
55
55
|
import { createStrReplaceEditorToolDefinition } from "./lib/editor.js";
|
|
56
|
+
import { checkAutoGenerated, autoGeneratedError } from "./lib/auto-generated.js";
|
|
57
|
+
import { archiveKind, readArchiveListing, readArchiveMember } from "./lib/read-archive.js";
|
|
58
|
+
import { isSqliteFile, readSqlite } from "./lib/read-sqlite.js";
|
|
56
59
|
import { checkDangerousCommand, isRecord, looksLikeCodePath } from "./lib/guards.js";
|
|
57
60
|
import { repairToolArguments, type RepairKind } from "./lib/input-repair.js";
|
|
58
61
|
import { applyPatchToFiles, parsePatch, PatchParseError } from "./lib/patch.js";
|
|
@@ -107,6 +110,76 @@ function applyReadSelector(args: Record<string, unknown>, cwd: string): unknown
|
|
|
107
110
|
return out;
|
|
108
111
|
}
|
|
109
112
|
|
|
113
|
+
// ── sqlite / archive views (OMP read-sqlite + read-archive) ──
|
|
114
|
+
|
|
115
|
+
/** Peel `db.sqlite:users` / `pkg.tgz:src/x.ts:50-80` for sqlite/archive
|
|
116
|
+
* views. Returns the model-facing text result, or null when the path is
|
|
117
|
+
* neither (caller falls through to the built-in read). The stem must exist
|
|
118
|
+
* (the caller probes the literal path first — literal-wins preserved). */
|
|
119
|
+
function applySpecialView(rawPath: string, cwd: string): { text: string } | null {
|
|
120
|
+
// Special-view peel: the LONGEST existing prefix path split at colons is
|
|
121
|
+
// the stem; the remainder is the sqlite sub-selector or archive member
|
|
122
|
+
// (+ optional line ranges). peelPathSelector can't do this — its grammar
|
|
123
|
+
// only recognizes line selectors, so `db.sqlite:users` never peels.
|
|
124
|
+
let stem = "";
|
|
125
|
+
let remainder = "";
|
|
126
|
+
const parts = rawPath.split(":");
|
|
127
|
+
if (parts.length < 2 || parts[0]!.length <= 1) return null; // no segments / drive letter
|
|
128
|
+
for (let take = parts.length - 1; take >= 1; take--) {
|
|
129
|
+
const candidate = parts.slice(0, take).join(":");
|
|
130
|
+
if (existsSync(resolvePath(cwd, candidate))) {
|
|
131
|
+
stem = candidate;
|
|
132
|
+
remainder = parts.slice(take).join(":");
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!stem) return null;
|
|
137
|
+
const stemAbs = resolvePath(cwd, stem);
|
|
138
|
+
const segments = remainder.split(":");
|
|
139
|
+
|
|
140
|
+
if (isSqliteFile(stemAbs)) {
|
|
141
|
+
try {
|
|
142
|
+
// The sqlite sub-selector spans ALL segments (users:2 is table+rowid).
|
|
143
|
+
return { text: readSqlite(stemAbs, remainder, stem) };
|
|
144
|
+
} catch (err) {
|
|
145
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const kind = archiveKind(stem);
|
|
150
|
+
if (kind) {
|
|
151
|
+
if (!remainder) return { text: readArchiveListing(stemAbs, kind, stem).text };
|
|
152
|
+
const res = readArchiveMember(stemAbs, kind, remainder, stem);
|
|
153
|
+
// A trailing :50-80 range on the member reuses the line slicer over the
|
|
154
|
+
// member body (line 1 of the result text is the path header).
|
|
155
|
+
if (segments.length > 1) {
|
|
156
|
+
const memberParsed = peelPathSelector(`x:${remainder}`);
|
|
157
|
+
if (memberParsed.selector) {
|
|
158
|
+
const lines = res.text.split("\n");
|
|
159
|
+
if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();
|
|
160
|
+
const sliced = sliceMemberLines(lines, memberParsed.selector);
|
|
161
|
+
if (sliced !== null) return { text: sliced };
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return { text: res.text };
|
|
165
|
+
}
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Slice `header + member lines` by a lines-selector, keeping the header. */
|
|
170
|
+
function sliceMemberLines(lines: string[], selector: ParsedSelector): string | null {
|
|
171
|
+
if (selector.kind !== "lines") return null;
|
|
172
|
+
const header = lines[0]!;
|
|
173
|
+
const body = lines.slice(1);
|
|
174
|
+
const total = body.length;
|
|
175
|
+
const parts = selector.ranges.map((r) => {
|
|
176
|
+
const end = Math.min(r.endLine ?? total, total);
|
|
177
|
+
return `── lines ${r.startLine}-${end} of ${total} ──\n${body.slice(r.startLine - 1, end).join("\n")}`;
|
|
178
|
+
});
|
|
179
|
+
const shown = selector.ranges.reduce((a, r) => a + (Math.min(r.endLine ?? total, total) - r.startLine + 1), 0);
|
|
180
|
+
return `${header}\n[lines ${selector.ranges.map((r) => `${r.startLine}-${r.endLine ?? total}`).join(", ")} of ${total} — ${shown} shown]\n\n${parts.join("\n\n")}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
110
183
|
/** In-memory slice for multi-range / raw / conflicts selectors. */
|
|
111
184
|
async function readWithSelector(
|
|
112
185
|
stem: string,
|
|
@@ -235,6 +308,26 @@ function parsePatchTargetPaths(patch: string): string[] {
|
|
|
235
308
|
return out;
|
|
236
309
|
}
|
|
237
310
|
|
|
311
|
+
/** Auto-generated write guard (OMP auto-generated-guard): refuse write/edit
|
|
312
|
+
* on generated files before the write lands. Returns the refusal text, or
|
|
313
|
+
* undefined (allowed). Setting-gated via repair.autoGenGuard (default on). */
|
|
314
|
+
function guardAutoGenerated(toolName: string, params: any, cwd: string): string | undefined {
|
|
315
|
+
if (!readRepairSettings().autoGenGuard) return undefined;
|
|
316
|
+
const paths: string[] = [];
|
|
317
|
+
if ((toolName === "write" || toolName === "edit") && isRecord(params) && typeof params.path === "string") {
|
|
318
|
+
paths.push(params.path);
|
|
319
|
+
}
|
|
320
|
+
if (toolName === "apply_patch" && isRecord(params) && typeof params.patch === "string") {
|
|
321
|
+
paths.push(...parsePatchTargetPaths(params.patch));
|
|
322
|
+
}
|
|
323
|
+
for (const p of paths) {
|
|
324
|
+
if (p.includes("://")) continue;
|
|
325
|
+
const match = checkAutoGenerated(p, cwd);
|
|
326
|
+
if (match) return autoGeneratedError(p, match);
|
|
327
|
+
}
|
|
328
|
+
return undefined;
|
|
329
|
+
}
|
|
330
|
+
|
|
238
331
|
/** Public seam for tools registered outside wrapToolDefinition (apply_patch,
|
|
239
332
|
* str_replace_editor) to refresh the freshness baseline after their own
|
|
240
333
|
* successful mutations. */
|
|
@@ -340,7 +433,7 @@ export function wrapToolDefinition(
|
|
|
340
433
|
// per wrapped instance (cache-safe: byte-stable for the session).
|
|
341
434
|
description:
|
|
342
435
|
base.name === "read"
|
|
343
|
-
? `${base.description}\n\nPath suffixes: file.ts:50 starts at line 50; :50-200 inclusive; :50+150 counts lines; :50- to EOF; :-60 last 60 lines; commas join ranges (:5-16,960-973) or single lines (:19,59); :conflicts lists merge-conflict blocks; :raw compounds with a range. A literal path that exists always wins over selector parsing.`
|
|
436
|
+
? `${base.description}\n\nPath suffixes: file.ts:50 starts at line 50; :50-200 inclusive; :50+150 counts lines; :50- to EOF; :-60 last 60 lines; commas join ranges (:5-16,960-973) or single lines (:19,59); :conflicts lists merge-conflict blocks; :raw compounds with a range. A literal path that exists always wins over selector parsing.\n\nSQLite and archive views: reading a *.db/*.sqlite file lists tables; db.sqlite:users shows schema + rows, :users:42 a rowid row, :users:name=alice a key lookup, :?SELECT … a read-only query. Archives (.tar, .tgz, .zip) list members; pkg.tgz:src/x.ts reads a member, :src/x.ts:50-80 slices it.`
|
|
344
437
|
: base.description,
|
|
345
438
|
prepareArguments(args: unknown) {
|
|
346
439
|
let prepared = base.prepareArguments ? base.prepareArguments(args as never) : args;
|
|
@@ -366,6 +459,35 @@ export function wrapToolDefinition(
|
|
|
366
459
|
base.name === "read" && isRecord(params) ? (params.__mtSelector as ParsedSelector | undefined) : undefined;
|
|
367
460
|
if (isRecord(params)) delete params.__mtSelector;
|
|
368
461
|
|
|
462
|
+
// sqlite / archive views: plain `db.sqlite` (exists literally, would
|
|
463
|
+
// read binary garbage) and peeled `db.sqlite:users` /
|
|
464
|
+
// `pkg.tgz:src/x.ts:50-80` forms (applySpecialView peels internally).
|
|
465
|
+
// Literal-wins is preserved: a raw path that exists and is NOT sqlite
|
|
466
|
+
// falls through to the normal read; the peeled forms only trigger when
|
|
467
|
+
// the raw path is missing (standard selector order).
|
|
468
|
+
if (base.name === "read" && isRecord(params) && typeof params.path === "string" && !selector) {
|
|
469
|
+
const rawPath: string = params.path;
|
|
470
|
+
const rawAbs = resolvePath(cwd, rawPath);
|
|
471
|
+
let view: { text: string } | null = null;
|
|
472
|
+
if (existsSync(rawAbs) && isSqliteFile(rawAbs)) {
|
|
473
|
+
try {
|
|
474
|
+
view = { text: readSqlite(rawAbs, undefined, rawPath) };
|
|
475
|
+
} catch (err) {
|
|
476
|
+
throw new Error(err instanceof Error ? err.message : String(err));
|
|
477
|
+
}
|
|
478
|
+
} else if (existsSync(rawAbs) && archiveKind(rawPath)) {
|
|
479
|
+
view = { text: readArchiveListing(rawAbs, archiveKind(rawPath)!, rawPath).text };
|
|
480
|
+
} else if (!existsSync(rawAbs) && rawPath.includes(":")) {
|
|
481
|
+
view = applySpecialView(rawPath, cwd);
|
|
482
|
+
}
|
|
483
|
+
if (view) {
|
|
484
|
+
// Record the freshness baseline for the STEM so a follow-up write
|
|
485
|
+
// to the extracted file is judged normally (members have none).
|
|
486
|
+
await recordReadMtimes({ path: rawPath }, cwd);
|
|
487
|
+
return { content: [{ type: "text", text: view.text }], details: undefined };
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
369
491
|
// Selector peel (execute-time: needs ctx.cwd for the literal-wins probe).
|
|
370
492
|
if (base.name === "read" && !selector && isRecord(params) && typeof params.path === "string" && params.path.includes(":")) {
|
|
371
493
|
params = applyReadSelector(params, cwd);
|
|
@@ -397,6 +519,8 @@ export function wrapToolDefinition(
|
|
|
397
519
|
// THIS session read earlier but someone else changed since must
|
|
398
520
|
// fail loudly instead of clobbering the foreign edit.
|
|
399
521
|
if (base.name === "write") {
|
|
522
|
+
const gen = guardAutoGenerated(base.name, params, cwd);
|
|
523
|
+
if (gen) return { content: [{ type: "text", text: gen }], isError: true, details: undefined };
|
|
400
524
|
const stale = await checkWriteFresh(params, cwd);
|
|
401
525
|
if (stale) {
|
|
402
526
|
return { content: [{ type: "text", text: stale }], isError: true, details: undefined };
|
|
@@ -436,6 +560,8 @@ export function wrapToolDefinition(
|
|
|
436
560
|
const noopIdx = (Array.isArray(params?.edits) ? params.edits : typeof params?.oldText === "string" ? [{ oldText: params.oldText, newText: params.newText }] : [])
|
|
437
561
|
.findIndex((e: any) => isRecord(e) && e.oldText === e.newText);
|
|
438
562
|
if (noopIdx !== -1) throw new Error(`edits[${noopIdx}] is a no-op: oldText equals newText. The replacement produces no change — check which region you meant to target.`);
|
|
563
|
+
const genBlock = guardAutoGenerated("edit", params, cwd);
|
|
564
|
+
if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
|
|
439
565
|
try {
|
|
440
566
|
const result = await freshDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
441
567
|
editMismatchCounts?.delete(resolvePath(cwd, typeof params?.path === "string" ? params.path : ""));
|
|
@@ -581,6 +707,8 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
581
707
|
renderShell: "self",
|
|
582
708
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
583
709
|
const cwd = ctx?.cwd || process.cwd();
|
|
710
|
+
const genBlock = guardAutoGenerated("apply_patch", params, cwd);
|
|
711
|
+
if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
|
|
584
712
|
let parsed;
|
|
585
713
|
try {
|
|
586
714
|
parsed = parsePatch(params.patch);
|
|
@@ -616,6 +744,8 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
616
744
|
pi.registerTool({
|
|
617
745
|
...strReplaceDef,
|
|
618
746
|
async execute(toolCallId: string, params: any, signal: any, onUpdate: any, ctx: any) {
|
|
747
|
+
const genBlock = guardAutoGenerated("str_replace_editor", params, ctx?.cwd || process.cwd());
|
|
748
|
+
if (genBlock) return { content: [{ type: "text", text: genBlock }], isError: true, details: undefined };
|
|
619
749
|
const result = await strReplaceDef.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
620
750
|
// Refresh the freshness baseline for the edited file (same rationale as
|
|
621
751
|
// apply_patch above) — only on success, only for plain file paths.
|
|
@@ -689,6 +819,7 @@ export default function repairModule(pi: ExtensionAPI) {
|
|
|
689
819
|
` Argument repair: ${live.arguments ? "on" : "off"}`,
|
|
690
820
|
` Edit mismatch repair: ${live.editRetry ? "on" : "off"}`,
|
|
691
821
|
` Tool-call guards: ${live.guards ? "on" : "off"}`,
|
|
822
|
+
` Auto-generated write guard: ${live.autoGenGuard ? "on" : "off"}`,
|
|
692
823
|
` Auto-background bash: ${live.autoBg ? `on @${live.autoBgSecs}s` : "off"}${live.autoBg !== autoBgOn || live.autoBgSecs !== autoBgSecs ? ` (bound at load: ${autoBgOn ? `on @${autoBgSecs}s` : "off"} — next session applies)` : ""}`,
|
|
693
824
|
"",
|
|
694
825
|
`**Repairs this session:** ${total} total`,
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// auto-generated.ts — refuse writes/edits to generated files (OMP
|
|
2
|
+
// auto-generated-guard, native detector swapped for a zero-dep matcher).
|
|
3
|
+
//
|
|
4
|
+
// A hand edit to a lockfile or a dist bundle is always wrong: the fix is to
|
|
5
|
+
// regenerate from source (npm install / cargo build / tsc). The guard hard-
|
|
6
|
+
// errors BEFORE the write with that remediation; bash stays the honest
|
|
7
|
+
// override hatch. Setting-gated via `repair.autoGenGuard` (default on).
|
|
8
|
+
|
|
9
|
+
import { isAbsolute, resolve as resolvePath } from "node:path";
|
|
10
|
+
|
|
11
|
+
/** Default generated-file patterns. Suffix/segment match, `**` crosses dirs. */
|
|
12
|
+
export const AUTO_GENERATED_PATTERNS: readonly string[] = [
|
|
13
|
+
// Lockfiles — regenerate via the package manager, never hand-edit.
|
|
14
|
+
"package-lock.json",
|
|
15
|
+
"yarn.lock",
|
|
16
|
+
"pnpm-lock.yaml",
|
|
17
|
+
"bun.lock",
|
|
18
|
+
"bun.lockb",
|
|
19
|
+
"Cargo.lock",
|
|
20
|
+
"poetry.lock",
|
|
21
|
+
"composer.lock",
|
|
22
|
+
"Gemfile.lock",
|
|
23
|
+
"flake.lock",
|
|
24
|
+
"Packages.lock.json",
|
|
25
|
+
// Minified bundles
|
|
26
|
+
"*.min.js",
|
|
27
|
+
"*.min.css",
|
|
28
|
+
"*.min.mjs",
|
|
29
|
+
"*.bundle.js",
|
|
30
|
+
// Build outputs (whole directories)
|
|
31
|
+
"dist/**",
|
|
32
|
+
"build/**",
|
|
33
|
+
"out/**",
|
|
34
|
+
"*.egg-info/**",
|
|
35
|
+
"__pycache__/**",
|
|
36
|
+
// Snapshots
|
|
37
|
+
"*.snap",
|
|
38
|
+
"__snapshots__/**",
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/** Minimal glob match: `*`/`**` = anything (crossing segments — `*.min.js`
|
|
42
|
+
* must catch a/b/app.min.js), a bare segment matches the path exactly.
|
|
43
|
+
* Zero-dep — the subagent .worktreeinclude matcher's shape. */
|
|
44
|
+
export function matchesPattern(relativePath: string, pattern: string): boolean {
|
|
45
|
+
const p = pattern.replaceAll("\\", "/");
|
|
46
|
+
const f = relativePath.replaceAll("\\", "/").replace(/^\.\//, "");
|
|
47
|
+
if (p === f) return true;
|
|
48
|
+
if (!p.includes("*")) return false; // plain name → equality only (above)
|
|
49
|
+
// Build a regex: * / ** → .* (segment-crossing)
|
|
50
|
+
let re = "^";
|
|
51
|
+
for (let i = 0; i < p.length; i++) {
|
|
52
|
+
const ch = p[i]!;
|
|
53
|
+
if (ch === "*") {
|
|
54
|
+
if (p[i + 1] === "*") i++; // `**` behaves like `*` here
|
|
55
|
+
re += ".*";
|
|
56
|
+
} else {
|
|
57
|
+
re += ch.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
re += "$";
|
|
61
|
+
return new RegExp(re).test(f);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface AutoGeneratedMatch {
|
|
65
|
+
pattern: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Match an absolute path against the pattern list. `patterns` injectable
|
|
69
|
+
* for tests; caller passes cwd-relative resolution. */
|
|
70
|
+
export function checkAutoGenerated(
|
|
71
|
+
absPath: string,
|
|
72
|
+
cwd: string,
|
|
73
|
+
patterns: readonly string[] = AUTO_GENERATED_PATTERNS,
|
|
74
|
+
): AutoGeneratedMatch | null {
|
|
75
|
+
const rel = isAbsolute(absPath) ? resolvePath(absPath).slice(cwd.length + 1) : absPath;
|
|
76
|
+
for (const pattern of patterns) {
|
|
77
|
+
if (matchesPattern(rel, pattern)) return { pattern };
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The model-facing refusal. Names the pattern + the bash override hatch. */
|
|
83
|
+
export function autoGeneratedError(path: string, match: AutoGeneratedMatch): string {
|
|
84
|
+
return (
|
|
85
|
+
`${path} is auto-generated (matched ${match.pattern}) — edit its source and regenerate ` +
|
|
86
|
+
`(npm install / cargo build / tsc …) instead of editing the output. ` +
|
|
87
|
+
`If you really must, use bash to write it deliberately.`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// read-archive — archive members through the wrapped read (OMP
|
|
2
|
+
// read-archive.ts idea, ponytail shape: shell out to `tar`/`unzip`, present
|
|
3
|
+
// on every darwin/linux target, instead of vendoring a zip reader).
|
|
4
|
+
//
|
|
5
|
+
// Grammar (peeled progressively by index.ts when the literal path misses):
|
|
6
|
+
// pkg.tgz → member listing
|
|
7
|
+
// pkg.tgz:src/x.ts → member content
|
|
8
|
+
// pkg.tgz:src/x.ts:50-80 → member content, then the existing line ranges
|
|
9
|
+
// Member match: exact first, then unique substring (OMP findSuffixMatch
|
|
10
|
+
// semantics); ambiguous → error listing candidates. 1 MB cap before
|
|
11
|
+
// buffering; NUL byte in the first 8 KB → refusal (binary member).
|
|
12
|
+
|
|
13
|
+
import { execFileSync } from "node:child_process";
|
|
14
|
+
|
|
15
|
+
/** Member bytes buffered before refusing/truncating. */
|
|
16
|
+
export const MEMBER_MAX_BYTES = 1024 * 1024;
|
|
17
|
+
/** Entry-listing cap. */
|
|
18
|
+
export const LISTING_MAX = 500;
|
|
19
|
+
const TAR_TIMEOUT_MS = 10_000;
|
|
20
|
+
|
|
21
|
+
export type ArchiveKind = "tar" | "tgz" | "zip";
|
|
22
|
+
|
|
23
|
+
/** Archive extension → kind (order matters: .tar.gz before .gz-less). */
|
|
24
|
+
export function archiveKind(path: string): ArchiveKind | null {
|
|
25
|
+
const p = path.toLowerCase();
|
|
26
|
+
if (p.endsWith(".tar.gz") || p.endsWith(".tgz")) return "tgz";
|
|
27
|
+
if (p.endsWith(".tar")) return "tar";
|
|
28
|
+
if (p.endsWith(".zip")) return "zip";
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function run(cmd: string, args: string[]): string {
|
|
33
|
+
return execFileSync(cmd, args, { timeout: TAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, encoding: "utf8" });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `tar -tf` / `unzip -Z1` listing parsed to member paths. Directories and
|
|
37
|
+
* PaxHeaders are dropped. Exported for tests. */
|
|
38
|
+
export function listMembers(archive: string, kind: ArchiveKind): string[] {
|
|
39
|
+
const out = kind === "zip" ? run("unzip", ["-Z1", archive]) : run("tar", ["-tf", archive]);
|
|
40
|
+
return out
|
|
41
|
+
.split("\n")
|
|
42
|
+
.map((l) => l.trim())
|
|
43
|
+
.filter(
|
|
44
|
+
(l) =>
|
|
45
|
+
l.length > 0 &&
|
|
46
|
+
!l.endsWith("/") &&
|
|
47
|
+
!l.startsWith("PaxHeader") &&
|
|
48
|
+
!l.includes("/PaxHeader") &&
|
|
49
|
+
// bsdtar may print './'-prefixed members
|
|
50
|
+
l !== "." && l !== "./",
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Match a member: exact, then unique substring (OMP findSuffixMatch). */
|
|
55
|
+
export function matchMember(members: string[], wanted: string): { member: string; via: "exact" | "suffix" } | { error: string } {
|
|
56
|
+
const wantedNorm = wanted.replace(/^\.\//, "");
|
|
57
|
+
const exact = members.find((m) => m === wantedNorm || m === `./${wantedNorm}` || m.replace(/^\.\//, "") === wantedNorm);
|
|
58
|
+
if (exact) return { member: exact, via: "exact" };
|
|
59
|
+
const hits = members.filter((m) => m.replace(/^\.\//, "").endsWith(wantedNorm));
|
|
60
|
+
if (hits.length === 1) return { member: hits[0]!, via: "suffix" };
|
|
61
|
+
if (hits.length > 1) {
|
|
62
|
+
return { error: `ambiguous member "${wanted}" — ${hits.length} candidates:\n${hits.slice(0, 10).map((h) => ` ${h}`).join("\n")}` };
|
|
63
|
+
}
|
|
64
|
+
return { error: `no member matching "${wanted}"` };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Extract one member's bytes (tar -xOf / unzip -p). Throws on missing. */
|
|
68
|
+
function extractMember(archive: string, kind: ArchiveKind, member: string): Buffer {
|
|
69
|
+
const cmd = kind === "zip" ? "unzip" : "tar";
|
|
70
|
+
const args = kind === "zip" ? ["-p", archive, member] : ["-xOf", archive, member];
|
|
71
|
+
// execFileSync with a Buffer return keeps binary bytes intact.
|
|
72
|
+
return execFileSync(cmd, args, { timeout: TAR_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024 });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ArchiveReadResult {
|
|
76
|
+
text: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Read an archive (no selector) → listing. */
|
|
80
|
+
export function readArchiveListing(archive: string, kind: ArchiveKind, displayPath: string): ArchiveReadResult {
|
|
81
|
+
const members = listMembers(archive, kind);
|
|
82
|
+
const shown = members.slice(0, LISTING_MAX);
|
|
83
|
+
const footer = members.length > shown.length ? `\n[showing ${shown.length} of ${members.length} members]` : "";
|
|
84
|
+
return { text: `${displayPath} — ${members.length} member(s)\n${shown.join("\n")}${footer}` };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Read one member (optionally pre-sliced by the caller's line ranges). */
|
|
88
|
+
export function readArchiveMember(archive: string, kind: ArchiveKind, member: string, displayPath: string): ArchiveReadResult {
|
|
89
|
+
const members = listMembers(archive, kind);
|
|
90
|
+
const match = matchMember(members, member);
|
|
91
|
+
if ("error" in match) return { text: `${displayPath} : ${member}\n${match.error}` };
|
|
92
|
+
const buf = extractMember(archive, kind, match.member);
|
|
93
|
+
if (buf.length > MEMBER_MAX_BYTES) {
|
|
94
|
+
return { text: `${displayPath} : ${match.member}\nmember is ${buf.length} bytes (cap ${MEMBER_MAX_BYTES}) — extract with bash, then read the file.` };
|
|
95
|
+
}
|
|
96
|
+
if (buf.subarray(0, 8192).includes(0)) {
|
|
97
|
+
return { text: `${displayPath} : ${match.member}\nbinary member — extract with bash (tar -xOf / unzip -p), then read the file.` };
|
|
98
|
+
}
|
|
99
|
+
const text = buf.toString("utf8");
|
|
100
|
+
return { text: `${displayPath} : ${match.member}${match.via === "suffix" ? ` (matched ${match.member})` : ""}\n${text}` };
|
|
101
|
+
}
|