notesoup 0.58.1 → 0.58.2
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/docs/claude-code-mod.md
CHANGED
|
@@ -12,9 +12,17 @@ The warning remains `resetMarginTokens` (default 8192) plus `warningRunwayTokens
|
|
|
12
12
|
|
|
13
13
|
Once per window, when the measured context crosses the warning point, main-agent tool results or prompt submission carry exactly the same budget warning as Pi, ending with `empty_brain` and the countdown. Delivery is consumed only when the downstream chain accepts the warning. The warned flag resets with the window ordinal. Its own `session.compact` hook answers native compaction in the main conversation instead of letting it summarize: an automatic compaction (threshold or prompt-too-long) becomes the freshly built notes boot followed by one randomly selected handoff paragraph (normal only when the model called `empty_brain`, otherwise forced), selected once for the new window and reused on retry — the same boot-then-handoff order as Pi — while user `/compact` and precompute are vetoed with a one-line notice. `prompt.context` still recomputes but does not duplicate that retained boot. The boot's protocol block binds the shared reset sentence to `mcp__notesoup__empty_brain`; Pi's boot text is unchanged. Boot window IDs end in the ordinal `:0`, `:1`, etc.; retained boots restore the ordinal on resume/reload. Original transcript rows remain on disk. `session.end` forgets the old window, and identity is refreshed lazily from `$.session.id()`, `$.session.cwd()` and the documented `$.session.model()` (slugified, with `claude` only as a fallback). `/clear`, `/resume` and `/branch` therefore acquire a boot again without needing another `session.start`. A failed boot build falls back to Claude's own summary, which invalidates a removed retained boot; vetoes, subagent compaction and precompute leave it alone.
|
|
14
14
|
|
|
15
|
-
The
|
|
15
|
+
The reset flow has three separate lifetimes. `ResetFlow.request` lasts until successful reset or cancellation; it owns the first valid tool call's sticky note and continuation policy. `ResetState.commit` lasts for one native command attempt and tracks proof that Claude kept the boot. The per-turn cutoff can outlive the request when native auto compaction consumes it before the next step. Successful explicit reset and automatic reset share the same window/boot bookkeeping. A failed compaction retains the request for retry; an aborted, failed, or refused main turn cancels it. Session changes discard the flow and invalidate asynchronous work by generation.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
`empty_brain` accepts optional `last_word` and boolean `terminate` (default `false`). Non-boolean `terminate` is refused before recording a request. The first valid tool call owns both arguments for that pending reset; duplicates can re-arm the cutoff but cannot replace them. Every tool in the response's batch finishes, including parallel siblings. At the requesting main turn's next `turn.step`, the cutoff yields a synthetic `end_turn` without another model request or aborting tools. Subagent steps pass through, and subagents cannot reset the main brain. After successful main `turn.complete`, the non-held reset worker compacts; a confirmed commit permits one plugin-origin continuation unless `terminate: true`, manual STOP, or natural input has taken over. The handoff and sticky are already retained alongside the boot and are not repeated by that prompt.
|
|
18
|
+
|
|
19
|
+
Accepted natural input owns its continuation. Input received within the running turn, including input accepted before the first tool latch, releases the cutoff at the next step for the whole subsequent tool workflow. Input not yet delivered to a model request prevents reset work from starting. A separately queued natural turn also runs normally. No input is replayed. Native auto compaction consumes a pending request without resetting twice, while preserving its armed cutoff until turn completion or natural-input delivery; further auto compaction does not disarm it. Once that reset has completed and natural input releases its cutoff, a new `empty_brain` owns its own sticky and `terminate` policy. A consumed request's STOP does not carry into the new request.
|
|
20
|
+
|
|
21
|
+
`/empty` and `/fresh-window` request STOP for the same pending or in-flight reset, including one first requested by a tool. While idle they start one hidden normal-model close-out using the shared budget warning, so the model can save notes; while busy they use the current turn. A close-out tool call may select the normal handoff pool and sticky but cannot undo manual STOP. If the warning cannot load, submission fails, or another hook drops it, the request is cancelled so the command can retry. STOP controls automatic continuation; handoff selection still follows actual tool origin (normal) or no tool origin (forced). `DISABLE_COMPACT` refuses explicit requests and suppresses warnings.
|
|
22
|
+
|
|
23
|
+
Both interactive and headless (`-p` / SDK) resets use `$.command.run({command:"compact",args:...})`. A waiter armed in `session.start` runs this work outside held hooks and re-arms before submitting a close-out, avoiding prompt deadlock and lost completion signals. The command carries a unique instruction marker stored in its commit attempt; only matching manual compaction is admitted, while user `/compact` stays vetoed. Direct `$.session.compact` skips the calling mod's hook interactively and is unavailable headlessly. The command is enqueued before `turn.complete` returns, supporting single-prompt `-p` runs and open SDK streams.
|
|
24
|
+
|
|
25
|
+
A command receipt and prepared boot are not commit evidence. On Claude Code 2.1.319, interactive completion exposes the installed boot through `$.session.messages()`. Headless completion still exposes the old request snapshot and precedes appends, so the worker waits for successful main `session.append` results: a kept compact boundary followed by the unchanged boot with its UUID. A missing or rewritten boot, veto, or rejected command cannot start continuation. Boot acquisition failure vetoes an explicit reset without advancing the window. After commit, a dropped or failed continuation is reported without compacting again. Native command/output rows remain alongside the fresh boot; no compaction model request is made. A Claude dream backend is not implemented, and budget reporting (`get_context_remaining`) remains Pi-only.
|
|
18
26
|
|
|
19
27
|
The notes tools also serve subagent calls, using the same session identity and shared operations. The plugin exposes the shared memory and dream skills and the dream playbook; the build keeps these copies byte-identical to the canonical files.
|
|
20
28
|
|
|
@@ -36,4 +44,8 @@ Without a path back to a root or retained boot, window ordinals are unknown. Tho
|
|
|
36
44
|
|
|
37
45
|
## Validation
|
|
38
46
|
|
|
39
|
-
`npm run typecheck` includes the mod against the vendored Claude Code 2.1.295 contract. `npm test` also typechecks it and runs `claude plugin validate plugins/claude --strict`, skipping validation with a clear message only if `claude` is not installed. Scanner regression tests deliberately reintroduce each of the three forbidden call shapes and require the gate to fail.
|
|
47
|
+
`npm run typecheck` includes the mod against the vendored Claude Code 2.1.295 contract. `npm test` also typechecks it and runs `claude plugin validate plugins/claude --strict`, skipping validation with a clear message only if `claude` is not installed. Scanner regression tests deliberately reintroduce each of the three forbidden call shapes and require the gate to fail. Unit regressions drain the `turn.step` generator (including its final return value), distinguish a command receipt from deferred kept rows, and cover optional/default/explicit `terminate`, first-request-wins arguments, invalid booleans, manual STOP, STOP consumed by native automatic compaction, accepted natural input, failed commits, submission failures, and session changes.
|
|
48
|
+
|
|
49
|
+
The reset sequence was also verified with the installed Claude Code 2.1.319 main loop, using a scripted Anthropic service bound to loopback, isolated homes/settings/working directories, fake credentials, and a sandbox blocking external network access and reads of the real home. Single-prompt `-p`, open `stream-json`, and an interactive PTY all produced one clean request after a committed tool reset. The probe also checked parallel fast/slow `Read` siblings, `terminate:true` (one original API request, one commit, no kickoff) and explicit `terminate:false` (one commit followed by one fresh-window API request), manual close-out STOP even when it calls the tool, compaction vetoes, continuation drops, interruption, and natural input delivered within the running turn. These are host integration observations, separate from the unit harness. A skip returned after `next()` has already compacted is rejected by 2.1.319; that compaction stands. Valid vetoes return before calling `next`.
|
|
50
|
+
|
|
51
|
+
From a built checkout, check the real load with `claude --plugin-dir plugins/claude -p "ok"`; a model/API failure after load is separate from a hooks-module refusal. The package build and `npm pack --dry-run` include the manifests, hooks module, helper, skills, and playbook.
|
package/package.json
CHANGED
|
@@ -8,7 +8,7 @@ const OUTPUT_LIMIT = 1024 * 1024
|
|
|
8
8
|
type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
|
|
9
9
|
type SchemaRow = { name: string; description: string; inputSchema: Record<string, unknown> }
|
|
10
10
|
type HistorySource = { sessionId: string; transcriptPath: string; headUuid?: string }
|
|
11
|
-
type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "
|
|
11
|
+
type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "prompt" | "env" | "settings" | "command">
|
|
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. */
|
|
@@ -17,14 +17,78 @@ 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
|
+
type ResetRequest = { tool?: { lastWord?: string }; resume: boolean }
|
|
21
|
+
/** Request: until consumed/cancelled. Cutoff: one turn, even after auto consumes the request.
|
|
22
|
+
* Commit lives separately in ResetState: one native command attempt, proved by kept rows. */
|
|
23
|
+
class ResetFlow {
|
|
24
|
+
request?: ResetRequest
|
|
25
|
+
cutoffTurnId?: string
|
|
26
|
+
turnId?: string
|
|
27
|
+
pendingInputTurnId?: string
|
|
28
|
+
running = false
|
|
29
|
+
|
|
30
|
+
requestReset(tool?: { lastWord?: string; terminate: boolean }): boolean {
|
|
31
|
+
const first = tool ? this.request?.tool === undefined : this.request === undefined
|
|
32
|
+
const request = this.request ??= { resume: true }
|
|
33
|
+
if (tool) {
|
|
34
|
+
if (first) {
|
|
35
|
+
request.tool = { lastWord: tool.lastWord }
|
|
36
|
+
request.resume &&= !tool.terminate
|
|
37
|
+
}
|
|
38
|
+
this.cutoffTurnId = this.turnId
|
|
39
|
+
} else request.resume = false
|
|
40
|
+
return first
|
|
41
|
+
}
|
|
42
|
+
input(turnId?: string) {
|
|
43
|
+
if (turnId !== undefined) this.pendingInputTurnId = turnId
|
|
44
|
+
if (this.request?.tool) this.request.resume = false
|
|
45
|
+
}
|
|
46
|
+
start(turnId: string) {
|
|
47
|
+
if (this.request?.tool) this.request.resume = false
|
|
48
|
+
this.turnId = turnId
|
|
49
|
+
this.running = true
|
|
50
|
+
}
|
|
51
|
+
cutoff(turnId: string): boolean {
|
|
52
|
+
// Input may predate the tool latch. Release the whole workflow, not just one request.
|
|
53
|
+
if (this.pendingInputTurnId !== undefined && this.pendingInputTurnId === turnId) {
|
|
54
|
+
this.pendingInputTurnId = undefined
|
|
55
|
+
this.cutoffTurnId = undefined
|
|
56
|
+
if (this.request) this.request.resume = false
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
return turnId === this.cutoffTurnId
|
|
60
|
+
}
|
|
61
|
+
complete(reason: string): boolean {
|
|
62
|
+
this.running = false
|
|
63
|
+
const cancelled = reason !== "answer" && this.request !== undefined
|
|
64
|
+
if (cancelled || !this.request) this.cancel()
|
|
65
|
+
return cancelled
|
|
66
|
+
}
|
|
67
|
+
get ready(): boolean {
|
|
68
|
+
return !!this.request && !this.running && !(this.pendingInputTurnId !== undefined && this.pendingInputTurnId === this.turnId)
|
|
69
|
+
}
|
|
70
|
+
consume(auto = false): boolean {
|
|
71
|
+
const request = this.request
|
|
72
|
+
// Another auto reset must not disarm an already consumed request's cutoff.
|
|
73
|
+
if (auto && !request) return false
|
|
74
|
+
this.cutoffTurnId = auto && request && !request.resume ? this.cutoffTurnId ?? (!request.tool ? this.turnId : undefined) : undefined
|
|
75
|
+
this.request = undefined
|
|
76
|
+
return request?.tool !== undefined && request.resume
|
|
77
|
+
}
|
|
78
|
+
cancel() {
|
|
79
|
+
this.request = undefined
|
|
80
|
+
this.cutoffTurnId = undefined
|
|
81
|
+
}
|
|
82
|
+
}
|
|
20
83
|
type ResetState = {
|
|
21
|
-
identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; disabled: boolean;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
continuation?: string; continuationWindow?: number
|
|
84
|
+
identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; disabled: boolean; flow: ResetFlow
|
|
85
|
+
headless: boolean; usageFailureLogged: boolean; commit?: { instructions: string; boot?: string; boundary: boolean; resolve: (kept: boolean) => void }; retainedBoot?: string
|
|
86
|
+
continuation?: { window: number; text: string }
|
|
25
87
|
compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsKey?: string
|
|
26
88
|
limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
27
89
|
}
|
|
90
|
+
type ResetWork = { kind: "closeout" | "reset"; generation: number }
|
|
91
|
+
type ResetSignal = { wake?: (work: ResetWork) => void }
|
|
28
92
|
const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
|
|
29
93
|
const NOTESOUP_DISABLED = "Notesoup is off with NOTESOUP_DISABLED"
|
|
30
94
|
const THRESHOLDS_UNAVAILABLE = "Brain size unknown · no budget warning"
|
|
@@ -61,7 +125,7 @@ async function resetMessages($: Engine, state: ResetState, identity: Identity):
|
|
|
61
125
|
return { boot: text, messages: [
|
|
62
126
|
{ role: "user", text, toolUses: [] },
|
|
63
127
|
{ role: "user", text: continuation, toolUses: [] },
|
|
64
|
-
...(state.lastWord ? [{ role: "user" as const, text: `*You peel a sticky note off your forehead.*\n${state.lastWord}`, toolUses: [] as [] }] : []),
|
|
128
|
+
...(state.flow.request?.tool?.lastWord ? [{ role: "user" as const, text: `*You peel a sticky note off your forehead.*\n${state.flow.request.tool.lastWord}`, toolUses: [] as [] }] : []),
|
|
65
129
|
] }
|
|
66
130
|
}
|
|
67
131
|
function numberOf(value: unknown): number | undefined {
|
|
@@ -185,15 +249,14 @@ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | un
|
|
|
185
249
|
}
|
|
186
250
|
/** One draw per reset artifact, reused on retry; only a real tool request is voluntary. */
|
|
187
251
|
async function continuationFor($: Engine, state: ResetState): Promise<string | undefined> {
|
|
188
|
-
if (state.continuation
|
|
252
|
+
if (state.continuation?.window === state.window) return state.continuation.text
|
|
189
253
|
const generation = state.generation
|
|
190
|
-
const response = await run($, { op: "continuation", origin: state.
|
|
254
|
+
const response = await run($, { op: "continuation", origin: state.flow.request?.tool ? "normal" : "forced" })
|
|
191
255
|
if (generation !== state.generation) return undefined
|
|
192
256
|
const result = response.ok ? response.result : undefined
|
|
193
257
|
const text = typeof result === "object" && result !== null ? (result as { text?: unknown }).text : undefined
|
|
194
258
|
if (typeof text !== "string" || text.length === 0) return undefined
|
|
195
|
-
state.continuation = text
|
|
196
|
-
state.continuationWindow = state.window
|
|
259
|
+
state.continuation = { window: state.window, text }
|
|
197
260
|
return text
|
|
198
261
|
}
|
|
199
262
|
function log($: Engine, text: string) {
|
|
@@ -230,23 +293,19 @@ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?:
|
|
|
230
293
|
// reason (`timed out after …`), which a bare phrase would throw away.
|
|
231
294
|
catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
|
|
232
295
|
}
|
|
233
|
-
function clearManualRequest(state: ResetState): void {
|
|
234
|
-
state.manualPending = false
|
|
235
|
-
state.toolResetRequested = state.lastWord = undefined
|
|
236
|
-
}
|
|
237
296
|
/** Session start does not fire on /clear, /resume or /branch. Forget the old window on end. */
|
|
238
297
|
function forgetSession(state: ResetState) {
|
|
239
298
|
state.generation++
|
|
240
299
|
state.identity = undefined
|
|
241
300
|
state.historyWindowHead = undefined
|
|
242
301
|
state.window = 0
|
|
243
|
-
state.
|
|
244
|
-
|
|
245
|
-
state.
|
|
246
|
-
state.
|
|
302
|
+
state.flow = new ResetFlow()
|
|
303
|
+
state.usageFailureLogged = false
|
|
304
|
+
state.commit?.resolve(false)
|
|
305
|
+
state.commit = undefined
|
|
306
|
+
state.retainedBoot = undefined
|
|
247
307
|
state.texts = state.limits = undefined
|
|
248
308
|
state.continuation = undefined
|
|
249
|
-
state.continuationWindow = undefined
|
|
250
309
|
state.limitsAttempts = 0
|
|
251
310
|
state.limitsKey = undefined
|
|
252
311
|
state.settingsFailureLogged = state.limitsFailureLogged = false
|
|
@@ -269,7 +328,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
|
|
|
269
328
|
if (state.identity?.sessionId === sessionId) {
|
|
270
329
|
state.identity = { ...state.identity, cwd, model }
|
|
271
330
|
await syncHistoryWindow($, state)
|
|
272
|
-
return state.identity
|
|
331
|
+
return generation === state.generation ? state.identity : undefined
|
|
273
332
|
}
|
|
274
333
|
const home = await $.env.get("NOTESOUP_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
|
|
275
334
|
if (generation !== state.generation) return undefined
|
|
@@ -288,7 +347,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
|
|
|
288
347
|
|
|
289
348
|
/** A committed append is the head evidence; the persisted file may trail it briefly. */
|
|
290
349
|
async function syncHistoryWindow($: Engine, state: ResetState) {
|
|
291
|
-
if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.
|
|
350
|
+
if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.commit || state.historyWindowHead === state.history.headUuid) return
|
|
292
351
|
const generation = state.generation, head = state.history.headUuid
|
|
293
352
|
const response = await run($, { op: "history_state", identity: state.identity, history: state.history })
|
|
294
353
|
if (generation !== state.generation || state.history?.headUuid !== head || !response.ok || typeof response.result !== "object" || response.result === null) return
|
|
@@ -299,8 +358,8 @@ async function syncHistoryWindow($: Engine, state: ResetState) {
|
|
|
299
358
|
}
|
|
300
359
|
|
|
301
360
|
export function register(on: On) {
|
|
302
|
-
const
|
|
303
|
-
const state: ResetState = { generation: 0, window: 0, disabled: false,
|
|
361
|
+
const resetSignal: ResetSignal = {}
|
|
362
|
+
const state: ResetState = { generation: 0, window: 0, disabled: false, flow: new ResetFlow(), headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, settingsFailureLogged: false }
|
|
304
363
|
const registered = new Set<string>()
|
|
305
364
|
let keepMemory = false
|
|
306
365
|
// Classic SessionStart precedes typed session.start and startup appends. Keep this binding
|
|
@@ -313,11 +372,26 @@ export function register(on: On) {
|
|
|
313
372
|
return next(e)
|
|
314
373
|
})
|
|
315
374
|
on("session.append", async ($, e, next) => {
|
|
375
|
+
const generation = state.generation, commit = state.commit
|
|
316
376
|
const sessionId = await $.session.id(), source = state.history
|
|
317
377
|
const result = await next(e)
|
|
318
|
-
if (e.agentId === undefined && result.uuid !== undefined &&
|
|
319
|
-
|
|
320
|
-
|
|
378
|
+
if (e.agentId === undefined && result.uuid !== undefined && generation === state.generation) {
|
|
379
|
+
if (state.history === source && source?.sessionId === sessionId) {
|
|
380
|
+
source.headUuid = result.uuid
|
|
381
|
+
state.historyWindowHead = undefined
|
|
382
|
+
}
|
|
383
|
+
// A native command resolves before its compaction rows finish appending;
|
|
384
|
+
// session.messages() still exposes the last request's snapshot. Observe
|
|
385
|
+
// the host's kept boundary and first plugin row, including rewrites.
|
|
386
|
+
if (commit && commit === state.commit && state.identity?.sessionId === sessionId) {
|
|
387
|
+
if (e.door === "compaction" && result.message.name === "compact_boundary") commit.boundary = true
|
|
388
|
+
if (e.origin.kind === "plugin" && "name" in e.origin && e.origin.name === "notesoup") {
|
|
389
|
+
if (commit.boundary && e.door === "prompt") {
|
|
390
|
+
const blocks = result.message.content
|
|
391
|
+
commit.resolve(result.message.type === "user" && blocks.length === 1 && blocks[0]?.type === "text" && blocks[0].text === commit.boot)
|
|
392
|
+
} else if (e.door === "command") commit.resolve(false)
|
|
393
|
+
}
|
|
394
|
+
}
|
|
321
395
|
}
|
|
322
396
|
return result
|
|
323
397
|
})
|
|
@@ -337,13 +411,13 @@ export function register(on: On) {
|
|
|
337
411
|
if (state.compactDisabled) log($, COMPACT_DISABLED)
|
|
338
412
|
registered.clear()
|
|
339
413
|
await loadTexts($, state)
|
|
340
|
-
|
|
414
|
+
armReset($, state, resetSignal)
|
|
341
415
|
await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
342
416
|
await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
|
|
343
417
|
const wipe = await $.tool.register({
|
|
344
418
|
name: "empty_brain",
|
|
345
419
|
description: "Clear your in-context memory and start a fresh context window. Your session, notes, and history survive. Pass `last_word` to stick a tiny note on your forehead for after the wipe.",
|
|
346
|
-
inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note, at most 300 characters. After the wipe it is slapped on your forehead; longer notes are refused." } }, additionalProperties: false },
|
|
420
|
+
inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note, at most 300 characters. After the wipe it is slapped on your forehead; longer notes are refused." }, terminate: { type: "boolean", description: "Stop after the wipe. Default: false.", default: false } }, additionalProperties: false },
|
|
347
421
|
isDeferred: false,
|
|
348
422
|
} satisfies ToolSpec)
|
|
349
423
|
registered.add(wipe.tool)
|
|
@@ -367,70 +441,73 @@ export function register(on: On) {
|
|
|
367
441
|
if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
|
|
368
442
|
return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
|
|
369
443
|
})
|
|
370
|
-
on("prompt.submit", ($, e, next) =>
|
|
371
|
-
|
|
444
|
+
on("prompt.submit", async ($, e, next) => {
|
|
445
|
+
const generation = state.generation
|
|
446
|
+
const result = await withWarning($, state, (warning) =>
|
|
447
|
+
next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] }))
|
|
448
|
+
// Our own submissions skip this hook; accepted input owns the continuation.
|
|
449
|
+
if (generation === state.generation && result.drop === undefined) state.flow.input(e.turnId)
|
|
450
|
+
return result
|
|
451
|
+
})
|
|
372
452
|
on("turn.start", async ($, e, next) => {
|
|
373
453
|
// The documented turn.start is main-loop only. Guard tagged host events too:
|
|
374
454
|
// only a main-agent turn.complete clears this latch.
|
|
375
455
|
if (state.disabled) return next(e)
|
|
376
456
|
if ("agentId" in e && e.agentId !== undefined) return next(e)
|
|
377
457
|
if (!await refreshIdentity($, state)) return next(e)
|
|
378
|
-
state.
|
|
458
|
+
state.flow.start(e.turnId)
|
|
379
459
|
return next(e)
|
|
380
460
|
})
|
|
461
|
+
on("turn.step", async function* ($, e, next) {
|
|
462
|
+
if (state.disabled || e.agentId !== undefined) return yield* next(e)
|
|
463
|
+
if (!state.flow.cutoff(e.turnId)) return yield* next(e)
|
|
464
|
+
// This boundary follows the entire tool batch. A synthetic streamed stop
|
|
465
|
+
// ends the main turn without aborting siblings or making an old-window request.
|
|
466
|
+
yield { kind: "stop", stopReason: "end_turn", usage: null }
|
|
467
|
+
return { turnId: e.turnId, index: e.index, answer: "", toolUses: [], stopReason: "end_turn", usage: null }
|
|
468
|
+
})
|
|
381
469
|
on("turn.complete", async ($, e, next) => {
|
|
470
|
+
const generation = state.generation
|
|
382
471
|
const result = await next(e)
|
|
383
|
-
if (e.agentId !== undefined) return result
|
|
384
|
-
|
|
472
|
+
if (e.agentId !== undefined || generation !== state.generation) return result
|
|
473
|
+
const cancelled = state.flow.complete(e.reason)
|
|
385
474
|
if (state.disabled) return result
|
|
386
|
-
// A failed turn proves nothing about whether its notes were saved.
|
|
387
|
-
|
|
388
|
-
if (e.reason !== "answer" && state.manualPending) cancelManualReset($, state, e.reason)
|
|
475
|
+
// A failed turn proves nothing about whether its notes were saved.
|
|
476
|
+
if (cancelled) log($, `Brain emptying cancelled · turn ended ${e.reason}; ask /fresh-window again`)
|
|
389
477
|
if (!await refreshIdentity($, state)) return result
|
|
390
|
-
if (e.reason === "answer" && state.
|
|
478
|
+
if (e.reason === "answer" && state.flow.request) resetSignal.wake?.({ kind: "reset", generation: state.generation })
|
|
391
479
|
return result
|
|
392
480
|
})
|
|
393
481
|
on("command.run", async ($, e, next) => {
|
|
394
482
|
if (state.disabled) return next(e)
|
|
395
|
-
// Only our queued native command admits manual compaction. A user's /compact
|
|
396
|
-
// still reaches the veto, even while a reset is pending.
|
|
397
|
-
if (e.command === "compact" && state.resetting && state.headless && e.origin.kind === "plugin" && e.origin.name === "notesoup") {
|
|
398
|
-
state.manualCompacting = true
|
|
399
|
-
try { return await next(e) } finally { state.manualCompacting = false }
|
|
400
|
-
}
|
|
401
483
|
if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
|
|
402
484
|
if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
|
|
403
485
|
if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
|
|
404
|
-
|
|
405
|
-
if (state.
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
// command.run holds a turn even when idle. Start one hidden close-out
|
|
410
|
-
// turn after it returns; turn.complete is the verified self-hook path.
|
|
411
|
-
state.manualPending = true
|
|
412
|
-
manualSignal.wake?.()
|
|
486
|
+
const first = state.flow.requestReset()
|
|
487
|
+
if (state.commit || !first) return { text: "🥣 Brain already being emptied" }
|
|
488
|
+
// command.run holds a turn even when idle; close out from the non-held waiter.
|
|
489
|
+
if (!state.flow.running) resetSignal.wake?.({ kind: "closeout", generation: state.generation })
|
|
413
490
|
return { text: "🥣 Dumping Brain" }
|
|
414
491
|
})
|
|
415
492
|
on("session.compact", async ($, e, next) => {
|
|
416
493
|
// Disabled means fully transparent: native compaction runs exactly as if the mod were absent.
|
|
417
494
|
if (state.disabled) return next(e)
|
|
418
495
|
if (e.agentId !== undefined) return next(e)
|
|
419
|
-
const identity = await refreshIdentity($, state)
|
|
420
496
|
const generation = state.generation
|
|
497
|
+
const identity = await refreshIdentity($, state)
|
|
421
498
|
// Every pass-through keeps the current boot unless the engine's own summary replaced it.
|
|
422
499
|
const passThrough = async () => {
|
|
423
500
|
const result = await next(e)
|
|
424
501
|
// Precompute installs nothing; a veto or subagent compact cannot remove our boot.
|
|
425
502
|
if (generation === state.generation && e.trigger !== "precompute" && result.skip === undefined) {
|
|
426
503
|
state.retainedBoot = result.messages.some((message) => message.text === state.retainedBoot) ? state.retainedBoot : undefined
|
|
427
|
-
state.
|
|
504
|
+
if (state.commit) state.commit.boot = undefined
|
|
428
505
|
}
|
|
429
506
|
return result
|
|
430
507
|
}
|
|
431
508
|
// Native compaction never runs the summarizer while notesoup is on: user
|
|
432
509
|
// manual and precompute are vetoed; auto becomes the notes-only reset.
|
|
433
|
-
const own = state.
|
|
510
|
+
const own = state.commit !== undefined && identity !== undefined && e.trigger === "manual" && e.instructions === state.commit.instructions
|
|
434
511
|
if (e.trigger === "manual" && !own) return { skip: "No compacting brains here · use /fresh-window" }
|
|
435
512
|
if (e.trigger === "precompute") return { skip: "No precomputing brains here" }
|
|
436
513
|
if (!own && e.trigger !== "auto") return passThrough()
|
|
@@ -442,16 +519,8 @@ export function register(on: On) {
|
|
|
442
519
|
log($, `Notes didn't load (${built.skip}) · Claude compacted natively`)
|
|
443
520
|
return passThrough()
|
|
444
521
|
}
|
|
445
|
-
if (
|
|
446
|
-
|
|
447
|
-
} else {
|
|
448
|
-
// The auto hijack keeps the books a successful plugin reset does.
|
|
449
|
-
state.retainedBoot = built.boot
|
|
450
|
-
state.preparedBoot = undefined
|
|
451
|
-
state.window++
|
|
452
|
-
clearManualRequest(state)
|
|
453
|
-
log($, "Brain emptied")
|
|
454
|
-
}
|
|
522
|
+
if (state.commit) state.commit.boot = own ? built.boot : undefined
|
|
523
|
+
if (!own) retainReset($, state, built.boot, true)
|
|
455
524
|
return { messages: built.messages }
|
|
456
525
|
})
|
|
457
526
|
// notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
|
|
@@ -495,17 +564,12 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
|
|
|
495
564
|
if (agentId !== undefined) return errorResult("only the main agent can empty this brain")
|
|
496
565
|
if (state.compactDisabled) return errorResult(COMPACT_DISABLED)
|
|
497
566
|
if (params.last_word !== undefined && typeof params.last_word !== "string") return errorResult("last_word must be a string")
|
|
567
|
+
if (params.terminate !== undefined && typeof params.terminate !== "boolean") return errorResult("terminate must be a boolean")
|
|
498
568
|
const lastWord = typeof params.last_word === "string" ? params.last_word.trim() || undefined : undefined
|
|
499
569
|
const length = lastWord ? Array.from(lastWord).length : 0
|
|
500
570
|
if (length > 500) return errorResult(`last_word is ${length} characters; the sticky note holds 500. Shorten it and call again.`)
|
|
501
|
-
if (
|
|
502
|
-
|
|
503
|
-
state.lastWord = lastWord
|
|
504
|
-
state.continuation = undefined
|
|
505
|
-
state.continuationWindow = undefined
|
|
506
|
-
}
|
|
507
|
-
state.manualPending = true
|
|
508
|
-
return { result: "Brain will be emptied after this turn. End your turn now; do not call more tools or explain things to the human before the reset." }
|
|
571
|
+
if (state.flow.requestReset({ lastWord, terminate: params.terminate === true })) state.continuation = undefined
|
|
572
|
+
return { result: `Brain reset requested. This tool batch will finish, then the turn stops before its next model request unless it has new user input to handle. Your notes and sticky note survive the reset.${state.flow.request!.resume ? " You will continue in a fresh window after the reset." : " No automatic continuation will be submitted."}` }
|
|
509
573
|
}
|
|
510
574
|
if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
|
|
511
575
|
const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
|
|
@@ -568,88 +632,92 @@ function restoreWindow(state: ResetState, messages: readonly { role: string; tex
|
|
|
568
632
|
}
|
|
569
633
|
}
|
|
570
634
|
|
|
571
|
-
//
|
|
572
|
-
//
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
const requested = new Promise<
|
|
576
|
-
void requested.then(() => {
|
|
577
|
-
signal.wake
|
|
578
|
-
|
|
579
|
-
|
|
635
|
+
// Create and re-arm this waiter in session.start's non-held context. Timers
|
|
636
|
+
// created in a held hook inherit that dispatch even after the hook returns.
|
|
637
|
+
function armReset($: Engine, state: ResetState, signal: ResetSignal) {
|
|
638
|
+
let wake!: (work: ResetWork) => void
|
|
639
|
+
const requested = new Promise<ResetWork>((resolve) => { signal.wake = wake = resolve })
|
|
640
|
+
void requested.then((work) => {
|
|
641
|
+
if (signal.wake !== wake) return
|
|
642
|
+
// A close-out submission resolves when its turn starts, so arm the next
|
|
643
|
+
// waiter before submitting: that turn's completion must not lose its wake.
|
|
644
|
+
armReset($, state, signal)
|
|
645
|
+
return runResetWork($, state, work)
|
|
580
646
|
})
|
|
581
647
|
}
|
|
582
|
-
async function
|
|
648
|
+
async function runResetWork($: Engine, state: ResetState, work: ResetWork) {
|
|
649
|
+
const { generation, kind } = work
|
|
650
|
+
if (generation !== state.generation || !state.flow.ready) return
|
|
583
651
|
try {
|
|
584
|
-
|
|
585
|
-
if (
|
|
652
|
+
let text: string
|
|
653
|
+
if (kind === "reset") {
|
|
654
|
+
const turnId = state.flow.turnId
|
|
655
|
+
if (!await reset($, state) || generation !== state.generation || turnId !== state.flow.turnId || state.flow.request?.resume === false) return
|
|
656
|
+
// The retained handoff is already present; this prompt only starts the next turn.
|
|
657
|
+
text = "Continue from your notes in this fresh context window."
|
|
658
|
+
} else {
|
|
586
659
|
const texts = await loadTexts($, state)
|
|
587
660
|
if (generation !== state.generation) return
|
|
588
661
|
if (texts?.warning === undefined) {
|
|
589
|
-
|
|
662
|
+
state.flow.cancel()
|
|
590
663
|
log($, "Brain still full: the close-out prompt didn't load")
|
|
591
664
|
return
|
|
592
665
|
}
|
|
593
|
-
|
|
594
|
-
if (generation === state.generation && result.drop !== undefined) {
|
|
595
|
-
clearManualRequest(state)
|
|
596
|
-
log($, "Brain still full: the close-out turn didn't start")
|
|
597
|
-
}
|
|
666
|
+
text = texts.warning
|
|
598
667
|
}
|
|
599
|
-
|
|
600
|
-
if (
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
668
|
+
const result = await $.prompt.submit({ text })
|
|
669
|
+
if (result.drop !== undefined) throw result.drop
|
|
670
|
+
} catch (error) {
|
|
671
|
+
if (generation !== state.generation) return
|
|
672
|
+
if (kind === "closeout") state.flow.cancel()
|
|
673
|
+
log($, kind === "closeout" ? "Brain still full: the close-out turn didn't start" : `Brain emptied, but continuation didn't start · ${describeFailure(error)}`)
|
|
674
|
+
}
|
|
605
675
|
}
|
|
606
676
|
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
677
|
+
function retainReset($: Engine, state: ResetState, boot: string, auto = false): boolean {
|
|
678
|
+
state.retainedBoot = boot
|
|
679
|
+
state.window++
|
|
680
|
+
const resume = state.flow.consume(auto)
|
|
681
|
+
log($, "Brain emptied")
|
|
682
|
+
return resume
|
|
611
683
|
}
|
|
612
684
|
|
|
613
685
|
// The sandbox permits $ forwarding only to file-top-level helpers.
|
|
614
|
-
async function reset($: Engine, state: ResetState): Promise<
|
|
615
|
-
if (!state.identity || state.compactDisabled || state.
|
|
686
|
+
async function reset($: Engine, state: ResetState): Promise<boolean> {
|
|
687
|
+
if (!state.identity || state.compactDisabled || state.commit) return false
|
|
616
688
|
const generation = state.generation
|
|
617
|
-
|
|
618
|
-
|
|
689
|
+
let resolveCommit!: (kept: boolean) => void
|
|
690
|
+
const committed = new Promise<boolean>((resolve) => { resolveCommit = resolve })
|
|
691
|
+
const commit = state.commit = { instructions: `${RESET_INSTRUCTIONS} ${crypto.randomUUID()}`, boot: undefined as string | undefined, boundary: false, resolve: resolveCommit }
|
|
619
692
|
try {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
//
|
|
626
|
-
//
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
693
|
+
// Both modes need the native command; direct compact skips our hook or is unavailable.
|
|
694
|
+
const receipt = await $.command.run({ command: "compact", args: commit.instructions })
|
|
695
|
+
if (generation !== state.generation) return false
|
|
696
|
+
let failure = commit.boot === undefined ? receipt.text ?? "notes boot was not retained" : undefined
|
|
697
|
+
if (failure === undefined) {
|
|
698
|
+
// Interactive command completion exposes the newly installed rows here;
|
|
699
|
+
// headless completion still sees the old request and appends afterwards.
|
|
700
|
+
const messages = await $.session.messages()
|
|
701
|
+
if (generation !== state.generation) return false
|
|
702
|
+
if (messages.some((message) => message.role === "user" && message.text === commit.boot)) commit.resolve(true)
|
|
703
|
+
else if (!state.headless) commit.resolve(false)
|
|
704
|
+
if (!await committed) failure = "notes boot was not committed"
|
|
631
705
|
}
|
|
632
|
-
if (generation !== state.generation) return
|
|
633
|
-
if (failure !== undefined ||
|
|
634
|
-
state.manualPending = true
|
|
706
|
+
if (generation !== state.generation) return false
|
|
707
|
+
if (failure !== undefined || commit.boot === undefined) {
|
|
635
708
|
log($, `Brain not emptied · ${failure ?? "notes boot was not retained"}`)
|
|
636
|
-
return
|
|
709
|
+
return false
|
|
637
710
|
}
|
|
638
|
-
|
|
639
|
-
state.window++
|
|
640
|
-
clearManualRequest(state)
|
|
641
|
-
log($, "Brain emptied")
|
|
711
|
+
return retainReset($, state, commit.boot)
|
|
642
712
|
} catch (error) {
|
|
643
|
-
if (generation !== state.generation) return
|
|
713
|
+
if (generation !== state.generation) return false
|
|
644
714
|
const text = String(error)
|
|
645
|
-
state.manualPending = true
|
|
646
715
|
if (!/a turn is (running|in flight)/.test(text)) {
|
|
647
716
|
log($, `Brain still full: ${text.replace(/[\r\n].*$/s, "")}`)
|
|
648
717
|
}
|
|
718
|
+
return false
|
|
649
719
|
} finally {
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
state.resetting = false
|
|
653
|
-
}
|
|
720
|
+
commit.resolve(false)
|
|
721
|
+
if (state.commit === commit) state.commit = undefined
|
|
654
722
|
}
|
|
655
723
|
}
|