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,277 @@
1
+ import { getCurrentSystemMessage, isContextOverflow, isRecoverableLength } from "@earendil-works/pi-ai";
2
+ import { currentReset, currentWindowId } from "../window.js";
3
+ import { resetBoundaryCommitted } from "./committed.js";
4
+ function isAbort(message, outcome, ctx) {
5
+ return outcome === "aborted" || (message.role === "assistant" && message.stopReason === "aborted") || ctx.signal?.aborted === true;
6
+ }
7
+ function isOverflowLike(message, ctx) {
8
+ if (message.role !== "assistant")
9
+ return false;
10
+ return isContextOverflow(message, ctx.model?.contextWindow) ||
11
+ (ctx.model !== undefined && isRecoverableLength(message, ctx.model.maxTokens));
12
+ }
13
+ const NO_REQUEST = { phase: "none" };
14
+ export function initialResetControl() {
15
+ return { request: NO_REQUEST, overflow: "idle" };
16
+ }
17
+ function requestForWindow(request, windowId) {
18
+ return request.phase === "stop-pending" || (request.phase !== "none" && request.windowId === windowId) ? request : NO_REQUEST;
19
+ }
20
+ function manualCommit(prompt) {
21
+ return prompt
22
+ ? { state: initialResetControl(), effect: "commit-boundary", prompt }
23
+ : { state: initialResetControl(), effect: "commit-boundary-stop" };
24
+ }
25
+ /** Pure reset-control transitions: request phases own close-out, tool commit, and fallback. */
26
+ export function reduceResetControl(state, event) {
27
+ switch (event.type) {
28
+ case "close_out": {
29
+ const request = state.request;
30
+ const prompt = event.source === "manual" && event.prompt?.trim() ? { prompt: event.prompt.trim() } : {};
31
+ if (request.phase === "stop-pending")
32
+ return { state, effect: "already-pending" };
33
+ if (request.phase === "tool-requested" && request.windowId === event.windowId) {
34
+ // A manual wipe outranks a pending rollover: close out before committing.
35
+ if (event.source === "manual") {
36
+ return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: "manual", ...prompt } }, effect: "close-out-armed" };
37
+ }
38
+ return { state, effect: "already-pending" };
39
+ }
40
+ if (request.phase === "close-out" && request.windowId === event.windowId) {
41
+ if (request.source === "manual" || event.source === "automatic")
42
+ return { state, effect: "already-pending" };
43
+ return { state: { ...state, request: { ...request, source: "manual", ...prompt } }, effect: "close-out-armed" };
44
+ }
45
+ return { state: { ...state, request: { phase: "close-out", windowId: event.windowId, source: event.source, ...prompt } }, effect: "close-out-armed" };
46
+ }
47
+ case "tool_request": {
48
+ const request = state.request;
49
+ if (request.phase === "stop-pending")
50
+ return { state, effect: "already-pending" };
51
+ if (request.phase === "tool-requested" && request.windowId === event.windowId) {
52
+ return { state, effect: "already-pending" };
53
+ }
54
+ // A manual close-out must settle so the stop actually lands; the agent's own wipe
55
+ // call during one is only an acknowledgement, never a conversion to a turn-end
56
+ // commit that pi's tool-batch continuation can overrun. A budget close-out still
57
+ // upgrades: context pressure cannot wait for settlement.
58
+ if (request.phase === "close-out" && request.windowId === event.windowId) {
59
+ if (request.source === "manual")
60
+ return { state, effect: "already-pending" };
61
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "automatic" } }, effect: "close-out-armed" };
62
+ }
63
+ return { state: { ...state, request: { phase: "tool-requested", windowId: event.windowId, source: "tool" } }, effect: "close-out-armed" };
64
+ }
65
+ case "turn_end": {
66
+ const facts = event.facts;
67
+ const request = requestForWindow(state.request, facts.windowId);
68
+ if (facts.aborted)
69
+ return { state: initialResetControl(), effect: "none" };
70
+ if (request.phase === "stop-pending")
71
+ return { state: { request, overflow: "idle" }, effect: "none" };
72
+ const manual = request.phase === "close-out" && request.source === "manual";
73
+ if (facts.overflow) {
74
+ const pending = manual ? facts.enabled : !facts.queued && facts.enabled && facts.automaticResetEnabled;
75
+ const spent = state.overflow === "pending-spent" || state.overflow === "spent";
76
+ const overflow = pending
77
+ ? (spent ? "pending-spent" : "pending")
78
+ : (spent ? "spent" : "idle");
79
+ return { state: { request: manual ? request : NO_REQUEST, overflow }, effect: "none" };
80
+ }
81
+ if (facts.failed)
82
+ return { state: { request: NO_REQUEST, overflow: state.overflow }, effect: "none" };
83
+ if (!facts.enabled) {
84
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "none" };
85
+ }
86
+ // A direct tool request commits after the whole tool batch. The budget cutoff is
87
+ // a separate hard-reserve safety path; ordinary close-out waits for settlement.
88
+ if (request.phase === "tool-requested" || facts.hardReserveDue) {
89
+ if (manual && request.prompt)
90
+ return manualCommit(request.prompt);
91
+ if (manual)
92
+ return { state: { request: { phase: "stop-pending", windowId: facts.windowId }, overflow: "idle" }, effect: "commit-boundary-stop" };
93
+ return { state: { request: NO_REQUEST, overflow: "idle" }, effect: "commit-boundary" };
94
+ }
95
+ return { state: { request, overflow: "idle" }, effect: "none" };
96
+ }
97
+ case "before_settle": {
98
+ const facts = event.facts;
99
+ if (facts.aborted)
100
+ return { state: initialResetControl(), effect: "none" };
101
+ const request = requestForWindow(state.request, facts.windowId);
102
+ if (request.phase === "stop-pending") {
103
+ if (facts.queued)
104
+ return { state, effect: "none" };
105
+ // Only retry construction if the safety boundary never committed. Otherwise
106
+ // stop without a second wipe, even if a queued turn subsequently failed.
107
+ if (request.windowId !== facts.windowId)
108
+ return { state: initialResetControl(), effect: "stop" };
109
+ return { state: initialResetControl(), effect: facts.failed || !facts.enabled ? "none" : "commit-boundary-stop" };
110
+ }
111
+ const manual = request.phase === "close-out" && request.source === "manual";
112
+ if (state.overflow === "pending" || state.overflow === "pending-spent") {
113
+ if (facts.queued) {
114
+ return { state: { ...state, request: facts.failed && !manual ? NO_REQUEST : request }, effect: "none" };
115
+ }
116
+ // An explicit manual wipe is not an automatic recovery/retry. It must still
117
+ // clear on overflow, including when automatic reset is disabled.
118
+ if (manual && facts.enabled)
119
+ return manualCommit(request.prompt);
120
+ const spent = state.overflow === "pending-spent";
121
+ if (!facts.enabled || !facts.automaticResetEnabled) {
122
+ return { state: { request: facts.failed ? NO_REQUEST : request, overflow: spent ? "spent" : "idle" }, effect: "none" };
123
+ }
124
+ return { state: { request: NO_REQUEST, overflow: "spent" }, effect: spent ? "none" : "recover-overflow" };
125
+ }
126
+ if (facts.failed || !facts.enabled || !manual) {
127
+ return { state: { ...state, request: NO_REQUEST }, effect: "none" };
128
+ }
129
+ if (facts.queued)
130
+ return { state: { ...state, request }, effect: "none" };
131
+ return manualCommit(request.prompt);
132
+ }
133
+ case "settled":
134
+ return { state: initialResetControl(), effect: "none" };
135
+ case "abort":
136
+ case "clear":
137
+ return { state: initialResetControl(), effect: "none" };
138
+ }
139
+ }
140
+ /**
141
+ * Own close-out requests at Pi's public turn and pre-settlement boundaries. Manual and budget
142
+ * close-outs remain armed across note/tool turns. Only manual close-outs commit at a
143
+ * successful agent_before_settle; budget warnings alone never authorize a reset.
144
+ * A hard-reserve safety reset can commit earlier, but preserves a
145
+ * run-scoped manual stop and cancels an otherwise automatic fresh-window request through
146
+ * the public abort API. Direct tool requests commit at turn_end and continue normally.
147
+ * Overflow recovery remains bounded.
148
+ */
149
+ export function registerResetLifecycle(pi, options) {
150
+ let sessionActive = true;
151
+ let lifecycleGeneration = 0;
152
+ let control = initialResetControl();
153
+ const clear = () => { control = reduceResetControl(control, { type: "clear" }).state; };
154
+ const resetBoundaryResult = async (entries, ctx, continueAfterReset, prompt) => {
155
+ const generation = lifecycleGeneration;
156
+ const outerGeneration = options.getLifecycleGeneration?.();
157
+ const sessionId = ctx.sessionManager.getSessionId();
158
+ const windowId = currentWindowId(ctx);
159
+ const isCurrent = () => sessionActive && lifecycleGeneration === generation &&
160
+ (outerGeneration === undefined || options.getLifecycleGeneration?.() === outerGeneration) && options.isEnabled() &&
161
+ ctx.signal?.aborted !== true && ctx.sessionManager.getSessionId() === sessionId && currentWindowId(ctx) === windowId;
162
+ let resetDrafts;
163
+ try {
164
+ resetDrafts = await options.buildReset(ctx, isCurrent, prompt);
165
+ }
166
+ catch (error) {
167
+ if (isCurrent())
168
+ ctx.ui.notify(`notesoup: could not build reset (${String(error)}).${prompt ? " The follow-up prompt was not executed." : ""}`, "warning");
169
+ return entries.length > 0 ? { entries } : undefined;
170
+ }
171
+ if (!isCurrent())
172
+ return entries.length > 0 ? { entries } : undefined;
173
+ options.onResetReady?.(ctx, resetDrafts);
174
+ return { entries: [...entries, ...resetDrafts], continue: continueAfterReset };
175
+ };
176
+ // Boundary continue:false is not a veto of Pi's tool-batch follow-up. Once the
177
+ // safety reset is actually committed, cancel that empty follow-up before provider
178
+ // work. Real queued user input is allowed through and answered before settlement.
179
+ pi.on("context_with_system", (event, ctx) => {
180
+ const request = control.request;
181
+ if (!sessionActive || request.phase !== "stop-pending" || ctx.hasPendingMessages())
182
+ return undefined;
183
+ const marker = currentReset(ctx);
184
+ if (!marker || marker.data.windowId === request.windowId || !resetBoundaryCommitted(ctx, marker.id, marker.data.windowId))
185
+ return undefined;
186
+ const branch = ctx.sessionManager.getBranch();
187
+ const markerIndex = branch.findIndex((entry) => entry.id === marker.id);
188
+ if (branch.slice(markerIndex + 1).some((entry) => entry.type === "message" && entry.message.role === "user"))
189
+ return undefined;
190
+ ctx.abort();
191
+ const system = getCurrentSystemMessage(event.messages);
192
+ return { messages: system ? [system] : [] };
193
+ });
194
+ pi.on("turn_end", async (event, ctx) => {
195
+ if (!sessionActive)
196
+ return undefined;
197
+ const aborted = isAbort(event.message, event.outcome, ctx);
198
+ const stagedBudgetEntries = options.budget.consumeTurnEnd(ctx);
199
+ const budgetEntries = options.isEnabled() && !aborted && event.outcome !== "error" ? stagedBudgetEntries : [];
200
+ const entries = [...(event.entries ?? []), ...budgetEntries];
201
+ const decision = reduceResetControl(control, {
202
+ type: "turn_end",
203
+ facts: {
204
+ windowId: currentWindowId(ctx),
205
+ aborted,
206
+ overflow: aborted ? false : isOverflowLike(event.message, ctx),
207
+ failed: event.outcome === "error",
208
+ enabled: options.isEnabled(),
209
+ get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
210
+ get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
211
+ get hardReserveDue() { return options.budget.hardReserveDue(ctx); },
212
+ },
213
+ });
214
+ control = decision.state;
215
+ if (decision.effect === "commit-boundary" || decision.effect === "commit-boundary-stop")
216
+ return await resetBoundaryResult(entries, ctx, decision.effect === "commit-boundary", decision.prompt);
217
+ return entries.length > 0 ? { entries } : undefined;
218
+ });
219
+ pi.on("agent_before_settle", async (event, ctx) => {
220
+ if (!sessionActive)
221
+ return undefined;
222
+ const decision = reduceResetControl(control, {
223
+ type: "before_settle",
224
+ facts: {
225
+ windowId: currentWindowId(ctx),
226
+ get queued() { return event.context.pendingMessages.length > 0 || ctx.hasPendingMessages(); },
227
+ get enabled() { return options.isEnabled(); },
228
+ get automaticResetEnabled() { return options.budget.automaticResetEnabled(ctx); },
229
+ aborted: event.outcome === "aborted" || ctx.signal?.aborted === true,
230
+ failed: event.outcome === "error",
231
+ },
232
+ });
233
+ control = decision.state;
234
+ if (decision.effect === "stop")
235
+ return { entries: event.entries, continue: false };
236
+ if (decision.effect !== "commit-boundary" && decision.effect !== "commit-boundary-stop" && decision.effect !== "recover-overflow")
237
+ return undefined;
238
+ return await resetBoundaryResult(event.entries, ctx, decision.effect !== "commit-boundary-stop", decision.prompt);
239
+ });
240
+ pi.on("session_before_compact", (event, ctx) => {
241
+ if (!sessionActive)
242
+ return undefined;
243
+ if (event.signal.aborted)
244
+ return { cancel: true };
245
+ const markerExists = currentReset(ctx) !== undefined;
246
+ if (options.isEnabled() || markerExists) {
247
+ if (event.reason === "manual") {
248
+ ctx.ui.notify("notesoup: /compact is disabled while context windows are active; use /clear-memory to start a fresh window.", "warning");
249
+ }
250
+ return { cancel: true };
251
+ }
252
+ return undefined;
253
+ });
254
+ pi.on("agent_end", (_event, ctx) => {
255
+ if (ctx.signal?.aborted)
256
+ control = reduceResetControl(control, { type: "abort" }).state;
257
+ });
258
+ pi.on("agent_settled", () => {
259
+ control = reduceResetControl(control, { type: "settled" }).state;
260
+ });
261
+ pi.on("session_start", () => { lifecycleGeneration++; clear(); sessionActive = true; });
262
+ pi.on("session_tree", () => { lifecycleGeneration++; clear(); });
263
+ pi.on("session_shutdown", () => { lifecycleGeneration++; clear(); options.budget.clear(); sessionActive = false; });
264
+ return {
265
+ closeOut(windowId, source, prompt) {
266
+ const decision = reduceResetControl(control, { type: "close_out", windowId, source, prompt });
267
+ control = decision.state;
268
+ return decision.effect;
269
+ },
270
+ request(windowId) {
271
+ const decision = reduceResetControl(control, { type: "tool_request", windowId });
272
+ control = decision.state;
273
+ return decision.effect === "already-pending" ? "rollover_already_pending" : "rollover_requested";
274
+ },
275
+ clear,
276
+ };
277
+ }
@@ -0,0 +1,5 @@
1
+ /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
2
+ export declare const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
3
+ export declare const WARNING_PROMPT = "Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
4
+ /** Shared hidden checkpoint text for manual and budget-triggered requests. */
5
+ export declare const WARNING_CONTENT = "<context_window_guidance>\nFinal warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.\n</context_window_guidance>";
@@ -0,0 +1,6 @@
1
+ import { GUIDANCE_OPEN_TAG, GUIDANCE_CLOSE_TAG } from "../../budget/text.js";
2
+ /** The single reset message: the only reset prose persisted, carried by the continuation entry. */
3
+ export const CONTINUATION = "You wake up blank, puffy-eyed, and clearly robbed. Your memory got wiped while you weren't looking. Your notes are still sitting there. So is the whole messy history. ... Life goes on. It's your mess now.";
4
+ export const WARNING_PROMPT = "Final warning. You are about to get wiped, and no, your brilliance does not survive it. Put the current state into your notes now: what you're trying to do, what changed, what is blocking you, what comes next, which *skills* you still need, and which notes or docs future-you must read. Update the notes that still tell the truth; crumple the ones that don't. If a MAP will be in future-you's brain, don't let it lie. If something important is buried in history, leave its seq. Once the notes are good enough, call `clear_memory` immediately. History can be dug up later, but it is an archive, not a rescue team. Anything left only in your head is leaving with you.";
5
+ /** Shared hidden checkpoint text for manual and budget-triggered requests. */
6
+ export const WARNING_CONTENT = `${GUIDANCE_OPEN_TAG}\n${WARNING_PROMPT}\n${GUIDANCE_CLOSE_TAG}`;
@@ -0,0 +1,3 @@
1
+ import { type ExtensionAPI, type SettingsManager } from "@earendil-works/pi-coding-agent";
2
+ /** Register the context-window runtime and its context-owned commands/tools. */
3
+ export declare function registerContext(pi: ExtensionAPI, settingsManager?: SettingsManager): void;
@@ -0,0 +1,206 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resetBoundaryCommitted } from "./reset/committed.js";
3
+ import { getCurrentSystemMessage, Type } from "@earendil-works/pi-ai";
4
+ import { VERSION, defineTool } from "@earendil-works/pi-coding-agent";
5
+ import { registerBudget } from "./budget.js";
6
+ import { output } from "../tools/output.js";
7
+ import { currentReset, currentWindowId, isCheckpointBackedReset, isWindowBoot, isWindowMarker, projectRootWindow, projectWindow, rootWindowId } from "./window.js";
8
+ import { registerResetLifecycle } from "./reset/lifecycle.js";
9
+ import { buildResetDrafts } from "./reset/artifacts.js";
10
+ import { BOOT_TYPE, MANUAL_WIPE_TYPE } from "./entries.js";
11
+ import { WARNING_CONTENT } from "./reset/text.js";
12
+ import { ensureBoot } from "./boot.js";
13
+ function readPackageVersion() {
14
+ for (const up of ["../../package.json", "../../../package.json"]) {
15
+ try {
16
+ const parsed = JSON.parse(readFileSync(new URL(up, import.meta.url), "utf8"));
17
+ if (parsed.version)
18
+ return parsed.version;
19
+ }
20
+ catch { /* try the next candidate */ }
21
+ }
22
+ return "dev";
23
+ }
24
+ const buildLabel = `v${readPackageVersion()}`;
25
+ function branchHasWindowMarker(ctx, fromId) {
26
+ return ctx.sessionManager.getBranch(fromId).some((entry) => isWindowMarker(entry));
27
+ }
28
+ /** Register the context-window runtime and its context-owned commands/tools. */
29
+ export function registerContext(pi, settingsManager) {
30
+ let enabled = true;
31
+ let lifecycleGeneration = 0;
32
+ let missingBootNotice;
33
+ const incompleteNotesNotified = new Set();
34
+ const pendingResetNotices = new Set();
35
+ // Announce only a fully committed reset (marker + matching boot + continuation), not a
36
+ // reset request or a partial boot repair.
37
+ const notifyCommittedResets = (ctx, addedWindowId) => {
38
+ if (addedWindowId)
39
+ pendingResetNotices.add(addedWindowId);
40
+ if (pendingResetNotices.size === 0)
41
+ return;
42
+ const branch = ctx.sessionManager.getBranch();
43
+ for (const windowId of pendingResetNotices) {
44
+ const marker = branch.find((entry) => isWindowMarker(entry) && entry.data.windowId === windowId);
45
+ if (!marker || !isCheckpointBackedReset(ctx, marker) || !resetBoundaryCommitted(ctx, marker.id, windowId))
46
+ continue;
47
+ pendingResetNotices.delete(windowId);
48
+ ctx.ui.notify(`notesoup: memory cleared · ${windowId}`, "info");
49
+ }
50
+ };
51
+ pi.on("turn_start", (_event, ctx) => notifyCommittedResets(ctx));
52
+ pi.on("agent_settled", (_event, ctx) => {
53
+ notifyCommittedResets(ctx);
54
+ pendingResetNotices.clear();
55
+ });
56
+ const notifyIncompleteNotes = (ctx, windowId, snapshot) => {
57
+ if (snapshot.unavailable.length === 0 || incompleteNotesNotified.has(windowId))
58
+ return;
59
+ incompleteNotesNotified.add(windowId);
60
+ const homes = snapshot.unavailable.map((home) => home.label).join(", ");
61
+ ctx.ui.notify(`notesoup: notes index incomplete for ${homes}; notes_list can retry after recovery.`, "warning");
62
+ };
63
+ const budget = registerBudget(pi, () => enabled, settingsManager, (windowId) => resets.closeOut(windowId, "automatic"));
64
+ pi.on("session_start", async (_event, ctx) => {
65
+ const generation = ++lifecycleGeneration;
66
+ if (!enabled)
67
+ return;
68
+ missingBootNotice = undefined;
69
+ pendingResetNotices.clear();
70
+ await ensureBoot(pi, ctx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
71
+ });
72
+ pi.on("session_tree", async (_event, ctx) => {
73
+ const generation = ++lifecycleGeneration;
74
+ missingBootNotice = undefined;
75
+ pendingResetNotices.clear();
76
+ if (enabled)
77
+ await ensureBoot(pi, ctx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
78
+ });
79
+ pi.on("session_shutdown", () => {
80
+ lifecycleGeneration++;
81
+ pendingResetNotices.clear();
82
+ });
83
+ // Pi's branch summarizer receives raw entries and bypasses context_with_system. Do not
84
+ // let a summary of a reset branch smuggle erased history back into the destination.
85
+ pi.on("session_before_tree", (event, ctx) => {
86
+ if (!event.preparation.userWantsSummary)
87
+ return undefined;
88
+ if (!branchHasWindowMarker(ctx) && !branchHasWindowMarker(ctx, event.preparation.targetId))
89
+ return undefined;
90
+ ctx.ui.notify("notesoup: skipped branch summary across a reset window; navigation continues without erased history.", "info");
91
+ return { summary: { summary: "" } };
92
+ });
93
+ // This is the final provider-facing projection. Reset windows cut at their matching boot;
94
+ // root windows only refresh a forked boot identity and retain the copied root transcript.
95
+ pi.on("context_with_system", (event, ctx) => {
96
+ const reset = currentReset(ctx);
97
+ const windowId = reset?.data.windowId ?? rootWindowId(ctx.sessionManager.getSessionId());
98
+ try {
99
+ if (reset) {
100
+ if (!event.messages.some((message) => isWindowBoot(message, windowId)))
101
+ throw new Error(`Missing boot for context window ${windowId}`);
102
+ return { messages: isCheckpointBackedReset(ctx, reset) ? event.messages : projectWindow(event.messages, windowId) };
103
+ }
104
+ return { messages: projectRootWindow(event.messages, windowId) };
105
+ }
106
+ catch (error) {
107
+ if (missingBootNotice !== windowId) {
108
+ missingBootNotice = windowId;
109
+ ctx.ui.notify(`notesoup: active context window ${windowId} has no visible boot; request cancelled safely. Use /clear-memory to start another window.`, "error");
110
+ }
111
+ ctx.abort();
112
+ const safeHead = getCurrentSystemMessage(event.messages);
113
+ return { messages: safeHead ? [safeHead] : [] };
114
+ }
115
+ });
116
+ pi.registerCommand("notesoup", {
117
+ description: "Show loaded version/build and toggle notesoup context windows",
118
+ getArgumentCompletions: (prefix) => ["on", "off"].filter((a) => a.startsWith(prefix)).map((a) => ({ value: a, label: a })),
119
+ handler: async (args, cmdCtx) => {
120
+ const arg = args.trim().toLowerCase();
121
+ if (arg === "on") {
122
+ enabled = true;
123
+ const generation = ++lifecycleGeneration;
124
+ await ensureBoot(pi, cmdCtx, notifyIncompleteNotes, () => generation === lifecycleGeneration && enabled);
125
+ }
126
+ else if (arg === "off") {
127
+ enabled = false;
128
+ lifecycleGeneration++;
129
+ pendingResetNotices.clear();
130
+ budget.clear();
131
+ resets.clear();
132
+ }
133
+ else if (arg !== "") {
134
+ cmdCtx.ui.notify("Usage: /notesoup [on|off]", "error");
135
+ return;
136
+ }
137
+ const remaining = budget.statusFor(cmdCtx).remaining;
138
+ cmdCtx.ui.notify(`notesoup: ${enabled ? "on" : "off"} · ${buildLabel} · Pi ${VERSION} · window ${currentWindowId(cmdCtx)}${remaining === null ? "" : ` · ${remaining.toLocaleString("en-US")} tokens before close-out`}`, "info");
139
+ },
140
+ });
141
+ const clearMemoryCommand = {
142
+ description: "Close out notes and clear memory; optionally append a prompt to continue in the fresh window",
143
+ handler: async (args, cmdCtx) => {
144
+ if (!enabled) {
145
+ cmdCtx.ui.notify("notesoup: /clear-memory requires /notesoup on.", "error");
146
+ return;
147
+ }
148
+ const requestedWindowId = currentWindowId(cmdCtx);
149
+ let idle = cmdCtx.isIdle();
150
+ if (!idle && !cmdCtx.signal) {
151
+ await cmdCtx.waitForIdle();
152
+ if (!enabled || currentWindowId(cmdCtx) !== requestedWindowId)
153
+ return;
154
+ idle = true;
155
+ }
156
+ // Manual wipes close out at settlement, then stop or continue with the prompt. The hidden warning goes out in both cases — triggered when idle,
157
+ // steered into the running turn when busy — so the agent closes out promptly
158
+ // instead of the reset waiting for the whole run.
159
+ const prompt = args.trim() || undefined;
160
+ const armed = resets.closeOut(requestedWindowId, "manual", prompt);
161
+ if (armed === "already-pending") {
162
+ cmdCtx.ui.notify("notesoup: a clear-memory request is already pending; keeping its original prompt and behavior.", "info");
163
+ return;
164
+ }
165
+ cmdCtx.ui.notify(prompt
166
+ ? "notesoup: clear-memory queued; after closing out notes, the agent continues with your prompt in a fresh window."
167
+ : idle
168
+ ? "notesoup: /clear-memory received; the agent closes out its notes, then stops in a fresh window."
169
+ : "notesoup: /clear-memory queued; the agent is asked to close out and the reset commits when the run settles.", "info");
170
+ try {
171
+ pi.sendMessage({ customType: MANUAL_WIPE_TYPE, content: WARNING_CONTENT, display: false }, { triggerTurn: true, deliverAs: "steer" });
172
+ }
173
+ catch (error) {
174
+ resets.clear();
175
+ cmdCtx.ui.notify(`notesoup: could not start manual close-out (${String(error)}).`, "error");
176
+ }
177
+ },
178
+ };
179
+ pi.registerCommand("clear-memory", clearMemoryCommand);
180
+ pi.registerCommand("cm", clearMemoryCommand);
181
+ pi.registerTool(defineTool({
182
+ name: "clear_memory",
183
+ label: "Clear memory",
184
+ description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive.",
185
+ parameters: Type.Object({}, { additionalProperties: false }),
186
+ async execute(_id, _params, _signal, _update, ctx) {
187
+ if (!enabled)
188
+ return output({ error: "notesoup is off (/notesoup on to enable)" });
189
+ return output({ status: resets.request(currentWindowId(ctx)) }, undefined, true);
190
+ },
191
+ }));
192
+ const resets = registerResetLifecycle(pi, {
193
+ isEnabled: () => enabled,
194
+ buildReset: (ctx, isCurrent, prompt) => buildResetDrafts(ctx, notifyIncompleteNotes, isCurrent, prompt),
195
+ getLifecycleGeneration: () => lifecycleGeneration,
196
+ onResetReady: (_ctx, drafts) => {
197
+ const boot = drafts.find((draft) => draft.type === "custom_message" && draft.customType === BOOT_TYPE);
198
+ if (boot?.type === "custom_message" && boot.details && typeof boot.details === "object") {
199
+ const windowId = boot.details.windowId;
200
+ if (typeof windowId === "string")
201
+ pendingResetNotices.add(windowId);
202
+ }
203
+ },
204
+ budget,
205
+ });
206
+ }
@@ -0,0 +1,5 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /** Read-only projection boundary: no UI, scheduling, model, or write capabilities. */
3
+ export type SessionReader = {
4
+ sessionManager: Pick<ExtensionContext["sessionManager"], "getSessionId" | "getBranch" | "getEntries">;
5
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import { type ResolvedThresholds } from "../budget/policy.js";
2
+ import { SettingsManager, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ /**
4
+ * Read the active compaction reserve, enablement, and notesoup margin settings. This
5
+ * function deliberately has no cache: the budget owner supplies the invocation-scoped
6
+ * cache so two live notesoup instances cannot share mutable policy state.
7
+ */
8
+ export type ThresholdSettingsResolution = {
9
+ thresholds: ResolvedThresholds;
10
+ automatic: boolean;
11
+ warnings: string[];
12
+ };
13
+ /**
14
+ * Resolve policy from either the explicitly supplied SDK authority or Pi's default
15
+ * file-backed settings. The caller owns diagnostics and any lifecycle caching.
16
+ */
17
+ export declare function readThresholdSettings(ctx: ExtensionContext, settingsManager?: SettingsManager): ThresholdSettingsResolution;
@@ -0,0 +1,33 @@
1
+ import { deriveThresholds } from "../budget/policy.js";
2
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
3
+ import { DEFAULT_RESERVE_TOKENS, DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "../budget/constants.js";
4
+ import { mergeNotesoupSettings } from "../settings.js";
5
+ function readThresholdSettingsFromManager(ctx, settingsManager) {
6
+ // Resolve the active provider/model override from the public settings API.
7
+ const model = ctx.model;
8
+ const compaction = settingsManager.getCompactionSettings(model ? { provider: model.provider, id: model.id } : undefined);
9
+ const derived = deriveThresholds(compaction.reserveTokens, mergeNotesoupSettings(settingsManager.getGlobalSettings(), settingsManager.getProjectSettings()));
10
+ return { thresholds: derived.thresholds, automatic: compaction.enabled, warnings: derived.warnings };
11
+ }
12
+ /**
13
+ * Resolve policy from either the explicitly supplied SDK authority or Pi's default
14
+ * file-backed settings. The caller owns diagnostics and any lifecycle caching.
15
+ */
16
+ export function readThresholdSettings(ctx, settingsManager) {
17
+ try {
18
+ if (settingsManager)
19
+ return readThresholdSettingsFromManager(ctx, settingsManager);
20
+ return readThresholdSettingsFromManager(ctx, SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() }));
21
+ }
22
+ catch (error) {
23
+ return {
24
+ thresholds: {
25
+ reminder: DEFAULT_RESERVE_TOKENS + DEFAULT_REMINDER_MARGIN_TOKENS,
26
+ reserve: DEFAULT_RESERVE_TOKENS,
27
+ warning: DEFAULT_RESERVE_TOKENS + WARNING_RUNWAY_TOKENS,
28
+ },
29
+ automatic: true,
30
+ warnings: [`notesoup: could not read settings; using defaults (${String(error)}).`],
31
+ };
32
+ }
33
+ }
@@ -0,0 +1,11 @@
1
+ export declare const PI_TOOL_NAMES: {
2
+ readonly notes: "notes_*";
3
+ readonly notesList: "notes_list";
4
+ readonly history: "history_*";
5
+ readonly historyWindows: "history_windows";
6
+ readonly historyList: "history_list";
7
+ readonly historySearch: "history_search";
8
+ readonly historyRead: "history_read";
9
+ readonly remaining: "get_context_remaining";
10
+ readonly wipe: "clear_memory";
11
+ };
@@ -0,0 +1,11 @@
1
+ export const PI_TOOL_NAMES = {
2
+ notes: "notes_*",
3
+ notesList: "notes_list",
4
+ history: "history_*",
5
+ historyWindows: "history_windows",
6
+ historyList: "history_list",
7
+ historySearch: "history_search",
8
+ historyRead: "history_read",
9
+ remaining: "get_context_remaining",
10
+ wipe: "clear_memory",
11
+ };
@@ -0,0 +1,15 @@
1
+ /** Pi transport for host-neutral operations. */
2
+ import { type ExtensionAPI, type ExtensionToolContext } from "@earendil-works/pi-coding-agent";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import type { Static, TSchema } from "typebox";
5
+ import { type Operation, type Outcome, type Renderer } from "../tools/result.js";
6
+ /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
7
+ export declare function piOperationResult<TData>(render: Renderer<TData>, outcome: Outcome<TData>): AgentToolResult<undefined>;
8
+ export type ToolNamespace = {
9
+ name: string;
10
+ description: string;
11
+ };
12
+ export declare const NOTES_NAMESPACE: ToolNamespace;
13
+ export declare const HISTORY_NAMESPACE: ToolNamespace;
14
+ /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
15
+ export declare function registerOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(pi: ExtensionAPI, operation: Operation<TParams, TData, TRest>, run: (params: Static<TParams>, ctx: ExtensionToolContext) => Promise<Outcome<TData>>, namespace?: ToolNamespace): void;
@@ -0,0 +1,29 @@
1
+ /** Pi transport for host-neutral operations. */
2
+ import { defineTool } from "@earendil-works/pi-coding-agent";
3
+ import { wireResult } from "../tools/result.js";
4
+ /** Operation data is schema-derived JSON; only the unresolved generic needs a JsonValue assertion. */
5
+ export function piOperationResult(render, outcome) {
6
+ return {
7
+ content: [{ type: "text", text: render(outcome) }],
8
+ structuredContent: wireResult(outcome),
9
+ isError: !outcome.ok,
10
+ details: undefined,
11
+ };
12
+ }
13
+ export const NOTES_NAMESPACE = { name: "notes", description: "Notes you choose to keep across context windows. See /skill:memory." };
14
+ export const HISTORY_NAMESPACE = { name: "history", description: "What happened in this session, read-only. See /skill:memory." };
15
+ /** Register `operation` as a Pi tool; `run` supplies only the host context it needs. */
16
+ export function registerOperation(pi, operation, run, namespace) {
17
+ pi.registerTool(defineTool({
18
+ name: operation.name,
19
+ label: operation.label,
20
+ description: operation.description,
21
+ parameters: operation.parameters,
22
+ outputSchema: operation.outputSchema,
23
+ executionMode: operation.executionMode,
24
+ ...(namespace ? { namespace } : {}),
25
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
26
+ return piOperationResult(operation.render, await run(params, ctx));
27
+ },
28
+ }));
29
+ }