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/README.md
CHANGED
|
@@ -76,6 +76,7 @@ The dreamer model is configured under the same key; `--dreamer <model pattern>`
|
|
|
76
76
|
- [Tool results](docs/tool-results.md) — receipts, paging, and error shapes
|
|
77
77
|
- [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
|
|
78
78
|
- [SDK integration](docs/sdk-integration.md) — binding notesoup to a host-built session
|
|
79
|
+
- [DeepSeek Harness](docs/dsh.md) — adapter and profile patch for dsh 0.2.1-alpha.2
|
|
79
80
|
- [Claude Code Mod](docs/claude-code-mod.md) — early-access notes tools for Claude Code
|
|
80
81
|
- [Skills, dream, and the notes doctor](docs/skills.md) — `/skill:memory`, `/skill:dream`, `dream doctor`, the dream lock
|
|
81
82
|
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Package bundle patch. Explicit llm-deepseek model declarations are also
|
|
2
|
+
# required: copy the example in docs/dsh.profile.patch.yml into your profile.
|
|
3
|
+
- id: compaction-basic
|
|
4
|
+
disabled: true
|
|
5
|
+
|
|
6
|
+
- insert:
|
|
7
|
+
- id: notesoup-engine
|
|
8
|
+
name: 'notesoup/dsh/engine'
|
|
9
|
+
config:
|
|
10
|
+
auto: true
|
|
11
|
+
thresholdRatio: 0.8
|
|
12
|
+
headroomTokens: 65536
|
|
13
|
+
- id: notesoup
|
|
14
|
+
name: 'notesoup/dsh'
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
import type { CompactionAgentContext } from "@deepseek-ai/dsh-compaction";
|
|
3
|
+
export type BudgetConfig = {
|
|
4
|
+
auto: boolean;
|
|
5
|
+
thresholdRatio: number;
|
|
6
|
+
headroomTokens: number;
|
|
7
|
+
reminderMarginTokens?: number;
|
|
8
|
+
};
|
|
9
|
+
export type Budget = {
|
|
10
|
+
used: number;
|
|
11
|
+
contextWindow: number;
|
|
12
|
+
reserve: number;
|
|
13
|
+
resetAt: number;
|
|
14
|
+
remaining: number;
|
|
15
|
+
countdown: number;
|
|
16
|
+
warning: number;
|
|
17
|
+
reminder: number;
|
|
18
|
+
};
|
|
19
|
+
/** The host's ratio and output/headroom reserves are one reset line, not competing policies. */
|
|
20
|
+
export declare function measureBudget(ctx: Context, agent: CompactionAgentContext, config: BudgetConfig, signal?: AbortSignal): Promise<Budget | null>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { estimateToolsTokens } from "@deepseek-ai/dsh-token-meter/estimate";
|
|
2
|
+
import { deriveThresholds, remainingBudget } from "../budget/policy.js";
|
|
3
|
+
/** The host's ratio and output/headroom reserves are one reset line, not competing policies. */
|
|
4
|
+
export async function measureBudget(ctx, agent, config, signal) {
|
|
5
|
+
const route = agent.session.requestHeader()?.config ?? agent.options;
|
|
6
|
+
if (!route.provider || !route.model)
|
|
7
|
+
return null;
|
|
8
|
+
const info = await ctx.llm.resolveModelInfo(route.provider, route.model, signal);
|
|
9
|
+
const contextWindow = info.context?.contextWindow;
|
|
10
|
+
if (!contextWindow)
|
|
11
|
+
return null;
|
|
12
|
+
const output = agent.session.requestHeader()?.config.maxTokens ?? agent.options.maxTokens ?? info.defaultMaxTokens ?? 0;
|
|
13
|
+
const resetAt = Math.floor(Math.min(contextWindow * config.thresholdRatio, contextWindow - output - config.headroomTokens));
|
|
14
|
+
if (resetAt <= 0)
|
|
15
|
+
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" });
|
|
16
|
+
const reserve = contextWindow - resetAt;
|
|
17
|
+
const { thresholds } = deriveThresholds(reserve, { reminderMarginTokens: config.reminderMarginTokens });
|
|
18
|
+
const measured = ctx.tokenMeter.measure(agent.session);
|
|
19
|
+
// alpha.2 carries a provider-usage anchor across a surface replacement. Until
|
|
20
|
+
// this window receives its own response, use the meter's current surface price.
|
|
21
|
+
const events = agent.session.snapshotEvents();
|
|
22
|
+
let used = measured.totalTokens;
|
|
23
|
+
for (let index = events.length - 1; index >= 0; index--) {
|
|
24
|
+
const event = events[index];
|
|
25
|
+
if (event.type === "assistant/message")
|
|
26
|
+
break;
|
|
27
|
+
if (event.type === "user/message" && event.data.source.kind === "compact-checkpoint") {
|
|
28
|
+
used = measured.surfaceTokens + estimateToolsTokens(agent.session.requestHeader());
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const remaining = Math.max(0, contextWindow - used);
|
|
33
|
+
return { used, contextWindow, reserve, resetAt, remaining, countdown: remainingBudget(remaining, thresholds.warning), warning: thresholds.warning, reminder: thresholds.reminder };
|
|
34
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
import type { CommandId } from "@deepseek-ai/dsh-commands/brand";
|
|
3
|
+
import { CompactionEngine, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from "@deepseek-ai/dsh-compaction";
|
|
4
|
+
import { type SessionSeq } from "@deepseek-ai/dsh-session";
|
|
5
|
+
import { type BudgetConfig } from "./budget.js";
|
|
6
|
+
import { Windows, type NotesConfig } from "./window.js";
|
|
7
|
+
export type EngineConfig = NotesConfig & Partial<BudgetConfig>;
|
|
8
|
+
export type ResolvedConfig = NotesConfig & BudgetConfig;
|
|
9
|
+
export declare class NotesoupCompactionEngine extends CompactionEngine {
|
|
10
|
+
static inject: string[];
|
|
11
|
+
readonly config: ResolvedConfig;
|
|
12
|
+
readonly windows: Windows;
|
|
13
|
+
private readonly lifecycle;
|
|
14
|
+
constructor(ctx: Context, config?: EngineConfig);
|
|
15
|
+
get automaticListenerPresent(): boolean;
|
|
16
|
+
compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null>;
|
|
17
|
+
compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal): Promise<CompactionResult>;
|
|
18
|
+
compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null>;
|
|
19
|
+
/** No model call, no shrink requirement: even a one-message window can be cleared. */
|
|
20
|
+
private transaction;
|
|
21
|
+
}
|
|
22
|
+
export default NotesoupCompactionEngine;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { CompactionEngine, CompactionId, ManualCompactionError, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore } from "@deepseek-ai/dsh-compaction";
|
|
3
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
4
|
+
import { appendPluginRecord } from "@deepseek-ai/dsh-session";
|
|
5
|
+
import { measureBudget } from "./budget.js";
|
|
6
|
+
import { checkpointText, Windows, WINDOW_RECORD } from "./window.js";
|
|
7
|
+
import { preflight } from "./preflight.js";
|
|
8
|
+
function resolveConfig(config) {
|
|
9
|
+
const resolved = { ...config, auto: config.auto ?? true, thresholdRatio: config.thresholdRatio ?? 0.8, headroomTokens: config.headroomTokens ?? 65536 };
|
|
10
|
+
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)))
|
|
11
|
+
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" });
|
|
12
|
+
const known = new Set(["auto", "thresholdRatio", "headroomTokens", "reminderMarginTokens", "notesHome", "agentName"]);
|
|
13
|
+
for (const key of Object.keys(config))
|
|
14
|
+
if (!known.has(key))
|
|
15
|
+
throw Object.assign(new Error(`notesoup: unknown engine parameter ${key}; remove it from the notesoup-engine profile row.`), { code: "CONFIG" });
|
|
16
|
+
return Object.freeze(resolved);
|
|
17
|
+
}
|
|
18
|
+
/** Durable lock and open-turn owner are separate facts, including after process reload. */
|
|
19
|
+
function entryState(session) {
|
|
20
|
+
let turn = null;
|
|
21
|
+
let start;
|
|
22
|
+
let seed = -1;
|
|
23
|
+
for (const event of session.snapshotEvents()) {
|
|
24
|
+
if (event.type === "turn/start")
|
|
25
|
+
turn = event.data.turn;
|
|
26
|
+
if (event.type === "turn/end")
|
|
27
|
+
turn = null;
|
|
28
|
+
if (event.type === "session/end-seed")
|
|
29
|
+
seed = event.seq;
|
|
30
|
+
if (event.type === "compaction/start")
|
|
31
|
+
start = event.seq;
|
|
32
|
+
if (event.type === "compaction/end")
|
|
33
|
+
start = undefined;
|
|
34
|
+
}
|
|
35
|
+
return { turn, busy: start !== undefined && start > seed };
|
|
36
|
+
}
|
|
37
|
+
function range(session) {
|
|
38
|
+
const nodes = session.surface.nodes;
|
|
39
|
+
// Node zero is host-owned even when no system head is present yet.
|
|
40
|
+
if (nodes.length <= 1)
|
|
41
|
+
return null;
|
|
42
|
+
const start = nodes[1];
|
|
43
|
+
const end = nodes.at(-1);
|
|
44
|
+
if (!toolPairingBalancedBefore(session, start) || !toolPairingBalancedAfter(session, end))
|
|
45
|
+
return null;
|
|
46
|
+
return { start, end };
|
|
47
|
+
}
|
|
48
|
+
export class NotesoupCompactionEngine extends CompactionEngine {
|
|
49
|
+
static inject = ["llm", "tokenMeter", "sessions"];
|
|
50
|
+
config;
|
|
51
|
+
windows;
|
|
52
|
+
lifecycle;
|
|
53
|
+
constructor(ctx, config = {}) {
|
|
54
|
+
super(ctx);
|
|
55
|
+
this.config = resolveConfig(config);
|
|
56
|
+
this.lifecycle = { fiber: ctx.fiber };
|
|
57
|
+
this.windows = new Windows(this.config);
|
|
58
|
+
// Assembly precedes pre-step. Reset here and refresh only our section in index.ts.
|
|
59
|
+
ctx.on("system-prompt/assemble", async (_assembly, input, next) => {
|
|
60
|
+
if (input.agent && input.signal && !input.signal.aborted) {
|
|
61
|
+
preflight(ctx);
|
|
62
|
+
await this.compactIfNeeded(input.agent, "pressure", input.signal);
|
|
63
|
+
}
|
|
64
|
+
return next();
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
get automaticListenerPresent() {
|
|
68
|
+
// Effect diagnostics are a public capability; no Cordis hook-table inspection.
|
|
69
|
+
return this.lifecycle.fiber.getEffects().some((effect) => effect.label === 'ctx.on("system-prompt/assemble")');
|
|
70
|
+
}
|
|
71
|
+
async compactIfNeeded(agent, trigger, signal) {
|
|
72
|
+
signal.throwIfAborted();
|
|
73
|
+
const state = this.windows.get(agent.session);
|
|
74
|
+
const forced = state.pendingReset;
|
|
75
|
+
if (!forced) {
|
|
76
|
+
if (!this.config.auto)
|
|
77
|
+
return null;
|
|
78
|
+
// Context overflow is deliberately left to the host. This adapter owns reserve resets.
|
|
79
|
+
if (trigger === "context-overflow")
|
|
80
|
+
return null;
|
|
81
|
+
const budget = await measureBudget(this.ctx, agent, this.config, signal);
|
|
82
|
+
if (!budget || budget.remaining > budget.reserve)
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const selected = range(agent.session);
|
|
86
|
+
if (!selected)
|
|
87
|
+
return null;
|
|
88
|
+
return this.compactRegion(selected.start, selected.end, agent, signal);
|
|
89
|
+
}
|
|
90
|
+
async compactRegion(start, end, agent, signal) {
|
|
91
|
+
if (entryState(agent.session).turn === null)
|
|
92
|
+
throw new ManualCompactionError("busy", "notesoup: compactRegion needs an open turn; use compactNow while idle.");
|
|
93
|
+
return this.transaction(start, end, agent, signal);
|
|
94
|
+
}
|
|
95
|
+
compactNow(agent, signal, sourceCommandId) {
|
|
96
|
+
signal.throwIfAborted();
|
|
97
|
+
try {
|
|
98
|
+
return agent.runMaintenance(async (ownerSignal) => {
|
|
99
|
+
const combined = AbortSignal.any([signal, ownerSignal]);
|
|
100
|
+
combined.throwIfAborted();
|
|
101
|
+
if (entryState(agent.session).turn !== null)
|
|
102
|
+
throw new ManualCompactionError("busy", "notesoup: an open turn remains; wait for the agent to stop, then retry.");
|
|
103
|
+
const selected = range(agent.session);
|
|
104
|
+
if (!selected)
|
|
105
|
+
return null;
|
|
106
|
+
return this.transaction(selected.start, selected.end, agent, combined, sourceCommandId, true);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
throw new ManualCompactionError("busy", "notesoup: wait for the agent to become idle, then retry compactNow.", { cause: error });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** No model call, no shrink requirement: even a one-message window can be cleared. */
|
|
114
|
+
async transaction(start, end, agent, signal, sourceCommandId, flush = false) {
|
|
115
|
+
const session = agent.session;
|
|
116
|
+
signal?.throwIfAborted();
|
|
117
|
+
const selected = range(session);
|
|
118
|
+
if (!selected || selected.start !== start || selected.end !== end)
|
|
119
|
+
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.`);
|
|
120
|
+
const entry = entryState(session);
|
|
121
|
+
if (entry.busy)
|
|
122
|
+
throw new ManualCompactionError("busy", "notesoup: a compaction/start has no matching end; reload this session before retrying.");
|
|
123
|
+
const state = this.windows.get(session);
|
|
124
|
+
const previous = state.snapshot;
|
|
125
|
+
const shadowedSeqs = [...session.surface.nodes.slice(1)];
|
|
126
|
+
const generation = session.surface.contentGeneration;
|
|
127
|
+
const measured = this.ctx.tokenMeter.measure(session);
|
|
128
|
+
const shadowedTokenCount = measured.nodes.slice(1).reduce((sum, node) => sum + node.heuristicTokens, 0);
|
|
129
|
+
const compactionId = CompactionId(randomUUID());
|
|
130
|
+
const lifecycle = { compactionId, turn: entry.turn, ...(sourceCommandId === undefined ? {} : { sourceCommandId }) };
|
|
131
|
+
// Synchronous lock acquisition precedes the snapshot's first await.
|
|
132
|
+
const opened = session.append("compaction/start", lifecycle);
|
|
133
|
+
let landed = false;
|
|
134
|
+
let closing = false;
|
|
135
|
+
let closed = false;
|
|
136
|
+
let result;
|
|
137
|
+
let failure;
|
|
138
|
+
try {
|
|
139
|
+
const next = await this.windows.mint(agent, previous.window + 1, opened.time);
|
|
140
|
+
signal?.throwIfAborted();
|
|
141
|
+
if (session.surface.contentGeneration !== generation || session.surface.nodes.length !== shadowedSeqs.length + 1)
|
|
142
|
+
throw new ManualCompactionError("changed", "notesoup: the surface changed while opening the next notebook; retry after current work finishes.");
|
|
143
|
+
// Mint BEFORE writing the checkpoint. A rejected append restores the previous notebook.
|
|
144
|
+
state.snapshot = next;
|
|
145
|
+
const summary = [{ type: "text", text: checkpointText(next) }];
|
|
146
|
+
const summarized = session.append("compaction/summary", { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount, provider: "notesoup", model: "notes" });
|
|
147
|
+
session.append("user/message", createUserMessage({ content: summary, source: compactCheckpointSource(compactionId, sourceCommandId) }), { surfaceOp: { op: "replace", startSeq: start, endSeq: end }, sourceEventSeqs: [opened.seq, summarized.seq, ...shadowedSeqs] });
|
|
148
|
+
landed = true;
|
|
149
|
+
state.pendingReset = false;
|
|
150
|
+
state.warned = false;
|
|
151
|
+
state.reminded = false;
|
|
152
|
+
closing = true;
|
|
153
|
+
const ended = session.append("compaction/end", lifecycle);
|
|
154
|
+
closed = true;
|
|
155
|
+
result = { compactionId, ...(sourceCommandId === undefined ? {} : { sourceCommandId }), startSeq: opened.seq, summarySeq: summarized.seq, endSeq: ended.seq, summary, shadowedRange: { start, end }, shadowedSeqs, shadowedTokenCount };
|
|
156
|
+
try {
|
|
157
|
+
appendPluginRecord(session, WINDOW_RECORD, next);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
this.ctx.logger.warn(`notesoup: window record could not be written; the checkpoint holds ${next.windowId}. ${String(error)}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (!landed)
|
|
165
|
+
state.snapshot = previous;
|
|
166
|
+
failure = error;
|
|
167
|
+
if (!closing) {
|
|
168
|
+
try {
|
|
169
|
+
session.append("compaction/end", { ...lifecycle, error: String(error) });
|
|
170
|
+
closed = true;
|
|
171
|
+
}
|
|
172
|
+
catch (closeError) {
|
|
173
|
+
failure = new ManualCompactionError("commit", "notesoup: compaction/end failed; reload the session before another reset.", { cause: closeError });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
else
|
|
177
|
+
failure = new ManualCompactionError("commit", "notesoup: checkpoint landed but compaction/end failed; reload before another reset.", { cause: error });
|
|
178
|
+
}
|
|
179
|
+
if (flush && closed) {
|
|
180
|
+
try {
|
|
181
|
+
await this.ctx.sessions.flush(session);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (!failure)
|
|
185
|
+
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 });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (failure)
|
|
189
|
+
throw failure;
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
export default NotesoupCompactionEngine;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
import type { SessionId, SessionEvent } from "@deepseek-ai/dsh-session";
|
|
3
|
+
import { type HistoryProjection } from "../history/history.js";
|
|
4
|
+
/** Native seq zero becomes public seq one. Forks contain only their selected seed prefix. */
|
|
5
|
+
export declare function decodeHistory(sessionId: string, events: readonly SessionEvent[]): HistoryProjection;
|
|
6
|
+
export declare function historyProjection(ctx: Context, sessionId: SessionId): Promise<HistoryProjection>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { projectHistory } from "../history/history.js";
|
|
2
|
+
import { checkpointSnapshot, recordSnapshot, windowId } from "./window.js";
|
|
3
|
+
/** Preserve every recorded block; attachments/reasoning have JSON evidence rather than invented text. */
|
|
4
|
+
function blockText(content, omitCalls = false) {
|
|
5
|
+
if (!Array.isArray(content))
|
|
6
|
+
return typeof content === "string" ? content : JSON.stringify(content) ?? "";
|
|
7
|
+
return content.filter((block) => !omitCalls || block.type !== "tool-call").map((block) => block.type === "text" ? block.text : JSON.stringify(block)).join("\n");
|
|
8
|
+
}
|
|
9
|
+
function argumentsOf(text) {
|
|
10
|
+
try {
|
|
11
|
+
const value = JSON.parse(text);
|
|
12
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** Native seq zero becomes public seq one. Forks contain only their selected seed prefix. */
|
|
19
|
+
export function decodeHistory(sessionId, events) {
|
|
20
|
+
let current = { windowId: windowId(sessionId, 0), items: [] };
|
|
21
|
+
const windows = [current];
|
|
22
|
+
const branchSeqs = new Set();
|
|
23
|
+
for (const event of events) {
|
|
24
|
+
const seq = event.seq + 1;
|
|
25
|
+
branchSeqs.add(seq);
|
|
26
|
+
const checkpoint = checkpointSnapshot(event);
|
|
27
|
+
const snapshot = checkpoint ?? recordSnapshot(event);
|
|
28
|
+
if (snapshot && current.windowId !== snapshot.windowId) {
|
|
29
|
+
// A root snapshot identifies the initial window; it does not create an empty extra window.
|
|
30
|
+
if (snapshot.window === 0 && windows.length === 1 && current.items.length === 0)
|
|
31
|
+
current.windowId = snapshot.windowId;
|
|
32
|
+
else {
|
|
33
|
+
current = { windowId: snapshot.windowId, createdAt: new Date(event.time).toISOString(), items: [] };
|
|
34
|
+
windows.push(current);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const base = { seq, windowId: current.windowId, createdAt: new Date(event.time).toISOString() };
|
|
38
|
+
let item;
|
|
39
|
+
switch (event.type) {
|
|
40
|
+
case "user/message":
|
|
41
|
+
item = { ...base, role: checkpoint ? "system" : "user", text: blockText(event.data.content) };
|
|
42
|
+
break;
|
|
43
|
+
case "system/message":
|
|
44
|
+
item = { ...base, role: "system", text: blockText(event.data.message.content) };
|
|
45
|
+
break;
|
|
46
|
+
case "developer/message":
|
|
47
|
+
item = { ...base, role: "developer", text: blockText(event.data.message.content) };
|
|
48
|
+
break;
|
|
49
|
+
case "assistant/message": {
|
|
50
|
+
const text = blockText(event.data.message.content, true);
|
|
51
|
+
if (text)
|
|
52
|
+
item = { ...base, role: "assistant", text };
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
case "assistant/attempt":
|
|
56
|
+
item = { ...base, role: "assistant", text: JSON.stringify(event.data.stream) };
|
|
57
|
+
break;
|
|
58
|
+
case "tool/call":
|
|
59
|
+
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) } : {}) };
|
|
60
|
+
break;
|
|
61
|
+
case "tool/result":
|
|
62
|
+
item = { ...base, role: "tool", text: blockText(event.data.message.content), toolCallId: event.data.message.source.callId, toolError: event.data.message.isError };
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
if (item)
|
|
66
|
+
current.items.push(item);
|
|
67
|
+
}
|
|
68
|
+
return projectHistory(windows, events.at(-1) === undefined ? 0 : events.at(-1).seq + 1, branchSeqs);
|
|
69
|
+
}
|
|
70
|
+
export async function historyProjection(ctx, sessionId) {
|
|
71
|
+
const log = await ctx.sessionQuery.readSession(sessionId);
|
|
72
|
+
return decodeHistory(sessionId, log.events);
|
|
73
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
export declare const name = "notesoup-dsh";
|
|
3
|
+
export declare const inject: string[];
|
|
4
|
+
declare module "@deepseek-ai/dsh-llm" {
|
|
5
|
+
interface MessageSourceMap {
|
|
6
|
+
"notesoup-budget": {
|
|
7
|
+
kind: "notesoup-budget";
|
|
8
|
+
windowId: string;
|
|
9
|
+
phase: "reminder" | "warning";
|
|
10
|
+
};
|
|
11
|
+
"notesoup-continuation": {
|
|
12
|
+
kind: "notesoup-continuation";
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export declare function apply(ctx: Context): void;
|
|
17
|
+
declare const _default: {
|
|
18
|
+
name: string;
|
|
19
|
+
inject: string[];
|
|
20
|
+
apply: typeof apply;
|
|
21
|
+
};
|
|
22
|
+
export default _default;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
2
|
+
import { CONTINUATION, WARNING_PROMPT, tokenBudgetGuidance } from "../budget/text.js";
|
|
3
|
+
import { measureBudget } from "./budget.js";
|
|
4
|
+
import { BOOT_SECTION, restoreWarnings } from "./window.js";
|
|
5
|
+
import { preflight } from "./preflight.js";
|
|
6
|
+
import { registerTools } from "./tools.js";
|
|
7
|
+
export const name = "notesoup-dsh";
|
|
8
|
+
export const inject = ["tools", "sessions", "systemPrompt", "llm", "tokenMeter", "sessionQuery", "compaction"];
|
|
9
|
+
export function apply(ctx) {
|
|
10
|
+
const engine = preflight(ctx);
|
|
11
|
+
ctx.on("agent/created", async ({ agent, signal }) => {
|
|
12
|
+
preflight(ctx);
|
|
13
|
+
await engine.windows.adopt(agent, signal);
|
|
14
|
+
});
|
|
15
|
+
ctx.systemPrompt.section({ name: BOOT_SECTION, order: 2450, interpolate: false, text: ({ agent }) => agent ? engine.windows.get(agent.session).snapshot.boot : "" });
|
|
16
|
+
// Section providers run before the engine's awaited reset. Refresh the accepted section
|
|
17
|
+
// after the entire assembly waterfall so the same request uses the newly minted boot.
|
|
18
|
+
ctx.on("system-prompt/assemble", async (_assembly, input, next) => {
|
|
19
|
+
const assembly = await next();
|
|
20
|
+
if (input.agent) {
|
|
21
|
+
const boot = assembly.sections.find((section) => section.name === BOOT_SECTION);
|
|
22
|
+
if (!boot)
|
|
23
|
+
throw Object.assign(new Error("notesoup: boot section was removed; restore notesoup:boot before running this agent."), { code: "BOOT_SECTION" });
|
|
24
|
+
boot.text = engine.windows.get(input.agent.session).snapshot.boot;
|
|
25
|
+
}
|
|
26
|
+
return assembly;
|
|
27
|
+
}, { prepend: true });
|
|
28
|
+
ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
|
|
29
|
+
preflight(ctx);
|
|
30
|
+
if (!signal.aborted && engine.config.auto) {
|
|
31
|
+
const budget = await measureBudget(ctx, agent, engine.config, signal);
|
|
32
|
+
if (budget) {
|
|
33
|
+
const state = engine.windows.get(agent.session);
|
|
34
|
+
const phase = budget.remaining <= budget.warning ? "warning" : budget.remaining <= budget.reminder ? "reminder" : undefined;
|
|
35
|
+
if (phase && !(phase === "warning" ? state.warned : state.reminded || state.warned)) {
|
|
36
|
+
const text = phase === "warning" ? WARNING_PROMPT : tokenBudgetGuidance(budget.countdown, "clear_memory");
|
|
37
|
+
agent.steer(createUserMessage({ content: [{ type: "text", text }], source: { kind: "notesoup-budget", windowId: state.snapshot.windowId, phase } }));
|
|
38
|
+
if (phase === "warning")
|
|
39
|
+
state.warned = true;
|
|
40
|
+
else
|
|
41
|
+
state.reminded = true;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return next();
|
|
46
|
+
});
|
|
47
|
+
ctx.on("agent/turn-stopping", async ({ agent, signal }) => {
|
|
48
|
+
if (signal.aborted)
|
|
49
|
+
return;
|
|
50
|
+
const result = await engine.compactIfNeeded(agent, "pressure", signal);
|
|
51
|
+
if (result)
|
|
52
|
+
agent.steer(createUserMessage({ content: [{ type: "text", text: CONTINUATION }], source: { kind: "notesoup-continuation" } }));
|
|
53
|
+
});
|
|
54
|
+
ctx.on("session/event", (session, event) => {
|
|
55
|
+
if (event.type === "turn/end" && event.data.reason.kind !== "completed") {
|
|
56
|
+
const state = engine.windows.get(session);
|
|
57
|
+
state.pendingReset = false;
|
|
58
|
+
restoreWarnings(state, session.snapshotEvents());
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
registerTools(ctx, engine);
|
|
62
|
+
}
|
|
63
|
+
export default { name, inject, apply };
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
2
|
+
import { NotesoupCompactionEngine } from "./engine.js";
|
|
3
|
+
export declare class PreflightError extends Error {
|
|
4
|
+
readonly code: string;
|
|
5
|
+
constructor(code: string, message: string);
|
|
6
|
+
}
|
|
7
|
+
/** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
|
|
8
|
+
export declare function preflight(ctx: Context): NotesoupCompactionEngine;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { NotesoupCompactionEngine } from "./engine.js";
|
|
2
|
+
export class PreflightError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code, message) {
|
|
5
|
+
super(`notesoup: ${message}`);
|
|
6
|
+
this.code = code;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Probe capabilities and the public loader/registry, not preview-version strings or private hooks. */
|
|
10
|
+
export function preflight(ctx) {
|
|
11
|
+
for (const [service, method] of [["systemPrompt", "section"], ["tools", "register"], ["sessionQuery", "readSession"], ["tokenMeter", "measure"], ["llm", "resolveModelInfo"]]) {
|
|
12
|
+
const mounted = ctx.get(service);
|
|
13
|
+
if (typeof mounted?.[method] !== "function")
|
|
14
|
+
throw new PreflightError("CAPABILITY", `${service}.${method} is unavailable; enable that service in the profile before using notesoup.`);
|
|
15
|
+
}
|
|
16
|
+
const engine = ctx.get("compaction");
|
|
17
|
+
if (!(engine instanceof NotesoupCompactionEngine))
|
|
18
|
+
throw new PreflightError("ENGINE", "ctx.compaction must be NotesoupCompactionEngine; disable compaction-basic and enable the notesoup-engine row, then restart dsh.");
|
|
19
|
+
const loader = ctx.get("loader");
|
|
20
|
+
if (loader) {
|
|
21
|
+
if (typeof loader.entries !== "function")
|
|
22
|
+
throw new PreflightError("CAPABILITY", "loader.entries is unavailable; this profile cannot be checked for two engines.");
|
|
23
|
+
for (const entry of loader.entries()) {
|
|
24
|
+
if ((entry.options.id === "compaction-basic" || /(?:^|\/)dsh-compaction-basic$/.test(entry.options.name)) && !entry.disabled)
|
|
25
|
+
throw new PreflightError("DOUBLE_ENGINE", "compaction-basic is enabled; set disabled: true on that profile row and restart dsh.");
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const [callback, runtime] of ctx.registry.entries()) {
|
|
29
|
+
if (callback.name === "BasicCompactionEngine" && runtime.fibers.length > 0)
|
|
30
|
+
throw new PreflightError("DOUBLE_ENGINE", "a BasicCompactionEngine fiber is mounted; remove it before starting notesoup.");
|
|
31
|
+
}
|
|
32
|
+
if (!engine.automaticListenerPresent)
|
|
33
|
+
throw new PreflightError("AUTO_LISTENER", "the automatic reset listener is missing; reload notesoup-engine before sending another request.");
|
|
34
|
+
return engine;
|
|
35
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { HarnessError } from "@deepseek-ai/dsh-llm";
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
3
|
+
import { Check, Errors } from "typebox/value";
|
|
4
|
+
import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
|
|
5
|
+
import { historyList, historyRead, historyWindows } from "../tools/history.js";
|
|
6
|
+
import { success } from "../tools/result.js";
|
|
7
|
+
import { historyProjection } from "./history.js";
|
|
8
|
+
import { notesIdentity } from "./window.js";
|
|
9
|
+
import { measureBudget } from "./budget.js";
|
|
10
|
+
import { preflight } from "./preflight.js";
|
|
11
|
+
/** dsh enforces a small schema subset; TypeBox remains the full validator at execution. */
|
|
12
|
+
function hostSchema(schema) {
|
|
13
|
+
const value = JSON.parse(JSON.stringify(schema));
|
|
14
|
+
const result = {};
|
|
15
|
+
for (const key of ["type", "required", "additionalProperties", "enum", "const", "description", "title", "default", "examples"])
|
|
16
|
+
if (value[key] !== undefined)
|
|
17
|
+
result[key] = value[key];
|
|
18
|
+
const bounds = ["minimum", "maximum", "minLength", "maxLength", "minItems", "maxItems"].filter((key) => value[key] !== undefined).map((key) => `${key}=${value[key]}`);
|
|
19
|
+
if (bounds.length)
|
|
20
|
+
result.description = [value.description, bounds.join(", ")].filter(Boolean).join("; ");
|
|
21
|
+
if (Array.isArray(value.anyOf))
|
|
22
|
+
result.oneOf = value.anyOf.map((branch) => hostSchema(branch));
|
|
23
|
+
if (value.properties)
|
|
24
|
+
result.properties = Object.fromEntries(Object.entries(value.properties).map(([key, child]) => [key, hostSchema(child)]));
|
|
25
|
+
if (value.items)
|
|
26
|
+
result.items = hostSchema(value.items);
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
function requireAgent(exec) {
|
|
30
|
+
if (!exec.agent)
|
|
31
|
+
throw new HarnessError("notesoup: this tool needs an agent session; call it from a dsh agent.", "AGENT_REQUIRED");
|
|
32
|
+
exec.signal.throwIfAborted();
|
|
33
|
+
return exec.agent;
|
|
34
|
+
}
|
|
35
|
+
function register(ctx, operation, inputs) {
|
|
36
|
+
ctx.tools.register({
|
|
37
|
+
name: operation.name,
|
|
38
|
+
description: operation.description,
|
|
39
|
+
parameters: hostSchema(operation.parameters),
|
|
40
|
+
output: {
|
|
41
|
+
schema: hostSchema(operation.outputSchema),
|
|
42
|
+
render: (_args, value) => [{ type: "text", text: operation.render(success(value)) }],
|
|
43
|
+
},
|
|
44
|
+
async execute(args, exec) {
|
|
45
|
+
const agent = requireAgent(exec);
|
|
46
|
+
preflight(ctx);
|
|
47
|
+
if (!Check(operation.parameters, args)) {
|
|
48
|
+
const error = Errors(operation.parameters, args).find((problem) => problem.keyword !== "boolean");
|
|
49
|
+
throw new HarnessError(`notesoup: invalid ${operation.name} parameter ${error?.instancePath || "/"}: ${error?.message ?? "invalid value"}; use the tool schema's bounds.`, "INVALID_PARAMS");
|
|
50
|
+
}
|
|
51
|
+
const rest = await inputs(agent);
|
|
52
|
+
exec.signal.throwIfAborted();
|
|
53
|
+
const result = await operation.execute(args, ...rest);
|
|
54
|
+
if (!result.ok)
|
|
55
|
+
throw new HarnessError(operation.render(result), result.error.code);
|
|
56
|
+
return result.data;
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
export function registerTools(ctx, engine) {
|
|
61
|
+
const nestedResets = new WeakMap();
|
|
62
|
+
ctx.on("tools/result", (exec, result) => {
|
|
63
|
+
if (!exec.agent)
|
|
64
|
+
return;
|
|
65
|
+
const state = engine.windows.get(exec.agent.session);
|
|
66
|
+
if (exec.name === "clear_memory" && !result.isError && result.value.window_id === state.snapshot.windowId) {
|
|
67
|
+
if (!exec.parent)
|
|
68
|
+
state.pendingReset = true;
|
|
69
|
+
else {
|
|
70
|
+
const roots = nestedResets.get(exec.agent) ?? new Set();
|
|
71
|
+
roots.add(exec.rootCallId);
|
|
72
|
+
nestedResets.set(exec.agent, roots);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (!exec.parent && nestedResets.get(exec.agent)?.delete(exec.rootCallId) && !result.isError)
|
|
76
|
+
state.pendingReset = true;
|
|
77
|
+
});
|
|
78
|
+
const identity = (agent) => notesIdentity(agent, engine.config);
|
|
79
|
+
register(ctx, notesWrite, (agent) => [identity(agent)]);
|
|
80
|
+
register(ctx, notesUpdate, (agent) => [identity(agent), (change) => change.kind === "none" ? "" : `note ${change.kind}`]);
|
|
81
|
+
register(ctx, notesRead, (agent) => [identity(agent)]);
|
|
82
|
+
register(ctx, notesList, (agent) => [identity(agent)]);
|
|
83
|
+
register(ctx, notesSearch, (agent) => [identity(agent)]);
|
|
84
|
+
register(ctx, historyList, async (agent) => [await historyProjection(ctx, agent.session.id)]);
|
|
85
|
+
register(ctx, historyRead, async (agent) => [await historyProjection(ctx, agent.session.id)]);
|
|
86
|
+
register(ctx, historyWindows, async (agent) => [await historyProjection(ctx, agent.session.id), agent.session.id]);
|
|
87
|
+
ctx.tools.register(defineTool({
|
|
88
|
+
name: "clear_memory",
|
|
89
|
+
description: "Open a fresh context window after this tool batch. Write recovery notes first; notes and raw history stay on disk.",
|
|
90
|
+
parameters: {},
|
|
91
|
+
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.` }] },
|
|
92
|
+
async execute(_args, exec) {
|
|
93
|
+
const agent = requireAgent(exec);
|
|
94
|
+
preflight(ctx);
|
|
95
|
+
const state = engine.windows.get(agent.session);
|
|
96
|
+
return { window_id: state.snapshot.windowId, reset_requested: true };
|
|
97
|
+
},
|
|
98
|
+
}));
|
|
99
|
+
ctx.tools.register(defineTool({
|
|
100
|
+
name: "get_context_remaining",
|
|
101
|
+
description: "Estimated tokens left before the notes close-out warning; null when dsh has no model contextWindow.",
|
|
102
|
+
parameters: {},
|
|
103
|
+
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) }] },
|
|
104
|
+
async execute(_args, exec) {
|
|
105
|
+
const agent = requireAgent(exec);
|
|
106
|
+
preflight(ctx);
|
|
107
|
+
const budget = await measureBudget(ctx, agent, engine.config, exec.signal);
|
|
108
|
+
return { remaining_tokens: budget?.countdown ?? null };
|
|
109
|
+
},
|
|
110
|
+
}));
|
|
111
|
+
}
|