ceulen 0.10.1 → 0.12.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 +107 -1
- package/README.md +56 -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/plan-bridge.ts +18 -0
- package/extensions/lib/registry.test.ts +8 -5
- package/extensions/lib/registry.ts +22 -3
- package/extensions/modules/a2a/configPanel.ts +42 -1
- package/extensions/modules/a2a/index.ts +4 -2
- 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/attachments/configPanel.ts +91 -0
- package/extensions/modules/attachments/index.ts +274 -0
- package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
- package/extensions/modules/attachments/lib/pastes.ts +45 -0
- package/extensions/modules/attachments/lib/paths.ts +74 -0
- package/extensions/modules/attachments/lib/registry.ts +70 -0
- package/extensions/modules/attachments/lib/settings.ts +99 -0
- package/extensions/modules/attachments/lib/tray.ts +74 -0
- package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
- package/extensions/modules/attachments/test/index.test.ts +870 -0
- package/extensions/modules/attachments/test/module.test.ts +53 -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/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/cron/configPanel.ts +103 -0
- package/extensions/modules/cron/index.ts +638 -0
- package/extensions/modules/cron/lib/jobs.ts +201 -0
- package/extensions/modules/cron/lib/schedule.ts +161 -0
- package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
- package/extensions/modules/cron/test/index.test.ts +859 -0
- package/extensions/modules/cron/test/schedule.test.ts +93 -0
- package/extensions/modules/munin/index.ts +3 -1
- package/extensions/modules/permission/index.ts +567 -0
- package/extensions/modules/permission/test/permission.test.ts +789 -0
- package/extensions/modules/plan/index.ts +5 -0
- package/extensions/modules/repair/index.ts +160 -5
- package/extensions/modules/repair/test/freshness.test.ts +209 -0
- package/extensions/modules/repair/test/guard-selector.test.ts +67 -0
- 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/subagent/index.ts +49 -10
- 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 +356 -14
- package/extensions/modules/subagent/test/routing.test.ts +45 -0
- package/extensions/modules/subagent/test/worktree.test.ts +230 -0
- package/extensions/modules/usage/index.ts +193 -71
- package/extensions/modules/usage/test/context.test.ts +160 -120
- package/extensions/modules/web/configPanel.ts +67 -8
- package/extensions/modules/web/index.ts +3 -1
- package/extensions/modules/web/test/a11y.test.ts +1 -1
- package/extensions/modules/web/test/configPanel.test.ts +7 -3
- package/extensions/modules/web/test/settings.test.ts +6 -0
- package/package.json +2 -2
- package/skills/cron/SKILL.md +58 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-attachments — real attachments from pasted/dropped file paths.
|
|
3
|
+
*
|
|
4
|
+
* Drag-drop / clipboard-paste flow:
|
|
5
|
+
* 1. onTerminalInput intercepts path-only bracketed pastes BEFORE the editor:
|
|
6
|
+
* each existing regular file becomes an [[attach:name]] token and a 📎 chip
|
|
7
|
+
* list shows above the editor (widget); non-file paths (directories, typos)
|
|
8
|
+
* stay literal text, and an all-non-file payload passes through untouched.
|
|
9
|
+
* Large plain-text pastes (≥ pasteCollapseLines / pasteCollapseChars) are
|
|
10
|
+
* saved to <agentDir>/pastes/ and collapse to one [[attach:]] token.
|
|
11
|
+
* 2. On submit, the input hook resolves tokens:
|
|
12
|
+
* - images → 📎 path text + real ImageContent parts
|
|
13
|
+
* - text files → 📎 path text (default; model reads on demand via read)
|
|
14
|
+
* or <file> content blocks (inlineTextFiles opt-in)
|
|
15
|
+
* The user's chat line shows only the tidy 📎 chips.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ExtensionAPI, InputEvent, TerminalInputHandler } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
import { detectSupportedImageMimeTypeFromFile } from "@earendil-works/pi-coding-agent";
|
|
20
|
+
import { readFile, stat } from "node:fs/promises";
|
|
21
|
+
import { basename } from "node:path";
|
|
22
|
+
import { readClipboardFilePaths } from "./lib/clipboard-files";
|
|
23
|
+
import { absolutePathSpans, extractImagePaths, isFile } from "./lib/paths";
|
|
24
|
+
import { PASTE_NAME_RE, savePaste } from "./lib/pastes";
|
|
25
|
+
import { lookup, remember } from "./lib/registry";
|
|
26
|
+
import { DEFAULTS, isValidShortcut, loadSettings } from "./lib/settings";
|
|
27
|
+
import { AttachmentTray } from "./lib/tray";
|
|
28
|
+
|
|
29
|
+
const BRACKETED_PASTE = /^\x1b\[200~([\s\S]*?)\x1b\[201~$/;
|
|
30
|
+
|
|
31
|
+
/** Split on whitespace NOT preceded by a backslash, so "/a/with\\ space.png" stays one token. */
|
|
32
|
+
function splitPathTokens(payload: string): string[] {
|
|
33
|
+
return payload.trim().split(/(?<!\\)\s+/).filter(Boolean);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Paste payload is all path-like tokens (optionally escaped spaces)? */
|
|
37
|
+
function looksLikePathPayload(payload: string): boolean {
|
|
38
|
+
const tokens = splitPathTokens(payload);
|
|
39
|
+
return tokens.length > 0 && tokens.every((t) => /^(?:\/|[A-Za-z]:[\\/])/.test(t.replace(/\\ /g, " ")));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export default function piAttachments(pi: ExtensionAPI): void {
|
|
43
|
+
// Re-read on session_start so settings.json edits apply without a full restart.
|
|
44
|
+
let settings = loadSettings();
|
|
45
|
+
const tray = new AttachmentTray();
|
|
46
|
+
let trayUi: { setWidget: (key: string, lines: string[]) => void } | undefined;
|
|
47
|
+
|
|
48
|
+
const updateWidget = () => {
|
|
49
|
+
trayUi?.setWidget("ceulen-attachments", tray.render());
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Captured at session_start — lets onPaste read the editor for prune-sync.
|
|
53
|
+
let editorText: (() => string) | undefined;
|
|
54
|
+
// Disposer returned by ui.onTerminalInput (SDK ≥0.87) — session_start fires
|
|
55
|
+
// once per session, so without disposing, listeners stack across sessions.
|
|
56
|
+
let detachPasteInput: (() => void) | undefined;
|
|
57
|
+
|
|
58
|
+
// 1. Intercept bracketed pastes BEFORE the editor:
|
|
59
|
+
// - path-only payloads → [[attach:]] tokens + chip widget (existing flow)
|
|
60
|
+
// - large plain-text payloads → paste file + one [[attach:]] token
|
|
61
|
+
// onTerminalInput fires for EVERY keystroke, so we also keep the chip
|
|
62
|
+
// list in sync for free: if the user deletes a [[attach:N]] token from
|
|
63
|
+
// the prompt, its chip disappears immediately (and the file is not sent).
|
|
64
|
+
const onPaste: TerminalInputHandler = (data) => {
|
|
65
|
+
if (tray.size > 0 && editorText) {
|
|
66
|
+
const before = tray.size;
|
|
67
|
+
tray.prune(editorText());
|
|
68
|
+
if (tray.size !== before) updateWidget();
|
|
69
|
+
}
|
|
70
|
+
const m = data.match(BRACKETED_PASTE);
|
|
71
|
+
if (!m) return undefined;
|
|
72
|
+
if (!looksLikePathPayload(m[1])) return collapseTextPaste(m[1]);
|
|
73
|
+
const tokens: string[] = [];
|
|
74
|
+
for (const raw of splitPathTokens(m[1])) {
|
|
75
|
+
const path = raw.replace(/\\ /g, " ");
|
|
76
|
+
if (!isFile(path)) {
|
|
77
|
+
// ponytail: directories/nonexistent paths stay literal text — the model
|
|
78
|
+
// reads or lists them itself; upgrade to 📁 chips if dir drops matter
|
|
79
|
+
tokens.push(raw);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const item = tray.add(path);
|
|
83
|
+
remember(item.name, item.path); // survive session restarts
|
|
84
|
+
tokens.push(item.token);
|
|
85
|
+
}
|
|
86
|
+
if (tokens.every((t) => !t.startsWith("[[attach:"))) return undefined;
|
|
87
|
+
updateWidget();
|
|
88
|
+
return { data: tokens.join(" ") };
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// Large plain-text paste → paste file + token (Hermes-style collapse). Unlike
|
|
92
|
+
// Hermes, which re-inlines the full content at submit, the token resolves to
|
|
93
|
+
// a 📎 path — the paste stays isolated from the chat text and is read on demand.
|
|
94
|
+
const collapseTextPaste = (payload: string): { data: string } | undefined => {
|
|
95
|
+
const text = payload.replace(/\r\n?/g, "\n").replace(/^\n+|\n+$/g, "");
|
|
96
|
+
const lines = text.split("\n").length;
|
|
97
|
+
const linesHit = settings.pasteCollapseLines > 0 && lines >= settings.pasteCollapseLines;
|
|
98
|
+
const charsHit = settings.pasteCollapseChars > 0 && text.length >= settings.pasteCollapseChars;
|
|
99
|
+
if (!linesHit && !charsHit) return undefined;
|
|
100
|
+
if (editorText?.()?.startsWith("/")) return undefined; // slash-command args pass through
|
|
101
|
+
// pi-tui invokes onTerminalInput listeners without try/catch — a disk failure
|
|
102
|
+
// here (EACCES/ENOSPC/ENOTDIR) would crash the agent. Degrade gracefully:
|
|
103
|
+
// the paste passes through to the editor untouched.
|
|
104
|
+
try {
|
|
105
|
+
const pastePath = savePaste(text);
|
|
106
|
+
const item = tray.add(pastePath, `pasted text, ${lines} lines`);
|
|
107
|
+
remember(item.name, pastePath); // survive session restarts
|
|
108
|
+
updateWidget();
|
|
109
|
+
return { data: item.token };
|
|
110
|
+
} catch {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
116
|
+
settings = loadSettings();
|
|
117
|
+
// The shortcut was registered at module load with factory-time settings —
|
|
118
|
+
// re-reading doesn't re-register, so an edited-but-valid shortcut is
|
|
119
|
+
// silently dead until restart. Say so instead of a silent no-op.
|
|
120
|
+
const notify = (msg: string) => {
|
|
121
|
+
try {
|
|
122
|
+
if (ctx?.ui?.notify) ctx.ui.notify(msg, "warning");
|
|
123
|
+
else console.warn(msg);
|
|
124
|
+
} catch { /* best-effort */ }
|
|
125
|
+
};
|
|
126
|
+
if (!isValidShortcut(settings.pasteFileShortcut)) {
|
|
127
|
+
notify(`attachments: pasteFileShortcut ${JSON.stringify(settings.pasteFileShortcut)} is not a valid keybinding (e.g. "${DEFAULTS.pasteFileShortcut}") — the paste-file shortcut will never trigger. Fix settings.json and restart Pi.`);
|
|
128
|
+
} else if (settings.pasteFileShortcut !== registeredShortcut) {
|
|
129
|
+
notify(`attachments: pasteFileShortcut changed to ${JSON.stringify(settings.pasteFileShortcut)} in settings.json, but ${JSON.stringify(registeredShortcut)} is active for this session — restart Pi to apply.`);
|
|
130
|
+
}
|
|
131
|
+
trayUi = ctx.ui;
|
|
132
|
+
editorText = (ctx.ui as any).getEditorText?.bind(ctx.ui);
|
|
133
|
+
detachPasteInput?.();
|
|
134
|
+
detachPasteInput = ctx.ui.onTerminalInput?.(onPaste);
|
|
135
|
+
updateWidget();
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// 2. On submit: resolve [[attach:name]] tokens → real content.
|
|
139
|
+
pi.on("input", async (event: InputEvent, ctx) => {
|
|
140
|
+
if (event.source === "extension") return; // don't reprocess our own sends
|
|
141
|
+
|
|
142
|
+
// Prune tray items whose tokens the user deleted from the editor.
|
|
143
|
+
tray.prune(ctx?.ui?.getEditorText?.() ?? event.text ?? "");
|
|
144
|
+
|
|
145
|
+
const raw = event.text ?? "";
|
|
146
|
+
if (!raw.trim()) {
|
|
147
|
+
updateWidget();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const images: Array<{ type: "image"; data: string; mimeType: string }> = [...(event.images ?? [])];
|
|
152
|
+
const attachedImages = new Set<string>(); // paths already attached via tokens
|
|
153
|
+
// All replacements are spans in `raw` coordinates (tokens + typed paths are
|
|
154
|
+
// disjoint by construction), applied right-to-left at the end — so generated
|
|
155
|
+
// blocks are never re-scanned (no nested <file> inlining).
|
|
156
|
+
const replacements: Array<{ start: number; end: number; block: string }> = [];
|
|
157
|
+
|
|
158
|
+
// a. Resolve [[attach:name]] tokens (tray first, then persistent registry).
|
|
159
|
+
// `]` in a basename is allowed when not followed by the closing `]]`
|
|
160
|
+
// (e.g. a dropped file named "we]ird.png").
|
|
161
|
+
const trayItems = tray.resolve(raw); // once per message — loop-invariant
|
|
162
|
+
for (const m of raw.matchAll(/\[\[attach:((?:[^\]]|\](?!\]))+)\]\]/g)) {
|
|
163
|
+
const token = m[0];
|
|
164
|
+
const name = m[1];
|
|
165
|
+
const start = m.index;
|
|
166
|
+
const trayItem = trayItems.find((i) => i.token === token);
|
|
167
|
+
const path = trayItem?.path ?? lookup(name);
|
|
168
|
+
if (!path) continue; // unknown token — leave as-is for the model
|
|
169
|
+
|
|
170
|
+
const mimeType = await detectSupportedImageMimeTypeFromFile(path).catch(() => null);
|
|
171
|
+
if (mimeType) {
|
|
172
|
+
if (!attachedImages.has(path)) {
|
|
173
|
+
// Distinct tokens may resolve to the same path (same file dropped twice) — attach once.
|
|
174
|
+
try {
|
|
175
|
+
const content = await readFile(path);
|
|
176
|
+
images.push({ type: "image", data: content.toString("base64"), mimeType });
|
|
177
|
+
attachedImages.add(path);
|
|
178
|
+
} catch {
|
|
179
|
+
ctx?.ui?.notify?.(`attachments: unreadable image ${path}; attached path only`, "warning");
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
replacements.push({ start, end: start + token.length, block: `📎 ${path}` });
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Non-image: inline as <file> only when inlineTextFiles is on and size allows;
|
|
187
|
+
// otherwise resolve to a 📎 path the model reads on demand.
|
|
188
|
+
let block = `📎 ${path}`;
|
|
189
|
+
if (trayItem?.hint) block += ` (${trayItem.hint})`;
|
|
190
|
+
// Collapsed pastes keep read-on-demand even in inline mode — re-inlining
|
|
191
|
+
// would defeat the whole point of the collapse.
|
|
192
|
+
if (settings.inlineTextFiles && !trayItem?.hint && !PASTE_NAME_RE.test(basename(path))) {
|
|
193
|
+
try {
|
|
194
|
+
const s = await stat(path);
|
|
195
|
+
if (s.size <= settings.maxInlineBytes) {
|
|
196
|
+
const content = (await readFile(path, "utf-8")).replace(/^\uFEFF/, "").replace(/\n$/, "");
|
|
197
|
+
block = `<file name="${path}">\n${content}\n</file>`;
|
|
198
|
+
}
|
|
199
|
+
} catch {
|
|
200
|
+
/* keep 📎 path */
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
replacements.push({ start, end: start + token.length, block });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// b. Existing image paths typed elsewhere in the message → attach too.
|
|
207
|
+
for (const p of extractImagePaths(raw)) {
|
|
208
|
+
if (attachedImages.has(p)) continue;
|
|
209
|
+
try {
|
|
210
|
+
const mimeType = await detectSupportedImageMimeTypeFromFile(p);
|
|
211
|
+
if (!mimeType) continue;
|
|
212
|
+
const content = await readFile(p);
|
|
213
|
+
images.push({ type: "image", data: content.toString("base64"), mimeType });
|
|
214
|
+
} catch {
|
|
215
|
+
/* unreadable file → skip */
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// c. Text-path inlining (opt-in old behavior): absolute text-file paths in
|
|
220
|
+
// the message → <file> blocks. One greedy regex pass yields disjoint
|
|
221
|
+
// spans that never overlap the token spans above.
|
|
222
|
+
if (settings.inlineTextFiles) {
|
|
223
|
+
for (const span of absolutePathSpans(raw)) {
|
|
224
|
+
try {
|
|
225
|
+
const s = await stat(span.path);
|
|
226
|
+
if (s.size > settings.maxInlineBytes) continue;
|
|
227
|
+
const content = (await readFile(span.path, "utf-8")).replace(/^\uFEFF/, "").replace(/\n$/, ""); // stripBom + trailing newline
|
|
228
|
+
replacements.push({ start: span.start, end: span.end, block: `<file name="${span.path}">\n${content}\n</file>` });
|
|
229
|
+
} catch {
|
|
230
|
+
/* unreadable file → skip */
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
let text = raw;
|
|
236
|
+
if (replacements.length) {
|
|
237
|
+
replacements.sort((a, b) => b.start - a.start);
|
|
238
|
+
for (const r of replacements) {
|
|
239
|
+
text = text.slice(0, r.start) + r.block + text.slice(r.end);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Message sent — chips are consumed; hide the widget. Also clear when no
|
|
244
|
+
// token survived into the submitted text (all hand-deleted): expansion
|
|
245
|
+
// produced no references, so keeping the tray would leave stale chips.
|
|
246
|
+
if (tray.size > 0 && (tray.expand(raw) !== raw || trayItems.length === 0)) tray.clear();
|
|
247
|
+
updateWidget();
|
|
248
|
+
|
|
249
|
+
if (text === raw && images.length === (event.images?.length ?? 0)) return;
|
|
250
|
+
return { action: "transform", text, images };
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// 3. Clipboard file paste shortcut → queue into the tray as tokens.
|
|
254
|
+
// ponytail: settings string → KeyId cast; an invalid key never matches (warned at session_start) — and note the shortcut is registered HERE, at module load, so settings edits need a restart
|
|
255
|
+
const registeredShortcut = settings.pasteFileShortcut;
|
|
256
|
+
pi.registerShortcut(registeredShortcut as Parameters<ExtensionAPI["registerShortcut"]>[0], {
|
|
257
|
+
description: "Paste file(s) from clipboard as attachments",
|
|
258
|
+
handler: async (ctx) => {
|
|
259
|
+
// only existing regular files are attachable — Finder/Explorer folder copies pass through
|
|
260
|
+
const paths = (await readClipboardFilePaths()).filter(isFile);
|
|
261
|
+
if (paths.length === 0) {
|
|
262
|
+
ctx.ui.notify("No files in clipboard", "info");
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
const tokens = paths.map((p) => {
|
|
266
|
+
const item = tray.add(p);
|
|
267
|
+
remember(item.name, item.path); // survive session restarts
|
|
268
|
+
return item.token;
|
|
269
|
+
});
|
|
270
|
+
ctx.ui.pasteToEditor(tokens.join(" "));
|
|
271
|
+
updateWidget();
|
|
272
|
+
},
|
|
273
|
+
});
|
|
274
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read file paths (not bytes) from the OS clipboard.
|
|
3
|
+
*
|
|
4
|
+
* Each platform exposes copied files as file URLs / file lists:
|
|
5
|
+
* - macOS: «class furl» via osascript (Finder "Copy")
|
|
6
|
+
* - Windows: FileDropList via PowerShell (Explorer "Copy")
|
|
7
|
+
* - Linux: text/uri-list (xclip / wl-paste), gnome-copied-files fallback
|
|
8
|
+
*
|
|
9
|
+
* Missing tools or an empty (file-less) clipboard yield [] — never throws.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { execFile } from "node:child_process";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { promisify } from "node:util";
|
|
15
|
+
|
|
16
|
+
const run = promisify(execFile);
|
|
17
|
+
|
|
18
|
+
export async function readClipboardFilePaths(): Promise<string[]> {
|
|
19
|
+
try {
|
|
20
|
+
if (process.platform === "darwin") return await readMac();
|
|
21
|
+
if (process.platform === "win32") return await readWindows();
|
|
22
|
+
return await readLinux();
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function readMac(): Promise<string[]> {
|
|
29
|
+
// ponytail: single file only; AppleScript repeat-loop if multi-file copies matter
|
|
30
|
+
const { stdout } = await run("osascript", ["-e", 'POSIX path of (the clipboard as «class furl»)'], { timeout: 3000 });
|
|
31
|
+
return [stdout.trim()].filter(Boolean);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function readWindows(): Promise<string[]> {
|
|
35
|
+
const { stdout } = await run(
|
|
36
|
+
"powershell",
|
|
37
|
+
// Newline-join, not ';': a filename containing ';' survives the split.
|
|
38
|
+
["-NoProfile", "-STA", "-Command", '(Get-Clipboard -Format FileDropList) -join "`n"'],
|
|
39
|
+
{ timeout: 5000 },
|
|
40
|
+
);
|
|
41
|
+
return stdout.split(/\r?\n/).map((p) => p.trim()).filter(Boolean);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function readLinux(): Promise<string[]> {
|
|
45
|
+
const isWayland = Boolean(process.env.WAYLAND_DISPLAY) || process.env.XDG_SESSION_TYPE === "wayland";
|
|
46
|
+
const targets: Array<{ cmd: string; args: string[] }> = isWayland
|
|
47
|
+
? [
|
|
48
|
+
{ cmd: "wl-paste", args: ["--type", "text/uri-list"] },
|
|
49
|
+
{ cmd: "wl-paste", args: ["--type", "x-special/gnome-copied-files"] },
|
|
50
|
+
]
|
|
51
|
+
: [
|
|
52
|
+
{ cmd: "xclip", args: ["-selection", "clipboard", "-t", "text/uri-list", "-o"] },
|
|
53
|
+
{ cmd: "xclip", args: ["-selection", "clipboard", "-t", "x-special/gnome-copied-files", "-o"] },
|
|
54
|
+
];
|
|
55
|
+
for (const t of targets) {
|
|
56
|
+
try {
|
|
57
|
+
const { stdout } = await run(t.cmd, t.args, { timeout: 2000 });
|
|
58
|
+
const paths = parseUriList(stdout);
|
|
59
|
+
if (paths.length) return paths;
|
|
60
|
+
} catch {
|
|
61
|
+
/* try next target */
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Parse `file:///a%20b` lines (uri-list) or `copy\nfile:///...` (gnome-copied-files). */
|
|
68
|
+
export function parseUriList(raw: string): string[] {
|
|
69
|
+
const out: string[] = [];
|
|
70
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
71
|
+
const trimmed = line.trim();
|
|
72
|
+
if (!trimmed.startsWith("file:///") && !trimmed.startsWith("file://localhost/")) continue;
|
|
73
|
+
try {
|
|
74
|
+
out.push(fileURLToPath(trimmed));
|
|
75
|
+
} catch {
|
|
76
|
+
/* skip malformed uri */
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Collapsed large text pastes (Hermes-style): the pasted payload is written to
|
|
3
|
+
* <agentDir>/pastes/paste_<n>_<HHMMSS>_<pid>.txt and the editor receives an
|
|
4
|
+
* [[attach:name]] token. Unlike Hermes — which re-inlines the full content at
|
|
5
|
+
* submit — the token resolves to a 📎 path, so the paste stays isolated from
|
|
6
|
+
* the chat text and the model reads it on demand.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
|
|
13
|
+
// ponytail: oldest-evicted cap; Hermes keeps paste files forever, we don't
|
|
14
|
+
const KEEP = 50;
|
|
15
|
+
|
|
16
|
+
/** Matches paste filenames across modules (inline-suppression, sweep). */
|
|
17
|
+
export const PASTE_NAME_RE = /^paste_\d+_\d{6}_\d+\.txt$/;
|
|
18
|
+
|
|
19
|
+
export function pastesDir(): string {
|
|
20
|
+
const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
21
|
+
return join(dir, "pastes");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let counter = 0;
|
|
25
|
+
|
|
26
|
+
/** Write a paste file, sweep old ones beyond `keep`, return its absolute path. */
|
|
27
|
+
export function savePaste(content: string, keep = KEEP): string {
|
|
28
|
+
const dir = pastesDir();
|
|
29
|
+
mkdirSync(dir, { recursive: true });
|
|
30
|
+
const time = new Date().toTimeString().slice(0, 8).replace(/:/g, "");
|
|
31
|
+
// pid suffix: counter is per-process and the timestamp has 1s resolution —
|
|
32
|
+
// two pi sessions sharing the agent dir could otherwise collide and overwrite.
|
|
33
|
+
const path = join(dir, `paste_${++counter}_${time}_${process.pid}.txt`);
|
|
34
|
+
writeFileSync(path, content, { mode: 0o600 });
|
|
35
|
+
try {
|
|
36
|
+
const files = readdirSync(dir)
|
|
37
|
+
.filter((f) => PASTE_NAME_RE.test(f))
|
|
38
|
+
.map((f) => ({ f, m: statSync(join(dir, f)).mtimeMs }))
|
|
39
|
+
.sort((a, b) => a.m - b.m);
|
|
40
|
+
for (const { f } of files.slice(0, Math.max(0, files.length - keep))) unlinkSync(join(dir, f));
|
|
41
|
+
} catch {
|
|
42
|
+
/* best-effort sweep */
|
|
43
|
+
}
|
|
44
|
+
return path;
|
|
45
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File-path extraction from submitted input text.
|
|
3
|
+
*
|
|
4
|
+
* Conservative by design: images match any existing path with an image
|
|
5
|
+
* extension; text files must be absolute paths (drag-drop and clipboard
|
|
6
|
+
* always produce absolute paths — prose mentions like "see main.rs" never
|
|
7
|
+
* match).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { statSync } from "node:fs";
|
|
11
|
+
// Token may contain backslash-escaped spaces ("with\ space.png" — the form
|
|
12
|
+
// terminals paste on file drops); the escaped form is unescaped before fs access.
|
|
13
|
+
const IMAGE_RE = /[^\s"']+(?:\\ [^\s"']+)*\.(?:png|jpe?g|webp|gif)\b/gi;
|
|
14
|
+
/**
|
|
15
|
+
* Absolute-path token regex: slash segments whose chars may include
|
|
16
|
+
* backslash-escaped spaces (terminal drop form), or Windows drive-letter
|
|
17
|
+
* paths (`C:\Users\x` / `C:/Users/x`) with the same escaped-space charset and
|
|
18
|
+
* backslash as an NTFS separator. isFile() gates every match, so POSIX never
|
|
19
|
+
* false-positives on `C:\…` text and Windows lets the real fs decide.
|
|
20
|
+
*/
|
|
21
|
+
export const ABSOLUTE_PATH_RE =
|
|
22
|
+
/(?:\/(?:[\w.@+-]|\\ )+)+|(?:[A-Za-z]:[\\/](?:[\w.@+-]|\\ )+(?:[\\/](?:[\w.@+-]|\\ )+)*)/g;
|
|
23
|
+
|
|
24
|
+
/** A matched absolute-path token: unescaped path plus its literal span in the text. */
|
|
25
|
+
export interface AbsolutePathSpan {
|
|
26
|
+
path: string;
|
|
27
|
+
/** Start of the literal match (incl. any `\ ` escapes) in the source text. */
|
|
28
|
+
start: number;
|
|
29
|
+
/** End of the literal match. */
|
|
30
|
+
end: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** All distinct existing-file image paths referenced in text (order-preserving). */
|
|
34
|
+
export function extractImagePaths(text: string): string[] {
|
|
35
|
+
const seen = new Set<string>();
|
|
36
|
+
const out: string[] = [];
|
|
37
|
+
for (const match of text.matchAll(IMAGE_RE)) {
|
|
38
|
+
const p = unescape(match[0]);
|
|
39
|
+
if (seen.has(p)) continue;
|
|
40
|
+
if (!isFile(p)) continue;
|
|
41
|
+
seen.add(p);
|
|
42
|
+
out.push(p);
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Existing absolute non-image path tokens with their literal text spans.
|
|
49
|
+
* One greedy regex pass yields disjoint matches, so a span can never be the
|
|
50
|
+
* prefix of another (e.g. /a/b inside /a/b.c); replacement can therefore use
|
|
51
|
+
* the spans directly, right-to-left.
|
|
52
|
+
*/
|
|
53
|
+
export function absolutePathSpans(text: string): AbsolutePathSpan[] {
|
|
54
|
+
const out: AbsolutePathSpan[] = [];
|
|
55
|
+
for (const match of text.matchAll(ABSOLUTE_PATH_RE)) {
|
|
56
|
+
const p = unescape(match[0]);
|
|
57
|
+
if (/\.(?:png|jpe?g|webp|gif)$/i.test(p)) continue; // images are handled separately
|
|
58
|
+
if (!isFile(p)) continue;
|
|
59
|
+
out.push({ path: p, start: match.index, end: match.index + match[0].length });
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function unescape(p: string): string {
|
|
65
|
+
return p.replace(/\\ /g, " ");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isFile(p: string): boolean {
|
|
69
|
+
try {
|
|
70
|
+
return statSync(p).isFile();
|
|
71
|
+
} catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent token→path registry: survives session restarts so an
|
|
3
|
+
* [[attach:file.ts]] token pasted/referenced in a LATER session still
|
|
4
|
+
* resolves to the dropped file's absolute path.
|
|
5
|
+
*
|
|
6
|
+
* Stored at <agentDir>/pi-attachments.json (non-secret: names + paths only),
|
|
7
|
+
* capped at REGISTRY_MAX entries (oldest evicted).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
|
|
14
|
+
const REGISTRY_MAX = 200;
|
|
15
|
+
|
|
16
|
+
export function registryPath(): string {
|
|
17
|
+
const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
18
|
+
return join(dir, "pi-attachments.json");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type Registry = Record<string, string>; // name → absolute path
|
|
22
|
+
|
|
23
|
+
function load(): Registry {
|
|
24
|
+
const p = registryPath();
|
|
25
|
+
if (!existsSync(p)) return {};
|
|
26
|
+
try {
|
|
27
|
+
const j = JSON.parse(readFileSync(p, "utf-8"));
|
|
28
|
+
return j && typeof j === "object" ? j : {};
|
|
29
|
+
} catch {
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function save(reg: Registry): void {
|
|
35
|
+
// Evict oldest (first-inserted) entries beyond the cap.
|
|
36
|
+
const keys = Object.keys(reg);
|
|
37
|
+
if (keys.length > REGISTRY_MAX) {
|
|
38
|
+
for (const k of keys.slice(0, keys.length - REGISTRY_MAX)) delete reg[k];
|
|
39
|
+
}
|
|
40
|
+
// Atomic write (tmp + rename): a crash mid-write never leaves a truncated
|
|
41
|
+
// registry, and a fresh PI_CODING_AGENT_DIR gets created on first save.
|
|
42
|
+
const p = registryPath();
|
|
43
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
44
|
+
writeFileSync(`${p}.tmp`, JSON.stringify(reg, null, 2));
|
|
45
|
+
renameSync(`${p}.tmp`, p);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function remember(name: string, path: string): void {
|
|
49
|
+
// Best-effort persistence: pi-tui invokes terminal-input listeners without
|
|
50
|
+
// try/catch, so an unwritable agent dir (EACCES/ENOSPC/ENOTDIR) would crash
|
|
51
|
+
// pi on a plain file drag-drop. Degrade gracefully like lookup() does.
|
|
52
|
+
try {
|
|
53
|
+
const reg = load();
|
|
54
|
+
delete reg[name]; // re-insert at the end (most recent)
|
|
55
|
+
reg[name] = path;
|
|
56
|
+
save(reg);
|
|
57
|
+
} catch {
|
|
58
|
+
/* keep session-local tray only */
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function lookup(name: string): string | undefined {
|
|
63
|
+
const path = load()[name];
|
|
64
|
+
if (!path) return undefined;
|
|
65
|
+
try {
|
|
66
|
+
return statSync(path).isFile() ? path : undefined;
|
|
67
|
+
} catch {
|
|
68
|
+
return undefined; // stale token — file deleted or volume gone
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settings from the `attachments` key of Pi's settings.json
|
|
3
|
+
* (~/.pi/agent/settings.json, or PI_CODING_AGENT_DIR). Non-secret only.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
|
|
10
|
+
export interface AttachmentsSettings {
|
|
11
|
+
/**
|
|
12
|
+
* When true, text-file attachments are inlined as <file> blocks (Claude Code
|
|
13
|
+
* @file style — content dumped into context, re-read every turn).
|
|
14
|
+
* When false (default), they resolve to a 📎 path the model reads on demand.
|
|
15
|
+
*/
|
|
16
|
+
inlineTextFiles: boolean;
|
|
17
|
+
/** Max bytes for text-file inlining (inlineTextFiles mode only). Default 100_000. */
|
|
18
|
+
maxInlineBytes: number;
|
|
19
|
+
/** Keybinding for paste-file-from-clipboard. Default "alt+shift+v". */
|
|
20
|
+
pasteFileShortcut: string;
|
|
21
|
+
/** Pastes with ≥ this many lines collapse to a paste file + token. 0 disables. Default 10. */
|
|
22
|
+
pasteCollapseLines: number;
|
|
23
|
+
/** Pastes with ≥ this many chars collapse even below the line threshold. 0 disables. Default 2000. */
|
|
24
|
+
pasteCollapseChars: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const DEFAULTS: AttachmentsSettings = {
|
|
28
|
+
inlineTextFiles: false,
|
|
29
|
+
maxInlineBytes: 100_000,
|
|
30
|
+
pasteFileShortcut: "alt+shift+v",
|
|
31
|
+
pasteCollapseLines: 10,
|
|
32
|
+
pasteCollapseChars: 2000,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Read-modify-write `attachments.*` keys into the GLOBAL settings.json
|
|
36
|
+
* (merge, never clobber; atomic tmp+rename; a corrupt file refuses to clobber).
|
|
37
|
+
* Only the given patch keys are written. Returns the written path.
|
|
38
|
+
* Exported for tests + the /config save path. */
|
|
39
|
+
export function writeAttachmentsSection(patch: Partial<AttachmentsSettings>): string {
|
|
40
|
+
const file = join(process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent"), "settings.json");
|
|
41
|
+
let settings: Record<string, unknown>;
|
|
42
|
+
try {
|
|
43
|
+
settings = existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>) : {};
|
|
44
|
+
} catch {
|
|
45
|
+
throw new Error(`${file} is not valid JSON — fix or remove it before saving.`);
|
|
46
|
+
}
|
|
47
|
+
const s = (settings.attachments ?? {}) as Record<string, unknown>;
|
|
48
|
+
Object.assign(s, patch);
|
|
49
|
+
settings.attachments = s;
|
|
50
|
+
mkdirSync(join(file, ".."), { recursive: true });
|
|
51
|
+
const tmp = file + ".tmp";
|
|
52
|
+
writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
|
|
53
|
+
renameSync(tmp, file);
|
|
54
|
+
return file;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function loadSettings(): AttachmentsSettings {
|
|
58
|
+
const dir = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
|
|
59
|
+
const p = join(dir, "settings.json");
|
|
60
|
+
if (!existsSync(p)) return { ...DEFAULTS };
|
|
61
|
+
try {
|
|
62
|
+
const raw = JSON.parse(readFileSync(p, "utf-8"))?.attachments ?? {};
|
|
63
|
+
return {
|
|
64
|
+
inlineTextFiles: typeof raw.inlineTextFiles === "boolean" ? raw.inlineTextFiles : DEFAULTS.inlineTextFiles,
|
|
65
|
+
maxInlineBytes: typeof raw.maxInlineBytes === "number" && raw.maxInlineBytes > 0 ? raw.maxInlineBytes : DEFAULTS.maxInlineBytes,
|
|
66
|
+
pasteFileShortcut: typeof raw.pasteFileShortcut === "string" && raw.pasteFileShortcut ? raw.pasteFileShortcut : DEFAULTS.pasteFileShortcut,
|
|
67
|
+
pasteCollapseLines: typeof raw.pasteCollapseLines === "number" && raw.pasteCollapseLines >= 0 ? raw.pasteCollapseLines : DEFAULTS.pasteCollapseLines,
|
|
68
|
+
pasteCollapseChars: typeof raw.pasteCollapseChars === "number" && raw.pasteCollapseChars >= 0 ? raw.pasteCollapseChars : DEFAULTS.pasteCollapseChars,
|
|
69
|
+
};
|
|
70
|
+
} catch {
|
|
71
|
+
return { ...DEFAULTS };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/* Runtime mirror of pi-tui's KeyId grammar: modifier(+modifier)*+base.
|
|
76
|
+
* A value outside this grammar registers fine but never matches a key event
|
|
77
|
+
* (the TUI compares against parsed KeyIds) — a silent no-op for the user. */
|
|
78
|
+
const MODIFIERS = new Set(["ctrl", "shift", "alt", "super"]);
|
|
79
|
+
// Lowercase entries — pi-tui lowercases the whole KeyId, so "pageUp" is
|
|
80
|
+
// parsed/compared as "pageup".
|
|
81
|
+
const SPECIAL_KEYS = new Set([
|
|
82
|
+
"escape", "esc", "enter", "return", "tab", "space", "backspace", "delete", "insert", "clear",
|
|
83
|
+
"home", "end", "pageup", "pagedown", "up", "down", "left", "right",
|
|
84
|
+
...Array.from({ length: 12 }, (_, i) => `f${i + 1}`),
|
|
85
|
+
]);
|
|
86
|
+
const SYMBOL_KEYS = new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(""));
|
|
87
|
+
|
|
88
|
+
/** True when `s` is a valid pi-tui KeyId (e.g. "alt+shift+v", "ctrl+enter", "f2").
|
|
89
|
+
* Matches pi-tui's parseKeyId exactly: case-insensitive (lowercases the whole
|
|
90
|
+
* id) and duplicate-modifier tolerant (parts.includes), so "Ctrl+Shift+V" and
|
|
91
|
+
* even "ctrl+ctrl+v" are real shortcuts — the validator must not warn about
|
|
92
|
+
* shortcuts pi-tui actually accepts. */
|
|
93
|
+
export function isValidShortcut(s: string): boolean {
|
|
94
|
+
if (typeof s !== "string" || s.length === 0) return false;
|
|
95
|
+
const parts = s.toLowerCase().split("+");
|
|
96
|
+
const base = parts.pop()!;
|
|
97
|
+
const isBase = /^[a-z0-9]$/.test(base) || SPECIAL_KEYS.has(base) || SYMBOL_KEYS.has(base);
|
|
98
|
+
return isBase && parts.every((m) => MODIFIERS.has(m));
|
|
99
|
+
}
|