pi-tuck 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +7 -3
- package/dist/index.d.ts +2 -6
- package/dist/index.js +16 -111
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +2 -103
- package/dist/src/compaction.js +29 -146
- package/dist/src/diagnostic-replay.js +2 -2
- package/dist/src/diagnostics.d.ts +3 -2
- package/dist/src/diagnostics.js +30 -9
- package/dist/src/history-tools.js +3 -3
- package/dist/src/kept-reads.d.ts +2 -2
- package/dist/src/kept-reads.js +144 -8
- package/dist/src/ledger.d.ts +1 -1
- package/dist/src/ledger.js +5 -3
- package/dist/src/legacy-cleanup.d.ts +3 -0
- package/dist/src/legacy-cleanup.js +190 -0
- package/dist/src/notify.d.ts +3 -0
- package/dist/src/notify.js +13 -0
- package/dist/src/omissions.d.ts +1 -1
- package/dist/src/omissions.js +3 -3
- package/dist/src/path-key.d.ts +3 -0
- package/dist/src/path-key.js +8 -0
- package/dist/src/request-capacity.js +1 -1
- package/dist/src/run.d.ts +1 -3
- package/dist/src/run.js +3 -5
- package/dist/src/source-export.d.ts +1 -1
- package/dist/src/source-export.js +1 -1
- package/dist/src/status.d.ts +0 -6
- package/dist/src/status.js +1 -6
- package/dist/src/tuck/core/content.js +6 -9
- package/dist/src/tuck/core/keyword-query.d.ts +2 -2
- package/dist/src/tuck/core/keyword-query.js +1 -1
- package/dist/src/tuck/core/search-entries.js +5 -5
- package/dist/src/tuck/core/transcript.js +2 -1
- package/dist/src/tuck.js +390 -394
- package/dist/src/windows-private-storage.d.ts +9 -0
- package/dist/src/windows-private-storage.js +90 -0
- package/index.ts +18 -82
- package/package.json +5 -8
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +28 -113
- package/src/diagnostic-replay.ts +2 -2
- package/src/diagnostics.ts +24 -9
- package/src/history-tools.ts +3 -3
- package/src/kept-reads.ts +78 -10
- package/src/ledger.ts +5 -3
- package/src/legacy-cleanup.ts +134 -0
- package/src/notify.ts +10 -0
- package/src/omissions.ts +3 -3
- package/src/path-key.ts +9 -0
- package/src/request-capacity.ts +1 -1
- package/src/run.ts +4 -6
- package/src/source-export.ts +1 -1
- package/src/status.ts +1 -10
- package/src/tuck/core/content.ts +5 -10
- package/src/tuck/core/keyword-query.ts +2 -2
- package/src/tuck/core/search-entries.ts +5 -5
- package/src/tuck/core/transcript.ts +2 -1
- package/src/tuck.ts +329 -335
- package/src/windows-private-storage.ts +94 -0
- package/dist/src/assets.d.ts +0 -58
- package/dist/src/assets.js +0 -80
- package/dist/src/eligibility-cache.d.ts +0 -19
- package/dist/src/eligibility-cache.js +0 -33
- package/dist/src/semantic-recall.d.ts +0 -422
- package/dist/src/semantic-recall.js +0 -1386
- package/dist/src/setup.d.ts +0 -3
- package/dist/src/setup.js +0 -191
- package/scripts/eg2-runtime.py +0 -307
- package/scripts/provision-eg2.py +0 -139
- package/scripts/semantic-worker.py +0 -234
- package/src/assets.ts +0 -92
- package/src/eligibility-cache.ts +0 -43
- package/src/semantic-recall.ts +0 -592
- package/src/setup.ts +0 -163
package/src/compaction.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { textOf } from "./tuck/core/content.js";
|
|
2
|
-
import { PendingCut, StartingPrompt,
|
|
2
|
+
import { PendingCut, StartingPrompt, Run, type CutEntry } from "./run.js";
|
|
3
3
|
import { requestReplyFloor, replyFit, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath, seedContextWindow, WINDOW_RECEIPT, type WindowReceipt } from "./request-capacity.js";
|
|
4
4
|
import { BUILD_ID } from "./build-id.js";
|
|
5
|
-
import { createSemanticRecall, budgetSemantic, type SemanticRecallController } from "./semantic-recall";
|
|
6
5
|
import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry, type Receipt, type RecorderOptions } from "./diagnostics.js";
|
|
7
6
|
import { createHash } from "node:crypto";
|
|
8
7
|
import { readFileSync } from "node:fs";
|
|
@@ -23,7 +22,7 @@ import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY
|
|
|
23
22
|
import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
|
|
24
23
|
import { LOADED_VERSION, statusText } from "./status.js";
|
|
25
24
|
import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
|
|
26
|
-
import {
|
|
25
|
+
import { notify } from "./notify.js";
|
|
27
26
|
import { applyHistoryTools, historyToolDeclarations, historyToolNames, stageHistoryTools } from "./history-tools.js";
|
|
28
27
|
|
|
29
28
|
const query = Type.String({ minLength: 1, maxLength: MAX_RECALL_QUERY_CHARACTERS });
|
|
@@ -46,7 +45,6 @@ const RecallInput = Type.Union([
|
|
|
46
45
|
Type.Object({ index: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }), query: Type.Optional(query), ...paging }, { additionalProperties: false }),
|
|
47
46
|
Type.Object(paging, { additionalProperties: false }),
|
|
48
47
|
]);
|
|
49
|
-
const SearchInput = Type.Object({query,priorResults:Type.Optional(Type.Array(Type.Object({sourceSha:Type.String({minLength:64,maxLength:64}),read:Type.Object({entryId,offset:Type.Integer({minimum:0}),limit:Type.Integer({minimum:0})},{additionalProperties:false})},{additionalProperties:false}),{maxItems:20}))},{additionalProperties:false});
|
|
50
48
|
const reply = (value: unknown) => ({ content: [{ type: "text" as const, text: JSON.stringify(value) }], details: {} });
|
|
51
49
|
/** The compactor's verdict that this attempt cannot be made: the cut it needs cannot be made, or the request cannot fit. Like every failure but
|
|
52
50
|
* a `CommitFault`, it ends with its attempt (`resetRun`), and the next attempt plans afresh from the session as it is. */
|
|
@@ -56,9 +54,6 @@ class Refusal extends Error {}
|
|
|
56
54
|
class CommitFault extends Error {}
|
|
57
55
|
/** A refusal for want of room, which the user can remedy: it carries advice. */
|
|
58
56
|
class CapacityError extends Refusal {}
|
|
59
|
-
function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") {
|
|
60
|
-
try { if (ctx.hasUI === false) process.stderr.write(message + "\n"); else ctx.ui.notify(message, level); } catch { /* ended */ }
|
|
61
|
-
}
|
|
62
57
|
/** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
|
|
63
58
|
* likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
|
|
64
59
|
export const refusalNotice = (message: string, factor: number): string =>
|
|
@@ -157,12 +152,6 @@ export function compactionState(model: { api: string; contextWindow?: number } |
|
|
|
157
152
|
return reason ? { kind: "standingDown", reason } : { kind: "active" };
|
|
158
153
|
}
|
|
159
154
|
export interface CompactionOptions {
|
|
160
|
-
semanticRecall?: SemanticRecallController;
|
|
161
|
-
/** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
|
|
162
|
-
search?: boolean;
|
|
163
|
-
/** Optional host-owned transient operator preference; handle operations never call back. */
|
|
164
|
-
onSemanticSetting?: (enabled: boolean) => Promise<unknown>;
|
|
165
|
-
semanticStatus?: () => unknown;
|
|
166
155
|
diagnostics?: RecorderOptions;
|
|
167
156
|
/** Optional read-only observation of actual corrected budget checks; no request content. */
|
|
168
157
|
observeBudget?: (measurement: { rawTokens: number; tokens: number; factor: number; response: number; room: number; hardLine?: number; context: ExtensionContext }) => void;
|
|
@@ -199,23 +188,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
199
188
|
const piClamp = piMath?.clampMaxTokensToContext;
|
|
200
189
|
const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
|
|
201
190
|
if (!validCutAt(cutAt)) throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
|
|
202
|
-
const semantic = options.semanticRecall ?? createSemanticRecall(), search = options.search ?? true;
|
|
203
191
|
const hostAccess = () => {
|
|
204
192
|
if (!active()) throw new Error("Compaction host is inactive");
|
|
205
193
|
options.assertAccess?.();
|
|
206
194
|
};
|
|
207
|
-
let semanticTransition: Promise<void> = Promise.resolve();
|
|
208
|
-
let semanticRequest = 0;
|
|
209
|
-
const semanticPending = new Set<Promise<unknown>>();
|
|
210
|
-
// Semantic indexing outlives any one attempt, so it checks only that the host still grants access: a compactor failure, which ends with its
|
|
211
|
-
// attempt, must not read as a revocation (that disables semantic recall and deletes its index for the rest of the session).
|
|
212
|
-
// A prompt's cut reaches the requests at once but the session only at the end of the first turn: until then search sees the history as the model does.
|
|
213
195
|
const view = (ctx: ExtensionContext, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
|
|
214
196
|
const liveCut = new PendingCut();
|
|
215
|
-
const semanticProvider = (ctx: ExtensionContext) => () => {
|
|
216
|
-
const current = view(ctx);
|
|
217
|
-
return memoizedEligibleSources(ctx, options.recallPolicy, hostAccess, current.pending ? current.keptFromId : undefined);
|
|
218
|
-
};
|
|
219
197
|
const recorder = new IncidentRecorder(options.diagnostics);
|
|
220
198
|
let proposalId: string | undefined;
|
|
221
199
|
const observe = (ctx: ExtensionContext) => recorder.measureInline(() => {
|
|
@@ -242,50 +220,14 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
242
220
|
ctx.ui.notify(JSON.stringify(recorder.status()), "info");
|
|
243
221
|
} });
|
|
244
222
|
pi.on("session_compact", (_event, ctx) => observe(ctx));
|
|
245
|
-
|
|
246
|
-
pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx)) semantic.indexAtCut(semanticProvider(ctx)); });
|
|
247
|
-
pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
|
|
248
|
-
pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close();void semanticTransition.catch(error => { options.fail?.(error); }); });
|
|
249
|
-
pi.on("turn_end", (_event,ctx) => { semantic.schedule(semanticProvider(ctx)); });
|
|
250
|
-
const applySemanticEnabled = async (enabled: boolean, ctx: ExtensionContext) => {
|
|
251
|
-
const request = ++semanticRequest;
|
|
252
|
-
if (!enabled) { semanticTransition = semantic.disable(); await semanticTransition; return semantic.status(); }
|
|
253
|
-
await semanticTransition;
|
|
254
|
-
if (request !== semanticRequest) return semantic.status();
|
|
255
|
-
access();
|
|
256
|
-
if (!semantic.status().configured) await semantic.configureExternal(ctx.cwd);
|
|
257
|
-
if (request !== semanticRequest) return semantic.status();
|
|
258
|
-
access(); semantic.enable(); semantic.schedule(semanticProvider(ctx));
|
|
259
|
-
return semantic.status();
|
|
260
|
-
};
|
|
261
|
-
const setSemanticEnabled = (enabled: boolean, ctx: ExtensionContext) => {
|
|
262
|
-
const operation = applySemanticEnabled(enabled,ctx);
|
|
263
|
-
semanticPending.add(operation);
|
|
264
|
-
void operation.then(()=>semanticPending.delete(operation),()=>semanticPending.delete(operation));
|
|
265
|
-
return operation;
|
|
266
|
-
};
|
|
267
|
-
const semanticStatus = () => ({local:semantic.status(),...(options.semanticStatus ? {host:options.semanticStatus()} : {})});
|
|
268
|
-
pi.registerCommand("tuck-semantic", {description:"Semantic recall for this session: on, off or status. To turn it off everywhere, set \"semanticRecall\": false in pi-tuck.json in Pi's agent folder.",handler:async(args,ctx)=>{
|
|
269
|
-
const command=args.trim();
|
|
270
|
-
if (!["on","off","status"].includes(command)) { ctx.ui.notify("Use on, off or status","warning"); return; }
|
|
271
|
-
const errors: string[] = [];
|
|
272
|
-
if (command!=="status") {
|
|
273
|
-
const enabled=command==="on";
|
|
274
|
-
// Both owners start directly. Off must attempt every host handle even if this one fails.
|
|
275
|
-
const operations=[setSemanticEnabled(enabled,ctx)];
|
|
276
|
-
if(options.onSemanticSetting) operations.push(Promise.resolve().then(()=>options.onSemanticSetting!(enabled)).then(()=>semantic.status()));
|
|
277
|
-
for(const result of await Promise.allSettled(operations)) if(result.status==="rejected") errors.push(String(result.reason));
|
|
278
|
-
}
|
|
279
|
-
ctx.ui.notify(JSON.stringify({...semanticStatus(),...(errors.length?{errors}:{})}),errors.length?"warning":"info");
|
|
280
|
-
}});
|
|
223
|
+
pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
|
|
281
224
|
pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
|
|
282
|
-
|
|
283
|
-
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
|
|
225
|
+
ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, pending: view(ctx).pending }), "info");
|
|
284
226
|
} });
|
|
285
227
|
// Pi's native start/settled events bracket the run and its post-turn cuts.
|
|
286
228
|
let run: Run | undefined;
|
|
287
229
|
// A commit-failed phase survives attempts/tree moves until session_start: native memory may be ahead of disk.
|
|
288
|
-
const failure = () => run?.
|
|
230
|
+
const failure = () => run?.error;
|
|
289
231
|
const protectedPrompt = (ctx: ExtensionContext) => run?.prompt?.id(ctx.sessionManager.getBranch());
|
|
290
232
|
const clips = () => run?.clips ?? emptyClips;
|
|
291
233
|
const emptyClips = new Map<string, Clip>();
|
|
@@ -294,7 +236,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
294
236
|
calibration.pending = undefined;
|
|
295
237
|
};
|
|
296
238
|
const beginRun = (phase: "decided" | "starting" | "admitted") => {
|
|
297
|
-
if (run?.phase === "commit-failed") run.clear(); else run =
|
|
239
|
+
if (run?.phase === "commit-failed") run.clear(); else run = new Run(phase);
|
|
298
240
|
};
|
|
299
241
|
const stateFor = (ctx: ExtensionContext) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
|
|
300
242
|
// A prerequisite can change with the model/settings; discard the old plan before returning control to native.
|
|
@@ -396,7 +338,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
396
338
|
// The operator's length-stop notice is decided at settle and is not attempt state: a run reset before then (a tree move inside another
|
|
397
339
|
// extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
|
|
398
340
|
let lengthStop = false;
|
|
399
|
-
pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??=
|
|
341
|
+
pi.on("agent_start", (_event, ctx) => { if (standDown(ctx)) return; run ??= new Run("starting"); if (!failure()) run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
|
|
400
342
|
pi.on("message_end", event => { if (event.message.role === "assistant") lengthStop = event.message.stopReason === "length"; });
|
|
401
343
|
pi.on("agent_settled", (_event, ctx) => {
|
|
402
344
|
try {
|
|
@@ -522,7 +464,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
522
464
|
const receipted = run?.refusalReceipted;
|
|
523
465
|
calibration.pending = undefined;
|
|
524
466
|
// Keep the same terminal run until Pi settles; later start hooks cannot admit it.
|
|
525
|
-
run ??=
|
|
467
|
+
run ??= new Run("starting"); run.clear();
|
|
526
468
|
run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
|
|
527
469
|
run.refusalReceipted = true;
|
|
528
470
|
try {
|
|
@@ -554,7 +496,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
554
496
|
|
|
555
497
|
pi.registerTool({
|
|
556
498
|
name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
|
|
557
|
-
description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged.
|
|
499
|
+
description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Hidden reasoning and system records are excluded.",
|
|
558
500
|
async execute(_id, raw, signal, _update, ctx) {
|
|
559
501
|
access();
|
|
560
502
|
const input = checkedInput(raw);
|
|
@@ -577,27 +519,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
577
519
|
return reply(tuckRecall(tuck, ctx.sessionManager.getEntries(), branch, input, options.recallPolicy));
|
|
578
520
|
},
|
|
579
521
|
});
|
|
580
|
-
if (search) pi.registerTool({name:"tuck_search",label:"History search",parameters:SearchInput,
|
|
581
|
-
description:"Find historical information relevant to a question, including different wording and related qualifications. Combines keyword and local embedding search. Knowing a name or identifier does not imply keyword-only lookup is sufficient. Returns original evidence up to 20000 characters; not exhaustive. Semantic search may be off or incomplete, which is not the same as no matches. Read exact originals and their context with tuck_recall at the returned locators. priorResults lists sources already read: pass each returned source's sourceSha and read unchanged.",
|
|
582
|
-
async execute(_id,raw,signal,_update,ctx){
|
|
583
|
-
access();if(!Check(SearchInput,raw))throw new Error("Invalid broad search input");const input=structuredClone(raw);
|
|
584
|
-
recorder.capture("recall-action","authorized-native-tool-invocation-no-result-copy",input);
|
|
585
|
-
// Bind the actual independent lexical offer, including attribution derived
|
|
586
|
-
// from custom markers and receipts excluded from semantic indexing. Rebuild
|
|
587
|
-
// under current caller policy after await, when the session moved; never send this block to the encoder.
|
|
588
|
-
// Keyword search over a very long history can hit its time limit. That limit guards one call, not the semantic half: the agent still gets the
|
|
589
|
-
// semantic results, and is told the keyword half stopped (seen in the field on an 84.7 MB session, where the whole search failed instead).
|
|
590
|
-
const wordOffer=()=>{try{return tuckRecall(tuck,ctx.sessionManager.getEntries(),ctx.sessionManager.getBranch(),{query:input.query},options.recallPolicy);}
|
|
591
|
-
catch(error){if(error instanceof Error&&error.message.startsWith("Search aborted:"))return{status:"keyword_timeout",notice:"Keyword search stopped at its time limit on this long history; the semantic results follow. For a keyword match, use more specific words or read an entry by index.",hits:[]};throw error;}};
|
|
592
|
-
// The key is taken in the same synchronous step as the first lexical pass. After the await the second pass runs only if it moved (see eligibilityKey); a moved key alone invalidates nothing.
|
|
593
|
-
// The snapshot id check covers every in-contract change (any branch change moves the id); the key-gated second pass is defence in depth for out-of-contract callers.
|
|
594
|
-
const provider=semanticProvider(ctx),initialSnapshot=provider(),initialKey=eligibilityKey(ctx),words=wordOffer(),wordText=JSON.stringify(words);
|
|
595
|
-
const related=await semantic.search(input.query,provider,signal,(input.priorResults??[]).map(({sourceSha,read})=>({entryId:read.entryId,sourceSha,start:read.offset,end:read.offset+read.limit})),words);
|
|
596
|
-
access();if(signal?.aborted)throw Object.assign(new Error('Semantic recall cancelled'),{name:'AbortError'});const now=provider();
|
|
597
|
-
if(initialSnapshot.id!==now.id||(eligibilityKeyMoved(ctx,initialKey)&&wordText!==JSON.stringify(wordOffer())))return{...reply({status:"snapshot_invalidated",notice:"Search source eligibility or version changed; no earlier evidence delivered. Request a fresh query."}),isError:true};
|
|
598
|
-
const page=budgetSemantic(related,20000-wordText.length-1);
|
|
599
|
-
return{content:[{type:"text" as const,text:wordText},{type:"text" as const,text:JSON.stringify(page)}],details:{semantic:{status:page.status,snapshotId:page.coverage.snapshotId}}};
|
|
600
|
-
}});
|
|
601
522
|
|
|
602
523
|
pi.on("session_before_compact", (event, ctx) => {
|
|
603
524
|
try {
|
|
@@ -650,7 +571,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
650
571
|
// Every cut asked while no run is admitted (an operator's cut) is planned for a run that has not begun: the session has moved on
|
|
651
572
|
// from any run that ended. A retry is inside its run.
|
|
652
573
|
const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined);
|
|
653
|
-
return draft.compaction ? { draft: true, after: draft.after,
|
|
574
|
+
return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
|
|
654
575
|
messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
|
|
655
576
|
: { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
656
577
|
},
|
|
@@ -722,14 +643,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
722
643
|
if (!draft.compaction) return { kind: "fault", capacity: Boolean(draft.capacityRejected), message: draft.unavailable };
|
|
723
644
|
const messages = plannedView(ctx, { type: "compaction", ...draft.compaction }).session.buildSessionProjection().messages;
|
|
724
645
|
assertNativeToolRounds(messages);
|
|
725
|
-
return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
|
|
646
|
+
return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
|
|
726
647
|
compaction: draft.compaction, reserve: 0, messages } };
|
|
727
648
|
};
|
|
728
649
|
// 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
|
|
729
650
|
// 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
|
|
730
651
|
// keepRecentTokens, and where those are the whole conversation it has nothing to cut, so every later prompt was refused for good (t06 at
|
|
731
|
-
// Pi's defaults on a 32k window). Each request
|
|
732
|
-
|
|
652
|
+
// Pi's defaults on a 32k window). Each request carries the cut until the next boundary saves it. A late steer uses the same path with
|
|
653
|
+
// its existing run owner's entry protected; an incoming prompt that starts a run has no saved owner yet.
|
|
654
|
+
const preflight = (ctx: ExtensionContext, incomingPart: number, incomingMessages: Messages, observedPrompt: string, tools: readonly string[], hostSnapshot?: Messages, protectedId?: string) => {
|
|
733
655
|
if (standDown(ctx)) return;
|
|
734
656
|
run!.cut.clear();
|
|
735
657
|
const branchLength = ctx.sessionManager.getBranch().length;
|
|
@@ -760,13 +682,15 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
760
682
|
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
761
683
|
// Only a due cut re-renders a summary that sits alone in the session: inside the band a cut is opportunistic, and a smaller summary
|
|
762
684
|
// there buys nothing the request needed and costs history the next recall would have found.
|
|
763
|
-
|
|
685
|
+
// A steer joins the admitted run: keep its starting prompt and the unexposed tool round, just as at a tool boundary.
|
|
686
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
687
|
+
newPrompt: !protectedId, protectedPromptEntryId: protectedId, reRenderSummary: !opportunistic }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, Boolean(protectedId));
|
|
764
688
|
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
765
689
|
const candidate = new PendingCut();
|
|
766
690
|
candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
|
|
767
691
|
const messages = candidate.view(ctx).session.buildSessionProjection().messages;
|
|
768
692
|
assertNativeToolRounds(messages);
|
|
769
|
-
return { draft: true, after: measure(messages),
|
|
693
|
+
return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
|
|
770
694
|
},
|
|
771
695
|
});
|
|
772
696
|
let decision: Decision<CutPlan> = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
|
|
@@ -778,13 +702,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
778
702
|
candidate => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory,
|
|
779
703
|
candidate => projectedRequest(candidate.kind === "cut" ? candidate.plan.messages : saved, ctx, hostInput, incomingMessages, observedPrompt, tools, candidate.kind === "cut"),
|
|
780
704
|
target => decide(target, target <= room ? band : target, false),
|
|
781
|
-
() => deepestDecision(ctx,
|
|
705
|
+
() => deepestDecision(ctx, !protectedId, Boolean(protectedId)));
|
|
782
706
|
}
|
|
783
707
|
if (decision.kind === "defer") return;
|
|
784
708
|
// An opportunistic cut inside the band that cannot reach it is no fault: the request goes to the guard.
|
|
785
709
|
if (decision.kind === "none") return;
|
|
786
710
|
if (decision.kind === "fault") throw new (decision.capacity ? CapacityError : Refusal)(decision.message);
|
|
787
|
-
const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before,
|
|
711
|
+
const compaction = captureDraft(decision.plan.compaction, ctx, decision.plan.reserve, "prompt", before, Boolean(protectedId), false, previousSummary,
|
|
788
712
|
{ response, host, mandatory, target: decision.target, margin: room - band });
|
|
789
713
|
run!.cut.plan({ type: "compaction", summary: compaction.summary, firstKeptEntryId: compaction.firstKeptEntryId, tokensBefore: before, details: compaction.details }, branchLength);
|
|
790
714
|
};
|
|
@@ -794,7 +718,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
794
718
|
// input, so no run started for it): plan afresh.
|
|
795
719
|
const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
|
|
796
720
|
if (!prompted && !failure()) beginRun("starting");
|
|
797
|
-
run ??=
|
|
721
|
+
run ??= new Run("starting");
|
|
798
722
|
if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
|
|
799
723
|
const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
|
|
800
724
|
run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
|
|
@@ -810,7 +734,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
810
734
|
else applyHistoryTools(pi, false);
|
|
811
735
|
const staged = pi.getActiveTools();
|
|
812
736
|
event.systemPromptOptions.selectedTools = historyToolNames(pi, event.systemPromptOptions.selectedTools, true).filter(name =>
|
|
813
|
-
name !== "tuck_recall"
|
|
737
|
+
name !== "tuck_recall" || staged.includes(name));
|
|
814
738
|
} catch (error) { fail(error, ctx); }
|
|
815
739
|
});
|
|
816
740
|
// The incoming user message is about to be appended (including steering inside a run), and later before_agent_start/turn_start
|
|
@@ -829,7 +753,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
829
753
|
const hostInput = hostMessages(ctx), host = conversationTokens(hostInput);
|
|
830
754
|
const system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), saved, ctx.getSystemPrompt());
|
|
831
755
|
if (fits(conversationTokens(saved) + system + incoming + host, limits(ctx).room, ctx)) return;
|
|
832
|
-
preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput);
|
|
756
|
+
preflight(ctx, incoming, [message], ctx.getSystemPrompt(), pi.getActiveTools(), hostInput, protectedPrompt(ctx));
|
|
833
757
|
syncHistoryTools(ctx);
|
|
834
758
|
} catch (error) { fail(error, ctx); }
|
|
835
759
|
});
|
|
@@ -862,7 +786,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
862
786
|
const lastCut = ctx.sessionManager.getBranch().findLast(entry => entry.type === "compaction");
|
|
863
787
|
if (reason === "run-end" && lastAssistant && (!lastCut || lastAssistant.timestamp > Date.parse(lastCut.timestamp)) &&
|
|
864
788
|
!saved.some(message => message.role === "assistant" &&
|
|
865
|
-
!
|
|
789
|
+
!isDiscardedResponse(message) && message.usage && calculateContextTokens(message.usage) > 0)) {
|
|
866
790
|
const forecast = historyToolDeclarations(saved, toolShapes(historyToolNames(pi, pi.getActiveTools(), true)), true);
|
|
867
791
|
if (forecast !== saved) {
|
|
868
792
|
const head = getCurrentSystemMessage(convertToLlm(forecast));
|
|
@@ -906,7 +830,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
906
830
|
const messages = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
907
831
|
assertNativeToolRounds(messages);
|
|
908
832
|
previews.push(messages);
|
|
909
|
-
return { draft: true, after: measure(messages),
|
|
833
|
+
return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
|
|
910
834
|
},
|
|
911
835
|
});
|
|
912
836
|
};
|
|
@@ -977,20 +901,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
977
901
|
};
|
|
978
902
|
const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
|
|
979
903
|
const current = view(ctx);
|
|
980
|
-
if (!current.pending)
|
|
981
|
-
const result = decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
982
|
-
// Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
|
|
983
|
-
if (result?.entries.some(entry => entry.type === "compaction")) setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
984
|
-
return result;
|
|
985
|
-
}
|
|
904
|
+
if (!current.pending) return decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
986
905
|
const entry = run!.cut.take()!;
|
|
987
906
|
const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
988
907
|
const more = decide && !event.entries.length
|
|
989
908
|
? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
|
|
990
909
|
const { tokensBefore: _, ...cut } = entry;
|
|
991
910
|
const saved = { ...cut, firstKeptEntryId: current.keptFromId! };
|
|
992
|
-
// As for a cut Pi makes (session_compact): the history the cut leaves behind is indexed, once Pi has committed the entries.
|
|
993
|
-
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
994
911
|
return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
|
|
995
912
|
};
|
|
996
913
|
const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
|
|
@@ -1037,8 +954,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1037
954
|
stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
|
|
1038
955
|
estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
1039
956
|
markBoundary(drafts);
|
|
1040
|
-
// As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
|
|
1041
|
-
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
1042
957
|
return { entries: drafts, continue: true };
|
|
1043
958
|
};
|
|
1044
959
|
pi.on("turn_end", (event, ctx) => {
|
|
@@ -1101,7 +1016,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1101
1016
|
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1102
1017
|
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1103
1018
|
assertNativeToolRounds(kept);
|
|
1104
|
-
return { draft: true, after: measure(kept),
|
|
1019
|
+
return { draft: true, after: measure(kept), compaction: draft.compaction, reserve, messages: kept };
|
|
1105
1020
|
},
|
|
1106
1021
|
});
|
|
1107
1022
|
const project = (candidate: Decision<CutPlan>) => candidate.kind === "cut"
|
|
@@ -1225,7 +1140,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1225
1140
|
|
|
1226
1141
|
} catch (error) { fail(error, ctx); }
|
|
1227
1142
|
});
|
|
1228
|
-
return {close:async()=>{
|
|
1143
|
+
return {close:async()=>{recorder.stop("caller-close");}, state: stateFor, inspectState: (ctx: ExtensionContext) => ({ run: run as Readonly<Run> | undefined, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending })};
|
|
1229
1144
|
}
|
|
1230
1145
|
|
|
1231
1146
|
function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
|
package/src/diagnostic-replay.ts
CHANGED
|
@@ -13,9 +13,9 @@ export function inspectIncident(records: IncidentRecord[]) {
|
|
|
13
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);
|
|
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
|
-
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference,
|
|
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.' };
|
|
17
17
|
});
|
|
18
|
-
return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all
|
|
18
|
+
return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
|
|
19
19
|
}
|
|
20
20
|
export function readableIncident(records: IncidentRecord[]): string {
|
|
21
21
|
return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
|
package/src/diagnostics.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { BUILD_ID } from './build-id.js';
|
|
2
2
|
import { constants } from 'node:fs';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { mkdir, open, readdir, lstat, unlink, realpath } from 'node:fs/promises';
|
|
4
|
+
import { mkdir, open, readdir, lstat, unlink, realpath, type FileHandle } from 'node:fs/promises';
|
|
5
5
|
import { join, resolve, relative, isAbsolute, dirname, basename } from 'node:path';
|
|
6
6
|
import { homedir } from 'node:os';
|
|
7
7
|
import { createRecall, type RecallPolicy } from './recall.js';
|
|
8
8
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
9
|
+
import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
|
|
9
10
|
export const DIAGNOSTIC_BUILD = BUILD_ID;
|
|
10
11
|
export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; learnedContextWindow?: number; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
|
|
11
12
|
export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
|
|
@@ -21,7 +22,7 @@ export function findReceiptEntry(entries: SessionEntry[], id: string) { const ma
|
|
|
21
22
|
export interface RecorderOptions { directory?: string; maxContentCharacters?: number; maxQueueCharacters?: number; maxFileBytes?: number; maxFiles?: number; durationMs?: number; write?: (path: string, content: string) => Promise<void>; }
|
|
22
23
|
export interface IncidentRecord { kind: string; scope: string; data: unknown; partial: boolean; }
|
|
23
24
|
/** A bounded clone. Budget is charged before every copy; forbidden fields are never traversed.
|
|
24
|
-
* This is conservative structural/pattern redaction, not
|
|
25
|
+
* This is conservative structural/pattern redaction, not detection of secrets conveyed by meaning. */
|
|
25
26
|
export function boundedCopy(value: unknown, limit: number): { data: unknown; characters: number; partial: boolean } {
|
|
26
27
|
let remaining = limit, partial = false;
|
|
27
28
|
const spend = (n: number) => { if (n > remaining) { partial = true; return false; } remaining -= n; return true; };
|
|
@@ -60,6 +61,7 @@ export function permittedEntries(entries: SessionEntry[], policy: RecallPolicy =
|
|
|
60
61
|
return { entries: allowed, partial };
|
|
61
62
|
}
|
|
62
63
|
export class IncidentRecorder {
|
|
64
|
+
private windowsFile?: FileHandle;
|
|
63
65
|
private queue: string[] = []; private queued = 0; private total = 0; private pumping?: Promise<void>; private timer?: ReturnType<typeof setTimeout>;
|
|
64
66
|
private captureCalls = 0; private inlineMs = 0; private hookMs = 0;
|
|
65
67
|
private projectDirectory = ''; private id = ''; private path = ''; private state = 'off'; private nextCut = false; private sawCut = false; private requests = 0; private response = false;
|
|
@@ -70,7 +72,7 @@ export class IncidentRecorder {
|
|
|
70
72
|
constructor(options: RecorderOptions = {}) {
|
|
71
73
|
const bound = (value: number | undefined, fallback: number, max: number) => Number.isSafeInteger(value) && value! > 0 ? Math.min(value!,max) : fallback;
|
|
72
74
|
this.options = { ...options, maxContentCharacters: bound(options.maxContentCharacters,200000,1500000), maxQueueCharacters: bound(options.maxQueueCharacters,500000,3000000), maxFileBytes: bound(options.maxFileBytes,2000000,10000000), maxFiles: bound(options.maxFiles,4,8), durationMs: bound(options.durationMs,120000,600000) };
|
|
73
|
-
this.directory = resolve(options.directory ?? join(homedir(), '.local
|
|
75
|
+
this.directory = resolve(options.directory ?? join(homedir(), '.local', 'state', 'pi-tuck-incidents')); }
|
|
74
76
|
get waitingForCut() { return this.enabled && this.nextCut && !this.sawCut; }
|
|
75
77
|
get enabled() { return this.state === 'recording'; }
|
|
76
78
|
status() { return { state: this.state, incidentId: this.id || null, queuedCharacters: this.queued, recordedCharacters: this.total, path: this.path || null, captureCalls: this.captureCalls, inlineMilliseconds: this.inlineMs, inlineHookMilliseconds: this.hookMs }; }
|
|
@@ -80,7 +82,7 @@ export class IncidentRecorder {
|
|
|
80
82
|
if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) { notify('Recorder directory must be outside project'); return; }
|
|
81
83
|
this.projectDirectory = resolve(project); this.notify = notify; this.state = 'recording'; this.nextCut = nextCut; this.sawCut = false; this.requests = 0; this.response = false; this.total = 0; this.captureCalls = 0; this.inlineMs = 0; this.hookMs = 0; this.id = randomUUID(); this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
|
|
82
84
|
this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs); this.timer.unref();
|
|
83
|
-
this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible.
|
|
85
|
+
this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
|
|
84
86
|
}
|
|
85
87
|
measureInline<T>(operation: () => T): T { if (!this.enabled) return operation(); const started = performance.now(); try { return operation(); } finally { this.hookMs += performance.now() - started; } }
|
|
86
88
|
capture(kind: string, scope: string, value: unknown, inheritedPartial = false) {
|
|
@@ -113,6 +115,7 @@ export class IncidentRecorder {
|
|
|
113
115
|
private schedule() { if (!this.pumping) this.pumping = Promise.resolve().then(() => this.pump()); }
|
|
114
116
|
private async pump() {
|
|
115
117
|
try {
|
|
118
|
+
const windows = process.platform === 'win32';
|
|
116
119
|
// Resolve existing ancestors before creating anything; an outside path may
|
|
117
120
|
// traverse a parent symlink into the active project.
|
|
118
121
|
let ancestor = this.directory; const missing: string[] = [];
|
|
@@ -124,21 +127,33 @@ export class IncidentRecorder {
|
|
|
124
127
|
const physicalProject = await realpath(this.projectDirectory).catch(() => this.projectDirectory);
|
|
125
128
|
const rel = relative(physicalProject, physicalDirectory);
|
|
126
129
|
if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) throw new Error('Recorder directory resolves inside project');
|
|
127
|
-
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
130
|
+
if (!windows) await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
131
|
+
else if (missing.length) await createPrivateDirectory(this.directory);
|
|
128
132
|
const directoryStat = await lstat(this.directory);
|
|
129
|
-
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || (directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.()) throw new Error('Recorder directory ownership/permissions');
|
|
133
|
+
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || !windows && ((directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.())) throw new Error('Recorder directory ownership/permissions');
|
|
130
134
|
const names: { name: string; time: number }[] = [];
|
|
131
|
-
for (const name of await readdir(this.directory)) if (/^tuck-incident-[0-9a-f-]{36}\.jsonl$/.test(name)) { const stat = await lstat(join(this.directory,name)); if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error('Retention ownership gap'); names.push({name,time:stat.mtimeMs}); }
|
|
135
|
+
for (const name of await readdir(this.directory)) if (/^tuck-incident-[0-9a-f-]{36}\.jsonl$/.test(name)) { const stat = await lstat(join(this.directory,name)); if (!stat.isFile() || stat.isSymbolicLink() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077))) throw new Error('Retention ownership gap'); names.push({name,time:stat.mtimeMs}); }
|
|
136
|
+
if (windows) await assertWindowsPrivateStorage([this.directory, ...names.map(({ name }) => join(this.directory, name))]);
|
|
132
137
|
names.sort((a,b)=>a.time-b.time);
|
|
133
138
|
while (names.length >= this.options.maxFiles) { const { name } = names.shift()!; if (join(this.directory, name) !== this.path) await unlink(join(this.directory, name)); }
|
|
139
|
+
if (windows && !this.options.write && !this.windowsFile) {
|
|
140
|
+
// O_NOFOLLOW is unavailable on Windows. Exclusive creation rejects an existing link/file,
|
|
141
|
+
// and the same handle is retained until recording stops; subsequent pumps never reopen the path.
|
|
142
|
+
this.windowsFile = await open(this.path, 'wx', 0o600);
|
|
143
|
+
await protectWindowsIncidentFile(this.path);
|
|
144
|
+
await assertWindowsPrivateStorage([this.path]);
|
|
145
|
+
}
|
|
134
146
|
while (this.queue.length) {
|
|
135
147
|
const line = this.queue.shift()!; this.queued -= line.length;
|
|
136
148
|
if (Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound');
|
|
137
149
|
if (this.options.write) await this.options.write(this.path, line);
|
|
138
|
-
else { const file = await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try { const stat = await file.stat(); if (stat.size + Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound'); if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error('Recorder file ownership/permissions'); await file.write(line); } finally { await file.close(); } }
|
|
150
|
+
else { const file = this.windowsFile ?? await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try { const stat = await file.stat(); if (stat.size + Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound'); if (!stat.isFile() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077))) throw new Error('Recorder file ownership/permissions'); await file.write(line); } finally { if (!windows) await file.close(); } }
|
|
139
151
|
}
|
|
140
152
|
} catch { this.queue = []; this.queued = 0; if (this.timer) clearTimeout(this.timer); this.timer = undefined; this.state = 'storage-failed-gap'; this.safeNotify('Compaction recorder storage failed; incident has a gap'); }
|
|
141
|
-
finally {
|
|
153
|
+
finally {
|
|
154
|
+
if (!this.enabled && this.windowsFile) { const file = this.windowsFile; this.windowsFile = undefined; await file.close().catch(() => {}); }
|
|
155
|
+
this.pumping = undefined; if (this.queue.length) this.schedule();
|
|
156
|
+
}
|
|
142
157
|
}
|
|
143
158
|
async flush() { while (this.pumping) await this.pumping; }
|
|
144
159
|
}
|
package/src/history-tools.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { getCurrentTools } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import { convertToLlm, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import type { Messages, ToolShape } from "./budget.js";
|
|
4
4
|
|
|
5
|
-
const own = (name: string) => name === "tuck_recall"
|
|
5
|
+
const own = (name: string) => name === "tuck_recall";
|
|
6
6
|
/** Native Pi compactions do not make pi-tuck history available. No session-wide activation state. */
|
|
7
7
|
export const hasTuckCut = (branch: readonly { type: string; details?: unknown }[]): boolean => branch.some(entry =>
|
|
8
8
|
entry.type === "compaction" && (entry.details as { compactor?: unknown } | null)?.compactor === "pi-tuck");
|
|
@@ -11,7 +11,7 @@ export const hasTuckCut = (branch: readonly { type: string; details?: unknown }[
|
|
|
11
11
|
export function historyToolNames(pi: ExtensionAPI, names: readonly string[], enabled: boolean): string[] {
|
|
12
12
|
if (!enabled) return names.filter(name => !own(name));
|
|
13
13
|
const registered = new Set(pi.getAllTools().map(tool => tool.name));
|
|
14
|
-
return [...names, ...["tuck_recall"
|
|
14
|
+
return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
export function applyHistoryTools(pi: ExtensionAPI, enabled: boolean): void {
|
|
@@ -45,7 +45,7 @@ export function historyToolDeclarations(messages: Messages, tools: readonly Tool
|
|
|
45
45
|
// Leave an already-correct transcript byte-identical, including the original placement of our declarations.
|
|
46
46
|
const declared = getCurrentTools(convertToLlm(messages));
|
|
47
47
|
const wanted = enabled ? tools.filter(tool => own(tool.name)) : [];
|
|
48
|
-
if (enabled && wanted.every(tool => declared.some(current =>
|
|
48
|
+
if (enabled && wanted.every(tool => declared.some(current => current.name === tool.name)) &&
|
|
49
49
|
declared.filter(tool => own(tool.name)).length === wanted.length) return messages;
|
|
50
50
|
if (!enabled || !wanted.length) return changed ? filtered : messages;
|
|
51
51
|
const at = filtered.findLastIndex(message => message.role === "system");
|
package/src/kept-reads.ts
CHANGED
|
@@ -1,23 +1,91 @@
|
|
|
1
|
-
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
1
|
+
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { pathKey } from "./path-key";
|
|
2
4
|
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
3
5
|
import { extractPath } from "./tuck/core/tool-args";
|
|
4
6
|
import type { TranscriptRecord } from "./tuck/core/transcript";
|
|
5
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
|
+
|
|
6
55
|
/** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
|
|
7
|
-
export function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>,
|
|
56
|
+
export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
|
|
8
57
|
resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
|
|
9
|
-
const
|
|
58
|
+
const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
|
|
59
|
+
const reads = new Map<string, { path: string; key: string; order: number }>(), mutations = new Map<string, number>();
|
|
60
|
+
let allMutated = -1;
|
|
10
61
|
let order = 0;
|
|
11
62
|
for (const entry of entries) {
|
|
12
63
|
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
13
64
|
for (const block of entry.message.content) {
|
|
14
|
-
if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
|
|
65
|
+
if (block.type !== "toolCall" || !["read", "write", "edit", "bash"].includes(block.name) ||
|
|
15
66
|
!block.arguments || typeof block.arguments !== "object") continue;
|
|
16
|
-
const
|
|
17
|
-
if (!path || /[\r\n]/u.test(path)) continue;
|
|
67
|
+
const args = block.arguments as Record<string, unknown>;
|
|
18
68
|
order++;
|
|
19
|
-
if (block.name === "
|
|
20
|
-
|
|
69
|
+
if (block.name === "bash") {
|
|
70
|
+
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;
|
|
79
|
+
const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
|
|
80
|
+
for (const name of names) if (name) { mutations.set(pathKey(name), order); mutations.set(pathKey(name, base), order); }
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const path = extractPath(args);
|
|
84
|
+
if (!path || /[\r\n]/u.test(path)) continue;
|
|
85
|
+
const key = pathKey(path, cwd);
|
|
86
|
+
if (block.name === "read") {
|
|
87
|
+
if (!("offset" in args) && !("limit" in args)) reads.set(block.id, { path, key, order });
|
|
88
|
+
} else mutations.set(key, order);
|
|
21
89
|
}
|
|
22
90
|
}
|
|
23
91
|
const seen = new Set<string>(), records: TranscriptRecord[] = [];
|
|
@@ -25,10 +93,10 @@ export function keptReadCandidates(entries: readonly SessionEntry[], indices: Re
|
|
|
25
93
|
const entry = entries[at]!;
|
|
26
94
|
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
|
|
27
95
|
const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
|
|
28
|
-
if (!read || seen.has(read.
|
|
96
|
+
if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
|
|
29
97
|
const text = textOf(entry.message.content);
|
|
30
98
|
if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
|
|
31
|
-
seen.add(read.
|
|
99
|
+
seen.add(read.key);
|
|
32
100
|
records.push({ kind: "section", title: "Kept-read", sourceIndex,
|
|
33
101
|
text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
|
|
34
102
|
}
|