notesoup 0.41.0 → 0.43.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/dist/src/boot/render.js +11 -20
- package/dist/src/boot/snapshot.js +1 -6
- package/dist/src/boot/text.d.ts +12 -0
- package/dist/src/boot/text.js +15 -3
- package/dist/src/budget/parse.d.ts +14 -0
- package/dist/src/budget/parse.js +36 -0
- package/dist/src/budget/policy.js +2 -7
- package/dist/src/budget/text.d.ts +14 -0
- package/dist/src/budget/text.js +14 -0
- package/dist/src/claude/helper.js +24 -4
- package/dist/src/claude/thresholds.d.ts +39 -0
- package/dist/src/claude/thresholds.js +128 -0
- package/dist/src/dream/doctor.js +1 -1
- package/dist/src/dream/jail.js +10 -10
- package/dist/src/dream/lock.js +6 -13
- package/dist/src/dream/report.js +5 -15
- package/dist/src/history/history.js +5 -3
- package/dist/src/history/query.js +14 -26
- package/dist/src/notes/address.d.ts +1 -2
- package/dist/src/notes/address.js +14 -26
- package/dist/src/notes/errors.d.ts +2 -0
- package/dist/src/notes/errors.js +5 -0
- package/dist/src/notes/frontmatter.js +16 -2
- package/dist/src/notes/identity.js +0 -3
- package/dist/src/notes/paths.d.ts +11 -1
- package/dist/src/notes/paths.js +28 -7
- package/dist/src/notes/store.d.ts +1 -0
- package/dist/src/notes/store.js +54 -49
- package/dist/src/pi/boot.js +1 -5
- package/dist/src/pi/budget.d.ts +3 -3
- package/dist/src/pi/budget.js +11 -11
- package/dist/src/pi/dream/cli.js +43 -11
- package/dist/src/pi/estimate.d.ts +1 -5
- package/dist/src/pi/estimate.js +4 -4
- package/dist/src/pi/history.js +1 -4
- package/dist/src/pi/notes/adapter.d.ts +1 -1
- package/dist/src/pi/notes/adapter.js +2 -2
- package/dist/src/pi/reset/artifacts.d.ts +0 -2
- package/dist/src/pi/reset/artifacts.js +4 -4
- package/dist/src/pi/reset/committed.js +2 -2
- package/dist/src/pi/runtime.js +9 -6
- package/dist/src/pi/thresholds.js +5 -9
- package/dist/src/pi/tool-result.d.ts +1 -4
- package/dist/src/pi/tool-result.js +3 -3
- package/dist/src/pi/window.d.ts +5 -0
- package/dist/src/pi/window.js +7 -0
- package/dist/src/settings.d.ts +10 -0
- package/dist/src/settings.js +10 -4
- package/dist/src/tools/history.js +15 -18
- package/dist/src/tools/notes.d.ts +3 -7
- package/dist/src/tools/notes.js +18 -27
- package/dist/src/tools/output.d.ts +2 -3
- package/dist/src/tools/output.js +3 -9
- package/dist/src/tools/result.d.ts +1 -0
- package/dist/src/tools/result.js +15 -21
- package/dist/src/tools/schema.d.ts +0 -1
- package/dist/src/tools/schema.js +3 -4
- package/dist/test/agent-loop.test.js +1 -2
- package/dist/test/boot.integration.test.js +1 -1
- package/dist/test/claude-mod.test.js +425 -23
- package/dist/test/claude-validation.test.d.ts +1 -0
- package/dist/test/claude-validation.test.js +73 -0
- package/dist/test/dream-skill.test.js +2 -4
- package/dist/test/dream.test.js +17 -3
- package/dist/test/helpers/extension.js +1 -1
- package/dist/test/history.integration.test.js +9 -9
- package/dist/test/host-neutral.test.js +16 -1
- package/dist/test/notes-library.test.js +31 -2
- package/dist/test/notes.integration.test.js +11 -11
- package/dist/test/notes.test.js +40 -21
- package/dist/test/reset-lifecycle.test.js +1 -1
- package/docs/claude-code-mod.md +13 -3
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +285 -152
- package/mods/notesoup/hooks/register.ts +308 -51
- package/mods/notesoup/playbook.md +1 -1
- package/mods/notesoup/skills/dream/SKILL.md +1 -1
- package/mods/notesoup/skills/memory/SKILL.md +61 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +5 -3
- package/playbook.md +1 -1
- package/skills/dream/SKILL.md +1 -1
- package/skills/memory/SKILL.md +1 -1
- package/src/boot/render.ts +11 -21
- package/src/boot/snapshot.ts +2 -7
- package/src/boot/text.ts +21 -3
- package/src/budget/parse.ts +39 -0
- package/src/budget/policy.ts +2 -6
- package/src/budget/text.ts +20 -0
- package/src/claude/helper.ts +22 -5
- package/src/claude/thresholds.ts +153 -0
- package/src/dream/doctor.ts +1 -1
- package/src/dream/jail.ts +10 -10
- package/src/dream/lock.ts +3 -9
- package/src/dream/report.ts +5 -10
- package/src/history/history.ts +5 -3
- package/src/history/query.ts +14 -27
- package/src/notes/address.ts +13 -25
- package/src/notes/errors.ts +6 -0
- package/src/notes/frontmatter.ts +12 -2
- package/src/notes/identity.ts +0 -2
- package/src/notes/paths.ts +23 -5
- package/src/notes/store.ts +50 -48
- package/src/pi/boot.ts +1 -13
- package/src/pi/budget.ts +10 -11
- package/src/pi/dream/cli.ts +35 -10
- package/src/pi/estimate.ts +4 -4
- package/src/pi/history.ts +1 -5
- package/src/pi/notes/adapter.ts +2 -2
- package/src/pi/reset/artifacts.ts +4 -4
- package/src/pi/reset/committed.ts +2 -2
- package/src/pi/runtime.ts +8 -7
- package/src/pi/thresholds.ts +5 -11
- package/src/pi/tool-result.ts +3 -3
- package/src/pi/window.ts +8 -0
- package/src/settings.ts +22 -5
- package/src/tools/history.ts +15 -19
- package/src/tools/notes.ts +21 -32
- package/src/tools/output.ts +3 -12
- package/src/tools/result.ts +14 -19
- package/src/tools/schema.ts +3 -4
- package/dist/src/dream/playbook.d.ts +0 -1
- package/dist/src/dream/playbook.js +0 -2
- package/dist/src/pi/reset/text.d.ts +0 -5
- package/dist/src/pi/reset/text.js +0 -6
- package/src/dream/playbook.ts +0 -3
- package/src/pi/reset/text.ts +0 -10
package/src/pi/budget.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { remainingBudget, type ResolvedThresholds } from "../budget/policy.js";
|
|
|
3
3
|
import { Type } from "@earendil-works/pi-ai";
|
|
4
4
|
import { defineTool, type ExtensionAPI, type ExtensionContext, type SessionBoundaryDraft, type SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { GUIDANCE_TYPE, WARNING_TYPE } from "./entries.js";
|
|
6
|
-
import { WARNING_CONTENT } from "
|
|
6
|
+
import { WARNING_CONTENT } from "../budget/text.js";
|
|
7
7
|
import { readThresholdSettings, type ThresholdSettingsResolution } from "./thresholds.js";
|
|
8
8
|
import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
|
|
9
9
|
import { tokenBudgetGuidance } from "../budget/text.js";
|
|
@@ -11,7 +11,7 @@ import { arrangeAnchoredReminders, type AnchorDetails } from "./anchored.js";
|
|
|
11
11
|
import { output } from "../tools/output.js";
|
|
12
12
|
|
|
13
13
|
/** Remaining tokens in the provider's active window, or null without a usable estimate. */
|
|
14
|
-
|
|
14
|
+
function remainingTokens(ctx: Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model">): number | null {
|
|
15
15
|
const usage = windowUsage(ctx);
|
|
16
16
|
return !usage || usage.tokens === null ? null : Math.max(0, usage.contextWindow - usage.tokens);
|
|
17
17
|
}
|
|
@@ -20,10 +20,12 @@ export function registerBudget(
|
|
|
20
20
|
pi: ExtensionAPI,
|
|
21
21
|
isEnabled: () => boolean,
|
|
22
22
|
settingsManager?: SettingsManager,
|
|
23
|
-
onCloseOut: (windowId: string) => void = () => {},
|
|
24
23
|
) {
|
|
25
24
|
let cachedPolicy: { thresholds: ResolvedThresholds; automatic: boolean } | undefined;
|
|
26
25
|
const notifiedWarnings = new Set<string>();
|
|
26
|
+
// The reset owner is wired after both sides exist, so no handler can observe a
|
|
27
|
+
// half-constructed pair (a close-out request cannot arrive before registration ends).
|
|
28
|
+
let onCloseOut: (windowId: string) => void = () => {};
|
|
27
29
|
const resolvePolicy = (ctx: ExtensionContext): ThresholdSettingsResolution => {
|
|
28
30
|
if (!settingsManager && cachedPolicy) return { ...cachedPolicy, warnings: [] };
|
|
29
31
|
const resolution = readThresholdSettings(ctx, settingsManager);
|
|
@@ -35,18 +37,13 @@ export function registerBudget(
|
|
|
35
37
|
if (!settingsManager) cachedPolicy = { thresholds: resolution.thresholds, automatic: resolution.automatic };
|
|
36
38
|
return resolution;
|
|
37
39
|
};
|
|
38
|
-
const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds =>
|
|
39
|
-
|
|
40
|
-
};
|
|
41
|
-
const automaticResetEnabled = (ctx: ExtensionContext): boolean => {
|
|
42
|
-
return resolvePolicy(ctx).automatic;
|
|
43
|
-
};
|
|
40
|
+
const thresholdsFor = (ctx: ExtensionContext): ResolvedThresholds => resolvePolicy(ctx).thresholds;
|
|
41
|
+
const automaticResetEnabled = (ctx: ExtensionContext): boolean => resolvePolicy(ctx).automatic;
|
|
44
42
|
const hardReserveDue = (ctx: ExtensionContext): boolean => {
|
|
45
43
|
if (!automaticResetEnabled(ctx)) return false;
|
|
46
44
|
const usage = windowUsage(ctx);
|
|
47
45
|
return usage !== undefined && usage.tokens !== null && usage.contextWindow - usage.tokens <= thresholdsFor(ctx).reserve;
|
|
48
46
|
};
|
|
49
|
-
const invalidateThresholds = () => { cachedPolicy = undefined; };
|
|
50
47
|
let pendingGuidance: { windowId: string; content: string } | undefined;
|
|
51
48
|
let pendingWarning: { windowId: string; content: string } | undefined;
|
|
52
49
|
let pendingNotices = new Map<string, { sessionId: string; windowId: string }>();
|
|
@@ -82,7 +79,7 @@ export function registerBudget(
|
|
|
82
79
|
const resetForTransition = () => {
|
|
83
80
|
clearStaged();
|
|
84
81
|
pendingNotices.clear();
|
|
85
|
-
|
|
82
|
+
cachedPolicy = undefined;
|
|
86
83
|
notifiedWarnings.clear();
|
|
87
84
|
};
|
|
88
85
|
|
|
@@ -172,6 +169,8 @@ export function registerBudget(
|
|
|
172
169
|
automaticResetEnabled,
|
|
173
170
|
hardReserveDue,
|
|
174
171
|
consumeTurnEnd,
|
|
172
|
+
/** The reset owner wires its close-out here once the lifecycle reducer exists. */
|
|
173
|
+
setCloseOut: (handler: (windowId: string) => void) => { onCloseOut = handler; },
|
|
175
174
|
/** The same close-out countdown the model sees, for user-facing status; null when usage is unknown. */
|
|
176
175
|
statusFor: (ctx: ExtensionContext): { remaining: number | null } => ({ remaining: remainingBudget(remainingTokens(ctx), thresholdsFor(ctx).warning) }),
|
|
177
176
|
clear: () => { clearStaged(); pendingNotices.clear(); },
|
package/src/pi/dream/cli.ts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { finishDream } from "../../dream/report.js";
|
|
3
3
|
import type { DreamerSetting } from "../../dream/settings.js";
|
|
4
|
-
import { loadPlaybook } from "../../dream/playbook.js";
|
|
5
4
|
import type { DreamResult } from "../../dream/result.js";
|
|
6
|
-
import { existsSync, mkdirSync, realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
7
6
|
import { dirname, join, resolve } from "node:path";
|
|
8
7
|
import { fileURLToPath } from "node:url";
|
|
9
8
|
import { acquireLock, failLock, lastRunPath, releaseLock } from "../../dream/lock.js";
|
|
@@ -16,6 +15,21 @@ import { notesRoot } from "../notes/adapter.js";
|
|
|
16
15
|
import { errorMessage } from "../../error-message.js";
|
|
17
16
|
|
|
18
17
|
function args(argv: string[]) { const out: Record<string, string | boolean> = {}; for (let i=0;i<argv.length;i++) { const a=argv[i]!; if (a === "--force" || a === "--help") out[a.slice(2)] = true; else if (a.startsWith("--")) out[a.slice(2)] = argv[++i] ?? ""; } return out; }
|
|
18
|
+
|
|
19
|
+
/** A positive whole-number flag, or undefined when the value is not one. */
|
|
20
|
+
function wholeNumberArg(raw: string | boolean | undefined): number | undefined {
|
|
21
|
+
if (raw === undefined) return undefined;
|
|
22
|
+
if (typeof raw !== "string" || raw.trim() === "") return undefined;
|
|
23
|
+
const value = Number(raw);
|
|
24
|
+
return Number.isInteger(value) && value > 0 ? value : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** A directory flag that must carry a real path, not a missing or flag-looking value. */
|
|
28
|
+
function directoryArg(raw: string | boolean | undefined): string | undefined {
|
|
29
|
+
if (raw === undefined) return undefined;
|
|
30
|
+
if (typeof raw !== "string" || raw.trim() === "" || raw.startsWith("--")) return undefined;
|
|
31
|
+
return raw;
|
|
32
|
+
}
|
|
19
33
|
function packageRoot(): string {
|
|
20
34
|
let dir = dirname(fileURLToPath(import.meta.url));
|
|
21
35
|
while (true) { if (existsSync(join(dir, "package.json"))) return dir; const parent = dirname(dir); if (parent === dir) throw new Error("could not locate installed package root"); dir = parent; }
|
|
@@ -32,18 +46,29 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
32
46
|
if (argv[0] === "doctor") {
|
|
33
47
|
const options = args(argv.slice(1));
|
|
34
48
|
if (options.help) { console.log("dream doctor [--notes-home <dir>] — read-only diagnostics; no model or repairs"); return 0; }
|
|
35
|
-
const home =
|
|
36
|
-
|
|
37
|
-
|
|
49
|
+
const home = directoryArg(options["notes-home"]);
|
|
50
|
+
if (options["notes-home"] !== undefined && home === undefined) { console.error("dream: --notes-home needs a directory path"); return 1; }
|
|
51
|
+
const root = resolve(home ?? notesRoot());
|
|
52
|
+
const issues = doctor(root);
|
|
53
|
+
console.log(issues.length ? issues.join("\n") : `dream doctor: OK (${root})`);
|
|
38
54
|
return issues.length ? 1 : 0;
|
|
39
55
|
}
|
|
40
56
|
const a = args(argv); if (a.help) { console.log("dream doctor [--notes-home <dir>] — read-only diagnostics\ndream --notes-home <dir> [--min-hours 24] [--min-sessions 3] [--force] [--dreamer <model pattern>] [--playbook <path>]\nDreamer model: --dreamer wins, else notesoup.dreamer from settings, else the automatic model. Default playbook: <installed package root>/playbook.md; --playbook overrides it."); return 0; }
|
|
41
|
-
|
|
57
|
+
// Validate every value flag before anything is created or gated on: a typo must refuse
|
|
58
|
+
// loudly instead of reading as "the last dream is too recent" and exiting successfully.
|
|
59
|
+
const homeArg = directoryArg(a["notes-home"]);
|
|
60
|
+
const minHours = wholeNumberArg(a["min-hours"]);
|
|
61
|
+
const minSessions = wholeNumberArg(a["min-sessions"]);
|
|
62
|
+
const badArg = a["notes-home"] !== undefined && homeArg === undefined ? "--notes-home needs a directory path"
|
|
63
|
+
: a["min-hours"] !== undefined && minHours === undefined ? "--min-hours needs a positive whole number"
|
|
64
|
+
: a["min-sessions"] !== undefined && minSessions === undefined ? "--min-sessions needs a positive whole number"
|
|
65
|
+
: undefined;
|
|
66
|
+
if (badArg) { console.error(`dream: ${badArg}`); return 1; }
|
|
67
|
+
const home = resolve(homeArg ?? notesRoot()); process.env.PI_NOTES_HOME = home; mkdirSync(home, { recursive: true });
|
|
42
68
|
const lockPath = join(home, ".dream.lock"); const stampPath = lastRunPath(lockPath);
|
|
43
|
-
const
|
|
44
|
-
const time = timeGate(stampPath, minHours); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
69
|
+
const time = timeGate(stampPath, minHours ?? 24); console.log(time.reason); if (!a.force && !time.ok) return 0;
|
|
45
70
|
const since = existsSync(stampPath) ? statSync(stampPath).mtimeMs : 0;
|
|
46
|
-
const material = materialGate(home, since, minSessions); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
71
|
+
const material = materialGate(home, since, minSessions ?? 3); console.log(material.reason); if (!a.force && !material.ok) return 0;
|
|
47
72
|
let lock; try { lock = acquireLock(lockPath); } catch (e) { console.log(`lock gate: ${errorMessage(e)}`); return 0; } if (!lock.held) { console.log(lock.reason); return 0; }
|
|
48
73
|
const stamp = new Date(lock.startedAt).toISOString().replace(/[:.]/g, "-"); const reportPath = join(home, "dreams", `${stamp}.md`);
|
|
49
74
|
let succeeded = false;
|
|
@@ -65,7 +90,7 @@ export async function main(argv = process.argv.slice(2), deps: DreamDependencies
|
|
|
65
90
|
const playbookPath = String(a.playbook ?? defaultBook);
|
|
66
91
|
let result: DreamResult;
|
|
67
92
|
try {
|
|
68
|
-
const playbook =
|
|
93
|
+
const playbook = readFileSync(playbookPath, "utf8");
|
|
69
94
|
result = await (deps.runDreamer ?? runDreamer)(playbook, home, { modelPattern, sessionFactory: deps.sessionFactory });
|
|
70
95
|
} catch (e) {
|
|
71
96
|
const message = errorMessage(e);
|
package/src/pi/estimate.ts
CHANGED
|
@@ -21,7 +21,7 @@ export interface ContextUsageEstimate {
|
|
|
21
21
|
lastUsageIndex: number | null;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
function calculateContextTokens(usage: Usage): number {
|
|
25
25
|
return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
26
26
|
}
|
|
27
27
|
|
|
@@ -40,15 +40,15 @@ function estimateTextAndImageContentChars(content: string | Array<TextContent |
|
|
|
40
40
|
return chars;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
function estimateTextTokens(text: string): number {
|
|
44
44
|
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number {
|
|
48
48
|
return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
function estimateMessageTokens(message: Message): number {
|
|
52
52
|
let chars = 0;
|
|
53
53
|
if (message.role === "system") {
|
|
54
54
|
return (
|
package/src/pi/history.ts
CHANGED
|
@@ -27,14 +27,10 @@ function isToolCall(part: unknown): part is ToolCall {
|
|
|
27
27
|
return typeof part === "object" && part !== null && (part as { type?: unknown }).type === "toolCall";
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
function mappedMessage(message: AgentMessage): boolean {
|
|
31
|
-
return mapRole(message.role) !== undefined;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
30
|
/** Seq allocation depends on entry kind and role, never on visible content. */
|
|
35
31
|
function sequenceCount(entry: SessionEntry): number {
|
|
36
32
|
if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "custom_message") return 1;
|
|
37
|
-
if (entry.type !== "message" ||
|
|
33
|
+
if (entry.type !== "message" || mapRole(entry.message.role) === undefined) return 0;
|
|
38
34
|
if (entry.message.role !== "assistant" || !Array.isArray(entry.message.content)) return 1;
|
|
39
35
|
return 1 + entry.message.content.filter(isToolCall).length;
|
|
40
36
|
}
|
package/src/pi/notes/adapter.ts
CHANGED
|
@@ -11,7 +11,7 @@ export function notesRoot(): string {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
/** Translate the current Pi runtime into a fresh, explicit identity snapshot. */
|
|
14
|
-
export function agentSlug(
|
|
14
|
+
export function agentSlug(): string {
|
|
15
15
|
return slugify(process.env.PI_NOTES_AGENT ?? "anonymous");
|
|
16
16
|
}
|
|
17
17
|
|
|
@@ -27,7 +27,7 @@ export function notesIdentityFromPi(ctx: ExtensionContext, home = notesRoot()):
|
|
|
27
27
|
home,
|
|
28
28
|
sessionId: ctx.sessionManager.getSessionId(),
|
|
29
29
|
projectKey: projectKey(ctx.cwd),
|
|
30
|
-
agent: agentSlug(
|
|
30
|
+
agent: agentSlug(),
|
|
31
31
|
model: modelSlug(ctx),
|
|
32
32
|
};
|
|
33
33
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { BOOT_TYPE, CONTINUATION_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
|
|
4
|
-
import { CONTINUATION } from "
|
|
5
|
-
import { currentWindowId, isWindowBootEntry, isWindowMarker, previousWindowId, type WindowMarker } from "../window.js";
|
|
4
|
+
import { CONTINUATION } from "../../budget/text.js";
|
|
5
|
+
import { currentWindowId, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker, previousWindowId, type WindowMarker } from "../window.js";
|
|
6
6
|
import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "../boot.js";
|
|
7
7
|
|
|
8
8
|
export type ResetTailState = { readonly boot: boolean; readonly continuation: boolean };
|
|
@@ -13,7 +13,7 @@ export function isWindowContinuationEntry(entry: SessionEntry): boolean {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
/** The single continuation sender: the only reset prose persisted for a window. */
|
|
16
|
-
|
|
16
|
+
function sendContinuation(pi: ExtensionAPI): void {
|
|
17
17
|
pi.sendMessage(
|
|
18
18
|
{ customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
|
|
19
19
|
{ triggerTurn: false },
|
|
@@ -74,7 +74,7 @@ export function inspectResetTail(ctx: ExtensionContext, markerId: string, window
|
|
|
74
74
|
continuation = true;
|
|
75
75
|
continue;
|
|
76
76
|
}
|
|
77
|
-
if (
|
|
77
|
+
if (isForeignResetTailEntry(entry)) {
|
|
78
78
|
return undefined;
|
|
79
79
|
}
|
|
80
80
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SessionReader } from "../session-reader.js";
|
|
2
|
-
import { isCheckpointBackedReset, isWindowBootEntry, isWindowMarker } from "../window.js";
|
|
2
|
+
import { isCheckpointBackedReset, isForeignResetTailEntry, isWindowBootEntry, isWindowMarker } from "../window.js";
|
|
3
3
|
import { isWindowContinuationEntry } from "./artifacts.js";
|
|
4
4
|
|
|
5
5
|
/**
|
|
@@ -20,7 +20,7 @@ export function resetBoundaryCommitted(ctx: SessionReader, markerId: string, win
|
|
|
20
20
|
continue;
|
|
21
21
|
}
|
|
22
22
|
if (isWindowContinuationEntry(entry)) return boot && entry.type === "custom_message" && entry.display === false;
|
|
23
|
-
if (
|
|
23
|
+
if (isForeignResetTailEntry(entry)) return false;
|
|
24
24
|
}
|
|
25
25
|
return false;
|
|
26
26
|
}
|
package/src/pi/runtime.ts
CHANGED
|
@@ -8,16 +8,14 @@ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, i
|
|
|
8
8
|
import { registerResetLifecycle } from "./reset/lifecycle.js";
|
|
9
9
|
import { buildResetDrafts } from "./reset/artifacts.js";
|
|
10
10
|
import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
|
|
11
|
-
import { WARNING_CONTENT } from "
|
|
11
|
+
import { WARNING_CONTENT } from "../budget/text.js";
|
|
12
12
|
import { ensureBoot, type IncompleteNotesNotifier } from "./boot.js";
|
|
13
13
|
import { errorMessage } from "../error-message.js";
|
|
14
14
|
|
|
15
15
|
function readPackageVersion(): string {
|
|
16
16
|
for (const up of ["../../package.json", "../../../package.json"]) {
|
|
17
|
-
try {
|
|
18
|
-
|
|
19
|
-
if (parsed.version) return parsed.version;
|
|
20
|
-
} catch { /* try the next candidate */ }
|
|
17
|
+
try { const { version } = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8")) as { version?: string }; if (version) return version; }
|
|
18
|
+
catch { /* try the next candidate */ }
|
|
21
19
|
}
|
|
22
20
|
return "dev";
|
|
23
21
|
}
|
|
@@ -59,7 +57,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
59
57
|
const homes = snapshot.unavailable.map((home) => home.label).join(", ");
|
|
60
58
|
ctx.ui.notify(`🥣 Some notes didn't load: ${homes}`, "warning");
|
|
61
59
|
};
|
|
62
|
-
const budget = registerBudget(pi, () => enabled, settingsManager
|
|
60
|
+
const budget = registerBudget(pi, () => enabled, settingsManager);
|
|
63
61
|
|
|
64
62
|
pi.on("session_start", async (_event, ctx) => {
|
|
65
63
|
const generation = ++lifecycleGeneration;
|
|
@@ -124,6 +122,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
124
122
|
enabled = false;
|
|
125
123
|
lifecycleGeneration++;
|
|
126
124
|
pendingResetNotices.clear();
|
|
125
|
+
incompleteNotesNotified.clear();
|
|
126
|
+
missingBootNotice = undefined;
|
|
127
127
|
budget.clear();
|
|
128
128
|
resets.clear();
|
|
129
129
|
} else if (arg !== "") {
|
|
@@ -176,7 +176,7 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
176
176
|
description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
|
|
177
177
|
parameters: Type.Object({}, { additionalProperties: false }),
|
|
178
178
|
async execute(_id, _params, _signal, _update, ctx) {
|
|
179
|
-
if (!enabled) return output({ error: "notesoup is off
|
|
179
|
+
if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
|
|
180
180
|
return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
|
|
181
181
|
},
|
|
182
182
|
}));
|
|
@@ -194,4 +194,5 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
|
|
|
194
194
|
},
|
|
195
195
|
budget,
|
|
196
196
|
});
|
|
197
|
+
budget.setCloseOut((windowId) => resets.closeOut(windowId, "automatic"));
|
|
197
198
|
}
|
package/src/pi/thresholds.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { deriveThresholds, type ResolvedThresholds } from "../budget/policy.js";
|
|
2
2
|
import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { DEFAULT_RESERVE_TOKENS
|
|
3
|
+
import { DEFAULT_RESERVE_TOKENS } from "../budget/constants.js";
|
|
4
4
|
import { mergeNotesoupSettings } from "../settings.js";
|
|
5
5
|
import { errorMessage } from "../error-message.js";
|
|
6
6
|
|
|
@@ -32,18 +32,12 @@ function readThresholdSettingsFromManager(ctx: ExtensionContext, settingsManager
|
|
|
32
32
|
*/
|
|
33
33
|
export function readThresholdSettings(ctx: ExtensionContext, settingsManager?: SettingsManager): ThresholdSettingsResolution {
|
|
34
34
|
try {
|
|
35
|
-
|
|
36
|
-
return readThresholdSettingsFromManager(
|
|
37
|
-
ctx,
|
|
38
|
-
SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }),
|
|
39
|
-
);
|
|
35
|
+
const manager = settingsManager ?? SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
|
|
36
|
+
return readThresholdSettingsFromManager(ctx, manager);
|
|
40
37
|
} catch (error) {
|
|
41
38
|
return {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
reserve: DEFAULT_RESERVE_TOKENS,
|
|
45
|
-
warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
|
|
46
|
-
},
|
|
39
|
+
// The same derivation over Pi's default reserve, so the fallback cannot drift from it.
|
|
40
|
+
thresholds: deriveThresholds(DEFAULT_RESERVE_TOKENS, {}).thresholds,
|
|
47
41
|
automatic: true,
|
|
48
42
|
warnings: [`🥣 Couldn't read settings · using defaults (${errorMessage(error)})`],
|
|
49
43
|
};
|
package/src/pi/tool-result.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { Static, TSchema } from "typebox";
|
|
|
6
6
|
import { wireResult, type Operation, type Outcome, type Renderer } from "../tools/result.js";
|
|
7
7
|
|
|
8
8
|
/** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
|
|
9
|
-
|
|
9
|
+
function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined> {
|
|
10
10
|
return {
|
|
11
11
|
content: [{ type: "text", text: render(outcome) }],
|
|
12
12
|
structuredContent: wireResult(outcome) as unknown as JsonValue,
|
|
@@ -16,8 +16,8 @@ export function piOperationResult<TData>(render: Renderer<TData>, outcome: Outco
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
export type ToolNamespace = { name: string; description: string };
|
|
19
|
-
export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See
|
|
20
|
-
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See
|
|
19
|
+
export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
|
|
20
|
+
export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
|
|
21
21
|
|
|
22
22
|
/** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
|
|
23
23
|
export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
|
package/src/pi/window.ts
CHANGED
|
@@ -71,6 +71,14 @@ function hasWindowId(details: unknown, windowId: string): boolean {
|
|
|
71
71
|
(details as { windowId: string }).windowId === windowId;
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/**
|
|
75
|
+
* An entry that cannot appear between a reset marker and its boot/continuation without
|
|
76
|
+
* breaking the closed reset shape. Shared so confirmation and repair cannot drift apart.
|
|
77
|
+
*/
|
|
78
|
+
export function isForeignResetTailEntry(entry: SessionEntry): boolean {
|
|
79
|
+
return isWindowMarker(entry) || entry.type === "message" || entry.type === "custom_message" || entry.type === "compaction" || entry.type === "branch_summary";
|
|
80
|
+
}
|
|
81
|
+
|
|
74
82
|
/** Match a provider-facing boot message, optionally by window identity. */
|
|
75
83
|
export function isWindowBoot(message: AgentMessage, windowId?: string): boolean {
|
|
76
84
|
return message.role === "custom" && message.customType === BOOT_TYPE && (windowId === undefined || hasWindowId(message.details, windowId));
|
package/src/settings.ts
CHANGED
|
@@ -2,21 +2,38 @@ export const NOTESOUP_SETTINGS_KEY = "notesoup";
|
|
|
2
2
|
/** Nested under "notesoup": the default dreamer model pattern, overridden by CLI --dreamer. */
|
|
3
3
|
export const NOTESOUP_DREAMER_KEY = "dreamer";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The one notesoup settings shape both hosts read. `reminderMarginTokens` is Pi's early
|
|
7
|
+
* reminder margin; `resetMarginTokens` and `warningRunwayTokens` are the Claude mod's
|
|
8
|
+
* margins against Claude's own auto-compact point (see src/claude/thresholds.ts). A host
|
|
9
|
+
* ignores the keys it does not use; every value is validated where it is consumed.
|
|
10
|
+
*/
|
|
11
|
+
export type NotesoupSettings = {
|
|
12
|
+
reminderMarginTokens?: unknown;
|
|
13
|
+
resetMarginTokens?: unknown;
|
|
14
|
+
warningRunwayTokens?: unknown;
|
|
15
|
+
dreamer?: unknown;
|
|
16
|
+
};
|
|
6
17
|
|
|
7
|
-
|
|
18
|
+
/** A plain settings object; arrays and null are not one. */
|
|
19
|
+
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
8
20
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
21
|
}
|
|
10
22
|
|
|
11
23
|
/** Read the raw "notesoup" object from one parsed settings scope. */
|
|
12
24
|
function notesoupSettings(settings: unknown): Record<string, unknown> {
|
|
13
|
-
if (!
|
|
25
|
+
if (!isPlainObject(settings)) return {};
|
|
14
26
|
const value = settings[NOTESOUP_SETTINGS_KEY];
|
|
15
|
-
return
|
|
27
|
+
return isPlainObject(value) ? value : {};
|
|
16
28
|
}
|
|
17
29
|
|
|
18
30
|
/** Merge the global and project "notesoup" objects per key; project wins, mirroring Pi's deep merge. */
|
|
19
31
|
export function mergeNotesoupSettings(globalSettings: unknown, projectSettings: unknown): NotesoupSettings {
|
|
20
32
|
const merged = { ...notesoupSettings(globalSettings), ...notesoupSettings(projectSettings) };
|
|
21
|
-
return {
|
|
33
|
+
return {
|
|
34
|
+
reminderMarginTokens: merged.reminderMarginTokens,
|
|
35
|
+
resetMarginTokens: merged.resetMarginTokens,
|
|
36
|
+
warningRunwayTokens: merged.warningRunwayTokens,
|
|
37
|
+
dreamer: merged.dreamer,
|
|
38
|
+
};
|
|
22
39
|
}
|
package/src/tools/history.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Host-neutral history operations: one bounded payload for text and structured results. */
|
|
2
2
|
import { Type, type Static } from "typebox";
|
|
3
|
-
import { HISTORY_PREVIEW_CHARS } from "./output.js";
|
|
3
|
+
import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
|
|
4
4
|
import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
|
|
5
5
|
import { historyRoles, searchQuery } from "./schema.js";
|
|
6
6
|
import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
|
|
@@ -54,10 +54,6 @@ function renderPageItem(item: HistoryPageItem): string {
|
|
|
54
54
|
return lines.join("\n");
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
function isFoldedRow(item: HistoryPageItem | HistoryFoldedRow): item is HistoryFoldedRow {
|
|
58
|
-
return "folded" in item;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
57
|
function renderFoldedRow(row: HistoryFoldedRow): string {
|
|
62
58
|
const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
|
|
63
59
|
const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
|
|
@@ -66,8 +62,8 @@ function renderFoldedRow(row: HistoryFoldedRow): string {
|
|
|
66
62
|
|
|
67
63
|
function renderPage(page: HistoryPage): string {
|
|
68
64
|
// An empty selection has no anchors either, so it would otherwise render as nothing at all.
|
|
69
|
-
if (page.items.length === 0) return "
|
|
70
|
-
const body = page.items.map((item) => (
|
|
65
|
+
if (page.items.length === 0) return "No events match these filters.";
|
|
66
|
+
const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
|
|
71
67
|
const cursors = [
|
|
72
68
|
page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
|
|
73
69
|
page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
|
|
@@ -94,7 +90,7 @@ const MAX_REPORTED_WINDOWS = 5;
|
|
|
94
90
|
|
|
95
91
|
/** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
|
|
96
92
|
function knownWindowSuffix(known: string[]): string {
|
|
97
|
-
return known.length === 0 ? "" : `;
|
|
93
|
+
return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
|
|
98
94
|
}
|
|
99
95
|
|
|
100
96
|
export const PREVIOUS_WINDOW = "@previous";
|
|
@@ -105,13 +101,13 @@ function resolveWindowId(projection: HistoryProjection, windowId: string | undef
|
|
|
105
101
|
const previous = projection.windows.at(-2);
|
|
106
102
|
if (previous !== undefined) return { ok: true, window_id: previous.windowId };
|
|
107
103
|
const known = projection.windows.map((current) => current.windowId);
|
|
108
|
-
return { ok: false, outcome: failure("unknown_window_id", `
|
|
104
|
+
return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
|
|
109
105
|
}
|
|
110
106
|
|
|
111
107
|
function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
|
|
112
108
|
const badWindow = unknownWindowId(projection, params);
|
|
113
109
|
if (!badWindow) return undefined;
|
|
114
|
-
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}
|
|
110
|
+
return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
|
|
115
111
|
}
|
|
116
112
|
|
|
117
113
|
/* ------------------------------------------------------------------ history_windows */
|
|
@@ -139,14 +135,14 @@ export const historyWindows: Operation<typeof historyWindowsParameters, HistoryW
|
|
|
139
135
|
data.windows.push(row);
|
|
140
136
|
data.more--;
|
|
141
137
|
}
|
|
142
|
-
return fits(data) ? success(data) : failure("output_too_large",
|
|
138
|
+
return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
|
|
143
139
|
},
|
|
144
140
|
render: (result) => renderOutcome(result, renderWindows),
|
|
145
141
|
};
|
|
146
142
|
|
|
147
143
|
function renderWindows(data: HistoryWindowsData): string {
|
|
148
144
|
const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
|
|
149
|
-
if (data.more > 0) lines.push(`${data.more} more windows not shown; \`history_list\` also
|
|
145
|
+
if (data.more > 0) lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
|
|
150
146
|
return lines.join("\n");
|
|
151
147
|
}
|
|
152
148
|
|
|
@@ -161,8 +157,8 @@ export const historyListParameters = Type.Object({
|
|
|
161
157
|
until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
|
|
162
158
|
from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
|
|
163
159
|
window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
|
|
164
|
-
limit: Type.Optional(Type.Integer({ description: "(optional, default 20) Max events per page; folded rows don't count." })),
|
|
165
|
-
max_chars_per_item: Type.Optional(Type.Integer({ description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
|
|
160
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
|
|
161
|
+
max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
|
|
166
162
|
}, { additionalProperties: false });
|
|
167
163
|
|
|
168
164
|
export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection]> = {
|
|
@@ -197,22 +193,22 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
|
|
|
197
193
|
// Address checks run in one order: past the end of the file, off this branch, then
|
|
198
194
|
// consumed by a pairing. Only the last two can mention what is at the address.
|
|
199
195
|
if (item === undefined && params.seq > projection.highestSeq) {
|
|
200
|
-
return failure("unknown_seq", `
|
|
196
|
+
return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
|
|
201
197
|
}
|
|
202
198
|
if (!projection.branchSeqs.has(params.seq)) {
|
|
203
|
-
return failure("not_on_branch", `
|
|
199
|
+
return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
|
|
204
200
|
}
|
|
205
201
|
if (item === undefined) {
|
|
206
202
|
const callSeq = projection.pairedResults.get(params.seq);
|
|
207
203
|
if (callSeq !== undefined) {
|
|
208
|
-
return failure("not_an_event", `
|
|
204
|
+
return failure("not_an_event", `Seq ${params.seq} is a tool result, shown together with its call; read seq ${callSeq} instead.`);
|
|
209
205
|
}
|
|
210
|
-
return failure("unknown_seq", `
|
|
206
|
+
return failure("unknown_seq", `Seq ${params.seq} holds nothing to read.`);
|
|
211
207
|
}
|
|
212
208
|
const document = eventDocument(item);
|
|
213
209
|
const totalChars = Array.from(document).length;
|
|
214
210
|
if (typeof params.offset_chars === "number" && params.offset_chars > totalChars) {
|
|
215
|
-
return failure("invalid_offset", `
|
|
211
|
+
return failure("invalid_offset", `This event ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
|
|
216
212
|
}
|
|
217
213
|
return readTextWindow(
|
|
218
214
|
document,
|