notesoup 0.0.0-stage → 0.39.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -2
  3. package/dist/src/boot/render.d.ts +16 -0
  4. package/dist/src/boot/render.js +95 -0
  5. package/dist/src/boot/snapshot.d.ts +32 -0
  6. package/dist/src/boot/snapshot.js +36 -0
  7. package/dist/src/boot/text.d.ts +21 -0
  8. package/dist/src/boot/text.js +52 -0
  9. package/dist/src/budget/constants.d.ts +9 -0
  10. package/dist/src/budget/constants.js +9 -0
  11. package/dist/src/budget/policy.d.ts +19 -0
  12. package/dist/src/budget/policy.js +36 -0
  13. package/dist/src/budget/text.d.ts +8 -0
  14. package/dist/src/budget/text.js +10 -0
  15. package/dist/src/claude/helper.d.ts +15 -0
  16. package/dist/src/claude/helper.js +87 -0
  17. package/dist/src/dream/doctor.d.ts +2 -0
  18. package/dist/src/dream/doctor.js +160 -0
  19. package/dist/src/dream/gates.d.ts +10 -0
  20. package/dist/src/dream/gates.js +26 -0
  21. package/dist/src/dream/git.d.ts +21 -0
  22. package/dist/src/dream/git.js +71 -0
  23. package/dist/src/dream/jail.d.ts +11 -0
  24. package/dist/src/dream/jail.js +71 -0
  25. package/dist/src/dream/lock.d.ts +31 -0
  26. package/dist/src/dream/lock.js +99 -0
  27. package/dist/src/dream/playbook.d.ts +1 -0
  28. package/dist/src/dream/playbook.js +2 -0
  29. package/dist/src/dream/report.d.ts +7 -0
  30. package/dist/src/dream/report.js +43 -0
  31. package/dist/src/dream/result.d.ts +9 -0
  32. package/dist/src/dream/result.js +1 -0
  33. package/dist/src/dream/settings.d.ts +10 -0
  34. package/dist/src/dream/settings.js +14 -0
  35. package/dist/src/history/history.d.ts +151 -0
  36. package/dist/src/history/history.js +195 -0
  37. package/dist/src/history/query.d.ts +75 -0
  38. package/dist/src/history/query.js +143 -0
  39. package/dist/src/index.d.ts +1 -0
  40. package/dist/src/index.js +1 -0
  41. package/dist/src/notes/address.d.ts +31 -0
  42. package/dist/src/notes/address.js +123 -0
  43. package/dist/src/notes/constants.d.ts +3 -0
  44. package/dist/src/notes/constants.js +3 -0
  45. package/dist/src/notes/errors.d.ts +11 -0
  46. package/dist/src/notes/errors.js +13 -0
  47. package/dist/src/notes/frontmatter.d.ts +44 -0
  48. package/dist/src/notes/frontmatter.js +145 -0
  49. package/dist/src/notes/fs-error.d.ts +2 -0
  50. package/dist/src/notes/fs-error.js +5 -0
  51. package/dist/src/notes/identity.d.ts +10 -0
  52. package/dist/src/notes/identity.js +33 -0
  53. package/dist/src/notes/index.d.ts +5 -0
  54. package/dist/src/notes/index.js +3 -0
  55. package/dist/src/notes/paths.d.ts +21 -0
  56. package/dist/src/notes/paths.js +113 -0
  57. package/dist/src/notes/store.d.ts +104 -0
  58. package/dist/src/notes/store.js +478 -0
  59. package/dist/src/pi/boot.d.ts +24 -0
  60. package/dist/src/pi/boot.js +56 -0
  61. package/dist/src/pi/budget.d.ts +13 -0
  62. package/dist/src/pi/budget.js +178 -0
  63. package/dist/src/pi/dream/cli.d.ts +10 -0
  64. package/dist/src/pi/dream/cli.js +140 -0
  65. package/dist/src/pi/dream/runner.d.ts +27 -0
  66. package/dist/src/pi/dream/runner.js +90 -0
  67. package/dist/src/pi/dream/settings.d.ts +7 -0
  68. package/dist/src/pi/dream/settings.js +17 -0
  69. package/dist/src/pi/entries.d.ts +7 -0
  70. package/dist/src/pi/entries.js +7 -0
  71. package/dist/src/pi/estimate.d.ts +16 -0
  72. package/dist/src/pi/estimate.js +99 -0
  73. package/dist/src/pi/extension.d.ts +10 -0
  74. package/dist/src/pi/extension.js +24 -0
  75. package/dist/src/pi/history-tools.d.ts +3 -0
  76. package/dist/src/pi/history-tools.js +10 -0
  77. package/dist/src/pi/history.d.ts +4 -0
  78. package/dist/src/pi/history.js +150 -0
  79. package/dist/src/pi/notes/adapter.d.ts +10 -0
  80. package/dist/src/pi/notes/adapter.js +27 -0
  81. package/dist/src/pi/notes/tools.d.ts +3 -0
  82. package/dist/src/pi/notes/tools.js +15 -0
  83. package/dist/src/pi/reset/artifacts.d.ts +24 -0
  84. package/dist/src/pi/reset/artifacts.js +84 -0
  85. package/dist/src/pi/reset/committed.d.ts +7 -0
  86. package/dist/src/pi/reset/committed.js +28 -0
  87. package/dist/src/pi/reset/lifecycle.d.ts +101 -0
  88. package/dist/src/pi/reset/lifecycle.js +277 -0
  89. package/dist/src/pi/reset/text.d.ts +5 -0
  90. package/dist/src/pi/reset/text.js +6 -0
  91. package/dist/src/pi/runtime.d.ts +3 -0
  92. package/dist/src/pi/runtime.js +206 -0
  93. package/dist/src/pi/session-reader.d.ts +5 -0
  94. package/dist/src/pi/session-reader.js +1 -0
  95. package/dist/src/pi/thresholds.d.ts +17 -0
  96. package/dist/src/pi/thresholds.js +33 -0
  97. package/dist/src/pi/tool-names.d.ts +11 -0
  98. package/dist/src/pi/tool-names.js +11 -0
  99. package/dist/src/pi/tool-result.d.ts +15 -0
  100. package/dist/src/pi/tool-result.js +29 -0
  101. package/dist/src/pi/window.d.ts +41 -0
  102. package/dist/src/pi/window.js +127 -0
  103. package/dist/src/settings.d.ts +9 -0
  104. package/dist/src/settings.js +18 -0
  105. package/dist/src/text-match.d.ts +5 -0
  106. package/dist/src/text-match.js +16 -0
  107. package/dist/src/tools/history.d.ts +67 -0
  108. package/dist/src/tools/history.js +251 -0
  109. package/dist/src/tools/notes.d.ts +282 -0
  110. package/dist/src/tools/notes.js +378 -0
  111. package/dist/src/tools/output.d.ts +23 -0
  112. package/dist/src/tools/output.js +39 -0
  113. package/dist/src/tools/result.d.ts +79 -0
  114. package/dist/src/tools/result.js +130 -0
  115. package/dist/src/tools/schema.d.ts +18 -0
  116. package/dist/src/tools/schema.js +31 -0
  117. package/dist/test/agent-loop.test.d.ts +1 -0
  118. package/dist/test/agent-loop.test.js +1497 -0
  119. package/dist/test/boot.integration.test.d.ts +1 -0
  120. package/dist/test/boot.integration.test.js +294 -0
  121. package/dist/test/budget-settings.integration.test.d.ts +1 -0
  122. package/dist/test/budget-settings.integration.test.js +144 -0
  123. package/dist/test/claude-mod.test.d.ts +1 -0
  124. package/dist/test/claude-mod.test.js +404 -0
  125. package/dist/test/dependencies.test.d.ts +1 -0
  126. package/dist/test/dependencies.test.js +101 -0
  127. package/dist/test/doctor.test.d.ts +1 -0
  128. package/dist/test/doctor.test.js +37 -0
  129. package/dist/test/dream-skill.test.d.ts +1 -0
  130. package/dist/test/dream-skill.test.js +72 -0
  131. package/dist/test/dream.test.d.ts +1 -0
  132. package/dist/test/dream.test.js +136 -0
  133. package/dist/test/helpers/dependency-graph.d.ts +5 -0
  134. package/dist/test/helpers/dependency-graph.js +73 -0
  135. package/dist/test/helpers/extension-test-environment.d.ts +1 -0
  136. package/dist/test/helpers/extension-test-environment.js +9 -0
  137. package/dist/test/helpers/extension.d.ts +119 -0
  138. package/dist/test/helpers/extension.js +368 -0
  139. package/dist/test/helpers/notes.d.ts +6 -0
  140. package/dist/test/helpers/notes.js +13 -0
  141. package/dist/test/history.integration.test.d.ts +1 -0
  142. package/dist/test/history.integration.test.js +556 -0
  143. package/dist/test/host-neutral.test.d.ts +1 -0
  144. package/dist/test/host-neutral.test.js +300 -0
  145. package/dist/test/notes-library.test.d.ts +1 -0
  146. package/dist/test/notes-library.test.js +214 -0
  147. package/dist/test/notes.integration.test.d.ts +1 -0
  148. package/dist/test/notes.integration.test.js +497 -0
  149. package/dist/test/notes.test.d.ts +1 -0
  150. package/dist/test/notes.test.js +528 -0
  151. package/dist/test/reset-lifecycle.test.d.ts +1 -0
  152. package/dist/test/reset-lifecycle.test.js +605 -0
  153. package/docs/architecture.md +63 -0
  154. package/docs/claude-code-mod.md +9 -0
  155. package/docs/notes-library.md +74 -0
  156. package/docs/reset-lifecycle.md +75 -0
  157. package/docs/sdk-integration.md +39 -0
  158. package/docs/skills.md +30 -0
  159. package/docs/tool-results.md +88 -0
  160. package/mods/notesoup/.claude-plugin/plugin.json +8 -0
  161. package/mods/notesoup/dist/claude/helper.js +9324 -0
  162. package/mods/notesoup/hooks/hooks.json +4 -0
  163. package/mods/notesoup/hooks/register.ts +241 -0
  164. package/mods/notesoup/playbook.md +34 -0
  165. package/mods/notesoup/skills/dream/SKILL.md +12 -0
  166. package/mods/pi-context/dist/claude/helper.js +9324 -0
  167. package/package.json +89 -5
  168. package/playbook.md +34 -0
  169. package/skills/dream/SKILL.md +12 -0
  170. package/skills/memory/SKILL.md +59 -0
  171. package/src/boot/render.ts +115 -0
  172. package/src/boot/snapshot.ts +46 -0
  173. package/src/boot/text.ts +66 -0
  174. package/src/budget/constants.ts +9 -0
  175. package/src/budget/policy.ts +36 -0
  176. package/src/budget/text.ts +11 -0
  177. package/src/claude/helper.ts +94 -0
  178. package/src/dream/doctor.ts +117 -0
  179. package/src/dream/gates.ts +26 -0
  180. package/src/dream/git.ts +73 -0
  181. package/src/dream/jail.ts +62 -0
  182. package/src/dream/lock.ts +82 -0
  183. package/src/dream/playbook.ts +3 -0
  184. package/src/dream/report.ts +36 -0
  185. package/src/dream/result.ts +2 -0
  186. package/src/dream/settings.ts +16 -0
  187. package/src/history/history.ts +270 -0
  188. package/src/history/query.ts +147 -0
  189. package/src/index.ts +1 -0
  190. package/src/notes/address.ts +110 -0
  191. package/src/notes/constants.ts +3 -0
  192. package/src/notes/errors.ts +15 -0
  193. package/src/notes/frontmatter.ts +166 -0
  194. package/src/notes/fs-error.ts +5 -0
  195. package/src/notes/identity.ts +40 -0
  196. package/src/notes/index.ts +24 -0
  197. package/src/notes/paths.ts +109 -0
  198. package/src/notes/store.ts +497 -0
  199. package/src/pi/boot.ts +88 -0
  200. package/src/pi/budget.ts +178 -0
  201. package/src/pi/dream/cli.ts +92 -0
  202. package/src/pi/dream/runner.ts +91 -0
  203. package/src/pi/dream/settings.ts +17 -0
  204. package/src/pi/entries.ts +7 -0
  205. package/src/pi/estimate.ts +116 -0
  206. package/src/pi/extension.ts +27 -0
  207. package/src/pi/history-tools.ts +12 -0
  208. package/src/pi/history.ts +162 -0
  209. package/src/pi/notes/adapter.ts +33 -0
  210. package/src/pi/notes/tools.ts +18 -0
  211. package/src/pi/reset/artifacts.ts +100 -0
  212. package/src/pi/reset/committed.ts +26 -0
  213. package/src/pi/reset/lifecycle.ts +342 -0
  214. package/src/pi/reset/text.ts +10 -0
  215. package/src/pi/runtime.ts +200 -0
  216. package/src/pi/session-reader.ts +6 -0
  217. package/src/pi/thresholds.ts +50 -0
  218. package/src/pi/tool-names.ts +13 -0
  219. package/src/pi/tool-result.ts +41 -0
  220. package/src/pi/window.ts +133 -0
  221. package/src/settings.ts +22 -0
  222. package/src/text-match.ts +14 -0
  223. package/src/tools/history.ts +273 -0
  224. package/src/tools/notes.ts +394 -0
  225. package/src/tools/output.ts +41 -0
  226. package/src/tools/result.ts +169 -0
  227. package/src/tools/schema.ts +31 -0
@@ -0,0 +1,151 @@
1
+ /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
+ import { Type, type Static } from "typebox";
3
+ /** 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 type HistoryRole = Static<typeof HistoryRoleSchema>;
6
+ /** 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 type ToolCallStatus = Static<typeof ToolCallStatusSchema>;
9
+ /** Internal recorded facts, not a second copy in the public read schema. */
10
+ export type NestedCallRecord = {
11
+ id: string;
12
+ name: string;
13
+ arguments?: Record<string, unknown>;
14
+ argumentsBytes?: number;
15
+ status: ToolCallStatus;
16
+ durationMs?: number;
17
+ error?: string;
18
+ };
19
+ export type RecordedNestedCalls = {
20
+ calls: NestedCallRecord[];
21
+ complete: boolean;
22
+ };
23
+ export type ToolExecutionFacts = {
24
+ name: string;
25
+ status: ToolCallStatus;
26
+ arguments?: Record<string, unknown>;
27
+ outputTruncated?: boolean;
28
+ fullOutputPath?: string;
29
+ nestedCalls?: RecordedNestedCalls;
30
+ };
31
+ /** One projection event: its facts, and the document they render to. */
32
+ export type HistoryEvent = {
33
+ seq: number;
34
+ windowId: string;
35
+ role: HistoryRole;
36
+ createdAt: string | undefined;
37
+ /** Message body for user/assistant/context; the run's output for a tool event. */
38
+ text: string;
39
+ /** Whole recorded facts, rendered by eventDocument. */
40
+ execution?: ToolExecutionFacts;
41
+ };
42
+ export type HistoryWindow = {
43
+ windowId: string;
44
+ createdAt?: string;
45
+ items: HistoryEvent[];
46
+ };
47
+ /** Paired result seqs stay on the branch but redirect readers to the call's event. */
48
+ export type HistoryProjection = {
49
+ windows: HistoryWindow[];
50
+ highestSeq: number;
51
+ branchSeqs: Set<number>;
52
+ pairedResults: Map<number, number>;
53
+ };
54
+ export type HistoryFilter = {
55
+ window_id?: string | null;
56
+ roles?: HistoryRole[] | null;
57
+ };
58
+ /** Native entries after the adapter allocates seqs and selects the active branch. */
59
+ export type DecodedHistoryItem = {
60
+ seq: number;
61
+ windowId: string;
62
+ role: "user" | "assistant" | "tool_call" | "tool" | "system" | "developer";
63
+ /** Message body; for a tool call or result, the arguments or output text respectively. */
64
+ text: string;
65
+ createdAt?: string;
66
+ toolName?: string;
67
+ /** Internal pairing key; never serialized. */
68
+ toolCallId?: string;
69
+ /** The recorded arguments object, exactly as the host stored it. */
70
+ arguments?: Record<string, unknown>;
71
+ outputTruncated?: boolean;
72
+ fullOutputPath?: string;
73
+ /** The run reported an error. */
74
+ toolError?: boolean;
75
+ /** Native outcome for a standalone run (e.g. bash exit status). */
76
+ recordedStatus?: ToolCallStatus;
77
+ /** toolResult only: the calls this run made to other tools. */
78
+ nestedCalls?: RecordedNestedCalls;
79
+ };
80
+ export type DecodedHistoryWindow = {
81
+ windowId: string;
82
+ createdAt?: string;
83
+ items: DecodedHistoryItem[];
84
+ };
85
+ export declare function contentText(content: unknown): string;
86
+ /** Canonical searchable/readable text, without UI headers or continuation footers. */
87
+ export declare function historyDocument(event: HistoryEvent): string;
88
+ /** Memoized `historyDocument`: search, preview, and read must agree on the same characters. */
89
+ export declare function eventDocument(event: HistoryEvent): string;
90
+ /** Pair results into call events; consumed result seqs are not alternate read addresses. */
91
+ export declare function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: number, branchSeqs: Set<number>): HistoryProjection;
92
+ /** Summary shared by list, search and read. Full arguments/calls are in the document. */
93
+ export declare const NestedCallSummarySchema: Type.TObject<{
94
+ call_count: Type.TInteger;
95
+ complete: Type.TBoolean;
96
+ }>;
97
+ export declare const ToolSummarySchema: Type.TObject<{
98
+ tool: Type.TOptional<Type.TString>;
99
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
100
+ output_truncated: Type.TOptional<Type.TBoolean>;
101
+ full_output_path: Type.TOptional<Type.TString>;
102
+ nested_calls: Type.TOptional<Type.TObject<{
103
+ call_count: Type.TInteger;
104
+ complete: Type.TBoolean;
105
+ }>>;
106
+ }>;
107
+ export declare function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema>;
108
+ /** Stable identity and a verbatim preview, starting at the search match when present. */
109
+ export declare const HistoryPageItemSchema: Type.TObject<{
110
+ tool_name_omitted: Type.TOptional<Type.TBoolean>;
111
+ truncated: Type.TBoolean;
112
+ total_chars: Type.TInteger;
113
+ content: Type.TString;
114
+ offset_chars: Type.TOptional<Type.TInteger>;
115
+ tool: Type.TOptional<Type.TString>;
116
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
117
+ output_truncated: Type.TOptional<Type.TBoolean>;
118
+ full_output_path: Type.TOptional<Type.TString>;
119
+ nested_calls: Type.TOptional<Type.TObject<{
120
+ call_count: Type.TInteger;
121
+ complete: Type.TBoolean;
122
+ }>>;
123
+ seq: Type.TInteger;
124
+ window_id: Type.TString;
125
+ role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
126
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
127
+ }>;
128
+ export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
129
+ /** A run of tool/context events the conversation view replaces with counts. */
130
+ export declare const HistoryFoldedRowSchema: Type.TObject<{
131
+ folded: Type.TLiteral<true>;
132
+ first_seq: Type.TInteger;
133
+ last_seq: Type.TInteger;
134
+ count: Type.TInteger;
135
+ tools: Type.TRecord<"^.*$", Type.TInteger>;
136
+ omitted_tools: Type.TOptional<Type.TInteger>;
137
+ }>;
138
+ export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
139
+ /** Bound fold summaries while preserving exact counts in count/omitted_tools. */
140
+ export declare const MAX_FOLD_TOOL_NAMES = 20;
141
+ /** Longest tool name a fold row lists; longer names are counted in `omitted_tools` instead. */
142
+ export declare const MAX_FOLD_TOOL_NAME_CHARS = 120;
143
+ /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
144
+ export declare function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem;
145
+ export declare function allItems(projection: HistoryProjection): HistoryEvent[];
146
+ export declare function unknownWindowId(projection: HistoryProjection, params: HistoryFilter): {
147
+ message: string;
148
+ known: string[];
149
+ } | undefined;
150
+ /** Default list is a conversation; explicit roles and search show the requested events. */
151
+ export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter, mode: "list" | "search"): HistoryEvent[];
@@ -0,0 +1,195 @@
1
+ /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
+ import { Type } from "typebox";
3
+ /** 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")]);
5
+ /** 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")]);
7
+ function isTextContent(part) {
8
+ return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
9
+ }
10
+ export function contentText(content) {
11
+ if (typeof content === "string")
12
+ return content;
13
+ return Array.isArray(content) ? content.filter(isTextContent).map((part) => part.text).join("\n") : "";
14
+ }
15
+ function argumentText(execution) {
16
+ return execution.arguments === undefined ? "(arguments not recorded)" : JSON.stringify(execution.arguments);
17
+ }
18
+ function nestedCallLine(call) {
19
+ const parts = [`${call.id} ${call.name} [${call.status}]`];
20
+ if (call.durationMs !== undefined)
21
+ parts.push(`${call.durationMs}ms`);
22
+ if (call.error !== undefined)
23
+ parts.push(`error: ${call.error}`);
24
+ parts.push(call.arguments === undefined ? (call.argumentsBytes === undefined ? "(arguments not recorded)" : `(arguments omitted: ${call.argumentsBytes} bytes)`) : JSON.stringify(call.arguments));
25
+ return `- ${parts.join(" ")}`;
26
+ }
27
+ /** Canonical searchable/readable text, without UI headers or continuation footers. */
28
+ export function historyDocument(event) {
29
+ if (event.execution === undefined)
30
+ return event.text;
31
+ const sections = [`${event.execution.name} ${argumentText(event.execution)}`];
32
+ // An unfinished call has no recorded output at all, and saying so by omission is truthful.
33
+ if (event.text !== "")
34
+ sections.push(`--- output ---\n${event.text}`);
35
+ const nested = event.execution.nestedCalls;
36
+ if (nested !== undefined) {
37
+ const header = nested.complete ? "complete" : "incomplete";
38
+ sections.push(`--- nested calls (${header}, ${nested.calls.length} recorded) ---\n${nested.calls.map(nestedCallLine).join("\n")}`);
39
+ }
40
+ return sections.join("\n");
41
+ }
42
+ const documents = new WeakMap();
43
+ /** Memoized `historyDocument`: search, preview, and read must agree on the same characters. */
44
+ export function eventDocument(event) {
45
+ const cached = documents.get(event);
46
+ if (cached !== undefined)
47
+ return cached;
48
+ const text = historyDocument(event);
49
+ documents.set(event, text);
50
+ return text;
51
+ }
52
+ /** Pair a call with its result, or preserve a standalone run's recorded outcome. */
53
+ function toolEvent(item, result) {
54
+ const run = result ?? item;
55
+ // Only a call without a result is unfinished; standalone results carry their own outcome.
56
+ const status = item.role === "tool_call" && result === undefined
57
+ ? "unfinished"
58
+ : run.recordedStatus ?? (run.toolError === true ? "error" : "ok");
59
+ const truncated = run.outputTruncated === true;
60
+ return {
61
+ seq: item.seq,
62
+ windowId: item.windowId,
63
+ role: "tool",
64
+ text: result?.text ?? (item.role === "tool" ? item.text : ""),
65
+ createdAt: item.createdAt,
66
+ execution: {
67
+ name: item.toolName ?? "unknown",
68
+ status,
69
+ // A call records its arguments; a bare result records none, and gets none invented.
70
+ ...(item.arguments === undefined ? {} : { arguments: item.arguments }),
71
+ ...(truncated ? { outputTruncated: true, ...(run.fullOutputPath ? { fullOutputPath: run.fullOutputPath } : {}) } : {}),
72
+ ...(run.nestedCalls ? { nestedCalls: run.nestedCalls } : {}),
73
+ },
74
+ };
75
+ }
76
+ /** Pair results into call events; consumed result seqs are not alternate read addresses. */
77
+ export function projectHistory(rawWindows, highestSeq, branchSeqs) {
78
+ const raw = rawWindows.flatMap((current) => current.items);
79
+ const resultsById = new Map();
80
+ for (const item of raw) {
81
+ if (item.role === "tool" && item.toolCallId && !resultsById.has(item.toolCallId))
82
+ resultsById.set(item.toolCallId, item);
83
+ }
84
+ const pairedResults = new Map();
85
+ const consumed = new Set();
86
+ const windows = rawWindows.map((current) => ({
87
+ windowId: current.windowId,
88
+ ...(current.createdAt ? { createdAt: current.createdAt } : {}),
89
+ items: current.items.flatMap((item) => {
90
+ if (consumed.has(item.seq))
91
+ return [];
92
+ if (item.role === "tool_call") {
93
+ const result = item.toolCallId ? resultsById.get(item.toolCallId) : undefined;
94
+ const paired = result && result.seq > item.seq && !consumed.has(result.seq) ? result : undefined;
95
+ if (paired) {
96
+ consumed.add(paired.seq);
97
+ pairedResults.set(paired.seq, item.seq);
98
+ }
99
+ return [toolEvent(item, paired)];
100
+ }
101
+ if (item.role === "tool")
102
+ return [toolEvent(item)];
103
+ return [{ seq: item.seq, windowId: item.windowId, role: item.role === "system" || item.role === "developer" ? "context" : item.role, text: item.text, createdAt: item.createdAt }];
104
+ }),
105
+ }));
106
+ return { windows, highestSeq, branchSeqs, pairedResults };
107
+ }
108
+ /** Summary shared by list, search and read. Full arguments/calls are in the document. */
109
+ export const NestedCallSummarySchema = Type.Object({
110
+ call_count: Type.Integer({ minimum: 0 }),
111
+ complete: Type.Boolean({ description: "Whether the host recorded all nested calls." }),
112
+ }, { additionalProperties: false });
113
+ export const ToolSummarySchema = Type.Object({
114
+ tool: Type.Optional(Type.String()),
115
+ tool_status: Type.Optional(ToolCallStatusSchema),
116
+ output_truncated: Type.Optional(Type.Boolean()),
117
+ full_output_path: Type.Optional(Type.String()),
118
+ nested_calls: Type.Optional(NestedCallSummarySchema),
119
+ }, { additionalProperties: false });
120
+ export function toolSummary(event) {
121
+ const execution = event.execution;
122
+ if (!execution)
123
+ return {};
124
+ return {
125
+ tool: execution.name,
126
+ tool_status: execution.status,
127
+ ...(execution.outputTruncated ? { output_truncated: true } : {}),
128
+ ...(execution.fullOutputPath ? { full_output_path: execution.fullOutputPath } : {}),
129
+ ...(execution.nestedCalls ? { nested_calls: { call_count: execution.nestedCalls.calls.length, complete: execution.nestedCalls.complete } } : {}),
130
+ };
131
+ }
132
+ /** Stable identity and a verbatim preview, starting at the search match when present. */
133
+ export const HistoryPageItemSchema = Type.Object({
134
+ seq: Type.Integer({ minimum: 1 }),
135
+ window_id: Type.String(),
136
+ role: HistoryRoleSchema,
137
+ created_at: Type.Union([Type.String(), Type.Null()]),
138
+ ...ToolSummarySchema.properties,
139
+ tool_name_omitted: Type.Optional(Type.Boolean({ description: "Name omitted to fit; read this seq." })),
140
+ truncated: Type.Boolean({ description: "Preview is partial; read this seq for more." }),
141
+ total_chars: Type.Integer({ minimum: 0 }),
142
+ content: Type.String(),
143
+ offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Search match/preview start, in code points." })),
144
+ }, { additionalProperties: false });
145
+ /** A run of tool/context events the conversation view replaces with counts. */
146
+ export const HistoryFoldedRowSchema = Type.Object({
147
+ folded: Type.Literal(true),
148
+ first_seq: Type.Integer({ minimum: 1 }),
149
+ last_seq: Type.Integer({ minimum: 1 }),
150
+ count: Type.Integer({ minimum: 1 }),
151
+ tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Counts by tool name." }),
152
+ omitted_tools: Type.Optional(Type.Integer({ minimum: 1, description: "Number of omitted tool names." })),
153
+ }, { additionalProperties: false });
154
+ /** Bound fold summaries while preserving exact counts in count/omitted_tools. */
155
+ export const MAX_FOLD_TOOL_NAMES = 20;
156
+ /** Longest tool name a fold row lists; longer names are counted in `omitted_tools` instead. */
157
+ export const MAX_FOLD_TOOL_NAME_CHARS = 120;
158
+ /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
159
+ export function visibleItem(event, maxChars, matchOffset) {
160
+ const document = eventDocument(event);
161
+ const chars = Array.from(document);
162
+ const start = matchOffset ?? 0;
163
+ const truncated = start > 0 || start + maxChars < chars.length;
164
+ return {
165
+ seq: event.seq,
166
+ window_id: event.windowId,
167
+ role: event.role,
168
+ created_at: event.createdAt ?? null,
169
+ ...toolSummary(event),
170
+ truncated,
171
+ total_chars: chars.length,
172
+ content: truncated ? chars.slice(start, start + maxChars).join("") : document,
173
+ ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
174
+ };
175
+ }
176
+ export function allItems(projection) {
177
+ return projection.windows.flatMap((current) => current.items);
178
+ }
179
+ export function unknownWindowId(projection, params) {
180
+ if (typeof params.window_id !== "string")
181
+ return undefined;
182
+ const known = projection.windows.map((current) => current.windowId);
183
+ return known.includes(params.window_id) ? undefined : { message: `unknown window_id "${params.window_id}"`, known };
184
+ }
185
+ /** Default list is a conversation; explicit roles and search show the requested events. */
186
+ export function filteredItems(projection, params, mode) {
187
+ let items = allItems(projection);
188
+ if (typeof params.window_id === "string")
189
+ items = items.filter((item) => item.windowId === params.window_id);
190
+ if (params.roles)
191
+ items = items.filter((item) => params.roles.includes(item.role));
192
+ if (!params.roles && mode === "list")
193
+ items = items.filter((item) => (item.role === "user" || item.role === "assistant") && eventDocument(item) !== "");
194
+ return items.sort((a, b) => a.seq - b.seq);
195
+ }
@@ -0,0 +1,75 @@
1
+ /** Stable-anchor paging and folding. The operation supplies the full-response budget check. */
2
+ import { Type, type Static } from "typebox";
3
+ import { type Outcome } from "../tools/result.js";
4
+ import { type HistoryEvent, type HistoryFilter, type HistoryPageItem, type HistoryProjection } from "./history.js";
5
+ type Candidate = {
6
+ event: HistoryEvent;
7
+ matchOffset?: number;
8
+ preview?: HistoryPageItem;
9
+ };
10
+ type AnchorParams = {
11
+ before?: number;
12
+ after?: number;
13
+ limit?: number;
14
+ max_chars_per_item?: number;
15
+ };
16
+ export declare const HistoryPageSchema: Type.TObject<{
17
+ items: Type.TArray<Type.TUnion<[Type.TObject<{
18
+ tool_name_omitted: Type.TOptional<Type.TBoolean>;
19
+ truncated: Type.TBoolean;
20
+ total_chars: Type.TInteger;
21
+ content: Type.TString;
22
+ offset_chars: Type.TOptional<Type.TInteger>;
23
+ tool: Type.TOptional<Type.TString>;
24
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
25
+ output_truncated: Type.TOptional<Type.TBoolean>;
26
+ full_output_path: Type.TOptional<Type.TString>;
27
+ nested_calls: Type.TOptional<Type.TObject<{
28
+ call_count: Type.TInteger;
29
+ complete: Type.TBoolean;
30
+ }>>;
31
+ seq: Type.TInteger;
32
+ window_id: Type.TString;
33
+ role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
34
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
35
+ }>, Type.TObject<{
36
+ folded: Type.TLiteral<true>;
37
+ first_seq: Type.TInteger;
38
+ last_seq: Type.TInteger;
39
+ count: Type.TInteger;
40
+ tools: Type.TRecord<"^.*$", Type.TInteger>;
41
+ omitted_tools: Type.TOptional<Type.TInteger>;
42
+ }>]>>;
43
+ older_before: Type.TUnion<[Type.TInteger, Type.TNull]>;
44
+ newer_after: Type.TUnion<[Type.TInteger, Type.TNull]>;
45
+ }>;
46
+ /** Search never returns conversation folds. */
47
+ export declare const HistorySearchPageSchema: Type.TObject<{
48
+ items: Type.TArray<Type.TObject<{
49
+ tool_name_omitted: Type.TOptional<Type.TBoolean>;
50
+ truncated: Type.TBoolean;
51
+ total_chars: Type.TInteger;
52
+ content: Type.TString;
53
+ offset_chars: Type.TOptional<Type.TInteger>;
54
+ tool: Type.TOptional<Type.TString>;
55
+ tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
56
+ output_truncated: Type.TOptional<Type.TBoolean>;
57
+ full_output_path: Type.TOptional<Type.TString>;
58
+ nested_calls: Type.TOptional<Type.TObject<{
59
+ call_count: Type.TInteger;
60
+ complete: Type.TBoolean;
61
+ }>>;
62
+ seq: Type.TInteger;
63
+ window_id: Type.TString;
64
+ role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
65
+ created_at: Type.TUnion<[Type.TString, Type.TNull]>;
66
+ }>>;
67
+ older_before: Type.TUnion<[Type.TInteger, Type.TNull]>;
68
+ newer_after: Type.TUnion<[Type.TInteger, Type.TNull]>;
69
+ }>;
70
+ /** One whole page payload, before it becomes an outcome. */
71
+ export type HistoryPage = Static<typeof HistoryPageSchema>;
72
+ export declare function isConversationView(params: HistoryFilter): boolean;
73
+ /** Grow the page in query order; shorten the first preview only when no full row fits. */
74
+ export declare function selectPage(projection: HistoryProjection, params: HistoryFilter & AnchorParams, vis: Candidate[], folds: boolean, fits: (page: HistoryPage) => boolean, maxChars: number): Outcome<HistoryPage>;
75
+ export {};
@@ -0,0 +1,143 @@
1
+ /** Stable-anchor paging and folding. The operation supplies the full-response budget check. */
2
+ import { Type } from "typebox";
3
+ import { failure, success } from "../tools/result.js";
4
+ import { prefixFit } from "../tools/output.js";
5
+ import { allItems, visibleItem, HistoryFoldedRowSchema, HistoryPageItemSchema, MAX_FOLD_TOOL_NAMES, MAX_FOLD_TOOL_NAME_CHARS } from "./history.js";
6
+ export const HistoryPageSchema = Type.Object({
7
+ items: Type.Array(Type.Union([HistoryPageItemSchema, HistoryFoldedRowSchema])),
8
+ older_before: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as before to page older." }),
9
+ newer_after: Type.Union([Type.Integer({ minimum: 1 }), Type.Null()], { description: "Pass as after to page newer." }),
10
+ }, { additionalProperties: false });
11
+ /** Search never returns conversation folds. */
12
+ export const HistorySearchPageSchema = Type.Object({
13
+ ...HistoryPageSchema.properties,
14
+ items: Type.Array(HistoryPageItemSchema),
15
+ }, { additionalProperties: false });
16
+ /** Shorten preview text first; omit an oversized tool name rather than invent a partial name. */
17
+ function truncateHistoryItem(item, fits) {
18
+ if (fits(item))
19
+ return item;
20
+ const shrinkContent = (base) => ({
21
+ ...base,
22
+ truncated: true,
23
+ content: prefixFit(base.content, (candidate) => fits({ ...base, truncated: true, content: candidate })),
24
+ });
25
+ const withContent = shrinkContent(item);
26
+ if (fits(withContent))
27
+ return withContent;
28
+ if (item.tool === undefined)
29
+ return withContent;
30
+ const { tool: _dropped, ...withoutName } = item;
31
+ const named = { ...withoutName, tool_name_omitted: true };
32
+ if (fits(named))
33
+ return named;
34
+ return shrinkContent(named);
35
+ }
36
+ function isFoldableEvent(event) {
37
+ return event.role === "tool" || event.role === "context";
38
+ }
39
+ export function isConversationView(params) {
40
+ return !params.roles;
41
+ }
42
+ /** Folded counts stay exact even when some distinct tool names must be omitted. */
43
+ function foldedRuns(events) {
44
+ if (events.length === 0)
45
+ return [];
46
+ const sorted = [...events].sort((a, b) => a.seq - b.seq);
47
+ const counts = new Map();
48
+ for (const event of sorted) {
49
+ if (event.role !== "tool")
50
+ continue;
51
+ const name = event.execution?.name ?? "unknown";
52
+ counts.set(name, (counts.get(name) ?? 0) + 1);
53
+ }
54
+ const entries = [...counts].filter(([name]) => name.length <= MAX_FOLD_TOOL_NAME_CHARS).slice(0, MAX_FOLD_TOOL_NAMES);
55
+ // fromEntries preserves __proto__ as an ordinary key without mutating the prototype.
56
+ const tools = Object.fromEntries(entries);
57
+ const omitted = counts.size - entries.length;
58
+ return [{ folded: true, first_seq: sorted[0].seq, last_seq: sorted.at(-1).seq, count: sorted.length, tools, ...(omitted > 0 ? { omitted_tools: omitted } : {}) }];
59
+ }
60
+ function pageAnchors(vis, selected, before, after) {
61
+ if (selected.length === 0)
62
+ return { older_before: null, newer_after: null };
63
+ const lower = after ?? 0;
64
+ const upper = before ?? Number.POSITIVE_INFINITY;
65
+ // Selected events are in seq order.
66
+ const first = selected[0].seq;
67
+ const last = selected.at(-1).seq;
68
+ return {
69
+ older_before: vis.some((event) => event.seq > lower && event.seq < first && event.seq < upper) ? first : null,
70
+ newer_after: vis.some((event) => event.seq > last && event.seq < upper && event.seq > lower) ? last : null,
71
+ };
72
+ }
73
+ function foldRows(projection, params, selected, anchors) {
74
+ const lower = params.after ?? 0;
75
+ const upper = params.before ?? Number.POSITIVE_INFINITY;
76
+ if (selected.length === 0) {
77
+ // Even a range with no conversation can contain tool/context events.
78
+ const hidden = allItems(projection).filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper && isFoldableEvent(event));
79
+ return foldedRuns(hidden);
80
+ }
81
+ const windowEvents = allItems(projection)
82
+ .filter((event) => (typeof params.window_id !== "string" || params.window_id === event.windowId) && event.seq > lower && event.seq < upper)
83
+ .sort((a, b) => a.seq - b.seq);
84
+ const folded = [];
85
+ const firstSeq = selected[0].seq;
86
+ const lastSeq = selected.at(-1).seq;
87
+ if (anchors.older_before === null)
88
+ folded.push(...foldedRuns(windowEvents.filter((event) => event.seq < firstSeq && isFoldableEvent(event))));
89
+ // pageData already ordered selected by seq.
90
+ for (let i = 0; i + 1 < selected.length; i++) {
91
+ const left = selected[i].seq;
92
+ const right = selected[i + 1].seq;
93
+ folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > left && event.seq < right && isFoldableEvent(event))));
94
+ }
95
+ if (anchors.newer_after === null)
96
+ folded.push(...foldedRuns(windowEvents.filter((event) => event.seq > lastSeq && isFoldableEvent(event))));
97
+ return folded;
98
+ }
99
+ function pageData(projection, params, vis, selected, maxChars, folds) {
100
+ const orderedSelected = [...selected].sort((a, b) => a.event.seq - b.event.seq);
101
+ const selectedEvents = orderedSelected.map((candidate) => candidate.event);
102
+ const anchors = pageAnchors(vis, selectedEvents, params.before, params.after);
103
+ const visible = orderedSelected.map((candidate) => candidate.preview ?? visibleItem(candidate.event, maxChars, candidate.matchOffset));
104
+ let rows = visible;
105
+ if (folds) {
106
+ const folded = foldRows(projection, params, selectedEvents, anchors);
107
+ rows = [...visible, ...folded].sort((a, b) => ("folded" in a ? a.first_seq : a.seq) - ("folded" in b ? b.first_seq : b.seq));
108
+ }
109
+ return { items: rows, ...anchors };
110
+ }
111
+ function orderedCandidates(vis, before, after, limit) {
112
+ const ascending = [...vis].sort((a, b) => a.event.seq - b.event.seq);
113
+ if (before !== undefined && after !== undefined)
114
+ return ascending.filter((candidate) => candidate.event.seq > after && candidate.event.seq < before).slice(0, limit);
115
+ if (after !== undefined)
116
+ return ascending.filter((candidate) => candidate.event.seq > after).slice(0, limit);
117
+ if (before !== undefined)
118
+ return ascending.filter((candidate) => candidate.event.seq < before).reverse().slice(0, limit);
119
+ return ascending.slice(-limit).reverse();
120
+ }
121
+ /** Grow the page in query order; shorten the first preview only when no full row fits. */
122
+ export function selectPage(projection, params, vis, folds, fits, maxChars) {
123
+ const before = params.before;
124
+ const after = params.after;
125
+ const limit = params.limit ?? 20;
126
+ const candidates = orderedCandidates(vis, before, after, limit);
127
+ const allVisible = vis.map((candidate) => candidate.event).sort((a, b) => a.seq - b.seq);
128
+ const kept = [];
129
+ for (const candidate of candidates) {
130
+ if (fits(pageData(projection, params, allVisible, [...kept, candidate], maxChars, folds))) {
131
+ kept.push(candidate);
132
+ continue;
133
+ }
134
+ if (kept.length === 0)
135
+ kept.push({ ...candidate, preview: truncateHistoryItem(visibleItem(candidate.event, maxChars, candidate.matchOffset), (preview) => fits(pageData(projection, params, allVisible, [{ ...candidate, preview }], maxChars, folds))) });
136
+ break;
137
+ }
138
+ const page = pageData(projection, params, allVisible, kept, maxChars, folds);
139
+ if (!fits(page)) {
140
+ return failure("page_too_large", `${page.items.length} history rows and their fold summary do not fit one response even at their smallest; narrow the range with before/after or read one seq`, { rows: page.items.length });
141
+ }
142
+ return success(page);
143
+ }
@@ -0,0 +1 @@
1
+ export { default, createNotesoup } from "./pi/extension.js";
@@ -0,0 +1 @@
1
+ export { default, createNotesoup } from "./pi/extension.js";
@@ -0,0 +1,31 @@
1
+ import type { NotesIdentity } from "./identity.js";
2
+ import { type Scope } from "./paths.js";
3
+ export type NoteAddress = {
4
+ scope: Scope;
5
+ path: string;
6
+ who?: string;
7
+ };
8
+ export declare const ADDRESS_FORMS = "use <path> with no @ for this session, or @project/, @human/, @self/, or @model/ followed by a path";
9
+ export declare function assertVirtualPath(value: unknown): string;
10
+ /**
11
+ * Minimal glob over virtual note paths: `*` matches any run within a segment (never
12
+ * `/`), `**` matches any run across segments (a leading double-star followed by a
13
+ * slash also matches zero segments, so it covers the root too), `?` matches exactly
14
+ * one non-`/` character. Everything else is literal and the match is anchored to the
15
+ * whole path.
16
+ */
17
+ export declare function globToRegExp(pattern: string): RegExp;
18
+ /** Glob patterns are not virtual paths (`*` is legal), so they get their own guard. */
19
+ export declare function assertGlobPattern(value: unknown): string | undefined;
20
+ /**
21
+ * Decode one public note address into its physical home and virtual path. @self and @model
22
+ * are relative; explicit agents/models addresses always name a canonical slug.
23
+ */
24
+ export declare function assertAddress(value: unknown): NoteAddress;
25
+ /** Render a virtual path in its one unambiguous address form, used to match patterns. */
26
+ export declare function canonicalAddressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string;
27
+ /**
28
+ * Render the address a caller sees. The current agent and model homes read as @self/ and
29
+ * @model/ so ordinary sessions are not taught explicit ids; only other homes (dream) name one.
30
+ */
31
+ export declare function addressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string;