notesoup 0.44.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +1 -0
  2. package/cordis.patch.yml +14 -0
  3. package/dist/src/boot/text.d.ts +7 -0
  4. package/dist/src/boot/text.js +7 -0
  5. package/dist/src/claude/helper.js +3 -8
  6. package/dist/src/dsh/budget.d.ts +20 -0
  7. package/dist/src/dsh/budget.js +34 -0
  8. package/dist/src/dsh/engine.d.ts +28 -0
  9. package/dist/src/dsh/engine.js +226 -0
  10. package/dist/src/dsh/history.d.ts +6 -0
  11. package/dist/src/dsh/history.js +73 -0
  12. package/dist/src/dsh/index.d.ts +22 -0
  13. package/dist/src/dsh/index.js +63 -0
  14. package/dist/src/dsh/tools.d.ts +3 -0
  15. package/dist/src/dsh/tools.js +111 -0
  16. package/dist/src/dsh/window.d.ts +46 -0
  17. package/dist/src/dsh/window.js +122 -0
  18. package/dist/src/notes/index.d.ts +4 -2
  19. package/dist/src/notes/index.js +4 -1
  20. package/dist/src/notes/paths.d.ts +0 -1
  21. package/dist/src/notes/paths.js +0 -1
  22. package/dist/src/pi/boot.d.ts +0 -5
  23. package/dist/src/pi/boot.js +4 -30
  24. package/dist/src/pi/budget.js +3 -3
  25. package/dist/src/pi/notes/adapter.d.ts +1 -1
  26. package/dist/src/pi/notes/adapter.js +1 -1
  27. package/dist/src/pi/runtime.js +28 -3
  28. package/dist/src/pi/tool-result.d.ts +9 -0
  29. package/dist/src/pi/tool-result.js +4 -0
  30. package/dist/src/tools/notes.d.ts +1 -1
  31. package/dist/src/tools/notes.js +1 -1
  32. package/dist/src/tools/output.d.ts +1 -14
  33. package/dist/src/tools/output.js +1 -9
  34. package/dist/test/dependencies.test.js +63 -1
  35. package/dist/test/dsh-cli.test.d.ts +1 -0
  36. package/dist/test/dsh-cli.test.js +44 -0
  37. package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
  38. package/dist/test/dsh-compaction-parity.test.js +143 -0
  39. package/dist/test/dsh.test.d.ts +1 -0
  40. package/dist/test/dsh.test.js +323 -0
  41. package/dist/test/helpers/dependency-graph.d.ts +3 -3
  42. package/dist/test/helpers/dependency-graph.js +64 -14
  43. package/dist/test/helpers/dsh-messages.d.ts +29 -0
  44. package/dist/test/helpers/dsh-messages.js +33 -0
  45. package/dist/test/helpers/dsh.d.ts +17 -0
  46. package/dist/test/helpers/dsh.js +50 -0
  47. package/dist/test/helpers/extension.js +2 -2
  48. package/dist/test/host-neutral.test.js +5 -0
  49. package/dist/test/notes.integration.test.js +4 -4
  50. package/dist/test/notes.test.js +1 -1
  51. package/docs/architecture.md +4 -1
  52. package/docs/dsh.md +61 -0
  53. package/docs/dsh.profile.patch.yml +34 -0
  54. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  55. package/mods/notesoup/dist/claude/helper.js +649 -651
  56. package/package.json +63 -4
  57. package/src/boot/text.ts +8 -0
  58. package/src/claude/helper.ts +3 -10
  59. package/src/dsh/budget.ts +35 -0
  60. package/src/dsh/engine.ts +186 -0
  61. package/src/dsh/history.ts +57 -0
  62. package/src/dsh/index.ts +69 -0
  63. package/src/dsh/tools.ts +106 -0
  64. package/src/dsh/window.ts +124 -0
  65. package/src/notes/index.ts +4 -2
  66. package/src/notes/paths.ts +0 -1
  67. package/src/pi/boot.ts +4 -33
  68. package/src/pi/budget.ts +3 -3
  69. package/src/pi/notes/adapter.ts +1 -2
  70. package/src/pi/notes/tools.ts +1 -1
  71. package/src/pi/runtime.ts +31 -3
  72. package/src/pi/tool-result.ts +5 -0
  73. package/src/tools/notes.ts +1 -1
  74. package/src/tools/output.ts +1 -10
  75. package/dist/src/pi/tool-names.d.ts +0 -7
  76. package/dist/src/pi/tool-names.js +0 -7
  77. package/mods/pi-context/dist/claude/helper.js +0 -9324
  78. package/src/pi/tool-names.ts +0 -9
@@ -0,0 +1,111 @@
1
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { Check, Errors } from "typebox/value";
4
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
5
+ import { historyList, historyRead, historyWindows } from "../tools/history.js";
6
+ import { success } from "../tools/result.js";
7
+ import { historyProjection } from "./history.js";
8
+ import { notesIdentity } from "./window.js";
9
+ import { measureBudget } from "./budget.js";
10
+ import { preflight } from "./engine.js";
11
+ /** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
12
+ function hostSchema(schema) {
13
+ const value = JSON.parse(JSON.stringify(schema));
14
+ const result = {};
15
+ for (const key of ["type", "required", "additionalProperties", "enum", "const", "description", "title", "default", "examples"])
16
+ if (value[key] !== undefined)
17
+ result[key] = value[key];
18
+ const bounds = ["minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems"].filter((key) => value[key] !== undefined).map((key) => `${key}=${value[key]}`);
19
+ if (bounds.length)
20
+ result.description = [value.description, bounds.join(", ")].filter(Boolean).join("; ");
21
+ if (Array.isArray(value.anyOf))
22
+ result.oneOf = value.anyOf.map((branch) => hostSchema(branch));
23
+ if (value.properties)
24
+ result.properties = Object.fromEntries(Object.entries(value.properties).map(([key, child]) => [key, hostSchema(child)]));
25
+ if (value.items)
26
+ result.items = hostSchema(value.items);
27
+ return result;
28
+ }
29
+ function requireAgent(exec) {
30
+ if (!exec.agent)
31
+ throw new HarnessError("notesoup: this tool needs an agent session; call it from a dsh agent.", "AGENT_REQUIRED");
32
+ exec.signal.throwIfAborted();
33
+ return exec.agent;
34
+ }
35
+ function register(ctx, operation, inputs) {
36
+ ctx.tools.register({
37
+ name: operation.name,
38
+ description: operation.description,
39
+ parameters: hostSchema(operation.parameters),
40
+ output: {
41
+ schema: hostSchema(operation.outputSchema),
42
+ render: (_args, value) => [{ type: "text", text: operation.render(success(value)) }],
43
+ },
44
+ async execute(args, exec) {
45
+ const agent = requireAgent(exec);
46
+ preflight(ctx);
47
+ if (!Check(operation.parameters, args)) {
48
+ const error = Errors(operation.parameters, args).find((problem) => problem.keyword !== "boolean");
49
+ throw new HarnessError(`notesoup: invalid ${operation.name} parameter ${error?.instancePath || "/"}: ${error?.message ?? "invalid value"}; use the tool schema's bounds.`, "INVALID_PARAMS");
50
+ }
51
+ const rest = await inputs(agent);
52
+ exec.signal.throwIfAborted();
53
+ const result = await operation.execute(args, ...rest);
54
+ if (!result.ok)
55
+ throw new HarnessError(operation.render(result), result.error.code);
56
+ return result.data;
57
+ },
58
+ });
59
+ }
60
+ export function registerTools(ctx, engine) {
61
+ const nestedResets = new WeakMap();
62
+ ctx.on("tools/result", (exec, result) => {
63
+ if (!exec.agent)
64
+ return;
65
+ const state = engine.windows.get(exec.agent.session);
66
+ if (exec.name === "clear_memory" && !result.isError && result.value.window_id === state.snapshot.windowId) {
67
+ if (!exec.parent)
68
+ state.pendingReset = true;
69
+ else {
70
+ const roots = nestedResets.get(exec.agent) ?? new Set();
71
+ roots.add(exec.rootCallId);
72
+ nestedResets.set(exec.agent, roots);
73
+ }
74
+ }
75
+ if (!exec.parent && nestedResets.get(exec.agent)?.delete(exec.rootCallId) && !result.isError)
76
+ state.pendingReset = true;
77
+ });
78
+ const identity = (agent) => notesIdentity(agent, engine.config);
79
+ register(ctx, notesWrite, (agent) => [identity(agent)]);
80
+ register(ctx, notesUpdate, (agent) => [identity(agent)]);
81
+ register(ctx, notesRead, (agent) => [identity(agent)]);
82
+ register(ctx, notesList, (agent) => [identity(agent)]);
83
+ register(ctx, notesSearch, (agent) => [identity(agent)]);
84
+ register(ctx, historyList, async (agent) => [await historyProjection(ctx, agent.session.id)]);
85
+ register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)]);
86
+ register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id]);
87
+ ctx.tools.register(defineTool({
88
+ name: "clear_memory",
89
+ description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
90
+ parameters: {},
91
+ output: { schema: { type: "object", properties: { window_id: { type: "string", required: true }, reset_requested: { type: "boolean", required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: `notesoup: reset requested for ${value.window_id}; finish this tool batch, then recover from your notes.` }] },
92
+ async execute(_args, exec) {
93
+ const agent = requireAgent(exec);
94
+ preflight(ctx);
95
+ const state = engine.windows.get(agent.session);
96
+ return { window_id: state.snapshot.windowId, reset_requested: true };
97
+ },
98
+ }));
99
+ ctx.tools.register(defineTool({
100
+ name: "get_context_remaining",
101
+ description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
102
+ parameters: {},
103
+ output: { schema: { type: "object", properties: { remaining_tokens: { oneOf: [{ type: "integer" }, { type: "null" }], required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
104
+ async execute(_args, exec) {
105
+ const agent = requireAgent(exec);
106
+ preflight(ctx);
107
+ const budget = await measureBudget(ctx, agent, engine.config, exec.signal);
108
+ return { remaining_tokens: budget?.countdown ?? null };
109
+ },
110
+ }));
111
+ }
@@ -0,0 +1,46 @@
1
+ import type { Agent } from "@deepseek-ai/dsh-agent";
2
+ import { type Session, type SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import { type NotesIdentity } from "../notes/index.js";
4
+ export declare const WINDOW_RECORD = "plugin:notesoup/window";
5
+ export declare const BOOT_SECTION = "notesoup:boot";
6
+ export type WindowSnapshot = Readonly<{
7
+ version: 1;
8
+ window: number;
9
+ windowId: string;
10
+ openedAt: number;
11
+ boot: string;
12
+ notesDigest: string;
13
+ }>;
14
+ export type WindowState = {
15
+ snapshot: WindowSnapshot;
16
+ pendingReset: boolean;
17
+ warned: boolean;
18
+ reminded: boolean;
19
+ };
20
+ export type NotesConfig = {
21
+ notesHome?: string;
22
+ agentName?: string;
23
+ };
24
+ export declare function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void;
25
+ declare module "@deepseek-ai/dsh-session/types" {
26
+ interface PluginRecordMap {
27
+ "plugin:notesoup/window": WindowSnapshot;
28
+ }
29
+ }
30
+ export declare function windowId(sessionId: string, window: number): string;
31
+ export declare function checkpointText(snapshot: WindowSnapshot): string;
32
+ export declare function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined;
33
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
34
+ export declare function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined;
35
+ export declare function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined;
36
+ /** Identity is extracted here, never in the filesystem domain. */
37
+ export declare function notesIdentity(agent: Pick<Agent, "session" | "options">, config: NotesConfig): NotesIdentity;
38
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
39
+ export declare class Windows {
40
+ readonly config: NotesConfig;
41
+ private states;
42
+ constructor(config: NotesConfig);
43
+ get(session: Session): WindowState;
44
+ adopt(agent: Agent, signal?: AbortSignal): Promise<WindowState>;
45
+ mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot>;
46
+ }
@@ -0,0 +1,122 @@
1
+ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
2
+ import { isCompactCheckpointSource } from "@deepseek-ai/dsh-compaction";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { createHash } from "node:crypto";
6
+ import { loadNotesSnapshot } from "../boot/snapshot.js";
7
+ import { renderBootBlock } from "../boot/render.js";
8
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
9
+ import { CONTINUATION } from "../budget/text.js";
10
+ import { contentText } from "../history/history.js";
11
+ import { projectKey, slugify, snapshotNotesIdentity } from "../notes/index.js";
12
+ export const WINDOW_RECORD = "plugin:notesoup/window";
13
+ export const BOOT_SECTION = "notesoup:boot";
14
+ const BOOT_OPEN = "<notesoup-boot>\n";
15
+ const BOOT_CLOSE = "\n</notesoup-boot>";
16
+ const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
17
+ export function restoreWarnings(state, events) {
18
+ state.warned = false;
19
+ state.reminded = false;
20
+ for (const event of events) {
21
+ if (event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.windowId === state.snapshot.windowId) {
22
+ if (event.data.source.phase === "warning")
23
+ state.warned = true;
24
+ else
25
+ state.reminded = true;
26
+ }
27
+ }
28
+ }
29
+ export function windowId(sessionId, window) { return `dsh:${sessionId}:${window}`; }
30
+ function digest(boot) { return createHash("sha256").update(boot).digest("hex"); }
31
+ export function checkpointText(snapshot) { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
32
+ export function recordSnapshot(event) {
33
+ const record = pluginRecordOf(event);
34
+ if (record?.type !== WINDOW_RECORD || typeof record.data !== "object" || record.data === null)
35
+ return undefined;
36
+ const value = record.data;
37
+ if (value.version !== 1 || !Number.isSafeInteger(value.window) || value.window < 0 || typeof value.windowId !== "string" || typeof value.openedAt !== "number" || typeof value.boot !== "string" || value.notesDigest !== digest(value.boot))
38
+ return undefined;
39
+ return Object.freeze(value);
40
+ }
41
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
42
+ export function checkpointSnapshot(event) {
43
+ if (event.type !== "user/message" || !isCompactCheckpointSource(event.data.source))
44
+ return undefined;
45
+ const text = contentText(event.data.content);
46
+ const end = text.lastIndexOf(CHECKPOINT_END);
47
+ if (end < 0 || !text.startsWith(BOOT_OPEN))
48
+ return undefined;
49
+ return snapshotFromBoot(text.slice(0, end), event.time);
50
+ }
51
+ function systemSnapshot(event) {
52
+ if (event.type !== "system/message")
53
+ return undefined;
54
+ const text = contentText(event.data.message.content);
55
+ const start = text.indexOf(BOOT_OPEN);
56
+ const end = text.lastIndexOf(BOOT_CLOSE);
57
+ if (start < 0 || end < 0)
58
+ return undefined;
59
+ return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
60
+ }
61
+ function snapshotFromBoot(boot, openedAt) {
62
+ const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
63
+ if (!id || !Number.isSafeInteger(Number(id[2])))
64
+ return undefined;
65
+ return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1], openedAt, boot, notesDigest: digest(boot) });
66
+ }
67
+ export function recoverSnapshot(events) {
68
+ let latest;
69
+ for (const event of events) {
70
+ const candidate = checkpointSnapshot(event) ?? recordSnapshot(event) ?? systemSnapshot(event);
71
+ if (candidate && (!latest || candidate.window >= latest.window))
72
+ latest = candidate;
73
+ }
74
+ return latest;
75
+ }
76
+ /** Identity is extracted here, never in the filesystem domain. */
77
+ export function notesIdentity(agent, config) {
78
+ const home = config.notesHome ?? join(homedir(), ".agents", "notes");
79
+ return snapshotNotesIdentity({
80
+ home,
81
+ sessionId: agent.session.id,
82
+ projectKey: projectKey(agent.session.header.cwd ?? process.cwd(), home),
83
+ agent: slugify(config.agentName ?? "dsh"),
84
+ model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
85
+ });
86
+ }
87
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
88
+ export class Windows {
89
+ config;
90
+ states = new WeakMap();
91
+ constructor(config) {
92
+ this.config = config;
93
+ }
94
+ get(session) {
95
+ const state = this.states.get(session);
96
+ if (!state)
97
+ throw Object.assign(new Error("notesoup: window missing; initialize at agent/created before sending a request."), { code: "WINDOW_MISSING" });
98
+ return state;
99
+ }
100
+ async adopt(agent, signal) {
101
+ const existing = this.states.get(agent.session);
102
+ if (existing)
103
+ return existing;
104
+ const restored = recoverSnapshot(agent.session.snapshotEvents());
105
+ const snapshot = restored ?? await this.mint(agent, 0, agent.session.header.createdAt);
106
+ signal?.throwIfAborted();
107
+ if (!restored)
108
+ appendPluginRecord(agent.session, WINDOW_RECORD, snapshot);
109
+ const state = { snapshot, pendingReset: false, warned: false, reminded: false };
110
+ restoreWarnings(state, agent.session.snapshotEvents());
111
+ this.states.set(agent.session, state);
112
+ return state;
113
+ }
114
+ async mint(agent, window, openedAt) {
115
+ const identity = notesIdentity(agent, this.config);
116
+ const notes = await loadNotesSnapshot(identity, openedAt);
117
+ const previous = this.states.get(agent.session)?.snapshot;
118
+ const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
119
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: DEFAULT_BOOT_TOOL_NAMES }) + BOOT_CLOSE;
120
+ return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
121
+ }
122
+ }
@@ -1,5 +1,7 @@
1
1
  export { createNotesStore, noteIdentity } from "./store.js";
2
2
  export { NoteError, type NoteErrorCode } from "./errors.js";
3
- export { projectKey, slugify } from "./paths.js";
4
- export type { NotesIdentity } from "./identity.js";
3
+ export { projectKey } from "./project-home.js";
4
+ export { slugify } from "./paths.js";
5
+ export { snapshotNotesIdentity, type NotesIdentity } from "./identity.js";
6
+ export { isFilesystemError } from "./fs-error.js";
5
7
  export type { EditOperation, EditOptions, NoteChange, NoteEditResult, NoteMatch, NoteMeta, NoteQueryResult, NoteQueryStatus, NoteReadResult, NoteRenameResult, NoteRow, NoteSearchRow, NoteWriteResult, NotesQuery, NotesStore, Origin, Scope, WriteOptions, } from "./store.js";
@@ -1,3 +1,6 @@
1
1
  export { createNotesStore, noteIdentity } from "./store.js";
2
2
  export { NoteError } from "./errors.js";
3
- export { projectKey, slugify } from "./paths.js";
3
+ export { projectKey } from "./project-home.js";
4
+ export { slugify } from "./paths.js";
5
+ export { snapshotNotesIdentity } from "./identity.js";
6
+ export { isFilesystemError } from "./fs-error.js";
@@ -1,4 +1,3 @@
1
- export { projectKey } from "./project-home.js";
2
1
  import type { NotesIdentity } from "./identity.js";
3
2
  export type Scope = "session" | "project" | "human" | "agent" | "model";
4
3
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
@@ -1,6 +1,5 @@
1
1
  import { readdir } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- export { projectKey } from "./project-home.js";
4
3
  import { NoteError, shown } from "./errors.js";
5
4
  /** The one legal home-name shape: lowercase [a-z0-9-] runs separated by single dashes. */
6
5
  export const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -17,8 +17,3 @@ export type BootMessage = {
17
17
  export declare function buildBootMessage(ctx: ExtensionContext, windowId: string, previousId: string | undefined, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean): Promise<BootMessage>;
18
18
  /** Persist one hidden boot message without triggering a model turn. */
19
19
  export declare function sendBoot(pi: ExtensionAPI, boot: BootMessage): void;
20
- /**
21
- * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
22
- * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
23
- */
24
- export declare function ensureBoot(pi: ExtensionAPI, ctx: ExtensionContext, notifyIncompleteNotes?: IncompleteNotesNotifier, isCurrent?: () => boolean): Promise<void>;
@@ -1,11 +1,10 @@
1
- import { PI_TOOL_NAMES } from "./tool-names.js";
1
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
2
2
  import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
3
3
  import { loadNotesSnapshot, unavailableNotesSnapshot } from "../boot/snapshot.js";
4
- import { isFilesystemError } from "../notes/fs-error.js";
4
+ import { isFilesystemError } from "../notes/index.js";
5
5
  import { BOOT_TYPE } from "./entries.js";
6
6
  import { renderBootBlock } from "../boot/render.js";
7
- import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
8
- import { repairResetTail } from "./reset/artifacts.js";
7
+ import { rootWindowId } from "./window.js";
9
8
  /**
10
9
  * Acquire one notes snapshot and build the boot custom message for a window. All identity
11
10
  * fields are captured synchronously before the first filesystem await.
@@ -28,7 +27,7 @@ export async function buildBootMessage(ctx, windowId, previousId, notifyIncomple
28
27
  notifyIncompleteNotes?.(ctx, windowId, notes);
29
28
  return {
30
29
  customType: BOOT_TYPE,
31
- content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
30
+ content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: DEFAULT_BOOT_TOOL_NAMES }),
32
31
  display: false,
33
32
  details: { windowId },
34
33
  };
@@ -37,28 +36,3 @@ export async function buildBootMessage(ctx, windowId, previousId, notifyIncomple
37
36
  export function sendBoot(pi, boot) {
38
37
  pi.sendMessage({ customType: boot.customType, content: boot.content, display: boot.display, details: boot.details }, { triggerTurn: false });
39
38
  }
40
- /**
41
- * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
42
- * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
43
- */
44
- export async function ensureBoot(pi, ctx, notifyIncompleteNotes, isCurrent = () => true) {
45
- const sessionId = ctx.sessionManager.getSessionId();
46
- const reset = currentReset(ctx);
47
- const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
48
- const stillCurrent = () => isCurrent() &&
49
- ctx.signal?.aborted !== true &&
50
- ctx.sessionManager.getSessionId() === sessionId &&
51
- currentWindowId(ctx) === windowId;
52
- if (reset) {
53
- await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
54
- return;
55
- }
56
- if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
57
- return;
58
- const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
59
- if (!stillCurrent())
60
- return;
61
- if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
62
- return;
63
- sendBoot(pi, boot);
64
- }
@@ -1,4 +1,4 @@
1
- import { PI_TOOL_NAMES } from "./tool-names.js";
1
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
2
2
  import { remainingBudget } from "../budget/policy.js";
3
3
  import { Type } from "@earendil-works/pi-ai";
4
4
  import { defineTool } from "@earendil-works/pi-coding-agent";
@@ -8,7 +8,7 @@ import { readThresholdSettings } from "./thresholds.js";
8
8
  import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
10
10
  import { arrangeAnchoredReminders } from "./anchored.js";
11
- import { output } from "../tools/output.js";
11
+ import { output } from "./tool-result.js";
12
12
  /** Remaining tokens in the provider's active window, or null without a usable estimate. */
13
13
  function remainingTokens(ctx) {
14
14
  const usage = windowUsage(ctx);
@@ -154,7 +154,7 @@ export function registerBudget(pi, isEnabled, settingsManager) {
154
154
  if (pendingGuidance?.windowId !== windowId) {
155
155
  if (remaining > reminder)
156
156
  return result();
157
- pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
157
+ pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
158
158
  }
159
159
  return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
160
160
  });
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { NotesIdentity } from "../../notes/identity.js";
2
+ import { type NotesIdentity } from "../../notes/index.js";
3
3
  /** Pi's default notes root; environment access stays on the host side of the library boundary. */
4
4
  export declare function notesRoot(): string;
5
5
  /** Translate the current Pi runtime into a fresh, explicit identity snapshot. */
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join, resolve } from "node:path";
3
- import { projectKey, slugify } from "../../notes/paths.js";
3
+ import { projectKey, slugify } from "../../notes/index.js";
4
4
  /** Pi's default notes root; environment access stays on the host side of the library boundary. */
5
5
  export function notesRoot() {
6
6
  const override = process.env.PI_NOTES_HOME;
@@ -3,13 +3,13 @@ import { resetBoundaryCommitted } from "./reset/committed.js";
3
3
  import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
4
  import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
5
  import { registerBudget } from "./budget.js";
6
- import { output } from "../tools/output.js";
6
+ import { output } from "./tool-result.js";
7
7
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
- import { buildResetDrafts } from "./reset/artifacts.js";
9
+ import { buildResetDrafts, repairResetTail } from "./reset/artifacts.js";
10
10
  import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
11
  import { WARNING_CONTENT } from "../budget/text.js";
12
- import { ensureBoot } from "./boot.js";
12
+ import { buildBootMessage, sendBoot } from "./boot.js";
13
13
  import { errorMessage } from "../error-message.js";
14
14
  function readPackageVersion() {
15
15
  for (const up of ["../../package.json", "../../../package.json"]) {
@@ -26,6 +26,31 @@ const buildLabel = `v${readPackageVersion()}`;
26
26
  function branchHasWindowMarker(ctx, fromId) {
27
27
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
28
28
  }
29
+ /**
30
+ * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
31
+ * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
32
+ */
33
+ async function ensureBoot(pi, ctx, notifyIncompleteNotes, isCurrent = () => true) {
34
+ const sessionId = ctx.sessionManager.getSessionId();
35
+ const reset = currentReset(ctx);
36
+ const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
37
+ const stillCurrent = () => isCurrent() &&
38
+ ctx.signal?.aborted !== true &&
39
+ ctx.sessionManager.getSessionId() === sessionId &&
40
+ currentWindowId(ctx) === windowId;
41
+ if (reset) {
42
+ await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
43
+ return;
44
+ }
45
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
46
+ return;
47
+ const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
48
+ if (!stillCurrent())
49
+ return;
50
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId)))
51
+ return;
52
+ sendBoot(pi, boot);
53
+ }
29
54
  /** Register the context-window runtime and its context-owned commands/tools. */
30
55
  export function registerContext(pi, settingsManager) {
31
56
  let enabled = true;
@@ -2,6 +2,15 @@
2
2
  import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static, TSchema } from "typebox";
4
4
  import { type Operation, type Outcome } from "../tools/result.js";
5
+ /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
6
+ export declare function output(value: unknown, details?: unknown, terminate?: boolean): {
7
+ content: {
8
+ type: "text";
9
+ text: string;
10
+ }[];
11
+ details: unknown;
12
+ terminate: boolean;
13
+ };
5
14
  export type ToolNamespace = {
6
15
  name: string;
7
16
  description: string;
@@ -1,6 +1,10 @@
1
1
  /** Pi transport for host-neutral operations. */
2
2
  import { defineTool } from "@earendil-works/pi-coding-agent";
3
3
  import { wireResult } from "../tools/result.js";
4
+ /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
5
+ export function output(value, details, terminate = false) {
6
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
7
+ }
4
8
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
9
  function piOperationResult(render, outcome) {
6
10
  return {
@@ -149,7 +149,7 @@ export declare const notesUpdate: {
149
149
  code: Type.TString;
150
150
  }>]>;
151
151
  readonly executionMode: "sequential";
152
- readonly execute: (params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string) => Promise<Outcome<NotesUpdateData>>;
152
+ readonly execute: (params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff?: (change: NoteChange) => string) => Promise<Outcome<NotesUpdateData>>;
153
153
  readonly render: typeof renderUpdate;
154
154
  };
155
155
  export declare const notesReadParameters: Type.TObject<{
@@ -230,7 +230,7 @@ export const notesUpdate = {
230
230
  name: "notes_update", label: "Notes update",
231
231
  description: `Edit a note, change its origin or crumpled state, or move it. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
232
232
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
233
- async execute(params, identity, renderDiff) {
233
+ async execute(params, identity, renderDiff = (change) => change.kind === "none" ? "" : `note ${change.kind}`) {
234
234
  try {
235
235
  const store = createNotesStore(identity);
236
236
  // Empty filler is not a request: models that pass every parameter get the edit path.
@@ -1,4 +1,4 @@
1
- /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
1
+ /** Shared output budget primitives. */
2
2
  export declare const TOOL_OUTPUT_MAX_BYTES: number;
3
3
  /** The per-call limit as the model reads it in refusals. */
4
4
  export declare const TOOL_OUTPUT_LIMIT = "32 KB";
@@ -7,16 +7,3 @@ export declare const MAX_READ_WINDOW_CHARS = 50000;
7
7
  export declare const HISTORY_PREVIEW_CHARS = 1200;
8
8
  /** Longest fitting code-point prefix, without inserted markers. Callers report omissions. */
9
9
  export declare function prefixFit(text: string, fits: (content: string) => boolean): string;
10
- /**
11
- * Encode a structured result through the common tool result boundary. `details` is slim
12
- * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
13
- * undefined unless the tool has metadata worth persisting.
14
- */
15
- export declare function output(value: unknown, details?: unknown, terminate?: boolean): {
16
- content: {
17
- type: "text";
18
- text: string;
19
- }[];
20
- details: unknown;
21
- terminate: boolean;
22
- };
@@ -1,4 +1,4 @@
1
- /** Budget primitives. Notes/history use result.ts; reset/budget tools retain output(). */
1
+ /** Shared output budget primitives. */
2
2
  export const TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
3
3
  /** The per-call limit as the model reads it in refusals. */
4
4
  export const TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
@@ -23,11 +23,3 @@ export function prefixFit(text, fits) {
23
23
  }
24
24
  return chars.slice(0, low).join("");
25
25
  }
26
- /**
27
- * Encode a structured result through the common tool result boundary. `details` is slim
28
- * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
29
- * undefined unless the tool has metadata worth persisting.
30
- */
31
- export function output(value, details, terminate = false) {
32
- return { content: [{ type: "text", text: JSON.stringify(value) }], details, terminate };
33
- }