notesoup 0.52.7 → 0.53.1

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 (59) hide show
  1. package/README.md +3 -1
  2. package/dist/plugins/codex/src/cli.d.ts +2 -0
  3. package/dist/plugins/codex/src/cli.js +25 -0
  4. package/dist/plugins/codex/src/history.d.ts +8 -0
  5. package/dist/plugins/codex/src/history.js +238 -0
  6. package/dist/plugins/codex/src/hooks.d.ts +9 -0
  7. package/dist/plugins/codex/src/hooks.js +196 -0
  8. package/dist/plugins/codex/src/identity.d.ts +35 -0
  9. package/dist/plugins/codex/src/identity.js +134 -0
  10. package/dist/plugins/codex/src/mcp.d.ts +7 -0
  11. package/dist/plugins/codex/src/mcp.js +159 -0
  12. package/dist/plugins/codex/src/state.d.ts +23 -0
  13. package/dist/plugins/codex/src/state.js +92 -0
  14. package/dist/plugins/codex/src/text.d.ts +14 -0
  15. package/dist/plugins/codex/src/text.js +25 -0
  16. package/dist/plugins/codex/src/transcript.d.ts +39 -0
  17. package/dist/plugins/codex/src/transcript.js +313 -0
  18. package/dist/src/boot/render.js +13 -12
  19. package/dist/src/boot/text.d.ts +5 -5
  20. package/dist/src/boot/text.js +15 -28
  21. package/dist/src/budget/text.d.ts +1 -1
  22. package/dist/src/budget/text.js +1 -1
  23. package/dist/test/codex-history.test.d.ts +1 -0
  24. package/dist/test/codex-history.test.js +330 -0
  25. package/dist/test/codex-plugin.test.d.ts +1 -0
  26. package/dist/test/codex-plugin.test.js +365 -0
  27. package/dist/test/dependencies.test.js +8 -2
  28. package/dist/test/dsh.test.js +1 -1
  29. package/dist/test/helpers/dependency-graph.js +1 -1
  30. package/dist/test/model-facing-text.test.js +47 -26
  31. package/dist/test/notes.integration.test.js +3 -0
  32. package/docs/codex.md +91 -0
  33. package/docs/dsh.md +1 -1
  34. package/docs/reset-lifecycle.md +1 -1
  35. package/package.json +6 -3
  36. package/playbook.md +1 -1
  37. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  38. package/plugins/claude/dist/claude/helper.js +27 -37
  39. package/plugins/claude/playbook.md +1 -1
  40. package/plugins/claude/skills/dream/SKILL.md +1 -1
  41. package/plugins/claude/skills/memory/SKILL.md +1 -1
  42. package/plugins/codex/README.md +43 -0
  43. package/plugins/codex/dist/codex/notesoup.js +27801 -0
  44. package/plugins/codex/hooks/hooks.json +41 -0
  45. package/plugins/codex/mcp.json +10 -0
  46. package/plugins/codex/plugin.json +6 -0
  47. package/plugins/codex/src/cli.ts +26 -0
  48. package/plugins/codex/src/history.ts +193 -0
  49. package/plugins/codex/src/hooks.ts +190 -0
  50. package/plugins/codex/src/identity.ts +147 -0
  51. package/plugins/codex/src/mcp.ts +171 -0
  52. package/plugins/codex/src/state.ts +102 -0
  53. package/plugins/codex/src/text.ts +31 -0
  54. package/plugins/codex/src/transcript.ts +275 -0
  55. package/skills/dream/SKILL.md +1 -1
  56. package/skills/memory/SKILL.md +1 -1
  57. package/src/boot/render.ts +13 -11
  58. package/src/boot/text.ts +17 -30
  59. package/src/budget/text.ts +1 -1
@@ -0,0 +1,41 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node \"${PLUGIN_ROOT}/dist/codex/notesoup.js\" hook SessionStart",
9
+ "timeout": 120,
10
+ "statusMessage": "notesoup: reading notes",
11
+ "additionalContextLimit": 0
12
+ }
13
+ ]
14
+ }
15
+ ],
16
+ "SubagentStart": [
17
+ {
18
+ "hooks": [
19
+ {
20
+ "type": "command",
21
+ "command": "node \"${PLUGIN_ROOT}/dist/codex/notesoup.js\" hook SubagentStart",
22
+ "timeout": 120,
23
+ "statusMessage": "notesoup: reading notes",
24
+ "additionalContextLimit": 0
25
+ }
26
+ ]
27
+ }
28
+ ],
29
+ "PreCompact": [
30
+ {
31
+ "hooks": [
32
+ {
33
+ "type": "command",
34
+ "command": "node \"${PLUGIN_ROOT}/dist/codex/notesoup.js\" hook PreCompact",
35
+ "timeout": 60
36
+ }
37
+ ]
38
+ }
39
+ ]
40
+ }
41
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
3
+ "mcpServers": {
4
+ "notesoup": {
5
+ "type": "stdio",
6
+ "command": "node",
7
+ "args": ["${PLUGIN_ROOT}/dist/codex/notesoup.js", "mcp"]
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
+ "name": "notesoup",
4
+ "description": "Host-neutral notes and native history for Codex, with a native-window boot.",
5
+ "keywords": ["notes", "history", "context-window"]
6
+ }
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ /** One bundled helper for both host surfaces: `mcp` speaks stdio JSON-RPC, `hook <Event>` answers a Codex hook. */
3
+ import { runMcp } from "./mcp.js";
4
+ import { readHookInput, runHook } from "./hooks.js";
5
+
6
+ async function main(): Promise<void> {
7
+ const [command, event] = process.argv.slice(2);
8
+ if (command === "mcp") {
9
+ await runMcp();
10
+ return;
11
+ }
12
+ if (command === "hook") {
13
+ const input = await readHookInput(process.stdin);
14
+ const output = await runHook(event, input);
15
+ if (output !== "") process.stdout.write(`${output}\n`);
16
+ return;
17
+ }
18
+ process.stderr.write("usage: notesoup mcp | notesoup hook <SessionStart|SubagentStart|PreCompact>\n");
19
+ process.exitCode = 64;
20
+ }
21
+
22
+ main().catch((error: unknown) => {
23
+ // A hook must not turn its own failure into a host crash; stderr is the only safe channel.
24
+ process.stderr.write(`notesoup: ${error instanceof Error ? error.message : String(error)}\n`);
25
+ process.exitCode = 1;
26
+ });
@@ -0,0 +1,193 @@
1
+ /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
+ import { projectHistory, type DecodedHistoryItem, type DecodedHistoryWindow, type HistoryProjection } from "../../../src/history/history.js";
3
+ import { nativeObject as obj, nativeString as str, readCodexTranscript, type CodexRecord, type CodexTranscriptSource, type CodexTranscriptState, type NativeObject } from "./transcript.js";
4
+ export type { CodexTranscriptSource } from "./transcript.js";
5
+ export type CodexHistoryState = CodexTranscriptState & { projection: HistoryProjection };
6
+
7
+ const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
8
+ const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
9
+ // protocol.rs serializes v1 task_* spellings; turn_* are explicit serde aliases.
10
+ const HOST_EVENTS = new Set(["token_count", "thread_goal_updated", "task_started", "task_complete", "turn_started", "turn_complete", "turn_aborted", "thread_settings_applied", "entered_review_mode", "exited_review_mode", "patch_apply_end", "sub_agent_activity"]);
11
+ const HOST_ITEMS = new Set(["Plan", "FileChange", "CollabAgentToolCall", "SubAgentActivity", "ImageView", "Extension", "EnteredReviewMode", "ExitedReviewMode"]);
12
+ const OPAQUE_RESPONSES = new Set(["reasoning", "compaction", "compaction_summary", "context_compaction", "image_generation_call"]);
13
+ const HOST_RESPONSES = new Set(["configuration_update", "tool_search_call", "tool_search_output", "web_search_call"]);
14
+ function optionalString(value: unknown, field: string): string | undefined { return value == null ? undefined : str(value, field); }
15
+ function array(value: unknown, field: string): unknown[] {
16
+ if (!Array.isArray(value)) throw new Error(`Invalid Codex ${field}: expected an array`);
17
+ return value;
18
+ }
19
+ /** No image/audio decoding, opaque plaintext recovery, or stringification disguised as message text. */
20
+ function textContent(value: unknown): string {
21
+ return array(value, "content").map((value) => {
22
+ const part = obj(value, "content part");
23
+ switch (part.type) {
24
+ case "input_text": case "output_text": return str(part.text, "content text");
25
+ case "input_image": return "[Codex image content omitted]";
26
+ case "input_audio": return "[Codex audio content omitted]";
27
+ case "encrypted_content": return "[Codex encrypted content unavailable]";
28
+ default: throw new Error(`Unsupported Codex content part: ${String(part.type)}`);
29
+ }
30
+ }).join("\n");
31
+ }
32
+ function output(value: unknown): string { return typeof value === "string" ? value : textContent(value); }
33
+ function argumentsOf(raw: string): NativeObject {
34
+ // Custom/invalid/non-object JSON cannot fit the shared object field. Keep the
35
+ // original wire string under an explicit raw label rather than lose it.
36
+ try {
37
+ const parsed: unknown = JSON.parse(raw);
38
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as NativeObject;
39
+ } catch { /* Native tool calls may persist unparseable model arguments. */ }
40
+ return { raw_arguments: raw };
41
+ }
42
+ function callKey(record: CodexRecord, callId: string): string { return `${record.owner}:${callId}`; }
43
+ function context(record: CodexRecord, text: string): DecodedHistoryItem {
44
+ if (!record.windowId) throw new Error(`Unavailable Codex history: native window identity missing at seq ${record.seq}; cannot assign a stable window address`);
45
+ return { seq: record.seq, windowId: record.windowId, role: "system", text, createdAt: record.timestamp };
46
+ }
47
+ function host(record: CodexRecord, kind: string, payload: unknown): DecodedHistoryItem { return context(record, `Codex ${kind}\n${JSON.stringify(payload)}`); }
48
+
49
+ type ToolFact = { error?: boolean; text?: string };
50
+ /** Presentation records contribute OUTCOME evidence, never duplicate raw tool dialogue. */
51
+ function fact(item: NativeObject): ToolFact {
52
+ if (item.type === "CommandExecution") {
53
+ const status = str(item.status, "CommandExecution.status");
54
+ if (!["completed", "failed", "declined", "in_progress"].includes(status)) throw new Error(`Unsupported Codex command status: ${status}`);
55
+ return { error: status === "failed" || status === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0), text: optionalString(item.formatted_output, "formatted_output") };
56
+ }
57
+ if (item.type === "McpToolCall") {
58
+ const result = item.result == null ? undefined : obj(item.result, "MCP result");
59
+ if (result?.isError != null && typeof result.isError !== "boolean") throw new Error("Invalid Codex MCP isError");
60
+ return { error: item.status === "failed" || item.error != null || result?.isError === true, ...(result === undefined ? {} : { text: JSON.stringify(result) }) };
61
+ }
62
+ if (item.type === "DynamicToolCall") return { error: item.success === false || item.status === "failed" || item.error != null };
63
+ if (item.type === "FileChange" || item.type === "CollabAgentToolCall") return { error: item.status === "failed" || item.status === "declined" || item.status === "interrupted" };
64
+ return {};
65
+ }
66
+ function toolDisplay(item: NativeObject): boolean {
67
+ return ["CommandExecution", "McpToolCall", "DynamicToolCall", "CollabAgentToolCall", "FileChange", "ImageView", "Extension"].includes(String(item.type));
68
+ }
69
+ function response(record: CodexRecord, facts: Map<string, ToolFact>): DecodedHistoryItem {
70
+ const p = record.payload, type = str(p.type, "response_item.type"), base = context(record, "");
71
+ if (type === "message") {
72
+ if (!["user", "assistant", "system", "developer"].includes(str(p.role, "message.role"))) throw new Error(`Unsupported Codex message role: ${String(p.role)}`);
73
+ return { ...base, role: record.metadata?.compaction_output === true ? "system" : p.role as "user" | "assistant" | "system" | "developer", text: textContent(p.content) };
74
+ }
75
+ if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
76
+ const callId = optionalString(p.call_id, "call_id") ?? (type === "local_shell_call" ? optionalString(p.id, "local shell id") : undefined);
77
+ if (!callId) throw new Error("Invalid Codex tool call: missing native call ID");
78
+ const name = type === "local_shell_call" ? "local_shell" : str(p.name, "tool name");
79
+ const args = type === "local_shell_call" ? obj(p.action, "local shell action") : type === "custom_tool_call" ? { input: str(p.input, "custom tool input") } : argumentsOf(str(p.arguments, "function arguments"));
80
+ return { ...base, role: "tool_call", toolName: p.namespace ? `${str(p.namespace, "namespace")}.${name}` : name, toolCallId: callKey(record, callId), arguments: args };
81
+ }
82
+ if (type === "function_call_output" || type === "custom_tool_call_output") {
83
+ const callId = optionalString(p.call_id, "output.call_id"), recorded = callId ? facts.get(callKey(record, callId)) : undefined;
84
+ return { ...base, role: "tool", text: output(p.output), ...(callId ? { toolCallId: callKey(record, callId) } : {}), ...(p.name == null ? {} : { toolName: str(p.name, "output.name") }), ...(recorded?.error === undefined ? {} : { toolError: recorded.error }) };
85
+ }
86
+ if (type === "agent_message") return host(record, "agent_message", { author: p.author, recipient: p.recipient, text: textContent(p.content) });
87
+ if (OPAQUE_RESPONSES.has(type)) {
88
+ // Preserve recorded summaries and available metadata, not encrypted blobs or image bytes.
89
+ const { encrypted_content: _encrypted, result: _image, ...readable } = p;
90
+ return host(record, `${type} (opaque content omitted; not recovered plaintext)`, readable);
91
+ }
92
+ if (HOST_RESPONSES.has(type)) return host(record, type, p);
93
+ throw new Error(`Unsupported Codex response item: ${type}`);
94
+ }
95
+
96
+ /** One display record without a raw equivalent (e.g. user-shell command). */
97
+ function standaloneTool(record: CodexRecord, item: NativeObject): DecodedHistoryItem {
98
+ const base = context(record, ""), recorded = fact(item);
99
+ if (item.type === "CommandExecution") {
100
+ array(item.command, "command").forEach((part) => str(part, "command argument"));
101
+ return { ...base, role: "tool", toolName: "terminal", arguments: { command: item.command, cwd: item.cwd, source: item.source, ...(item.interaction_input == null ? {} : { interaction_input: item.interaction_input }) }, text: recorded.text ?? JSON.stringify({ stdout: item.stdout, stderr: item.stderr, aggregated_output: item.aggregated_output }), recordedStatus: item.status === "in_progress" ? "unfinished" : recorded.error ? "error" : "ok" };
102
+ }
103
+ const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
104
+ return { ...base, role: "tool", toolName: name, arguments: obj(item.arguments, "MCP arguments"), text: recorded.text ?? (item.error == null ? "" : JSON.stringify(item.error)), recordedStatus: item.status === "inProgress" ? "unfinished" : recorded.error ? "error" : "ok" };
105
+ }
106
+
107
+ export async function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState> {
108
+ const { state, records, highestSeq } = await readCodexTranscript(source);
109
+ const facts = new Map<string, ToolFact>(), callsSeen = new Set<string>(), responseIdsSeen = new Set<string>();
110
+ const windows = new Map<string, DecodedHistoryWindow>(), branchSeqs = new Set<number>();
111
+ const addWindow = (nativeId: string, createdAt?: string): DecodedHistoryWindow => {
112
+ const windowId = `codex:${source.threadId}:${nativeId}`;
113
+ let window = windows.get(windowId);
114
+ if (!window) { window = { windowId, createdAt, items: [] }; windows.set(windowId, window); }
115
+ return window;
116
+ };
117
+ // Outcome inventory can enrich the raw result even when ItemCompleted follows it.
118
+ for (const record of records) {
119
+ const p = record.payload;
120
+ if (record.type === "event_msg" && p.type === "item_completed") {
121
+ if (p.thread_id !== record.owner) throw new Error("Invalid Codex ItemCompleted thread identity");
122
+ const item = obj(p.item, "ItemCompleted.item");
123
+ if (toolDisplay(item)) facts.set(callKey(record, str(item.id, "TurnItem.id")), fact(item));
124
+ } else if (record.type === "event_msg" && p.type === "patch_apply_end") {
125
+ if (typeof p.success !== "boolean") throw new Error("Invalid Codex patch_apply_end.success");
126
+ facts.set(callKey(record, str(p.call_id, "patch call_id")), { error: !p.success });
127
+ } else if (record.type === "event_msg" && p.type === "mcp_tool_call_end") {
128
+ const result = obj(p.result, "MCP Result envelope");
129
+ const ok = result.Ok == null ? undefined : obj(result.Ok, "MCP Result.Ok");
130
+ if (ok === undefined && typeof result.Err !== "string") throw new Error("Invalid Codex MCP Result: expected Ok or Err");
131
+ facts.set(callKey(record, str(p.call_id, "MCP call_id")), { error: result.Err != null || ok?.isError === true, text: JSON.stringify(result) });
132
+ }
133
+ }
134
+ for (const record of records) {
135
+ branchSeqs.add(record.seq);
136
+ if (record.windowId) addWindow(record.windowId, record.type === "session_meta" || record.type === "compacted" ? record.timestamp : undefined);
137
+ const p = record.payload;
138
+ let item: DecodedHistoryItem | undefined;
139
+ switch (record.type) {
140
+ case "session_meta":
141
+ if (p.subagent_history_start_ordinal != null) item = context(record, `Codex copied subagent inference prefix omitted: child-local history starts at native ordinal ${String(p.subagent_history_start_ordinal)}. Copied model context does not prove original parent event addresses.`);
142
+ break;
143
+ case "response_item": {
144
+ item = response(record, facts);
145
+ if (p.id != null) responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
146
+ if (item.role === "tool_call" && item.toolCallId) {
147
+ if (callsSeen.has(item.toolCallId)) throw new Error(`Unavailable Codex history: duplicate native call ID ${item.toolCallId}`);
148
+ callsSeen.add(item.toolCallId);
149
+ }
150
+ break;
151
+ }
152
+ case "compacted": item = context(record, `Codex compaction boundary\n${JSON.stringify({ message: p.message, window_number: p.window_number, first_window_id: p.first_window_id, previous_window_id: p.previous_window_id, window_id: p.window_id, replacement_history_items: Array.isArray(p.replacement_history) ? p.replacement_history.length : null })}\nreplacement_history is an inference checkpoint, not new conversation events.`); break;
153
+ case "event_msg": {
154
+ const type = str(p.type, "event_msg.type");
155
+ if (DISPLAY_COPIES.has(type)) break;
156
+ // A rollback changes the native selected window retrospectively. Until its
157
+ // turn semantics are decoded, don't return stale-but-plausible boot facts.
158
+ if (type === "thread_rolled_back") throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
159
+ if (type === "patch_apply_end" && callsSeen.has(callKey(record, str(p.call_id, "patch call_id")))) break;
160
+ if (type === "mcp_tool_call_end") {
161
+ const call = callKey(record, str(p.call_id, "MCP call_id"));
162
+ if (!callsSeen.has(call)) item = host(record, "MCP completion without a recorded raw call", p);
163
+ break;
164
+ }
165
+ if (type === "item_completed") {
166
+ const display = obj(p.item, "ItemCompleted.item"), kind = str(display.type, "TurnItem.type");
167
+ if (ITEM_COPIES.has(kind)) break;
168
+ if (toolDisplay(display) && callsSeen.has(callKey(record, str(display.id, "TurnItem.id")))) break;
169
+ if (kind === "CommandExecution" || kind === "McpToolCall") {
170
+ item = standaloneTool(record, display);
171
+ } else if (kind === "FunctionCallOutput") {
172
+ // hook_runtime.rs record_pending_input persists raw output FIRST,
173
+ // then emits this presentation copy with the SAME response-item ID.
174
+ if (!responseIdsSeen.has(callKey(record, str(display.id, "FunctionCallOutput.id")))) item = host(record, "FunctionCallOutput display without raw output", display);
175
+ } else if (HOST_ITEMS.has(kind) || kind === "DynamicToolCall") item = host(record, kind, display);
176
+ else throw new Error(`Unsupported Codex TurnItem: ${kind}`);
177
+ } else if (HOST_EVENTS.has(type)) {
178
+ // Lifecycle's repeated final answer isn't a second assistant message.
179
+ const { last_agent_message: _displayCopy, ...facts } = p;
180
+ item = host(record, type, facts);
181
+ }
182
+ else throw new Error(`Unsupported Codex persisted event: ${type}`);
183
+ break;
184
+ }
185
+ case "turn_context": case "token_usage_record": case "security_risk_score": case "inter_agent_communication_metadata": break;
186
+ case "world_state": item = context(record, "Codex world_state snapshot/patch omitted from the text projection; not a newly spoken message."); break;
187
+ case "inter_agent_communication": item = host(record, "inter-agent communication", { author: p.author, recipient: p.recipient, content: p.encrypted_content == null ? p.content : "[encrypted content unavailable]", trigger_turn: p.trigger_turn }); break;
188
+ case "retained_context": case "realtime_item": item = context(record, `Codex ${record.type} omitted from text projection; native structured/retained context is not newly spoken dialogue.`); break;
189
+ }
190
+ if (item) addWindow(record.windowId!).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
191
+ }
192
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
193
+ }
@@ -0,0 +1,190 @@
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, type NotesSnapshot } from "../../../src/boot/snapshot.js";
5
+ import { isFilesystemError, slugify } from "../../../src/notes/index.js";
6
+ import { CodexIdentityError, modelSlug, notesHome, notesIdentityFor, pluginDataRoot, readBinding, safeThreadId, writeBinding, type ThreadBinding } from "./identity.js";
7
+ import { findRecordedBoot, readStartState, recheckStartState, renderCodexBoot } from "./state.js";
8
+ import { CODEX_SETUP_HINT, missingNativeFacts, notesFailureBoot, unsupportedChildCompaction } from "./text.js";
9
+
10
+ const MAX_HOOK_INPUT_BYTES = 1024 * 1024;
11
+ /** additionalContextLimit:0 disables host spilling, so this local cap is the only truncation guard. */
12
+ export const MAX_BOOT_BYTES = 128 * 1024;
13
+
14
+ type HookPayload = Record<string, unknown>;
15
+
16
+ function text(value: unknown): string | undefined {
17
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
18
+ }
19
+
20
+ function shellFree(reason: unknown): string {
21
+ const value = reason instanceof Error ? reason.message : String(reason);
22
+ return value.replace(/[\r\n]+/g, " ").slice(0, 500);
23
+ }
24
+
25
+ export function warningOutput(message: string): string {
26
+ return JSON.stringify({ systemMessage: message });
27
+ }
28
+
29
+ export function contextOutput(event: "SessionStart" | "SubagentStart", text: string): string {
30
+ return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
31
+ }
32
+
33
+ /** An oversized boot is refused rather than silently truncated or spilled by the host. */
34
+ export function bootWithinCap(boot: string): string | undefined {
35
+ const bytes = Buffer.byteLength(boot, "utf8");
36
+ return bytes <= MAX_BOOT_BYTES
37
+ ? undefined
38
+ : `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.`;
39
+ }
40
+
41
+ export async function readHookInput(stream: NodeJS.ReadableStream): Promise<string> {
42
+ return await new Promise((resolveInput, reject) => {
43
+ let size = 0;
44
+ const chunks: Buffer[] = [];
45
+ stream.on("data", (chunk: Buffer | string) => {
46
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
47
+ size += bytes.length;
48
+ if (size > MAX_HOOK_INPUT_BYTES) {
49
+ stream.pause();
50
+ reject(new Error("hook input exceeds 1 MiB"));
51
+ return;
52
+ }
53
+ chunks.push(bytes);
54
+ });
55
+ stream.on("end", () => resolveInput(Buffer.concat(chunks).toString("utf8")));
56
+ stream.on("error", reject);
57
+ });
58
+ }
59
+
60
+ type StartTarget = { threadId: string; rootSessionId: string; cwd: string; agent: string; model: string; agentType?: string };
61
+
62
+ function samePath(left: string, right: string): boolean {
63
+ const a = resolve(left), b = resolve(right);
64
+ if (a === b) return true;
65
+ try { return realpathSync(a) === realpathSync(b); } catch { return false; }
66
+ }
67
+
68
+ async function snapshotFor(binding: ThreadBinding, model: string): Promise<{ notes: NotesSnapshot; failure?: string }> {
69
+ const openedAt = Date.now();
70
+ try {
71
+ return { notes: await loadNotesSnapshot(notesIdentityFor(binding, model), openedAt) };
72
+ } catch (error) {
73
+ if (isFilesystemError(error)) return { notes: unavailableNotesSnapshot(openedAt) };
74
+ return { notes: unavailableNotesSnapshot(openedAt), failure: shellFree(error) };
75
+ }
76
+ }
77
+
78
+ async function startHook(event: "SessionStart" | "SubagentStart", payload: HookPayload, env: NodeJS.ProcessEnv): Promise<string> {
79
+ let root: string;
80
+ try {
81
+ root = pluginDataRoot(env);
82
+ } catch (error) {
83
+ return warningOutput(shellFree(error));
84
+ }
85
+ const rootSession = text(payload.session_id);
86
+ const childThread = text(payload.agent_id);
87
+ const threadId = event === "SubagentStart" ? childThread : rootSession;
88
+ const cwd = text(payload.cwd);
89
+ const model = modelSlug(payload.model);
90
+ if (threadId === undefined || rootSession === undefined || cwd === undefined || model === undefined) {
91
+ return warningOutput(`notesoup: the ${event} payload is missing a native thread, cwd, or model fact. ${CODEX_SETUP_HINT}`);
92
+ }
93
+ const agentType = event === "SubagentStart" ? text(payload.agent_type) : undefined;
94
+ const agent = event === "SubagentStart"
95
+ ? (agentType === undefined ? "anonymous" : slugify(agentType))
96
+ : slugify(env.NOTESOUP_AGENT ?? "anonymous");
97
+ let target: StartTarget;
98
+ try {
99
+ target = { threadId: safeThreadId(threadId), rootSessionId: rootSession, cwd, agent, model, ...(agentType === undefined ? {} : { agentType }) };
100
+ } catch (error) {
101
+ return warningOutput(shellFree(error));
102
+ }
103
+ const transcriptPath = text(payload.transcript_path);
104
+ if (transcriptPath === undefined) return warningOutput(missingNativeFacts("the hook supplied no transcript_path"));
105
+ let native: Awaited<ReturnType<typeof readStartState>>;
106
+ try {
107
+ native = await readStartState({ transcriptPath, threadId: target.threadId });
108
+ if (native.state.rootSessionId !== target.rootSessionId) throw new CodexIdentityError("mismatched_root", "The native transcript's root session does not match the hook's session_id.");
109
+ if (!samePath(native.state.cwd, target.cwd)) throw new CodexIdentityError("mismatched_cwd", "The native transcript's cwd does not match the hook's cwd; refusing to bind a guessed project.");
110
+ if (native.state.currentWindowId === undefined) throw new CodexIdentityError("missing_window", "The native transcript has no materialized context window yet.");
111
+ } catch (error) {
112
+ return warningOutput(missingNativeFacts(shellFree(error)));
113
+ }
114
+ const binding: ThreadBinding = {
115
+ version: 1,
116
+ threadId: target.threadId,
117
+ rootSessionId: native.state.rootSessionId,
118
+ cwd: target.cwd,
119
+ model: target.model,
120
+ agent: target.agent,
121
+ home: notesHome(env),
122
+ transcriptPath,
123
+ windowId: native.state.currentWindowId,
124
+ ...(target.agentType === undefined ? {} : { agentType: target.agentType }),
125
+ boundAt: new Date().toISOString(),
126
+ };
127
+ let existing: ThreadBinding | undefined;
128
+ try {
129
+ existing = await readBinding(root, target.threadId);
130
+ } catch (error) {
131
+ if (!(error instanceof CodexIdentityError && error.code === "unknown_thread")) return warningOutput(`notesoup: ${shellFree(error)}`);
132
+ }
133
+ if (existing !== undefined && existing.rootSessionId !== binding.rootSessionId) {
134
+ 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.");
135
+ }
136
+ try {
137
+ await writeBinding(root, binding);
138
+ } catch (error) {
139
+ return warningOutput(`notesoup: could not store this thread's binding (${shellFree(error)}). No boot was injected.`);
140
+ }
141
+ if (findRecordedBoot(native.records, target.threadId, binding.windowId)) {
142
+ // This exact native window already has this thread's own host-injected boot.
143
+ return "";
144
+ }
145
+ const snapshot = await snapshotFor(binding, target.model);
146
+ try {
147
+ await recheckStartState({ transcriptPath, threadId: target.threadId }, native.state);
148
+ } catch (error) {
149
+ return warningOutput(`notesoup: ${shellFree(error)}`);
150
+ }
151
+ const boot = renderCodexBoot({
152
+ threadId: target.threadId,
153
+ agent: target.agent,
154
+ model: target.model,
155
+ state: native.state,
156
+ records: native.records,
157
+ notes: snapshot.notes,
158
+ });
159
+ const withFailure = snapshot.failure === undefined ? boot : `${boot}\n\n${notesFailureBoot(snapshot.failure)}`;
160
+ const tooLarge = bootWithinCap(withFailure);
161
+ if (tooLarge !== undefined) return warningOutput(tooLarge);
162
+ return contextOutput(event, withFailure);
163
+ }
164
+
165
+ function preCompactHook(payload: HookPayload): string {
166
+ // A child rollover has no supported post-compact boot in this native version; stop before history is cut.
167
+ return text(payload.agent_id) === undefined ? "" : JSON.stringify({ continue: false, stopReason: unsupportedChildCompaction() });
168
+ }
169
+
170
+ /** One hook event in, one stdout body out; an unrecognized event is transparent. */
171
+ export async function runHook(event: string | undefined, input: string, env: NodeJS.ProcessEnv = process.env): Promise<string> {
172
+ let payload: HookPayload;
173
+ try {
174
+ const value: unknown = JSON.parse(input);
175
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("hook input is not an object");
176
+ payload = value as HookPayload;
177
+ } catch (error) {
178
+ return warningOutput(`notesoup: could not read its hook input (${shellFree(error)}). ${CODEX_SETUP_HINT}`);
179
+ }
180
+ // The payload's own event name is advisory; the configured command names the event.
181
+ switch (event) {
182
+ case "SessionStart":
183
+ case "SubagentStart":
184
+ return await startHook(event, payload, env);
185
+ case "PreCompact":
186
+ return preCompactHook(payload);
187
+ default:
188
+ return "";
189
+ }
190
+ }
@@ -0,0 +1,147 @@
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, type NotesIdentity } from "../../../src/notes/index.js";
6
+
7
+ const SAFE_THREAD_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8
+ const BINDINGS = "bindings";
9
+
10
+ /** A refusal the model can read and act on, not a crash. */
11
+ export class CodexIdentityError extends Error {
12
+ constructor(readonly code: string, message: string) {
13
+ super(message);
14
+ this.name = "CodexIdentityError";
15
+ }
16
+ }
17
+
18
+ export type ThreadBinding = Readonly<{
19
+ version: 1;
20
+ threadId: string;
21
+ rootSessionId: string;
22
+ cwd: string;
23
+ /** Session-start model, used only to label this window's boot. */
24
+ model: string;
25
+ agent: string;
26
+ home: string;
27
+ transcriptPath: string;
28
+ /** Native window at bind time; a later MCP call must name this same window. */
29
+ windowId: string;
30
+ agentType?: string;
31
+ boundAt: string;
32
+ }>;
33
+
34
+ export function safeThreadId(value: unknown, field = "threadId"): string {
35
+ if (typeof value !== "string" || !SAFE_THREAD_ID.test(value) || value === "." || value === "..") {
36
+ throw new CodexIdentityError("invalid_thread", `Codex ${field} is missing or not a safe native thread id.`);
37
+ }
38
+ return value;
39
+ }
40
+
41
+ /** The portable server and the hook must share this root; Codex injects it into both. */
42
+ export function pluginDataRoot(env: NodeJS.ProcessEnv = process.env): string {
43
+ const value = env.PLUGIN_DATA;
44
+ if (typeof value !== "string" || value.trim() === "" || !isAbsolute(value)) {
45
+ 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.");
46
+ }
47
+ return resolve(value);
48
+ }
49
+
50
+ export function notesHome(env: NodeJS.ProcessEnv = process.env): string {
51
+ const value = env.NOTESOUP_HOME;
52
+ return value !== undefined && value.trim() !== "" ? resolve(value) : join(homedir(), ".agents", "notes");
53
+ }
54
+
55
+ /** Native ids arrive provider-prefixed; @model is the last segment, slugged like every other home. */
56
+ export function modelSlug(value: unknown): string | undefined {
57
+ if (typeof value !== "string") return undefined;
58
+ const id = value.trim();
59
+ if (id === "") return undefined;
60
+ const slug = slugify(id.split("/").pop() ?? id);
61
+ return slug === "root" ? undefined : slug;
62
+ }
63
+
64
+ function bindingPath(root: string, threadId: string): string {
65
+ return join(root, BINDINGS, `${safeThreadId(threadId)}.json`);
66
+ }
67
+
68
+ function required(value: unknown, field: string): string {
69
+ if (typeof value !== "string" || value.length === 0) throw new CodexIdentityError("invalid_binding", `Stored notesoup binding is missing ${field}; resume the Codex thread once so its hooks rebind it.`);
70
+ return value;
71
+ }
72
+
73
+ /** Validate every field before it becomes an identity; a corrupt binding never half-applies. */
74
+ export async function readBinding(root: string, threadId: string): Promise<ThreadBinding> {
75
+ let raw: string;
76
+ try {
77
+ raw = await readFile(bindingPath(root, threadId), "utf8");
78
+ } catch (error) {
79
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
80
+ 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.");
81
+ }
82
+ throw error;
83
+ }
84
+ let value: unknown;
85
+ try {
86
+ value = JSON.parse(raw);
87
+ } catch {
88
+ throw new CodexIdentityError("invalid_binding", "The stored notesoup binding is not valid JSON; resume the Codex thread once so its hooks rebind it.");
89
+ }
90
+ const row = value as Record<string, unknown>;
91
+ if (row.version !== 1) throw new CodexIdentityError("invalid_binding", "The stored notesoup binding has an unsupported version; resume the Codex thread once so its hooks rebind it.");
92
+ const storedThread = safeThreadId(row.threadId, "binding threadId");
93
+ if (storedThread !== threadId) throw new CodexIdentityError("mismatched_thread", "The stored notesoup binding belongs to another thread; refuse to read or write with it.");
94
+ const home = required(row.home, "home");
95
+ const cwd = required(row.cwd, "cwd");
96
+ const transcriptPath = required(row.transcriptPath, "transcriptPath");
97
+ const windowId = required(row.windowId, "windowId");
98
+ if (!isAbsolute(home) || !isAbsolute(cwd) || !isAbsolute(transcriptPath)) throw new CodexIdentityError("invalid_binding", "The stored notesoup binding contains a non-absolute path.");
99
+ return {
100
+ version: 1,
101
+ threadId,
102
+ rootSessionId: required(row.rootSessionId, "rootSessionId"),
103
+ cwd,
104
+ model: required(row.model, "model"),
105
+ agent: required(row.agent, "agent"),
106
+ home,
107
+ transcriptPath,
108
+ windowId,
109
+ ...(typeof row.agentType === "string" && row.agentType.length > 0 ? { agentType: row.agentType } : {}),
110
+ boundAt: required(row.boundAt, "boundAt"),
111
+ };
112
+ }
113
+
114
+ /** Atomic replace; a failed write never leaves a half binding behind. */
115
+ export async function writeBinding(root: string, binding: ThreadBinding): Promise<void> {
116
+ const path = bindingPath(root, binding.threadId);
117
+ await mkdir(join(root, BINDINGS), { recursive: true });
118
+ const temp = `${path}.${process.pid}.${Date.now()}.tmp`;
119
+ await writeFile(temp, `${JSON.stringify(binding)}\n`, { mode: 0o600 });
120
+ await rename(temp, path);
121
+ }
122
+
123
+ export function notesIdentityFor(binding: ThreadBinding, model: string): NotesIdentity {
124
+ return snapshotNotesIdentity({
125
+ home: binding.home,
126
+ sessionId: binding.threadId,
127
+ projectKey: projectKey(binding.cwd, binding.home),
128
+ agent: binding.agent,
129
+ model,
130
+ });
131
+ }
132
+
133
+ /** The current turn's model, not the cached session-start model, chooses @model. */
134
+ export function turnModel(meta: Record<string, unknown>): string {
135
+ let value: unknown = meta["x-codex-turn-metadata"];
136
+ if (typeof value === "string") {
137
+ try { value = JSON.parse(value); } catch { value = undefined; }
138
+ }
139
+ const model = typeof value === "object" && value !== null ? (value as Record<string, unknown>).model : undefined;
140
+ const slug = modelSlug(model);
141
+ if (slug === undefined) 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.");
142
+ return slug;
143
+ }
144
+
145
+ export function rootSessionIdOf(meta: Record<string, unknown>): string {
146
+ return required(meta.sessionId, "MCP sessionId");
147
+ }