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,10 +1,11 @@
1
1
  /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
2
  import { Type, type Static } from "typebox";
3
+ export declare function stringEnum<const T extends readonly [string, ...string[]]>(values: T, options?: Record<string, unknown>): Type.TUnsafe<T[number]>;
3
4
  /** The four public roles a history event carries on the wire, in presentation order. */
4
- export declare const HistoryRoleSchema: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
5
+ export declare const HistoryRoleSchema: Type.TUnsafe<"user" | "assistant" | "tool" | "context">;
5
6
  export type HistoryRole = Static<typeof HistoryRoleSchema>;
6
7
  /** How a recorded tool run ended. A call with no recorded result has not ended. */
7
- export declare const ToolCallStatusSchema: Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>;
8
+ export declare const ToolCallStatusSchema: Type.TUnsafe<"error" | "ok" | "unfinished">;
8
9
  export type ToolCallStatus = Static<typeof ToolCallStatusSchema>;
9
10
  /** Internal recorded facts, not a second copy in the public read schema. */
10
11
  export type NestedCallRecord = {
@@ -61,6 +62,8 @@ export type HistoryFilter = {
61
62
  roles?: HistoryRole[];
62
63
  after?: HistoryBound;
63
64
  before?: HistoryBound;
65
+ since?: number;
66
+ until?: number;
64
67
  };
65
68
  /** Native entries after the adapter allocates seqs and selects the active branch. */
66
69
  export type DecodedHistoryItem = {
@@ -97,54 +100,40 @@ export declare function eventDocument(event: HistoryEvent): string;
97
100
  /** Pair results into call events; consumed result seqs redirect to their call event on read. */
98
101
  export declare function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: number, branchSeqs: Set<number>): HistoryProjection;
99
102
  /** Summary shared by list, search and read. Full arguments/calls are in the document. */
100
- export declare const NestedCallSummarySchema: Type.TObject<{
101
- call_count: Type.TInteger;
102
- complete: Type.TBoolean;
103
- }>;
104
- /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
105
- export declare const ToolSummarySchema: Type.TObject<{
106
- tool: Type.TOptional<Type.TString>;
107
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
108
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
109
- full_output_path: Type.TOptional<Type.TString>;
110
- }>;
111
- export declare function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema>;
103
+ export type NestedCallSummary = {
104
+ call_count: number;
105
+ complete: boolean;
106
+ };
107
+ export type ToolSummary = {
108
+ tool?: string;
109
+ tool_status?: ToolCallStatus;
110
+ output_truncated?: true;
111
+ full_output_path?: string;
112
+ };
113
+ export declare function toolSummary(event: HistoryEvent): ToolSummary;
112
114
  /** Nested-call evidence is read with one event, not listed on every page row. */
113
115
  export declare function nestedCallSummary(event: HistoryEvent): {
114
- nested_calls?: Static<typeof NestedCallSummarySchema>;
116
+ nested_calls?: NestedCallSummary;
115
117
  };
116
118
  /** A run of tool/context events the conversation view replaces with counts. */
117
- export declare const HistoryFoldedRowSchema: Type.TObject<{
118
- session: Type.TOptional<Type.TString>;
119
- first_seq: Type.TInteger;
120
- last_seq: Type.TInteger;
121
- count: Type.TInteger;
122
- tools: Type.TRecord<"^.*$", Type.TInteger>;
123
- }>;
124
- export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
119
+ export type HistoryFoldedRow = {
120
+ first_seq: number;
121
+ last_seq: number;
122
+ count: number;
123
+ tools: Record<string, number>;
124
+ };
125
125
  /** Stable identity and a verbatim preview, starting at the search match when present. */
126
- export declare const HistoryPageItemSchema: Type.TObject<{
127
- content: Type.TString;
128
- truncated: Type.TBoolean;
129
- offset_chars: Type.TOptional<Type.TInteger>;
130
- tool: Type.TOptional<Type.TString>;
131
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
132
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
133
- full_output_path: Type.TOptional<Type.TString>;
134
- session: Type.TOptional<Type.TString>;
135
- folded_before: Type.TOptional<Type.TObject<{
136
- session: Type.TOptional<Type.TString>;
137
- first_seq: Type.TInteger;
138
- last_seq: Type.TInteger;
139
- count: Type.TInteger;
140
- tools: Type.TRecord<"^.*$", Type.TInteger>;
141
- }>>;
142
- context: Type.TOptional<Type.TLiteral<true>>;
143
- seq: Type.TInteger;
144
- role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
145
- created_at: Type.TUnion<[Type.TString, Type.TNull]>;
146
- }>;
147
- export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
126
+ export type HistoryPageItem = ToolSummary & {
127
+ session?: string;
128
+ folded_before?: HistoryFoldedRow;
129
+ context?: true;
130
+ seq: number;
131
+ role: HistoryRole;
132
+ created_at: string | null;
133
+ content: string;
134
+ truncated: boolean;
135
+ offset_chars?: number;
136
+ };
148
137
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
149
138
  export declare const MAX_FOLD_TOOL_NAMES = 20;
150
139
  /** Longest tool name a fold row lists. */
@@ -152,6 +141,8 @@ export declare const MAX_FOLD_TOOL_NAME_CHARS = 120;
152
141
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
153
142
  export declare function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem;
154
143
  export declare function allItems(projection: HistoryProjection): HistoryEvent[];
155
- export declare function matchesFilter(event: HistoryEvent, { after, before, roles }: HistoryFilter): boolean;
144
+ /** Memoized `Date.parse(event.createdAt)` (NaN when missing or invalid). */
145
+ export declare function eventTimestampMs(event: HistoryEvent): number;
146
+ export declare function matchesFilter(event: HistoryEvent, { after, before, since, until, roles }: HistoryFilter): boolean;
156
147
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
157
148
  export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter): HistoryEvent[];
@@ -1,9 +1,13 @@
1
1
  /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
2
  import { Type } from "typebox";
3
+ import { sliceCodePoints } from "../text-match.js";
4
+ export function stringEnum(values, options = {}) {
5
+ return Type.Unsafe({ ...Type.Enum([...values], options), type: "string" });
6
+ }
3
7
  /** The four public roles a history event carries on the wire, in presentation order. */
4
- export const HistoryRoleSchema = Type.Union([Type.Literal("user"), Type.Literal("assistant"), Type.Literal("tool"), Type.Literal("context")]);
8
+ export const HistoryRoleSchema = stringEnum(["user", "assistant", "tool", "context"]);
5
9
  /** How a recorded tool run ended. A call with no recorded result has not ended. */
6
- export const ToolCallStatusSchema = Type.Union([Type.Literal("ok"), Type.Literal("error"), Type.Literal("unfinished")]);
10
+ export const ToolCallStatusSchema = stringEnum(["ok", "error", "unfinished"]);
7
11
  function isTextContent(part) {
8
12
  return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
9
13
  }
@@ -106,18 +110,6 @@ export function projectHistory(rawWindows, highestSeq, branchSeqs) {
106
110
  }));
107
111
  return { windows, highestSeq, branchSeqs, pairedResults };
108
112
  }
109
- /** Summary shared by list, search and read. Full arguments/calls are in the document. */
110
- export const NestedCallSummarySchema = Type.Object({
111
- call_count: Type.Integer({ minimum: 0 }),
112
- complete: Type.Boolean({ description: "true = every nested call was recorded." }),
113
- }, { additionalProperties: false });
114
- /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
115
- export const ToolSummarySchema = Type.Object({
116
- tool: Type.Optional(Type.String()),
117
- tool_status: Type.Optional(ToolCallStatusSchema),
118
- output_truncated: Type.Optional(Type.Literal(true)),
119
- full_output_path: Type.Optional(Type.String()),
120
- }, { additionalProperties: false });
121
113
  export function toolSummary(event) {
122
114
  const execution = event.execution;
123
115
  if (!execution)
@@ -134,27 +126,6 @@ export function nestedCallSummary(event) {
134
126
  const nested = event.execution?.nestedCalls;
135
127
  return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
136
128
  }
137
- /** A run of tool/context events the conversation view replaces with counts. */
138
- export const HistoryFoldedRowSchema = Type.Object({
139
- session: Type.Optional(Type.String()),
140
- first_seq: Type.Integer({ minimum: 1 }),
141
- last_seq: Type.Integer({ minimum: 1 }),
142
- count: Type.Integer({ minimum: 1 }),
143
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
144
- }, { additionalProperties: false });
145
- /** Stable identity and a verbatim preview, starting at the search match when present. */
146
- export const HistoryPageItemSchema = Type.Object({
147
- session: Type.Optional(Type.String()),
148
- folded_before: Type.Optional(HistoryFoldedRowSchema),
149
- context: Type.Optional(Type.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
150
- seq: Type.Integer({ minimum: 1 }),
151
- role: HistoryRoleSchema,
152
- created_at: Type.Union([Type.String(), Type.Null()]),
153
- ...ToolSummarySchema.properties,
154
- content: Type.String(),
155
- truncated: Type.Boolean({ description: "Preview is partial." }),
156
- offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
157
- }, { additionalProperties: false });
158
129
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
159
130
  export const MAX_FOLD_TOOL_NAMES = 20;
160
131
  /** Longest tool name a fold row lists. */
@@ -162,17 +133,16 @@ export const MAX_FOLD_TOOL_NAME_CHARS = 120;
162
133
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
163
134
  export function visibleItem(event, maxChars, matchOffset) {
164
135
  const document = eventDocument(event);
165
- const chars = Array.from(document);
166
136
  const start = matchOffset ?? 0;
167
137
  // A negative budget would cut the tail and still call the result a prefix.
168
138
  const limit = Math.max(0, maxChars);
169
- const truncated = start > 0 || start + limit < chars.length;
139
+ const { text: content, truncated } = sliceCodePoints(document, start, limit);
170
140
  return {
171
141
  seq: event.seq,
172
142
  role: event.role,
173
143
  created_at: event.createdAt ?? null,
174
144
  ...toolSummary(event),
175
- content: truncated ? chars.slice(start, start + limit).join("") : document,
145
+ content,
176
146
  truncated,
177
147
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
178
148
  };
@@ -180,11 +150,22 @@ export function visibleItem(event, maxChars, matchOffset) {
180
150
  export function allItems(projection) {
181
151
  return projection.windows.flatMap((current) => current.items);
182
152
  }
153
+ const timestamps = new WeakMap();
154
+ /** Memoized `Date.parse(event.createdAt)` (NaN when missing or invalid). */
155
+ export function eventTimestampMs(event) {
156
+ const cached = timestamps.get(event);
157
+ if (cached !== undefined)
158
+ return cached;
159
+ const parsed = event.createdAt ? Date.parse(event.createdAt) : NaN;
160
+ timestamps.set(event, parsed);
161
+ return parsed;
162
+ }
183
163
  function compareBound(event, bound) {
184
- return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
164
+ return "seq" in bound ? event.seq - bound.seq : eventTimestampMs(event) - bound.at;
185
165
  }
186
- export function matchesFilter(event, { after, before, roles }) {
166
+ export function matchesFilter(event, { after, before, since, until, roles }) {
187
167
  return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0)
168
+ && (since === undefined || eventTimestampMs(event) > since) && (until === undefined || eventTimestampMs(event) < until)
188
169
  && (!roles || roles.includes(event.role));
189
170
  }
190
171
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
@@ -1,14 +1,30 @@
1
1
  /** Local read-only corpus. Wire decoders have no SDK dependencies; DSH supplies its query service. */
2
- import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { readdir, stat } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { piHistoryFromJsonl } from "./pi.js";
6
- import { offlineClaudeHistoryFromJsonl } from "./claude.js";
5
+ import { piHistoryFromFile } from "./pi.js";
6
+ import { offlineClaudeHistoryFromFile } from "./claude.js";
7
7
  import { readCodexHistory } from "./codex.js";
8
8
  import { createCodexTranscriptReader } from "./codex-transcript.js";
9
9
  import { createHistoryPrefilter, historyFileMayMatch } from "./prefilter.js";
10
10
  import { sessionIdentity } from "./corpus.js";
11
- import { cachedSessionRepresentative, historySummaryCacheRoot } from "./summary-cache.js";
11
+ import { cachedSessionSummary, historySummaryCacheRoot, peekCachedSessionSummary } from "./summary-cache.js";
12
+ const DIR_CONCURRENCY = 32;
13
+ const STAT_CONCURRENCY = 64;
14
+ async function mapConcurrent(items, concurrency, fn) {
15
+ if (items.length === 0)
16
+ return [];
17
+ const results = new Array(items.length);
18
+ let next = 0;
19
+ const workers = Math.min(concurrency, items.length);
20
+ await Promise.all(Array.from({ length: workers }, async () => {
21
+ while (next < items.length) {
22
+ const index = next++;
23
+ results[index] = await fn(items[index]);
24
+ }
25
+ }));
26
+ return results;
27
+ }
12
28
  function rootsFor(options) {
13
29
  const env = options.env ?? process.env;
14
30
  const home = options.home ?? env.HOME ?? homedir();
@@ -29,39 +45,48 @@ async function filesAt(root, depth) {
29
45
  return [];
30
46
  throw error;
31
47
  }
32
- const paths = [];
33
- for (const entry of entries) {
34
- const path = join(root, entry.name);
35
- if (entry.isDirectory() && depth > 0)
36
- paths.push(...await filesAt(path, depth - 1));
37
- else if (entry.isFile() && depth === 0)
38
- paths.push(path);
48
+ if (depth === 0) {
49
+ const paths = [];
50
+ for (const entry of entries)
51
+ if (entry.isFile())
52
+ paths.push(join(root, entry.name));
53
+ return paths;
39
54
  }
40
- return paths;
55
+ const dirs = entries.filter((entry) => entry.isDirectory()).map((entry) => join(root, entry.name));
56
+ const nested = await mapConcurrent(dirs, DIR_CONCURRENCY, (dir) => filesAt(dir, depth - 1));
57
+ return nested.flat();
41
58
  }
42
59
  async function localSessions(harness, root, cacheRoot, prefilters) {
43
60
  const paths = await filesAt(root, harness === "codex" ? 3 : 1);
44
- const sessions = [];
61
+ const matched = [];
45
62
  for (const path of paths) {
46
63
  const name = path.split(/[\\/]/).at(-1);
47
64
  const id = harness === "pi" ? /^.+_(.+)\.jsonl$/.exec(name)?.[1]
48
65
  : harness === "claude" ? /^(.+)\.jsonl$/.exec(name)?.[1]
49
66
  : /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_[0-9a-f-]{36})?\.jsonl(?:\.zst)?$/.exec(name)?.[1];
50
- if (!id)
51
- continue;
52
- let modifiedAt;
67
+ if (id)
68
+ matched.push({ path, id });
69
+ }
70
+ const statted = await mapConcurrent(matched, STAT_CONCURRENCY, async ({ path, id }) => {
53
71
  try {
54
- modifiedAt = (await stat(path)).mtimeMs;
72
+ const info = await stat(path);
73
+ return { path, id, modifiedAt: info.mtimeMs, size: info.size };
55
74
  }
56
75
  catch (error) {
57
76
  if (error.code === "ENOENT")
58
- continue;
77
+ return undefined;
59
78
  throw error;
60
79
  }
61
- sessions.push({
80
+ });
81
+ const sessions = [];
82
+ for (const entry of statted) {
83
+ if (!entry)
84
+ continue;
85
+ const { path, id, modifiedAt, size } = entry;
86
+ const session = {
62
87
  harness, id, modifiedAt,
63
- async loadRepresentative() {
64
- return cachedSessionRepresentative(this, path, cacheRoot, async (track) => {
88
+ async loadSummary() {
89
+ return cachedSessionSummary(this, path, cacheRoot, async (track) => {
65
90
  if (harness === "codex") {
66
91
  const readBytes = createCodexTranscriptReader();
67
92
  const history = await readCodexHistory({ threadId: id, transcriptPath: path }, async (source, remaining) => {
@@ -76,6 +101,13 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
76
101
  return { data };
77
102
  });
78
103
  },
104
+ async loadRepresentative() {
105
+ const { event, notice } = await this.loadSummary();
106
+ return { event, notice };
107
+ },
108
+ async peekSummary() {
109
+ return peekCachedSessionSummary(this, path, cacheRoot);
110
+ },
79
111
  async load(queries) {
80
112
  if (queries?.length) {
81
113
  let prefilter = prefilters.get(queries);
@@ -86,14 +118,14 @@ async function localSessions(harness, root, cacheRoot, prefilters) {
86
118
  }
87
119
  if (harness === "codex")
88
120
  return { projection: (await readCodexHistory({ threadId: id, transcriptPath: path })).projection };
89
- const text = await readFile(path, "utf8");
90
121
  if (harness === "pi")
91
- return { projection: piHistoryFromJsonl(text, id) };
92
- const projection = offlineClaudeHistoryFromJsonl(text, id);
122
+ return { projection: await piHistoryFromFile(path, id, size) };
123
+ const projection = await offlineClaudeHistoryFromFile(path, id, size);
93
124
  const missing = projection.missingAncestors;
94
125
  return { projection, ...(missing.length === 0 ? {} : { notice: `Claude history is incomplete: missing ancestor UUID(s): ${missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.slice(0, 160))).join(", ")}. Only confirmed ancestry is returned; disconnected prefixes are excluded.\n\n` }) };
95
126
  },
96
- });
127
+ };
128
+ sessions.push(session);
97
129
  }
98
130
  return sessions;
99
131
  }
@@ -105,22 +137,25 @@ export function localHistoryCorpus(options) {
105
137
  const roots = rootsFor(options);
106
138
  const env = options.env ?? process.env;
107
139
  const cacheRoot = options.summaryCacheRoot ?? historySummaryCacheRoot(options.home ?? env.HOME ?? homedir(), env);
108
- const discovered = [];
109
140
  const prefilters = new WeakMap();
141
+ const tasks = [];
110
142
  for (const harness of ["pi", "claude", "codex"]) {
111
143
  if (onlyHarness !== undefined && onlyHarness !== harness)
112
144
  continue;
113
145
  const root = roots[harness];
114
146
  if (root != null)
115
- discovered.push(...await localSessions(harness, root, cacheRoot, prefilters));
147
+ tasks.push(localSessions(harness, root, cacheRoot, prefilters));
116
148
  }
117
149
  if (options.dshSessions && (onlyHarness === undefined || onlyHarness === "dsh"))
118
- discovered.push(...await options.dshSessions());
119
- discovered.sort((a, b) => b.modifiedAt - a.modifiedAt || sessionIdentity(a).localeCompare(sessionIdentity(b)));
150
+ tasks.push(options.dshSessions());
151
+ const discovered = (await Promise.all(tasks)).flat();
120
152
  const unique = new Map();
121
- for (const session of discovered)
122
- if (!unique.has(sessionIdentity(session)))
123
- unique.set(sessionIdentity(session), session);
153
+ for (const session of discovered) {
154
+ const key = sessionIdentity(session);
155
+ const existing = unique.get(key);
156
+ if (!existing || session.modifiedAt > existing.modifiedAt)
157
+ unique.set(key, session);
158
+ }
124
159
  const current = { harness: options.current.harness, id: options.current.id, load: options.current.load, modifiedAt: Date.now() };
125
160
  if (onlyHarness === undefined || onlyHarness === current.harness)
126
161
  unique.set(sessionIdentity(current), current);
@@ -1,4 +1,3 @@
1
- /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
1
  import { type HistoryProjection, type RecordedNestedCalls } from "./history.js";
3
2
  /** Structural views also accept native SDK values without converting or allocating seqs twice. */
4
3
  type Message = {
@@ -33,4 +32,6 @@ export declare function piSequenceCount(entry: Pick<PiHistoryEntry, "type" | "me
33
32
  export declare function piHistoryFromEntries(sessionId: string, entries: readonly PiHistoryEntry[], branch: readonly PiHistoryEntry[]): HistoryProjection;
34
33
  /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
35
34
  export declare function piHistoryFromJsonl(text: string, sessionId: string): HistoryProjection;
35
+ /** Stream oversized Pi JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
36
+ export declare function piHistoryFromFile(path: string, sessionId: string, sizeHint?: number): Promise<HistoryProjection>;
36
37
  export {};
@@ -1,5 +1,9 @@
1
1
  /** Pi's persisted entry/message wire format, independent of the Pi SDK. */
2
+ import { createReadStream } from "node:fs";
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import { StringDecoder } from "node:string_decoder";
2
5
  import { contentText, projectHistory } from "./history.js";
6
+ const STREAM_FILE_BYTES = 64 * 1024 * 1024;
3
7
  function mapRole(role) {
4
8
  if (role === "user" || role === "assistant")
5
9
  return role;
@@ -144,59 +148,129 @@ export function piHistoryFromEntries(sessionId, entries, branch) {
144
148
  }
145
149
  return projectHistory(rawWindows, highestSeq, branchSeqs);
146
150
  }
151
+ function slimMessage(message) {
152
+ let content = message.content;
153
+ if (Array.isArray(content)) {
154
+ content = content.filter((part) => (typeof part === "object" && part !== null && (part.type === "text" || part.type === "toolCall")));
155
+ }
156
+ return {
157
+ role: message.role,
158
+ ...(content === undefined ? {} : { content }),
159
+ ...(message.output === undefined ? {} : { output: message.output }),
160
+ ...(message.summary === undefined ? {} : { summary: message.summary }),
161
+ ...(message.command === undefined ? {} : { command: message.command }),
162
+ ...(message.cancelled === undefined ? {} : { cancelled: message.cancelled }),
163
+ ...(message.exitCode === undefined ? {} : { exitCode: message.exitCode }),
164
+ ...(message.truncated === undefined ? {} : { truncated: message.truncated }),
165
+ ...(message.fullOutputPath === undefined ? {} : { fullOutputPath: message.fullOutputPath }),
166
+ ...(message.toolName === undefined ? {} : { toolName: message.toolName }),
167
+ ...(message.toolCallId === undefined ? {} : { toolCallId: message.toolCallId }),
168
+ ...(message.isError === undefined ? {} : { isError: message.isError }),
169
+ ...(message.nestedCalls === undefined ? {} : { nestedCalls: message.nestedCalls }),
170
+ };
171
+ }
172
+ function slimEntry(row) {
173
+ return {
174
+ type: row.type,
175
+ id: row.id,
176
+ parentId: row.parentId,
177
+ ...(row.timestamp === undefined ? {} : { timestamp: row.timestamp }),
178
+ ...(row.summary === undefined ? {} : { summary: row.summary }),
179
+ ...(row.customType === undefined ? {} : { customType: row.customType }),
180
+ ...(row.customType === "notesoup/reset-marker" && row.data !== undefined ? { data: row.data } : {}),
181
+ ...(row.type === "custom_message" && row.content !== undefined ? { content: contentText(row.content) } : {}),
182
+ ...(row.type === "message" && row.message ? { message: slimMessage(row.message) } : {}),
183
+ };
184
+ }
185
+ function createPiJsonlParser(sessionId) {
186
+ const entries = [];
187
+ let header = false;
188
+ return {
189
+ push(line, lineNumber, allowIncompleteTail) {
190
+ if (line.trim() === "")
191
+ return;
192
+ let row;
193
+ try {
194
+ row = JSON.parse(line);
195
+ }
196
+ catch {
197
+ if (allowIncompleteTail)
198
+ return;
199
+ throw new Error(`malformed Pi transcript JSON at line ${lineNumber}`);
200
+ }
201
+ if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string")
202
+ throw new Error("invalid Pi transcript entry");
203
+ if (!header) {
204
+ if (row.type !== "session" || row.id !== sessionId)
205
+ throw new Error("Pi transcript belongs to a different session or has no header");
206
+ header = true;
207
+ return;
208
+ }
209
+ if (row.parentId !== null && typeof row.parentId !== "string")
210
+ throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
211
+ if (row.type === "message" && (!row.message || typeof row.message.role !== "string"))
212
+ throw new Error("invalid Pi transcript message");
213
+ entries.push(slimEntry(row));
214
+ },
215
+ finish() {
216
+ if (!header)
217
+ throw new Error("Pi transcript has no session header");
218
+ const byId = new Map();
219
+ for (const entry of entries) {
220
+ if (byId.has(entry.id))
221
+ throw new Error(`duplicate Pi entry ID: ${entry.id}`);
222
+ byId.set(entry.id, entry);
223
+ }
224
+ const branch = [], seen = new Set();
225
+ let cursor = entries.at(-1);
226
+ while (cursor) {
227
+ if (seen.has(cursor.id))
228
+ throw new Error("cyclic Pi transcript ancestry");
229
+ seen.add(cursor.id);
230
+ branch.push(cursor);
231
+ if (cursor.parentId === null)
232
+ break;
233
+ const parent = byId.get(cursor.parentId);
234
+ if (!parent)
235
+ throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
236
+ cursor = parent;
237
+ }
238
+ return piHistoryFromEntries(sessionId, entries, branch.reverse());
239
+ },
240
+ };
241
+ }
147
242
  /** Offline files persist append order and parent links; select the final tree entry's ancestry. */
148
243
  export function piHistoryFromJsonl(text, sessionId) {
149
244
  const lines = text.split("\n");
150
- const entries = [];
151
- let header = false;
245
+ const parser = createPiJsonlParser(sessionId);
152
246
  for (let index = 0; index < lines.length; index++) {
153
- const line = lines[index];
154
- if (line.trim() === "")
155
- continue;
156
- let row;
157
- try {
158
- row = JSON.parse(line);
159
- }
160
- catch {
161
- if (index === lines.length - 1 && !text.endsWith("\n"))
162
- break;
163
- throw new Error(`malformed Pi transcript JSON at line ${index + 1}`);
164
- }
165
- if (!row || typeof row !== "object" || typeof row.type !== "string" || typeof row.id !== "string")
166
- throw new Error("invalid Pi transcript entry");
167
- if (!header) {
168
- if (row.type !== "session" || row.id !== sessionId)
169
- throw new Error("Pi transcript belongs to a different session or has no header");
170
- header = true;
171
- continue;
172
- }
173
- if (row.parentId !== null && typeof row.parentId !== "string")
174
- throw new Error("Pi transcript has no tree parent link (unsupported legacy format)");
175
- if (row.type === "message" && (!row.message || typeof row.message.role !== "string"))
176
- throw new Error("invalid Pi transcript message");
177
- entries.push(row);
247
+ parser.push(lines[index], index + 1, index === lines.length - 1 && !text.endsWith("\n"));
178
248
  }
179
- if (!header)
180
- throw new Error("Pi transcript has no session header");
181
- const byId = new Map();
182
- for (const entry of entries) {
183
- if (byId.has(entry.id))
184
- throw new Error(`duplicate Pi entry ID: ${entry.id}`);
185
- byId.set(entry.id, entry);
249
+ return parser.finish();
250
+ }
251
+ /** Stream oversized Pi JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
252
+ export async function piHistoryFromFile(path, sessionId, sizeHint) {
253
+ const size = sizeHint ?? (await stat(path)).size;
254
+ if (size < STREAM_FILE_BYTES)
255
+ return piHistoryFromJsonl(await readFile(path, "utf8"), sessionId);
256
+ const parser = createPiJsonlParser(sessionId);
257
+ const decoder = new StringDecoder("utf8");
258
+ let remainder = "";
259
+ let lineNumber = 0;
260
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
261
+ const text = remainder + decoder.write(chunk);
262
+ let start = 0;
263
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
264
+ lineNumber++;
265
+ parser.push(text.slice(start, nl), lineNumber, false);
266
+ start = nl + 1;
267
+ }
268
+ remainder = text.slice(start);
186
269
  }
187
- const branch = [], seen = new Set();
188
- let cursor = entries.at(-1);
189
- while (cursor) {
190
- if (seen.has(cursor.id))
191
- throw new Error("cyclic Pi transcript ancestry");
192
- seen.add(cursor.id);
193
- branch.push(cursor);
194
- if (cursor.parentId === null)
195
- break;
196
- const parent = byId.get(cursor.parentId);
197
- if (!parent)
198
- throw new Error(`Pi transcript missing parent: ${cursor.parentId}`);
199
- cursor = parent;
270
+ remainder += decoder.end();
271
+ if (remainder.length > 0) {
272
+ lineNumber++;
273
+ parser.push(remainder, lineNumber, true);
200
274
  }
201
- return piHistoryFromEntries(sessionId, entries, branch.reverse());
275
+ return parser.finish();
202
276
  }