notesoup 0.54.1 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/plugins/pi/budget.js +1 -1
  2. package/dist/plugins/pi/marker.d.ts +1 -1
  3. package/dist/plugins/pi/marker.js +11 -7
  4. package/dist/plugins/pi/notes/tools.js +5 -1
  5. package/dist/plugins/pi/render.d.ts +4 -1
  6. package/dist/plugins/pi/render.js +3 -7
  7. package/dist/plugins/pi/runtime.js +4 -2
  8. package/dist/plugins/pi/tool-result.d.ts +4 -2
  9. package/dist/plugins/pi/tool-result.js +4 -3
  10. package/dist/src/history/history.d.ts +1 -1
  11. package/dist/src/history/history.js +1 -1
  12. package/dist/src/tools/history.js +4 -7
  13. package/dist/src/tools/notes.d.ts +2 -7
  14. package/dist/src/tools/notes.js +5 -26
  15. package/dist/test/budget-settings.integration.test.js +2 -2
  16. package/dist/test/claude-history.test.js +4 -6
  17. package/dist/test/codex-history.test.js +3 -2
  18. package/dist/test/dependencies.test.js +3 -4
  19. package/dist/test/dream-tools.test.js +3 -3
  20. package/dist/test/history-corpus.test.js +1 -1
  21. package/dist/test/history.integration.test.js +9 -9
  22. package/dist/test/host-neutral.test.js +7 -9
  23. package/dist/test/marker.test.js +34 -27
  24. package/dist/test/notes.integration.test.js +8 -10
  25. package/dist/test/notes.test.js +9 -7
  26. package/dist/test/pi-render.test.js +7 -7
  27. package/dist/test/project-namespace.test.js +4 -4
  28. package/docs/tool-results.md +1 -1
  29. package/package.json +3 -4
  30. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  31. package/plugins/claude/dist/claude/helper.js +493 -514
  32. package/plugins/codex/dist/codex/notesoup.js +667 -688
  33. package/plugins/paseo/OVERVIEW.md +2 -2
  34. package/plugins/paseo/client/brain-empty-card.tsx +1 -1
  35. package/plugins/paseo/client/notes-op-card.tsx +2 -2
  36. package/plugins/paseo/client/notes-op-transformer.ts +16 -1
  37. package/plugins/paseo/client/paper-palette.ts +18 -18
  38. package/plugins/paseo/test/fixtures/claude-tool-calls.ts +1 -1
  39. package/plugins/paseo/test/notes-op.test.ts +4 -4
  40. package/plugins/paseo/test/paper-palette.test.ts +3 -3
  41. package/plugins/pi/budget.ts +1 -1
  42. package/plugins/pi/marker.ts +11 -6
  43. package/plugins/pi/notes/tools.ts +5 -1
  44. package/plugins/pi/render.ts +7 -8
  45. package/plugins/pi/runtime.ts +3 -1
  46. package/plugins/pi/tool-result.ts +9 -8
  47. package/src/history/history.ts +1 -1
  48. package/src/tools/history.ts +4 -7
  49. package/src/tools/notes.ts +5 -27
@@ -4,9 +4,9 @@ Displays notesoup last-word messages already present in Paseo’s timeline as ex
4
4
 
5
5
  This client-only plugin transforms existing timeline rows in place: last-word custom messages become sticky cards, and notes_read/notes_write/notes_update tool calls become paper cards with the address, state, and a content or diff preview. It accepts the bare Pi tool names and Claude's exact `mcp__notesoup__` prefix; same-named tools from other MCP servers are unchanged. It does not read session files or append messages. Other timeline items are unchanged.
6
6
 
7
- Notes cards start collapsed; update cards also show the sentence just added. The whole header row expands and collapses the body. Long content scrolls inside a bounded panel. Read text and diffs come from the existing tool-result text; writes come from the call's content argument. Live and history use the same projection without a persisted copy. Each displayed body/diff is capped at 32,000 UTF-16 units, retaining the beginning and end with a visible omission line; collapsed previews are capped at 1,000 units before layout. Expanding does not fetch more content; original tool results and notes are unchanged. Diff lines of the same color share a text run rather than one component per line.
7
+ Notes cards start collapsed; update cards also show the sentence just added. The whole header row expands and collapses the body. Long content scrolls inside a bounded panel. Read text comes from the existing tool-result text, update diffs come from Pi's `details.diff` (falling back to legacy diff text or `input.edits` on MCP hosts), and writes come from the call's content argument. Live and history use the same projection without a persisted copy. Each displayed body/diff is capped at 32,000 UTF-16 units, retaining the beginning and end with a visible omission line; collapsed previews are capped at 1,000 units before layout. Expanding does not fetch more content; original tool results and notes are unchanged. Diff lines of the same color share a text run rather than one component per line.
8
8
 
9
- Notes cards use the same rendered-text parser for Pi live events and replayed history; Claude supplies that text under the adapter's `output` field. Write previews come from the call arguments. The UI does not depend on Pi's live-only `structuredContent`. Failed calls also read the adapter's error content (string or text blocks) or transport message when no result is available.
9
+ Notes cards use the same projection for Pi live events and replayed history; Claude supplies its receipt text under the adapter's `output` field and its edits under `input.edits`. The UI does not depend on Pi's live-only `structuredContent`. Failed calls also read the adapter's error content (string or text blocks) or transport message when no result is available.
10
10
 
11
11
  `empty_brain` (including `mcp__notesoup__empty_brain`) becomes a divider for running, completed and failed calls. Pi's JSON rollover outcomes are preserved. Claude's plain acknowledgement only completes the tool call; it does not invent a Pi outcome or assert that the deferred reset has committed.
12
12
 
@@ -6,7 +6,7 @@ function label(data: BrainEmpty): string {
6
6
  if (data.status === "running") return "✂ emptying brain …";
7
7
  if (data.error !== undefined) return "✂ brain refused to empty";
8
8
  if (data.outcome === "rollover_already_pending") return "✂ already emptying";
9
- if (data.outcome === "rollover_requested") return "✂ reset requested";
9
+ if (data.outcome === "rollover_requested") return "✂ brain emptied";
10
10
  // A completed tool call (including Claude's acknowledgement) does not prove a reset committed.
11
11
  return "✂ empty_brain completed";
12
12
  }
@@ -12,7 +12,7 @@ const OP_LABEL_RUNNING: Record<NotesOp["op"], string> = { read: "reading", write
12
12
 
13
13
  /** First added line of an update diff, without its line-number prefix: the sentence the agent just wrote down. */
14
14
  function addedLine(diff: string): string | undefined {
15
- return /^\+.*/m.exec(diff)?.[0].replace(/^\+\s*\d+\s+\+\s?/, "");
15
+ return /^\+.*/m.exec(diff)?.[0].replace(/^\+(?:\s*\d+\s+\+|\s*\d+)?\s?/, "");
16
16
  }
17
17
 
18
18
  function DiffBody({ diff, paper }: { diff: string; paper: PaperPalette }) {
@@ -70,7 +70,7 @@ export function NotesOpCard({ item, layout, theme }: PluginTimelineItemProps<Not
70
70
  {data.error !== undefined && <Text selectable style={{ color: paper.removed, fontSize: 13, lineHeight: 19 }}>{data.error}</Text>}
71
71
  </Pressable>
72
72
  {expanded && hasBody && (
73
- <ScrollView style={{ maxHeight: layout.compact ? 280 : 400, borderTopWidth: 1, borderTopColor: paper.edge }} contentContainerStyle={{ gap: 5, paddingTop: 8 }} nestedScrollEnabled>
73
+ <ScrollView style={{ maxHeight: layout.compact ? 280 : 400, marginTop: 2, borderTopWidth: 1, borderTopColor: paper.edge }} contentContainerStyle={{ gap: 5, paddingTop: 8 }} nestedScrollEnabled>
74
74
  {data.text !== undefined && <NoteMarkdown text={outputPreview(data.text)} paper={paper} />}
75
75
  {data.preview !== undefined && <NoteMarkdown text={outputPreview(data.preview)} paper={paper} muted />}
76
76
  {data.diff !== undefined && <DiffBody diff={outputPreview(data.diff)} paper={paper} />}
@@ -18,6 +18,17 @@ const OP_BY_TOOL: Record<NotesOpTool, NotesOp["op"]> = {
18
18
  notes_update: "update",
19
19
  };
20
20
 
21
+ function editsDiff(input: unknown): string | undefined {
22
+ if (!isRecord(input) || !Array.isArray(input.edits)) return undefined;
23
+ const lines: string[] = [];
24
+ for (const edit of input.edits) {
25
+ if (!isRecord(edit) || typeof edit.oldText !== "string" || typeof edit.newText !== "string" || edit.oldText === edit.newText) continue;
26
+ for (const line of edit.oldText.split("\n")) lines.push(`- ${line}`);
27
+ for (const line of edit.newText.split("\n")) lines.push(`+ ${line}`);
28
+ }
29
+ return lines.length > 0 ? lines.join("\n") : undefined;
30
+ }
31
+
21
32
  function notesOpData(item: ToolCallItem, tool: NotesOpTool): NotesOp | undefined {
22
33
  const op = OP_BY_TOOL[tool];
23
34
  if (item.detail.type !== "unknown") return undefined;
@@ -38,11 +49,15 @@ function notesOpData(item: ToolCallItem, tool: NotesOpTool): NotesOp | undefined
38
49
  const text = resultText(output);
39
50
  if (text === undefined) return data;
40
51
  if (op === "read") return { ...data, text: outputPreview(text.split("\n").slice(2).join("\n").replace(/^\n/, "")) };
52
+ const detailsDiff = isRecord(output) && isRecord(output.details) && typeof output.details.diff === "string" && output.details.diff.length > 0
53
+ ? output.details.diff
54
+ : undefined;
41
55
  const diffStart = text.indexOf("\ndiff:\n");
56
+ const rawDiff = detailsDiff ?? (diffStart >= 0 ? text.slice(diffStart + 7) : text.startsWith("unchanged ") ? undefined : editsDiff(input));
42
57
  return {
43
58
  ...data,
44
59
  ...(text.startsWith("moved ") && isRecord(input) && typeof input.rename_to === "string" ? { renamedFrom: data.address, address: input.rename_to } : {}),
45
- ...(diffStart >= 0 ? { diff: outputPreview(text.slice(diffStart + 7)) } : {}),
60
+ ...(rawDiff !== undefined ? { diff: outputPreview(rawDiff) } : {}),
46
61
  };
47
62
  }
48
63
 
@@ -1,29 +1,29 @@
1
1
  import type { PluginTheme } from "@getpaseo/plugin";
2
2
 
3
3
  const LIGHT_PAPER = {
4
- background: "#f8f3e1",
5
- edge: "#cbbd94",
6
- tape: "rgba(222, 205, 140, 0.72)",
7
- tapeEdge: "rgba(160, 140, 80, 0.18)",
8
- ink: "#33301f",
9
- inkMuted: "#867c63",
10
- added: "#357a44",
11
- removed: "#b0493e",
12
- crumpled: "#ece6d1",
4
+ background: "#faf6eb",
5
+ edge: "#dcd0b4",
6
+ tape: "rgba(224, 206, 148, 0.62)",
7
+ tapeEdge: "rgba(165, 145, 86, 0.16)",
8
+ ink: "#2c281e",
9
+ inkMuted: "#7d735d",
10
+ added: "#2f743e",
11
+ removed: "#b3463b",
12
+ crumpled: "#f1ead8",
13
13
  };
14
14
 
15
15
  export type PaperPalette = typeof LIGHT_PAPER;
16
16
 
17
17
  const DARK_PAPER: PaperPalette = {
18
- background: "#302e27",
19
- edge: "#58513e",
20
- tape: "rgba(139, 122, 70, 0.55)",
21
- tapeEdge: "rgba(194, 170, 100, 0.18)",
22
- ink: "#e8e1cc",
23
- inkMuted: "#b5aa8e",
24
- added: "#91c79a",
25
- removed: "#e69a8f",
26
- crumpled: "#292824",
18
+ background: "#26231d",
19
+ edge: "#463f31",
20
+ tape: "rgba(182, 160, 104, 0.38)",
21
+ tapeEdge: "rgba(218, 195, 134, 0.16)",
22
+ ink: "#ece5d5",
23
+ inkMuted: "#a89e86",
24
+ added: "#8cc494",
25
+ removed: "#e29488",
26
+ crumpled: "#1e1b16",
27
27
  };
28
28
 
29
29
  /** Paseo theme colors are hex (#RGB, #RRGGBB or #RRGGBBAA). */
@@ -40,7 +40,7 @@ export const claudeUpdateCompleted = {
40
40
  detail: {
41
41
  type: "unknown",
42
42
  input: { address: "a.md", edits: [{ oldText: "old", newText: "new" }] },
43
- output: { output: "updated a.md (project pi-context)\ndiff:\n- 1 - old\n+ 1 + new" },
43
+ output: { output: "updated a.md (project pi-context)" },
44
44
  },
45
45
  } as const;
46
46
 
@@ -35,10 +35,10 @@ test("write and moved update project the entire input and delivered diff", () =>
35
35
  input: { address: "a.md", content: body }, output: { content: [{ type: "text", text: "created a.md" }] },
36
36
  } });
37
37
  assert.equal(notesOpSchema.parse(write!.items[0]!.data).preview, body);
38
- const diff = "+ 1 + new\n".repeat(2000) + "[diff truncated; update applied]";
38
+ const diff = "+1 new\n".repeat(2000);
39
39
  const update = transform({ name: "notes_update", detail: { type: "unknown",
40
40
  input: { address: "a.md", rename_to: "b.md" },
41
- output: { content: [{ type: "text", text: `moved a.md -> b.md\ndiff:\n${diff}` }] },
41
+ output: { content: [{ type: "text", text: "moved a.md -> b.md" }], details: { diff } },
42
42
  } });
43
43
  assert.deepEqual(notesOpSchema.parse(update!.items[0]!.data), {
44
44
  op: "update", address: "b.md", renamedFrom: "a.md", status: "completed", diff,
@@ -110,14 +110,14 @@ test("non-notes tools, unknown shapes and missing addresses stay untouched", ()
110
110
  assert.equal(notesOpTransformer.transform({ item: { type: "user_message", text: "hi" } as never }), undefined);
111
111
  });
112
112
 
113
- test("Claude completed calls use the adapter's output text for read, write preview and update diff", () => {
113
+ test("Claude completed calls use the adapter's output text for read, write preview and input.edits for update diff", () => {
114
114
  const read = notesOpSchema.parse(transform(claudeReadCompleted)!.items[0]!.data);
115
115
  assert.deepEqual(read, { op: "read", address: "@self/foo.md", status: "completed", text: "body line one\nbody line two" });
116
116
  assert.deepEqual(notesOpSchema.parse(transform(claudeWriteCompleted)!.items[0]!.data), {
117
117
  op: "write", address: "a.md", status: "completed", preview: "the new body",
118
118
  });
119
119
  assert.deepEqual(notesOpSchema.parse(transform(claudeUpdateCompleted)!.items[0]!.data), {
120
- op: "update", address: "a.md", status: "completed", diff: "- 1 - old\n+ 1 + new",
120
+ op: "update", address: "a.md", status: "completed", diff: "- old\n+ new",
121
121
  });
122
122
  });
123
123
 
@@ -30,8 +30,8 @@ test("paper follows the host theme and preserves the light palette when switchin
30
30
  const light = theme("#ffffff", "#18181b");
31
31
  const dark = theme("#18181b", "#fafafa");
32
32
  const paper = paperPalette(light);
33
- assert.equal(paper.background, "#f8f3e1");
34
- assert.equal(paper.ink, "#33301f");
33
+ assert.equal(paper.background, "#faf6eb");
34
+ assert.equal(paper.ink, "#2c281e");
35
35
  assert.ok(luminance(paperPalette(dark).background) < 0.05);
36
36
  assert.notDeepEqual(paperPalette(dark), paper);
37
37
  assert.deepEqual(paperPalette(light), paper);
@@ -41,7 +41,7 @@ test("host hex shorthand and alpha colors select the same dark paper", () => {
41
41
  const paper = paperPalette(theme("#000000", "#ffffff"));
42
42
  assert.deepEqual(paperPalette(theme("#000", "#fff")), paper);
43
43
  assert.deepEqual(paperPalette(theme("#000000ff", "#ffffffff")), paper);
44
- assert.equal(paperPalette(theme("#fff", "#000")).background, "#f8f3e1");
44
+ assert.equal(paperPalette(theme("#fff", "#000")).background, "#faf6eb");
45
45
  });
46
46
 
47
47
  test("dark text, muted labels, additions and errors remain readable on normal and crumpled paper", () => {
@@ -104,7 +104,7 @@ export function registerBudget(
104
104
  // An aborted request does not undo the low-budget condition or repeat the toast.
105
105
  if (!notifiedWindows.has(windowId)) {
106
106
  notifiedWindows.add(windowId);
107
- ctx.ui.notify("🥣 Brain almost full · taking notes", "warning");
107
+ ctx.ui.notify("🥣 Brain almost full", "warning");
108
108
  }
109
109
  return result({ customType: WARNING_TYPE, content: pendingWarning.content });
110
110
  }
@@ -1,20 +1,25 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { MARKER_TYPE } from "./entries.js";
2
+ import { piSequenceCount } from "../../src/history/pi.js";
3
+ import { BOOT_TYPE, MARKER_TYPE } from "./entries.js";
3
4
  import { nextHistorySeq } from "./history.js";
4
5
  import { inspectResetTail } from "./reset/artifacts.js";
5
6
  import { markerContent } from "./text.js";
6
7
  import { currentReset } from "./window.js";
7
8
 
8
9
  /** Spacing between durable seq breadcrumbs, in projected history seq. */
9
- export const MARKER_INTERVAL = 50;
10
+ export const MARKER_INTERVAL = 120;
10
11
 
11
- /** Highest seq already stamped by a marker; 0 before the first. */
12
+ /** Highest seq already anchored by a window boot or marker; 0 before the first. */
12
13
  function lastMarkerSeq(ctx: ExtensionContext): number {
13
14
  let last = 0;
15
+ let nextSeq = 1;
14
16
  for (const entry of ctx.sessionManager.getEntries()) {
15
- if (entry.type !== "custom_message" || entry.customType !== MARKER_TYPE) continue;
16
- const seq = (entry.details as { seq?: unknown } | undefined)?.seq;
17
- if (typeof seq === "number" && seq > last) last = seq;
17
+ const count = piSequenceCount(entry);
18
+ if (count === 0) continue;
19
+ if (entry.type === "custom_message" && (entry.customType === MARKER_TYPE || entry.customType === BOOT_TYPE)) {
20
+ last = nextSeq;
21
+ }
22
+ nextSeq += count;
18
23
  }
19
24
  return last;
20
25
  }
@@ -28,7 +28,11 @@ export function registerNotesTools(pi: ExtensionAPI) {
28
28
  const identity = (ctx: ExtensionContext) => dreamingIdentity(notesIdentityFromPi(ctx), dreamOf(ctx));
29
29
  const toolContext = (ctx: ExtensionContext) => notesToolContext(identity(ctx), ctx.cwd);
30
30
  registerOperation(pi, notesWrite, (params, ctx) => notesWrite.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesWriteRenderers);
31
- registerOperation(pi, notesUpdate, (params, ctx) => notesUpdate.execute(params, toolContext(ctx), renderDiff), NOTES_NAMESPACE, notesUpdateRenderers);
31
+ registerOperation(pi, notesUpdate, async (params, ctx) => {
32
+ let diff = "";
33
+ const outcome = await notesUpdate.execute(params, toolContext(ctx), (change) => { diff = renderDiff(change); });
34
+ return diff ? { ...outcome, details: { diff } } : outcome;
35
+ }, NOTES_NAMESPACE, notesUpdateRenderers);
32
36
  registerOperation(pi, notesRead, (params, ctx) => notesRead.execute(params, toolContext(ctx)), NOTES_NAMESPACE, notesReadRenderers);
33
37
  registerOperation(pi, notesList, (params, ctx) => notesList.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
34
38
  registerOperation(pi, notesSearch, (params, ctx) => notesSearch.execute(params, toolContext(ctx)), NOTES_NAMESPACE);
@@ -14,7 +14,7 @@ const EXPANDED_LINE_CAP = 80;
14
14
  type WireError = { error: string; code: string };
15
15
 
16
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 } {
17
+ function wireOf<T>(result: AgentToolResult<unknown>): { data?: T; error?: WireError } {
18
18
  const sc = result.structuredContent;
19
19
  if (sc !== null && typeof sc === "object" && !Array.isArray(sc)) {
20
20
  const obj = sc as Record<string, unknown>;
@@ -25,7 +25,7 @@ function wireOf<T>(result: AgentToolResult<undefined>): { data?: T; error?: Wire
25
25
  }
26
26
 
27
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 {
28
+ function receiptFallback(result: AgentToolResult<unknown>, theme: Theme): Component {
29
29
  const text = result.content.find((c) => c.type === "text")?.text ?? "";
30
30
  return new TruncatedText(theme.fg("dim", text.split("\n")[0] ?? ""), 0, 0);
31
31
  }
@@ -77,6 +77,7 @@ export const notesWriteRenderers = {
77
77
  };
78
78
 
79
79
  export type NotesUpdateArgs = Static<typeof notesUpdateParameters>;
80
+ export type NotesUpdateDetails = { diff?: string };
80
81
  export const notesUpdateRenderers = {
81
82
  renderCall(args: NotesUpdateArgs, theme: Theme): Component {
82
83
  let suffix = "";
@@ -85,10 +86,11 @@ export const notesUpdateRenderers = {
85
86
  if (typeof args.rename_to === "string" && args.rename_to !== "") suffix += ` → ${args.rename_to}`;
86
87
  return callLine(theme, "notes_update", args.address, suffix);
87
88
  },
88
- renderResult(result: AgentToolResult<undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component {
89
+ renderResult(result: AgentToolResult<NotesUpdateDetails | undefined>, options: { expanded: boolean }, theme: Theme, context: CallContext<NotesUpdateArgs>): Component {
89
90
  const { data, error } = wireOf<NotesUpdateData>(result);
90
91
  if (error) return errorComponent(theme, error, options.expanded);
91
92
  if (!data) return receiptFallback(result, theme);
93
+ const diff = result.details?.diff ?? "";
92
94
  let head: string;
93
95
  if (context.args?.crumpled === true) {
94
96
  head = `✂ crumpled ${theme.strikethrough(theme.fg("dim", data.address))}`;
@@ -100,14 +102,11 @@ export const notesUpdateRenderers = {
100
102
  head = theme.fg("dim", "unchanged ") + addressText(theme, data.address);
101
103
  } else {
102
104
  head = `edited ${addressText(theme, data.address)}`;
103
- const peek = firstAddedLine(data.diff);
105
+ const peek = firstAddedLine(diff);
104
106
  if (peek !== undefined && peek !== "") head += theme.fg("dim", " · ") + theme.fg("toolDiffAdded", `+ ${peek}`);
105
107
  }
106
108
  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);
109
+ return new Text(diff !== "" ? `${head}\n\n${renderDiff(diff)}` : head, 0, 0);
111
110
  },
112
111
  };
113
112
 
@@ -77,9 +77,11 @@ export function registerContext(pi: ExtensionAPI, settingsManager?: SettingsMana
77
77
  if (markerResetOrigin(marker) === "forced") ctx.ui.notify("🥣 Brain forcibly emptied: overflow", "warning");
78
78
  }
79
79
  };
80
+ pi.on("before_agent_start", (_event, ctx) => {
81
+ if (enabled) maybeSendMarker(pi, ctx);
82
+ });
80
83
  pi.on("turn_start", (_event, ctx) => {
81
84
  notifyCommittedResets(ctx);
82
- if (enabled) maybeSendMarker(pi, ctx);
83
85
  });
84
86
  pi.on("agent_settled", (_event, ctx) => {
85
87
  notifyCommittedResets(ctx);
@@ -13,12 +13,12 @@ export function output(value: unknown, details?: unknown, terminate = false) {
13
13
  }
14
14
 
15
15
  /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
16
- function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined> {
16
+ function piOperationResult<TData, TDetails = undefined>(render: Renderer<TData>, outcome: Outcome<TData>, details?: TDetails): AgentToolResult<TDetails> {
17
17
  return {
18
18
  content: [{ type: "text", text: render(outcome) }],
19
19
  structuredContent: wireResult(outcome) as unknown as JsonValue,
20
20
  isError: !outcome.ok,
21
- details: undefined,
21
+ details: details as TDetails,
22
22
  };
23
23
  }
24
24
 
@@ -28,18 +28,18 @@ export const DREAM_NAMESPACE: ToolNamespace = { name: "dream", description: "Con
28
28
  export const HISTORY_NAMESPACE: ToolNamespace = { name: "history", description: "What happened in this session, read-only. See the memory skill." };
29
29
 
30
30
  /** Optional TUI renderers; without them the host draws its default call line and receipt text. */
31
- export type OperationRenderers<TParams extends TSchema> = Pick<ToolDefinition<TParams, undefined>, "renderCall" | "renderResult">;
31
+ export type OperationRenderers<TParams extends TSchema, TDetails = undefined> = Pick<ToolDefinition<TParams, TDetails>, "renderCall" | "renderResult">;
32
32
 
33
33
  /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
34
- export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
34
+ export function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[], TDetails = undefined>(
35
35
  pi: ExtensionAPI,
36
36
  operation: Operation<TParams, TData, TRest>,
37
- run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>,
37
+ run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData> & { details?: TDetails }>,
38
38
  namespace?: ToolNamespace,
39
- renderers?: OperationRenderers<TParams>,
39
+ renderers?: OperationRenderers<TParams, TDetails>,
40
40
  exposure?: ToolExposure,
41
41
  ): void {
42
- pi.registerTool(defineTool<TParams, undefined>({
42
+ pi.registerTool(defineTool<TParams, TDetails>({
43
43
  name: operation.name,
44
44
  label: operation.label,
45
45
  description: operation.description,
@@ -50,7 +50,8 @@ export function registerOperation<TParams extends TSchema, TData, TRest extends
50
50
  ...(exposure ? { exposure } : {}),
51
51
  ...renderers,
52
52
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
53
- return piOperationResult(operation.render, await run(params, ctx));
53
+ const result = await run(params, ctx);
54
+ return piOperationResult(operation.render, result, result.details);
54
55
  },
55
56
  }));
56
57
  }
@@ -144,7 +144,7 @@ function toolEvent(item: DecodedHistoryItem, result?: DecodedHistoryItem): Histo
144
144
  };
145
145
  }
146
146
 
147
- /** Pair results into call events; consumed result seqs are not alternate read addresses. */
147
+ /** Pair results into call events; consumed result seqs redirect to their call event on read. */
148
148
  export function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: number, branchSeqs: Set<number>): HistoryProjection {
149
149
  // Pair in durable address order, not window presentation order. Unnumbered
150
150
  // segments need not have a provable chronological order relative to each other.
@@ -159,21 +159,18 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
159
159
  projection = loaded.data.projection;
160
160
  identity = { session: sessionIdentity(target.data), ...(loaded.data.notice === undefined ? {} : { notice: loaded.data.notice }) };
161
161
  }
162
- const item = allItems(projection).find((event) => event.seq === params.seq);
163
162
  // Address checks run in one order: past the end of the file, off this branch, then
164
- // consumed by a pairing. Only the last two can mention what is at the address.
165
- if (item === undefined && params.seq > projection.highestSeq) {
163
+ // resolved through any tool-result pairing to its call event.
164
+ if (params.seq > projection.highestSeq) {
166
165
  return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
167
166
  }
168
167
  if (!projection.branchSeqs.has(params.seq)) {
169
168
  if (identity.notice) return failure("unconfirmed_seq", `Seq ${params.seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`);
170
169
  return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
171
170
  }
171
+ const targetSeq = projection.pairedResults.get(params.seq) ?? params.seq;
172
+ const item = allItems(projection).find((event) => event.seq === targetSeq);
172
173
  if (item === undefined) {
173
- const callSeq = projection.pairedResults.get(params.seq);
174
- if (callSeq !== undefined) {
175
- return failure("not_an_event", `Seq ${params.seq} is a tool result, shown together with its call; read seq ${callSeq} instead.`);
176
- }
177
174
  return failure("unknown_seq", `Seq ${params.seq} holds nothing to read.`);
178
175
  }
179
176
  const document = eventDocument(item);
@@ -150,7 +150,6 @@ export type NotesWriteData = Static<typeof NotesWriteDataSchema>;
150
150
  export const NotesUpdateDataSchema = Type.Object({
151
151
  ...NoteIdentitySchema,
152
152
  change_kind: Type.Union([Type.Literal("none"), Type.Literal("body"), Type.Literal("metadata"), Type.Literal("moved")]),
153
- diff: Type.String(),
154
153
  rename_from: Type.Optional(Type.String()),
155
154
  }, { additionalProperties: false });
156
155
  export type NotesUpdateData = Static<typeof NotesUpdateDataSchema>;
@@ -239,50 +238,29 @@ export const notesUpdateParameters = Type.Object({
239
238
  }, { additionalProperties: false });
240
239
 
241
240
  function renderUpdateData(data: NotesUpdateData): string {
242
- const head = data.rename_from === undefined
241
+ return data.rename_from === undefined
243
242
  ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}`
244
243
  : `moved ${data.rename_from} -> ${data.address}`;
245
- const lines = [head];
246
- if (data.diff.length > 0) lines.push("diff:", data.diff);
247
- return lines.join("\n");
248
- }
249
-
250
- function renderUpdate(result: Outcome<NotesUpdateData>): string {
251
- return renderOutcome(result, renderUpdateData);
252
- }
253
-
254
- /** A shortened diff still says so in the receipt's own text, on both surfaces. */
255
- export const DIFF_SHORTENED_MARKER = "[diff truncated; update applied]";
256
-
257
- const RECEIPT_TOO_LONG = `Saved, but the receipt is too long to hand back (${TOOL_OUTPUT_LIMIT} per call). Check the note with \`notes_read\`.`;
258
-
259
- /** Bound a mutation receipt on both surfaces; a huge diff is cut to the longest fitting prefix and marked. */
260
- function boundedUpdate(data: NotesUpdateData): Outcome<NotesUpdateData> {
261
- if (fitsResult(success(data), renderUpdate)) return success(data);
262
- if (data.diff === "") return failure("output_too_large", RECEIPT_TOO_LONG);
263
- const diff = prefixFit(data.diff, (candidate) => fitsResult(success({ ...data, diff: `${candidate}\n${DIFF_SHORTENED_MARKER}` }), renderUpdate));
264
- const result = success({ ...data, diff: `${diff}\n${DIFF_SHORTENED_MARKER}` });
265
- return fitsResult(result, renderUpdate) ? result : failure("output_too_large", RECEIPT_TOO_LONG);
266
244
  }
267
245
 
268
246
  export const notesUpdate = {
269
247
  name: "notes_update", label: "Notes update",
270
248
  description: `Change part of a note's body, its origin or crumpled state, or its address. When things change, replace the stale part in place; don't just tack an update onto the bottom. Each \`oldText\` must match exactly once unless \`replace_all\` is true. ${ADDRESS_DESCRIPTION}`,
271
249
  parameters: notesUpdateParameters, outputSchema: resultSchema(NotesUpdateDataSchema), executionMode: "sequential",
272
- async execute(params: Static<typeof notesUpdateParameters>, context: NotesToolContext, renderDiff: (change: NoteChange) => string = (change) => change.kind === "none" ? "" : `note ${change.kind}`): Promise<Outcome<NotesUpdateData>> {
250
+ async execute(params: Static<typeof notesUpdateParameters>, context: NotesToolContext, onChange?: (change: NoteChange) => void): Promise<Outcome<NotesUpdateData>> {
273
251
  try {
274
252
  const identity = notesIdentityForCall(context, params.cwd);
275
253
  const store = createNotesStore(identity);
276
254
  // Empty filler is not a request: models that pass every parameter get the edit path.
277
255
  const renameTo = params.rename_to === "" ? undefined : params.rename_to;
278
256
  const { change, moved } = await store.update(params.address, params.edits, { origin: params.origin, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
257
+ onChange?.(change);
279
258
  const from = noteIdentity(identity, params.address).address;
280
259
  const to = noteIdentity(identity, renameTo ?? params.address);
281
- const diff = renderDiff(change);
282
- return boundedUpdate({ ...to, ...(moved ? { rename_from: from } : {}), change_kind: moved ? "moved" : change.kind, diff: moved ? [`rename ${from} -> ${to.address}`, diff].filter(Boolean).join("\n") : diff });
260
+ return success({ ...to, ...(moved ? { rename_from: from } : {}), change_kind: moved ? "moved" : change.kind });
283
261
  } catch (error) { return failureOf(error); }
284
262
  },
285
- render: renderUpdate,
263
+ render: (result: Outcome<NotesUpdateData>): string => renderOutcome(result, renderUpdateData),
286
264
  } as const;
287
265
 
288
266
  export const notesReadParameters = Type.Object({ address: Type.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });