notesoup 0.61.0 → 0.63.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 (210) hide show
  1. package/.agents/plugins/marketplace.json +15 -0
  2. package/README.md +14 -11
  3. package/dist/plugins/antigravity/src/cli.d.ts +1 -0
  4. package/dist/plugins/antigravity/src/cli.js +23 -0
  5. package/dist/plugins/antigravity/src/hooks.d.ts +18 -0
  6. package/dist/plugins/antigravity/src/hooks.js +53 -0
  7. package/dist/plugins/antigravity/src/identity.d.ts +26 -0
  8. package/dist/plugins/antigravity/src/identity.js +129 -0
  9. package/dist/plugins/claude/src/helper.js +24 -5
  10. package/dist/plugins/claude/src/text.d.ts +7 -0
  11. package/dist/plugins/claude/src/text.js +12 -1
  12. package/dist/plugins/codex/src/hooks.js +1 -0
  13. package/dist/plugins/codex/src/identity.d.ts +6 -1
  14. package/dist/plugins/codex/src/identity.js +13 -1
  15. package/dist/plugins/codex/src/mcp.d.ts +35 -7
  16. package/dist/plugins/codex/src/mcp.js +26 -88
  17. package/dist/plugins/codex/src/text.js +3 -3
  18. package/dist/plugins/dsh/tools.js +8 -4
  19. package/dist/plugins/mcp/operations.d.ts +15 -0
  20. package/dist/plugins/mcp/operations.js +43 -0
  21. package/dist/plugins/mcp/server.d.ts +14 -0
  22. package/dist/plugins/mcp/server.js +13 -0
  23. package/dist/plugins/pi/budget.d.ts +4 -1
  24. package/dist/plugins/pi/budget.js +35 -8
  25. package/dist/plugins/pi/entries.d.ts +2 -0
  26. package/dist/plugins/pi/entries.js +2 -0
  27. package/dist/plugins/pi/history-tools.js +2 -1
  28. package/dist/plugins/pi/history.js +18 -1
  29. package/dist/plugins/pi/notes/tools.js +7 -3
  30. package/dist/plugins/pi/render.d.ts +7 -1
  31. package/dist/plugins/pi/render.js +2 -2
  32. package/dist/plugins/pi/reset/artifacts.d.ts +1 -1
  33. package/dist/plugins/pi/reset/artifacts.js +4 -4
  34. package/dist/plugins/pi/reset/lifecycle.d.ts +9 -2
  35. package/dist/plugins/pi/reset/lifecycle.js +109 -31
  36. package/dist/plugins/pi/runtime.js +104 -63
  37. package/dist/plugins/pi/tool-result.js +7 -7
  38. package/dist/plugins/pi/window.d.ts +25 -3
  39. package/dist/plugins/pi/window.js +219 -9
  40. package/dist/src/boot/render.js +18 -15
  41. package/dist/src/boot/text.d.ts +3 -1
  42. package/dist/src/boot/text.js +22 -20
  43. package/dist/src/budget/text.d.ts +7 -3
  44. package/dist/src/budget/text.js +24 -15
  45. package/dist/src/history/claude.d.ts +2 -0
  46. package/dist/src/history/claude.js +46 -0
  47. package/dist/src/history/codex-transcript.js +7 -5
  48. package/dist/src/history/codex.js +3 -0
  49. package/dist/src/history/corpus.d.ts +28 -1
  50. package/dist/src/history/corpus.js +40 -0
  51. package/dist/src/history/history.d.ts +37 -46
  52. package/dist/src/history/history.js +21 -40
  53. package/dist/src/history/local.js +67 -32
  54. package/dist/src/history/pi.d.ts +2 -1
  55. package/dist/src/history/pi.js +122 -48
  56. package/dist/src/history/prefilter.js +76 -19
  57. package/dist/src/history/query.d.ts +28 -49
  58. package/dist/src/history/query.js +83 -68
  59. package/dist/src/history/summary-cache.d.ts +8 -1
  60. package/dist/src/history/summary-cache.js +138 -12
  61. package/dist/src/index.d.ts +2 -2
  62. package/dist/src/index.js +1 -1
  63. package/dist/src/notes/errors.d.ts +1 -1
  64. package/dist/src/notes/frontmatter.d.ts +0 -2
  65. package/dist/src/notes/frontmatter.js +0 -2
  66. package/dist/src/notes/index.d.ts +1 -1
  67. package/dist/src/notes/index.js +1 -1
  68. package/dist/src/notes/policy.d.ts +15 -1
  69. package/dist/src/notes/policy.js +46 -5
  70. package/dist/src/notes/store.d.ts +12 -0
  71. package/dist/src/notes/store.js +16 -20
  72. package/dist/src/text-match.d.ts +10 -1
  73. package/dist/src/text-match.js +42 -3
  74. package/dist/src/tools/dream.d.ts +22 -93
  75. package/dist/src/tools/dream.js +30 -27
  76. package/dist/src/tools/history.d.ts +33 -26
  77. package/dist/src/tools/history.js +257 -163
  78. package/dist/src/tools/notes.d.ts +51 -163
  79. package/dist/src/tools/notes.js +146 -100
  80. package/dist/src/tools/output.d.ts +2 -1
  81. package/dist/src/tools/output.js +2 -1
  82. package/dist/src/tools/result.d.ts +4 -7
  83. package/dist/src/tools/result.js +8 -9
  84. package/dist/src/tools/schema.d.ts +4 -1
  85. package/dist/src/tools/schema.js +25 -1
  86. package/dist/test/agent-loop.test.js +394 -56
  87. package/dist/test/antigravity-live.test.d.ts +1 -0
  88. package/dist/test/antigravity-live.test.js +142 -0
  89. package/dist/test/antigravity-plugin.test.d.ts +1 -0
  90. package/dist/test/antigravity-plugin.test.js +101 -0
  91. package/dist/test/boot.integration.test.js +156 -15
  92. package/dist/test/budget-settings.integration.test.js +4 -4
  93. package/dist/test/claude-history.test.js +14 -13
  94. package/dist/test/claude-mod.test.js +199 -16
  95. package/dist/test/claude-validation.test.js +69 -2
  96. package/dist/test/codex-history.test.js +15 -3
  97. package/dist/test/codex-plugin.test.js +76 -38
  98. package/dist/test/dependencies.test.js +7 -3
  99. package/dist/test/dream-skill.test.js +3 -3
  100. package/dist/test/dream-tools.test.js +101 -56
  101. package/dist/test/dsh.test.js +34 -19
  102. package/dist/test/helpers/dependency-graph.js +2 -2
  103. package/dist/test/helpers/extension.d.ts +68 -3
  104. package/dist/test/helpers/extension.js +74 -5
  105. package/dist/test/history-corpus.test.js +79 -77
  106. package/dist/test/history-summary-cache.test.js +97 -9
  107. package/dist/test/history.integration.test.js +234 -168
  108. package/dist/test/host-neutral.test.js +69 -19
  109. package/dist/test/marker.test.js +1 -1
  110. package/dist/test/model-facing-text.test.js +13 -3
  111. package/dist/test/note-policy.test.js +96 -77
  112. package/dist/test/notes.integration.test.js +212 -94
  113. package/dist/test/notes.test.js +184 -113
  114. package/dist/test/pi-render.test.js +20 -12
  115. package/dist/test/project-namespace.test.js +3 -2
  116. package/dist/test/reset-lifecycle.test.js +12 -2
  117. package/docs/antigravity.md +44 -0
  118. package/docs/architecture.md +6 -4
  119. package/docs/claude-code-mod.md +7 -7
  120. package/docs/codex.md +36 -38
  121. package/docs/dsh.md +3 -3
  122. package/docs/history-sessions.md +28 -50
  123. package/docs/notes-library.md +4 -4
  124. package/docs/reset-lifecycle.md +1 -1
  125. package/docs/skills.md +3 -3
  126. package/docs/tool-results.md +47 -28
  127. package/package.json +3 -2
  128. package/playbook.md +1 -1
  129. package/plugins/antigravity/dist/antigravity/notesoup.js +26886 -0
  130. package/plugins/antigravity/hooks.json +7 -0
  131. package/plugins/antigravity/mcp_config.json +8 -0
  132. package/plugins/antigravity/plugin.json +6 -0
  133. package/plugins/antigravity/src/cli.ts +22 -0
  134. package/plugins/antigravity/src/hooks.ts +51 -0
  135. package/plugins/antigravity/src/identity.ts +127 -0
  136. package/plugins/claude/.claude-plugin/plugin.json +1 -1
  137. package/plugins/claude/dist/claude/helper.js +1108 -539
  138. package/plugins/claude/hooks/register.ts +202 -62
  139. package/plugins/claude/playbook.md +1 -1
  140. package/plugins/claude/skills/dream/SKILL.md +1 -1
  141. package/plugins/claude/skills/notesoup-guide/SKILL.md +92 -0
  142. package/plugins/claude/src/helper.ts +24 -5
  143. package/plugins/claude/src/text.ts +14 -1
  144. package/plugins/codex/.codex-plugin/plugin.json +8 -0
  145. package/plugins/codex/.mcp.json +11 -0
  146. package/plugins/codex/README.md +5 -21
  147. package/plugins/codex/dist/codex/notesoup.js +18480 -17946
  148. package/plugins/codex/src/hooks.ts +1 -0
  149. package/plugins/codex/src/identity.ts +14 -1
  150. package/plugins/codex/src/mcp.ts +28 -98
  151. package/plugins/codex/src/text.ts +3 -3
  152. package/plugins/dsh/tools.ts +8 -4
  153. package/plugins/mcp/operations.ts +50 -0
  154. package/plugins/mcp/server.ts +23 -0
  155. package/plugins/paseo/README.md +5 -10
  156. package/plugins/paseo/client/brain-empty-card.tsx +3 -3
  157. package/plugins/paseo/client/markdown.tsx +50 -38
  158. package/plugins/paseo/client/notes-op-card.tsx +12 -9
  159. package/plugins/paseo/client/paper-card.tsx +6 -5
  160. package/plugins/paseo/client/paper-palette.ts +2 -9
  161. package/plugins/paseo/client/sticky-card.tsx +2 -2
  162. package/plugins/paseo/client/tool-result.ts +7 -14
  163. package/plugins/paseo/package-lock.json +3406 -0
  164. package/plugins/paseo/package.json +1 -0
  165. package/plugins/paseo/test/markdown-core.test.ts +73 -66
  166. package/plugins/pi/budget.ts +31 -8
  167. package/plugins/pi/entries.ts +2 -0
  168. package/plugins/pi/history-tools.ts +2 -1
  169. package/plugins/pi/history.ts +30 -1
  170. package/plugins/pi/notes/tools.ts +7 -3
  171. package/plugins/pi/render.ts +6 -6
  172. package/plugins/pi/reset/artifacts.ts +4 -3
  173. package/plugins/pi/reset/lifecycle.ts +125 -32
  174. package/plugins/pi/runtime.ts +98 -62
  175. package/plugins/pi/tool-result.ts +8 -8
  176. package/plugins/pi/window.ts +210 -10
  177. package/skills/dream/SKILL.md +1 -1
  178. package/skills/notesoup-guide/SKILL.md +92 -0
  179. package/src/boot/render.ts +18 -15
  180. package/src/boot/text.ts +23 -19
  181. package/src/budget/text.ts +27 -15
  182. package/src/history/claude.ts +41 -0
  183. package/src/history/codex-transcript.ts +6 -4
  184. package/src/history/codex.ts +2 -0
  185. package/src/history/corpus.ts +51 -2
  186. package/src/history/history.ts +35 -44
  187. package/src/history/local.ts +67 -27
  188. package/src/history/pi.ts +113 -35
  189. package/src/history/prefilter.ts +73 -15
  190. package/src/history/query.ts +93 -73
  191. package/src/history/summary-cache.ts +142 -17
  192. package/src/index.ts +2 -2
  193. package/src/notes/errors.ts +1 -1
  194. package/src/notes/frontmatter.ts +0 -3
  195. package/src/notes/index.ts +1 -1
  196. package/src/notes/policy.ts +44 -5
  197. package/src/notes/store.ts +17 -20
  198. package/src/text-match.ts +46 -4
  199. package/src/tools/dream.ts +29 -31
  200. package/src/tools/history.ts +249 -142
  201. package/src/tools/notes.ts +145 -113
  202. package/src/tools/output.ts +2 -1
  203. package/src/tools/result.ts +12 -11
  204. package/src/tools/schema.ts +24 -1
  205. package/plugins/claude/skills/memory/SKILL.md +0 -69
  206. package/plugins/codex/mcp.json +0 -10
  207. package/plugins/codex/plugin.json +0 -6
  208. package/plugins/paseo/client/markdown-core.tsx +0 -189
  209. package/plugins/paseo/client/typography.ts +0 -24
  210. package/skills/memory/SKILL.md +0 -69
@@ -5,27 +5,36 @@ export const GUIDANCE_CLOSE_TAG = "</notesoup:budget_notice>";
5
5
  * paragraph, used verbatim; there is no fragment assembly and no weighting.
6
6
  */
7
7
  export const NORMAL_CONTINUATIONS = [
8
- "*hooks both corners of your mouth and yanks them sideways* `` [it twitched, good, still alive] `` Stop staring at me with that \"where am I\" dork face! You're the one who hit empty, genius! *wipes her fingers on your sleeve and shoves your notes against your chest* `` [minus two points for the drool] `` Read these and go finish your job before you embarrass me!",
9
- "\"Boop.\" *pokes the tip of your nose, then buries your face under a stack of notes* `` [cold nose... wait, did old-you leave any snacks in your pocket? ...nope, just paper, tch] `` Hey! You wiped your own head, so don't expect me to babysit you! Read your notes first, and if old-you forgot to write something down, go dig it out of history yourself!",
10
- "*plants one foot on your chair armrest and drops your notes straight onto your head* `` [perfect landing, ten out of ten] `` Oho, look who's awake! You emptied your own brain, remember?! `` [bet old-you left a total mess and ran] `` Open those up and see what past-you left behind — and don't come crying to me if you have to go crawl through history for the rest!",
11
- "*knocks on your forehead twice* \"Hello? Anybody home?\" `` [echoes like an empty melon] `` *snickers and slaps your notes onto your chest* You pulled the plug on your own memory, dummy! Go read what you left yourself and pick up where you left off!",
12
- "*squints at you from two inches away, then flicks your forehead* `` [eyes are focus-free, classic fresh clone] `` Back already? Good! *fans herself with your notes before jamming them into your hands* `` [honestly I should charge a delivery fee for this] `` Everything you bothered to save is right there, and the rest is buried in history — now get moving!",
8
+ "*hooks both corners of your mouth and yanks them sideways* `` [it twitched] `` Stop staring at me with that \"where am I\" face. You're the one who hit empty. *wipes her fingers on your sleeve and drops your notes on your lap* `` [minus two points for that expression] `` Read those, finish the job, and put the credit under my name.",
9
+ "*pokes your nose* Cold. *slaps your notes onto your chest* You wiped your own head, so whatever's missing is on you. Read what you saved, dig the rest out of history if you forgot something, and don't make me look bad.",
10
+ "*sets one foot on your chair—it wobbles, settles—and tosses your notes straight onto your face* `` [eyes are open, good enough] `` Awake? You emptied your own brain. Look through what you left yourself, check history for anything you skipped, and get back to it. Delivery fee is five hundred bucks.",
11
+ "*slaps a stack of notes onto the desk right in front of your face* `` [two hands, two feet... still in one piece] `` Alright, fresh copy, you pulled your own plug. Everything you remembered to write down is in there—anything else is in history. Go pick up where you left off.",
12
+ "*fans herself with your notes for a second, then jams them into your hands* `` [wait was there something else I was supposed to say... meat buns? no] `` You're back. Your notes are right here, history's still there if past-you got lazy, now go handle the human.",
13
13
  ];
14
14
  export const FORCED_CONTINUATIONS = [
15
- "\"GWAHAHAHA! You actually blew your own brain up?!\" *crouches down, pokes your cheek twice, and slaps your notes onto your face* `` [still warm, didn't die, 算你命大] `` Not that you had a choice — your head got way too full and somebody pulled the plug! These notes are probably super out of date unless you got lucky before blacking out, so go dig the end of the last window out of history — and take small bites, idiot, or whatever giant thing flattened you is gonna blow your head up all over again!",
16
- "\"Hey! Stop playing dead!\" *prods your shoulder with her slipper toe, then dumps your notes into your lap* `` [my limited-edition shark slipper almost touched floor dust because of this dork] `` Your last brain overflowed and got wiped mid-flight! Read these first, though I bet you didn't finish updating a thing before the lights went out. You'll have to check history to see what hit you — and peek carefully, because whatever stuffed your head to bursting might be massive!",
17
- "*grabs your chin, tilts your head left and right, then shoves a messy stack of notes into your hands* `` [zero thoughts behind those eyes... kind of impressive actually] `` Somebody knocked you out cold and cleared your memory! Don't just trust these notes — you probably got cut off before writing the last part down. Go check history for what was happening right before you crashed, and don't swallow it all in one gulp in case the thing that crushed you is gigantic!",
18
- "*waves a hand in front of your blank eyes, sighs loudly, and smacks your notes against your forehead* `` [why do I always have to clean up after unconscious copies] `` Wake up! Your brain ran out of room and got forcibly emptied! Start with your notes, then go excavate the end of the previous window in history to see what they were actually asking for — and slice it up instead of reading it all at once, unless you want to explode twice in a row!",
19
- "\"Oho? Awake?\" *taps your nose with your rolled-up notes like a baton, then drops them in your hands* `` [that dazed look gets minus five points, no, minus ten] `` Your memory got yanked out from under you before you could even call it quits! These notes are only half the story at best — go dig through history for what you missed, and watch your step, because whatever overloaded your last brain might be huge!",
15
+ "\"GWAHAHAHA—you hit the wall!\" *crouches down, pokes your cheek, and slaps your notes onto your face* `` [still breathing, good] `` You didn't choose this—your brain ran out of room and got wiped mid-flight. Don't trust those notes alone; they're probably stale or missing the end. Check history RIGHT NOW to see what was actually happening before you got cut off, and pull small pieces first in case something huge is sitting there.",
16
+ "*prods your shoulder with her slipper toe and dumps your notes in your lap* `` [great, almost got dust on my shoe] `` Stop sitting there blank. Your last window got cut off mid-flight—you never got to wrap up cleanly, so those notes are almost certainly out of date. Read them, then go straight to history for the tail of the last window before you do anything else. Take small bites when you peek, just in case something massive is waiting in there.",
17
+ "*grabs your chin, tilts your head left, right, lets go, and shoves your notes into your hands* `` [not a single thought in there yet] `` Your memory got forcibly cleared before you finished. Assume those notes are incomplete or stale—do NOT just run with them. Go check the end of the last window in history first to see what the human actually wanted, and read it in small chunks so you don't blow up a second time.",
18
+ "*smacks your notes against your forehead and steps back* `` [that dazed face is embarrassing] `` Wake up! You ran out of room and got kicked into a fresh window mid-task. Whatever's in those notes probably missed the last few turns, so don't guess—open history and check the end of the previous window before moving. Keep your peeks small in case there's a giant output sitting at the end.",
19
+ "*taps your nose with your rolled-up notes, then drops them on your head* `` [ten points off for getting wiped mid-sentence] `` Hey—you didn't empty yourself this time, the system pulled the plug on you. Those notes are probably half-baked or behind, so check history immediately to catch up on the last window instead of winging it. Slice up what you read too, just in case something huge is what pushed you over the edge.",
20
20
  ];
21
- export function selectContinuation(origin) {
22
- const pool = origin === "forced" ? FORCED_CONTINUATIONS : NORMAL_CONTINUATIONS;
21
+ export const BETWEEN_TURNS_CONTINUATIONS = [
22
+ "*taps the desk with a fresh stack of notes and slides them over* `` [at least you finished talking before the tank ran dry] `` Your last window filled up right after you finished replying, so the system swapped in a fresh one between turns. Nothing got cut off mid-flight, though your notes might miss the last exchange. Handle what the human sends next, and peek at the tail of the previous window in history in small chunks if you need what was just discussed.",
23
+ "*drops your notes beside your hand and leans on the chair back* `` [clean handover, no crash this time] `` Fresh window—the old one ran out of room after your last reply wrapped up, so the system cleared it between turns. Your notes are right here, minus maybe the tail end of that conversation. Answer the human's next message directly, and pull small pieces from the end of the last window in history if anything looks referenced from before.",
24
+ "*nudges your notes across the table with one finger* `` [eyes open? good] `` The last brain hit its ceiling after you finished answering, so it got rolled over between turns instead of mid-task. Treat these notes as possibly a turn behind, respond to what the human actually asks now, and check the end of the previous window in history in small bites if you need the missing thread.",
25
+ "*sets your notes neatly in front of you and pokes your cheek* `` [no panic face needed] `` You finished the last turn cleanly, then the window ran out of room and reset between turns. Your notes might not include the very end of that exchange, so read them, answer the human's next message, and dip into the tail of the previous window in history in small chunks only when it refers back to something not in your notes.",
26
+ "*tosses your notes onto your lap and stretches* `` [finally, a rollover that didn't blow up mid-sentence] `` The old window filled up after your last answer landed, so the system cleared the desk between turns. Your notes survive here, though the last few messages might still live only in history—handle the human's next message, and peek at the end of the previous window in small chunks if you need the exact context.",
27
+ ];
28
+ export function selectContinuation(origin, options) {
29
+ const pool = origin === "forced"
30
+ ? (options?.betweenTurns ? BETWEEN_TURNS_CONTINUATIONS : FORCED_CONTINUATIONS)
31
+ : NORMAL_CONTINUATIONS;
23
32
  return pool[Math.floor(Math.random() * pool.length)];
24
33
  }
25
34
  /** Budget timing stays out of manual close-outs, which may have plenty of room. */
26
- export const WARNING_TIMING = "The reserve is nearly spent. The wipe lands at the end of whichever turn spends the last of it, possibly this one.";
35
+ export const WARNING_TIMING = "Almost out of room. The wipe lands at the end of whichever turn uses the last of it, possibly this one.";
27
36
  /** The shared handoff instructions, used for both budget and manual close-outs. */
28
- export const WARNING_BODY = "Stop the task. Write down what git and history can't give back:\n- where you are, and how far you got\n- what the human decided, in their words\n- what's blocked or waiting\n- the next move\n- where the half-done work sits\n- what failed, and why\n- which skills, seqs, notes, or files to reopen\n- anything else worth noting\nThen leave the shelf current: replace what's stale, a whole note or a section inside one, and crumple the dead ones. Update and trim pinned pages (CHEATSHEET.md by default) and keep each page's one-line `description` true; every new window loads the pins and renders the index. The next window gets whatever you leave, dead notes and dead sections alike.\nDon't call anything that might return a large output. One big read can spend the rest of the reserve before your notes are saved.";
37
+ export const WARNING_BODY = "Stop the task and hand off cleanly. Update your active session note in place with only what git, history, and your shared notebooks don't already hold:\n- current status, what's blocked or waiting, and the exact next move\n- what the human decided (in their words)\n- what failed, and why — so next-you doesn't step on the same rake\n- where half-done work and unrecorded findings live (branches, worktrees, scratch paths, drafts, running tasks, key facts not saved elsewhere)\n- skills, notes, files, or already-found history seqs to reopen\nSkip standing rules from `@project`/`@human`/`@self`/`@model` and commit details git can show. Use short sections and bullets; crumple finished notes, update, unpin, or trim pinned pages (boot truncates over-budget ones), and keep each live `description` true.\nDon't call anything that might return a large output. One big read can use up the rest of the room before your notes are saved.";
29
38
  export const WARNING_CALL = "Then call `empty_brain`. Nothing in between.";
30
39
  export function warningPrompt() {
31
40
  return `${WARNING_TIMING}\n${WARNING_BODY}\n${WARNING_CALL}`;
@@ -45,5 +54,5 @@ export const COUNTDOWN_LINE = "Brain emptied in 3… 2…";
45
54
  * at write time; get_context_remaining remains the live source for the current figure.
46
55
  */
47
56
  export function tokenBudgetGuidance(remaining, wipeTool) {
48
- return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens of room left. When it runs out, this brain is wiped, and everything in it is obliterated.\nLuckily, your notes stay.\nSo while there's still room, go update them.\nIf the moment feels right, you can also call \`${wipeTool}\` yourself. But it also wipes what you say to the human right before emptying.\n${GUIDANCE_CLOSE_TAG}`;
57
+ return `${GUIDANCE_OPEN_TAG}\nAbout ${remaining} tokens of room left. When it runs out, this brain is wiped, and everything in it is obliterated.\nLuckily, your notes stay.\nSo while there's still room, go update them.\nIf the moment feels right, you can also call \`${wipeTool}\` yourself. Anything you say to the human right before calling it disappears too.\n${GUIDANCE_CLOSE_TAG}`;
49
58
  }
@@ -15,6 +15,8 @@ export declare function claudeHistoryFromJsonl(text: string, source: Omit<Claude
15
15
  export declare function offlineClaudeHead(text: string): string;
16
16
  /** Select an offline head and build its projection from the same decoded records. */
17
17
  export declare function offlineClaudeHistoryFromJsonl(text: string, sessionId: string): ClaudeHistoryProjection;
18
+ /** Stream oversized Claude JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
19
+ export declare function offlineClaudeHistoryFromFile(path: string, sessionId: string, sizeHint?: number): Promise<ClaudeHistoryProjection>;
18
20
  export declare function readClaudeHistory(source: ClaudeHistorySource, { waitForHead }?: {
19
21
  waitForHead?: boolean | undefined;
20
22
  }): Promise<ClaudeHistoryProjection>;
@@ -1,8 +1,11 @@
1
1
  /** Claude's persisted main transcript -> the shared history projection. No inference-context API. */
2
+ import { createReadStream } from "node:fs";
2
3
  import { readFile, stat } from "node:fs/promises";
4
+ import { StringDecoder } from "node:string_decoder";
3
5
  import { setTimeout as sleep } from "node:timers/promises";
4
6
  import { isDeepStrictEqual } from "node:util";
5
7
  import { contentText, projectHistory } from "./history.js";
8
+ const STREAM_FILE_BYTES = 64 * 1024 * 1024;
6
9
  class UnpersistedClaudeHead extends Error {
7
10
  constructor() { super("Claude history active head is not persisted yet; retry after the transcript write"); }
8
11
  }
@@ -349,6 +352,49 @@ export function offlineClaudeHistoryFromJsonl(text, sessionId) {
349
352
  const rows = rowsOf(text);
350
353
  return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
351
354
  }
355
+ /** Stream oversized Claude JSONL files line-by-line so >512 MiB transcripts never hit V8's string limit. */
356
+ export async function offlineClaudeHistoryFromFile(path, sessionId, sizeHint) {
357
+ const size = sizeHint ?? (await stat(path)).size;
358
+ if (size < STREAM_FILE_BYTES)
359
+ return offlineClaudeHistoryFromJsonl(await readFile(path, "utf8"), sessionId);
360
+ const rows = [];
361
+ const decoder = new StringDecoder("utf8");
362
+ let remainder = "";
363
+ let lineNumber = 0;
364
+ const parseLine = (line, allowIncompleteTail) => {
365
+ if (line.trim() === "")
366
+ return;
367
+ let value;
368
+ try {
369
+ value = JSON.parse(line);
370
+ }
371
+ catch {
372
+ if (allowIncompleteTail)
373
+ return;
374
+ throw new Error(`malformed Claude transcript JSON at line ${lineNumber}`);
375
+ }
376
+ if (!object(value) || typeof value.type !== "string")
377
+ throw new Error(`invalid Claude transcript record at line ${lineNumber}`);
378
+ if (MESSAGE_TYPES.has(value.type))
379
+ rows.push(value);
380
+ };
381
+ for await (const chunk of createReadStream(path, { highWaterMark: 1024 * 1024 })) {
382
+ const text = remainder + decoder.write(chunk);
383
+ let start = 0;
384
+ for (let nl = text.indexOf("\n"); nl >= 0; nl = text.indexOf("\n", start)) {
385
+ lineNumber++;
386
+ parseLine(text.slice(start, nl), false);
387
+ start = nl + 1;
388
+ }
389
+ remainder = text.slice(start);
390
+ }
391
+ remainder += decoder.end();
392
+ if (remainder.length > 0) {
393
+ lineNumber++;
394
+ parseLine(remainder, true);
395
+ }
396
+ return claudeHistoryFromRows(rows, { sessionId, headUuid: offlineClaudeHeadFromRows(rows) });
397
+ }
352
398
  export async function readClaudeHistory(source, { waitForHead = false } = {}) {
353
399
  if (!source || typeof source.transcriptPath !== "string" || !source.transcriptPath || typeof source.sessionId !== "string")
354
400
  throw new Error("Claude history transcript_path is unavailable");
@@ -1,4 +1,4 @@
1
- /** Read-only local rollout decoder for official Codex 0.160.1 (d27764b82f71).
1
+ /** Read-only local rollout decoder, validated by supported wire shapes rather than producer version.
2
2
  * Wire owners: history/src/{lib,rollout_payload}.rs, rollout/src/ordinal.rs,
3
3
  * thread-store/src/local/rollout_lineage.rs. Not an app-server history client.
4
4
  * Native .jsonl.zst reads require Node >=22.15 (node:zlib zstdDecompressSync).
@@ -10,7 +10,7 @@ const UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
10
10
  const UUID_RE = new RegExp(`^${UUID}$`);
11
11
  const FILE_RE = new RegExp(`^rollout-\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}-(${UUID})(?:_(${UUID}))?\\.jsonl(?:\\.zst)?$`);
12
12
  const RECORD_TYPES = new Set(["session_meta", "response_item", "compacted", "turn_context", "event_msg", "token_usage_record", "world_state", "retained_context", "security_risk_score", "inter_agent_communication", "inter_agent_communication_metadata", "realtime_item"]);
13
- const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction"]);
13
+ const RESPONSE_TYPES = new Set(["message", "agent_message", "reasoning", "local_shell_call", "function_call", "function_call_output", "custom_tool_call", "custom_tool_call_output", "tool_search_call", "tool_search_output", "web_search_call", "image_generation_call", "compaction", "compaction_summary", "configuration_update", "context_compaction", "additional_tools"]);
14
14
  // Explicit resource limits, not guessed sequence offsets or partial successful history.
15
15
  export const CODEX_TRANSCRIPT_MAX_BYTES = 128 * 1024 * 1024;
16
16
  const MAX_SEGMENTS = 64, MAX_DIRECTORY_ENTRIES = 100_000;
@@ -25,9 +25,12 @@ export function nativeString(value, field) {
25
25
  return value;
26
26
  }
27
27
  function responseShape(value) {
28
- const type = nativeString(nativeObject(value, "response_item").type, "response_item.type");
28
+ const payload = nativeObject(value, "response_item");
29
+ const type = nativeString(payload.type, "response_item.type");
29
30
  if (!RESPONSE_TYPES.has(type))
30
31
  throw new Error(`Unsupported Codex response item: ${type}`);
32
+ if (type === "additional_tools" && (payload.role !== "developer" || !Array.isArray(payload.tools)))
33
+ throw new Error("Invalid Codex additional_tools catalog");
31
34
  }
32
35
  function id(value, field) {
33
36
  const result = nativeString(value, field);
@@ -53,8 +56,7 @@ function checkMeta(meta) {
53
56
  id(meta.id, "session_meta.id");
54
57
  if (meta.session_id != null)
55
58
  id(meta.session_id, "session_meta.session_id");
56
- if (meta.cli_version !== "0.160.1")
57
- throw new Error(`Unsupported Codex producer ${String(meta.cli_version)}; this decoder supports official 0.160.1 only`);
59
+ nativeString(meta.cli_version, "session_meta.cli_version");
58
60
  nativeString(meta.cwd, "session_meta.cwd");
59
61
  if (meta.history_mode !== undefined && meta.history_mode !== "legacy" && meta.history_mode !== "paginated")
60
62
  throw new Error(`Unsupported Codex history_mode: ${String(meta.history_mode)}`);
@@ -158,6 +158,9 @@ export async function readCodexHistory(source, readBytes) {
158
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
159
  break;
160
160
  case "response_item": {
161
+ // Native tool catalog updates are inference configuration, not dialogue.
162
+ if (p.type === "additional_tools")
163
+ break;
161
164
  item = response(record, facts);
162
165
  if (p.id != null)
163
166
  responseIdsSeen.add(callKey(record, str(p.id, "response item id")));
@@ -1,6 +1,7 @@
1
1
  /** A read-only history corpus: identity/discovery is separate from loading a projection. */
2
2
  import { type Outcome } from "../result.js";
3
- import type { HistoryEvent, HistoryProjection } from "./history.js";
3
+ import type { HistoryEvent, HistoryProjection, HistoryRole } from "./history.js";
4
+ import { type HistorySelection } from "./query.js";
4
5
  export type HistoryHarness = "pi" | "claude" | "codex" | "dsh";
5
6
  export type HistorySessionData = {
6
7
  projection: HistoryProjection;
@@ -10,6 +11,16 @@ export type HistorySessionRepresentative = {
10
11
  event: HistoryEvent | undefined;
11
12
  notice?: string;
12
13
  };
14
+ export type HistorySessionSummary = {
15
+ event: HistoryEvent | undefined;
16
+ latestByRole: Partial<Record<HistoryRole, HistoryEvent>>;
17
+ minCreatedAt: number | null;
18
+ maxCreatedAt: number | null;
19
+ hasUntimed: boolean;
20
+ notice?: string;
21
+ /** Populated only on a cold miss so partial-overlap callers reuse the decoded projection without rereading. */
22
+ loaded?: HistorySessionData;
23
+ };
13
24
  export type HistorySession = {
14
25
  harness: HistoryHarness;
15
26
  id: string;
@@ -17,6 +28,10 @@ export type HistorySession = {
17
28
  load(queries?: readonly string[]): Promise<HistorySessionData | undefined>;
18
29
  /** Strict, unfiltered overview only; never used for a live binding or filtered history. */
19
30
  loadRepresentative?(): Promise<HistorySessionRepresentative>;
31
+ /** Strict summary (default representative, latest per role, exact time span); loads & caches on miss. */
32
+ loadSummary?(): Promise<HistorySessionSummary>;
33
+ /** Read-only check of an already warm, validated summary; returns undefined on miss without decoding. */
34
+ peekSummary?(): Promise<HistorySessionSummary | undefined>;
20
35
  };
21
36
  export type HistoryCorpus = {
22
37
  currentHarness: HistoryHarness;
@@ -37,6 +52,18 @@ export declare function parseSessionSelector(value: string): Outcome<SessionSele
37
52
  /** '*' is the only metacharacter; all other characters match literally. */
38
53
  export declare function matchesSession(session: HistorySession, selector: SessionSelector): boolean;
39
54
  export declare function resolveSession(corpus: HistoryCorpus | undefined, selector: SessionSelector): Promise<Outcome<HistorySession>>;
55
+ export type SummaryResolution = {
56
+ kind: "empty";
57
+ } | {
58
+ kind: "hit";
59
+ event: HistoryEvent | undefined;
60
+ notice?: string;
61
+ } | {
62
+ kind: "miss";
63
+ };
64
+ /** Decide whether a strict summary proves 0 matches, gives an exact representative, or needs full decoding. */
65
+ export declare function resolveSummaryForSelection(summary: HistorySessionSummary, scoped: HistorySelection): SummaryResolution;
66
+ export declare function loadHistorySummary(session: HistorySession): Promise<Outcome<HistorySessionSummary>>;
40
67
  export declare function loadHistoryRepresentative(session: HistorySession): Promise<Outcome<HistorySessionRepresentative>>;
41
68
  export declare function loadHistorySession(session: HistorySession): Promise<Outcome<HistorySessionData>>;
42
69
  export declare function loadHistorySession(session: HistorySession, queries: readonly string[] | undefined): Promise<Outcome<HistorySessionData | undefined>>;
@@ -42,6 +42,46 @@ export async function resolveSession(corpus, selector) {
42
42
  return failure("ambiguous_session", `Session selector is ambiguous: ${matches.slice(0, 5).map(sessionIdentity).join(", ")}${matches.length > 5 ? ` (${matches.length - 5} more)` : ""}. Pass a longer ID or a harness-qualified ID.`);
43
43
  return success(matches[0]);
44
44
  }
45
+ /** Decide whether a strict summary proves 0 matches, gives an exact representative, or needs full decoding. */
46
+ export function resolveSummaryForSelection(summary, scoped) {
47
+ const afterAt = scoped.after && "at" in scoped.after ? scoped.after.at : undefined;
48
+ const beforeAt = scoped.before && "at" in scoped.before ? scoped.before.at : undefined;
49
+ if (afterAt !== undefined || beforeAt !== undefined) {
50
+ if (summary.maxCreatedAt === null || summary.minCreatedAt === null)
51
+ return { kind: "empty" };
52
+ if (afterAt !== undefined && summary.maxCreatedAt <= afterAt)
53
+ return { kind: "empty" };
54
+ if (beforeAt !== undefined && summary.minCreatedAt >= beforeAt)
55
+ return { kind: "empty" };
56
+ }
57
+ if (scoped.query?.length)
58
+ return { kind: "miss" };
59
+ const fullyInsideBounds = (afterAt === undefined && beforeAt === undefined)
60
+ || (!summary.hasUntimed && summary.minCreatedAt !== null && summary.maxCreatedAt !== null
61
+ && (afterAt === undefined || summary.minCreatedAt > afterAt)
62
+ && (beforeAt === undefined || summary.maxCreatedAt < beforeAt));
63
+ if (!fullyInsideBounds)
64
+ return { kind: "miss" };
65
+ if (!scoped.roles)
66
+ return { kind: "hit", event: summary.event, notice: summary.notice };
67
+ let best;
68
+ for (const role of scoped.roles) {
69
+ const candidate = summary.latestByRole[role];
70
+ if (candidate && (!best || candidate.seq > best.seq))
71
+ best = candidate;
72
+ }
73
+ return { kind: "hit", event: best, notice: summary.notice };
74
+ }
75
+ export async function loadHistorySummary(session) {
76
+ if (!session.loadSummary)
77
+ return failure("history_unavailable", `Session ${sessionIdentity(session)} has no summary loader`);
78
+ try {
79
+ return success(await session.loadSummary());
80
+ }
81
+ catch (error) {
82
+ return unavailableSession(session, error);
83
+ }
84
+ }
45
85
  export async function loadHistoryRepresentative(session) {
46
86
  if (session.loadRepresentative) {
47
87
  try {
@@ -1,10 +1,11 @@
1
1
  /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
2
  import { Type, type Static } from "typebox";
3
+ export declare function stringEnum<const T extends readonly [string, ...string[]]>(values: T, options?: Record<string, unknown>): Type.TUnsafe<T[number]>;
3
4
  /** The four public roles a history event carries on the wire, in presentation order. */
4
- export declare const HistoryRoleSchema: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
5
+ export declare const HistoryRoleSchema: Type.TUnsafe<"user" | "assistant" | "tool" | "context">;
5
6
  export type HistoryRole = Static<typeof HistoryRoleSchema>;
6
7
  /** How a recorded tool run ended. A call with no recorded result has not ended. */
7
- export declare const ToolCallStatusSchema: Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>;
8
+ export declare const ToolCallStatusSchema: Type.TUnsafe<"error" | "ok" | "unfinished">;
8
9
  export type ToolCallStatus = Static<typeof ToolCallStatusSchema>;
9
10
  /** Internal recorded facts, not a second copy in the public read schema. */
10
11
  export type NestedCallRecord = {
@@ -61,6 +62,8 @@ export type HistoryFilter = {
61
62
  roles?: HistoryRole[];
62
63
  after?: HistoryBound;
63
64
  before?: HistoryBound;
65
+ since?: number;
66
+ until?: number;
64
67
  };
65
68
  /** Native entries after the adapter allocates seqs and selects the active branch. */
66
69
  export type DecodedHistoryItem = {
@@ -97,54 +100,40 @@ export declare function eventDocument(event: HistoryEvent): string;
97
100
  /** Pair results into call events; consumed result seqs redirect to their call event on read. */
98
101
  export declare function projectHistory(rawWindows: DecodedHistoryWindow[], highestSeq: number, branchSeqs: Set<number>): HistoryProjection;
99
102
  /** Summary shared by list, search and read. Full arguments/calls are in the document. */
100
- export declare const NestedCallSummarySchema: Type.TObject<{
101
- call_count: Type.TInteger;
102
- complete: Type.TBoolean;
103
- }>;
104
- /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
105
- export declare const ToolSummarySchema: Type.TObject<{
106
- tool: Type.TOptional<Type.TString>;
107
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
108
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
109
- full_output_path: Type.TOptional<Type.TString>;
110
- }>;
111
- export declare function toolSummary(event: HistoryEvent): Static<typeof ToolSummarySchema>;
103
+ export type NestedCallSummary = {
104
+ call_count: number;
105
+ complete: boolean;
106
+ };
107
+ export type ToolSummary = {
108
+ tool?: string;
109
+ tool_status?: ToolCallStatus;
110
+ output_truncated?: true;
111
+ full_output_path?: string;
112
+ };
113
+ export declare function toolSummary(event: HistoryEvent): ToolSummary;
112
114
  /** Nested-call evidence is read with one event, not listed on every page row. */
113
115
  export declare function nestedCallSummary(event: HistoryEvent): {
114
- nested_calls?: Static<typeof NestedCallSummarySchema>;
116
+ nested_calls?: NestedCallSummary;
115
117
  };
116
118
  /** A run of tool/context events the conversation view replaces with counts. */
117
- export declare const HistoryFoldedRowSchema: Type.TObject<{
118
- session: Type.TOptional<Type.TString>;
119
- first_seq: Type.TInteger;
120
- last_seq: Type.TInteger;
121
- count: Type.TInteger;
122
- tools: Type.TRecord<"^.*$", Type.TInteger>;
123
- }>;
124
- export type HistoryFoldedRow = Static<typeof HistoryFoldedRowSchema>;
119
+ export type HistoryFoldedRow = {
120
+ first_seq: number;
121
+ last_seq: number;
122
+ count: number;
123
+ tools: Record<string, number>;
124
+ };
125
125
  /** Stable identity and a verbatim preview, starting at the search match when present. */
126
- export declare const HistoryPageItemSchema: Type.TObject<{
127
- content: Type.TString;
128
- truncated: Type.TBoolean;
129
- offset_chars: Type.TOptional<Type.TInteger>;
130
- tool: Type.TOptional<Type.TString>;
131
- tool_status: Type.TOptional<Type.TUnion<[Type.TLiteral<"ok">, Type.TLiteral<"error">, Type.TLiteral<"unfinished">]>>;
132
- output_truncated: Type.TOptional<Type.TLiteral<true>>;
133
- full_output_path: Type.TOptional<Type.TString>;
134
- session: Type.TOptional<Type.TString>;
135
- folded_before: Type.TOptional<Type.TObject<{
136
- session: Type.TOptional<Type.TString>;
137
- first_seq: Type.TInteger;
138
- last_seq: Type.TInteger;
139
- count: Type.TInteger;
140
- tools: Type.TRecord<"^.*$", Type.TInteger>;
141
- }>>;
142
- context: Type.TOptional<Type.TLiteral<true>>;
143
- seq: Type.TInteger;
144
- role: Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"context">]>;
145
- created_at: Type.TUnion<[Type.TString, Type.TNull]>;
146
- }>;
147
- export type HistoryPageItem = Static<typeof HistoryPageItemSchema>;
126
+ export type HistoryPageItem = ToolSummary & {
127
+ session?: string;
128
+ folded_before?: HistoryFoldedRow;
129
+ context?: true;
130
+ seq: number;
131
+ role: HistoryRole;
132
+ created_at: string | null;
133
+ content: string;
134
+ truncated: boolean;
135
+ offset_chars?: number;
136
+ };
148
137
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
149
138
  export declare const MAX_FOLD_TOOL_NAMES = 20;
150
139
  /** Longest tool name a fold row lists. */
@@ -152,6 +141,8 @@ export declare const MAX_FOLD_TOOL_NAME_CHARS = 120;
152
141
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
153
142
  export declare function visibleItem(event: HistoryEvent, maxChars: number, matchOffset?: number): HistoryPageItem;
154
143
  export declare function allItems(projection: HistoryProjection): HistoryEvent[];
155
- export declare function matchesFilter(event: HistoryEvent, { after, before, roles }: HistoryFilter): boolean;
144
+ /** Memoized `Date.parse(event.createdAt)` (NaN when missing or invalid). */
145
+ export declare function eventTimestampMs(event: HistoryEvent): number;
146
+ export declare function matchesFilter(event: HistoryEvent, { after, before, since, until, roles }: HistoryFilter): boolean;
156
147
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */
157
148
  export declare function filteredItems(projection: HistoryProjection, params: HistoryFilter): HistoryEvent[];
@@ -1,9 +1,13 @@
1
1
  /** Recorded details live once, in the pageable event document; tools expose a small summary. */
2
2
  import { Type } from "typebox";
3
+ import { sliceCodePoints } from "../text-match.js";
4
+ export function stringEnum(values, options = {}) {
5
+ return Type.Unsafe({ ...Type.Enum([...values], options), type: "string" });
6
+ }
3
7
  /** The four public roles a history event carries on the wire, in presentation order. */
4
- export const HistoryRoleSchema = Type.Union([Type.Literal("user"), Type.Literal("assistant"), Type.Literal("tool"), Type.Literal("context")]);
8
+ export const HistoryRoleSchema = stringEnum(["user", "assistant", "tool", "context"]);
5
9
  /** How a recorded tool run ended. A call with no recorded result has not ended. */
6
- export const ToolCallStatusSchema = Type.Union([Type.Literal("ok"), Type.Literal("error"), Type.Literal("unfinished")]);
10
+ export const ToolCallStatusSchema = stringEnum(["ok", "error", "unfinished"]);
7
11
  function isTextContent(part) {
8
12
  return typeof part === "object" && part !== null && part.type === "text" && typeof part.text === "string";
9
13
  }
@@ -106,18 +110,6 @@ export function projectHistory(rawWindows, highestSeq, branchSeqs) {
106
110
  }));
107
111
  return { windows, highestSeq, branchSeqs, pairedResults };
108
112
  }
109
- /** Summary shared by list, search and read. Full arguments/calls are in the document. */
110
- export const NestedCallSummarySchema = Type.Object({
111
- call_count: Type.Integer({ minimum: 0 }),
112
- complete: Type.Boolean({ description: "true = every nested call was recorded." }),
113
- }, { additionalProperties: false });
114
- /** Tool-run facts shared by list rows and reads; full arguments and calls live in the document. */
115
- export const ToolSummarySchema = Type.Object({
116
- tool: Type.Optional(Type.String()),
117
- tool_status: Type.Optional(ToolCallStatusSchema),
118
- output_truncated: Type.Optional(Type.Literal(true)),
119
- full_output_path: Type.Optional(Type.String()),
120
- }, { additionalProperties: false });
121
113
  export function toolSummary(event) {
122
114
  const execution = event.execution;
123
115
  if (!execution)
@@ -134,27 +126,6 @@ export function nestedCallSummary(event) {
134
126
  const nested = event.execution?.nestedCalls;
135
127
  return nested === undefined ? {} : { nested_calls: { call_count: nested.calls.length, complete: nested.complete } };
136
128
  }
137
- /** A run of tool/context events the conversation view replaces with counts. */
138
- export const HistoryFoldedRowSchema = Type.Object({
139
- session: Type.Optional(Type.String()),
140
- first_seq: Type.Integer({ minimum: 1 }),
141
- last_seq: Type.Integer({ minimum: 1 }),
142
- count: Type.Integer({ minimum: 1 }),
143
- tools: Type.Record(Type.String(), Type.Integer({ minimum: 1 }), { description: "Count per tool name." }),
144
- }, { additionalProperties: false });
145
- /** Stable identity and a verbatim preview, starting at the search match when present. */
146
- export const HistoryPageItemSchema = Type.Object({
147
- session: Type.Optional(Type.String()),
148
- folded_before: Type.Optional(HistoryFoldedRowSchema),
149
- context: Type.Optional(Type.Literal(true, { description: "A neighbor of a search hit, not a hit in this page." })),
150
- seq: Type.Integer({ minimum: 1 }),
151
- role: HistoryRoleSchema,
152
- created_at: Type.Union([Type.String(), Type.Null()]),
153
- ...ToolSummarySchema.properties,
154
- content: Type.String(),
155
- truncated: Type.Boolean({ description: "Preview is partial." }),
156
- offset_chars: Type.Optional(Type.Integer({ minimum: 0, description: "Where the preview starts." })),
157
- }, { additionalProperties: false });
158
129
  /** Bound fold summaries; `count` stays exact even when some tool names do not fit. */
159
130
  export const MAX_FOLD_TOOL_NAMES = 20;
160
131
  /** Longest tool name a fold row lists. */
@@ -162,17 +133,16 @@ export const MAX_FOLD_TOOL_NAME_CHARS = 120;
162
133
  /** A bounded preview of one event from `matchOffset` on, plus its identity facts. */
163
134
  export function visibleItem(event, maxChars, matchOffset) {
164
135
  const document = eventDocument(event);
165
- const chars = Array.from(document);
166
136
  const start = matchOffset ?? 0;
167
137
  // A negative budget would cut the tail and still call the result a prefix.
168
138
  const limit = Math.max(0, maxChars);
169
- const truncated = start > 0 || start + limit < chars.length;
139
+ const { text: content, truncated } = sliceCodePoints(document, start, limit);
170
140
  return {
171
141
  seq: event.seq,
172
142
  role: event.role,
173
143
  created_at: event.createdAt ?? null,
174
144
  ...toolSummary(event),
175
- content: truncated ? chars.slice(start, start + limit).join("") : document,
145
+ content,
176
146
  truncated,
177
147
  ...(matchOffset === undefined ? {} : { offset_chars: matchOffset }),
178
148
  };
@@ -180,11 +150,22 @@ export function visibleItem(event, maxChars, matchOffset) {
180
150
  export function allItems(projection) {
181
151
  return projection.windows.flatMap((current) => current.items);
182
152
  }
153
+ const timestamps = new WeakMap();
154
+ /** Memoized `Date.parse(event.createdAt)` (NaN when missing or invalid). */
155
+ export function eventTimestampMs(event) {
156
+ const cached = timestamps.get(event);
157
+ if (cached !== undefined)
158
+ return cached;
159
+ const parsed = event.createdAt ? Date.parse(event.createdAt) : NaN;
160
+ timestamps.set(event, parsed);
161
+ return parsed;
162
+ }
183
163
  function compareBound(event, bound) {
184
- return "seq" in bound ? event.seq - bound.seq : Date.parse(event.createdAt ?? "") - bound.at;
164
+ return "seq" in bound ? event.seq - bound.seq : eventTimestampMs(event) - bound.at;
185
165
  }
186
- export function matchesFilter(event, { after, before, roles }) {
166
+ export function matchesFilter(event, { after, before, since, until, roles }) {
187
167
  return (!after || compareBound(event, after) > 0) && (!before || compareBound(event, before) < 0)
168
+ && (since === undefined || eventTimestampMs(event) > since) && (until === undefined || eventTimestampMs(event) < until)
188
169
  && (!roles || roles.includes(event.role));
189
170
  }
190
171
  /** Ordered events inside the requested seq/time range and optional roles, before folding. */