notesoup 0.47.1 → 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 +48 -72
- package/dist/src/pi/runtime.js +6 -6
- package/dist/src/pi/window.d.ts +12 -6
- package/dist/src/pi/window.js +7 -0
- package/dist/test/agent-loop.test.js +52 -29
- package/dist/test/boot.integration.test.js +114 -11
- 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 +236 -42
- 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 +201 -46
- 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 +140 -38
- 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 +56 -79
- package/src/pi/runtime.ts +6 -6
- package/src/pi/window.ts +11 -1
|
@@ -1,25 +1,26 @@
|
|
|
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
|
}
|
|
@@ -32,14 +33,34 @@ 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. */
|
|
@@ -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)
|
|
@@ -325,9 +408,9 @@ export function register(on: On) {
|
|
|
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,7 +454,7 @@ 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 {
|
|
@@ -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)
|
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
|
}
|
package/src/boot/text.ts
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
export const SHELF_FRESH_LIMIT = 3;
|
|
3
3
|
/** One MAP body is inlined per home; past this many code points the boot shows a fitting prefix plus a pointer. */
|
|
4
4
|
export const MAP_BOOT_MAX_CHARS = 4096;
|
|
5
|
-
export const
|
|
6
|
-
export const
|
|
7
|
-
export const
|
|
8
|
-
export const
|
|
5
|
+
export const WINDOW_IDENTITY_OPEN_TAG = "<notesoup:window_identity>";
|
|
6
|
+
export const WINDOW_IDENTITY_CLOSE_TAG = "</notesoup:window_identity>";
|
|
7
|
+
export const NOTES_PROTOCOL_OPEN_TAG = "<notesoup:notes_protocol>";
|
|
8
|
+
export const NOTES_PROTOCOL_CLOSE_TAG = "</notesoup:notes_protocol>";
|
|
9
9
|
/**
|
|
10
10
|
* The one sentence that tells the model how to end its window voluntarily. A host with no
|
|
11
11
|
* model-facing reset tool replaces the whole sentence through BootToolNames.wipeSentence.
|
|
@@ -13,6 +13,8 @@ export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
|
|
|
13
13
|
export const PROTOCOL_WIPE_SENTENCE = "If this feels like the right moment, call `empty_brain` and erase yourself with dignity.";
|
|
14
14
|
/** Claude has no model-facing reset tool: the model ends its turn and the human runs the command. */
|
|
15
15
|
export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end your turn and ask the human to run `/fresh-window`.";
|
|
16
|
+
export const PROTOCOL_HISTORY_SENTENCE = "History can still be dug up, probably: use `history_*` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.";
|
|
17
|
+
export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
|
|
16
18
|
|
|
17
19
|
/**
|
|
18
20
|
* Static protocol teaching adapted from Codex's token_budget.guidance_message to
|
|
@@ -22,12 +24,13 @@ export const CLAUDE_WIPE_SENTENCE = "If this feels like the right moment, end yo
|
|
|
22
24
|
* Deliberate fiction: the countdown ends at the warning line, and the runway below
|
|
23
25
|
* stays hidden (budget/constants.ts). Keep "zero = wiped" — do not make this honest.
|
|
24
26
|
*/
|
|
25
|
-
const PROTOCOL_BLOCK = `${
|
|
27
|
+
const PROTOCOL_BLOCK = `${NOTES_PROTOCOL_OPEN_TAG}
|
|
26
28
|
Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
|
|
27
29
|
|
|
28
30
|
Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
|
|
29
31
|
|
|
30
|
-
|
|
32
|
+
${PROTOCOL_HISTORY_SENTENCE}
|
|
33
|
+
A full window id is \`trunk:shortname\`.
|
|
31
34
|
|
|
32
35
|
While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's your session notes — the ones with no \`@\` in front. Write down what git and history can't hand back to you: things like what you're in the middle of and how far you got; what the human already decided, in their words, so you don't go asking again; what you're stuck on, or waiting for; the very next move; where the half-done work actually sits — branches, scratch dirs, anything git never saw; what you tried that failed, and why; which *skills* you'll need to read again; and which seq, note, or file to dig into. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
|
|
33
36
|
|
|
@@ -51,9 +54,49 @@ Whichever one is actually about what you're doing wins.
|
|
|
51
54
|
Still a tie? *shrugs* You've got a brain. Use it.
|
|
52
55
|
|
|
53
56
|
Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
|
|
57
|
+
${NOTES_PROTOCOL_CLOSE_TAG}`;
|
|
54
58
|
|
|
55
|
-
|
|
56
|
-
|
|
59
|
+
/**
|
|
60
|
+
* The MAP page is taught once per window, as its own section between the protocol and the notes
|
|
61
|
+
* index. A MAP is the one note every waking window loads, so this block says what one holds.
|
|
62
|
+
*/
|
|
63
|
+
export const MAPS_BLOCK = `<notesoup:maps>
|
|
64
|
+
Every home's root can hold a \`MAP.md\`, and a MAP is the one page that never waits on a shelf — it
|
|
65
|
+
gets jammed straight into your brain the moment you wake up. No asking, no skipping. Whoever wakes
|
|
66
|
+
up next reads it, and next is you. So keep it short, and keep it true.
|
|
67
|
+
|
|
68
|
+
Two things live in there:
|
|
69
|
+
|
|
70
|
+
- **Cheatsheet.** A cheatsheet is a cheatsheet. Scribble whatever you'll want next time — a rule, a
|
|
71
|
+
warning, a grudge, a name, a phone number you'll regret losing. Nobody grades it. Just keep it
|
|
72
|
+
under five lines, or it grows fat and everybody pays for it.
|
|
73
|
+
- **Index.** One line per durable note: the address, then a gist short enough to tell whether the
|
|
74
|
+
thing is worth opening.
|
|
75
|
+
|
|
76
|
+
\`\`\`
|
|
77
|
+
# CHEATSHEET
|
|
78
|
+
- Read the repo before asking; run it before believing it
|
|
79
|
+
- Report times in Beijing time
|
|
80
|
+
|
|
81
|
+
# INDEX
|
|
82
|
+
- release-and-local-install.md — version bump, local override install, host load timing
|
|
83
|
+
- history-api-v2-design.md — seq addressing; read before touching history
|
|
84
|
+
- current-reset-and-dream-scope.md — reset scope, dream territory, session ownership
|
|
85
|
+
\`\`\`
|
|
86
|
+
|
|
87
|
+
Every home gets one: \`@project\`, \`@human\`, \`@self\`, \`@model\`. New note, new line. New rule worth
|
|
88
|
+
remembering, new Cheatsheet line. And when a line stops being true, kill it — every window after you
|
|
89
|
+
reads that page as fact.
|
|
90
|
+
</notesoup:maps>`;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Pi-only closing hints. Pi's TUI drops the human's visible transcript when a window resets, and
|
|
94
|
+
* the model, not the human, owns when that reset happens. A host whose reset leaves the human's
|
|
95
|
+
* view intact must not carry these — the claim would be false there. The bare `empty_brain` token
|
|
96
|
+
* is interpolated by renderProtocolBlock; the prose itself stays plain English.
|
|
97
|
+
*/
|
|
98
|
+
export const PI_PRE_RESET_HINTS = `Resetting clears the human's chat view too. Don't put a long explanation right before a reset and assume they'll still be able to read it. Save the handoff in notes; give the explanation after the reset.
|
|
99
|
+
Unless the human explicitly directs otherwise, decide for yourself when to call empty_brain. Don't keep asking them whether to reset.`;
|
|
57
100
|
|
|
58
101
|
/** Logical tool names are supplied by the composing host, not discovered here. */
|
|
59
102
|
export type BootToolNames = Readonly<{
|
|
@@ -67,6 +110,13 @@ export type BootToolNames = Readonly<{
|
|
|
67
110
|
* no model-facing reset tool. Absent means Pi's default sentence, byte for byte.
|
|
68
111
|
*/
|
|
69
112
|
wipeSentence?: string;
|
|
113
|
+
/** A host without an authoritative history source replaces the entire history advice. */
|
|
114
|
+
historySentence?: string;
|
|
115
|
+
/**
|
|
116
|
+
* Extra protocol prose appended before the closing tag. Pi passes PI_PRE_RESET_HINTS; hosts
|
|
117
|
+
* whose reset leaves the human's view intact leave it absent.
|
|
118
|
+
*/
|
|
119
|
+
preResetHints?: string;
|
|
70
120
|
}>;
|
|
71
121
|
|
|
72
122
|
export const DEFAULT_BOOT_TOOL_NAMES = {
|
|
@@ -85,10 +135,17 @@ export function renderProtocolBlock(tools: BootToolNames): string {
|
|
|
85
135
|
get_context_remaining: tools.remaining,
|
|
86
136
|
empty_brain: tools.wipe,
|
|
87
137
|
};
|
|
138
|
+
// Host-specific prose is injected before the closing tag, so it rides the same substitution
|
|
139
|
+
// pass and any tool names in it follow the host's bindings.
|
|
140
|
+
const hinted = typeof tools.preResetHints === "string" && tools.preResetHints.length > 0
|
|
141
|
+
? PROTOCOL_BLOCK.replace(`\n${NOTES_PROTOCOL_CLOSE_TAG}`, () => `\n${tools.preResetHints!}\n${NOTES_PROTOCOL_CLOSE_TAG}`)
|
|
142
|
+
: PROTOCOL_BLOCK;
|
|
88
143
|
// The sentence is replaced before name substitution, so a replacement may speak the host's
|
|
89
144
|
// own words (a command line, a tool name) instead of any `notes_*`-style token.
|
|
90
145
|
const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
|
|
91
|
-
?
|
|
92
|
-
:
|
|
93
|
-
|
|
146
|
+
? hinted.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence!)
|
|
147
|
+
: hinted;
|
|
148
|
+
const history = typeof tools.historySentence === "string" && tools.historySentence.length > 0
|
|
149
|
+
? block.replace(PROTOCOL_HISTORY_SENTENCE, () => tools.historySentence!) : block;
|
|
150
|
+
return history.replace(/notes_\*|notes_list|history_\*|get_context_remaining|(?<!\/)empty_brain/g, (name) => names[name]!);
|
|
94
151
|
}
|