notesoup 0.54.0 → 0.54.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +4 -2
  2. package/dist/plugins/claude/src/helper.d.ts +2 -1
  3. package/dist/plugins/claude/src/helper.js +19 -23
  4. package/dist/plugins/claude/src/history.d.ts +3 -14
  5. package/dist/plugins/claude/src/history.js +2 -298
  6. package/dist/plugins/claude/src/text.d.ts +0 -1
  7. package/dist/plugins/claude/src/text.js +0 -1
  8. package/dist/plugins/codex/src/history.d.ts +3 -8
  9. package/dist/plugins/codex/src/history.js +2 -238
  10. package/dist/plugins/codex/src/mcp.js +7 -7
  11. package/dist/plugins/codex/src/transcript.d.ts +3 -39
  12. package/dist/plugins/codex/src/transcript.js +2 -313
  13. package/dist/plugins/dsh/history.d.ts +3 -0
  14. package/dist/plugins/dsh/history.js +15 -0
  15. package/dist/plugins/dsh/tools.js +4 -5
  16. package/dist/plugins/pi/history-tools.d.ts +1 -1
  17. package/dist/plugins/pi/history-tools.js +9 -5
  18. package/dist/plugins/pi/history.d.ts +2 -3
  19. package/dist/plugins/pi/history.js +4 -147
  20. package/dist/src/boot/render.js +2 -4
  21. package/dist/src/boot/text.d.ts +3 -1
  22. package/dist/src/boot/text.js +11 -5
  23. package/dist/src/history/claude.d.ts +16 -0
  24. package/dist/src/history/claude.js +336 -0
  25. package/dist/src/history/codex-transcript.d.ts +39 -0
  26. package/dist/src/history/codex-transcript.js +315 -0
  27. package/dist/src/history/codex.d.ts +8 -0
  28. package/dist/src/history/codex.js +238 -0
  29. package/dist/src/history/corpus.d.ts +35 -0
  30. package/dist/src/history/corpus.js +54 -0
  31. package/dist/src/history/history.d.ts +4 -8
  32. package/dist/src/history/history.js +3 -11
  33. package/dist/src/history/local.d.ts +17 -0
  34. package/dist/src/history/local.js +101 -0
  35. package/dist/src/history/pi.d.ts +36 -0
  36. package/dist/src/history/pi.js +202 -0
  37. package/dist/src/history/query.d.ts +15 -5
  38. package/dist/src/history/query.js +42 -13
  39. package/dist/src/index.d.ts +4 -2
  40. package/dist/src/index.js +4 -3
  41. package/dist/src/tools/history.d.ts +7 -19
  42. package/dist/src/tools/history.js +80 -93
  43. package/dist/test/boot.integration.test.js +1 -2
  44. package/dist/test/claude-history.test.js +47 -34
  45. package/dist/test/claude-mod.test.js +7 -7
  46. package/dist/test/codex-history.test.js +4 -10
  47. package/dist/test/codex-plugin.test.js +32 -11
  48. package/dist/test/dependencies.test.js +3 -3
  49. package/dist/test/dsh.test.js +26 -4
  50. package/dist/test/helpers/extension.d.ts +0 -1
  51. package/dist/test/helpers/history-corpus.d.ts +7 -0
  52. package/dist/test/helpers/history-corpus.js +26 -0
  53. package/dist/test/history-corpus.test.d.ts +1 -0
  54. package/dist/test/history-corpus.test.js +307 -0
  55. package/dist/test/history.integration.test.js +40 -48
  56. package/dist/test/host-neutral.test.js +3 -18
  57. package/dist/test/model-facing-text.test.js +2 -0
  58. package/dist/test/notes.integration.test.js +1 -1
  59. package/dist/test/notes.test.js +1 -1
  60. package/docs/architecture.md +7 -5
  61. package/docs/claude-code-mod.md +7 -5
  62. package/docs/codex.md +3 -3
  63. package/docs/dsh.md +2 -2
  64. package/docs/history-sessions.md +52 -0
  65. package/docs/notes-library.md +1 -1
  66. package/docs/skills.md +1 -1
  67. package/docs/tool-results.md +8 -6
  68. package/package.json +3 -4
  69. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  70. package/plugins/claude/dist/claude/helper.js +1992 -1231
  71. package/plugins/claude/skills/memory/SKILL.md +5 -3
  72. package/plugins/claude/src/helper.ts +19 -23
  73. package/plugins/claude/src/history.ts +3 -257
  74. package/plugins/claude/src/text.ts +0 -1
  75. package/plugins/codex/dist/codex/notesoup.js +1364 -813
  76. package/plugins/codex/src/history.ts +3 -193
  77. package/plugins/codex/src/mcp.ts +7 -7
  78. package/plugins/codex/src/transcript.ts +3 -275
  79. package/plugins/dsh/history.ts +17 -0
  80. package/plugins/dsh/tools.ts +4 -5
  81. package/plugins/paseo/client/markdown.tsx +19 -39
  82. package/plugins/paseo/client/notes-op-card.tsx +1 -1
  83. package/plugins/pi/history-tools.ts +11 -5
  84. package/plugins/pi/history.ts +8 -157
  85. package/skills/memory/SKILL.md +5 -3
  86. package/src/boot/render.ts +2 -5
  87. package/src/boot/text.ts +11 -5
  88. package/src/history/claude.ts +286 -0
  89. package/src/history/codex-transcript.ts +276 -0
  90. package/src/history/codex.ts +193 -0
  91. package/src/history/corpus.ts +69 -0
  92. package/src/history/history.ts +5 -12
  93. package/src/history/local.ts +93 -0
  94. package/src/history/pi.ts +199 -0
  95. package/src/history/query.ts +45 -15
  96. package/src/index.ts +5 -3
  97. package/src/tools/history.ts +71 -101
@@ -6,8 +6,8 @@ import { earliestMatchOffsetChars } from "../text-match.js";
6
6
  import { InvalidQueryError, searchQueries } from "../tools/schema.js";
7
7
  import { eventDocument, filteredItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS, type HistoryEvent, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection } from "./history.js";
8
8
 
9
- type Candidate = { event: HistoryEvent; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
- type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow };
9
+ type Candidate = { event: HistoryEvent; session?: string; matchOffset?: number; preview?: HistoryPageItem; before?: HistoryFoldedRow };
10
+ type PreparedSelection = { candidates: Candidate[]; tail?: HistoryFoldedRow; session?: string; multi?: boolean };
11
11
 
12
12
  /** Which end of one selection `limit` is taken from; page items always come back ascending. */
13
13
  export type HistoryOrder = "newest" | "oldest";
@@ -18,6 +18,7 @@ export type HistoryOrder = "newest" | "oldest";
18
18
  * every role, with no folded rows.
19
19
  */
20
20
  export type HistorySelection = HistoryFilter & {
21
+ session?: string;
21
22
  from?: HistoryOrder;
22
23
  limit?: number;
23
24
  query?: string | string[];
@@ -51,15 +52,18 @@ function resolveTimeBounds(params: HistorySelection): Outcome<{ sinceMs?: number
51
52
 
52
53
  /** The params to merge into the previous call to continue toward older events. */
53
54
  export const HistoryOlderSchema = Type.Object({
55
+ session: Type.Optional(Type.String()),
54
56
  before_seq: Type.Integer({ minimum: 1 }),
55
57
  }, { additionalProperties: false });
56
58
  /** The params to merge into the previous call to continue toward newer events. */
57
59
  export const HistoryNewerSchema = Type.Object({
60
+ session: Type.Optional(Type.String()),
58
61
  after_seq: Type.Integer({ minimum: 1 }),
59
62
  from: Type.Literal("oldest"),
60
63
  }, { additionalProperties: false });
61
64
 
62
65
  export const HistoryPageSchema = Type.Object({
66
+ notice: Type.Optional(Type.String()),
63
67
  items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
64
68
  page_older: Type.Union([HistoryOlderSchema, Type.Null()]),
65
69
  page_newer: Type.Union([HistoryNewerSchema, Type.Null()]),
@@ -84,7 +88,7 @@ function truncateHistoryItem(item: HistoryPageItem, fits: (candidate: HistoryPag
84
88
  }
85
89
 
86
90
  /** Summarize one already ordered gap; omitted tool names never change its exact count. */
87
- function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
91
+ function foldedRun(events: HistoryEvent[], session?: string): HistoryFoldedRow | undefined {
88
92
  if (events.length === 0) return undefined;
89
93
  const counts = new Map<string, number>();
90
94
  for (const event of events) {
@@ -95,7 +99,7 @@ function foldedRun(events: HistoryEvent[]): HistoryFoldedRow | undefined {
95
99
  const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
96
100
  // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
97
101
  const tools = Object.fromEntries(entries);
98
- return { folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
102
+ return { ...(session === undefined ? {} : { session }), folded: true, first_seq: events[0]!.seq, last_seq: events.at(-1)!.seq, count: events.length, tools };
99
103
  }
100
104
 
101
105
  /** Filter and order once. Conversation candidates own the folded gap immediately before them. */
@@ -112,26 +116,27 @@ function prepareSelection(projection: HistoryProjection, params: HistorySelectio
112
116
  if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
113
117
  const matchOffset = params.query === undefined ? undefined : earliestMatchOffsetChars(eventDocument(event), params.query as string[]);
114
118
  if (matchOffset !== undefined && matchOffset < 0) continue;
115
- candidates.push({ event, matchOffset, before: foldedRun(run) });
119
+ candidates.push({ event, ...(params.session === undefined ? {} : { session: params.session }), matchOffset, before: foldedRun(run, params.session) });
116
120
  run = [];
117
121
  }
118
- return { candidates, tail: foldedRun(run) };
122
+ return { candidates, session: params.session, tail: foldedRun(run, params.session) };
119
123
  }
120
124
 
121
125
  /** Assemble only the admitted interval. Edge folds belong only to a page reaching that edge. */
122
126
  function pageData(prepared: PreparedSelection, start: number, end: number, maxChars: number, preview?: HistoryPageItem): HistoryPage {
123
127
  const { candidates, tail } = prepared;
128
+ const identity = prepared.session === undefined ? {} : { session: prepared.session };
124
129
  const items: HistoryPage["items"] = [];
125
130
  for (let index = start; index < end; index++) {
126
131
  const candidate = candidates[index]!;
127
132
  if (candidate.before && (index > start || start === 0)) items.push(candidate.before);
128
- items.push(preview ?? (candidate.preview ??= visibleItem(candidate.event, maxChars, candidate.matchOffset)));
133
+ items.push(preview ?? (candidate.preview ??= { ...visibleItem(candidate.event, maxChars, candidate.matchOffset), ...(candidate.session === undefined ? {} : { session: candidate.session }) }));
129
134
  }
130
135
  if (end === candidates.length && tail) items.push(tail);
131
136
  return {
132
137
  items,
133
- page_older: start > 0 && start < end ? { before_seq: candidates[start]!.event.seq } : null,
134
- page_newer: end < candidates.length && start < end ? { after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
138
+ page_older: !prepared.multi && start > 0 && start < end ? { ...identity, before_seq: candidates[start]!.event.seq } : null,
139
+ page_newer: !prepared.multi && end < candidates.length && start < end ? { ...identity, after_seq: candidates[end - 1]!.event.seq, from: "oldest" } : null,
135
140
  };
136
141
  }
137
142
 
@@ -139,18 +144,42 @@ function pageData(prepared: PreparedSelection, start: number, end: number, maxCh
139
144
  * Resolve the time bounds once, then filter and fold against the same [sinceMs, untilMs) window.
140
145
  * Grow the page in selection order; shorten the first preview only when no full row fits.
141
146
  */
142
- export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
147
+ function resolveSelection(params: HistorySelection): Outcome<HistorySelection> {
143
148
  const bounds = resolveTimeBounds(params);
144
149
  if (!bounds.ok) return bounds;
145
- let queries: string[];
146
150
  try {
147
- queries = searchQueries(params.query);
151
+ const queries = searchQueries(params.query);
152
+ return success({ ...params, ...bounds.data, query: queries.length ? queries : undefined });
148
153
  } catch (error) {
149
154
  if (error instanceof InvalidQueryError) return failure("invalid_query", error.message);
150
155
  throw error;
151
156
  }
152
- const scoped = { ...params, ...bounds.data, query: queries.length ? queries : undefined };
153
- const prepared = prepareSelection(projection, scoped);
157
+ }
158
+
159
+ export function selectPage(projection: HistoryProjection, params: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
160
+ const scoped = resolveSelection(params);
161
+ if (!scoped.ok) return scoped;
162
+ return selectPrepared(prepareSelection(projection, scoped.data), scoped.data, fits, maxChars);
163
+ }
164
+
165
+ /** Validate before corpus discovery or I/O: per-session seqs cannot bound a multi-session search. */
166
+ export function corpusSelection(params: HistorySelection): Outcome<HistorySelection> {
167
+ const scoped = resolveSelection(params);
168
+ if (!scoped.ok) return scoped;
169
+ if (scoped.data.query === undefined) return failure("missing_query", "Wildcard session search requires a non-empty `query`.");
170
+ if (params.before_seq !== undefined || params.after_seq !== undefined) return failure("invalid_bounds", "`before_seq` and `after_seq` are per-session; omit them for wildcard session search.");
171
+ return scoped;
172
+ }
173
+
174
+ /** Merge events, never folds or per-session cursors. Equal timestamps have a stable identity tie-break. */
175
+ export function selectCorpusPage(sessions: { session: string; projection: HistoryProjection }[], scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
176
+ const candidates = sessions.flatMap(({ session, projection }) => prepareSelection(projection, { ...scoped, session }).candidates);
177
+ const time = (event: HistoryEvent) => event.createdAt === undefined || Number.isNaN(Date.parse(event.createdAt)) ? -Infinity : Date.parse(event.createdAt);
178
+ candidates.sort((a, b) => (time(a.event) - time(b.event) || a.session!.localeCompare(b.session!) || a.event.seq - b.event.seq));
179
+ return selectPrepared({ candidates, multi: true }, scoped, fits, maxChars);
180
+ }
181
+
182
+ function selectPrepared(prepared: PreparedSelection, scoped: HistorySelection, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage> {
154
183
  const { candidates } = prepared;
155
184
  // Grow a contiguous interval from the requested end; even a byte-limited newest page stays ascending.
156
185
  const newest = scoped.from !== "oldest";
@@ -175,7 +204,8 @@ export function selectPage(projection: HistoryProjection, params: HistorySelecti
175
204
  }
176
205
  const page = pageData(prepared, start, end, maxChars);
177
206
  if (!fits(page)) {
178
- return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows and their folded runs fill the ${TOOL_OUTPUT_LIMIT} a call can carry; narrow with \`before_seq\`/\`after_seq\` or \`since\`/\`until\`, pass \`roles\` to skip folding, or \`history_read\` one seq.`);
207
+ const narrow = prepared.multi ? "narrow the session pattern, query, roles or `since`/`until`, or read one session/seq with `history_read`" : "narrow with `before_seq`/`after_seq` or `since`/`until`, pass `roles` to skip folding, or `history_read` one seq";
208
+ return failure("page_too_large", `Even trimmed to their shortest, these ${page.items.length} rows${prepared.multi ? "" : " and their folded runs"} fill the ${TOOL_OUTPUT_LIMIT} a call can carry; ${narrow}.`);
179
209
  }
180
210
  return success(page);
181
211
  }
package/src/index.ts CHANGED
@@ -2,7 +2,8 @@
2
2
  * Host-neutral core entry.
3
3
  *
4
4
  * Everything under `src/` is independent of any host SDK: notes, boot, history, budget and the
5
- * shared operations know nothing about Pi, Claude Code or dsh. Each plugin under `plugins/`
5
+ * shared operations use explicit facts, not live Pi, Claude Code or dsh services. History's
6
+ * read-only wire decoders understand persisted formats without importing those hosts. Each plugin under `plugins/`
6
7
  * composes these domains into that host's registration and owns that host's text, lifecycle and
7
8
  * SDK types. Nothing here imports a plugin.
8
9
  *
@@ -38,12 +39,13 @@ export { DEFAULT_BOOT_TOOL_NAMES, renderProtocolBlock } from "./boot/text.js";
38
39
  export type { BootToolNames } from "./boot/text.js";
39
40
 
40
41
  // Operations: the schemas and typed outcomes a host registers as its own tools, over a
41
- // host-supplied notes tool context or decoded history projection.
42
+ // host-supplied notes tool context or decoded history projection/lazy corpus context.
42
43
  export { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "./tools/notes.js";
43
44
  export { notesIdentityForCall, notesToolContext, type NotesToolContext } from "./tools/notes-context.js";
44
- export { historyList, historyRead, historyWindows } from "./tools/history.js";
45
+ export { historyList, historyRead } from "./tools/history.js";
45
46
  export { projectHistory } from "./history/history.js";
46
47
  export type { HistoryProjection } from "./history/history.js";
48
+ export type { HistoryContext, HistoryCorpus, HistoryHarness, HistorySession, HistorySessionData } from "./history/corpus.js";
47
49
  export type { Operation, OperationError, Outcome, Renderer, TextWindow } from "./tools/result.js";
48
50
 
49
51
  // Budget: pure thresholds and the approved reset prose.
@@ -1,15 +1,17 @@
1
1
  /** Host-neutral history operations: one bounded payload for text and structured results. */
2
2
  import { Type, type Static } from "typebox";
3
- import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS, TOOL_OUTPUT_LIMIT } from "./output.js";
4
- import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation, type Outcome } from "./result.js";
3
+ import { HISTORY_PREVIEW_CHARS, MAX_READ_WINDOW_CHARS } from "./output.js";
4
+ import { failure, fitsResult, resultSchema, readTextWindow, renderOutcome, renderTextWindow, success, TextWindowRequestSchema, TextWindowSchema, type Operation } from "./result.js";
5
5
  import { historyRoles, searchQuery } from "./schema.js";
6
- import { HistoryPageSchema, selectPage, type HistoryPage } from "../history/query.js";
7
- import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFilter, type HistoryFoldedRow, type HistoryPageItem, type HistoryProjection, unknownWindowId } from "../history/history.js";
6
+ import { HistoryPageSchema, corpusSelection, selectCorpusPage, selectPage, type HistoryPage } from "../history/query.js";
7
+ import { currentHistory, loadHistorySession, matchesSession, parseSessionSelector, resolveSession, sessionIdentity, type HistoryContext } from "../history/corpus.js";
8
+ import { allItems, eventDocument, nestedCallSummary, toolSummary, HistoryRoleSchema, NestedCallSummarySchema, ToolSummarySchema, type HistoryFoldedRow, type HistoryPageItem } from "../history/history.js";
8
9
 
9
10
  /** One read: identity, tool summary and a flat document slice. */
10
11
  const HistoryReadDataSchema = Type.Object({
12
+ session: Type.Optional(Type.String()),
13
+ notice: Type.Optional(Type.String()),
11
14
  seq: Type.Integer({ minimum: 1 }),
12
- window_id: Type.String(),
13
15
  role: HistoryRoleSchema,
14
16
  created_at: Type.Union([Type.String(), Type.Null()]),
15
17
  ...ToolSummarySchema.properties,
@@ -18,22 +20,10 @@ const HistoryReadDataSchema = Type.Object({
18
20
  }, { additionalProperties: false });
19
21
  type HistoryReadData = Static<typeof HistoryReadDataSchema>;
20
22
 
21
- const HistoryWindowsDataSchema = Type.Object({
22
- session_id: Type.String(),
23
- windows: Type.Array(Type.Object({
24
- window_id: Type.String(),
25
- created_at: Type.Union([Type.String(), Type.Null()]),
26
- first_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
27
- last_seq: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()]),
28
- }, { additionalProperties: false })),
29
- more: Type.Integer({ minimum: 0, description: "How many more were left out." }),
30
- }, { additionalProperties: false });
31
- type HistoryWindowsData = Static<typeof HistoryWindowsDataSchema>;
32
-
33
23
  /* ------------------------------------------------------------------ rendering */
34
24
 
35
- function header(item: { seq: number; window_id: string; role: string }): string {
36
- return `seq ${item.seq} | window ${item.window_id} | ${item.role}`;
25
+ function header(item: { session?: string; seq: number; role: string }): string {
26
+ return `${item.session === undefined ? "" : `session ${item.session} | `}seq ${item.seq} | ${item.role}`;
37
27
  }
38
28
 
39
29
  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 {
@@ -56,26 +46,27 @@ function renderPageItem(item: HistoryPageItem): string {
56
46
 
57
47
  function renderFoldedRow(row: HistoryFoldedRow): string {
58
48
  const tools = Object.entries(row.tools).map(([name, count]) => `${name} ${count}`).join(", ");
59
- const expand = `\n\t→ expand: {"after_seq":${row.first_seq - 1},"before_seq":${row.last_seq + 1},"from":"oldest","roles":["tool","context"]}`;
60
- return `seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
49
+ const identity = row.session === undefined ? {} : { session: row.session };
50
+ const expand = `\n\t→ expand: ${JSON.stringify({ ...identity, after_seq: row.first_seq - 1, before_seq: row.last_seq + 1, from: "oldest", roles: ["tool", "context"] })}`;
51
+ return `${row.session === undefined ? "" : `session ${row.session} | `}seqs ${row.first_seq}-${row.last_seq} | folded ${row.count} events${tools ? ` | ${tools}` : ""}${expand}`;
61
52
  }
62
53
 
63
54
  function renderPage(page: HistoryPage): string {
64
55
  // An empty selection has no anchors either, so it would otherwise render as nothing at all.
65
- if (page.items.length === 0) return "No events match these filters.";
56
+ if (page.items.length === 0) return `${page.notice ?? ""}No events match these filters.`;
66
57
  const body = page.items.map((item) => ("folded" in item ? renderFoldedRow(item) : renderPageItem(item))).join("\n\n");
67
58
  const cursors = [
68
59
  page.page_older === null ? "" : `→ older: ${JSON.stringify(page.page_older)}`,
69
60
  page.page_newer === null ? "" : `→ newer: ${JSON.stringify(page.page_newer)}`,
70
61
  ].filter((line) => line !== "");
71
- return cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`;
62
+ return (page.notice ?? "") + (cursors.length === 0 ? body : `${body}\n\n${cursors.join(" | ")}`);
72
63
  }
73
64
 
74
65
  function renderRead(data: HistoryReadData): string {
75
66
  const tool = toolHeader(data);
76
67
  const afterSeq = data.seq - 10;
77
- const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
78
- return [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
68
+ const neighborhood = `neighborhood → \`history_list\`(${JSON.stringify({ ...(data.session === undefined ? {} : { session: data.session }), ...(afterSeq >= 1 ? { after_seq: afterSeq } : {}), before_seq: data.seq + 10 })})`;
69
+ return (data.notice ?? "") + [header(data), ...(tool ? [tool] : []), neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
79
70
  }
80
71
 
81
72
  /* ------------------------------------------------------------------ shared bounding */
@@ -84,70 +75,12 @@ function renderRead(data: HistoryReadData): string {
84
75
  export type HistoryTextWrapper = (text: string) => string;
85
76
  const plainText: HistoryTextWrapper = (text) => text;
86
77
 
87
- // Sample known ids in the refusal message itself, never as a second listing.
88
- const MAX_REPORTED_WINDOWS = 5;
89
-
90
- /** At most `MAX_REPORTED_WINDOWS` known ids, appended to an unknown_window_id message. */
91
- function knownWindowSuffix(known: string[]): string {
92
- return known.length === 0 ? "" : `; its windows: ${known.slice(0, MAX_REPORTED_WINDOWS).join(", ")}`;
93
- }
94
-
95
- export const PREVIOUS_WINDOW = "@previous";
96
-
97
- /** Resolve "@previous" against oldest-first windows; every other value passes through. */
98
- function resolveWindowId(projection: HistoryProjection, windowId: string | undefined): { ok: true; window_id: string | undefined } | { ok: false; outcome: Outcome<never> } {
99
- if (windowId !== PREVIOUS_WINDOW) return { ok: true, window_id: windowId };
100
- const previous = projection.windows.at(-2);
101
- if (previous !== undefined) return { ok: true, window_id: previous.windowId };
102
- const known = projection.windows.map((current) => current.windowId);
103
- return { ok: false, outcome: failure("unknown_window_id", `"${PREVIOUS_WINDOW}" has nothing to point at: this session has no window before the current one${knownWindowSuffix(known)}.`) };
104
- }
105
-
106
- function badWindowId(projection: HistoryProjection, params: HistoryFilter): Outcome<never> | undefined {
107
- const badWindow = unknownWindowId(projection, params);
108
- if (!badWindow) return undefined;
109
- return failure("unknown_window_id", `${badWindow.message}${knownWindowSuffix(badWindow.known)}.`);
110
- }
111
-
112
- /* ------------------------------------------------------------------ history_windows */
113
-
114
- export const historyWindowsParameters = Type.Object({}, { additionalProperties: false });
115
-
116
- export const historyWindows: Operation<typeof historyWindowsParameters, HistoryWindowsData, [HistoryProjection, string, HistoryTextWrapper?]> = {
117
- name: "history_windows",
118
- label: "History list windows",
119
- description: "List this session's context windows, oldest first, with seq ranges.",
120
- parameters: historyWindowsParameters,
121
- outputSchema: resultSchema(HistoryWindowsDataSchema),
122
- async execute(_params, projection, sessionId, wrapText = plainText) {
123
- const data: HistoryWindowsData = { session_id: sessionId, windows: [], more: projection.windows.length };
124
- const fits = (candidate: HistoryWindowsData) => fitsResult(success(candidate), (result) => wrapText(renderOutcome(result, renderWindows)));
125
- for (const window of projection.windows) {
126
- let first: number | null = null;
127
- let last: number | null = null;
128
- for (const event of window.items) {
129
- first = first === null ? event.seq : Math.min(first, event.seq);
130
- last = last === null ? event.seq : Math.max(last, event.seq);
131
- }
132
- const row = { window_id: window.windowId, created_at: window.createdAt ?? null, first_seq: first, last_seq: last };
133
- if (!fits({ ...data, windows: [...data.windows, row], more: data.more - 1 })) break;
134
- data.windows.push(row);
135
- data.more--;
136
- }
137
- return fits(data) ? success(data) : failure("output_too_large", `The session id alone fills the ${TOOL_OUTPUT_LIMIT} a call can carry.`);
138
- },
139
- render: (result) => renderOutcome(result, renderWindows),
140
- };
141
-
142
- function renderWindows(data: HistoryWindowsData): string {
143
- const lines = [`session ${data.session_id}`, ...data.windows.map((window) => `window ${window.window_id} | seqs ${window.first_seq ?? "-"}-${window.last_seq ?? "-"}`)];
144
- if (data.more > 0) lines.push(`${data.more} more windows not shown; every \`history_list\` event also names its window.`);
145
- return lines.join("\n");
146
- }
147
-
148
78
  /* ------------------------------------------------------------------ history_list */
149
79
 
80
+ const sessionParameter = Type.Optional(Type.String({ minLength: 1, description: "(optional) Session ID or unique prefix, optionally pi:, claude:, codex:, or dsh:. Omit for this session. In history_list, * searches sessions (query required); history_read needs one session." }));
81
+
150
82
  export const historyListParameters = Type.Object({
83
+ session: sessionParameter,
151
84
  query: Type.Optional(searchQuery("(optional) Text, or a list of texts (any match). Empty text/list means no search filter; empty entries are ignored. Searches every role, tool arguments and output included; returns only hits.")),
152
85
  roles: historyRoles(),
153
86
  before_seq: Type.Optional(Type.Integer({ minimum: 1, description: "(optional) Only events with seq below this." })),
@@ -155,41 +88,77 @@ export const historyListParameters = Type.Object({
155
88
  since: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events at or after it. UTC if no offset." })),
156
89
  until: Type.Optional(Type.String({ minLength: 1, description: "(optional) ISO 8601 time; only events before it. UTC if no offset." })),
157
90
  from: Type.Optional(Type.Union([Type.Literal("newest"), Type.Literal("oldest")], { description: "(optional, default newest) Which end `limit` counts from: newest or oldest. Results stay oldest first." })),
158
- window_id: Type.Optional(Type.String({ minLength: 1, description: `(optional) Only this context window. From \`history_windows\` or any event; \`${PREVIOUS_WINDOW}\` is the one before this.` })),
159
91
  limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 500, description: "(optional, default 20) Max events per page; folded rows don't count." })),
160
92
  max_chars_per_item: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_READ_WINDOW_CHARS, description: `(optional, default ${HISTORY_PREVIEW_CHARS}) Max preview chars per event.` })),
161
93
  }, { additionalProperties: false });
162
94
 
163
- export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryProjection, HistoryTextWrapper?]> = {
95
+ export const historyList: Operation<typeof historyListParameters, HistoryPage, [HistoryContext, HistoryTextWrapper?]> = {
164
96
  name: "history_list",
165
97
  label: "History list items",
166
- description: "Browse or search this session's events, a page at a time. Read one in full with `history_read`.",
98
+ description: "Browse or search events, a page at a time. Omit session for this session; pass an ID/prefix for another, or * with query to search across local harnesses. Read one in full with `history_read`.",
167
99
  parameters: historyListParameters,
168
100
  outputSchema: resultSchema(HistoryPageSchema),
169
- async execute(params, projection, wrapText = plainText) {
170
- const resolved = resolveWindowId(projection, params.window_id);
171
- if (!resolved.ok) return resolved.outcome;
172
- const scoped = { ...params, window_id: resolved.window_id };
173
- const badWindow = badWindowId(projection, scoped);
174
- if (badWindow) return badWindow;
175
- // Charge wrapped rendering and cursors, not only event previews.
101
+ async execute(params, context, wrapText = plainText) {
102
+ // Charge wrapped rendering, identities, notices and recipes, not only event previews.
176
103
  const fits = (page: HistoryPage) => fitsResult(success(page), (result) => wrapText(renderOutcome(result, renderPage)));
177
- return selectPage(projection, scoped, fits, scoped.max_chars_per_item ?? HISTORY_PREVIEW_CHARS);
104
+ const maxChars = params.max_chars_per_item ?? HISTORY_PREVIEW_CHARS;
105
+ if (params.session === undefined) return selectPage(await currentHistory(context), params, fits, maxChars);
106
+ const selector = parseSessionSelector(params.session);
107
+ if (!selector.ok) return selector;
108
+ const corpus = "corpus" in context ? context.corpus : undefined;
109
+ if (selector.data.wildcard) {
110
+ const scoped = corpusSelection(params);
111
+ if (!scoped.ok) return scoped;
112
+ if (corpus === undefined) return failure("unknown_session", "This host supplied no cross-session history corpus.");
113
+ const sessions = (await corpus.sessions(selector.data.harness)).filter((session) => matchesSession(session, selector.data));
114
+ const loaded = [];
115
+ const notices: string[] = [];
116
+ for (const session of sessions) {
117
+ const result = await loadHistorySession(session);
118
+ if (!result.ok) return result;
119
+ loaded.push({ session: sessionIdentity(session), projection: result.data.projection });
120
+ if (result.data.notice) notices.push(`session ${sessionIdentity(session)}: ${result.data.notice}`);
121
+ }
122
+ const notice = notices.length ? { notice: notices.join("") } : {};
123
+ const result = selectCorpusPage(loaded, scoped.data, (page) => fits({ ...page, ...notice }), maxChars);
124
+ return result.ok ? success({ ...result.data, ...notice }) : result;
125
+ }
126
+ const target = await resolveSession(corpus, selector.data);
127
+ if (!target.ok) return target;
128
+ const loaded = await loadHistorySession(target.data);
129
+ if (!loaded.ok) return loaded;
130
+ const notice = loaded.data.notice === undefined ? {} : { notice: loaded.data.notice };
131
+ const result = selectPage(loaded.data.projection, { ...params, session: sessionIdentity(target.data) }, (page) => fits({ ...page, ...notice }), maxChars);
132
+ return result.ok ? success({ ...result.data, ...notice }) : result;
178
133
  },
179
134
  render: (result) => renderOutcome(result, renderPage),
180
135
  };
181
136
 
182
137
  /* ------------------------------------------------------------------ history_read */
183
138
 
184
- export const historyReadParameters = Type.Object({ seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`." }), ...TextWindowRequestSchema }, { additionalProperties: false });
139
+ export const historyReadParameters = Type.Object({ session: sessionParameter, seq: Type.Integer({ minimum: 1, description: "Event seq, from `history_list`. Pass its session too when present." }), ...TextWindowRequestSchema }, { additionalProperties: false });
185
140
 
186
- export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryProjection, HistoryTextWrapper?]> = {
141
+ export const historyRead: Operation<typeof historyReadParameters, HistoryReadData, [HistoryContext, HistoryTextWrapper?]> = {
187
142
  name: "history_read",
188
143
  label: "History read item",
189
144
  description: "Read one event in full: tool arguments, output, and nested calls.",
190
145
  parameters: historyReadParameters,
191
146
  outputSchema: resultSchema(HistoryReadDataSchema),
192
- async execute(params, projection, wrapText = plainText) {
147
+ async execute(params, context, wrapText = plainText) {
148
+ let projection;
149
+ let identity: { session?: string; notice?: string } = {};
150
+ if (params.session === undefined) projection = await currentHistory(context);
151
+ else {
152
+ const selector = parseSessionSelector(params.session);
153
+ if (!selector.ok) return selector;
154
+ if (selector.data.wildcard) return failure("invalid_session", "`history_read` reads one session; pass a specific `session` ID, not a wildcard.");
155
+ const target = await resolveSession("corpus" in context ? context.corpus : undefined, selector.data);
156
+ if (!target.ok) return target;
157
+ const loaded = await loadHistorySession(target.data);
158
+ if (!loaded.ok) return loaded;
159
+ projection = loaded.data.projection;
160
+ identity = { session: sessionIdentity(target.data), ...(loaded.data.notice === undefined ? {} : { notice: loaded.data.notice }) };
161
+ }
193
162
  const item = allItems(projection).find((event) => event.seq === params.seq);
194
163
  // Address checks run in one order: past the end of the file, off this branch, then
195
164
  // consumed by a pairing. Only the last two can mention what is at the address.
@@ -197,6 +166,7 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
197
166
  return failure("unknown_seq", `There is no seq ${params.seq}; this session runs from seq 1 to ${projection.highestSeq}.`);
198
167
  }
199
168
  if (!projection.branchSeqs.has(params.seq)) {
169
+ if (identity.notice) return failure("unconfirmed_seq", `Seq ${params.seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`);
200
170
  return failure("not_on_branch", `Seq ${params.seq} is on another branch of this session; it can't be read from here.`);
201
171
  }
202
172
  if (item === undefined) {
@@ -216,8 +186,8 @@ export const historyRead: Operation<typeof historyReadParameters, HistoryReadDat
216
186
  params.offset_chars,
217
187
  params.max_chars,
218
188
  (window) => ({
189
+ ...identity,
219
190
  seq: item.seq,
220
- window_id: item.windowId,
221
191
  role: item.role,
222
192
  created_at: item.createdAt ?? null,
223
193
  ...toolSummary(item),