notesoup 0.51.9 → 0.52.2
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 +3 -10
- package/dist/plugins/claude/src/history.js +9 -12
- package/dist/plugins/pi/notes/tools.d.ts +1 -1
- package/dist/plugins/pi/notes/tools.js +26 -7
- package/dist/plugins/pi/tool-result.d.ts +3 -2
- package/dist/plugins/pi/tool-result.js +3 -1
- package/dist/src/dream/git.d.ts +2 -3
- package/dist/src/dream/git.js +3 -8
- package/dist/src/dream/lock.d.ts +10 -27
- package/dist/src/dream/lock.js +16 -79
- package/dist/src/history/query.js +2 -1
- package/dist/src/notes/errors.d.ts +1 -1
- package/dist/src/notes/identity.d.ts +2 -0
- package/dist/src/notes/identity.js +3 -1
- package/dist/src/notes/store.d.ts +2 -0
- package/dist/src/notes/store.js +40 -4
- package/dist/src/tools/dream.d.ts +113 -0
- package/dist/src/tools/dream.js +112 -0
- package/dist/src/tools/history.js +1 -1
- package/dist/src/tools/notes.d.ts +15 -1
- package/dist/src/tools/notes.js +4 -4
- package/dist/test/claude-history.test.js +49 -2
- package/dist/test/claude-mod.test.js +136 -30
- package/dist/test/dependencies.test.js +3 -6
- package/dist/test/dream-skill.test.js +2 -3
- package/dist/test/dream-tools.test.js +67 -0
- package/docs/claude-code-mod.md +2 -2
- package/docs/notes-library.md +1 -1
- package/docs/skills.md +12 -15
- package/package.json +2 -5
- package/plugins/claude/.claude-plugin/plugin.json +1 -1
- package/plugins/claude/dist/claude/helper.js +36 -29
- package/plugins/claude/hooks/register.ts +71 -47
- package/plugins/claude/src/history.ts +9 -11
- package/plugins/pi/notes/tools.ts +25 -8
- package/plugins/pi/tool-result.ts +4 -1
- package/src/dream/git.ts +3 -8
- package/src/dream/lock.ts +18 -66
- package/src/history/query.ts +2 -1
- package/src/notes/errors.ts +1 -1
- package/src/notes/identity.ts +4 -1
- package/src/notes/store.ts +37 -4
- package/src/tools/dream.ts +112 -0
- package/src/tools/history.ts +1 -1
- package/src/tools/notes.ts +4 -4
- package/dist/plugins/pi/dream/cli.d.ts +0 -10
- package/dist/plugins/pi/dream/cli.js +0 -173
- package/dist/plugins/pi/dream/runner.d.ts +0 -27
- package/dist/plugins/pi/dream/runner.js +0 -91
- package/dist/plugins/pi/dream/settings.d.ts +0 -7
- package/dist/plugins/pi/dream/settings.js +0 -17
- package/dist/src/dream/doctor.d.ts +0 -2
- package/dist/src/dream/doctor.js +0 -161
- package/dist/src/dream/gates.d.ts +0 -10
- package/dist/src/dream/gates.js +0 -26
- package/dist/src/dream/jail.d.ts +0 -11
- package/dist/src/dream/jail.js +0 -71
- package/dist/src/dream/report.d.ts +0 -7
- package/dist/src/dream/report.js +0 -34
- package/dist/src/dream/result.d.ts +0 -9
- package/dist/src/dream/settings.d.ts +0 -9
- package/dist/src/dream/settings.js +0 -16
- package/dist/test/doctor.test.d.ts +0 -1
- package/dist/test/doctor.test.js +0 -37
- package/dist/test/dream.test.d.ts +0 -1
- package/dist/test/dream.test.js +0 -150
- package/plugins/pi/dream/cli.ts +0 -118
- package/plugins/pi/dream/runner.ts +0 -92
- package/plugins/pi/dream/settings.ts +0 -17
- package/src/dream/doctor.ts +0 -118
- package/src/dream/gates.ts +0 -26
- package/src/dream/jail.ts +0 -62
- package/src/dream/report.ts +0 -32
- package/src/dream/result.ts +0 -2
- package/src/dream/settings.ts +0 -19
- /package/dist/{src/dream/result.js → test/dream-tools.test.d.ts} +0 -0
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
-
import { execFileSync } from "node:child_process";
|
|
3
2
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
3
|
import { tmpdir } from "node:os";
|
|
5
4
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -149,7 +148,7 @@ test("the core entry is host-neutral and the Pi plugin entry owns the extension"
|
|
|
149
148
|
assert.equal(pi.createNotesoup, createNotesoup);
|
|
150
149
|
assert.equal(typeof createNotesoup(), "function");
|
|
151
150
|
});
|
|
152
|
-
test("the configured extension source
|
|
151
|
+
test("the configured extension source is the executable current entry", async () => {
|
|
153
152
|
const root = repository();
|
|
154
153
|
const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
155
154
|
assert.deepEqual(manifest.pi.extensions, ["./plugins/pi/index.ts"], "Pi loads the plugin entry from TypeScript source");
|
|
@@ -163,11 +162,9 @@ test("the configured extension source and the moved dream CLI are executable cur
|
|
|
163
162
|
registerTool(tool) { tools.push(tool); },
|
|
164
163
|
registerCommand(name) { commands.push(name); },
|
|
165
164
|
});
|
|
166
|
-
assert.deepEqual(tools.map((tool) => tool.name).sort(), ["empty_brain", "get_context_remaining", "history_list", "history_read", "history_windows", "notes_list", "notes_read", "notes_search", "notes_update", "notes_write"]);
|
|
165
|
+
assert.deepEqual(tools.map((tool) => tool.name).sort(), ["dream_begin", "dream_end", "dream_forget", "empty_brain", "get_context_remaining", "history_list", "history_read", "history_windows", "notes_list", "notes_read", "notes_search", "notes_update", "notes_write"]);
|
|
166
|
+
assert.deepEqual(tools.filter((tool) => tool.exposure === "deferred").map((tool) => tool.name).sort(), ["dream_begin", "dream_end", "dream_forget"], "dream tools stay hidden until searched");
|
|
167
167
|
assert.deepEqual(commands.sort(), ["empty", "fresh-window", "notesoup"]);
|
|
168
|
-
const help = execFileSync(process.execPath, [resolve(root, manifest.bin.dream), "--help"], { cwd: root, encoding: "utf8" });
|
|
169
|
-
assert.ok(help.startsWith("dream doctor [--notes-home <dir>]"));
|
|
170
|
-
assert.ok(help.includes("Default playbook: <installed package root>/playbook.md"));
|
|
171
168
|
});
|
|
172
169
|
test("NOTESOUP_DISABLED turns the Pi extension fully off", async () => {
|
|
173
170
|
const built = await import(pathToFileURL(resolve(repository(), "dist/plugins/pi/index.js")).href);
|
|
@@ -24,12 +24,12 @@ function discoverSkill(skillsDir, name) {
|
|
|
24
24
|
assert.ok(skill.description.length > 0);
|
|
25
25
|
return skill;
|
|
26
26
|
}
|
|
27
|
-
test("dream skill is publicly discoverable and resolves the
|
|
27
|
+
test("dream skill is publicly discoverable and resolves the shared playbook", () => {
|
|
28
28
|
const root = packageRoot();
|
|
29
29
|
const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
30
30
|
assert.deepEqual(manifest.pi.skills, ["./skills"]);
|
|
31
31
|
assert.deepEqual(manifest.pi.extensions, ["./plugins/pi/index.ts"]);
|
|
32
|
-
assert.equal(manifest.bin
|
|
32
|
+
assert.equal(manifest.bin, undefined, "the dream CLI is gone; dreams run through the dream_* tools");
|
|
33
33
|
assert.ok(manifest.files.includes("skills"));
|
|
34
34
|
discoverSkill(join(root, "skills"), "memory");
|
|
35
35
|
const skill = discoverSkill(join(root, "skills"), "dream");
|
|
@@ -53,7 +53,6 @@ test("npm tarball keeps the skill's relative playbook path portable after extrac
|
|
|
53
53
|
assert.ok(packedPaths.includes("skills/memory/SKILL.md"));
|
|
54
54
|
assert.ok(packedPaths.includes("playbook.md"));
|
|
55
55
|
assert.ok(packedPaths.includes("plugins/pi/index.ts"));
|
|
56
|
-
assert.ok(packedPaths.includes("dist/plugins/pi/dream/cli.js"));
|
|
57
56
|
const extracted = join(fixture, "extracted");
|
|
58
57
|
execFileSync("mkdir", ["-p", extracted]);
|
|
59
58
|
execFileSync("tar", ["-xzf", join(fixture, packed.filename), "-C", extracted]);
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
import { createNotesStore } from "../src/notes/index.js";
|
|
8
|
+
import { dreamBegin, dreamEnd, dreamForget, dreamingIdentity } from "../src/tools/dream.js";
|
|
9
|
+
import { notesRead, notesUpdate, notesWrite } from "../src/tools/notes.js";
|
|
10
|
+
function fixture(t) {
|
|
11
|
+
const home = mkdtempSync(join(tmpdir(), "dream-tools-"));
|
|
12
|
+
t.after(() => rmSync(home, { recursive: true, force: true }));
|
|
13
|
+
const mark = (name) => {
|
|
14
|
+
mkdirSync(join(home, "project", name), { recursive: true });
|
|
15
|
+
writeFileSync(join(home, "project", name, ".project"), JSON.stringify({ id: name, path: `/work/${name}` }));
|
|
16
|
+
};
|
|
17
|
+
mark("alpha");
|
|
18
|
+
mark("beta");
|
|
19
|
+
const as = (sessionId, projectKey) => ({ home, sessionId, projectKey, agent: "root", model: "m" });
|
|
20
|
+
return { home, as };
|
|
21
|
+
}
|
|
22
|
+
test("a dream opens one other project, writes its notes, deletes only crumpled ones, then closes", async (t) => {
|
|
23
|
+
const { home, as } = fixture(t);
|
|
24
|
+
// Seed: beta's project note and two beta sessions, plus one alpha session.
|
|
25
|
+
await createNotesStore(as("b1", "beta")).write("@project/rule", "keep");
|
|
26
|
+
await createNotesStore(as("b1", "beta")).write("checkpoint", "old");
|
|
27
|
+
await createNotesStore(as("b2", "beta")).write("trash", "x");
|
|
28
|
+
await createNotesStore(as("b2", "beta")).update("trash", undefined, { crumpled: true });
|
|
29
|
+
await createNotesStore(as("a1", "alpha")).write("mine", "alpha only");
|
|
30
|
+
const me = as("now", "alpha");
|
|
31
|
+
const state = {};
|
|
32
|
+
const ident = () => dreamingIdentity(me, state);
|
|
33
|
+
// Closed: named homes are read-only and forget refuses.
|
|
34
|
+
assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false);
|
|
35
|
+
assert.equal((await dreamForget.execute({ address: "@sessions/b2/trash" }, me, state)).ok, false);
|
|
36
|
+
const begun = await dreamBegin.execute({ project: "beta" }, me, state);
|
|
37
|
+
assert.ok(begun.ok);
|
|
38
|
+
assert.deepEqual(begun.data.files.map(f => f.address).sort(), ["@projects/beta/rule.md", "@sessions/b1/checkpoint.md", "@sessions/b2/trash.md"]);
|
|
39
|
+
assert.equal((await dreamBegin.execute({}, me, state)).ok, false, "only one dream at a time");
|
|
40
|
+
assert.ok(existsSync(join(home, ".dream.lock.beta")), "the project lock is held");
|
|
41
|
+
assert.equal((await dreamBegin.execute({ project: "beta" }, as("other", "alpha"), {})).ok, false, "another session can't dream the same project");
|
|
42
|
+
assert.ok((await notesWrite.execute({ address: "@projects/beta/rule", content: "merged" }, ident())).ok);
|
|
43
|
+
assert.ok((await notesUpdate.execute({ address: "@sessions/b1/checkpoint", edits: [{ oldText: "old", newText: "new" }] }, ident(), () => "")).ok);
|
|
44
|
+
assert.equal((await notesWrite.execute({ address: "@sessions/a1/mine", content: "x" }, ident())).ok, false, "another project's session stays read-only");
|
|
45
|
+
assert.equal((await notesWrite.execute({ address: "@projects/alpha/x", content: "x" }, ident())).ok, false, "other projects stay read-only");
|
|
46
|
+
const read = await notesRead.execute({ address: "@human/none" }, ident());
|
|
47
|
+
assert.equal(read.ok, false);
|
|
48
|
+
await createNotesStore(me).write("@human/pref", "p");
|
|
49
|
+
const before = (await createNotesStore(me).list({ glob: "@human/**" }))[0].meta.accessCount;
|
|
50
|
+
assert.ok((await notesRead.execute({ address: "@human/pref" }, ident())).ok);
|
|
51
|
+
assert.equal((await createNotesStore(me).list({ glob: "@human/**" }))[0].meta.accessCount, before, "dream reads leave no stamp");
|
|
52
|
+
assert.equal((await dreamForget.execute({ address: "@sessions/b1/checkpoint" }, me, state)).ok, false, "live notes refuse");
|
|
53
|
+
assert.ok((await dreamForget.execute({ address: "@sessions/b2/trash" }, me, state)).ok);
|
|
54
|
+
assert.equal(existsSync(join(home, "pi", "session", "b2", "trash.md")), false);
|
|
55
|
+
const ended = await dreamEnd.execute({}, me, state);
|
|
56
|
+
assert.ok(ended.ok && ended.data.commit && ended.data.commit !== begun.data.baseline, "dream_end commits the changes");
|
|
57
|
+
assert.equal(existsSync(join(home, ".dream.lock.beta")), false, "the lock is released");
|
|
58
|
+
assert.equal(execFileSync("git", ["status", "--porcelain"], { cwd: home, encoding: "utf8" }), "", "the audit leaves a clean tree");
|
|
59
|
+
assert.equal((await notesWrite.execute({ address: "@projects/beta/rule", content: "x" }, ident())).ok, false, "closed again");
|
|
60
|
+
assert.equal((await dreamEnd.execute({}, me, state)).ok, false);
|
|
61
|
+
});
|
|
62
|
+
test("dream_begin refuses an unknown project", async (t) => {
|
|
63
|
+
const { as } = fixture(t);
|
|
64
|
+
const state = {};
|
|
65
|
+
assert.equal((await dreamBegin.execute({ project: "nope" }, as("s", "alpha"), state)).ok, false);
|
|
66
|
+
assert.equal(state.project, undefined);
|
|
67
|
+
});
|
package/docs/claude-code-mod.md
CHANGED
|
@@ -22,9 +22,9 @@ The notes tools also serve subagent calls, using the same session identity and s
|
|
|
22
22
|
|
|
23
23
|
The active head comes from the main loop's successful `session.append` result UUID, including attachments and notices. On startup/resume, before such an append, the public API supplies no authoritative selected leaf: history explicitly refuses instead of assuming the last file row or `last-prompt.leafUuid` is current. The append result means the engine kept a row, but its disk write may lag; a head missing on disk is a retryable refusal, not permission to switch branches. Session end clears the binding; a new classic start rebinds it.
|
|
24
24
|
|
|
25
|
-
Seqs are allocated over first-occurrence persisted append order, before active-branch filtering: one address per logical message/attachment/notice and additional addresses for each tool use/result. Repeated UUID records do not allocate again. Results pair by `tool_use_id`; pending calls remain unfinished, and a paired result's seq redirects to its call. Only text blocks and recorded attachment renderings become visible text; thinking and raw, unrendered attachment payloads are never exposed.
|
|
25
|
+
Seqs are allocated over first-occurrence persisted append order, before active-branch filtering: one address per logical message/attachment/notice and additional addresses for each tool use/result. Repeated UUID records do not allocate again. List pages skip empty user/assistant envelopes even with explicit roles, so tool-only and thinking-only rows do not crowd out dialogue; direct reads preserve those addresses and explicitly say when no visible text was recorded. Results pair by `tool_use_id`; pending calls remain unfinished, and a paired result's seq redirects to its call. Only text blocks and recorded attachment renderings become visible text; thinking and raw, unrendered attachment payloads are never exposed. Record types other than user, assistant, system and attachment are ignored, including future metadata, without allocating addresses or exposing payloads. If the selected branch requires a skipped record as an ancestor, history refuses with the missing ancestor UUID. Invalid supported message/block schemas and malformed committed JSONL lines still refuse explicitly. An incomplete final unterminated write is tolerated. Valid forward parent references are resolved after reading the snapshot, without reallocating addresses.
|
|
26
26
|
|
|
27
|
-
The selected tree follows the latest native `parentUuid` links. Compact boundaries also join their `logicalParentUuid` and recorded preserved segments through original ancestry, retaining old events instead of presenting only retained inference context. Auxiliary preservation UUIDs that were never persisted are skipped. Windows use `claude:<sessionId>:<ordinal>`, matching the boot: native compact boundaries advance the ordinal, and retained notesoup boot markers name that same ordinal rather than advancing it again. Preserved duplicate rows keep their original window; new children of their rewritten versions inherit the new window. `@previous` resolves through this oldest-first window list. A missing required ancestor is an explicit refusal.
|
|
27
|
+
The selected tree follows the latest native `parentUuid` links. Compact boundaries also join their `logicalParentUuid` and recorded preserved segments through original ancestry, retaining old events instead of presenting only retained inference context. Auxiliary preservation UUIDs that were never persisted are skipped. Windows use `claude:<sessionId>:<ordinal>`, matching the current boot: native compact boundaries advance the ordinal, and retained notesoup boot markers name that same ordinal rather than advancing it again. A fork preserves the copied boot's ordinal but uses its own session id for public window ids. Copied prompt-context boot blocks are rebuilt with a fresh notes snapshot and the current session identity; historical boot messages in the transcript remain unchanged. Preserved duplicate rows keep their original window; new children of their rewritten versions inherit the new window. `@previous` resolves through this oldest-first window list. A missing required ancestor is an explicit refusal.
|
|
28
28
|
|
|
29
29
|
## Validation
|
|
30
30
|
|
package/docs/notes-library.md
CHANGED
|
@@ -26,7 +26,7 @@ const files = await notes.list({ glob: "@project/**" });
|
|
|
26
26
|
const matches = await notes.search(["library"]);
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
`/notes` ships JavaScript and TypeScript declarations. It does not import Pi or read `PI_*` environment variables. Pi packages are optional peers: a notes-only installation does not install them. Using the Pi plugin
|
|
29
|
+
`/notes` ships JavaScript and TypeScript declarations. It does not import Pi or read `PI_*` environment variables. Pi packages are optional peers: a notes-only installation does not install them. Using the Pi plugin or the dsh rows (`notesoup/dsh`) still requires its host. This is a filesystem library for Node, not a browser storage API.
|
|
30
30
|
|
|
31
31
|
## API and identity
|
|
32
32
|
|
package/docs/skills.md
CHANGED
|
@@ -1,30 +1,27 @@
|
|
|
1
|
-
# Skills
|
|
1
|
+
# Skills and dream
|
|
2
2
|
|
|
3
3
|
## Memory skill
|
|
4
4
|
|
|
5
5
|
The package provides `/skill:memory`, a short self-contained guide to the notes and history tools: note addresses and homes, finding and paging notes, searching and paging history, saving recovery state, and what to do when a memory tool is unavailable. It is a fallback for sessions where the boot protocol is missing or unclear and a reference on demand; normal tool calls do not require reading it. It is written independently of the boot text rather than generated from it. The Claude Code Mod ships the same guide; its history tools require the documented main-session transcript path and a confirmed append head.
|
|
6
6
|
|
|
7
|
-
## Dream
|
|
7
|
+
## Dream
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
`/skill:dream` reviews notes in the current agent session, following the shared `playbook.md`.
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
In Pi the session gets three hidden `dream_*` tools; they are not declared to the model and are found with `tool_search` or codemode's `searchTools("dream")`:
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
- `dream_begin(project?)` opens one project, by default the current one, as in `@projects/<name>/`. It lists that project's notes and every session note whose frontmatter `project` names it, crumpled notes included. While it is open, `notes_write` and `notes_update` may edit those addresses (existing notes only in other sessions), and reads leave no access stamp. Other projects stay read-only.
|
|
14
|
+
- `dream_forget(address)` permanently deletes one crumpled note within reach; live notes refuse.
|
|
15
|
+
- `dream_end()` closes the dream.
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
One session dreams over one project at a time. New session notes record their project key in `project`; notes without it never appear in a project's dream. Standard linked Git worktrees share the main checkout's project key.
|
|
16
18
|
|
|
17
|
-
|
|
19
|
+
## The dream lock and Git audit
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
`dream_begin` takes an exclusive `.dream.lock.<project>` in the notes home with a single O_CREAT|O_EXCL creation, then commits a baseline of the notes home to its Git repository (initialized on first use). `dream_end` commits the dream's changes and releases the lock, so `git show` reviews a dream and `git revert` rolls it back. A session shutdown releases the lock without the final commit.
|
|
20
22
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
If a dream process crashed, its lock remains and later runs refuse to start. There is no automatic recovery and no force-unlock command: after you have confirmed that no dream process is running, remove the stale lock by hand.
|
|
23
|
+
An existing lock refuses a new dream regardless of its age. If a Pi process crashed mid-dream, remove the stale lock by hand after confirming no dream is running:
|
|
24
24
|
|
|
25
25
|
```sh
|
|
26
|
-
|
|
27
|
-
rm "${NOTESOUP_HOME:-$HOME/.agents/notes}/.dream.lock"
|
|
26
|
+
rm "${NOTESOUP_HOME:-$HOME/.agents/notes}/.dream.lock.<project>"
|
|
28
27
|
```
|
|
29
|
-
|
|
30
|
-
Removing a lock while a holder is running is outside the supported cooperative protocol and can let two dreams run at once.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "notesoup",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/src/index.js",
|
|
6
6
|
"types": "./dist/src/index.d.ts",
|
|
@@ -56,11 +56,8 @@
|
|
|
56
56
|
"!plugins/claude/tsconfig.json",
|
|
57
57
|
"cordis.patch.yml"
|
|
58
58
|
],
|
|
59
|
-
"bin": {
|
|
60
|
-
"dream": "dist/plugins/pi/dream/cli.js"
|
|
61
|
-
},
|
|
62
59
|
"scripts": {
|
|
63
|
-
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs
|
|
60
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs",
|
|
64
61
|
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p plugins/claude/tsconfig.json",
|
|
65
62
|
"test": "npm run build && node --test --test-concurrency=4 $(ls dist/test/*.test.js | grep -v dist/test/claude-validation.test.js) && node --test dist/test/claude-validation.test.js",
|
|
66
63
|
"prepublishOnly": "npm run typecheck",
|
|
@@ -7975,7 +7975,7 @@ function isFilesystemError(error) {
|
|
|
7975
7975
|
|
|
7976
7976
|
// src/notes/store.ts
|
|
7977
7977
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
7978
|
-
import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
7978
|
+
import { mkdir, readdir as readdir2, readFile, realpath, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
7979
7979
|
import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
|
|
7980
7980
|
|
|
7981
7981
|
// src/text-match.ts
|
|
@@ -8146,8 +8146,9 @@ function snapshotNotesIdentity(value) {
|
|
|
8146
8146
|
if (!SLUG_PATTERN.test(projectKey2)) throw new TypeError("notes context projectKey must be a canonical lowercase slug");
|
|
8147
8147
|
if (!SLUG_PATTERN.test(agent)) throw new TypeError("notes context agent must be a canonical lowercase slug");
|
|
8148
8148
|
if (!SLUG_PATTERN.test(model)) throw new TypeError("notes context model must be a canonical lowercase slug");
|
|
8149
|
+
if (value.dreaming !== void 0 && !SLUG_PATTERN.test(value.dreaming)) throw new TypeError("notes context dreaming must be a canonical lowercase slug");
|
|
8149
8150
|
const home = resolve(homeValue);
|
|
8150
|
-
return Object.freeze({ home, sessionId, projectKey: projectKey2, agent, model });
|
|
8151
|
+
return Object.freeze({ home, sessionId, projectKey: projectKey2, agent, model, ...value.dreaming === void 0 ? {} : { dreaming: value.dreaming } });
|
|
8151
8152
|
}
|
|
8152
8153
|
|
|
8153
8154
|
// src/notes/constants.ts
|
|
@@ -8510,6 +8511,7 @@ function frontmatterOf(meta) {
|
|
|
8510
8511
|
}
|
|
8511
8512
|
function assertWritableHome(scope, who, identity2) {
|
|
8512
8513
|
if (who === void 0) return;
|
|
8514
|
+
if (identity2.dreaming !== void 0 && (scope === "session" || scope === "project" && who === identity2.dreaming)) return;
|
|
8513
8515
|
if (scope === "session") throw new NoteError("invalid_scope", `@sessions/${who}/ is read-only; use a bare path to write to this session.`);
|
|
8514
8516
|
if (scope === "project") throw new NoteError("invalid_scope", `@projects/${who}/ is read-only; use @project/ to write to your own project.`);
|
|
8515
8517
|
const current = scope === "agent" ? identity2.agent : identity2.model;
|
|
@@ -8517,6 +8519,11 @@ function assertWritableHome(scope, who, identity2) {
|
|
|
8517
8519
|
const home = scope === "agent" ? `@agents/${who}/` : `@models/${who}/`;
|
|
8518
8520
|
throw new NoteError("invalid_scope", `${home} is someone else's home; you can write to this session, @project/, @human/, @self/, or @model/.`);
|
|
8519
8521
|
}
|
|
8522
|
+
function assertDreamSessionNote(scope, who, identity2, raw, address) {
|
|
8523
|
+
if (scope !== "session" || who === void 0 || identity2.dreaming === void 0) return;
|
|
8524
|
+
if (raw !== void 0 && parseNote(raw).meta.project === identity2.dreaming) return;
|
|
8525
|
+
throw new NoteError("invalid_scope", raw === void 0 ? `${address}: a dream edits other sessions' existing notes, it doesn't create new ones there.` : `${address} belongs to another project, not the one being dreamed over (${identity2.dreaming}).`);
|
|
8526
|
+
}
|
|
8520
8527
|
function createNotesStore(input) {
|
|
8521
8528
|
const identity2 = snapshotNotesIdentity(input);
|
|
8522
8529
|
async function write(address, content, options = {}) {
|
|
@@ -8531,6 +8538,7 @@ function createNotesStore(input) {
|
|
|
8531
8538
|
const now = writeStamp();
|
|
8532
8539
|
const cleanBody = stripLeadingFrontmatter(content);
|
|
8533
8540
|
const existingRaw = await readFileIfExists(path);
|
|
8541
|
+
assertDreamSessionNote(scope, destination.who, identity2, existingRaw, address);
|
|
8534
8542
|
const existing = existingRaw === void 0 ? void 0 : parseNote(existingRaw, now).meta;
|
|
8535
8543
|
const outcome = existing === void 0 ? "created" : existing.crumpledAt === void 0 ? "overwrote" : "uncrumpled";
|
|
8536
8544
|
const meta = existing ?? {
|
|
@@ -8561,7 +8569,7 @@ function createNotesStore(input) {
|
|
|
8561
8569
|
if (raw === void 0) return void 0;
|
|
8562
8570
|
const now = Date.now();
|
|
8563
8571
|
const parsed = parseNote(raw, now);
|
|
8564
|
-
if ((scope === "project" || scope === "session") && destination.who !== void 0) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
|
|
8572
|
+
if (identity2.dreaming !== void 0 || (scope === "project" || scope === "session") && destination.who !== void 0) return { meta: { ...parsed.meta, scope }, body: parsed.body, resolvedScope: scope };
|
|
8565
8573
|
const meta = { ...parsed.meta, scope, lastAccessed: now, accessCount: (typeof parsed.meta.accessCount === "number" ? parsed.meta.accessCount : 0) + 1 };
|
|
8566
8574
|
await atomicWrite(path, serializeNote(meta, parsed.body));
|
|
8567
8575
|
return { meta, body: parsed.body, resolvedScope: scope };
|
|
@@ -8586,6 +8594,8 @@ function createNotesStore(input) {
|
|
|
8586
8594
|
const raw = await readFileIfExists(fromPath);
|
|
8587
8595
|
if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
|
|
8588
8596
|
const targetRaw = differentPaths ? await readFileIfExists(path) : void 0;
|
|
8597
|
+
assertDreamSessionNote(from.scope, from.who, identity2, raw, address);
|
|
8598
|
+
if (differentPaths) assertDreamSessionNote(scope, destination.who, identity2, targetRaw, stableOptions.renameTo);
|
|
8589
8599
|
const sourceReal = targetRaw === void 0 ? void 0 : await realpath(fromPath);
|
|
8590
8600
|
const sameFile = sourceReal !== void 0 && sourceReal === await realpath(path);
|
|
8591
8601
|
const moved = differentPaths && !sameFile;
|
|
@@ -8642,6 +8652,21 @@ function createNotesStore(input) {
|
|
|
8642
8652
|
const { meta, replacedCrumpledTarget } = await update(fromAddress, void 0, { renameTo: toAddress });
|
|
8643
8653
|
return { meta, replacedCrumpledTarget };
|
|
8644
8654
|
}
|
|
8655
|
+
async function forget(address) {
|
|
8656
|
+
if (identity2.dreaming === void 0) throw new NoteError("invalid_scope", "Only a dream can delete notes; begin one first.");
|
|
8657
|
+
const target = assertAddress(address);
|
|
8658
|
+
assertWritableHome(target.scope, target.who, identity2);
|
|
8659
|
+
const path = physicalPath(target.scope, target.path, identity2, target.who);
|
|
8660
|
+
return withPathQueue(path, async () => {
|
|
8661
|
+
const raw = await readFileIfExists(path);
|
|
8662
|
+
if (raw === void 0) throw new NoteError("not_found", `No note at ${noteIdentity(identity2, address).address}.`);
|
|
8663
|
+
assertDreamSessionNote(target.scope, target.who, identity2, raw, address);
|
|
8664
|
+
const { meta } = parseNote(raw);
|
|
8665
|
+
if (meta.crumpledAt === void 0) throw new NoteError("not_crumpled", `${noteIdentity(identity2, address).address} isn't crumpled; crumple it before deleting.`);
|
|
8666
|
+
await unlink(path);
|
|
8667
|
+
return { ...meta, scope: target.scope };
|
|
8668
|
+
});
|
|
8669
|
+
}
|
|
8645
8670
|
async function* scan(options, status) {
|
|
8646
8671
|
const glob = assertGlobPattern(options.glob);
|
|
8647
8672
|
const pattern = glob === "@default" ? void 0 : glob;
|
|
@@ -8723,7 +8748,7 @@ function createNotesStore(input) {
|
|
|
8723
8748
|
function searchWithStatus(queries, options = {}) {
|
|
8724
8749
|
return searchRows(queries, options, { homesUnavailable: [] });
|
|
8725
8750
|
}
|
|
8726
|
-
return { write, read, update, rename: rename2, list, search, listWithStatus, searchWithStatus };
|
|
8751
|
+
return { write, read, update, rename: rename2, forget, list, search, listWithStatus, searchWithStatus };
|
|
8727
8752
|
}
|
|
8728
8753
|
|
|
8729
8754
|
// src/tools/output.ts
|
|
@@ -9387,7 +9412,7 @@ function prepareSelection(projection, params) {
|
|
|
9387
9412
|
run.push(event);
|
|
9388
9413
|
continue;
|
|
9389
9414
|
}
|
|
9390
|
-
if (
|
|
9415
|
+
if ((event.role === "user" || event.role === "assistant") && eventDocument(event) === "") continue;
|
|
9391
9416
|
const matchOffset = params.query === void 0 ? void 0 : earliestMatchOffsetChars(eventDocument(event), params.query);
|
|
9392
9417
|
if (matchOffset !== void 0 && matchOffset < 0) continue;
|
|
9393
9418
|
candidates.push({ event, matchOffset, before: foldedRun(run) });
|
|
@@ -9510,7 +9535,7 @@ function renderRead(data) {
|
|
|
9510
9535
|
const tool = toolHeader(data);
|
|
9511
9536
|
const afterSeq = data.seq - 10;
|
|
9512
9537
|
const neighborhood = `neighborhood \u2192 \`history_list\`(${JSON.stringify({ ...afterSeq >= 1 ? { after_seq: afterSeq } : {}, before_seq: data.seq + 10 })})`;
|
|
9513
|
-
return [header(data), ...tool ? [tool] : [], neighborhood, "", renderTextWindow(data)].join("\n");
|
|
9538
|
+
return [header(data), ...tool ? [tool] : [], neighborhood, "", data.total_chars === 0 ? "No visible text recorded for this event." : renderTextWindow(data)].join("\n");
|
|
9514
9539
|
}
|
|
9515
9540
|
function pageFits(page) {
|
|
9516
9541
|
return fitsResult(success(page), (result) => renderOutcome(result, renderPage));
|
|
@@ -9640,22 +9665,6 @@ var historyRead = {
|
|
|
9640
9665
|
// plugins/claude/src/history.ts
|
|
9641
9666
|
import { readFile as readFile2 } from "node:fs/promises";
|
|
9642
9667
|
import { isDeepStrictEqual } from "node:util";
|
|
9643
|
-
var METADATA = /* @__PURE__ */ new Set([
|
|
9644
|
-
"queue-operation",
|
|
9645
|
-
"last-prompt",
|
|
9646
|
-
"atis-latch",
|
|
9647
|
-
"mode",
|
|
9648
|
-
"permission-mode",
|
|
9649
|
-
"file-history-snapshot",
|
|
9650
|
-
"cost-state",
|
|
9651
|
-
"summary",
|
|
9652
|
-
"custom-title",
|
|
9653
|
-
"agent-name",
|
|
9654
|
-
"agent-color",
|
|
9655
|
-
"tag",
|
|
9656
|
-
"session-title",
|
|
9657
|
-
"progress"
|
|
9658
|
-
]);
|
|
9659
9668
|
var MESSAGE_TYPES = /* @__PURE__ */ new Set(["user", "assistant", "system", "attachment"]);
|
|
9660
9669
|
var NON_TEXT_BLOCKS = /* @__PURE__ */ new Set(["thinking", "redacted_thinking", "image", "document", "audio", "video", "server_tool_use", "web_search_tool_result", "tool_reference"]);
|
|
9661
9670
|
function object(value) {
|
|
@@ -9738,13 +9747,12 @@ function decode(row, seq) {
|
|
|
9738
9747
|
var BOOT_IDENTITY = /^<(?:notesoup:window_identity|context_window)>\nAgent name: claude \(/;
|
|
9739
9748
|
var BOOT_PROTOCOL_OPEN = /\n<(?:notesoup:notes_protocol|context_window_protocol)>\n/;
|
|
9740
9749
|
var BOOT_PROTOCOL_CLOSE = /\n<\/(?:notesoup:notes_protocol|context_window_protocol)>/;
|
|
9741
|
-
function bootOrdinal(row,
|
|
9750
|
+
function bootOrdinal(row, retained) {
|
|
9742
9751
|
if (!retained || row.type !== "user" || !object(row.message)) return void 0;
|
|
9743
9752
|
const text = contentText(row.message.content);
|
|
9744
9753
|
if (!BOOT_IDENTITY.test(text) || !BOOT_PROTOCOL_OPEN.test(text) || !BOOT_PROTOCOL_CLOSE.test(text)) return void 0;
|
|
9745
|
-
const
|
|
9746
|
-
|
|
9747
|
-
if (suffix === void 0 || !/^\d+$/.test(suffix)) return void 0;
|
|
9754
|
+
const suffix = /^Current context window id: claude:[^\n]+:(\d+)$/m.exec(text)?.[1];
|
|
9755
|
+
if (suffix === void 0) return void 0;
|
|
9748
9756
|
const ordinal = Number(suffix);
|
|
9749
9757
|
return Number.isSafeInteger(ordinal) ? ordinal : void 0;
|
|
9750
9758
|
}
|
|
@@ -9752,8 +9760,7 @@ function claudeHistoryFromJsonl(text, source) {
|
|
|
9752
9760
|
const nodes = /* @__PURE__ */ new Map();
|
|
9753
9761
|
let nextSeq = 1;
|
|
9754
9762
|
for (const row of rowsOf(text)) {
|
|
9755
|
-
if (
|
|
9756
|
-
if (!MESSAGE_TYPES.has(row.type)) throw new Error(`unsupported Claude transcript record type: ${row.type}`);
|
|
9763
|
+
if (!MESSAGE_TYPES.has(row.type)) continue;
|
|
9757
9764
|
const uuid = requiredString(row.uuid, "uuid");
|
|
9758
9765
|
parent(row);
|
|
9759
9766
|
if (row.sessionId !== source.sessionId) throw new Error("Claude transcript belongs to a different session");
|
|
@@ -9787,7 +9794,7 @@ function claudeHistoryFromJsonl(text, source) {
|
|
|
9787
9794
|
let before = cursor.ordinal ?? 0;
|
|
9788
9795
|
for (const current of chain.reverse()) {
|
|
9789
9796
|
const retained = current.row.isCompactSummary === true || current.ancestor !== void 0 && boundary(current.ancestor.row);
|
|
9790
|
-
const marked = bootOrdinal(current.row,
|
|
9797
|
+
const marked = bootOrdinal(current.row, retained);
|
|
9791
9798
|
current.ordinal = marked === void 0 ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
|
|
9792
9799
|
before = current.ordinal;
|
|
9793
9800
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { EngineInterface, On, ProcessRunResult, ToolCallResult, ToolSpec } from "claude-code"
|
|
1
|
+
import type { EngineInterface, On, ProcessRunResult, ToolCallInput, ToolCallResult, ToolSpec } from "claude-code"
|
|
2
2
|
|
|
3
3
|
const PREFIX = "mcp__notesoup__"
|
|
4
4
|
const HELPER = `${import.meta.dir}/../dist/claude/helper.js`
|
|
@@ -22,7 +22,7 @@ type ResetState = {
|
|
|
22
22
|
manualPending: boolean; headless: boolean; usageFailureLogged: boolean; preparedBoot?: string; retainedBoot?: string
|
|
23
23
|
continuation?: string; continuationWindow?: number
|
|
24
24
|
compactDisabled: boolean; limitsFailureLogged: boolean; limitsAttempts: number; limitsWindow: number
|
|
25
|
-
limits?: ClaudeLimits; warnedWindow?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
25
|
+
limits?: ClaudeLimits; warnedWindow?: number; warningPending?: number; texts?: SharedTexts; settingsFailureLogged: boolean
|
|
26
26
|
}
|
|
27
27
|
const HEADLESS = "No brain when headless"
|
|
28
28
|
const COMPACT_DISABLED = "Brain can't be emptied with DISABLE_COMPACT"
|
|
@@ -104,12 +104,9 @@ async function compactDisabled($: Engine): Promise<boolean> {
|
|
|
104
104
|
// The same presence convention as the helper's flag parsing: "off"/"no" mean not disabled.
|
|
105
105
|
return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off"
|
|
106
106
|
}
|
|
107
|
-
/** Presence-style
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
try { value = await $.env.get("NOTESOUP_DISABLED") } catch { return false }
|
|
111
|
-
if (value === undefined) return false
|
|
112
|
-
const text = value.trim().toLowerCase()
|
|
107
|
+
/** Presence-style env switch; the same convention as DISABLE_COMPACT. The loader requires literal env names. */
|
|
108
|
+
function envFlag(value: string | undefined): boolean {
|
|
109
|
+
const text = value?.trim().toLowerCase() ?? ""
|
|
113
110
|
return text !== "" && text !== "0" && text !== "false" && text !== "no" && text !== "off"
|
|
114
111
|
}
|
|
115
112
|
async function readSettings($: Engine, state: ResetState): Promise<unknown> {
|
|
@@ -267,7 +264,7 @@ function forgetSession(state: ResetState) {
|
|
|
267
264
|
state.continuationWindow = undefined
|
|
268
265
|
state.limitsAttempts = state.limitsWindow = 0
|
|
269
266
|
state.settingsFailureLogged = state.limitsFailureLogged = false
|
|
270
|
-
state.warnedWindow = undefined
|
|
267
|
+
state.warnedWindow = state.warningPending = undefined
|
|
271
268
|
}
|
|
272
269
|
async function modelOf($: Engine): Promise<string> {
|
|
273
270
|
// session.model() is the documented main-loop model API. Match the notes library's slug.
|
|
@@ -319,6 +316,7 @@ export function register(on: On) {
|
|
|
319
316
|
const manualSignal: { wake?: () => void } = {}
|
|
320
317
|
const state: ResetState = { generation: 0, window: 0, disabled: false, turnRunning: false, resetting: false, manualPending: false, headless: false, usageFailureLogged: false, compactDisabled: false, limitsFailureLogged: false, limitsAttempts: 0, limitsWindow: 0, settingsFailureLogged: false }
|
|
321
318
|
const registered = new Set<string>()
|
|
319
|
+
let keepMemory = false
|
|
322
320
|
// Classic SessionStart precedes typed session.start and startup appends. Keep this binding
|
|
323
321
|
// across forgetSession; re-key it only against the actual session id, never a guessed path.
|
|
324
322
|
on("classic.SessionStart", async ($, e, next) => {
|
|
@@ -339,12 +337,13 @@ export function register(on: On) {
|
|
|
339
337
|
})
|
|
340
338
|
on("session.start", async ($, e, next) => {
|
|
341
339
|
forgetSession(state)
|
|
342
|
-
state.disabled = await
|
|
340
|
+
state.disabled = envFlag(await $.env.get("NOTESOUP_DISABLED").catch(() => undefined))
|
|
343
341
|
if (state.disabled) {
|
|
344
342
|
registered.clear()
|
|
345
343
|
log($, NOTESOUP_DISABLED)
|
|
346
344
|
return next(e)
|
|
347
345
|
}
|
|
346
|
+
keepMemory = envFlag(await $.env.get("NOTESOUP_KEEP_MEMORY").catch(() => undefined))
|
|
348
347
|
await refreshIdentity($, state)
|
|
349
348
|
state.headless = !e.isInteractive
|
|
350
349
|
if (state.headless) log($, HEADLESS)
|
|
@@ -371,19 +370,13 @@ export function register(on: On) {
|
|
|
371
370
|
})
|
|
372
371
|
on("tool.call", async ($, e, next) => {
|
|
373
372
|
if (state.disabled) return next(e)
|
|
374
|
-
|
|
375
|
-
const
|
|
376
|
-
if (
|
|
377
|
-
|
|
378
|
-
const name = tool.slice(PREFIX.length)
|
|
379
|
-
if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
|
|
380
|
-
const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
|
|
381
|
-
if (!result.ok) return errorResult(result.error)
|
|
382
|
-
// The outcome already decided success or refusal; Claude requires isError: true on errors and no discriminator on success.
|
|
383
|
-
const outcome = toolResultOf(result.result)
|
|
384
|
-
if (!outcome) return errorResult("helper returned an invalid tool result")
|
|
385
|
-
return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
|
|
373
|
+
const generation = state.generation
|
|
374
|
+
const result = registered.has(e.tool) ? await callNotesTool($, state, e) : await next(e)
|
|
375
|
+
if (e.agentId !== undefined || result.deny !== undefined || generation !== state.generation) return result
|
|
376
|
+
return withWarning($, state, (warning) => warning === undefined ? result : { ...result, context: [...(result.context ?? []), warning] })
|
|
386
377
|
})
|
|
378
|
+
on("prompt.submit", ($, e, next) => withWarning($, state, (warning) =>
|
|
379
|
+
next(warning === undefined ? e : { ...e, context: [...(e.context ?? []), warning] })))
|
|
387
380
|
on("turn.start", async ($, e, next) => {
|
|
388
381
|
// The documented turn.start is main-loop only. Guard tagged host events too:
|
|
389
382
|
// only a main-agent turn.complete clears this latch.
|
|
@@ -465,6 +458,9 @@ export function register(on: On) {
|
|
|
465
458
|
}
|
|
466
459
|
return { messages: built.messages }
|
|
467
460
|
})
|
|
461
|
+
// notesoup replaces Claude's summarization and auto-memory guidance; memory can be kept on request.
|
|
462
|
+
on("prompt.section", { name: "context_management" }, ($, e, next) => state.disabled ? next(e) : { text: null })
|
|
463
|
+
on("prompt.section", { name: "memory" }, ($, e, next) => state.disabled || keepMemory ? next(e) : { text: null })
|
|
468
464
|
on("prompt.context", async ($, e, next) => {
|
|
469
465
|
if (state.disabled) return next(e)
|
|
470
466
|
const result = await next(e)
|
|
@@ -473,7 +469,11 @@ export function register(on: On) {
|
|
|
473
469
|
// The reset already retained its boot as the sole conversation message.
|
|
474
470
|
// Prompt context still recomputes, but must not inject a duplicate snapshot.
|
|
475
471
|
const retained = state.retainedBoot !== undefined
|
|
476
|
-
let blocks =
|
|
472
|
+
let blocks = result.blocks.filter((block) => {
|
|
473
|
+
if (block.name !== "notesoup:boot" || !identity) return true
|
|
474
|
+
const marker = bootWindow(block.text)
|
|
475
|
+
return !retained && (!marker || (marker.sessionId === identity.sessionId && marker.window === state.window))
|
|
476
|
+
})
|
|
477
477
|
if (!retained && !blocks.some((block) => block.name === "notesoup:boot") && identity) {
|
|
478
478
|
const texts = await loadTexts($, state)
|
|
479
479
|
const boot = await buildBoot($, identity, state.window, texts, state.history)
|
|
@@ -485,18 +485,27 @@ export function register(on: On) {
|
|
|
485
485
|
}
|
|
486
486
|
blocks = [...blocks, { name: "notesoup:boot", text: boot.ok ? String(boot.result) : `# notesoup\nYour notes didn't load this time (${boot.error}). Try \`${PREFIX}notes_list\`; if it fails too, tell the human.` }]
|
|
487
487
|
}
|
|
488
|
-
|
|
489
|
-
return { ...result, blocks: warning === undefined ? blocks : [...blocks, warning] }
|
|
488
|
+
return { ...result, blocks }
|
|
490
489
|
})
|
|
491
490
|
|
|
492
491
|
}
|
|
493
492
|
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
if (
|
|
493
|
+
async function callNotesTool($: Engine, state: ResetState, e: ToolCallInput): Promise<ToolCallResult> {
|
|
494
|
+
const identity = await refreshIdentity($, state)
|
|
495
|
+
if (!identity) return errorResult("session changed during identity lookup")
|
|
496
|
+
const { tool, tool_use_id: _toolUseId, agentId, ...params } = e
|
|
497
|
+
const name = tool.slice(PREFIX.length)
|
|
498
|
+
if (name.startsWith("history_") && agentId !== undefined) return errorResult("history is unavailable for subagents; main-session history is not their transcript")
|
|
499
|
+
const result = await run($, { op: "tool", tool: name, params, identity, history: state.history })
|
|
500
|
+
if (!result.ok) return errorResult(result.error)
|
|
501
|
+
const outcome = toolResultOf(result.result)
|
|
502
|
+
if (!outcome) return errorResult("helper returned an invalid tool result")
|
|
503
|
+
return outcome.ok ? { result: outcome.text } : { result: outcome.text, isError: true }
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Read the warning without consuming this window's delivery. */
|
|
507
|
+
async function warningText($: Engine, state: ResetState): Promise<string | undefined> {
|
|
508
|
+
if (state.disabled || state.headless || state.compactDisabled || !state.identity || state.warnedWindow === state.window || state.warningPending === state.window) return undefined
|
|
500
509
|
const generation = state.generation
|
|
501
510
|
const usage = await contextUsage($, state)
|
|
502
511
|
if (generation !== state.generation || usage === undefined) return undefined
|
|
@@ -505,30 +514,45 @@ async function warningBlock($: Engine, state: ResetState): Promise<{ name: strin
|
|
|
505
514
|
const measured = measuredValue(limits, usage)
|
|
506
515
|
if (measured === undefined || measured < limits.warn) return undefined
|
|
507
516
|
const texts = await loadTexts($, state)
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
517
|
+
return generation === state.generation ? texts?.warning : undefined
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** Reserve across next(), but consume only context the chain actually accepted. */
|
|
521
|
+
async function withWarning<T extends { context?: readonly string[]; drop?: string; deny?: string }>($: Engine, state: ResetState, deliver: (warning?: string) => T | Promise<T>): Promise<T> {
|
|
522
|
+
if (state.disabled || state.headless || state.compactDisabled || !await refreshIdentity($, state)) return deliver()
|
|
523
|
+
const generation = state.generation, window = state.window
|
|
524
|
+
const warning = await warningText($, state)
|
|
525
|
+
if (warning === undefined || generation !== state.generation || window !== state.window || state.warnedWindow === window || state.warningPending === window) return deliver()
|
|
526
|
+
state.warningPending = window
|
|
527
|
+
try {
|
|
528
|
+
const result = await deliver(warning)
|
|
529
|
+
if (generation === state.generation && window === state.window && result.drop === undefined && result.deny === undefined && result.context?.includes(warning)) state.warnedWindow = window
|
|
530
|
+
return result
|
|
531
|
+
} finally {
|
|
532
|
+
if (generation === state.generation && state.warningPending === window) state.warningPending = undefined
|
|
533
|
+
}
|
|
511
534
|
}
|
|
512
535
|
|
|
513
536
|
/** The boot's identity line; `context_window` is the pre-rename tag still in old transcripts. */
|
|
514
537
|
const BOOT_IDENTITY = /<(?:notesoup:window_identity|context_window)>\nAgent name: claude /
|
|
515
538
|
|
|
516
|
-
/**
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
539
|
+
/** Old and new tag spellings, including a boot copied into a fork. */
|
|
540
|
+
function bootWindow(text: string): { sessionId: string; window: number } | undefined {
|
|
541
|
+
if (!BOOT_IDENTITY.test(text)) return undefined
|
|
542
|
+
const marker = /^Current context window id: claude:([^\n]+):(\d+)$/m.exec(text)
|
|
543
|
+
if (!marker) return undefined
|
|
544
|
+
const window = Number(marker[2])
|
|
545
|
+
return Number.isSafeInteger(window) ? { sessionId: marker[1]!, window } : undefined
|
|
546
|
+
}
|
|
547
|
+
/** Keep the copied boot ordinal, but rebuild its snapshot and identity for the new session. */
|
|
520
548
|
function restoreWindow(state: ResetState, messages: readonly { role: string; text: string }[]) {
|
|
521
549
|
if (!state.identity) return
|
|
522
|
-
const prefix = `Current context window id: claude:${state.identity.sessionId}:`
|
|
523
550
|
for (const message of messages) {
|
|
524
|
-
if (message.role !== "user"
|
|
525
|
-
const
|
|
526
|
-
if (!
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
if (!/^\d+$/.test(suffix) || !Number.isSafeInteger(window) || window <= state.window) continue
|
|
530
|
-
state.window = window
|
|
531
|
-
state.retainedBoot = message.text
|
|
551
|
+
if (message.role !== "user") continue
|
|
552
|
+
const marker = bootWindow(message.text)
|
|
553
|
+
if (!marker || marker.window <= state.window) continue
|
|
554
|
+
state.window = marker.window
|
|
555
|
+
state.retainedBoot = marker.sessionId === state.identity.sessionId ? message.text : undefined
|
|
532
556
|
}
|
|
533
557
|
}
|
|
534
558
|
|