notesoup 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/dist/plugins/claude/src/helper.js +22 -4
  3. package/dist/plugins/claude/src/text.d.ts +7 -0
  4. package/dist/plugins/claude/src/text.js +12 -1
  5. package/dist/plugins/pi/budget.d.ts +3 -0
  6. package/dist/plugins/pi/budget.js +32 -6
  7. package/dist/plugins/pi/entries.d.ts +1 -0
  8. package/dist/plugins/pi/entries.js +1 -0
  9. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  10. package/dist/plugins/pi/reset/artifacts.js +4 -4
  11. package/dist/plugins/pi/reset/lifecycle.d.ts +8 -1
  12. package/dist/plugins/pi/reset/lifecycle.js +101 -22
  13. package/dist/plugins/pi/runtime.js +4 -4
  14. package/dist/plugins/pi/tool-result.js +1 -1
  15. package/dist/plugins/pi/window.d.ts +2 -10
  16. package/dist/plugins/pi/window.js +32 -22
  17. package/dist/src/budget/text.d.ts +5 -1
  18. package/dist/src/budget/text.js +11 -2
  19. package/dist/src/index.d.ts +1 -1
  20. package/dist/test/agent-loop.test.js +197 -41
  21. package/dist/test/boot.integration.test.js +23 -1
  22. package/dist/test/budget-settings.integration.test.js +4 -4
  23. package/dist/test/claude-mod.test.js +192 -12
  24. package/dist/test/claude-validation.test.js +69 -2
  25. package/dist/test/dream-skill.test.js +3 -3
  26. package/dist/test/helpers/extension.d.ts +3 -1
  27. package/dist/test/helpers/extension.js +2 -2
  28. package/dist/test/model-facing-text.test.js +13 -3
  29. package/dist/test/reset-lifecycle.test.js +10 -0
  30. package/docs/claude-code-mod.md +6 -6
  31. package/docs/reset-lifecycle.md +1 -1
  32. package/docs/skills.md +2 -2
  33. package/package.json +1 -1
  34. package/plugins/antigravity/plugin.json +1 -1
  35. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  36. package/plugins/claude/dist/claude/helper.js +49 -5
  37. package/plugins/claude/hooks/register.ts +201 -61
  38. package/plugins/claude/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  39. package/plugins/claude/src/helper.ts +22 -4
  40. package/plugins/claude/src/text.ts +14 -1
  41. package/plugins/pi/budget.ts +28 -5
  42. package/plugins/pi/entries.ts +1 -0
  43. package/plugins/pi/reset/artifacts.ts +4 -3
  44. package/plugins/pi/reset/lifecycle.ts +116 -22
  45. package/plugins/pi/runtime.ts +4 -4
  46. package/plugins/pi/tool-result.ts +1 -1
  47. package/plugins/pi/window.ts +30 -19
  48. package/skills/{notesoup → notesoup-guide}/SKILL.md +2 -2
  49. package/src/budget/text.ts +14 -2
  50. package/src/index.ts +1 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "notesoup",
3
- "version": "0.62.0",
3
+ "version": "0.63.0",
4
4
  "description": "Durable notes and a host-scoped notes boot section for Claude Code.",
5
5
  "author": {
6
6
  "name": "AstroSheep"
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // plugins/claude/src/helper.ts
8
- import { realpathSync as realpathSync2 } from "node:fs";
8
+ import { readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
9
9
  import { pathToFileURL } from "node:url";
10
10
 
11
11
  // node_modules/typebox/build/system/arguments/arguments.mjs
@@ -11979,8 +11979,15 @@ var FORCED_CONTINUATIONS = [
11979
11979
  "*smacks your notes against your forehead and steps back* `` [that dazed face is embarrassing] `` Wake up! You ran out of room and got kicked into a fresh window mid-task. Whatever's in those notes probably missed the last few turns, so don't guess\u2014open history and check the end of the previous window before moving. Keep your peeks small in case there's a giant output sitting at the end.",
11980
11980
  "*taps your nose with your rolled-up notes, then drops them on your head* `` [ten points off for getting wiped mid-sentence] `` Hey\u2014you didn't empty yourself this time, the system pulled the plug on you. Those notes are probably half-baked or behind, so check history immediately to catch up on the last window instead of winging it. Slice up what you read too, just in case something huge is what pushed you over the edge."
11981
11981
  ];
11982
- function selectContinuation(origin) {
11983
- const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
11982
+ var BETWEEN_TURNS_CONTINUATIONS = [
11983
+ "*taps the desk with a fresh stack of notes and slides them over* `` [at least you finished talking before the tank ran dry] `` Your last window filled up right after you finished replying, so the system swapped in a fresh one between turns. Nothing got cut off mid-flight, though your notes might miss the last exchange. Handle what the human sends next, and peek at the tail of the previous window in history in small chunks if you need what was just discussed.",
11984
+ "*drops your notes beside your hand and leans on the chair back* `` [clean handover, no crash this time] `` Fresh window\u2014the old one ran out of room after your last reply wrapped up, so the system cleared it between turns. Your notes are right here, minus maybe the tail end of that conversation. Answer the human's next message directly, and pull small pieces from the end of the last window in history if anything looks referenced from before.",
11985
+ "*nudges your notes across the table with one finger* `` [eyes open? good] `` The last brain hit its ceiling after you finished answering, so it got rolled over between turns instead of mid-task. Treat these notes as possibly a turn behind, respond to what the human actually asks now, and check the end of the previous window in history in small bites if you need the missing thread.",
11986
+ "*sets your notes neatly in front of you and pokes your cheek* `` [no panic face needed] `` You finished the last turn cleanly, then the window ran out of room and reset between turns. Your notes might not include the very end of that exchange, so read them, answer the human's next message, and dip into the tail of the previous window in history in small chunks only when it refers back to something not in your notes.",
11987
+ "*tosses your notes onto your lap and stretches* `` [finally, a rollover that didn't blow up mid-sentence] `` The old window filled up after your last answer landed, so the system cleared the desk between turns. Your notes survive here, though the last few messages might still live only in history\u2014handle the human's next message, and peek at the end of the previous window in small chunks if you need the exact context."
11988
+ ];
11989
+ function selectContinuation(origin, options) {
11990
+ const pool = origin === "forced" ? options?.betweenTurns ? BETWEEN_TURNS_CONTINUATIONS : FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
11984
11991
  return pool[Math.floor(Math.random() * pool.length)];
11985
11992
  }
11986
11993
  var WARNING_TIMING = "Almost out of room. The wipe lands at the end of whichever turn uses the last of it, possibly this one.";
@@ -12002,6 +12009,26 @@ var COUNTDOWN_LINE = "Brain emptied in 3\u2026 2\u2026";
12002
12009
  // plugins/claude/src/text.ts
12003
12010
  var 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.";
12004
12011
  var CLAUDE_WARNING_PROMPT = warningNotice();
12012
+ var CLAUDE_COMMAND_NOTICE = {
12013
+ prompted: "The human ran /empty. Save your notes now and call `empty_brain` immediately. The command below is context for your notes, not a task for the fresh window.",
12014
+ bare: "The human ran /empty. Save your notes now and call `empty_brain` immediately."
12015
+ };
12016
+ var CLAUDE_COMMAND_PROMPTED_HEAD = `${GUIDANCE_OPEN_TAG}
12017
+ ${CLAUDE_COMMAND_NOTICE.prompted}
12018
+ ${WARNING_BODY}
12019
+ ${WARNING_CALL}
12020
+ ${COUNTDOWN_LINE}
12021
+ ${GUIDANCE_CLOSE_TAG}`;
12022
+ function claudeCommandWarningContent(commandLine) {
12023
+ if (commandLine) return `${CLAUDE_COMMAND_PROMPTED_HEAD}
12024
+ ${commandLine}`;
12025
+ return `${GUIDANCE_OPEN_TAG}
12026
+ ${CLAUDE_COMMAND_NOTICE.bare}
12027
+ ${WARNING_BODY}
12028
+ ${WARNING_CALL}
12029
+ ${COUNTDOWN_LINE}
12030
+ ${GUIDANCE_CLOSE_TAG}`;
12031
+ }
12005
12032
  var CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
12006
12033
  function claudeHistoryUnconfirmedSeq(seq) {
12007
12034
  return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
@@ -12175,6 +12202,17 @@ function historySource(value, sessionId) {
12175
12202
  if (source.sessionId !== sessionId) throw new Error("Claude history binding belongs to a different session");
12176
12203
  return source;
12177
12204
  }
12205
+ function readPluginVersion() {
12206
+ for (const candidate of ["../../.claude-plugin/plugin.json", "../../../../package.json", "../../../package.json"]) {
12207
+ try {
12208
+ const parsed = JSON.parse(readFileSync2(new URL(candidate, import.meta.url), "utf8"));
12209
+ if (typeof parsed.version === "string" && parsed.version.length > 0) return parsed.version;
12210
+ } catch {
12211
+ }
12212
+ }
12213
+ return "dev";
12214
+ }
12215
+ var PLUGIN_VERSION = readPluginVersion();
12178
12216
  async function dispatch(request, historyOptions = {}) {
12179
12217
  if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
12180
12218
  const value = request;
@@ -12189,10 +12227,16 @@ async function dispatch(request, historyOptions = {}) {
12189
12227
  return { cap };
12190
12228
  }
12191
12229
  if (value.op === "schemas") return [...Object.entries(OPERATIONS), ...Object.entries(HISTORY_OPERATIONS)].map(([name, operation]) => ({ name, description: operation.description, inputSchema: JSON.parse(JSON.stringify(operation.parameters)) }));
12192
- if (value.op === "texts") return { warning: CLAUDE_WARNING_PROMPT, historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE };
12230
+ if (value.op === "texts") return {
12231
+ version: PLUGIN_VERSION,
12232
+ warning: CLAUDE_WARNING_PROMPT,
12233
+ commandBare: claudeCommandWarningContent(),
12234
+ commandPrompted: CLAUDE_COMMAND_PROMPTED_HEAD,
12235
+ historyUnavailableSentence: CLAUDE_HISTORY_UNAVAILABLE_SENTENCE
12236
+ };
12193
12237
  if (value.op === "continuation") {
12194
12238
  if (value.origin !== "normal" && value.origin !== "forced") throw new Error("invalid reset origin");
12195
- return { text: selectContinuation(value.origin) };
12239
+ return { text: selectContinuation(value.origin, { betweenTurns: value.betweenTurns === true }) };
12196
12240
  }
12197
12241
  if (value.op === "limits") return resolveClaudeLimits(value.facts);
12198
12242
  if (value.op === "tool") {
@@ -13,13 +13,19 @@ type HistorySource = { sessionId: string; transcriptPath: string; headUuid?: str
13
13
  type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "prompt" | "env" | "settings" | "command">
14
14
  /** The measured context, as much of it as the engine reported. */
15
15
  type ContextUsage = { tokens?: number; window?: number; percent?: number }
16
- /** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
17
- type SharedTexts = { warning?: string; historyUnavailableSentence?: string }
16
+ /** Shared reset prose and version, fetched once per session so Pi and Claude cannot drift apart. */
17
+ type SharedTexts = { version?: string; warning?: string; commandBare?: string; commandPrompted?: string; historyUnavailableSentence?: string }
18
+ type ToolsHealth = { started: boolean; notes: number; history: number; wipe: boolean; remaining: boolean; degraded?: string }
18
19
  type ClaudeLimits = {
19
20
  source: string; autoCompact: boolean; unit: "tokens" | "percent"
20
21
  native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
21
22
  }
22
- type ResetRequest = { tool?: { lastWord?: string }; resume: boolean }
23
+ type ResetRequest = {
24
+ tool?: { lastWord?: string }
25
+ command?: { name: string; args?: string; warned: boolean }
26
+ resume: boolean
27
+ betweenTurns: boolean
28
+ }
23
29
  /** Request: until consumed/cancelled. Cutoff: one turn, even after auto consumes the request.
24
30
  * Commit lives separately in ResetState: one native command attempt, proved by kept rows. */
25
31
  class ResetFlow {
@@ -29,21 +35,27 @@ class ResetFlow {
29
35
  pendingInputTurnId?: string
30
36
  running = false
31
37
 
32
- requestReset(tool?: { lastWord?: string; terminate: boolean }): boolean {
38
+ requestReset(tool?: { lastWord?: string; terminate: boolean }, command?: { name: string; args?: string }): boolean {
33
39
  const first = tool ? this.request?.tool === undefined : this.request === undefined
34
- const request = this.request ??= { resume: true }
40
+ const request = this.request ??= { resume: true, betweenTurns: false }
35
41
  if (tool) {
36
42
  if (first) {
37
43
  request.tool = { lastWord: tool.lastWord }
38
44
  request.resume &&= !tool.terminate
45
+ request.betweenTurns = false
39
46
  }
40
47
  this.cutoffTurnId = this.turnId
41
- } else request.resume = false
48
+ } else {
49
+ request.resume = false
50
+ request.betweenTurns = false
51
+ if (command && !request.command) request.command = { name: command.name, args: command.args, warned: false }
52
+ }
42
53
  return first
43
54
  }
44
- requestAutomatic() {
45
- this.request ??= { resume: true }
46
- this.cutoffTurnId = this.turnId
55
+ /** Automatic budget reset: mid-turn cutoff resumes unfinished work; post-answer settlement waits for the human. */
56
+ requestAutomatic(resume: boolean) {
57
+ if (!this.request) this.request = { resume, betweenTurns: !resume }
58
+ if (resume) this.cutoffTurnId = this.turnId
47
59
  }
48
60
  input(turnId?: string) {
49
61
  if (turnId !== undefined) this.pendingInputTurnId = turnId
@@ -89,7 +101,7 @@ class ResetFlow {
89
101
  type ResetState = {
90
102
  identity?: Identity; history?: HistorySource; historyWindowHead?: string; generation: number; window: number; disabled: boolean; flow: ResetFlow
91
103
  headless: boolean; usageFailureLogged: boolean; commit?: { instructions: string; boot?: string; boundary: boolean; resolve: (kept: boolean) => void }; retainedBoot?: string
92
- continuation?: { window: number; text: string }
104
+ continuation?: { window: number; origin: "normal" | "forced"; betweenTurns: boolean; text: string }
93
105
  compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsKey?: string
94
106
  capTokens?: number; limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
95
107
  }
@@ -105,22 +117,23 @@ const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window
105
117
  const BOOT_TOOLS = {
106
118
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
107
119
  history: "history_* (unavailable: no main transcript_path)",
108
- remaining: "get_context_remaining (unavailable in Claude)", wipe: `${PREFIX}empty_brain`,
120
+ remaining: `${PREFIX}get_context_remaining`, wipe: `${PREFIX}empty_brain`,
109
121
  }
110
122
 
111
- /** Bind the shared protocol to the registered Claude tools. */
112
- async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts, history?: HistorySource) {
113
- const available = history?.sessionId === identity.sessionId
114
- const tools = { ...BOOT_TOOLS, ...(available ? { history: `${PREFIX}history_*` } : { historySentence: texts?.historyUnavailableSentence }) }
123
+ /** Bind the shared protocol to the tools actually registered in this Claude session. */
124
+ async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts, history?: HistorySource, health?: ToolsHealth) {
125
+ const historyAvailable = history?.sessionId === identity.sessionId && (!health?.started || health.history > 0)
126
+ const remaining = health?.started && !health.remaining ? "get_context_remaining (unavailable)" : BOOT_TOOLS.remaining
127
+ const tools = { ...BOOT_TOOLS, remaining, ...(historyAvailable ? { history: `${PREFIX}history_*` } : { historySentence: texts?.historyUnavailableSentence }) }
115
128
  return run($, { op: "boot", identity, window, tools })
116
129
  }
117
130
  /** The notes-only reset shape, shared by our own reset and Claude's native auto compaction. */
118
131
  type ResetMessages = { boot: string; messages: Array<{ role: "user"; text: string; toolUses: [] }> }
119
- async function resetMessages($: Engine, state: ResetState, identity: Identity): Promise<ResetMessages | { skip: string }> {
132
+ async function resetMessages($: Engine, state: ResetState, identity: Identity, health?: ToolsHealth): Promise<ResetMessages | { skip: string }> {
120
133
  const generation = state.generation
121
134
  const texts = await loadTexts($, state)
122
135
  if (texts === undefined) return { skip: "reset text didn't load" }
123
- const boot = await buildBoot($, identity, state.window + 1, texts, state.history)
136
+ const boot = await buildBoot($, identity, state.window + 1, texts, state.history, health)
124
137
  if (generation !== state.generation) return { skip: "session changed while building the notes boot" }
125
138
  if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
126
139
  const continuation = await continuationFor($, state)
@@ -141,10 +154,17 @@ function sharedTextsOf(value: unknown): SharedTexts | undefined {
141
154
  if (typeof value !== "object" || value === null) return undefined
142
155
  const row = value as Record<string, unknown>
143
156
  const texts: SharedTexts = {}
157
+ if (typeof row.version === "string" && row.version.length > 0) texts.version = row.version
144
158
  if (typeof row.warning === "string" && row.warning.length > 0) texts.warning = row.warning
159
+ if (typeof row.commandBare === "string" && row.commandBare.length > 0) texts.commandBare = row.commandBare
160
+ if (typeof row.commandPrompted === "string" && row.commandPrompted.length > 0) texts.commandPrompted = row.commandPrompted
145
161
  if (typeof row.historyUnavailableSentence === "string" && row.historyUnavailableSentence.length > 0) texts.historyUnavailableSentence = row.historyUnavailableSentence
146
162
  return Object.keys(texts).length > 0 ? texts : undefined
147
163
  }
164
+ function commandCloseoutText(texts: SharedTexts | undefined, command?: { name: string; args?: string }): string | undefined {
165
+ if (command?.args) return texts?.commandPrompted ? `${texts.commandPrompted}\n/${command.name} ${command.args}` : undefined
166
+ return texts?.commandBare ?? texts?.warning
167
+ }
148
168
  /** The helper's resolved points, accepted only when every number is a real number. */
149
169
  function limitsShape(value: unknown): ClaudeLimits | undefined {
150
170
  if (typeof value !== "object" || value === null) return undefined
@@ -244,9 +264,18 @@ function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | unde
244
264
  if (usage.tokens !== undefined) return usage.tokens
245
265
  return usage.percent !== undefined && usage.window !== undefined && usage.window > 0 ? (usage.percent / 100) * usage.window : undefined
246
266
  }
267
+ /** Remaining tokens before the hard-reset line (reaches zero at reset); null when unknown. */
268
+ function remainingTokensFor(limits: ClaudeLimits | undefined, usage: ContextUsage | undefined): number | null {
269
+ if (!limits || !usage) return null
270
+ const measured = measuredValue(limits, usage)
271
+ if (measured === undefined) return null
272
+ if (limits.unit === "tokens") return Math.max(0, Math.floor(limits.reset - measured))
273
+ if (usage.window !== undefined && usage.window > 0) return Math.max(0, Math.floor(((limits.reset - measured) / 100) * usage.window))
274
+ return null
275
+ }
247
276
  /** The warning and hard clear share one policy; only a safe main-loop boundary acts on it. */
248
- async function hardResetDue($: Engine, state: ResetState): Promise<boolean> {
249
- if (state.disabled || state.compactDisabled || !state.identity || state.commit) return false
277
+ async function hardResetDue($: Engine, state: ResetState, health: ToolsHealth): Promise<boolean> {
278
+ if (state.disabled || state.compactDisabled || health.degraded || !state.identity || state.commit) return false
250
279
  const generation = state.generation, window = state.window, cap = state.capTokens
251
280
  const usage = await contextUsage($, state)
252
281
  if (generation !== state.generation || usage === undefined) return false
@@ -256,8 +285,8 @@ async function hardResetDue($: Engine, state: ResetState): Promise<boolean> {
256
285
  return measured !== undefined && measured >= limits.reset
257
286
  }
258
287
 
259
- /** Runtime-only capacity; never writes Claude's settings or its process environment. */
260
- async function capCommand($: Engine, state: ResetState, args: string): Promise<{ text: string }> {
288
+ /** Runtime-only capacity and health readout; never writes Claude's settings or process environment. */
289
+ async function capCommand($: Engine, state: ResetState, health: ToolsHealth, args: string): Promise<{ text: string }> {
261
290
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /notesoup again" }
262
291
  const parts = args.trim().toLowerCase().split(/\s+/)
263
292
  if (parts[0] !== "" && (parts[0] !== "cap" || parts.length > 2)) return { text: "Usage: /notesoup cap [100k|1m|tokens|off]" }
@@ -272,7 +301,24 @@ async function capCommand($: Engine, state: ResetState, args: string): Promise<{
272
301
  if (cap !== null && (typeof cap !== "number" || !Number.isSafeInteger(cap) || cap <= 0)) return { text: "🥣 Invalid cap from helper" }
273
302
  state.capTokens = cap ?? undefined
274
303
  }
275
- return { text: `🥣 notesoup · cap ${state.capTokens === undefined ? "off" : state.capTokens.toLocaleString("en-US")} · current session only` }
304
+ const texts = await loadTexts($, state)
305
+ const label = texts?.version ? `notesoup v${texts.version}` : "notesoup"
306
+ const capText = `cap ${state.capTokens === undefined ? "off" : state.capTokens.toLocaleString("en-US")}`
307
+ const fields = [label, capText]
308
+ if (health.degraded) {
309
+ fields.push(`degraded (${health.degraded})`)
310
+ } else {
311
+ const usage = await contextUsage($, state)
312
+ const limits = usage ? await limitsOf($, state, usage) : undefined
313
+ const remaining = remainingTokensFor(limits, usage)
314
+ if (remaining !== null) fields.push(`${remaining.toLocaleString("en-US")} tokens left`)
315
+ if (health.started) {
316
+ const total = (health.wipe ? 1 : 0) + (health.remaining ? 1 : 0) + health.notes + health.history
317
+ fields.push(`tools ${total}/9`)
318
+ }
319
+ fields.push(state.history?.sessionId === state.identity?.sessionId ? "history ready" : "history unavailable")
320
+ }
321
+ return { text: `🥣 ${fields.join(" · ")} · current session only` }
276
322
  }
277
323
 
278
324
  /** The shared reset prose: one helper round trip per session, retried until it lands. */
@@ -288,19 +334,25 @@ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | un
288
334
  }
289
335
  /** One draw per reset artifact, reused on retry; only a real tool request is voluntary. */
290
336
  async function continuationFor($: Engine, state: ResetState): Promise<string | undefined> {
291
- if (state.continuation?.window === state.window) return state.continuation.text
337
+ const origin: "normal" | "forced" = state.flow.request?.tool ? "normal" : "forced"
338
+ const betweenTurns = origin === "forced" && state.flow.request?.betweenTurns === true
339
+ const cached = state.continuation
340
+ if (cached && cached.window === state.window && cached.origin === origin && cached.betweenTurns === betweenTurns) return cached.text
292
341
  const generation = state.generation
293
- const response = await run($, { op: "continuation", origin: state.flow.request?.tool ? "normal" : "forced" })
342
+ const response = await run($, { op: "continuation", origin, ...(betweenTurns ? { betweenTurns: true } : {}) })
294
343
  if (generation !== state.generation) return undefined
295
344
  const result = response.ok ? response.result : undefined
296
345
  const text = typeof result === "object" && result !== null ? (result as { text?: unknown }).text : undefined
297
346
  if (typeof text !== "string" || text.length === 0) return undefined
298
- state.continuation = { window: state.window, text }
347
+ state.continuation = { window: state.window, origin, betweenTurns, text }
299
348
  return text
300
349
  }
301
350
  function log($: Engine, text: string) {
302
351
  try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
303
352
  }
353
+ async function toast($: Engine, text: string) {
354
+ try { await $.ui.toast(text) } catch { /* Notification failure must not break a turn or startup. */ }
355
+ }
304
356
  /** A rejected call's reason, one line, bounded: the caller reads it, not a stack. */
305
357
  function describeFailure(error: unknown): string {
306
358
  const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
@@ -401,6 +453,7 @@ export function register(on: On) {
401
453
  const resetSignal: ResetSignal = {}
402
454
  const state: ResetState = { generation: 0, window: 0, disabled: false, flow: new ResetFlow(), headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, settingsFailureLogged: false }
403
455
  const registered = new Set<string>()
456
+ const health: ToolsHealth = { started: false, notes: 0, history: 0, wipe: false, remaining: false }
404
457
  let keepMemory = false
405
458
  // Classic SessionStart precedes typed session.start and startup appends. Keep this binding
406
459
  // across forgetSession; re-key it only against the actual session id, never a guessed path.
@@ -437,9 +490,13 @@ export function register(on: On) {
437
490
  })
438
491
  on("session.start", async ($, e, next) => {
439
492
  forgetSession(state)
493
+ registered.clear()
494
+ health.started = false
495
+ health.notes = health.history = 0
496
+ health.wipe = health.remaining = false
497
+ health.degraded = undefined
440
498
  state.disabled = envFlag(await $.env.get("NOTESOUP_DISABLED").catch(() => undefined))
441
499
  if (state.disabled) {
442
- registered.clear()
443
500
  log($, NOTESOUP_DISABLED)
444
501
  return next(e)
445
502
  }
@@ -449,24 +506,74 @@ export function register(on: On) {
449
506
  // Compaction is the capability explicit resets and budget warnings depend on.
450
507
  state.compactDisabled = envFlag(await $.env.get("DISABLE_COMPACT").catch(() => undefined))
451
508
  if (state.compactDisabled) log($, COMPACT_DISABLED)
452
- registered.clear()
453
509
  await loadTexts($, state)
454
- armReset($, state, resetSignal)
455
- await $.command.register({ name: "notesoup", description: "Show or cap the notesoup context capacity: cap [100k|1m|tokens|off]", immediate: true })
456
- await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", immediate: true })
457
- await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", immediate: true })
458
- const wipe = await $.tool.register({
459
- name: "empty_brain",
460
- 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.",
461
- inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note (at most 300 characters), slapped on your forehead after the wipe." }, terminate: { type: "boolean", description: "Stop after the wipe.", default: false } }, additionalProperties: false },
462
- isDeferred: false,
463
- } satisfies ToolSpec)
464
- registered.add(wipe.tool)
510
+ health.started = true
511
+ // Register tools before slash commands and isolate every failure: a broken command must
512
+ // never take down tools, and missing core tools must disarm automatic resets instead of wiping blind.
513
+ const toolErrors: string[] = []
514
+ try {
515
+ const wipe = await $.tool.register({
516
+ name: "empty_brain",
517
+ 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.",
518
+ inputSchema: { type: "object", properties: { last_word: { type: "string", description: "A tiny sticky note (at most 300 characters), slapped on your forehead after the wipe." }, terminate: { type: "boolean", description: "Stop after the wipe.", default: false } }, additionalProperties: false },
519
+ isDeferred: false,
520
+ } satisfies ToolSpec)
521
+ registered.add(wipe.tool)
522
+ health.wipe = true
523
+ } catch (error) {
524
+ toolErrors.push(`empty_brain: ${describeFailure(error)}`)
525
+ }
526
+ try {
527
+ const remaining = await $.tool.register({
528
+ name: "get_context_remaining",
529
+ description: "Check how much room your brain has left before it gets forcibly emptied. Returns null when unknown.",
530
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
531
+ isDeferred: false,
532
+ } satisfies ToolSpec)
533
+ registered.add(remaining.tool)
534
+ health.remaining = true
535
+ } catch (error) {
536
+ log($, `Tool get_context_remaining failed to register · ${describeFailure(error)}`)
537
+ }
465
538
  const schemas = await run($, { op: "schemas" })
466
- if (!schemas.ok || !Array.isArray(schemas.result)) return next(e)
467
- for (const row of schemas.result as SchemaRow[]) {
468
- const full = await $.tool.register({ name: row.name, description: row.description, inputSchema: row.inputSchema, isDeferred: false } satisfies ToolSpec)
469
- registered.add(full.tool)
539
+ if (!schemas.ok || !Array.isArray(schemas.result)) {
540
+ toolErrors.push(schemas.ok ? "helper returned invalid tool schemas" : schemas.error)
541
+ } else {
542
+ for (const row of schemas.result as SchemaRow[]) {
543
+ try {
544
+ const full = await $.tool.register({ name: row.name, description: row.description, inputSchema: row.inputSchema, isDeferred: false } satisfies ToolSpec)
545
+ registered.add(full.tool)
546
+ if (row.name.startsWith("notes_")) health.notes++
547
+ else if (row.name.startsWith("history_")) health.history++
548
+ } catch (error) {
549
+ toolErrors.push(`${row.name}: ${describeFailure(error)}`)
550
+ }
551
+ }
552
+ }
553
+ try {
554
+ await $.command.register({ name: "notesoup", description: "Show notesoup status or cap capacity: cap [100k|1m|tokens|off]", immediate: true })
555
+ } catch (error) {
556
+ log($, `Command /notesoup failed to register · ${describeFailure(error)}`)
557
+ await toast($, "🥣 Notesoup /notesoup command failed to load")
558
+ }
559
+ try {
560
+ await $.command.register({ name: "empty", description: "Reset context to a fresh notes-only window", argumentHint: "[context for notes]", immediate: true })
561
+ } catch (error) {
562
+ log($, `Command /empty failed to register · ${describeFailure(error)}`)
563
+ await toast($, "🥣 Notesoup /empty command failed to load")
564
+ }
565
+ try {
566
+ await $.command.register({ name: "fresh-window", description: "Reset context to a fresh notes-only window", argumentHint: "[context for notes]", immediate: true })
567
+ } catch (error) {
568
+ log($, `Command /fresh-window failed to register · ${describeFailure(error)}`)
569
+ await toast($, "🥣 Notesoup /fresh-window command failed to load")
570
+ }
571
+ if (health.notes < 4 || !health.wipe) {
572
+ health.degraded = toolErrors[0] ?? "core notesoup tools did not register"
573
+ log($, `Notesoup tools unavailable (${health.degraded}) · automatic brain reset disabled`)
574
+ await toast($, "🥣 Notesoup tools failed to load · auto-reset off")
575
+ } else {
576
+ armReset($, state, resetSignal)
470
577
  }
471
578
  return next(e)
472
579
  })
@@ -479,12 +586,21 @@ export function register(on: On) {
479
586
  if (state.disabled) return next(e)
480
587
  const generation = state.generation
481
588
  const result = registered.has(e.tool) ? await callNotesTool($, state, e) : await next(e)
482
- if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
483
- return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
589
+ if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation || health.degraded) return result
590
+ const pendingCommand = state.flow.request?.command && !state.flow.request.command.warned && !state.flow.request.tool ? state.flow.request.command : undefined
591
+ if (pendingCommand) {
592
+ const texts = await loadTexts($, state)
593
+ const notice = commandCloseoutText(texts, pendingCommand)
594
+ if (generation === state.generation && notice !== undefined && state.flow.request?.command === pendingCommand && !pendingCommand.warned) {
595
+ pendingCommand.warned = true
596
+ return { ...result, context: [...(result.context ?? []), notice] }
597
+ }
598
+ }
599
+ return withWarning($, state, health, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
484
600
  })
485
601
  on("prompt.submit", async ($, e, next) => {
486
602
  const generation = state.generation
487
- const result = await withWarning($, state, (warning) =>
603
+ const result = await withWarning($, state, health, (warning) =>
488
604
  next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] }))
489
605
  // Our own submissions skip this hook; accepted input owns the continuation.
490
606
  if (generation === state.generation && result.drop === undefined) state.flow.input(e.turnId)
@@ -503,7 +619,7 @@ export function register(on: On) {
503
619
  if (state.disabled || e.agentId !== undefined) return yield* next(e)
504
620
  // Like the warning, the hard point consumes the same resolved limits. This boundary
505
621
  // follows the whole previous tool batch; no sibling tool or in-flight request is aborted.
506
- if (await hardResetDue($, state)) state.flow.requestAutomatic()
622
+ if (await hardResetDue($, state, health)) state.flow.requestAutomatic(true)
507
623
  if (!state.flow.cutoff(e.turnId)) return yield* next(e)
508
624
  // This boundary follows the entire tool batch. A synthetic streamed stop
509
625
  // ends the main turn without aborting siblings or making an old-window request.
@@ -515,22 +631,34 @@ export function register(on: On) {
515
631
  const result = await next(e)
516
632
  if (e.agentId !== undefined || generation !== state.generation) return result
517
633
  const cancelled = state.flow.complete(e.reason)
518
- if (state.disabled) return result
634
+ if (state.disabled || health.degraded) return result
519
635
  // A failed turn proves nothing about whether its notes were saved.
520
636
  if (cancelled) log($, `Brain emptying cancelled · turn ended ${e.reason}; ask /fresh-window again`)
521
637
  if (!await refreshIdentity($, state)) return result
522
638
  if (e.reason === "answer") {
523
- if (!state.flow.request && await hardResetDue($, state)) state.flow.requestAutomatic()
524
- if (state.flow.request) resetSignal.wake?.({ kind: "reset", generation: state.generation })
639
+ // A clean end_turn with no prior mid-turn cutoff already delivered its answer:
640
+ // rotate quietly to a fresh window without waking the model for a ghost turn.
641
+ if (!state.flow.request && await hardResetDue($, state, health)) state.flow.requestAutomatic(false)
642
+ const req = state.flow.request
643
+ if (req) {
644
+ // If /empty [args] arrived mid-turn while the model was already finishing without
645
+ // further tool calls, give it one close-out turn while room remains so notes and
646
+ // any trailing context args are not silently dropped.
647
+ const unwarnedCommand = req.command !== undefined && !req.command.warned && req.tool === undefined
648
+ const needsCloseout = unwarnedCommand && !await hardResetDue($, state, health)
649
+ resetSignal.wake?.({ kind: needsCloseout ? "closeout" : "reset", generation: state.generation })
650
+ }
525
651
  }
526
652
  return result
527
653
  })
528
654
  on("command.run", { command: ["notesoup", "empty", "fresh-window"] }, async ($, e, next) => {
529
655
  if (state.disabled) return next(e)
530
- if (e.command === "notesoup") return capCommand($, state, e.args)
656
+ if (e.command === "notesoup") return capCommand($, state, health, e.args)
657
+ if (health.degraded) return { text: `🥣 Notesoup tools unavailable (${health.degraded}) · cannot empty brain` }
531
658
  if (!await refreshIdentity($, state)) return { text: "🥣 Different brain now · try /fresh-window again" }
532
659
  if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
533
- const first = state.flow.requestReset()
660
+ const trimmed = e.args?.trim() || undefined
661
+ const first = state.flow.requestReset(undefined, { name: e.command, args: trimmed })
534
662
  if (state.commit || !first) return { text: "🥣 Brain already being emptied" }
535
663
  // command.run holds a turn even when idle; close out from the non-held waiter.
536
664
  if (!state.flow.running) resetSignal.wake?.({ kind: "closeout", generation: state.generation })
@@ -552,6 +680,7 @@ export function register(on: On) {
552
680
  }
553
681
  return result
554
682
  }
683
+ if (health.degraded) return passThrough()
555
684
  // Native compaction never runs the summarizer while notesoup is on: user
556
685
  // manual and precompute are vetoed; auto becomes the notes-only reset.
557
686
  const own = state.commit !== undefined && identity !== undefined && e.trigger === "manual" && e.instructions === state.commit.instructions
@@ -559,7 +688,7 @@ export function register(on: On) {
559
688
  if (e.trigger === "precompute") return { skip: "No precomputing brains here" }
560
689
  if (!own && e.trigger !== "auto") return passThrough()
561
690
  if (identity === undefined) return passThrough()
562
- const built = await resetMessages($, state, identity)
691
+ const built = await resetMessages($, state, identity, health)
563
692
  if ("skip" in built) {
564
693
  if (own) return { skip: built.skip }
565
694
  // An over-long prompt must still compact: fall back to the engine's summary.
@@ -571,13 +700,17 @@ export function register(on: On) {
571
700
  return { messages: built.messages }
572
701
  })
573
702
  // notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
574
- on("prompt.section", { name: "context_management" }, ($, e, next) => state.disabled ? next(e) : { text: null })
703
+ on("prompt.section", { name: "context_management" }, ($, e, next) => state.disabled || health.degraded ? next(e) : { text: null })
575
704
  on("prompt.section", { name: "memory" }, ($, e, next) => state.disabled || keepMemory ? next(e) : { text: null })
576
705
  on("prompt.context", async ($, e, next) => {
577
706
  if (state.disabled) return next(e)
578
707
  const result = await next(e)
579
708
  const identity = await refreshIdentity($, state)
580
709
  const generation = state.generation
710
+ if (health.degraded) {
711
+ const blocks = result.blocks.filter((block) => block.name !== "notesoup:boot")
712
+ return { ...result, blocks: [...blocks, { name: "notesoup:boot", text: `# notesoup\nNotesoup tools failed to load in this session (${health.degraded}). Automatic brain reset is disabled and native compaction remains active; tell the human if you need notes or history.` }] }
713
+ }
581
714
  // The reset already retained its boot as the sole conversation message.
582
715
  // Prompt context still recomputes, but must not inject a duplicate snapshot.
583
716
  const retained = state.retainedBoot !== undefined
@@ -588,12 +721,10 @@ export function register(on: On) {
588
721
  })
589
722
  if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
590
723
  const texts = await loadTexts($, state)
591
- const boot = await buildBoot($, identity, state.window, texts, state.history)
724
+ const boot = await buildBoot($, identity, state.window, texts, state.history, health)
592
725
  if (generation !== state.generation) return result
593
726
  if (!boot.ok) {
594
- try {
595
- await $.ui.toast("🥣 Notes went missing")
596
- } catch { /* Notification failure must not suppress the fallback block. */ }
727
+ await toast($, "🥣 Notes went missing")
597
728
  }
598
729
  blocks = [...blocks, { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\nYour notes didn't load this time (${boot.error}). Try \`${PREFIX}notes_list\`; if it fails too, tell the human.` }]
599
730
  }
@@ -620,6 +751,12 @@ async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Pr
620
751
  if (state.flow.requestReset({ lastWord, terminate: terminate === true })) state.continuation = undefined
621
752
  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."}` }
622
753
  }
754
+ if (name === "get_context_remaining") {
755
+ if (agentId !== undefined) return errorResult("context remaining is unavailable for subagents; main-session usage is not their context")
756
+ const usage = await contextUsage($, state)
757
+ const limits = usage ? await limitsOf($, state, usage) : undefined
758
+ return { result: JSON.stringify({ remaining_tokens: remainingTokensFor(limits, usage) }) }
759
+ }
623
760
  const history = name === "history_list" || name === "history_search" || name === "history_read"
624
761
  if (history && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
625
762
  const result = await run($, { op: "tool", tool: name, params, identity, history: state.history }, history ? HISTORY_TIMEOUT_MS : TIMEOUT_MS)
@@ -644,8 +781,8 @@ async function warningText($: Engine, state: ResetState): Promise<string | undef
644
781
  }
645
782
 
646
783
  /** Reserve across next(), but consume only context the chain actually accepted. */
647
- async function withWarning<T extends { context?: readonly string[]; drop?: string; deny?: string }>($: Engine, state: ResetState, deliver: (warning?: string) => T | Promise<T>): Promise<T> {
648
- if (state.disabled || state.compactDisabled || !await refreshIdentity($, state)) return deliver()
784
+ async function withWarning<T extends { context?: readonly string[]; drop?: string; deny?: string }>($: Engine, state: ResetState, health: ToolsHealth, deliver: (warning?: string) => T | Promise<T>): Promise<T> {
785
+ if (state.disabled || state.compactDisabled || health.degraded || !await refreshIdentity($, state)) return deliver()
649
786
  const generation = state.generation, window = state.window
650
787
  const warning = await warningText($, state)
651
788
  if (warning === undefined || generation !== state.generation || window !== state.window || state.warnedWindow === window || state.warningPending === window) return deliver()
@@ -708,12 +845,15 @@ async function runResetWork($: Engine, state: ResetState, work: ResetWork) {
708
845
  } else {
709
846
  const texts = await loadTexts($, state)
710
847
  if (generation !== state.generation) return
711
- if (texts?.warning === undefined) {
848
+ const command = state.flow.request?.command
849
+ const closeout = commandCloseoutText(texts, command)
850
+ if (closeout === undefined) {
712
851
  state.flow.cancel()
713
852
  log($, "Brain still full: the close-out prompt didn't load")
714
853
  return
715
854
  }
716
- text = texts.warning
855
+ if (command) command.warned = true
856
+ text = closeout
717
857
  }
718
858
  const result = await $.prompt.submit({ text })
719
859
  if (result.drop !== undefined) throw result.drop
@@ -1,9 +1,9 @@
1
1
  ---
2
- name: notesoup
2
+ name: notesoup-guide
3
3
  description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and notebooks, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
4
4
  ---
5
5
 
6
- # Notesoup
6
+ # Notesoup Guide
7
7
 
8
8
  Two stores outlive the context window. Anything in neither is lost when the window ends or is wiped.
9
9