notesoup 0.51.7 → 0.51.9

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.
@@ -96,11 +96,11 @@ test("history replay has no structured payload: the rendered text is parsed inst
96
96
 
97
97
  const write = transform({
98
98
  name: "notes_write",
99
- detail: { type: "unknown", input: { address: "a.md", content: "ignored" }, output: { content: [{ type: "text", text: "overwrote a.md (project pi-context)" }] } },
99
+ detail: { type: "unknown", input: { address: "a.md", content: "the new body" }, output: { content: [{ type: "text", text: "overwrote a.md (project pi-context)" }] } },
100
100
  });
101
101
  const writeData = notesOpSchema.parse(write!.items[0]!.data);
102
102
  assert.equal(writeData.outcome, "overwrote");
103
- assert.equal(writeData.preview, undefined, "replay has no input preview authority beyond the address");
103
+ assert.equal(writeData.preview, "the new body", "replay carries the call arguments, so the content preview comes from input on every path");
104
104
 
105
105
  const update = transform({
106
106
  name: "notes_update",
@@ -127,3 +127,18 @@ test("non-notes tools, unknown shapes and missing addresses stay untouched", ()
127
127
  function result_items(result: { items: Array<{ data: unknown }> } | undefined) {
128
128
  return result!.items.map((item) => item.data);
129
129
  }
130
+
131
+ test("a crumple call is marked from the input alone", () => {
132
+ const result = transform({
133
+ name: "notes_update",
134
+ detail: {
135
+ type: "unknown",
136
+ input: { address: "@self/stale.md", crumpled: true },
137
+ output: { structuredContent: { address: "@self/stale.md", change_kind: "metadata" } },
138
+ },
139
+ });
140
+ const data = notesOpSchema.parse(result!.items[0]!.data);
141
+ assert.equal(data.crumpled, true);
142
+ assert.equal(transform({ name: "notes_update", detail: { type: "unknown", input: { address: "@self/a.md", crumpled: false }, output: { structuredContent: { address: "@self/a.md", change_kind: "metadata" } } } })!
143
+ .items[0]!.data.crumpled, undefined);
144
+ });
@@ -1,6 +1,7 @@
1
1
  import { generateDiffString, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { notesWrite, notesUpdate, notesRead, notesList, notesSearch } from "../../../src/tools/notes.js";
3
3
  import { notesIdentityFromPi } from "./adapter.js";
4
+ import { notesReadRenderers, notesUpdateRenderers, notesWriteRenderers } from "../render.js";
4
5
  import { NOTES_NAMESPACE, registerOperation } from "../tool-result.js";
5
6
  import type { NoteChange } from "../../../src/notes/index.js";
6
7
 
@@ -10,9 +11,9 @@ function renderDiff(change: NoteChange): string {
10
11
 
11
12
  /** Register the five shared note operations; each one supplies Pi's session identity and nothing else. */
12
13
  export function registerNotesTools(pi: ExtensionAPI) {
13
- registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
14
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE);
15
- registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
14
+ registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
15
+ registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, notesIdentityFromPi(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
16
+ registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE, notesReadRenderers);
16
17
  registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
17
18
  registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, notesIdentityFromPi(ctx)), NOTES_NAMESPACE);
18
19
  }
@@ -0,0 +1,165 @@
1
+ /** Pi TUI renderers for notesoup's own tools: collapsed one-line slips, expandable bodies. */
2
+ import { renderDiff, type AgentToolResult, type Theme } from "@earendil-works/pi-coding-agent";
3
+ import { Text, TruncatedText, visibleWidth, type Component } from "@earendil-works/pi-tui";
4
+ import type { Static } from "typebox";
5
+ import type { NotesReadData, NotesUpdateData, NotesWriteData } from "../../src/tools/notes.js";
6
+ import { notesReadParameters, notesUpdateParameters, notesWriteParameters } from "../../src/tools/notes.js";
7
+
8
+ /** Only the render-context members these renderers read; the host's ToolRenderContext satisfies this. */
9
+ type CallContext<TArgs> = { args: TArgs };
10
+
11
+ /** Expanded bodies show this many lines before a "more lines" marker; the full text is in the receipt. */
12
+ const EXPANDED_LINE_CAP = 80;
13
+
14
+ type WireError = { error: string; code: string };
15
+
16
+ /** structuredContent is wireResult(outcome): the data itself, or {error, code}. Old sessions may lack it. */
17
+ function wireOf<T>(result: AgentToolResult<undefined>): { data?: T; error?: WireError } {
18
+ const sc = result.structuredContent;
19
+ if (sc !== null && typeof sc === "object" && !Array.isArray(sc)) {
20
+ const obj = sc as Record<string, unknown>;
21
+ if (typeof obj.error === "string") return { error: { error: obj.error, code: typeof obj.code === "string" ? obj.code : "error" } };
22
+ return { data: obj as T };
23
+ }
24
+ return {};
25
+ }
26
+
27
+ /** Results without a structured payload (resumed old sessions) fall back to the receipt's first line. */
28
+ function receiptFallback(result: AgentToolResult<undefined>, theme: Theme): Component {
29
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
30
+ return new TruncatedText(theme.fg("dim", text.split("\n")[0] ?? ""), 0, 0);
31
+ }
32
+
33
+ function errorComponent(theme: Theme, error: WireError, expanded: boolean): Component {
34
+ if (!expanded) return new TruncatedText(theme.fg("error", `${error.code}: ${error.error.split("\n")[0]}`), 0, 0);
35
+ return new Text(theme.fg("error", `${error.code}: ${error.error}`), 0, 0);
36
+ }
37
+
38
+ function addressText(theme: Theme, address: string): string {
39
+ return theme.fg("accent", address);
40
+ }
41
+
42
+ function callLine(theme: Theme, tool: string, target?: string, suffix = ""): Component {
43
+ let line = theme.fg("toolTitle", theme.bold(tool));
44
+ if (target !== undefined && target !== "") line += " " + addressText(theme, target);
45
+ if (suffix !== "") line += theme.fg("dim", suffix);
46
+ return new TruncatedText(line, 0, 0);
47
+ }
48
+
49
+ /** First `+` line of a generateDiffString diff, without its line-number prefix: the sentence just written down. */
50
+ function firstAddedLine(diff: string): string | undefined {
51
+ for (const line of diff.split("\n")) {
52
+ const match = /^\+(\s*\d*)?\s?(.*)$/.exec(line);
53
+ if (match) return match[2];
54
+ }
55
+ return undefined;
56
+ }
57
+
58
+ function boundedLines(text: string, theme: Theme): string {
59
+ const lines = text.split("\n");
60
+ if (lines.length <= EXPANDED_LINE_CAP) return text;
61
+ return `${lines.slice(0, EXPANDED_LINE_CAP).join("\n")}\n${theme.fg("dim", `… ${lines.length - EXPANDED_LINE_CAP} more lines`)}`;
62
+ }
63
+
64
+ export type NotesWriteArgs = Static<typeof notesWriteParameters>;
65
+ export const notesWriteRenderers = {
66
+ renderCall: (args: NotesWriteArgs, theme: Theme): Component => callLine(theme, "notes_write", args.address),
67
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesWriteArgs>): Component {
68
+ const { data, error } = wireOf<NotesWriteData>(result);
69
+ if (error) return errorComponent(theme, error, options.expanded);
70
+ if (!data) return receiptFallback(result, theme);
71
+ const content = typeof context.args?.content === "string" ? context.args.content : "";
72
+ const qualifier = data.outcome === "created" ? "" : theme.fg("dim", ` · ${data.outcome}`);
73
+ const head = `wrote ${addressText(theme, data.address)}${qualifier}${theme.fg("dim", ` · ${Array.from(content).length} chars`)}`;
74
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
75
+ return new Text(`${head}\n\n${boundedLines(content, theme)}`, 0, 0);
76
+ },
77
+ };
78
+
79
+ export type NotesUpdateArgs = Static<typeof notesUpdateParameters>;
80
+ export const notesUpdateRenderers = {
81
+ renderCall(args: NotesUpdateArgs, theme: Theme): Component {
82
+ let suffix = "";
83
+ if (args.crumpled === true) suffix = " · crumple";
84
+ else if (args.crumpled === false) suffix = " · restore";
85
+ if (typeof args.rename_to === "string" && args.rename_to !== "") suffix += ` → ${args.rename_to}`;
86
+ return callLine(theme, "notes_update", args.address, suffix);
87
+ },
88
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component {
89
+ const { data, error } = wireOf<NotesUpdateData>(result);
90
+ if (error) return errorComponent(theme, error, options.expanded);
91
+ if (!data) return receiptFallback(result, theme);
92
+ let head: string;
93
+ if (context.args?.crumpled === true) {
94
+ head = `✂ crumpled ${theme.strikethrough(theme.fg("dim", data.address))}`;
95
+ } else if (context.args?.crumpled === false) {
96
+ head = `restored ${addressText(theme, data.address)}`;
97
+ } else if (data.change_kind === "moved") {
98
+ head = `renamed ${theme.fg("dim", data.rename_from ?? "?")}${theme.fg("dim", " → ")}${addressText(theme, data.address)}`;
99
+ } else if (data.change_kind === "none") {
100
+ head = theme.fg("dim", "unchanged ") + addressText(theme, data.address);
101
+ } else {
102
+ head = `edited ${addressText(theme, data.address)}`;
103
+ const peek = firstAddedLine(data.diff);
104
+ if (peek !== undefined && peek !== "") head += theme.fg("dim", " · ") + theme.fg("toolDiffAdded", `+ ${peek}`);
105
+ }
106
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
107
+ const parts = [head];
108
+ if (data.diff !== "") parts.push("", renderDiff(data.diff));
109
+ if (data.change_kind !== "moved" && data.rename_from !== undefined) parts.push(theme.fg("dim", `renamed from ${data.rename_from}`));
110
+ return new Text(parts.join("\n"), 0, 0);
111
+ },
112
+ };
113
+
114
+ export type NotesReadArgs = Static<typeof notesReadParameters>;
115
+ export const notesReadRenderers = {
116
+ renderCall: (args: NotesReadArgs, theme: Theme): Component =>
117
+ callLine(theme, "notes_read", args.address, args.offset_chars !== undefined && args.offset_chars !== 0 ? ` · offset ${args.offset_chars}` : ""),
118
+ renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme): Component {
119
+ const { data, error } = wireOf<NotesReadData>(result);
120
+ if (error) return errorComponent(theme, error, options.expanded);
121
+ if (!data) return receiptFallback(result, theme);
122
+ const truncated = data.next_offset_chars !== null;
123
+ let head = `read ${addressText(theme, data.address)}${theme.fg("dim", ` · ${data.total_chars} chars${truncated ? " · truncated" : ""}`)}`;
124
+ const peek = data.text.split("\n").find((line) => line.trim() !== "");
125
+ if (peek !== undefined) head += theme.fg("dim", ` — ${peek.trim()}`);
126
+ if (!options.expanded) return new TruncatedText(head, 0, 0);
127
+ const tail = truncated ? `\n${theme.fg("dim", `… continue at offset_chars=${data.next_offset_chars}`)}` : "";
128
+ return new Text(`${head}\n\n${boundedLines(data.text, theme)}${tail}`, 0, 0);
129
+ },
130
+ };
131
+
132
+ export type EmptyBrainArgs = { last_word?: string };
133
+
134
+ /** The empty_brain result is the JSON receipt text; there is no structured payload. */
135
+ function emptyBrainPayload(result: AgentToolResult<unknown>): { status?: string; error?: string } {
136
+ try {
137
+ const text = result.content.find((c) => c.type === "text")?.text ?? "";
138
+ const parsed: unknown = JSON.parse(text);
139
+ if (parsed !== null && typeof parsed === "object") return parsed as { status?: string; error?: string };
140
+ } catch { /* a non-JSON receipt renders as a plain line */ }
141
+ return {};
142
+ }
143
+
144
+ export const emptyBrainRenderers = {
145
+ renderCall: (_args: EmptyBrainArgs, theme: Theme): Component => callLine(theme, "empty_brain"),
146
+ renderResult(result: AgentToolResult<unknown>, _options: { expanded: boolean }, theme: Theme, context: CallContext<EmptyBrainArgs>): Component {
147
+ const payload = emptyBrainPayload(result);
148
+ if (result.isError || payload.error !== undefined) {
149
+ return new TruncatedText(theme.fg("error", `✂ brain refused to empty — ${payload.error ?? "unknown error"}`), 0, 0);
150
+ }
151
+ if (payload.status === "rollover_already_pending") return new TruncatedText(theme.fg("dim", "✂ brain already being emptied"), 0, 0);
152
+ const lastWord = typeof context.args?.last_word === "string" && context.args.last_word !== "" ? context.args.last_word : undefined;
153
+ return {
154
+ invalidate() {},
155
+ render(width: number): string[] {
156
+ const label = "✂ brain emptied";
157
+ const prefix = "── ";
158
+ const fill = Math.max(2, width - visibleWidth(prefix) - visibleWidth(label) - 1);
159
+ const lines = [theme.fg("dim", `${prefix}${label} ${"─".repeat(fill)}`)];
160
+ if (lastWord !== undefined) lines.push(theme.fg("warning", theme.italic(`“${lastWord}”`)));
161
+ return lines;
162
+ },
163
+ };
164
+ },
165
+ };
@@ -4,6 +4,7 @@ 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
6
  import { output } from "./tool-result.js";
7
+ import { emptyBrainRenderers } from "./render.js";
7
8
  import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, markerResetOrigin, projectRootWindow, projectWindow, rootWindowId, type WindowMarker } from "./window.js";
8
9
  import { registerResetLifecycle } from "./reset/lifecycle.js";
9
10
  import { buildResetDrafts, LAST_WORD_ADVERTISED_CHARS, MAX_LAST_WORD_CHARS, repairResetTail, sanitizeLastWord } from "./reset/artifacts.js";
@@ -205,6 +206,8 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
205
206
  label: "Empty Brain",
206
207
  description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
207
208
  parameters: Type.Object({ last_word: Type.Optional(Type.String({ description: `A tiny sticky note, at most ${LAST_WORD_ADVERTISED_CHARS} characters. After the wipe it is slapped on your forehead; longer notes are refused.` })) }, { additionalProperties: false }),
209
+ renderCall: emptyBrainRenderers.renderCall,
210
+ renderResult: emptyBrainRenderers.renderResult,
208
211
  async execute(_id, params, _signal, _update, ctx) {
209
212
  if (!enabled) return output({ error: "notesoup is off, so memory can't be cleared; the user can turn it on with `/notesoup on`." });
210
213
  const lastWord = sanitizeLastWord(params.last_word);
@@ -1,5 +1,5 @@
1
1
  /** Pi transport for host-neutral operations. */
2
- import { defineTool, type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineTool, type ExtensionAPI, type ExtensionToolContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import type { JsonValue } from "@earendil-works/pi-ai";
5
5
  import type { Static, TSchema } from "typebox";
@@ -26,12 +26,16 @@ export type ToolNamespace = { name: string; description: string };
26
26
  export const NOTES_NAMESPACE: ToolNamespace = { name: "notes", description: "Notes you choose to keep across context windows. See the memory skill." };
27
27
  export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
28
28
 
29
+ /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
30
+ export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
31
+
29
32
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
30
33
  export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
31
34
  pi: ExtensionAPI,
32
35
  operation: Operation<TParams, TData, TRest>,
33
36
  run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>,
34
37
  namespace?: ToolNamespace,
38
+ renderers?: OperationRenderers<TParams>,
35
39
  ): void {
36
40
  pi.registerTool(defineTool<TParams, undefined>({
37
41
  name: operation.name,
@@ -41,6 +45,7 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
41
45
  outputSchema: operation.outputSchema,
42
46
  executionMode: operation.executionMode,
43
47
  ...(namespace ? { namespace } : {}),
48
+ ...renderers,
44
49
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
45
50
  return piOperationResult(operation.render, await run(params, ctx));
46
51
  },
@@ -33,9 +33,9 @@ export function selectContinuation(origin: ResetOrigin): string {
33
33
  * instruction differs — Pi can reset the model itself, Claude can only end the turn.
34
34
  */
35
35
  export const WARNING_BODY =
36
- "This brain is about to be emptied. The notes stay where they are; history has the rest written down, though digging it back out is on you. Whatever lives only in this brain goes with it.\nBefore that, put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
36
+ "This brain is already spent. Whatever lives only in this brain goes with it — but the notes stay where they are, and history has the rest written down, though digging it back out is on you.\nUse the last of this brain to put down what the next window can't get back:\n- what you're in the middle of, and how far it has progressed\n- decisions the human has made, in their words\n- what is blocked or pending\n- the next step\n- where the unfinished work sits (branches, scratch directories, uncommitted changes)\n- what failed, and why\n- skills to re-read, and history seqs, notes, or files to consult\n- anything else you expect to be useful after the reset\n- and refresh the stale notes with what has changed since you last wrote them — the notes the next window gets are the old ones, unless you fix them now\nCorrect or crumple notes that are no longer accurate, starting with MAP files, since every new window loads them.";
37
37
 
38
- export const WARNING_CALL = "When the notes are ready, call `empty_brain` to reset now instead of being cut off mid-task.";
38
+ export const WARNING_CALL = "The moment the notes are saved, call `empty_brain`. Not one more probe, not one more test — the next thing you do after saving is reset.";
39
39
 
40
40
  export function warningPrompt(): string {
41
41
  return `${WARNING_BODY}\n${WARNING_CALL}`;