notesoup 0.52.7 → 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 (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 +11 -10
  19. package/dist/src/boot/text.d.ts +4 -5
  20. package/dist/src/boot/text.js +14 -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 +41 -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 +24 -35
  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 +27800 -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 +11 -9
  58. package/src/boot/text.ts +16 -30
  59. package/src/budget/text.ts +1 -1
package/README.md CHANGED
@@ -81,7 +81,7 @@ Environment variables:
81
81
  - `NOTESOUP_DISABLED` — presence-style kill switch: any value but an explicit no (`0`, `false`, `no`, `off`) turns notesoup off. On Pi the extension registers nothing at all; on Claude the mod passes every event through and native compaction behaves as if the mod were absent.
82
82
  - `NOTESOUP_KEEP_MEMORY` — Claude only: keep Claude Code's auto-memory guidance, which notesoup omits by default (its summarization guidance is always omitted). Enabled by any non-empty value except `0`, `false`, `no`, or `off` (case-insensitive); read at session startup.
83
83
  - `NOTESOUP_HOME` — overrides the notes root (default `~/.agents/notes`).
84
- - `NOTESOUP_AGENT` — overrides the agent name on Pi (default `anonymous`).
84
+ - `NOTESOUP_AGENT` — overrides the root agent name on Pi and Codex (default `anonymous`; Codex children use `agent_type`).
85
85
 
86
86
  ## Documentation
87
87
 
@@ -90,6 +90,7 @@ Environment variables:
90
90
  - [Standalone notes library](docs/notes-library.md) — use the notes store from Node, no Pi required
91
91
  - [DeepSeek Harness](docs/dsh.md) — adapter and profile patch for dsh 0.2.1-alpha.2
92
92
  - [Claude Code Mod](docs/claude-code-mod.md) — early-access notes and persisted-session history tools for Claude Code
93
+ - [Codex plugin](docs/codex.md) — native notes boot, persisted history and native `new_context` for Codex 0.160.1
93
94
  - [Skills and dream](docs/skills.md) — `/skill:memory`, `/skill:dream`, the `dream_*` tools and the dream lock
94
95
 
95
96
  ## Development
@@ -110,6 +111,7 @@ The repository splits host-neutral code from host plugins:
110
111
  | `plugins/pi/` | The Pi extension (`plugins/pi/index.ts` is what `pi.extensions` loads from source). |
111
112
  | `plugins/claude/` | The self-contained Claude Code plugin (`.claude-plugin/`, `hooks/`, bundled `dist/claude/helper.js`, skills and playbook), with its adapter sources in `plugins/claude/src/`. |
112
113
  | `plugins/dsh/` | The Cordis rows published as `notesoup/dsh` and `notesoup/dsh/engine`. |
114
+ | `plugins/codex/` | The Agent Plugins package for Codex 0.160.1: manifests, hooks, and the bundled `dist/codex/notesoup.js` MCP/hook helper. |
113
115
 
114
116
  Each plugin owns its host's words — Pi's pre-reset hints and `last_word` nudge live in `plugins/pi/text.ts`, Claude's reset and missing-history prose in `plugins/claude/src/text.ts` — while the shared boot, protocol and warning bodies stay in `src/boot/text.ts` and `src/budget/text.ts`.
115
117
 
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,25 @@
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
+ async function main() {
6
+ const [command, event] = process.argv.slice(2);
7
+ if (command === "mcp") {
8
+ await runMcp();
9
+ return;
10
+ }
11
+ if (command === "hook") {
12
+ const input = await readHookInput(process.stdin);
13
+ const output = await runHook(event, input);
14
+ if (output !== "")
15
+ 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
+ main().catch((error) => {
22
+ // A hook must not turn its own failure into a host crash; stderr is the only safe channel.
23
+ process.stderr.write(`notesoup: ${error instanceof Error ? error.message : String(error)}\n`);
24
+ process.exitCode = 1;
25
+ });
@@ -0,0 +1,8 @@
1
+ /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
+ import { type HistoryProjection } from "../../../src/history/history.js";
3
+ import { type CodexTranscriptSource, type CodexTranscriptState } from "./transcript.js";
4
+ export type { CodexTranscriptSource } from "./transcript.js";
5
+ export type CodexHistoryState = CodexTranscriptState & {
6
+ projection: HistoryProjection;
7
+ };
8
+ export declare function readCodexHistory(source: CodexTranscriptSource): Promise<CodexHistoryState>;
@@ -0,0 +1,238 @@
1
+ /** Codex-owned decoding; selection, pairing, paging and budgets belong to shared history/tools. */
2
+ import { projectHistory } from "../../../src/history/history.js";
3
+ import { nativeObject as obj, nativeString as str, readCodexTranscript } from "./transcript.js";
4
+ const DISPLAY_COPIES = new Set(["user_message", "agent_message", "agent_reasoning", "agent_reasoning_raw_content", "context_compacted", "web_search_end", "image_generation_end"]);
5
+ const ITEM_COPIES = new Set(["UserMessage", "AgentMessage", "Reasoning", "ContextCompaction", "WebSearch", "ImageGeneration", "HookPrompt"]);
6
+ // protocol.rs serializes v1 task_* spellings; turn_* are explicit serde aliases.
7
+ 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"]);
8
+ const HOST_ITEMS = new Set(["Plan", "FileChange", "CollabAgentToolCall", "SubAgentActivity", "ImageView", "Extension", "EnteredReviewMode", "ExitedReviewMode"]);
9
+ const OPAQUE_RESPONSES = new Set(["reasoning", "compaction", "compaction_summary", "context_compaction", "image_generation_call"]);
10
+ const HOST_RESPONSES = new Set(["configuration_update", "tool_search_call", "tool_search_output", "web_search_call"]);
11
+ function optionalString(value, field) { return value == null ? undefined : str(value, field); }
12
+ function array(value, field) {
13
+ if (!Array.isArray(value))
14
+ throw new Error(`Invalid Codex ${field}: expected an array`);
15
+ return value;
16
+ }
17
+ /** No image/audio decoding, opaque plaintext recovery, or stringification disguised as message text. */
18
+ function textContent(value) {
19
+ return array(value, "content").map((value) => {
20
+ const part = obj(value, "content part");
21
+ switch (part.type) {
22
+ case "input_text":
23
+ case "output_text": return str(part.text, "content text");
24
+ case "input_image": return "[Codex image content omitted]";
25
+ case "input_audio": return "[Codex audio content omitted]";
26
+ case "encrypted_content": return "[Codex encrypted content unavailable]";
27
+ default: throw new Error(`Unsupported Codex content part: ${String(part.type)}`);
28
+ }
29
+ }).join("\n");
30
+ }
31
+ function output(value) { return typeof value === "string" ? value : textContent(value); }
32
+ function argumentsOf(raw) {
33
+ // Custom/invalid/non-object JSON cannot fit the shared object field. Keep the
34
+ // original wire string under an explicit raw label rather than lose it.
35
+ try {
36
+ const parsed = JSON.parse(raw);
37
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed))
38
+ return parsed;
39
+ }
40
+ catch { /* Native tool calls may persist unparseable model arguments. */ }
41
+ return { raw_arguments: raw };
42
+ }
43
+ function callKey(record, callId) { return `${record.owner}:${callId}`; }
44
+ function context(record, text) {
45
+ if (!record.windowId)
46
+ throw new Error(`Unavailable Codex history: native window identity missing at seq ${record.seq}; cannot assign a stable window address`);
47
+ return { seq: record.seq, windowId: record.windowId, role: "system", text, createdAt: record.timestamp };
48
+ }
49
+ function host(record, kind, payload) { return context(record, `Codex ${kind}\n${JSON.stringify(payload)}`); }
50
+ /** Presentation records contribute OUTCOME evidence, never duplicate raw tool dialogue. */
51
+ function fact(item) {
52
+ if (item.type === "CommandExecution") {
53
+ const status = str(item.status, "CommandExecution.status");
54
+ if (!["completed", "failed", "declined", "in_progress"].includes(status))
55
+ throw new Error(`Unsupported Codex command status: ${status}`);
56
+ return { error: status === "failed" || status === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0), text: optionalString(item.formatted_output, "formatted_output") };
57
+ }
58
+ if (item.type === "McpToolCall") {
59
+ const result = item.result == null ? undefined : obj(item.result, "MCP result");
60
+ if (result?.isError != null && typeof result.isError !== "boolean")
61
+ throw new Error("Invalid Codex MCP isError");
62
+ return { error: item.status === "failed" || item.error != null || result?.isError === true, ...(result === undefined ? {} : { text: JSON.stringify(result) }) };
63
+ }
64
+ if (item.type === "DynamicToolCall")
65
+ return { error: item.success === false || item.status === "failed" || item.error != null };
66
+ if (item.type === "FileChange" || item.type === "CollabAgentToolCall")
67
+ return { error: item.status === "failed" || item.status === "declined" || item.status === "interrupted" };
68
+ return {};
69
+ }
70
+ function toolDisplay(item) {
71
+ return ["CommandExecution", "McpToolCall", "DynamicToolCall", "CollabAgentToolCall", "FileChange", "ImageView", "Extension"].includes(String(item.type));
72
+ }
73
+ function response(record, facts) {
74
+ const p = record.payload, type = str(p.type, "response_item.type"), base = context(record, "");
75
+ if (type === "message") {
76
+ if (!["user", "assistant", "system", "developer"].includes(str(p.role, "message.role")))
77
+ throw new Error(`Unsupported Codex message role: ${String(p.role)}`);
78
+ return { ...base, role: record.metadata?.compaction_output === true ? "system" : p.role, text: textContent(p.content) };
79
+ }
80
+ if (type === "function_call" || type === "custom_tool_call" || type === "local_shell_call") {
81
+ const callId = optionalString(p.call_id, "call_id") ?? (type === "local_shell_call" ? optionalString(p.id, "local shell id") : undefined);
82
+ if (!callId)
83
+ throw new Error("Invalid Codex tool call: missing native call ID");
84
+ const name = type === "local_shell_call" ? "local_shell" : str(p.name, "tool name");
85
+ 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"));
86
+ return { ...base, role: "tool_call", toolName: p.namespace ? `${str(p.namespace, "namespace")}.${name}` : name, toolCallId: callKey(record, callId), arguments: args };
87
+ }
88
+ if (type === "function_call_output" || type === "custom_tool_call_output") {
89
+ const callId = optionalString(p.call_id, "output.call_id"), recorded = callId ? facts.get(callKey(record, callId)) : undefined;
90
+ 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 }) };
91
+ }
92
+ if (type === "agent_message")
93
+ return host(record, "agent_message", { author: p.author, recipient: p.recipient, text: textContent(p.content) });
94
+ if (OPAQUE_RESPONSES.has(type)) {
95
+ // Preserve recorded summaries and available metadata, not encrypted blobs or image bytes.
96
+ const { encrypted_content: _encrypted, result: _image, ...readable } = p;
97
+ return host(record, `${type} (opaque content omitted; not recovered plaintext)`, readable);
98
+ }
99
+ if (HOST_RESPONSES.has(type))
100
+ return host(record, type, p);
101
+ throw new Error(`Unsupported Codex response item: ${type}`);
102
+ }
103
+ /** One display record without a raw equivalent (e.g. user-shell command). */
104
+ function standaloneTool(record, item) {
105
+ const base = context(record, ""), recorded = fact(item);
106
+ if (item.type === "CommandExecution") {
107
+ array(item.command, "command").forEach((part) => str(part, "command argument"));
108
+ 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" };
109
+ }
110
+ const name = `${str(item.server, "MCP server")}/${str(item.tool, "MCP tool")}`;
111
+ 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" };
112
+ }
113
+ export async function readCodexHistory(source) {
114
+ const { state, records, highestSeq } = await readCodexTranscript(source);
115
+ const facts = new Map(), callsSeen = new Set(), responseIdsSeen = new Set();
116
+ const windows = new Map(), branchSeqs = new Set();
117
+ const addWindow = (nativeId, createdAt) => {
118
+ const windowId = `codex:${source.threadId}:${nativeId}`;
119
+ let window = windows.get(windowId);
120
+ if (!window) {
121
+ window = { windowId, createdAt, items: [] };
122
+ windows.set(windowId, window);
123
+ }
124
+ return window;
125
+ };
126
+ // Outcome inventory can enrich the raw result even when ItemCompleted follows it.
127
+ for (const record of records) {
128
+ const p = record.payload;
129
+ if (record.type === "event_msg" && p.type === "item_completed") {
130
+ if (p.thread_id !== record.owner)
131
+ throw new Error("Invalid Codex ItemCompleted thread identity");
132
+ const item = obj(p.item, "ItemCompleted.item");
133
+ if (toolDisplay(item))
134
+ facts.set(callKey(record, str(item.id, "TurnItem.id")), fact(item));
135
+ }
136
+ else if (record.type === "event_msg" && p.type === "patch_apply_end") {
137
+ if (typeof p.success !== "boolean")
138
+ throw new Error("Invalid Codex patch_apply_end.success");
139
+ facts.set(callKey(record, str(p.call_id, "patch call_id")), { error: !p.success });
140
+ }
141
+ else if (record.type === "event_msg" && p.type === "mcp_tool_call_end") {
142
+ const result = obj(p.result, "MCP Result envelope");
143
+ const ok = result.Ok == null ? undefined : obj(result.Ok, "MCP Result.Ok");
144
+ if (ok === undefined && typeof result.Err !== "string")
145
+ throw new Error("Invalid Codex MCP Result: expected Ok or Err");
146
+ facts.set(callKey(record, str(p.call_id, "MCP call_id")), { error: result.Err != null || ok?.isError === true, text: JSON.stringify(result) });
147
+ }
148
+ }
149
+ for (const record of records) {
150
+ branchSeqs.add(record.seq);
151
+ if (record.windowId)
152
+ addWindow(record.windowId, record.type === "session_meta" || record.type === "compacted" ? record.timestamp : undefined);
153
+ const p = record.payload;
154
+ let item;
155
+ switch (record.type) {
156
+ case "session_meta":
157
+ if (p.subagent_history_start_ordinal != null)
158
+ 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.`);
159
+ break;
160
+ case "response_item": {
161
+ item = response(record, facts);
162
+ if (p.id != null)
163
+ responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
164
+ if (item.role === "tool_call" && item.toolCallId) {
165
+ if (callsSeen.has(item.toolCallId))
166
+ throw new Error(`Unavailable Codex history: duplicate native call ID ${item.toolCallId}`);
167
+ callsSeen.add(item.toolCallId);
168
+ }
169
+ break;
170
+ }
171
+ case "compacted":
172
+ 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.`);
173
+ break;
174
+ case "event_msg": {
175
+ const type = str(p.type, "event_msg.type");
176
+ if (DISPLAY_COPIES.has(type))
177
+ break;
178
+ // A rollback changes the native selected window retrospectively. Until its
179
+ // turn semantics are decoded, don't return stale-but-plausible boot facts.
180
+ if (type === "thread_rolled_back")
181
+ throw new Error("Unavailable Codex history: thread_rolled_back selection is not supported");
182
+ if (type === "patch_apply_end" && callsSeen.has(callKey(record, str(p.call_id, "patch call_id"))))
183
+ break;
184
+ if (type === "mcp_tool_call_end") {
185
+ const call = callKey(record, str(p.call_id, "MCP call_id"));
186
+ if (!callsSeen.has(call))
187
+ item = host(record, "MCP completion without a recorded raw call", p);
188
+ break;
189
+ }
190
+ if (type === "item_completed") {
191
+ const display = obj(p.item, "ItemCompleted.item"), kind = str(display.type, "TurnItem.type");
192
+ if (ITEM_COPIES.has(kind))
193
+ break;
194
+ if (toolDisplay(display) && callsSeen.has(callKey(record, str(display.id, "TurnItem.id"))))
195
+ break;
196
+ if (kind === "CommandExecution" || kind === "McpToolCall") {
197
+ item = standaloneTool(record, display);
198
+ }
199
+ else if (kind === "FunctionCallOutput") {
200
+ // hook_runtime.rs record_pending_input persists raw output FIRST,
201
+ // then emits this presentation copy with the SAME response-item ID.
202
+ if (!responseIdsSeen.has(callKey(record, str(display.id, "FunctionCallOutput.id"))))
203
+ item = host(record, "FunctionCallOutput display without raw output", display);
204
+ }
205
+ else if (HOST_ITEMS.has(kind) || kind === "DynamicToolCall")
206
+ item = host(record, kind, display);
207
+ else
208
+ throw new Error(`Unsupported Codex TurnItem: ${kind}`);
209
+ }
210
+ else if (HOST_EVENTS.has(type)) {
211
+ // Lifecycle's repeated final answer isn't a second assistant message.
212
+ const { last_agent_message: _displayCopy, ...facts } = p;
213
+ item = host(record, type, facts);
214
+ }
215
+ else
216
+ throw new Error(`Unsupported Codex persisted event: ${type}`);
217
+ break;
218
+ }
219
+ case "turn_context":
220
+ case "token_usage_record":
221
+ case "security_risk_score":
222
+ case "inter_agent_communication_metadata": break;
223
+ case "world_state":
224
+ item = context(record, "Codex world_state snapshot/patch omitted from the text projection; not a newly spoken message.");
225
+ break;
226
+ case "inter_agent_communication":
227
+ 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 });
228
+ break;
229
+ case "retained_context":
230
+ case "realtime_item":
231
+ item = context(record, `Codex ${record.type} omitted from text projection; native structured/retained context is not newly spoken dialogue.`);
232
+ break;
233
+ }
234
+ if (item)
235
+ addWindow(record.windowId).items.push({ ...item, windowId: `codex:${source.threadId}:${record.windowId}` });
236
+ }
237
+ return { ...state, projection: projectHistory([...windows.values()], highestSeq, branchSeqs) };
238
+ }
@@ -0,0 +1,9 @@
1
+ /** additionalContextLimit:0 disables host spilling, so this local cap is the only truncation guard. */
2
+ export declare const MAX_BOOT_BYTES: number;
3
+ export declare function warningOutput(message: string): string;
4
+ export declare function contextOutput(event: "SessionStart" | "SubagentStart", text: string): string;
5
+ /** An oversized boot is refused rather than silently truncated or spilled by the host. */
6
+ export declare function bootWithinCap(boot: string): string | undefined;
7
+ export declare function readHookInput(stream: NodeJS.ReadableStream): Promise<string>;
8
+ /** One hook event in, one stdout body out; an unrecognized event is transparent. */
9
+ export declare function runHook(event: string | undefined, input: string, env?: NodeJS.ProcessEnv): Promise<string>;
@@ -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;