pi-tuck 1.1.2 → 1.2.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 +65 -0
- package/README.md +7 -3
- package/dist/index.d.ts +2 -6
- package/dist/index.js +16 -111
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +2 -103
- package/dist/src/compaction.js +29 -146
- package/dist/src/diagnostic-replay.js +2 -2
- package/dist/src/diagnostics.d.ts +3 -2
- package/dist/src/diagnostics.js +30 -9
- package/dist/src/history-tools.js +3 -3
- package/dist/src/kept-reads.d.ts +2 -2
- package/dist/src/kept-reads.js +144 -8
- package/dist/src/ledger.d.ts +1 -1
- package/dist/src/ledger.js +5 -3
- package/dist/src/legacy-cleanup.d.ts +3 -0
- package/dist/src/legacy-cleanup.js +190 -0
- package/dist/src/notify.d.ts +3 -0
- package/dist/src/notify.js +13 -0
- package/dist/src/omissions.d.ts +1 -1
- package/dist/src/omissions.js +3 -3
- package/dist/src/path-key.d.ts +3 -0
- package/dist/src/path-key.js +8 -0
- package/dist/src/request-capacity.js +1 -1
- package/dist/src/run.d.ts +1 -3
- package/dist/src/run.js +3 -5
- package/dist/src/source-export.d.ts +1 -1
- package/dist/src/source-export.js +1 -1
- package/dist/src/status.d.ts +0 -6
- package/dist/src/status.js +1 -6
- package/dist/src/tuck/core/content.js +6 -9
- package/dist/src/tuck/core/keyword-query.d.ts +2 -2
- package/dist/src/tuck/core/keyword-query.js +1 -1
- package/dist/src/tuck/core/search-entries.js +5 -5
- package/dist/src/tuck/core/transcript.js +2 -1
- package/dist/src/tuck.js +390 -394
- package/dist/src/windows-private-storage.d.ts +9 -0
- package/dist/src/windows-private-storage.js +90 -0
- package/index.ts +18 -82
- package/package.json +5 -8
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +28 -113
- package/src/diagnostic-replay.ts +2 -2
- package/src/diagnostics.ts +24 -9
- package/src/history-tools.ts +3 -3
- package/src/kept-reads.ts +78 -10
- package/src/ledger.ts +5 -3
- package/src/legacy-cleanup.ts +134 -0
- package/src/notify.ts +10 -0
- package/src/omissions.ts +3 -3
- package/src/path-key.ts +9 -0
- package/src/request-capacity.ts +1 -1
- package/src/run.ts +4 -6
- package/src/source-export.ts +1 -1
- package/src/status.ts +1 -10
- package/src/tuck/core/content.ts +5 -10
- package/src/tuck/core/keyword-query.ts +2 -2
- package/src/tuck/core/search-entries.ts +5 -5
- package/src/tuck/core/transcript.ts +2 -1
- package/src/tuck.ts +329 -335
- package/src/windows-private-storage.ts +94 -0
- package/dist/src/assets.d.ts +0 -58
- package/dist/src/assets.js +0 -80
- package/dist/src/eligibility-cache.d.ts +0 -19
- package/dist/src/eligibility-cache.js +0 -33
- package/dist/src/semantic-recall.d.ts +0 -422
- package/dist/src/semantic-recall.js +0 -1386
- package/dist/src/setup.d.ts +0 -3
- package/dist/src/setup.js +0 -191
- package/scripts/eg2-runtime.py +0 -307
- package/scripts/provision-eg2.py +0 -139
- package/scripts/semantic-worker.py +0 -234
- package/src/assets.ts +0 -92
- package/src/eligibility-cache.ts +0 -43
- package/src/semantic-recall.ts +0 -592
- package/src/setup.ts +0 -163
package/dist/src/kept-reads.js
CHANGED
|
@@ -1,24 +1,160 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { pathKey } from "./path-key.js";
|
|
1
3
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
2
4
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
|
+
// A deliberately bounded shell recognizer: substitutions, redirections and
|
|
6
|
+
// unrecognized composition never certify a command as read-only.
|
|
7
|
+
function shellWords(command, windows) {
|
|
8
|
+
const words = [];
|
|
9
|
+
let word = "", quote = "", started = false, simple = true;
|
|
10
|
+
const flush = () => { if (started)
|
|
11
|
+
words.push(word); word = ""; started = false; };
|
|
12
|
+
for (let i = 0; i < command.length; i++) {
|
|
13
|
+
const c = command[i];
|
|
14
|
+
if (quote === "'") {
|
|
15
|
+
if (c === quote)
|
|
16
|
+
quote = "";
|
|
17
|
+
else
|
|
18
|
+
word += c;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (c === "\\" && !windows) {
|
|
22
|
+
if (command[i + 1] === "\n") {
|
|
23
|
+
i++;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
started = true;
|
|
27
|
+
if (i + 1 < command.length)
|
|
28
|
+
word += command[++i];
|
|
29
|
+
else
|
|
30
|
+
simple = false;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (c === "$" || c === "`")
|
|
34
|
+
simple = false;
|
|
35
|
+
if (windows && (c === "%" || c === "^"))
|
|
36
|
+
simple = false;
|
|
37
|
+
if (quote) {
|
|
38
|
+
if (c === quote)
|
|
39
|
+
quote = "";
|
|
40
|
+
else
|
|
41
|
+
word += c;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (c === "'" || c === '"') {
|
|
45
|
+
quote = c;
|
|
46
|
+
started = true;
|
|
47
|
+
}
|
|
48
|
+
else if (/\s/u.test(c)) {
|
|
49
|
+
flush();
|
|
50
|
+
if (c === "\n") {
|
|
51
|
+
words.push(";");
|
|
52
|
+
simple = false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
else if (/[|&;<>]/u.test(c)) {
|
|
56
|
+
flush();
|
|
57
|
+
const op = command[i + 1] === c ? c + command[++i] : c;
|
|
58
|
+
words.push(op);
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
word += c;
|
|
62
|
+
started = true;
|
|
63
|
+
if (/[(){}]/u.test(c))
|
|
64
|
+
simple = false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
flush();
|
|
68
|
+
return { words, simple: simple && !quote };
|
|
69
|
+
}
|
|
70
|
+
const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
|
|
71
|
+
const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
|
|
72
|
+
const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
|
|
73
|
+
const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
|
|
74
|
+
function mutatingGit(words) {
|
|
75
|
+
return words.some((word, at) => {
|
|
76
|
+
if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git")
|
|
77
|
+
return false;
|
|
78
|
+
for (let i = at + 1; i < words.length; i++) {
|
|
79
|
+
const arg = words[i];
|
|
80
|
+
if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) {
|
|
81
|
+
i++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (arg.startsWith("-"))
|
|
85
|
+
continue;
|
|
86
|
+
return gitMutations.has(arg);
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
function readOnly(words, simple) {
|
|
92
|
+
if (!simple)
|
|
93
|
+
return false;
|
|
94
|
+
if (words[0] === "cd" && words[2] === "&&")
|
|
95
|
+
words = words.slice(3);
|
|
96
|
+
if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word)))
|
|
97
|
+
return false;
|
|
98
|
+
const commands = [[]];
|
|
99
|
+
for (const word of words) {
|
|
100
|
+
if (word === "|")
|
|
101
|
+
commands.push([]);
|
|
102
|
+
else
|
|
103
|
+
commands.at(-1).push(word);
|
|
104
|
+
}
|
|
105
|
+
return commands.every(([name, ...args]) => readers.has(name) || windowsReaders.has(name?.toLowerCase() ?? "") ||
|
|
106
|
+
name === "find" && !args.some(arg => /^-(exec|delete|fprint)/u.test(arg)) ||
|
|
107
|
+
name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
|
|
108
|
+
name === "git" && ["status", "log", "diff", "show"].includes(args[0]));
|
|
109
|
+
}
|
|
3
110
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
4
111
|
export function keptReadCandidates(entries, indices, resolvable) {
|
|
112
|
+
const cwd = entries.find((entry) => entry.type === "session")?.cwd;
|
|
5
113
|
const reads = new Map(), mutations = new Map();
|
|
114
|
+
let allMutated = -1;
|
|
6
115
|
let order = 0;
|
|
7
116
|
for (const entry of entries) {
|
|
8
117
|
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
9
118
|
continue;
|
|
10
119
|
for (const block of entry.message.content) {
|
|
11
|
-
if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
|
|
120
|
+
if (block.type !== "toolCall" || !["read", "write", "edit", "bash"].includes(block.name) ||
|
|
12
121
|
!block.arguments || typeof block.arguments !== "object")
|
|
13
122
|
continue;
|
|
14
|
-
const
|
|
123
|
+
const args = block.arguments;
|
|
124
|
+
order++;
|
|
125
|
+
if (block.name === "bash") {
|
|
126
|
+
if (!reads.size || typeof args.command !== "string")
|
|
127
|
+
continue;
|
|
128
|
+
// Interpret the recorded shell, even when this session is read on another OS.
|
|
129
|
+
const commandName = args.command.trim().split(/\s/u)[0].toLowerCase();
|
|
130
|
+
const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(args.command) ||
|
|
131
|
+
windowsReaders.has(commandName) || windowsMutators.has(commandName);
|
|
132
|
+
const { words, simple } = shellWords(args.command, windows);
|
|
133
|
+
if (readOnly(words, simple))
|
|
134
|
+
continue;
|
|
135
|
+
if (mutatingGit(words) || !simple && mutatingGit(args.command.split(/[\s'"`();|&]+/u))) {
|
|
136
|
+
allMutated = order;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const base = words[0] === "cd" && words[2] === "&&" ? pathKey(words[1], cwd) : cwd;
|
|
140
|
+
const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
|
|
141
|
+
for (const name of names)
|
|
142
|
+
if (name) {
|
|
143
|
+
mutations.set(pathKey(name), order);
|
|
144
|
+
mutations.set(pathKey(name, base), order);
|
|
145
|
+
}
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const path = extractPath(args);
|
|
15
149
|
if (!path || /[\r\n]/u.test(path))
|
|
16
150
|
continue;
|
|
17
|
-
|
|
18
|
-
if (block.name === "read")
|
|
19
|
-
|
|
151
|
+
const key = pathKey(path, cwd);
|
|
152
|
+
if (block.name === "read") {
|
|
153
|
+
if (!("offset" in args) && !("limit" in args))
|
|
154
|
+
reads.set(block.id, { path, key, order });
|
|
155
|
+
}
|
|
20
156
|
else
|
|
21
|
-
mutations.set(
|
|
157
|
+
mutations.set(key, order);
|
|
22
158
|
}
|
|
23
159
|
}
|
|
24
160
|
const seen = new Set(), records = [];
|
|
@@ -27,12 +163,12 @@ export function keptReadCandidates(entries, indices, resolvable) {
|
|
|
27
163
|
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
|
|
28
164
|
continue;
|
|
29
165
|
const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
|
|
30
|
-
if (!read || seen.has(read.
|
|
166
|
+
if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
|
|
31
167
|
continue;
|
|
32
168
|
const text = textOf(entry.message.content);
|
|
33
169
|
if (!text.length || sourceIndex === undefined || !resolvable(entry))
|
|
34
170
|
continue;
|
|
35
|
-
seen.add(read.
|
|
171
|
+
seen.add(read.key);
|
|
36
172
|
records.push({ kind: "section", title: "Kept-read", sourceIndex,
|
|
37
173
|
text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
|
|
38
174
|
}
|
package/dist/src/ledger.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export interface LedgerItem {
|
|
|
18
18
|
}
|
|
19
19
|
/** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
|
|
20
20
|
* A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
|
|
21
|
-
export declare function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string
|
|
21
|
+
export declare function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[];
|
|
22
22
|
/** The ledger: a heading, one record per listed path (at most `keep` and the line cap, newest first), then a count of the older ones.
|
|
23
23
|
* Each line carries its own source index, so a later native omission of that entry removes that line only. */
|
|
24
24
|
export declare function ledgerRecords(items: readonly LedgerItem[], keep?: number): TranscriptRecord[];
|
package/dist/src/ledger.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isLookupTool } from "./tuck/core/recall-operation.js";
|
|
2
2
|
import { isDiscardedResponse } from "./protocol.js";
|
|
3
3
|
import { extractPath } from "./tuck/core/tool-args.js";
|
|
4
|
+
import { pathKey } from "./path-key.js";
|
|
4
5
|
/** Owner default; older distinct paths are counted, not listed. */
|
|
5
6
|
export const MAX_LEDGER_LINES = 60;
|
|
6
7
|
const LEDGER_TITLE = "Files";
|
|
@@ -14,7 +15,7 @@ export const head = (text, max) => {
|
|
|
14
15
|
};
|
|
15
16
|
/** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
|
|
16
17
|
* A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
|
|
17
|
-
export function ledgerItems(entries, indices, resolvable, failedCalls) {
|
|
18
|
+
export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
|
|
18
19
|
const results = new Map();
|
|
19
20
|
for (const entry of entries)
|
|
20
21
|
if (entry.type === "message" && entry.message.role === "toolResult")
|
|
@@ -32,8 +33,9 @@ export function ledgerItems(entries, indices, resolvable, failedCalls) {
|
|
|
32
33
|
const path = operation && extractPath(block.arguments);
|
|
33
34
|
if (!operation || !path || /[\r\n]/u.test(path) || operation === "wrote/edited" && failedCalls.has(block.id))
|
|
34
35
|
continue;
|
|
35
|
-
|
|
36
|
-
last.
|
|
36
|
+
const key = pathKey(path, cwd);
|
|
37
|
+
last.delete(key);
|
|
38
|
+
last.set(key, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
|
|
37
39
|
}
|
|
38
40
|
}
|
|
39
41
|
// Only listed lines show a locator, so resolvability (which renders the entry) is checked for those alone.
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, join } from "node:path";
|
|
5
|
+
import { notify } from "./notify.js";
|
|
6
|
+
const pending = new Map();
|
|
7
|
+
const directories = ["runtime", "python", "index", "downloads"];
|
|
8
|
+
const temporaryDirectory = /^(?:staging-\d+|\.pi-semantic-[A-Za-z0-9]{6})$/;
|
|
9
|
+
const missing = (error) => error.code === "ENOENT";
|
|
10
|
+
async function realDirectory(path) {
|
|
11
|
+
try {
|
|
12
|
+
return (await lstat(path)).isDirectory();
|
|
13
|
+
} // lstat never admits a symlink.
|
|
14
|
+
catch (error) {
|
|
15
|
+
if (missing(error))
|
|
16
|
+
return false;
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Recognize the EG-2 pin fields written by the old setup/provisioner, without pinning a particular release's hashes. */
|
|
21
|
+
function ownPins(value) {
|
|
22
|
+
const record = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
23
|
+
const strings = (v, keys) => keys.every(key => typeof v[key] === "string");
|
|
24
|
+
if (!record(value))
|
|
25
|
+
return false;
|
|
26
|
+
const { embedding, backend, runtime } = value;
|
|
27
|
+
return record(embedding) && record(backend) && record(runtime)
|
|
28
|
+
&& embedding.model === "google/embeddinggemma-2" && backend.name === "llama.cpp"
|
|
29
|
+
&& strings(embedding, ["revision", "queryInstruction", "documentInstruction", "pooling", "dtype"])
|
|
30
|
+
&& embedding.dimensions === 768 && embedding.maxTokens === 8192 && embedding.textOnly === true
|
|
31
|
+
&& strings(backend, ["commit", "artifact", "computePrecision", "compute", "modelRepository", "modelRevision", "modelSHA256"])
|
|
32
|
+
&& typeof backend.gpuLayers === "number" && strings(runtime, ["tokenizers", "python"]);
|
|
33
|
+
}
|
|
34
|
+
async function ownRuntime(path) {
|
|
35
|
+
for (const child of await readdir(path)) {
|
|
36
|
+
// These names come only from this directory's inventory; never follow links to claim ownership.
|
|
37
|
+
const directory = join(path, child), pins = join(directory, "pins.json");
|
|
38
|
+
try {
|
|
39
|
+
if (await realDirectory(directory) && (await lstat(pins)).isFile() && ownPins(JSON.parse(await readFile(pins, "utf8"))))
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (!missing(error) && !(error instanceof SyntaxError))
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
/** lsof uses exit 1 with no output for no matching open files; every other failure is unsafe to delete. */
|
|
50
|
+
async function idle(path) {
|
|
51
|
+
return new Promise((done, reject) => {
|
|
52
|
+
execFile("lsof", ["-t", "+D", path], { timeout: 3000, killSignal: "SIGKILL", maxBuffer: 16 * 1024 }, (error, stdout, stderr) => {
|
|
53
|
+
if (stdout.trim()) {
|
|
54
|
+
done(false);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (error && !(error.code === 1 && !error.killed && !error.signal && !stderr.trim()))
|
|
58
|
+
reject(error);
|
|
59
|
+
else if (stderr.trim())
|
|
60
|
+
reject(new Error(stderr.trim()));
|
|
61
|
+
else
|
|
62
|
+
done(true);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** One bounded, best-effort measurement of only the candidates, so retained files are not counted as freed. */
|
|
67
|
+
async function sizes(paths) {
|
|
68
|
+
if (process.platform === "win32" || !paths.length)
|
|
69
|
+
return new Map();
|
|
70
|
+
const started = performance.now();
|
|
71
|
+
return new Promise(done => {
|
|
72
|
+
try {
|
|
73
|
+
execFile("du", ["-sk", ...paths], { timeout: 1000, killSignal: "SIGKILL", maxBuffer: 16 * 1024 }, (error, stdout) => {
|
|
74
|
+
const measured = new Map();
|
|
75
|
+
if (!error && performance.now() - started <= 1000)
|
|
76
|
+
for (const line of stdout.trimEnd().split("\n")) {
|
|
77
|
+
const match = /^\s*(\d+)\s+(.+)$/.exec(line);
|
|
78
|
+
if (match && paths.includes(match[2]))
|
|
79
|
+
measured.set(match[2], Number(match[1]));
|
|
80
|
+
}
|
|
81
|
+
done(measured);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
done(new Map());
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function reportFailure(failure) {
|
|
90
|
+
try {
|
|
91
|
+
const reason = String(failure.code ?? failure).replace(/[\r\n]+/g, " ");
|
|
92
|
+
process.stderr.write(`pi-tuck could not finish removing its old search files: ${reason}\n`);
|
|
93
|
+
}
|
|
94
|
+
catch { /* A closed stderr must not break a session either. */ }
|
|
95
|
+
}
|
|
96
|
+
/** Once per home, including partial attempts. A later recreation belongs to whoever created it. */
|
|
97
|
+
export function cleanupLegacyFiles(ctx) {
|
|
98
|
+
let home;
|
|
99
|
+
try {
|
|
100
|
+
home = homedir();
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
reportFailure(error);
|
|
104
|
+
return Promise.resolve();
|
|
105
|
+
}
|
|
106
|
+
// Deliberately independent of Pi's per-arm agent folder.
|
|
107
|
+
const agent = join(home, ".pi", "agent"), root = join(agent, "pi-tuck"), marker = join(agent, "pi-tuck-semantic-removed");
|
|
108
|
+
const held = pending.get(root);
|
|
109
|
+
if (held)
|
|
110
|
+
return held;
|
|
111
|
+
const cleanup = (async () => {
|
|
112
|
+
let failure, started = false, removedRoot = false, freed = 0, sized = process.platform !== "win32";
|
|
113
|
+
const removed = [];
|
|
114
|
+
try {
|
|
115
|
+
// Check this before inspecting or sizing the old root, even if Pi's agent folder points elsewhere.
|
|
116
|
+
try {
|
|
117
|
+
await lstat(marker);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (!missing(error))
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
await readdir(home); // An unreadable/missing home means no attempt could start; retry on the next load.
|
|
125
|
+
if (process.platform === "win32" || !await realDirectory(root)) {
|
|
126
|
+
started = true;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const children = await readdir(root);
|
|
130
|
+
started = true;
|
|
131
|
+
const names = [...directories, ...children.filter(name => temporaryDirectory.exec(name)?.[0] === name)];
|
|
132
|
+
const candidates = [];
|
|
133
|
+
for (const name of names) {
|
|
134
|
+
const path = join(root, name);
|
|
135
|
+
try {
|
|
136
|
+
if (await realDirectory(path) && (name !== "runtime" || await ownRuntime(path)) && await idle(path))
|
|
137
|
+
candidates.push(path);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
failure ??= error;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const measured = await sizes(candidates);
|
|
144
|
+
for (const path of candidates) {
|
|
145
|
+
try {
|
|
146
|
+
if (!await realDirectory(root) || !await realDirectory(path))
|
|
147
|
+
continue;
|
|
148
|
+
await rm(path, { recursive: true, force: false });
|
|
149
|
+
removed.push(basename(path));
|
|
150
|
+
sized &&= measured.has(path);
|
|
151
|
+
freed += measured.get(path) ?? 0;
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
if (!missing(error))
|
|
155
|
+
failure ??= error;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// rmdir, rather than recursive removal, preserves every foreign file or skipped directory/link.
|
|
159
|
+
try {
|
|
160
|
+
await rmdir(root);
|
|
161
|
+
removedRoot = true;
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (!missing(error) && !["ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
|
|
165
|
+
failure ??= error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
failure ??= error;
|
|
170
|
+
}
|
|
171
|
+
finally {
|
|
172
|
+
if (started)
|
|
173
|
+
try {
|
|
174
|
+
await mkdir(agent, { recursive: true });
|
|
175
|
+
await writeFile(marker, "", { flag: "wx" });
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error.code !== "EEXIST")
|
|
179
|
+
failure ??= error;
|
|
180
|
+
}
|
|
181
|
+
if (removed.length || removedRoot)
|
|
182
|
+
notify(ctx, `pi-tuck removed its old semantic search files from ${root}${sized ? ` (about ${Math.round(freed / 1024)} MB freed)` : ""}.${removed.length ? ` Removed: ${removed.join(", ")}.` : ""}`, "info");
|
|
183
|
+
if (failure)
|
|
184
|
+
reportFailure(failure);
|
|
185
|
+
}
|
|
186
|
+
})();
|
|
187
|
+
pending.set(root, cleanup);
|
|
188
|
+
void cleanup.finally(() => { pending.delete(root); });
|
|
189
|
+
return cleanup;
|
|
190
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** Operator notices stay outside model context; an ended UI or closed stderr cannot break the session. */
|
|
3
|
+
export declare function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error"): boolean;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Operator notices stay outside model context; an ended UI or closed stderr cannot break the session. */
|
|
2
|
+
export function notify(ctx, message, level) {
|
|
3
|
+
try {
|
|
4
|
+
if (ctx.hasUI === false)
|
|
5
|
+
process.stderr.write(message + "\n");
|
|
6
|
+
else
|
|
7
|
+
ctx.ui.notify(message, level);
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
package/dist/src/omissions.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-a
|
|
|
2
2
|
import { type RecallPolicy } from './recall.js';
|
|
3
3
|
/** Native branch edits supply exclusion; original global indices supply provenance. */
|
|
4
4
|
export declare function omittedSourceIndices(entries: readonly SessionEntry[], branch: readonly SessionEntry[]): ReadonlySet<number>;
|
|
5
|
-
/** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or
|
|
5
|
+
/** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or inference about meaning. */
|
|
6
6
|
export declare function filterOmittedSummary(summary: string, omitted: ReadonlySet<number>, sources?: readonly SessionEntry[], rangeOmitted?: ReadonlySet<number>): string;
|
|
7
7
|
/** Custom quotes carry native entry identity; no text matching or legacy fallback. */
|
|
8
8
|
export declare function filterCustomQuotes(summary: string, entries: readonly SessionEntry[], branch: readonly SessionEntry[], policy?: RecallPolicy): string;
|
package/dist/src/omissions.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { buildGlobalIndexById } from './tuck/core/global-indices.js';
|
|
2
|
-
import { parseRecords, serializeRecord, splitSummary, transcriptHeader } from './tuck/core/transcript.js';
|
|
2
|
+
import { CLOSING_SEPARATOR, parseRecords, serializeRecord, splitSummary, transcriptHeader } from './tuck/core/transcript.js';
|
|
3
3
|
import { textOf } from "./tuck/core/content.js";
|
|
4
4
|
import { isDiscardedResponse } from "./protocol.js";
|
|
5
5
|
import { createRecall } from './recall.js';
|
|
@@ -17,7 +17,7 @@ export function omittedSourceIndices(entries, branch) {
|
|
|
17
17
|
const indices = buildGlobalIndexById(entries);
|
|
18
18
|
return new Set([...edits].flatMap(id => indices.has(id) ? [indices.get(id)] : []));
|
|
19
19
|
}
|
|
20
|
-
/** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or
|
|
20
|
+
/** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or inference about meaning. */
|
|
21
21
|
export function filterOmittedSummary(summary, omitted, sources, rangeOmitted = omitted) {
|
|
22
22
|
if (!omitted.size)
|
|
23
23
|
return summary;
|
|
@@ -101,7 +101,7 @@ export function filterCustomQuotes(summary, entries, branch, policy = {}) {
|
|
|
101
101
|
const { body, closing, version } = split;
|
|
102
102
|
const records = parseRecords(body, version);
|
|
103
103
|
if (!records.some(record => record.role === "custom"))
|
|
104
|
-
return summary;
|
|
104
|
+
return summary.slice(0, summary.indexOf(CLOSING_SEPARATOR)) + closing;
|
|
105
105
|
const omitted = new Set(branch.flatMap(entry => entry.type === 'context_edit' && entry.replacement === null ? [entry.targetId] : []));
|
|
106
106
|
const eligible = createRecall(policy).isHistorySource, indices = buildGlobalIndexById(entries);
|
|
107
107
|
const globalCounts = new Map(), branchSources = new Map();
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
/** Lexical identity for recorded paths, independent of the machine reading the session.
|
|
3
|
+
* Only drive letters fold case; callers retain the original spelling for display. */
|
|
4
|
+
export function pathKey(path, cwd) {
|
|
5
|
+
const slashes = (value) => value.replace(/\\/gu, "/").replace(/^[A-Z]:/u, drive => drive.toLowerCase());
|
|
6
|
+
const name = slashes(path);
|
|
7
|
+
return posix.normalize(cwd && !posix.isAbsolute(name) && !/^[a-z]:\//u.test(name) ? posix.join(slashes(cwd), name) : name);
|
|
8
|
+
}
|
|
@@ -128,6 +128,6 @@ export function carriesPrompt(messages, prompt, role = 'user') {
|
|
|
128
128
|
if (message.role !== 'compactionSummary')
|
|
129
129
|
return false;
|
|
130
130
|
const split = splitSummary(message.summary);
|
|
131
|
-
return split !==
|
|
131
|
+
return split !== undefined && parseRecords(split.body, split.version).some(record => record.kind === 'excerpt' && record.role === role && record.text.includes(prompt));
|
|
132
132
|
});
|
|
133
133
|
}
|
package/dist/src/run.d.ts
CHANGED
|
@@ -11,7 +11,6 @@ type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'>;
|
|
|
11
11
|
export interface CutView {
|
|
12
12
|
session: ExtensionContext['sessionManager'];
|
|
13
13
|
keptFromId: string | undefined;
|
|
14
|
-
viewStart: number;
|
|
15
14
|
hasTuckCut: boolean;
|
|
16
15
|
pending: boolean;
|
|
17
16
|
}
|
|
@@ -43,7 +42,7 @@ export declare class Run {
|
|
|
43
42
|
private state;
|
|
44
43
|
private expiredPlan;
|
|
45
44
|
constructor(phase: Exclude<RunPhase, 'failed' | 'commit-failed'>);
|
|
46
|
-
get phase(): "
|
|
45
|
+
get phase(): "decided" | "claimed" | "expired" | "starting" | "admitted" | "failed" | "commit-failed";
|
|
47
46
|
get expired(): boolean;
|
|
48
47
|
/** Failure data, only present in a failed phase. The phase alone decides admission. */
|
|
49
48
|
get error(): Error | undefined;
|
|
@@ -56,5 +55,4 @@ export declare class Run {
|
|
|
56
55
|
refusalReceipted: boolean;
|
|
57
56
|
clear(): void;
|
|
58
57
|
}
|
|
59
|
-
export declare const createRun: (phase: ConstructorParameters<typeof Run>[0]) => Run;
|
|
60
58
|
export {};
|
package/dist/src/run.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import { hasTuckCut } from './history-tools.js';
|
|
3
|
-
import { viewStart } from './semantic-recall.js';
|
|
4
3
|
import { textOf } from './tuck/core/content.js';
|
|
5
4
|
/** The only owner of a cut that requests carry before Pi saves it. */
|
|
6
5
|
export class PendingCut {
|
|
@@ -12,7 +11,7 @@ export class PendingCut {
|
|
|
12
11
|
take() { const cut = this.cut; this.clear(); return cut; }
|
|
13
12
|
view(ctx, entries = []) {
|
|
14
13
|
const live = ctx.sessionManager, leaf = live.getLeafId?.(), held = this.preview;
|
|
15
|
-
// Native entries are append-only; a leaf move invalidates both the saved and pending views
|
|
14
|
+
// Native entries are append-only; a leaf move invalidates both the saved and pending views.
|
|
16
15
|
if (!entries.length && leaf !== undefined && held && held.manager === live && held.cwd === ctx.cwd && held.leaf === leaf)
|
|
17
16
|
return held.view;
|
|
18
17
|
const branch = live.getBranch(), cut = this.cut;
|
|
@@ -24,7 +23,7 @@ export class PendingCut {
|
|
|
24
23
|
if (!cut && !entries.length) {
|
|
25
24
|
const last = branch.findLast(entry => entry.type === 'compaction');
|
|
26
25
|
return remember({ session: live, keptFromId: last?.type === 'compaction' ? last.firstKeptEntryId : undefined,
|
|
27
|
-
|
|
26
|
+
hasTuckCut: hasTuckCut(branch), pending: false });
|
|
28
27
|
}
|
|
29
28
|
// A compact-all plan predates the prompt. Keep from the first appended entry, skipping our capacity receipts.
|
|
30
29
|
const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.branchLength)
|
|
@@ -48,7 +47,7 @@ export class PendingCut {
|
|
|
48
47
|
}
|
|
49
48
|
const previewBranch = session.getBranch(), last = previewBranch.findLast(entry => entry.type === 'compaction');
|
|
50
49
|
return remember({ session, keptFromId: last?.type === 'compaction' ? last.firstKeptEntryId : undefined,
|
|
51
|
-
|
|
50
|
+
hasTuckCut: hasTuckCut(previewBranch), pending: Boolean(cut) });
|
|
52
51
|
}
|
|
53
52
|
}
|
|
54
53
|
/** Text bridges before Pi appends the starting message. Once visible, every reader uses its entry id.
|
|
@@ -141,4 +140,3 @@ export class Run {
|
|
|
141
140
|
this.expiredPlan = false;
|
|
142
141
|
}
|
|
143
142
|
}
|
|
144
|
-
export const createRun = (phase) => new Run(phase);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { type RecallPolicy, type ReadableEntry } from "./recall.js";
|
|
3
|
-
/** Select one original readable source. No filesystem, state, paging or
|
|
3
|
+
/** Select one original readable source. No filesystem, state, paging or inference about meaning. */
|
|
4
4
|
export declare function exportSource(entries: readonly SessionEntry[], branch: readonly SessionEntry[], input: {
|
|
5
5
|
entryId: string;
|
|
6
6
|
} | {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
|
|
2
2
|
import { createRecall } from "./recall.js";
|
|
3
|
-
/** Select one original readable source. No filesystem, state, paging or
|
|
3
|
+
/** Select one original readable source. No filesystem, state, paging or inference about meaning. */
|
|
4
4
|
export function exportSource(entries, branch, input, policy = {}) {
|
|
5
5
|
if (branch.some(e => e.type === "context_edit" && e.replacement !== null))
|
|
6
6
|
throw new Error("pi-tuck does not support replacement context edits");
|
package/dist/src/status.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { SemanticState } from "./semantic-recall.js";
|
|
2
1
|
/** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
|
|
3
2
|
export declare const LOADED_VERSION: string;
|
|
4
3
|
/** `/tuck`: what an operator needs to know in words, from what is already recorded. It reads; it changes nothing the model sees. */
|
|
@@ -15,9 +14,4 @@ export declare function statusText(input: {
|
|
|
15
14
|
}[];
|
|
16
15
|
pending?: boolean;
|
|
17
16
|
cutAt: number | undefined;
|
|
18
|
-
search: boolean;
|
|
19
|
-
semantic: {
|
|
20
|
-
state: SemanticState;
|
|
21
|
-
lastError: string | null;
|
|
22
|
-
};
|
|
23
17
|
}): string;
|
package/dist/src/status.js
CHANGED
|
@@ -25,10 +25,6 @@ export function statusText(input) {
|
|
|
25
25
|
const native = cuts.length - ours.length;
|
|
26
26
|
const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
|
|
27
27
|
entry.data?.kind === "retry").length;
|
|
28
|
-
const searchLine = !input.search ? "Search: by keyword (search by meaning needs macOS on Apple silicon)."
|
|
29
|
-
: input.semantic.state === "ready" || input.semantic.state === "waiting" ? "Search: by meaning and keyword."
|
|
30
|
-
: input.semantic.state === "preparing" ? "Search: by meaning and keyword; indexing history in the background."
|
|
31
|
-
: `Search: by keyword; ${lower(input.semantic.lastError ?? "semantic recall is off in this session (/tuck-semantic on)")}.`.replace(/\.\.$/, ".");
|
|
32
28
|
return [
|
|
33
29
|
`pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
|
|
34
30
|
cutLine,
|
|
@@ -36,7 +32,6 @@ export function statusText(input) {
|
|
|
36
32
|
...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
|
|
37
33
|
...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
|
|
38
34
|
input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: fixed at cutAt ${input.cutAt} of the input room. Remove cutAt from pi-tuck.json to let it adapt.`,
|
|
39
|
-
|
|
35
|
+
"Search: by keyword.",
|
|
40
36
|
].join("\n");
|
|
41
37
|
}
|
|
42
|
-
const lower = (text) => text.charAt(0).toLowerCase() + text.slice(1);
|
|
@@ -12,18 +12,15 @@ export const clip = (text, max = 200) => {
|
|
|
12
12
|
}
|
|
13
13
|
return text.slice(0, end);
|
|
14
14
|
};
|
|
15
|
-
|
|
15
|
+
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
16
|
+
export const isTextOnly = (content) => typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
|
|
17
|
+
export const textOf = (content) => {
|
|
16
18
|
if (!content)
|
|
17
|
-
return
|
|
19
|
+
return "";
|
|
18
20
|
if (typeof content === "string")
|
|
19
|
-
return
|
|
20
|
-
return content
|
|
21
|
-
.filter((part) => part.type === "text")
|
|
22
|
-
.map((part) => part.text);
|
|
21
|
+
return content;
|
|
22
|
+
return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
23
23
|
};
|
|
24
|
-
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
25
|
-
export const isTextOnly = (content) => typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
|
|
26
|
-
export const textOf = (content) => textParts(content).join("\n");
|
|
27
24
|
/**
|
|
28
25
|
* Extract every scalar string argument from a tool call for search indexing
|
|
29
26
|
* — command, query, content, oldText/newText, etc. Generic value walk (no
|