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
@@ -1,36 +1,53 @@
1
- /** Host-neutral history operations: one bounded payload for text and structured results. */
1
+ /** Host-neutral history operations: bounded plain-text output. */
2
2
  import { Type, type Static } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
3
+ import { HISTORY_PREVIEW_CHARS, HISTORY_READ_WINDOW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
4
  import { failure, success, type Outcome } from "../result.js";
5
- import { fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
6
- import { historyRoles, searchQuery } from "./schema.js";
5
+ import { fitsText, readTextWindow, renderOutcome, renderTextWindow, TextWindowRequestSchema, type TextWindow, type Operation } from "./result.js";
6
+ import { historyRoles, parseIsoTimestamp, searchQuery } from "./schema.js";
7
+ import { localIso } from "../notes/frontmatter.js";
7
8
  import { InvalidQueryError, searchQueries } from "../text-match.js";
8
- import { HistoryPageSchema, CorpusCollector, isMultiPage, markMultiPage, selectPage, type HistoryPage, type HistoryPageResult, type HistorySelection } from "../history/query.js";
9
- import { currentHistory, loadHistoryRepresentative, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
10
- import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryBound, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
9
+ import { CorpusCollector, selectPage, type HistoryPage, type HistoryPageResult, type HistorySelection } from "../history/query.js";
10
+ import { currentHistory, loadHistoryRepresentative, loadHistorySession, loadHistorySummary, matchesSession, parseSessionSelector, resolveSession, resolveSummaryForSelection, sessionIdentity, type HistoryContext, type HistorySession, type SessionSelector } from "../history/corpus.js";
11
+ import { allItems, eventDocument, nestedCallSummary, toolSummary, type HistoryRole, type NestedCallSummary, type ToolSummary, type HistoryEvent, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "../history/history.js";
12
+
13
+ const WILDCARD_CONCURRENCY = 12;
14
+
15
+ async function loadOverviewSession(
16
+ session: HistorySession,
17
+ scoped: HistorySelection,
18
+ ): Promise<{ projection?: HistoryProjection; event?: HistoryEvent; notice?: string } | undefined> {
19
+ if (session.loadSummary) {
20
+ const summary = await loadHistorySummary(session);
21
+ if (!summary.ok) return undefined;
22
+ const resolved = resolveSummaryForSelection(summary.data, scoped);
23
+ if (resolved.kind === "empty") return undefined;
24
+ if (resolved.kind === "hit") return { event: resolved.event, notice: resolved.notice };
25
+ if (summary.data.loaded) return summary.data.loaded;
26
+ } else if (!scoped.roles && !scoped.after && !scoped.before && session.loadRepresentative) {
27
+ const rep = await loadHistoryRepresentative(session);
28
+ return rep.ok ? rep.data : undefined;
29
+ }
30
+ const loaded = await loadHistorySession(session);
31
+ return loaded.ok ? loaded.data : undefined;
32
+ }
11
33
 
12
34
  /** One read: identity, tool summary and a flat document slice. */
13
- const HistoryReadDataSchema = Type.Object({
14
- session: Type.Optional(Type.String()),
15
- notice: Type.Optional(Type.String()),
16
- seq: Type.Integer({ minimum: 1 }),
17
- role: HistoryRoleSchema,
18
- created_at: Type.Union([Type.String(), Type.Null()]),
19
- ...ToolSummarySchema.properties,
20
- nested_calls: Type.Optional(NestedCallSummarySchema),
21
- ...TextWindowSchema.properties,
22
- }, { additionalProperties: false });
23
- type HistoryReadData = Static<typeof HistoryReadDataSchema>;
35
+ type HistoryReadData = ToolSummary & TextWindow & {
36
+ session?: string; notice?: string; seq: number; role: HistoryRole;
37
+ created_at: string | null; nested_calls?: NestedCallSummary;
38
+ };
24
39
 
25
40
  /* ------------------------------------------------------------------ rendering */
26
41
 
27
- function header(item: { session?: string; seq: number; role: string }): string {
28
- return `${item.session === undefined ? "" : `session ${item.session} | `}seq ${item.seq} | ${item.role}`;
42
+ function header(item: { session?: string; seq: number; role: string; created_at?: string | null }): string {
43
+ const atMs = item.created_at ? Date.parse(item.created_at) : NaN;
44
+ const at = Number.isFinite(atMs) ? localIso(atMs) : undefined;
45
+ return [item.session === undefined ? undefined : `session ${item.session}`, `seq ${item.seq}`, item.role, ...(at === undefined ? [] : [at])].filter(Boolean).join(" | ");
29
46
  }
30
47
 
31
48
  function toolHeader(item: { role: string; tool?: string; tool_status?: string; output_truncated?: true; full_output_path?: string; nested_calls?: { call_count: number; complete: boolean } }): string | undefined {
32
49
  if (item.role !== "tool") return undefined;
33
- const parts = [`tool ${item.tool}`, `status ${item.tool_status}`];
50
+ const parts = [...(item.tool ? [`tool ${item.tool}`] : []), `status ${item.tool_status}`];
34
51
  if (item.output_truncated) parts.push(`output truncated${item.full_output_path ? `, full text at ${item.full_output_path}` : ""}`);
35
52
  if (item.nested_calls) {
36
53
  parts.push(`nested calls ${item.nested_calls.call_count} recorded, ${item.nested_calls.complete ? "complete" : "incomplete"}`);
@@ -40,40 +57,50 @@ function toolHeader(item: { role: string; tool?: string; tool_status?: string; o
40
57
 
41
58
  function renderPageItem(item: HistoryPageItem): string {
42
59
  const tool = toolHeader(item);
43
- const lines = [header(item) + (item.context ? " | search context" : ""), ...(tool ? [tool] : [])];
44
- if (item.truncated) lines.push(`[truncated; from offset ${item.offset_chars ?? 0}]`);
45
- lines.push(item.content);
60
+ const offset = (item.offset_chars ?? 0) > 0 ? ` | offset_chars ${item.offset_chars}` : "";
61
+ // The session banner already names the session above its rows; per-row identity stays local.
62
+ const lines = [header({ seq: item.seq, role: item.role, created_at: item.created_at }) + offset + (item.context ? " | search context" : ""), ...(tool ? [tool] : [])];
63
+ lines.push(item.truncated ? (item.content ? `${item.content} [truncated]` : "[truncated]") : item.content);
46
64
  return lines.join("\n");
47
65
  }
48
66
 
49
- function renderFoldedRow(row: HistoryFoldedRow): string {
67
+ function renderFoldedRow(row: HistoryFoldedRow, session?: string): string {
50
68
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
51
- const identity = row.session === undefined ? {} : { session: row.session };
52
- const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] })}`;
53
- return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
69
+ const expand = JSON.stringify({ session, after: row.first_seq - 1, before: row.last_seq + 1, roles: ["tool", "context"] });
70
+ return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}\n\t→ expand: ${expand}`;
54
71
  }
55
72
 
56
- function renderPage(page: HistoryPage): string {
57
- // An empty selection has no anchors either, so it would otherwise render as nothing at all.
58
- if (page.items.length === 0 && !page.folded_after) return `${page.notice ?? ""}No events match these filters.`;
59
- 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");
60
- if (isMultiPage(page)) {
61
- const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
62
- return (page.notice ?? "") + body + (directions ? `\n\n→ more ${directions} results: narrow with time bounds (after/before), query, roles or the session pattern` : "");
63
- }
64
- const hits = page.items.filter(item => !item.context);
65
- const first = hits[0]!;
66
- const last = hits.at(-1)!;
73
+ const sessionBanner = (session?: string) => session === undefined ? "" : `=== session ${session} ===\n`;
74
+ const EMPTY_PAGE = "No events match these filters.";
75
+
76
+ type TimelinePage = HistoryPage & { paging: Omit<Static<typeof historyListParameters>, "after" | "before"> };
77
+
78
+ function renderTimelinePage(page: TimelinePage): string {
79
+ const { session } = page.paging;
80
+ 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");
67
81
  const cursors = [
68
- page.has_older ? `→ older: ${JSON.stringify({ session: first.session, before: first.seq })}` : "",
69
- page.has_newer ? `→ newer: ${JSON.stringify({ session: last.session, after: last.seq })}` : "",
70
- ].filter((line) => line !== "");
71
- return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
82
+ page.has_older ? `→ older: ${JSON.stringify({ ...page.paging, before: page.items[0]!.seq })}` : "",
83
+ page.has_newer ? `→ newer: ${JSON.stringify({ ...page.paging, after: page.items.at(-1)!.seq })}` : "",
84
+ ].filter(Boolean);
85
+ return (page.notice ?? "") + sessionBanner(session) + (body || EMPTY_PAGE) + (cursors.length ? `\n\n${cursors.join(" | ")}` : "");
86
+ }
87
+
88
+ type SearchPage = HistoryPage & { session?: string };
89
+
90
+ function renderCollectionPage(page: SearchPage, narrow: string): string {
91
+ const sessions = new Map(page.items.filter(item => !item.context).map(item => [item.session, [] as HistoryPageItem[]]));
92
+ for (const item of page.items) sessions.get(item.session)!.push(item);
93
+ const body = [...sessions].map(([session, items]) => sessionBanner(session) + items.sort((a, b) => a.seq - b.seq).map(renderPageItem).join("\n\n")).join("\n\n");
94
+ const directions = [page.has_older && "older", page.has_newer && "newer"].filter(Boolean).join("|");
95
+ return (page.notice ?? "") + (body || sessionBanner(page.session) + EMPTY_PAGE) + (directions ? `\n\n→ more ${directions} results: ${narrow}` : "");
72
96
  }
73
97
 
98
+ const renderOverviewPage = (page: SearchPage) => renderCollectionPage(page, "narrow with since/until, roles or the session pattern");
99
+ const renderSearchPage = (page: SearchPage) => renderCollectionPage(page, "narrow with since/until, query, roles or the session pattern");
100
+
74
101
  function renderRead(data: HistoryReadData): string {
75
102
  const tool = toolHeader(data);
76
- const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), after: Math.max(0, data.seq - 10), before: data.seq + 10 })})`;
103
+ const neighborhood = `→ history_list: ${JSON.stringify({ session: data.session, after: Math.max(0, data.seq - 10), before: data.seq + 10 })}`;
77
104
  return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
78
105
  }
79
106
 
@@ -84,136 +111,216 @@ export type HistoryTextWrapper = (text: string) => string;
84
111
  const plainText: HistoryTextWrapper = (text) => text;
85
112
 
86
113
  /** Translate query budget facts into this tool's bounded refusal; successful pages are unchanged. */
87
- function pageOutcome(result: HistoryPageResult): Outcome<HistoryPage> {
114
+ function pageOutcome(result: HistoryPageResult, narrow: string): Outcome<HistoryPage> {
88
115
  if (!("pageTooLarge" in result)) return result;
89
- const { count, multi } = result.pageTooLarge;
90
- 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";
91
- 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}.`);
116
+ return failure("page_too_large", `These events exceed the ${TOOL_OUTPUT_LIMIT} limit; ${narrow}, or use history_read for one event.`);
117
+ }
118
+
119
+ async function loadNamedSession(context: HistoryContext, selector: SessionSelector) {
120
+ if (!("corpus" in context)) return failure("unknown_session", "Other sessions are unavailable here.");
121
+ const target = await resolveSession(context.corpus, selector);
122
+ if (!target.ok) return target;
123
+ const loaded = await loadHistorySession(target.data);
124
+ return loaded.ok ? success({ ...loaded.data, session: sessionIdentity(target.data) }) : loaded;
125
+ }
126
+
127
+ async function loadTimeline(context: HistoryContext, session: string | undefined, tool: string): Promise<Outcome<{ projection: HistoryProjection; notice?: string; session?: string }>> {
128
+ if (session === undefined) return success({ projection: await currentHistory(context) });
129
+ const selector = parseSessionSelector(session);
130
+ if (!selector.ok) return selector;
131
+ if (selector.data.wildcard) return failure("invalid_session", `${tool} needs one session ID or prefix. Use history_list or history_search for wildcards.`);
132
+ return loadNamedSession(context, selector.data);
92
133
  }
93
134
 
94
135
  /* ------------------------------------------------------------------ history_list */
95
136
 
96
- const boundParameter = (description: string) => Type.Optional(Type.Union([Type.String(), Type.Number()], { description: `${description} Use a seq (number or digits) or ISO 8601 time (UTC without offset); wildcards take only times.` }));
137
+ const sessionParameter = (description: string) => Type.Optional(Type.String({ minLength: 1, description }));
138
+ const limitParameter = (description: string) => Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description }));
139
+ const previewParameter = Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "Maximum characters per preview." }));
140
+ const seqBound = (description: string) => Type.Optional(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description }));
141
+ const timeBound = (description: string) => Type.Optional(Type.String({ description: `${description} ISO 8601 (local time if no offset).` }));
142
+
143
+ function parseTimeBounds(params: { since?: string; until?: string }): Outcome<{ since?: number; until?: number }> {
144
+ const since = params.since === undefined ? undefined : parseIsoTimestamp(params.since);
145
+ const until = params.until === undefined ? undefined : parseIsoTimestamp(params.until);
146
+ if (params.since !== undefined && since === undefined) return failure("invalid_bounds", `since must be an ISO 8601 time; got ${JSON.stringify(params.since)}.`);
147
+ if (params.until !== undefined && until === undefined) return failure("invalid_bounds", `until must be an ISO 8601 time; got ${JSON.stringify(params.until)}.`);
148
+ return success({ since, until });
149
+ }
150
+
97
151
  export const historyListParameters = Type.Object({
98
- session: Type.Optional(Type.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." })),
99
- roles: historyRoles(),
100
- query: Type.Optional(searchQuery("Text to look for, or a list (any match). Searches what was said, tool arguments and output.")),
101
- after: boundParameter("Start strictly after this bound, paging forward; 0 starts at the oldest event."),
102
- before: boundParameter("Stop strictly before this bound; without `after`, take the newest eligible events."),
103
- context: Type.Optional(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events on each side of a hit in its own session; requires a query." })),
104
- limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "How many events or hits per page; folds and search context don't count." })),
105
- max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: "How much of each entry to show." })),
152
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`) for one event per session. Omit for current session."),
153
+ roles: historyRoles(true),
154
+ after: seqBound("Exclusive seq; page forward (0 starts at the beginning)."),
155
+ before: seqBound("Exclusive seq; without `after`, takes newest events."),
156
+ since: timeBound("Exclusive start time; oldest first."),
157
+ until: timeBound("Exclusive end time; without `since`, newest first."),
158
+ limit: limitParameter("Events or sessions per page."),
159
+ max_chars_per_item: previewParameter,
106
160
  }, { additionalProperties: false });
107
161
 
108
- const ISO_8601 = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
109
- function parseBound(name: "after" | "before", value?: number | string): Outcome<HistoryBound | undefined> {
110
- if (value === undefined) return success(undefined);
111
- if (typeof value === "number" || /^\d+$/.test(value)) {
112
- const seq = Number(value);
113
- if (Number.isSafeInteger(seq) && seq >= 0) return success({ seq });
114
- } else if (typeof value === "string") {
115
- const match = ISO_8601.exec(value);
116
- const at = match ? Date.parse(match[1] ? value : `${value}Z`) : NaN;
117
- if (!Number.isNaN(at) && new Date(value.slice(0, 10)).toISOString().startsWith(value.slice(0, 10))) return success({ at });
118
- }
119
- return failure("invalid_bounds", `\`${name}\` must be a non-negative integer seq or an ISO 8601 time; got ${JSON.stringify(value)}.`);
120
- }
162
+ export const historyList: Operation<typeof historyListParameters, TimelinePage | SearchPage, [HistoryContext, HistoryTextWrapper?]> = {
163
+ name: "history_list",
164
+ label: "Browse history",
165
+ description: "Browse one session's timeline (oldest to newest), or pass a wildcard `session` to overview matching sessions.",
166
+ parameters: historyListParameters,
167
+ async execute(params, context, wrapText = plainText) {
168
+ const { after, before, roles, limit, max_chars_per_item } = params;
169
+ const bounds = parseTimeBounds(params);
170
+ if (!bounds.ok) return bounds;
171
+ const { since, until } = bounds.data;
172
+ const selector = params.session === undefined ? undefined : parseSessionSelector(params.session);
173
+ if (selector && !selector.ok) return selector;
174
+ if (selector?.ok && selector.data.wildcard) {
175
+ if (after !== undefined || before !== undefined) {
176
+ return failure("invalid_bounds", "after and before are seq numbers for a single session; use since and until with wildcard sessions.");
177
+ }
178
+ const wild = selector.data;
179
+ if (!("corpus" in context)) return failure("unknown_session", "Other sessions are unavailable here.");
180
+ const scoped: HistorySelection = {
181
+ after: since === undefined ? undefined : { at: since },
182
+ before: until === undefined ? undefined : { at: until },
183
+ roles,
184
+ limit,
185
+ };
186
+ const sessions = (await context.corpus.sessions(wild.harness)).filter((s) => matchesSession(s, wild));
187
+ sessions.sort((a, b) => (since !== undefined ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
188
+ const targetCount = Math.min(500, Math.max(1, limit ?? 20));
189
+ const collector = new CorpusCollector(scoped);
190
+ const notices: string[] = [];
191
+ let qualifying = 0, offset = 0;
192
+ while (offset < sessions.length && qualifying < targetCount) {
193
+ const batchSize = Math.min(WILDCARD_CONCURRENCY, targetCount - qualifying, sessions.length - offset);
194
+ const batch = sessions.slice(offset, offset + batchSize);
195
+ const loadedBatch = await Promise.all(batch.map((s) => loadOverviewSession(s, scoped)));
196
+ for (let i = 0; i < batch.length; i++) {
197
+ const s = batch[i]!;
198
+ const item = loadedBatch[i];
199
+ if (!item) continue;
200
+ const added = collector.addRepresentative(sessionIdentity(s), item.projection ?? item.event);
201
+ if (!added) continue;
202
+ qualifying++;
203
+ if (item.notice) notices.push(`session ${sessionIdentity(s)}: ${item.notice}`);
204
+ }
205
+ offset += batch.length;
206
+ }
207
+ const unvisited = offset < sessions.length;
208
+ const decorateOverview = (page: HistoryPage): SearchPage => ({ ...page, ...(notices.length ? { notice: notices.join("") } : {}) });
209
+ 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");
210
+ return overview.ok ? success(decorateOverview(overview.data)) : overview;
211
+ }
212
+ const loaded = await loadTimeline(context, params.session, "history_list");
213
+ if (!loaded.ok) return loaded;
214
+ const { projection, session, notice } = loaded.data;
215
+ const paging = { session, roles, since: params.since, until: params.until, limit, max_chars_per_item };
216
+ const decorate = (page: HistoryPage): TimelinePage => ({ ...page, paging, ...(notice === undefined ? {} : { notice }) });
217
+ const result = pageOutcome(selectPage(projection, {
218
+ roles, limit,
219
+ after: after === undefined ? undefined : { seq: after },
220
+ before: before === undefined ? undefined : { seq: before },
221
+ since, until,
222
+ }, page => fitsText(wrapText(renderTimelinePage(decorate(page)))), max_chars_per_item ?? HISTORY_PREVIEW_CHARS), "narrow with after/before, since/until or specify roles");
223
+ return result.ok ? success(decorate(result.data)) : result;
224
+ },
225
+ render: (result) => renderOutcome(result, (page) => "paging" in page ? renderTimelinePage(page) : renderOverviewPage(page)),
226
+ };
227
+
228
+ /* ------------------------------------------------------------------ history_search */
229
+
230
+ export const historySearchParameters = Type.Object({
231
+ session: sessionParameter("Session ID, prefix, or wildcard (e.g. `*`, `pi:*`). Omit for current session."),
232
+ query: searchQuery("Case-insensitive literal text, or a list (any match)."),
233
+ since: timeBound("Exclusive start time; oldest matches first."),
234
+ until: timeBound("Exclusive end time; without `since`, newest matches first."),
235
+ roles: historyRoles(),
236
+ context: Type.Optional(Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER, description: "Neighboring events shown on each side of a hit." })),
237
+ limit: limitParameter("Hits per page."),
238
+ max_chars_per_item: previewParameter,
239
+ }, { additionalProperties: false });
121
240
 
122
- function parseSelection(params: Static<typeof historyListParameters>): Outcome<HistorySelection> {
123
- const after = parseBound("after", params.after);
124
- if (!after.ok) return after;
125
- const before = parseBound("before", params.before);
126
- if (!before.ok) return before;
241
+ function searchSelection(params: Static<typeof historySearchParameters>): Outcome<HistorySelection> {
242
+ const bounds = parseTimeBounds(params);
243
+ if (!bounds.ok) return bounds;
244
+ const { since, until } = bounds.data;
127
245
  try {
128
246
  const query = searchQueries(params.query);
129
- if (!query.length && params.context !== undefined) return failure("invalid_params", "`context` requires a non-empty `query`.");
130
- return success({ after: after.data, before: before.data, query: query.length ? query : undefined, roles: params.roles, context: params.context, limit: params.limit });
247
+ return success({ after: since === undefined ? undefined : { at: since }, before: until === undefined ? undefined : { at: until }, query, roles: params.roles, context: params.context, limit: params.limit });
131
248
  } catch (error) {
132
249
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
133
250
  throw error;
134
251
  }
135
252
  }
136
253
 
137
- export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
138
- name: "history_list",
139
- label: "History list items",
140
- 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.",
141
- parameters: historyListParameters,
142
- outputSchema: resultSchema(HistoryPageSchema),
254
+ export const historySearch: Operation<typeof historySearchParameters, SearchPage, [HistoryContext, HistoryTextWrapper?]> = {
255
+ name: "history_search",
256
+ label: "Search history",
257
+ description: "Search passages by literal text in one or more sessions, including tool arguments and output.",
258
+ parameters: historySearchParameters,
143
259
  async execute(params, context, wrapText = plainText) {
144
- const selection = parseSelection(params);
260
+ const selection = searchSelection(params);
145
261
  if (!selection.ok) return selection;
146
262
  const scoped = selection.data;
147
- // Charge wrapped rendering, identities, notices and recipes, not only event previews.
148
- const fits = (page: HistoryPage) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
149
- const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
150
- if (params.session === undefined) return pageOutcome(selectPage(await currentHistory(context), scoped, fits, maxChars));
151
- const selector = parseSessionSelector(params.session);
152
- if (!selector.ok) return selector;
153
- const corpus = "corpus" in context ? context.corpus : undefined;
154
- if (selector.data.wildcard) {
155
- const { after, before, query, roles } = scoped;
156
- if ((after && "seq" in after) || (before && "seq" in before)) return failure("invalid_bounds", "Wildcard history requires times, not seqs, for `after` and `before`.");
157
- if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
158
- const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
159
- if (!query) sessions.sort((a, b) => (after ? a.modifiedAt - b.modifiedAt : b.modifiedAt - a.modifiedAt) || sessionIdentity(a).localeCompare(sessionIdentity(b)));
160
- const representative = !query && !roles && !after && !before;
161
- const collector = new CorpusCollector(scoped);
162
- let qualifying = 0;
163
- const notices: string[] = [];
164
- let unvisited = false;
165
- for (const [index, session] of sessions.entries()) {
166
- const result = representative ? await loadHistoryRepresentative(session) : await loadHistorySession(session, query);
167
- if (!result.ok || !result.data) continue;
168
- const added = "projection" in result.data ? collector.add(sessionIdentity(session), result.data.projection) : collector.addRepresentative(sessionIdentity(session), result.data.event);
169
- if (!added) continue;
170
- qualifying++;
171
- if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
172
- if (!query && qualifying >= Math.min(500, Math.max(1, params.limit ?? 20))) {
173
- unvisited = index + 1 < sessions.length;
174
- break;
263
+ const { after, before, query } = scoped;
264
+ const collector = new CorpusCollector(scoped);
265
+ const notices: string[] = [];
266
+ let session: string | undefined;
267
+ if (params.session === undefined) collector.addMatches("", await currentHistory(context));
268
+ else {
269
+ const selector = parseSessionSelector(params.session);
270
+ if (!selector.ok) return selector;
271
+ const corpus = "corpus" in context ? context.corpus : undefined;
272
+ if (!selector.data.wildcard) {
273
+ const loaded = await loadNamedSession(context, selector.data);
274
+ if (!loaded.ok) return loaded;
275
+ session = loaded.data.session;
276
+ collector.addMatches(session, loaded.data.projection);
277
+ if (loaded.data.notice) notices.push(loaded.data.notice);
278
+ } else {
279
+ if (!corpus) return failure("unknown_session", "Other sessions are unavailable here.");
280
+ if (query && query.length > 0) {
281
+ const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
282
+ const hasTimeBounds = after !== undefined || before !== undefined;
283
+ const noticesByIndex = new Array<string | undefined>(sessions.length);
284
+ let next = 0;
285
+ const workers = Math.min(WILDCARD_CONCURRENCY, sessions.length);
286
+ await Promise.all(Array.from({ length: workers }, async () => {
287
+ while (next < sessions.length) {
288
+ const index = next++;
289
+ const session = sessions[index]!;
290
+ if (hasTimeBounds && session.peekSummary) {
291
+ const summary = await session.peekSummary();
292
+ if (summary && resolveSummaryForSelection(summary, scoped).kind === "empty") continue;
293
+ }
294
+ const result = await loadHistorySession(session, query);
295
+ if (!result.ok || !result.data) continue;
296
+ collector.addMatches(sessionIdentity(session), result.data.projection);
297
+ if (result.data.notice) noticesByIndex[index] = `session ${sessionIdentity(session)}: ${result.data.notice}`;
298
+ }
299
+ }));
300
+ for (const entry of noticesByIndex) if (entry) notices.push(entry);
175
301
  }
176
302
  }
177
- const notice = notices.length ? { notice: notices.join("") } : {};
178
- const result = pageOutcome(collector.page((page) => fits(markMultiPage({ ...page, ...notice })), maxChars, unvisited));
179
- return result.ok ? success(markMultiPage({ ...result.data, ...notice })) : result;
180
303
  }
181
- const target = await resolveSession(corpus, selector.data);
182
- if (!target.ok) return target;
183
- const loaded = await loadHistorySession(target.data);
184
- if (!loaded.ok) return loaded;
185
- const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
186
- const result = pageOutcome(selectPage(loaded.data.projection, { ...scoped, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars));
187
- return result.ok ? success({ ...result.data, ...notice }) : result;
304
+ const decorate = (page: HistoryPage): SearchPage => ({ ...page, ...(session === undefined ? {} : { session }), ...(notices.length ? { notice: notices.join("") } : {}) });
305
+ 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");
306
+ return result.ok ? success(decorate(result.data)) : result;
188
307
  },
189
- render: (result) => renderOutcome(result, renderPage),
308
+ render: (result) => renderOutcome(result, renderSearchPage),
190
309
  };
191
310
 
192
311
  /* ------------------------------------------------------------------ history_read */
193
312
 
194
- export const historyReadParameters = Type.Object({ session: Type.Optional(Type.String({ minLength: 1, description: "Whose record: a session ID or prefix. Leave it out for this one." })), seq: Type.Integer({ minimum: 1, description: "Which entry, by its seq from `history_list`; bring its session along if it had one." }), ...TextWindowRequestSchema }, { additionalProperties: false });
313
+ export const historyReadParameters = Type.Object({ session: sessionParameter("Session ID or prefix. Omit for current session."), seq: Type.Integer({ minimum: 1, description: "Event seq to read." }), ...TextWindowRequestSchema }, { additionalProperties: false });
195
314
 
196
315
  export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryContext, HistoryTextWrapper?]> = {
197
316
  name: "history_read",
198
- label: "History read item",
199
- description: "Open one entry: what was called, what came back, the calls nested inside. Long entries come in slices; follow `next_offset_chars`.",
317
+ label: "Read history event",
318
+ description: "Read one history event, including tool arguments, output, and nested calls.",
200
319
  parameters: historyReadParameters,
201
- outputSchema: resultSchema(HistoryReadDataSchema),
202
320
  async execute(params, context, wrapText = plainText) {
203
- let projection;
204
- let identity: { session?: string; notice?: string } = {};
205
- if (params.session === undefined) projection = await currentHistory(context);
206
- else {
207
- const selector = parseSessionSelector(params.session);
208
- if (!selector.ok) return selector;
209
- if (selector.data.wildcard) return failure("invalid_session", "`history_read` reads one session; pass a specific `session` ID, not a wildcard.");
210
- const target = await resolveSession("corpus" in context ? context.corpus : undefined, selector.data);
211
- if (!target.ok) return target;
212
- const loaded = await loadHistorySession(target.data);
213
- if (!loaded.ok) return loaded;
214
- projection = loaded.data.projection;
215
- identity = { session: sessionIdentity(target.data), ...(loaded.data.notice === undefined ? {} : { notice: loaded.data.notice }) };
216
- }
321
+ const loaded = await loadTimeline(context, params.session, "history_read");
322
+ if (!loaded.ok) return loaded;
323
+ const { projection, ...identity } = loaded.data;
217
324
  // Address checks run in one order: past the end of the file, off this branch, then
218
325
  // resolved through any tool-result pairing to its call event.
219
326
  if (params.seq > projection.highestSeq) {
@@ -236,7 +343,7 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
236
343
  return readTextWindow(
237
344
  document,
238
345
  params.offset_chars,
239
- params.max_chars,
346
+ params.max_chars ?? HISTORY_READ_WINDOW_CHARS,
240
347
  (window) => ({
241
348
  ...identity,
242
349
  seq: item.seq,