notesoup 0.52.6 → 0.53.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.
Files changed (84) hide show
  1. package/README.md +3 -1
  2. package/dist/plugins/claude/src/helper.js +34 -7
  3. package/dist/plugins/claude/src/history.d.ts +7 -2
  4. package/dist/plugins/claude/src/history.js +53 -22
  5. package/dist/plugins/claude/src/text.d.ts +5 -0
  6. package/dist/plugins/claude/src/text.js +12 -0
  7. package/dist/plugins/codex/src/cli.d.ts +2 -0
  8. package/dist/plugins/codex/src/cli.js +25 -0
  9. package/dist/plugins/codex/src/history.d.ts +8 -0
  10. package/dist/plugins/codex/src/history.js +238 -0
  11. package/dist/plugins/codex/src/hooks.d.ts +9 -0
  12. package/dist/plugins/codex/src/hooks.js +196 -0
  13. package/dist/plugins/codex/src/identity.d.ts +35 -0
  14. package/dist/plugins/codex/src/identity.js +134 -0
  15. package/dist/plugins/codex/src/mcp.d.ts +7 -0
  16. package/dist/plugins/codex/src/mcp.js +159 -0
  17. package/dist/plugins/codex/src/state.d.ts +23 -0
  18. package/dist/plugins/codex/src/state.js +92 -0
  19. package/dist/plugins/codex/src/text.d.ts +14 -0
  20. package/dist/plugins/codex/src/text.js +25 -0
  21. package/dist/plugins/codex/src/transcript.d.ts +39 -0
  22. package/dist/plugins/codex/src/transcript.js +313 -0
  23. package/dist/src/boot/render.js +11 -10
  24. package/dist/src/boot/text.d.ts +4 -5
  25. package/dist/src/boot/text.js +14 -28
  26. package/dist/src/budget/text.d.ts +1 -1
  27. package/dist/src/budget/text.js +1 -1
  28. package/dist/src/history/history.js +12 -11
  29. package/dist/src/tools/history.d.ts +5 -3
  30. package/dist/src/tools/history.js +9 -11
  31. package/dist/test/claude-history.test.js +135 -3
  32. package/dist/test/codex-history.test.d.ts +1 -0
  33. package/dist/test/codex-history.test.js +330 -0
  34. package/dist/test/codex-plugin.test.d.ts +1 -0
  35. package/dist/test/codex-plugin.test.js +365 -0
  36. package/dist/test/dependencies.test.js +8 -2
  37. package/dist/test/dsh.test.js +1 -1
  38. package/dist/test/helpers/dependency-graph.js +1 -1
  39. package/dist/test/history.integration.test.js +26 -1
  40. package/dist/test/model-facing-text.test.js +41 -26
  41. package/dist/test/notes.integration.test.js +3 -0
  42. package/docs/claude-code-mod.md +6 -2
  43. package/docs/codex.md +91 -0
  44. package/docs/dsh.md +1 -1
  45. package/docs/reset-lifecycle.md +1 -1
  46. package/docs/tool-results.md +2 -2
  47. package/package.json +6 -3
  48. package/playbook.md +1 -1
  49. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  50. package/plugins/claude/dist/claude/helper.js +120 -74
  51. package/plugins/claude/playbook.md +1 -1
  52. package/plugins/claude/skills/dream/SKILL.md +1 -1
  53. package/plugins/claude/skills/memory/SKILL.md +1 -1
  54. package/plugins/claude/src/helper.ts +34 -9
  55. package/plugins/claude/src/history.ts +54 -22
  56. package/plugins/claude/src/text.ts +13 -0
  57. package/plugins/codex/README.md +43 -0
  58. package/plugins/codex/dist/codex/notesoup.js +27800 -0
  59. package/plugins/codex/hooks/hooks.json +41 -0
  60. package/plugins/codex/mcp.json +10 -0
  61. package/plugins/codex/plugin.json +6 -0
  62. package/plugins/codex/src/cli.ts +26 -0
  63. package/plugins/codex/src/history.ts +193 -0
  64. package/plugins/codex/src/hooks.ts +190 -0
  65. package/plugins/codex/src/identity.ts +147 -0
  66. package/plugins/codex/src/mcp.ts +171 -0
  67. package/plugins/codex/src/state.ts +102 -0
  68. package/plugins/codex/src/text.ts +31 -0
  69. package/plugins/codex/src/transcript.ts +275 -0
  70. package/plugins/paseo/OVERVIEW.md +6 -2
  71. package/plugins/paseo/client/brain-empty-card.tsx +3 -1
  72. package/plugins/paseo/client/brain-empty-transformer.ts +7 -14
  73. package/plugins/paseo/client/notes-op-transformer.ts +10 -18
  74. package/plugins/paseo/client/tool-result.ts +31 -0
  75. package/plugins/paseo/test/brain-empty.test.ts +24 -1
  76. package/plugins/paseo/test/fixtures/claude-tool-calls.ts +86 -0
  77. package/plugins/paseo/test/notes-op.test.ts +39 -1
  78. package/skills/dream/SKILL.md +1 -1
  79. package/skills/memory/SKILL.md +1 -1
  80. package/src/boot/render.ts +11 -9
  81. package/src/boot/text.ts +16 -30
  82. package/src/budget/text.ts +1 -1
  83. package/src/history/history.ts +12 -10
  84. package/src/tools/history.ts +14 -13
@@ -0,0 +1,196 @@
1
+ /** Codex command hooks: bind verified native thread identity, then render or refuse a native-window boot. */
2
+ import { realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { loadNotesSnapshot, unavailableNotesSnapshot } from "../../../src/boot/snapshot.js";
5
+ import { isFilesystemError, slugify } from "../../../src/notes/index.js";
6
+ import { CodexIdentityError, modelSlug, notesHome, notesIdentityFor, pluginDataRoot, readBinding, safeThreadId, writeBinding } from "./identity.js";
7
+ import { findRecordedBoot, readStartState, recheckStartState, renderCodexBoot } from "./state.js";
8
+ import { CODEX_SETUP_HINT, missingNativeFacts, notesFailureBoot, unsupportedChildCompaction } from "./text.js";
9
+ const MAX_HOOK_INPUT_BYTES = 1024 * 1024;
10
+ /** additionalContextLimit:0 disables host spilling, so this local cap is the only truncation guard. */
11
+ export const MAX_BOOT_BYTES = 128 * 1024;
12
+ function text(value) {
13
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
14
+ }
15
+ function shellFree(reason) {
16
+ const value = reason instanceof Error ? reason.message : String(reason);
17
+ return value.replace(/[\r\n]+/g, " ").slice(0, 500);
18
+ }
19
+ export function warningOutput(message) {
20
+ return JSON.stringify({ systemMessage: message });
21
+ }
22
+ export function contextOutput(event, text) {
23
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
24
+ }
25
+ /** An oversized boot is refused rather than silently truncated or spilled by the host. */
26
+ export function bootWithinCap(boot) {
27
+ const bytes = Buffer.byteLength(boot, "utf8");
28
+ return bytes <= MAX_BOOT_BYTES
29
+ ? undefined
30
+ : `notesoup: this window's boot is ${bytes} bytes, over the ${MAX_BOOT_BYTES}-byte cap. No truncated or spilled boot was injected; slim the home MAPs and restart/resume the thread.`;
31
+ }
32
+ export async function readHookInput(stream) {
33
+ return await new Promise((resolveInput, reject) => {
34
+ let size = 0;
35
+ const chunks = [];
36
+ stream.on("data", (chunk) => {
37
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
38
+ size += bytes.length;
39
+ if (size > MAX_HOOK_INPUT_BYTES) {
40
+ stream.pause();
41
+ reject(new Error("hook input exceeds 1 MiB"));
42
+ return;
43
+ }
44
+ chunks.push(bytes);
45
+ });
46
+ stream.on("end", () => resolveInput(Buffer.concat(chunks).toString("utf8")));
47
+ stream.on("error", reject);
48
+ });
49
+ }
50
+ function samePath(left, right) {
51
+ const a = resolve(left), b = resolve(right);
52
+ if (a === b)
53
+ return true;
54
+ try {
55
+ return realpathSync(a) === realpathSync(b);
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ async function snapshotFor(binding, model) {
62
+ const openedAt = Date.now();
63
+ try {
64
+ return { notes: await loadNotesSnapshot(notesIdentityFor(binding, model), openedAt) };
65
+ }
66
+ catch (error) {
67
+ if (isFilesystemError(error))
68
+ return { notes: unavailableNotesSnapshot(openedAt) };
69
+ return { notes: unavailableNotesSnapshot(openedAt), failure: shellFree(error) };
70
+ }
71
+ }
72
+ async function startHook(event, payload, env) {
73
+ let root;
74
+ try {
75
+ root = pluginDataRoot(env);
76
+ }
77
+ catch (error) {
78
+ return warningOutput(shellFree(error));
79
+ }
80
+ const rootSession = text(payload.session_id);
81
+ const childThread = text(payload.agent_id);
82
+ const threadId = event === "SubagentStart" ? childThread : rootSession;
83
+ const cwd = text(payload.cwd);
84
+ const model = modelSlug(payload.model);
85
+ if (threadId === undefined || rootSession === undefined || cwd === undefined || model === undefined) {
86
+ return warningOutput(`notesoup: the ${event} payload is missing a native thread, cwd, or model fact. ${CODEX_SETUP_HINT}`);
87
+ }
88
+ const agentType = event === "SubagentStart" ? text(payload.agent_type) : undefined;
89
+ const agent = event === "SubagentStart"
90
+ ? (agentType === undefined ? "anonymous" : slugify(agentType))
91
+ : slugify(env.NOTESOUP_AGENT ?? "anonymous");
92
+ let target;
93
+ try {
94
+ target = { threadId: safeThreadId(threadId), rootSessionId: rootSession, cwd, agent, model, ...(agentType === undefined ? {} : { agentType }) };
95
+ }
96
+ catch (error) {
97
+ return warningOutput(shellFree(error));
98
+ }
99
+ const transcriptPath = text(payload.transcript_path);
100
+ if (transcriptPath === undefined)
101
+ return warningOutput(missingNativeFacts("the hook supplied no transcript_path"));
102
+ let native;
103
+ try {
104
+ native = await readStartState({ transcriptPath, threadId: target.threadId });
105
+ if (native.state.rootSessionId !== target.rootSessionId)
106
+ throw new CodexIdentityError("mismatched_root", "The native transcript's root session does not match the hook's session_id.");
107
+ if (!samePath(native.state.cwd, target.cwd))
108
+ throw new CodexIdentityError("mismatched_cwd", "The native transcript's cwd does not match the hook's cwd; refusing to bind a guessed project.");
109
+ if (native.state.currentWindowId === undefined)
110
+ throw new CodexIdentityError("missing_window", "The native transcript has no materialized context window yet.");
111
+ }
112
+ catch (error) {
113
+ return warningOutput(missingNativeFacts(shellFree(error)));
114
+ }
115
+ const binding = {
116
+ version: 1,
117
+ threadId: target.threadId,
118
+ rootSessionId: native.state.rootSessionId,
119
+ cwd: target.cwd,
120
+ model: target.model,
121
+ agent: target.agent,
122
+ home: notesHome(env),
123
+ transcriptPath,
124
+ windowId: native.state.currentWindowId,
125
+ ...(target.agentType === undefined ? {} : { agentType: target.agentType }),
126
+ boundAt: new Date().toISOString(),
127
+ };
128
+ let existing;
129
+ try {
130
+ existing = await readBinding(root, target.threadId);
131
+ }
132
+ catch (error) {
133
+ if (!(error instanceof CodexIdentityError && error.code === "unknown_thread"))
134
+ return warningOutput(`notesoup: ${shellFree(error)}`);
135
+ }
136
+ if (existing !== undefined && existing.rootSessionId !== binding.rootSessionId) {
137
+ return warningOutput("notesoup: a previous binding for this thread disagrees on its native root session; refusing to clobber it. Resume the thread once so its hooks rebind it.");
138
+ }
139
+ try {
140
+ await writeBinding(root, binding);
141
+ }
142
+ catch (error) {
143
+ return warningOutput(`notesoup: could not store this thread's binding (${shellFree(error)}). No boot was injected.`);
144
+ }
145
+ if (findRecordedBoot(native.records, target.threadId, binding.windowId)) {
146
+ // This exact native window already has this thread's own host-injected boot.
147
+ return "";
148
+ }
149
+ const snapshot = await snapshotFor(binding, target.model);
150
+ try {
151
+ await recheckStartState({ transcriptPath, threadId: target.threadId }, native.state);
152
+ }
153
+ catch (error) {
154
+ return warningOutput(`notesoup: ${shellFree(error)}`);
155
+ }
156
+ const boot = renderCodexBoot({
157
+ threadId: target.threadId,
158
+ agent: target.agent,
159
+ model: target.model,
160
+ state: native.state,
161
+ records: native.records,
162
+ notes: snapshot.notes,
163
+ });
164
+ const withFailure = snapshot.failure === undefined ? boot : `${boot}\n\n${notesFailureBoot(snapshot.failure)}`;
165
+ const tooLarge = bootWithinCap(withFailure);
166
+ if (tooLarge !== undefined)
167
+ return warningOutput(tooLarge);
168
+ return contextOutput(event, withFailure);
169
+ }
170
+ function preCompactHook(payload) {
171
+ // A child rollover has no supported post-compact boot in this native version; stop before history is cut.
172
+ return text(payload.agent_id) === undefined ? "" : JSON.stringify({ continue: false, stopReason: unsupportedChildCompaction() });
173
+ }
174
+ /** One hook event in, one stdout body out; an unrecognized event is transparent. */
175
+ export async function runHook(event, input, env = process.env) {
176
+ let payload;
177
+ try {
178
+ const value = JSON.parse(input);
179
+ if (typeof value !== "object" || value === null || Array.isArray(value))
180
+ throw new Error("hook input is not an object");
181
+ payload = value;
182
+ }
183
+ catch (error) {
184
+ return warningOutput(`notesoup: could not read its hook input (${shellFree(error)}). ${CODEX_SETUP_HINT}`);
185
+ }
186
+ // The payload's own event name is advisory; the configured command names the event.
187
+ switch (event) {
188
+ case "SessionStart":
189
+ case "SubagentStart":
190
+ return await startHook(event, payload, env);
191
+ case "PreCompact":
192
+ return preCompactHook(payload);
193
+ default:
194
+ return "";
195
+ }
196
+ }
@@ -0,0 +1,35 @@
1
+ import { type NotesIdentity } from "../../../src/notes/index.js";
2
+ /** A refusal the model can read and act on, not a crash. */
3
+ export declare class CodexIdentityError extends Error {
4
+ readonly code: string;
5
+ constructor(code: string, message: string);
6
+ }
7
+ export type ThreadBinding = Readonly<{
8
+ version: 1;
9
+ threadId: string;
10
+ rootSessionId: string;
11
+ cwd: string;
12
+ /** Session-start model, used only to label this window's boot. */
13
+ model: string;
14
+ agent: string;
15
+ home: string;
16
+ transcriptPath: string;
17
+ /** Native window at bind time; a later MCP call must name this same window. */
18
+ windowId: string;
19
+ agentType?: string;
20
+ boundAt: string;
21
+ }>;
22
+ export declare function safeThreadId(value: unknown, field?: string): string;
23
+ /** The portable server and the hook must share this root; Codex injects it into both. */
24
+ export declare function pluginDataRoot(env?: NodeJS.ProcessEnv): string;
25
+ export declare function notesHome(env?: NodeJS.ProcessEnv): string;
26
+ /** Native ids arrive provider-prefixed; @model is the last segment, slugged like every other home. */
27
+ export declare function modelSlug(value: unknown): string | undefined;
28
+ /** Validate every field before it becomes an identity; a corrupt binding never half-applies. */
29
+ export declare function readBinding(root: string, threadId: string): Promise<ThreadBinding>;
30
+ /** Atomic replace; a failed write never leaves a half binding behind. */
31
+ export declare function writeBinding(root: string, binding: ThreadBinding): Promise<void>;
32
+ export declare function notesIdentityFor(binding: ThreadBinding, model: string): NotesIdentity;
33
+ /** The current turn's model, not the cached session-start model, chooses @model. */
34
+ export declare function turnModel(meta: Record<string, unknown>): string;
35
+ export declare function rootSessionIdOf(meta: Record<string, unknown>): string;
@@ -0,0 +1,134 @@
1
+ /** Hook-captured thread identity and the only mutable plugin state: per-thread bindings under PLUGIN_DATA. */
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
5
+ import { projectKey, slugify, snapshotNotesIdentity } from "../../../src/notes/index.js";
6
+ const SAFE_THREAD_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ const BINDINGS = "bindings";
8
+ /** A refusal the model can read and act on, not a crash. */
9
+ export class CodexIdentityError extends Error {
10
+ code;
11
+ constructor(code, message) {
12
+ super(message);
13
+ this.code = code;
14
+ this.name = "CodexIdentityError";
15
+ }
16
+ }
17
+ export function safeThreadId(value, field = "threadId") {
18
+ if (typeof value !== "string" || !SAFE_THREAD_ID.test(value) || value === "." || value === "..") {
19
+ throw new CodexIdentityError("invalid_thread", `Codex ${field} is missing or not a safe native thread id.`);
20
+ }
21
+ return value;
22
+ }
23
+ /** The portable server and the hook must share this root; Codex injects it into both. */
24
+ export function pluginDataRoot(env = process.env) {
25
+ const value = env.PLUGIN_DATA;
26
+ if (typeof value !== "string" || value.trim() === "" || !isAbsolute(value)) {
27
+ throw new CodexIdentityError("missing_plugin_data", "PLUGIN_DATA is unavailable. Install notesoup as a Codex plugin (or set PLUGIN_DATA for a standalone test) so hook bindings have one mutable home.");
28
+ }
29
+ return resolve(value);
30
+ }
31
+ export function notesHome(env = process.env) {
32
+ const value = env.NOTESOUP_HOME;
33
+ return value !== undefined && value.trim() !== "" ? resolve(value) : join(homedir(), ".agents", "notes");
34
+ }
35
+ /** Native ids arrive provider-prefixed; @model is the last segment, slugged like every other home. */
36
+ export function modelSlug(value) {
37
+ if (typeof value !== "string")
38
+ return undefined;
39
+ const id = value.trim();
40
+ if (id === "")
41
+ return undefined;
42
+ const slug = slugify(id.split("/").pop() ?? id);
43
+ return slug === "root" ? undefined : slug;
44
+ }
45
+ function bindingPath(root, threadId) {
46
+ return join(root, BINDINGS, `${safeThreadId(threadId)}.json`);
47
+ }
48
+ function required(value, field) {
49
+ if (typeof value !== "string" || value.length === 0)
50
+ throw new CodexIdentityError("invalid_binding", `Stored notesoup binding is missing ${field}; resume the Codex thread once so its hooks rebind it.`);
51
+ return value;
52
+ }
53
+ /** Validate every field before it becomes an identity; a corrupt binding never half-applies. */
54
+ export async function readBinding(root, threadId) {
55
+ let raw;
56
+ try {
57
+ raw = await readFile(bindingPath(root, threadId), "utf8");
58
+ }
59
+ catch (error) {
60
+ if (error.code === "ENOENT") {
61
+ throw new CodexIdentityError("unknown_thread", "notesoup has no hook binding for this Codex thread. Enable and trust the notesoup plugin hooks, then start or resume the thread; notesoup never guesses a project from the MCP server's own cwd.");
62
+ }
63
+ throw error;
64
+ }
65
+ let value;
66
+ try {
67
+ value = JSON.parse(raw);
68
+ }
69
+ catch {
70
+ throw new CodexIdentityError("invalid_binding", "The stored notesoup binding is not valid JSON; resume the Codex thread once so its hooks rebind it.");
71
+ }
72
+ const row = value;
73
+ if (row.version !== 1)
74
+ throw new CodexIdentityError("invalid_binding", "The stored notesoup binding has an unsupported version; resume the Codex thread once so its hooks rebind it.");
75
+ const storedThread = safeThreadId(row.threadId, "binding threadId");
76
+ if (storedThread !== threadId)
77
+ throw new CodexIdentityError("mismatched_thread", "The stored notesoup binding belongs to another thread; refuse to read or write with it.");
78
+ const home = required(row.home, "home");
79
+ const cwd = required(row.cwd, "cwd");
80
+ const transcriptPath = required(row.transcriptPath, "transcriptPath");
81
+ const windowId = required(row.windowId, "windowId");
82
+ if (!isAbsolute(home) || !isAbsolute(cwd) || !isAbsolute(transcriptPath))
83
+ throw new CodexIdentityError("invalid_binding", "The stored notesoup binding contains a non-absolute path.");
84
+ return {
85
+ version: 1,
86
+ threadId,
87
+ rootSessionId: required(row.rootSessionId, "rootSessionId"),
88
+ cwd,
89
+ model: required(row.model, "model"),
90
+ agent: required(row.agent, "agent"),
91
+ home,
92
+ transcriptPath,
93
+ windowId,
94
+ ...(typeof row.agentType === "string" && row.agentType.length > 0 ? { agentType: row.agentType } : {}),
95
+ boundAt: required(row.boundAt, "boundAt"),
96
+ };
97
+ }
98
+ /** Atomic replace; a failed write never leaves a half binding behind. */
99
+ export async function writeBinding(root, binding) {
100
+ const path = bindingPath(root, binding.threadId);
101
+ await mkdir(join(root, BINDINGS), { recursive: true });
102
+ const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
103
+ await writeFile(temp, `${JSON.stringify(binding)}\n`, { mode: 0o600 });
104
+ await rename(temp, path);
105
+ }
106
+ export function notesIdentityFor(binding, model) {
107
+ return snapshotNotesIdentity({
108
+ home: binding.home,
109
+ sessionId: binding.threadId,
110
+ projectKey: projectKey(binding.cwd, binding.home),
111
+ agent: binding.agent,
112
+ model,
113
+ });
114
+ }
115
+ /** The current turn's model, not the cached session-start model, chooses @model. */
116
+ export function turnModel(meta) {
117
+ let value = meta["x-codex-turn-metadata"];
118
+ if (typeof value === "string") {
119
+ try {
120
+ value = JSON.parse(value);
121
+ }
122
+ catch {
123
+ value = undefined;
124
+ }
125
+ }
126
+ const model = typeof value === "object" && value !== null ? value.model : undefined;
127
+ const slug = modelSlug(model);
128
+ if (slug === undefined)
129
+ throw new CodexIdentityError("missing_model", "Codex did not supply this turn's model in MCP metadata, so notesoup cannot choose an @model home. Update Codex, or call notes from a model turn.");
130
+ return slug;
131
+ }
132
+ export function rootSessionIdOf(meta) {
133
+ return required(meta.sessionId, "MCP sessionId");
134
+ }
@@ -0,0 +1,7 @@
1
+ /** The portable stdio MCP server: shared notes/history operations over host-owned tool names. */
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.js";
4
+ export declare function callTool(name: string, args: unknown, meta: Record<string, unknown>, env?: NodeJS.ProcessEnv): Promise<CallToolResult>;
5
+ export declare function tools(): Tool[];
6
+ export declare function createServer(env?: NodeJS.ProcessEnv): Server;
7
+ export declare function runMcp(env?: NodeJS.ProcessEnv): Promise<void>;
@@ -0,0 +1,159 @@
1
+ /** The portable stdio MCP server: shared notes/history operations over host-owned tool names. */
2
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
+ import { Check, Errors } from "typebox/value";
6
+ import { notesList, notesRead, notesSearch, notesUpdate, notesWrite } from "../../../src/tools/notes.js";
7
+ import { historyList, historyRead, historyWindows } from "../../../src/tools/history.js";
8
+ import { wireResult } from "../../../src/tools/result.js";
9
+ import { CodexIdentityError, notesIdentityFor, pluginDataRoot, readBinding, rootSessionIdOf, safeThreadId, turnModel } from "./identity.js";
10
+ import { readCodexHistory } from "./history.js";
11
+ import { readStartState } from "./state.js";
12
+ const OPERATIONS = {
13
+ notes_write: { operation: notesWrite, history: false },
14
+ notes_update: { operation: notesUpdate, history: false },
15
+ notes_read: { operation: notesRead, history: false },
16
+ notes_list: { operation: notesList, history: false },
17
+ notes_search: { operation: notesSearch, history: false },
18
+ history_list: { operation: historyList, history: true },
19
+ history_read: { operation: historyRead, history: true },
20
+ history_windows: { operation: historyWindows, history: true },
21
+ };
22
+ function shellFree(reason) {
23
+ const value = reason instanceof Error ? reason.message : String(reason);
24
+ return value.replace(/[\r\n]+/g, " ").slice(0, 500);
25
+ }
26
+ function failure(code, message) {
27
+ return {
28
+ content: [{ type: "text", text: `error: ${code}: ${message}` }],
29
+ structuredContent: { error: message, code },
30
+ isError: true,
31
+ };
32
+ }
33
+ function successFor(bound, outcome) {
34
+ const wire = wireResult(outcome);
35
+ return {
36
+ content: [{ type: "text", text: bound.operation.render(outcome) }],
37
+ structuredContent: wire,
38
+ // A refusal stays a tool-level error so the model does not mistake it for data.
39
+ ...(outcome.ok ? {} : { isError: true }),
40
+ };
41
+ }
42
+ /** The first schema violation, named by parameter so the model can fix that one field. */
43
+ function paramProblem(schema, params) {
44
+ const first = Errors(schema, params).find((error) => error.keyword !== "boolean");
45
+ if (!first)
46
+ return "unrecognized shape";
47
+ const extra = first.keyword === "additionalProperties" ? `: ${first.params.additionalProperties.join(", ")}` : "";
48
+ const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
49
+ return `${field ? `${field} ` : ""}${first.message}${extra}`;
50
+ }
51
+ /** MCP metadata is the caller's claim; it must agree with the hook binding before any read. */
52
+ function metaFacts(meta, binding) {
53
+ const rootSessionId = rootSessionIdOf(meta);
54
+ if (binding.rootSessionId !== rootSessionId) {
55
+ throw new CodexIdentityError("stale_thread_binding", "This thread's hook binding disagrees with Codex's current root session. Resume the thread once so its hooks rebind it; notesoup will not read or write through stale identity.");
56
+ }
57
+ const windowId = typeof meta.windowId === "string" && meta.windowId !== "" ? meta.windowId : undefined;
58
+ if (windowId === undefined)
59
+ throw new CodexIdentityError("missing_window", "Codex did not supply the current native window in MCP metadata; refusing to use a possibly stale binding.");
60
+ if (binding.windowId !== windowId)
61
+ throw new CodexIdentityError("stale_thread_binding", "This thread's hook binding belongs to a different native window. Resume or compact once so the SessionStart hook rebinds it; notesoup will not read or write through stale identity.");
62
+ return { rootSessionId };
63
+ }
64
+ async function identityFor(meta, env) {
65
+ const threadId = safeThreadId(meta.threadId, "MCP threadId");
66
+ const binding = await readBinding(pluginDataRoot(env), threadId);
67
+ const { rootSessionId } = metaFacts(meta, binding);
68
+ return { binding, rootSessionId, model: turnModel(meta) };
69
+ }
70
+ /** The binding is only a cache: the transcript is the fact. Both notes and history must pass this. */
71
+ function verifyNativeFacts(binding, rootSessionId, native) {
72
+ if (native.threadId !== binding.threadId)
73
+ throw new CodexIdentityError("stale_native_state", "The native transcript belongs to a different thread than the hook binding; refusing to read or write through it.");
74
+ if (native.rootSessionId !== binding.rootSessionId || native.rootSessionId !== rootSessionId) {
75
+ throw new CodexIdentityError("stale_native_state", "The native transcript no longer matches this thread's root session; refusing to read or write mixed or stale identity.");
76
+ }
77
+ if (native.currentWindowId === undefined)
78
+ throw new CodexIdentityError("missing_window", "The native transcript has no materialized current window; refusing to guess one.");
79
+ if (native.currentWindowId !== binding.windowId) {
80
+ throw new CodexIdentityError("stale_native_state", "The native transcript advanced to a different window. Resume or compact once so the SessionStart hook rebinds it; notesoup will not read or write through stale identity.");
81
+ }
82
+ }
83
+ function sameBinding(left, right) {
84
+ return left.version === right.version
85
+ && left.threadId === right.threadId
86
+ && left.rootSessionId === right.rootSessionId
87
+ && left.cwd === right.cwd
88
+ && left.agent === right.agent
89
+ && left.home === right.home
90
+ && left.transcriptPath === right.transcriptPath
91
+ && left.windowId === right.windowId
92
+ && left.agentType === right.agentType;
93
+ }
94
+ async function readNative(binding, rootSessionId, history, meta, env) {
95
+ if (binding.transcriptPath === "")
96
+ throw new CodexIdentityError("missing_transcript", "This thread's hook binding has no native transcript path; notes and history are unavailable until Codex materializes a transcript and the hook rebinds it.");
97
+ const source = { transcriptPath: binding.transcriptPath, threadId: binding.threadId };
98
+ const native = history ? await readCodexHistory(source) : (await readStartState(source)).state;
99
+ verifyNativeFacts(binding, rootSessionId, native);
100
+ // Native reads are asynchronous: a hook may have rebound this thread while we were
101
+ // reading. Compare again before trusting either the cached binding or a mutation.
102
+ const reread = await readBinding(pluginDataRoot(env), binding.threadId);
103
+ if (!sameBinding(binding, reread)) {
104
+ throw new CodexIdentityError("stale_thread_binding", "This thread's hook binding changed while notesoup was reading native facts; retry once the new native window is settled.");
105
+ }
106
+ // The caller's metadata and the fresh binding must still agree after the await.
107
+ metaFacts(meta, reread);
108
+ verifyNativeFacts(reread, rootSessionId, native);
109
+ return native;
110
+ }
111
+ export async function callTool(name, args, meta, env = process.env) {
112
+ const bound = Object.hasOwn(OPERATIONS, name) ? OPERATIONS[name] : undefined;
113
+ if (bound === undefined)
114
+ return failure("unknown_tool", `No notesoup operation named ${JSON.stringify(name)}.`);
115
+ const params = args ?? {};
116
+ if (!Check(bound.operation.parameters, params))
117
+ return failure("invalid_params", `invalid ${name} parameters: ${paramProblem(bound.operation.parameters, params)}`);
118
+ try {
119
+ const { binding, rootSessionId, model } = await identityFor(meta, env);
120
+ const native = await readNative(binding, rootSessionId, bound.history, meta, env);
121
+ if (!bound.history) {
122
+ const outcome = await bound.operation.execute(params, notesIdentityFor(binding, model));
123
+ return successFor(bound, outcome);
124
+ }
125
+ const projection = native.projection;
126
+ const outcome = name === "history_windows"
127
+ ? await bound.operation.execute(params, projection, binding.threadId)
128
+ : await bound.operation.execute(params, projection);
129
+ return successFor(bound, outcome);
130
+ }
131
+ catch (error) {
132
+ if (error instanceof CodexIdentityError)
133
+ return failure(error.code, error.message);
134
+ return failure("codex_error", shellFree(error));
135
+ }
136
+ }
137
+ export function tools() {
138
+ return Object.entries(OPERATIONS).map(([name, bound]) => ({
139
+ name,
140
+ description: bound.operation.description,
141
+ inputSchema: JSON.parse(JSON.stringify(bound.operation.parameters)),
142
+ // Every shared success and refusal is an object; the union stays the same
143
+ // logical schema, wrapped in the object shape the MCP tool schema requires.
144
+ outputSchema: { type: "object", ...JSON.parse(JSON.stringify(bound.operation.outputSchema)) },
145
+ }));
146
+ }
147
+ export function createServer(env = process.env) {
148
+ const server = new Server({ name: "notesoup", version: "1.0.0" }, { capabilities: { tools: {} } });
149
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: tools() }));
150
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
151
+ const meta = (request.params._meta ?? {});
152
+ return await callTool(request.params.name, request.params.arguments, meta, env);
153
+ });
154
+ return server;
155
+ }
156
+ export async function runMcp(env = process.env) {
157
+ const server = createServer(env);
158
+ await server.connect(new StdioServerTransport());
159
+ }
@@ -0,0 +1,23 @@
1
+ import type { NotesSnapshot } from "../../../src/boot/snapshot.js";
2
+ import { type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState } from "./transcript.js";
3
+ export type CodexSource = CodexTranscriptSource;
4
+ /** The one marker that makes a persisted notesoup boot verifiable in a native window. */
5
+ export declare function bootMarker(threadId: string, windowId: string): string;
6
+ /** Does this exact native window already carry this thread's own host-injected notesoup boot? */
7
+ export declare function findRecordedBoot(records: readonly CodexRecord[], threadId: string, nativeWindowId: string): boolean;
8
+ /** Boot text is the shared snapshot plus a native window marker; nothing is fabricated without facts. */
9
+ export declare function renderCodexBoot(input: {
10
+ threadId: string;
11
+ agent: string;
12
+ model: string;
13
+ state: CodexTranscriptState;
14
+ records: readonly CodexRecord[];
15
+ notes: NotesSnapshot;
16
+ }): string;
17
+ /** One parser and one validation point for both the boot and its dedupe evidence. */
18
+ export declare function readStartState(source: CodexSource): Promise<{
19
+ state: CodexTranscriptState;
20
+ records: CodexRecord[];
21
+ }>;
22
+ /** A second read after slow work catches a compact/reset that moved the window mid-boot. */
23
+ export declare function recheckStartState(source: CodexSource, expected: CodexTranscriptState): Promise<void>;
@@ -0,0 +1,92 @@
1
+ /** Native Codex facts shared by hook boot and MCP history; no second parser and no invented window. */
2
+ import { DEFAULT_BOOT_TOOL_NAMES } from "../../../src/boot/text.js";
3
+ import { renderBootBlock } from "../../../src/boot/render.js";
4
+ import { readCodexTranscript } from "./transcript.js";
5
+ import { CODEX_PRE_RESET_HINTS, CODEX_WIPE_SENTENCE } from "./text.js";
6
+ /** The one marker that makes a persisted notesoup boot verifiable in a native window. */
7
+ export function bootMarker(threadId, windowId) {
8
+ return `<notesoup:codex_window>\nthread: ${threadId}\nwindow: ${windowId}\n</notesoup:codex_window>`;
9
+ }
10
+ function nativeText(record) {
11
+ const payload = record.payload;
12
+ if (record.type !== "response_item" || payload.type !== "message" || payload.role !== "developer")
13
+ return "";
14
+ const content = payload.content;
15
+ if (!Array.isArray(content))
16
+ return "";
17
+ return content.map((part) => {
18
+ if (typeof part !== "object" || part === null)
19
+ return "";
20
+ const value = part;
21
+ return value.type === "input_text" && typeof value.text === "string" ? value.text : "";
22
+ }).join("\n");
23
+ }
24
+ /** Only the host's own hook additionalContext record is boot evidence, never a quoted marker. */
25
+ function isHookBoot(record) {
26
+ const payload = record.payload;
27
+ if (record.type !== "response_item" || payload.type !== "message" || payload.role !== "developer")
28
+ return false;
29
+ const metadata = payload.internal_chat_message_metadata_passthrough;
30
+ if (typeof metadata !== "object" || metadata === null)
31
+ return false;
32
+ const kinds = metadata.content_item_kinds;
33
+ return Array.isArray(kinds) && kinds.includes("hooks.additional_context");
34
+ }
35
+ /** Does this exact native window already carry this thread's own host-injected notesoup boot? */
36
+ export function findRecordedBoot(records, threadId, nativeWindowId) {
37
+ const marker = bootMarker(threadId, nativeWindowId);
38
+ return records.some((record) => record.owner === threadId
39
+ && record.windowId === nativeWindowId
40
+ && isHookBoot(record)
41
+ && nativeText(record).includes(marker));
42
+ }
43
+ /** Native windows in append order; seq ranges are omitted rather than approximated from raw records. */
44
+ function nativeTree(threadId, state, records) {
45
+ const ids = [];
46
+ for (const record of records) {
47
+ if (record.windowId !== undefined && !ids.includes(record.windowId))
48
+ ids.push(record.windowId);
49
+ }
50
+ if (state.currentWindowId !== undefined && !ids.includes(state.currentWindowId))
51
+ ids.push(state.currentWindowId);
52
+ return {
53
+ trunk: `codex:${threadId}`,
54
+ // The native window UUID is the short name, so the shared `trunk:shortname` rule
55
+ // yields the exact `codex:<thread>:<window>` address history tools serve.
56
+ windows: ids.map((id) => ({ shortName: id, isCurrent: id === state.currentWindowId })),
57
+ };
58
+ }
59
+ /** Boot text is the shared snapshot plus a native window marker; nothing is fabricated without facts. */
60
+ export function renderCodexBoot(input) {
61
+ const { threadId, state } = input;
62
+ const rendered = renderBootBlock({
63
+ agentName: input.agent,
64
+ modelName: input.model,
65
+ tree: nativeTree(threadId, state, input.records),
66
+ notes: input.notes,
67
+ tools: {
68
+ ...DEFAULT_BOOT_TOOL_NAMES,
69
+ wipe: "new_context",
70
+ wipeSentence: CODEX_WIPE_SENTENCE,
71
+ preResetHints: CODEX_PRE_RESET_HINTS,
72
+ },
73
+ });
74
+ // A boot without native window facts would be a fabricated tree, so this marker is required.
75
+ return state.currentWindowId === undefined ? rendered : `${rendered}\n\n${bootMarker(threadId, state.currentWindowId)}`;
76
+ }
77
+ /** One parser and one validation point for both the boot and its dedupe evidence. */
78
+ export async function readStartState(source) {
79
+ const result = await readCodexTranscript(source);
80
+ if (result.state.threadId !== source.threadId)
81
+ throw new Error("Codex transcript belongs to another thread; no notesoup data was used.");
82
+ if (result.state.rootSessionId === "")
83
+ throw new Error("Codex transcript has no root session attribution.");
84
+ return result;
85
+ }
86
+ /** A second read after slow work catches a compact/reset that moved the window mid-boot. */
87
+ export async function recheckStartState(source, expected) {
88
+ const result = await readCodexTranscript(source);
89
+ if (result.state.threadId !== expected.threadId || result.state.rootSessionId !== expected.rootSessionId || result.state.currentWindowId !== expected.currentWindowId) {
90
+ throw new Error("the native window changed while notesoup was preparing its boot; no stale snapshot was injected.");
91
+ }
92
+ }
@@ -0,0 +1,14 @@
1
+ /** Codex's own prose. Shared notesoup wording lives in src/boot; this file only says what Codex changes. */
2
+ /** Native `new_context` takes no argument, unlike empty_brain's sticky note. */
3
+ export declare const CODEX_WIPE_SENTENCE = "If this feels like the right moment, call Codex's native `new_context` and erase yourself with dignity. Write your handoff note first: `new_context` takes no `last_word`.";
4
+ /**
5
+ * Native mode is a prerequisite the plugin cannot switch on. The note authority difference
6
+ * matters: Codex injects hook context as developer context, unlike Pi's user-role boot.
7
+ * Child recovery is a known native gap in this stage, not a notesoup promise.
8
+ */
9
+ export declare const CODEX_PRE_RESET_HINTS: string;
10
+ export declare const CODEX_SETUP_HINT = "Enable and trust the notesoup plugin in Codex, then start or resume the thread. notesoup binds identities from hooks and never from the MCP server's cwd.";
11
+ export declare function unsupportedChildCompaction(): string;
12
+ export declare function missingNativeFacts(reason: string): string;
13
+ /** A boot can still identify itself when the note store itself refused; it must not pretend homes are empty. */
14
+ export declare function notesFailureBoot(reason: string): string;