pi-tuck 1.2.0 → 1.3.2
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 +33 -0
- package/README.md +30 -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/compaction.js +67 -21
- 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/run.d.ts +2 -0
- package/dist/src/run.js +3 -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 +3 -2
- package/src/bash-command.ts +59 -0
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +61 -22
- package/src/diagnostic-replay.ts +1 -1
- package/src/kept-reads.ts +5 -56
- package/src/kept-searches.ts +163 -0
- package/src/run.ts +3 -1
- 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/compaction.js
CHANGED
|
@@ -440,8 +440,9 @@ export async function installCompaction(pi, options = {}) {
|
|
|
440
440
|
const requestClamp = (messages, ctx) => {
|
|
441
441
|
const context = normalizeContext({ messages: convertToLlm(messages) });
|
|
442
442
|
const cap = piClamp?.({ ...ctx.model, contextWindow: contextWindow(ctx) }, context, ctx.model.maxTokens);
|
|
443
|
-
|
|
444
|
-
|
|
443
|
+
const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
|
|
444
|
+
return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
|
|
445
|
+
fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
|
|
445
446
|
};
|
|
446
447
|
const projectedRequest = (messages, ctx, host, incoming, prompt, tools, cut) => {
|
|
447
448
|
const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
|
|
@@ -485,13 +486,14 @@ export async function installCompaction(pi, options = {}) {
|
|
|
485
486
|
const isNoWork = (message) => ["Already compacted", "Nothing to compact (session too small)"].includes(message?.replace(/^Compaction failed: /, "") ?? "");
|
|
486
487
|
// A missing model is configuration, not capacity.
|
|
487
488
|
const missingModel = () => new Error("No context model for the request budget");
|
|
488
|
-
const receipt = (kind, reason, ctx) => {
|
|
489
|
+
const receipt = (kind, reason, ctx, check) => {
|
|
489
490
|
let room = null, hardLine = null;
|
|
490
491
|
try {
|
|
491
492
|
({ room, hardLine } = limits(ctx));
|
|
492
493
|
}
|
|
493
494
|
catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
|
|
494
|
-
pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID
|
|
495
|
+
pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
|
|
496
|
+
...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
|
|
495
497
|
};
|
|
496
498
|
const fail = (error, ctx) => {
|
|
497
499
|
recorder.stop("native-attempt-failed");
|
|
@@ -689,9 +691,9 @@ export async function installCompaction(pi, options = {}) {
|
|
|
689
691
|
};
|
|
690
692
|
// The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
|
|
691
693
|
// get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
|
|
692
|
-
const deepestDecision = (ctx, newPrompt, retain) => {
|
|
694
|
+
const deepestDecision = (ctx, newPrompt, retain, clipFresh = true) => {
|
|
693
695
|
const saved = ctx.sessionManager.buildSessionProjection().messages;
|
|
694
|
-
if (!newPrompt) {
|
|
696
|
+
if (!newPrompt && clipFresh) {
|
|
695
697
|
const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
|
|
696
698
|
const response = saved[at];
|
|
697
699
|
const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
|
|
@@ -723,6 +725,22 @@ export async function installCompaction(pi, options = {}) {
|
|
|
723
725
|
return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
|
|
724
726
|
compaction: draft.compaction, reserve: 0, messages } };
|
|
725
727
|
};
|
|
728
|
+
// Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
|
|
729
|
+
// Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
|
|
730
|
+
// This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
|
|
731
|
+
// and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
|
|
732
|
+
const nativeFloorDecision = (ctx, newPrompt, retain, project) => {
|
|
733
|
+
if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending)
|
|
734
|
+
return;
|
|
735
|
+
const candidate = deepestDecision(ctx, newPrompt, retain, false);
|
|
736
|
+
if (candidate.kind !== "cut")
|
|
737
|
+
return;
|
|
738
|
+
const messages = project(candidate);
|
|
739
|
+
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
|
|
740
|
+
return;
|
|
741
|
+
if (requestClamp(messages, ctx).fitsWindow)
|
|
742
|
+
return candidate;
|
|
743
|
+
};
|
|
726
744
|
// The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
|
|
727
745
|
// custom message starts). The cut is pi-tuck's own, planned as at a tool boundary. It is not Pi's: Pi's cut finder keeps the last
|
|
728
746
|
// keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
|
|
@@ -732,6 +750,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
732
750
|
if (standDown(ctx))
|
|
733
751
|
return;
|
|
734
752
|
run.cut.clear();
|
|
753
|
+
run.nativeFloorPending = false;
|
|
735
754
|
const branchLength = ctx.sessionManager.getBranch().length;
|
|
736
755
|
if (!active())
|
|
737
756
|
return;
|
|
@@ -788,6 +807,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
788
807
|
// An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
|
|
789
808
|
if (decision.kind === "none")
|
|
790
809
|
return;
|
|
810
|
+
if (decision.kind === "fault" && decision.capacity) {
|
|
811
|
+
const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId), candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
|
|
812
|
+
if (floor) {
|
|
813
|
+
decision = floor;
|
|
814
|
+
run.nativeFloorPending = true;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
791
817
|
if (decision.kind === "fault")
|
|
792
818
|
throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
|
|
793
819
|
const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary, { response, host, mandatory, target: decision.target, margin: room - band });
|
|
@@ -896,12 +922,10 @@ export async function installCompaction(pi, options = {}) {
|
|
|
896
922
|
// request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
|
|
897
923
|
let previews = [];
|
|
898
924
|
let floorKept;
|
|
899
|
-
let wholePromptFloor;
|
|
900
925
|
const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
|
|
901
926
|
const decide = (targetRoom = room, targetBand = band, required = false) => {
|
|
902
927
|
previews = [];
|
|
903
928
|
floorKept = undefined;
|
|
904
|
-
wholePromptFloor = undefined;
|
|
905
929
|
const before = measure(saved);
|
|
906
930
|
const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan", opportunistic: false } :
|
|
907
931
|
gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
|
|
@@ -914,8 +938,6 @@ export async function installCompaction(pi, options = {}) {
|
|
|
914
938
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
915
939
|
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
916
940
|
if (!draft.compaction) {
|
|
917
|
-
if (protectedId && draft.floorMessages)
|
|
918
|
-
wholePromptFloor = measure(draft.floorMessages) + mandatory;
|
|
919
941
|
// The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
|
|
920
942
|
if (draft.floorMessages && event.toolResults) {
|
|
921
943
|
const fresh = new Set(event.toolResults.map(result => result.toolCallId));
|
|
@@ -981,9 +1003,15 @@ export async function installCompaction(pi, options = {}) {
|
|
|
981
1003
|
}, () => deepestDecision(ctx, false, true));
|
|
982
1004
|
}
|
|
983
1005
|
if (decision.kind === "fault" && reason === "tool-loop") {
|
|
984
|
-
if (
|
|
1006
|
+
if (decision.capacity)
|
|
1007
|
+
decision = nativeFloorDecision(ctx, false, true, candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, event.context.pendingMessages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
|
|
1008
|
+
}
|
|
1009
|
+
if (decision.kind === "fault" && reason === "tool-loop") {
|
|
1010
|
+
if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx))
|
|
985
1011
|
throw promptRefusal();
|
|
986
|
-
|
|
1012
|
+
if (decision.capacity)
|
|
1013
|
+
throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
|
|
1014
|
+
throw new Refusal(decision.message);
|
|
987
1015
|
}
|
|
988
1016
|
if (decision.kind !== "cut")
|
|
989
1017
|
return;
|
|
@@ -1156,16 +1184,24 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1156
1184
|
};
|
|
1157
1185
|
if (!accepts(decision))
|
|
1158
1186
|
decision = deepestDecision(ctx, false, true);
|
|
1187
|
+
let native = false;
|
|
1159
1188
|
if (decision.kind !== "cut" || !accepts(decision)) {
|
|
1160
1189
|
clips().clear();
|
|
1161
1190
|
for (const [id, clip] of previousClips)
|
|
1162
1191
|
clips().set(id, clip);
|
|
1163
|
-
|
|
1192
|
+
const floor = nativeFloorDecision(ctx, false, true, project);
|
|
1193
|
+
if (!floor)
|
|
1194
|
+
return { messages };
|
|
1195
|
+
decision = floor;
|
|
1196
|
+
native = true;
|
|
1164
1197
|
}
|
|
1198
|
+
if (decision.kind !== "cut")
|
|
1199
|
+
return { messages };
|
|
1165
1200
|
const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary, { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
|
|
1166
1201
|
run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
|
|
1202
|
+
run.nativeFloorPending = native;
|
|
1167
1203
|
syncHistoryTools(ctx);
|
|
1168
|
-
return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true);
|
|
1204
|
+
return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true), native };
|
|
1169
1205
|
};
|
|
1170
1206
|
pi.on("context", (event, ctx) => {
|
|
1171
1207
|
try {
|
|
@@ -1263,8 +1299,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1263
1299
|
let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1264
1300
|
let tokens = system + conversationTokens(messages);
|
|
1265
1301
|
const { room, hardLine } = limits(ctx);
|
|
1266
|
-
|
|
1267
|
-
|
|
1302
|
+
let native = false;
|
|
1303
|
+
const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
|
|
1304
|
+
piClamp && !requestClamp(messages, ctx).leavesFloor;
|
|
1305
|
+
if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1306
|
+
const cut = guardCut(messages, tokens, system, ctx);
|
|
1307
|
+
messages = cut.messages;
|
|
1308
|
+
native = Boolean(cut.native);
|
|
1268
1309
|
system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1269
1310
|
tokens = system + conversationTokens(messages);
|
|
1270
1311
|
assertNativeToolRounds(messages);
|
|
@@ -1273,13 +1314,18 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1273
1314
|
calibration.estimatedTokens = corrected(tokens, ctx);
|
|
1274
1315
|
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
|
|
1275
1316
|
throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
|
|
1276
|
-
|
|
1317
|
+
// A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
|
|
1318
|
+
native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
|
|
1319
|
+
native &&= requestClamp(messages, ctx).fitsWindow;
|
|
1320
|
+
if (!native && !fits(tokens, hardLine, ctx))
|
|
1277
1321
|
throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
|
|
1278
|
-
//
|
|
1279
|
-
//
|
|
1280
|
-
if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
|
|
1322
|
+
// Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
|
|
1323
|
+
// only the refusal-path compiler floor may instead use native window admission.
|
|
1324
|
+
if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
|
|
1281
1325
|
throw new CapacityError(clampMessage);
|
|
1282
|
-
if (
|
|
1326
|
+
if (native)
|
|
1327
|
+
receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
|
|
1328
|
+
else if (calibration.estimatedTokens > room)
|
|
1283
1329
|
receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
|
|
1284
1330
|
if (recorder.enabled && !recorder.waitingForCut)
|
|
1285
1331
|
recorder.measureInline(() => {
|
|
@@ -12,7 +12,7 @@ export function inspectIncident(records) {
|
|
|
12
12
|
if (i.branchEntryIds?.length)
|
|
13
13
|
manager.branch(i.branchEntryIds.at(-1));
|
|
14
14
|
const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } };
|
|
15
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary
|
|
15
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
16
16
|
const proposal = records.find(r => r.kind === 'proposal' && r.data?.details?.diagnosticReceipt?.id === i.receiptId)?.data;
|
|
17
17
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
18
18
|
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.' };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type RecallPolicy } from './recall.js';
|
|
2
2
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
export declare const DIAGNOSTIC_BUILD = "
|
|
3
|
+
export declare const DIAGNOSTIC_BUILD = "b6a612ac60abaf5564c6020053627662851d7c7162337cf023ed686c1d598466";
|
|
4
4
|
export interface Receipt {
|
|
5
5
|
id: string;
|
|
6
6
|
build: string;
|
package/dist/src/kept-reads.js
CHANGED
|
@@ -1,112 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { classifyBash } from "./bash-command.js";
|
|
2
2
|
import { pathKey } from "./path-key.js";
|
|
3
3
|
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
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
|
-
}
|
|
110
5
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
111
6
|
export function keptReadCandidates(entries, indices, resolvable) {
|
|
112
7
|
const cwd = entries.find((entry) => entry.type === "session")?.cwd;
|
|
@@ -125,18 +20,14 @@ export function keptReadCandidates(entries, indices, resolvable) {
|
|
|
125
20
|
if (block.name === "bash") {
|
|
126
21
|
if (!reads.size || typeof args.command !== "string")
|
|
127
22
|
continue;
|
|
128
|
-
|
|
129
|
-
|
|
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))
|
|
23
|
+
const command = classifyBash(args.command, cwd), { words } = command;
|
|
24
|
+
if (command.readOnly)
|
|
134
25
|
continue;
|
|
135
|
-
if (
|
|
26
|
+
if (command.mutatesAll) {
|
|
136
27
|
allMutated = order;
|
|
137
28
|
continue;
|
|
138
29
|
}
|
|
139
|
-
const base =
|
|
30
|
+
const base = command.directory === undefined ? cwd : pathKey(command.directory, cwd);
|
|
140
31
|
const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
|
|
141
32
|
for (const name of names)
|
|
142
33
|
if (name) {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { TranscriptRecord } from "./tuck/core/transcript.js";
|
|
3
|
+
interface Pipeline {
|
|
4
|
+
directory?: string;
|
|
5
|
+
stages: string[][];
|
|
6
|
+
}
|
|
7
|
+
export declare const parseSearchCommand: (command: string, windows?: boolean) => Pipeline | undefined;
|
|
8
|
+
export declare function searchPathsMatch(a: string, b: string): boolean;
|
|
9
|
+
/** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
|
|
10
|
+
export declare function keptSearchCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { classifyBash } from "./bash-command.js";
|
|
2
|
+
import { pathKey } from "./path-key.js";
|
|
3
|
+
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
|
+
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
|
+
const searchTail = new Set(["head", "tail", "sort", "uniq", "wc", "cut", "grep"]);
|
|
6
|
+
/** A small shell lexer, not a shell interpreter. Unclassified shell syntax fails closed. */
|
|
7
|
+
function pipeline(command, windows) {
|
|
8
|
+
if (/[;<>`\r\n]/u.test(command) || command.includes("$("))
|
|
9
|
+
return;
|
|
10
|
+
const expands = (at) => command[at] === "$" && /[\w{@*#!?$-]/u.test(command[at + 1] ?? "");
|
|
11
|
+
const tokens = [];
|
|
12
|
+
let word = "", started = false, quote = "";
|
|
13
|
+
const flush = () => { if (started)
|
|
14
|
+
tokens.push({ word }); word = ""; started = false; };
|
|
15
|
+
for (let at = 0; at < command.length; at++) {
|
|
16
|
+
const ch = command[at];
|
|
17
|
+
if (quote) {
|
|
18
|
+
if (ch === quote)
|
|
19
|
+
quote = "";
|
|
20
|
+
else if (!windows && ch === "\\" && quote === '"' && /[\\"$]/u.test(command[at + 1] ?? ""))
|
|
21
|
+
word += command[++at];
|
|
22
|
+
else if (quote === '"' && expands(at))
|
|
23
|
+
return;
|
|
24
|
+
else
|
|
25
|
+
word += ch;
|
|
26
|
+
}
|
|
27
|
+
else if (ch === "'" || ch === '"') {
|
|
28
|
+
quote = ch;
|
|
29
|
+
started = true;
|
|
30
|
+
}
|
|
31
|
+
else if (!windows && ch === "\\") {
|
|
32
|
+
if (++at === command.length)
|
|
33
|
+
return;
|
|
34
|
+
word += command[at];
|
|
35
|
+
started = true;
|
|
36
|
+
}
|
|
37
|
+
else if (/\s/u.test(ch))
|
|
38
|
+
flush();
|
|
39
|
+
else if (ch === "|" || ch === "&") {
|
|
40
|
+
flush();
|
|
41
|
+
const op = command[at + 1] === ch ? ch + command[++at] : ch;
|
|
42
|
+
if (op !== "|" && op !== "&&")
|
|
43
|
+
return;
|
|
44
|
+
tokens.push({ word: op, operator: true });
|
|
45
|
+
}
|
|
46
|
+
else if (/[()]/u.test(ch) || ch === "#" && !started || expands(at))
|
|
47
|
+
return;
|
|
48
|
+
else {
|
|
49
|
+
word += ch;
|
|
50
|
+
started = true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (quote)
|
|
54
|
+
return;
|
|
55
|
+
flush();
|
|
56
|
+
let directory;
|
|
57
|
+
if (tokens[0]?.word === "cd" && tokens[1] && !tokens[1].operator && tokens[1].word &&
|
|
58
|
+
!tokens[1].word.startsWith("-") && tokens[2]?.operator && tokens[2].word === "&&") {
|
|
59
|
+
directory = tokens[1].word;
|
|
60
|
+
tokens.splice(0, 3);
|
|
61
|
+
}
|
|
62
|
+
const stages = [[]];
|
|
63
|
+
for (const token of tokens) {
|
|
64
|
+
if (token.operator) {
|
|
65
|
+
if (token.word !== "|" || !stages.at(-1).length)
|
|
66
|
+
return;
|
|
67
|
+
stages.push([]);
|
|
68
|
+
}
|
|
69
|
+
else
|
|
70
|
+
stages.at(-1).push(token.word);
|
|
71
|
+
}
|
|
72
|
+
if (!stages.at(-1).length)
|
|
73
|
+
return;
|
|
74
|
+
return { directory, stages };
|
|
75
|
+
}
|
|
76
|
+
const isSearch = ({ stages }) => ["grep", "rg"].includes(stages[0][0]) &&
|
|
77
|
+
stages.slice(1).every(stage => searchTail.has(stage[0]));
|
|
78
|
+
export const parseSearchCommand = (command, windows = false) => {
|
|
79
|
+
const parsed = pipeline(command, windows);
|
|
80
|
+
return parsed && isSearch(parsed) ? parsed : undefined;
|
|
81
|
+
};
|
|
82
|
+
// Options whose next word is a value, rather than a path operand. Pattern-file options name files too.
|
|
83
|
+
const searchValues = new Set(["regexp", "file", "after-context", "before-context", "context", "max-count", "color", "colour",
|
|
84
|
+
"binary-files", "devices", "directories", "exclude", "exclude-dir", "include", "label", "glob", "iglob", "type", "type-not",
|
|
85
|
+
"type-add", "type-clear", "encoding", "engine", "max-columns", "max-depth", "max-filesize", "path-separator",
|
|
86
|
+
"pre", "pre-glob", "replace", "sort", "sortr", "threads", "ignore-file", "hostname-bin", "hyperlink-format", "field-match-separator", "field-context-separator"]);
|
|
87
|
+
const shortValues = { grep: "efABCmDd", rg: "efgtrjABCmME",
|
|
88
|
+
head: "nc", tail: "ncs", sort: "ktoST", uniq: "fsw", cut: "bcfd" };
|
|
89
|
+
const otherValues = new Set(["lines", "bytes", "sleep-interval", "key", "field-separator", "output", "buffer-size", "temporary-directory",
|
|
90
|
+
"skip-fields", "skip-chars", "check-chars", "characters", "fields", "delimiter"]);
|
|
91
|
+
function pathOperands(stage) {
|
|
92
|
+
const [name, ...args] = stage, search = name === "grep" || name === "rg";
|
|
93
|
+
const paths = [], positional = [];
|
|
94
|
+
let literal = false, explicitPattern = false, filesOnly = false;
|
|
95
|
+
for (let at = 0; at < args.length; at++) {
|
|
96
|
+
const arg = args[at];
|
|
97
|
+
if (!literal && arg === "--") {
|
|
98
|
+
literal = true;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (!literal && arg.startsWith("--")) {
|
|
102
|
+
const [option, ...value] = arg.slice(2).split("=");
|
|
103
|
+
if (search && (option === "regexp" || option === "file"))
|
|
104
|
+
explicitPattern = true;
|
|
105
|
+
if (name === "rg" && option === "files")
|
|
106
|
+
filesOnly = true;
|
|
107
|
+
if ((search ? searchValues : otherValues).has(option)) {
|
|
108
|
+
const optional = name === "grep" && (option === "color" || option === "colour");
|
|
109
|
+
const operand = value.length ? value.join("=") : optional ? undefined : args[++at];
|
|
110
|
+
if (option === "file" && operand)
|
|
111
|
+
paths.push(operand);
|
|
112
|
+
}
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!literal && arg.startsWith("-") && arg !== "-") {
|
|
116
|
+
for (let i = 1; i < arg.length; i++)
|
|
117
|
+
if (shortValues[name]?.includes(arg[i])) {
|
|
118
|
+
const option = arg[i], value = arg.slice(i + 1) || args[++at];
|
|
119
|
+
if (search && (option === "e" || option === "f"))
|
|
120
|
+
explicitPattern = true;
|
|
121
|
+
if (search && option === "f" && value)
|
|
122
|
+
paths.push(value);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
positional.push(arg);
|
|
128
|
+
}
|
|
129
|
+
if (search && !explicitPattern && !filesOnly)
|
|
130
|
+
positional.shift();
|
|
131
|
+
return [...paths, ...positional].filter(path => path && path !== "-");
|
|
132
|
+
}
|
|
133
|
+
export function searchPathsMatch(a, b) {
|
|
134
|
+
const left = pathKey(a).replace(/^\/+|\/+$/gu, ""), right = pathKey(b).replace(/^\/+|\/+$/gu, "");
|
|
135
|
+
return !!left && !!right && (left === right || left.endsWith("/" + right) || right.endsWith("/" + left));
|
|
136
|
+
}
|
|
137
|
+
/** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
|
|
138
|
+
export function keptSearchCandidates(entries, indices, resolvable) {
|
|
139
|
+
const cwd = entries.find((entry) => entry.type === "session")?.cwd;
|
|
140
|
+
const results = new Map(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [[entry.message.toolCallId, entry.message]] : []));
|
|
141
|
+
const searches = new Map();
|
|
142
|
+
const mutations = [];
|
|
143
|
+
let order = 0, lastUnsafeBash = -1;
|
|
144
|
+
for (const entry of entries) {
|
|
145
|
+
if (entry.type === "message" && entry.message.role === "bashExecution") {
|
|
146
|
+
order++;
|
|
147
|
+
if (!classifyBash(entry.message.command, cwd).readOnly)
|
|
148
|
+
lastUnsafeBash = order;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
152
|
+
continue;
|
|
153
|
+
for (const block of entry.message.content) {
|
|
154
|
+
if (block.type !== "toolCall")
|
|
155
|
+
continue;
|
|
156
|
+
order++;
|
|
157
|
+
const args = block.arguments && typeof block.arguments === "object" ? block.arguments : {};
|
|
158
|
+
if (block.name === "bash") {
|
|
159
|
+
const command = args.command;
|
|
160
|
+
const classified = typeof command === "string" ? classifyBash(command, cwd) : undefined;
|
|
161
|
+
if (!classified?.readOnly)
|
|
162
|
+
lastUnsafeBash = order;
|
|
163
|
+
const parsed = typeof command === "string" ? parseSearchCommand(command, classified.windows) : undefined;
|
|
164
|
+
if (parsed)
|
|
165
|
+
searches.set(block.id, { command: command, parsed, order });
|
|
166
|
+
}
|
|
167
|
+
else if (["write", "edit"].includes(block.name) && !results.get(block.id)?.isError) {
|
|
168
|
+
const path = extractPath(args);
|
|
169
|
+
if (path)
|
|
170
|
+
mutations.push({ path: pathKey(path), order });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const seen = new Set(), records = [];
|
|
175
|
+
for (let at = entries.length - 1; at >= 0; at--) {
|
|
176
|
+
const entry = entries[at];
|
|
177
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult")
|
|
178
|
+
continue;
|
|
179
|
+
const search = searches.get(entry.message.toolCallId);
|
|
180
|
+
if (!search)
|
|
181
|
+
continue;
|
|
182
|
+
const key = search.command.replace(/\s+/gu, " ").trim();
|
|
183
|
+
if (seen.has(key))
|
|
184
|
+
continue;
|
|
185
|
+
seen.add(key);
|
|
186
|
+
const sourceIndex = indices.get(entry.id);
|
|
187
|
+
if (search.order < lastUnsafeBash || entry.message.isError || !isTextOnly(entry.message.content) || sourceIndex === undefined || !resolvable(entry))
|
|
188
|
+
continue;
|
|
189
|
+
const text = textOf(entry.message.content);
|
|
190
|
+
if (!text.length || text.length > 2000)
|
|
191
|
+
continue;
|
|
192
|
+
const paths = [...search.parsed.stages.flatMap(pathOperands), ...text.split("\n").flatMap(line => {
|
|
193
|
+
const prefix = /^((?:[a-z]:[\\/])?[^:\r\n]+):/iu.exec(line)?.[1];
|
|
194
|
+
return prefix ? [prefix] : [];
|
|
195
|
+
})].map(path => pathKey(path, search.parsed.directory ? pathKey(search.parsed.directory, cwd) : undefined));
|
|
196
|
+
if (mutations.some(mutation => mutation.order > search.order && paths.some(path => searchPathsMatch(path, mutation.path))))
|
|
197
|
+
continue;
|
|
198
|
+
records.push({ kind: "section", title: "Kept-search", sourceIndex,
|
|
199
|
+
text: `bash ${search.command} (as recorded at #${sourceIndex}; no file it lists was written or edited since):\n${text}` });
|
|
200
|
+
}
|
|
201
|
+
return records;
|
|
202
|
+
}
|
package/dist/src/run.d.ts
CHANGED
|
@@ -52,6 +52,8 @@ export declare class Run {
|
|
|
52
52
|
clips: Map<string, Clip>;
|
|
53
53
|
pendingBoundaryReceipts: string[];
|
|
54
54
|
thinkingRetryPending: boolean;
|
|
55
|
+
/** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
|
|
56
|
+
nativeFloorPending: boolean;
|
|
55
57
|
refusalReceipted: boolean;
|
|
56
58
|
clear(): void;
|
|
57
59
|
}
|
package/dist/src/run.js
CHANGED
|
@@ -129,6 +129,8 @@ export class Run {
|
|
|
129
129
|
clips = new Map();
|
|
130
130
|
pendingBoundaryReceipts = [];
|
|
131
131
|
thinkingRetryPending = false;
|
|
132
|
+
/** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
|
|
133
|
+
nativeFloorPending = false;
|
|
132
134
|
refusalReceipted = false;
|
|
133
135
|
clear() {
|
|
134
136
|
this.prompt = undefined;
|
|
@@ -136,6 +138,7 @@ export class Run {
|
|
|
136
138
|
this.clips.clear();
|
|
137
139
|
this.pendingBoundaryReceipts = [];
|
|
138
140
|
this.thinkingRetryPending = false;
|
|
141
|
+
this.nativeFloorPending = false;
|
|
139
142
|
this.refusalReceipted = false;
|
|
140
143
|
this.expiredPlan = false;
|
|
141
144
|
}
|
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
-
export declare const clip: (text: string, max?: number) => string;
|
|
3
2
|
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
4
3
|
export declare const isTextOnly: (content: string | readonly {
|
|
5
4
|
type: string;
|
|
6
5
|
}[] | undefined) => boolean;
|
|
7
6
|
export declare const textOf: (content: Message["content"]) => string;
|
|
8
|
-
/**
|
|
9
|
-
* Extract every scalar string argument from a tool call for search indexing
|
|
10
|
-
* — command, query, content, oldText/newText, etc. Generic value walk (no
|
|
11
|
-
* tool-name allowlist): top-level strings plus strings one level into
|
|
12
|
-
* array-of-object fields (e.g. `edits`). Unbounded by design — a single
|
|
13
|
-
* toolCall's raw argument text — so a message with several toolCalls doesn't
|
|
14
|
-
* silently multiply an internal cap. The caller (search-entries.ts) applies
|
|
15
|
-
* one shared budget across all toolCalls in a message.
|
|
16
|
-
*/
|
|
17
|
-
export declare const extractToolCallArgsText: (args: Record<string, unknown>) => string;
|