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
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
 
@@ -7,7 +7,7 @@ import { readClaudeHistory } from "./history.js";
7
7
  import { loadNotesSnapshot } from "../../../src/boot/snapshot.js";
8
8
  import { renderBootBlock } from "../../../src/boot/render.js";
9
9
  import { selectContinuation } from "../../../src/budget/text.js";
10
- import { CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
10
+ import { claudeHistoryGapNotice, claudeHistoryUnconfirmedSeq, CLAUDE_HISTORY_UNKNOWN_PREVIOUS, CLAUDE_HISTORY_UNKNOWN_WINDOW, CLAUDE_HISTORY_UNAVAILABLE_SENTENCE, CLAUDE_WARNING_PROMPT } from "./text.js";
11
11
  import { resolveClaudeLimits } from "./thresholds.js";
12
12
  import { projectKey, snapshotNotesIdentity } from "../../../src/notes/index.js";
13
13
  const MAX_REQUEST_BYTES = 512 * 1024;
@@ -27,15 +27,12 @@ function paramProblem(schema, params) {
27
27
  const field = first.instancePath.replace(/^\//, "").replaceAll("/", ".");
28
28
  return `${field ? `${field} ` : ""}${first.message}${extra}`;
29
29
  }
30
- /** Bind one shared operation to the identity Claude supplies. Validate untyped Claude parameters against the shared operation schema before execution. */
30
+ /** Bind shared execution/rendering to a host context; dispatch validates parameters before calling. */
31
31
  function boundOperation(operation) {
32
32
  return {
33
33
  description: operation.description,
34
34
  parameters: operation.parameters,
35
35
  async call(params, ...context) {
36
- // Refuse before the operation can act: a rejected shape never reaches a write.
37
- if (!Check(operation.parameters, params))
38
- throw new Error(`invalid ${operation.name} parameters: ${paramProblem(operation.parameters, params)}`);
39
36
  // The same business outcome and the same renderer as the Pi tool; only the envelope differs.
40
37
  const outcome = await operation.execute(params, ...context);
41
38
  return { text: operation.render(outcome), ok: outcome.ok };
@@ -85,17 +82,47 @@ export async function dispatch(request) {
85
82
  if (value.op === "tool") {
86
83
  if (typeof value.tool !== "string" || (!Object.hasOwn(OPERATIONS, value.tool) && !Object.hasOwn(HISTORY_OPERATIONS, value.tool)))
87
84
  throw new Error("unknown tool");
85
+ const operation = Object.hasOwn(OPERATIONS, value.tool) ? OPERATIONS[value.tool] : HISTORY_OPERATIONS[value.tool];
86
+ // Refuse before any operation can act: a rejected shape never reaches a write.
87
+ if (!Check(operation.parameters, value.params))
88
+ throw new Error(`invalid ${value.tool} parameters: ${paramProblem(operation.parameters, value.params)}`);
88
89
  const id = identity(value.identity);
89
90
  if (Object.hasOwn(HISTORY_OPERATIONS, value.tool)) {
91
+ const tool = value.tool;
90
92
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
91
- return HISTORY_OPERATIONS[value.tool].call(value.params, projection, id.sessionId);
93
+ const notice = claudeHistoryGapNotice(projection.missingAncestors);
94
+ const wrapText = (text) => notice + text;
95
+ let params = value.params;
96
+ if (projection.missingAncestors.length > 0) {
97
+ // An unknown segment is not evidence for the window before the current
98
+ // one. Resolve the exact ordinal, never array adjacency across a gap.
99
+ if (params.window_id === "@previous") {
100
+ const previous = projection.currentWindowOrdinal === undefined ? undefined : `claude:${id.sessionId}:${projection.currentWindowOrdinal - 1}`;
101
+ if (!projection.windows.some((window) => window.windowId === previous)) {
102
+ return { ok: false, text: wrapText(CLAUDE_HISTORY_UNKNOWN_PREVIOUS) };
103
+ }
104
+ params = { ...params, window_id: previous };
105
+ }
106
+ if (value.tool === "history_read") {
107
+ const { seq } = params;
108
+ if (seq <= projection.highestSeq && !projection.branchSeqs.has(seq)) {
109
+ return { ok: false, text: wrapText(claudeHistoryUnconfirmedSeq(seq)) };
110
+ }
111
+ }
112
+ }
113
+ const result = tool === "history_windows"
114
+ ? await HISTORY_OPERATIONS[tool].call(params, projection, id.sessionId, wrapText)
115
+ : await HISTORY_OPERATIONS[tool].call(params, projection, wrapText);
116
+ return { ...result, text: wrapText(result.text) };
92
117
  }
93
118
  return OPERATIONS[value.tool].call(value.params, id);
94
119
  }
95
120
  if (value.op === "history_state") {
96
121
  const id = identity(value.identity);
97
122
  const projection = await readClaudeHistory(historySource(value.history, id.sessionId));
98
- return { window: projection.windows.length - 1 };
123
+ if (projection.currentWindowOrdinal === undefined)
124
+ throw new Error(CLAUDE_HISTORY_UNKNOWN_WINDOW);
125
+ return { window: projection.currentWindowOrdinal };
99
126
  }
100
127
  if (value.op === "boot") {
101
128
  const id = identity(value.identity);
@@ -4,6 +4,11 @@ export type ClaudeHistorySource = {
4
4
  transcriptPath: string;
5
5
  headUuid?: string;
6
6
  };
7
+ /** Claude graph evidence stays in the adapter; shared queries only see addressed windows. */
8
+ export type ClaudeHistoryProjection = HistoryProjection & {
9
+ missingAncestors: string[];
10
+ currentWindowOrdinal: number | undefined;
11
+ };
7
12
  /** All addresses are allocated on the full first-occurrence log, before branch selection. */
8
- export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): HistoryProjection;
9
- export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<HistoryProjection>;
13
+ export declare function claudeHistoryFromJsonl(text: string, source: Omit<ClaudeHistorySource, "transcriptPath">): ClaudeHistoryProjection;
14
+ export declare function readClaudeHistory(source: ClaudeHistorySource): Promise<ClaudeHistoryProjection>;
@@ -132,8 +132,8 @@ export function claudeHistoryFromJsonl(text, source) {
132
132
  const nodes = new Map();
133
133
  let nextSeq = 1;
134
134
  for (const row of rowsOf(text)) {
135
- // Ignore non-message records, including future metadata. A skipped UUID that
136
- // the selected branch actually requires still fails ancestry resolution below.
135
+ // Ignore non-message records, including future metadata. If selected ancestry
136
+ // reaches a skipped UUID, it becomes a gap, never permission to expose its payload.
137
137
  if (!MESSAGE_TYPES.has(row.type))
138
138
  continue;
139
139
  const uuid = requiredString(row.uuid, "uuid");
@@ -160,32 +160,39 @@ export function claudeHistoryFromJsonl(text, source) {
160
160
  nextSeq += items.length;
161
161
  nodes.set(uuid, { first: version, latest: version, items });
162
162
  }
163
- function ordinalOf(version) {
164
- // Persisted history is not limited to the host's newest 4096 inference rows.
165
- // Resolve long parent chains iteratively, not with the JavaScript call stack.
163
+ const missingAncestors = new Set();
164
+ function positionOf(version) {
165
+ // Resolve long chains iteratively. A gap destroys ordinal evidence, not the
166
+ // confirmed suffix. Only a retained boot can re-anchor that suffix's ordinal.
166
167
  const chain = [], calculating = new Set();
167
168
  let cursor = version;
168
- while (cursor.ordinal === undefined) {
169
- // A notice can precede its parent on disk; use that parent's first eventual version.
169
+ let before = { ordinal: 0 };
170
+ while (cursor.position === undefined) {
171
+ // Forward references use the parent's first eventual version, not a rewrite.
170
172
  cursor.ancestor ??= cursor.ancestorUuid === undefined ? undefined : nodes.get(cursor.ancestorUuid)?.first;
171
173
  if (calculating.has(cursor))
172
174
  throw new Error("cyclic Claude transcript ancestry");
173
- if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined)
174
- throw new Error(`missing Claude transcript ancestor: ${cursor.ancestorUuid}`);
175
175
  calculating.add(cursor);
176
176
  chain.push(cursor);
177
+ if (cursor.ancestorUuid !== undefined && cursor.ancestor === undefined) {
178
+ missingAncestors.add(cursor.ancestorUuid);
179
+ before = { unknownAncestor: cursor.ancestorUuid };
180
+ break;
181
+ }
177
182
  if (cursor.ancestor === undefined)
178
183
  break;
179
184
  cursor = cursor.ancestor;
180
185
  }
181
- let before = cursor.ordinal ?? 0;
186
+ before = cursor.position ?? before;
182
187
  for (const current of chain.reverse()) {
183
188
  const retained = current.row.isCompactSummary === true || (current.ancestor !== undefined && boundary(current.ancestor.row));
184
189
  const marked = bootOrdinal(current.row, retained);
185
- current.ordinal = marked === undefined ? before + (boundary(current.row) ? 1 : 0) : Math.max(before, marked);
186
- before = current.ordinal;
190
+ current.position = marked !== undefined
191
+ ? { ordinal: "ordinal" in before ? Math.max(before.ordinal, marked) : marked }
192
+ : "ordinal" in before ? { ordinal: before.ordinal + (boundary(current.row) ? 1 : 0) } : before;
193
+ before = current.position;
187
194
  }
188
- return version.ordinal;
195
+ return version.position;
189
196
  }
190
197
  if (!source.headUuid)
191
198
  throw new Error("Claude history has no confirmed active head yet; wait for a main-session append after startup/resume");
@@ -210,8 +217,10 @@ export function claudeHistoryFromJsonl(text, source) {
210
217
  visiting.add(key);
211
218
  stack.push({ ...step, exit: true });
212
219
  const node = nodes.get(uuid);
213
- if (!node)
214
- throw new Error(`missing Claude transcript ancestor: ${uuid}`);
220
+ if (!node) {
221
+ missingAncestors.add(uuid);
222
+ continue;
223
+ }
215
224
  selected.add(uuid);
216
225
  const row = (historical ? node.first : node.latest).row;
217
226
  const ancestor = parent(row);
@@ -244,22 +253,44 @@ export function claudeHistoryFromJsonl(text, source) {
244
253
  }
245
254
  }
246
255
  }
247
- let maxOrdinal = ordinalOf(nodes.get(source.headUuid).latest);
248
- for (const uuid of selected)
249
- maxOrdinal = Math.max(maxOrdinal, ordinalOf(nodes.get(uuid).first));
250
- const windows = Array.from({ length: maxOrdinal + 1 }, (_, index) => ({ windowId: `claude:${source.sessionId}:${index}`, items: [] }));
256
+ const current = positionOf(nodes.get(source.headUuid).latest);
257
+ const windowId = (position) => `claude:${source.sessionId}:${"ordinal" in position ? position.ordinal : `unknown:${position.unknownAncestor}`}`;
258
+ const windowsById = new Map();
251
259
  const branchSeqs = new Set();
260
+ let maxOrdinal = "ordinal" in current ? current.ordinal : 0;
252
261
  for (const [uuid, node] of nodes) {
253
262
  if (!selected.has(uuid))
254
263
  continue;
255
- const window = windows[ordinalOf(node.first)];
264
+ const position = positionOf(node.first);
265
+ if ("ordinal" in position)
266
+ maxOrdinal = Math.max(maxOrdinal, position.ordinal);
267
+ const id = windowId(position);
268
+ let window = windowsById.get(id);
269
+ if (!window) {
270
+ window = { windowId: id, ...("ordinal" in position ? { ordinal: position.ordinal } : {}), items: [] };
271
+ windowsById.set(id, window);
272
+ }
256
273
  window.createdAt ??= node.items[0]?.createdAt;
257
274
  for (const item of node.items) {
258
275
  branchSeqs.add(item.seq);
259
- window.items.push({ ...item, windowId: window.windowId });
276
+ window.items.push({ ...item, windowId: id });
277
+ }
278
+ }
279
+ // Preserve complete-history empty windows (including copied boot ordinals).
280
+ // With gaps, report only evidenced windows, never invent the missing ordinals.
281
+ if (missingAncestors.size === 0) {
282
+ for (let ordinal = 0; ordinal <= maxOrdinal; ordinal++) {
283
+ const id = windowId({ ordinal });
284
+ if (!windowsById.has(id))
285
+ windowsById.set(id, { windowId: id, ordinal, items: [] });
260
286
  }
261
287
  }
262
- return projectHistory(windows, nextSeq - 1, branchSeqs);
288
+ // Forward references can put a newer numbered window on disk first. Unknown
289
+ // segments are a separate, unordered group, not an inferred place in that timeline.
290
+ const windows = [...windowsById.values()].sort((a, b) => a.ordinal === undefined
291
+ ? b.ordinal === undefined ? 0 : 1
292
+ : b.ordinal === undefined ? -1 : a.ordinal - b.ordinal);
293
+ return { ...projectHistory(windows, nextSeq - 1, branchSeqs), missingAncestors: [...missingAncestors], currentWindowOrdinal: "ordinal" in current ? current.ordinal : undefined };
263
294
  }
264
295
  export async function readClaudeHistory(source) {
265
296
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
@@ -2,3 +2,8 @@
2
2
  export declare const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
3
3
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
4
4
  export declare const CLAUDE_WARNING_PROMPT: string;
5
+ export declare const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
6
+ export declare const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = "Cannot resolve \"@previous\": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.";
7
+ export declare function claudeHistoryUnconfirmedSeq(seq: number): string;
8
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
9
+ export declare function claudeHistoryGapNotice(missing: readonly string[]): string;
@@ -3,3 +3,15 @@ import { warningNotice } from "../../../src/budget/text.js";
3
3
  export const CLAUDE_HISTORY_UNAVAILABLE_SENTENCE = "History isn't available in this Claude session: no main transcript_path was supplied. Keep essential state in notes; don't pretend those notes are the missing transcript.";
4
4
  /** The same notice as Pi; empty_brain's result explains Claude's deferred reset. */
5
5
  export const CLAUDE_WARNING_PROMPT = warningNotice();
6
+ export const CLAUDE_HISTORY_UNKNOWN_WINDOW = "Claude history cannot determine the current window ordinal across a missing ancestor; restore the ancestry or use a retained notesoup boot to re-anchor it.";
7
+ export const CLAUDE_HISTORY_UNKNOWN_PREVIOUS = 'Cannot resolve "@previous": the immediately preceding window is not confirmed across the ancestry gap. Use an explicit window id from history_windows.';
8
+ export function claudeHistoryUnconfirmedSeq(seq) {
9
+ return `Seq ${seq} is outside the confirmed selected history; it may be on another branch or beyond an unresolved ancestry gap.`;
10
+ }
11
+ /** Bounded host-only evidence, outside event documents/search offsets and shared schemas. */
12
+ export function claudeHistoryGapNotice(missing) {
13
+ if (missing.length === 0)
14
+ return "";
15
+ const evidence = missing.slice(0, 5).map((uuid) => JSON.stringify(uuid.length > 160 ? `${uuid.slice(0, 160)}…` : uuid)).join(", ");
16
+ return `Claude history is incomplete: missing ancestor UUID(s): ${evidence}${missing.length > 5 ? `; ${missing.length - 5} more` : ""}. Only confirmed selected ancestry is returned; disconnected prefixes and unrelated branches are excluded. Window IDs containing :unknown: have unconfirmed ordinal/ownership and may span native compactions; they are listed separately after numbered windows, not placed in a chronological order. A later retained boot can re-anchor window numbering, but cannot fill the history gap.\n\n`;
17
+ }
@@ -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>;