pi-tuck 1.1.3 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +64 -0
- package/README.md +28 -59
- package/dist/index.d.ts +2 -6
- package/dist/index.js +16 -111
- package/dist/src/bash-command.d.ts +8 -0
- package/dist/src/bash-command.js +116 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +2 -103
- package/dist/src/compaction.js +20 -140
- package/dist/src/diagnostic-replay.js +3 -3
- 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 +35 -8
- package/dist/src/kept-searches.d.ts +11 -0
- package/dist/src/kept-searches.js +202 -0
- 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.d.ts +0 -11
- package/dist/src/tuck/core/content.js +5 -55
- 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.d.ts +5 -28
- package/dist/src/tuck/core/search-entries.js +14 -156
- package/dist/src/tuck/core/transcript.js +2 -1
- package/dist/src/tuck.d.ts +7 -15
- package/dist/src/tuck.js +409 -409
- 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/bash-command.ts +59 -0
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +19 -107
- package/src/diagnostic-replay.ts +3 -3
- package/src/diagnostics.ts +24 -9
- package/src/history-tools.ts +3 -3
- package/src/kept-reads.ts +27 -10
- package/src/kept-searches.ts +163 -0
- 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 +4 -52
- package/src/tuck/core/keyword-query.ts +2 -2
- package/src/tuck/core/search-entries.ts +15 -202
- package/src/tuck/core/transcript.ts +2 -1
- package/src/tuck.ts +350 -357
- 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,7 +643,7 @@ 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
|
|
@@ -769,7 +690,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
769
690
|
candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
|
|
770
691
|
const messages = candidate.view(ctx).session.buildSessionProjection().messages;
|
|
771
692
|
assertNativeToolRounds(messages);
|
|
772
|
-
return { draft: true, after: measure(messages),
|
|
693
|
+
return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
|
|
773
694
|
},
|
|
774
695
|
});
|
|
775
696
|
let decision: Decision<CutPlan> = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
|
|
@@ -797,7 +718,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
797
718
|
// input, so no run started for it): plan afresh.
|
|
798
719
|
const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
|
|
799
720
|
if (!prompted && !failure()) beginRun("starting");
|
|
800
|
-
run ??=
|
|
721
|
+
run ??= new Run("starting");
|
|
801
722
|
if (!failure() && run.phase !== "starting") run.transition("starting", ctx);
|
|
802
723
|
const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
|
|
803
724
|
run.prompt = prompt ? new StartingPrompt(prompt, ctx.sessionManager.getBranch().length, event.messageType) : undefined;
|
|
@@ -813,7 +734,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
813
734
|
else applyHistoryTools(pi, false);
|
|
814
735
|
const staged = pi.getActiveTools();
|
|
815
736
|
event.systemPromptOptions.selectedTools = historyToolNames(pi, event.systemPromptOptions.selectedTools, true).filter(name =>
|
|
816
|
-
name !== "tuck_recall"
|
|
737
|
+
name !== "tuck_recall" || staged.includes(name));
|
|
817
738
|
} catch (error) { fail(error, ctx); }
|
|
818
739
|
});
|
|
819
740
|
// The incoming user message is about to be appended (including steering inside a run), and later before_agent_start/turn_start
|
|
@@ -865,7 +786,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
865
786
|
const lastCut = ctx.sessionManager.getBranch().findLast(entry => entry.type === "compaction");
|
|
866
787
|
if (reason === "run-end" && lastAssistant && (!lastCut || lastAssistant.timestamp > Date.parse(lastCut.timestamp)) &&
|
|
867
788
|
!saved.some(message => message.role === "assistant" &&
|
|
868
|
-
!
|
|
789
|
+
!isDiscardedResponse(message) && message.usage && calculateContextTokens(message.usage) > 0)) {
|
|
869
790
|
const forecast = historyToolDeclarations(saved, toolShapes(historyToolNames(pi, pi.getActiveTools(), true)), true);
|
|
870
791
|
if (forecast !== saved) {
|
|
871
792
|
const head = getCurrentSystemMessage(convertToLlm(forecast));
|
|
@@ -909,7 +830,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
909
830
|
const messages = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
910
831
|
assertNativeToolRounds(messages);
|
|
911
832
|
previews.push(messages);
|
|
912
|
-
return { draft: true, after: measure(messages),
|
|
833
|
+
return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
|
|
913
834
|
},
|
|
914
835
|
});
|
|
915
836
|
};
|
|
@@ -980,20 +901,13 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
980
901
|
};
|
|
981
902
|
const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
|
|
982
903
|
const current = view(ctx);
|
|
983
|
-
if (!current.pending)
|
|
984
|
-
const result = decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
985
|
-
// Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
|
|
986
|
-
if (result?.entries.some(entry => entry.type === "compaction")) setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
987
|
-
return result;
|
|
988
|
-
}
|
|
904
|
+
if (!current.pending) return decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
989
905
|
const entry = run!.cut.take()!;
|
|
990
906
|
const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
991
907
|
const more = decide && !event.entries.length
|
|
992
908
|
? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
|
|
993
909
|
const { tokensBefore: _, ...cut } = entry;
|
|
994
910
|
const saved = { ...cut, firstKeptEntryId: current.keptFromId! };
|
|
995
|
-
// As for a cut Pi makes (session_compact): the history the cut leaves behind is indexed, once Pi has committed the entries.
|
|
996
|
-
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
997
911
|
return { entries: [...event.entries as CutEntry[], saved, ...(more?.entries ?? [])] };
|
|
998
912
|
};
|
|
999
913
|
const retryLength = (event: TurnEndEvent, ctx: ExtensionContext) => {
|
|
@@ -1040,8 +954,6 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1040
954
|
stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
|
|
1041
955
|
estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
1042
956
|
markBoundary(drafts);
|
|
1043
|
-
// As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
|
|
1044
|
-
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
1045
957
|
return { entries: drafts, continue: true };
|
|
1046
958
|
};
|
|
1047
959
|
pi.on("turn_end", (event, ctx) => {
|
|
@@ -1104,7 +1016,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1104
1016
|
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1105
1017
|
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1106
1018
|
assertNativeToolRounds(kept);
|
|
1107
|
-
return { draft: true, after: measure(kept),
|
|
1019
|
+
return { draft: true, after: measure(kept), compaction: draft.compaction, reserve, messages: kept };
|
|
1108
1020
|
},
|
|
1109
1021
|
});
|
|
1110
1022
|
const project = (candidate: Decision<CutPlan>) => candidate.kind === "cut"
|
|
@@ -1228,7 +1140,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1228
1140
|
|
|
1229
1141
|
} catch (error) { fail(error, ctx); }
|
|
1230
1142
|
});
|
|
1231
|
-
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 })};
|
|
1232
1144
|
}
|
|
1233
1145
|
|
|
1234
1146
|
function checkedInput(raw: unknown) { if (!Check(RecallInput, raw)) throw new Error("Invalid recall input"); return structuredClone(raw); }
|
package/src/diagnostic-replay.ts
CHANGED
|
@@ -10,12 +10,12 @@ export function inspectIncident(records: IncidentRecord[]) {
|
|
|
10
10
|
const manager = SessionManager.inMemory('/offline-compaction-replay', undefined, [i.header, ...i.entries]);
|
|
11
11
|
if (i.branchEntryIds?.length) manager.branch(i.branchEntryIds.at(-1)!);
|
|
12
12
|
const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } } as unknown as ExtensionContext;
|
|
13
|
-
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary
|
|
13
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary }, ctx, i.reserve!, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
14
14
|
const proposal = records.find(r => r.kind === 'proposal' && (r.data as { details?: { diagnosticReceipt?: { id?: string } } })?.details?.diagnosticReceipt?.id === i.receiptId)?.data as { summary?: string; firstKeptEntryId?: string } | undefined;
|
|
15
15
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
16
|
-
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,40 @@
|
|
|
1
|
-
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
1
|
+
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { classifyBash } from "./bash-command";
|
|
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
|
|
|
6
8
|
/** 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>,
|
|
9
|
+
export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
|
|
8
10
|
resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
|
|
9
|
-
const
|
|
11
|
+
const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
|
|
12
|
+
const reads = new Map<string, { path: string; key: string; order: number }>(), mutations = new Map<string, number>();
|
|
13
|
+
let allMutated = -1;
|
|
10
14
|
let order = 0;
|
|
11
15
|
for (const entry of entries) {
|
|
12
16
|
if (entry.type !== "message" || entry.message.role !== "assistant") continue;
|
|
13
17
|
for (const block of entry.message.content) {
|
|
14
|
-
if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
|
|
18
|
+
if (block.type !== "toolCall" || !["read", "write", "edit", "bash"].includes(block.name) ||
|
|
15
19
|
!block.arguments || typeof block.arguments !== "object") continue;
|
|
16
|
-
const
|
|
17
|
-
if (!path || /[\r\n]/u.test(path)) continue;
|
|
20
|
+
const args = block.arguments as Record<string, unknown>;
|
|
18
21
|
order++;
|
|
19
|
-
if (block.name === "
|
|
20
|
-
|
|
22
|
+
if (block.name === "bash") {
|
|
23
|
+
if (!reads.size || typeof args.command !== "string") continue;
|
|
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);
|
|
28
|
+
const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
|
|
29
|
+
for (const name of names) if (name) { mutations.set(pathKey(name), order); mutations.set(pathKey(name, base), order); }
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const path = extractPath(args);
|
|
33
|
+
if (!path || /[\r\n]/u.test(path)) continue;
|
|
34
|
+
const key = pathKey(path, cwd);
|
|
35
|
+
if (block.name === "read") {
|
|
36
|
+
if (!("offset" in args) && !("limit" in args)) reads.set(block.id, { path, key, order });
|
|
37
|
+
} else mutations.set(key, order);
|
|
21
38
|
}
|
|
22
39
|
}
|
|
23
40
|
const seen = new Set<string>(), records: TranscriptRecord[] = [];
|
|
@@ -25,10 +42,10 @@ export function keptReadCandidates(entries: readonly SessionEntry[], indices: Re
|
|
|
25
42
|
const entry = entries[at]!;
|
|
26
43
|
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
|
|
27
44
|
const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
|
|
28
|
-
if (!read || seen.has(read.
|
|
45
|
+
if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
|
|
29
46
|
const text = textOf(entry.message.content);
|
|
30
47
|
if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
|
|
31
|
-
seen.add(read.
|
|
48
|
+
seen.add(read.key);
|
|
32
49
|
records.push({ kind: "section", title: "Kept-read", sourceIndex,
|
|
33
50
|
text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
|
|
34
51
|
}
|