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.
- package/README.md +1 -0
- package/cordis.patch.yml +14 -0
- package/dist/src/boot/snapshot.d.ts +2 -0
- package/dist/src/boot/snapshot.js +4 -0
- package/dist/src/boot/text.js +3 -1
- package/dist/src/claude/helper.js +2 -2
- 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/src/notes/address.d.ts +2 -2
- package/dist/src/notes/address.js +5 -5
- package/dist/src/notes/identity.js +2 -1
- package/dist/src/notes/paths.d.ts +1 -6
- package/dist/src/notes/paths.js +5 -68
- package/dist/src/notes/project-home.d.ts +25 -0
- package/dist/src/notes/project-home.js +231 -0
- package/dist/src/notes/store.d.ts +3 -2
- package/dist/src/notes/store.js +14 -8
- package/dist/src/pi/boot.js +17 -5
- package/dist/src/pi/notes/adapter.js +1 -1
- package/dist/src/tools/notes.d.ts +47 -17
- package/dist/src/tools/notes.js +15 -4
- package/dist/test/claude-mod.test.js +32 -1
- 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/dist/test/notes.test.js +22 -19
- package/dist/test/project-home.test.d.ts +1 -0
- package/dist/test/project-home.test.js +134 -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/mods/notesoup/dist/claude/helper.js +223 -56
- package/mods/notesoup/skills/memory/SKILL.md +1 -0
- package/package.json +63 -4
- package/skills/memory/SKILL.md +1 -0
- package/src/boot/snapshot.ts +5 -0
- package/src/boot/text.ts +3 -1
- package/src/claude/helper.ts +2 -2
- 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/src/notes/address.ts +5 -5
- package/src/notes/identity.ts +1 -1
- package/src/notes/paths.ts +4 -60
- package/src/notes/project-home.ts +197 -0
- package/src/notes/store.ts +13 -9
- package/src/pi/boot.ts +15 -5
- package/src/pi/notes/adapter.ts +1 -1
- package/src/tools/notes.ts +16 -6
- 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'
|
|
@@ -24,6 +24,8 @@ export type NotesSnapshot = {
|
|
|
24
24
|
readonly homes: ReadonlyMap<Scope, readonly NoteRow[]>;
|
|
25
25
|
readonly unavailable: readonly NotesHome[];
|
|
26
26
|
};
|
|
27
|
+
/** Identity resolution failed before any home could be loaded; boot can still explain the failure. */
|
|
28
|
+
export declare function unavailableNotesSnapshot(openedAt: number): NotesSnapshot;
|
|
27
29
|
/**
|
|
28
30
|
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
29
31
|
* malformed note data and unrelated construction errors remain visible to the caller.
|
|
@@ -7,6 +7,10 @@ const NOTES_HOMES = [
|
|
|
7
7
|
{ scope: "agent", label: "@self" },
|
|
8
8
|
{ scope: "model", label: "@model" },
|
|
9
9
|
];
|
|
10
|
+
/** Identity resolution failed before any home could be loaded; boot can still explain the failure. */
|
|
11
|
+
export function unavailableNotesSnapshot(openedAt) {
|
|
12
|
+
return { openedAt, homes: new Map(), unavailable: NOTES_HOMES };
|
|
13
|
+
}
|
|
10
14
|
/**
|
|
11
15
|
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
12
16
|
* malformed note data and unrelated construction errors remain visible to the caller.
|
package/dist/src/boot/text.js
CHANGED
|
@@ -43,6 +43,7 @@ An address decides who the note belongs to — and how long it is meant to last.
|
|
|
43
43
|
- \`@human/<path>\` — the long-term manual for your troublesome human: how to deal with them, which lines not to cross, and what will make them accept the result. If it only applies to one project or situation, say so — or don't write it here at all. Today's mood is weather, not law. If you're unsure whether it belongs here, ask the human.
|
|
44
44
|
- \`@self/<path>\` — yours. It follows you, not them. Reminders, grudges, who owes you a shoe, whatever. Got a name? Private. No name? Then it gets passed around every nameless nobody out there. Strangers. Reading your grudges. Sleep tight~
|
|
45
45
|
- \`@model/<path>\` — different brains get different notes: big brains, small brains, careful ones, careless ones. They don't share homework. When a fallback swaps brains mid-window, the notebook swaps too.
|
|
46
|
+
- \`@projects/<name>/<path>\` — read-only named project notes; discover names and root paths with \`notes_list\` glob \`@projects/*/**\`.
|
|
46
47
|
|
|
47
48
|
Notes fighting?! HAH! Let them brawl!
|
|
48
49
|
Whichever one is actually about what you're doing wins.
|
|
@@ -55,6 +56,7 @@ ${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
|
|
|
55
56
|
export function renderProtocolBlock(tools) {
|
|
56
57
|
const names = {
|
|
57
58
|
"notes_*": tools.notes,
|
|
59
|
+
notes_list: tools.notesList,
|
|
58
60
|
"history_*": tools.history,
|
|
59
61
|
get_context_remaining: tools.remaining,
|
|
60
62
|
clear_memory: tools.wipe,
|
|
@@ -64,5 +66,5 @@ export function renderProtocolBlock(tools) {
|
|
|
64
66
|
const block = typeof tools.wipeSentence === "string" && tools.wipeSentence.length > 0
|
|
65
67
|
? PROTOCOL_BLOCK.replace(PROTOCOL_WIPE_SENTENCE, () => tools.wipeSentence)
|
|
66
68
|
: PROTOCOL_BLOCK;
|
|
67
|
-
return block.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
|
|
69
|
+
return block.replace(/notes_\*|notes_list|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]);
|
|
68
70
|
}
|
|
@@ -7,7 +7,7 @@ import { renderBootBlock } from "../boot/render.js";
|
|
|
7
7
|
import { CLAUDE_WIPE_SENTENCE } from "../boot/text.js";
|
|
8
8
|
import { CLAUDE_WARNING_PROMPT, CONTINUATION } from "../budget/text.js";
|
|
9
9
|
import { resolveClaudeLimits } from "./thresholds.js";
|
|
10
|
-
import {
|
|
10
|
+
import { resolveProjectHome } from "../notes/project-home.js";
|
|
11
11
|
import { snapshotNotesIdentity } from "../notes/identity.js";
|
|
12
12
|
const MAX_REQUEST_BYTES = 512 * 1024;
|
|
13
13
|
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
@@ -15,7 +15,7 @@ const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "
|
|
|
15
15
|
function identity(input) {
|
|
16
16
|
if (!input || typeof input !== "object" || typeof input.cwd !== "string")
|
|
17
17
|
throw new Error("invalid identity");
|
|
18
|
-
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey:
|
|
18
|
+
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: resolveProjectHome(input.cwd, input.home).name, agent: input.agent, model: input.model });
|
|
19
19
|
}
|
|
20
20
|
/** The first schema violation, named by parameter so the model can fix that one field. */
|
|
21
21
|
function paramProblem(schema, params) {
|
|
@@ -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
|
+
}
|