pi-tuck 1.2.0 → 1.3.1
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 +18 -0
- package/README.md +28 -59
- package/dist/src/bash-command.d.ts +8 -0
- package/dist/src/bash-command.js +116 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/diagnostic-replay.js +1 -1
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/kept-reads.js +5 -114
- package/dist/src/kept-searches.d.ts +11 -0
- package/dist/src/kept-searches.js +202 -0
- package/dist/src/tuck/core/content.d.ts +0 -11
- package/dist/src/tuck/core/content.js +0 -47
- package/dist/src/tuck/core/search-entries.d.ts +5 -28
- package/dist/src/tuck/core/search-entries.js +13 -155
- package/dist/src/tuck.d.ts +7 -15
- package/dist/src/tuck.js +32 -28
- package/package.json +1 -1
- package/src/bash-command.ts +59 -0
- package/src/build-id.ts +1 -1
- package/src/diagnostic-replay.ts +1 -1
- package/src/kept-reads.ts +5 -56
- package/src/kept-searches.ts +163 -0
- package/src/tuck/core/content.ts +0 -43
- package/src/tuck/core/search-entries.ts +14 -201
- package/src/tuck.ts +33 -34
package/dist/src/tuck.js
CHANGED
|
@@ -8,6 +8,7 @@ import { omissionRecord, userPrefixRecords } from "./tuck/core/brief.js";
|
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
10
|
import { keptReadCandidates } from "./kept-reads.js";
|
|
11
|
+
import { keptSearchCandidates } from "./kept-searches.js";
|
|
11
12
|
import { convertToLlm, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
12
13
|
import { ATTEMPT_NOTICE, createRecall } from "./recall.js";
|
|
13
14
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
@@ -17,11 +18,12 @@ import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/
|
|
|
17
18
|
import { buildGlobalIndexById } from "./tuck/core/global-indices.js";
|
|
18
19
|
import { compileDialogue } from "./tuck/core/summarize.js";
|
|
19
20
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query.js";
|
|
20
|
-
import {
|
|
21
|
-
export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery,
|
|
22
|
-
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
import { rankRecallRows } from "./tuck/core/search-entries.js";
|
|
22
|
+
export const tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
23
|
+
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
24
|
+
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
25
|
+
export function tuckDraft(tuck, event, ctx, reserveTokens, measure, policy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId) {
|
|
26
|
+
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
|
|
25
27
|
}
|
|
26
28
|
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
|
|
27
29
|
/** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
|
|
@@ -377,22 +379,26 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
377
379
|
const maxSummaryCharactersAt = (at) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
378
380
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
379
381
|
let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
+
const keptResults = [], counts = new Map();
|
|
383
|
+
const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry) => readable(entry) !== undefined;
|
|
384
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
385
|
+
.sort((a, b) => b.sourceIndex - a.sourceIndex || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
386
|
+
for (const record of candidates) {
|
|
387
|
+
if ((counts.get(record.title) ?? 0) === 4)
|
|
388
|
+
continue;
|
|
382
389
|
const cost = lineCost([record]);
|
|
383
390
|
if (cost > allowance)
|
|
384
391
|
continue;
|
|
385
|
-
|
|
392
|
+
keptResults.push(record);
|
|
386
393
|
allowance -= cost;
|
|
387
|
-
|
|
388
|
-
break;
|
|
394
|
+
counts.set(record.title, (counts.get(record.title) ?? 0) + 1);
|
|
389
395
|
}
|
|
390
|
-
let ledger = [...lists.records, ...
|
|
396
|
+
let ledger = [...lists.records, ...keptResults];
|
|
391
397
|
// List caps are existing ranking policy; only the carried target is a
|
|
392
398
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
393
|
-
while (
|
|
394
|
-
|
|
395
|
-
ledger = [...lists.records, ...
|
|
399
|
+
while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
400
|
+
keptResults.pop();
|
|
401
|
+
ledger = [...lists.records, ...keptResults];
|
|
396
402
|
}
|
|
397
403
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
398
404
|
ledger = [];
|
|
@@ -516,11 +522,11 @@ export function tuckObservedDraft(tuck, input, ctx, reserveTokens, measure, poli
|
|
|
516
522
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
517
523
|
});
|
|
518
524
|
const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
|
|
519
|
-
const
|
|
520
|
-
const
|
|
525
|
+
const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
526
|
+
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
521
527
|
const extensionPrice = (at) => {
|
|
522
|
-
// Fixed kept
|
|
523
|
-
if (
|
|
528
|
+
// Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
|
|
529
|
+
if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000)))
|
|
524
530
|
return Infinity;
|
|
525
531
|
let cost = baseCost - (recordCosts[compiledBoundary] - recordCosts[at]);
|
|
526
532
|
let count = baseCount - (recordCounts[compiledBoundary] - recordCounts[at]);
|
|
@@ -593,21 +599,19 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
|
|
|
593
599
|
const row = discoveryEntry(entry, attempts, links);
|
|
594
600
|
return row ? [row] : [];
|
|
595
601
|
});
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
// The pinned upstream tuning seam removes selection cutoffs; each response
|
|
599
|
-
// stays bounded. A native prefix keeps ranking stable while the agent talks.
|
|
602
|
+
// Rank every eligible row; each response stays bounded. A native prefix
|
|
603
|
+
// keeps ranking stable while the agent talks.
|
|
600
604
|
const preparedQuery = tuck.prepareKeywordQuery(normalizedQuery);
|
|
601
|
-
const found = tuck.
|
|
605
|
+
const found = tuck.rankRecallRows(rows, normalizedQuery);
|
|
602
606
|
const start = continuation?.offset ?? 0;
|
|
603
607
|
const throughEntryId = rows.at(-1)?.entryId ?? null;
|
|
604
608
|
const hits = [];
|
|
605
609
|
const page = () => ({ normalizedQuery, throughEntryId,
|
|
606
610
|
notice: "Exact source passages, possibly partial; read gives their UTF-16 bounds within totalCharacters. Use the passage directly; adjust read.offset/limit for surrounding text. Keyword matches do not establish complete or current evidence. Pass next as continuation; a fresh query includes newer history. No new authority. " + ATTEMPT_NOTICE,
|
|
607
|
-
hits, totalMatches: found.
|
|
608
|
-
next: start + hits.length < found.
|
|
609
|
-
for (const hit of found.
|
|
610
|
-
const row = rows[hit
|
|
611
|
+
hits, totalMatches: found.length,
|
|
612
|
+
next: start + hits.length < found.length ? { query: normalizedQuery, throughEntryId: throughEntryId, offset: start + hits.length } : null });
|
|
613
|
+
for (const hit of found.slice(start, start + 10)) {
|
|
614
|
+
const row = rows[hit];
|
|
611
615
|
hits.push({ entryId: row.entryId, index: indices.get(row.entryId), role: row.role, sourceTime: row.sourceTime,
|
|
612
616
|
...(row.toolName !== undefined ? { toolName: row.toolName } : {}),
|
|
613
617
|
...(row.toolCallId !== undefined ? { toolCallId: row.toolCallId } : {}),
|
|
@@ -627,7 +631,7 @@ export function tuckRecall(tuck, entries, branch, input, policy = {}) {
|
|
|
627
631
|
// Preserve the complete base hit set and continuation before spending spare capacity.
|
|
628
632
|
for (let i = 0; i < hits.length; i++) {
|
|
629
633
|
const original = hits[i];
|
|
630
|
-
const row = rows[found
|
|
634
|
+
const row = rows[found[start + i]];
|
|
631
635
|
hits[i] = { ...original, ...discoveryWholeRange(row, original) };
|
|
632
636
|
if (JSON.stringify(page()).length > MAX_RANKED_RESPONSE_CHARACTERS)
|
|
633
637
|
hits[i] = original;
|
package/package.json
CHANGED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
|
|
3
|
+
// A deliberately bounded shell recognizer: substitutions, redirections and
|
|
4
|
+
// unrecognized composition never certify a command as read-only.
|
|
5
|
+
function shellWords(command: string, windows: boolean): { words: string[]; simple: boolean } {
|
|
6
|
+
const words: string[] = []; let word = "", quote = "", started = false, simple = true;
|
|
7
|
+
const flush = () => { if (started) words.push(word); word = ""; started = false; };
|
|
8
|
+
for (let i = 0; i < command.length; i++) {
|
|
9
|
+
const c = command[i]!;
|
|
10
|
+
if (quote === "'") { if (c === quote) quote = ""; else word += c; continue; }
|
|
11
|
+
if (c === "\\" && !windows) { if (command[i + 1] === "\n") { i++; continue; } started = true; if (i + 1 < command.length) word += command[++i]; else simple = false; continue; }
|
|
12
|
+
if (c === "$" || c === "`") simple = false;
|
|
13
|
+
if (windows && (c === "%" || c === "^")) simple = false;
|
|
14
|
+
if (quote) { if (c === quote) quote = ""; else word += c; continue; }
|
|
15
|
+
if (c === "'" || c === '"') { quote = c; started = true; }
|
|
16
|
+
else if (/\s/u.test(c)) { flush(); if (c === "\n") { words.push(";"); simple = false; } }
|
|
17
|
+
else if (/[|&;<>]/u.test(c)) { flush(); const op = command[i + 1] === c ? c + command[++i] : c; words.push(op); }
|
|
18
|
+
else { word += c; started = true; if (/[(){}]/u.test(c)) simple = false; }
|
|
19
|
+
}
|
|
20
|
+
flush(); return { words, simple: simple && !quote };
|
|
21
|
+
}
|
|
22
|
+
const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
|
|
23
|
+
const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
|
|
24
|
+
const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
|
|
25
|
+
const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
|
|
26
|
+
function mutatingGit(words: string[]): boolean {
|
|
27
|
+
return words.some((word, at) => {
|
|
28
|
+
if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git") return false;
|
|
29
|
+
for (let i = at + 1; i < words.length; i++) {
|
|
30
|
+
const arg = words[i]!;
|
|
31
|
+
if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) { i++; continue; }
|
|
32
|
+
if (arg.startsWith("-")) continue;
|
|
33
|
+
return gitMutations.has(arg);
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
function readOnly(words: string[], simple: boolean): boolean {
|
|
39
|
+
if (!simple) return false;
|
|
40
|
+
if (words[0] === "cd" && words[2] === "&&") words = words.slice(3);
|
|
41
|
+
if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word))) return false;
|
|
42
|
+
const commands: string[][] = [[]];
|
|
43
|
+
for (const word of words) { if (word === "|") commands.push([]); else commands.at(-1)!.push(word); }
|
|
44
|
+
return commands.every(([name, ...args]) => readers.has(name!) || windowsReaders.has(name?.toLowerCase() ?? "") ||
|
|
45
|
+
name === "find" && !args.some(arg => /^-(exec|ok|delete|fprint)/u.test(arg)) ||
|
|
46
|
+
name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
|
|
47
|
+
name === "git" && ["status", "log", "diff", "show"].includes(args[0]!));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Classify the recorded shell independently of the host OS. Both kept-result lanes use this decision. */
|
|
51
|
+
export function classifyBash(command: string, cwd?: string) {
|
|
52
|
+
const commandName = command.trim().split(/\s/u)[0]!.toLowerCase();
|
|
53
|
+
const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(command) ||
|
|
54
|
+
windowsReaders.has(commandName) || windowsMutators.has(commandName);
|
|
55
|
+
const { words, simple } = shellWords(command, windows);
|
|
56
|
+
return { words, windows, readOnly: readOnly(words, simple),
|
|
57
|
+
mutatesAll: mutatingGit(words) || !simple && mutatingGit(command.split(/[\s'"`();|&]+/u)),
|
|
58
|
+
directory: words[0] === "cd" && words[2] === "&&" ? words[1] : undefined };
|
|
59
|
+
}
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
|
package/src/diagnostic-replay.ts
CHANGED
|
@@ -10,7 +10,7 @@ export function inspectIncident(records: IncidentRecord[]) {
|
|
|
10
10
|
const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
|
|
11
11
|
if (i.branchEntryIds?.length) manager.branch(i.branchEntryIds.at(-1)!);
|
|
12
12
|
const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } } as unknown as ExtensionContext;
|
|
13
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary
|
|
13
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
14
14
|
const proposal = records.find(r => r.kind === 'proposal' && (r.data as { details?: { diagnosticReceipt?: { id?: string } } })?.details?.diagnosticReceipt?.id === i.receiptId)?.data as { summary?: string; firstKeptEntryId?: string } | undefined;
|
|
15
15
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
16
16
|
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
|
package/src/kept-reads.ts
CHANGED
|
@@ -1,57 +1,10 @@
|
|
|
1
1
|
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
2
|
+
import { classifyBash } from "./bash-command";
|
|
3
3
|
import { pathKey } from "./path-key";
|
|
4
4
|
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
5
5
|
import { extractPath } from "./tuck/core/tool-args";
|
|
6
6
|
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
7
7
|
|
|
8
|
-
// A deliberately bounded shell recognizer: substitutions, redirections and
|
|
9
|
-
// unrecognized composition never certify a command as read-only.
|
|
10
|
-
function shellWords(command: string, windows: boolean): { words: string[]; simple: boolean } {
|
|
11
|
-
const words: string[] = []; let word = "", quote = "", started = false, simple = true;
|
|
12
|
-
const flush = () => { if (started) words.push(word); word = ""; started = false; };
|
|
13
|
-
for (let i = 0; i < command.length; i++) {
|
|
14
|
-
const c = command[i]!;
|
|
15
|
-
if (quote === "'") { if (c === quote) quote = ""; else word += c; continue; }
|
|
16
|
-
if (c === "\\" && !windows) { if (command[i + 1] === "\n") { i++; continue; } started = true; if (i + 1 < command.length) word += command[++i]; else simple = false; continue; }
|
|
17
|
-
if (c === "$" || c === "`") simple = false;
|
|
18
|
-
if (windows && (c === "%" || c === "^")) simple = false;
|
|
19
|
-
if (quote) { if (c === quote) quote = ""; else word += c; continue; }
|
|
20
|
-
if (c === "'" || c === '"') { quote = c; started = true; }
|
|
21
|
-
else if (/\s/u.test(c)) { flush(); if (c === "\n") { words.push(";"); simple = false; } }
|
|
22
|
-
else if (/[|&;<>]/u.test(c)) { flush(); const op = command[i + 1] === c ? c + command[++i] : c; words.push(op); }
|
|
23
|
-
else { word += c; started = true; if (/[(){}]/u.test(c)) simple = false; }
|
|
24
|
-
}
|
|
25
|
-
flush(); return { words, simple: simple && !quote };
|
|
26
|
-
}
|
|
27
|
-
const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
|
|
28
|
-
const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
|
|
29
|
-
const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
|
|
30
|
-
const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
|
|
31
|
-
function mutatingGit(words: string[]): boolean {
|
|
32
|
-
return words.some((word, at) => {
|
|
33
|
-
if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git") return false;
|
|
34
|
-
for (let i = at + 1; i < words.length; i++) {
|
|
35
|
-
const arg = words[i]!;
|
|
36
|
-
if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) { i++; continue; }
|
|
37
|
-
if (arg.startsWith("-")) continue;
|
|
38
|
-
return gitMutations.has(arg);
|
|
39
|
-
}
|
|
40
|
-
return false;
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
function readOnly(words: string[], simple: boolean): boolean {
|
|
44
|
-
if (!simple) return false;
|
|
45
|
-
if (words[0] === "cd" && words[2] === "&&") words = words.slice(3);
|
|
46
|
-
if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word))) return false;
|
|
47
|
-
const commands: string[][] = [[]];
|
|
48
|
-
for (const word of words) { if (word === "|") commands.push([]); else commands.at(-1)!.push(word); }
|
|
49
|
-
return commands.every(([name, ...args]) => readers.has(name!) || windowsReaders.has(name?.toLowerCase() ?? "") ||
|
|
50
|
-
name === "find" && !args.some(arg => /^-(exec|delete|fprint)/u.test(arg)) ||
|
|
51
|
-
name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
|
|
52
|
-
name === "git" && ["status", "log", "diff", "show"].includes(args[0]!));
|
|
53
|
-
}
|
|
54
|
-
|
|
55
8
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
56
9
|
export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
|
|
57
10
|
resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
|
|
@@ -68,14 +21,10 @@ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHead
|
|
|
68
21
|
order++;
|
|
69
22
|
if (block.name === "bash") {
|
|
70
23
|
if (!reads.size || typeof args.command !== "string") continue;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const { words, simple } = shellWords(args.command, windows);
|
|
76
|
-
if (readOnly(words, simple)) continue;
|
|
77
|
-
if (mutatingGit(words) || !simple && mutatingGit(args.command.split(/[\s'"`();|&]+/u))) { allMutated = order; continue; }
|
|
78
|
-
const base = words[0] === "cd" && words[2] === "&&" ? pathKey(words[1]!, cwd) : cwd;
|
|
24
|
+
const command = classifyBash(args.command, cwd), { words } = command;
|
|
25
|
+
if (command.readOnly) continue;
|
|
26
|
+
if (command.mutatesAll) { allMutated = order; continue; }
|
|
27
|
+
const base = command.directory === undefined ? cwd : pathKey(command.directory, cwd);
|
|
79
28
|
const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
|
|
80
29
|
for (const name of names) if (name) { mutations.set(pathKey(name), order); mutations.set(pathKey(name, base), order); }
|
|
81
30
|
continue;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { classifyBash } from "./bash-command";
|
|
3
|
+
import { pathKey } from "./path-key";
|
|
4
|
+
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
5
|
+
import { extractPath } from "./tuck/core/tool-args";
|
|
6
|
+
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
7
|
+
|
|
8
|
+
interface Pipeline { directory?: string; stages: string[][] }
|
|
9
|
+
const searchTail = new Set(["head", "tail", "sort", "uniq", "wc", "cut", "grep"]);
|
|
10
|
+
|
|
11
|
+
/** A small shell lexer, not a shell interpreter. Unclassified shell syntax fails closed. */
|
|
12
|
+
function pipeline(command: string, windows: boolean): Pipeline | undefined {
|
|
13
|
+
if (/[;<>`\r\n]/u.test(command) || command.includes("$(")) return;
|
|
14
|
+
const expands = (at: number) => command[at] === "$" && /[\w{@*#!?$-]/u.test(command[at + 1] ?? "");
|
|
15
|
+
const tokens: { word: string; operator?: boolean }[] = [];
|
|
16
|
+
let word = "", started = false, quote = "";
|
|
17
|
+
const flush = () => { if (started) tokens.push({ word }); word = ""; started = false; };
|
|
18
|
+
for (let at = 0; at < command.length; at++) {
|
|
19
|
+
const ch = command[at]!;
|
|
20
|
+
if (quote) {
|
|
21
|
+
if (ch === quote) quote = "";
|
|
22
|
+
else if (!windows && ch === "\\" && quote === '"' && /[\\"$]/u.test(command[at + 1] ?? "")) word += command[++at];
|
|
23
|
+
else if (quote === '"' && expands(at)) return;
|
|
24
|
+
else word += ch;
|
|
25
|
+
} else if (ch === "'" || ch === '"') { quote = ch; started = true; }
|
|
26
|
+
else if (!windows && ch === "\\") { if (++at === command.length) return; word += command[at]; started = true; }
|
|
27
|
+
else if (/\s/u.test(ch)) flush();
|
|
28
|
+
else if (ch === "|" || ch === "&") {
|
|
29
|
+
flush();
|
|
30
|
+
const op = command[at + 1] === ch ? ch + command[++at] : ch;
|
|
31
|
+
if (op !== "|" && op !== "&&") return;
|
|
32
|
+
tokens.push({ word: op, operator: true });
|
|
33
|
+
} else if (/[()]/u.test(ch) || ch === "#" && !started || expands(at)) return;
|
|
34
|
+
else { word += ch; started = true; }
|
|
35
|
+
}
|
|
36
|
+
if (quote) return;
|
|
37
|
+
flush();
|
|
38
|
+
let directory: string | undefined;
|
|
39
|
+
if (tokens[0]?.word === "cd" && tokens[1] && !tokens[1].operator && tokens[1].word &&
|
|
40
|
+
!tokens[1].word.startsWith("-") && tokens[2]?.operator && tokens[2].word === "&&") {
|
|
41
|
+
directory = tokens[1].word; tokens.splice(0, 3);
|
|
42
|
+
}
|
|
43
|
+
const stages: string[][] = [[]];
|
|
44
|
+
for (const token of tokens) {
|
|
45
|
+
if (token.operator) {
|
|
46
|
+
if (token.word !== "|" || !stages.at(-1)!.length) return;
|
|
47
|
+
stages.push([]);
|
|
48
|
+
} else stages.at(-1)!.push(token.word);
|
|
49
|
+
}
|
|
50
|
+
if (!stages.at(-1)!.length) return;
|
|
51
|
+
return { directory, stages };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const isSearch = ({ stages }: Pipeline) => ["grep", "rg"].includes(stages[0]![0]!) &&
|
|
55
|
+
stages.slice(1).every(stage => searchTail.has(stage[0]!));
|
|
56
|
+
|
|
57
|
+
export const parseSearchCommand = (command: string, windows = false): Pipeline | undefined => {
|
|
58
|
+
const parsed = pipeline(command, windows);
|
|
59
|
+
return parsed && isSearch(parsed) ? parsed : undefined;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Options whose next word is a value, rather than a path operand. Pattern-file options name files too.
|
|
63
|
+
const searchValues = new Set(["regexp", "file", "after-context", "before-context", "context", "max-count", "color", "colour",
|
|
64
|
+
"binary-files", "devices", "directories", "exclude", "exclude-dir", "include", "label", "glob", "iglob", "type", "type-not",
|
|
65
|
+
"type-add", "type-clear", "encoding", "engine", "max-columns", "max-depth", "max-filesize", "path-separator",
|
|
66
|
+
"pre", "pre-glob", "replace", "sort", "sortr", "threads", "ignore-file", "hostname-bin", "hyperlink-format", "field-match-separator", "field-context-separator"]);
|
|
67
|
+
const shortValues: Record<string, string> = { grep: "efABCmDd", rg: "efgtrjABCmME",
|
|
68
|
+
head: "nc", tail: "ncs", sort: "ktoST", uniq: "fsw", cut: "bcfd" };
|
|
69
|
+
const otherValues = new Set(["lines", "bytes", "sleep-interval", "key", "field-separator", "output", "buffer-size", "temporary-directory",
|
|
70
|
+
"skip-fields", "skip-chars", "check-chars", "characters", "fields", "delimiter"]);
|
|
71
|
+
|
|
72
|
+
function pathOperands(stage: string[]): string[] {
|
|
73
|
+
const [name, ...args] = stage, search = name === "grep" || name === "rg";
|
|
74
|
+
const paths: string[] = [], positional: string[] = [];
|
|
75
|
+
let literal = false, explicitPattern = false, filesOnly = false;
|
|
76
|
+
for (let at = 0; at < args.length; at++) {
|
|
77
|
+
const arg = args[at]!;
|
|
78
|
+
if (!literal && arg === "--") { literal = true; continue; }
|
|
79
|
+
if (!literal && arg.startsWith("--")) {
|
|
80
|
+
const [option, ...value] = arg.slice(2).split("=");
|
|
81
|
+
if (search && (option === "regexp" || option === "file")) explicitPattern = true;
|
|
82
|
+
if (name === "rg" && option === "files") filesOnly = true;
|
|
83
|
+
if ((search ? searchValues : otherValues).has(option!)) {
|
|
84
|
+
const optional = name === "grep" && (option === "color" || option === "colour");
|
|
85
|
+
const operand = value.length ? value.join("=") : optional ? undefined : args[++at];
|
|
86
|
+
if (option === "file" && operand) paths.push(operand);
|
|
87
|
+
}
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (!literal && arg.startsWith("-") && arg !== "-") {
|
|
91
|
+
for (let i = 1; i < arg.length; i++) if (shortValues[name!]?.includes(arg[i]!)) {
|
|
92
|
+
const option = arg[i]!, value = arg.slice(i + 1) || args[++at];
|
|
93
|
+
if (search && (option === "e" || option === "f")) explicitPattern = true;
|
|
94
|
+
if (search && option === "f" && value) paths.push(value);
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
positional.push(arg);
|
|
100
|
+
}
|
|
101
|
+
if (search && !explicitPattern && !filesOnly) positional.shift();
|
|
102
|
+
return [...paths, ...positional].filter(path => path && path !== "-");
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function searchPathsMatch(a: string, b: string): boolean {
|
|
106
|
+
const left = pathKey(a).replace(/^\/+|\/+$/gu, ""), right = pathKey(b).replace(/^\/+|\/+$/gu, "");
|
|
107
|
+
return !!left && !!right && (left === right || left.endsWith("/" + right) || right.endsWith("/" + left));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
|
|
111
|
+
export function keptSearchCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
|
|
112
|
+
resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
|
|
113
|
+
const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
|
|
114
|
+
const results = new Map(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [[entry.message.toolCallId, entry.message] as const] : []));
|
|
115
|
+
const searches = new Map<string, { command: string; parsed: Pipeline; order: number }>();
|
|
116
|
+
const mutations: { path: string; order: number }[] = [];
|
|
117
|
+
let order = 0, lastUnsafeBash = -1;
|
|
118
|
+
for (const entry of entries) {
|
|
119
|
+
if (entry.type === "message" && entry.message.role === "bashExecution") {
|
|
120
|
+
order++;
|
|
121
|
+
if (!classifyBash(entry.message.command, cwd).readOnly) lastUnsafeBash = order;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
125
|
+
for (const block of entry.message.content) {
|
|
126
|
+
if (block.type !== "toolCall") continue;
|
|
127
|
+
order++;
|
|
128
|
+
const args = block.arguments && typeof block.arguments === "object" ? block.arguments as Record<string, unknown> : {};
|
|
129
|
+
if (block.name === "bash") {
|
|
130
|
+
const command = args.command;
|
|
131
|
+
const classified = typeof command === "string" ? classifyBash(command, cwd) : undefined;
|
|
132
|
+
if (!classified?.readOnly) lastUnsafeBash = order;
|
|
133
|
+
const parsed = typeof command === "string" ? parseSearchCommand(command, classified!.windows) : undefined;
|
|
134
|
+
if (parsed) searches.set(block.id, { command: command as string, parsed, order });
|
|
135
|
+
} else if (["write", "edit"].includes(block.name) && !results.get(block.id)?.isError) {
|
|
136
|
+
const path = extractPath(args);
|
|
137
|
+
if (path) mutations.push({ path: pathKey(path), order });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const seen = new Set<string>(), records: TranscriptRecord[] = [];
|
|
142
|
+
for (let at = entries.length - 1; at >= 0; at--) {
|
|
143
|
+
const entry = entries[at]!;
|
|
144
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult") continue;
|
|
145
|
+
const search = searches.get(entry.message.toolCallId);
|
|
146
|
+
if (!search) continue;
|
|
147
|
+
const key = search.command.replace(/\s+/gu, " ").trim();
|
|
148
|
+
if (seen.has(key)) continue;
|
|
149
|
+
seen.add(key);
|
|
150
|
+
const sourceIndex = indices.get(entry.id);
|
|
151
|
+
if (search.order < lastUnsafeBash || entry.message.isError || !isTextOnly(entry.message.content) || sourceIndex === undefined || !resolvable(entry)) continue;
|
|
152
|
+
const text = textOf(entry.message.content);
|
|
153
|
+
if (!text.length || text.length > 2000) continue;
|
|
154
|
+
const paths = [...search.parsed.stages.flatMap(pathOperands), ...text.split("\n").flatMap(line => {
|
|
155
|
+
const prefix = /^((?:[a-z]:[\\/])?[^:\r\n]+):/iu.exec(line)?.[1];
|
|
156
|
+
return prefix ? [prefix] : [];
|
|
157
|
+
})].map(path => pathKey(path, search.parsed.directory ? pathKey(search.parsed.directory, cwd) : undefined));
|
|
158
|
+
if (mutations.some(mutation => mutation.order > search.order && paths.some(path => searchPathsMatch(path, mutation.path)))) continue;
|
|
159
|
+
records.push({ kind: "section", title: "Kept-search", sourceIndex,
|
|
160
|
+
text: `bash ${search.command} (as recorded at #${sourceIndex}; no file it lists was written or edited since):\n${text}` });
|
|
161
|
+
}
|
|
162
|
+
return records;
|
|
163
|
+
}
|
package/src/tuck/core/content.ts
CHANGED
|
@@ -1,18 +1,5 @@
|
|
|
1
1
|
import type { Message } from "@earendil-works/pi-ai";
|
|
2
2
|
|
|
3
|
-
export const clip = (text: string, max = 200): string => {
|
|
4
|
-
if (text.length <= max) return text;
|
|
5
|
-
// Try to cut at a word boundary
|
|
6
|
-
const cut = text.lastIndexOf(" ", max);
|
|
7
|
-
let end = cut > max * 0.6 ? cut : max;
|
|
8
|
-
// Avoid splitting a surrogate pair
|
|
9
|
-
if (end > 0 && end < text.length) {
|
|
10
|
-
const code = text.charCodeAt(end - 1);
|
|
11
|
-
if (code >= 0xd800 && code <= 0xdbff) end--;
|
|
12
|
-
}
|
|
13
|
-
return text.slice(0, end);
|
|
14
|
-
};
|
|
15
|
-
|
|
16
3
|
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
17
4
|
export const isTextOnly = (content: string | readonly { type: string }[] | undefined): boolean =>
|
|
18
5
|
typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
|
|
@@ -22,33 +9,3 @@ export const textOf = (content: Message["content"]): string => {
|
|
|
22
9
|
if (typeof content === "string") return content;
|
|
23
10
|
return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
24
11
|
};
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Extract every scalar string argument from a tool call for search indexing
|
|
28
|
-
* — command, query, content, oldText/newText, etc. Generic value walk (no
|
|
29
|
-
* tool-name allowlist): top-level strings plus strings one level into
|
|
30
|
-
* array-of-object fields (e.g. `edits`). Unbounded by design — a single
|
|
31
|
-
* toolCall's raw argument text — so a message with several toolCalls doesn't
|
|
32
|
-
* silently multiply an internal cap. The caller (search-entries.ts) applies
|
|
33
|
-
* one shared budget across all toolCalls in a message.
|
|
34
|
-
*/
|
|
35
|
-
export const extractToolCallArgsText = (args: Record<string, unknown>): string => {
|
|
36
|
-
if (!args || typeof args !== "object") return "";
|
|
37
|
-
const parts: string[] = [];
|
|
38
|
-
for (const value of Object.values(args)) {
|
|
39
|
-
if (typeof value === "string") {
|
|
40
|
-
parts.push(value);
|
|
41
|
-
} else if (Array.isArray(value)) {
|
|
42
|
-
for (const item of value) {
|
|
43
|
-
if (typeof item === "string") {
|
|
44
|
-
parts.push(item);
|
|
45
|
-
} else if (item && typeof item === "object") {
|
|
46
|
-
for (const v of Object.values(item)) {
|
|
47
|
-
if (typeof v === "string") parts.push(v);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
return parts.join("\n");
|
|
54
|
-
};
|