notesoup 0.44.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.
- package/README.md +1 -0
- package/cordis.patch.yml +14 -0
- package/dist/src/dsh/budget.d.ts +20 -0
- package/dist/src/dsh/budget.js +34 -0
- package/dist/src/dsh/engine.d.ts +22 -0
- package/dist/src/dsh/engine.js +193 -0
- package/dist/src/dsh/history.d.ts +6 -0
- package/dist/src/dsh/history.js +73 -0
- package/dist/src/dsh/index.d.ts +22 -0
- package/dist/src/dsh/index.js +63 -0
- package/dist/src/dsh/preflight.d.ts +8 -0
- package/dist/src/dsh/preflight.js +35 -0
- package/dist/src/dsh/tools.d.ts +3 -0
- package/dist/src/dsh/tools.js +111 -0
- package/dist/src/dsh/window.d.ts +46 -0
- package/dist/src/dsh/window.js +124 -0
- package/dist/test/dependencies.test.js +27 -1
- package/dist/test/dsh-cli.test.d.ts +1 -0
- package/dist/test/dsh-cli.test.js +44 -0
- package/dist/test/dsh-compaction-parity.test.d.ts +1 -0
- package/dist/test/dsh-compaction-parity.test.js +143 -0
- package/dist/test/dsh.test.d.ts +1 -0
- package/dist/test/dsh.test.js +323 -0
- package/dist/test/helpers/dependency-graph.js +3 -3
- package/dist/test/helpers/dsh-messages.d.ts +29 -0
- package/dist/test/helpers/dsh-messages.js +33 -0
- package/dist/test/helpers/dsh.d.ts +17 -0
- package/dist/test/helpers/dsh.js +50 -0
- package/docs/architecture.md +4 -1
- package/docs/dsh.md +61 -0
- package/docs/dsh.profile.patch.yml +34 -0
- package/mods/notesoup/.claude-plugin/plugin.json +1 -1
- package/package.json +63 -4
- package/src/dsh/budget.ts +35 -0
- package/src/dsh/engine.ts +160 -0
- package/src/dsh/history.ts +57 -0
- package/src/dsh/index.ts +69 -0
- package/src/dsh/preflight.ts +29 -0
- package/src/dsh/tools.ts +107 -0
- package/src/dsh/window.ts +126 -0
- package/mods/pi-context/dist/claude/helper.js +0 -9324
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "notesoup",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.45.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/src/index.js",
|
|
6
6
|
"types": "./dist/src/index.d.ts",
|
|
@@ -13,7 +13,15 @@
|
|
|
13
13
|
"types": "./dist/src/notes/index.d.ts",
|
|
14
14
|
"import": "./dist/src/notes/index.js"
|
|
15
15
|
},
|
|
16
|
-
"./package.json": "./package.json"
|
|
16
|
+
"./package.json": "./package.json",
|
|
17
|
+
"./dsh": {
|
|
18
|
+
"types": "./dist/src/dsh/index.d.ts",
|
|
19
|
+
"import": "./dist/src/dsh/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./dsh/engine": {
|
|
22
|
+
"types": "./dist/src/dsh/engine.d.ts",
|
|
23
|
+
"import": "./dist/src/dsh/engine.js"
|
|
24
|
+
}
|
|
17
25
|
},
|
|
18
26
|
"description": "Codex-style context windows for Pi: durable reset windows, session history tools, and persistent notes.",
|
|
19
27
|
"license": "MIT",
|
|
@@ -45,7 +53,8 @@
|
|
|
45
53
|
"skills",
|
|
46
54
|
"mods",
|
|
47
55
|
"!mods/notesoup/types",
|
|
48
|
-
"!mods/notesoup/tsconfig.json"
|
|
56
|
+
"!mods/notesoup/tsconfig.json",
|
|
57
|
+
"cordis.patch.yml"
|
|
49
58
|
],
|
|
50
59
|
"bin": {
|
|
51
60
|
"dream": "dist/src/pi/dream/cli.js"
|
|
@@ -61,7 +70,18 @@
|
|
|
61
70
|
"@earendil-works/pi-agent-core": "*",
|
|
62
71
|
"@earendil-works/pi-ai": "*",
|
|
63
72
|
"@earendil-works/pi-coding-agent": "*",
|
|
64
|
-
"typebox": "*"
|
|
73
|
+
"typebox": "*",
|
|
74
|
+
"@deepseek-ai/cordis": "*",
|
|
75
|
+
"@deepseek-ai/cordis-plugin-loader": "*",
|
|
76
|
+
"@deepseek-ai/dsh-agent": "*",
|
|
77
|
+
"@deepseek-ai/dsh-compaction": "*",
|
|
78
|
+
"@deepseek-ai/dsh-commands": "*",
|
|
79
|
+
"@deepseek-ai/dsh-llm": "*",
|
|
80
|
+
"@deepseek-ai/dsh-session": "*",
|
|
81
|
+
"@deepseek-ai/dsh-session-query": "*",
|
|
82
|
+
"@deepseek-ai/dsh-system-prompt": "*",
|
|
83
|
+
"@deepseek-ai/dsh-token-meter": "*",
|
|
84
|
+
"@deepseek-ai/dsh-tools": "*"
|
|
65
85
|
},
|
|
66
86
|
"peerDependenciesMeta": {
|
|
67
87
|
"@earendil-works/pi-agent-core": {
|
|
@@ -75,9 +95,43 @@
|
|
|
75
95
|
},
|
|
76
96
|
"typebox": {
|
|
77
97
|
"optional": true
|
|
98
|
+
},
|
|
99
|
+
"@deepseek-ai/cordis": {
|
|
100
|
+
"optional": true
|
|
101
|
+
},
|
|
102
|
+
"@deepseek-ai/cordis-plugin-loader": {
|
|
103
|
+
"optional": true
|
|
104
|
+
},
|
|
105
|
+
"@deepseek-ai/dsh-agent": {
|
|
106
|
+
"optional": true
|
|
107
|
+
},
|
|
108
|
+
"@deepseek-ai/dsh-compaction": {
|
|
109
|
+
"optional": true
|
|
110
|
+
},
|
|
111
|
+
"@deepseek-ai/dsh-commands": {
|
|
112
|
+
"optional": true
|
|
113
|
+
},
|
|
114
|
+
"@deepseek-ai/dsh-llm": {
|
|
115
|
+
"optional": true
|
|
116
|
+
},
|
|
117
|
+
"@deepseek-ai/dsh-session": {
|
|
118
|
+
"optional": true
|
|
119
|
+
},
|
|
120
|
+
"@deepseek-ai/dsh-session-query": {
|
|
121
|
+
"optional": true
|
|
122
|
+
},
|
|
123
|
+
"@deepseek-ai/dsh-system-prompt": {
|
|
124
|
+
"optional": true
|
|
125
|
+
},
|
|
126
|
+
"@deepseek-ai/dsh-token-meter": {
|
|
127
|
+
"optional": true
|
|
128
|
+
},
|
|
129
|
+
"@deepseek-ai/dsh-tools": {
|
|
130
|
+
"optional": true
|
|
78
131
|
}
|
|
79
132
|
},
|
|
80
133
|
"devDependencies": {
|
|
134
|
+
"@deepseek-ai/dsh": "0.2.1-alpha.2",
|
|
81
135
|
"@earendil-works/pi-agent-core": "^1.0.0",
|
|
82
136
|
"@earendil-works/pi-ai": "^1.0.0",
|
|
83
137
|
"@earendil-works/pi-coding-agent": "^1.0.0",
|
|
@@ -88,5 +142,10 @@
|
|
|
88
142
|
},
|
|
89
143
|
"publishConfig": {
|
|
90
144
|
"access": "public"
|
|
145
|
+
},
|
|
146
|
+
"dsh": {
|
|
147
|
+
"bundle": {
|
|
148
|
+
"patch": "./cordis.patch.yml"
|
|
149
|
+
}
|
|
91
150
|
}
|
|
92
151
|
}
|
|
@@ -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
|
+
}
|
package/src/dsh/index.ts
ADDED
|
@@ -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
|
+
}
|
package/src/dsh/tools.ts
ADDED
|
@@ -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
|
+
}
|