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/src/compaction.ts CHANGED
@@ -411,8 +411,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
411
411
  const requestClamp = (messages: Messages, ctx: ExtensionContext) => {
412
412
  const context = normalizeContext({ messages: convertToLlm(messages) });
413
413
  const cap = piClamp?.({ ...ctx.model!, contextWindow: contextWindow(ctx) }, context, ctx.model!.maxTokens);
414
- return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor,
415
- estimate: piMath ? piMath.estimateContextTokens(context).tokens : 0 };
414
+ const estimate = piMath ? piMath.estimateContextTokens(context).tokens : 0;
415
+ return { cap, leavesFloor: cap === undefined || cap >= limits(ctx).replyFloor, estimate,
416
+ fitsWindow: cap !== undefined && cap > 0 && estimate + piMargin + cap <= contextWindow(ctx) };
416
417
  };
417
418
  const projectedRequest = (messages: Messages, ctx: ExtensionContext, host: Messages, incoming: Messages, prompt: string, tools: readonly string[], cut: boolean) => {
418
419
  const enabled = cut || historyToolsEnabled(ctx), shapes = toolShapes(historyToolNames(pi, tools, enabled));
@@ -450,10 +451,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
450
451
  // A missing model is configuration, not capacity.
451
452
  const missingModel = () => new Error("No context model for the request budget");
452
453
  type CutPlan = { compaction: NonNullable<ReturnType<typeof tuckDraft>["compaction"]>; reserve: number; messages: Messages };
453
- const receipt = (kind: "refusal" | "above-room", reason: string, ctx: ExtensionContext) => {
454
+ const receipt = (kind: "refusal" | "above-room" | "native-floor", reason: string, ctx: ExtensionContext, check?: ReturnType<typeof requestClamp>) => {
454
455
  let room: number | null = null, hardLine: number | null = null;
455
456
  try { ({ room, hardLine } = limits(ctx)); } catch { /* Invalid configuration has no usable capacity. Preserve its original failure. */ }
456
- pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID });
457
+ pi.appendEntry("pi-tuck-capacity", { kind, reason, estimatedTokens: calibration.estimatedTokens, room, hardLine, buildId: BUILD_ID,
458
+ ...(check ? { piEstimateTokens: check.estimate, piCap: check.cap } : {}) });
457
459
  };
458
460
  const fail = (error: unknown, ctx: ExtensionContext) => {
459
461
  recorder.stop("native-attempt-failed");
@@ -618,9 +620,9 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
618
620
  };
619
621
  // The shared final planner: preserve the compiler's prompt/protocol floor and spend nothing on optional history. Fresh text results
620
622
  // get the smallest existing head/tail + recall-locator representation; their originals remain in the session, as for ordinary clips.
621
- const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean): Decision<CutPlan> => {
623
+ const deepestDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean, clipFresh = true): Decision<CutPlan> => {
622
624
  const saved = ctx.sessionManager.buildSessionProjection().messages;
623
- if (!newPrompt) {
625
+ if (!newPrompt && clipFresh) {
624
626
  const at = saved.findLastIndex(message => message.role === "assistant" && !isDiscardedResponse(message));
625
627
  const response = saved[at];
626
628
  const calls = new Set(response?.role === "assistant" ? response.content.flatMap(block => block.type === "toolCall" ? [block.id] : []) : []);
@@ -646,6 +648,19 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
646
648
  return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
647
649
  compaction: draft.compaction, reserve: 0, messages } };
648
650
  };
651
+ // Refusal path only: the hard line remains the cut target, but the compiler's floor may use Pi's remaining reply cap.
652
+ // Read both the estimate and saturated clamp from the running Pi: a positive (minimum) cap alone does not prove window fit.
653
+ // This does not relax thinking-only length recovery: retryLength still requires the observed reply floor before continuing,
654
+ // and its pending retry cannot use this escape. No fresh content is clipped or edited by this admission attempt.
655
+ const nativeFloorDecision = (ctx: ExtensionContext, newPrompt: boolean, retain: boolean,
656
+ project: (candidate: Decision<CutPlan>) => Messages): Extract<Decision<CutPlan>, { kind: "cut" }> | undefined => {
657
+ if (options.requestReserve || options.activeInputTokens !== undefined || !piMath || run?.thinkingRetryPending) return;
658
+ const candidate = deepestDecision(ctx, newPrompt, retain, false);
659
+ if (candidate.kind !== "cut") return;
660
+ const messages = project(candidate);
661
+ if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role)) return;
662
+ if (requestClamp(messages, ctx).fitsWindow) return candidate;
663
+ };
649
664
  // 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
650
665
  // 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
651
666
  // keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
@@ -654,6 +669,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
654
669
  const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages, protectedId?: string) => {
655
670
  if (standDown(ctx)) return;
656
671
  run!.cut.clear();
672
+ run!.nativeFloorPending = false;
657
673
  const branchLength = ctx.sessionManager.getBranch().length;
658
674
  if (!active()) return;
659
675
  access();
@@ -707,6 +723,11 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
707
723
  if (decision.kind === "defer") return;
708
724
  // An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
709
725
  if (decision.kind === "none") return;
726
+ if (decision.kind === "fault" && decision.capacity) {
727
+ const floor = nativeFloorDecision(ctx, !protectedId, Boolean(protectedId),
728
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, true));
729
+ if (floor) { decision = floor; run!.nativeFloorPending = true; }
730
+ }
710
731
  if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
711
732
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
712
733
  { response, host, mandatory, target: decision.target, margin: room - band });
@@ -799,12 +820,10 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
799
820
  // request besides the fresh results. Reset per decision, so a retry sizes itself against the cut it is retrying, not an earlier attempt's.
800
821
  let previews: Messages[] = [];
801
822
  let floorKept: number | undefined;
802
- let wholePromptFloor: number | undefined;
803
823
  const protectedId = reason === "tool-loop" ? protectedPrompt(ctx) : undefined;
804
824
  const decide = (targetRoom = room, targetBand = band, required = false) => {
805
825
  previews = [];
806
826
  floorKept = undefined;
807
- wholePromptFloor = undefined;
808
827
  const before = measure(saved);
809
828
  const gate = required && fits(mandatory, targetRoom, ctx) ? { kind: "plan" as const, opportunistic: false } :
810
829
  gateCut({ total: before + mandatory, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx) });
@@ -816,7 +835,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
816
835
  const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
817
836
  const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: densityTokens ?? before, previousSummary, protectedPromptEntryId: protectedId }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
818
837
  if (!draft.compaction) {
819
- if (protectedId && draft.floorMessages) wholePromptFloor = measure(draft.floorMessages) + mandatory;
820
838
  // The planner's own floor, so a clip's second budget is measured against what the smallest cut really keeps.
821
839
  if (draft.floorMessages && event.toolResults) {
822
840
  const fresh = new Set(event.toolResults.map(result => result.toolCallId));
@@ -875,8 +893,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
875
893
  }, () => deepestDecision(ctx, false, true));
876
894
  }
877
895
  if (decision.kind === "fault" && reason === "tool-loop") {
878
- if (wholePromptFloor !== undefined && !fits(wholePromptFloor, hardLine, ctx)) throw promptRefusal();
879
- throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
896
+ if (decision.capacity) decision = nativeFloorDecision(ctx, false, true,
897
+ candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput,
898
+ event.context.pendingMessages as Messages, ctx.getSystemPrompt(), pi.getActiveTools(), true)) ?? decision;
899
+ }
900
+ if (decision.kind === "fault" && reason === "tool-loop") {
901
+ if (protectedId && run?.prompt && !fits(incomingTokens(run.prompt.text(ctx.sessionManager.getBranch()), []), room, ctx)) throw promptRefusal();
902
+ if (decision.capacity) throw new CapacityError("The fresh tool round and required context exceed the estimated request budget");
903
+ throw new Refusal(decision.message);
880
904
  }
881
905
  if (decision.kind !== "cut") return;
882
906
  const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, reason, before, true, false, previousSummary,
@@ -999,7 +1023,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
999
1023
  };
1000
1024
  // A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
1001
1025
  // atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
1002
- const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): Messages => {
1026
+ const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): { messages: Messages; native?: boolean } => {
1003
1027
  const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
1004
1028
  const before = conversationTokens(source), mandatory = tokens - before;
1005
1029
  const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
@@ -1036,16 +1060,22 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1036
1060
  return fits(reduced, hardLine, ctx) && (Boolean(options.requestReserve) || corrected(reduced, ctx) <= room || requestClamp(request, ctx).leavesFloor);
1037
1061
  };
1038
1062
  if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
1063
+ let native = false;
1039
1064
  if (decision.kind !== "cut" || !accepts(decision)) {
1040
1065
  clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
1041
- return messages;
1066
+ const floor = nativeFloorDecision(ctx, false, true, project);
1067
+ if (!floor) return { messages };
1068
+ decision = floor;
1069
+ native = true;
1042
1070
  }
1071
+ if (decision.kind !== "cut") return { messages };
1043
1072
  const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
1044
1073
  { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
1045
1074
  run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
1075
+ run!.nativeFloorPending = native;
1046
1076
  syncHistoryTools(ctx);
1047
- return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1048
- toolShapes(pi.getActiveTools()), true);
1077
+ return { messages: historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
1078
+ toolShapes(pi.getActiveTools()), true), native };
1049
1079
  };
1050
1080
  pi.on("context", (event, ctx) => {
1051
1081
  try {
@@ -1108,8 +1138,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1108
1138
  let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1109
1139
  let tokens = system + conversationTokens(messages);
1110
1140
  const { room, hardLine } = limits(ctx);
1111
- if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1112
- messages = guardCut(messages, tokens, system, ctx);
1141
+ let native = false;
1142
+ const wouldRefuse = !fits(tokens, hardLine, ctx) || !options.requestReserve && corrected(tokens, ctx) > room &&
1143
+ piClamp && !requestClamp(messages, ctx).leavesFloor;
1144
+ if (wouldRefuse && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
1145
+ const cut = guardCut(messages, tokens, system, ctx);
1146
+ messages = cut.messages;
1147
+ native = Boolean(cut.native);
1113
1148
  system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
1114
1149
  tokens = system + conversationTokens(messages);
1115
1150
  assertNativeToolRounds(messages);
@@ -1118,13 +1153,17 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
1118
1153
  calibration.estimatedTokens = corrected(tokens, ctx);
1119
1154
  if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
1120
1155
  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");
1121
- if (!fits(tokens, hardLine, ctx))
1156
+ // A floor already planned at input is pending here; recheck the exact complete request with Pi's own math.
1157
+ native ||= Boolean(wouldRefuse && view(ctx).pending && run?.nativeFloorPending);
1158
+ native &&= requestClamp(messages, ctx).fitsWindow;
1159
+ if (!native && !fits(tokens, hardLine, ctx))
1122
1160
  throw new CapacityError("Complete Pi context and response reserve exceed the estimated request budget");
1123
- // Pi's request estimator and its compaction estimator need not agree. The hard line is
1124
- // necessary; above the room, also require the real request clamp to preserve the floor.
1125
- if (!options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1161
+ // Ordinary admission above the room also asks Pi's real clamp to preserve the reply floor;
1162
+ // only the refusal-path compiler floor may instead use native window admission.
1163
+ if (!native && !options.requestReserve && calibration.estimatedTokens > room && piClamp && !requestClamp(messages, ctx).leavesFloor)
1126
1164
  throw new CapacityError(clampMessage);
1127
- if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1165
+ if (native) receipt("native-floor", "Planner floor fits Pi's native request limit after ordinary admission failed", ctx, requestClamp(messages, ctx));
1166
+ else if (calibration.estimatedTokens > room) receipt("above-room", "Request exceeds the room and fits the hard line", ctx);
1128
1167
  if (recorder.enabled && !recorder.waitingForCut) recorder.measureInline(() => {
1129
1168
  recorder.request();
1130
1169
  // No system prompt or hidden assistant blocks; no provider payload/headers.
@@ -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, operatorManual: i.operatorManual }, ctx, i.reserve!, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
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 { posix } from "node:path";
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
- // Interpret the recorded shell, even when this session is read on another OS.
72
- const commandName = args.command.trim().split(/\s/u)[0]!.toLowerCase();
73
- const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(args.command) ||
74
- windowsReaders.has(commandName) || windowsMutators.has(commandName);
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/run.ts CHANGED
@@ -117,9 +117,11 @@ export class Run {
117
117
  clips = new Map<string, Clip>();
118
118
  pendingBoundaryReceipts: string[] = [];
119
119
  thinkingRetryPending = false;
120
+ /** A refusal-path floor carried by cut; the complete request must still pass Pi's window check. */
121
+ nativeFloorPending = false;
120
122
  refusalReceipted = false;
121
123
  clear() {
122
124
  this.prompt = undefined; this.cut.clear(); this.clips.clear(); this.pendingBoundaryReceipts = [];
123
- this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
+ this.thinkingRetryPending = false; this.nativeFloorPending = false; this.refusalReceipted = false; this.expiredPlan = false;
124
126
  }
125
127
  }
@@ -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
- };