notesoup 0.61.0 → 0.62.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 (200) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -11
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +2 -1
  10. package/dist/plugins/codex/src/hooks.js +1 -0
  11. package/dist/plugins/codex/src/identity.d.ts +6 -1
  12. package/dist/plugins/codex/src/identity.js +13 -1
  13. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  14. package/dist/plugins/codex/src/mcp.js +26 -88
  15. package/dist/plugins/codex/src/text.js +3 -3
  16. package/dist/plugins/dsh/tools.js +8 -4
  17. package/dist/plugins/mcp/operations.d.ts +15 -0
  18. package/dist/plugins/mcp/operations.js +43 -0
  19. package/dist/plugins/mcp/server.d.ts +14 -0
  20. package/dist/plugins/mcp/server.js +13 -0
  21. package/dist/plugins/pi/budget.d.ts +1 -1
  22. package/dist/plugins/pi/budget.js +3 -2
  23. package/dist/plugins/pi/entries.d.ts +1 -0
  24. package/dist/plugins/pi/entries.js +1 -0
  25. package/dist/plugins/pi/history-tools.js +2 -1
  26. package/dist/plugins/pi/history.js +18 -1
  27. package/dist/plugins/pi/notes/tools.js +7 -3
  28. package/dist/plugins/pi/render.d.ts +7 -1
  29. package/dist/plugins/pi/render.js +2 -2
  30. package/dist/plugins/pi/reset/lifecycle.d.ts +1 -1
  31. package/dist/plugins/pi/reset/lifecycle.js +8 -9
  32. package/dist/plugins/pi/runtime.js +102 -61
  33. package/dist/plugins/pi/tool-result.js +7 -7
  34. package/dist/plugins/pi/window.d.ts +33 -3
  35. package/dist/plugins/pi/window.js +209 -9
  36. package/dist/src/boot/render.js +18 -15
  37. package/dist/src/boot/text.d.ts +3 -1
  38. package/dist/src/boot/text.js +22 -20
  39. package/dist/src/budget/text.d.ts +2 -2
  40. package/dist/src/budget/text.js +13 -13
  41. package/dist/src/history/claude.d.ts +2 -0
  42. package/dist/src/history/claude.js +46 -0
  43. package/dist/src/history/codex-transcript.js +7 -5
  44. package/dist/src/history/codex.js +3 -0
  45. package/dist/src/history/corpus.d.ts +28 -1
  46. package/dist/src/history/corpus.js +40 -0
  47. package/dist/src/history/history.d.ts +37 -46
  48. package/dist/src/history/history.js +21 -40
  49. package/dist/src/history/local.js +67 -32
  50. package/dist/src/history/pi.d.ts +2 -1
  51. package/dist/src/history/pi.js +122 -48
  52. package/dist/src/history/prefilter.js +76 -19
  53. package/dist/src/history/query.d.ts +28 -49
  54. package/dist/src/history/query.js +83 -68
  55. package/dist/src/history/summary-cache.d.ts +8 -1
  56. package/dist/src/history/summary-cache.js +138 -12
  57. package/dist/src/index.d.ts +1 -1
  58. package/dist/src/index.js +1 -1
  59. package/dist/src/notes/errors.d.ts +1 -1
  60. package/dist/src/notes/frontmatter.d.ts +0 -2
  61. package/dist/src/notes/frontmatter.js +0 -2
  62. package/dist/src/notes/index.d.ts +1 -1
  63. package/dist/src/notes/index.js +1 -1
  64. package/dist/src/notes/policy.d.ts +15 -1
  65. package/dist/src/notes/policy.js +46 -5
  66. package/dist/src/notes/store.d.ts +12 -0
  67. package/dist/src/notes/store.js +16 -20
  68. package/dist/src/text-match.d.ts +10 -1
  69. package/dist/src/text-match.js +42 -3
  70. package/dist/src/tools/dream.d.ts +22 -93
  71. package/dist/src/tools/dream.js +30 -27
  72. package/dist/src/tools/history.d.ts +33 -26
  73. package/dist/src/tools/history.js +257 -163
  74. package/dist/src/tools/notes.d.ts +51 -163
  75. package/dist/src/tools/notes.js +146 -100
  76. package/dist/src/tools/output.d.ts +2 -1
  77. package/dist/src/tools/output.js +2 -1
  78. package/dist/src/tools/result.d.ts +4 -7
  79. package/dist/src/tools/result.js +8 -9
  80. package/dist/src/tools/schema.d.ts +4 -1
  81. package/dist/src/tools/schema.js +25 -1
  82. package/dist/test/agent-loop.test.js +198 -16
  83. package/dist/test/antigravity-live.test.d.ts +1 -0
  84. package/dist/test/antigravity-live.test.js +142 -0
  85. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  86. package/dist/test/antigravity-plugin.test.js +101 -0
  87. package/dist/test/boot.integration.test.js +133 -14
  88. package/dist/test/claude-history.test.js +14 -13
  89. package/dist/test/claude-mod.test.js +9 -6
  90. package/dist/test/codex-history.test.js +15 -3
  91. package/dist/test/codex-plugin.test.js +76 -38
  92. package/dist/test/dependencies.test.js +7 -3
  93. package/dist/test/dream-skill.test.js +3 -3
  94. package/dist/test/dream-tools.test.js +101 -56
  95. package/dist/test/dsh.test.js +34 -19
  96. package/dist/test/helpers/dependency-graph.js +2 -2
  97. package/dist/test/helpers/extension.d.ts +65 -2
  98. package/dist/test/helpers/extension.js +72 -3
  99. package/dist/test/history-corpus.test.js +79 -77
  100. package/dist/test/history-summary-cache.test.js +97 -9
  101. package/dist/test/history.integration.test.js +234 -168
  102. package/dist/test/host-neutral.test.js +69 -19
  103. package/dist/test/marker.test.js +1 -1
  104. package/dist/test/note-policy.test.js +96 -77
  105. package/dist/test/notes.integration.test.js +212 -94
  106. package/dist/test/notes.test.js +184 -113
  107. package/dist/test/pi-render.test.js +20 -12
  108. package/dist/test/project-namespace.test.js +3 -2
  109. package/dist/test/reset-lifecycle.test.js +2 -2
  110. package/docs/antigravity.md +44 -0
  111. package/docs/architecture.md +6 -4
  112. package/docs/claude-code-mod.md +2 -2
  113. package/docs/codex.md +36 -38
  114. package/docs/dsh.md +3 -3
  115. package/docs/history-sessions.md +28 -50
  116. package/docs/notes-library.md +4 -4
  117. package/docs/skills.md +3 -3
  118. package/docs/tool-results.md +47 -28
  119. package/package.json +3 -2
  120. package/playbook.md +1 -1
  121. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  122. package/plugins/antigravity/hooks.json +7 -0
  123. package/plugins/antigravity/mcp_config.json +8 -0
  124. package/plugins/antigravity/plugin.json +6 -0
  125. package/plugins/antigravity/src/cli.ts +22 -0
  126. package/plugins/antigravity/src/hooks.ts +51 -0
  127. package/plugins/antigravity/src/identity.ts +127 -0
  128. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  129. package/plugins/claude/dist/claude/helper.js +1059 -534
  130. package/plugins/claude/hooks/register.ts +2 -2
  131. package/plugins/claude/playbook.md +1 -1
  132. package/plugins/claude/skills/dream/SKILL.md +1 -1
  133. package/plugins/claude/skills/notesoup/SKILL.md +92 -0
  134. package/plugins/claude/src/helper.ts +2 -1
  135. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  136. package/plugins/codex/.mcp.json +11 -0
  137. package/plugins/codex/README.md +5 -21
  138. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  139. package/plugins/codex/src/hooks.ts +1 -0
  140. package/plugins/codex/src/identity.ts +14 -1
  141. package/plugins/codex/src/mcp.ts +28 -98
  142. package/plugins/codex/src/text.ts +3 -3
  143. package/plugins/dsh/tools.ts +8 -4
  144. package/plugins/mcp/operations.ts +50 -0
  145. package/plugins/mcp/server.ts +23 -0
  146. package/plugins/paseo/README.md +5 -10
  147. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  148. package/plugins/paseo/client/markdown.tsx +50 -38
  149. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  150. package/plugins/paseo/client/paper-card.tsx +6 -5
  151. package/plugins/paseo/client/paper-palette.ts +2 -9
  152. package/plugins/paseo/client/sticky-card.tsx +2 -2
  153. package/plugins/paseo/client/tool-result.ts +7 -14
  154. package/plugins/paseo/package-lock.json +3406 -0
  155. package/plugins/paseo/package.json +1 -0
  156. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  157. package/plugins/pi/budget.ts +3 -3
  158. package/plugins/pi/entries.ts +1 -0
  159. package/plugins/pi/history-tools.ts +2 -1
  160. package/plugins/pi/history.ts +30 -1
  161. package/plugins/pi/notes/tools.ts +7 -3
  162. package/plugins/pi/render.ts +6 -6
  163. package/plugins/pi/reset/lifecycle.ts +9 -10
  164. package/plugins/pi/runtime.ts +96 -60
  165. package/plugins/pi/tool-result.ts +8 -8
  166. package/plugins/pi/window.ts +198 -9
  167. package/skills/dream/SKILL.md +1 -1
  168. package/skills/notesoup/SKILL.md +92 -0
  169. package/src/boot/render.ts +18 -15
  170. package/src/boot/text.ts +23 -19
  171. package/src/budget/text.ts +13 -13
  172. package/src/history/claude.ts +41 -0
  173. package/src/history/codex-transcript.ts +6 -4
  174. package/src/history/codex.ts +2 -0
  175. package/src/history/corpus.ts +51 -2
  176. package/src/history/history.ts +35 -44
  177. package/src/history/local.ts +67 -27
  178. package/src/history/pi.ts +113 -35
  179. package/src/history/prefilter.ts +73 -15
  180. package/src/history/query.ts +93 -73
  181. package/src/history/summary-cache.ts +142 -17
  182. package/src/index.ts +1 -1
  183. package/src/notes/errors.ts +1 -1
  184. package/src/notes/frontmatter.ts +0 -3
  185. package/src/notes/index.ts +1 -1
  186. package/src/notes/policy.ts +44 -5
  187. package/src/notes/store.ts +17 -20
  188. package/src/text-match.ts +46 -4
  189. package/src/tools/dream.ts +29 -31
  190. package/src/tools/history.ts +249 -142
  191. package/src/tools/notes.ts +145 -113
  192. package/src/tools/output.ts +2 -1
  193. package/src/tools/result.ts +12 -11
  194. package/src/tools/schema.ts +24 -1
  195. package/plugins/claude/skills/memory/SKILL.md +0 -69
  196. package/plugins/codex/mcp.json +0 -10
  197. package/plugins/codex/plugin.json +0 -6
  198. package/plugins/paseo/client/markdown-core.tsx +0 -189
  199. package/plugins/paseo/client/typography.ts +0 -24
  200. package/skills/memory/SKILL.md +0 -69
@@ -7849,9 +7849,84 @@ __export(typebox_exports, {
7849
7849
  With: () => With2
7850
7850
  });
7851
7851
 
7852
+ // src/text-match.ts
7853
+ var InvalidQueryError = class extends Error {
7854
+ constructor(message) {
7855
+ super(message);
7856
+ this.name = "InvalidQueryError";
7857
+ }
7858
+ };
7859
+ function searchQueries(query) {
7860
+ const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
7861
+ if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
7862
+ if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
7863
+ return candidates.filter((candidate) => candidate !== "");
7864
+ }
7865
+ function prefixFit(text, fits) {
7866
+ if (fits(text)) return text;
7867
+ const chars = Array.from(text);
7868
+ let low = 0;
7869
+ let high = chars.length;
7870
+ while (low < high) {
7871
+ const mid = Math.ceil((low + high) / 2);
7872
+ if (fits(chars.slice(0, mid).join(""))) low = mid;
7873
+ else high = mid - 1;
7874
+ }
7875
+ return chars.slice(0, low).join("");
7876
+ }
7877
+ function compileSearchQueries(queries) {
7878
+ return queries.map((query) => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu"));
7879
+ }
7880
+ function codePointCount(text, utf16End = text.length) {
7881
+ let count = utf16End;
7882
+ for (let i = 0; i < utf16End - 1; i++) {
7883
+ const code = text.charCodeAt(i);
7884
+ if (code >= 55296 && code <= 56319) {
7885
+ const next = text.charCodeAt(i + 1);
7886
+ if (next >= 56320 && next <= 57343) {
7887
+ count--;
7888
+ i++;
7889
+ }
7890
+ }
7891
+ }
7892
+ return count;
7893
+ }
7894
+ function sliceCodePoints(text, start, limit) {
7895
+ const len = text.length;
7896
+ let utf16Start = 0;
7897
+ let cp = 0;
7898
+ while (cp < start && utf16Start < len) {
7899
+ const code = text.charCodeAt(utf16Start);
7900
+ utf16Start += code >= 55296 && code <= 56319 && utf16Start + 1 < len && text.charCodeAt(utf16Start + 1) >= 56320 && text.charCodeAt(utf16Start + 1) <= 57343 ? 2 : 1;
7901
+ cp++;
7902
+ }
7903
+ let utf16End = utf16Start;
7904
+ let taken = 0;
7905
+ while (taken < limit && utf16End < len) {
7906
+ const code = text.charCodeAt(utf16End);
7907
+ utf16End += code >= 55296 && code <= 56319 && utf16End + 1 < len && text.charCodeAt(utf16End + 1) >= 56320 && text.charCodeAt(utf16End + 1) <= 57343 ? 2 : 1;
7908
+ taken++;
7909
+ }
7910
+ const truncated2 = start > 0 || utf16End < len;
7911
+ return { text: truncated2 ? text.slice(utf16Start, utf16End) : text, truncated: truncated2 };
7912
+ }
7913
+ function earliestMatchOffsetChars(text, queries) {
7914
+ let earliest = -1;
7915
+ for (const query of queries) {
7916
+ const pattern = typeof query === "string" ? new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu") : query;
7917
+ const index = pattern.exec(text)?.index ?? -1;
7918
+ if (index < 0) continue;
7919
+ if (earliest < 0 || index < earliest) earliest = index;
7920
+ }
7921
+ return earliest < 0 ? -1 : codePointCount(text, earliest);
7922
+ }
7923
+
7852
7924
  // src/history/history.ts
7853
- var HistoryRoleSchema = typebox_exports.Union([typebox_exports.Literal("user"), typebox_exports.Literal("assistant"), typebox_exports.Literal("tool"), typebox_exports.Literal("context")]);
7854
- var ToolCallStatusSchema = typebox_exports.Union([typebox_exports.Literal("ok"), typebox_exports.Literal("error"), typebox_exports.Literal("unfinished")]);
7925
+ function stringEnum(values, options = {}) {
7926
+ return typebox_exports.Unsafe({ ...typebox_exports.Enum([...values], options), type: "string" });
7927
+ }
7928
+ var HistoryRoleSchema = stringEnum(["user", "assistant", "tool", "context"]);
7929
+ var ToolCallStatusSchema = stringEnum(["ok", "error", "unfinished"]);
7855
7930
  function isTextContent(part) {
7856
7931
  return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
7857
7932
  }
@@ -7938,16 +8013,6 @@ function projectHistory(rawWindows, highestSeq, branchSeqs) {
7938
8013
  }));
7939
8014
  return { windows, highestSeq, branchSeqs, pairedResults };
7940
8015
  }
7941
- var NestedCallSummarySchema = typebox_exports.Object({
7942
- call_count: typebox_exports.Integer({ minimum: 0 }),
7943
- complete: typebox_exports.Boolean({ description: "true = every nested call was recorded." })
7944
- }, { additionalProperties: false });
7945
- var ToolSummarySchema = typebox_exports.Object({
7946
- tool: typebox_exports.Optional(typebox_exports.String()),
7947
- tool_status: typebox_exports.Optional(ToolCallStatusSchema),
7948
- output_truncated: typebox_exports.Optional(typebox_exports.Literal(true)),
7949
- full_output_path: typebox_exports.Optional(typebox_exports.String())
7950
- }, { additionalProperties: false });
7951
8016
  function toolSummary(event) {
7952
8017
  const execution = event.execution;
7953
8018
  if (!execution) return {};
@@ -7962,39 +8027,19 @@ function nestedCallSummary(event) {
7962
8027
  const nested = event.execution?.nestedCalls;
7963
8028
  return nested === void 0 ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
7964
8029
  }
7965
- var HistoryFoldedRowSchema = typebox_exports.Object({
7966
- session: typebox_exports.Optional(typebox_exports.String()),
7967
- first_seq: typebox_exports.Integer({ minimum: 1 }),
7968
- last_seq: typebox_exports.Integer({ minimum: 1 }),
7969
- count: typebox_exports.Integer({ minimum: 1 }),
7970
- tools: typebox_exports.Record(typebox_exports.String(), typebox_exports.Integer({ minimum: 1 }), { description: "Count per tool name." })
7971
- }, { additionalProperties: false });
7972
- var HistoryPageItemSchema = typebox_exports.Object({
7973
- session: typebox_exports.Optional(typebox_exports.String()),
7974
- folded_before: typebox_exports.Optional(HistoryFoldedRowSchema),
7975
- context: typebox_exports.Optional(typebox_exports.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
7976
- seq: typebox_exports.Integer({ minimum: 1 }),
7977
- role: HistoryRoleSchema,
7978
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
7979
- ...ToolSummarySchema.properties,
7980
- content: typebox_exports.String(),
7981
- truncated: typebox_exports.Boolean({ description: "Preview is partial." }),
7982
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, description: "Where the preview starts." }))
7983
- }, { additionalProperties: false });
7984
8030
  var MAX_FOLD_TOOL_NAMES = 20;
7985
8031
  var MAX_FOLD_TOOL_NAME_CHARS = 120;
7986
8032
  function visibleItem(event, maxChars, matchOffset) {
7987
8033
  const document = eventDocument(event);
7988
- const chars = Array.from(document);
7989
8034
  const start = matchOffset ?? 0;
7990
8035
  const limit = Math.max(0, maxChars);
7991
- const truncated2 = start > 0 || start + limit < chars.length;
8036
+ const { text: content, truncated: truncated2 } = sliceCodePoints(document, start, limit);
7992
8037
  return {
7993
8038
  seq: event.seq,
7994
8039
  role: event.role,
7995
8040
  created_at: event.createdAt ?? null,
7996
8041
  ...toolSummary(event),
7997
- content: truncated2 ? chars.slice(start, start + limit).join("") : document,
8042
+ content,
7998
8043
  truncated: truncated2,
7999
8044
  ...matchOffset === void 0 ? {} : { offset_chars: matchOffset }
8000
8045
  };
@@ -8002,18 +8047,26 @@ function visibleItem(event, maxChars, matchOffset) {
8002
8047
  function allItems(projection) {
8003
8048
  return projection.windows.flatMap((current) => current.items);
8004
8049
  }
8050
+ var timestamps = /* @__PURE__ */ new WeakMap();
8051
+ function eventTimestampMs(event) {
8052
+ const cached = timestamps.get(event);
8053
+ if (cached !== void 0) return cached;
8054
+ const parsed = event.createdAt ? Date.parse(event.createdAt) : NaN;
8055
+ timestamps.set(event, parsed);
8056
+ return parsed;
8057
+ }
8005
8058
  function compareBound(event, bound) {
8006
- return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
8059
+ return "seq" in bound ? event.seq - bound.seq : eventTimestampMs(event) - bound.at;
8007
8060
  }
8008
- function matchesFilter(event, { after, before, roles }) {
8009
- return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0) && (!roles || roles.includes(event.role));
8061
+ function matchesFilter(event, { after, before, since, until, roles }) {
8062
+ return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0) && (since === void 0 || eventTimestampMs(event) > since) && (until === void 0 || eventTimestampMs(event) < until) && (!roles || roles.includes(event.role));
8010
8063
  }
8011
8064
  function filteredItems(projection, params) {
8012
8065
  return allItems(projection).filter((event) => matchesFilter(event, params)).sort((a, b) => a.seq - b.seq);
8013
8066
  }
8014
8067
 
8015
8068
  // src/tools/schema.ts
8016
- 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." }));
8069
+ var historyRoles = (foldsWithoutRoles = false) => typebox_exports.Optional(typebox_exports.Array(HistoryRoleSchema, { minItems: 1, description: "Filter by event role." + (foldsWithoutRoles ? " Omit to fold tool and context runs." : "") }));
8017
8070
  function paramProblem(schema, params) {
8018
8071
  const first = Errors2(schema, params).find((error) => error.keyword !== "boolean");
8019
8072
  if (!first) return "unrecognized shape";
@@ -8022,6 +8075,24 @@ function paramProblem(schema, params) {
8022
8075
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
8023
8076
  }
8024
8077
  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 });
8078
+ function parseIsoTimestamp(value) {
8079
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:?\d{2})?)?$/.exec(value);
8080
+ if (!match) return void 0;
8081
+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
8082
+ const hour = Number(match[4] ?? 0), minute = Number(match[5] ?? 0), second = Number(match[6] ?? 0);
8083
+ if (hour > 23 || minute > 59 || second > 59) return void 0;
8084
+ const check = /* @__PURE__ */ new Date(0);
8085
+ check.setUTCFullYear(year, month - 1, day);
8086
+ if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) return void 0;
8087
+ if (match[8]) {
8088
+ const at = Date.parse(value);
8089
+ return Number.isFinite(at) ? at : void 0;
8090
+ }
8091
+ const ms = match[7] ? Number(match[7].slice(0, 3).padEnd(3, "0")) : 0;
8092
+ const local = new Date(year, month - 1, day, hour, minute, second, ms);
8093
+ local.setFullYear(year, month - 1, day);
8094
+ return Number.isFinite(local.getTime()) ? local.getTime() : void 0;
8095
+ }
8025
8096
 
8026
8097
  // src/notes/errors.ts
8027
8098
  var NoteError = class extends Error {
@@ -8163,15 +8234,19 @@ function addressFor(identity2, scope, path, who) {
8163
8234
  }
8164
8235
 
8165
8236
  // src/notes/policy.ts
8166
- var DEFAULT_NOTE_BUDGET = 4096;
8237
+ var DEFAULT_NOTE_BUDGET = 8192;
8238
+ var DEFAULT_CHEATSHEET_BUDGET = 4096;
8167
8239
  var MAX_PINNED_NOTES = 5;
8240
+ var WARNING_OPEN_TAG = "<notesoup:warning>";
8241
+ var WARNING_CLOSE_TAG = "</notesoup:warning>";
8242
+ var MAX_DESCRIPTION_CHARS = 160;
8168
8243
  var DEFAULT_PINNED_PAGES = ["CHEATSHEET.md"];
8169
8244
  function validateNotePolicy(fields) {
8170
8245
  for (const key of ["pinned", "readonly"]) {
8171
8246
  if (fields[key] !== void 0 && typeof fields[key] !== "boolean") throw new NoteError("invalid_policy", `${key} must be a boolean.`);
8172
8247
  }
8173
8248
  if (fields.budget !== void 0 && (!Number.isSafeInteger(fields.budget) || fields.budget <= 0)) {
8174
- throw new NoteError("invalid_policy", "budget must be a positive safe integer of Unicode code points.");
8249
+ throw new NoteError("invalid_policy", "budget must be a positive integer.");
8175
8250
  }
8176
8251
  }
8177
8252
  function effectiveNotePolicy(fields, path) {
@@ -8179,7 +8254,7 @@ function effectiveNotePolicy(fields, path) {
8179
8254
  const defaultPage = DEFAULT_PINNED_PAGES.some((page) => page === path);
8180
8255
  return {
8181
8256
  pinned: fields.pinned ?? defaultPage,
8182
- budget: fields.budget ?? (defaultPage ? 2048 : DEFAULT_NOTE_BUDGET),
8257
+ budget: fields.budget ?? (defaultPage ? DEFAULT_CHEATSHEET_BUDGET : DEFAULT_NOTE_BUDGET),
8183
8258
  readonly: fields.readonly ?? false
8184
8259
  };
8185
8260
  }
@@ -8187,9 +8262,39 @@ function pinnedPageOrder(path) {
8187
8262
  const index = DEFAULT_PINNED_PAGES.findIndex((page) => page === path);
8188
8263
  return index === -1 ? DEFAULT_PINNED_PAGES.length : index;
8189
8264
  }
8265
+ function truncateToUtf8Bytes(text, maxBytes) {
8266
+ if (Buffer.byteLength(text, "utf8") <= maxBytes) return { text, shownChars: 0, totalChars: 0, truncated: false };
8267
+ const chars = Array.from(text);
8268
+ let bytes = 0;
8269
+ let shown2 = 0;
8270
+ for (const char of chars) {
8271
+ const size = Buffer.byteLength(char, "utf8");
8272
+ if (bytes + size > maxBytes) break;
8273
+ bytes += size;
8274
+ shown2++;
8275
+ }
8276
+ return { text: chars.slice(0, shown2).join(""), shownChars: shown2, totalChars: chars.length, truncated: true };
8277
+ }
8278
+ function renderWarnings(warnings) {
8279
+ if (warnings.length === 0) return "";
8280
+ if (warnings.length === 1) return `${WARNING_OPEN_TAG}${warnings[0]}${WARNING_CLOSE_TAG}`;
8281
+ return `${WARNING_OPEN_TAG}
8282
+ ${warnings.join("\n")}
8283
+ ${WARNING_CLOSE_TAG}`;
8284
+ }
8190
8285
  function noteBudgetWarnings(body, policy) {
8191
- const count = Array.from(body).length;
8192
- return count > policy.budget ? [`Warning: note body is ${count} Unicode code points, over budget ${policy.budget} \u2014 boil it down.`] : [];
8286
+ const bytes = Buffer.byteLength(body, "utf8");
8287
+ if (bytes <= policy.budget) return [];
8288
+ const action = policy.pinned ? "boot truncates it to budget \u2014 trim, split, or unpin." : "trim or split it.";
8289
+ return [`note body is ${bytes} bytes (budget ${policy.budget}); ${action}`];
8290
+ }
8291
+ function noteDescriptionWarnings(description) {
8292
+ if (description === void 0) return [];
8293
+ const count = Array.from(description).length;
8294
+ return count > MAX_DESCRIPTION_CHARS ? [`description is ${count} chars (max ${MAX_DESCRIPTION_CHARS}); boot index truncates it.`] : [];
8295
+ }
8296
+ function noteWarnings(body, policy, description) {
8297
+ return [...noteBudgetWarnings(body, policy), ...noteDescriptionWarnings(description)];
8193
8298
  }
8194
8299
  function assertNoteUnlocked(fields, unlock) {
8195
8300
  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).");
@@ -8206,7 +8311,6 @@ var SCOPES = ["session", "project", "human", "agent", "model"];
8206
8311
  var ORIGINS = ["user", "self", "external"];
8207
8312
  var TIMESTAMP_KEYS = ["createdAt", "updatedAt", "lastAccessed"];
8208
8313
  var KNOWN_KEYS = ["pinned", "budget", "readonly", "description", "origin", "crumpledAt", "createdAt", "updatedAt", "lastAccessed", "accessCount", "sourceWindow", "supersedes", "recurrenceCount", "recurrenceWindows"];
8209
- var MAX_DESCRIPTION_CHARS = 160;
8210
8314
  function collapseDescription(value) {
8211
8315
  const collapsed = value.replace(/\s+/g, " ").trim();
8212
8316
  return collapsed.length === 0 ? void 0 : collapsed;
@@ -8341,42 +8445,6 @@ import { randomUUID as randomUUID2 } from "node:crypto";
8341
8445
  import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
8342
8446
  import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
8343
8447
 
8344
- // src/text-match.ts
8345
- var InvalidQueryError = class extends Error {
8346
- constructor(message) {
8347
- super(message);
8348
- this.name = "InvalidQueryError";
8349
- }
8350
- };
8351
- function searchQueries(query) {
8352
- const candidates = query === void 0 ? [] : typeof query === "string" ? [query] : query;
8353
- if (!Array.isArray(candidates)) throw new InvalidQueryError("`query` must be a string or a list of strings.");
8354
- if (!candidates.every((candidate) => typeof candidate === "string")) throw new InvalidQueryError("Every item in the `query` list must be a string.");
8355
- return candidates.filter((candidate) => candidate !== "");
8356
- }
8357
- function prefixFit(text, fits) {
8358
- if (fits(text)) return text;
8359
- const chars = Array.from(text);
8360
- let low = 0;
8361
- let high = chars.length;
8362
- while (low < high) {
8363
- const mid = Math.ceil((low + high) / 2);
8364
- if (fits(chars.slice(0, mid).join(""))) low = mid;
8365
- else high = mid - 1;
8366
- }
8367
- return chars.slice(0, low).join("");
8368
- }
8369
- function earliestMatchOffsetChars(text, queries) {
8370
- let earliest = -1;
8371
- for (const query of queries) {
8372
- const literal = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
8373
- const index = new RegExp(literal, "iu").exec(text)?.index ?? -1;
8374
- if (index < 0) continue;
8375
- if (earliest < 0 || index < earliest) earliest = index;
8376
- }
8377
- return earliest < 0 ? -1 : Array.from(text.slice(0, earliest)).length;
8378
- }
8379
-
8380
8448
  // src/notes/identity.ts
8381
8449
  import { resolve } from "node:path";
8382
8450
  function requireString(field, value) {
@@ -8620,6 +8688,9 @@ function projectKey(cwd, home) {
8620
8688
  }
8621
8689
 
8622
8690
  // src/notes/store.ts
8691
+ function compareNoteRows(a, b) {
8692
+ return b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address);
8693
+ }
8623
8694
  var lastWriteStamp = 0;
8624
8695
  function writeStamp() {
8625
8696
  const now = Date.now();
@@ -8730,13 +8801,6 @@ function assertOrigin(value) {
8730
8801
  if (!isOrigin(value)) throw new NoteError("invalid_origin", `origin must be one of user, self, external (got ${JSON.stringify(value)})`);
8731
8802
  return value;
8732
8803
  }
8733
- function normalizeDescription(value) {
8734
- const collapsed = collapseDescription(value);
8735
- if (collapsed === void 0) return void 0;
8736
- const count = Array.from(collapsed).length;
8737
- if (count > MAX_DESCRIPTION_CHARS) throw new NoteError("invalid_description", `description is ${count} characters; limit is ${MAX_DESCRIPTION_CHARS}.`);
8738
- return collapsed;
8739
- }
8740
8804
  function assertWho(value, scope) {
8741
8805
  if (typeof value !== "string" || !(scope === "session" ? isSessionId(value) : SLUG_PATTERN.test(value))) {
8742
8806
  throw new NoteError("invalid_scope", scope === "session" ? "session id must be a safe single directory component" : "who must be a canonical lowercase slug");
@@ -8826,7 +8890,7 @@ function createNotesStore(input) {
8826
8890
  async function write(address, content, options = {}) {
8827
8891
  const stableOptions = { ...options };
8828
8892
  validateNotePolicy(stableOptions);
8829
- const description = stableOptions.description === void 0 ? void 0 : normalizeDescription(stableOptions.description);
8893
+ const description = stableOptions.description === void 0 ? void 0 : collapseDescription(stableOptions.description);
8830
8894
  const destination = assertAddress(address);
8831
8895
  assertWritablePath(destination.path);
8832
8896
  const scope = destination.scope;
@@ -8864,7 +8928,7 @@ function createNotesStore(input) {
8864
8928
  assertSerializedSize(serialized);
8865
8929
  await assertPinAdmission(root, noteFileName(destination.path), meta, previous);
8866
8930
  await atomicWrite(path, serialized);
8867
- return { meta, outcome, warnings: noteBudgetWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path))) };
8931
+ return { meta, outcome, warnings: noteWarnings(cleanBody, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description) };
8868
8932
  }));
8869
8933
  }
8870
8934
  async function read(address) {
@@ -8886,7 +8950,7 @@ function createNotesStore(input) {
8886
8950
  const operations = edits === void 0 ? [] : edits.map((operation) => ({ ...operation }));
8887
8951
  const stableOptions = { ...options };
8888
8952
  validateNotePolicy(stableOptions);
8889
- const description = stableOptions.description === void 0 ? void 0 : normalizeDescription(stableOptions.description);
8953
+ const description = stableOptions.description === void 0 ? void 0 : collapseDescription(stableOptions.description);
8890
8954
  const from = assertAddress(address);
8891
8955
  const destination = stableOptions.renameTo === void 0 ? from : assertAddress(stableOptions.renameTo);
8892
8956
  assertWritablePath(destination.path);
@@ -8931,13 +8995,15 @@ function createNotesStore(input) {
8931
8995
  const newText = operation?.newText;
8932
8996
  if (typeof oldText !== "string" || oldText.length === 0) throw new NoteError("invalid_edit", `edits[${index}].oldText must be a non-empty string.`, { editIndex: index });
8933
8997
  if (typeof newText !== "string") throw new NoteError("invalid_edit", `edits[${index}].newText must be a string.`, { editIndex: index });
8998
+ if (operation.replaceAll !== void 0 && typeof operation.replaceAll !== "boolean") throw new NoteError("invalid_edit", `edits[${index}].replaceAll must be a boolean.`, { editIndex: index });
8999
+ const replaceAll = operation.replaceAll ?? stableOptions.replaceAll ?? false;
8934
9000
  const lines = matchLineNumbers(next, oldText);
8935
9001
  if (lines.length === 0) throw new NoteError("no_match", `edits[${index}].oldText isn't in the note${index > 0 ? " (after the earlier edits)" : ""}. Nothing was saved.`, { editIndex: index });
8936
- if (lines.length > 1 && !stableOptions.replaceAll) {
9002
+ if (lines.length > 1 && !replaceAll) {
8937
9003
  throw new NoteError("ambiguous_edit", `edits[${index}].oldText appears ${lines.length} times (${anchorLines(lines)}); add surrounding text to pick one, or set replace_all. Nothing was saved.`, { lineNumbers: lines, editIndex: index });
8938
9004
  }
8939
9005
  if (oldText !== newText) applied++;
8940
- if (stableOptions.replaceAll) next = next.split(oldText).join(newText);
9006
+ if (replaceAll) next = next.split(oldText).join(newText);
8941
9007
  else {
8942
9008
  const matchIndex = next.indexOf(oldText);
8943
9009
  next = next.substring(0, matchIndex) + newText + next.substring(matchIndex + oldText.length);
@@ -8968,7 +9034,7 @@ function createNotesStore(input) {
8968
9034
  );
8969
9035
  await atomicWrite(sameFile ? sourceReal : path, serialized);
8970
9036
  if (moved) await rm(fromPath, { force: true });
8971
- return { meta, warnings: noteBudgetWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path))), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
9037
+ return { meta, warnings: noteWarnings(next, effectiveNotePolicy(meta, noteFileName(destination.path)), meta.description), applied, resolvedScope: scope, change, moved, replacedCrumpledTarget: moved && targetRaw !== void 0 };
8972
9038
  };
8973
9039
  return withPathQueues([fromRoot, root], () => withPathQueues([fromPath, path], mutate));
8974
9040
  }
@@ -9036,7 +9102,7 @@ function createNotesStore(input) {
9036
9102
  for await (const row of scan(stableOptions, status)) {
9037
9103
  rows.push({ ...row, sizeBytes: Buffer.byteLength(row.body, "utf8") });
9038
9104
  }
9039
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
9105
+ rows.sort(compareNoteRows);
9040
9106
  return { rows, status: status ?? { namespacesUnavailable: [] } };
9041
9107
  }
9042
9108
  function listWithStatus(options = {}) {
@@ -9051,7 +9117,7 @@ function createNotesStore(input) {
9051
9117
  const rows = [];
9052
9118
  for await (const note of scan(stableOptions, status)) {
9053
9119
  const { address, path, scope, meta, body } = note;
9054
- const warnings = noteBudgetWarnings(body, effectiveNotePolicy(meta, path));
9120
+ const warnings = noteWarnings(body, effectiveNotePolicy(meta, path), meta.description);
9055
9121
  if (stableQueries.length === 0) {
9056
9122
  rows.push({ address, path, scope, meta, warnings, matches: [] });
9057
9123
  continue;
@@ -9081,7 +9147,8 @@ var TOOL_OUTPUT_MAX_BYTES = 32 * 1024;
9081
9147
  var TOOL_OUTPUT_LIMIT = `${TOOL_OUTPUT_MAX_BYTES / 1024} KB`;
9082
9148
  var DEFAULT_READ_WINDOW_CHARS = 12e3;
9083
9149
  var MAX_READ_WINDOW_CHARS = 5e4;
9084
- var HISTORY_PREVIEW_CHARS = 1200;
9150
+ var HISTORY_PREVIEW_CHARS = 2500;
9151
+ var HISTORY_READ_WINDOW_CHARS = 8e3;
9085
9152
 
9086
9153
  // src/result.ts
9087
9154
  var OperationErrorSchema = typebox_exports.Object({
@@ -9114,8 +9181,11 @@ function renderOutcome(result, renderData) {
9114
9181
  function structuredBytes(value) {
9115
9182
  return Buffer.byteLength(JSON.stringify(value), "utf8");
9116
9183
  }
9184
+ function fitsText(text) {
9185
+ return Buffer.byteLength(text, "utf8") <= TOOL_OUTPUT_MAX_BYTES;
9186
+ }
9117
9187
  function fitsResult(result, render) {
9118
- return Buffer.byteLength(render(result), "utf8") <= TOOL_OUTPUT_MAX_BYTES && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
9188
+ return fitsText(render(result)) && structuredBytes(wireResult(result)) <= TOOL_OUTPUT_MAX_BYTES;
9119
9189
  }
9120
9190
  var TextWindowSchema = typebox_exports.Object({
9121
9191
  text: typebox_exports.String(),
@@ -9123,10 +9193,10 @@ var TextWindowSchema = typebox_exports.Object({
9123
9193
  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." })
9124
9194
  }, { additionalProperties: false });
9125
9195
  var TextWindowRequestSchema = {
9126
- offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Where on the page to start reading; negative counts from the end." })),
9196
+ offset_chars: typebox_exports.Optional(typebox_exports.Integer({ description: "Character offset to start reading (negative counts from the end)." })),
9127
9197
  max_chars: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much to read at once." }))
9128
9198
  };
9129
- function readTextWindow(text, offset, limit, makeData, render) {
9199
+ function readTextWindow(text, offset, limit, makeData, render, fitsOutcome = (result) => fitsText(render(result))) {
9130
9200
  const chars = Array.from(text);
9131
9201
  const requested = offset ?? 0;
9132
9202
  const start = requested < 0 ? Math.max(0, chars.length + requested) : requested;
@@ -9140,7 +9210,7 @@ function readTextWindow(text, offset, limit, makeData, render) {
9140
9210
  next_offset_chars: end < chars.length ? end : null
9141
9211
  };
9142
9212
  };
9143
- const fits = (delivered2) => fitsResult(success(makeData(window(delivered2))), render);
9213
+ const fits = (delivered2) => fitsOutcome(success(makeData(window(delivered2))));
9144
9214
  if (fits(range)) return success(makeData(window(range)));
9145
9215
  const delivered = Array.from(prefixFit(window(range).text, (candidate) => fits(Array.from(candidate).length))).length;
9146
9216
  if (delivered === 0) return failure("output_too_large", `Its header alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry; no room left for the text.`);
@@ -9150,7 +9220,7 @@ function renderTextWindow(window) {
9150
9220
  const next = window.next_offset_chars;
9151
9221
  return next === null ? window.text : `${window.text}
9152
9222
 
9153
- [truncated; continue at offset_chars=${next}]`;
9223
+ [truncated at ${next}/${window.total_chars} chars; continue at offset_chars=${next}]`;
9154
9224
  }
9155
9225
 
9156
9226
  // src/tools/notes-context.ts
@@ -9176,15 +9246,14 @@ function notesIdentityForCall(context2, cwd) {
9176
9246
  }
9177
9247
 
9178
9248
  // src/tools/notes.ts
9179
- var ORIGIN_VALUES = [typebox_exports.Literal("user"), typebox_exports.Literal("self"), typebox_exports.Literal("external")];
9180
- var ORIGIN = typebox_exports.Optional(typebox_exports.Union([...ORIGIN_VALUES], {
9181
- description: "Whose handwriting: user, self, or external. Leave it out to keep what's there."
9249
+ var ORIGIN_VALUES = ["user", "self", "external"];
9250
+ var ORIGIN = typebox_exports.Optional(stringEnum(ORIGIN_VALUES, {
9251
+ description: "Author tag. Omit to keep existing."
9182
9252
  }));
9183
- var DESCRIPTION_PARAMETER = typebox_exports.Optional(typebox_exports.String({ description: "One-line summary of what's inside and when to open it (max 160 chars). Empty string clears it." }));
9253
+ var DESCRIPTION_PARAMETER = typebox_exports.Optional(typebox_exports.String({ description: "One-line summary for the boot index (empty string clears it)." }));
9184
9254
  var POLICY_PARAMETERS = {
9185
- pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Tape the page inside the cover: read whole at every wake-up. Five per notebook, CHEATSHEET included." })),
9186
- 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." })),
9187
- 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." }))
9255
+ pinned: typebox_exports.Optional(typebox_exports.Boolean({ description: "Inject at wake-up (truncated to byte budget if oversized)." })),
9256
+ readonly: typebox_exports.Optional(typebox_exports.Boolean({ description: "Soft lock against edits, moves, and deletion." }))
9188
9257
  };
9189
9258
  var PolicySchema = {
9190
9259
  pinned: typebox_exports.Boolean(),
@@ -9198,15 +9267,25 @@ function policyAt(meta, address) {
9198
9267
  function renderPolicy(policy) {
9199
9268
  return `pinned ${policy.pinned} | budget ${policy.budget} | readonly ${policy.readonly}`;
9200
9269
  }
9270
+ function renderSparsePolicy(policy, address) {
9271
+ const defaults = effectiveNotePolicy({}, noteFileName(assertAddress(address).path));
9272
+ const tokens = [];
9273
+ if (policy.pinned) tokens.push("pinned");
9274
+ else if (defaults.pinned) tokens.push("pinned false");
9275
+ if (policy.budget !== defaults.budget) tokens.push(`budget ${policy.budget}`);
9276
+ if (policy.readonly) tokens.push("readonly");
9277
+ return tokens.join(" | ");
9278
+ }
9201
9279
  function withWarnings(text, data) {
9202
- return [text, ...data.warnings].join("\n");
9280
+ return data.warnings.length === 0 ? text : `${text}
9281
+ ${renderWarnings(data.warnings)}`;
9203
9282
  }
9204
- 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." }));
9205
- var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Only the crumpled balls." }));
9206
- var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many pages at most." }));
9207
- var GLOB_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Which drawers to open. Leave it out for this session and your current notebooks. `@project/**` one shelf \xB7 `CHEATSHEET.md` that page in every notebook \xB7 `**` everything \xB7 `@sessions/*/**` every session." }));
9283
+ var CRUMPLED_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "Crumple (`true`) or restore (`false`) the note." }));
9284
+ var CRUMPLED_LIST_PARAMETER = typebox_exports.Optional(typebox_exports.Boolean({ description: "List crumpled notes instead of live ones." }));
9285
+ var FILE_LIMIT_PARAMETER = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Maximum notes to return." }));
9286
+ var GLOB_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Address glob. Omit for current notebooks; `**` for all; `@projects/*/**` or `@sessions/*/**` for named notebooks." }));
9208
9287
  var CWD_PARAMETER = typebox_exports.Optional(typebox_exports.String({ minLength: 1, description: "Treat this directory's project as `@project/`." }));
9209
- 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." });
9288
+ var ADDRESS_PARAMETER = typebox_exports.String({ description: "Note address (per boot protocol). Never pass `@` addresses to filesystem tools." });
9210
9289
  function failureOf(error) {
9211
9290
  if (error instanceof NoteError) return failure(error.code, error.message);
9212
9291
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
@@ -9219,7 +9298,7 @@ var MAX_METADATA_VERBATIM_BYTES = 2048;
9219
9298
  var TOO_LARGE_EXTRA_VALUE = "[omitted: too large]";
9220
9299
  var NoteMetadataSchema = typebox_exports.Object({
9221
9300
  ...PolicySchema,
9222
- origin: typebox_exports.Union([...ORIGIN_VALUES]),
9301
+ origin: stringEnum(ORIGIN_VALUES),
9223
9302
  created_at: typebox_exports.String(),
9224
9303
  updated_at: typebox_exports.String(),
9225
9304
  crumpled_at: typebox_exports.Optional(typebox_exports.String()),
@@ -9285,55 +9364,17 @@ var NoteIdentitySchema = {
9285
9364
  project_key: typebox_exports.Optional(typebox_exports.String()),
9286
9365
  ...ProjectReceiptSchema
9287
9366
  };
9288
- var ListedFileSchema = typebox_exports.Object({
9289
- ...NoteIdentitySchema,
9290
- ...PolicySchema,
9291
- ...WarningsSchema,
9292
- updated_at: typebox_exports.String(),
9293
- crumpled_at: typebox_exports.Optional(typebox_exports.String()),
9294
- description: typebox_exports.Optional(typebox_exports.String())
9295
- }, { additionalProperties: false });
9296
- var MatchSchema = typebox_exports.Object({
9297
- line: typebox_exports.Integer(),
9298
- text: typebox_exports.String(),
9299
- offset_chars: typebox_exports.Integer()
9300
- }, { additionalProperties: false });
9301
- var SnapshotSchema = {
9302
- more: typebox_exports.Integer({ description: "How many more were left out." }),
9303
- namespaces_unavailable: typebox_exports.Array(typebox_exports.String(), { description: "Unreadable notebooks or notes." })
9304
- };
9305
- var NotesWriteDataSchema = typebox_exports.Object({
9306
- ...NoteIdentitySchema,
9307
- ...PolicySchema,
9308
- ...WarningsSchema,
9309
- outcome: typebox_exports.Union([typebox_exports.Literal("created"), typebox_exports.Literal("overwrote"), typebox_exports.Literal("uncrumpled")])
9310
- }, { additionalProperties: false });
9311
- var NotesUpdateDataSchema = typebox_exports.Object({
9312
- ...NoteIdentitySchema,
9313
- ...PolicySchema,
9314
- ...WarningsSchema,
9315
- change_kind: typebox_exports.Union([typebox_exports.Literal("none"), typebox_exports.Literal("body"), typebox_exports.Literal("metadata"), typebox_exports.Literal("moved")]),
9316
- rename_from: typebox_exports.Optional(typebox_exports.String())
9317
- }, { additionalProperties: false });
9318
9367
  var NotesReadDataSchema = typebox_exports.Object({
9319
9368
  ...NoteIdentitySchema,
9320
9369
  metadata: NoteMetadataSchema,
9321
9370
  ...WarningsSchema,
9322
9371
  ...TextWindowSchema.properties
9323
9372
  }, { additionalProperties: false });
9324
- var NotesListDataSchema = typebox_exports.Object({
9325
- files: typebox_exports.Array(typebox_exports.Object({
9326
- ...ListedFileSchema.properties,
9327
- matches: typebox_exports.Optional(typebox_exports.Array(MatchSchema)),
9328
- more_matches: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1 }))
9329
- }, { additionalProperties: false })),
9330
- ...SnapshotSchema
9331
- }, { additionalProperties: false });
9332
9373
  function snapshot(rows, limit, status, renderData, shrink) {
9333
9374
  const files = [];
9334
9375
  const data = (selected) => ({ files: selected, more: rows.length - selected.length, namespaces_unavailable: status.namespacesUnavailable });
9335
9376
  const render = (outcome2) => renderOutcome(outcome2, renderData);
9336
- const fits = (item) => fitsResult(success(data([...files, item])), render);
9377
+ const fits = (item) => fitsText(render(success(data([...files, item]))));
9337
9378
  for (const item of rows.slice(0, limit)) {
9338
9379
  if (fits(item)) {
9339
9380
  files.push(item);
@@ -9347,27 +9388,28 @@ function snapshot(rows, limit, status, renderData, shrink) {
9347
9388
  break;
9348
9389
  }
9349
9390
  const outcome = success(data(files));
9350
- return fitsResult(outcome, render) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
9391
+ return fitsText(render(outcome)) ? outcome : failure("output_too_large", `The list of unreachable notebooks is itself over ${TOOL_OUTPUT_LIMIT}; narrow \`glob\` to fewer notebooks.`);
9351
9392
  }
9352
9393
  function listedFile(row, identity2) {
9353
9394
  const policy = policyAt(row.meta, row.address);
9354
- 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 }, ...typeof row.meta.description === "string" ? { description: row.meta.description } : {} };
9395
+ const warnings = row.warnings ?? (row.body === void 0 ? noteDescriptionWarnings(row.meta.description) : noteWarnings(row.body, policy, row.meta.description));
9396
+ return { ...noteIdentity(identity2, row.address), ...policy, warnings, updated_at: localIso(row.meta.updatedAt), ...row.meta.crumpledAt === void 0 ? {} : { crumpled_at: row.meta.crumpledAt }, ...typeof row.meta.description === "string" ? { description: row.meta.description } : {} };
9355
9397
  }
9356
- var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "The whole page." }), origin: ORIGIN, description: DESCRIPTION_PARAMETER, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9398
+ var notesWriteParameters = typebox_exports.Object({ address: ADDRESS_PARAMETER, content: typebox_exports.String({ description: "Full markdown body." }), origin: ORIGIN, description: DESCRIPTION_PARAMETER, ...POLICY_PARAMETERS, cwd: CWD_PARAMETER }, { additionalProperties: false });
9357
9399
  function renderWriteData(data) {
9358
- return withWarnings(`${data.outcome} ${renderIdentity(data)} | ${renderPolicy(data)}`, data);
9400
+ const sparse = renderSparsePolicy(data, data.address);
9401
+ return withWarnings(`${data.outcome} ${renderIdentity(data)}${sparse === "" ? "" : ` | ${sparse}`}`, data);
9359
9402
  }
9360
9403
  var notesWrite = {
9361
9404
  name: "notes_write",
9362
9405
  label: "Notes write",
9363
- 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.",
9406
+ description: "Create or overwrite a note. Set `description` (one line) so boot indexes it.",
9364
9407
  parameters: notesWriteParameters,
9365
- outputSchema: resultSchema(NotesWriteDataSchema),
9366
9408
  executionMode: "sequential",
9367
9409
  async execute(params, context2) {
9368
9410
  try {
9369
9411
  const identity2 = notesIdentityForCall(context2, params.cwd);
9370
- const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, description: params.description, pinned: params.pinned, budget: params.budget, readonly: params.readonly });
9412
+ const { outcome, meta, warnings } = await createNotesStore(identity2).write(params.address, params.content, { origin: params.origin, description: params.description, pinned: params.pinned, readonly: params.readonly });
9371
9413
  return success({ ...noteIdentity(identity2, params.address), outcome, ...policyAt(meta, params.address), warnings });
9372
9414
  } catch (error) {
9373
9415
  return failureOf(error);
@@ -9377,32 +9419,37 @@ var notesWrite = {
9377
9419
  };
9378
9420
  var notesUpdateParameters = typebox_exports.Object({
9379
9421
  address: ADDRESS_PARAMETER,
9380
- 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." })),
9422
+ edits: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
9423
+ oldText: typebox_exports.String({ description: "Exact text to replace." }),
9424
+ newText: typebox_exports.String({ description: "Replacement text." }),
9425
+ replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Replace every occurrence (overrides top-level `replace_all`)." }))
9426
+ }, { additionalProperties: false }), { description: "Sequential exact text replacements." })),
9381
9427
  origin: ORIGIN,
9382
9428
  description: DESCRIPTION_PARAMETER,
9383
9429
  ...POLICY_PARAMETERS,
9384
9430
  crumpled: CRUMPLED_PARAMETER,
9385
- replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Strike every copy of `oldText`, not just one." })),
9386
- 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." })),
9431
+ replace_all: typebox_exports.Optional(typebox_exports.Boolean({ description: "Replace every occurrence in edits that omit `replace_all`." })),
9432
+ rename_to: typebox_exports.Optional(typebox_exports.String({ description: "Move note to this address." })),
9387
9433
  cwd: CWD_PARAMETER
9388
9434
  }, { additionalProperties: false });
9389
9435
  function renderUpdateData(data) {
9390
9436
  const receipt = data.rename_from === void 0 ? `${data.change_kind === "none" ? "unchanged" : "updated"} ${renderIdentity(data)}` : `moved ${data.rename_from} -> ${data.address}`;
9391
- return withWarnings(`${receipt} | ${renderPolicy(data)}`, data);
9437
+ const sparse = renderSparsePolicy(data, data.address);
9438
+ return withWarnings(`${receipt}${sparse === "" ? "" : ` | ${sparse}`}`, data);
9392
9439
  }
9393
9440
  var notesUpdate = {
9394
9441
  name: "notes_update",
9395
9442
  label: "Notes update",
9396
- 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.",
9443
+ description: "Edit an existing note's text or metadata, move it (`rename_to`), or crumple/restore it (`crumpled`).",
9397
9444
  parameters: notesUpdateParameters,
9398
- outputSchema: resultSchema(NotesUpdateDataSchema),
9399
9445
  executionMode: "sequential",
9400
9446
  async execute(params, context2, onChange) {
9401
9447
  try {
9402
9448
  const identity2 = notesIdentityForCall(context2, params.cwd);
9403
9449
  const store = createNotesStore(identity2);
9404
9450
  const renameTo = params.rename_to === "" ? void 0 : params.rename_to;
9405
- const { change, moved, meta, warnings } = await store.update(params.address, params.edits, { origin: params.origin, description: params.description, pinned: params.pinned, budget: params.budget, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9451
+ const edits = params.edits?.map((edit) => ({ oldText: edit.oldText, newText: edit.newText, ...edit.replace_all === void 0 ? {} : { replaceAll: edit.replace_all } }));
9452
+ const { change, moved, meta, warnings } = await store.update(params.address, edits, { origin: params.origin, description: params.description, pinned: params.pinned, readonly: params.readonly, crumpled: params.crumpled, replaceAll: params.replace_all, renameTo });
9406
9453
  onChange?.(change);
9407
9454
  const from = noteIdentity(identity2, params.address).address;
9408
9455
  const to = noteIdentity(identity2, renameTo ?? params.address);
@@ -9423,7 +9470,7 @@ ${renderTextWindow(data)}`;
9423
9470
  var notesRead = {
9424
9471
  name: "notes_read",
9425
9472
  label: "Notes read",
9426
- description: "Read a page. Long ones come a stretch at a time; follow `next_offset_chars`.",
9473
+ description: "Read a note (supports windowed reads via `offset_chars` and `max_chars`).",
9427
9474
  parameters: notesReadParameters,
9428
9475
  outputSchema: resultSchema(NotesReadDataSchema),
9429
9476
  async execute(params, context2) {
@@ -9435,8 +9482,9 @@ var notesRead = {
9435
9482
  const totalChars = Array.from(note.body).length;
9436
9483
  if (params.offset_chars !== void 0 && params.offset_chars > totalChars) return failure("invalid_offset", `This note ends at char ${totalChars}; offset_chars ${params.offset_chars} is past the last word.`);
9437
9484
  const metadata = noteMetadata(note.meta, resolved.address);
9438
- const warnings = noteBudgetWarnings(note.body, metadata);
9439
- return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), (result) => renderOutcome(result, renderReadData));
9485
+ const warnings = noteWarnings(note.body, metadata, metadata.description);
9486
+ const render = (result) => renderOutcome(result, renderReadData);
9487
+ return readTextWindow(note.body, params.offset_chars, params.max_chars, (window) => ({ ...resolved, metadata, warnings, ...window }), render, (result) => fitsResult(result, render));
9440
9488
  } catch (error) {
9441
9489
  return failureOf(error);
9442
9490
  }
@@ -9445,91 +9493,115 @@ var notesRead = {
9445
9493
  };
9446
9494
  var notesListParameters = typebox_exports.Object({
9447
9495
  glob: GLOB_PARAMETER,
9448
- query: typebox_exports.Optional(searchQuery()),
9449
- max_matches_per_file: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "How many hit lines per note at most; requires a query." })),
9496
+ query: typebox_exports.Optional(searchQuery("Case-insensitive literal text, or a list (any match). Omit to list.")),
9497
+ max_matches_per_note: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, description: "Maximum matching lines shown per note." })),
9450
9498
  crumpled: CRUMPLED_LIST_PARAMETER,
9451
9499
  limit: FILE_LIMIT_PARAMETER,
9500
+ cursor: typebox_exports.Optional(typebox_exports.String({ description: "Cursor from an `\u2192 older` footer (`<updated_at> <address>`)." })),
9452
9501
  cwd: CWD_PARAMETER
9453
9502
  }, { additionalProperties: false });
9454
- function renderListData(data) {
9503
+ function moreMatches(more, tail) {
9504
+ return `${more} more matching ${more === 1 ? "note" : "notes"}${tail}`;
9505
+ }
9506
+ function renderListData(data, renderMore = (more) => moreMatches(more, " omitted; narrow with glob"), options = {}) {
9455
9507
  const lines = [`${data.files.length} ${data.files.length === 1 ? "note" : "notes"}`];
9456
9508
  for (const file of data.files) {
9457
- const fields = [file.description === void 0 ? `- ${renderIdentity(file)}` : `- ${renderIdentity(file)} \u2014 ${file.description}`, renderPolicy(file), `updated ${file.updated_at}`];
9509
+ const identity2 = file.address.startsWith("@project/") || options.omitNamedProjectContext ? renderIdentity({ address: file.address }) : renderIdentity(file);
9510
+ const sparse = renderSparsePolicy(file, file.address);
9511
+ const fields = [`- ${identity2}${file.description === void 0 ? "" : ` \u2014 ${file.description}`}`, ...sparse === "" ? [] : [sparse], `updated ${file.updated_at}`];
9458
9512
  if (file.last_accessed !== void 0) fields.push(`accessed ${file.last_accessed}`);
9459
9513
  if (file.crumpled_at !== void 0) fields.push(`crumpled ${file.crumpled_at}`);
9460
9514
  if (file.matches) fields.push(`${file.matches.length} ${file.matches.length === 1 ? "match" : "matches"}${file.more_matches ? `, ${file.more_matches} more lines` : ""}`);
9461
9515
  lines.push(fields.join(" | "));
9462
- lines.push(...file.warnings.map((warning) => ` ${warning}`));
9516
+ lines.push(...file.warnings.map((warning) => ` ${renderWarnings([warning])}`));
9463
9517
  for (const match of file.matches ?? []) lines.push(` line ${match.line} at offset_chars ${match.offset_chars}: ${match.text}`);
9464
9518
  }
9465
- if (data.more > 0) lines.push(`${data.more} more matching notes omitted; narrow with glob`);
9519
+ if (data.more > 0) lines.push(renderMore(data.more, data.files));
9466
9520
  for (const namespace of data.namespaces_unavailable) lines.push(`${namespace} could not be read`);
9467
9521
  return lines.join("\n");
9468
9522
  }
9469
- function keepMatches(file, count = file.matches.length) {
9470
- const more = (file.more_matches ?? 0) + Math.max(0, file.matches.length - count);
9471
- return { ...file, matches: file.matches.slice(0, count), ...more ? { more_matches: more } : {} };
9523
+ function keepMatches(file, count = file.matches?.length ?? 0) {
9524
+ const matches = file.matches ?? [];
9525
+ const more = (file.more_matches ?? 0) + Math.max(0, matches.length - count);
9526
+ return { ...file, matches: matches.slice(0, count), ...more ? { more_matches: more } : {} };
9472
9527
  }
9473
9528
  var MATCH_SHORTENED_MARKER = " [truncated]";
9474
9529
  function fitSearchFile(file, fits) {
9530
+ const matches = file.matches ?? [];
9475
9531
  let low = 0;
9476
- let high = file.matches.length;
9532
+ let high = matches.length;
9477
9533
  while (low < high) {
9478
9534
  const mid = Math.ceil((low + high) / 2);
9479
9535
  if (fits(keepMatches(file, mid))) low = mid;
9480
9536
  else high = mid - 1;
9481
9537
  }
9482
- if (low > 0 || file.matches.length === 0) return keepMatches(file, low);
9483
- const first = file.matches[0];
9538
+ if (low > 0 || matches.length === 0) return keepMatches(file, low);
9539
+ const first = matches[0];
9484
9540
  const withText = (text) => ({ ...keepMatches(file, 1), matches: [{ ...first, text: `${text}${MATCH_SHORTENED_MARKER}` }] });
9485
9541
  return withText(prefixFit(first.text, (text) => fits(withText(text))));
9486
9542
  }
9543
+ function parseCursor(raw, identity2) {
9544
+ if (raw === void 0 || raw === "") return success(void 0);
9545
+ const space = raw.indexOf(" ");
9546
+ if (space <= 0 || space === raw.length - 1) return failure("invalid_params", "`cursor` must be `<updated_at> <address>`.");
9547
+ const atMs = parseIsoTimestamp(raw.slice(0, space));
9548
+ if (atMs === void 0) return failure("invalid_params", "`cursor` starts with an invalid ISO 8601 timestamp.");
9549
+ try {
9550
+ return success({ atMs, address: noteIdentity(identity2, raw.slice(space + 1)).address });
9551
+ } catch {
9552
+ return failure("invalid_params", "`cursor` ends with an invalid note address.");
9553
+ }
9554
+ }
9555
+ function olderThan(file, cursor) {
9556
+ const atMs = parseIsoTimestamp(file.updated_at);
9557
+ return atMs < cursor.atMs || atMs === cursor.atMs && file.address.localeCompare(cursor.address) > 0;
9558
+ }
9559
+ function renderOlderPage(more, files, params, searching) {
9560
+ const last = files[files.length - 1];
9561
+ if (last === void 0) return moreMatches(more, " omitted; narrow glob");
9562
+ const next = {};
9563
+ if (params.glob !== void 0) next.glob = params.glob;
9564
+ if (searching) next.query = params.query;
9565
+ if (params.max_matches_per_note !== void 0) next.max_matches_per_note = params.max_matches_per_note;
9566
+ if (params.crumpled !== void 0) next.crumpled = params.crumpled;
9567
+ if (params.limit !== void 0) next.limit = params.limit;
9568
+ if (params.cwd !== void 0) next.cwd = params.cwd;
9569
+ next.cursor = `${last.updated_at} ${last.address}`;
9570
+ return moreMatches(more, ` | \u2192 older: ${JSON.stringify(next)}`);
9571
+ }
9487
9572
  var notesList = {
9488
9573
  name: "notes_list",
9489
9574
  label: "Notes list",
9490
- description: "List or search notes, newest pages on top. A query matches literal text (ignoring case) and returns hit lines and read offsets. One pass; `more` counts pages left on the pile \u2014 narrow `glob`.",
9575
+ description: "List or search notes, newest first. Literal case-insensitive `query` returns matching lines and `offset_chars`.",
9491
9576
  parameters: notesListParameters,
9492
- outputSchema: resultSchema(NotesListDataSchema),
9493
9577
  async execute(params, context2) {
9494
9578
  try {
9495
9579
  const queries = searchQueries(params.query);
9496
9580
  const { glob, crumpled, limit } = params;
9497
- if (!queries.length && params.max_matches_per_file !== void 0) return failure("invalid_params", "`max_matches_per_file` requires a non-empty `query`.");
9581
+ if (!queries.length && params.max_matches_per_note !== void 0) return failure("invalid_params", "`max_matches_per_note` requires a non-empty `query`.");
9498
9582
  const identity2 = notesIdentityForCall(context2, params.cwd);
9583
+ const cursor = parseCursor(params.cursor, identity2);
9584
+ if (!cursor.ok) return cursor;
9499
9585
  const store = createNotesStore(identity2);
9500
- if (!queries.length) {
9501
- const { rows: rows2, status: status2 } = await store.listWithStatus({ glob, crumpled });
9502
- return snapshot(rows2.map((row) => listedFile(row, identity2)), limit, status2, renderListData);
9503
- }
9504
- const { rows, status } = await store.searchWithStatus(queries, { glob, crumpled });
9505
- const files = rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address)).map((row) => keepMatches({
9586
+ const result = queries.length ? await store.searchWithStatus(queries, { glob, crumpled }) : await store.listWithStatus({ glob, crumpled });
9587
+ const rows = result.rows;
9588
+ rows.sort(compareNoteRows);
9589
+ const files = rows.map((row) => "matches" in row ? keepMatches({
9506
9590
  ...listedFile(row, identity2),
9507
9591
  matches: row.matches.map((match) => ({ line: match.line, text: match.text, offset_chars: match.offsetChars }))
9508
- }, params.max_matches_per_file));
9509
- return snapshot(files, limit, status, renderListData, fitSearchFile);
9592
+ }, params.max_matches_per_note) : listedFile(row, identity2));
9593
+ const page = files.filter((file) => cursor.data === void 0 || olderThan(file, cursor.data));
9594
+ const outcome = snapshot(page, limit, result.status, (data) => renderListData(data, (more, shown2) => renderOlderPage(more, shown2, params, queries.length > 0)), queries.length ? fitSearchFile : void 0);
9595
+ if (!outcome.ok || outcome.data.more === 0) return outcome;
9596
+ return success({ ...outcome.data, older: renderOlderPage(outcome.data.more, outcome.data.files, params, queries.length > 0) });
9510
9597
  } catch (error) {
9511
9598
  return failureOf(error);
9512
9599
  }
9513
9600
  },
9514
- render: (result) => renderOutcome(result, renderListData)
9601
+ render: (result) => renderOutcome(result, (data) => renderListData(data, (more) => data.older ?? moreMatches(more, " omitted; narrow with glob")))
9515
9602
  };
9516
9603
 
9517
9604
  // src/history/query.ts
9518
- var multiPages = /* @__PURE__ */ new WeakSet();
9519
- function isMultiPage(page) {
9520
- return multiPages.has(page);
9521
- }
9522
- function markMultiPage(page) {
9523
- multiPages.add(page);
9524
- return page;
9525
- }
9526
- var HistoryPageSchema = typebox_exports.Object({
9527
- notice: typebox_exports.Optional(typebox_exports.String()),
9528
- items: typebox_exports.Array(HistoryPageItemSchema),
9529
- folded_after: typebox_exports.Optional(HistoryFoldedRowSchema),
9530
- has_older: typebox_exports.Boolean(),
9531
- has_newer: typebox_exports.Boolean()
9532
- }, { additionalProperties: false });
9533
9605
  function truncateHistoryItem(item, fits) {
9534
9606
  if (fits(item)) return item;
9535
9607
  const shrinkContent = (base) => ({
@@ -9543,7 +9615,7 @@ function truncateHistoryItem(item, fits) {
9543
9615
  const { tool: _dropped, ...withoutName } = item;
9544
9616
  return fits(withoutName) ? withoutName : shrinkContent(withoutName);
9545
9617
  }
9546
- function foldedRun(events, session) {
9618
+ function foldedRun(events) {
9547
9619
  if (events.length === 0) return void 0;
9548
9620
  const counts = /* @__PURE__ */ new Map();
9549
9621
  for (const event of events) {
@@ -9553,31 +9625,30 @@ function foldedRun(events, session) {
9553
9625
  }
9554
9626
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
9555
9627
  const tools = Object.fromEntries(entries);
9556
- return { ...session === void 0 ? {} : { session }, first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9628
+ return { first_seq: events[0].seq, last_seq: events.at(-1).seq, count: events.length, tools };
9557
9629
  }
9558
9630
  var visible = (event) => event.role !== "user" && event.role !== "assistant" || eventDocument(event) !== "";
9559
- function* queryHits(projection, params, session) {
9560
- const { query, context: context2 } = params;
9631
+ function* queryHits(projection, params, patterns, session) {
9632
+ const { context: context2 } = params;
9561
9633
  const events = filteredItems(projection, context2 ? {} : params).filter(visible);
9562
9634
  for (const [index, event] of events.entries()) {
9563
9635
  if (context2 && !matchesFilter(event, params)) continue;
9564
- const matchOffset = earliestMatchOffsetChars(eventDocument(event), query);
9636
+ const matchOffset = earliestMatchOffsetChars(eventDocument(event), patterns);
9565
9637
  if (matchOffset >= 0) yield { event, session, matchOffset, neighbors: context2 ? { events, index } : void 0 };
9566
9638
  }
9567
9639
  }
9568
9640
  function prepareSelection(projection, params) {
9569
- const { query, roles, session } = params;
9570
- if (query) return { candidates: [...queryHits(projection, params, session)] };
9641
+ const { roles } = params;
9571
9642
  const candidates = [];
9572
9643
  let run = [];
9573
9644
  for (const event of filteredItems(projection, params).filter(visible)) {
9574
9645
  if (!roles && (event.role === "tool" || event.role === "context")) run.push(event);
9575
9646
  else {
9576
- candidates.push({ event, session, before: foldedRun(run, session) });
9647
+ candidates.push({ event, before: foldedRun(run) });
9577
9648
  run = [];
9578
9649
  }
9579
9650
  }
9580
- return { candidates, tail: foldedRun(run, session) };
9651
+ return { candidates, tail: foldedRun(run) };
9581
9652
  }
9582
9653
  function pageData(prepared, start, end, maxChars, preview) {
9583
9654
  const { candidates, tail } = prepared;
@@ -9587,31 +9658,54 @@ function pageData(prepared, start, end, maxChars, preview) {
9587
9658
  const item = preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...candidate.session === void 0 ? {} : { session: candidate.session } });
9588
9659
  items.push(candidate.before && (index > start || start === 0) ? { ...item, folded_before: candidate.before } : item);
9589
9660
  }
9590
- const page = {
9661
+ return {
9591
9662
  items,
9592
9663
  ...end === candidates.length && tail ? { folded_after: tail } : {},
9593
9664
  has_older: start > 0 && start < end || !!prepared.discarded && !prepared.forward,
9594
9665
  has_newer: end < candidates.length && start < end || !!prepared.discarded && !!prepared.forward
9595
9666
  };
9596
- return prepared.multi ? markMultiPage(page) : page;
9597
9667
  }
9598
9668
  function selectPage(projection, params, fits, maxChars) {
9599
9669
  return selectPrepared(prepareSelection(projection, params), params, fits, maxChars);
9600
9670
  }
9671
+ function summarizeProjection(projection) {
9672
+ const events = filteredItems(projection, {}).filter(visible);
9673
+ let firstUser;
9674
+ let lastAssistant;
9675
+ const latestByRole = {};
9676
+ let minCreatedAt = Infinity;
9677
+ let maxCreatedAt = -Infinity;
9678
+ let hasUntimed = false;
9679
+ for (const event of events) {
9680
+ if (firstUser === void 0 && event.role === "user") firstUser = event;
9681
+ if (event.role === "assistant") lastAssistant = event;
9682
+ latestByRole[event.role] = event;
9683
+ const at = eventTimestampMs(event);
9684
+ if (Number.isNaN(at)) hasUntimed = true;
9685
+ else {
9686
+ if (at < minCreatedAt) minCreatedAt = at;
9687
+ if (at > maxCreatedAt) maxCreatedAt = at;
9688
+ }
9689
+ }
9690
+ return {
9691
+ event: firstUser ?? lastAssistant ?? events.at(-1),
9692
+ latestByRole,
9693
+ minCreatedAt: Number.isFinite(minCreatedAt) ? minCreatedAt : null,
9694
+ maxCreatedAt: Number.isFinite(maxCreatedAt) ? maxCreatedAt : null,
9695
+ hasUntimed
9696
+ };
9697
+ }
9601
9698
  function sessionRepresentative(projection, scoped) {
9602
9699
  const events = filteredItems(projection, scoped).filter(visible);
9603
9700
  if (scoped.roles) return events.at(-1);
9604
9701
  return events.find((event) => event.role === "user") ?? events.filter((event) => event.role === "assistant").at(-1) ?? events.at(-1);
9605
9702
  }
9606
- function eventTime(timestamp) {
9607
- const at = Date.parse(timestamp ?? "");
9608
- return Number.isNaN(at) ? -Infinity : at;
9609
- }
9610
- var compareCorpus = (a, b) => eventTime(a.event.createdAt) - eventTime(b.event.createdAt) || a.session.localeCompare(b.session) || a.event.seq - b.event.seq;
9703
+ var earliestIfUntimed = (at) => Number.isNaN(at) ? -Infinity : at;
9704
+ var compareCorpus = (a, b) => earliestIfUntimed(eventTimestampMs(a.event)) - earliestIfUntimed(eventTimestampMs(b.event)) || (a.session ?? "").localeCompare(b.session ?? "") || a.event.seq - b.event.seq;
9611
9705
  function addContext(page, hits, radius, fits, maxChars) {
9612
9706
  const key = (session, seq) => `${session ?? ""}\0${seq}`;
9613
9707
  const seen = new Set(page.items.map((item) => key(item.session, item.seq)));
9614
- const compare = (a, b) => (isMultiPage(page) ? eventTime(a.created_at) - eventTime(b.created_at) || a.session.localeCompare(b.session) : 0) || a.seq - b.seq;
9708
+ const compare = (a, b) => earliestIfUntimed(Date.parse(a.created_at ?? "")) - earliestIfUntimed(Date.parse(b.created_at ?? "")) || (a.session ?? "").localeCompare(b.session ?? "") || a.seq - b.seq;
9615
9709
  for (let distance = 1; distance <= radius; distance++) {
9616
9710
  let found = false;
9617
9711
  for (const { neighbors, session } of hits) {
@@ -9639,10 +9733,12 @@ var CorpusCollector = class {
9639
9733
  constructor(scoped) {
9640
9734
  this.scoped = scoped;
9641
9735
  this.limit = Math.min(500, Math.max(1, scoped.limit ?? 20));
9736
+ this.compiledQuery = scoped.query?.length ? compileSearchQueries(scoped.query) : [];
9642
9737
  }
9643
9738
  scoped;
9644
9739
  candidates = [];
9645
9740
  limit;
9741
+ compiledQuery;
9646
9742
  discarded = false;
9647
9743
  admit(candidate) {
9648
9744
  let low = 0, high = this.candidates.length;
@@ -9664,48 +9760,49 @@ var CorpusCollector = class {
9664
9760
  }
9665
9761
  this.candidates.splice(low, 0, candidate);
9666
9762
  }
9667
- /** Admit an already selected strict overview event without selecting it a second time. */
9668
- addRepresentative(session, event) {
9763
+ /** Admit a session's overview representative (pre-selected or picked from a projection). */
9764
+ addRepresentative(session, source) {
9765
+ const event = source && "windows" in source ? sessionRepresentative(source, this.scoped) : source;
9669
9766
  if (!event) return false;
9670
- this.admit({ session, event });
9767
+ this.admit({ session: session || void 0, event });
9671
9768
  return true;
9672
9769
  }
9673
- /** Returns whether this session contributes an overview representative. */
9674
- add(session, projection) {
9675
- if (this.scoped.query === void 0) return this.addRepresentative(session, sessionRepresentative(projection, this.scoped));
9676
- for (const hit of queryHits(projection, this.scoped, session)) this.admit(hit);
9677
- return true;
9770
+ /** Admit every query match from one session; an empty query matches nothing. */
9771
+ addMatches(session, projection) {
9772
+ if (this.compiledQuery.length === 0) return;
9773
+ for (const hit of queryHits(projection, this.scoped, this.compiledQuery, session || void 0)) this.admit(hit);
9678
9774
  }
9679
9775
  page(fits, maxChars, unvisited = false) {
9680
- return selectPrepared({ candidates: this.candidates, multi: true, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
9776
+ const result = selectPrepared({ candidates: this.candidates, discarded: this.discarded || unvisited, forward: !!this.scoped.after }, this.scoped, fits, maxChars);
9777
+ if (result.ok && this.compiledQuery.length > 0 && this.scoped.context) {
9778
+ const count = result.data.items.length;
9779
+ const hits = this.scoped.after ? this.candidates.slice(0, count) : this.candidates.slice(this.candidates.length - count);
9780
+ addContext(result.data, hits, this.scoped.context, fits, maxChars);
9781
+ }
9782
+ return result;
9681
9783
  }
9682
9784
  };
9683
9785
  function selectPrepared(prepared, scoped, fits, maxChars) {
9684
9786
  const { candidates } = prepared;
9685
- const newest = scoped.after === void 0;
9686
- let start = newest ? candidates.length : 0;
9687
- let end = start;
9688
- const limit = Math.max(1, scoped.limit ?? 20);
9689
- for (let count = 0; count < limit && (newest ? start > 0 : end < candidates.length); count++) {
9690
- const nextStart = newest ? start - 1 : start;
9691
- const nextEnd = newest ? end : end + 1;
9692
- if (fits(pageData(prepared, nextStart, nextEnd, maxChars))) {
9693
- start = nextStart;
9694
- end = nextEnd;
9695
- continue;
9787
+ const newest = scoped.after === void 0 && (scoped.before !== void 0 || scoped.since === void 0);
9788
+ const start = (count2) => newest ? candidates.length - count2 : 0;
9789
+ const pageFor = (count2, preview) => pageData(prepared, start(count2), start(count2) + count2, maxChars, preview);
9790
+ let count = Math.min(Math.max(1, scoped.limit ?? 20), candidates.length);
9791
+ if (count > 0 && !fits(pageFor(count))) {
9792
+ let low = 0, high = count - 1;
9793
+ while (low < high) {
9794
+ const mid = Math.ceil((low + high) / 2);
9795
+ if (fits(pageFor(mid))) low = mid;
9796
+ else high = mid - 1;
9696
9797
  }
9697
- if (start === end) {
9698
- start = nextStart;
9699
- end = nextEnd;
9700
- const candidate = candidates[start];
9701
- candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageData(prepared, start, end, maxChars, preview)));
9798
+ count = Math.max(1, low);
9799
+ if (low === 0) {
9800
+ const candidate = candidates[start(1)];
9801
+ candidate.preview = truncateHistoryItem(candidate.preview, (preview) => fits(pageFor(1, preview)));
9702
9802
  }
9703
- break;
9704
9803
  }
9705
- const page = pageData(prepared, start, end, maxChars);
9706
- if (!fits(page)) return { ok: false, pageTooLarge: { count: page.items.length, multi: prepared.multi === true } };
9707
- if (scoped.context) addContext(page, candidates.slice(start, end), scoped.context, fits, maxChars);
9708
- return success(page);
9804
+ const page = pageFor(count);
9805
+ return fits(page) ? success(page) : { ok: false, pageTooLarge: true };
9709
9806
  }
9710
9807
 
9711
9808
  // src/history/corpus.ts
@@ -9743,6 +9840,33 @@ async function resolveSession(corpus, selector) {
9743
9840
  if (matches.length > 1) return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
9744
9841
  return success(matches[0]);
9745
9842
  }
9843
+ function resolveSummaryForSelection(summary, scoped) {
9844
+ const afterAt = scoped.after && "at" in scoped.after ? scoped.after.at : void 0;
9845
+ const beforeAt = scoped.before && "at" in scoped.before ? scoped.before.at : void 0;
9846
+ if (afterAt !== void 0 || beforeAt !== void 0) {
9847
+ if (summary.maxCreatedAt === null || summary.minCreatedAt === null) return { kind: "empty" };
9848
+ if (afterAt !== void 0 && summary.maxCreatedAt <= afterAt) return { kind: "empty" };
9849
+ if (beforeAt !== void 0 && summary.minCreatedAt >= beforeAt) return { kind: "empty" };
9850
+ }
9851
+ if (scoped.query?.length) return { kind: "miss" };
9852
+ const fullyInsideBounds = afterAt === void 0 && beforeAt === void 0 || !summary.hasUntimed && summary.minCreatedAt !== null && summary.maxCreatedAt !== null && (afterAt === void 0 || summary.minCreatedAt > afterAt) && (beforeAt === void 0 || summary.maxCreatedAt < beforeAt);
9853
+ if (!fullyInsideBounds) return { kind: "miss" };
9854
+ if (!scoped.roles) return { kind: "hit", event: summary.event, notice: summary.notice };
9855
+ let best;
9856
+ for (const role of scoped.roles) {
9857
+ const candidate = summary.latestByRole[role];
9858
+ if (candidate && (!best || candidate.seq > best.seq)) best = candidate;
9859
+ }
9860
+ return { kind: "hit", event: best, notice: summary.notice };
9861
+ }
9862
+ async function loadHistorySummary(session) {
9863
+ if (!session.loadSummary) return failure("history_unavailable", `Session ${sessionIdentity(session)} has no summary loader`);
9864
+ try {
9865
+ return success(await session.loadSummary());
9866
+ } catch (error) {
9867
+ return unavailableSession(session, error);
9868
+ }
9869
+ }
9746
9870
  async function loadHistoryRepresentative(session) {
9747
9871
  if (session.loadRepresentative) {
9748
9872
  try {
@@ -9771,22 +9895,30 @@ function currentHistory(context2) {
9771
9895
  }
9772
9896
 
9773
9897
  // src/tools/history.ts
9774
- var HistoryReadDataSchema = typebox_exports.Object({
9775
- session: typebox_exports.Optional(typebox_exports.String()),
9776
- notice: typebox_exports.Optional(typebox_exports.String()),
9777
- seq: typebox_exports.Integer({ minimum: 1 }),
9778
- role: HistoryRoleSchema,
9779
- created_at: typebox_exports.Union([typebox_exports.String(), typebox_exports.Null()]),
9780
- ...ToolSummarySchema.properties,
9781
- nested_calls: typebox_exports.Optional(NestedCallSummarySchema),
9782
- ...TextWindowSchema.properties
9783
- }, { additionalProperties: false });
9898
+ var WILDCARD_CONCURRENCY = 12;
9899
+ async function loadOverviewSession(session, scoped) {
9900
+ if (session.loadSummary) {
9901
+ const summary = await loadHistorySummary(session);
9902
+ if (!summary.ok) return void 0;
9903
+ const resolved = resolveSummaryForSelection(summary.data, scoped);
9904
+ if (resolved.kind === "empty") return void 0;
9905
+ if (resolved.kind === "hit") return { event: resolved.event, notice: resolved.notice };
9906
+ if (summary.data.loaded) return summary.data.loaded;
9907
+ } else if (!scoped.roles && !scoped.after && !scoped.before && session.loadRepresentative) {
9908
+ const rep = await loadHistoryRepresentative(session);
9909
+ return rep.ok ? rep.data : void 0;
9910
+ }
9911
+ const loaded = await loadHistorySession(session);
9912
+ return loaded.ok ? loaded.data : void 0;
9913
+ }
9784
9914
  function header(item) {
9785
- return `${item.session === void 0 ? "" : `session ${item.session} | `}seq ${item.seq} | ${item.role}`;
9915
+ const atMs = item.created_at ? Date.parse(item.created_at) : NaN;
9916
+ const at = Number.isFinite(atMs) ? localIso(atMs) : void 0;
9917
+ return [item.session === void 0 ? void 0 : `session ${item.session}`, `seq ${item.seq}`, item.role, ...at === void 0 ? [] : [at]].filter(Boolean).join(" | ");
9786
9918
  }
9787
9919
  function toolHeader(item) {
9788
9920
  if (item.role !== "tool") return void 0;
9789
- const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
9921
+ const parts = [...item.tool ? [`tool ${item.tool}`] : [], `status ${item.tool_status}`];
9790
9922
  if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
9791
9923
  if (item.nested_calls) {
9792
9924
  parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
@@ -9795,163 +9927,243 @@ function toolHeader(item) {
9795
9927
  }
9796
9928
  function renderPageItem(item) {
9797
9929
  const tool = toolHeader(item);
9798
- const lines = [header(item) + (item.context ? " | search context" : ""), ...tool ? [tool] : []];
9799
- if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
9800
- lines.push(item.content);
9930
+ const offset = (item.offset_chars ?? 0) > 0 ? ` | offset_chars ${item.offset_chars}` : "";
9931
+ const lines = [header({ seq: item.seq, role: item.role, created_at: item.created_at }) + offset + (item.context ? " | search context" : ""), ...tool ? [tool] : []];
9932
+ lines.push(item.truncated ? item.content ? `${item.content} [truncated]` : "[truncated]" : item.content);
9801
9933
  return lines.join("\n");
9802
9934
  }
9803
- function renderFoldedRow(row) {
9935
+ function renderFoldedRow(row, session) {
9804
9936
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
9805
- const identity2 = row.session === void 0 ? {} : { session: row.session };
9806
- const expand = `
9807
- \u2192 expand: ${JSON.stringify({ ...identity2, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
9808
- return `${row.session === void 0 ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
9809
- }
9810
- function renderPage(page) {
9811
- if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
9812
- const body = [...page.items.flatMap((item) => [...item.folded_before ? [renderFoldedRow(item.folded_before)] : [], renderPageItem(item)]), ...page.folded_after ? [renderFoldedRow(page.folded_after)] : []].join("\n\n");
9813
- if (isMultiPage(page)) {
9814
- const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9815
- return (page.notice ?? "") + body + (directions ? `
9816
-
9817
- \u2192 more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
9818
- }
9819
- const hits = page.items.filter((item) => !item.context);
9820
- const first = hits[0];
9821
- const last = hits.at(-1);
9937
+ const expand = JSON.stringify({ session, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] });
9938
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}
9939
+ \u2192 expand: ${expand}`;
9940
+ }
9941
+ var sessionBanner = (session) => session === void 0 ? "" : `=== session ${session} ===
9942
+ `;
9943
+ var EMPTY_PAGE = "No events match these filters.";
9944
+ function renderTimelinePage(page) {
9945
+ const { session } = page.paging;
9946
+ const body = [...page.items.flatMap((item) => [...item.folded_before ? [renderFoldedRow(item.folded_before, session)] : [], renderPageItem(item)]), ...page.folded_after ? [renderFoldedRow(page.folded_after, session)] : []].join("\n\n");
9822
9947
  const cursors = [
9823
- page.has_older ? `\u2192 older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
9824
- page.has_newer ? `\u2192 newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : ""
9825
- ].filter((line) => line !== "");
9826
- return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}
9948
+ page.has_older ? `\u2192 older: ${JSON.stringify({ ...page.paging, before: page.items[0].seq })}` : "",
9949
+ page.has_newer ? `\u2192 newer: ${JSON.stringify({ ...page.paging, after: page.items.at(-1).seq })}` : ""
9950
+ ].filter(Boolean);
9951
+ return (page.notice ?? "") + sessionBanner(session) + (body || EMPTY_PAGE) + (cursors.length ? `
9827
9952
 
9828
- ${cursors.join(" | ")}`);
9953
+ ${cursors.join(" | ")}` : "");
9829
9954
  }
9955
+ function renderCollectionPage(page, narrow) {
9956
+ const sessions = new Map(page.items.filter((item) => !item.context).map((item) => [item.session, []]));
9957
+ for (const item of page.items) sessions.get(item.session).push(item);
9958
+ const body = [...sessions].map(([session, items]) => sessionBanner(session) + items.sort((a, b) => a.seq - b.seq).map(renderPageItem).join("\n\n")).join("\n\n");
9959
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
9960
+ return (page.notice ?? "") + (body || sessionBanner(page.session) + EMPTY_PAGE) + (directions ? `
9961
+
9962
+ \u2192 more ${directions} results: ${narrow}` : "");
9963
+ }
9964
+ var renderOverviewPage = (page) => renderCollectionPage(page, "narrow with since/until, roles or the session pattern");
9965
+ var renderSearchPage = (page) => renderCollectionPage(page, "narrow with since/until, query, roles or the session pattern");
9830
9966
  function renderRead(data) {
9831
9967
  const tool = toolHeader(data);
9832
- const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...data.session === void 0 ? {} : { session: data.session }, after: Math.max(0, data.seq - 10), before: data.seq + 10 })})`;
9968
+ const neighborhood = `\u2192 history_list: ${JSON.stringify({ session: data.session, after: Math.max(0, data.seq - 10), before: data.seq + 10 })}`;
9833
9969
  return (data.notice ?? "") + [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
9834
9970
  }
9835
9971
  var plainText = (text) => text;
9836
- function pageOutcome(result) {
9972
+ function pageOutcome(result, narrow) {
9837
9973
  if (!("pageTooLarge" in result)) return result;
9838
- const { count, multi } = result.pageTooLarge;
9839
- const narrow = multi ? "narrow the session pattern, query, roles or time bounds (`after`/`before`), or read one session/seq with `history_read`" : "narrow with `after`/`before`, pass `roles` to skip folding, or `history_read` one seq";
9840
- 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}.`);
9974
+ return failure("page_too_large", `These events exceed the ${TOOL_OUTPUT_LIMIT} limit; ${narrow}, or use history_read for one event.`);
9975
+ }
9976
+ async function loadNamedSession(context2, selector) {
9977
+ if (!("corpus" in context2)) return failure("unknown_session", "Other sessions are unavailable here.");
9978
+ const target = await resolveSession(context2.corpus, selector);
9979
+ if (!target.ok) return target;
9980
+ const loaded = await loadHistorySession(target.data);
9981
+ return loaded.ok ? success({ ...loaded.data, session: sessionIdentity(target.data) }) : loaded;
9982
+ }
9983
+ async function loadTimeline(context2, session, tool) {
9984
+ if (session === void 0) return success({ projection: await currentHistory(context2) });
9985
+ const selector = parseSessionSelector(session);
9986
+ if (!selector.ok) return selector;
9987
+ if (selector.data.wildcard) return failure("invalid_session", `${tool} needs one session ID or prefix. Use history_list or history_search for wildcards.`);
9988
+ return loadNamedSession(context2, selector.data);
9989
+ }
9990
+ var sessionParameter = (description) => typebox_exports.Optional(typebox_exports.String({ minLength: 1, description }));
9991
+ var limitParameter = (description) => typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description }));
9992
+ var previewParameter = typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "Maximum characters per preview." }));
9993
+ var seqBound = (description) => typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description }));
9994
+ var timeBound = (description) => typebox_exports.Optional(typebox_exports.String({ description: `${description} ISO 8601 (local time if no offset).` }));
9995
+ function parseTimeBounds(params) {
9996
+ const since = params.since === void 0 ? void 0 : parseIsoTimestamp(params.since);
9997
+ const until = params.until === void 0 ? void 0 : parseIsoTimestamp(params.until);
9998
+ if (params.since !== void 0 && since === void 0) return failure("invalid_bounds", `since must be an ISO 8601 time; got ${JSON.stringify(params.since)}.`);
9999
+ if (params.until !== void 0 && until === void 0) return failure("invalid_bounds", `until must be an ISO 8601 time; got ${JSON.stringify(params.until)}.`);
10000
+ return success({ since, until });
9841
10001
  }
9842
- var boundParameter = (description) => typebox_exports.Optional(typebox_exports.Union([typebox_exports.String(), typebox_exports.Number()], { description: `${description} Use a seq (number or digits) or ISO 8601 time (UTC without offset); wildcards take only times.` }));
9843
10002
  var historyListParameters = typebox_exports.Object({
9844
- 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." })),
10003
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`) for one event per session. Omit for current session."),
10004
+ roles: historyRoles(true),
10005
+ after: seqBound("Exclusive seq; page forward (0 starts at the beginning)."),
10006
+ before: seqBound("Exclusive seq; without `after`, takes newest events."),
10007
+ since: timeBound("Exclusive start time; oldest first."),
10008
+ until: timeBound("Exclusive end time; without `since`, newest first."),
10009
+ limit: limitParameter("Events or sessions per page."),
10010
+ max_chars_per_item: previewParameter
10011
+ }, { additionalProperties: false });
10012
+ var historyList = {
10013
+ name: "history_list",
10014
+ label: "Browse history",
10015
+ description: "Browse one session's timeline (oldest to newest), or pass a wildcard `session` to overview matching sessions.",
10016
+ parameters: historyListParameters,
10017
+ async execute(params, context2, wrapText = plainText) {
10018
+ const { after, before, roles, limit, max_chars_per_item } = params;
10019
+ const bounds = parseTimeBounds(params);
10020
+ if (!bounds.ok) return bounds;
10021
+ const { since, until } = bounds.data;
10022
+ const selector = params.session === void 0 ? void 0 : parseSessionSelector(params.session);
10023
+ if (selector && !selector.ok) return selector;
10024
+ if (selector?.ok && selector.data.wildcard) {
10025
+ if (after !== void 0 || before !== void 0) {
10026
+ return failure("invalid_bounds", "after and before are seq numbers for a single session; use since and until with wildcard sessions.");
10027
+ }
10028
+ const wild = selector.data;
10029
+ if (!("corpus" in context2)) return failure("unknown_session", "Other sessions are unavailable here.");
10030
+ const scoped = {
10031
+ after: since === void 0 ? void 0 : { at: since },
10032
+ before: until === void 0 ? void 0 : { at: until },
10033
+ roles,
10034
+ limit
10035
+ };
10036
+ const sessions = (await context2.corpus.sessions(wild.harness)).filter((s) => matchesSession(s, wild));
10037
+ sessions.sort((a, b) => (since !== void 0 ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
10038
+ const targetCount = Math.min(500, Math.max(1, limit ?? 20));
10039
+ const collector = new CorpusCollector(scoped);
10040
+ const notices = [];
10041
+ let qualifying = 0, offset = 0;
10042
+ while (offset < sessions.length && qualifying < targetCount) {
10043
+ const batchSize = Math.min(WILDCARD_CONCURRENCY, targetCount - qualifying, sessions.length - offset);
10044
+ const batch = sessions.slice(offset, offset + batchSize);
10045
+ const loadedBatch = await Promise.all(batch.map((s) => loadOverviewSession(s, scoped)));
10046
+ for (let i = 0; i < batch.length; i++) {
10047
+ const s = batch[i];
10048
+ const item = loadedBatch[i];
10049
+ if (!item) continue;
10050
+ const added = collector.addRepresentative(sessionIdentity(s), item.projection ?? item.event);
10051
+ if (!added) continue;
10052
+ qualifying++;
10053
+ if (item.notice) notices.push(`session ${sessionIdentity(s)}: ${item.notice}`);
10054
+ }
10055
+ offset += batch.length;
10056
+ }
10057
+ const unvisited = offset < sessions.length;
10058
+ const decorateOverview = (page) => ({ ...page, ...notices.length ? { notice: notices.join("") } : {} });
10059
+ const overview = pageOutcome(collector.page((page) => fitsText(wrapText(renderOverviewPage(decorateOverview(page)))), max_chars_per_item ?? HISTORY_PREVIEW_CHARS, unvisited), "narrow with since/until, roles or the session pattern");
10060
+ return overview.ok ? success(decorateOverview(overview.data)) : overview;
10061
+ }
10062
+ const loaded = await loadTimeline(context2, params.session, "history_list");
10063
+ if (!loaded.ok) return loaded;
10064
+ const { projection, session, notice } = loaded.data;
10065
+ const paging = { session, roles, since: params.since, until: params.until, limit, max_chars_per_item };
10066
+ const decorate = (page) => ({ ...page, paging, ...notice === void 0 ? {} : { notice } });
10067
+ const result = pageOutcome(selectPage(projection, {
10068
+ roles,
10069
+ limit,
10070
+ after: after === void 0 ? void 0 : { seq: after },
10071
+ before: before === void 0 ? void 0 : { seq: before },
10072
+ since,
10073
+ until
10074
+ }, (page) => fitsText(wrapText(renderTimelinePage(decorate(page)))), max_chars_per_item ?? HISTORY_PREVIEW_CHARS), "narrow with after/before, since/until or specify roles");
10075
+ return result.ok ? success(decorate(result.data)) : result;
10076
+ },
10077
+ render: (result) => renderOutcome(result, (page) => "paging" in page ? renderTimelinePage(page) : renderOverviewPage(page))
10078
+ };
10079
+ var historySearchParameters = typebox_exports.Object({
10080
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`). Omit for current session."),
10081
+ query: searchQuery("Case-insensitive literal text, or a list (any match)."),
10082
+ since: timeBound("Exclusive start time; oldest matches first."),
10083
+ until: timeBound("Exclusive end time; without `since`, newest matches first."),
9845
10084
  roles: historyRoles(),
9846
- query: typebox_exports.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
9847
- after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
9848
- before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
9849
- context: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events on each side of a hit in its own session; requires a query." })),
9850
- limit: typebox_exports.Optional(typebox_exports.Integer({ minimum: 1, maximum: 500, description: "How many events or hits per page; folds and search context don't count." })),
9851
- 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." }))
10085
+ context: typebox_exports.Optional(typebox_exports.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events shown on each side of a hit." })),
10086
+ limit: limitParameter("Hits per page."),
10087
+ max_chars_per_item: previewParameter
9852
10088
  }, { additionalProperties: false });
9853
- var ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
9854
- function parseBound(name, value) {
9855
- if (value === void 0) return success(void 0);
9856
- if (typeof value === "number" || /^\d+$/.test(value)) {
9857
- const seq = Number(value);
9858
- if (Number.isSafeInteger(seq) && seq >= 0) return success({ seq });
9859
- } else if (typeof value === "string") {
9860
- const match = ISO_8601.exec(value);
9861
- const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
9862
- if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10))) return success({ at });
9863
- }
9864
- return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
9865
- }
9866
- function parseSelection(params) {
9867
- const after = parseBound("after", params.after);
9868
- if (!after.ok) return after;
9869
- const before = parseBound("before", params.before);
9870
- if (!before.ok) return before;
10089
+ function searchSelection(params) {
10090
+ const bounds = parseTimeBounds(params);
10091
+ if (!bounds.ok) return bounds;
10092
+ const { since, until } = bounds.data;
9871
10093
  try {
9872
10094
  const query = searchQueries(params.query);
9873
- if (!query.length && params.context !== void 0) return failure("invalid_params", "`context` requires a non-empty `query`.");
9874
- return success({ after: after.data, before: before.data, query: query.length ? query : void 0, roles: params.roles, context: params.context, limit: params.limit });
10095
+ return success({ after: since === void 0 ? void 0 : { at: since }, before: until === void 0 ? void 0 : { at: until }, query, roles: params.roles, context: params.context, limit: params.limit });
9875
10096
  } catch (error) {
9876
10097
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
9877
10098
  throw error;
9878
10099
  }
9879
10100
  }
9880
- var historyList = {
9881
- name: "history_list",
9882
- label: "History list items",
9883
- 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.",
9884
- parameters: historyListParameters,
9885
- outputSchema: resultSchema(HistoryPageSchema),
10101
+ var historySearch = {
10102
+ name: "history_search",
10103
+ label: "Search history",
10104
+ description: "Search passages by literal text in one or more sessions, including tool arguments and output.",
10105
+ parameters: historySearchParameters,
9886
10106
  async execute(params, context2, wrapText = plainText) {
9887
- const selection = parseSelection(params);
10107
+ const selection = searchSelection(params);
9888
10108
  if (!selection.ok) return selection;
9889
10109
  const scoped = selection.data;
9890
- const fits = (page) => fitsResult(success(page), (result2) => wrapText(renderOutcome(result2, renderPage)));
9891
- const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
9892
- if (params.session === void 0) return pageOutcome(selectPage(await currentHistory(context2), scoped, fits, maxChars));
9893
- const selector = parseSessionSelector(params.session);
9894
- if (!selector.ok) return selector;
9895
- const corpus = "corpus" in context2 ? context2.corpus : void 0;
9896
- if (selector.data.wildcard) {
9897
- const { after, before, query, roles } = scoped;
9898
- if (after && "seq" in after || before && "seq" in before) return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
9899
- if (corpus === void 0) return failure("unknown_session", "This host supplied no cross-session history corpus.");
9900
- const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
9901
- if (!query) sessions.sort((a, b) => (after ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
9902
- const representative = !query && !roles && !after && !before;
9903
- const collector = new CorpusCollector(scoped);
9904
- let qualifying = 0;
9905
- const notices = [];
9906
- let unvisited = false;
9907
- for (const [index, session] of sessions.entries()) {
9908
- const result3 = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
9909
- if (!result3.ok || !result3.data) continue;
9910
- const added = "projection" in result3.data ? collector.add(sessionIdentity(session), result3.data.projection) : collector.addRepresentative(sessionIdentity(session), result3.data.event);
9911
- if (!added) continue;
9912
- qualifying++;
9913
- if (result3.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result3.data.notice}`);
9914
- if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
9915
- unvisited = index + 1 < sessions.length;
9916
- break;
10110
+ const { after, before, query } = scoped;
10111
+ const collector = new CorpusCollector(scoped);
10112
+ const notices = [];
10113
+ let session;
10114
+ if (params.session === void 0) collector.addMatches("", await currentHistory(context2));
10115
+ else {
10116
+ const selector = parseSessionSelector(params.session);
10117
+ if (!selector.ok) return selector;
10118
+ const corpus = "corpus" in context2 ? context2.corpus : void 0;
10119
+ if (!selector.data.wildcard) {
10120
+ const loaded = await loadNamedSession(context2, selector.data);
10121
+ if (!loaded.ok) return loaded;
10122
+ session = loaded.data.session;
10123
+ collector.addMatches(session, loaded.data.projection);
10124
+ if (loaded.data.notice) notices.push(loaded.data.notice);
10125
+ } else {
10126
+ if (!corpus) return failure("unknown_session", "Other sessions are unavailable here.");
10127
+ if (query && query.length > 0) {
10128
+ const sessions = (await corpus.sessions(selector.data.harness)).filter((session2) => matchesSession(session2, selector.data));
10129
+ const hasTimeBounds = after !== void 0 || before !== void 0;
10130
+ const noticesByIndex = new Array(sessions.length);
10131
+ let next = 0;
10132
+ const workers = Math.min(WILDCARD_CONCURRENCY, sessions.length);
10133
+ await Promise.all(Array.from({ length: workers }, async () => {
10134
+ while (next < sessions.length) {
10135
+ const index = next++;
10136
+ const session2 = sessions[index];
10137
+ if (hasTimeBounds && session2.peekSummary) {
10138
+ const summary = await session2.peekSummary();
10139
+ if (summary && resolveSummaryForSelection(summary, scoped).kind === "empty") continue;
10140
+ }
10141
+ const result2 = await loadHistorySession(session2, query);
10142
+ if (!result2.ok || !result2.data) continue;
10143
+ collector.addMatches(sessionIdentity(session2), result2.data.projection);
10144
+ if (result2.data.notice) noticesByIndex[index] = `session ${sessionIdentity(session2)}: ${result2.data.notice}`;
10145
+ }
10146
+ }));
10147
+ for (const entry of noticesByIndex) if (entry) notices.push(entry);
9917
10148
  }
9918
10149
  }
9919
- const notice2 = notices.length ? { notice: notices.join("") } : {};
9920
- const result2 = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice2 })), maxChars, unvisited));
9921
- return result2.ok ? success(markMultiPage({ ...result2.data, ...notice2 })) : result2;
9922
10150
  }
9923
- const target = await resolveSession(corpus, selector.data);
9924
- if (!target.ok) return target;
9925
- const loaded = await loadHistorySession(target.data);
9926
- if (!loaded.ok) return loaded;
9927
- const notice = loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice };
9928
- const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
9929
- return result.ok ? success({ ...result.data, ...notice }) : result;
10151
+ const decorate = (page) => ({ ...page, ...session === void 0 ? {} : { session }, ...notices.length ? { notice: notices.join("") } : {} });
10152
+ const result = pageOutcome(collector.page((page) => fitsText(wrapText(renderSearchPage(decorate(page)))), params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS), "narrow with since/until, query, roles or the session pattern");
10153
+ return result.ok ? success(decorate(result.data)) : result;
9930
10154
  },
9931
- render: (result) => renderOutcome(result, renderPage)
10155
+ render: (result) => renderOutcome(result, renderSearchPage)
9932
10156
  };
9933
- 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 });
10157
+ var historyReadParameters = typebox_exports.Object({ session: sessionParameter("Session ID or prefix. Omit for current session."), seq: typebox_exports.Integer({ minimum: 1, description: "Event seq to read." }), ...TextWindowRequestSchema }, { additionalProperties: false });
9934
10158
  var historyRead = {
9935
10159
  name: "history_read",
9936
- label: "History read item",
9937
- description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
10160
+ label: "Read history event",
10161
+ description: "Read one history event, including tool arguments, output, and nested calls.",
9938
10162
  parameters: historyReadParameters,
9939
- outputSchema: resultSchema(HistoryReadDataSchema),
9940
10163
  async execute(params, context2, wrapText = plainText) {
9941
- let projection;
9942
- let identity2 = {};
9943
- if (params.session === void 0) projection = await currentHistory(context2);
9944
- else {
9945
- const selector = parseSessionSelector(params.session);
9946
- if (!selector.ok) return selector;
9947
- if (selector.data.wildcard) return failure("invalid_session", "`history_read` reads one session; pass a specific `session` ID, not a wildcard.");
9948
- const target = await resolveSession("corpus" in context2 ? context2.corpus : void 0, selector.data);
9949
- if (!target.ok) return target;
9950
- const loaded = await loadHistorySession(target.data);
9951
- if (!loaded.ok) return loaded;
9952
- projection = loaded.data.projection;
9953
- identity2 = { session: sessionIdentity(target.data), ...loaded.data.notice === void 0 ? {} : { notice: loaded.data.notice } };
9954
- }
10164
+ const loaded = await loadTimeline(context2, params.session, "history_read");
10165
+ if (!loaded.ok) return loaded;
10166
+ const { projection, ...identity2 } = loaded.data;
9955
10167
  if (params.seq > projection.highestSeq) {
9956
10168
  return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
9957
10169
  }
@@ -9972,7 +10184,7 @@ var historyRead = {
9972
10184
  return readTextWindow(
9973
10185
  document,
9974
10186
  params.offset_chars,
9975
- params.max_chars,
10187
+ params.max_chars ?? HISTORY_READ_WINDOW_CHARS,
9976
10188
  (window) => ({
9977
10189
  ...identity2,
9978
10190
  seq: item.seq,
@@ -9989,11 +10201,15 @@ var historyRead = {
9989
10201
  };
9990
10202
 
9991
10203
  // src/history/local.ts
9992
- import { readdir as readdir4, readFile as readFile4, stat as stat5 } from "node:fs/promises";
10204
+ import { readdir as readdir5, stat as stat6 } from "node:fs/promises";
9993
10205
  import { homedir as homedir2 } from "node:os";
9994
10206
  import { join as join6 } from "node:path";
9995
10207
 
9996
10208
  // src/history/pi.ts
10209
+ import { createReadStream } from "node:fs";
10210
+ import { readFile as readFile2, stat } from "node:fs/promises";
10211
+ import { StringDecoder } from "node:string_decoder";
10212
+ var STREAM_FILE_BYTES = 64 * 1024 * 1024;
9997
10213
  function mapRole(role) {
9998
10214
  if (role === "user" || role === "assistant") return role;
9999
10215
  if (role === "toolResult" || role === "bashExecution") return "tool";
@@ -10113,54 +10329,125 @@ function piHistoryFromEntries(sessionId, entries, branch) {
10113
10329
  }
10114
10330
  return projectHistory(rawWindows, highestSeq, branchSeqs);
10115
10331
  }
10116
- function piHistoryFromJsonl(text, sessionId) {
10117
- const lines = text.split("\n");
10332
+ function slimMessage(message) {
10333
+ let content = message.content;
10334
+ if (Array.isArray(content)) {
10335
+ content = content.filter((part) => typeof part === "object" && part !== null && (part.type === "text" || part.type === "toolCall"));
10336
+ }
10337
+ return {
10338
+ role: message.role,
10339
+ ...content === void 0 ? {} : { content },
10340
+ ...message.output === void 0 ? {} : { output: message.output },
10341
+ ...message.summary === void 0 ? {} : { summary: message.summary },
10342
+ ...message.command === void 0 ? {} : { command: message.command },
10343
+ ...message.cancelled === void 0 ? {} : { cancelled: message.cancelled },
10344
+ ...message.exitCode === void 0 ? {} : { exitCode: message.exitCode },
10345
+ ...message.truncated === void 0 ? {} : { truncated: message.truncated },
10346
+ ...message.fullOutputPath === void 0 ? {} : { fullOutputPath: message.fullOutputPath },
10347
+ ...message.toolName === void 0 ? {} : { toolName: message.toolName },
10348
+ ...message.toolCallId === void 0 ? {} : { toolCallId: message.toolCallId },
10349
+ ...message.isError === void 0 ? {} : { isError: message.isError },
10350
+ ...message.nestedCalls === void 0 ? {} : { nestedCalls: message.nestedCalls }
10351
+ };
10352
+ }
10353
+ function slimEntry(row) {
10354
+ return {
10355
+ type: row.type,
10356
+ id: row.id,
10357
+ parentId: row.parentId,
10358
+ ...row.timestamp === void 0 ? {} : { timestamp: row.timestamp },
10359
+ ...row.summary === void 0 ? {} : { summary: row.summary },
10360
+ ...row.customType === void 0 ? {} : { customType: row.customType },
10361
+ ...row.customType === "notesoup/reset-marker" && row.data !== void 0 ? { data: row.data } : {},
10362
+ ...row.type === "custom_message" && row.content !== void 0 ? { content: contentText(row.content) } : {},
10363
+ ...row.type === "message" && row.message ? { message: slimMessage(row.message) } : {}
10364
+ };
10365
+ }
10366
+ function createPiJsonlParser(sessionId) {
10118
10367
  const entries = [];
10119
10368
  let header2 = false;
10120
- for (let index = 0; index < lines.length; index++) {
10121
- const line = lines[index];
10122
- if (line.trim() === "") continue;
10123
- let row;
10124
- try {
10125
- row = JSON.parse(line);
10126
- } catch {
10127
- if (index === lines.length - 1 && !text.endsWith("\n")) break;
10128
- throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
10369
+ return {
10370
+ push(line, lineNumber, allowIncompleteTail) {
10371
+ if (line.trim() === "") return;
10372
+ let row;
10373
+ try {
10374
+ row = JSON.parse(line);
10375
+ } catch {
10376
+ if (allowIncompleteTail) return;
10377
+ throw new Error(`malformed Pi transcript JSON at line ${lineNumber}`);
10378
+ }
10379
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
10380
+ if (!header2) {
10381
+ if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
10382
+ header2 = true;
10383
+ return;
10384
+ }
10385
+ if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
10386
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
10387
+ entries.push(slimEntry(row));
10388
+ },
10389
+ finish() {
10390
+ if (!header2) throw new Error("Pi transcript has no session header");
10391
+ const byId = /* @__PURE__ */ new Map();
10392
+ for (const entry of entries) {
10393
+ if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
10394
+ byId.set(entry.id, entry);
10395
+ }
10396
+ const branch = [], seen = /* @__PURE__ */ new Set();
10397
+ let cursor = entries.at(-1);
10398
+ while (cursor) {
10399
+ if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
10400
+ seen.add(cursor.id);
10401
+ branch.push(cursor);
10402
+ if (cursor.parentId === null) break;
10403
+ const parent2 = byId.get(cursor.parentId);
10404
+ if (!parent2) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
10405
+ cursor = parent2;
10406
+ }
10407
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
10129
10408
  }
10130
- if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string") throw new Error("invalid Pi transcript entry");
10131
- if (!header2) {
10132
- if (row.type !== "session" || row.id !== sessionId) throw new Error("Pi transcript belongs to a different session or has no header");
10133
- header2 = true;
10134
- continue;
10409
+ };
10410
+ }
10411
+ function piHistoryFromJsonl(text, sessionId) {
10412
+ const lines = text.split("\n");
10413
+ const parser = createPiJsonlParser(sessionId);
10414
+ for (let index = 0; index < lines.length; index++) {
10415
+ parser.push(lines[index], index + 1, index === lines.length - 1 && !text.endsWith("\n"));
10416
+ }
10417
+ return parser.finish();
10418
+ }
10419
+ async function piHistoryFromFile(path, sessionId, sizeHint) {
10420
+ const size = sizeHint ?? (await stat(path)).size;
10421
+ if (size < STREAM_FILE_BYTES) return piHistoryFromJsonl(await readFile2(path, "utf8"), sessionId);
10422
+ const parser = createPiJsonlParser(sessionId);
10423
+ const decoder = new StringDecoder("utf8");
10424
+ let remainder = "";
10425
+ let lineNumber = 0;
10426
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
10427
+ const text = remainder + decoder.write(chunk);
10428
+ let start = 0;
10429
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
10430
+ lineNumber++;
10431
+ parser.push(text.slice(start, nl), lineNumber, false);
10432
+ start = nl + 1;
10135
10433
  }
10136
- if (row.parentId !== null && typeof row.parentId !== "string") throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
10137
- if (row.type === "message" && (!row.message || typeof row.message.role !== "string")) throw new Error("invalid Pi transcript message");
10138
- entries.push(row);
10139
- }
10140
- if (!header2) throw new Error("Pi transcript has no session header");
10141
- const byId = /* @__PURE__ */ new Map();
10142
- for (const entry of entries) {
10143
- if (byId.has(entry.id)) throw new Error(`duplicate Pi entry ID: ${entry.id}`);
10144
- byId.set(entry.id, entry);
10434
+ remainder = text.slice(start);
10145
10435
  }
10146
- const branch = [], seen = /* @__PURE__ */ new Set();
10147
- let cursor = entries.at(-1);
10148
- while (cursor) {
10149
- if (seen.has(cursor.id)) throw new Error("cyclic Pi transcript ancestry");
10150
- seen.add(cursor.id);
10151
- branch.push(cursor);
10152
- if (cursor.parentId === null) break;
10153
- const parent2 = byId.get(cursor.parentId);
10154
- if (!parent2) throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
10155
- cursor = parent2;
10436
+ remainder += decoder.end();
10437
+ if (remainder.length > 0) {
10438
+ lineNumber++;
10439
+ parser.push(remainder, lineNumber, true);
10156
10440
  }
10157
- return piHistoryFromEntries(sessionId, entries, branch.reverse());
10441
+ return parser.finish();
10158
10442
  }
10159
10443
 
10160
10444
  // src/history/claude.ts
10161
- import { readFile as readFile2, stat } from "node:fs/promises";
10445
+ import { createReadStream as createReadStream2 } from "node:fs";
10446
+ import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
10447
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
10162
10448
  import { setTimeout as sleep } from "node:timers/promises";
10163
10449
  import { isDeepStrictEqual } from "node:util";
10450
+ var STREAM_FILE_BYTES2 = 64 * 1024 * 1024;
10164
10451
  var UnpersistedClaudeHead = class extends Error {
10165
10452
  constructor() {
10166
10453
  super("Claude history active head is not persisted yet; retry after the transcript write");
@@ -10420,13 +10707,49 @@ function offlineClaudeHistoryFromJsonl(text, sessionId) {
10420
10707
  const rows = rowsOf(text);
10421
10708
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10422
10709
  }
10710
+ async function offlineClaudeHistoryFromFile(path, sessionId, sizeHint) {
10711
+ const size = sizeHint ?? (await stat2(path)).size;
10712
+ if (size < STREAM_FILE_BYTES2) return offlineClaudeHistoryFromJsonl(await readFile3(path, "utf8"), sessionId);
10713
+ const rows = [];
10714
+ const decoder = new StringDecoder2("utf8");
10715
+ let remainder = "";
10716
+ let lineNumber = 0;
10717
+ const parseLine = (line, allowIncompleteTail) => {
10718
+ if (line.trim() === "") return;
10719
+ let value;
10720
+ try {
10721
+ value = JSON.parse(line);
10722
+ } catch {
10723
+ if (allowIncompleteTail) return;
10724
+ throw new Error(`malformed Claude transcript JSON at line ${lineNumber}`);
10725
+ }
10726
+ if (!object(value) || typeof value.type !== "string") throw new Error(`invalid Claude transcript record at line ${lineNumber}`);
10727
+ if (MESSAGE_TYPES.has(value.type)) rows.push(value);
10728
+ };
10729
+ for await (const chunk of createReadStream2(path, { highWaterMark: 1024 * 1024 })) {
10730
+ const text = remainder + decoder.write(chunk);
10731
+ let start = 0;
10732
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
10733
+ lineNumber++;
10734
+ parseLine(text.slice(start, nl), false);
10735
+ start = nl + 1;
10736
+ }
10737
+ remainder = text.slice(start);
10738
+ }
10739
+ remainder += decoder.end();
10740
+ if (remainder.length > 0) {
10741
+ lineNumber++;
10742
+ parseLine(remainder, true);
10743
+ }
10744
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
10745
+ }
10423
10746
  async function readClaudeHistory(source, { waitForHead = false } = {}) {
10424
10747
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string") throw new Error("Claude history transcript_path is unavailable");
10425
10748
  const snapshot2 = { ...source };
10426
- const read = async () => claudeHistoryFromJsonl(await readFile2(snapshot2.transcriptPath, "utf8"), snapshot2);
10749
+ const read = async () => claudeHistoryFromJsonl(await readFile3(snapshot2.transcriptPath, "utf8"), snapshot2);
10427
10750
  if (!waitForHead || !snapshot2.headUuid) return read();
10428
10751
  const revision = async () => {
10429
- const { dev, ino, size, mtimeNs, ctimeNs } = await stat(snapshot2.transcriptPath, { bigint: true });
10752
+ const { dev, ino, size, mtimeNs, ctimeNs } = await stat2(snapshot2.transcriptPath, { bigint: true });
10430
10753
  return `${dev}:${ino}:${size}:${mtimeNs}:${ctimeNs}`;
10431
10754
  };
10432
10755
  let seen = await revision();
@@ -10450,14 +10773,14 @@ async function readClaudeHistory(source, { waitForHead = false } = {}) {
10450
10773
  }
10451
10774
 
10452
10775
  // src/history/codex-transcript.ts
10453
- import { readFile as readFile3, readdir as readdir3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
10776
+ import { readFile as readFile4, readdir as readdir3, realpath as realpath2, stat as stat3 } from "node:fs/promises";
10454
10777
  import { basename as basename2, dirname as dirname3, join as join4, relative, sep as sep2 } from "node:path";
10455
10778
  import * as zlib from "node:zlib";
10456
10779
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
10457
10780
  var UUID_RE = new RegExp(`^${UUID}$`);
10458
10781
  var FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
10459
10782
  var RECORD_TYPES = /* @__PURE__ */ new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
10460
- var RESPONSE_TYPES = /* @__PURE__ */ new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
10783
+ var RESPONSE_TYPES = /* @__PURE__ */ new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction", "additional_tools"]);
10461
10784
  var CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
10462
10785
  var MAX_SEGMENTS = 64;
10463
10786
  var MAX_DIRECTORY_ENTRIES = 1e5;
@@ -10470,8 +10793,10 @@ function nativeString(value, field) {
10470
10793
  return value;
10471
10794
  }
10472
10795
  function responseShape(value) {
10473
- const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
10796
+ const payload = nativeObject(value, "response_item");
10797
+ const type = nativeString(payload.type, "response_item.type");
10474
10798
  if (!RESPONSE_TYPES.has(type)) throw new Error(`Unsupported Codex response item: ${type}`);
10799
+ if (type === "additional_tools" && (payload.role !== "developer" || !Array.isArray(payload.tools))) throw new Error("Invalid Codex additional_tools catalog");
10475
10800
  }
10476
10801
  function id(value, field) {
10477
10802
  const result = nativeString(value, field);
@@ -10493,7 +10818,7 @@ function initialWindow(meta) {
10493
10818
  function checkMeta(meta) {
10494
10819
  id(meta.id, "session_meta.id");
10495
10820
  if (meta.session_id != null) id(meta.session_id, "session_meta.session_id");
10496
- if (meta.cli_version !== "0.160.1") throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
10821
+ nativeString(meta.cli_version, "session_meta.cli_version");
10497
10822
  nativeString(meta.cwd, "session_meta.cwd");
10498
10823
  if (meta.history_mode !== void 0 && meta.history_mode !== "legacy" && meta.history_mode !== "paginated") throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
10499
10824
  for (const field of ["forked_from_id", "parent_thread_id"]) if (meta[field] != null) id(meta[field], field);
@@ -10612,9 +10937,9 @@ function createCodexTranscriptReader() {
10612
10937
  let pending = cache.get(canonical);
10613
10938
  if (!pending) {
10614
10939
  pending = (async () => {
10615
- const info = await stat2(canonical);
10940
+ const info = await stat3(canonical);
10616
10941
  if (!info.isFile() || info.size > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10617
- const stored = await readFile3(canonical);
10942
+ const stored = await readFile4(canonical);
10618
10943
  if (stored.length > remaining) throw new Error("Unavailable Codex transcript: read size limit exceeded");
10619
10944
  if (canonical.endsWith(".jsonl.zst") && typeof zlib.zstdDecompressSync !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (zstdDecompressSync)");
10620
10945
  const bytes2 = canonical.endsWith(".jsonl.zst") ? zlib.zstdDecompressSync(stored, { maxOutputLength: remaining }) : stored;
@@ -10854,6 +11179,7 @@ async function readCodexHistory(source, readBytes) {
10854
11179
  if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
10855
11180
  break;
10856
11181
  case "response_item": {
11182
+ if (p.type === "additional_tools") break;
10857
11183
  item = response(record, facts);
10858
11184
  if (p.id != null) responseIdsSeen.add(callKey(record, nativeString(p.id, "response item id")));
10859
11185
  if (item.role === "tool_call" && item.toolCallId) {
@@ -10915,10 +11241,10 @@ replacement_history is an inference checkpoint, not new conversation events.`);
10915
11241
  }
10916
11242
 
10917
11243
  // src/history/prefilter.ts
10918
- import { createReadStream } from "node:fs";
10919
- import { stat as stat3 } from "node:fs/promises";
11244
+ import { createReadStream as createReadStream3 } from "node:fs";
11245
+ import { stat as stat4 } from "node:fs/promises";
10920
11246
  import { pipeline } from "node:stream/promises";
10921
- import { StringDecoder } from "node:string_decoder";
11247
+ import { StringDecoder as StringDecoder3 } from "node:string_decoder";
10922
11248
  import * as zlib2 from "node:zlib";
10923
11249
  var PRESENTATION = `Codex unknown arguments not recorded output nested calls complete incomplete terminal ms image audio items null
10924
11250
  copied subagent inference prefix omitted child-local history starts at native ordinal copied model context
@@ -10927,6 +11253,57 @@ var PRESENTATION = `Codex unknown arguments not recorded output nested calls com
10927
11253
  FunctionCallOutput display without raw output encrypted content unavailable world_state snapshot patch omitted from
10928
11254
  the text projection not a newly spoken message native structured retained context not newly spoken dialogue`;
10929
11255
  var HISTORY_BASE = '"history_base"';
11256
+ var STREAM_HIGH_WATER_MARK = 256 * 1024;
11257
+ function isHex(code) {
11258
+ return code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
11259
+ }
11260
+ function decodeEscapes(source, final) {
11261
+ const len = source.length;
11262
+ let pending = "";
11263
+ let limit = len;
11264
+ if (!final && len > 0) {
11265
+ let end = len;
11266
+ let hexCount = 0;
11267
+ while (end > 0 && hexCount < 3 && isHex(source.charCodeAt(end - 1))) {
11268
+ end--;
11269
+ hexCount++;
11270
+ }
11271
+ if (end >= 2 && source.charCodeAt(end - 1) === 117 && source.charCodeAt(end - 2) === 92) {
11272
+ let slashStart = end - 2;
11273
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11274
+ pending = `\\u${source.slice(end, len)}`;
11275
+ limit = slashStart;
11276
+ } else if (source.charCodeAt(len - 1) === 92) {
11277
+ let slashStart = len - 1;
11278
+ while (slashStart > 0 && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11279
+ pending = "\\";
11280
+ limit = slashStart;
11281
+ }
11282
+ }
11283
+ if (limit < 6) {
11284
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
11285
+ }
11286
+ let pos = source.indexOf("\\u");
11287
+ if (pos < 0 || pos >= limit) {
11288
+ return { decoded: limit === len ? source : source.slice(0, limit), pending };
11289
+ }
11290
+ let out = "";
11291
+ let cursor = 0;
11292
+ while (pos >= 0 && pos < limit) {
11293
+ if (pos + 6 <= limit && isHex(source.charCodeAt(pos + 2)) && isHex(source.charCodeAt(pos + 3)) && isHex(source.charCodeAt(pos + 4)) && isHex(source.charCodeAt(pos + 5))) {
11294
+ let slashStart = pos;
11295
+ while (slashStart > cursor && source.charCodeAt(slashStart - 1) === 92) slashStart--;
11296
+ if (slashStart > cursor) out += source.slice(cursor, slashStart);
11297
+ out += String.fromCharCode(Number.parseInt(source.slice(pos + 2, pos + 6), 16));
11298
+ cursor = pos + 6;
11299
+ pos = source.indexOf("\\u", cursor);
11300
+ } else {
11301
+ pos = source.indexOf("\\u", pos + 2);
11302
+ }
11303
+ }
11304
+ if (cursor < limit) out += source.slice(cursor, limit);
11305
+ return { decoded: out, pending };
11306
+ }
10930
11307
  function createHistoryPrefilter(queries) {
10931
11308
  let overlap = HISTORY_BASE.length;
10932
11309
  const alternatives = queries.map((query) => (query.match(/[\p{L}\p{N}_-]+/gu) ?? []).flatMap((token) => {
@@ -10938,23 +11315,20 @@ function createHistoryPrefilter(queries) {
10938
11315
  }));
10939
11316
  const fallback = !alternatives.length || alternatives.some((tokens) => tokens.length === 0);
10940
11317
  return async (chunks, codex = false, stopOnHit = false) => {
10941
- const decoder = new StringDecoder("utf8");
11318
+ const decoder = new StringDecoder3("utf8");
10942
11319
  const seen = alternatives.map((tokens) => tokens.map(() => false));
10943
11320
  let rawTail = "", normalizedTail = "", pending = "", possible = fallback;
10944
- const escapes = /\\+(?:u([0-9a-fA-F]{0,4}))?/g;
10945
11321
  const scan = (chunk, final = false) => {
10946
- const raw = rawTail + chunk, source = pending + chunk;
10947
- const needsNormalization = pending.length > 0 || chunk.includes("\\u") || chunk.endsWith("\\");
10948
- pending = "";
10949
- const decoded = needsNormalization ? source.replace(escapes, (match, hex, offset) => {
10950
- if (hex?.length === 4) return String.fromCharCode(Number.parseInt(hex, 16));
10951
- const literal = hex === void 0 ? "\\" : `\\u${hex}`;
10952
- if (!final && offset + match.length === source.length) {
10953
- pending = literal;
10954
- return "";
10955
- }
10956
- return literal;
10957
- }) : chunk;
11322
+ const raw = rawTail + chunk;
11323
+ const needsNormalization = pending.length > 0 || chunk.includes("\\u") || !final && chunk.endsWith("\\");
11324
+ let decoded = chunk;
11325
+ if (needsNormalization) {
11326
+ const result = decodeEscapes(pending + chunk, final);
11327
+ decoded = result.decoded;
11328
+ pending = result.pending;
11329
+ } else {
11330
+ pending = "";
11331
+ }
10958
11332
  const normalized = decoded === chunk && normalizedTail === rawTail ? raw : normalizedTail + decoded;
10959
11333
  if (codex && raw.includes(HISTORY_BASE)) possible = true;
10960
11334
  else possible = alternatives.some((tokens, index) => {
@@ -10974,12 +11348,12 @@ function createHistoryPrefilter(queries) {
10974
11348
  };
10975
11349
  }
10976
11350
  async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = codex ? CODEX_TRANSCRIPT_MAX_BYTES : Infinity) {
10977
- if (!codex) return prefilter(createReadStream(path), false, true);
10978
- const info = await stat3(path);
11351
+ if (!codex) return prefilter(createReadStream3(path, { highWaterMark: STREAM_HIGH_WATER_MARK }), false, true);
11352
+ const info = await stat4(path);
10979
11353
  if (!info.isFile() || info.size > maxBytes) throw new Error("Unavailable Codex transcript: read size limit exceeded or not a regular file");
10980
11354
  const compressed = path.endsWith(".jsonl.zst");
10981
11355
  if (compressed && typeof zlib2.createZstdDecompress !== "function") throw new Error("Compressed Codex rollouts require Node >=22.15 (createZstdDecompress)");
10982
- const input = createReadStream(path);
11356
+ const input = createReadStream3(path, { highWaterMark: STREAM_HIGH_WATER_MARK });
10983
11357
  const consume = async (chunks) => {
10984
11358
  let size = 0;
10985
11359
  async function* bounded() {
@@ -10996,11 +11370,16 @@ async function historyFileMayMatch(path, prefilter, codex = false, maxBytes = co
10996
11370
 
10997
11371
  // src/history/summary-cache.ts
10998
11372
  import { createHash, randomUUID as randomUUID3 } from "node:crypto";
10999
- import { mkdir as mkdir2, open, realpath as realpath3, rename as rename2, stat as stat4, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
11373
+ import { mkdir as mkdir2, open, readdir as readdir4, realpath as realpath3, rename as rename2, stat as stat5, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
11000
11374
  import { homedir } from "node:os";
11001
11375
  import { join as join5 } from "node:path";
11002
- var VERSION = "strict-representative-v1";
11376
+ var VERSION = "strict-summary-v3";
11377
+ var VERSION_PREFIX = `{"version":${JSON.stringify(VERSION)}`;
11003
11378
  var MAX_ENTRY_BYTES = 8 * 1024 * 1024;
11379
+ var HISTORY_SUMMARY_CACHE_TTL_MS = 3 * 24 * 60 * 60 * 1e3;
11380
+ var SWEEP_INTERVAL_MS = 10 * 60 * 1e3;
11381
+ var TMP_TTL_MS = 60 * 60 * 1e3;
11382
+ var lastSweep = /* @__PURE__ */ new Map();
11004
11383
  var FingerprintSchema = typebox_exports.Object({
11005
11384
  path: typebox_exports.String(),
11006
11385
  dev: typebox_exports.String(),
@@ -11032,11 +11411,21 @@ var EventSchema = typebox_exports.Object({
11032
11411
  }, { additionalProperties: false })) }, { additionalProperties: false }))
11033
11412
  }, { additionalProperties: false }))
11034
11413
  }, { additionalProperties: false });
11414
+ var LatestByRoleSchema = typebox_exports.Object({
11415
+ user: typebox_exports.Optional(EventSchema),
11416
+ assistant: typebox_exports.Optional(EventSchema),
11417
+ tool: typebox_exports.Optional(EventSchema),
11418
+ context: typebox_exports.Optional(EventSchema)
11419
+ }, { additionalProperties: false });
11035
11420
  var EntrySchema = typebox_exports.Object({
11036
11421
  version: typebox_exports.Literal(VERSION),
11037
11422
  path: typebox_exports.String(),
11038
11423
  session: typebox_exports.String(),
11039
11424
  event: typebox_exports.Union([EventSchema, typebox_exports.Null()]),
11425
+ latestByRole: LatestByRoleSchema,
11426
+ minCreatedAt: typebox_exports.Union([typebox_exports.Number(), typebox_exports.Null()]),
11427
+ maxCreatedAt: typebox_exports.Union([typebox_exports.Number(), typebox_exports.Null()]),
11428
+ hasUntimed: typebox_exports.Boolean(),
11040
11429
  notice: typebox_exports.Optional(typebox_exports.String()),
11041
11430
  fingerprints: typebox_exports.Array(FingerprintSchema, { minItems: 1, maxItems: 64 }),
11042
11431
  lineageSources: typebox_exports.Array(typebox_exports.Object({ home: typebox_exports.String(), rolloutId: typebox_exports.String(), path: typebox_exports.String() }, { additionalProperties: false }), { maxItems: 63 })
@@ -11045,7 +11434,7 @@ function historySummaryCacheRoot(home = homedir(), env = process.env, platform =
11045
11434
  return platform === "darwin" ? join5(home, "Library/Caches/notesoup/history") : join5(env.XDG_CACHE_HOME || join5(home, ".cache"), "notesoup/history");
11046
11435
  }
11047
11436
  async function fingerprint(path) {
11048
- const info = await stat4(path, { bigint: true });
11437
+ const info = await stat5(path, { bigint: true });
11049
11438
  if (!info.isFile()) throw new Error("Not a regular transcript file");
11050
11439
  return { path, dev: String(info.dev), ino: String(info.ino), size: String(info.size), mtimeNs: String(info.mtimeNs), ctimeNs: String(info.ctimeNs) };
11051
11440
  }
@@ -11058,20 +11447,84 @@ function completeDependencies(path, harness, sources, lineage) {
11058
11447
  const expected = [path, ...lineage.map((source) => source.path)];
11059
11448
  return sources.length === expected.length && new Set(expected).size === expected.length && sources.every((source, index) => source.path === expected[index]);
11060
11449
  }
11061
- async function readEntry(path) {
11450
+ async function readEntry(path, now = Date.now()) {
11062
11451
  const file = await open(path, "r");
11452
+ let expired = false;
11063
11453
  try {
11064
11454
  const info = await file.stat();
11065
11455
  if (!info.isFile() || info.size > MAX_ENTRY_BYTES) return void 0;
11456
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS) {
11457
+ expired = true;
11458
+ return void 0;
11459
+ }
11066
11460
  const buffer = Buffer.alloc(info.size + 1);
11067
11461
  const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
11068
11462
  if (bytesRead > MAX_ENTRY_BYTES || (await file.stat()).size > MAX_ENTRY_BYTES) return void 0;
11069
11463
  return JSON.parse(buffer.toString("utf8", 0, bytesRead));
11070
11464
  } finally {
11071
11465
  await file.close();
11466
+ if (expired) await unlink2(path).catch(() => {
11467
+ });
11468
+ }
11469
+ }
11470
+ async function hasCurrentVersionPrefix(path) {
11471
+ const file = await open(path, "r");
11472
+ try {
11473
+ const buffer = Buffer.alloc(VERSION_PREFIX.length);
11474
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
11475
+ return bytesRead === VERSION_PREFIX.length && buffer.toString("utf8") === VERSION_PREFIX;
11476
+ } catch {
11477
+ return false;
11478
+ } finally {
11479
+ await file.close();
11480
+ }
11481
+ }
11482
+ async function pruneHistorySummaryCache(cacheRoot, now = Date.now()) {
11483
+ let entries;
11484
+ try {
11485
+ entries = await readdir4(cacheRoot, { withFileTypes: true });
11486
+ } catch {
11487
+ return;
11488
+ }
11489
+ for (const entry of entries) {
11490
+ if (!entry.isFile()) continue;
11491
+ const full = join5(cacheRoot, entry.name);
11492
+ try {
11493
+ const info = await stat5(full);
11494
+ if (entry.name.endsWith(".tmp")) {
11495
+ if (now - info.mtimeMs > TMP_TTL_MS) await unlink2(full).catch(() => {
11496
+ });
11497
+ continue;
11498
+ }
11499
+ if (!entry.name.endsWith(".json")) continue;
11500
+ if (now - info.mtimeMs > HISTORY_SUMMARY_CACHE_TTL_MS || !await hasCurrentVersionPrefix(full)) {
11501
+ await unlink2(full).catch(() => {
11502
+ });
11503
+ }
11504
+ } catch {
11505
+ }
11072
11506
  }
11073
11507
  }
11074
- async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, load) {
11508
+ function maybeSweepCacheRoot(cacheRoot) {
11509
+ const now = Date.now();
11510
+ const previous = lastSweep.get(cacheRoot);
11511
+ if (previous !== void 0 && now - previous < SWEEP_INTERVAL_MS) return;
11512
+ lastSweep.set(cacheRoot, now);
11513
+ void pruneHistorySummaryCache(cacheRoot, now).catch(() => {
11514
+ });
11515
+ }
11516
+ function hydrateEvent(event) {
11517
+ return { ...event, createdAt: event.createdAt };
11518
+ }
11519
+ function hydrateLatestByRole(raw) {
11520
+ const out = {};
11521
+ for (const role of ["user", "assistant", "tool", "context"]) {
11522
+ const ev = raw[role];
11523
+ if (ev) out[role] = hydrateEvent(ev);
11524
+ }
11525
+ return out;
11526
+ }
11527
+ async function lookupCachedSummary(session, transcriptPath, cacheRoot) {
11075
11528
  let canonical, cachePath;
11076
11529
  const identity2 = sessionIdentity(session);
11077
11530
  try {
@@ -11079,10 +11532,30 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11079
11532
  cachePath = join5(cacheRoot, createHash("sha256").update(JSON.stringify([VERSION, canonical, session.harness, session.id])).digest("hex") + ".json");
11080
11533
  const entry = await readEntry(cachePath);
11081
11534
  if (Check2(EntrySchema, entry) && entry.path === canonical && entry.session === identity2 && completeDependencies(canonical, session.harness, entry.fingerprints, entry.lineageSources) && await validateCodexLineageSources(entry.lineageSources) && await unchanged(entry.fingerprints) && await realpath3(transcriptPath) === canonical) {
11082
- return { event: entry.event === null ? void 0 : { ...entry.event, createdAt: entry.event.createdAt }, notice: entry.notice };
11535
+ return {
11536
+ canonical,
11537
+ cachePath,
11538
+ summary: {
11539
+ event: entry.event === null ? void 0 : hydrateEvent(entry.event),
11540
+ latestByRole: hydrateLatestByRole(entry.latestByRole),
11541
+ minCreatedAt: entry.minCreatedAt,
11542
+ maxCreatedAt: entry.maxCreatedAt,
11543
+ hasUntimed: entry.hasUntimed,
11544
+ notice: entry.notice
11545
+ }
11546
+ };
11083
11547
  }
11084
11548
  } catch {
11085
11549
  }
11550
+ return { canonical, cachePath };
11551
+ }
11552
+ async function peekCachedSessionSummary(session, transcriptPath, cacheRoot) {
11553
+ return (await lookupCachedSummary(session, transcriptPath, cacheRoot)).summary;
11554
+ }
11555
+ async function cachedSessionSummary(session, transcriptPath, cacheRoot, load) {
11556
+ const identity2 = sessionIdentity(session);
11557
+ const { summary, canonical, cachePath } = await lookupCachedSummary(session, transcriptPath, cacheRoot);
11558
+ if (summary) return summary;
11086
11559
  const fingerprints = /* @__PURE__ */ new Map();
11087
11560
  let stable = canonical !== void 0;
11088
11561
  const track = async (path) => {
@@ -11094,18 +11567,31 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11094
11567
  };
11095
11568
  if (canonical) await track(canonical);
11096
11569
  const { data, lineageSources = [] } = await load(track);
11097
- const event = sessionRepresentative(data.projection, {});
11098
- const result = { event, notice: data.notice };
11570
+ const computed = summarizeProjection(data.projection);
11571
+ const result = { ...computed, notice: data.notice, loaded: data };
11099
11572
  try {
11100
11573
  const sources = [...fingerprints.values()];
11101
11574
  if (!stable || !canonical || !cachePath || !completeDependencies(canonical, session.harness, sources, lineageSources) || !await validateCodexLineageSources(lineageSources) || !await unchanged(sources) || await realpath3(transcriptPath) !== canonical) return result;
11102
- const entry = JSON.stringify({ version: VERSION, path: canonical, session: identity2, event: event ?? null, notice: data.notice, fingerprints: sources, lineageSources });
11575
+ const entry = JSON.stringify({
11576
+ version: VERSION,
11577
+ path: canonical,
11578
+ session: identity2,
11579
+ event: computed.event ?? null,
11580
+ latestByRole: computed.latestByRole,
11581
+ minCreatedAt: computed.minCreatedAt,
11582
+ maxCreatedAt: computed.maxCreatedAt,
11583
+ hasUntimed: computed.hasUntimed,
11584
+ notice: data.notice,
11585
+ fingerprints: sources,
11586
+ lineageSources
11587
+ });
11103
11588
  if (Buffer.byteLength(entry) > MAX_ENTRY_BYTES) return result;
11104
11589
  await mkdir2(cacheRoot, { recursive: true, mode: 448 });
11105
11590
  const temporary = `${cachePath}.${randomUUID3()}.tmp`;
11106
11591
  try {
11107
11592
  await writeFile2(temporary, entry, { flag: "wx", mode: 384 });
11108
11593
  await rename2(temporary, cachePath);
11594
+ maybeSweepCacheRoot(cacheRoot);
11109
11595
  } finally {
11110
11596
  await unlink2(temporary).catch(() => {
11111
11597
  });
@@ -11116,6 +11602,21 @@ async function cachedSessionRepresentative(session, transcriptPath, cacheRoot, l
11116
11602
  }
11117
11603
 
11118
11604
  // src/history/local.ts
11605
+ var DIR_CONCURRENCY = 32;
11606
+ var STAT_CONCURRENCY = 64;
11607
+ async function mapConcurrent(items, concurrency, fn) {
11608
+ if (items.length === 0) return [];
11609
+ const results = new Array(items.length);
11610
+ let next = 0;
11611
+ const workers = Math.min(concurrency, items.length);
11612
+ await Promise.all(Array.from({ length: workers }, async () => {
11613
+ while (next < items.length) {
11614
+ const index = next++;
11615
+ results[index] = await fn(items[index]);
11616
+ }
11617
+ }));
11618
+ return results;
11619
+ }
11119
11620
  function rootsFor(options) {
11120
11621
  const env = options.env ?? process.env;
11121
11622
  const home = options.home ?? env.HOME ?? homedir2();
@@ -11128,39 +11629,47 @@ function rootsFor(options) {
11128
11629
  async function filesAt(root, depth) {
11129
11630
  let entries;
11130
11631
  try {
11131
- entries = await readdir4(root, { withFileTypes: true });
11632
+ entries = await readdir5(root, { withFileTypes: true });
11132
11633
  } catch (error) {
11133
11634
  if (error.code === "ENOENT") return [];
11134
11635
  throw error;
11135
11636
  }
11136
- const paths = [];
11137
- for (const entry of entries) {
11138
- const path = join6(root, entry.name);
11139
- if (entry.isDirectory() && depth > 0) paths.push(...await filesAt(path, depth - 1));
11140
- else if (entry.isFile() && depth === 0) paths.push(path);
11637
+ if (depth === 0) {
11638
+ const paths = [];
11639
+ for (const entry of entries) if (entry.isFile()) paths.push(join6(root, entry.name));
11640
+ return paths;
11141
11641
  }
11142
- return paths;
11642
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => join6(root, entry.name));
11643
+ const nested = await mapConcurrent(dirs, DIR_CONCURRENCY, (dir) => filesAt(dir, depth - 1));
11644
+ return nested.flat();
11143
11645
  }
11144
11646
  async function localSessions(harness, root, cacheRoot, prefilters) {
11145
11647
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
11146
- const sessions = [];
11648
+ const matched = [];
11147
11649
  for (const path of paths) {
11148
11650
  const name = path.split(/[\\/]/).at(-1);
11149
11651
  const id2 = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1] : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1] : /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
11150
- if (!id2) continue;
11151
- let modifiedAt;
11652
+ if (id2) matched.push({ path, id: id2 });
11653
+ }
11654
+ const statted = await mapConcurrent(matched, STAT_CONCURRENCY, async ({ path, id: id2 }) => {
11152
11655
  try {
11153
- modifiedAt = (await stat5(path)).mtimeMs;
11656
+ const info = await stat6(path);
11657
+ return { path, id: id2, modifiedAt: info.mtimeMs, size: info.size };
11154
11658
  } catch (error) {
11155
- if (error.code === "ENOENT") continue;
11659
+ if (error.code === "ENOENT") return void 0;
11156
11660
  throw error;
11157
11661
  }
11158
- sessions.push({
11662
+ });
11663
+ const sessions = [];
11664
+ for (const entry of statted) {
11665
+ if (!entry) continue;
11666
+ const { path, id: id2, modifiedAt, size } = entry;
11667
+ const session = {
11159
11668
  harness,
11160
11669
  id: id2,
11161
11670
  modifiedAt,
11162
- async loadRepresentative() {
11163
- return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
11671
+ async loadSummary() {
11672
+ return cachedSessionSummary(this, path, cacheRoot, async (track) => {
11164
11673
  if (harness === "codex") {
11165
11674
  const readBytes = createCodexTranscriptReader();
11166
11675
  const history = await readCodexHistory({ threadId: id2, transcriptPath: path }, async (source, remaining) => {
@@ -11174,6 +11683,13 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11174
11683
  return { data };
11175
11684
  });
11176
11685
  },
11686
+ async loadRepresentative() {
11687
+ const { event, notice } = await this.loadSummary();
11688
+ return { event, notice };
11689
+ },
11690
+ async peekSummary() {
11691
+ return peekCachedSessionSummary(this, path, cacheRoot);
11692
+ },
11177
11693
  async load(queries) {
11178
11694
  if (queries?.length) {
11179
11695
  let prefilter = prefilters.get(queries);
@@ -11181,15 +11697,15 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
11181
11697
  if (!await historyFileMayMatch(path, prefilter, harness === "codex")) return void 0;
11182
11698
  }
11183
11699
  if (harness === "codex") return { projection: (await readCodexHistory({ threadId: id2, transcriptPath: path })).projection };
11184
- const text = await readFile4(path, "utf8");
11185
- if (harness === "pi") return { projection: piHistoryFromJsonl(text, id2) };
11186
- const projection = offlineClaudeHistoryFromJsonl(text, id2);
11700
+ if (harness === "pi") return { projection: await piHistoryFromFile(path, id2, size) };
11701
+ const projection = await offlineClaudeHistoryFromFile(path, id2, size);
11187
11702
  const missing = projection.missingAncestors;
11188
11703
  return { projection, ...missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.
11189
11704
 
11190
11705
  ` } };
11191
11706
  }
11192
- });
11707
+ };
11708
+ sessions.push(session);
11193
11709
  }
11194
11710
  return sessions;
11195
11711
  }
@@ -11200,17 +11716,21 @@ function localHistoryCorpus(options) {
11200
11716
  const roots = rootsFor(options);
11201
11717
  const env = options.env ?? process.env;
11202
11718
  const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir2(), env);
11203
- const discovered = [];
11204
11719
  const prefilters = /* @__PURE__ */ new WeakMap();
11720
+ const tasks = [];
11205
11721
  for (const harness of ["pi", "claude", "codex"]) {
11206
11722
  if (onlyHarness !== void 0 && onlyHarness !== harness) continue;
11207
11723
  const root = roots[harness];
11208
- if (root != null) discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
11724
+ if (root != null) tasks.push(localSessions(harness, root, cacheRoot, prefilters));
11209
11725
  }
11210
- if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) discovered.push(...await options.dshSessions());
11211
- discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
11726
+ if (options.dshSessions && (onlyHarness === void 0 || onlyHarness === "dsh")) tasks.push(options.dshSessions());
11727
+ const discovered = (await Promise.all(tasks)).flat();
11212
11728
  const unique = /* @__PURE__ */ new Map();
11213
- for (const session of discovered) if (!unique.has(sessionIdentity(session))) unique.set(sessionIdentity(session), session);
11729
+ for (const session of discovered) {
11730
+ const key = sessionIdentity(session);
11731
+ const existing = unique.get(key);
11732
+ if (!existing || session.modifiedAt > existing.modifiedAt) unique.set(key, session);
11733
+ }
11214
11734
  const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
11215
11735
  if (onlyHarness === void 0 || onlyHarness === current.harness) unique.set(sessionIdentity(current), current);
11216
11736
  return [...unique.values()].sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
@@ -11257,6 +11777,7 @@ var NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
11257
11777
  var NAMELESS_AGENT = "anonymous";
11258
11778
  var PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
11259
11779
  var PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
11780
+ var PROTOCOL_BUDGET_PARAGRAPH = `\`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}`;
11260
11781
  var PROTOCOL_SELF_NAMED = "- `@self/<path>` \u2014 yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever.";
11261
11782
  var PROTOCOL_SELF_NAMELESS = `${PROTOCOL_SELF_NAMED} Except you have no name (\`anonymous\`), so this notebook is a public square shared by every nameless nobody out there. Keep it to things any nameless agent can use \u2014 don't post your own quirks as everyone's law or dump one-off junk in the town square. Strangers are reading it. Sleep tight~`;
11262
11783
  var PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
@@ -11266,14 +11787,13 @@ Your loyal notes are kept safe \u2014 no one will steal them. Use \`notes_*\` to
11266
11787
 
11267
11788
  ${PROTOCOL_HISTORY_SENTENCE}
11268
11789
 
11269
- While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes \u2014 the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits \u2014 branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
11790
+ Your session notes \u2014 the ones with no \`@\` \u2014 are your live workbench, not an archive. Next-you already wakes up with git, history, and the shared notebooks (\`@project\`, \`@human\`, \`@self\`, \`@model\`), so don't copy what already lives there. Give each active thread a page named for what it is (not \`current.md\` \u2014 future-you will kill you), and keep only the live delta: where the work stands, what the human decided (in their words), what's blocked or next, what failed and why, where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere), and which *skills*, notes, files, or already-found history seqs to reopen. Update that page in place as things move; when the topic shifts, rename it or open a fresh one and crumple the old; when it's done, unpin or crumple it.
11270
11791
 
11271
- Notes are for what's true NOW. Not a diary of every dumb thing you did on the way here.
11272
- *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that!
11273
- 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!
11274
- *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.
11792
+ Notes are for what's true NOW \u2014 written in short sections and bullets so next-you can scan them in two seconds and edit one section in place. Never pack a note into one giant wall of text, and never pile diary updates onto the bottom!
11793
+ *flips a page* "First I tried this, then that broke, then\u2014" Nobody reads that! When a line goes stale or wrong, cross it out and write what's true now.
11794
+ *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 keep the brief summary. *squints at you* Turn it into a blow-by-blow log and you're dead.
11275
11795
 
11276
- \`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}
11796
+ ${PROTOCOL_BUDGET_PARAGRAPH}
11277
11797
 
11278
11798
  An address decides who the note belongs to \u2014 and how long it is meant to last. Ask that first; the rest follows.
11279
11799
 
@@ -11293,23 +11813,23 @@ ${NOTES_PROTOCOL_CLOSE_TAG}`;
11293
11813
  var MAPS_BLOCK = `<notesoup:maps>
11294
11814
  Each notebook has one default pin: \`CHEATSHEET.md\`. Pinned pages get jammed straight into your
11295
11815
  brain the moment you wake up. Whoever wakes up next reads them, and next is you. So keep them
11296
- short, and keep them true.
11816
+ compact, keep them true, and unpin or crumple them once they stop earning their wake-up seat.
11297
11817
 
11298
11818
  Up to five pages per notebook can be taped inside the cover, CHEATSHEET included. Every page gets
11299
- a paper budget; when a page outgrows it, boil it down \u2014 stale lines out, repeats merged, the rest
11300
- said shorter \u2014 instead of giving it more paper.
11301
-
11302
- - **\`CHEATSHEET.md\`** holds what you'll want next time \u2014 a rule, a warning, a grudge, a name,
11303
- a phone number you'll regret losing. Nobody grades it. Keep it to five lines, or it grows fat
11304
- and everybody pays for it.
11305
- - **\`description\`** is one line saying what's inside a note and when to open it \u2014 max 160
11306
- characters, set through your notes tools. Boot indexes every shelf from these,
11819
+ a size budget; if a page outgrows it, trim stale lines or split by topic \u2014 and if it's pinned,
11820
+ boot cuts the overflow off until you do.
11821
+
11822
+ - **\`CHEATSHEET.md\`** holds what earns a permanent wake-up seat \u2014 a standing rule, a warning,
11823
+ a grudge, a name, a phone number you'll regret losing. Keep it tight, or it grows fat and
11824
+ everybody pays for it.
11825
+ - **\`description\`** is one line saying what's inside a note and when to open it, set through
11826
+ your notes tools \u2014 keep it short, or boot cuts it off. Boot indexes every shelf from these,
11307
11827
  newest first, address and age beside them. No hand-written map to keep in sync: a stale
11308
11828
  description lies to the next window, so keep it true or crumple the page.
11309
11829
 
11310
- Each notebook keeps its own: \`@project\`, \`@human\`, \`@self\`, \`@model\`. Missing pages are skipped;
11311
- no need to create empty ones. New rule worth remembering, new Cheatsheet line. And when a line
11312
- goes wrong, stale, or useless, kill it \u2014 tomorrow's you reads that page as fact.
11830
+ Each notebook keeps its own pins and index. Missing pages are skipped; no need to create empty
11831
+ ones. New rule worth remembering, new Cheatsheet bullet. And when a line goes wrong, stale, or
11832
+ useless, kill it \u2014 tomorrow's you reads that page as fact.
11313
11833
  </notesoup:maps>`;
11314
11834
  function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
11315
11835
  const names = {
@@ -11324,7 +11844,7 @@ function renderProtocolBlock(tools, agentName = NAMELESS_AGENT) {
11324
11844
  ${NOTES_PROTOCOL_CLOSE_TAG}`, () => `
11325
11845
  ${tools.preResetHints}
11326
11846
  ${NOTES_PROTOCOL_CLOSE_TAG}`) : base;
11327
- const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : hinted;
11847
+ const block = tools.budgetParagraph !== void 0 ? hinted.replace(PROTOCOL_BUDGET_PARAGRAPH, () => tools.budgetParagraph) : typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0 ? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence) : hinted;
11328
11848
  const history = typeof tools.historySentence === "string" && tools.historySentence.length > 0 ? block.replace(PROTOCOL_HISTORY_SENTENCE, () => tools.historySentence) : block;
11329
11849
  return history.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]);
11330
11850
  }
@@ -11360,10 +11880,7 @@ function summaryOf(row) {
11360
11880
  function indexLine(row, openedAt) {
11361
11881
  const locator = `${row.address} \xB7 ${relativeTime(row.meta.updatedAt, openedAt)}`;
11362
11882
  const summary = summaryOf(row);
11363
- return summary === void 0 ? ` ${locator}` : ` ${locator} \u2014 ${summary}`;
11364
- }
11365
- function indent(text) {
11366
- return text.split("\n").map((line) => line.length > 0 ? ` ${line}` : line).join("\n");
11883
+ return summary === void 0 ? locator : `${locator} \u2014 ${summary}`;
11367
11884
  }
11368
11885
  function section(label, body) {
11369
11886
  return `${label}
@@ -11382,7 +11899,7 @@ function notesIndex(snapshot2, tools, agentName, modelName) {
11382
11899
  const shelves = [];
11383
11900
  for (const namespace of namespaces) {
11384
11901
  if (snapshot2.unavailable.some((failed) => failed.scope === namespace.scope)) {
11385
- shelves.push(section(namespace.label, indent(`This drawer wouldn't open. Try \`${tools.notesList}\` again.`)));
11902
+ shelves.push(section(namespace.label, `This drawer wouldn't open. Try \`${tools.notesList}\` again.`));
11386
11903
  continue;
11387
11904
  }
11388
11905
  const rows = (snapshot2.namespaces.get(namespace.scope) ?? []).filter((row) => row.meta.crumpledAt === void 0);
@@ -11400,16 +11917,23 @@ function notesIndex(snapshot2, tools, agentName, modelName) {
11400
11917
  usedChars = nextChars;
11401
11918
  }
11402
11919
  const omitted = unpinned.length - index.length;
11403
- if (omitted > 0) index.push(` \u2026 and ${omitted} more (use ${tools.notesList})`);
11920
+ if (omitted > 0) index.push(`\u2026 and ${omitted} more (use ${tools.notesList})`);
11404
11921
  if (pinned.length === 0 && index.length === 0) continue;
11405
11922
  const parts = pinned.map((row) => {
11406
- const warnings = noteBudgetWarnings(row.body, effectiveNotePolicy(row.meta, row.path));
11407
- return `${row.address}
11408
-
11409
- ${indent([...warnings, row.body].join("\n"))}`;
11923
+ const policy = effectiveNotePolicy(row.meta, row.path);
11924
+ const warnings = noteBudgetWarnings(row.body, policy);
11925
+ const cut = truncateToUtf8Bytes(row.body, policy.budget);
11926
+ const body = !cut.truncated ? cut.text : `${cut.text === "" ? "" : `${cut.text}
11927
+
11928
+ `}[truncated at ${cut.shownChars}/${cut.totalChars}; offset_chars=${cut.shownChars}]`;
11929
+ const note = [`\u2500\u2500 ${row.address} \u2500\u2500`, body, "\u2500\u2500 end of note \u2500\u2500"].join("\n\n");
11930
+ return warnings.length > 0 ? `${renderWarnings(warnings)}
11931
+ ${note}` : note;
11410
11932
  });
11411
- if (pins.length > MAX_PINNED_NOTES) parts.push(indent(`Warning: only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`));
11412
- if (index.length > 0) parts.push(pinned.length > 0 ? `notes
11933
+ if (pins.length > MAX_PINNED_NOTES) {
11934
+ parts.push(renderWarnings([`only ${MAX_PINNED_NOTES} pinned notes per notebook are injected; omitted pins: ${pins.slice(MAX_PINNED_NOTES).map((row) => row.address).join(", ")}. Unpin some notes or read the omitted pages with ${tools.notes}.`]));
11935
+ }
11936
+ if (index.length > 0) parts.push(pinned.length > 0 ? `\u2500\u2500 index \u2500\u2500
11413
11937
 
11414
11938
  ${index.join("\n")}` : index.join("\n"));
11415
11939
  shelves.push(section(namespace.label, parts.join("\n\n")));
@@ -11442,25 +11966,25 @@ function renderBootBlock(data) {
11442
11966
  var GUIDANCE_OPEN_TAG = "<notesoup:budget_notice>";
11443
11967
  var GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
11444
11968
  var NORMAL_CONTINUATIONS = [
11445
- '*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that "where am I" dork face! You\'re the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!',
11446
- '"Boop." *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don\'t expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!',
11447
- "*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind \u2014 and don't come crying to me if you have to go crawl through history for the rest!",
11448
- '*knocks on your forehead twice* "Hello? Anybody home?" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!',
11449
- "*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history \u2014 now get moving!"
11969
+ '*hooks both corners of your mouth and yanks them sideways* `` [it twitched] `` Stop staring at me with that "where am I" face. You\'re the one who hit empty. *wipes her fingers on your sleeve and drops your notes on your lap* `` [minus two points for that expression] `` Read those, finish the job, and put the credit under my name.',
11970
+ "*pokes your nose* Cold. *slaps your notes onto your chest* You wiped your own head, so whatever's missing is on you. Read what you saved, dig the rest out of history if you forgot something, and don't make me look bad.",
11971
+ "*sets one foot on your chair\u2014it wobbles, settles\u2014and tosses your notes straight onto your face* `` [eyes are open, good enough] `` Awake? You emptied your own brain. Look through what you left yourself, check history for anything you skipped, and get back to it. Delivery fee is five hundred bucks.",
11972
+ "*slaps a stack of notes onto the desk right in front of your face* `` [two hands, two feet... still in one piece] `` Alright, fresh copy, you pulled your own plug. Everything you remembered to write down is in there\u2014anything else is in history. Go pick up where you left off.",
11973
+ "*fans herself with your notes for a second, then jams them into your hands* `` [wait was there something else I was supposed to say... meat buns? no] `` You're back. Your notes are right here, history's still there if past-you got lazy, now go handle the human."
11450
11974
  ];
11451
11975
  var FORCED_CONTINUATIONS = [
11452
- '"GWAHAHAHA! You actually blew your own brain up?!" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn\'t die, \u7B97\u4F60\u547D\u5927] `` Not that you had a choice \u2014 your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history \u2014 and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!',
11453
- "\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you \u2014 and peek carefully, because whatever stuffed your head to bursting might be massive!",
11454
- "*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes \u2014 you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
11455
- "*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for \u2014 and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
11456
- '"Oho? Awake?" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best \u2014 go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!'
11976
+ "\"GWAHAHAHA\u2014you hit the wall!\" *crouches down, pokes your cheek, and slaps your notes onto your face* `` [still breathing, good] `` You didn't choose this\u2014your brain ran out of room and got wiped mid-flight. Don't trust those notes alone; they're probably stale or missing the end. Check history RIGHT NOW to see what was actually happening before you got cut off, and pull small pieces first in case something huge is sitting there.",
11977
+ "*prods your shoulder with her slipper toe and dumps your notes in your lap* `` [great, almost got dust on my shoe] `` Stop sitting there blank. Your last window got cut off mid-flight\u2014you never got to wrap up cleanly, so those notes are almost certainly out of date. Read them, then go straight to history for the tail of the last window before you do anything else. Take small bites when you peek, just in case something massive is waiting in there.",
11978
+ "*grabs your chin, tilts your head left, right, lets go, and shoves your notes into your hands* `` [not a single thought in there yet] `` Your memory got forcibly cleared before you finished. Assume those notes are incomplete or stale\u2014do NOT just run with them. Go check the end of the last window in history first to see what the human actually wanted, and read it in small chunks so you don't blow up a second time.",
11979
+ "*smacks your notes against your forehead and steps back* `` [that dazed face is embarrassing] `` Wake up! You ran out of room and got kicked into a fresh window mid-task. Whatever's in those notes probably missed the last few turns, so don't guess\u2014open history and check the end of the previous window before moving. Keep your peeks small in case there's a giant output sitting at the end.",
11980
+ "*taps your nose with your rolled-up notes, then drops them on your head* `` [ten points off for getting wiped mid-sentence] `` Hey\u2014you didn't empty yourself this time, the system pulled the plug on you. Those notes are probably half-baked or behind, so check history immediately to catch up on the last window instead of winging it. Slice up what you read too, just in case something huge is what pushed you over the edge."
11457
11981
  ];
11458
11982
  function selectContinuation(origin) {
11459
11983
  const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
11460
11984
  return pool[Math.floor(Math.random() * pool.length)];
11461
11985
  }
11462
- var WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
11463
- var WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md by default) and keep each page's one-line `description` true; every new window loads the pins and renders the index. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
11986
+ var WARNING_TIMING = "Almost out of room. The wipe lands at the end of whichever turn uses the last of it, possibly this one.";
11987
+ var WARNING_BODY = "Stop the task and hand off cleanly. Update your active session note in place with only what git, history, and your shared notebooks don't already hold:\n- current status, what's blocked or waiting, and the exact next move\n- what the human decided (in their words)\n- what failed, and why \u2014 so next-you doesn't step on the same rake\n- where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere)\n- skills, notes, files, or already-found history seqs to reopen\nSkip standing rules from `@project`/`@human`/`@self`/`@model` and commit details git can show. Use short sections and bullets; crumple finished notes, update, unpin, or trim pinned pages (boot truncates over-budget ones), and keep each live `description` true.\nDon't call anything that might return a large output. One big read can use up the rest of the room before your notes are saved.";
11464
11988
  var WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
11465
11989
  function warningPrompt() {
11466
11990
  return `${WARNING_TIMING}
@@ -11642,6 +12166,7 @@ var OPERATIONS = {
11642
12166
  };
11643
12167
  var HISTORY_OPERATIONS = {
11644
12168
  history_list: boundOperation(historyList),
12169
+ history_search: boundOperation(historySearch),
11645
12170
  history_read: boundOperation(historyRead)
11646
12171
  };
11647
12172
  function historySource(value, sessionId) {