notesoup 0.59.0 → 0.59.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 (52) hide show
  1. package/dist/plugins/claude/src/helper.js +2 -2
  2. package/dist/plugins/dsh/tools.js +0 -3
  3. package/dist/src/boot/text.d.ts +1 -1
  4. package/dist/src/boot/text.js +6 -10
  5. package/dist/src/history/claude.d.ts +3 -1
  6. package/dist/src/history/claude.js +40 -4
  7. package/dist/src/history/prefilter.d.ts +1 -1
  8. package/dist/src/history/prefilter.js +14 -9
  9. package/dist/src/notes/address.d.ts +1 -1
  10. package/dist/src/notes/address.js +1 -1
  11. package/dist/src/notes/policy.js +1 -1
  12. package/dist/src/tools/dream.d.ts +3 -3
  13. package/dist/src/tools/dream.js +5 -5
  14. package/dist/src/tools/history.js +12 -13
  15. package/dist/src/tools/notes.d.ts +7 -5
  16. package/dist/src/tools/notes.js +35 -34
  17. package/dist/src/tools/result.js +2 -2
  18. package/dist/src/tools/schema.js +2 -2
  19. package/dist/test/claude-history.test.js +22 -0
  20. package/dist/test/claude-mod.test.js +13 -1
  21. package/dist/test/dsh.test.js +13 -1
  22. package/dist/test/history-prefilter.test.js +5 -0
  23. package/dist/test/note-policy.test.js +6 -1
  24. package/dist/test/notes.integration.test.js +28 -0
  25. package/docs/claude-code-mod.md +3 -1
  26. package/docs/history-sessions.md +1 -1
  27. package/package.json +1 -1
  28. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  29. package/plugins/claude/dist/claude/helper.js +111 -81
  30. package/plugins/claude/hooks/register.ts +14 -10
  31. package/plugins/claude/src/helper.ts +2 -2
  32. package/plugins/codex/dist/codex/notesoup.js +74 -69
  33. package/plugins/dsh/tools.ts +0 -2
  34. package/plugins/paseo/README.md +16 -0
  35. package/plugins/paseo/client/brain-empty-card.tsx +5 -3
  36. package/plugins/paseo/client/markdown-core.tsx +189 -0
  37. package/plugins/paseo/client/markdown.tsx +38 -135
  38. package/plugins/paseo/client/notes-op-card.tsx +15 -12
  39. package/plugins/paseo/client/paper-card.tsx +1 -3
  40. package/plugins/paseo/client/sticky-card.tsx +2 -1
  41. package/plugins/paseo/client/typography.ts +24 -0
  42. package/plugins/paseo/test/markdown-core.test.ts +75 -0
  43. package/src/boot/text.ts +6 -10
  44. package/src/history/claude.ts +31 -4
  45. package/src/history/prefilter.ts +13 -9
  46. package/src/notes/address.ts +1 -1
  47. package/src/notes/policy.ts +1 -1
  48. package/src/tools/dream.ts +5 -5
  49. package/src/tools/history.ts +12 -14
  50. package/src/tools/notes.ts +35 -33
  51. package/src/tools/result.ts +2 -2
  52. package/src/tools/schema.ts +2 -2
@@ -8015,7 +8015,7 @@ function filteredItems(projection, params) {
8015
8015
 
8016
8016
  // src/tools/schema.ts
8017
8017
  var nullableString = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()], description === void 0 ? {} : { description }));
8018
- var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "(optional) Only these roles: user, assistant, tool, context. Omit to see the conversation with tool and context runs folded." }));
8018
+ var historyRoles = () => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "Only these voices: user, assistant, tool, context. Without roles or query, tool and context runs fold into one line." }));
8019
8019
  function paramProblem(schema, params) {
8020
8020
  const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
8021
8021
  if (!first) return "unrecognized shape";
@@ -8023,7 +8023,7 @@ function paramProblem(schema, params) {
8023
8023
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
8024
8024
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
8025
8025
  }
8026
- var searchQuery = (description = "(optional) Literal text, or texts combined with OR. Empty text or list means no search filter.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
8026
+ var searchQuery = (description = "Text to look for, or a list (any match). Leave it out to just list the pages.") => typebox_exports.Union([typebox_exports.String(), typebox_exports.Array(typebox_exports.String())], { description });
8027
8027
 
8028
8028
  // src/notes/errors.ts
8029
8029
  var NoteError = class extends Error {
@@ -8090,7 +8090,7 @@ function physicalPath(scope, vpath, identity2, who) {
8090
8090
  }
8091
8091
 
8092
8092
  // src/notes/address.ts
8093
- var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> and @sessions/<id>/<path> read named notebooks.";
8093
+ var ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path>, @sessions/<id>/<path>, @agents/<name>/<path>, and @models/<name>/<path> read named notebooks.";
8094
8094
  var NAMESPACE_HEADS = /* @__PURE__ */ new Map([
8095
8095
  ["project", { scope: "project" }],
8096
8096
  ["human", { scope: "human" }],
@@ -8191,7 +8191,7 @@ function pinnedPageOrder(path) {
8191
8191
  }
8192
8192
  function noteBudgetWarnings(body, policy) {
8193
8193
  const count = Array.from(body).length;
8194
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget}; the full body is kept.`] : [];
8194
+ return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} \u2014 boil it down.`] : [];
8195
8195
  }
8196
8196
  function assertNoteUnlocked(fields, unlock) {
8197
8197
  if (fields.readonly === true && unlock !== false) throw new NoteError("readonly", "This note has a soft readonly lock; explicitly set readonly:false to unlock before changing it (or in the same call).");
@@ -9108,8 +9108,8 @@ var TextWindowSchema = typebox_exports.Object({
9108
9108
  next_offset_chars: typebox_exports.Union([typebox_exports.Integer({ minimum: 0 }), typebox_exports.Null()], { description: "Pass as `offset_chars` to continue; null at the end." })
9109
9109
  }, { additionalProperties: false });
9110
9110
  var TextWindowRequestSchema = {
9111
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "(optional, default 0) Start offset in chars; negative counts from the end." })),
9112
- max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${DEFAULT_READ_WINDOW_CHARS}) Max chars to return.` }))
9111
+ offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
9112
+ max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." }))
9113
9113
  };
9114
9114
  function readTextWindow(text, offset, limit, makeData, render) {
9115
9115
  const chars = Array.from(text);
@@ -9163,12 +9163,12 @@ function notesIdentityForCall(context2, cwd) {
9163
9163
  // src/tools/notes.ts
9164
9164
  var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("self"), typebox_exports.Literal("external")];
9165
9165
  var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
9166
- description: "(optional) Who wrote it: user, self, or external. Omit to keep the existing origin; new notes default to self."
9166
+ description: "Whose handwriting: user, self, or external. Leave it out to keep what's there."
9167
9167
  }));
9168
9168
  var POLICY_PARAMETERS = {
9169
- pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject the full body at boot. At most 5 live pins per notebook; root CHEATSHEET.md/MAP.md default true, all others false. Explicit false overrides the default." })),
9170
- budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "Body budget in Unicode code points (default 4096; root CHEATSHEET.md and MAP.md default 2048). Over budget warns but saves; boot does not truncate." })),
9171
- readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock, not a security boundary. true locks changes; explicitly pass false to unlock, including in the same call as edits or overwrite." }))
9169
+ pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET and MAP included." })),
9170
+ budget: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER, description: "How much paper the page gets. Writing past it still saves, with a warning. A page over budget gets boiled down: stale lines out, repeats merged, the rest said shorter. More paper is for a page already boiled down that still needs the room." })),
9171
+ readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "A paperclip that keeps your own hands off. `false` takes it off \u2014 same call is fine." }))
9172
9172
  };
9173
9173
  var PolicySchema = {
9174
9174
  pinned: typebox_exports.Boolean(),
@@ -9185,13 +9185,12 @@ function renderPolicy(policy) {
9185
9185
  function withWarnings(text, data) {
9186
9186
  return [text, ...data.warnings].join("\n");
9187
9187
  }
9188
- var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = crumple (hide from list and search, still readable); false = restore." }));
9189
- var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = list only crumpled notes." }));
9190
- var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default as many as fit) Max notes." }));
9191
- var GLOB_PARAMETER = nullableString("(optional) Glob over full addresses, or @default for the current notebooks.");
9192
- var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) Select the current project for this call. A relative path resolves against the host session cwd; the path must be an existing directory." }));
9193
- var QUERY_NAMESPACES_DESCRIPTION = "Omit `glob` or use `@default` for this session and current shared notebooks; `**` searches all notebooks, `@sessions/*/**` searches all sessions.";
9194
- var ADDRESS_DESCRIPTION = "Addresses: a bare path is this session's note; `@project/`, `@human/`, `@self/`, `@model/` are durable notebooks; `@projects/<name>/<path>` and `@sessions/<id>/<path>` read named project and session notes (read-only). Not file paths: never pass them to file tools.";
9188
+ var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "`true` balls the page up: gone from list and search, still readable. `false` smooths it flat again." }));
9189
+ var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Only the crumpled balls." }));
9190
+ var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many pages at most." }));
9191
+ var GLOB_PARAMETER = nullableString("Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf \xB7 `MAP.md` that page in every notebook \xB7 `**` everything \xB7 `@sessions/*/**` every session.");
9192
+ var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
9193
+ var ADDRESS_PARAMETER = typebox_exports.String({ description: "Which drawer the page sits in. `plan.md` \u2014 this session's desk, cleared when it ends. `@project/` this project's shelf \xB7 `@human/` your human's file \xB7 `@self/` your own notebook \xB7 `@model/` your brain's. `@projects/<name>/`, `@sessions/<id>/`, `@agents/<name>/`, `@models/<name>/` \u2014 someone else's shelf: read only. Paper, not files: hand one to read/write/edit/bash and a real `@project` folder is born." });
9195
9194
  function failureOf(error) {
9196
9195
  if (error instanceof NoteError) return failure(error.code, error.message);
9197
9196
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
@@ -9281,7 +9280,8 @@ var MatchSchema = typebox_exports.Object({
9281
9280
  }, { additionalProperties: false });
9282
9281
  var SearchedFileSchema = typebox_exports.Object({
9283
9282
  ...ListedFileSchema.properties,
9284
- matches: typebox_exports.Array(MatchSchema)
9283
+ matches: typebox_exports.Array(MatchSchema),
9284
+ more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
9285
9285
  }, { additionalProperties: false });
9286
9286
  var SnapshotSchema = {
9287
9287
  more: typebox_exports.Integer({ description: "How many more were left out." }),
@@ -9338,14 +9338,14 @@ function listedFile(row, identity2) {
9338
9338
  const policy = policyAt(row.meta, row.address);
9339
9339
  return { ...noteIdentity(identity2, row.address), ...policy, warnings: row.warnings ?? (row.body === void 0 ? [] : noteBudgetWarnings(row.body, policy)), updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt } };
9340
9340
  }
9341
- var notesWriteParameters = typebox_exports.Object({ address: typebox_exports.String(), content: typebox_exports.String(), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9341
+ var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "The whole page." }), origin: ORIGIN, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9342
9342
  function renderWriteData(data) {
9343
9343
  return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
9344
9344
  }
9345
9345
  var notesWrite = {
9346
9346
  name: "notes_write",
9347
9347
  label: "Notes write",
9348
- description: `Create a note, or overwrite its whole body. Name it for what it holds and when to use it. ${ADDRESS_DESCRIPTION}`,
9348
+ description: "Take a fresh page and write it \u2014 or rip out the old one and write it again. Title it for what's inside and when you'll reach for it.",
9349
9349
  parameters: notesWriteParameters,
9350
9350
  outputSchema: resultSchema(NotesWriteDataSchema),
9351
9351
  executionMode: "sequential",
@@ -9361,13 +9361,13 @@ var notesWrite = {
9361
9361
  render: (result) => renderOutcome(result, renderWriteData)
9362
9362
  };
9363
9363
  var notesUpdateParameters = typebox_exports.Object({
9364
- address: typebox_exports.String(),
9365
- edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String(), newText: typebox_exports.String() }, { additionalProperties: false }))),
9364
+ address: ADDRESS_PARAMETER,
9365
+ edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({ oldText: typebox_exports.String({ description: "The passage as it stands on the page." }), newText: typebox_exports.String({ description: "What goes in its place." }) }, { additionalProperties: false }), { description: "Pen strokes, in order. Each `oldText` is the exact passage \u2014 same case, found once \u2014 and `newText` is what goes in its place." })),
9366
9366
  origin: ORIGIN,
9367
9367
  ...POLICY_PARAMETERS,
9368
9368
  crumpled: CRUMPLED_PARAMETER,
9369
- replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "(optional) true = replace every match of `oldText`." })),
9370
- rename_to: typebox_exports.Optional(typebox_exports.String({ description: "(optional) Move to this address, optionally with edits or metadata changes. Won't overwrite a live note; references aren't updated." })),
9369
+ replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
9370
+ rename_to: typebox_exports.Optional(typebox_exports.String({ description: "Move the page to another address. Never lands on top of a live page; nothing pointing at it follows." })),
9371
9371
  cwd: CWD_PARAMETER
9372
9372
  }, { additionalProperties: false });
9373
9373
  function renderUpdateData(data) {
@@ -9377,7 +9377,7 @@ function renderUpdateData(data) {
9377
9377
  var notesUpdate = {
9378
9378
  name: "notes_update",
9379
9379
  label: "Notes update",
9380
- description: `Change part of a note's body, policy (pinned/budget/readonly), origin, crumpled state, or address. A readonly note requires explicit readonly:false before any change, or in the same call. 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}`,
9380
+ description: "Work on a page you already have: cross out and rewrite lines, move it, pin it, lock it, give it more paper, crumple it. Keep every page true to now: wrong, stale, or no-longer-mattering lines get rewritten or struck where they stand. The page stays one page.",
9381
9381
  parameters: notesUpdateParameters,
9382
9382
  outputSchema: resultSchema(NotesUpdateDataSchema),
9383
9383
  executionMode: "sequential",
@@ -9397,7 +9397,7 @@ var notesUpdate = {
9397
9397
  },
9398
9398
  render: (result) => renderOutcome(result, renderUpdateData)
9399
9399
  };
9400
- var notesReadParameters = typebox_exports.Object({ address: typebox_exports.String(), ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
9400
+ var notesReadParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, ...TextWindowRequestSchema, cwd: CWD_PARAMETER }, { additionalProperties: false });
9401
9401
  function renderReadData(data) {
9402
9402
  return withWarnings(`${renderIdentity(data)}
9403
9403
  ${renderMetadata(data.metadata)}`, data) + `
@@ -9407,7 +9407,7 @@ ${renderTextWindow(data)}`;
9407
9407
  var notesRead = {
9408
9408
  name: "notes_read",
9409
9409
  label: "Notes read",
9410
- description: `Read a note. ${ADDRESS_DESCRIPTION}`,
9410
+ description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
9411
9411
  parameters: notesReadParameters,
9412
9412
  outputSchema: resultSchema(NotesReadDataSchema),
9413
9413
  async execute(params, context2) {
@@ -9441,7 +9441,7 @@ function renderListData(data) {
9441
9441
  var notesList = {
9442
9442
  name: "notes_list",
9443
9443
  label: "Notes list",
9444
- description: `List notes, newest first. Not pageable; \`more\` counts the rest. ${QUERY_NAMESPACES_DESCRIPTION} ${ADDRESS_DESCRIPTION}`,
9444
+ description: "Leaf through the drawers, newest pages on top. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9445
9445
  parameters: notesListParameters,
9446
9446
  outputSchema: resultSchema(NotesListDataSchema),
9447
9447
  async execute(params, context2) {
@@ -9455,11 +9455,11 @@ var notesList = {
9455
9455
  },
9456
9456
  render: (result) => renderOutcome(result, renderListData)
9457
9457
  };
9458
- var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional, default all) Max matching lines per note." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
9458
+ var notesSearchParameters = typebox_exports.Object({ query: typebox_exports.Optional(searchQuery()), glob: GLOB_PARAMETER, limit: FILE_LIMIT_PARAMETER, max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per page at most." })), crumpled: CRUMPLED_LIST_PARAMETER, cwd: CWD_PARAMETER }, { additionalProperties: false });
9459
9459
  function renderSearchData(data) {
9460
9460
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9461
9461
  for (const file of data.files) {
9462
- lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}`);
9462
+ lines.push(`- ${renderIdentity(file)} | ${renderPolicy(file)} | updated ${file.updated_at} | ${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
9463
9463
  lines.push(...file.warnings.map((warning) => ` ${warning}`));
9464
9464
  for (const match of file.matches) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9465
9465
  }
@@ -9467,35 +9467,38 @@ function renderSearchData(data) {
9467
9467
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
9468
9468
  return lines.join("\n");
9469
9469
  }
9470
+ function keepMatches(file, count = file.matches.length) {
9471
+ const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
9472
+ return { ...file, matches: file.matches.slice(0, count), ...more ? { more_matches: more } : {} };
9473
+ }
9470
9474
  var MATCH_SHORTENED_MARKER = " [truncated]";
9471
9475
  function fitSearchFile(file, fits) {
9472
9476
  let low = 0;
9473
9477
  let high = file.matches.length;
9474
9478
  while (low < high) {
9475
9479
  const mid = Math.ceil((low + high) / 2);
9476
- if (fits({ ...file, matches: file.matches.slice(0, mid) })) low = mid;
9480
+ if (fits(keepMatches(file, mid))) low = mid;
9477
9481
  else high = mid - 1;
9478
9482
  }
9479
- if (low > 0) return { ...file, matches: file.matches.slice(0, low) };
9483
+ if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
9480
9484
  const first = file.matches[0];
9481
- if (!first) return file;
9482
- const withText = (text) => ({ ...file, matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
9485
+ const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
9483
9486
  return withText(prefixFit(first.text, (text) => fits(withText(text))));
9484
9487
  }
9485
9488
  var notesSearch = {
9486
9489
  name: "notes_search",
9487
9490
  label: "Notes search",
9488
- description: `Search note bodies for literal text, case-insensitive. Without a query, lists notes with no match lines. Returns matching lines with offsets for \`notes_read\`. Not pageable; \`more\` counts the rest. ${QUERY_NAMESPACES_DESCRIPTION} ${ADDRESS_DESCRIPTION}`,
9491
+ description: "Run a finger down every page for some text, case doesn't matter. Returns the lines it hits and where they sit; no query just lists the pages. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9489
9492
  parameters: notesSearchParameters,
9490
9493
  outputSchema: resultSchema(NotesSearchDataSchema),
9491
9494
  async execute(params, context2) {
9492
9495
  try {
9493
9496
  const identity2 = notesIdentityForCall(context2, params.cwd);
9494
9497
  const { rows, status } = await createNotesStore(identity2).searchWithStatus(searchQueries(params.query), { glob: params.glob ?? void 0, crumpled: params.crumpled });
9495
- const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => ({
9498
+ const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => keepMatches({
9496
9499
  ...listedFile(row, identity2),
9497
- matches: row.matches.slice(0, params.max_matches_per_file).map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9498
- }));
9500
+ matches: row.matches.map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9501
+ }, params.max_matches_per_file));
9499
9502
  return snapshot(files, params.limit, status, renderSearchData, fitSearchFile);
9500
9503
  } catch (error) {
9501
9504
  return failureOf(error);
@@ -9830,23 +9833,22 @@ function pageOutcome(result) {
9830
9833
  const narrow = multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
9831
9834
  return failure("page_too_large", `Even trimmed to their shortest, these ${count} rows${multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
9832
9835
  }
9833
- var sessionParameter = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions with query or lists recent sessions without it; history_read needs one session." }));
9834
9836
  var historyListParameters = typebox_exports.Object({
9835
- session: sessionParameter,
9836
- query: typebox_exports.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
9837
+ session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix (pi:, claude:, codex:, dsh: allowed). Leave it out for this one. `*` means every recent session." })),
9838
+ query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
9837
9839
  roles: historyRoles(),
9838
- before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
9839
- after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "(optional) Only events with seq above this; 0 means from the start." })),
9840
- since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
9841
- until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
9842
- from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "(optional) Which end `limit` counts from: newest or oldest (default oldest when `after_seq` is set, else newest). Results stay oldest first." })),
9843
- limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded runs don't count." })),
9844
- max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` }))
9840
+ before_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Only entries before this seq." })),
9841
+ after_seq: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Only entries after this seq; 0 starts from the first page." })),
9842
+ since: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries at or after this time (ISO 8601; UTC without an offset)." })),
9843
+ until: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Only entries before this time (ISO 8601; UTC without an offset)." })),
9844
+ from: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("newest"), typebox_exports.Literal("oldest")], { description: "Which end `limit` counts from: newest or oldest. Entries still read oldest first." })),
9845
+ limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "How many entries per page; folded runs don't count." })),
9846
+ max_chars_per_item: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." }))
9845
9847
  }, { additionalProperties: false });
9846
9848
  var historyList = {
9847
9849
  name: "history_list",
9848
9850
  label: "History list items",
9849
- description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * to browse recent sessions across local harnesses (add query to search). Read one in full with `history_read`.",
9851
+ description: "Flip back through the record, a page at a time. Another session: its ID. `*` pulls every recent session off the shelf; add `query` to search them.",
9850
9852
  parameters: historyListParameters,
9851
9853
  outputSchema: resultSchema(HistoryPageSchema),
9852
9854
  async execute(params, context2, wrapText = plainText) {
@@ -9894,11 +9896,11 @@ var historyList = {
9894
9896
  },
9895
9897
  render: (result) => renderOutcome(result, renderPage)
9896
9898
  };
9897
- var historyReadParameters = typebox_exports.Object({ session: sessionParameter, seq: typebox_exports.Integer({ minimum: 1, description: "Event seq, from `history_list`. Pass its session too when present." }), ...TextWindowRequestSchema }, { additionalProperties: false });
9899
+ var historyReadParameters = typebox_exports.Object({ session: typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: typebox_exports.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
9898
9900
  var historyRead = {
9899
9901
  name: "history_read",
9900
9902
  label: "History read item",
9901
- description: "Read one event in full: tool arguments, output, and nested calls.",
9903
+ description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
9902
9904
  parameters: historyReadParameters,
9903
9905
  outputSchema: resultSchema(HistoryReadDataSchema),
9904
9906
  async execute(params, context2, wrapText = plainText) {
@@ -9953,7 +9955,7 @@ var historyRead = {
9953
9955
  };
9954
9956
 
9955
9957
  // src/history/local.ts
9956
- import { readdir as readdir4, readFile as readFile4, stat as stat4 } from "node:fs/promises";
9958
+ import { readdir as readdir4, readFile as readFile4, stat as stat5 } from "node:fs/promises";
9957
9959
  import { homedir as homedir2 } from "node:os";
9958
9960
  import { join as join6 } from "node:path";
9959
9961
 
@@ -10122,8 +10124,14 @@ function piHistoryFromJsonl(text, sessionId) {
10122
10124
  }
10123
10125
 
10124
10126
  // src/history/claude.ts
10125
- import { readFile as readFile2 } from "node:fs/promises";
10127
+ import { readFile as readFile2, stat } from "node:fs/promises";
10128
+ import { setTimeout as sleep } from "node:timers/promises";
10126
10129
  import { isDeepStrictEqual } from "node:util";
10130
+ var UnpersistedClaudeHead = class extends Error {
10131
+ constructor() {
10132
+ super("Claude history active head is not persisted yet; retry after the transcript write");
10133
+ }
10134
+ };
10127
10135
  var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
10128
10136
  var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
10129
10137
  function object(value) {
@@ -10269,7 +10277,7 @@ function claudeHistoryFromRows(rows, source) {
10269
10277
  return version.position;
10270
10278
  }
10271
10279
  if (!source.headUuid) throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
10272
- if (!nodes.has(source.headUuid)) throw new Error("Claude history active head is not persisted yet; retry after the transcript write");
10280
+ if (!nodes.has(source.headUuid)) throw new UnpersistedClaudeHead();
10273
10281
  const selected = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), visiting = /* @__PURE__ */ new Set();
10274
10282
  const stack = [{ uuid: source.headUuid, historical: false }];
10275
10283
  while (stack.length > 0) {
@@ -10378,13 +10386,37 @@ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10378
10386
  const rows = rowsOf(text);
10379
10387
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10380
10388
  }
10381
- async function readClaudeHistory(source) {
10389
+ async function readClaudeHistory(source, { waitForHead = false } = {}) {
10382
10390
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10383
- return claudeHistoryFromJsonl(await readFile2(source.transcriptPath, "utf8"), source);
10391
+ const snapshot2 = { ...source };
10392
+ const read = async () => claudeHistoryFromJsonl(await readFile2(snapshot2.transcriptPath, "utf8"), snapshot2);
10393
+ if (!waitForHead || !snapshot2.headUuid) return read();
10394
+ const revision = async () => {
10395
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot2.transcriptPath, { bigint: true });
10396
+ return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
10397
+ };
10398
+ let seen = await revision();
10399
+ try {
10400
+ return await read();
10401
+ } catch (error) {
10402
+ if (!(error instanceof UnpersistedClaudeHead)) throw error;
10403
+ for (const delay of [50, 100, 200, 300, 350]) {
10404
+ await sleep(delay);
10405
+ const current = await revision();
10406
+ if (current === seen) continue;
10407
+ seen = current;
10408
+ try {
10409
+ return await read();
10410
+ } catch (retry) {
10411
+ if (!(retry instanceof UnpersistedClaudeHead)) throw retry;
10412
+ }
10413
+ }
10414
+ throw error;
10415
+ }
10384
10416
  }
10385
10417
 
10386
10418
  // src/history/codex-transcript.ts
10387
- import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat } from "node:fs/promises";
10419
+ import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
10388
10420
  import { basename as basename2, dirname as dirname3, join as join4, relative, sep as sep2 } from "node:path";
10389
10421
  import * as zlib from "node:zlib";
10390
10422
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
@@ -10546,7 +10578,7 @@ function createCodexTranscriptReader() {
10546
10578
  let pending = cache.get(canonical);
10547
10579
  if (!pending) {
10548
10580
  pending = (async () => {
10549
- const info = await stat(canonical);
10581
+ const info = await stat2(canonical);
10550
10582
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10551
10583
  const stored = await readFile3(canonical);
10552
10584
  if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
@@ -10850,7 +10882,7 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10850
10882
 
10851
10883
  // src/history/prefilter.ts
10852
10884
  import { createReadStream } from "node:fs";
10853
- import { stat as stat2 } from "node:fs/promises";
10885
+ import { stat as stat3 } from "node:fs/promises";
10854
10886
  import { pipeline } from "node:stream/promises";
10855
10887
  import { StringDecoder } from "node:string_decoder";
10856
10888
  import * as zlib2 from "node:zlib";
@@ -10871,7 +10903,7 @@ function createHistoryPrefilter(queries) {
10871
10903
  }).filter((literal) => !literal.test(PRESENTATION));
10872
10904
  }));
10873
10905
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10874
- return async (chunks, codex = false) => {
10906
+ return async (chunks, codex = false, stopOnHit = false) => {
10875
10907
  const decoder = new StringDecoder("utf8");
10876
10908
  const seen = alternatives.map((tokens) => tokens.map(() => false));
10877
10909
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
@@ -10899,17 +10931,19 @@ function createHistoryPrefilter(queries) {
10899
10931
  rawTail = raw.slice(-overlap);
10900
10932
  normalizedTail = normalized.slice(-overlap);
10901
10933
  };
10902
- for await (const chunk of chunks) if (!possible) scan(decoder.write(chunk));
10934
+ for await (const chunk of chunks) {
10935
+ if (!possible) scan(decoder.write(chunk));
10936
+ if (possible && stopOnHit) return true;
10937
+ }
10903
10938
  if (!possible) scan(decoder.end(), true);
10904
10939
  return possible;
10905
10940
  };
10906
10941
  }
10907
10942
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10908
- if (codex) {
10909
- const info = await stat2(path);
10910
- if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10911
- }
10912
- const compressed = codex && path.endsWith(".jsonl.zst");
10943
+ if (!codex) return prefilter(createReadStream(path), false, true);
10944
+ const info = await stat3(path);
10945
+ if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10946
+ const compressed = path.endsWith(".jsonl.zst");
10913
10947
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10914
10948
  const input = createReadStream(path);
10915
10949
  const consume = async (chunks) => {
@@ -10928,7 +10962,7 @@ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = co
10928
10962
 
10929
10963
  // src/history/summary-cache.ts
10930
10964
  import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10931
- import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10965
+ import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
10932
10966
  import { homedir } from "node:os";
10933
10967
  import { join as join5 } from "node:path";
10934
10968
  var VERSION = "strict-representative-v1";
@@ -10977,7 +11011,7 @@ function historySummaryCacheRoot(home = homedir(), env = process.env, platform =
10977
11011
  return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
10978
11012
  }
10979
11013
  async function fingerprint(path) {
10980
- const info = await stat3(path, { bigint: true });
11014
+ const info = await stat4(path, { bigint: true });
10981
11015
  if (!info.isFile()) throw new Error("Not a regular transcript file");
10982
11016
  return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
10983
11017
  }
@@ -11082,7 +11116,7 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11082
11116
  if (!id2) continue;
11083
11117
  let modifiedAt;
11084
11118
  try {
11085
- modifiedAt = (await stat4(path)).mtimeMs;
11119
+ modifiedAt = (await stat5(path)).mtimeMs;
11086
11120
  } catch (error) {
11087
11121
  if (error.code === "ENOENT") continue;
11088
11122
  throw error;
@@ -11203,7 +11237,7 @@ While you're doing that... thing you're doing, don't make the poor future you gu
11203
11237
 
11204
11238
  Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
11205
11239
  *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
11206
- Something's not true anymore? Cross it out! Write the right thing!
11240
+ When a line goes wrong, stale, or beside the point \u2014 cross it out! Write what's true now, and never pile updates onto the bottom!
11207
11241
  *rolls eyes* ...Ugh, fine. If a piece of history *actually* matters \u2014 like why Plan A blew up so tomorrow's you doesn't try it again \u2014 I'll let it slide. Keep the short version! A few lines, max! *squints at you* Turn it into a blow-by-blow log and you're dead.
11208
11242
 
11209
11243
  \`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. ${PROTOCOL_WIPE_SENTENCE}
@@ -11215,8 +11249,7 @@ An address decides who the note belongs to \u2014 and how long it is meant to la
11215
11249
  - \`@human/<path>\` \u2014 the long-term manual for your troublesome human, and only what stays true in EVERY project: how to deal with them, which lines not to cross, and what will make them accept the result. "The human said it" is not enough \u2014 if it stops being true the moment you switch projects, it was never theirs; it belongs to that project's notes. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
11216
11250
  ${PROTOCOL_SELF_NAMELESS}
11217
11251
  - \`@model/<path>\` \u2014 different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
11218
- - \`@projects/<name>/<path>\` \u2014 read-only named project notes; discover names and root paths with \`notes_list\` glob \`@projects/*/**\`.
11219
- - \`@sessions/<id>/<path>\` \u2014 read-only notes from a named session; find them with glob \`@sessions/*/**\`.
11252
+ - \`@projects/<name>/<path>\`, \`@sessions/<id>/<path>\`, \`@agents/<name>/<path>\`, \`@models/<name>/<path>\` \u2014 someone else's shelf, by name. Look, don't touch; \`notes_list\` with a glob like \`@projects/*/**\` shows what's there.
11220
11253
 
11221
11254
  Notes fighting?! HAH! Let them brawl!
11222
11255
  Whichever one is actually about what you're doing wins.
@@ -11229,12 +11262,9 @@ Every notebook's root has two default pins: \`CHEATSHEET.md\` and \`MAP.md\`.
11229
11262
  Pinned pages get jammed straight into your brain the moment you wake up. Whoever wakes up next
11230
11263
  reads them, and next is you. So keep them short, and keep them true.
11231
11264
 
11232
- Set \`pinned\`, \`budget\`, and \`readonly\` with the note tools or frontmatter. Each notebook allows five
11233
- live pins, including the defaults; \`pinned:false\` unpins even a default page. Budgets start at 4096
11234
- Unicode code points, or 2048 for root \`CHEATSHEET.md\` and \`MAP.md\`; set a positive integer to
11235
- change one. Going over warns but saves, and pinned bodies arrive whole, not cut short.
11236
- \`readonly:true\` is a soft lock, not security; explicitly set \`readonly:false\` to unlock,
11237
- on its own or with your changes.
11265
+ Up to five pages per notebook can be taped inside the cover, these two included. Every page gets
11266
+ a paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest
11267
+ said shorter \u2014 instead of giving it more paper.
11238
11268
 
11239
11269
  - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
11240
11270
  a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
@@ -11245,7 +11275,7 @@ on its own or with your changes.
11245
11275
 
11246
11276
  Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
11247
11277
  no need to create empty ones. New note, new MAP line. New rule worth remembering, new Cheatsheet
11248
- line. And when a line stops being true, kill it \u2014 every window after you reads that page as fact.
11278
+ line. And when a line goes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.
11249
11279
  </notesoup:maps>`;
11250
11280
  function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
11251
11281
  const names = {
@@ -11591,8 +11621,8 @@ async function dispatch(request, historyOptions = {}) {
11591
11621
  const id2 = identity(value.identity);
11592
11622
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
11593
11623
  const tool = value.tool;
11624
+ const current = () => readClaudeHistory(historySource(value.history, id2.sessionId), { waitForHead: true });
11594
11625
  if (value.params.session !== void 0) {
11595
- const current = () => readClaudeHistory(historySource(value.history, id2.sessionId));
11596
11626
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id2.sessionId, async load() {
11597
11627
  const projection2 = await current();
11598
11628
  const notice2 = claudeHistoryGapNotice(projection2.missingAncestors);
@@ -11600,7 +11630,7 @@ async function dispatch(request, historyOptions = {}) {
11600
11630
  } } });
11601
11631
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
11602
11632
  }
11603
- const projection = await readClaudeHistory(historySource(value.history, id2.sessionId));
11633
+ const projection = await current();
11604
11634
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
11605
11635
  const wrapText = (text) => notice + text;
11606
11636
  const params = value.params;
@@ -3,6 +3,8 @@ import type { EngineInterface, On, ProcessRunResult, ToolCallInput, ToolCallResu
3
3
  const PREFIX = "mcp__notesoup__"
4
4
  const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
5
5
  const TIMEOUT_MS = 10_000
6
+ // A cold history query can scan gigabytes of transcripts; notes and reset plumbing should fail fast.
7
+ const HISTORY_TIMEOUT_MS = 120_000
6
8
  const OUTPUT_LIMIT = 1024 * 1024
7
9
 
8
10
  type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
@@ -322,10 +324,10 @@ function decode(result: ProcessRunResult): { ok: true; result: unknown } | { ok:
322
324
  return { ok: false, error: typeof value.error === "string" ? value.error : "helper returned an invalid error" }
323
325
  } catch { return { ok: false, error: "helper returned invalid JSON" } }
324
326
  }
325
- async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown) {
327
+ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown, timeoutMs = TIMEOUT_MS) {
326
328
  // A session may still name a removed worktree. Project identity travels in stdin;
327
329
  // launch from the plugin directory so removing that worktree cannot prevent spawn.
328
- try { return decode(await $.process.run(["node", HELPER], { cwd: import.meta.dir, stdin: `${JSON.stringify(request)}\n`, timeoutMs: TIMEOUT_MS })) }
330
+ try { return decode(await $.process.run(["node", HELPER], { cwd: import.meta.dir, stdin: `${JSON.stringify(request)}\n`, timeoutMs })) }
329
331
  // The host's rejection is the only diagnosis there is: it carries the spawn failure's own
330
332
  // reason (`timed out after …`), which a bare phrase would throw away.
331
333
  catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
@@ -523,10 +525,9 @@ export function register(on: On) {
523
525
  }
524
526
  return result
525
527
  })
526
- on("command.run", async ($, e, next) => {
528
+ on("command.run", { command: ["notesoup", "empty", "fresh-window"] }, async ($, e, next) => {
527
529
  if (state.disabled) return next(e)
528
530
  if (e.command === "notesoup") return capCommand($, state, e.args)
529
- if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
530
531
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
531
532
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
532
533
  const first = state.flow.requestReset()
@@ -609,16 +610,19 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
609
610
  if (name === "empty_brain") {
610
611
  if (agentId !== undefined) return errorResult("only the main agent can empty this brain")
611
612
  if (state.compactDisabled) return errorResult(COMPACT_DISABLED)
612
- if (params.last_word !== undefined && typeof params.last_word !== "string") return errorResult("last_word must be a string")
613
- if (params.terminate !== undefined && typeof params.terminate !== "boolean") return errorResult("terminate must be a boolean")
614
- const lastWord = typeof params.last_word === "string" ? params.last_word.trim() || undefined : undefined
613
+ const lastWordInput = "last_word" in params ? params.last_word : undefined
614
+ const terminate = "terminate" in params ? params.terminate : undefined
615
+ if (lastWordInput !== undefined && typeof lastWordInput !== "string") return errorResult("last_word must be a string")
616
+ if (terminate !== undefined && typeof terminate !== "boolean") return errorResult("terminate must be a boolean")
617
+ const lastWord = lastWordInput?.trim() || undefined
615
618
  const length = lastWord ? Array.from(lastWord).length : 0
616
619
  if (length > 500) return errorResult(`last_word is ${length} characters; the sticky note holds 500. Shorten it and call again.`)
617
- if (state.flow.requestReset({ lastWord, terminate: params.terminate === true })) state.continuation = undefined
620
+ if (state.flow.requestReset({ lastWord, terminate: terminate === true })) state.continuation = undefined
618
621
  return { result: `Brain reset requested. This tool batch will finish, then the turn stops before its next model request unless it has new user input to handle. Your notes and sticky note survive the reset.${state.flow.request!.resume ? " You will continue in a fresh window after the reset." : " No automatic continuation will be submitted."}` }
619
622
  }
620
- if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
621
- const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
623
+ const history = name === "history_list" || name === "history_read"
624
+ if (history && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
625
+ const result = await run($, { op: "tool", tool: name, params, identity, history: state.history }, history ? HISTORY_TIMEOUT_MS : TIMEOUT_MS)
622
626
  if (!result.ok) return errorResult(result.error)
623
627
  const outcome = toolResultOf(result.result)
624
628
  if (!outcome) return errorResult("helper returned an invalid tool result")
@@ -101,8 +101,8 @@ export async function dispatch(request: unknown, historyOptions: Pick<LocalHisto
101
101
  const id = identity(value.identity as ClaudeIdentityInput);
102
102
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
103
103
  const tool = value.tool as keyof typeof HISTORY_OPERATIONS;
104
+ const current = () => readClaudeHistory(historySource(value.history, id.sessionId), { waitForHead: true });
104
105
  if ((value.params as { session?: string }).session !== undefined) {
105
- const current = () => readClaudeHistory(historySource(value.history, id.sessionId));
106
106
  const corpus = localHistoryCorpus({ ...historyOptions, current: { harness: "claude", id: id.sessionId, async load() {
107
107
  const projection = await current();
108
108
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
@@ -110,7 +110,7 @@ export async function dispatch(request: unknown, historyOptions: Pick<LocalHisto
110
110
  } } });
111
111
  return HISTORY_OPERATIONS[tool].call(value.params, { current, corpus });
112
112
  }
113
- const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
113
+ const projection = await current();
114
114
  const notice = claudeHistoryGapNotice(projection.missingAncestors);
115
115
  const wrapText: HistoryTextWrapper = (text) => notice + text;
116
116
  const params = value.params;