notesoup 0.43.0 → 0.45.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 (76) hide show
  1. package/README.md +1 -0
  2. package/cordis.patch.yml +14 -0
  3. package/dist/src/boot/snapshot.d.ts +2 -0
  4. package/dist/src/boot/snapshot.js +4 -0
  5. package/dist/src/boot/text.js +3 -1
  6. package/dist/src/claude/helper.js +2 -2
  7. package/dist/src/dsh/budget.d.ts +20 -0
  8. package/dist/src/dsh/budget.js +34 -0
  9. package/dist/src/dsh/engine.d.ts +22 -0
  10. package/dist/src/dsh/engine.js +193 -0
  11. package/dist/src/dsh/history.d.ts +6 -0
  12. package/dist/src/dsh/history.js +73 -0
  13. package/dist/src/dsh/index.d.ts +22 -0
  14. package/dist/src/dsh/index.js +63 -0
  15. package/dist/src/dsh/preflight.d.ts +8 -0
  16. package/dist/src/dsh/preflight.js +35 -0
  17. package/dist/src/dsh/tools.d.ts +3 -0
  18. package/dist/src/dsh/tools.js +111 -0
  19. package/dist/src/dsh/window.d.ts +46 -0
  20. package/dist/src/dsh/window.js +124 -0
  21. package/dist/src/notes/address.d.ts +2 -2
  22. package/dist/src/notes/address.js +5 -5
  23. package/dist/src/notes/identity.js +2 -1
  24. package/dist/src/notes/paths.d.ts +1 -6
  25. package/dist/src/notes/paths.js +5 -68
  26. package/dist/src/notes/project-home.d.ts +25 -0
  27. package/dist/src/notes/project-home.js +231 -0
  28. package/dist/src/notes/store.d.ts +3 -2
  29. package/dist/src/notes/store.js +14 -8
  30. package/dist/src/pi/boot.js +17 -5
  31. package/dist/src/pi/notes/adapter.js +1 -1
  32. package/dist/src/tools/notes.d.ts +47 -17
  33. package/dist/src/tools/notes.js +15 -4
  34. package/dist/test/claude-mod.test.js +32 -1
  35. package/dist/test/dependencies.test.js +27 -1
  36. package/dist/test/dsh-cli.test.d.ts +1 -0
  37. package/dist/test/dsh-cli.test.js +44 -0
  38. package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
  39. package/dist/test/dsh-compaction-parity.test.js +143 -0
  40. package/dist/test/dsh.test.d.ts +1 -0
  41. package/dist/test/dsh.test.js +323 -0
  42. package/dist/test/helpers/dependency-graph.js +3 -3
  43. package/dist/test/helpers/dsh-messages.d.ts +29 -0
  44. package/dist/test/helpers/dsh-messages.js +33 -0
  45. package/dist/test/helpers/dsh.d.ts +17 -0
  46. package/dist/test/helpers/dsh.js +50 -0
  47. package/dist/test/notes.test.js +22 -19
  48. package/dist/test/project-home.test.d.ts +1 -0
  49. package/dist/test/project-home.test.js +134 -0
  50. package/docs/architecture.md +4 -1
  51. package/docs/dsh.md +61 -0
  52. package/docs/dsh.profile.patch.yml +34 -0
  53. package/mods/notesoup/.claude-plugin/plugin.json +1 -1
  54. package/mods/notesoup/dist/claude/helper.js +223 -56
  55. package/mods/notesoup/skills/memory/SKILL.md +1 -0
  56. package/package.json +63 -4
  57. package/skills/memory/SKILL.md +1 -0
  58. package/src/boot/snapshot.ts +5 -0
  59. package/src/boot/text.ts +3 -1
  60. package/src/claude/helper.ts +2 -2
  61. package/src/dsh/budget.ts +35 -0
  62. package/src/dsh/engine.ts +160 -0
  63. package/src/dsh/history.ts +57 -0
  64. package/src/dsh/index.ts +69 -0
  65. package/src/dsh/preflight.ts +29 -0
  66. package/src/dsh/tools.ts +107 -0
  67. package/src/dsh/window.ts +126 -0
  68. package/src/notes/address.ts +5 -5
  69. package/src/notes/identity.ts +1 -1
  70. package/src/notes/paths.ts +4 -60
  71. package/src/notes/project-home.ts +197 -0
  72. package/src/notes/store.ts +13 -9
  73. package/src/pi/boot.ts +15 -5
  74. package/src/pi/notes/adapter.ts +1 -1
  75. package/src/tools/notes.ts +16 -6
  76. package/mods/pi-context/dist/claude/helper.js +0 -9324
@@ -0,0 +1,35 @@
1
+ import type {} from "@deepseek-ai/dsh-token-meter";
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import type { CompactionAgentContext } from "@deepseek-ai/dsh-compaction";
4
+ import { estimateToolsTokens } from "@deepseek-ai/dsh-token-meter/estimate";
5
+ import type { LlmResolvedModelInfo } from "@deepseek-ai/dsh-llm";
6
+ import { deriveThresholds, remainingBudget } from "../budget/policy.js";
7
+
8
+ export type BudgetConfig = { auto: boolean; thresholdRatio: number; headroomTokens: number; reminderMarginTokens?: number };
9
+ export type Budget = { used: number; contextWindow: number; reserve: number; resetAt: number; remaining: number; countdown: number; warning: number; reminder: number };
10
+
11
+ /** The host's ratio and output/headroom reserves are one reset line, not competing policies. */
12
+ export async function measureBudget(ctx: Context, agent: CompactionAgentContext, config: BudgetConfig, signal?: AbortSignal): Promise<Budget | null> {
13
+ const route = agent.session.requestHeader()?.config ?? agent.options;
14
+ if (!route.provider || !route.model) return null;
15
+ const info: LlmResolvedModelInfo = await ctx.llm.resolveModelInfo(route.provider, route.model, signal);
16
+ const contextWindow = info.context?.contextWindow;
17
+ if (!contextWindow) return null;
18
+ const output = agent.session.requestHeader()?.config.maxTokens ?? (agent.options as { maxTokens?: number }).maxTokens ?? info.defaultMaxTokens ?? 0;
19
+ const resetAt = Math.floor(Math.min(contextWindow * config.thresholdRatio, contextWindow - output - config.headroomTokens));
20
+ if (resetAt <= 0) throw Object.assign(new Error(`notesoup: contextWindow=${contextWindow}, maxTokens=${output}, headroomTokens=${config.headroomTokens} leave resetAt=${resetAt}; reduce maxTokens or headroomTokens in the profile patch.`), { code: "BUDGET_CONFIG" });
21
+ const reserve = contextWindow - resetAt;
22
+ const { thresholds } = deriveThresholds(reserve, { reminderMarginTokens: config.reminderMarginTokens });
23
+ const measured = ctx.tokenMeter.measure(agent.session);
24
+ // alpha.2 carries a provider-usage anchor across a surface replacement. Until
25
+ // this window receives its own response, use the meter's current surface price.
26
+ const events = agent.session.snapshotEvents();
27
+ let used = measured.totalTokens;
28
+ for (let index = events.length - 1; index >= 0; index--) {
29
+ const event = events[index]!;
30
+ if (event.type === "assistant/message") break;
31
+ if (event.type === "user/message" && event.data.source.kind === "compact-checkpoint") { used = measured.surfaceTokens + estimateToolsTokens(agent.session.requestHeader()); break; }
32
+ }
33
+ const remaining = Math.max(0, contextWindow - used);
34
+ return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, thresholds.warning)!, warning: thresholds.warning, reminder: thresholds.reminder };
35
+ }
@@ -0,0 +1,160 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Context } from "@deepseek-ai/cordis";
3
+ import type { CommandId } from "@deepseek-ai/dsh-commands/brand";
4
+ import { CompactionEngine, CompactionId, ManualCompactionError, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from "@deepseek-ai/dsh-compaction";
5
+ import { createUserMessage, type ContentBlock } from "@deepseek-ai/dsh-llm";
6
+ import { appendPluginRecord, type Session, type SessionSeq } from "@deepseek-ai/dsh-session";
7
+ import { measureBudget, type BudgetConfig } from "./budget.js";
8
+ import { checkpointText, Windows, WINDOW_RECORD, type NotesConfig } from "./window.js";
9
+ import { preflight } from "./preflight.js";
10
+
11
+ export type EngineConfig = NotesConfig & Partial<BudgetConfig>;
12
+ export type ResolvedConfig = NotesConfig & BudgetConfig;
13
+ function resolveConfig(config: EngineConfig): ResolvedConfig {
14
+ const resolved = { ...config, auto: config.auto ?? true, thresholdRatio: config.thresholdRatio ?? 0.8, headroomTokens: config.headroomTokens ?? 65536 };
15
+ if (typeof resolved.auto !== "boolean" || !Number.isFinite(resolved.thresholdRatio) || resolved.thresholdRatio <= 0 || resolved.thresholdRatio > 1 || !Number.isSafeInteger(resolved.headroomTokens) || resolved.headroomTokens < 0 || (resolved.reminderMarginTokens !== undefined && (!Number.isSafeInteger(resolved.reminderMarginTokens) || resolved.reminderMarginTokens <= 0))) throw Object.assign(new Error("notesoup: auto must be boolean; thresholdRatio must be in (0,1]; headroomTokens must be an integer >=0; reminderMarginTokens must be an integer >0. Fix the notesoup-engine profile row."), { code: "CONFIG" });
16
+ const known = new Set(["auto", "thresholdRatio", "headroomTokens", "reminderMarginTokens", "notesHome", "agentName"]);
17
+ for (const key of Object.keys(config)) if (!known.has(key)) throw Object.assign(new Error(`notesoup: unknown engine parameter ${key}; remove it from the notesoup-engine profile row.`), { code: "CONFIG" });
18
+ return Object.freeze(resolved);
19
+ }
20
+
21
+ /** Durable lock and open-turn owner are separate facts, including after process reload. */
22
+ function entryState(session: Session): { turn: number | null; busy: boolean } {
23
+ let turn: number | null = null;
24
+ let start: SessionSeq | undefined;
25
+ let seed = -1;
26
+ for (const event of session.snapshotEvents()) {
27
+ if (event.type === "turn/start") turn = event.data.turn;
28
+ if (event.type === "turn/end") turn = null;
29
+ if (event.type === "session/end-seed") seed = event.seq;
30
+ if (event.type === "compaction/start") start = event.seq;
31
+ if (event.type === "compaction/end") start = undefined;
32
+ }
33
+ return { turn, busy: start !== undefined && start > seed };
34
+ }
35
+
36
+ function range(session: Session): { start: SessionSeq; end: SessionSeq } | null {
37
+ const nodes = session.surface.nodes;
38
+ // Node zero is host-owned even when no system head is present yet.
39
+ if (nodes.length <= 1) return null;
40
+ const start = nodes[1]!;
41
+ const end = nodes.at(-1)!;
42
+ if (!toolPairingBalancedBefore(session, start) || !toolPairingBalancedAfter(session, end)) return null;
43
+ return { start, end };
44
+ }
45
+
46
+ export class NotesoupCompactionEngine extends CompactionEngine {
47
+ static inject = ["llm", "tokenMeter", "sessions"];
48
+ readonly config: ResolvedConfig;
49
+ readonly windows: Windows;
50
+ private readonly lifecycle: { fiber: Context["fiber"] };
51
+ constructor(ctx: Context, config: EngineConfig = {}) {
52
+ super(ctx);
53
+ this.config = resolveConfig(config);
54
+ this.lifecycle = { fiber: ctx.fiber };
55
+ this.windows = new Windows(this.config);
56
+ // Assembly precedes pre-step. Reset here and refresh only our section in index.ts.
57
+ ctx.on("system-prompt/assemble", async (_assembly, input, next) => {
58
+ if (input.agent && input.signal && !input.signal.aborted) {
59
+ preflight(ctx);
60
+ await this.compactIfNeeded(input.agent, "pressure", input.signal);
61
+ }
62
+ return next();
63
+ });
64
+ }
65
+ get automaticListenerPresent(): boolean {
66
+ // Effect diagnostics are a public capability; no Cordis hook-table inspection.
67
+ return this.lifecycle.fiber.getEffects().some((effect) => effect.label === 'ctx.on("system-prompt/assemble")');
68
+ }
69
+ async compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null> {
70
+ signal.throwIfAborted();
71
+ const state = this.windows.get(agent.session);
72
+ const forced = state.pendingReset;
73
+ if (!forced) {
74
+ if (!this.config.auto) return null;
75
+ // Context overflow is deliberately left to the host. This adapter owns reserve resets.
76
+ if (trigger === "context-overflow") return null;
77
+ const budget = await measureBudget(this.ctx, agent, this.config, signal);
78
+ if (!budget || budget.remaining > budget.reserve) return null;
79
+ }
80
+ const selected = range(agent.session);
81
+ if (!selected) return null;
82
+ return this.compactRegion(selected.start, selected.end, agent, signal);
83
+ }
84
+ async compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal): Promise<CompactionResult> {
85
+ if (entryState(agent.session).turn === null) throw new ManualCompactionError("busy", "notesoup: compactRegion needs an open turn; use compactNow while idle.");
86
+ return this.transaction(start, end, agent, signal);
87
+ }
88
+ compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null> {
89
+ signal.throwIfAborted();
90
+ try {
91
+ return agent.runMaintenance(async (ownerSignal) => {
92
+ const combined = AbortSignal.any([signal, ownerSignal]);
93
+ combined.throwIfAborted();
94
+ if (entryState(agent.session).turn !== null) throw new ManualCompactionError("busy", "notesoup: an open turn remains; wait for the agent to stop, then retry.");
95
+ const selected = range(agent.session);
96
+ if (!selected) return null;
97
+ return this.transaction(selected.start, selected.end, agent, combined, sourceCommandId, true);
98
+ });
99
+ } catch (error) { throw new ManualCompactionError("busy", "notesoup: wait for the agent to become idle, then retry compactNow.", { cause: error }); }
100
+ }
101
+
102
+ /** No model call, no shrink requirement: even a one-message window can be cleared. */
103
+ private async transaction(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal, sourceCommandId?: CommandId, flush = false): Promise<CompactionResult> {
104
+ const session = agent.session;
105
+ signal?.throwIfAborted();
106
+ const selected = range(session);
107
+ if (!selected || selected.start !== start || selected.end !== end) throw new ManualCompactionError("changed", `notesoup: reset must cover surface positions 1..${session.surface.nodes.length - 1} with balanced tools; retry after the tool batch finishes.`);
108
+ const entry = entryState(session);
109
+ if (entry.busy) throw new ManualCompactionError("busy", "notesoup: a compaction/start has no matching end; reload this session before retrying.");
110
+ const state = this.windows.get(session);
111
+ const previous = state.snapshot;
112
+ const shadowedSeqs = [...session.surface.nodes.slice(1)];
113
+ const generation = session.surface.contentGeneration;
114
+ const measured = this.ctx.tokenMeter.measure(session);
115
+ const shadowedTokenCount = measured.nodes.slice(1).reduce((sum, node) => sum + node.heuristicTokens, 0);
116
+ const compactionId = CompactionId(randomUUID());
117
+ const lifecycle = { compactionId, turn: entry.turn, ...(sourceCommandId === undefined ? {} : { sourceCommandId }) };
118
+ // Synchronous lock acquisition precedes the snapshot's first await.
119
+ const opened = session.append("compaction/start", lifecycle);
120
+ let landed = false;
121
+ let closing = false;
122
+ let closed = false;
123
+ let result: CompactionResult | undefined;
124
+ let failure: unknown;
125
+ try {
126
+ const next = await this.windows.mint(agent, previous.window + 1, opened.time);
127
+ signal?.throwIfAborted();
128
+ if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1) throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
129
+ // Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
130
+ state.snapshot = next;
131
+ const summary: ContentBlock[] = [{ type: "text", text: checkpointText(next) }];
132
+ const summarized = session.append("compaction/summary", { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount, provider: "notesoup", model: "notes" });
133
+ session.append("user/message", createUserMessage({ content: summary, source: compactCheckpointSource(compactionId, sourceCommandId) }), { surfaceOp: { op: "replace", startSeq: start, endSeq: end }, sourceEventSeqs: [opened.seq, summarized.seq, ...shadowedSeqs] });
134
+ landed = true;
135
+ state.pendingReset = false;
136
+ state.warned = false;
137
+ state.reminded = false;
138
+ closing = true;
139
+ const ended = session.append("compaction/end", lifecycle);
140
+ closed = true;
141
+ result = { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), startSeq: opened.seq, summarySeq: summarized.seq, endSeq: ended.seq, summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount };
142
+ try { appendPluginRecord(session, WINDOW_RECORD, next); }
143
+ catch (error) { this.ctx.logger.warn(`notesoup: window record could not be written; the checkpoint holds ${next.windowId}. ${String(error)}`); }
144
+ } catch (error) {
145
+ if (!landed) state.snapshot = previous;
146
+ failure = error;
147
+ if (!closing) {
148
+ try { session.append("compaction/end", { ...lifecycle, error: String(error) }); closed = true; }
149
+ catch (closeError) { failure = new ManualCompactionError("commit", "notesoup: compaction/end failed; reload the session before another reset.", { cause: closeError }); }
150
+ } else failure = new ManualCompactionError("commit", "notesoup: checkpoint landed but compaction/end failed; reload before another reset.", { cause: error });
151
+ }
152
+ if (flush && closed) {
153
+ try { await this.ctx.sessions.flush(session); }
154
+ catch (error) { if (!failure) failure = new ManualCompactionError("persistence", "notesoup: the reset is in the live log but its disk flush failed; retry the session flush before exiting.", { cause: error }); }
155
+ }
156
+ if (failure) throw failure;
157
+ return result!;
158
+ }
159
+ }
160
+ export default NotesoupCompactionEngine;
@@ -0,0 +1,57 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { SessionId, SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import type {} from "@deepseek-ai/dsh-session-query";
4
+ import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "../history/history.js";
5
+ import { checkpointSnapshot, recordSnapshot, windowId } from "./window.js";
6
+
7
+ /** Preserve every recorded block; attachments/reasoning have JSON evidence rather than invented text. */
8
+ function blockText(content: unknown, omitCalls = false): string {
9
+ if (!Array.isArray(content)) return typeof content === "string" ? content : JSON.stringify(content) ?? "";
10
+ return content.filter((block) => !omitCalls || block.type !== "tool-call").map((block) => block.type === "text" ? block.text : JSON.stringify(block)).join("\n");
11
+ }
12
+ function argumentsOf(text: string): Record<string, unknown> | undefined {
13
+ try {
14
+ const value: unknown = JSON.parse(text);
15
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
16
+ } catch { return undefined; }
17
+ }
18
+
19
+ /** Native seq zero becomes public seq one. Forks contain only their selected seed prefix. */
20
+ export function decodeHistory(sessionId: string, events: readonly SessionEvent[]): HistoryProjection {
21
+ let current: DecodedHistoryWindow = { windowId: windowId(sessionId, 0), items: [] };
22
+ const windows = [current];
23
+ const branchSeqs = new Set<number>();
24
+ for (const event of events) {
25
+ const seq = event.seq + 1;
26
+ branchSeqs.add(seq);
27
+ const checkpoint = checkpointSnapshot(event);
28
+ const snapshot = checkpoint ?? recordSnapshot(event);
29
+ if (snapshot && current.windowId !== snapshot.windowId) {
30
+ // A root snapshot identifies the initial window; it does not create an empty extra window.
31
+ if (snapshot.window === 0 && windows.length === 1 && current.items.length === 0) current.windowId = snapshot.windowId;
32
+ else { current = { windowId: snapshot.windowId, createdAt: new Date(event.time).toISOString(), items: [] }; windows.push(current); }
33
+ }
34
+ const base = { seq, windowId: current.windowId, createdAt: new Date(event.time).toISOString() };
35
+ let item: DecodedHistoryItem | undefined;
36
+ switch (event.type) {
37
+ case "user/message": item = { ...base, role: checkpoint ? "system" : "user", text: blockText(event.data.content) }; break;
38
+ case "system/message": item = { ...base, role: "system", text: blockText(event.data.message.content) }; break;
39
+ case "developer/message": item = { ...base, role: "developer", text: blockText(event.data.message.content) }; break;
40
+ case "assistant/message": {
41
+ const text = blockText(event.data.message.content, true);
42
+ if (text) item = { ...base, role: "assistant", text };
43
+ break;
44
+ }
45
+ case "assistant/attempt": item = { ...base, role: "assistant", text: JSON.stringify(event.data.stream) }; break;
46
+ case "tool/call": item = { ...base, role: "tool_call", text: event.data.arguments, toolName: event.data.name, toolCallId: event.data.callId, ...(argumentsOf(event.data.arguments) ? { arguments: argumentsOf(event.data.arguments) } : {}) }; break;
47
+ case "tool/result": item = { ...base, role: "tool", text: blockText(event.data.message.content), toolCallId: event.data.message.source.callId, toolError: event.data.message.isError }; break;
48
+ }
49
+ if (item) current.items.push(item);
50
+ }
51
+ return projectHistory(windows, events.at(-1) === undefined ? 0 : events.at(-1)!.seq + 1, branchSeqs);
52
+ }
53
+
54
+ export async function historyProjection(ctx: Context, sessionId: SessionId): Promise<HistoryProjection> {
55
+ const log = await ctx.sessionQuery.readSession(sessionId);
56
+ return decodeHistory(sessionId, log.events);
57
+ }
@@ -0,0 +1,69 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type {} from "@deepseek-ai/dsh-agent";
3
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
+ import { CONTINUATION, WARNING_PROMPT, tokenBudgetGuidance } from "../budget/text.js";
5
+ import { measureBudget } from "./budget.js";
6
+ import { BOOT_SECTION, restoreWarnings } from "./window.js";
7
+ import { preflight } from "./preflight.js";
8
+ import { registerTools } from "./tools.js";
9
+
10
+ export const name = "notesoup-dsh";
11
+ export const inject = ["tools", "sessions", "systemPrompt", "llm", "tokenMeter", "sessionQuery", "compaction"];
12
+
13
+ declare module "@deepseek-ai/dsh-llm" {
14
+ interface MessageSourceMap {
15
+ "notesoup-budget": { kind: "notesoup-budget"; windowId: string; phase: "reminder" | "warning" };
16
+ "notesoup-continuation": { kind: "notesoup-continuation" };
17
+ }
18
+ }
19
+
20
+ export function apply(ctx: Context): void {
21
+ const engine = preflight(ctx);
22
+ ctx.on("agent/created", async ({ agent, signal }) => {
23
+ preflight(ctx);
24
+ await engine.windows.adopt(agent, signal);
25
+ });
26
+ ctx.systemPrompt.section({ name: BOOT_SECTION, order: 2450, interpolate: false, text: ({ agent }) => agent ? engine.windows.get(agent.session).snapshot.boot : "" });
27
+ // Section providers run before the engine's awaited reset. Refresh the accepted section
28
+ // after the entire assembly waterfall so the same request uses the newly minted boot.
29
+ ctx.on("system-prompt/assemble", async (_assembly, input, next) => {
30
+ const assembly = await next();
31
+ if (input.agent) {
32
+ const boot = assembly.sections.find((section) => section.name === BOOT_SECTION);
33
+ if (!boot) throw Object.assign(new Error("notesoup: boot section was removed; restore notesoup:boot before running this agent."), { code: "BOOT_SECTION" });
34
+ boot.text = engine.windows.get(input.agent.session).snapshot.boot;
35
+ }
36
+ return assembly;
37
+ }, { prepend: true });
38
+ ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
39
+ preflight(ctx);
40
+ if (!signal.aborted && engine.config.auto) {
41
+ const budget = await measureBudget(ctx, agent, engine.config, signal);
42
+ if (budget) {
43
+ const state = engine.windows.get(agent.session);
44
+ const phase = budget.remaining <= budget.warning ? "warning" : budget.remaining <= budget.reminder ? "reminder" : undefined;
45
+ if (phase && !(phase === "warning" ? state.warned : state.reminded || state.warned)) {
46
+ const text = phase === "warning" ? WARNING_PROMPT : tokenBudgetGuidance(budget.countdown, "clear_memory");
47
+ agent.steer(createUserMessage({ content: [{ type: "text", text }], source: { kind: "notesoup-budget", windowId: state.snapshot.windowId, phase } }));
48
+ if (phase === "warning") state.warned = true;
49
+ else state.reminded = true;
50
+ }
51
+ }
52
+ }
53
+ return next();
54
+ });
55
+ ctx.on("agent/turn-stopping", async ({ agent, signal }) => {
56
+ if (signal.aborted) return;
57
+ const result = await engine.compactIfNeeded(agent, "pressure", signal);
58
+ if (result) agent.steer(createUserMessage({ content: [{ type: "text", text: CONTINUATION }], source: { kind: "notesoup-continuation" } }));
59
+ });
60
+ ctx.on("session/event", (session, event) => {
61
+ if (event.type === "turn/end" && event.data.reason.kind !== "completed") {
62
+ const state = engine.windows.get(session);
63
+ state.pendingReset = false;
64
+ restoreWarnings(state, session.snapshotEvents());
65
+ }
66
+ });
67
+ registerTools(ctx, engine);
68
+ }
69
+ export default { name, inject, apply };
@@ -0,0 +1,29 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type {} from "@deepseek-ai/cordis-plugin-loader";
3
+ import { NotesoupCompactionEngine } from "./engine.js";
4
+
5
+ export class PreflightError extends Error {
6
+ constructor(readonly code: string, message: string) { super(`notesoup: ${message}`); }
7
+ }
8
+
9
+ /** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
10
+ export function preflight(ctx: Context): NotesoupCompactionEngine {
11
+ for (const [service, method] of [["systemPrompt", "section"], ["tools", "register"], ["sessionQuery", "readSession"], ["tokenMeter", "measure"], ["llm", "resolveModelInfo"]] as const) {
12
+ const mounted = ctx.get(service) as unknown as Record<string, unknown> | undefined;
13
+ if (typeof mounted?.[method] !== "function") throw new PreflightError("CAPABILITY", `${service}.${method} is unavailable; enable that service in the profile before using notesoup.`);
14
+ }
15
+ const engine = ctx.get("compaction");
16
+ if (!(engine instanceof NotesoupCompactionEngine)) throw new PreflightError("ENGINE", "ctx.compaction must be NotesoupCompactionEngine; disable compaction-basic and enable the notesoup-engine row, then restart dsh.");
17
+ const loader = ctx.get("loader");
18
+ if (loader) {
19
+ if (typeof loader.entries !== "function") throw new PreflightError("CAPABILITY", "loader.entries is unavailable; this profile cannot be checked for two engines.");
20
+ for (const entry of loader.entries()) {
21
+ if ((entry.options.id === "compaction-basic" || /(?:^|\/)dsh-compaction-basic$/.test(entry.options.name)) && !entry.disabled) throw new PreflightError("DOUBLE_ENGINE", "compaction-basic is enabled; set disabled: true on that profile row and restart dsh.");
22
+ }
23
+ }
24
+ for (const [callback, runtime] of ctx.registry.entries()) {
25
+ if (callback.name === "BasicCompactionEngine" && runtime.fibers.length > 0) throw new PreflightError("DOUBLE_ENGINE", "a BasicCompactionEngine fiber is mounted; remove it before starting notesoup.");
26
+ }
27
+ if (!engine.automaticListenerPresent) throw new PreflightError("AUTO_LISTENER", "the automatic reset listener is missing; reload notesoup-engine before sending another request.");
28
+ return engine;
29
+ }
@@ -0,0 +1,107 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { Agent } from "@deepseek-ai/dsh-agent";
3
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
4
+ import { defineTool, type JsonSchemaNode, type ObjectJsonSchema, type ToolRunContext } from "@deepseek-ai/dsh-tools";
5
+ import type { Static, TSchema } from "typebox";
6
+ import { Check, Errors } from "typebox/value";
7
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
8
+ import { historyList, historyRead, historyWindows } from "../tools/history.js";
9
+ import { success, type Operation } from "../tools/result.js";
10
+ import { historyProjection } from "./history.js";
11
+ import { notesIdentity } from "./window.js";
12
+ import { measureBudget } from "./budget.js";
13
+ import { preflight } from "./preflight.js";
14
+ import type { NotesoupCompactionEngine } from "./engine.js";
15
+
16
+ /** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
17
+ function hostSchema(schema: TSchema): JsonSchemaNode {
18
+ const value = JSON.parse(JSON.stringify(schema)) as Record<string, unknown>;
19
+ const result: Record<string, unknown> = {};
20
+ for (const key of ["type", "required", "additionalProperties", "enum", "const", "description", "title", "default", "examples"]) if (value[key] !== undefined) result[key] = value[key];
21
+ const bounds = ["minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems"].filter((key) => value[key] !== undefined).map((key) => `${key}=${value[key]}`);
22
+ if (bounds.length) result.description = [value.description, bounds.join(", ")].filter(Boolean).join("; ");
23
+ if (Array.isArray(value.anyOf)) result.oneOf = value.anyOf.map((branch) => hostSchema(branch as TSchema));
24
+ if (value.properties) result.properties = Object.fromEntries(Object.entries(value.properties as Record<string, TSchema>).map(([key, child]) => [key, hostSchema(child)]));
25
+ if (value.items) result.items = hostSchema(value.items as TSchema);
26
+ return result as JsonSchemaNode;
27
+ }
28
+ function requireAgent(exec: ToolRunContext): Agent {
29
+ if (!exec.agent) throw new HarnessError("notesoup: this tool needs an agent session; call it from a dsh agent.", "AGENT_REQUIRED");
30
+ exec.signal.throwIfAborted();
31
+ return exec.agent;
32
+ }
33
+
34
+ function register<P extends TSchema, D, R extends readonly unknown[]>(ctx: Context, operation: Operation<P, D, R>, inputs: (agent: Agent) => Readonly<R> | Promise<Readonly<R>>): void {
35
+ ctx.tools.register({
36
+ name: operation.name,
37
+ description: operation.description,
38
+ parameters: hostSchema(operation.parameters) as ObjectJsonSchema & Record<string, unknown>,
39
+ output: {
40
+ schema: hostSchema(operation.outputSchema),
41
+ render: (_args, value) => [{ type: "text", text: operation.render(success(value as D)) }],
42
+ },
43
+ async execute(args, exec) {
44
+ const agent = requireAgent(exec);
45
+ preflight(ctx);
46
+ if (!Check(operation.parameters, args)) {
47
+ const error = Errors(operation.parameters, args).find((problem) => problem.keyword !== "boolean");
48
+ throw new HarnessError(`notesoup: invalid ${operation.name} parameter ${error?.instancePath || "/"}: ${error?.message ?? "invalid value"}; use the tool schema's bounds.`, "INVALID_PARAMS");
49
+ }
50
+ const rest = await inputs(agent);
51
+ exec.signal.throwIfAborted();
52
+ const result = await operation.execute(args as Static<P>, ...rest);
53
+ if (!result.ok) throw new HarnessError(operation.render(result), result.error.code);
54
+ return result.data;
55
+ },
56
+ });
57
+ }
58
+
59
+ export function registerTools(ctx: Context, engine: NotesoupCompactionEngine): void {
60
+ const nestedResets = new WeakMap<Agent, Set<string>>();
61
+ ctx.on("tools/result", (exec, result) => {
62
+ if (!exec.agent) return;
63
+ const state = engine.windows.get(exec.agent.session);
64
+ if (exec.name === "clear_memory" && !result.isError && (result.value as { window_id?: string }).window_id === state.snapshot.windowId) {
65
+ if (!exec.parent) state.pendingReset = true;
66
+ else {
67
+ const roots = nestedResets.get(exec.agent) ?? new Set<string>();
68
+ roots.add(exec.rootCallId);
69
+ nestedResets.set(exec.agent, roots);
70
+ }
71
+ }
72
+ if (!exec.parent && nestedResets.get(exec.agent)?.delete(exec.rootCallId) && !result.isError) state.pendingReset = true;
73
+ });
74
+ const identity = (agent: Agent) => notesIdentity(agent, engine.config);
75
+ register(ctx, notesWrite, (agent) => [identity(agent)] as const);
76
+ register(ctx, notesUpdate, (agent) => [identity(agent), (change) => change.kind === "none" ? "" : `note ${change.kind}`] as const);
77
+ register(ctx, notesRead, (agent) => [identity(agent)] as const);
78
+ register(ctx, notesList, (agent) => [identity(agent)] as const);
79
+ register(ctx, notesSearch, (agent) => [identity(agent)] as const);
80
+ register(ctx, historyList, async (agent) => [await historyProjection(ctx, agent.session.id)] as const);
81
+ register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)] as const);
82
+ register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id] as const);
83
+ ctx.tools.register(defineTool({
84
+ name: "clear_memory",
85
+ description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
86
+ parameters: {},
87
+ output: { schema: { type: "object", properties: { window_id: { type: "string", required: true }, reset_requested: { type: "boolean", required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: `notesoup: reset requested for ${value.window_id}; finish this tool batch, then recover from your notes.` }] },
88
+ async execute(_args, exec) {
89
+ const agent = requireAgent(exec);
90
+ preflight(ctx);
91
+ const state = engine.windows.get(agent.session);
92
+ return { window_id: state.snapshot.windowId, reset_requested: true };
93
+ },
94
+ }));
95
+ ctx.tools.register(defineTool({
96
+ name: "get_context_remaining",
97
+ description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
98
+ parameters: {},
99
+ output: { schema: { type: "object", properties: { remaining_tokens: { oneOf: [{ type: "integer" }, { type: "null" }], required: true } }, additionalProperties: false }, render: (_args, value) => [{ type: "text", text: JSON.stringify(value) }] },
100
+ async execute(_args, exec) {
101
+ const agent = requireAgent(exec);
102
+ preflight(ctx);
103
+ const budget = await measureBudget(ctx, agent, engine.config, exec.signal);
104
+ return { remaining_tokens: budget?.countdown ?? null };
105
+ },
106
+ }));
107
+ }
@@ -0,0 +1,126 @@
1
+ import type { Agent } from "@deepseek-ai/dsh-agent";
2
+ import { appendPluginRecord, pluginRecordOf, type Session, type SessionEvent } from "@deepseek-ai/dsh-session";
3
+ import { isCompactCheckpointSource } from "@deepseek-ai/dsh-compaction";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { loadNotesSnapshot } from "../boot/snapshot.js";
8
+ import { renderBootBlock } from "../boot/render.js";
9
+ import { CONTINUATION } from "../budget/text.js";
10
+ import { contentText } from "../history/history.js";
11
+ import { slugify } from "../notes/paths.js";
12
+ import { resolveProjectHome } from "../notes/project-home.js";
13
+ import { snapshotNotesIdentity, type NotesIdentity } from "../notes/identity.js";
14
+
15
+ export const WINDOW_RECORD = "plugin:notesoup/window";
16
+ export const BOOT_SECTION = "notesoup:boot";
17
+ const BOOT_OPEN = "<notesoup-boot>\n";
18
+ const BOOT_CLOSE = "\n</notesoup-boot>";
19
+ const CHECKPOINT_END = "\n\n<notesoup-continuation>\n";
20
+ const TOOLS = { notes: "notes_*", notesList: "notes_list", history: "history_*", remaining: "get_context_remaining", wipe: "clear_memory" };
21
+ export type WindowSnapshot = Readonly<{ version: 1; window: number; windowId: string; openedAt: number; boot: string; notesDigest: string }>;
22
+ export type WindowState = { snapshot: WindowSnapshot; pendingReset: boolean; warned: boolean; reminded: boolean };
23
+ export type NotesConfig = { notesHome?: string; agentName?: string };
24
+
25
+ export function restoreWarnings(state: WindowState, events: readonly SessionEvent[]): void {
26
+ state.warned = false;
27
+ state.reminded = false;
28
+ for (const event of events) {
29
+ if (event.type === "user/message" && event.data.source.kind === "notesoup-budget" && event.data.source.windowId === state.snapshot.windowId) {
30
+ if (event.data.source.phase === "warning") state.warned = true;
31
+ else state.reminded = true;
32
+ }
33
+ }
34
+ }
35
+
36
+ declare module "@deepseek-ai/dsh-session/types" {
37
+ interface PluginRecordMap { "plugin:notesoup/window": WindowSnapshot }
38
+ }
39
+
40
+ export function windowId(sessionId: string, window: number): string { return `dsh:${sessionId}:${window}`; }
41
+ function digest(boot: string): string { return createHash("sha256").update(boot).digest("hex"); }
42
+ export function checkpointText(snapshot: WindowSnapshot): string { return snapshot.boot + CHECKPOINT_END + CONTINUATION + "\n</notesoup-continuation>"; }
43
+
44
+ export function recordSnapshot(event: SessionEvent): WindowSnapshot | undefined {
45
+ const record = pluginRecordOf(event);
46
+ if (record?.type !== WINDOW_RECORD || typeof record.data !== "object" || record.data === null) return undefined;
47
+ const value = record.data as Partial<WindowSnapshot>;
48
+ if (value.version !== 1 || !Number.isSafeInteger(value.window) || value.window! < 0 || typeof value.windowId !== "string" || typeof value.openedAt !== "number" || typeof value.boot !== "string" || value.notesDigest !== digest(value.boot)) return undefined;
49
+ return Object.freeze(value as WindowSnapshot);
50
+ }
51
+
52
+ /** The checkpoint is authoritative when an ignorable record was lost or the transaction's close failed. */
53
+ export function checkpointSnapshot(event: SessionEvent): WindowSnapshot | undefined {
54
+ if (event.type !== "user/message" || !isCompactCheckpointSource(event.data.source)) return undefined;
55
+ const text = contentText(event.data.content);
56
+ const end = text.lastIndexOf(CHECKPOINT_END);
57
+ if (end < 0 || !text.startsWith(BOOT_OPEN)) return undefined;
58
+ return snapshotFromBoot(text.slice(0, end), event.time);
59
+ }
60
+
61
+ function systemSnapshot(event: SessionEvent): WindowSnapshot | undefined {
62
+ if (event.type !== "system/message") return undefined;
63
+ const text = contentText(event.data.message.content);
64
+ const start = text.indexOf(BOOT_OPEN);
65
+ const end = text.lastIndexOf(BOOT_CLOSE);
66
+ if (start < 0 || end < 0) return undefined;
67
+ return snapshotFromBoot(text.slice(start, end + BOOT_CLOSE.length), event.time);
68
+ }
69
+
70
+ function snapshotFromBoot(boot: string, openedAt: number): WindowSnapshot | undefined {
71
+ const id = /^Current context window id: (dsh:.*:(\d+))$/m.exec(boot);
72
+ if (!id || !Number.isSafeInteger(Number(id[2]))) return undefined;
73
+ return Object.freeze({ version: 1, window: Number(id[2]), windowId: id[1]!, openedAt, boot, notesDigest: digest(boot) });
74
+ }
75
+
76
+ export function recoverSnapshot(events: readonly SessionEvent[]): WindowSnapshot | undefined {
77
+ let latest: WindowSnapshot | undefined;
78
+ for (const event of events) {
79
+ const candidate = checkpointSnapshot(event) ?? recordSnapshot(event) ?? systemSnapshot(event);
80
+ if (candidate && (!latest || candidate.window >= latest.window)) latest = candidate;
81
+ }
82
+ return latest;
83
+ }
84
+
85
+ /** Identity is extracted here, never in the filesystem domain. */
86
+ export function notesIdentity(agent: Pick<Agent, "session" | "options">, config: NotesConfig): NotesIdentity {
87
+ const home = config.notesHome ?? join(homedir(), ".agents", "notes");
88
+ return snapshotNotesIdentity({
89
+ home,
90
+ sessionId: agent.session.id,
91
+ projectKey: resolveProjectHome(agent.session.header.cwd ?? process.cwd(), home).name,
92
+ agent: slugify(config.agentName ?? "dsh"),
93
+ model: slugify(agent.session.requestHeader()?.config.model ?? agent.options.model ?? "unknown"),
94
+ });
95
+ }
96
+
97
+ /** Engine-owned, per-session state; prompt reads are synchronous and never read notes again. */
98
+ export class Windows {
99
+ private states = new WeakMap<Session, WindowState>();
100
+ constructor(readonly config: NotesConfig) {}
101
+ get(session: Session): WindowState {
102
+ const state = this.states.get(session);
103
+ if (!state) throw Object.assign(new Error("notesoup: window missing; initialize at agent/created before sending a request."), { code: "WINDOW_MISSING" });
104
+ return state;
105
+ }
106
+ async adopt(agent: Agent, signal?: AbortSignal): Promise<WindowState> {
107
+ const existing = this.states.get(agent.session);
108
+ if (existing) return existing;
109
+ const restored = recoverSnapshot(agent.session.snapshotEvents());
110
+ const snapshot = restored ?? await this.mint(agent, 0, agent.session.header.createdAt);
111
+ signal?.throwIfAborted();
112
+ if (!restored) appendPluginRecord(agent.session, WINDOW_RECORD, snapshot);
113
+ const state = { snapshot, pendingReset: false, warned: false, reminded: false };
114
+ restoreWarnings(state, agent.session.snapshotEvents());
115
+ this.states.set(agent.session, state);
116
+ return state;
117
+ }
118
+ async mint(agent: Pick<Agent, "session" | "options">, window: number, openedAt: number): Promise<WindowSnapshot> {
119
+ const identity = notesIdentity(agent, this.config);
120
+ const notes = await loadNotesSnapshot(identity, openedAt);
121
+ const previous = this.states.get(agent.session)?.snapshot;
122
+ const firstWindowId = previous?.boot.match(/^First context window id: (.+)$/m)?.[1] ?? windowId(agent.session.id, 0);
123
+ const boot = BOOT_OPEN + renderBootBlock({ agentName: identity.agent, modelName: identity.model, firstWindowId, currentWindowId: windowId(agent.session.id, window), ...(window ? { previousWindowId: previous?.windowId ?? windowId(agent.session.id, window - 1) } : {}), notes, tools: TOOLS }) + BOOT_CLOSE;
124
+ return Object.freeze({ version: 1, window, windowId: windowId(agent.session.id, window), openedAt, boot, notesDigest: digest(boot) });
125
+ }
126
+ }
@@ -4,7 +4,7 @@ import { assertVirtualPath, SLUG_PATTERN, type Scope } from "./paths.js";
4
4
 
5
5
  export type NoteAddress = { scope: Scope; path: string; who?: string };
6
6
 
7
- export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path.";
7
+ export const ADDRESS_FORMS = "Use <path> for this session, or @project/, @human/, @self/, or @model/ followed by a path; @projects/<name>/<path> reads a named project home.";
8
8
 
9
9
  /**
10
10
  * Minimal glob over virtual note paths: `*` matches any run within a segment (never
@@ -44,7 +44,7 @@ export function assertGlobPattern(value: unknown): string | undefined {
44
44
 
45
45
  /**
46
46
  * Decode one public note address into its physical home and virtual path. @self and @model
47
- * are relative; explicit agents/models addresses always name a canonical slug.
47
+ * are relative; explicit projects/agents/models addresses always name one canonical slug.
48
48
  */
49
49
  export function assertAddress(value: unknown): NoteAddress {
50
50
  if (typeof value !== "string") throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -61,11 +61,11 @@ export function assertAddress(value: unknown): NoteAddress {
61
61
  else if (head === "human") scope = "human";
62
62
  else if (head === "self") scope = "agent";
63
63
  else if (head === "model") scope = "model";
64
- else if (head === "agents" || head === "models") {
64
+ else if (head === "projects" || head === "agents" || head === "models") {
65
65
  const nameEnd = tail.indexOf("/");
66
66
  who = nameEnd === -1 ? tail : tail.slice(0, nameEnd);
67
67
  if (!SLUG_PATTERN.test(who)) throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
68
- scope = head === "agents" ? "agent" : "model";
68
+ scope = head === "projects" ? "project" : head === "agents" ? "agent" : "model";
69
69
  path = nameEnd === -1 ? "" : tail.slice(nameEnd + 1);
70
70
  } else {
71
71
  throw new NoteError("invalid_address", `${shown(value)} isn't a note address. ${ADDRESS_FORMS}`);
@@ -81,7 +81,7 @@ export function assertAddress(value: unknown): NoteAddress {
81
81
  /** Render a virtual path in its one unambiguous address form, used to match patterns. */
82
82
  export function canonicalAddressFor(identity: NotesIdentity, scope: Scope, path: string, who?: string): string {
83
83
  if (scope === "session") return path;
84
- if (scope === "project") return `@project/${path}`;
84
+ if (scope === "project") return who === undefined ? `@project/${path}` : `@projects/${who}/${path}`;
85
85
  if (scope === "human") return `@human/${path}`;
86
86
  if (scope === "agent") return `@agents/${who ?? identity.agent}/${path}`;
87
87
  return `@models/${who ?? identity.model}/${path}`;
@@ -30,7 +30,7 @@ export function snapshotNotesIdentity(value: NotesIdentity): NotesIdentity {
30
30
  const agent = requireString("agent", value.agent);
31
31
  const model = requireString("model", value.model);
32
32
  assertDirectoryComponent("sessionId", sessionId);
33
- assertDirectoryComponent("projectKey", projectKey);
33
+ if (!SLUG_PATTERN.test(projectKey)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
34
34
  if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
35
35
  if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
36
36
  const home = resolve(homeValue);