notesoup 0.61.0 → 0.63.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 (210) 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 +24 -5
  10. package/dist/plugins/claude/src/text.d.ts +7 -0
  11. package/dist/plugins/claude/src/text.js +12 -1
  12. package/dist/plugins/codex/src/hooks.js +1 -0
  13. package/dist/plugins/codex/src/identity.d.ts +6 -1
  14. package/dist/plugins/codex/src/identity.js +13 -1
  15. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  16. package/dist/plugins/codex/src/mcp.js +26 -88
  17. package/dist/plugins/codex/src/text.js +3 -3
  18. package/dist/plugins/dsh/tools.js +8 -4
  19. package/dist/plugins/mcp/operations.d.ts +15 -0
  20. package/dist/plugins/mcp/operations.js +43 -0
  21. package/dist/plugins/mcp/server.d.ts +14 -0
  22. package/dist/plugins/mcp/server.js +13 -0
  23. package/dist/plugins/pi/budget.d.ts +4 -1
  24. package/dist/plugins/pi/budget.js +35 -8
  25. package/dist/plugins/pi/entries.d.ts +2 -0
  26. package/dist/plugins/pi/entries.js +2 -0
  27. package/dist/plugins/pi/history-tools.js +2 -1
  28. package/dist/plugins/pi/history.js +18 -1
  29. package/dist/plugins/pi/notes/tools.js +7 -3
  30. package/dist/plugins/pi/render.d.ts +7 -1
  31. package/dist/plugins/pi/render.js +2 -2
  32. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  33. package/dist/plugins/pi/reset/artifacts.js +4 -4
  34. package/dist/plugins/pi/reset/lifecycle.d.ts +9 -2
  35. package/dist/plugins/pi/reset/lifecycle.js +109 -31
  36. package/dist/plugins/pi/runtime.js +104 -63
  37. package/dist/plugins/pi/tool-result.js +7 -7
  38. package/dist/plugins/pi/window.d.ts +25 -3
  39. package/dist/plugins/pi/window.js +219 -9
  40. package/dist/src/boot/render.js +18 -15
  41. package/dist/src/boot/text.d.ts +3 -1
  42. package/dist/src/boot/text.js +22 -20
  43. package/dist/src/budget/text.d.ts +7 -3
  44. package/dist/src/budget/text.js +24 -15
  45. package/dist/src/history/claude.d.ts +2 -0
  46. package/dist/src/history/claude.js +46 -0
  47. package/dist/src/history/codex-transcript.js +7 -5
  48. package/dist/src/history/codex.js +3 -0
  49. package/dist/src/history/corpus.d.ts +28 -1
  50. package/dist/src/history/corpus.js +40 -0
  51. package/dist/src/history/history.d.ts +37 -46
  52. package/dist/src/history/history.js +21 -40
  53. package/dist/src/history/local.js +67 -32
  54. package/dist/src/history/pi.d.ts +2 -1
  55. package/dist/src/history/pi.js +122 -48
  56. package/dist/src/history/prefilter.js +76 -19
  57. package/dist/src/history/query.d.ts +28 -49
  58. package/dist/src/history/query.js +83 -68
  59. package/dist/src/history/summary-cache.d.ts +8 -1
  60. package/dist/src/history/summary-cache.js +138 -12
  61. package/dist/src/index.d.ts +2 -2
  62. package/dist/src/index.js +1 -1
  63. package/dist/src/notes/errors.d.ts +1 -1
  64. package/dist/src/notes/frontmatter.d.ts +0 -2
  65. package/dist/src/notes/frontmatter.js +0 -2
  66. package/dist/src/notes/index.d.ts +1 -1
  67. package/dist/src/notes/index.js +1 -1
  68. package/dist/src/notes/policy.d.ts +15 -1
  69. package/dist/src/notes/policy.js +46 -5
  70. package/dist/src/notes/store.d.ts +12 -0
  71. package/dist/src/notes/store.js +16 -20
  72. package/dist/src/text-match.d.ts +10 -1
  73. package/dist/src/text-match.js +42 -3
  74. package/dist/src/tools/dream.d.ts +22 -93
  75. package/dist/src/tools/dream.js +30 -27
  76. package/dist/src/tools/history.d.ts +33 -26
  77. package/dist/src/tools/history.js +257 -163
  78. package/dist/src/tools/notes.d.ts +51 -163
  79. package/dist/src/tools/notes.js +146 -100
  80. package/dist/src/tools/output.d.ts +2 -1
  81. package/dist/src/tools/output.js +2 -1
  82. package/dist/src/tools/result.d.ts +4 -7
  83. package/dist/src/tools/result.js +8 -9
  84. package/dist/src/tools/schema.d.ts +4 -1
  85. package/dist/src/tools/schema.js +25 -1
  86. package/dist/test/agent-loop.test.js +394 -56
  87. package/dist/test/antigravity-live.test.d.ts +1 -0
  88. package/dist/test/antigravity-live.test.js +142 -0
  89. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  90. package/dist/test/antigravity-plugin.test.js +101 -0
  91. package/dist/test/boot.integration.test.js +156 -15
  92. package/dist/test/budget-settings.integration.test.js +4 -4
  93. package/dist/test/claude-history.test.js +14 -13
  94. package/dist/test/claude-mod.test.js +199 -16
  95. package/dist/test/claude-validation.test.js +69 -2
  96. package/dist/test/codex-history.test.js +15 -3
  97. package/dist/test/codex-plugin.test.js +76 -38
  98. package/dist/test/dependencies.test.js +7 -3
  99. package/dist/test/dream-skill.test.js +3 -3
  100. package/dist/test/dream-tools.test.js +101 -56
  101. package/dist/test/dsh.test.js +34 -19
  102. package/dist/test/helpers/dependency-graph.js +2 -2
  103. package/dist/test/helpers/extension.d.ts +68 -3
  104. package/dist/test/helpers/extension.js +74 -5
  105. package/dist/test/history-corpus.test.js +79 -77
  106. package/dist/test/history-summary-cache.test.js +97 -9
  107. package/dist/test/history.integration.test.js +234 -168
  108. package/dist/test/host-neutral.test.js +69 -19
  109. package/dist/test/marker.test.js +1 -1
  110. package/dist/test/model-facing-text.test.js +13 -3
  111. package/dist/test/note-policy.test.js +96 -77
  112. package/dist/test/notes.integration.test.js +212 -94
  113. package/dist/test/notes.test.js +184 -113
  114. package/dist/test/pi-render.test.js +20 -12
  115. package/dist/test/project-namespace.test.js +3 -2
  116. package/dist/test/reset-lifecycle.test.js +12 -2
  117. package/docs/antigravity.md +44 -0
  118. package/docs/architecture.md +6 -4
  119. package/docs/claude-code-mod.md +7 -7
  120. package/docs/codex.md +36 -38
  121. package/docs/dsh.md +3 -3
  122. package/docs/history-sessions.md +28 -50
  123. package/docs/notes-library.md +4 -4
  124. package/docs/reset-lifecycle.md +1 -1
  125. package/docs/skills.md +3 -3
  126. package/docs/tool-results.md +47 -28
  127. package/package.json +3 -2
  128. package/playbook.md +1 -1
  129. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  130. package/plugins/antigravity/hooks.json +7 -0
  131. package/plugins/antigravity/mcp_config.json +8 -0
  132. package/plugins/antigravity/plugin.json +6 -0
  133. package/plugins/antigravity/src/cli.ts +22 -0
  134. package/plugins/antigravity/src/hooks.ts +51 -0
  135. package/plugins/antigravity/src/identity.ts +127 -0
  136. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  137. package/plugins/claude/dist/claude/helper.js +1108 -539
  138. package/plugins/claude/hooks/register.ts +202 -62
  139. package/plugins/claude/playbook.md +1 -1
  140. package/plugins/claude/skills/dream/SKILL.md +1 -1
  141. package/plugins/claude/skills/notesoup-guide/SKILL.md +92 -0
  142. package/plugins/claude/src/helper.ts +24 -5
  143. package/plugins/claude/src/text.ts +14 -1
  144. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  145. package/plugins/codex/.mcp.json +11 -0
  146. package/plugins/codex/README.md +5 -21
  147. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  148. package/plugins/codex/src/hooks.ts +1 -0
  149. package/plugins/codex/src/identity.ts +14 -1
  150. package/plugins/codex/src/mcp.ts +28 -98
  151. package/plugins/codex/src/text.ts +3 -3
  152. package/plugins/dsh/tools.ts +8 -4
  153. package/plugins/mcp/operations.ts +50 -0
  154. package/plugins/mcp/server.ts +23 -0
  155. package/plugins/paseo/README.md +5 -10
  156. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  157. package/plugins/paseo/client/markdown.tsx +50 -38
  158. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  159. package/plugins/paseo/client/paper-card.tsx +6 -5
  160. package/plugins/paseo/client/paper-palette.ts +2 -9
  161. package/plugins/paseo/client/sticky-card.tsx +2 -2
  162. package/plugins/paseo/client/tool-result.ts +7 -14
  163. package/plugins/paseo/package-lock.json +3406 -0
  164. package/plugins/paseo/package.json +1 -0
  165. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  166. package/plugins/pi/budget.ts +31 -8
  167. package/plugins/pi/entries.ts +2 -0
  168. package/plugins/pi/history-tools.ts +2 -1
  169. package/plugins/pi/history.ts +30 -1
  170. package/plugins/pi/notes/tools.ts +7 -3
  171. package/plugins/pi/render.ts +6 -6
  172. package/plugins/pi/reset/artifacts.ts +4 -3
  173. package/plugins/pi/reset/lifecycle.ts +125 -32
  174. package/plugins/pi/runtime.ts +98 -62
  175. package/plugins/pi/tool-result.ts +8 -8
  176. package/plugins/pi/window.ts +210 -10
  177. package/skills/dream/SKILL.md +1 -1
  178. package/skills/notesoup-guide/SKILL.md +92 -0
  179. package/src/boot/render.ts +18 -15
  180. package/src/boot/text.ts +23 -19
  181. package/src/budget/text.ts +27 -15
  182. package/src/history/claude.ts +41 -0
  183. package/src/history/codex-transcript.ts +6 -4
  184. package/src/history/codex.ts +2 -0
  185. package/src/history/corpus.ts +51 -2
  186. package/src/history/history.ts +35 -44
  187. package/src/history/local.ts +67 -27
  188. package/src/history/pi.ts +113 -35
  189. package/src/history/prefilter.ts +73 -15
  190. package/src/history/query.ts +93 -73
  191. package/src/history/summary-cache.ts +142 -17
  192. package/src/index.ts +2 -2
  193. package/src/notes/errors.ts +1 -1
  194. package/src/notes/frontmatter.ts +0 -3
  195. package/src/notes/index.ts +1 -1
  196. package/src/notes/policy.ts +44 -5
  197. package/src/notes/store.ts +17 -20
  198. package/src/text-match.ts +46 -4
  199. package/src/tools/dream.ts +29 -31
  200. package/src/tools/history.ts +249 -142
  201. package/src/tools/notes.ts +145 -113
  202. package/src/tools/output.ts +2 -1
  203. package/src/tools/result.ts +12 -11
  204. package/src/tools/schema.ts +24 -1
  205. package/plugins/claude/skills/memory/SKILL.md +0 -69
  206. package/plugins/codex/mcp.json +0 -10
  207. package/plugins/codex/plugin.json +0 -6
  208. package/plugins/paseo/client/markdown-core.tsx +0 -189
  209. package/plugins/paseo/client/typography.ts +0 -24
  210. package/skills/memory/SKILL.md +0 -69
@@ -2,13 +2,14 @@
2
2
  import { join } from "node:path";
3
3
  import { Type, type Static } from "typebox";
4
4
  import { localIso } from "../notes/frontmatter.js";
5
- import { createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
6
- import { projectNamespaces } from "../notes/project-namespace.js";
5
+ import { compareNoteRows, createNotesStore, noteIdentity, type NoteRow, type NotesIdentity } from "../notes/index.js";
6
+ import { projectReceipt, type ProjectReceipt } from "../notes/project-namespace.js";
7
7
  import { gitCommit } from "../dream/git.js";
8
8
  import { trySqliteLock } from "../sqlite-lock.js";
9
9
  import { failure, success, type Outcome } from "../result.js";
10
- import { renderOutcome, resultSchema } from "./result.js";
11
- import { failureOf, listedFile, ListedFileSchema, NoteIdentitySchema, renderListData, snapshot, SnapshotSchema } from "./notes.js";
10
+ import { renderOutcome } from "./result.js";
11
+ import { failureOf, listedFile, renderListData, snapshot, type ListedFile, type Snapshot } from "./notes.js";
12
+ import { notesIdentityForCall, type NotesToolContext } from "./notes-context.js";
12
13
 
13
14
  /** The one open dream per session; the host owns where it lives. */
14
15
  type DreamOpening = { project: string; release: () => void; generation: number };
@@ -54,33 +55,30 @@ export function dreamingIdentity(identity: NotesIdentity, state: DreamState): No
54
55
  const NOT_DREAMING = "No dream is open; call dream_begin first.";
55
56
 
56
57
  export const dreamBeginParameters = Type.Object({
57
- project: Type.Optional(Type.String({ description: "Which project's pages; leave it out for this one." })),
58
+ cwd: Type.Optional(Type.String({ minLength: 1, description: "Treat this directory's project as current." })),
58
59
  }, { additionalProperties: false });
59
60
 
60
- export const DreamBeginDataSchema = Type.Object({
61
- project: Type.String(), baseline: Type.String(),
62
- files: Type.Array(Type.Object({ ...ListedFileSchema.properties, last_accessed: Type.String() }, { additionalProperties: false })),
63
- ...SnapshotSchema,
64
- }, { additionalProperties: false });
65
- export type DreamBeginData = Static<typeof DreamBeginDataSchema>;
61
+ export type DreamBeginData = Snapshot<ListedFile & { last_accessed: string }> & { project: string; baseline: string } & ProjectReceipt;
66
62
 
67
63
  function renderBeginData(data: DreamBeginData): string {
68
- return `dreaming over ${data.project} (baseline ${data.baseline})\n${renderListData(data)}`;
64
+ const header = `dreaming over ${data.project} (baseline ${data.baseline}${data.project_root === undefined ? "" : `, project_root ${data.project_root}`})`;
65
+ const siblings = data.project_siblings === undefined ? "" : `\n Same-basename projects: ${data.project_siblings.map(sibling => `${sibling.name} (${sibling.path})`).join(", ")}`;
66
+ return `${header}${siblings}\n${renderListData(data, undefined, { omitNamedProjectContext: true })}`;
69
67
  }
70
68
 
71
69
  export const dreamBegin = {
72
70
  name: "dream_begin", label: "Dream begin",
73
- description: "Spread one project's pages across the table — its project shelf, every session page born there, crumpled balls included. Until `dream_end` your pen works on all of them; other sessions' pages can be rewritten, not added to.",
74
- parameters: dreamBeginParameters, outputSchema: resultSchema(DreamBeginDataSchema),
75
- async execute(params: Static<typeof dreamBeginParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamBeginData>> {
71
+ description: "Open a project's notes and its session notes for consolidation after committing a Git baseline; unlocks writes until `dream_end`.",
72
+ parameters: dreamBeginParameters,
73
+ async execute(params: Static<typeof dreamBeginParameters>, context: NotesToolContext, state: DreamState): Promise<Outcome<DreamBeginData>> {
76
74
  if (state.project !== undefined || state.pending !== undefined) {
77
75
  const project = state.project ?? state.pending?.project;
78
76
  return failure("already_dreaming", `Already dreaming over ${project}; call dream_end before opening another project.`);
79
77
  }
80
- const project = params.project ?? identity.projectKey;
81
- if (project !== identity.projectKey && !projectNamespaces(identity.home).some(namespace => namespace.name === project)) {
82
- return failure("not_found", `No project named ${JSON.stringify(project)}; notes_list with glob @projects/*/** shows the names.`);
83
- }
78
+ let identity: NotesIdentity;
79
+ try { identity = notesIdentityForCall(context, params.cwd); } catch (error) { return failureOf(error); }
80
+ const project = identity.projectKey;
81
+ const receipt = projectReceipt(identity.home, project);
84
82
  const release = trySqliteLock(join(identity.home, ".dream.lock.sqlite"), 0);
85
83
  if (!release) return failure("already_dreaming", "Another dream is open in this notes home.");
86
84
  // Publish ownership before the first await so shutdown can release this transaction.
@@ -98,8 +96,10 @@ export const dreamBegin = {
98
96
  unavailable.push(...result.status.namespacesUnavailable);
99
97
  }
100
98
  }
101
- rows.sort((a, b) => b.meta.updatedAt - a.meta.updatedAt || a.address.localeCompare(b.address));
102
- const listed = snapshot(rows.map(row => ({ ...listedFile(row, identity), last_accessed: localIso(row.meta.lastAccessed) })), undefined, { namespacesUnavailable: unavailable }, renderListData);
99
+ rows.sort(compareNoteRows);
100
+ const listed = snapshot(rows.map(row => ({ ...listedFile(row, identity), last_accessed: localIso(row.meta.lastAccessed) })), undefined, { namespacesUnavailable: unavailable },
101
+ // Reserve the header before committing; Git object IDs are at most 64 hex digits.
102
+ (data) => renderBeginData({ ...data, project, baseline: "0".repeat(64), ...receipt }));
103
103
  if (!listed.ok) {
104
104
  releaseOpening(state, opening);
105
105
  return listed;
@@ -114,7 +114,7 @@ export const dreamBegin = {
114
114
  state.project = opening.project;
115
115
  state.release = opening.release;
116
116
  delete state.pending;
117
- return success({ project, baseline: baseline.commit, ...listed.data });
117
+ return success({ project, baseline: baseline.commit, ...receipt, ...listed.data });
118
118
  } catch (error) {
119
119
  if (!currentOpening(state, opening)) return cancelledOpening(state, opening);
120
120
  releaseOpening(state, opening);
@@ -124,14 +124,13 @@ export const dreamBegin = {
124
124
  render: (result: Outcome<DreamBeginData>): string => renderOutcome(result, renderBeginData),
125
125
  } as const;
126
126
 
127
- export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Which crumpled page goes in the bin." }) }, { additionalProperties: false });
128
- export const DreamForgetDataSchema = Type.Object({ ...NoteIdentitySchema }, { additionalProperties: false });
129
- export type DreamForgetData = Static<typeof DreamForgetDataSchema>;
127
+ export const dreamForgetParameters = Type.Object({ address: Type.String({ description: "Address of the crumpled note to delete." }) }, { additionalProperties: false });
128
+ export type DreamForgetData = ReturnType<typeof noteIdentity>;
130
129
 
131
130
  export const dreamForget = {
132
131
  name: "dream_forget", label: "Dream forget",
133
- description: "Throw a crumpled page in the bin for good. Only crumpled pages go.",
134
- parameters: dreamForgetParameters, outputSchema: resultSchema(DreamForgetDataSchema),
132
+ description: "Permanently delete a crumpled note in the open dream.",
133
+ parameters: dreamForgetParameters,
135
134
  async execute(params: Static<typeof dreamForgetParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamForgetData>> {
136
135
  if (state.project === undefined) return failure("not_dreaming", NOT_DREAMING);
137
136
  try {
@@ -144,13 +143,12 @@ export const dreamForget = {
144
143
  } as const;
145
144
 
146
145
  export const dreamEndParameters = Type.Object({}, { additionalProperties: false });
147
- export const DreamEndDataSchema = Type.Object({ project: Type.String(), commit: Type.Optional(Type.String()), audit_error: Type.Optional(Type.String()) }, { additionalProperties: false });
148
- export type DreamEndData = Static<typeof DreamEndDataSchema>;
146
+ export type DreamEndData = { project: string; commit?: string; audit_error?: string };
149
147
 
150
148
  export const dreamEnd = {
151
149
  name: "dream_end", label: "Dream end",
152
- description: "Stack the pages, file them, close the drawer.",
153
- parameters: dreamEndParameters, outputSchema: resultSchema(DreamEndDataSchema),
150
+ description: "Commit dream changes to the notes Git repo and close the open dream.",
151
+ parameters: dreamEndParameters,
154
152
  async execute(_params: Static<typeof dreamEndParameters>, identity: NotesIdentity, state: DreamState): Promise<Outcome<DreamEndData>> {
155
153
  const project = state.project;
156
154
  if (project === undefined) return failure("not_dreaming", NOT_DREAMING);
@@ -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,