notesoup 0.41.0 → 0.42.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 (59) hide show
  1. package/dist/src/boot/text.d.ts +12 -0
  2. package/dist/src/boot/text.js +14 -2
  3. package/dist/src/budget/text.d.ts +12 -0
  4. package/dist/src/budget/text.js +12 -0
  5. package/dist/src/claude/helper.js +23 -2
  6. package/dist/src/claude/thresholds.d.ts +39 -0
  7. package/dist/src/claude/thresholds.js +149 -0
  8. package/dist/src/dream/doctor.js +1 -1
  9. package/dist/src/dream/jail.js +10 -10
  10. package/dist/src/history/history.js +1 -1
  11. package/dist/src/history/query.js +6 -6
  12. package/dist/src/notes/address.d.ts +1 -1
  13. package/dist/src/notes/address.js +12 -12
  14. package/dist/src/notes/store.js +16 -12
  15. package/dist/src/pi/reset/text.d.ts +2 -3
  16. package/dist/src/pi/reset/text.js +5 -4
  17. package/dist/src/pi/runtime.js +1 -1
  18. package/dist/src/pi/tool-result.js +2 -2
  19. package/dist/src/settings.d.ts +8 -0
  20. package/dist/src/settings.js +6 -1
  21. package/dist/src/tools/history.js +12 -12
  22. package/dist/src/tools/notes.d.ts +3 -3
  23. package/dist/src/tools/notes.js +12 -11
  24. package/dist/src/tools/output.d.ts +2 -0
  25. package/dist/src/tools/output.js +2 -0
  26. package/dist/src/tools/result.js +2 -2
  27. package/dist/src/tools/schema.js +3 -3
  28. package/dist/test/claude-mod.test.js +206 -16
  29. package/dist/test/dream.test.js +3 -3
  30. package/dist/test/history.integration.test.js +7 -8
  31. package/dist/test/host-neutral.test.js +1 -1
  32. package/dist/test/notes-library.test.js +1 -1
  33. package/dist/test/notes.integration.test.js +4 -4
  34. package/dist/test/notes.test.js +16 -16
  35. package/docs/claude-code-mod.md +10 -2
  36. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  37. package/mods/notesoup/dist/claude/helper.js +200 -41
  38. package/mods/notesoup/hooks/register.ts +193 -27
  39. package/mods/pi-context/dist/claude/helper.js +9324 -0
  40. package/package.json +1 -1
  41. package/src/boot/text.ts +20 -2
  42. package/src/budget/text.ts +17 -0
  43. package/src/claude/helper.ts +20 -3
  44. package/src/claude/thresholds.ts +170 -0
  45. package/src/dream/doctor.ts +1 -1
  46. package/src/dream/jail.ts +10 -10
  47. package/src/history/history.ts +1 -1
  48. package/src/history/query.ts +6 -6
  49. package/src/notes/address.ts +12 -12
  50. package/src/notes/store.ts +17 -12
  51. package/src/pi/reset/text.ts +6 -7
  52. package/src/pi/runtime.ts +1 -1
  53. package/src/pi/tool-result.ts +2 -2
  54. package/src/settings.ts +18 -2
  55. package/src/tools/history.ts +12 -12
  56. package/src/tools/notes.ts +14 -12
  57. package/src/tools/output.ts +2 -0
  58. package/src/tools/result.ts +2 -2
  59. package/src/tools/schema.ts +3 -3
@@ -9,12 +9,27 @@ const OUTPUT_LIMIT = 1024 * 1024
9
9
 
10
10
  type Identity = { home: string; sessionId: string; cwd: string; agent: string; model: string }
11
11
  type SchemaRow = { name: string; description: string; inputSchema: Record<string, unknown> }
12
- type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt">
12
+ type Engine = Pick<EngineInterface, "process" | "session" | "ui" | "clock" | "prompt" | "env">
13
+ type UsageSample = { context?: unknown }
14
+ /** `usage({breakdown:true})` is wired in the engine but absent from the public typings. */
15
+ type UsageReader = (options?: { breakdown?: boolean }) => Promise<UsageSample | undefined>
16
+ /** The measured context, as much of it as the engine reported. */
17
+ type ContextUsage = { tokens?: number; window?: number; percent?: number }
18
+ /** Shared reset prose, fetched once per session so Pi and Claude cannot drift apart. */
19
+ type SharedTexts = { warning?: string; continuation?: string; wipeSentence?: string }
20
+ type ClaudeLimits = {
21
+ source: string; autoCompact: boolean; unit: "tokens" | "percent"
22
+ native: number; reset: number; warn: number; resetMargin: number; warningRunway: number
23
+ }
13
24
  type ResetState = {
14
25
  identity?: Identity; window: number; turnRunning: boolean; resetting: boolean
15
26
  manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
27
+ compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempted: boolean; limitsWindow: number
28
+ limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts
16
29
  }
17
30
  const HEADLESS = "Clear-memory is off in headless (-p / SDK) sessions"
31
+ const COMPACT_DISABLED = "Clear-memory can't run: compaction is off in this session (DISABLE_COMPACT)"
32
+ const THRESHOLDS_UNAVAILABLE = "Context thresholds unavailable · automatic clear-memory skipped"
18
33
  const RESET_INSTRUCTIONS = "notesoup: reset to a fresh notes-only context window."
19
34
  const BOOT_TOOLS = {
20
35
  notes: `${PREFIX}notes_*`, notesList: `${PREFIX}notes_list`,
@@ -22,8 +37,117 @@ const BOOT_TOOLS = {
22
37
  remaining: "get_context_remaining (unavailable in Claude)", wipe: "/clear-memory (user command; no model reset tool in Claude)",
23
38
  }
24
39
 
25
- async function buildBoot($: Engine, identity: Identity, window: number) {
26
- return run($, { op: "boot", identity, window, tools: BOOT_TOOLS }, identity.cwd)
40
+ /** The boot names the host's own wipe path, so the protocol block speaks about `/clear-memory`. */
41
+ async function buildBoot($: Engine, identity: Identity, window: number, texts?: SharedTexts) {
42
+ const tools = texts?.wipeSentence === undefined ? BOOT_TOOLS : { ...BOOT_TOOLS, wipeSentence: texts.wipeSentence }
43
+ return run($, { op: "boot", identity, window, tools }, identity.cwd)
44
+ }
45
+ function numberOf(value: unknown): number | undefined {
46
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined
47
+ }
48
+ function sharedTextsOf(value: unknown): SharedTexts | undefined {
49
+ if (typeof value !== "object" || value === null) return undefined
50
+ const row = value as Record<string, unknown>
51
+ const texts: SharedTexts = {}
52
+ if (typeof row.warning === "string" && row.warning.length > 0) texts.warning = row.warning
53
+ if (typeof row.continuation === "string" && row.continuation.length > 0) texts.continuation = row.continuation
54
+ if (typeof row.wipeSentence === "string" && row.wipeSentence.length > 0) texts.wipeSentence = row.wipeSentence
55
+ return Object.keys(texts).length > 0 ? texts : undefined
56
+ }
57
+ /** The helper's resolved points, accepted only when every number is a real number. */
58
+ function limitsShape(value: unknown): ClaudeLimits | undefined {
59
+ if (typeof value !== "object" || value === null) return undefined
60
+ const row = value as Record<string, unknown>
61
+ const unit = row.unit === "tokens" || row.unit === "percent" ? row.unit : undefined
62
+ const native = numberOf(row.native), reset = numberOf(row.reset), warn = numberOf(row.warn)
63
+ const resetMargin = numberOf(row.resetMargin), warningRunway = numberOf(row.warningRunway)
64
+ if (unit === undefined || native === undefined || reset === undefined || warn === undefined || resetMargin === undefined || warningRunway === undefined) return undefined
65
+ return { source: typeof row.source === "string" ? row.source : "unknown", autoCompact: row.autoCompact !== false, unit, native, reset, warn, resetMargin, warningRunway }
66
+ }
67
+ async function envValue($: Engine, name: string): Promise<string | undefined> {
68
+ try { const value = await $.env.get(name); return typeof value === "string" ? value : undefined } catch { return undefined }
69
+ }
70
+ /** Presence-style environment flags: any value but an explicit no counts as on. */
71
+ async function envFlag($: Engine, name: string): Promise<boolean> {
72
+ const value = await envValue($, name)
73
+ if (value === undefined) return false
74
+ const text = value.trim().toLowerCase()
75
+ return text !== "" && text !== "0" && text !== "false"
76
+ }
77
+ async function readSettings($: Engine): Promise<unknown> {
78
+ const settings = ($ as { settings?: { read?: (options?: unknown) => Promise<unknown> } }).settings
79
+ if (typeof settings?.read !== "function") return undefined
80
+ try { return await settings.read() } catch { return undefined }
81
+ }
82
+ /** The measured context, or undefined when the engine cannot report it. The failure logs once. */
83
+ async function contextUsage($: Engine, state: ResetState): Promise<ContextUsage | undefined> {
84
+ try {
85
+ const read = $.session.usage as unknown as UsageReader
86
+ const context = (await read())?.context
87
+ if (typeof context !== "object" || context === null) return {}
88
+ const row = context as Record<string, unknown>
89
+ return { tokens: numberOf(row.tokens), window: numberOf(row.window), percent: numberOf(row.percent) }
90
+ } catch {
91
+ if (!state.usageFailureLogged) {
92
+ state.usageFailureLogged = true
93
+ log($, "Context usage unavailable · automatic clear-memory skipped")
94
+ }
95
+ return undefined
96
+ }
97
+ }
98
+ async function breakdownContext($: Engine): Promise<Record<string, unknown> | undefined> {
99
+ try {
100
+ const read = $.session.usage as unknown as UsageReader
101
+ const context = (await read({ breakdown: true }))?.context
102
+ return typeof context === "object" && context !== null ? context as Record<string, unknown> : undefined
103
+ } catch { return undefined }
104
+ }
105
+ /** Everything the resolver may read: measured usage plus the raw settings and environment. */
106
+ async function limitFacts($: Engine, usage: ContextUsage): Promise<Record<string, unknown>> {
107
+ return {
108
+ usage,
109
+ breakdown: await breakdownContext($),
110
+ settings: await readSettings($),
111
+ env: {
112
+ pctOverride: await envValue($, "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE"),
113
+ autoCompactWindow: await envValue($, "CLAUDE_CODE_AUTO_COMPACT_WINDOW"),
114
+ disableAutoCompact: await envValue($, "DISABLE_AUTO_COMPACT"),
115
+ },
116
+ }
117
+ }
118
+ /**
119
+ * The points the current window is measured against, resolved by the helper's shared
120
+ * derivation. One attempt per reported window value: an unknown window resolves the percent
121
+ * fallback, and a later real window re-resolves against it.
122
+ */
123
+ async function limitsOf($: Engine, state: ResetState, usage: ContextUsage): Promise<ClaudeLimits | undefined> {
124
+ const window = usage.window !== undefined && usage.window > 0 ? usage.window : 0
125
+ if (state.limitsAttempted && state.limitsWindow === window) return state.limits
126
+ const response = await run($, { op: "limits", facts: await limitFacts($, usage) }, state.identity?.cwd ?? ".")
127
+ const limits = response.ok ? limitsShape(response.result) : undefined
128
+ state.limitsAttempted = true
129
+ state.limitsWindow = window
130
+ if (limits) state.limits = limits
131
+ else if (!state.limitsFailureLogged) {
132
+ state.limitsFailureLogged = true
133
+ log($, THRESHOLDS_UNAVAILABLE)
134
+ }
135
+ return limits ?? state.limits
136
+ }
137
+ /** The measured value the points are expressed in; tokens win, percent × window stands in. */
138
+ function measuredValue(limits: ClaudeLimits, usage: ContextUsage): number | undefined {
139
+ if (limits.unit === "percent") return usage.percent
140
+ if (usage.tokens !== undefined) return usage.tokens
141
+ return usage.percent !== undefined && usage.window !== undefined && usage.window > 0 ? (usage.percent / 100) * usage.window : undefined
142
+ }
143
+ /** The shared reset prose: one helper round trip per session, retried until it lands. */
144
+ async function loadTexts($: Engine, state: ResetState): Promise<SharedTexts | undefined> {
145
+ if (state.texts) return state.texts
146
+ if (!state.identity) return undefined
147
+ const response = await run($, { op: "texts" }, state.identity.cwd)
148
+ const texts = response.ok ? sharedTextsOf(response.result) : undefined
149
+ if (texts) state.texts = texts
150
+ return texts
27
151
  }
28
152
  function log($: Engine, text: string) {
29
153
  try { $.ui.log(`🥣 ${text}`) } catch { /* UI must not break a turn or reset. */ }
@@ -59,7 +183,7 @@ function identityOf(e: { cwd: string }, sessionId: string, home: string, model:
59
183
  export function register(on: On) {
60
184
  let identity: Identity | undefined
61
185
  const manualSignal: { wake?: () => void } = {}
62
- const state: ResetState = { window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false }
186
+ const state: ResetState = { window: 0, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempted: false, limitsWindow: 0 }
63
187
  const registered = new Set<string>()
64
188
  on("session.start", async ($, e, next) => {
65
189
  const home = await $.env.get("PI_NOTES_HOME") ?? `${await $.env.get("HOME") ?? await $.env.get("USERPROFILE") ?? ""}/.agents/notes`
@@ -70,10 +194,18 @@ export function register(on: On) {
70
194
  state.headless = !e.isInteractive
71
195
  if (state.headless) log($, HEADLESS)
72
196
  state.preparedBoot = state.retainedBoot = undefined
197
+ state.texts = state.limits = undefined
198
+ state.limitsAttempted = false
199
+ state.limitsWindow = 0
200
+ state.warnedWindow = undefined
201
+ // Compaction is the capability the reset is built on; without it, automatic resets stop here.
202
+ state.compactDisabled = await envFlag($, "DISABLE_COMPACT")
203
+ if (state.compactDisabled) log($, COMPACT_DISABLED)
73
204
  // The engine's history view includes retained boots on resume/reload.
74
205
  // Recover their ordinal without treating that view as inference context.
75
206
  try { restoreWindow(state, await $.session.messages()) } catch { /* A fresh session starts at zero. */ }
76
207
  registered.clear()
208
+ await loadTexts($, state)
77
209
  armManual($, state, manualSignal)
78
210
  await $.command.register({ name: "clear-memory", description: "Reset context to a fresh notes-only window", immediate: true })
79
211
  const schemas = await run($, { op: "schemas" }, e.cwd)
@@ -114,6 +246,7 @@ export function register(on: On) {
114
246
  on("command.run", async ($, e, next) => {
115
247
  if (e.command !== "clear-memory") return next(e)
116
248
  if (state.headless) return { text: `🥣 ${HEADLESS}` }
249
+ if (state.compactDisabled) return { text: `🥣 ${COMPACT_DISABLED}` }
117
250
  if (state.resetting || state.manualPending) return { text: "🥣 Clear-memory already queued" }
118
251
  if (state.turnRunning) {
119
252
  state.manualPending = true
@@ -128,30 +261,57 @@ export function register(on: On) {
128
261
  on("session.compact", async ($, e, next) => {
129
262
  // Do not take over native /compact or another plugin's compaction.
130
263
  if (!state.resetting || e.trigger !== "plugin" || e.agentId !== undefined || !identity) return next(e)
131
- const boot = await buildBoot($, identity, state.window + 1)
264
+ const texts = await loadTexts($, state)
265
+ if (texts?.continuation === undefined) return { skip: "reset text didn't load" }
266
+ const boot = await buildBoot($, identity, state.window + 1, texts)
132
267
  if (!boot.ok) return { skip: `notes didn't load: ${boot.error}` }
133
268
  state.preparedBoot = String(boot.result)
134
- return { messages: [{ role: "user", text: state.preparedBoot, toolUses: [] }] }
269
+ // The same closed reset shape as Pi: notes boot first, then the one reset message.
270
+ return { messages: [
271
+ { role: "user", text: state.preparedBoot, toolUses: [] },
272
+ { role: "user", text: texts.continuation, toolUses: [] },
273
+ ] }
135
274
  })
136
275
  on("prompt.context", async ($, e, next) => {
137
276
  const result = await next(e)
138
277
  // The reset already retained its boot as the sole conversation message.
139
278
  // Prompt context still recomputes, but must not inject a duplicate snapshot.
140
- if (state.retainedBoot !== undefined) return { ...result, blocks: result.blocks.filter((block) => block.name !== "notesoup:boot") }
141
- if (result.blocks.some((block) => block.name === "notesoup:boot")) return result
142
- if (!identity) return result
143
- const boot = await buildBoot($, identity, state.window)
144
- if (!boot.ok) {
145
- try {
146
- await $.ui.notify("🥣 Notes didn't load")
147
- } catch { /* Notification failure must not suppress the fallback block. */ }
279
+ const retained = state.retainedBoot !== undefined
280
+ let blocks = retained ? result.blocks.filter((block) => block.name !== "notesoup:boot") : [...result.blocks]
281
+ if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
282
+ const texts = await loadTexts($, state)
283
+ const boot = await buildBoot($, identity, state.window, texts)
284
+ if (!boot.ok) {
285
+ try {
286
+ await $.ui.notify("🥣 Notes didn't load")
287
+ } catch { /* Notification failure must not suppress the fallback block. */ }
288
+ }
289
+ 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.` }]
148
290
  }
149
- const block = { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\n${boot.error}` }
150
- return { ...result, blocks: [...result.blocks, block] }
291
+ const warning = await warningBlock($, state)
292
+ return { ...result, blocks: warning === undefined ? blocks : [...blocks, warning] }
151
293
  })
152
294
 
153
295
  }
154
296
 
297
+ /**
298
+ * The one warning per window: injected only once the measured context crosses the resolved
299
+ * warn point, and only until the window changes. The reset decision runs independently.
300
+ */
301
+ async function warningBlock($: Engine, state: ResetState): Promise<{ name: string; text: string } | undefined> {
302
+ if (state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window) return undefined
303
+ const usage = await contextUsage($, state)
304
+ if (usage === undefined) return undefined
305
+ const limits = await limitsOf($, state, usage)
306
+ if (limits === undefined) return undefined
307
+ const measured = measuredValue(limits, usage)
308
+ if (measured === undefined || measured < limits.warn) return undefined
309
+ const texts = await loadTexts($, state)
310
+ if (texts?.warning === undefined) return undefined
311
+ state.warnedWindow = state.window
312
+ return { name: "notesoup:warning", text: texts.warning }
313
+ }
314
+
155
315
  function restoreWindow(state: ResetState, messages: readonly { role: string; text: string }[]) {
156
316
  if (!state.identity) return
157
317
  const prefix = `Current context window id: claude:${state.identity.sessionId}:`
@@ -180,7 +340,13 @@ function armManual($: Engine, state: ResetState, signal: { wake?: () => void })
180
340
  async function finishManual($: Engine, state: ResetState, signal: { wake?: () => void }) {
181
341
  try {
182
342
  if (state.manualPending && !state.turnRunning) {
183
- await $.prompt.submit({ text: "A context reset was requested. Save any essential checkpoint to session notes now, then end this turn. notesoup will reset to a fresh notes-only window after the turn completes." })
343
+ const texts = await loadTexts($, state)
344
+ if (texts?.warning === undefined) {
345
+ state.manualPending = false
346
+ log($, "Couldn't clear memory: the close-out prompt didn't load")
347
+ return
348
+ }
349
+ await $.prompt.submit({ text: texts.warning })
184
350
  }
185
351
  } catch {
186
352
  state.manualPending = false
@@ -190,17 +356,17 @@ async function finishManual($: Engine, state: ResetState, signal: { wake?: () =>
190
356
 
191
357
  // The sandbox permits $ forwarding only to file-top-level helpers.
192
358
  async function maybeReset($: Engine, state: ResetState, complete: boolean) {
193
- if (!state.identity || state.resetting || state.headless) return
194
- let percent: number | undefined
195
- try { percent = (await $.session.usage()).context?.percent }
196
- catch {
197
- if (!state.usageFailureLogged) {
198
- state.usageFailureLogged = true
199
- log($, "Context usage unavailable · automatic clear-memory skipped")
200
- }
201
- }
359
+ if (!state.identity || state.resetting || state.headless || state.compactDisabled) return
360
+ const usage = await contextUsage($, state)
202
361
  if (state.turnRunning) return
203
- if ((complete && state.manualPending) || (typeof percent === "number" && Number.isFinite(percent) && percent >= 85)) {
362
+ let due = complete && state.manualPending
363
+ if (!due && usage !== undefined) {
364
+ const limits = await limitsOf($, state, usage)
365
+ const measured = limits === undefined ? undefined : measuredValue(limits, usage)
366
+ // Missing measurements do not trigger a reset.
367
+ if (limits !== undefined && measured !== undefined && measured >= limits.reset) due = true
368
+ }
369
+ if (due) {
204
370
  state.manualPending = false
205
371
  await reset($, state)
206
372
  }