pi-tuck 1.0.29 → 1.0.32
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 +40 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.js +82 -15
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/semantic-recall.d.ts +13 -4
- package/dist/src/semantic-recall.js +74 -8
- package/package.json +1 -1
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +83 -15
- package/src/semantic-recall.ts +37 -10
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,46 @@
|
|
|
3
3
|
All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
|
|
4
4
|
[Semantic Versioning](https://semver.org/).
|
|
5
5
|
|
|
6
|
+
## [1.0.32] - 2026-11-13
|
|
7
|
+
|
|
8
|
+
### Changed
|
|
9
|
+
|
|
10
|
+
- **Search by meaning is ready sooner in sessions that have not searched yet.** At every cut, pi-tuck now indexes in the background what the
|
|
11
|
+
cut moved out of view, so a first tuck_search finds it without embedding it then. One background indexer runs per machine at a time,
|
|
12
|
+
holding a lock in the index folder, so several Pi sessions do not each load the encoder; a search never waits for that lock. The worker
|
|
13
|
+
is given back once the window is indexed, and the cut itself never waits for indexing.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **Background indexing never started at the cuts pi-tuck makes itself.** Pi announces only its own compactions, so cuts pi-tuck saved
|
|
18
|
+
after a tool round, at the end of a run, or before retrying a reply that hit the output limit started no indexing. Each of these cuts now
|
|
19
|
+
starts it.
|
|
20
|
+
|
|
21
|
+
### Release gates
|
|
22
|
+
|
|
23
|
+
- **Replay matches 1.0.31:** 13,946 requests, 0 different, 0 lost or dead tasks, clips 17 → 17. Indexing changes nothing the model sees.
|
|
24
|
+
- **Live check, 5 tasks:** no breakage; the indexer ran at all 13 cuts, using 1-2 seconds of worker CPU per cut.
|
|
25
|
+
- **Strict stress, 313 cells:** 0 findings on Pi 1.2.0 and the newest Pi, including the 85 MB large-session test. Tests and CI. The
|
|
26
|
+
packed tarball loaded in the real installed Pi 1.5.2.
|
|
27
|
+
|
|
28
|
+
## [1.0.31] - 2026-11-12
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- **Input that arrived after a tool round had been checked could make pi-tuck refuse a request it could still cut.** pi-tuck decides
|
|
33
|
+
whether to cut when a tool round ends. Input added after that point, such as another extension's context or a newly enabled tool, was
|
|
34
|
+
not seen there. When it pushed the next request past the hard line, the final check refused the request and the run stopped. It now cuts
|
|
35
|
+
at that check instead, carries the cut in that request, and saves it at the next boundary. It refuses only when no cut can fit.
|
|
36
|
+
|
|
37
|
+
### Release gates
|
|
38
|
+
|
|
39
|
+
- **Shipped without a live gate under the defect rule, because its replay matches 1.0.29:** 13,946 requests, 0 different, 0 lost or
|
|
40
|
+
dead tasks, clips 17 → 17.
|
|
41
|
+
- **A new test reproduces the refusal on 1.0.29** and passes with the fix. On 1.0.29 it needed late input larger than the gap between the
|
|
42
|
+
early cut and the room.
|
|
43
|
+
- **Strict stress, 313 cells:** 0 findings, on Pi 1.2.0 and the newest Pi. Tests and CI. The packed tarball loaded in the real
|
|
44
|
+
installed Pi 1.5.2.
|
|
45
|
+
|
|
6
46
|
## [1.0.29] - 2026-11-11
|
|
7
47
|
|
|
8
48
|
### Fixed
|
package/dist/src/build-id.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const BUILD_ID = "
|
|
1
|
+
export declare const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
|
package/dist/src/build-id.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
|
package/dist/src/compaction.js
CHANGED
|
@@ -1029,8 +1029,13 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1029
1029
|
};
|
|
1030
1030
|
const atBoundary = (event, ctx, reason, decide) => {
|
|
1031
1031
|
const current = view(ctx);
|
|
1032
|
-
if (!current.pending)
|
|
1033
|
-
|
|
1032
|
+
if (!current.pending) {
|
|
1033
|
+
const result = decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
1034
|
+
// Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
|
|
1035
|
+
if (result?.entries.some(entry => entry.type === "compaction"))
|
|
1036
|
+
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
1037
|
+
return result;
|
|
1038
|
+
}
|
|
1034
1039
|
const entry = run.cut.take();
|
|
1035
1040
|
const preview = current.session, context = Object.create(ctx, { sessionManager: { value: preview } });
|
|
1036
1041
|
const more = decide && !event.entries.length
|
|
@@ -1088,6 +1093,8 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1088
1093
|
stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
|
|
1089
1094
|
estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
1090
1095
|
markBoundary(drafts);
|
|
1096
|
+
// As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
|
|
1097
|
+
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
1091
1098
|
return { entries: drafts, continue: true };
|
|
1092
1099
|
};
|
|
1093
1100
|
pi.on("turn_end", (event, ctx) => {
|
|
@@ -1121,17 +1128,71 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1121
1128
|
}
|
|
1122
1129
|
}
|
|
1123
1130
|
});
|
|
1124
|
-
|
|
1125
|
-
//
|
|
1126
|
-
//
|
|
1127
|
-
const cutRequest = (messages, ctx) => {
|
|
1131
|
+
const projectContext = (messages, ctx, enabled = historyToolsEnabled(ctx)) => applyClips(enabled ? projectedMessages(messages, ctx, options.recallPolicy) : messages, clips());
|
|
1132
|
+
// Replace only the saved conversation, preserving other handlers' surrounding messages. At the final guard the saved side is already
|
|
1133
|
+
// projected. Replay system state as Pi does after a changed `context` result, so interleaved prompt/tool updates survive the cut too.
|
|
1134
|
+
const cutRequest = (messages, ctx, saved = ctx.sessionManager.buildSessionProjection().messages, kept = view(ctx).session.buildSessionProjection().messages) => {
|
|
1128
1135
|
const conversation = (all) => all.filter(message => message.role !== "system");
|
|
1129
|
-
const saved = conversation(
|
|
1130
|
-
for (let at = 0; at +
|
|
1131
|
-
if (
|
|
1132
|
-
|
|
1136
|
+
const source = conversation(saved), request = conversation(messages);
|
|
1137
|
+
for (let at = 0; at + source.length <= request.length; at++)
|
|
1138
|
+
if (source.every((message, i) => isDeepStrictEqual(request[at + i], message))) {
|
|
1139
|
+
const reduced = [...request.slice(0, at), ...conversation(kept), ...request.slice(at + source.length)];
|
|
1140
|
+
const head = getCurrentSystemMessage(messages.filter(message => message.role === "system"));
|
|
1141
|
+
return head ? [head, ...reduced] : reduced;
|
|
1142
|
+
}
|
|
1133
1143
|
throw new Error("The prompt's cut cannot be applied: the request does not carry the saved conversation");
|
|
1134
1144
|
};
|
|
1145
|
+
// A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
|
|
1146
|
+
// atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
|
|
1147
|
+
const guardCut = (messages, tokens, system, ctx) => {
|
|
1148
|
+
const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
|
|
1149
|
+
const before = conversationTokens(source), mandatory = tokens - before;
|
|
1150
|
+
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
|
|
1151
|
+
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1152
|
+
const previousClips = new Map(clips());
|
|
1153
|
+
const measure = measureFor(ctx);
|
|
1154
|
+
const decide = (targetRoom, targetBand) => !fits(mandatory, targetRoom, ctx) ? { kind: "defer" } : chooseCut({
|
|
1155
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
|
|
1156
|
+
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
1157
|
+
plan: (target) => {
|
|
1158
|
+
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
1159
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1160
|
+
protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
1161
|
+
if (!draft.compaction)
|
|
1162
|
+
return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1163
|
+
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1164
|
+
assertNativeToolRounds(kept);
|
|
1165
|
+
return { draft: true, after: measure(kept), mode: draft.mode, compaction: draft.compaction, reserve, messages: kept };
|
|
1166
|
+
},
|
|
1167
|
+
});
|
|
1168
|
+
const project = (candidate) => candidate.kind === "cut"
|
|
1169
|
+
? historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(candidate.plan.messages, ctx, true)), toolShapes(historyToolNames(pi, pi.getActiveTools(), true)), true) : messages;
|
|
1170
|
+
const total = (candidate) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
|
|
1171
|
+
let decision = decide(room, band);
|
|
1172
|
+
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
1173
|
+
decision = decide(hardLine, hardLine);
|
|
1174
|
+
decision = clampAboveRoom(decision, ctx, room, hardLine, total, project, target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true));
|
|
1175
|
+
}
|
|
1176
|
+
const accepts = (candidate) => {
|
|
1177
|
+
if (candidate.kind !== "cut" || candidate.plan.after >= before)
|
|
1178
|
+
return false;
|
|
1179
|
+
const request = project(candidate);
|
|
1180
|
+
const reduced = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), request, ctx.getSystemPrompt()) + conversationTokens(request);
|
|
1181
|
+
return fits(reduced, hardLine, ctx) && (Boolean(options.requestReserve) || corrected(reduced, ctx) <= room || requestClamp(request, ctx).leavesFloor);
|
|
1182
|
+
};
|
|
1183
|
+
if (!accepts(decision))
|
|
1184
|
+
decision = deepestDecision(ctx, false, true);
|
|
1185
|
+
if (decision.kind !== "cut" || !accepts(decision)) {
|
|
1186
|
+
clips().clear();
|
|
1187
|
+
for (const [id, clip] of previousClips)
|
|
1188
|
+
clips().set(id, clip);
|
|
1189
|
+
return messages;
|
|
1190
|
+
}
|
|
1191
|
+
const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary, { response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
|
|
1192
|
+
run.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
|
|
1193
|
+
syncHistoryTools(ctx);
|
|
1194
|
+
return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)), toolShapes(pi.getActiveTools()), true);
|
|
1195
|
+
};
|
|
1135
1196
|
pi.on("context", (event, ctx) => {
|
|
1136
1197
|
try {
|
|
1137
1198
|
if (!active())
|
|
@@ -1141,7 +1202,7 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1141
1202
|
if (!historyToolsEnabled(ctx))
|
|
1142
1203
|
return clips().size ? { messages: applyClips(event.messages, clips()) } : undefined;
|
|
1143
1204
|
access();
|
|
1144
|
-
return { messages:
|
|
1205
|
+
return { messages: projectContext(view(ctx).pending ? cutRequest(event.messages, ctx) : event.messages, ctx) };
|
|
1145
1206
|
}
|
|
1146
1207
|
catch (error) {
|
|
1147
1208
|
try {
|
|
@@ -1218,12 +1279,18 @@ export async function installCompaction(pi, options = {}) {
|
|
|
1218
1279
|
// The complete request, counted after Pi's conversion (summary/custom/bash envelopes), with the effective system once.
|
|
1219
1280
|
// Pi applies a forced prompt after this hook; the public prompt already observes it.
|
|
1220
1281
|
syncHistoryTools(ctx);
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1282
|
+
let messages = historyToolsEnabled(ctx) ? historyToolDeclarations(event.messages, toolShapes(pi.getActiveTools()), true) : event.messages;
|
|
1283
|
+
let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1284
|
+
let tokens = system + conversationTokens(messages);
|
|
1285
|
+
const { room, hardLine } = limits(ctx);
|
|
1286
|
+
if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1287
|
+
messages = guardCut(messages, tokens, system, ctx);
|
|
1288
|
+
system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1289
|
+
tokens = system + conversationTokens(messages);
|
|
1290
|
+
assertNativeToolRounds(messages);
|
|
1291
|
+
}
|
|
1224
1292
|
observeBudget(tokens, ctx);
|
|
1225
1293
|
estimatedTokens = corrected(tokens, ctx);
|
|
1226
|
-
const { room, hardLine } = limits(ctx);
|
|
1227
1294
|
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
|
|
1228
1295
|
throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
|
|
1229
1296
|
if (!fits(tokens, hardLine, ctx))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type RecallPolicy } from './recall.js';
|
|
2
2
|
import type { SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
export declare const DIAGNOSTIC_BUILD = "
|
|
3
|
+
export declare const DIAGNOSTIC_BUILD = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
|
|
4
4
|
export interface Receipt {
|
|
5
5
|
id: string;
|
|
6
6
|
build: string;
|
|
@@ -110,6 +110,11 @@ export declare const HEAL_DELAYS_MS: readonly number[];
|
|
|
110
110
|
export declare const HEAL_STEADY_MS = 600000;
|
|
111
111
|
/** A session that has not searched for this long gives its worker back (the index stays on disk). Enabling starts nothing; a search starts the worker again. */
|
|
112
112
|
export declare const IDLE_STOP_MS = 600000;
|
|
113
|
+
/** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
|
|
114
|
+
* several Pi sessions on one machine embed one at a time: one encoder's memory at a time instead of one per session. A search never waits for it. */
|
|
115
|
+
export declare const INDEXER_LOCK = "background-indexer.lock";
|
|
116
|
+
/** How long background indexing waits before trying the lock again when another process holds it. */
|
|
117
|
+
export declare const INDEXER_RETRY_MS = 15000;
|
|
113
118
|
/** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
|
|
114
119
|
export declare const CALL_DEADLINE_MS = 60000;
|
|
115
120
|
/** Why semantic recall is off where the embedding server cannot start on Metal (a VM, a Mac without a GPU): it runs on Metal only. */
|
|
@@ -186,7 +191,9 @@ export declare class SemanticRecallController {
|
|
|
186
191
|
private healRetryAt;
|
|
187
192
|
private recycle;
|
|
188
193
|
private active;
|
|
189
|
-
private fullIndexing;
|
|
194
|
+
private fullIndexing; /** Work a cut started with no search or wait behind it: it takes the machine's indexer lock, and its worker stops once the window is indexed. */
|
|
195
|
+
private backgroundOnly; /** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */
|
|
196
|
+
private releaseLock?;
|
|
190
197
|
private idleTimer?;
|
|
191
198
|
private idling?;
|
|
192
199
|
private quietStop;
|
|
@@ -310,14 +317,15 @@ export declare class SemanticRecallController {
|
|
|
310
317
|
};
|
|
311
318
|
};
|
|
312
319
|
schedule(provider: () => Snapshot): void;
|
|
313
|
-
/** A saved cut has moved entries out of view: start indexing
|
|
314
|
-
*
|
|
315
|
-
*
|
|
320
|
+
/** A saved cut has moved entries out of view: start indexing the whole window now, whether or not this session has searched. Awaits nothing; a failure goes to `heal` like any preparation.
|
|
321
|
+
* Every session indexes at its cuts, but only one background indexer runs per machine (the lock in the index folder), so several sessions never run several encoders at once on a 16 GB machine;
|
|
322
|
+
* its worker is given back once the window is indexed. A heal backoff in progress is not bypassed. Callers: Pi's own compactions (session_compact) and every cut pi-tuck saves at a boundary. */
|
|
316
323
|
indexAtCut(provider: () => Snapshot): void;
|
|
317
324
|
private runtime;
|
|
318
325
|
private path;
|
|
319
326
|
private index;
|
|
320
327
|
private prepare;
|
|
328
|
+
private prepareLocked;
|
|
321
329
|
waitForReady(timeoutMs?: number, signal?: AbortSignal, expectedSnapshotId?: string, forSearch?: boolean): Promise<{
|
|
322
330
|
setup: SemanticSetup;
|
|
323
331
|
setupMessage: string | null;
|
|
@@ -383,6 +391,7 @@ export declare class SemanticRecallController {
|
|
|
383
391
|
private demand;
|
|
384
392
|
private cancelIdle;
|
|
385
393
|
private armIdle;
|
|
394
|
+
private freeLock;
|
|
386
395
|
private idleStop;
|
|
387
396
|
/** A search or wait the caller cancelled (Esc) or that a stop overtook ends, and the worker with it, but recall stays enabled: the next search starts a worker again. Only access loss disables (see `searchOwned`). */
|
|
388
397
|
private cancelled;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { readFile, rm, mkdtemp, mkdir } from 'node:fs/promises';
|
|
3
|
+
import { readFile, rm, mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
|
4
4
|
import { lstatSync, realpathSync } from 'node:fs';
|
|
5
5
|
import { resolve, relative, join, dirname, basename, isAbsolute, sep } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
@@ -168,6 +168,40 @@ export const HEAL_DELAYS_MS = [5000, 30000, 120000];
|
|
|
168
168
|
export const HEAL_STEADY_MS = 600000;
|
|
169
169
|
/** A session that has not searched for this long gives its worker back (the index stays on disk). Enabling starts nothing; a search starts the worker again. */
|
|
170
170
|
export const IDLE_STOP_MS = 600000;
|
|
171
|
+
/** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
|
|
172
|
+
* several Pi sessions on one machine embed one at a time: one encoder's memory at a time instead of one per session. A search never waits for it. */
|
|
173
|
+
export const INDEXER_LOCK = 'background-indexer.lock';
|
|
174
|
+
/** How long background indexing waits before trying the lock again when another process holds it. */
|
|
175
|
+
export const INDEXER_RETRY_MS = 15000;
|
|
176
|
+
const alive = (pid) => { try {
|
|
177
|
+
process.kill(pid, 0);
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
return error.code === 'EPERM';
|
|
182
|
+
} };
|
|
183
|
+
/** Take the machine's background-indexer lock, or null when another live holder has it. A holder that has died leaves a stale lock, which is taken over. */
|
|
184
|
+
async function tryIndexerLock(directory) {
|
|
185
|
+
const path = join(directory, INDEXER_LOCK), take = async () => { try {
|
|
186
|
+
await mkdir(path);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (error.code === 'EEXIST')
|
|
191
|
+
return false;
|
|
192
|
+
throw error;
|
|
193
|
+
} };
|
|
194
|
+
if (!await take()) {
|
|
195
|
+
const holder = Number(await readFile(join(path, 'pid'), 'utf8').catch(() => ''));
|
|
196
|
+
if (holder && alive(holder))
|
|
197
|
+
return null;
|
|
198
|
+
await rm(path, { recursive: true, force: true });
|
|
199
|
+
if (!await take())
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
await writeFile(join(path, 'pid'), String(process.pid));
|
|
203
|
+
return () => rm(path, { recursive: true, force: true });
|
|
204
|
+
}
|
|
171
205
|
/** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
|
|
172
206
|
export const CALL_DEADLINE_MS = 60000;
|
|
173
207
|
/** Why semantic recall is off where the embedding server cannot start on Metal (a VM, a Mac without a GPU): it runs on Metal only. */
|
|
@@ -584,7 +618,9 @@ export class SemanticRecallController {
|
|
|
584
618
|
recycle = false;
|
|
585
619
|
// Lazy start: background work runs only for a session that searched within the idle limit, or that searched at some point and has just been cut (`indexAtCut`).
|
|
586
620
|
active = false;
|
|
587
|
-
fullIndexing = false;
|
|
621
|
+
fullIndexing = false; /** Work a cut started with no search or wait behind it: it takes the machine's indexer lock, and its worker stops once the window is indexed. */
|
|
622
|
+
backgroundOnly = false; /** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */
|
|
623
|
+
releaseLock;
|
|
588
624
|
idleTimer;
|
|
589
625
|
idling;
|
|
590
626
|
quietStop = false;
|
|
@@ -663,11 +699,13 @@ export class SemanticRecallController {
|
|
|
663
699
|
this.error = null;
|
|
664
700
|
this.schedule(this.provider);
|
|
665
701
|
} }); }, 5); }
|
|
666
|
-
/** A saved cut has moved entries out of view: start indexing
|
|
667
|
-
*
|
|
668
|
-
*
|
|
669
|
-
indexAtCut(provider) { if (this.enabled && !this.healTimer &&
|
|
702
|
+
/** A saved cut has moved entries out of view: start indexing the whole window now, whether or not this session has searched. Awaits nothing; a failure goes to `heal` like any preparation.
|
|
703
|
+
* Every session indexes at its cuts, but only one background indexer runs per machine (the lock in the index folder), so several sessions never run several encoders at once on a 16 GB machine;
|
|
704
|
+
* its worker is given back once the window is indexed. A heal backoff in progress is not bypassed. Callers: Pi's own compactions (session_compact) and every cut pi-tuck saves at a boundary. */
|
|
705
|
+
indexAtCut(provider) { if (this.enabled && !this.healTimer && !this.active) {
|
|
670
706
|
this.active = true;
|
|
707
|
+
this.fullIndexing = true;
|
|
708
|
+
this.backgroundOnly = true;
|
|
671
709
|
this.armIdle();
|
|
672
710
|
} this.schedule(provider); }
|
|
673
711
|
async runtime(project) {
|
|
@@ -725,6 +763,30 @@ export class SemanticRecallController {
|
|
|
725
763
|
const prior = this.current;
|
|
726
764
|
if (prior?.complete && prior.id === snapshot.id)
|
|
727
765
|
return;
|
|
766
|
+
let release = null;
|
|
767
|
+
if (this.backgroundOnly) {
|
|
768
|
+
await mkdir(this.config.indexDirectory, { recursive: true });
|
|
769
|
+
release = await tryIndexerLock(this.config.indexDirectory);
|
|
770
|
+
if (!release) {
|
|
771
|
+
const retry = setTimeout(() => { if (this.enabled && generation === this.generation)
|
|
772
|
+
this.schedule(provider); }, INDEXER_RETRY_MS);
|
|
773
|
+
retry.unref();
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
try {
|
|
778
|
+
await this.prepareLocked(provider, full, generation, started, snapshot, prior);
|
|
779
|
+
}
|
|
780
|
+
finally {
|
|
781
|
+
if (release) {
|
|
782
|
+
if (this.backgroundOnly && this.current?.complete)
|
|
783
|
+
this.releaseLock = release;
|
|
784
|
+
else
|
|
785
|
+
await release();
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
async prepareLocked(provider, full, generation, started, snapshot, prior) {
|
|
728
790
|
// Both caps bound the window instead of failing above them. The unit cap (MAX_INDEX_UNITS) stays below the worker's 8,008-row store; the character cap, 2,000,000, usually binds first, at about 2.2 thousand units.
|
|
729
791
|
const maxChars = this.config.maxSourceCharacters ?? 2000000, maxUnits = this.config.maxUnits ?? MAX_INDEX_UNITS;
|
|
730
792
|
const check = () => { if (generation !== this.generation || !this.enabled)
|
|
@@ -840,6 +902,8 @@ export class SemanticRecallController {
|
|
|
840
902
|
snapshot.complete = true;
|
|
841
903
|
if (full)
|
|
842
904
|
this.fullIndexing = false;
|
|
905
|
+
if (this.backgroundOnly)
|
|
906
|
+
setTimeout(() => { void (this.backgroundOnly ? this.idleStop() : Promise.resolve()).finally(() => this.freeLock()); }, 0).unref();
|
|
843
907
|
}
|
|
844
908
|
this.error = null;
|
|
845
909
|
this.recovered();
|
|
@@ -1093,11 +1157,12 @@ export class SemanticRecallController {
|
|
|
1093
1157
|
throw error;
|
|
1094
1158
|
} }
|
|
1095
1159
|
/** A search, or a wait for readiness, is demand: it lets background work start and keeps it alive for IDLE_STOP_MS after the last one. */
|
|
1096
|
-
demand() { this.active = true; this.fullIndexing = true; this.cancelIdle(); }
|
|
1160
|
+
demand() { this.active = true; this.fullIndexing = true; this.backgroundOnly = false; this.cancelIdle(); }
|
|
1097
1161
|
cancelIdle() { if (this.idleTimer)
|
|
1098
1162
|
clearTimeout(this.idleTimer); this.idleTimer = undefined; }
|
|
1099
1163
|
armIdle() { this.cancelIdle(); if (!this.enabled || !this.active)
|
|
1100
1164
|
return; this.idleTimer = setTimeout(() => { this.idleTimer = undefined; void this.idleStop(); }, this.timing.idleStopMs ?? IDLE_STOP_MS); this.idleTimer.unref(); }
|
|
1165
|
+
async freeLock() { const release = this.releaseLock; this.releaseLock = undefined; await release?.().catch(() => { }); }
|
|
1101
1166
|
idleStop() {
|
|
1102
1167
|
if (this.idling || !this.enabled || !this.active || this.joiningSearches || this.activeSearches.size)
|
|
1103
1168
|
return Promise.resolve();
|
|
@@ -1117,6 +1182,7 @@ export class SemanticRecallController {
|
|
|
1117
1182
|
const stop = (async () => {
|
|
1118
1183
|
this.active = false;
|
|
1119
1184
|
this.fullIndexing = false;
|
|
1185
|
+
this.backgroundOnly = false;
|
|
1120
1186
|
this.quietStop = true;
|
|
1121
1187
|
this.generation++;
|
|
1122
1188
|
this.dirty = false;
|
|
@@ -1188,7 +1254,7 @@ export class SemanticRecallController {
|
|
|
1188
1254
|
// A source that can no longer be read stops recall; the reason stays readable until the next enable, so this never looks like recall that was never on.
|
|
1189
1255
|
async revoked(error) { await this.disable(false); this.error = error instanceof Error ? error.message : 'Source access denied'; }
|
|
1190
1256
|
async invalidate() { await this.disable(); this.error = 'Caller invalidated semantic source access; explicit enable required'; }
|
|
1191
|
-
async close() { await this.disable(true, false); this.provider = undefined; this.searched = false; } // a closed controller serves a new session, which has not searched; a disable and enable keeps it
|
|
1257
|
+
async close() { await this.disable(true, false); await this.freeLock(); this.provider = undefined; this.searched = false; } // a closed controller serves a new session, which has not searched; a disable and enable keeps it
|
|
1192
1258
|
}
|
|
1193
1259
|
export const createSemanticRecall = (config) => new SemanticRecallController(config);
|
|
1194
1260
|
/** Consolidate only source-bound coordinate overlap; equal text in distinct events is retained.
|
package/package.json
CHANGED
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
|
package/src/compaction.ts
CHANGED
|
@@ -907,7 +907,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
907
907
|
};
|
|
908
908
|
const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
|
|
909
909
|
const current = view(ctx);
|
|
910
|
-
if (!current.pending)
|
|
910
|
+
if (!current.pending) {
|
|
911
|
+
const result = decide ? boundaryCut(event, ctx, reason) : undefined;
|
|
912
|
+
// Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
|
|
913
|
+
if (result?.entries.some(entry => entry.type === "compaction")) setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
914
|
+
return result;
|
|
915
|
+
}
|
|
911
916
|
const entry = run!.cut.take()!;
|
|
912
917
|
const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
|
|
913
918
|
const more = decide && !event.entries.length
|
|
@@ -960,6 +965,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
960
965
|
stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
|
|
961
966
|
estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
|
|
962
967
|
markBoundary(drafts);
|
|
968
|
+
// As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
|
|
969
|
+
setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
|
|
963
970
|
return { entries: drafts, continue: true };
|
|
964
971
|
};
|
|
965
972
|
pi.on("turn_end", (event, ctx) => {
|
|
@@ -986,17 +993,72 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
986
993
|
}
|
|
987
994
|
}
|
|
988
995
|
});
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
//
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
996
|
+
const projectContext = (messages: Messages, ctx: ExtensionContext, enabled = historyToolsEnabled(ctx)) =>
|
|
997
|
+
applyClips(enabled ? projectedMessages(messages, ctx, options.recallPolicy) : messages, clips());
|
|
998
|
+
// Replace only the saved conversation, preserving other handlers' surrounding messages. At the final guard the saved side is already
|
|
999
|
+
// projected. Replay system state as Pi does after a changed `context` result, so interleaved prompt/tool updates survive the cut too.
|
|
1000
|
+
const cutRequest = (messages: Messages, ctx: ExtensionContext, saved = ctx.sessionManager.buildSessionProjection().messages,
|
|
1001
|
+
kept = view(ctx).session.buildSessionProjection().messages): Messages => {
|
|
1002
|
+
const conversation = (all: Messages) => all.filter(message => message.role !== "system");
|
|
1003
|
+
const source = conversation(saved), request = conversation(messages);
|
|
1004
|
+
for (let at = 0; at + source.length <= request.length; at++)
|
|
1005
|
+
if (source.every((message, i) => isDeepStrictEqual(request[at + i], message))) {
|
|
1006
|
+
const reduced = [...request.slice(0, at), ...conversation(kept), ...request.slice(at + source.length)];
|
|
1007
|
+
const head = getCurrentSystemMessage(messages.filter(message => message.role === "system"));
|
|
1008
|
+
return head ? [head, ...reduced] : reduced;
|
|
1009
|
+
}
|
|
998
1010
|
throw new Error("The prompt's cut cannot be applied: the request does not carry the saved conversation");
|
|
999
1011
|
};
|
|
1012
|
+
// A late cut prices everything outside the saved conversation from this request itself. Its pending view is carried now and saved by
|
|
1013
|
+
// atBoundary, just like a prompt cut; the existing final checks still decide admission on the rebuilt request.
|
|
1014
|
+
const guardCut = (messages: Messages, tokens: number, system: number, ctx: ExtensionContext): Messages => {
|
|
1015
|
+
const saved = ctx.sessionManager.buildSessionProjection().messages, source = projectContext(saved, ctx);
|
|
1016
|
+
const before = conversationTokens(source), mandatory = tokens - before;
|
|
1017
|
+
const { response, room, hardLine } = limits(ctx), band = decisionBand(ctx, room, system);
|
|
1018
|
+
const previousSummary = saved.find(message => message.role === "compactionSummary")?.summary;
|
|
1019
|
+
const previousClips = new Map(clips());
|
|
1020
|
+
const measure = measureFor(ctx);
|
|
1021
|
+
const decide = (targetRoom: number, targetBand: number): Decision<CutPlan> => !fits(mandatory, targetRoom, ctx) ? { kind: "defer" } : chooseCut({
|
|
1022
|
+
before, mandatory, room: targetRoom, band: targetBand, fits: (tokens, limit) => fits(tokens, limit, ctx), opportunistic: false,
|
|
1023
|
+
unreduced: "Tool-loop preflight compaction did not reduce context within the estimated request budget",
|
|
1024
|
+
plan: (target): Plan<CutPlan> => {
|
|
1025
|
+
const reserve = planReserve(target, targetRoom, targetBand, mandatory, ctx);
|
|
1026
|
+
const draft = tuckObservedDraft(tuck, { branchEntries: ctx.sessionManager.getBranch(), tokensBefore: before, previousSummary,
|
|
1027
|
+
protectedPromptEntryId: protectedPrompt(ctx) }, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, true);
|
|
1028
|
+
if (!draft.compaction) return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
|
|
1029
|
+
const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
|
|
1030
|
+
assertNativeToolRounds(kept);
|
|
1031
|
+
return { draft: true, after: measure(kept), mode: draft.mode, compaction: draft.compaction, reserve, messages: kept };
|
|
1032
|
+
},
|
|
1033
|
+
});
|
|
1034
|
+
const project = (candidate: Decision<CutPlan>) => candidate.kind === "cut"
|
|
1035
|
+
? historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(candidate.plan.messages, ctx, true)),
|
|
1036
|
+
toolShapes(historyToolNames(pi, pi.getActiveTools(), true)), true) : messages;
|
|
1037
|
+
const total = (candidate: Decision<CutPlan>) => (candidate.kind === "cut" ? candidate.plan.after : before) + mandatory;
|
|
1038
|
+
let decision = decide(room, band);
|
|
1039
|
+
if (hardLine > room && (decision.kind === "defer" || decision.kind === "fault")) {
|
|
1040
|
+
decision = decide(hardLine, hardLine);
|
|
1041
|
+
decision = clampAboveRoom(decision, ctx, room, hardLine, total, project,
|
|
1042
|
+
target => decide(target, target <= room ? band : target), () => deepestDecision(ctx, false, true));
|
|
1043
|
+
}
|
|
1044
|
+
const accepts = (candidate: Decision<CutPlan>) => {
|
|
1045
|
+
if (candidate.kind !== "cut" || candidate.plan.after >= before) return false;
|
|
1046
|
+
const request = project(candidate);
|
|
1047
|
+
const reduced = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), request, ctx.getSystemPrompt()) + conversationTokens(request);
|
|
1048
|
+
return fits(reduced, hardLine, ctx) && (Boolean(options.requestReserve) || corrected(reduced, ctx) <= room || requestClamp(request, ctx).leavesFloor);
|
|
1049
|
+
};
|
|
1050
|
+
if (!accepts(decision)) decision = deepestDecision(ctx, false, true);
|
|
1051
|
+
if (decision.kind !== "cut" || !accepts(decision)) {
|
|
1052
|
+
clips().clear(); for (const [id, clip] of previousClips) clips().set(id, clip);
|
|
1053
|
+
return messages;
|
|
1054
|
+
}
|
|
1055
|
+
const compaction = captureDraft({ ...decision.plan.compaction, tokensBefore: before }, ctx, decision.plan.reserve, "tool-loop", before, true, false, previousSummary,
|
|
1056
|
+
{ response, host: conversationTokens(hostMessages(ctx)), mandatory, target: decision.target, margin: room - band });
|
|
1057
|
+
run!.cut.plan({ type: "compaction", ...compaction, tokensBefore: before }, ctx.sessionManager.getBranch().length);
|
|
1058
|
+
syncHistoryTools(ctx);
|
|
1059
|
+
return historyToolDeclarations(cutRequest(messages, ctx, source, projectContext(view(ctx).session.buildSessionProjection().messages, ctx)),
|
|
1060
|
+
toolShapes(pi.getActiveTools()), true);
|
|
1061
|
+
};
|
|
1000
1062
|
pi.on("context", (event, ctx) => {
|
|
1001
1063
|
try {
|
|
1002
1064
|
if (!active()) return;
|
|
@@ -1004,7 +1066,7 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1004
1066
|
// Before a cut, Pi owns the whole request, including its object identities and system-message serialization.
|
|
1005
1067
|
if (!historyToolsEnabled(ctx)) return clips().size ? { messages: applyClips(event.messages, clips()) } : undefined;
|
|
1006
1068
|
access();
|
|
1007
|
-
return { messages:
|
|
1069
|
+
return { messages: projectContext(view(ctx).pending ? cutRequest(event.messages, ctx) : event.messages, ctx) };
|
|
1008
1070
|
} catch (error) { try { fail(error, ctx); } finally { return historyToolsEnabled(ctx) ? { messages: [] } : undefined; } }
|
|
1009
1071
|
});
|
|
1010
1072
|
pi.on("session_compact_failed", (event, ctx) => {
|
|
@@ -1050,12 +1112,18 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
|
|
|
1050
1112
|
// The complete request, counted after Pi's conversion (summary/custom/bash envelopes), with the effective system once.
|
|
1051
1113
|
// Pi applies a forced prompt after this hook; the public prompt already observes it.
|
|
1052
1114
|
syncHistoryTools(ctx);
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1115
|
+
let messages = historyToolsEnabled(ctx) ? historyToolDeclarations(event.messages, toolShapes(pi.getActiveTools()), true) : event.messages;
|
|
1116
|
+
let system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1117
|
+
let tokens = system + conversationTokens(messages);
|
|
1118
|
+
const { room, hardLine } = limits(ctx);
|
|
1119
|
+
if (!fits(tokens, hardLine, ctx) && run?.phase === "admitted" && !view(ctx).pending && settingsFor().getCompactionSettings(ctx.model).enabled) {
|
|
1120
|
+
messages = guardCut(messages, tokens, system, ctx);
|
|
1121
|
+
system = requestSystemPart(ctx.getSystemPrompt(), pi.getActiveTools(), messages, ctx.getSystemPrompt());
|
|
1122
|
+
tokens = system + conversationTokens(messages);
|
|
1123
|
+
assertNativeToolRounds(messages);
|
|
1124
|
+
}
|
|
1056
1125
|
observeBudget(tokens, ctx);
|
|
1057
1126
|
estimatedTokens = corrected(tokens, ctx);
|
|
1058
|
-
const { room, hardLine } = limits(ctx);
|
|
1059
1127
|
if (run?.prompt && !carriesPrompt(messages, run.prompt.text(ctx.sessionManager.getBranch()), run.prompt.role))
|
|
1060
1128
|
throw new Refusal("Prompt check failed: the request is missing the whole text of the prompt that started this run. Shorten the prompt or choose a model with a larger context window, then retry");
|
|
1061
1129
|
if (!fits(tokens, hardLine, ctx))
|
package/src/semantic-recall.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {spawn,type ChildProcessWithoutNullStreams} from 'node:child_process';
|
|
2
2
|
import {createHash,randomUUID} from 'node:crypto';
|
|
3
|
-
import {readFile,rm,mkdtemp,mkdir} from 'node:fs/promises';
|
|
3
|
+
import {readFile,rm,mkdtemp,mkdir,writeFile} from 'node:fs/promises';
|
|
4
4
|
import {lstatSync,realpathSync} from 'node:fs';
|
|
5
5
|
import {resolve,relative,join,dirname,basename,isAbsolute,sep} from 'node:path';
|
|
6
6
|
import {fileURLToPath} from 'node:url';
|
|
@@ -101,6 +101,23 @@ export const HEAL_DELAYS_MS:readonly number[]=[5000,30000,120000];
|
|
|
101
101
|
export const HEAL_STEADY_MS=600000;
|
|
102
102
|
/** A session that has not searched for this long gives its worker back (the index stays on disk). Enabling starts nothing; a search starts the worker again. */
|
|
103
103
|
export const IDLE_STOP_MS=600000;
|
|
104
|
+
/** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
|
|
105
|
+
* several Pi sessions on one machine embed one at a time: one encoder's memory at a time instead of one per session. A search never waits for it. */
|
|
106
|
+
export const INDEXER_LOCK='background-indexer.lock';
|
|
107
|
+
/** How long background indexing waits before trying the lock again when another process holds it. */
|
|
108
|
+
export const INDEXER_RETRY_MS=15000;
|
|
109
|
+
const alive=(pid:number)=>{try{process.kill(pid,0);return true;}catch(error){return (error as NodeJS.ErrnoException).code==='EPERM';}};
|
|
110
|
+
/** Take the machine's background-indexer lock, or null when another live holder has it. A holder that has died leaves a stale lock, which is taken over. */
|
|
111
|
+
async function tryIndexerLock(directory:string):Promise<(()=>Promise<void>)|null>{
|
|
112
|
+
const path=join(directory,INDEXER_LOCK),take=async()=>{try{await mkdir(path);return true;}catch(error){if((error as NodeJS.ErrnoException).code==='EEXIST')return false;throw error;}};
|
|
113
|
+
if(!await take()){
|
|
114
|
+
const holder=Number(await readFile(join(path,'pid'),'utf8').catch(()=>''));
|
|
115
|
+
if(holder&&alive(holder))return null;
|
|
116
|
+
await rm(path,{recursive:true,force:true});if(!await take())return null;
|
|
117
|
+
}
|
|
118
|
+
await writeFile(join(path,'pid'),String(process.pid));
|
|
119
|
+
return ()=>rm(path,{recursive:true,force:true});
|
|
120
|
+
}
|
|
104
121
|
/** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
|
|
105
122
|
export const CALL_DEADLINE_MS=60000;
|
|
106
123
|
/** Why semantic recall is off where the embedding server cannot start on Metal (a VM, a Mac without a GPU): it runs on Metal only. */
|
|
@@ -277,7 +294,7 @@ export class SemanticRecallController {
|
|
|
277
294
|
private tokenized=new Map<string,Unit[]>();
|
|
278
295
|
private healReason:string|null=null;private healIntegrity=false;private healAttempts=0;private healTimer?:ReturnType<typeof setTimeout>;private healRetryAt:number|null=null;private recycle=false;
|
|
279
296
|
// Lazy start: background work runs only for a session that searched within the idle limit, or that searched at some point and has just been cut (`indexAtCut`).
|
|
280
|
-
private active=false;private fullIndexing=false
|
|
297
|
+
private active=false;private fullIndexing=false;/** Work a cut started with no search or wait behind it: it takes the machine's indexer lock, and its worker stops once the window is indexed. */private backgroundOnly=false;/** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */private releaseLock?:()=>Promise<void>;private idleTimer?:ReturnType<typeof setTimeout>;private idling?:Promise<void>;private quietStop=false;
|
|
281
298
|
// Whether this session ran a search since the controller was created or last closed; it survives idle stops, so a cut after a long quiet spell still indexes.
|
|
282
299
|
private searched=false;
|
|
283
300
|
private readonly listeners=new Set<(state:SemanticState,reason:string|null)=>void>();private announced='disabled\0';private announcing=false;
|
|
@@ -300,10 +317,10 @@ export class SemanticRecallController {
|
|
|
300
317
|
/** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
|
|
301
318
|
requestCoverage(){const {setup,setupMessage,...coverage}=this.status();return coverage;}
|
|
302
319
|
schedule(provider:()=>Snapshot){this.provider=provider;if(!this.enabled||this.timer||!this.active||this.healTimer)return;this.timer=setTimeout(()=>{this.timer=undefined;if(this.task){this.dirty=true;return;}this.task=this.prepare(provider,this.fullIndexing).catch(async error=>{if(this.quietStop||!this.enabled)return;this.error=error instanceof Error?error.message:'local failure';if(error instanceof Error&&error.name==='SemanticAccessError'){this.enabled=false;this.generation++;this.dirty=false;try{await this.closeResources();}catch(cleanup){this.cleanupError=cleanup instanceof Error?cleanup.message:'Semantic cleanup failed';this.error=this.cleanupError;}}else this.heal(error);}).finally(()=>{this.task=undefined;if(this.enabled&&this.dirty){this.dirty=false;this.error=null;this.schedule(this.provider!);}});},5);}
|
|
303
|
-
/** A saved cut has moved entries out of view: start indexing
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
indexAtCut(provider:()=>Snapshot){if(this.enabled&&!this.healTimer
|
|
320
|
+
/** A saved cut has moved entries out of view: start indexing the whole window now, whether or not this session has searched. Awaits nothing; a failure goes to `heal` like any preparation.
|
|
321
|
+
* Every session indexes at its cuts, but only one background indexer runs per machine (the lock in the index folder), so several sessions never run several encoders at once on a 16 GB machine;
|
|
322
|
+
* its worker is given back once the window is indexed. A heal backoff in progress is not bypassed. Callers: Pi's own compactions (session_compact) and every cut pi-tuck saves at a boundary. */
|
|
323
|
+
indexAtCut(provider:()=>Snapshot){if(this.enabled&&!this.healTimer&&!this.active){this.active=true;this.fullIndexing=true;this.backgroundOnly=true;this.armIdle();}this.schedule(provider);}
|
|
307
324
|
private async runtime(project:string){if(this.idling)await this.idling;if(!this.enabled)throw abort();outsideProject(project,this.config!.runtimeRoot,'runtime');outsideProject(project,scratchParent(this.config!),'scratch');outsideRuntime(this.config!.runtimeRoot,scratchParent(this.config!),'scratch');if(this.worker&&this.recycle){const old=this.worker;await old.close();if(this.worker===old){this.worker=undefined;this.identity='';this.recycle=false;}if(!this.enabled)throw abort();}
|
|
308
325
|
if(!this.worker){const worker=new LocalWorker(this.config!,project,error=>{if(this.worker!==worker)return;this.cleanupError=error instanceof Error?error.message:'Semantic cleanup failed';this.error=this.cleanupError;this.enabled=false;this.generation++;},reason=>{if(this.worker===worker)this.heal(new WorkerFailure(reason));},{startMs:this.timing.startDeadlineMs??START_DEADLINE_MS,callMs:this.timing.callDeadlineMs??CALL_DEADLINE_MS,embedTextMs:this.timing.embedTextMs??EMBED_TEXT_MS});this.worker=worker;}if(!this.identity){const ready=await this.worker.call('ready');if(ready.dimensions!==768||ready.maxTokens!==8192||!ready.offline)throw new Error('Incompatible semantic model; EG2 768/8192 offline required');this.identity=hash({worker:ready.identity,chunk:'eg2-passage256-focused-disjoint-direct-v3'});}return this.worker;}
|
|
309
326
|
private path(snapshot:Snapshot){const directory=this.config!.indexDirectory;outsideProject(snapshot.project,directory,'index');return join(directory,hash({owner:this.ownerId,session:snapshot.session,project:resolve(snapshot.project)})+'.sqlite');}
|
|
@@ -312,6 +329,15 @@ export class SemanticRecallController {
|
|
|
312
329
|
if(!this.enabled)return;
|
|
313
330
|
const generation=this.generation,started=performance.now();let snapshot=provider();const prior=this.current;
|
|
314
331
|
if(prior?.complete&&prior.id===snapshot.id)return;
|
|
332
|
+
let release:(()=>Promise<void>)|null=null;
|
|
333
|
+
if(this.backgroundOnly){
|
|
334
|
+
await mkdir(this.config!.indexDirectory,{recursive:true});release=await tryIndexerLock(this.config!.indexDirectory);
|
|
335
|
+
if(!release){const retry=setTimeout(()=>{if(this.enabled&&generation===this.generation)this.schedule(provider);},INDEXER_RETRY_MS);retry.unref();return;}
|
|
336
|
+
}
|
|
337
|
+
try{await this.prepareLocked(provider,full,generation,started,snapshot,prior);}
|
|
338
|
+
finally{if(release){if(this.backgroundOnly&&this.current?.complete)this.releaseLock=release;else await release();}}
|
|
339
|
+
}
|
|
340
|
+
private async prepareLocked(provider:()=>Snapshot,full:boolean,generation:number,started:number,snapshot:Snapshot,prior:Snapshot|undefined){
|
|
315
341
|
// Both caps bound the window instead of failing above them. The unit cap (MAX_INDEX_UNITS) stays below the worker's 8,008-row store; the character cap, 2,000,000, usually binds first, at about 2.2 thousand units.
|
|
316
342
|
const maxChars=this.config!.maxSourceCharacters??2000000,maxUnits=this.config!.maxUnits??MAX_INDEX_UNITS;
|
|
317
343
|
const check=()=>{if(generation!==this.generation||!this.enabled)throw abort();this.recheck(provider,snapshot);};
|
|
@@ -366,7 +392,7 @@ export class SemanticRecallController {
|
|
|
366
392
|
await yieldWork();if(progressed&&performance.now()-started>(this.config!.prepareWorkMs??30000)){this.error='Preparation work slice exhausted; indexing incomplete';this.dirty=true;return;}
|
|
367
393
|
}
|
|
368
394
|
check();
|
|
369
|
-
if(snapshot.units.every(unit=>snapshot.indexed.has(unit.key))){snapshot.complete=true;if(full)this.fullIndexing=false;}
|
|
395
|
+
if(snapshot.units.every(unit=>snapshot.indexed.has(unit.key))){snapshot.complete=true;if(full)this.fullIndexing=false;if(this.backgroundOnly)setTimeout(()=>{void (this.backgroundOnly?this.idleStop():Promise.resolve()).finally(()=>this.freeLock());},0).unref();}
|
|
370
396
|
this.error=null;this.recovered();
|
|
371
397
|
}
|
|
372
398
|
async waitForReady(timeoutMs=this.config?.queryWaitMs??30000,signal?:AbortSignal,expectedSnapshotId?:string,forSearch=false){if(this.enabled)this.demand();let targetId=expectedSnapshotId;try{targetId??=this.provider?.().id;}catch(error){await this.revoked(error);throw error;}if(this.enabled&&this.provider&&this.current?.id!==targetId){this.error=null;this.schedule(this.provider);}const started=performance.now();while(this.enabled&&!this.readyFor(targetId,forSearch)&&!this.error&&!this.healTimer&&performance.now()-started<timeoutMs){if(signal?.aborted){await this.cancelled();throw abort();}if(this.provider&&!this.timer&&!this.task)this.schedule(this.provider);await new Promise(done=>setTimeout(done,10));}this.armIdle();return this.status();}
|
|
@@ -442,9 +468,10 @@ export class SemanticRecallController {
|
|
|
442
468
|
private async stopOwner(){this.dirty=false;this.enabled=false;this.generation++;if(this.timer){clearTimeout(this.timer);this.timer=undefined;}try{await this.closeResources();await this.task;this.task=undefined;}catch(error){this.cleanupError=error instanceof Error?error.message:'Semantic cleanup failed';throw error;}}
|
|
443
469
|
|
|
444
470
|
/** A search, or a wait for readiness, is demand: it lets background work start and keeps it alive for IDLE_STOP_MS after the last one. */
|
|
445
|
-
private demand(){this.active=true;this.fullIndexing=true;this.cancelIdle();}
|
|
471
|
+
private demand(){this.active=true;this.fullIndexing=true;this.backgroundOnly=false;this.cancelIdle();}
|
|
446
472
|
private cancelIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=undefined;}
|
|
447
473
|
private armIdle(){this.cancelIdle();if(!this.enabled||!this.active)return;this.idleTimer=setTimeout(()=>{this.idleTimer=undefined;void this.idleStop();},this.timing.idleStopMs??IDLE_STOP_MS);this.idleTimer.unref();}
|
|
474
|
+
private async freeLock(){const release=this.releaseLock;this.releaseLock=undefined;await release?.().catch(()=>{});}
|
|
448
475
|
private idleStop(){
|
|
449
476
|
if(this.idling||!this.enabled||!this.active||this.joiningSearches||this.activeSearches.size)return Promise.resolve();
|
|
450
477
|
return this.stopWorker();
|
|
@@ -457,7 +484,7 @@ export class SemanticRecallController {
|
|
|
457
484
|
if(this.idling)return this.idling;
|
|
458
485
|
const running=this.task; // a preparation a search starts during the stop waits for it in runtime(), so the stop must not wait for that one
|
|
459
486
|
const stop=(async()=>{
|
|
460
|
-
this.active=false;this.fullIndexing=false;this.quietStop=true;this.generation++;this.dirty=false;
|
|
487
|
+
this.active=false;this.fullIndexing=false;this.backgroundOnly=false;this.quietStop=true;this.generation++;this.dirty=false;
|
|
461
488
|
if(this._timer){clearTimeout(this._timer);this.timer=undefined;}
|
|
462
489
|
this.cancelHeal();
|
|
463
490
|
const worker=this.worker;
|
|
@@ -490,7 +517,7 @@ export class SemanticRecallController {
|
|
|
490
517
|
// A source that can no longer be read stops recall; the reason stays readable until the next enable, so this never looks like recall that was never on.
|
|
491
518
|
private async revoked(error:unknown){await this.disable(false);this.error=error instanceof Error?error.message:'Source access denied';}
|
|
492
519
|
async invalidate(){await this.disable();this.error='Caller invalidated semantic source access; explicit enable required';}
|
|
493
|
-
async close(){await this.disable(true,false);this.provider=undefined;this.searched=false;} // a closed controller serves a new session, which has not searched; a disable and enable keeps it
|
|
520
|
+
async close(){await this.disable(true,false);await this.freeLock();this.provider=undefined;this.searched=false;} // a closed controller serves a new session, which has not searched; a disable and enable keeps it
|
|
494
521
|
}
|
|
495
522
|
export const createSemanticRecall=(config?:SemanticRecallConfig)=>new SemanticRecallController(config);
|
|
496
523
|
/** Consolidate only source-bound coordinate overlap; equal text in distinct events is retained.
|