notesoup 0.45.0 → 0.45.2

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 (72) hide show
  1. package/dist/src/boot/text.d.ts +7 -0
  2. package/dist/src/boot/text.js +7 -0
  3. package/dist/src/budget/text.d.ts +4 -2
  4. package/dist/src/budget/text.js +4 -2
  5. package/dist/src/claude/helper.js +3 -8
  6. package/dist/src/dsh/engine.d.ts +6 -0
  7. package/dist/src/dsh/engine.js +34 -1
  8. package/dist/src/dsh/index.js +1 -1
  9. package/dist/src/dsh/tools.d.ts +1 -1
  10. package/dist/src/dsh/tools.js +2 -2
  11. package/dist/src/dsh/window.d.ts +1 -1
  12. package/dist/src/dsh/window.js +4 -6
  13. package/dist/src/notes/index.d.ts +4 -2
  14. package/dist/src/notes/index.js +4 -1
  15. package/dist/src/notes/paths.d.ts +0 -1
  16. package/dist/src/notes/paths.js +0 -1
  17. package/dist/src/pi/boot.d.ts +0 -5
  18. package/dist/src/pi/boot.js +4 -30
  19. package/dist/src/pi/budget.js +3 -3
  20. package/dist/src/pi/entries.d.ts +1 -0
  21. package/dist/src/pi/entries.js +1 -0
  22. package/dist/src/pi/notes/adapter.d.ts +1 -1
  23. package/dist/src/pi/notes/adapter.js +1 -1
  24. package/dist/src/pi/reset/artifacts.d.ts +6 -2
  25. package/dist/src/pi/reset/artifacts.js +14 -3
  26. package/dist/src/pi/reset/lifecycle.d.ts +6 -2
  27. package/dist/src/pi/reset/lifecycle.js +28 -18
  28. package/dist/src/pi/runtime.js +33 -8
  29. package/dist/src/pi/tool-result.d.ts +9 -0
  30. package/dist/src/pi/tool-result.js +4 -0
  31. package/dist/src/tools/notes.d.ts +1 -1
  32. package/dist/src/tools/notes.js +1 -1
  33. package/dist/src/tools/output.d.ts +1 -14
  34. package/dist/src/tools/output.js +1 -9
  35. package/dist/test/dependencies.test.js +53 -17
  36. package/dist/test/dsh.test.js +1 -1
  37. package/dist/test/helpers/dependency-graph.d.ts +3 -3
  38. package/dist/test/helpers/dependency-graph.js +64 -14
  39. package/dist/test/helpers/extension.js +2 -2
  40. package/dist/test/host-neutral.test.js +5 -0
  41. package/dist/test/notes.integration.test.js +4 -4
  42. package/dist/test/notes.test.js +1 -1
  43. package/dist/test/reset-lifecycle.test.js +47 -3
  44. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  45. package/mods/notesoup/dist/claude/helper.js +166 -166
  46. package/package.json +1 -1
  47. package/src/boot/text.ts +8 -0
  48. package/src/budget/text.ts +5 -2
  49. package/src/claude/helper.ts +3 -10
  50. package/src/dsh/engine.ts +27 -1
  51. package/src/dsh/index.ts +1 -1
  52. package/src/dsh/tools.ts +2 -3
  53. package/src/dsh/window.ts +4 -6
  54. package/src/notes/index.ts +4 -2
  55. package/src/notes/paths.ts +0 -1
  56. package/src/pi/boot.ts +4 -33
  57. package/src/pi/budget.ts +3 -3
  58. package/src/pi/entries.ts +1 -0
  59. package/src/pi/notes/adapter.ts +1 -2
  60. package/src/pi/notes/tools.ts +1 -1
  61. package/src/pi/reset/artifacts.ts +15 -2
  62. package/src/pi/reset/lifecycle.ts +34 -21
  63. package/src/pi/runtime.ts +36 -8
  64. package/src/pi/tool-result.ts +5 -0
  65. package/src/tools/notes.ts +1 -1
  66. package/src/tools/output.ts +1 -10
  67. package/dist/src/dsh/preflight.d.ts +0 -8
  68. package/dist/src/dsh/preflight.js +0 -35
  69. package/dist/src/pi/tool-names.d.ts +0 -7
  70. package/dist/src/pi/tool-names.js +0 -7
  71. package/src/dsh/preflight.ts +0 -29
  72. package/src/pi/tool-names.ts +0 -9
package/src/dsh/engine.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { Context } from "@deepseek-ai/cordis";
3
+ import type {} from "@deepseek-ai/cordis-plugin-loader";
3
4
  import type { CommandId } from "@deepseek-ai/dsh-commands/brand";
4
5
  import { CompactionEngine, CompactionId, ManualCompactionError, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from "@deepseek-ai/dsh-compaction";
5
6
  import { createUserMessage, type ContentBlock } from "@deepseek-ai/dsh-llm";
6
7
  import { appendPluginRecord, type Session, type SessionSeq } from "@deepseek-ai/dsh-session";
7
8
  import { measureBudget, type BudgetConfig } from "./budget.js";
8
9
  import { checkpointText, Windows, WINDOW_RECORD, type NotesConfig } from "./window.js";
9
- import { preflight } from "./preflight.js";
10
10
 
11
11
  export type EngineConfig = NotesConfig & Partial<BudgetConfig>;
12
12
  export type ResolvedConfig = NotesConfig & BudgetConfig;
@@ -158,3 +158,29 @@ export class NotesoupCompactionEngine extends CompactionEngine {
158
158
  }
159
159
  }
160
160
  export default NotesoupCompactionEngine;
161
+
162
+ export class PreflightError extends Error {
163
+ constructor(readonly code: string, message: string) { super(`notesoup: ${message}`); }
164
+ }
165
+
166
+ /** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
167
+ export function preflight(ctx: Context): NotesoupCompactionEngine {
168
+ for (const [service, method] of [["systemPrompt", "section"], ["tools", "register"], ["sessionQuery", "readSession"], ["tokenMeter", "measure"], ["llm", "resolveModelInfo"]] as const) {
169
+ const mounted = ctx.get(service) as unknown as Record<string, unknown> | undefined;
170
+ if (typeof mounted?.[method] !== "function") throw new PreflightError("CAPABILITY", `${service}.${method} is unavailable; enable that service in the profile before using notesoup.`);
171
+ }
172
+ const engine = ctx.get("compaction");
173
+ if (!(engine instanceof NotesoupCompactionEngine)) throw new PreflightError("ENGINE", "ctx.compaction must be NotesoupCompactionEngine; disable compaction-basic and enable the notesoup-engine row, then restart dsh.");
174
+ const loader = ctx.get("loader");
175
+ if (loader) {
176
+ if (typeof loader.entries !== "function") throw new PreflightError("CAPABILITY", "loader.entries is unavailable; this profile cannot be checked for two engines.");
177
+ for (const entry of loader.entries()) {
178
+ if ((entry.options.id === "compaction-basic" || /(?:^|\/)dsh-compaction-basic$/.test(entry.options.name)) && !entry.disabled) throw new PreflightError("DOUBLE_ENGINE", "compaction-basic is enabled; set disabled: true on that profile row and restart dsh.");
179
+ }
180
+ }
181
+ for (const [callback, runtime] of ctx.registry.entries()) {
182
+ if (callback.name === "BasicCompactionEngine" && runtime.fibers.length > 0) throw new PreflightError("DOUBLE_ENGINE", "a BasicCompactionEngine fiber is mounted; remove it before starting notesoup.");
183
+ }
184
+ if (!engine.automaticListenerPresent) throw new PreflightError("AUTO_LISTENER", "the automatic reset listener is missing; reload notesoup-engine before sending another request.");
185
+ return engine;
186
+ }
package/src/dsh/index.ts CHANGED
@@ -4,7 +4,7 @@ import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
4
  import { CONTINUATION, WARNING_PROMPT, tokenBudgetGuidance } from "../budget/text.js";
5
5
  import { measureBudget } from "./budget.js";
6
6
  import { BOOT_SECTION, restoreWarnings } from "./window.js";
7
- import { preflight } from "./preflight.js";
7
+ import { preflight } from "./engine.js";
8
8
  import { registerTools } from "./tools.js";
9
9
 
10
10
  export const name = "notesoup-dsh";
package/src/dsh/tools.ts CHANGED
@@ -10,8 +10,7 @@ import { success, type Operation } from "../tools/result.js";
10
10
  import { historyProjection } from "./history.js";
11
11
  import { notesIdentity } from "./window.js";
12
12
  import { measureBudget } from "./budget.js";
13
- import { preflight } from "./preflight.js";
14
- import type { NotesoupCompactionEngine } from "./engine.js";
13
+ import { preflight, type NotesoupCompactionEngine } from "./engine.js";
15
14
 
16
15
  /** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
17
16
  function hostSchema(schema: TSchema): JsonSchemaNode {
@@ -73,7 +72,7 @@ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): v
73
72
  });
74
73
  const identity = (agent: Agent) => notesIdentity(agent, engine.config);
75
74
  register(ctx, notesWrite, (agent) => [identity(agent)] as const);
76
- register(ctx, notesUpdate, (agent) => [identity(agent), (change) => change.kind === "none" ? "" : `note ${change.kind}`] as const);
75
+ register(ctx, notesUpdate, (agent) => [identity(agent)] as const);
77
76
  register(ctx, notesRead, (agent) => [identity(agent)] as const);
78
77
  register(ctx, notesList, (agent) => [identity(agent)] as const);
79
78
  register(ctx, notesSearch, (agent) => [identity(agent)] as const);
package/src/dsh/window.ts CHANGED
@@ -6,18 +6,16 @@ import { join } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
7
  import { loadNotesSnapshot } from "../boot/snapshot.js";
8
8
  import { renderBootBlock } from "../boot/render.js";
9
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
9
10
  import { CONTINUATION } from "../budget/text.js";
10
11
  import { contentText } from "../history/history.js";
11
- import { slugify } from "../notes/paths.js";
12
- import { resolveProjectHome } from "../notes/project-home.js";
13
- import { snapshotNotesIdentity, type NotesIdentity } from "../notes/identity.js";
12
+ import { projectKey, slugify, snapshotNotesIdentity, type NotesIdentity } from "../notes/index.js";
14
13
 
15
14
  export const WINDOW_RECORD = "plugin:notesoup/window";
16
15
  export const BOOT_SECTION = "notesoup:boot";
17
16
  const BOOT_OPEN = "<notesoup-boot>\n";
18
17
  const BOOT_CLOSE = "\n</notesoup-boot>";
19
18
  const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
20
- const TOOLS = { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "clear_memory" };
21
19
  export type WindowSnapshot = Readonly<{ version: 1; window: number; windowId: string; openedAt: number; boot: string; notesDigest: string }>;
22
20
  export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean };
23
21
  export type NotesConfig = { notesHome?: string; agentName?: string };
@@ -88,7 +86,7 @@ export function notesIdentity(agent: Pick<Agent, "session" | "options">, config:
88
86
  return snapshotNotesIdentity({
89
87
  home,
90
88
  sessionId: agent.session.id,
91
- projectKey: resolveProjectHome(agent.session.header.cwd ?? process.cwd(), home).name,
89
+ projectKey: projectKey(agent.session.header.cwd ?? process.cwd(), home),
92
90
  agent: slugify(config.agentName ?? "dsh"),
93
91
  model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
94
92
  });
@@ -120,7 +118,7 @@ export class Windows {
120
118
  const notes = await loadNotesSnapshot(identity, openedAt);
121
119
  const previous = this.states.get(agent.session)?.snapshot;
122
120
  const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
123
- 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: TOOLS }) + BOOT_CLOSE;
121
+ 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;
124
122
  return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
125
123
  }
126
124
  }
@@ -1,7 +1,9 @@
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 {
6
8
  EditOperation,
7
9
  EditOptions,
@@ -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
  import type { NotesIdentity } from "./identity.js";
6
5
 
package/src/pi/boot.ts CHANGED
@@ -1,12 +1,11 @@
1
- import { PI_TOOL_NAMES } from "./tool-names.js";
1
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../boot/text.js";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { agentSlug, modelSlug, notesIdentityFromPi } from "./notes/adapter.js";
4
4
  import { loadNotesSnapshot, unavailableNotesSnapshot, type NotesSnapshot } from "../boot/snapshot.js";
5
- import { isFilesystemError } from "../notes/fs-error.js";
5
+ import { isFilesystemError } from "../notes/index.js";
6
6
  import { BOOT_TYPE } from "./entries.js";
7
7
  import { renderBootBlock } from "../boot/render.js";
8
- import { currentReset, currentWindowId, isWindowBoot, rootWindowId } from "./window.js";
9
- import { repairResetTail } from "./reset/artifacts.js";
8
+ import { rootWindowId } from "./window.js";
10
9
 
11
10
  export type IncompleteNotesNotifier = (ctx: ExtensionContext, windowId: string, snapshot: NotesSnapshot) => void;
12
11
 
@@ -43,7 +42,7 @@ export async function buildBootMessage(
43
42
  if (isCurrent()) notifyIncompleteNotes?.(ctx, windowId, notes);
44
43
  return {
45
44
  customType: BOOT_TYPE,
46
- content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: PI_TOOL_NAMES }),
45
+ content: renderBootBlock({ agentName, modelName, firstWindowId: rootWindowId(sessionId), currentWindowId: windowId, previousWindowId: previousId, notes, tools: DEFAULT_BOOT_TOOL_NAMES }),
47
46
  display: false,
48
47
  details: { windowId },
49
48
  };
@@ -56,31 +55,3 @@ export function sendBoot(pi: ExtensionAPI, boot: BootMessage): void {
56
55
  { triggerTurn: false },
57
56
  );
58
57
  }
59
-
60
- /**
61
- * Boot entry point for `session_start` / `session_tree`. Ordinary startup ensures one root
62
- * boot; a reset marker instead asks reset-artifact repair to complete its persisted tail.
63
- */
64
- export async function ensureBoot(
65
- pi: ExtensionAPI,
66
- ctx: ExtensionContext,
67
- notifyIncompleteNotes?: IncompleteNotesNotifier,
68
- isCurrent: () => boolean = () => true,
69
- ): Promise<void> {
70
- const sessionId = ctx.sessionManager.getSessionId();
71
- const reset = currentReset(ctx);
72
- const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
73
- const stillCurrent = () => isCurrent() &&
74
- ctx.signal?.aborted !== true &&
75
- ctx.sessionManager.getSessionId() === sessionId &&
76
- currentWindowId(ctx) === windowId;
77
- if (reset) {
78
- await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
79
- return;
80
- }
81
- if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
82
- const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
83
- if (!stillCurrent()) return;
84
- if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
85
- sendBoot(pi, boot);
86
- }
package/src/pi/budget.ts CHANGED
@@ -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, 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";
@@ -8,7 +8,7 @@ import { readThresholdSettings, type ThresholdSettingsResolution } from "./thres
8
8
  import { currentWindowId, hasWindowMessage, isWindowMarker, rootWindowId, windowUsage } from "./window.js";
9
9
  import { tokenBudgetGuidance } from "../budget/text.js";
10
10
  import { arrangeAnchoredReminders, type AnchorDetails } from "./anchored.js";
11
- import { output } from "../tools/output.js";
11
+ import { output } from "./tool-result.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 {
@@ -147,7 +147,7 @@ export function registerBudget(
147
147
  if (hasWindowMessage(ctx, GUIDANCE_TYPE)) return result();
148
148
  if (pendingGuidance?.windowId !== windowId) {
149
149
  if (remaining > reminder) return result();
150
- pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, PI_TOOL_NAMES.wipe) };
150
+ pendingGuidance = { windowId, content: tokenBudgetGuidance(remainingBudget(remaining, warning) ?? 0, DEFAULT_BOOT_TOOL_NAMES.wipe) };
151
151
  }
152
152
  return result({ customType: GUIDANCE_TYPE, content: pendingGuidance.content });
153
153
  });
package/src/pi/entries.ts CHANGED
@@ -5,3 +5,4 @@ export const MANUAL_WIPE_TYPE = "notesoup/manual-wipe";
5
5
  export const RESET_MARKER_TYPE = "notesoup/reset-marker";
6
6
  export const CONTINUATION_TYPE = "notesoup/continuation";
7
7
  export const RESET_PROMPT_TYPE = "notesoup/reset-prompt";
8
+ export const RESET_LAST_WORD_TYPE = "notesoup/reset-last-word";
@@ -1,8 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
- import type { NotesIdentity } from "../../notes/identity.js";
5
- import { projectKey, slugify } from "../../notes/paths.js";
4
+ import { projectKey, slugify, type NotesIdentity } from "../../notes/index.js";
6
5
 
7
6
  /** Pi's default notes root; environment access stays on the host side of the library boundary. */
8
7
  export function notesRoot(): string {
@@ -2,7 +2,7 @@ import { generateDiffString, type ExtensionAPI } from "@earendil-works/pi-coding
2
2
  import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../tools/notes.js";
3
3
  import { notesIdentityFromPi } from "./adapter.js";
4
4
  import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
5
- import type { NoteChange } from "../../notes/store.js";
5
+ import type { NoteChange } from "../../notes/index.js";
6
6
 
7
7
  function renderDiff(change: NoteChange): string {
8
8
  return change.kind === "none" ? "" : generateDiffString(change.before, change.after).diff;
@@ -1,12 +1,23 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { ExtensionAPI, ExtensionContext, SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
3
- import { BOOT_TYPE, CONTINUATION_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
3
+ import { BOOT_TYPE, CONTINUATION_TYPE, RESET_LAST_WORD_TYPE, RESET_MARKER_TYPE, RESET_PROMPT_TYPE } from "../entries.js";
4
4
  import { CONTINUATION } from "../../budget/text.js";
5
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 };
9
9
 
10
+ /** Cap for the parting line: one visible line, not an essay. */
11
+ export const MAX_LAST_WORD_CHARS = 500;
12
+
13
+ /** Trim and cap a parting line; blank input leaves no last word. */
14
+ export function sanitizeLastWord(raw: string | undefined): string | undefined {
15
+ const trimmed = raw?.trim();
16
+ if (!trimmed) return undefined;
17
+ const chars = Array.from(trimmed);
18
+ return chars.length > MAX_LAST_WORD_CHARS ? `${chars.slice(0, MAX_LAST_WORD_CHARS).join("")}…` : trimmed;
19
+ }
20
+
10
21
  /** Match the hidden continuation entry that carries the one reset message. */
11
22
  export function isWindowContinuationEntry(entry: SessionEntry): boolean {
12
23
  return entry.type === "custom_message" && entry.customType === CONTINUATION_TYPE;
@@ -22,13 +33,14 @@ function sendContinuation(pi: ExtensionAPI): void {
22
33
 
23
34
  /**
24
35
  * The closed, ordered reset shape: retain-none native checkpoint, marker, matching boot,
25
- * continuation, then an optional command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
36
+ * continuation, then an optional parting line and command prompt. The boot snapshot is acquired asynchronously after capturing this identity.
26
37
  */
27
38
  export async function buildResetDrafts(
28
39
  ctx: ExtensionContext,
29
40
  notifyIncompleteNotes?: IncompleteNotesNotifier,
30
41
  isCurrent: () => boolean = () => true,
31
42
  prompt?: string,
43
+ lastWord?: string,
32
44
  ): Promise<SessionBoundaryDraft[]> {
33
45
  const sessionId = ctx.sessionManager.getSessionId();
34
46
  const previousId = currentWindowId(ctx);
@@ -46,6 +58,7 @@ export async function buildResetDrafts(
46
58
  { type: "custom", customType: RESET_MARKER_TYPE, data: { windowId } },
47
59
  { type: "custom_message", customType: BOOT_TYPE, content: boot.content, display: false, details: { windowId } },
48
60
  { type: "custom_message", customType: CONTINUATION_TYPE, content: CONTINUATION, display: false },
61
+ ...(lastWord ? [{ type: "custom_message" as const, customType: RESET_LAST_WORD_TYPE, content: lastWord, display: true }] : []),
49
62
  ...(prompt ? [{ type: "custom_message" as const, customType: RESET_PROMPT_TYPE, content: prompt, display: true }] : []),
50
63
  ];
51
64
  }
@@ -15,7 +15,7 @@ type BudgetOwner = {
15
15
  type ResetOptions = {
16
16
  isEnabled: () => boolean;
17
17
  budget: BudgetOwner;
18
- buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, prompt?: string) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
18
+ buildReset: (ctx: ExtensionContext, isCurrent: () => boolean, prompt?: string, lastWord?: string) => SessionBoundaryDraft[] | Promise<SessionBoundaryDraft[]>;
19
19
  getLifecycleGeneration?: () => number;
20
20
  onResetReady?: (ctx: ExtensionContext, drafts: readonly SessionBoundaryDraft[]) => void;
21
21
  };
@@ -37,8 +37,8 @@ export type ResetRequest =
37
37
  // The safety reset may change windows before Pi finishes its tool-batch continuation.
38
38
  // This run-scoped stop intent survives that change; windowId is the pre-reset window.
39
39
  | { readonly phase: "stop-pending"; readonly windowId: string }
40
- | { readonly phase: "close-out"; readonly windowId: string; readonly source: ResetRequestSource; readonly prompt?: string }
41
- | { readonly phase: "tool-requested"; readonly windowId: string; readonly source: ToolResetRequestSource };
40
+ | { readonly phase: "close-out"; readonly windowId: string; readonly source: ResetRequestSource; readonly prompt?: string; readonly lastWord?: string }
41
+ | { readonly phase: "tool-requested"; readonly windowId: string; readonly source: ToolResetRequestSource; readonly lastWord?: string };
42
42
  export type ResetOverflowPhase = "idle" | "pending" | "pending-spent" | "spent";
43
43
 
44
44
  export interface ResetControlState {
@@ -76,7 +76,7 @@ export interface ResetBeforeSettleFacts {
76
76
 
77
77
  export type ResetControlEvent =
78
78
  | { readonly type: "close_out"; readonly windowId: string; readonly source: ResetRequestSource; readonly prompt?: string }
79
- | { readonly type: "tool_request"; readonly windowId: string }
79
+ | { readonly type: "tool_request"; readonly windowId: string; readonly lastWord?: string }
80
80
  | { readonly type: "turn_end"; readonly facts: ResetTurnEndFacts }
81
81
  | { readonly type: "before_settle"; readonly facts: ResetBeforeSettleFacts }
82
82
  | { readonly type: "settled" }
@@ -96,16 +96,23 @@ export interface ResetControlResult {
96
96
  readonly state: ResetControlState;
97
97
  readonly effect: ResetControlEffect;
98
98
  readonly prompt?: string;
99
+ readonly lastWord?: string;
99
100
  }
100
101
 
101
102
  function requestForWindow(request: ResetRequest, windowId: string): ResetRequest {
102
103
  return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
103
104
  }
104
105
 
105
- function manualCommit(prompt?: string): ResetControlResult {
106
+ function manualCommit(prompt?: string, lastWord?: string): ResetControlResult {
107
+ const parting = lastWord ? { lastWord } : {};
106
108
  return prompt
107
- ? { state: initialResetControl(), effect: "commit-boundary", prompt }
108
- : { state: initialResetControl(), effect: "commit-boundary-stop" };
109
+ ? { state: initialResetControl(), effect: "commit-boundary", prompt, ...parting }
110
+ : { state: initialResetControl(), effect: "commit-boundary-stop", ...parting };
111
+ }
112
+
113
+ /** The parting line rides either committing phase; other phases never carry one. */
114
+ function requestLastWord(request: ResetRequest): string | undefined {
115
+ return request.phase === "close-out" || request.phase === "tool-requested" ? request.lastWord : undefined;
109
116
  }
110
117
 
111
118
  /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
@@ -134,15 +141,20 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
134
141
  if (request.phase === "tool-requested" && request.windowId === event.windowId) {
135
142
  return { state, effect: "already-pending" };
136
143
  }
144
+ const parting = event.lastWord ? { lastWord: event.lastWord } : {};
137
145
  // A manual close-out must settle so the stop actually lands; the agent's own wipe
138
146
  // call during one is only an acknowledgement, never a conversion to a turn-end
139
147
  // commit that pi's tool-batch continuation can overrun. A budget close-out still
140
148
  // upgrades: context pressure cannot wait for settlement.
141
149
  if (request.phase === "close-out" && request.windowId === event.windowId) {
142
- if (request.source === "manual") return { state, effect: "already-pending" };
143
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic" } }, effect: "close-out-armed" };
150
+ // The acknowledging call still contributes its last word; the manual commit keeps the wheel.
151
+ if (request.source === "manual") {
152
+ const lastWord = request.lastWord ?? event.lastWord;
153
+ return { state: { ...state, request: { ...request, ...(lastWord ? { lastWord } : {}) } }, effect: "already-pending" };
154
+ }
155
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic", ...parting } }, effect: "close-out-armed" };
144
156
  }
145
- return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool" } }, effect: "close-out-armed" };
157
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool", ...parting } }, effect: "close-out-armed" };
146
158
  }
147
159
  case "turn_end": {
148
160
  const facts = event.facts;
@@ -165,9 +177,10 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
165
177
  // A direct tool request commits after the whole tool batch. The budget cutoff is
166
178
  // a separate hard-reserve safety path; ordinary close-out waits for settlement.
167
179
  if (request.phase === "tool-requested" || facts.hardReserveDue) {
168
- if (manual && request.prompt) return manualCommit(request.prompt);
169
- if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop" };
170
- return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary" };
180
+ const lastWord = requestLastWord(request);
181
+ if (manual && request.prompt) return manualCommit(request.prompt, lastWord);
182
+ if (manual) return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop", ...(lastWord ? { lastWord } : {}) };
183
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary", ...(lastWord ? { lastWord } : {}) };
171
184
  }
172
185
  return { state: { request, overflow: "idle" }, effect: "none" };
173
186
  }
@@ -189,7 +202,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
189
202
  }
190
203
  // An explicit manual wipe is not an automatic recovery/retry. It must still
191
204
  // clear on overflow, including when automatic reset is disabled.
192
- if (manual && facts.enabled) return manualCommit(request.prompt);
205
+ if (manual && facts.enabled) return manualCommit(request.prompt, requestLastWord(request));
193
206
  const spent = state.overflow === "pending-spent";
194
207
  if (!facts.enabled || !facts.automaticResetEnabled) {
195
208
  return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
@@ -200,7 +213,7 @@ export function reduceResetControl(state: ResetControlState, event: ResetControl
200
213
  return { state: { ...state, request: NO_REQUEST }, effect: "none" };
201
214
  }
202
215
  if (facts.queued) return { state: { ...state, request }, effect: "none" };
203
- return manualCommit(request.prompt);
216
+ return manualCommit(request.prompt, requestLastWord(request));
204
217
  }
205
218
  case "settled":
206
219
  return { state: initialResetControl(), effect: "none" };
@@ -225,7 +238,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
225
238
  let control = initialResetControl();
226
239
 
227
240
  const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
228
- const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, continueAfterReset: boolean, prompt?: string) => {
241
+ const resetBoundaryResult = async (entries: SessionBoundaryDraft[], ctx: ExtensionContext, continueAfterReset: boolean, prompt?: string, lastWord?: string) => {
229
242
  const generation = lifecycleGeneration;
230
243
  const outerGeneration = options.getLifecycleGeneration?.();
231
244
  const sessionId = ctx.sessionManager.getSessionId();
@@ -235,7 +248,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
235
248
  ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
236
249
  let resetDrafts: SessionBoundaryDraft[];
237
250
  try {
238
- resetDrafts = await options.buildReset(ctx, isCurrent, prompt);
251
+ resetDrafts = await options.buildReset(ctx, isCurrent, prompt, lastWord);
239
252
  } catch (error) {
240
253
  if (isCurrent()) ctx.ui.notify(`🥣 Couldn't clear memory: ${errorMessage(error)}${prompt ? " · your prompt was not sent" : ""}`, "warning");
241
254
  return entries.length > 0 ? { entries } : undefined;
@@ -281,7 +294,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
281
294
  },
282
295
  });
283
296
  control = decision.state;
284
- if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt);
297
+ if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop") return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt, decision.lastWord);
285
298
  return entries.length > 0 ? { entries } : undefined;
286
299
  });
287
300
 
@@ -301,7 +314,7 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
301
314
  control = decision.state;
302
315
  if (decision.effect === "stop") return { entries: event.entries, continue: false };
303
316
  if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow") return undefined;
304
- return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt);
317
+ return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt, decision.lastWord);
305
318
  });
306
319
 
307
320
  pi.on("session_before_compact", (event, ctx) => {
@@ -333,8 +346,8 @@ export function registerResetLifecycle(pi: ExtensionAPI, options: ResetOptions)
333
346
  control = decision.state;
334
347
  return decision.effect;
335
348
  },
336
- request(windowId: string) {
337
- const decision = reduceResetControl(control, { type: "tool_request", windowId });
349
+ request(windowId: string, lastWord?: string) {
350
+ const decision = reduceResetControl(control, { type: "tool_request", windowId, ...(lastWord ? { lastWord } : {}) });
338
351
  control = decision.state;
339
352
  return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
340
353
  },
package/src/pi/runtime.ts CHANGED
@@ -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, type ExtensionAPI, type ExtensionCommandContext, type ExtensionContext, type SettingsManager } 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, type WindowMarker } from "./window.js";
8
8
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
- import { buildResetDrafts } from "./reset/artifacts.js";
9
+ import { buildResetDrafts, repairResetTail, sanitizeLastWord } 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, type IncompleteNotesNotifier } from "./boot.js";
12
+ import { buildBootMessage, sendBoot, type IncompleteNotesNotifier } from "./boot.js";
13
13
  import { errorMessage } from "../error-message.js";
14
14
 
15
15
  function readPackageVersion(): string {
@@ -26,6 +26,34 @@ function branchHasWindowMarker(ctx: ExtensionContext, fromId?: string): boolean
26
26
  return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
27
27
  }
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(
34
+ pi: ExtensionAPI,
35
+ ctx: ExtensionContext,
36
+ notifyIncompleteNotes?: IncompleteNotesNotifier,
37
+ isCurrent: () => boolean = () => true,
38
+ ): Promise<void> {
39
+ const sessionId = ctx.sessionManager.getSessionId();
40
+ const reset = currentReset(ctx);
41
+ const windowId = reset?.data.windowId ?? rootWindowId(sessionId);
42
+ const stillCurrent = () => isCurrent() &&
43
+ ctx.signal?.aborted !== true &&
44
+ ctx.sessionManager.getSessionId() === sessionId &&
45
+ currentWindowId(ctx) === windowId;
46
+ if (reset) {
47
+ await repairResetTail(pi, ctx, reset, notifyIncompleteNotes, stillCurrent);
48
+ return;
49
+ }
50
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
51
+ const boot = await buildBootMessage(ctx, windowId, undefined, notifyIncompleteNotes, stillCurrent);
52
+ if (!stillCurrent()) return;
53
+ if (ctx.sessionManager.buildSessionProjection().messages.some((message) => isWindowBoot(message, windowId))) return;
54
+ sendBoot(pi, boot);
55
+ }
56
+
29
57
  /** Register the context-window runtime and its context-owned commands/tools. */
30
58
  export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsManager): void {
31
59
  let enabled = true;
@@ -173,17 +201,17 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
173
201
  pi.registerTool(defineTool({
174
202
  name: "clear_memory",
175
203
  label: "Clear memory",
176
- description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
177
- parameters: Type.Object({}, { additionalProperties: false }),
178
- async execute(_id, _params, _signal, _update, ctx) {
204
+ description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to leave one short visible line where this window closes.",
205
+ parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: "A parting line shown where this window closes; the next window can read it too." })) }, { additionalProperties: false }),
206
+ async execute(_id, params, _signal, _update, ctx) {
179
207
  if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
180
- return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
208
+ return output({ status: resets.request(currentWindowId(ctx), sanitizeLastWord(params.last_word)) }, undefined, true);
181
209
  },
182
210
  }));
183
211
 
184
212
  const resets = registerResetLifecycle(pi, {
185
213
  isEnabled: () => enabled,
186
- buildReset: (ctx, isCurrent, prompt) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt),
214
+ buildReset: (ctx, isCurrent, prompt, lastWord) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt, lastWord),
187
215
  getLifecycleGeneration: () => lifecycleGeneration,
188
216
  onResetReady: (_ctx, drafts) => {
189
217
  const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
@@ -5,6 +5,11 @@ import type { JsonValue } from "@earendil-works/pi-ai";
5
5
  import type { Static, TSchema } from "typebox";
6
6
  import { wireResult, type Operation, type Outcome, type Renderer } from "../tools/result.js";
7
7
 
8
+ /** Pi's JSON envelope for reset and budget tools; details carry only log/UI metadata. */
9
+ export function output(value: unknown, details?: unknown, terminate = false) {
10
+ return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details, terminate };
11
+ }
12
+
8
13
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
9
14
  function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined> {
10
15
  return {
@@ -258,7 +258,7 @@ export const notesUpdate = {
258
258
  name: "notes_update", label: "Notes update",
259
259
  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}`,
260
260
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
261
- async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string): Promise<Outcome<NotesUpdateData>> {
261
+ async execute(params: Static<typeof notesUpdateParameters>, identity: NotesIdentity, renderDiff: (change: NoteChange) => string = (change) => change.kind === "none" ? "" : `note ${change.kind}`): Promise<Outcome<NotesUpdateData>> {
262
262
  try {
263
263
  const store = createNotesStore(identity);
264
264
  // 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 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`;
@@ -21,12 +21,3 @@ export function prefixFit(text: string, fits: (content: string) => boolean): str
21
21
  }
22
22
  return chars.slice(0, low).join("");
23
23
  }
24
-
25
- /**
26
- * Encode a structured result through the common tool result boundary. `details` is slim
27
- * metadata for logs/UI (pi convention: never a second copy of the payload) and stays
28
- * undefined unless the tool has metadata worth persisting.
29
- */
30
- export function output(value: unknown, details?: unknown, terminate = false) {
31
- return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details, terminate };
32
- }
@@ -1,8 +0,0 @@
1
- import type { Context } from "@deepseek-ai/cordis";
2
- import { NotesoupCompactionEngine } from "./engine.js";
3
- export declare class PreflightError extends Error {
4
- readonly code: string;
5
- constructor(code: string, message: string);
6
- }
7
- /** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
8
- export declare function preflight(ctx: Context): NotesoupCompactionEngine;
@@ -1,35 +0,0 @@
1
- import { NotesoupCompactionEngine } from "./engine.js";
2
- export class PreflightError extends Error {
3
- code;
4
- constructor(code, message) {
5
- super(`notesoup: ${message}`);
6
- this.code = code;
7
- }
8
- }
9
- /** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
10
- export function preflight(ctx) {
11
- for (const [service, method] of [["systemPrompt", "section"], ["tools", "register"], ["sessionQuery", "readSession"], ["tokenMeter", "measure"], ["llm", "resolveModelInfo"]]) {
12
- const mounted = ctx.get(service);
13
- if (typeof mounted?.[method] !== "function")
14
- throw new PreflightError("CAPABILITY", `${service}.${method} is unavailable; enable that service in the profile before using notesoup.`);
15
- }
16
- const engine = ctx.get("compaction");
17
- if (!(engine instanceof NotesoupCompactionEngine))
18
- throw new PreflightError("ENGINE", "ctx.compaction must be NotesoupCompactionEngine; disable compaction-basic and enable the notesoup-engine row, then restart dsh.");
19
- const loader = ctx.get("loader");
20
- if (loader) {
21
- if (typeof loader.entries !== "function")
22
- throw new PreflightError("CAPABILITY", "loader.entries is unavailable; this profile cannot be checked for two engines.");
23
- for (const entry of loader.entries()) {
24
- if ((entry.options.id === "compaction-basic" || /(?:^|\/)dsh-compaction-basic$/.test(entry.options.name)) && !entry.disabled)
25
- throw new PreflightError("DOUBLE_ENGINE", "compaction-basic is enabled; set disabled: true on that profile row and restart dsh.");
26
- }
27
- }
28
- for (const [callback, runtime] of ctx.registry.entries()) {
29
- if (callback.name === "BasicCompactionEngine" && runtime.fibers.length > 0)
30
- throw new PreflightError("DOUBLE_ENGINE", "a BasicCompactionEngine fiber is mounted; remove it before starting notesoup.");
31
- }
32
- if (!engine.automaticListenerPresent)
33
- throw new PreflightError("AUTO_LISTENER", "the automatic reset listener is missing; reload notesoup-engine before sending another request.");
34
- return engine;
35
- }
@@ -1,7 +0,0 @@
1
- export declare const PI_TOOL_NAMES: {
2
- readonly notes: "notes_*";
3
- readonly notesList: "notes_list";
4
- readonly history: "history_*";
5
- readonly remaining: "get_context_remaining";
6
- readonly wipe: "clear_memory";
7
- };