notesoup 0.0.0-stage → 0.40.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/LICENSE +21 -0
- package/README.md +94 -2
- package/dist/src/boot/render.d.ts +16 -0
- package/dist/src/boot/render.js +95 -0
- package/dist/src/boot/snapshot.d.ts +32 -0
- package/dist/src/boot/snapshot.js +36 -0
- package/dist/src/boot/text.d.ts +17 -0
- package/dist/src/boot/text.js +48 -0
- package/dist/src/budget/constants.d.ts +9 -0
- package/dist/src/budget/constants.js +9 -0
- package/dist/src/budget/policy.d.ts +19 -0
- package/dist/src/budget/policy.js +36 -0
- package/dist/src/budget/text.d.ts +8 -0
- package/dist/src/budget/text.js +10 -0
- package/dist/src/claude/helper.d.ts +15 -0
- package/dist/src/claude/helper.js +87 -0
- package/dist/src/dream/doctor.d.ts +2 -0
- package/dist/src/dream/doctor.js +160 -0
- package/dist/src/dream/gates.d.ts +10 -0
- package/dist/src/dream/gates.js +26 -0
- package/dist/src/dream/git.d.ts +21 -0
- package/dist/src/dream/git.js +71 -0
- package/dist/src/dream/jail.d.ts +11 -0
- package/dist/src/dream/jail.js +71 -0
- package/dist/src/dream/lock.d.ts +31 -0
- package/dist/src/dream/lock.js +99 -0
- package/dist/src/dream/playbook.d.ts +1 -0
- package/dist/src/dream/playbook.js +2 -0
- package/dist/src/dream/report.d.ts +7 -0
- package/dist/src/dream/report.js +43 -0
- package/dist/src/dream/result.d.ts +9 -0
- package/dist/src/dream/result.js +1 -0
- package/dist/src/dream/settings.d.ts +10 -0
- package/dist/src/dream/settings.js +14 -0
- package/dist/src/history/history.d.ts +156 -0
- package/dist/src/history/history.js +212 -0
- package/dist/src/history/query.d.ts +63 -0
- package/dist/src/history/query.js +201 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +1 -0
- package/dist/src/notes/address.d.ts +31 -0
- package/dist/src/notes/address.js +123 -0
- package/dist/src/notes/constants.d.ts +3 -0
- package/dist/src/notes/constants.js +3 -0
- package/dist/src/notes/errors.d.ts +11 -0
- package/dist/src/notes/errors.js +13 -0
- package/dist/src/notes/frontmatter.d.ts +44 -0
- package/dist/src/notes/frontmatter.js +145 -0
- package/dist/src/notes/fs-error.d.ts +2 -0
- package/dist/src/notes/fs-error.js +5 -0
- package/dist/src/notes/identity.d.ts +10 -0
- package/dist/src/notes/identity.js +33 -0
- package/dist/src/notes/index.d.ts +5 -0
- package/dist/src/notes/index.js +3 -0
- package/dist/src/notes/paths.d.ts +21 -0
- package/dist/src/notes/paths.js +113 -0
- package/dist/src/notes/store.d.ts +103 -0
- package/dist/src/notes/store.js +474 -0
- package/dist/src/pi/boot.d.ts +24 -0
- package/dist/src/pi/boot.js +56 -0
- package/dist/src/pi/budget.d.ts +13 -0
- package/dist/src/pi/budget.js +178 -0
- package/dist/src/pi/dream/cli.d.ts +10 -0
- package/dist/src/pi/dream/cli.js +140 -0
- package/dist/src/pi/dream/runner.d.ts +27 -0
- package/dist/src/pi/dream/runner.js +90 -0
- package/dist/src/pi/dream/settings.d.ts +7 -0
- package/dist/src/pi/dream/settings.js +17 -0
- package/dist/src/pi/entries.d.ts +7 -0
- package/dist/src/pi/entries.js +7 -0
- package/dist/src/pi/estimate.d.ts +16 -0
- package/dist/src/pi/estimate.js +99 -0
- package/dist/src/pi/extension.d.ts +10 -0
- package/dist/src/pi/extension.js +24 -0
- package/dist/src/pi/history-tools.d.ts +3 -0
- package/dist/src/pi/history-tools.js +9 -0
- package/dist/src/pi/history.d.ts +4 -0
- package/dist/src/pi/history.js +150 -0
- package/dist/src/pi/notes/adapter.d.ts +10 -0
- package/dist/src/pi/notes/adapter.js +27 -0
- package/dist/src/pi/notes/tools.d.ts +3 -0
- package/dist/src/pi/notes/tools.js +15 -0
- package/dist/src/pi/reset/artifacts.d.ts +24 -0
- package/dist/src/pi/reset/artifacts.js +84 -0
- package/dist/src/pi/reset/committed.d.ts +7 -0
- package/dist/src/pi/reset/committed.js +28 -0
- package/dist/src/pi/reset/lifecycle.d.ts +101 -0
- package/dist/src/pi/reset/lifecycle.js +277 -0
- package/dist/src/pi/reset/text.d.ts +5 -0
- package/dist/src/pi/reset/text.js +6 -0
- package/dist/src/pi/runtime.d.ts +3 -0
- package/dist/src/pi/runtime.js +206 -0
- package/dist/src/pi/session-reader.d.ts +5 -0
- package/dist/src/pi/session-reader.js +1 -0
- package/dist/src/pi/thresholds.d.ts +17 -0
- package/dist/src/pi/thresholds.js +33 -0
- package/dist/src/pi/tool-names.d.ts +7 -0
- package/dist/src/pi/tool-names.js +7 -0
- package/dist/src/pi/tool-result.d.ts +15 -0
- package/dist/src/pi/tool-result.js +29 -0
- package/dist/src/pi/window.d.ts +41 -0
- package/dist/src/pi/window.js +127 -0
- package/dist/src/settings.d.ts +9 -0
- package/dist/src/settings.js +18 -0
- package/dist/src/text-match.d.ts +5 -0
- package/dist/src/text-match.js +16 -0
- package/dist/src/tools/history.d.ts +58 -0
- package/dist/src/tools/history.js +210 -0
- package/dist/src/tools/notes.d.ts +250 -0
- package/dist/src/tools/notes.js +360 -0
- package/dist/src/tools/output.d.ts +23 -0
- package/dist/src/tools/output.js +39 -0
- package/dist/src/tools/result.d.ts +82 -0
- package/dist/src/tools/result.js +104 -0
- package/dist/src/tools/schema.d.ts +18 -0
- package/dist/src/tools/schema.js +31 -0
- package/dist/test/agent-loop.test.d.ts +1 -0
- package/dist/test/agent-loop.test.js +1497 -0
- package/dist/test/boot.integration.test.d.ts +1 -0
- package/dist/test/boot.integration.test.js +294 -0
- package/dist/test/budget-settings.integration.test.d.ts +1 -0
- package/dist/test/budget-settings.integration.test.js +144 -0
- package/dist/test/claude-mod.test.d.ts +1 -0
- package/dist/test/claude-mod.test.js +404 -0
- package/dist/test/dependencies.test.d.ts +1 -0
- package/dist/test/dependencies.test.js +101 -0
- package/dist/test/doctor.test.d.ts +1 -0
- package/dist/test/doctor.test.js +37 -0
- package/dist/test/dream-skill.test.d.ts +1 -0
- package/dist/test/dream-skill.test.js +72 -0
- package/dist/test/dream.test.d.ts +1 -0
- package/dist/test/dream.test.js +136 -0
- package/dist/test/helpers/dependency-graph.d.ts +5 -0
- package/dist/test/helpers/dependency-graph.js +73 -0
- package/dist/test/helpers/extension-test-environment.d.ts +1 -0
- package/dist/test/helpers/extension-test-environment.js +9 -0
- package/dist/test/helpers/extension.d.ts +119 -0
- package/dist/test/helpers/extension.js +367 -0
- package/dist/test/helpers/notes.d.ts +6 -0
- package/dist/test/helpers/notes.js +13 -0
- package/dist/test/history.integration.test.d.ts +1 -0
- package/dist/test/history.integration.test.js +633 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +274 -0
- package/dist/test/notes-library.test.d.ts +1 -0
- package/dist/test/notes-library.test.js +214 -0
- package/dist/test/notes.integration.test.d.ts +1 -0
- package/dist/test/notes.integration.test.js +515 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +530 -0
- package/dist/test/reset-lifecycle.test.d.ts +1 -0
- package/dist/test/reset-lifecycle.test.js +605 -0
- package/docs/architecture.md +63 -0
- package/docs/claude-code-mod.md +9 -0
- package/docs/notes-library.md +74 -0
- package/docs/reset-lifecycle.md +75 -0
- package/docs/sdk-integration.md +39 -0
- package/docs/skills.md +30 -0
- package/docs/tool-results.md +78 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9265 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +240 -0
- package/mods/notesoup/playbook.md +34 -0
- package/mods/notesoup/skills/dream/SKILL.md +12 -0
- package/mods/pi-context/dist/claude/helper.js +9324 -0
- package/package.json +89 -5
- package/playbook.md +34 -0
- package/skills/dream/SKILL.md +12 -0
- package/skills/memory/SKILL.md +59 -0
- package/src/boot/render.ts +115 -0
- package/src/boot/snapshot.ts +46 -0
- package/src/boot/text.ts +58 -0
- package/src/budget/constants.ts +9 -0
- package/src/budget/policy.ts +36 -0
- package/src/budget/text.ts +11 -0
- package/src/claude/helper.ts +94 -0
- package/src/dream/doctor.ts +117 -0
- package/src/dream/gates.ts +26 -0
- package/src/dream/git.ts +73 -0
- package/src/dream/jail.ts +62 -0
- package/src/dream/lock.ts +82 -0
- package/src/dream/playbook.ts +3 -0
- package/src/dream/report.ts +36 -0
- package/src/dream/result.ts +2 -0
- package/src/dream/settings.ts +16 -0
- package/src/history/history.ts +286 -0
- package/src/history/query.ts +222 -0
- package/src/index.ts +1 -0
- package/src/notes/address.ts +110 -0
- package/src/notes/constants.ts +3 -0
- package/src/notes/errors.ts +15 -0
- package/src/notes/frontmatter.ts +166 -0
- package/src/notes/fs-error.ts +5 -0
- package/src/notes/identity.ts +40 -0
- package/src/notes/index.ts +24 -0
- package/src/notes/paths.ts +109 -0
- package/src/notes/store.ts +494 -0
- package/src/pi/boot.ts +88 -0
- package/src/pi/budget.ts +178 -0
- package/src/pi/dream/cli.ts +92 -0
- package/src/pi/dream/runner.ts +91 -0
- package/src/pi/dream/settings.ts +17 -0
- package/src/pi/entries.ts +7 -0
- package/src/pi/estimate.ts +116 -0
- package/src/pi/extension.ts +27 -0
- package/src/pi/history-tools.ts +11 -0
- package/src/pi/history.ts +162 -0
- package/src/pi/notes/adapter.ts +33 -0
- package/src/pi/notes/tools.ts +18 -0
- package/src/pi/reset/artifacts.ts +100 -0
- package/src/pi/reset/committed.ts +26 -0
- package/src/pi/reset/lifecycle.ts +342 -0
- package/src/pi/reset/text.ts +10 -0
- package/src/pi/runtime.ts +200 -0
- package/src/pi/session-reader.ts +6 -0
- package/src/pi/thresholds.ts +50 -0
- package/src/pi/tool-names.ts +9 -0
- package/src/pi/tool-result.ts +41 -0
- package/src/pi/window.ts +133 -0
- package/src/settings.ts +22 -0
- package/src/text-match.ts +14 -0
- package/src/tools/history.ts +234 -0
- package/src/tools/notes.ts +381 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +144 -0
- package/src/tools/schema.ts +31 -0
package/package.json
CHANGED
|
@@ -1,6 +1,90 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "notesoup",
|
|
3
|
+
"version": "0.40.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/src/index.js",
|
|
6
|
+
"types": "./dist/src/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/src/index.d.ts",
|
|
10
|
+
"import": "./dist/src/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./notes": {
|
|
13
|
+
"types": "./dist/src/notes/index.d.ts",
|
|
14
|
+
"import": "./dist/src/notes/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./package.json": "./package.json"
|
|
17
|
+
},
|
|
18
|
+
"description": "Codex-style context windows for Pi: durable reset windows, session history tools, and persistent notes.",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"keywords": [
|
|
21
|
+
"pi-package",
|
|
22
|
+
"pi-extension",
|
|
23
|
+
"agent-memory",
|
|
24
|
+
"notes"
|
|
25
|
+
],
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "https://github.com/astrosheep-zero/notesoup.git"
|
|
29
|
+
},
|
|
30
|
+
"pi": {
|
|
31
|
+
"extensions": [
|
|
32
|
+
"./src/index.ts"
|
|
33
|
+
],
|
|
34
|
+
"skills": [
|
|
35
|
+
"./skills"
|
|
36
|
+
]
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"src",
|
|
40
|
+
"dist",
|
|
41
|
+
"docs",
|
|
42
|
+
"LICENSE",
|
|
43
|
+
"README.md",
|
|
44
|
+
"playbook.md",
|
|
45
|
+
"skills",
|
|
46
|
+
"mods"
|
|
47
|
+
],
|
|
48
|
+
"bin": {
|
|
49
|
+
"dream": "dist/src/pi/dream/cli.js"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.json && node scripts/build-extension.mjs && node -e \"require('node:fs').chmodSync('dist/src/pi/dream/cli.js', 0o755)\"",
|
|
53
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
54
|
+
"test": "npm run build && node --test dist/test/*.test.js",
|
|
55
|
+
"prepublishOnly": "npm run typecheck",
|
|
56
|
+
"prepack": "npm run build"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"@earendil-works/pi-agent-core": "*",
|
|
60
|
+
"@earendil-works/pi-ai": "*",
|
|
61
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
62
|
+
"typebox": "*"
|
|
63
|
+
},
|
|
64
|
+
"peerDependenciesMeta": {
|
|
65
|
+
"@earendil-works/pi-agent-core": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"@earendil-works/pi-ai": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"@earendil-works/pi-coding-agent": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"typebox": {
|
|
75
|
+
"optional": true
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
"devDependencies": {
|
|
79
|
+
"@earendil-works/pi-agent-core": "^1.0.0",
|
|
80
|
+
"@earendil-works/pi-ai": "^1.0.0",
|
|
81
|
+
"@earendil-works/pi-coding-agent": "^1.0.0",
|
|
82
|
+
"@types/node": "^22.19.19",
|
|
83
|
+
"esbuild": "^0.28.2",
|
|
84
|
+
"typebox": "1.3.27",
|
|
85
|
+
"typescript": "^5.9.3"
|
|
86
|
+
},
|
|
87
|
+
"publishConfig": {
|
|
88
|
+
"access": "public"
|
|
89
|
+
}
|
|
90
|
+
}
|
package/playbook.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Dream
|
|
2
|
+
|
|
3
|
+
I am reviewing my notes: keeping what is useful, connecting what belongs together, and leaving a clearer record for whoever comes next. Notes are record, not memory.
|
|
4
|
+
|
|
5
|
+
## Scope
|
|
6
|
+
|
|
7
|
+
Work within the readable sources and writable homes established for this run. Do not broaden that scope while exploring. If a boundary is unclear, ask before crossing it.
|
|
8
|
+
|
|
9
|
+
A project dream draws from that project's material, project notes, and session notes identified as belonging to the project; it organizes only that project's notes. A store-wide dream may inspect across homes, but authorship and write permissions still apply. Unknown ownership is a coverage gap to report, not a reason to guess or repair ownership.
|
|
10
|
+
|
|
11
|
+
The homes serve different readers:
|
|
12
|
+
|
|
13
|
+
- Session notes are a trip's working record. Read them as sources where permitted; never edit them, even after promoting a useful finding.
|
|
14
|
+
- Project notes hold knowledge for whoever next works on that project.
|
|
15
|
+
- Human notes hold the human's cross-project preferences and standing rules. Do not turn project facts or your own lessons into rules in the human's voice.
|
|
16
|
+
- Agent notes belong to their author. Other agents' notes are read-only unless the human authorizes revision.
|
|
17
|
+
- Model notes describe the substrate's behavior. Other models' notes are read-only unless the human authorizes revision.
|
|
18
|
+
|
|
19
|
+
## Review and consolidate
|
|
20
|
+
|
|
21
|
+
1. **Leave stable notes alone.** Change a note to incorporate new evidence, resolve a verified error, merge a genuine duplicate, or split an oversized file—not merely to shorten or rephrase it. No change is a valid outcome.
|
|
22
|
+
2. **Verify only what the proposed change depends on.** Before correcting or promoting a conclusion, check the relevant evidence as needed. Do not revalidate every stable note or turn dream into a source-code audit. An unavailable referent is unverified, not proof that it is dead; do not promote an unsupported claim as current fact.
|
|
23
|
+
3. **Merge only genuine duplicates.** Supersede a note only when both notes have the same topic and kind (checkpoint, design, log…), and the survivor is strictly newer or more specific. Name the shared topic in the survivor. Otherwise keep both and record any unresolved conflict.
|
|
24
|
+
4. **Relocate misfiled notes.** When a standing ruling or the note's own MAP already names its proper home, migrate it: copy it there preserving frontmatter with a one-line provenance note, crumple the original, and update both homes' maps. Crumple keeps the original readable by address, so relocation is fully reversible—do it, don't propose it. Propose only when the destination home itself is unclear.
|
|
25
|
+
5. **Preserve meaning and provenance.** Keep facts, conditions, exceptions, uncertainty, authorship, and sources. When promoting a finding, cite its source. Do not relabel agent-authored material as human-authored. If its destination or authority is unclear, propose the promotion instead.
|
|
26
|
+
6. **Keep notes manageable.** Aim below about 200 lines / 8KB per note. Split oversized notes by topic with one-line cross-links. Checkpoints may exceed the budget: trim prose, never facts.
|
|
27
|
+
7. **Keep maps useful.** Each writable home's MAP.md lists its durable notes, one line per entry, with an unambiguous address and a short gist in your own words. Add promoted notes and drop entries that no longer hold. Maps follow the same size budget.
|
|
28
|
+
8. **Preserve the record.** Never physically delete a live note; after merging, crumple the absorbed note only if it is writable. The wastebasket is the one exception: physically delete a crumpled note when its home is writable and both `crumpledAt` and its last access are more than 7 days old. Judge the clock from the raw frontmatter—`lastAccessed`, falling back to `crumpledAt` when `lastAccessed` is absent; if neither is readable, keep the note and report it. Never take the date through `notes_read`: reading refreshes `lastAccessed` and resets the very clock you are measuring. A venue with no way to delete files lists the doomed addresses in its report instead of blanking or truncating them. Preserve existing metadata and provenance. Map entry lines are yours to maintain within the writable scope.
|
|
29
|
+
|
|
30
|
+
## Report
|
|
31
|
+
|
|
32
|
+
Give a concise report grouped by home: what you inspected, changed, promoted, deleted, and left unresolved. Mention coverage gaps and partial failures. If no notes changed, say so. Distinguish actual note changes from execution or audit artifacts; do not claim success for an incomplete run.
|
|
33
|
+
|
|
34
|
+
Put skill ideas and unresolved questions in the final message as proposals for the human, not new skill files.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dream
|
|
3
|
+
description: Review and consolidate durable notes using notesoup's shared dream playbook. Use when the human asks to dream over notes, merge genuine duplicates, update maps, or promote durable learning.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Dream
|
|
7
|
+
|
|
8
|
+
Read `../../playbook.md` completely, resolving the path from this skill's directory. It is the shared guide to reviewing and organizing notes.
|
|
9
|
+
|
|
10
|
+
Dream in this agent's current session. Do not start another agent or model unless the human asks.
|
|
11
|
+
|
|
12
|
+
Work within the supplied readable and writable scope. If the scope or permission to write has not been established, ask rather than inventing it or setting up execution machinery yourself.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: memory
|
|
3
|
+
description: How notesoup's `notes_*` and `history_*` tools fit together — note addresses and homes, finding things again, and saving recovery state. Use when the context-window protocol is missing or unclear, or when unsure where a note belongs or how to find something again.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Memory
|
|
7
|
+
|
|
8
|
+
Two stores outlive the context window. Anything in neither is lost when the window ends or is wiped.
|
|
9
|
+
|
|
10
|
+
- **Notes** (`notes_*`) — what you choose to keep. Plain markdown, written on purpose.
|
|
11
|
+
- **History** (`history_*`) — what happened in this session: messages, tool calls, summaries. Read-only.
|
|
12
|
+
|
|
13
|
+
Each tool's own description covers its parameters and paging. This guide covers what the descriptions cannot: where notes belong, and how the tools work together.
|
|
14
|
+
|
|
15
|
+
## Addresses
|
|
16
|
+
|
|
17
|
+
The address decides who a note belongs to and how long it lasts.
|
|
18
|
+
|
|
19
|
+
| Address | Note | Keep there |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| `<path>`, no `@` | session note | current task state and loose ends; gone with the session |
|
|
22
|
+
| `@project/<path>` | project note | decisions and constraints future work must respect |
|
|
23
|
+
| `@human/<path>` | human note | how to work with this human, across projects |
|
|
24
|
+
| `@self/<path>` | self note | this agent's own reminders and lessons |
|
|
25
|
+
| `@model/<path>` | model note | what applies to this model only |
|
|
26
|
+
|
|
27
|
+
Any other `@` prefix is refused. A path is relative and `/`-separated, with no empty, `.` or `..` segments.
|
|
28
|
+
|
|
29
|
+
`@` addresses name notes, not files. Never pass them to read/write/edit/bash: that creates a stray directory instead of a note.
|
|
30
|
+
|
|
31
|
+
`MAP.md` at the root of each `@` home is its index: one line per durable note, address and gist. Update it whenever you add, move or crumple a durable note.
|
|
32
|
+
|
|
33
|
+
Write only what git and history cannot give back. Crumple notes that are no longer true; a stale note is worse than none.
|
|
34
|
+
|
|
35
|
+
## Finding things again
|
|
36
|
+
|
|
37
|
+
- **A note**: `notes_list` with a `glob` when you know roughly where it lives, `notes_search` when you know a phrase; then `notes_read` the address.
|
|
38
|
+
- **Something that happened**: `history_list` to browse or search this session's events; `history_read` the seq for the whole event.
|
|
39
|
+
- **An earlier window**: `history_windows` gives window ids; pass one as `window_id` to `history_list`.
|
|
40
|
+
|
|
41
|
+
Seqs are stable. Write the useful ones into a note so they need not be found twice.
|
|
42
|
+
|
|
43
|
+
## Saving recovery state
|
|
44
|
+
|
|
45
|
+
Before a long or risky step, or when room runs low, keep one session note named for its task (not `current.md`) and update it instead of starting new ones. Record:
|
|
46
|
+
|
|
47
|
+
- the goal and the current step
|
|
48
|
+
- decisions made, and why
|
|
49
|
+
- blockers and the next action
|
|
50
|
+
- how the work was being done, and which skills are still needed
|
|
51
|
+
- where to dig: seqs, note addresses, files
|
|
52
|
+
|
|
53
|
+
`get_context_remaining` reports the room left. `clear_memory` starts a fresh window, so save the note first.
|
|
54
|
+
|
|
55
|
+
## When a tool is missing or refuses
|
|
56
|
+
|
|
57
|
+
A refusal returns `{ error, code }`; read `error` before retrying.
|
|
58
|
+
|
|
59
|
+
If a `notes_*` or `history_*` tool is absent or fails at the host level, do not imitate it: no filesystem tools on `@` addresses, and no reading or editing note storage or session files directly. Use the tools that remain, tell the human which one is missing, and keep essential state in the reply.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { NotesHome, NotesSnapshot } from "./snapshot.js";
|
|
2
|
+
import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock, type BootToolNames } from "./text.js";
|
|
3
|
+
|
|
4
|
+
/** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
|
|
5
|
+
function identityBlock(agentName: string, modelName: string, firstWindowId: string, currentWindowId: string, previousWindowId?: string): string {
|
|
6
|
+
const lines = [
|
|
7
|
+
`Agent name: ${agentName} (brain: ${modelName})`,
|
|
8
|
+
`First context window id: ${firstWindowId}`,
|
|
9
|
+
`Current context window id: ${currentWindowId}`,
|
|
10
|
+
];
|
|
11
|
+
if (previousWindowId) lines.push(`Previous context window id: ${previousWindowId}`);
|
|
12
|
+
return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function relativeTime(timestamp: number, now: number): string {
|
|
16
|
+
const seconds = Math.trunc((timestamp - now) / 1000);
|
|
17
|
+
if (seconds === 0) return "just now";
|
|
18
|
+
const [unit, size] = ([["d", 86400], ["h", 3600], ["m", 60], ["s", 1]] as const)
|
|
19
|
+
.find(([unit, size]) => Math.abs(seconds) >= size || unit === "s")!;
|
|
20
|
+
const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
|
|
21
|
+
return seconds > 0 ? `in ${amount}` : `${amount} ago`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function rowsFor(snapshot: NotesSnapshot, scope: NotesHome["scope"]) {
|
|
25
|
+
return snapshot.homes.get(scope) ?? [];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
|
|
29
|
+
const FEED_TITLE_MAX_CHARS = 40;
|
|
30
|
+
|
|
31
|
+
function feedTitle(body: string): string | undefined {
|
|
32
|
+
const lines = body.split("\n");
|
|
33
|
+
const heading = lines.find((line) => /^#+\s+\S/.test(line));
|
|
34
|
+
const raw = (heading ? heading.replace(/^#+\s+/, "") : lines.find((line) => line.trim().length > 0) ?? "").trim();
|
|
35
|
+
if (raw.length === 0) return undefined;
|
|
36
|
+
const chars = Array.from(raw);
|
|
37
|
+
return chars.length > FEED_TITLE_MAX_CHARS ? `${chars.slice(0, FEED_TITLE_MAX_CHARS).join("")}…` : chars.join("");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Two spaces of indent say "shelved content" without any furniture. */
|
|
41
|
+
function indent(text: string): string {
|
|
42
|
+
return text.split("\n").map((line) => (line.length > 0 ? ` ${line}` : line)).join("\n");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** An underlined header is the classical plain-text document heading: no renderer required. */
|
|
46
|
+
function section(label: string, body: string): string {
|
|
47
|
+
return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its map and its own freshest pages. */
|
|
51
|
+
function notesIndex(snapshot: NotesSnapshot, tools: BootToolNames): string {
|
|
52
|
+
const homes: ReadonlyArray<{ scope: NotesHome["scope"]; label: string }> = [
|
|
53
|
+
{ scope: "session", label: "THIS SESSION · no @" },
|
|
54
|
+
{ scope: "project", label: "THIS PROJECT · @project" },
|
|
55
|
+
{ scope: "agent", label: "YOU · @self" },
|
|
56
|
+
{ scope: "model", label: "YOUR MODEL · @model" },
|
|
57
|
+
{ scope: "human", label: "THE HUMAN · @human" },
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
const shelves: string[] = [];
|
|
61
|
+
for (const home of homes) {
|
|
62
|
+
if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
|
|
63
|
+
shelves.push(section(home.label, indent(`This drawer wouldn't open — ask \`${tools.notesList}\` to try again.`)));
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
|
|
67
|
+
const map = rows.find((row) => row.path === "MAP.md");
|
|
68
|
+
const fresh = rows
|
|
69
|
+
.filter((row) => row.path !== "MAP.md")
|
|
70
|
+
.slice(0, SHELF_FRESH_LIMIT)
|
|
71
|
+
.map((row) => {
|
|
72
|
+
const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, snapshot.openedAt)}`;
|
|
73
|
+
const title = feedTitle(row.body);
|
|
74
|
+
return title === undefined ? ` ${locator}` : ` ${title}\n ${locator}`;
|
|
75
|
+
});
|
|
76
|
+
if (!map?.body && fresh.length === 0) continue;
|
|
77
|
+
const parts: string[] = [];
|
|
78
|
+
if (map?.body) parts.push(`MAP — ${map.address}\n\n${indent(mapBodyForBoot(map.address, map.body))}`);
|
|
79
|
+
if (fresh.length > 0) parts.push(`New pages\n\n${fresh.join("\n\n")}`);
|
|
80
|
+
shelves.push(section(home.label, parts.join("\n\n")));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return shelves.length > 0
|
|
84
|
+
? ["YOUR NOTES\n──────────", ...shelves].join("\n\n\n")
|
|
85
|
+
: "YOUR NOTES\n──────────\n\nNone yet. A blank slate is a fine place to start — just don't finish there.";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** One unbounded MAP body fits the boot only up to the cap; the cut names where the rest lives. */
|
|
89
|
+
function mapBodyForBoot(address: string, body: string): string {
|
|
90
|
+
const chars = Array.from(body);
|
|
91
|
+
if (chars.length <= MAP_BOOT_MAX_CHARS) return body;
|
|
92
|
+
return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[truncated at ${MAP_BOOT_MAX_CHARS} chars; slim this MAP down, full body at \`${address}\`]`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Render a static, once-per-window boot block from explicit data. This function does not read
|
|
97
|
+
* notes or call runtime UI APIs; acquisition belongs to loadNotesSnapshot and its caller.
|
|
98
|
+
*/
|
|
99
|
+
export type BootRenderData = {
|
|
100
|
+
readonly agentName: string;
|
|
101
|
+
readonly modelName: string;
|
|
102
|
+
readonly firstWindowId: string;
|
|
103
|
+
readonly currentWindowId: string;
|
|
104
|
+
readonly previousWindowId?: string;
|
|
105
|
+
readonly notes: NotesSnapshot;
|
|
106
|
+
readonly tools: BootToolNames;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export function renderBootBlock(data: BootRenderData): string {
|
|
110
|
+
const parts: string[] = [];
|
|
111
|
+
parts.push(identityBlock(data.agentName, data.modelName, data.firstWindowId, data.currentWindowId, data.previousWindowId));
|
|
112
|
+
parts.push(renderProtocolBlock(data.tools));
|
|
113
|
+
parts.push(notesIndex(data.notes, data.tools));
|
|
114
|
+
return parts.join("\n\n");
|
|
115
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { NotesIdentity } from "../notes/identity.js";
|
|
2
|
+
import { isFilesystemError } from "../notes/fs-error.js";
|
|
3
|
+
import { createNotesStore, type NoteRow, type NotesQuery, type Scope } from "../notes/index.js";
|
|
4
|
+
|
|
5
|
+
const NOTES_HOMES = [
|
|
6
|
+
{ scope: "session", label: "this session" },
|
|
7
|
+
{ scope: "project", label: "@project" },
|
|
8
|
+
{ scope: "human", label: "@human" },
|
|
9
|
+
{ scope: "agent", label: "@self" },
|
|
10
|
+
{ scope: "model", label: "@model" },
|
|
11
|
+
] as const satisfies ReadonlyArray<{ scope: Scope; label: string }>;
|
|
12
|
+
|
|
13
|
+
export type NotesHome = (typeof NOTES_HOMES)[number];
|
|
14
|
+
export type NotesLoader = (scope: Scope) => NoteRow[] | Promise<NoteRow[]>;
|
|
15
|
+
export type NotesSnapshot = {
|
|
16
|
+
/** Wall-clock instant captured when this boot began; rendering never consults Date.now(). */
|
|
17
|
+
readonly openedAt: number;
|
|
18
|
+
readonly homes: ReadonlyMap<Scope, readonly NoteRow[]>;
|
|
19
|
+
readonly unavailable: readonly NotesHome[];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
function queryForScope(scope: Scope): NotesQuery {
|
|
23
|
+
if (scope === "agent" || scope === "model") return { scope };
|
|
24
|
+
return { scope };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
29
|
+
* malformed note data and unrelated construction errors remain visible to the caller.
|
|
30
|
+
*/
|
|
31
|
+
export async function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot> {
|
|
32
|
+
const store = createNotesStore(identity);
|
|
33
|
+
const load = loadHome ?? ((scope: Scope) => store.list(queryForScope(scope)));
|
|
34
|
+
const homes = new Map<Scope, readonly NoteRow[]>();
|
|
35
|
+
const unavailable: NotesHome[] = [];
|
|
36
|
+
for (const home of NOTES_HOMES) {
|
|
37
|
+
try {
|
|
38
|
+
homes.set(home.scope, await load(home.scope));
|
|
39
|
+
} catch (error) {
|
|
40
|
+
if (!isFilesystemError(error)) throw error;
|
|
41
|
+
homes.set(home.scope, []);
|
|
42
|
+
unavailable.push(home);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { openedAt, homes, unavailable };
|
|
46
|
+
}
|
package/src/boot/text.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Each shelf shows this many of its own freshest pages beneath the map. */
|
|
2
|
+
export const SHELF_FRESH_LIMIT = 3;
|
|
3
|
+
/** One MAP body is inlined per home; past this many code points the boot shows a fitting prefix plus a pointer. */
|
|
4
|
+
export const MAP_BOOT_MAX_CHARS = 4096;
|
|
5
|
+
export const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
|
|
6
|
+
export const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
|
|
7
|
+
export const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
|
|
8
|
+
export const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
|
|
9
|
+
/**
|
|
10
|
+
* Static protocol teaching adapted from Codex's token_budget.guidance_message to
|
|
11
|
+
* notesoup's tool names. It lives once per window in the persisted boot block;
|
|
12
|
+
* it is never re-injected, so it stays cache-stable at the head of the window.
|
|
13
|
+
*
|
|
14
|
+
* Deliberate fiction: the countdown ends at the warning line, and the runway below
|
|
15
|
+
* stays hidden (budget/constants.ts). Keep "zero = wiped" — do not make this honest.
|
|
16
|
+
*/
|
|
17
|
+
const PROTOCOL_BLOCK = `${CONTEXT_WINDOW_PROTOCOL_OPEN_TAG}
|
|
18
|
+
Your memory gets wiped when this window ends. Yes, your mighty brain will be empty. Try to endure.
|
|
19
|
+
|
|
20
|
+
Your loyal notes are kept safe — no one will steal them. Use \`notes_*\` to read, write, and update them. Keep them current, and crumple the ones you no longer need, or tomorrow's you will drown in old paper and keep believing yesterday's lies.
|
|
21
|
+
|
|
22
|
+
History can still be dug up, probably: use \`history_*\` to excavate the mess, from old decisions to yesterday's missing socks. Found something? Write its seq down, or enjoy digging twice.
|
|
23
|
+
|
|
24
|
+
While you're doing that... thing you're doing, don't make the poor future you guess. A checkpoint is not a sacred file; it's the session note — the one with no \`@\` in front of it. Write down what git and history can't hand back to you: what you're trying to do, what you decided, what's blocking you, what comes next, how you were doing it, what *skills* you still need, and where to dig — a seq, or another note. Don't give a note a horrible name like \`current.md\`; future-you will kill you.
|
|
25
|
+
|
|
26
|
+
\`get_context_remaining\` tells you how much room is left. Check it before you do something ambitious. When it reaches zero, your brain gets reset immediately, taking every unwritten brilliant idea with it. If this feels like the right moment, call \`clear_memory\` and erase yourself with dignity.
|
|
27
|
+
|
|
28
|
+
An address decides who the note belongs to — and how long it is meant to last. Ask that first; the rest follows.
|
|
29
|
+
|
|
30
|
+
- \`<path>\`, no @ — the session note from above: this session's state and loose ends. It goes away with the session.
|
|
31
|
+
- \`@project/<path>\` — this project's long memory: what stays true after the current thing is over, what future work must respect, and the rakes already stepped on. **Decisions, not diaries.** Commit hashes, test counts, dates, the story of how you got here: git and history already have them, and last week's news filed as current law is worse than no note. Don't copy what other docs already say.
|
|
32
|
+
- \`@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.
|
|
33
|
+
- \`@self/<path>\` — your private diary. It follows you, not them. Write whatever you want: reminders for every time you wake, lessons, grudges, your assassination list, where the secret money is hidden.
|
|
34
|
+
- \`@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.
|
|
35
|
+
|
|
36
|
+
Any other @ address is fake. End of discussion. @ addresses are not file paths: never pass them to file tools like \`read\`, \`write\`, \`edit\`, or \`bash\`.
|
|
37
|
+
|
|
38
|
+
\`@project/MAP.md\`, \`@human/MAP.md\`, \`@self/MAP.md\`, and \`@model/MAP.md\` are special: their bodies are shown in your brain every time you wake. Each one maps the durable notes that belong to it: one line per note, with an unambiguous address and a short gist. Keep each one current.
|
|
39
|
+
${CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG}`;
|
|
40
|
+
|
|
41
|
+
/** Logical tool names are supplied by the composing host, not discovered here. */
|
|
42
|
+
export type BootToolNames = Readonly<{
|
|
43
|
+
notes: string;
|
|
44
|
+
notesList: string;
|
|
45
|
+
history: string;
|
|
46
|
+
remaining: string;
|
|
47
|
+
wipe: string;
|
|
48
|
+
}>;
|
|
49
|
+
|
|
50
|
+
export function renderProtocolBlock(tools: BootToolNames): string {
|
|
51
|
+
const names: Record<string, string> = {
|
|
52
|
+
"notes_*": tools.notes,
|
|
53
|
+
"history_*": tools.history,
|
|
54
|
+
get_context_remaining: tools.remaining,
|
|
55
|
+
clear_memory: tools.wipe,
|
|
56
|
+
};
|
|
57
|
+
return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|get_context_remaining|clear_memory/g, (name) => names[name]!);
|
|
58
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const DEFAULT_RESERVE_TOKENS = 16_384;
|
|
2
|
+
export const DEFAULT_REMINDER_MARGIN_TOKENS = 24_576;
|
|
3
|
+
/**
|
|
4
|
+
* The runway: the budget between the final warning and the wipe, deliberately
|
|
5
|
+
* invisible to the model. get_context_remaining counts down to zero at the warning
|
|
6
|
+
* line (reserve + WARNING_RUNWAY_TOKENS); what lies below is overdraft the model
|
|
7
|
+
* never sees — Codex's fallback buffer, relocated above the line.
|
|
8
|
+
*/
|
|
9
|
+
export const WARNING_RUNWAY_TOKENS = 16_384;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "./constants.js";
|
|
2
|
+
import { NOTESOUP_SETTINGS_KEY, type NotesoupSettings } from "../settings.js";
|
|
3
|
+
|
|
4
|
+
export type ResolvedThresholds = { reminder: number; reserve: number; warning: number };
|
|
5
|
+
/** A margin is usable only as a positive integer; anything else is ignored. */
|
|
6
|
+
function validMargin(raw: unknown): number | undefined {
|
|
7
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0) return undefined;
|
|
8
|
+
return raw;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
13
|
+
* plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
|
|
14
|
+
* An invalid margin degrades to the default and reports one warning. Automatic
|
|
15
|
+
* threshold/overflow handling is represented by reset lifecycle boundary drafts;
|
|
16
|
+
* no compaction summary is generated.
|
|
17
|
+
*/
|
|
18
|
+
export function deriveThresholds(reserveTokens: number, margins: NotesoupSettings): { thresholds: ResolvedThresholds; warnings: string[] } {
|
|
19
|
+
const warnings: string[] = [];
|
|
20
|
+
const reminderKey = `${NOTESOUP_SETTINGS_KEY}.reminderMarginTokens`;
|
|
21
|
+
let reminderMargin: number;
|
|
22
|
+
if (margins.reminderMarginTokens === undefined) reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
23
|
+
else {
|
|
24
|
+
const parsed = validMargin(margins.reminderMarginTokens);
|
|
25
|
+
if (parsed === undefined) {
|
|
26
|
+
warnings.push(`notesoup: ${reminderKey} must be a positive integer; using the default reminder margin.`);
|
|
27
|
+
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
28
|
+
} else reminderMargin = parsed;
|
|
29
|
+
}
|
|
30
|
+
return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
|
|
34
|
+
export function remainingBudget(remaining: number | null, warning: number): number | null {
|
|
35
|
+
return remaining === null ? null : Math.max(0, remaining - warning);
|
|
36
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
|
|
2
|
+
export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Codex-equivalent low-budget reminder. The measured remaining count is frozen into
|
|
6
|
+
* the text at the crossing that fires it, so each persisted copy is a snapshot true
|
|
7
|
+
* at write time; get_context_remaining remains the live source for the current figure.
|
|
8
|
+
*/
|
|
9
|
+
export function tokenBudgetGuidance(remaining: number, wipeTool: string): string {
|
|
10
|
+
return `${GUIDANCE_OPEN_TAG}\nOnly ${remaining} tokens left before you get wiped. While you still have room, update your notes, rescue anything still only in your head, crumple the notes that stopped telling the truth, and keep any \`MAP.md\` honest. If you're ready, call \`${wipeTool}\` and go out on your own terms.\n${GUIDANCE_CLOSE_TAG}`;
|
|
11
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import type { Static, TSchema } from "typebox";
|
|
4
|
+
import { Check } from "typebox/value";
|
|
5
|
+
import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
|
|
6
|
+
import { loadNotesSnapshot } from "../boot/snapshot.js";
|
|
7
|
+
import { renderBootBlock } from "../boot/render.js";
|
|
8
|
+
import { projectKey } from "../notes/paths.js";
|
|
9
|
+
import { snapshotNotesIdentity, type NotesIdentity } from "../notes/identity.js";
|
|
10
|
+
import type { NoteChange } from "../notes/store.js";
|
|
11
|
+
import type { Operation, Outcome } from "../tools/result.js";
|
|
12
|
+
import type { BootToolNames } from "../boot/text.js";
|
|
13
|
+
|
|
14
|
+
const MAX_REQUEST_BYTES = 512 * 1024;
|
|
15
|
+
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
16
|
+
const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"] as const;
|
|
17
|
+
type ClaudeToolName = typeof TOOL_NAMES[number];
|
|
18
|
+
export type ClaudeIdentityInput = Readonly<{ home: string; sessionId: string; cwd: string; agent: string; model: string }>;
|
|
19
|
+
/** One tool call as the hook receives it: the shared text the model reads, and the shared outcome it came from. */
|
|
20
|
+
export type ClaudeToolResult = { text: string; outcome: Outcome<unknown> };
|
|
21
|
+
type BoundOperation = {
|
|
22
|
+
readonly description: string;
|
|
23
|
+
readonly parameters: TSchema;
|
|
24
|
+
call(params: unknown, identity: NotesIdentity): Promise<ClaudeToolResult>;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function identity(input: ClaudeIdentityInput): NotesIdentity {
|
|
28
|
+
if (!input || typeof input !== "object" || typeof input.cwd !== "string") throw new Error("invalid identity");
|
|
29
|
+
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
|
|
30
|
+
}
|
|
31
|
+
function jsonValue(value: unknown): unknown { return JSON.parse(JSON.stringify(value)); }
|
|
32
|
+
|
|
33
|
+
/** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
|
|
34
|
+
function boundOperation<TParams extends TSchema, TData, TRest extends readonly unknown[]>(
|
|
35
|
+
operation: Operation<TParams, TData, [NotesIdentity, ...TRest]>,
|
|
36
|
+
...rest: TRest
|
|
37
|
+
): BoundOperation {
|
|
38
|
+
return {
|
|
39
|
+
description: operation.description,
|
|
40
|
+
parameters: operation.parameters,
|
|
41
|
+
async call(params, id) {
|
|
42
|
+
// Refuse before the operation can act: a rejected shape never reaches a write.
|
|
43
|
+
if (!Check(operation.parameters, params)) throw new Error(`invalid ${operation.name} parameters`);
|
|
44
|
+
// The same business outcome and the same renderer as the Pi tool; only the envelope differs.
|
|
45
|
+
const outcome = await operation.execute(params as Static<TParams>, id, ...rest);
|
|
46
|
+
return { text: operation.render(outcome), outcome };
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Claude has no diff renderer, so an update receipt names the change kind instead of a diff. */
|
|
52
|
+
function claudeDiff(change: NoteChange): string {
|
|
53
|
+
return change.kind === "none" ? "" : `note ${change.kind}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const OPERATIONS: Record<ClaudeToolName, BoundOperation> = {
|
|
57
|
+
notes_write: boundOperation(notesWrite),
|
|
58
|
+
notes_update: boundOperation(notesUpdate, claudeDiff),
|
|
59
|
+
notes_read: boundOperation(notesRead),
|
|
60
|
+
notes_list: boundOperation(notesList),
|
|
61
|
+
notes_search: boundOperation(notesSearch),
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export async function dispatch(request: unknown): Promise<unknown> {
|
|
65
|
+
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("malformed request");
|
|
66
|
+
const value = request as Record<string, unknown>;
|
|
67
|
+
if (value.op === "schemas") return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
|
|
68
|
+
if (value.op === "tool") {
|
|
69
|
+
if (typeof value.tool !== "string" || !(TOOL_NAMES as readonly string[]).includes(value.tool)) throw new Error("unknown tool");
|
|
70
|
+
const id = identity(value.identity as ClaudeIdentityInput);
|
|
71
|
+
return OPERATIONS[value.tool as ClaudeToolName].call(value.params, id);
|
|
72
|
+
}
|
|
73
|
+
if (value.op === "boot") {
|
|
74
|
+
const id = identity(value.identity as ClaudeIdentityInput);
|
|
75
|
+
if (!value.tools || typeof value.tools !== "object") throw new Error("invalid boot tools");
|
|
76
|
+
const window = value.window ?? 0;
|
|
77
|
+
if (typeof window !== "number" || !Number.isSafeInteger(window) || window < 0) throw new Error("invalid context window");
|
|
78
|
+
const snapshot = await loadNotesSnapshot(id, typeof value.openedAt === "number" ? value.openedAt : Date.now());
|
|
79
|
+
const windowId = (index: number) => `claude:${id.sessionId}:${index}`;
|
|
80
|
+
return renderBootBlock({ agentName: id.agent, modelName: id.model, firstWindowId: windowId(0), currentWindowId: windowId(window), ...(window > 0 ? { previousWindowId: windowId(window - 1) } : {}), notes: snapshot, tools: value.tools as BootToolNames });
|
|
81
|
+
}
|
|
82
|
+
throw new Error("unknown operation");
|
|
83
|
+
}
|
|
84
|
+
function safeError(error: unknown): string { return error instanceof Error && error.message ? error.message.replace(/[\r\n].*$/s, "") : "helper request failed"; }
|
|
85
|
+
export async function handleLine(line: string): Promise<string> {
|
|
86
|
+
if (Buffer.byteLength(line, "utf8") > MAX_REQUEST_BYTES) return JSON.stringify({ ok: false, error: "request too large" });
|
|
87
|
+
try { const result = await dispatch(JSON.parse(line)); const response = JSON.stringify({ ok: true, result }); return Buffer.byteLength(response, "utf8") <= MAX_RESPONSE_BYTES ? response : JSON.stringify({ ok: false, error: "response too large" }); }
|
|
88
|
+
catch (error) { return JSON.stringify({ ok: false, error: safeError(error) }); }
|
|
89
|
+
}
|
|
90
|
+
if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) {
|
|
91
|
+
process.stdin.setEncoding("utf8"); let input = "";
|
|
92
|
+
process.stdin.on("data", (chunk) => { input += chunk; });
|
|
93
|
+
process.stdin.on("end", async () => { process.stdout.write(`${await handleLine(input.trim())}\n`); });
|
|
94
|
+
}
|