notesoup 0.58.0 → 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.
@@ -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" | "clock" | "prompt" | "env" | "settings" | "command">
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; turnRunning: boolean; resetting: boolean
22
- manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
23
- toolResetRequested?: boolean; lastWord?: string; manualCompacting?: boolean
24
- continuation?: string; continuationWindow?: number
25
- compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: 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 }
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 {
@@ -131,11 +195,12 @@ async function breakdownContext($: Engine): Promise<Record<string, unknown> | un
131
195
  return typeof breakdown === "object" && breakdown !== null ? breakdown as unknown as Record<string, unknown> : undefined
132
196
  } catch { return undefined }
133
197
  }
134
- /** Everything the resolver may read: measured usage plus the raw settings and environment. */
198
+ /** Threshold inputs only: changing fill must not invalidate the resolved points. */
135
199
  async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Promise<Record<string, unknown>> {
200
+ const breakdown = await breakdownContext($)
136
201
  return {
137
- usage,
138
- breakdown: await breakdownContext($),
202
+ usage: { window: usage.window },
203
+ breakdown: { model: breakdown?.model, autoCompactThreshold: breakdown?.autoCompactThreshold, isAutoCompactEnabled: breakdown?.isAutoCompactEnabled },
139
204
  settings: await readSettings($, state),
140
205
  env: {
141
206
  pctOverride: await envPctOverride($),
@@ -144,35 +209,26 @@ async function limitFacts($: Engine, state: ResetState, usage: ContextUsage): Pr
144
209
  },
145
210
  }
146
211
  }
147
- /**
148
- * The points the current window is measured against, resolved by the helper's shared
149
- * derivation. One resolved result per reported window value: an unknown window resolves the
150
- * percent fallback, and a later real window re-resolves against it. A failed round trip is
151
- * retried a bounded number of times instead of disabling thresholds for the whole window.
152
- */
212
+ /** Reuse points only while their inputs match; bound retries per configuration, not capacity. */
153
213
  async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Promise<ClaudeLimits | undefined> {
154
- const window = usage.window !== undefined && usage.window > 0 ? usage.window : 0
155
- const sameWindow = state.limitsWindow === window
156
- if (sameWindow && state.limits !== undefined) return state.limits
157
- if (sameWindow && state.limitsAttempts >= MAX_LIMITS_ATTEMPTS) return undefined
158
214
  const generation = state.generation
159
215
  const facts = await limitFacts($, state, usage)
160
216
  if (generation !== state.generation) return undefined
217
+ const key = JSON.stringify([state.identity?.model, facts])
218
+ const sameFacts = state.limitsKey === key
219
+ if (sameFacts && state.limits !== undefined) return state.limits
220
+ if (sameFacts && state.limitsAttempts >= MAX_LIMITS_ATTEMPTS) return undefined
161
221
  const response = await run($, { op: "limits", facts })
162
222
  if (generation !== state.generation) return undefined
163
223
  const limits = response.ok ? limitsShape(response.result) : undefined
164
- state.limitsWindow = window
165
- if (limits) {
166
- state.limits = limits
167
- state.limitsAttempts = 0
168
- return limits
169
- }
170
- state.limitsAttempts = sameWindow ? state.limitsAttempts + 1 : 1
171
- if (!state.limitsFailureLogged) {
224
+ state.limitsKey = key
225
+ state.limits = limits
226
+ state.limitsAttempts = limits ? 0 : sameFacts ? state.limitsAttempts + 1 : 1
227
+ if (!limits && !state.limitsFailureLogged) {
172
228
  state.limitsFailureLogged = true
173
229
  log($, THRESHOLDS_UNAVAILABLE)
174
230
  }
175
- return undefined
231
+ return limits
176
232
  }
177
233
  /** The measured value the points are expressed in; tokens win, percent × window stands in. */
178
234
  function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | undefined {
@@ -193,15 +249,14 @@ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | un
193
249
  }
194
250
  /** One draw per reset artifact, reused on retry; only a real tool request is voluntary. */
195
251
  async function continuationFor($: Engine, state: ResetState): Promise<string | undefined> {
196
- if (state.continuation !== undefined && state.continuationWindow === state.window) return state.continuation
252
+ if (state.continuation?.window === state.window) return state.continuation.text
197
253
  const generation = state.generation
198
- const response = await run($, { op: "continuation", origin: state.toolResetRequested ? "normal" : "forced" })
254
+ const response = await run($, { op: "continuation", origin: state.flow.request?.tool ? "normal" : "forced" })
199
255
  if (generation !== state.generation) return undefined
200
256
  const result = response.ok ? response.result : undefined
201
257
  const text = typeof result === "object" && result !== null ? (result as { text?: unknown }).text : undefined
202
258
  if (typeof text !== "string" || text.length === 0) return undefined
203
- state.continuation = text
204
- state.continuationWindow = state.window
259
+ state.continuation = { window: state.window, text }
205
260
  return text
206
261
  }
207
262
  function log($: Engine, text: string) {
@@ -238,24 +293,21 @@ async function run($: { process: { run: (argv: readonly string[], init?: { cwd?:
238
293
  // reason (`timed out after …`), which a bare phrase would throw away.
239
294
  catch (error) { return { ok: false as const, error: `helper execution failed: ${describeFailure(error)}` } }
240
295
  }
241
- function clearManualRequest(state: ResetState): void {
242
- state.manualPending = false
243
- state.toolResetRequested = state.lastWord = undefined
244
- }
245
296
  /** Session start does not fire on /clear, /resume or /branch. Forget the old window on end. */
246
297
  function forgetSession(state: ResetState) {
247
298
  state.generation++
248
299
  state.identity = undefined
249
300
  state.historyWindowHead = undefined
250
301
  state.window = 0
251
- state.turnRunning = state.resetting = state.usageFailureLogged = false
252
- clearManualRequest(state)
253
- state.manualCompacting = false
254
- state.preparedBoot = state.retainedBoot = undefined
302
+ state.flow = new ResetFlow()
303
+ state.usageFailureLogged = false
304
+ state.commit?.resolve(false)
305
+ state.commit = undefined
306
+ state.retainedBoot = undefined
255
307
  state.texts = state.limits = undefined
256
308
  state.continuation = undefined
257
- state.continuationWindow = undefined
258
- state.limitsAttempts = state.limitsWindow = 0
309
+ state.limitsAttempts = 0
310
+ state.limitsKey = undefined
259
311
  state.settingsFailureLogged = state.limitsFailureLogged = false
260
312
  state.warnedWindow = state.warningPending = undefined
261
313
  }
@@ -276,7 +328,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
276
328
  if (state.identity?.sessionId === sessionId) {
277
329
  state.identity = { ...state.identity, cwd, model }
278
330
  await syncHistoryWindow($, state)
279
- return state.identity
331
+ return generation === state.generation ? state.identity : undefined
280
332
  }
281
333
  const home = await $.env.get("NOTESOUP_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
282
334
  if (generation !== state.generation) return undefined
@@ -295,7 +347,7 @@ async function refreshIdentity($: Engine, state: ResetState): Promise<Identity |
295
347
 
296
348
  /** A committed append is the head evidence; the persisted file may trail it briefly. */
297
349
  async function syncHistoryWindow($: Engine, state: ResetState) {
298
- if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.resetting || state.historyWindowHead === state.history.headUuid) return
350
+ if (!state.identity || !state.history?.headUuid || state.history.sessionId !== state.identity.sessionId || state.commit || state.historyWindowHead === state.history.headUuid) return
299
351
  const generation = state.generation, head = state.history.headUuid
300
352
  const response = await run($, { op: "history_state", identity: state.identity, history: state.history })
301
353
  if (generation !== state.generation || state.history?.headUuid !== head || !response.ok || typeof response.result !== "object" || response.result === null) return
@@ -306,8 +358,8 @@ async function syncHistoryWindow($: Engine, state: ResetState) {
306
358
  }
307
359
 
308
360
  export function register(on: On) {
309
- const manualSignal: { wake?: () => void } = {}
310
- const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: 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 }
311
363
  const registered = new Set<string>()
312
364
  let keepMemory = false
313
365
  // Classic SessionStart precedes typed session.start and startup appends. Keep this binding
@@ -320,11 +372,26 @@ export function register(on: On) {
320
372
  return next(e)
321
373
  })
322
374
  on("session.append", async ($, e, next) => {
375
+ const generation = state.generation, commit = state.commit
323
376
  const sessionId = await $.session.id(), source = state.history
324
377
  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
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
+ }
328
395
  }
329
396
  return result
330
397
  })
@@ -344,13 +411,13 @@ export function register(on: On) {
344
411
  if (state.compactDisabled) log($, COMPACT_DISABLED)
345
412
  registered.clear()
346
413
  await loadTexts($, state)
347
- armManual($, state, manualSignal)
414
+ armReset($, state, resetSignal)
348
415
  await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", immediate: true })
349
416
  await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
350
417
  const wipe = await $.tool.register({
351
418
  name: "empty_brain",
352
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.",
353
- 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 },
354
421
  isDeferred: false,
355
422
  } satisfies ToolSpec)
356
423
  registered.add(wipe.tool)
@@ -374,70 +441,73 @@ export function register(on: On) {
374
441
  if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
375
442
  return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
376
443
  })
377
- on("prompt.submit", ($, e, next) => withWarning($, state, (warning) =>
378
- next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] })))
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
+ })
379
452
  on("turn.start", async ($, e, next) => {
380
453
  // The documented turn.start is main-loop only. Guard tagged host events too:
381
454
  // only a main-agent turn.complete clears this latch.
382
455
  if (state.disabled) return next(e)
383
456
  if ("agentId" in e && e.agentId !== undefined) return next(e)
384
457
  if (!await refreshIdentity($, state)) return next(e)
385
- state.turnRunning = true
458
+ state.flow.start(e.turnId)
386
459
  return next(e)
387
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
+ })
388
469
  on("turn.complete", async ($, e, next) => {
470
+ const generation = state.generation
389
471
  const result = await next(e)
390
- if (e.agentId !== undefined) return result
391
- state.turnRunning = false
472
+ if (e.agentId !== undefined || generation !== state.generation) return result
473
+ const cancelled = state.flow.complete(e.reason)
392
474
  if (state.disabled) return result
393
- // A failed turn proves nothing about whether its notes were saved. Cancel
394
- // the request instead of compacting now or springing it on a later turn.
395
- 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`)
396
477
  if (!await refreshIdentity($, state)) return result
397
- if (e.reason === "answer" && state.manualPending) await reset($, state)
478
+ if (e.reason === "answer" && state.flow.request) resetSignal.wake?.({ kind: "reset", generation: state.generation })
398
479
  return result
399
480
  })
400
481
  on("command.run", async ($, e, next) => {
401
482
  if (state.disabled) return next(e)
402
- // Only our queued native command admits manual compaction. A user's /compact
403
- // still reaches the veto, even while a reset is pending.
404
- if (e.command === "compact" && state.resetting && state.headless && e.origin.kind === "plugin" && e.origin.name === "notesoup") {
405
- state.manualCompacting = true
406
- try { return await next(e) } finally { state.manualCompacting = false }
407
- }
408
483
  if (e.command !== "empty" && e.command !== "fresh-window") return next(e)
409
484
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
410
485
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
411
- if (state.resetting || state.manualPending) return { text: "🥣 Brain already being emptied" }
412
- if (state.turnRunning) {
413
- state.manualPending = true
414
- return { text: "🥣 Dumping Brain" }
415
- }
416
- // command.run holds a turn even when idle. Start one hidden close-out
417
- // turn after it returns; turn.complete is the verified self-hook path.
418
- state.manualPending = true
419
- 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 })
420
490
  return { text: "🥣 Dumping Brain" }
421
491
  })
422
492
  on("session.compact", async ($, e, next) => {
423
493
  // Disabled means fully transparent: native compaction runs exactly as if the mod were absent.
424
494
  if (state.disabled) return next(e)
425
495
  if (e.agentId !== undefined) return next(e)
426
- const identity = await refreshIdentity($, state)
427
496
  const generation = state.generation
497
+ const identity = await refreshIdentity($, state)
428
498
  // Every pass-through keeps the current boot unless the engine's own summary replaced it.
429
499
  const passThrough = async () => {
430
500
  const result = await next(e)
431
501
  // Precompute installs nothing; a veto or subagent compact cannot remove our boot.
432
502
  if (generation === state.generation && e.trigger !== "precompute" && result.skip === undefined) {
433
503
  state.retainedBoot = result.messages.some((message) => message.text === state.retainedBoot) ? state.retainedBoot : undefined
434
- state.preparedBoot = undefined
504
+ if (state.commit) state.commit.boot = undefined
435
505
  }
436
506
  return result
437
507
  }
438
508
  // Native compaction never runs the summarizer while notesoup is on: user
439
509
  // manual and precompute are vetoed; auto becomes the notes-only reset.
440
- const own = state.resetting && identity !== undefined && (e.trigger === "plugin" || (e.trigger === "manual" && state.manualCompacting === true))
510
+ const own = state.commit !== undefined && identity !== undefined && e.trigger === "manual" && e.instructions === state.commit.instructions
441
511
  if (e.trigger === "manual" && !own) return { skip: "No compacting brains here · use /fresh-window" }
442
512
  if (e.trigger === "precompute") return { skip: "No precomputing brains here" }
443
513
  if (!own && e.trigger !== "auto") return passThrough()
@@ -449,16 +519,8 @@ export function register(on: On) {
449
519
  log($, `Notes didn't load (${built.skip}) · Claude compacted natively`)
450
520
  return passThrough()
451
521
  }
452
- if (own) {
453
- state.preparedBoot = built.boot
454
- } else {
455
- // The auto hijack keeps the books a successful plugin reset does.
456
- state.retainedBoot = built.boot
457
- state.preparedBoot = undefined
458
- state.window++
459
- clearManualRequest(state)
460
- log($, "Brain emptied")
461
- }
522
+ if (state.commit) state.commit.boot = own ? built.boot : undefined
523
+ if (!own) retainReset($, state, built.boot, true)
462
524
  return { messages: built.messages }
463
525
  })
464
526
  // notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
@@ -502,17 +564,12 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
502
564
  if (agentId !== undefined) return errorResult("only the main agent can empty this brain")
503
565
  if (state.compactDisabled) return errorResult(COMPACT_DISABLED)
504
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")
505
568
  const lastWord = typeof params.last_word === "string" ? params.last_word.trim() || undefined : undefined
506
569
  const length = lastWord ? Array.from(lastWord).length : 0
507
570
  if (length > 500) return errorResult(`last_word is ${length} characters; the sticky note holds 500. Shorten it and call again.`)
508
- if (!state.toolResetRequested) {
509
- state.toolResetRequested = true
510
- state.lastWord = lastWord
511
- state.continuation = undefined
512
- state.continuationWindow = undefined
513
- }
514
- state.manualPending = true
515
- 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."}` }
516
573
  }
517
574
  if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
518
575
  const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
@@ -575,82 +632,92 @@ function restoreWindow(state: ResetState, messages: readonly { role: string; tex
575
632
  }
576
633
  }
577
634
 
578
- // The waiter is created in session.start, so its Promise continuation keeps
579
- // that non-held host context. Timers started inside command.run inherit its
580
- // held dispatch even after the command returns. No polling timer is needed.
581
- function armManual($: Engine, state: ResetState, signal: { wake?: () => void }) {
582
- const requested = new Promise<void>((resolve) => { signal.wake = resolve })
583
- void requested.then(() => {
584
- signal.wake = undefined
585
- const generation = state.generation
586
- $.clock.after(0, () => finishManual($, state, signal, generation))
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)
587
646
  })
588
647
  }
589
- async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }, generation: number) {
648
+ async function runResetWork($: Engine, state: ResetState, work: ResetWork) {
649
+ const { generation, kind } = work
650
+ if (generation !== state.generation || !state.flow.ready) return
590
651
  try {
591
- if (generation !== state.generation) return
592
- if (state.manualPending && !state.turnRunning) {
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 {
593
659
  const texts = await loadTexts($, state)
594
660
  if (generation !== state.generation) return
595
661
  if (texts?.warning === undefined) {
662
+ state.flow.cancel()
596
663
  log($, "Brain still full: the close-out prompt didn't load")
597
664
  return
598
665
  }
599
- await $.prompt.submit({ text: texts.warning })
666
+ text = texts.warning
600
667
  }
601
- } catch {
602
- if (generation === state.generation) {
603
- log($, "Brain still full: the close-out turn didn't start")
604
- }
605
- } finally { armManual($, state, signal) }
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
+ }
606
675
  }
607
676
 
608
- /** A non-answer ends the request, never the context; the user can explicitly ask again. */
609
- function cancelManualReset($: Engine, state: ResetState, reason: "aborted" | "refusal" | "error"): void {
610
- clearManualRequest(state)
611
- log($, `Brain emptying cancelled · turn ended ${reason}; ask /fresh-window again`)
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
612
683
  }
613
684
 
614
685
  // The sandbox permits $ forwarding only to file-top-level helpers.
615
- async function reset($: Engine, state: ResetState): Promise<void> {
616
- if (!state.identity || state.compactDisabled || state.resetting) return
686
+ async function reset($: Engine, state: ResetState): Promise<boolean> {
687
+ if (!state.identity || state.compactDisabled || state.commit) return false
617
688
  const generation = state.generation
618
- state.resetting = true
619
- state.preparedBoot = undefined
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 }
620
692
  try {
621
- let failure: string | undefined
622
- if (state.headless) {
623
- const receipt = await $.command.run({ command: "compact" })
624
- if (generation !== state.generation) return
625
- // A command receipt is not SessionCompacted. Our admitted hook must have
626
- // prepared the boot; session.messages() here still reads the completed
627
- // turn's snapshot, not the next request's newly compacted context.
628
- if (state.preparedBoot === undefined) failure = receipt.text ?? "notes boot was not retained"
629
- } else {
630
- const result = await $.session.compact({ instructions: RESET_INSTRUCTIONS })
631
- failure = result.skip
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"
632
705
  }
633
- if (generation !== state.generation) return
634
- if (failure !== undefined || state.preparedBoot === undefined) {
635
- state.manualPending = true
706
+ if (generation !== state.generation) return false
707
+ if (failure !== undefined || commit.boot === undefined) {
636
708
  log($, `Brain not emptied · ${failure ?? "notes boot was not retained"}`)
637
- return
709
+ return false
638
710
  }
639
- state.retainedBoot = state.preparedBoot
640
- state.window++
641
- clearManualRequest(state)
642
- log($, "Brain emptied")
711
+ return retainReset($, state, commit.boot)
643
712
  } catch (error) {
644
- if (generation !== state.generation) return
713
+ if (generation !== state.generation) return false
645
714
  const text = String(error)
646
- state.manualPending = true
647
715
  if (!/a turn is (running|in flight)/.test(text)) {
648
716
  log($, `Brain still full: ${text.replace(/[\r\n].*$/s, "")}`)
649
717
  }
718
+ return false
650
719
  } finally {
651
- if (generation === state.generation) {
652
- state.preparedBoot = undefined
653
- state.resetting = false
654
- }
720
+ commit.resolve(false)
721
+ if (state.commit === commit) state.commit = undefined
655
722
  }
656
723
  }
@@ -81,17 +81,6 @@ function tokenLimits(source: ClaudeLimitSource, autoCompact: boolean, native: nu
81
81
  };
82
82
  }
83
83
 
84
- /** The percent fallback: the same reserves expressed as points of ASSUMED_WINDOW_TOKENS. */
85
- function percentLimits(autoCompact: boolean, pct: number | undefined, resetMargin: number, warningRunway: number): ClaudeLimits {
86
- const base = 100 * (1 - (CLAUDE_OUTPUT_RESERVE_TOKENS + CLAUDE_AUTOCOMPACT_BUFFER_TOKENS) / ASSUMED_WINDOW_TOKENS);
87
- const native = pct === undefined ? base : Math.min(pct, base);
88
- const reset = Math.max(MIN_POINT_PERCENT, native - (resetMargin / ASSUMED_WINDOW_TOKENS) * 100);
89
- return {
90
- source: "percent", autoCompact, unit: "percent",
91
- native, reset, warn: Math.max(MIN_POINT_PERCENT, reset - (warningRunway / ASSUMED_WINDOW_TOKENS) * 100), resetMargin, warningRunway,
92
- };
93
- }
94
-
95
84
  /**
96
85
  * Resolve the points from whatever the host could read. Every field is undocumented-adjacent,
97
86
  * so a missing or malformed one degrades to the next source and finally to the percent
@@ -125,21 +114,22 @@ export function resolveClaudeLimits(facts: unknown): ClaudeLimits {
125
114
  if (native > 0) return tokenLimits("auto-compact", true, native, resetMargin, warningRunway);
126
115
  }
127
116
 
128
- // (b) The same point computed from the reported window plus settings and environment. A real
129
- // window always answers here: falling through to the percent fallback would express the
130
- // points on an assumed 200K window, which is later than the window notesoup can see.
117
+ // (b/c) Compute once, using the classic 200K capacity only when the host reports none.
131
118
  const window = positiveNumber(usage.window);
132
- if (window !== undefined) {
133
- const configured = configuredWindow(settings, env, breakdown.model);
134
- const effective = Math.min(configured ?? window, window);
135
- const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
136
- const threshold = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
137
- const native = autoCompact
138
- ? pct === undefined ? threshold : Math.min(Math.floor(available * (pct / 100)), threshold)
139
- : available;
140
- return tokenLimits("window", autoCompact, native, resetMargin, warningRunway);
141
- }
142
-
143
- // (c) Nothing usable but percentages.
144
- return percentLimits(autoCompact, pct, resetMargin, warningRunway);
119
+ const capacity = window ?? ASSUMED_WINDOW_TOKENS;
120
+ const configured = configuredWindow(settings, env, breakdown.model);
121
+ const effective = Math.min(configured ?? capacity, capacity);
122
+ const available = effective - CLAUDE_OUTPUT_RESERVE_TOKENS;
123
+ const thresholdFromWindow = available - CLAUDE_AUTOCOMPACT_BUFFER_TOKENS;
124
+ const native = autoCompact
125
+ ? pct === undefined ? thresholdFromWindow : Math.min(Math.floor(available * (pct / 100)), thresholdFromWindow)
126
+ : available;
127
+ const limits = tokenLimits(window === undefined ? "percent" : "window", autoCompact, native, resetMargin, warningRunway);
128
+ if (window !== undefined) return limits;
129
+ return {
130
+ ...limits, unit: "percent",
131
+ native: limits.native / capacity * 100,
132
+ reset: Math.max(MIN_POINT_PERCENT, limits.reset / capacity * 100),
133
+ warn: Math.max(MIN_POINT_PERCENT, limits.warn / capacity * 100),
134
+ };
145
135
  }