pi-tuck 1.1.3 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/index.d.ts +2 -6
- package/dist/index.js +16 -111
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/compaction.d.ts +2 -103
- package/dist/src/compaction.js +20 -140
- package/dist/src/diagnostic-replay.js +2 -2
- package/dist/src/diagnostics.d.ts +3 -2
- package/dist/src/diagnostics.js +30 -9
- package/dist/src/history-tools.js +3 -3
- package/dist/src/kept-reads.d.ts +2 -2
- package/dist/src/kept-reads.js +144 -8
- package/dist/src/ledger.d.ts +1 -1
- package/dist/src/ledger.js +5 -3
- package/dist/src/legacy-cleanup.d.ts +3 -0
- package/dist/src/legacy-cleanup.js +190 -0
- package/dist/src/notify.d.ts +3 -0
- package/dist/src/notify.js +13 -0
- package/dist/src/omissions.d.ts +1 -1
- package/dist/src/omissions.js +3 -3
- package/dist/src/path-key.d.ts +3 -0
- package/dist/src/path-key.js +8 -0
- package/dist/src/request-capacity.js +1 -1
- package/dist/src/run.d.ts +1 -3
- package/dist/src/run.js +3 -5
- package/dist/src/source-export.d.ts +1 -1
- package/dist/src/source-export.js +1 -1
- package/dist/src/status.d.ts +0 -6
- package/dist/src/status.js +1 -6
- package/dist/src/tuck/core/content.js +6 -9
- package/dist/src/tuck/core/keyword-query.d.ts +2 -2
- package/dist/src/tuck/core/keyword-query.js +1 -1
- package/dist/src/tuck/core/search-entries.js +5 -5
- package/dist/src/tuck/core/transcript.js +2 -1
- package/dist/src/tuck.js +390 -394
- package/dist/src/windows-private-storage.d.ts +9 -0
- package/dist/src/windows-private-storage.js +90 -0
- package/index.ts +18 -82
- package/package.json +5 -8
- package/src/build-id.ts +1 -1
- package/src/compaction.ts +19 -107
- package/src/diagnostic-replay.ts +2 -2
- package/src/diagnostics.ts +24 -9
- package/src/history-tools.ts +3 -3
- package/src/kept-reads.ts +78 -10
- package/src/ledger.ts +5 -3
- package/src/legacy-cleanup.ts +134 -0
- package/src/notify.ts +10 -0
- package/src/omissions.ts +3 -3
- package/src/path-key.ts +9 -0
- package/src/request-capacity.ts +1 -1
- package/src/run.ts +4 -6
- package/src/source-export.ts +1 -1
- package/src/status.ts +1 -10
- package/src/tuck/core/content.ts +5 -10
- package/src/tuck/core/keyword-query.ts +2 -2
- package/src/tuck/core/search-entries.ts +5 -5
- package/src/tuck/core/transcript.ts +2 -1
- package/src/tuck.ts +329 -335
- package/src/windows-private-storage.ts +94 -0
- package/dist/src/assets.d.ts +0 -58
- package/dist/src/assets.js +0 -80
- package/dist/src/eligibility-cache.d.ts +0 -19
- package/dist/src/eligibility-cache.js +0 -33
- package/dist/src/semantic-recall.d.ts +0 -422
- package/dist/src/semantic-recall.js +0 -1386
- package/dist/src/setup.d.ts +0 -3
- package/dist/src/setup.js +0 -191
- package/scripts/eg2-runtime.py +0 -307
- package/scripts/provision-eg2.py +0 -139
- package/scripts/semantic-worker.py +0 -234
- package/src/assets.ts +0 -92
- package/src/eligibility-cache.ts +0 -43
- package/src/semantic-recall.ts +0 -592
- package/src/setup.ts +0 -163
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Create private storage without changing any pre-existing directory's permissions.
|
|
2
|
+
* Callers must still verify existing storage before using it. */
|
|
3
|
+
export declare function createPrivateDirectory(directory: string): Promise<void>;
|
|
4
|
+
/** Only call for an empty file we just created exclusively inside verified private storage.
|
|
5
|
+
* The recorder retains its handle, protects the file, then verifies it before writing content. */
|
|
6
|
+
export declare function protectWindowsIncidentFile(path: string): Promise<void>;
|
|
7
|
+
/** Only the current user, SYSTEM and local administrators may receive access.
|
|
8
|
+
* No ACLs are changed: shared/custom storage fails closed before content is written. */
|
|
9
|
+
export declare function assertWindowsPrivateStorage(paths: readonly string[]): Promise<void>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { mkdir } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
// Node's Windows mode/uid fields cannot prove private storage. Check the native DACL instead.
|
|
5
|
+
// Pass paths as data, never PowerShell source; SID comparisons also work on non-English hosts.
|
|
6
|
+
const CHECK_ACL = `
|
|
7
|
+
$ErrorActionPreference = 'Stop'
|
|
8
|
+
try {
|
|
9
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
10
|
+
$trusted = @($user, 'S-1-5-18', 'S-1-5-32-544')
|
|
11
|
+
foreach ($path in (ConvertFrom-Json -InputObject $env:PI_TUCK_STORAGE_PATHS)) {
|
|
12
|
+
$item = Get-Item -LiteralPath $path -Force
|
|
13
|
+
if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { throw 'Recorder reparse point' }
|
|
14
|
+
$acl = Get-Acl -LiteralPath $path
|
|
15
|
+
if ($trusted -notcontains $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value) { throw 'Recorder owner' }
|
|
16
|
+
$rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])
|
|
17
|
+
if ($rules.Count -eq 0) { throw 'Recorder missing DACL' }
|
|
18
|
+
foreach ($rule in $rules) {
|
|
19
|
+
if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { continue }
|
|
20
|
+
$sid = $rule.IdentityReference.Value
|
|
21
|
+
if ($trusted -contains $sid) { continue }
|
|
22
|
+
if ($sid -eq 'S-1-3-0' -and ($rule.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly)) { continue }
|
|
23
|
+
throw 'Recorder non-private DACL'
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
} catch { [Console]::Error.WriteLine('Recorder requires private Windows storage'); exit 1 }
|
|
27
|
+
`;
|
|
28
|
+
// Build a fresh protected DACL, dropping both inherited and explicit foreign entries.
|
|
29
|
+
// Directories pass this security descriptor at creation, including missing ancestors;
|
|
30
|
+
// existing directories are returned unchanged by Directory.CreateDirectory.
|
|
31
|
+
const PRIVATE_DACL = `
|
|
32
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
|
|
33
|
+
$acl.SetOwner($user)
|
|
34
|
+
$acl.SetAccessRuleProtection($true, $false)
|
|
35
|
+
foreach ($sid in @($user.Value, 'S-1-5-18', 'S-1-5-32-544')) {
|
|
36
|
+
$identity = [System.Security.Principal.SecurityIdentifier]::new($sid)
|
|
37
|
+
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow)
|
|
38
|
+
$acl.AddAccessRule($rule)
|
|
39
|
+
}
|
|
40
|
+
`;
|
|
41
|
+
const CREATE_DIRECTORY = `
|
|
42
|
+
$ErrorActionPreference = 'Stop'
|
|
43
|
+
try {
|
|
44
|
+
$acl = [System.Security.AccessControl.DirectorySecurity]::new()
|
|
45
|
+
$inheritance = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
|
|
46
|
+
${PRIVATE_DACL}
|
|
47
|
+
foreach ($path in (ConvertFrom-Json -InputObject $env:PI_TUCK_STORAGE_PATHS)) {
|
|
48
|
+
[void][System.IO.Directory]::CreateDirectory($path, $acl)
|
|
49
|
+
}
|
|
50
|
+
} catch { [Console]::Error.WriteLine('Recorder could not create private Windows directory'); exit 1 }
|
|
51
|
+
`;
|
|
52
|
+
const PROTECT_FILE = `
|
|
53
|
+
$ErrorActionPreference = 'Stop'
|
|
54
|
+
try {
|
|
55
|
+
$acl = [System.Security.AccessControl.FileSecurity]::new()
|
|
56
|
+
$inheritance = [System.Security.AccessControl.InheritanceFlags]::None
|
|
57
|
+
${PRIVATE_DACL}
|
|
58
|
+
foreach ($path in (ConvertFrom-Json -InputObject $env:PI_TUCK_STORAGE_PATHS)) {
|
|
59
|
+
$item = Get-Item -LiteralPath $path -Force
|
|
60
|
+
if ($item.PSIsContainer -or ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) { throw 'Recorder file type' }
|
|
61
|
+
Set-Acl -LiteralPath $path -AclObject $acl
|
|
62
|
+
}
|
|
63
|
+
} catch { [Console]::Error.WriteLine('Recorder could not protect Windows file'); exit 1 }
|
|
64
|
+
`;
|
|
65
|
+
function runAclCommand(script, paths) {
|
|
66
|
+
const powershell = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
execFile(powershell, ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script], {
|
|
69
|
+
env: { ...process.env, PI_TUCK_STORAGE_PATHS: JSON.stringify(paths) }, windowsHide: true, timeout: 10_000, maxBuffer: 16_384,
|
|
70
|
+
}, error => error ? reject(error) : resolve());
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/** Create private storage without changing any pre-existing directory's permissions.
|
|
74
|
+
* Callers must still verify existing storage before using it. */
|
|
75
|
+
export async function createPrivateDirectory(directory) {
|
|
76
|
+
if (process.platform === 'win32')
|
|
77
|
+
await runAclCommand(CREATE_DIRECTORY, [directory]);
|
|
78
|
+
else
|
|
79
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
80
|
+
}
|
|
81
|
+
/** Only call for an empty file we just created exclusively inside verified private storage.
|
|
82
|
+
* The recorder retains its handle, protects the file, then verifies it before writing content. */
|
|
83
|
+
export function protectWindowsIncidentFile(path) {
|
|
84
|
+
return runAclCommand(PROTECT_FILE, [path]);
|
|
85
|
+
}
|
|
86
|
+
/** Only the current user, SYSTEM and local administrators may receive access.
|
|
87
|
+
* No ACLs are changed: shared/custom storage fails closed before content is written. */
|
|
88
|
+
export function assertWindowsPrivateStorage(paths) {
|
|
89
|
+
return runAclCommand(CHECK_ACL, paths);
|
|
90
|
+
}
|
package/index.ts
CHANGED
|
@@ -1,22 +1,17 @@
|
|
|
1
|
-
import { VERSION, getAgentDir, type ExtensionAPI
|
|
2
|
-
import {
|
|
3
|
-
import { join
|
|
1
|
+
import { VERSION, getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
4
|
import { installCompaction } from "./src/compaction";
|
|
5
5
|
import { validCutAt } from "./src/budget";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import { ensureSemanticRuntime } from "./src/setup";
|
|
6
|
+
import { notify } from "./src/notify";
|
|
7
|
+
import { cleanupLegacyFiles } from "./src/legacy-cleanup";
|
|
9
8
|
|
|
10
9
|
export type { CompactionOptions } from "./src/compaction";
|
|
11
10
|
export { installCompaction } from "./src/compaction";
|
|
12
11
|
export { inspectIncident, readableIncident } from "./src/diagnostic-replay.js";
|
|
13
|
-
export { createSemanticRecall, SemanticRecallController } from "./src/semantic-recall";
|
|
14
|
-
export type { SemanticRecallConfig, PriorResult, SemanticState, SemanticSetup } from "./src/semantic-recall";
|
|
15
|
-
export { ensureSemanticRuntime } from "./src/setup";
|
|
16
12
|
|
|
17
|
-
/** pi-tuck as a Pi extension: compaction and history recall
|
|
18
|
-
*
|
|
19
|
-
* (a number above 0 and at most 1) is the fraction of the input room a cut is triggered at, 0.6 by default. */
|
|
13
|
+
/** pi-tuck as a Pi extension: compaction and history recall. `"cutAt"` in `pi-tuck.json` in Pi's agent folder (a number above 0 and at most
|
|
14
|
+
* 1) fixes the cut point as a fraction of the input room; without it, the cut point adapts. */
|
|
20
15
|
/** The oldest Pi with every hook and API pi-tuck uses, and the oldest its tests pass on (Pi 1.2 added the custom message that starts a
|
|
21
16
|
* run to before_agent_start, which the prompt's cut counts). */
|
|
22
17
|
export const PI_FLOOR = "1.2.0";
|
|
@@ -39,84 +34,25 @@ export default async function (pi: ExtensionAPI) {
|
|
|
39
34
|
});
|
|
40
35
|
return;
|
|
41
36
|
}
|
|
42
|
-
const semanticRecall = createSemanticRecall();
|
|
43
|
-
// `/tuck-semantic off` holds for the rest of the session, including over a setup that finishes later.
|
|
44
37
|
const settings = readSettings(join(getAgentDir(), "pi-tuck.json"));
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
else if (semanticRecall.status().setup === "off-user") semanticRecall.setSetup("starting", { installed: existsSync(runtimeConfigPath(defaultRoot())) });
|
|
50
|
-
} });
|
|
51
|
-
if (settings.semanticRecall === false) {
|
|
52
|
-
semanticRecall.setSetup("off-settings");
|
|
53
|
-
pi.on("session_start", () => { semanticRecall.setSetup("off-settings"); });
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
let session = 0, said = "", announced = false, setup: Promise<unknown> | undefined;
|
|
57
|
-
// A context outlives its session (a setup can finish after /new); a notice to an ended session is dropped.
|
|
58
|
-
// With no UI (pi -p), Pi shows no notices, so a settings error or an off or failing semantic recall would go unsaid: write each to stderr
|
|
59
|
-
// instead, once per session. stderr is the operator's; it never enters the model's context.
|
|
60
|
-
const stderrSaid = new Set<string>();
|
|
61
|
-
const say = (ctx: ExtensionContext, message: string, level: "info" | "warning") => {
|
|
62
|
-
if (!ctx.hasUI) { if (!stderrSaid.has(message)) { stderrSaid.add(message); try { process.stderr.write(message + "\n"); } catch { /* closed */ } } return; }
|
|
63
|
-
try { ctx.ui.notify(message, level); } catch { /* ended */ }
|
|
64
|
-
};
|
|
65
|
-
const once = (ctx: ExtensionContext, message: string, level: "info" | "warning") => { if (said !== message) { said = message; say(ctx, message, level); } };
|
|
66
|
-
const announce = (ctx: ExtensionContext, state: Parameters<typeof semanticRecall.setSetup>[0], detail?: Parameters<typeof semanticRecall.setSetup>[1]) => {
|
|
67
|
-
semanticRecall.setSetup(state, detail);
|
|
68
|
-
const notice = semanticRecall.setupNotice();
|
|
69
|
-
if (notice) (state === "off-platform" || state === "off-project" ? once : say)(ctx, notice.message, notice.level);
|
|
70
|
-
};
|
|
71
|
-
pi.on("session_shutdown", () => { session++; });
|
|
72
|
-
pi.on("session_start", (_event, ctx) => {
|
|
73
|
-
const current = ++session;
|
|
74
|
-
stderrSaid.clear();
|
|
38
|
+
const handle = await installCompaction(pi, { cutAt: settings.cutAt });
|
|
39
|
+
let said = false;
|
|
40
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
41
|
+
await cleanupLegacyFiles(ctx);
|
|
75
42
|
if (handle.state?.(ctx).kind === "standingDown") return;
|
|
76
|
-
if (settings.error
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
// Semantic recall keeps its runtime and indexes outside the project it serves, so not when Pi runs in a folder that holds its
|
|
80
|
-
// agent folder, such as the home folder.
|
|
81
|
-
if (within(real(getAgentDir()), real(ctx.cwd)))
|
|
82
|
-
return announce(ctx, "off-project");
|
|
83
|
-
// A run with no UI (pi -p, RPC, JSON) uses a runtime that is already installed: that needs no download. It does not start a first-time
|
|
84
|
-
// setup, which would outlast a one-shot run, and it says why, so tuck_search and /tuck name the real state.
|
|
85
|
-
const installed = existsSync(runtimeConfigPath(defaultRoot()));
|
|
86
|
-
if (!ctx.hasUI && !installed) return announce(ctx, "not-installed");
|
|
87
|
-
// The download's announcement outlives the session that made it: a session that starts while the shared setup is still running
|
|
88
|
-
// owes the "set up" notice once, as before the refactor.
|
|
89
|
-
semanticRecall.setSetup("starting", { installed, announced });
|
|
90
|
-
setup ??= ensureSemanticRuntime(defaultRoot(), message => {
|
|
91
|
-
announced = true;
|
|
92
|
-
if (current === session && semanticRecall.status().setup !== "off-user") announce(ctx, "starting", { installed, notice: message, announced: true });
|
|
93
|
-
});
|
|
94
|
-
setup.then(async () => {
|
|
95
|
-
if (current !== session || semanticRecall.status().setup === "off-user") return;
|
|
96
|
-
try {
|
|
97
|
-
await handle.setSemanticEnabled(true, ctx);
|
|
98
|
-
if (current === session && semanticRecall.status().setup !== "off-user") { announce(ctx, "ready", { announced }); announced = false; }
|
|
99
|
-
} catch (error) {
|
|
100
|
-
if (current === session && semanticRecall.status().setup !== "off-user") announce(ctx, "failed", { stage: "start", reason: reason(error) });
|
|
101
|
-
}
|
|
102
|
-
}, error => {
|
|
103
|
-
setup = undefined; // the next session start tries again
|
|
104
|
-
if (current === session && semanticRecall.status().setup !== "off-user") announce(ctx, "failed", { stage: "setup", reason: reason(error) });
|
|
105
|
-
});
|
|
43
|
+
if (settings.error && !said) {
|
|
44
|
+
said = notify(ctx, `pi-tuck: ${settings.error}; using the defaults.`, "warning");
|
|
45
|
+
}
|
|
106
46
|
});
|
|
107
47
|
}
|
|
108
48
|
|
|
109
|
-
function readSettings(path: string): {
|
|
49
|
+
function readSettings(path: string): { cutAt?: number; error?: string } {
|
|
110
50
|
let text: string;
|
|
111
51
|
try { text = readFileSync(path, "utf8"); } catch { return {}; }
|
|
112
52
|
try {
|
|
113
53
|
const value = JSON.parse(text);
|
|
114
|
-
if (value && typeof value === "object" &&
|
|
115
|
-
(value.cutAt === undefined || validCutAt(value.cutAt))) return value;
|
|
54
|
+
if (value && typeof value === "object" &&
|
|
55
|
+
(value.cutAt === undefined || validCutAt(value.cutAt))) return { cutAt: value.cutAt };
|
|
116
56
|
} catch { /* reported below */ }
|
|
117
|
-
return { error: `${path} should be a JSON object like {"
|
|
57
|
+
return { error: `${path} should be a JSON object like {"cutAt": 0.8}, with cutAt a number above 0 and at most 1` };
|
|
118
58
|
}
|
|
119
|
-
|
|
120
|
-
const reason = (error: unknown) => error instanceof Error ? error.message : String(error);
|
|
121
|
-
const within = (path: string, folder: string) => path === folder || path.startsWith(folder.endsWith(sep) ? folder : folder + sep);
|
|
122
|
-
const real = (path: string) => { try { return realpathSync(path); } catch { return path; } };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-tuck",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
7
7
|
"pi",
|
|
@@ -9,7 +9,6 @@
|
|
|
9
9
|
"compaction",
|
|
10
10
|
"context",
|
|
11
11
|
"recall",
|
|
12
|
-
"semantic-search",
|
|
13
12
|
"pi-coding-agent",
|
|
14
13
|
"coding-agent",
|
|
15
14
|
"context-window",
|
|
@@ -26,7 +25,8 @@
|
|
|
26
25
|
"type": "module",
|
|
27
26
|
"os": [
|
|
28
27
|
"darwin",
|
|
29
|
-
"linux"
|
|
28
|
+
"linux",
|
|
29
|
+
"win32"
|
|
30
30
|
],
|
|
31
31
|
"engines": {
|
|
32
32
|
"node": ">=22.19.0"
|
|
@@ -46,14 +46,11 @@
|
|
|
46
46
|
"index.ts",
|
|
47
47
|
"src",
|
|
48
48
|
"dist",
|
|
49
|
-
"scripts/eg2-runtime.py",
|
|
50
|
-
"scripts/provision-eg2.py",
|
|
51
|
-
"scripts/semantic-worker.py",
|
|
52
49
|
"CHANGELOG.md"
|
|
53
50
|
],
|
|
54
51
|
"scripts": {
|
|
55
52
|
"check": "tsc -p tsconfig.tests.json",
|
|
56
|
-
"test": "vitest run --config vitest.config.ts
|
|
53
|
+
"test": "vitest run --config vitest.config.ts",
|
|
57
54
|
"build": "node scripts/build.mjs",
|
|
58
55
|
"prepack": "npm run build"
|
|
59
56
|
},
|
package/src/build-id.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const BUILD_ID = "
|
|
1
|
+
export const BUILD_ID = "f653b17921c5383797b70c8962152e6b4537a7769e05118290fc34d492a06ec1";
|
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
|
@@ -13,9 +13,9 @@ export function inspectIncident(records: IncidentRecord[]) {
|
|
|
13
13
|
const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore!, previousSummary: i.previousSummary, operatorManual: i.operatorManual }, ctx, i.reserve!, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
|
|
14
14
|
const proposal = records.find(r => r.kind === 'proposal' && (r.data as { details?: { diagnosticReceipt?: { id?: string } } })?.details?.diagnosticReceipt?.id === i.receiptId)?.data as { summary?: string; firstKeptEntryId?: string } | undefined;
|
|
15
15
|
const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
|
|
16
|
-
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference,
|
|
16
|
+
return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
|
|
17
17
|
});
|
|
18
|
-
return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all
|
|
18
|
+
return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
|
|
19
19
|
}
|
|
20
20
|
export function readableIncident(records: IncidentRecord[]): string {
|
|
21
21
|
return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
|