notesoup 0.0.0-stage → 0.39.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 +91 -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 +21 -0
- package/dist/src/boot/text.js +52 -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 +151 -0
- package/dist/src/history/history.js +195 -0
- package/dist/src/history/query.d.ts +75 -0
- package/dist/src/history/query.js +143 -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 +104 -0
- package/dist/src/notes/store.js +478 -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 +10 -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 +11 -0
- package/dist/src/pi/tool-names.js +11 -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 +67 -0
- package/dist/src/tools/history.js +251 -0
- package/dist/src/tools/notes.d.ts +282 -0
- package/dist/src/tools/notes.js +378 -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 +79 -0
- package/dist/src/tools/result.js +130 -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 +368 -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 +556 -0
- package/dist/test/host-neutral.test.d.ts +1 -0
- package/dist/test/host-neutral.test.js +300 -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 +497 -0
- package/dist/test/notes.test.d.ts +1 -0
- package/dist/test/notes.test.js +528 -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 +88 -0
- package/mods/notesoup/.claude-plugin/plugin.json +8 -0
- package/mods/notesoup/dist/claude/helper.js +9324 -0
- package/mods/notesoup/hooks/hooks.json +4 -0
- package/mods/notesoup/hooks/register.ts +241 -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 +66 -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 +270 -0
- package/src/history/query.ts +147 -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 +497 -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 +12 -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 +13 -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 +273 -0
- package/src/tools/notes.ts +394 -0
- package/src/tools/output.ts +41 -0
- package/src/tools/result.ts +169 -0
- package/src/tools/schema.ts +31 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 astrosheep-zero
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# notesoup
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Your agent's memory gets wiped when the context fills. notesoup makes that survivable: the agent writes itself a checkpoint before the wipe, wakes up in a fresh window, and digs up whatever it still needs from the old conversation. For you it's mostly invisible — an occasional notification, `/clear-memory` to force a fresh window, `/notesoup` to toggle.
|
|
4
|
+
|
|
5
|
+
The architecture — durable context windows, model-authored notes, searchable history — is the one OpenAI prototyped in Codex's `context_management` experiment and switched off ten days later, because it was welded to their backend. notesoup is the same architecture running entirely on your machine, built only on [Pi](https://github.com/earendil-works/pi)'s public extension APIs. No backend, no subscription gate, no server that can 404 at the worst possible moment. It can't be switched off from far away, because there is no far away.
|
|
6
|
+
|
|
7
|
+
## Renamed from pi-context
|
|
8
|
+
|
|
9
|
+
The old name is retired: `@astrosheep/pi-context` is deprecated, and the package is now `notesoup`. The settings key renamed from `pi-context` to `notesoup`, and the Claude Code Mod's MCP tool prefix renamed from `mcp__pi-context__` to `mcp__notesoup__` (reinstall the mod). Old notes data is unaffected.
|
|
10
|
+
|
|
11
|
+
## Why not just compaction?
|
|
12
|
+
|
|
13
|
+
- **Reset ≠ summary.** Compaction is lossy compression you sit and wait for — and the next one summarizes the summary of the summary. A notesoup reset summarizes *nothing*: the window closes in O(1), because whatever mattered was already written to notes beforehand. Fast because there's nothing to compute; safe because the raw history never leaves disk.
|
|
14
|
+
- **Notes are files you can open.** Plain Markdown in `~/.agents/notes`, in named homes (`@project`, `@human`, `@self`, `@model`, plus per-session). Readable, editable, greppable, git-able. Not an encrypted blob — and not a secret the model is instructed to keep from you. (Yes, that was a real instruction. No, we didn't port it.)
|
|
15
|
+
- **History never forgets.** Every closed window — messages, tool calls, tool output — stays fully searchable through the `history_*` tools. Notes are the agent's lossy index; history is the lossless record underneath. This is the half the original experiment never shipped.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pi install npm:notesoup
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or load it for a single invocation without installing:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
pi -e npm:notesoup
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## What you get
|
|
30
|
+
|
|
31
|
+
- **Durable context windows.** `/clear-memory` (alias `/cm`) clears and stops; `/cm Continue reviewing the implementation` clears and continues. The model can also request a window itself with `clear_memory`, and a budget close-out fires automatically before the window runs out. Abort and ordinary errors never count as completion; the raw conversation stays in the session, just out of the next context.
|
|
32
|
+
- **A boot block at every window head.** Static once-per-window content (cache-stable) with the window identity, the recent-notes index, and a short protocol teaching the model how to recover: notes for its own bookkeeping, history tools for everything before the reset.
|
|
33
|
+
- **`get_context_remaining`** — the live countdown to the close-out line, so the agent can see the cliff before it drives off it.
|
|
34
|
+
- **Nine history/notes tools**, flattened from the original Codex actions:
|
|
35
|
+
|
|
36
|
+
| Codex action | Pi tool |
|
|
37
|
+
| --- | --- |
|
|
38
|
+
| `history.list_windows` | `history_windows` |
|
|
39
|
+
| `history.list_items` | `history_list` |
|
|
40
|
+
| `history.read_item` | `history_read` |
|
|
41
|
+
| `history.search_contents` | `history_search` |
|
|
42
|
+
| `notes.write` | `notes_write` |
|
|
43
|
+
| `notes.update` | `notes_update` |
|
|
44
|
+
| `notes.rename` | `notes_update` (`rename_to`) |
|
|
45
|
+
| `notes.read` | `notes_read` |
|
|
46
|
+
| `notes.list` | `notes_list` |
|
|
47
|
+
| `notes.search` | `notes_search` |
|
|
48
|
+
|
|
49
|
+
- **Runtime toggle** — `/notesoup off` stops new automatic resets; `/notesoup on` re-enables them; bare `/notesoup` reports the state.
|
|
50
|
+
|
|
51
|
+
## Configuration
|
|
52
|
+
|
|
53
|
+
The reminder threshold is Pi's compaction reserve plus a margin, configured under the top-level `notesoup` key in `~/.pi/agent/settings.json` or `<cwd>/.pi/settings.json` (project values win per key):
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"compaction": { "reserveTokens": 16384 },
|
|
58
|
+
"notesoup": { "reminderMarginTokens": 24576 }
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The dreamer model is configured under the same key; `--dreamer <model pattern>` on the `dream` CLI wins, then a non-empty `notesoup.dreamer` string, then the automatic model:
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{
|
|
66
|
+
"notesoup": { "reminderMarginTokens": 24576, "dreamer": "anthropic/claude-sonnet-4-5" }
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Documentation
|
|
71
|
+
|
|
72
|
+
- [Architecture](docs/architecture.md) and [reset lifecycle](docs/reset-lifecycle.md) — how windows, checkpoints, markers and branches actually work
|
|
73
|
+
- [Tool results](docs/tool-results.md) — receipts, paging, and error shapes
|
|
74
|
+
- [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
|
|
75
|
+
- [SDK integration](docs/sdk-integration.md) — binding notesoup to a host-built session
|
|
76
|
+
- [Claude Code Mod](docs/claude-code-mod.md) — early-access notes tools for Claude Code
|
|
77
|
+
- [Skills, dream, and the notes doctor](docs/skills.md) — `/skill:memory`, `/skill:dream`, `dream doctor`, the dream lock
|
|
78
|
+
|
|
79
|
+
## Development
|
|
80
|
+
|
|
81
|
+
```sh
|
|
82
|
+
npm test # build from a clean dist, then run the suite
|
|
83
|
+
npm run typecheck
|
|
84
|
+
git diff --check
|
|
85
|
+
node scripts/check-notes-package.mjs # optional built /notes CRUD smoke; no install
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The harness runs against the real installed Pi `SessionManager`/`SettingsManager` in temporary directories with fake credentials — no model or network calls, and the real `~/.pi` is never touched. See [CONTRIBUTING.md](CONTRIBUTING.md) for ownership and verification rules.
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
MIT
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { NotesSnapshot } from "./snapshot.js";
|
|
2
|
+
import { type BootToolNames } from "./text.js";
|
|
3
|
+
/**
|
|
4
|
+
* Render a static, once-per-window boot block from explicit data. This function does not read
|
|
5
|
+
* notes or call runtime UI APIs; acquisition belongs to loadNotesSnapshot and its caller.
|
|
6
|
+
*/
|
|
7
|
+
export type BootRenderData = {
|
|
8
|
+
readonly agentName: string;
|
|
9
|
+
readonly modelName: string;
|
|
10
|
+
readonly firstWindowId: string;
|
|
11
|
+
readonly currentWindowId: string;
|
|
12
|
+
readonly previousWindowId?: string;
|
|
13
|
+
readonly notes: NotesSnapshot;
|
|
14
|
+
readonly tools: BootToolNames;
|
|
15
|
+
};
|
|
16
|
+
export declare function renderBootBlock(data: BootRenderData): string;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { CONTEXT_WINDOW_OPEN_TAG, CONTEXT_WINDOW_CLOSE_TAG, MAP_BOOT_MAX_CHARS, SHELF_FRESH_LIMIT, renderProtocolBlock } from "./text.js";
|
|
2
|
+
/** Codex-style <context_window> identity block: the resolved agent and model names plus first/current/previous window ids. */
|
|
3
|
+
function identityBlock(agentName, modelName, firstWindowId, currentWindowId, previousWindowId) {
|
|
4
|
+
const lines = [
|
|
5
|
+
`Agent name: ${agentName} (brain: ${modelName})`,
|
|
6
|
+
`First context window id: ${firstWindowId}`,
|
|
7
|
+
`Current context window id: ${currentWindowId}`,
|
|
8
|
+
];
|
|
9
|
+
if (previousWindowId)
|
|
10
|
+
lines.push(`Previous context window id: ${previousWindowId}`);
|
|
11
|
+
return `${CONTEXT_WINDOW_OPEN_TAG}\n${lines.join("\n")}\n${CONTEXT_WINDOW_CLOSE_TAG}`;
|
|
12
|
+
}
|
|
13
|
+
function relativeTime(timestamp, now) {
|
|
14
|
+
const seconds = Math.trunc((timestamp - now) / 1000);
|
|
15
|
+
if (seconds === 0)
|
|
16
|
+
return "just now";
|
|
17
|
+
const [unit, size] = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]]
|
|
18
|
+
.find(([unit, size]) => Math.abs(seconds) >= size || unit === "s");
|
|
19
|
+
const amount = `${Math.abs(Math.trunc(seconds / size))}${unit}`;
|
|
20
|
+
return seconds > 0 ? `in ${amount}` : `${amount} ago`;
|
|
21
|
+
}
|
|
22
|
+
function rowsFor(snapshot, scope) {
|
|
23
|
+
return snapshot.homes.get(scope) ?? [];
|
|
24
|
+
}
|
|
25
|
+
/** A feed entry is announced in the note's own words: its first heading, else its first line, cut short. */
|
|
26
|
+
const FEED_TITLE_MAX_CHARS = 40;
|
|
27
|
+
function feedTitle(body) {
|
|
28
|
+
const lines = body.split("\n");
|
|
29
|
+
const heading = lines.find((line) => /^#+\s+\S/.test(line));
|
|
30
|
+
const raw = (heading ? heading.replace(/^#+\s+/, "") : lines.find((line) => line.trim().length > 0) ?? "").trim();
|
|
31
|
+
if (raw.length === 0)
|
|
32
|
+
return undefined;
|
|
33
|
+
const chars = Array.from(raw);
|
|
34
|
+
return chars.length > FEED_TITLE_MAX_CHARS ? `${chars.slice(0, FEED_TITLE_MAX_CHARS).join("")}…` : chars.join("");
|
|
35
|
+
}
|
|
36
|
+
/** Two spaces of indent say "shelved content" without any furniture. */
|
|
37
|
+
function indent(text) {
|
|
38
|
+
return text.split("\n").map((line) => (line.length > 0 ? ` ${line}` : line)).join("\n");
|
|
39
|
+
}
|
|
40
|
+
/** An underlined header is the classical plain-text document heading: no renderer required. */
|
|
41
|
+
function section(label, body) {
|
|
42
|
+
return `${label}\n${"─".repeat(Array.from(label).length)}\n\n${body}`;
|
|
43
|
+
}
|
|
44
|
+
/** One closed boot snapshot: five tabbed shelves, current hands first, durable last; each shelf keeps its map and its own freshest pages. */
|
|
45
|
+
function notesIndex(snapshot, tools) {
|
|
46
|
+
const homes = [
|
|
47
|
+
{ scope: "session", label: "THIS SESSION · no @" },
|
|
48
|
+
{ scope: "project", label: "THIS PROJECT · @project" },
|
|
49
|
+
{ scope: "agent", label: "YOU · @self" },
|
|
50
|
+
{ scope: "model", label: "YOUR MODEL · @model" },
|
|
51
|
+
{ scope: "human", label: "THE HUMAN · @human" },
|
|
52
|
+
];
|
|
53
|
+
const shelves = [];
|
|
54
|
+
for (const home of homes) {
|
|
55
|
+
if (snapshot.unavailable.some((failed) => failed.scope === home.scope)) {
|
|
56
|
+
shelves.push(section(home.label, indent(`This drawer wouldn't open — ask ${tools.notesList} to try again.`)));
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const rows = rowsFor(snapshot, home.scope).filter((row) => row.meta.crumpledAt === undefined);
|
|
60
|
+
const map = rows.find((row) => row.path === "MAP.md");
|
|
61
|
+
const fresh = rows
|
|
62
|
+
.filter((row) => row.path !== "MAP.md")
|
|
63
|
+
.slice(0, SHELF_FRESH_LIMIT)
|
|
64
|
+
.map((row) => {
|
|
65
|
+
const locator = `${row.address} · ${relativeTime(row.meta.updatedAt, snapshot.openedAt)}`;
|
|
66
|
+
const title = feedTitle(row.body);
|
|
67
|
+
return title === undefined ? ` ${locator}` : ` ${title}\n ${locator}`;
|
|
68
|
+
});
|
|
69
|
+
if (!map?.body && fresh.length === 0)
|
|
70
|
+
continue;
|
|
71
|
+
const parts = [];
|
|
72
|
+
if (map?.body)
|
|
73
|
+
parts.push(`MAP — ${map.address}\n\n${indent(mapBodyForBoot(map.address, map.body))}`);
|
|
74
|
+
if (fresh.length > 0)
|
|
75
|
+
parts.push(`New pages\n\n${fresh.join("\n\n")}`);
|
|
76
|
+
shelves.push(section(home.label, parts.join("\n\n")));
|
|
77
|
+
}
|
|
78
|
+
return shelves.length > 0
|
|
79
|
+
? ["YOUR NOTES\n──────────", ...shelves].join("\n\n\n")
|
|
80
|
+
: "YOUR NOTES\n──────────\n\nNone yet. A blank slate is a fine place to start — just don't finish there.";
|
|
81
|
+
}
|
|
82
|
+
/** One unbounded MAP body fits the boot only up to the cap; the cut names where the rest lives. */
|
|
83
|
+
function mapBodyForBoot(address, body) {
|
|
84
|
+
const chars = Array.from(body);
|
|
85
|
+
if (chars.length <= MAP_BOOT_MAX_CHARS)
|
|
86
|
+
return body;
|
|
87
|
+
return `${chars.slice(0, MAP_BOOT_MAX_CHARS).join("")}\n[MAP cut at ${MAP_BOOT_MAX_CHARS} chars — slim it down; full body at ${address}]`;
|
|
88
|
+
}
|
|
89
|
+
export function renderBootBlock(data) {
|
|
90
|
+
const parts = [];
|
|
91
|
+
parts.push(identityBlock(data.agentName, data.modelName, data.firstWindowId, data.currentWindowId, data.previousWindowId));
|
|
92
|
+
parts.push(renderProtocolBlock(data.tools));
|
|
93
|
+
parts.push(notesIndex(data.notes, data.tools));
|
|
94
|
+
return parts.join("\n\n");
|
|
95
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { NotesIdentity } from "../notes/identity.js";
|
|
2
|
+
import { type NoteRow, type Scope } from "../notes/index.js";
|
|
3
|
+
declare const NOTES_HOMES: readonly [{
|
|
4
|
+
readonly scope: "session";
|
|
5
|
+
readonly label: "this session";
|
|
6
|
+
}, {
|
|
7
|
+
readonly scope: "project";
|
|
8
|
+
readonly label: "@project";
|
|
9
|
+
}, {
|
|
10
|
+
readonly scope: "human";
|
|
11
|
+
readonly label: "@human";
|
|
12
|
+
}, {
|
|
13
|
+
readonly scope: "agent";
|
|
14
|
+
readonly label: "@self";
|
|
15
|
+
}, {
|
|
16
|
+
readonly scope: "model";
|
|
17
|
+
readonly label: "@model";
|
|
18
|
+
}];
|
|
19
|
+
export type NotesHome = (typeof NOTES_HOMES)[number];
|
|
20
|
+
export type NotesLoader = (scope: Scope) => NoteRow[] | Promise<NoteRow[]>;
|
|
21
|
+
export type NotesSnapshot = {
|
|
22
|
+
/** Wall-clock instant captured when this boot began; rendering never consults Date.now(). */
|
|
23
|
+
readonly openedAt: number;
|
|
24
|
+
readonly homes: ReadonlyMap<Scope, readonly NoteRow[]>;
|
|
25
|
+
readonly unavailable: readonly NotesHome[];
|
|
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 declare function loadNotesSnapshot(identity: NotesIdentity, openedAt: number, loadHome?: NotesLoader): Promise<NotesSnapshot>;
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isFilesystemError } from "../notes/fs-error.js";
|
|
2
|
+
import { createNotesStore } from "../notes/index.js";
|
|
3
|
+
const NOTES_HOMES = [
|
|
4
|
+
{ scope: "session", label: "this session" },
|
|
5
|
+
{ scope: "project", label: "@project" },
|
|
6
|
+
{ scope: "human", label: "@human" },
|
|
7
|
+
{ scope: "agent", label: "@self" },
|
|
8
|
+
{ scope: "model", label: "@model" },
|
|
9
|
+
];
|
|
10
|
+
function queryForScope(scope) {
|
|
11
|
+
if (scope === "agent" || scope === "model")
|
|
12
|
+
return { scope };
|
|
13
|
+
return { scope };
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Acquire the five homes once for one boot. Only filesystem-style errno failures are isolated;
|
|
17
|
+
* malformed note data and unrelated construction errors remain visible to the caller.
|
|
18
|
+
*/
|
|
19
|
+
export async function loadNotesSnapshot(identity, openedAt, loadHome) {
|
|
20
|
+
const store = createNotesStore(identity);
|
|
21
|
+
const load = loadHome ?? ((scope) => store.list(queryForScope(scope)));
|
|
22
|
+
const homes = new Map();
|
|
23
|
+
const unavailable = [];
|
|
24
|
+
for (const home of NOTES_HOMES) {
|
|
25
|
+
try {
|
|
26
|
+
homes.set(home.scope, await load(home.scope));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (!isFilesystemError(error))
|
|
30
|
+
throw error;
|
|
31
|
+
homes.set(home.scope, []);
|
|
32
|
+
unavailable.push(home);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { openedAt, homes, unavailable };
|
|
36
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Each shelf shows this many of its own freshest pages beneath the map. */
|
|
2
|
+
export declare 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 declare const MAP_BOOT_MAX_CHARS = 4096;
|
|
5
|
+
export declare const CONTEXT_WINDOW_OPEN_TAG = "<context_window>";
|
|
6
|
+
export declare const CONTEXT_WINDOW_CLOSE_TAG = "</context_window>";
|
|
7
|
+
export declare const CONTEXT_WINDOW_PROTOCOL_OPEN_TAG = "<context_window_protocol>";
|
|
8
|
+
export declare const CONTEXT_WINDOW_PROTOCOL_CLOSE_TAG = "</context_window_protocol>";
|
|
9
|
+
/** Logical tool names are supplied by the composing host, not discovered here. */
|
|
10
|
+
export type BootToolNames = Readonly<{
|
|
11
|
+
notes: string;
|
|
12
|
+
notesList: string;
|
|
13
|
+
history: string;
|
|
14
|
+
historyWindows: string;
|
|
15
|
+
historyList: string;
|
|
16
|
+
historySearch: string;
|
|
17
|
+
historyRead: string;
|
|
18
|
+
remaining: string;
|
|
19
|
+
wipe: string;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function renderProtocolBlock(tools: BootToolNames): string;
|
|
@@ -0,0 +1,52 @@
|
|
|
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. Everything else is gone. \`history_windows\` lists the windows themselves; pass its window_id to list or search inside one window. \`history_list\` and \`history_search\` hand you seqs; \`history_read({seq})\` pulls one back out whole. Write the 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 what this place has already learned the hard way. It exists so the next session doesn't re-ask, re-argue, or step on the same rake. **Decisions, not diaries.** A commit hash, a test count, a date, the story of how you got here — git and history still have all of it, and last week's news filed as current law is worse than no note at all. Don't copy what already lives in other docs.
|
|
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. These @ addresses belong to the notes namespace, not the filesystem: never pass them to general read/write/edit/bash tools.
|
|
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
|
+
export function renderProtocolBlock(tools) {
|
|
41
|
+
const names = {
|
|
42
|
+
"notes_*": tools.notes,
|
|
43
|
+
"history_*": tools.history,
|
|
44
|
+
"history_windows": tools.historyWindows,
|
|
45
|
+
history_list: tools.historyList,
|
|
46
|
+
history_search: tools.historySearch,
|
|
47
|
+
history_read: tools.historyRead,
|
|
48
|
+
get_context_remaining: tools.remaining,
|
|
49
|
+
clear_memory: tools.wipe,
|
|
50
|
+
};
|
|
51
|
+
return PROTOCOL_BLOCK.replace(/notes_\*|history_\*|history_windows|history_list|history_search|history_read|get_context_remaining|clear_memory/g, (name) => names[name]);
|
|
52
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export declare const DEFAULT_RESERVE_TOKENS = 16384;
|
|
2
|
+
export declare const DEFAULT_REMINDER_MARGIN_TOKENS = 24576;
|
|
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 declare const WARNING_RUNWAY_TOKENS = 16384;
|
|
@@ -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,19 @@
|
|
|
1
|
+
import { type NotesoupSettings } from "../settings.js";
|
|
2
|
+
export type ResolvedThresholds = {
|
|
3
|
+
reminder: number;
|
|
4
|
+
reserve: number;
|
|
5
|
+
warning: number;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
9
|
+
* plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
|
|
10
|
+
* An invalid margin degrades to the default and reports one warning. Automatic
|
|
11
|
+
* threshold/overflow handling is represented by reset lifecycle boundary drafts;
|
|
12
|
+
* no compaction summary is generated.
|
|
13
|
+
*/
|
|
14
|
+
export declare function deriveThresholds(reserveTokens: number, margins: NotesoupSettings): {
|
|
15
|
+
thresholds: ResolvedThresholds;
|
|
16
|
+
warnings: string[];
|
|
17
|
+
};
|
|
18
|
+
/** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
|
|
19
|
+
export declare function remainingBudget(remaining: number | null, warning: number): number | null;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { DEFAULT_REMINDER_MARGIN_TOKENS, WARNING_RUNWAY_TOKENS } from "./constants.js";
|
|
2
|
+
import { NOTESOUP_SETTINGS_KEY } from "../settings.js";
|
|
3
|
+
/** A margin is usable only as a positive integer; anything else is ignored. */
|
|
4
|
+
function validMargin(raw) {
|
|
5
|
+
if (typeof raw !== "number" || !Number.isSafeInteger(raw) || raw <= 0)
|
|
6
|
+
return undefined;
|
|
7
|
+
return raw;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Pure derivation of the thresholds from Pi's reserve: the reminder fires at reserve
|
|
11
|
+
* plus the notesoup margin, the warning steer at reserve plus WARNING_RUNWAY_TOKENS.
|
|
12
|
+
* An invalid margin degrades to the default and reports one warning. Automatic
|
|
13
|
+
* threshold/overflow handling is represented by reset lifecycle boundary drafts;
|
|
14
|
+
* no compaction summary is generated.
|
|
15
|
+
*/
|
|
16
|
+
export function deriveThresholds(reserveTokens, margins) {
|
|
17
|
+
const warnings = [];
|
|
18
|
+
const reminderKey = `${NOTESOUP_SETTINGS_KEY}.reminderMarginTokens`;
|
|
19
|
+
let reminderMargin;
|
|
20
|
+
if (margins.reminderMarginTokens === undefined)
|
|
21
|
+
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
22
|
+
else {
|
|
23
|
+
const parsed = validMargin(margins.reminderMarginTokens);
|
|
24
|
+
if (parsed === undefined) {
|
|
25
|
+
warnings.push(`notesoup: ${reminderKey} must be a positive integer; using the default reminder margin.`);
|
|
26
|
+
reminderMargin = DEFAULT_REMINDER_MARGIN_TOKENS;
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
reminderMargin = parsed;
|
|
30
|
+
}
|
|
31
|
+
return { thresholds: { reminder: reserveTokens + reminderMargin, reserve: reserveTokens, warning: reserveTokens + WARNING_RUNWAY_TOKENS }, warnings };
|
|
32
|
+
}
|
|
33
|
+
/** Countdown excludes the hidden warning runway; unknown usage stays unknown. */
|
|
34
|
+
export function remainingBudget(remaining, warning) {
|
|
35
|
+
return remaining === null ? null : Math.max(0, remaining - warning);
|
|
36
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
|
|
2
|
+
export declare const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
|
|
3
|
+
/**
|
|
4
|
+
* Codex-equivalent low-budget reminder. The measured remaining count is frozen into
|
|
5
|
+
* the text at the crossing that fires it, so each persisted copy is a snapshot true
|
|
6
|
+
* at write time; get_context_remaining remains the live source for the current figure.
|
|
7
|
+
*/
|
|
8
|
+
export declare function tokenBudgetGuidance(remaining: number, wipeTool: string): string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export const GUIDANCE_OPEN_TAG = "<context_window_guidance>";
|
|
2
|
+
export const GUIDANCE_CLOSE_TAG = "</context_window_guidance>";
|
|
3
|
+
/**
|
|
4
|
+
* Codex-equivalent low-budget reminder. The measured remaining count is frozen into
|
|
5
|
+
* the text at the crossing that fires it, so each persisted copy is a snapshot true
|
|
6
|
+
* at write time; get_context_remaining remains the live source for the current figure.
|
|
7
|
+
*/
|
|
8
|
+
export function tokenBudgetGuidance(remaining, wipeTool) {
|
|
9
|
+
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}`;
|
|
10
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Outcome } from "../tools/result.js";
|
|
2
|
+
export type ClaudeIdentityInput = Readonly<{
|
|
3
|
+
home: string;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
cwd: string;
|
|
6
|
+
agent: string;
|
|
7
|
+
model: string;
|
|
8
|
+
}>;
|
|
9
|
+
/** One tool call as the hook receives it: the shared text the model reads, and the shared outcome it came from. */
|
|
10
|
+
export type ClaudeToolResult = {
|
|
11
|
+
text: string;
|
|
12
|
+
outcome: Outcome<unknown>;
|
|
13
|
+
};
|
|
14
|
+
export declare function dispatch(request: unknown): Promise<unknown>;
|
|
15
|
+
export declare function handleLine(line: string): Promise<string>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { pathToFileURL } from "node:url";
|
|
3
|
+
import { Check } from "typebox/value";
|
|
4
|
+
import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../tools/notes.js";
|
|
5
|
+
import { loadNotesSnapshot } from "../boot/snapshot.js";
|
|
6
|
+
import { renderBootBlock } from "../boot/render.js";
|
|
7
|
+
import { projectKey } from "../notes/paths.js";
|
|
8
|
+
import { snapshotNotesIdentity } from "../notes/identity.js";
|
|
9
|
+
const MAX_REQUEST_BYTES = 512 * 1024;
|
|
10
|
+
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
11
|
+
const TOOL_NAMES = ["notes_write", "notes_update", "notes_read", "notes_list", "notes_search"];
|
|
12
|
+
function identity(input) {
|
|
13
|
+
if (!input || typeof input !== "object" || typeof input.cwd !== "string")
|
|
14
|
+
throw new Error("invalid identity");
|
|
15
|
+
return snapshotNotesIdentity({ home: input.home, sessionId: input.sessionId, projectKey: projectKey(input.cwd), agent: input.agent, model: input.model });
|
|
16
|
+
}
|
|
17
|
+
function jsonValue(value) { return JSON.parse(JSON.stringify(value)); }
|
|
18
|
+
/** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
|
|
19
|
+
function boundOperation(operation, ...rest) {
|
|
20
|
+
return {
|
|
21
|
+
description: operation.description,
|
|
22
|
+
parameters: operation.parameters,
|
|
23
|
+
async call(params, id) {
|
|
24
|
+
// Refuse before the operation can act: a rejected shape never reaches a write.
|
|
25
|
+
if (!Check(operation.parameters, params))
|
|
26
|
+
throw new Error(`invalid ${operation.name} parameters`);
|
|
27
|
+
// The same business outcome and the same renderer as the Pi tool; only the envelope differs.
|
|
28
|
+
const outcome = await operation.execute(params, id, ...rest);
|
|
29
|
+
return { text: operation.render(outcome), outcome };
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** Claude has no diff renderer, so an update receipt names the change kind instead of a diff. */
|
|
34
|
+
function claudeDiff(change) {
|
|
35
|
+
return change.kind === "none" ? "" : `note ${change.kind}`;
|
|
36
|
+
}
|
|
37
|
+
const OPERATIONS = {
|
|
38
|
+
notes_write: boundOperation(notesWrite),
|
|
39
|
+
notes_update: boundOperation(notesUpdate, claudeDiff),
|
|
40
|
+
notes_read: boundOperation(notesRead),
|
|
41
|
+
notes_list: boundOperation(notesList),
|
|
42
|
+
notes_search: boundOperation(notesSearch),
|
|
43
|
+
};
|
|
44
|
+
export async function dispatch(request) {
|
|
45
|
+
if (!request || typeof request !== "object" || Array.isArray(request))
|
|
46
|
+
throw new Error("malformed request");
|
|
47
|
+
const value = request;
|
|
48
|
+
if (value.op === "schemas")
|
|
49
|
+
return TOOL_NAMES.map((name) => ({ name, description: OPERATIONS[name].description, inputSchema: jsonValue(OPERATIONS[name].parameters) }));
|
|
50
|
+
if (value.op === "tool") {
|
|
51
|
+
if (typeof value.tool !== "string" || !TOOL_NAMES.includes(value.tool))
|
|
52
|
+
throw new Error("unknown tool");
|
|
53
|
+
const id = identity(value.identity);
|
|
54
|
+
return OPERATIONS[value.tool].call(value.params, id);
|
|
55
|
+
}
|
|
56
|
+
if (value.op === "boot") {
|
|
57
|
+
const id = identity(value.identity);
|
|
58
|
+
if (!value.tools || typeof value.tools !== "object")
|
|
59
|
+
throw new Error("invalid boot tools");
|
|
60
|
+
const window = value.window ?? 0;
|
|
61
|
+
if (typeof window !== "number" || !Number.isSafeInteger(window) || window < 0)
|
|
62
|
+
throw new Error("invalid context window");
|
|
63
|
+
const snapshot = await loadNotesSnapshot(id, typeof value.openedAt === "number" ? value.openedAt : Date.now());
|
|
64
|
+
const windowId = (index) => `claude:${id.sessionId}:${index}`;
|
|
65
|
+
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 });
|
|
66
|
+
}
|
|
67
|
+
throw new Error("unknown operation");
|
|
68
|
+
}
|
|
69
|
+
function safeError(error) { return error instanceof Error && error.message ? error.message.replace(/[\r\n].*$/s, "") : "helper request failed"; }
|
|
70
|
+
export async function handleLine(line) {
|
|
71
|
+
if (Buffer.byteLength(line, "utf8") > MAX_REQUEST_BYTES)
|
|
72
|
+
return JSON.stringify({ ok: false, error: "request too large" });
|
|
73
|
+
try {
|
|
74
|
+
const result = await dispatch(JSON.parse(line));
|
|
75
|
+
const response = JSON.stringify({ ok: true, result });
|
|
76
|
+
return Buffer.byteLength(response, "utf8") <= MAX_RESPONSE_BYTES ? response : JSON.stringify({ ok: false, error: "response too large" });
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
return JSON.stringify({ ok: false, error: safeError(error) });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) {
|
|
83
|
+
process.stdin.setEncoding("utf8");
|
|
84
|
+
let input = "";
|
|
85
|
+
process.stdin.on("data", (chunk) => { input += chunk; });
|
|
86
|
+
process.stdin.on("end", async () => { process.stdout.write(`${await handleLine(input.trim())}\n`); });
|
|
87
|
+
}
|