notesoup 0.47.0 → 0.48.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.
- package/README.md +1 -1
- package/dist/src/boot/render.d.ts +14 -7
- package/dist/src/boot/render.js +29 -16
- package/dist/src/boot/text.d.ts +25 -4
- package/dist/src/boot/text.js +59 -11
- package/dist/src/budget/text.d.ts +29 -9
- package/dist/src/budget/text.js +51 -10
- package/dist/src/claude/helper.d.ts +2 -3
- package/dist/src/claude/helper.js +45 -11
- package/dist/src/claude/history.d.ts +9 -0
- package/dist/src/claude/history.js +271 -0
- package/dist/src/dsh/engine.d.ts +2 -1
- package/dist/src/dsh/engine.js +18 -9
- package/dist/src/dsh/index.js +9 -4
- package/dist/src/dsh/window.d.ts +2 -1
- package/dist/src/dsh/window.js +14 -8
- package/dist/src/history/query.js +59 -81
- package/dist/src/notes/address.d.ts +5 -0
- package/dist/src/notes/address.js +20 -21
- package/dist/src/notes/store.js +12 -19
- package/dist/src/pi/boot.d.ts +1 -1
- package/dist/src/pi/boot.js +28 -5
- package/dist/src/pi/budget.d.ts +0 -2
- package/dist/src/pi/budget.js +13 -53
- package/dist/src/pi/entries.d.ts +0 -1
- package/dist/src/pi/entries.js +0 -1
- package/dist/src/pi/history.d.ts +3 -0
- package/dist/src/pi/history.js +4 -0
- package/dist/src/pi/reset/artifacts.d.ts +7 -2
- package/dist/src/pi/reset/artifacts.js +16 -14
- package/dist/src/pi/reset/lifecycle.d.ts +21 -25
- package/dist/src/pi/reset/lifecycle.js +49 -73
- package/dist/src/pi/runtime.js +19 -18
- package/dist/src/pi/window.d.ts +12 -6
- package/dist/src/pi/window.js +7 -0
- package/dist/test/agent-loop.test.js +65 -42
- package/dist/test/boot.integration.test.js +119 -16
- package/dist/test/budget-settings.integration.test.js +4 -2
- package/dist/test/claude-history.test.d.ts +1 -0
- package/dist/test/claude-history.test.js +184 -0
- package/dist/test/claude-mod.test.js +243 -49
- package/dist/test/dsh.test.js +79 -2
- package/dist/test/helpers/extension.d.ts +3 -0
- package/dist/test/helpers/extension.js +33 -5
- package/dist/test/history.integration.test.js +66 -0
- package/dist/test/host-neutral.test.js +1 -1
- package/dist/test/model-facing-text.test.d.ts +1 -0
- package/dist/test/model-facing-text.test.js +181 -0
- package/dist/test/notes.integration.test.js +16 -18
- package/dist/test/reset-lifecycle.test.js +202 -47
- package/docs/architecture.md +3 -3
- package/docs/claude-code-mod.md +15 -3
- package/docs/dsh.md +1 -1
- package/docs/reset-lifecycle.md +32 -20
- package/docs/skills.md +1 -1
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/mods/notesoup/dist/claude/helper.js +836 -92
- package/mods/notesoup/hooks/register.ts +154 -52
- package/package.json +1 -1
- package/src/boot/render.ts +41 -23
- package/src/boot/text.ts +68 -11
- package/src/budget/text.ts +61 -10
- package/src/claude/helper.ts +53 -22
- package/src/claude/history.ts +228 -0
- package/src/dsh/engine.ts +16 -9
- package/src/dsh/index.ts +8 -3
- package/src/dsh/window.ts +15 -9
- package/src/history/query.ts +57 -82
- package/src/notes/address.ts +19 -16
- package/src/notes/store.ts +9 -14
- package/src/pi/boot.ts +27 -5
- package/src/pi/budget.ts +13 -50
- package/src/pi/entries.ts +0 -1
- package/src/pi/history.ts +7 -2
- package/src/pi/reset/artifacts.ts +17 -14
- package/src/pi/reset/lifecycle.ts +57 -80
- package/src/pi/runtime.ts +19 -18
- package/src/pi/window.ts +11 -1
|
@@ -1,45 +1,66 @@
|
|
|
1
1
|
import type { EngineInterface, On, ProcessRunResult, ToolCallResult, ToolSpec } from "claude-code"
|
|
2
2
|
|
|
3
3
|
const PREFIX = "mcp__notesoup__"
|
|
4
|
-
const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"] as const
|
|
5
4
|
const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
|
|
6
5
|
const TIMEOUT_MS = 10_000
|
|
7
6
|
const OUTPUT_LIMIT = 1024 * 1024
|
|
8
7
|
|
|
9
8
|
type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
|
|
10
9
|
type SchemaRow = { name: string; description: string; inputSchema: Record<string, unknown> }
|
|
10
|
+
type HistorySource = { sessionId: string; transcriptPath: string; headUuid?: string }
|
|
11
11
|
type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt" | "env" | "settings">
|
|
12
12
|
/** The measured context, as much of it as the engine reported. */
|
|
13
13
|
type ContextUsage = { tokens?: number; window?: number; percent?: number }
|
|
14
14
|
/** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
|
|
15
|
-
type SharedTexts = { warning?: string;
|
|
15
|
+
type SharedTexts = { warning?: string; wipeSentence?: string; historyUnavailableSentence?: string }
|
|
16
16
|
type ClaudeLimits = {
|
|
17
17
|
source: string; autoCompact: boolean; unit: "tokens" | "percent"
|
|
18
18
|
native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
|
|
19
19
|
}
|
|
20
20
|
type ResetState = {
|
|
21
|
-
identity?: Identity; generation: number; window: number; turnRunning: boolean; resetting: boolean
|
|
21
|
+
identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; turnRunning: boolean; resetting: boolean
|
|
22
22
|
manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
|
|
23
|
+
continuation?: string; continuationWindow?: number
|
|
23
24
|
compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
|
|
24
25
|
limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
25
26
|
}
|
|
26
|
-
const HEADLESS = "
|
|
27
|
-
const COMPACT_DISABLED = "
|
|
28
|
-
const THRESHOLDS_UNAVAILABLE = "
|
|
27
|
+
const HEADLESS = "No brain when headless"
|
|
28
|
+
const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
|
|
29
|
+
const THRESHOLDS_UNAVAILABLE = "Brain size unknown · no automatic emptying"
|
|
29
30
|
const SETTINGS_UNAVAILABLE = "Notesoup settings unreadable · using the default flush margins"
|
|
30
31
|
/** Bounded retries: a transient helper failure must not disable thresholds for a whole window. */
|
|
31
32
|
const MAX_LIMITS_ATTEMPTS = 3
|
|
32
33
|
const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
|
|
33
34
|
const BOOT_TOOLS = {
|
|
34
35
|
notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
|
|
35
|
-
history: "history_* (unavailable
|
|
36
|
+
history: "history_* (unavailable: no main transcript_path)",
|
|
36
37
|
remaining: "get_context_remaining (unavailable in Claude)", wipe: "/fresh-window (user command; no model reset tool in Claude)",
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
/** The boot names the host's own wipe path, so the protocol block speaks about `/fresh-window`. */
|
|
40
|
-
async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts) {
|
|
41
|
-
const
|
|
42
|
-
|
|
41
|
+
async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts, history?: HistorySource) {
|
|
42
|
+
const available = history?.sessionId === identity.sessionId
|
|
43
|
+
const tools = { ...BOOT_TOOLS, ...(available ? { history: `${PREFIX}history_*` } : { historySentence: texts?.historyUnavailableSentence }), ...(texts?.wipeSentence === undefined ? {} : { wipeSentence: texts.wipeSentence }) }
|
|
44
|
+
return run($, { op: "boot", identity, window, tools })
|
|
45
|
+
}
|
|
46
|
+
/** The notes-only reset shape, shared by our own reset and Claude's native auto compaction. */
|
|
47
|
+
type ResetMessages = { boot: string; messages: Array<{ role: "user"; text: string; toolUses: [] }> }
|
|
48
|
+
async function resetMessages($: Engine, state: ResetState, identity: Identity): Promise<ResetMessages | { skip: string }> {
|
|
49
|
+
const generation = state.generation
|
|
50
|
+
const texts = await loadTexts($, state)
|
|
51
|
+
if (texts === undefined) return { skip: "reset text didn't load" }
|
|
52
|
+
const boot = await buildBoot($, identity, state.window + 1, texts, state.history)
|
|
53
|
+
if (generation !== state.generation) return { skip: "session changed while building the notes boot" }
|
|
54
|
+
if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
|
|
55
|
+
const continuation = await continuationFor($, state)
|
|
56
|
+
if (generation !== state.generation) return { skip: "session changed while building the notes boot" }
|
|
57
|
+
if (continuation === undefined) return { skip: "reset text didn't load" }
|
|
58
|
+
// The same closed reset shape as Pi: notes boot first, then the one reset message.
|
|
59
|
+
const text = String(boot.result)
|
|
60
|
+
return { boot: text, messages: [
|
|
61
|
+
{ role: "user", text, toolUses: [] },
|
|
62
|
+
{ role: "user", text: continuation, toolUses: [] },
|
|
63
|
+
] }
|
|
43
64
|
}
|
|
44
65
|
function numberOf(value: unknown): number | undefined {
|
|
45
66
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined
|
|
@@ -49,8 +70,8 @@ function sharedTextsOf(value: unknown): SharedTexts | undefined {
|
|
|
49
70
|
const row = value as Record<string, unknown>
|
|
50
71
|
const texts: SharedTexts = {}
|
|
51
72
|
if (typeof row.warning === "string" && row.warning.length > 0) texts.warning = row.warning
|
|
52
|
-
if (typeof row.continuation === "string" && row.continuation.length > 0) texts.continuation = row.continuation
|
|
53
73
|
if (typeof row.wipeSentence === "string" && row.wipeSentence.length > 0) texts.wipeSentence = row.wipeSentence
|
|
74
|
+
if (typeof row.historyUnavailableSentence === "string" && row.historyUnavailableSentence.length > 0) texts.historyUnavailableSentence = row.historyUnavailableSentence
|
|
54
75
|
return Object.keys(texts).length > 0 ? texts : undefined
|
|
55
76
|
}
|
|
56
77
|
/** The helper's resolved points, accepted only when every number is a real number. */
|
|
@@ -102,7 +123,7 @@ async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage
|
|
|
102
123
|
} catch {
|
|
103
124
|
if (!state.usageFailureLogged) {
|
|
104
125
|
state.usageFailureLogged = true
|
|
105
|
-
log($, "
|
|
126
|
+
log($, "Brain fullness unknown · no automatic emptying")
|
|
106
127
|
}
|
|
107
128
|
return undefined
|
|
108
129
|
}
|
|
@@ -140,7 +161,7 @@ async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Prom
|
|
|
140
161
|
const generation = state.generation
|
|
141
162
|
const facts = await limitFacts($, state, usage)
|
|
142
163
|
if (generation !== state.generation) return undefined
|
|
143
|
-
const response = await run($, { op: "limits", facts }
|
|
164
|
+
const response = await run($, { op: "limits", facts })
|
|
144
165
|
if (generation !== state.generation) return undefined
|
|
145
166
|
const limits = response.ok ? limitsShape(response.result) : undefined
|
|
146
167
|
state.limitsWindow = window
|
|
@@ -167,24 +188,44 @@ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | un
|
|
|
167
188
|
if (state.texts) return state.texts
|
|
168
189
|
if (!state.identity) return undefined
|
|
169
190
|
const generation = state.generation
|
|
170
|
-
const response = await run($, { op: "texts" }
|
|
191
|
+
const response = await run($, { op: "texts" })
|
|
171
192
|
if (generation !== state.generation) return undefined
|
|
172
193
|
const texts = response.ok ? sharedTextsOf(response.result) : undefined
|
|
173
194
|
if (texts) state.texts = texts
|
|
174
195
|
return texts
|
|
175
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* The one fresh-window line for the artifact being created. Claude has no model reset tool, so
|
|
199
|
+
* every reset here is system-triggered; one draw per window keeps a retried compaction from
|
|
200
|
+
* redrawing a line the same reset already carries.
|
|
201
|
+
*/
|
|
202
|
+
async function continuationFor($: Engine, state: ResetState): Promise<string | undefined> {
|
|
203
|
+
if (state.continuation !== undefined && state.continuationWindow === state.window) return state.continuation
|
|
204
|
+
const generation = state.generation
|
|
205
|
+
const response = await run($, { op: "continuation", origin: "forced" })
|
|
206
|
+
if (generation !== state.generation) return undefined
|
|
207
|
+
const result = response.ok ? response.result : undefined
|
|
208
|
+
const text = typeof result === "object" && result !== null ? (result as { text?: unknown }).text : undefined
|
|
209
|
+
if (typeof text !== "string" || text.length === 0) return undefined
|
|
210
|
+
state.continuation = text
|
|
211
|
+
state.continuationWindow = state.window
|
|
212
|
+
return text
|
|
213
|
+
}
|
|
176
214
|
function log($: Engine, text: string) {
|
|
177
215
|
try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
|
|
178
216
|
}
|
|
217
|
+
/** A rejected call's reason, one line, bounded: the caller reads it, not a stack. */
|
|
218
|
+
function describeFailure(error: unknown): string {
|
|
219
|
+
const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
|
|
220
|
+
return text.replace(/[\r\n]+/g, " ").slice(0, 200) || "unknown failure"
|
|
221
|
+
}
|
|
179
222
|
|
|
180
223
|
function errorResult(message: string): ToolCallResult { return { result: `notesoup: ${message}`, isError: true } }
|
|
181
224
|
/** The helper's tool result: the shared text the model reads, plus whether that outcome refused. */
|
|
182
225
|
function toolResultOf(value: unknown): { text: string; ok: boolean } | undefined {
|
|
183
226
|
if (typeof value !== "object" || value === null) return undefined
|
|
184
|
-
const { text,
|
|
185
|
-
if (typeof text !== "string" || typeof
|
|
186
|
-
const ok = (outcome as { ok?: unknown }).ok
|
|
187
|
-
if (typeof ok !== "boolean") return undefined
|
|
227
|
+
const { text, ok } = value as { text?: unknown; ok?: unknown }
|
|
228
|
+
if (typeof text !== "string" || typeof ok !== "boolean") return undefined
|
|
188
229
|
return { text, ok }
|
|
189
230
|
}
|
|
190
231
|
function decode(result: ProcessRunResult): { ok: true; result: unknown } | { ok: false; error: string } {
|
|
@@ -196,18 +237,25 @@ function decode(result: ProcessRunResult): { ok: true; result: unknown } | { ok:
|
|
|
196
237
|
return { ok: false, error: typeof value.error === "string" ? value.error : "helper returned an invalid error" }
|
|
197
238
|
} catch { return { ok: false, error: "helper returned invalid JSON" } }
|
|
198
239
|
}
|
|
199
|
-
async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown
|
|
200
|
-
|
|
201
|
-
|
|
240
|
+
async function run($: { process: { run: (argv: readonly string[], init?: { cwd?: string; stdin?: string; timeoutMs?: number }) => Promise<ProcessRunResult> } }, request: unknown) {
|
|
241
|
+
// A session may still name a removed worktree. Project identity travels in stdin;
|
|
242
|
+
// launch from the plugin directory so removing that worktree cannot prevent spawn.
|
|
243
|
+
try { return decode(await $.process.run(["node", HELPER], { cwd: import.meta.dir, stdin: `${JSON.stringify(request)}\n`, timeoutMs: TIMEOUT_MS })) }
|
|
244
|
+
// The host's rejection is the only diagnosis there is: it carries the spawn failure's own
|
|
245
|
+
// reason (`timed out after …`), which a bare phrase would throw away.
|
|
246
|
+
catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
|
|
202
247
|
}
|
|
203
248
|
/** Session start does not fire on /clear, /resume or /branch. Forget the old window on end. */
|
|
204
249
|
function forgetSession(state: ResetState) {
|
|
205
250
|
state.generation++
|
|
206
251
|
state.identity = undefined
|
|
252
|
+
state.historyWindowHead = undefined
|
|
207
253
|
state.window = 0
|
|
208
254
|
state.turnRunning = state.resetting = state.manualPending = state.usageFailureLogged = false
|
|
209
255
|
state.preparedBoot = state.retainedBoot = undefined
|
|
210
256
|
state.texts = state.limits = undefined
|
|
257
|
+
state.continuation = undefined
|
|
258
|
+
state.continuationWindow = undefined
|
|
211
259
|
state.limitsAttempts = state.limitsWindow = 0
|
|
212
260
|
state.settingsFailureLogged = state.limitsFailureLogged = false
|
|
213
261
|
state.warnedWindow = undefined
|
|
@@ -228,25 +276,58 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
|
|
|
228
276
|
if (generation !== state.generation) return undefined
|
|
229
277
|
if (state.identity?.sessionId === sessionId) {
|
|
230
278
|
state.identity = { ...state.identity, cwd, model }
|
|
279
|
+
await syncHistoryWindow($, state)
|
|
231
280
|
return state.identity
|
|
232
281
|
}
|
|
233
282
|
const home = await $.env.get("PI_NOTES_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
|
|
234
283
|
if (generation !== state.generation) return undefined
|
|
235
284
|
forgetSession(state)
|
|
236
285
|
state.identity = { home, sessionId, cwd, agent: "claude", model }
|
|
286
|
+
if (state.history?.sessionId !== sessionId) state.history = undefined
|
|
237
287
|
const freshGeneration = state.generation
|
|
238
288
|
// History is not inference context; recover a retained boot only for this session id.
|
|
239
289
|
try {
|
|
240
290
|
const messages = await $.session.messages()
|
|
241
291
|
if (freshGeneration === state.generation) restoreWindow(state, messages)
|
|
242
292
|
} catch { /* A fresh session starts at zero. */ }
|
|
293
|
+
await syncHistoryWindow($, state)
|
|
243
294
|
return freshGeneration === state.generation ? state.identity : undefined
|
|
244
295
|
}
|
|
245
296
|
|
|
297
|
+
/** A committed append is the head evidence; the persisted file may trail it briefly. */
|
|
298
|
+
async function syncHistoryWindow($: Engine, state: ResetState) {
|
|
299
|
+
if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.resetting || state.historyWindowHead === state.history.headUuid) return
|
|
300
|
+
const generation = state.generation, head = state.history.headUuid
|
|
301
|
+
const response = await run($, { op: "history_state", identity: state.identity, history: state.history })
|
|
302
|
+
if (generation !== state.generation || state.history?.headUuid !== head || !response.ok || typeof response.result !== "object" || response.result === null) return
|
|
303
|
+
const window = (response.result as { window?: unknown }).window
|
|
304
|
+
if (typeof window !== "number" || !Number.isSafeInteger(window) || window < 0) return
|
|
305
|
+
state.historyWindowHead = head
|
|
306
|
+
if (state.window !== window) { state.window = window; state.retainedBoot = undefined }
|
|
307
|
+
}
|
|
308
|
+
|
|
246
309
|
export function register(on: On) {
|
|
247
310
|
const manualSignal: { wake?: () => void } = {}
|
|
248
311
|
const state: ResetState = { generation: 0, window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: false }
|
|
249
312
|
const registered = new Set<string>()
|
|
313
|
+
// Classic SessionStart precedes typed session.start and startup appends. Keep this binding
|
|
314
|
+
// across forgetSession; re-key it only against the actual session id, never a guessed path.
|
|
315
|
+
on("classic.SessionStart", async ($, e, next) => {
|
|
316
|
+
if (e.agent_id !== undefined) return next(e)
|
|
317
|
+
if (e.source !== "compact" || state.history?.sessionId !== e.session_id) {
|
|
318
|
+
state.history = { sessionId: e.session_id, transcriptPath: e.transcript_path }
|
|
319
|
+
} else state.history.transcriptPath = e.transcript_path
|
|
320
|
+
return next(e)
|
|
321
|
+
})
|
|
322
|
+
on("session.append", async ($, e, next) => {
|
|
323
|
+
const sessionId = await $.session.id(), source = state.history
|
|
324
|
+
const result = await next(e)
|
|
325
|
+
if (e.agentId === undefined && result.uuid !== undefined && state.history === source && source?.sessionId === sessionId) {
|
|
326
|
+
source.headUuid = result.uuid
|
|
327
|
+
state.historyWindowHead = undefined
|
|
328
|
+
}
|
|
329
|
+
return result
|
|
330
|
+
})
|
|
250
331
|
on("session.start", async ($, e, next) => {
|
|
251
332
|
forgetSession(state)
|
|
252
333
|
await refreshIdentity($, state)
|
|
@@ -260,16 +341,16 @@ export function register(on: On) {
|
|
|
260
341
|
armManual($, state, manualSignal)
|
|
261
342
|
await $.command.register({ name: "empty-brain", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
262
343
|
await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
263
|
-
const schemas = await run($, { op: "schemas" }
|
|
344
|
+
const schemas = await run($, { op: "schemas" })
|
|
264
345
|
if (!schemas.ok || !Array.isArray(schemas.result)) return next(e)
|
|
265
346
|
for (const row of schemas.result as SchemaRow[]) {
|
|
266
|
-
if (!TOOL_NAMES.includes(row.name as typeof TOOL_NAMES[number])) continue
|
|
267
347
|
const full = await $.tool.register({ name: row.name, description: row.description, inputSchema: row.inputSchema, isDeferred: false } satisfies ToolSpec)
|
|
268
348
|
registered.add(full.tool)
|
|
269
349
|
}
|
|
270
350
|
return next(e)
|
|
271
351
|
})
|
|
272
352
|
on("session.end", async ($, e, next) => {
|
|
353
|
+
state.history = undefined
|
|
273
354
|
forgetSession(state)
|
|
274
355
|
return next(e)
|
|
275
356
|
})
|
|
@@ -277,8 +358,10 @@ export function register(on: On) {
|
|
|
277
358
|
if (!registered.has(e.tool)) return next(e)
|
|
278
359
|
const identity = await refreshIdentity($, state)
|
|
279
360
|
if (!identity) return errorResult("session changed during identity lookup")
|
|
280
|
-
const { tool, tool_use_id: _toolUseId, agentId
|
|
281
|
-
const
|
|
361
|
+
const { tool, tool_use_id: _toolUseId, agentId, ...params } = e
|
|
362
|
+
const name = tool.slice(PREFIX.length)
|
|
363
|
+
if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
|
|
364
|
+
const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
|
|
282
365
|
if (!result.ok) return errorResult(result.error)
|
|
283
366
|
// The outcome already decided success or refusal; Claude requires isError: true on errors and no discriminator on success.
|
|
284
367
|
const outcome = toolResultOf(result.result)
|
|
@@ -308,26 +391,26 @@ export function register(on: On) {
|
|
|
308
391
|
})
|
|
309
392
|
on("command.run", async ($, e, next) => {
|
|
310
393
|
if (e.command !== "empty-brain" && e.command !== "fresh-window") return next(e)
|
|
311
|
-
if (!await refreshIdentity($, state)) return { text: "🥣
|
|
394
|
+
if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
|
|
312
395
|
if (state.headless) return { text: `🥣 ${HEADLESS}` }
|
|
313
396
|
if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
|
|
314
|
-
if (state.resetting || state.manualPending) return { text: "🥣
|
|
397
|
+
if (state.resetting || state.manualPending) return { text: "🥣 Brain already being emptied" }
|
|
315
398
|
if (state.turnRunning) {
|
|
316
399
|
state.manualPending = true
|
|
317
|
-
return { text: "🥣
|
|
400
|
+
return { text: "🥣 Brain being emptied" }
|
|
318
401
|
}
|
|
319
402
|
// command.run holds a turn even when idle. Start one hidden close-out
|
|
320
403
|
// turn after it returns; turn.complete is the verified self-hook path.
|
|
321
404
|
state.manualPending = true
|
|
322
405
|
manualSignal.wake?.()
|
|
323
|
-
return { text: "🥣
|
|
406
|
+
return { text: "🥣 Brain being emptied" }
|
|
324
407
|
})
|
|
325
408
|
on("session.compact", async ($, e, next) => {
|
|
326
409
|
if (e.agentId !== undefined) return next(e)
|
|
327
410
|
const identity = await refreshIdentity($, state)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
411
|
+
const generation = state.generation
|
|
412
|
+
// Every pass-through keeps the current boot unless the engine's own summary replaced it.
|
|
413
|
+
const passThrough = async () => {
|
|
331
414
|
const result = await next(e)
|
|
332
415
|
// Precompute installs nothing; a veto or subagent compact cannot remove our boot.
|
|
333
416
|
if (generation === state.generation && e.trigger !== "precompute" && result.skip === undefined) {
|
|
@@ -336,18 +419,30 @@ export function register(on: On) {
|
|
|
336
419
|
}
|
|
337
420
|
return result
|
|
338
421
|
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
if (
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
if (!
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
422
|
+
// Native compaction never runs the summarizer while notesoup is on: manual and
|
|
423
|
+
// precompute are vetoed, an automatic compaction becomes the notes-only reset.
|
|
424
|
+
if (e.trigger === "manual") return { skip: "No compacting brains here · use /fresh-window" }
|
|
425
|
+
if (e.trigger === "precompute") return { skip: "No precomputing brains here" }
|
|
426
|
+
const own = state.resetting && e.trigger === "plugin" && identity !== undefined
|
|
427
|
+
if (!own && e.trigger !== "auto") return passThrough()
|
|
428
|
+
if (identity === undefined) return passThrough()
|
|
429
|
+
const built = await resetMessages($, state, identity)
|
|
430
|
+
if ("skip" in built) {
|
|
431
|
+
if (own) return { skip: built.skip }
|
|
432
|
+
// An over-long prompt must still compact: fall back to the engine's summary.
|
|
433
|
+
log($, `Notes didn't load (${built.skip}) · Claude compacted natively`)
|
|
434
|
+
return passThrough()
|
|
435
|
+
}
|
|
436
|
+
if (own) {
|
|
437
|
+
state.preparedBoot = built.boot
|
|
438
|
+
} else {
|
|
439
|
+
// The auto hijack keeps the books a successful plugin reset does.
|
|
440
|
+
state.retainedBoot = built.boot
|
|
441
|
+
state.preparedBoot = undefined
|
|
442
|
+
state.window++
|
|
443
|
+
log($, "Brain emptied")
|
|
444
|
+
}
|
|
445
|
+
return { messages: built.messages }
|
|
351
446
|
})
|
|
352
447
|
on("prompt.context", async ($, e, next) => {
|
|
353
448
|
const result = await next(e)
|
|
@@ -359,11 +454,11 @@ export function register(on: On) {
|
|
|
359
454
|
let blocks = retained ? result.blocks.filter((block) => block.name !== "notesoup:boot") : [...result.blocks]
|
|
360
455
|
if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
|
|
361
456
|
const texts = await loadTexts($, state)
|
|
362
|
-
const boot = await buildBoot($, identity, state.window, texts)
|
|
457
|
+
const boot = await buildBoot($, identity, state.window, texts, state.history)
|
|
363
458
|
if (generation !== state.generation) return result
|
|
364
459
|
if (!boot.ok) {
|
|
365
460
|
try {
|
|
366
|
-
await $.ui.toast("🥣 Notes
|
|
461
|
+
await $.ui.toast("🥣 Notes went missing")
|
|
367
462
|
} catch { /* Notification failure must not suppress the fallback block. */ }
|
|
368
463
|
}
|
|
369
464
|
blocks = [...blocks, { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\nYour notes didn't load this time (${boot.error}). Try \`${PREFIX}notes_list\`; if it fails too, tell the human.` }]
|
|
@@ -393,11 +488,18 @@ async function warningBlock($: Engine, state: ResetState): Promise<{ name: strin
|
|
|
393
488
|
return { name: "notesoup:warning", text: texts.warning }
|
|
394
489
|
}
|
|
395
490
|
|
|
491
|
+
/** The boot's identity line; `context_window` is the pre-rename tag still in old transcripts. */
|
|
492
|
+
const BOOT_IDENTITY = /<(?:notesoup:window_identity|context_window)>\nAgent name: claude /
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* A retained boot carries the window ordinal in a trailing id line. Old and new tag spellings
|
|
496
|
+
* both count: a transcript written before the rename must not lose its window numbering.
|
|
497
|
+
*/
|
|
396
498
|
function restoreWindow(state: ResetState, messages: readonly { role: string; text: string }[]) {
|
|
397
499
|
if (!state.identity) return
|
|
398
500
|
const prefix = `Current context window id: claude:${state.identity.sessionId}:`
|
|
399
501
|
for (const message of messages) {
|
|
400
|
-
if (message.role !== "user" || !message.text
|
|
502
|
+
if (message.role !== "user" || !BOOT_IDENTITY.test(message.text)) continue
|
|
401
503
|
const line = message.text.split("\n").find((value) => value.startsWith(prefix))
|
|
402
504
|
if (!line) continue
|
|
403
505
|
const suffix = line.slice(prefix.length)
|
|
@@ -427,7 +529,7 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
|
|
|
427
529
|
if (generation !== state.generation) return
|
|
428
530
|
if (texts?.warning === undefined) {
|
|
429
531
|
state.manualPending = false
|
|
430
|
-
log($, "
|
|
532
|
+
log($, "Brain still full: the close-out prompt didn't load")
|
|
431
533
|
return
|
|
432
534
|
}
|
|
433
535
|
await $.prompt.submit({ text: texts.warning })
|
|
@@ -435,7 +537,7 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
|
|
|
435
537
|
} catch {
|
|
436
538
|
if (generation === state.generation) {
|
|
437
539
|
state.manualPending = false
|
|
438
|
-
log($, "
|
|
540
|
+
log($, "Brain still full: the close-out turn didn't start")
|
|
439
541
|
}
|
|
440
542
|
} finally { armManual($, state, signal) }
|
|
441
543
|
}
|
|
@@ -467,12 +569,12 @@ async function reset($: Engine, state: ResetState): Promise<void> {
|
|
|
467
569
|
const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
|
|
468
570
|
if (generation !== state.generation) return
|
|
469
571
|
if (result.skip !== undefined || state.preparedBoot === undefined) {
|
|
470
|
-
log($, `
|
|
572
|
+
log($, `Brain not emptied · ${result.skip ?? "notes boot was not retained"}`)
|
|
471
573
|
return
|
|
472
574
|
}
|
|
473
575
|
state.retainedBoot = state.preparedBoot
|
|
474
576
|
state.window++
|
|
475
|
-
log($, "
|
|
577
|
+
log($, "Brain emptied")
|
|
476
578
|
} catch (error) {
|
|
477
579
|
if (generation !== state.generation) return
|
|
478
580
|
const text = String(error)
|
|
@@ -482,7 +584,7 @@ async function reset($: Engine, state: ResetState): Promise<void> {
|
|
|
482
584
|
} else if (/a turn is (running|in flight)/.test(text)) {
|
|
483
585
|
state.manualPending = true
|
|
484
586
|
} else {
|
|
485
|
-
log($, `
|
|
587
|
+
log($, `Brain still full: ${text.replace(/[\r\n].*$/s, "")}`)
|
|
486
588
|
}
|
|
487
589
|
} finally {
|
|
488
590
|
if (generation === state.generation) {
|
package/package.json
CHANGED
package/src/boot/render.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { NotesHome, NotesSnapshot } from "./snapshot.js";
|
|
2
|
-
import {
|
|
2
|
+
import { WINDOW_IDENTITY_OPEN_TAG, WINDOW_IDENTITY_CLOSE_TAG, MAPS_BLOCK, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
|
|
3
3
|
|
|
4
4
|
function relativeTime(timestamp: number, now: number): string {
|
|
5
5
|
const seconds = Math.trunc((timestamp - now) / 1000);
|
|
@@ -32,14 +32,17 @@ function section(label: string, body: string): string {
|
|
|
32
32
|
return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/** Pi's default agent slug: an unnamed agent shares its `@self` shelf with every other nameless one. */
|
|
36
|
+
const NAMELESS_AGENT = "anonymous";
|
|
37
|
+
|
|
35
38
|
/** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its map and its own freshest pages. */
|
|
36
|
-
function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
|
|
39
|
+
function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames, agentName: string, modelName: string): string {
|
|
37
40
|
const homes: ReadonlyArray<{ scope: NotesHome["scope"]; label: string }> = [
|
|
38
|
-
{ scope: "session", label: "
|
|
39
|
-
{ scope: "project", label: "
|
|
40
|
-
{ scope: "agent", label:
|
|
41
|
-
{ scope: "model", label:
|
|
42
|
-
{ scope: "human", label: "
|
|
41
|
+
{ scope: "session", label: "no @ — this session" },
|
|
42
|
+
{ scope: "project", label: "@project — this project" },
|
|
43
|
+
{ scope: "agent", label: agentName === NAMELESS_AGENT ? "@self — every nameless agent shares this" : `@self — ${agentName} only` },
|
|
44
|
+
{ scope: "model", label: `@model — ${modelName} only` },
|
|
45
|
+
{ scope: "human", label: "@human — the human" },
|
|
43
46
|
];
|
|
44
47
|
|
|
45
48
|
const shelves: string[] = [];
|
|
@@ -60,8 +63,8 @@ function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
|
|
|
60
63
|
});
|
|
61
64
|
if (!map?.body && fresh.length === 0) continue;
|
|
62
65
|
const parts: string[] = [];
|
|
63
|
-
if (map?.body) parts.push(`
|
|
64
|
-
if (fresh.length > 0) parts.push(`
|
|
66
|
+
if (map?.body) parts.push(`map\n\n${indent(mapBodyForBoot(map.address, map.body))}`);
|
|
67
|
+
if (fresh.length > 0) parts.push(`recent\n\n${fresh.join("\n\n")}`);
|
|
65
68
|
shelves.push(section(home.label, parts.join("\n\n")));
|
|
66
69
|
}
|
|
67
70
|
|
|
@@ -77,29 +80,44 @@ function mapBodyForBoot(address: string, body: string): string {
|
|
|
77
80
|
return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
|
|
78
81
|
}
|
|
79
82
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
83
|
+
export type BootWindowTree = {
|
|
84
|
+
readonly trunk: string;
|
|
85
|
+
readonly windows: ReadonlyArray<{
|
|
86
|
+
readonly shortName: string;
|
|
87
|
+
readonly firstSeq?: number;
|
|
88
|
+
readonly lastSeq?: number;
|
|
89
|
+
readonly isCurrent: boolean;
|
|
90
|
+
}>;
|
|
91
|
+
};
|
|
92
|
+
|
|
84
93
|
export type BootRenderData = {
|
|
85
94
|
readonly agentName: string;
|
|
86
95
|
readonly modelName: string;
|
|
87
|
-
readonly
|
|
88
|
-
readonly currentWindowId: string;
|
|
89
|
-
readonly previousWindowId?: string;
|
|
96
|
+
readonly tree: BootWindowTree;
|
|
90
97
|
readonly notes: NotesSnapshot;
|
|
91
98
|
readonly tools: BootToolNames;
|
|
92
99
|
};
|
|
93
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Render a static, once-per-window boot block from explicit data. This function does not read
|
|
103
|
+
* notes or call runtime UI APIs; acquisition belongs to loadNotesSnapshot and its caller.
|
|
104
|
+
*/
|
|
94
105
|
export function renderBootBlock(data: BootRenderData): string {
|
|
95
|
-
//
|
|
96
|
-
//
|
|
106
|
+
// Root, the window before this one, and this one: the block is rewritten every window, so an
|
|
107
|
+
// unbounded list would repeat the whole history once per window for no new information.
|
|
108
|
+
const shown = new Set([0, data.tree.windows.length - 2, data.tree.windows.length - 1]);
|
|
109
|
+
const windows = data.tree.windows.filter((_window, index) => shown.has(index));
|
|
110
|
+
const width = Math.max(8, ...windows.map((window) => window.shortName.length));
|
|
97
111
|
const lines = [
|
|
98
112
|
`Agent name: ${data.agentName} (brain: ${data.modelName})`,
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
...(
|
|
113
|
+
"",
|
|
114
|
+
data.tree.trunk,
|
|
115
|
+
...windows.map((window) => {
|
|
116
|
+
const range = window.firstSeq === undefined ? "" : ` ${window.firstSeq}–${window.isCurrent ? "" : window.lastSeq}`;
|
|
117
|
+
const name = range ? window.shortName.padEnd(width) : window.shortName;
|
|
118
|
+
return `${window.isCurrent ? "└─" : "├─"} ${name}${range}${window.isCurrent ? " ← you are here" : ""}`;
|
|
119
|
+
}),
|
|
102
120
|
];
|
|
103
|
-
const identity = `${
|
|
104
|
-
return [identity, renderProtocolBlock(data.tools), notesIndex(data.notes, data.tools)].join("\n\n");
|
|
121
|
+
const identity = `${WINDOW_IDENTITY_OPEN_TAG}\n${lines.join("\n")}\n${WINDOW_IDENTITY_CLOSE_TAG}`;
|
|
122
|
+
return [identity, renderProtocolBlock(data.tools), MAPS_BLOCK, notesIndex(data.notes, data.tools, data.agentName, data.modelName)].join("\n\n");
|
|
105
123
|
}
|