@pi-chamber/web 0.9.7 → 0.9.8

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 (61) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramView-BvrCkm_z.js → DiagramView-vaGEmGJn.js} +1 -1
  3. package/dist/assets/{DiffView-DMvRLRN1.js → DiffView-BUOaq70P.js} +1 -1
  4. package/dist/assets/{FileSaveConflictDialog-DGa9u43J.js → FileSaveConflictDialog-B3wIsdE1.js} +1 -1
  5. package/dist/assets/{FilesView-CNHu4RnC.js → FilesView-DPwCE-XA.js} +4 -4
  6. package/dist/assets/{GitView-Cbepz-bR.js → GitView-CGk98LhV.js} +3 -3
  7. package/dist/assets/{JsonTreeView-C2X5oXQm.js → JsonTreeView-HNtRoqVA.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-BanSCkPy.js → MarkdownRendererImpl-DUYL-Wn3.js} +1 -1
  9. package/dist/assets/{PatchDiff-i_9BIlgo.js → PatchDiff-Bluz53zj.js} +1 -1
  10. package/dist/assets/{SessionSwitcherContent-DxS_rFuS.js → SessionSwitcherContent-DDncCwpE.js} +1 -1
  11. package/dist/assets/{SessionSwitcherDropdown-AVghToww.js → SessionSwitcherDropdown-Cw_g3ai3.js} +2 -2
  12. package/dist/assets/SessionUnreadDot-CT5M3-qK.js +1 -0
  13. package/dist/assets/SettingsView-C26Mwkzp.js +2 -0
  14. package/dist/assets/{SettingsWindow-BfPUzBbq.js → SettingsWindow-B_oA1yV4.js} +1 -1
  15. package/dist/assets/{ToolOutputDialog-CJ87b80H.js → ToolOutputDialog-C3xiVDyE.js} +5 -5
  16. package/dist/assets/{ToolPartDiffPreview-bF486Lz1.js → ToolPartDiffPreview-xrxYTK3l.js} +1 -1
  17. package/dist/assets/{VirtualizedFileDiff-CFpvcZ1g.js → VirtualizedFileDiff-Bpgyk3yt.js} +4 -4
  18. package/dist/assets/collapsible-_urywMu5.js +1 -0
  19. package/dist/assets/{computeVirtualFileMetrics-CsAu9rOt.js → computeVirtualFileMetrics-DPPmLfoR.js} +2 -2
  20. package/dist/assets/{contextFileOpenGuard-rILslsBJ.js → contextFileOpenGuard-CV7L_UMk.js} +1 -1
  21. package/dist/assets/{gitStatusPredicates-D_31YElh.js → gitStatusPredicates-BTkHRMCD.js} +1 -1
  22. package/dist/assets/{index-CXLVW_GG.js → index-C3PSe3Mq.js} +1 -1
  23. package/dist/assets/index-CrqlVJXp.js +8 -0
  24. package/dist/assets/{isDiffPlainText-BX609Lau.js → isDiffPlainText-Djb-erNZ.js} +1 -1
  25. package/dist/assets/{isFilePlainText-FgBWqu9b.js → isFilePlainText-BQ-Wnk8C.js} +1 -1
  26. package/dist/assets/{main-tv2uysSs.js → main-7I7_paNp.js} +3 -3
  27. package/dist/assets/{main-C_pL2r_k.js → main-Dpqrd5dA.js} +2 -2
  28. package/dist/assets/{markdownCore-D3Ibaffd.js → markdownCore-DOQQqV2i.js} +1 -1
  29. package/dist/assets/{miniChat-B0xQlBzZ.js → miniChat-b1O4Yu1o.js} +2 -2
  30. package/dist/assets/{mobile-BmSlVuhn.js → mobile-BTpbHrim.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-C4xZzAnn.js → renderElectronMiniChatApp-Cisrg0Iv.js} +2 -2
  32. package/dist/assets/{renderMobileApp-Bi8wTGd5.js → renderMobileApp-CSBtWiZ2.js} +3 -3
  33. package/dist/assets/{runtimeEndpointReset-B6_gFvBD.js → runtimeEndpointReset-sDOkJ0dT.js} +6 -6
  34. package/dist/assets/{runtimeSurface-egSD9pqj.js → runtimeSurface-C9kx2zfD.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-C9QQrBIx.js → useAppFontEffects-BH5qeSfx.js} +83 -83
  36. package/dist/assets/{useFilesViewSearch-BTZutbn-.js → useFilesViewSearch-Bdxwr4SZ.js} +2 -2
  37. package/dist/assets/{usePushVisibilityBeacon-BZcHxSo-.js → usePushVisibilityBeacon-Czfhm8lw.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-Dw5tHQh8.js → useSwitcherItems-CiTeIjW3.js} +1 -1
  39. package/dist/assets/{vendor-base-ui-CdaWtC7e.js → vendor-base-ui-C60wdVnS.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-language-data-0f_rLdj_.js → vendor-codemirror-language-data-BhPKX-r-.js} +2 -2
  41. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-Bkw82kL9.js} +1 -1
  42. package/dist/assets/{vendor-floating-ui-react-dom-BZOGXAGe.js → vendor-floating-ui-react-dom-KLmnYDaG.js} +1 -1
  43. package/dist/assets/{web-components-CYngz9Ml.js → web-components-CuVJfuw8.js} +3 -3
  44. package/dist/index.html +3 -3
  45. package/dist/mini-chat.html +2 -2
  46. package/dist/mobile.html +2 -2
  47. package/package.json +1 -1
  48. package/server/lib/pi/routes.js +12 -6
  49. package/server/lib/pi/routes.test.js +44 -16
  50. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  51. package/server/lib/pi/session-daemon/prompt-preflight.test.js +5 -1
  52. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +15 -5
  53. package/server/lib/pi/session-daemon/send-operation-registry.js +26 -23
  54. package/server/lib/pi/session-daemon/send-operation-registry.test.js +26 -20
  55. package/server/lib/pi/session-daemon/session-daemon.js +24 -12
  56. package/server/lib/pi/ui-settings-store.js +6 -0
  57. package/server/lib/pi/ui-settings-store.test.js +16 -0
  58. package/dist/assets/SessionUnreadDot-CDRZswx-.js +0 -1
  59. package/dist/assets/SettingsView-hyAGp836.js +0 -2
  60. package/dist/assets/collapsible-DesjbW8a.js +0 -1
  61. package/dist/assets/index-BZpvAhrX.js +0 -8
@@ -453,9 +453,9 @@ describe('Pi runtime route', () => {
453
453
  const upload = await fetch(`${base}/attachments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: 'note.txt', mime: 'text/plain', base64: 'YWJj' }) });
454
454
  expect(upload.status).toBe(201);
455
455
  await expect(upload.json()).resolves.toEqual({ attachment: { id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, expiresAt: 3_600_000 } });
456
- const prompt = await fetch(`${base}/sessions/session-1/prompt`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'read this', attachments: [{ id: 'attachment-1' }] }) });
456
+ const prompt = await fetch(`${base}/sessions/session-1/prompt`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'read this', streamEpoch: 'epoch-routes', attachments: [{ id: 'attachment-1' }] }) });
457
457
  expect(prompt.status).toBe(202);
458
- expect(calls).toEqual([{ command: 'sessions.prompt', payload: { sessionId: 'session-1', text: 'read this', attachments: [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }] } }]);
458
+ expect(calls).toEqual([{ command: 'sessions.prompt', payload: { sessionId: 'session-1', text: 'read this', streamEpoch: 'epoch-routes', attachments: [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }] } }]);
459
459
  });
460
460
 
461
461
  it('forwards the send operation id and reports a deduplicated receipt with consumed attachments', async () => {
@@ -482,7 +482,7 @@ describe('Pi runtime route', () => {
482
482
  const send = () => fetch(`${base}/sessions/session-1/prompt`, {
483
483
  method: 'POST',
484
484
  headers: { 'Content-Type': 'application/json' },
485
- body: JSON.stringify({ text: 'one intent', operationId: 'op-1', attachments: [{ id: 'attachment-1' }] }),
485
+ body: JSON.stringify({ text: 'one intent', operationId: 'op-1', streamEpoch: 'epoch-routes', attachments: [{ id: 'attachment-1' }] }),
486
486
  });
487
487
  const first = await send();
488
488
  expect(first.status).toBe(202);
@@ -497,9 +497,14 @@ describe('Pi runtime route', () => {
497
497
  expect(calls[1].payload.operationId).toBe('op-1');
498
498
  });
499
499
 
500
- it('rejects invalid send ids and maps payload mismatch (409) and expiry (410)', async () => {
500
+ it('rejects invalid send ids and maps stale epoch/payload mismatch (409) and expiry (410)', async () => {
501
501
  const runtime = {
502
502
  request: async (_command, payload) => {
503
+ if (payload.operationId === 'op-stale') {
504
+ const error = new Error('stale');
505
+ error.code = 'STALE_STREAM_EPOCH';
506
+ throw error;
507
+ }
503
508
  if (payload.operationId === 'op-mismatch') {
504
509
  const error = new Error('mismatch');
505
510
  error.code = 'OPERATION_PAYLOAD_MISMATCH';
@@ -522,7 +527,7 @@ describe('Pi runtime route', () => {
522
527
  const invalid = await fetch(`${base}/sessions/session-1/prompt`, {
523
528
  method: 'POST',
524
529
  headers: { 'Content-Type': 'application/json' },
525
- body: JSON.stringify({ text: 'hello', operationId: 'bad id with spaces' }),
530
+ body: JSON.stringify({ text: 'hello', operationId: 'bad id with spaces', streamEpoch: 'epoch-routes' }),
526
531
  });
527
532
  expect(invalid.status).toBe(400);
528
533
  await expect(invalid.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
@@ -535,10 +540,25 @@ describe('Pi runtime route', () => {
535
540
  expect(invalidMessage.status).toBe(400);
536
541
  await expect(invalidMessage.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
537
542
 
543
+ const missingEpoch = await fetch(`${base}/sessions/session-1/prompt`, {
544
+ method: 'POST',
545
+ headers: { 'Content-Type': 'application/json' },
546
+ body: JSON.stringify({ text: 'hello', operationId: 'op-missing-epoch' }),
547
+ });
548
+ expect(missingEpoch.status).toBe(400);
549
+
550
+ const stale = await fetch(`${base}/sessions/session-1/prompt`, {
551
+ method: 'POST',
552
+ headers: { 'Content-Type': 'application/json' },
553
+ body: JSON.stringify({ text: 'hello', operationId: 'op-stale', streamEpoch: 'epoch-retired' }),
554
+ });
555
+ expect(stale.status).toBe(409);
556
+ await expect(stale.json()).resolves.toEqual({ error: { code: 'STALE_STREAM_EPOCH' } });
557
+
538
558
  const mismatch = await fetch(`${base}/sessions/session-1/prompt`, {
539
559
  method: 'POST',
540
560
  headers: { 'Content-Type': 'application/json' },
541
- body: JSON.stringify({ text: 'hello', operationId: 'op-mismatch' }),
561
+ body: JSON.stringify({ text: 'hello', operationId: 'op-mismatch', streamEpoch: 'epoch-routes' }),
542
562
  });
543
563
  expect(mismatch.status).toBe(409);
544
564
  await expect(mismatch.json()).resolves.toEqual({ error: { code: 'OPERATION_PAYLOAD_MISMATCH' } });
@@ -546,7 +566,7 @@ describe('Pi runtime route', () => {
546
566
  const expired = await fetch(`${base}/sessions/session-1/prompt`, {
547
567
  method: 'POST',
548
568
  headers: { 'Content-Type': 'application/json' },
549
- body: JSON.stringify({ text: 'hello', operationId: 'op-expired' }),
569
+ body: JSON.stringify({ text: 'hello', operationId: 'op-expired', streamEpoch: 'epoch-routes' }),
550
570
  });
551
571
  expect(expired.status).toBe(410);
552
572
  await expect(expired.json()).resolves.toEqual({ error: { code: 'OPERATION_EXPIRED' } });
@@ -575,7 +595,7 @@ describe('Pi runtime route', () => {
575
595
  const accepted = await fetch(base, {
576
596
  method: 'POST',
577
597
  headers: { 'Content-Type': 'application/json' },
578
- body: JSON.stringify({ kind: 'prompt', operationId: 'op-accepted' }),
598
+ body: JSON.stringify({ kind: 'prompt', operationId: 'op-accepted', streamEpoch: 'epoch-routes' }),
579
599
  });
580
600
  expect(accepted.status).toBe(200);
581
601
  await expect(accepted.json()).resolves.toEqual({ status: 'accepted', receipt: { accepted: true, messageId: 'message-1' } });
@@ -583,7 +603,7 @@ describe('Pi runtime route', () => {
583
603
  const pending = await fetch(base, {
584
604
  method: 'POST',
585
605
  headers: { 'Content-Type': 'application/json' },
586
- body: JSON.stringify({ kind: 'steer', operationId: 'op-pending' }),
606
+ body: JSON.stringify({ kind: 'steer', operationId: 'op-pending', streamEpoch: 'epoch-routes' }),
587
607
  });
588
608
  expect(pending.status).toBe(200);
589
609
  // Pending carries no receipt: the outcome is still being accepted.
@@ -592,7 +612,7 @@ describe('Pi runtime route', () => {
592
612
  const expired = await fetch(base, {
593
613
  method: 'POST',
594
614
  headers: { 'Content-Type': 'application/json' },
595
- body: JSON.stringify({ kind: 'prompt', operationId: 'op-expired' }),
615
+ body: JSON.stringify({ kind: 'prompt', operationId: 'op-expired', streamEpoch: 'epoch-routes' }),
596
616
  });
597
617
  expect(expired.status).toBe(200);
598
618
  await expect(expired.json()).resolves.toEqual({ status: 'expired' });
@@ -600,13 +620,21 @@ describe('Pi runtime route', () => {
600
620
  const unknown = await fetch(base, {
601
621
  method: 'POST',
602
622
  headers: { 'Content-Type': 'application/json' },
603
- body: JSON.stringify({ kind: 'followUp', operationId: 'op-unknown' }),
623
+ body: JSON.stringify({ kind: 'followUp', operationId: 'op-unknown', streamEpoch: 'epoch-routes' }),
604
624
  });
605
625
  expect(unknown.status).toBe(200);
606
626
  await expect(unknown.json()).resolves.toEqual({ status: 'unknown' });
607
627
 
608
- expect(calls.filter((call) => call.command === 'sessions.sendReceipt')).toHaveLength(4);
609
- expect(calls[0].payload).toEqual({ kind: 'prompt', sessionId: 'session-1', operationId: 'op-accepted' });
628
+ const missingEpoch = await fetch(base, {
629
+ method: 'POST',
630
+ headers: { 'Content-Type': 'application/json' },
631
+ body: JSON.stringify({ kind: 'followUp', operationId: 'op-no-epoch' }),
632
+ });
633
+ expect(missingEpoch.status).toBe(200);
634
+ await expect(missingEpoch.json()).resolves.toEqual({ status: 'unknown' });
635
+
636
+ expect(calls.filter((call) => call.command === 'sessions.sendReceipt')).toHaveLength(5);
637
+ expect(calls[0].payload).toEqual({ kind: 'prompt', sessionId: 'session-1', operationId: 'op-accepted', streamEpoch: 'epoch-routes' });
610
638
 
611
639
  const invalidKind = await fetch(base, {
612
640
  method: 'POST',
@@ -810,13 +838,13 @@ describe('Pi runtime route', () => {
810
838
  extensionStatuses: [{ key: 'mode', text: 'mode:economy/xhigh' }],
811
839
  });
812
840
  const promptResponse = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-4/prompt`, {
813
- method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }),
841
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello', streamEpoch: 'epoch-routes' }),
814
842
  });
815
843
  expect(promptResponse.status).toBe(202);
816
844
  await expect(promptResponse.json()).resolves.toEqual({ accepted: true, messageId: 'entry-2' });
817
845
  expect(calls).toEqual([
818
846
  { command: 'sessions.open', payload: { sessionId: 'pi-session-4' } },
819
- { command: 'sessions.prompt', payload: { sessionId: 'pi-session-4', text: 'hello' } },
847
+ { command: 'sessions.prompt', payload: { sessionId: 'pi-session-4', text: 'hello', streamEpoch: 'epoch-routes' } },
820
848
  ]);
821
849
  });
822
850
 
@@ -902,7 +930,7 @@ describe('Pi runtime route', () => {
902
930
  expect((await fetch(`${base}/fork`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', messageId: 'entry-1' }) })).status).toBe(201);
903
931
  expect((await fetch(`${base}/clone`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other' }) })).status).toBe(201);
904
932
  for (const suffix of ['prompt', 'steer', 'follow-up']) {
905
- expect((await fetch(`${base}/${suffix}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }) })).status).toBe(202);
933
+ expect((await fetch(`${base}/${suffix}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello', streamEpoch: 'epoch-routes' }) })).status).toBe(202);
906
934
  }
907
935
  for (const [suffix, body] of [['abort', {}], ['model', { model: { providerId: 'test', modelId: 'model' } }], ['thinking', { thinking: 'high' }]]) {
908
936
  expect((await fetch(`${base}/${suffix}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', ...body }) })).status).toBe(204);
@@ -39,7 +39,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
39
39
  - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/sendReceipt/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts from transient per-mutation services (never retained; Pi 0.84.1 exposes no dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager — file reads plus a cleared create-time timeout, no watchers/intervals/listeners, so dropping the reference lets GC reclaim it) with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. `providers.refresh` touches only live runtimes; the returned catalog always comes from the active runtime via `providers.list`. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Session deletion publishes an explicit `session.deleted` event; archive and directory moves keep the id and never publish it. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
40
40
  - Each event and reconnect snapshot has a monotonic sequence. Replay is capability-negotiated: the subscriber stamps its cursor with the `streamEpoch` it was established under, a marker-less cursor fails as `DAEMON_PROTOCOL_MISMATCH`, and a cursor from a retired epoch resyncs from a snapshot instead of replaying — even when this daemon's sequence numerically overtook the old cursor, replaying from it would silently skip the head of the new space. Every event, snapshot, and health result carries an opaque random `streamEpoch` regenerated on every daemon process start (never derived from daemon id, profile key, pid, or any private identity); `runtime.health` advertises the `events.streamEpoch` capability, session reads stamp it so clients can reject stale-epoch responses, and a snapshot published because the cursor could not be replayed is additionally stamped `resync: true` as a recovery baseline. A reconnect replays the retained contiguous suffix after its cursor when available, otherwise it receives an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions. The suffix lives in `session-replay.js` and is bounded by both count (1,024 events) and encoded wire bytes (8 MiB): eviction removes whole oldest events first and never truncates content, each event is serialized once and the cached line is reused for live broadcast and replay, and live delivery stays full-fidelity even for events too large to retain. The byte budget counts encoded wire bytes, not heap, and snapshots assign sequence numbers without replay insertion so numeric gaps from private snapshots are intentional. A single oversized event clears the retained suffix without being retained, an empty ring never replays, and a cursor beyond the latest sequence resynchronizes from a snapshot; contiguity is judged on the global suffix while delivery stays session-filtered, so a filtered client never replays through a gap. A missed suffix recovers through `session.snapshot` plus `sessions.open` hydrate, which re-reads persisted entries for tool finals and lifecycle.
41
41
  - Prompt, steer, and follow-up requests acknowledge acceptance only after the Pi SDK preflight signal (session.prompt with preflightResult(true)); the daemon owns the still-running turn promise and publishes any asynchronous rejection as `session.error`. A preflight rejection (preflightResult(false)) propagates as the request rejection so dedup never caches it as accepted and the operation id stays reusable. Plain text uses prompt() with expandPromptTemplates:false and source:extension plus images; slash input keeps source:rpc. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata per delivery kind (`prompt`/`steer`/`followUp`) and adds it to the matching user start. SDK `queue_update` shrink is the authoritative owner of the next user start (steering drains before followUp regardless of send order); direct starts emit no shrink and fall back to oldest-by-generation. Requested `steer`/`followUp` always travels as SDK `streamingBehavior` (ignored while idle) so an idle arrival that races another sender still queues. Retention is decided at resolution from authoritative runtime state (`isStreaming` or SDK queue non-empty, never for handled extension commands); only queued resolutions keep metadata until their per-delivery start, all other completions clean a still-pending entry (an extension command that never emits a user start). The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
42
- - Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId`, the daemon claims `kind + sessionId + operationId` BEFORE Pi activation, and an identical retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same `kind + sessionId + operationId` with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId` identity, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime at-most-once guarantee, only within the retention window; a restart loses receipts (documented crash window, replay re-executes). Send-receipt lookup and replay protection remain separate contracts. The stream epoch guards event cursors across daemon restarts; send/config locking remains session-scoped.
42
+ - Send-intent deduplication (`send-operation-registry.js`) owns the authoritative execution boundary for prompt/steer/followUp: the client labels each intent with a stable `operationId` and the health-verified `streamEpoch`, the daemon claims `kind + sessionId + operationId + streamEpoch` BEFORE Pi activation, and an identical same-epoch retry returns the original acceptance receipt (`{ accepted, messageId, deduplicated: true }`) without invoking Pi again. A concurrent duplicate of a still-pending intent shares the original outcome; the same full key with a different payload (text, model, thinking, message id, or attachments) fails as `OPERATION_PAYLOAD_MISMATCH` (HTTP 409). An intent from another daemon lifetime fails as `STALE_STREAM_EPOCH` (HTTP 409) before Pi or attachment-consumption side effects. The same id on a different kind or session is a different intent and executes independently, never a mismatch. Only acceptances are retained: request-path rejections happen before Pi runs (nothing executed, id reusable) while pending duplicates still share the original rejection, and every claim settles so pending duplicates never hang. Retention is bounded: receipts expire after `sendOperationTtlMs` (default ten minutes) and at most 1,024 accepted receipts are retained (oldest evicted to a bounded expired tombstone); pending claims are bounded separately (256 entries, never expired while active, new distinct pending past the bound fails as `SESSION_BUSY`). An expired or evicted id reports `expired` and a retry with the same id fails as `OPERATION_EXPIRED` (HTTP 410), never an automatic re-execution — callers must use a new operation id. `sessions.sendReceipt` is the exact read-only receipt lookup for an uncertain send: it requires the full `kind + sessionId + operationId + streamEpoch` identity; a missing epoch returns `unknown`, never invokes Pi, and returns `accepted` (retained receipt), `pending`, `expired` (seen but retention gone, outcome unknown, never assume success), or `unknown` (never seen in this retention window, tombstone pressure, post-restart, or rejected before Pi ran). The registry is in-memory per daemon process with bounded tombstones (`expired` degrades to `unknown` under pressure): there is no lifetime receipt guarantee, only within the retention window. A restart loses receipts, but the replacement daemon rejects the retired epoch instead of replaying the old intent. Receipt lookup and replay protection remain separate read-only contracts.
43
43
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
44
44
  - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). View-only access (`sessions.open`, `sessions.messages`, `sessions.tree`, plus navigate/fork/clone/abort/model/thinking/rename settlement) arms the same lifetime through `touchIdleDisposal`, so browsing old sessions without prompting cannot grow the registry unboundedly while the UI keeps only a bounded transcript cache. Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt or open. The touch clears first and re-arms only when the session is resident and idle-safe, so a read cannot race a pending operation and a repeated open extends the deadline. Agent and compaction starts cancel pending disposal, and prompt/compact entry clears it before activation. The timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative, while a send is in flight (`activeSessionInputs`), while a resource reload is pending or running, while a provider retry is scheduled, or while compaction is running/retrying; pending extension dialogs are instead cancelled with an authoritative dismiss event. A read or prompt that arrives during an in-flight disposal waits for it and reopens from JSONL instead of adopting a dying runtime. There is deliberately no acquisition-path eviction: capacity pressure alone never disposes entries that are actively mounting.
45
45
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
@@ -169,12 +169,15 @@ describe('prompt preflight acceptance', () => {
169
169
  const daemons = [];
170
170
  let client;
171
171
  let currentEndpoint;
172
+ let currentStreamEpoch;
172
173
 
173
174
  const send = async (command, payload) => {
174
175
  const connection = connectClient(currentEndpoint);
175
176
  await connection.authenticate();
176
177
  try {
177
- return await connection.request(command, payload);
178
+ return await connection.request(command, payload.operationId
179
+ ? { ...payload, streamEpoch: currentStreamEpoch }
180
+ : payload);
178
181
  } finally {
179
182
  await connection.close().catch(() => {});
180
183
  }
@@ -207,6 +210,7 @@ describe('prompt preflight acceptance', () => {
207
210
  currentEndpoint = endpoint;
208
211
  client = connectClient(endpoint);
209
212
  await client.authenticate();
213
+ currentStreamEpoch = (await client.request('runtime.health')).result.streamEpoch;
210
214
  if (openSession) await client.request('sessions.open', { sessionId: 'session-1' });
211
215
  return { session, endpoint, root, sessionFile };
212
216
  };
@@ -177,6 +177,7 @@ describe('send dedup (finding #3)', () => {
177
177
  const daemons = [];
178
178
  let client;
179
179
  let currentEndpoint;
180
+ let currentStreamEpoch;
180
181
 
181
182
  // The daemon destroys a request connection on a rejected command, so each
182
183
  // send uses its own short-lived authenticated connection.
@@ -184,7 +185,10 @@ describe('send dedup (finding #3)', () => {
184
185
  const connection = connectClient(currentEndpoint);
185
186
  await connection.authenticate();
186
187
  try {
187
- return await connection.request(command, payload);
188
+ const epochBound = ['sessions.prompt', 'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt'].includes(command)
189
+ ? { ...payload, streamEpoch: payload.streamEpoch ?? currentStreamEpoch }
190
+ : payload;
191
+ return await connection.request(command, epochBound);
188
192
  } finally {
189
193
  await connection.close().catch(() => {});
190
194
  }
@@ -221,6 +225,8 @@ describe('send dedup (finding #3)', () => {
221
225
  currentEndpoint = endpoint;
222
226
  client = connectClient(endpoint);
223
227
  await client.authenticate();
228
+ const health = await client.request('runtime.health');
229
+ currentStreamEpoch = health.result.streamEpoch;
224
230
  if (openSession) await client.request('sessions.open', { sessionId: 'session-1' });
225
231
  return { session, endpoint, root, sessionFile };
226
232
  };
@@ -264,10 +270,11 @@ describe('send dedup (finding #3)', () => {
264
270
  expect(session.sent).toHaveLength(2);
265
271
  });
266
272
 
267
- it('treats a daemon restart as the explicit crash window: a replayed id re-executes on the new daemon', async () => {
273
+ it('rejects an old-epoch id after a daemon restart without re-executing it', async () => {
268
274
  const first = await startDaemonWithSession();
269
275
  const { sessionFile, root } = first;
270
- const payload = { sessionId: 'session-1', text: 'across restart', operationId: 'op-restart' };
276
+ const oldEpoch = currentStreamEpoch;
277
+ const payload = { sessionId: 'session-1', text: 'across restart', operationId: 'op-restart', streamEpoch: oldEpoch };
271
278
  await expect(send('sessions.prompt', payload)).resolves.toMatchObject({ result: { accepted: true } });
272
279
  expect(first.session.sent).toHaveLength(1);
273
280
  await client.close();
@@ -289,9 +296,12 @@ describe('send dedup (finding #3)', () => {
289
296
  await daemon.start();
290
297
  client = connectClient(endpoint);
291
298
  await client.authenticate();
299
+ const health = await client.request('runtime.health');
300
+ currentStreamEpoch = health.result.streamEpoch;
301
+ expect(currentStreamEpoch).not.toBe(oldEpoch);
292
302
 
293
- await expect(send('sessions.prompt', payload)).resolves.toMatchObject({ result: { accepted: true } });
294
- expect(session.sent).toHaveLength(1);
303
+ await expect(send('sessions.prompt', payload)).rejects.toMatchObject({ code: 'STALE_STREAM_EPOCH' });
304
+ expect(session.sent).toHaveLength(0);
295
305
  });
296
306
 
297
307
  it('sessions.sendReceipt tracks pending then accepted then expired with no false guarantee', async () => {
@@ -24,13 +24,10 @@
24
24
  * - The same id with a different payload (text, model, thinking, message id,
25
25
  * or attachments) is rejected as `OPERATION_PAYLOAD_MISMATCH` — a
26
26
  * duplicated id never silently executes unrelated work. Identity is
27
- * `kind + sessionId + operationId`: the same id on a different session or
28
- * delivery kind is a different intent and executes independently (never a
29
- * mismatch). `streamEpoch` (stamped only by the stream-epoch split)
30
- * is intentionally NOT fingerprinted, so adding or omitting it on a retry
31
- * in the same lifetime never causes a mismatch. This split performs no
32
- * epoch guard; the stream-epoch branch enforces `STALE_STREAM_EPOCH`
33
- * before the claim.
27
+ * `kind + sessionId + operationId + streamEpoch`: the same id on a
28
+ * different session or delivery kind is a different intent. An epoch that
29
+ * does not match this daemon lifetime is rejected as `stale` before a claim
30
+ * is created, so a post-restart retry cannot execute.
34
31
  *
35
32
  * Retention is bounded and explicit: accepted receipts are kept for `ttlMs`
36
33
  * and at most `maxEntries` accepted receipts are retained (oldest evicted).
@@ -51,10 +48,8 @@
51
48
  * are not auto-expired: a leaked claim occupies one of `maxPending` slots
52
49
  * until restart instead of risking a duplicate execution. The registry is
53
50
  * in-memory per daemon process: a daemon restart loses receipts, which is
54
- * the documented crash-window — a client retry across a restart may
55
- * re-execute an accepted intent, and clients must not replay uncertain
56
- * sends across restarts (the stream-epoch split adds a verified-epoch guard
57
- * for this window; this split documents the raw window without it). After `ttlMs` the receipt is
51
+ * the documented receipt-loss window. The required epoch prevents an old
52
+ * intent from being claimed by the replacement process. After `ttlMs` the receipt is
58
53
  * gone: a retry with the same id is rejected as expired, never a silent
59
54
  * deduplicated success nor an automatic re-execution — callers must treat
60
55
  * the retention window as the only safe retry window and use a new
@@ -74,6 +69,10 @@ export const isValidSendOperationId = (value) => (
74
69
  typeof value === 'string' && SEND_OPERATION_ID_PATTERN.test(value)
75
70
  );
76
71
 
72
+ export const isValidStreamEpoch = (value) => (
73
+ typeof value === 'string' && value.length > 0 && value.length <= 128
74
+ );
75
+
77
76
  /** Deterministic stringify so payload fingerprints are order-independent. */
78
77
  export const stableFingerprint = (value) => {
79
78
  if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
@@ -82,15 +81,17 @@ export const stableFingerprint = (value) => {
82
81
  return `{${keys.map((key) => `${JSON.stringify(key)}:${stableFingerprint(value[key])}`).join(',')}}`;
83
82
  };
84
83
 
85
- const entryKey = ({ kind, sessionId, operationId }) => `${kind}\u0000${sessionId}\u0000${operationId}`;
84
+ const entryKey = ({ kind, sessionId, operationId, streamEpoch }) => `${kind}\u0000${sessionId}\u0000${operationId}\u0000${streamEpoch}`;
86
85
 
87
86
  export const createSendOperationRegistry = ({
87
+ streamEpoch,
88
88
  now = () => Date.now(),
89
89
  ttlMs = 10 * 60 * 1_000,
90
90
  maxEntries = 1_024,
91
91
  maxPending = 256,
92
92
  pendingTtlMs = 30_000,
93
93
  } = {}) => {
94
+ if (!isValidStreamEpoch(streamEpoch)) throw new Error('send operation streamEpoch must be an opaque string no longer than 128 characters');
94
95
  if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error('send operation ttlMs must be positive');
95
96
  if (!Number.isFinite(maxEntries) || maxEntries <= 0) throw new Error('send operation maxEntries must be positive');
96
97
  if (!Number.isFinite(maxPending) || maxPending <= 0) throw new Error('send operation maxPending must be positive');
@@ -153,8 +154,9 @@ export const createSendOperationRegistry = ({
153
154
  }
154
155
  };
155
156
 
156
- const claim = ({ kind, sessionId, operationId, fingerprint }) => {
157
- const key = entryKey({ kind, sessionId, operationId });
157
+ const claim = ({ kind, sessionId, operationId, streamEpoch: requestedEpoch, fingerprint }) => {
158
+ if (!isValidStreamEpoch(requestedEpoch) || requestedEpoch !== streamEpoch) return { outcome: 'stale' };
159
+ const key = entryKey({ kind, sessionId, operationId, streamEpoch: requestedEpoch });
158
160
  evictExpired();
159
161
  const existing = entries.get(key);
160
162
  if (existing) {
@@ -209,18 +211,18 @@ export const createSendOperationRegistry = ({
209
211
  return { outcome: 'new', entry };
210
212
  };
211
213
 
212
- const getReceipt = ({ kind, sessionId, operationId }) => {
214
+ const getReceipt = ({ kind, sessionId, operationId, streamEpoch: requestedEpoch }) => {
213
215
  evictExpired();
216
+ if (!isValidStreamEpoch(requestedEpoch)) return undefined;
214
217
  if (typeof kind === 'string' && kind.length > 0) {
215
- const entry = entries.get(entryKey({ kind, sessionId, operationId }));
218
+ const entry = entries.get(entryKey({ kind, sessionId, operationId, streamEpoch: requestedEpoch }));
216
219
  if (entry?.state === 'accepted') return { receipt: entry.receipt, fingerprint: entry.fingerprint };
217
220
  return undefined;
218
221
  }
219
222
  for (const [key, entry] of entries) {
220
223
  if (entry.state !== 'accepted') continue;
221
- // Keys are `kind + NUL + sessionId + NUL + operationId`; match the
222
- // session+operation suffix when the caller did not specify a kind.
223
- if (key.endsWith(`\u0000${sessionId}\u0000${operationId}`)) {
224
+ // Keys are `kind + NUL + sessionId + NUL + operationId + NUL + epoch`.
225
+ if (key.endsWith(`\u0000${sessionId}\u0000${operationId}\u0000${requestedEpoch}`)) {
224
226
  return { receipt: entry.receipt, fingerprint: entry.fingerprint, kind: key.slice(0, key.indexOf('\u0000')) };
225
227
  }
226
228
  }
@@ -228,20 +230,21 @@ export const createSendOperationRegistry = ({
228
230
  };
229
231
 
230
232
  // Exact-identity receipt lookup for `sessions.sendReceipt`: requires the
231
- // full `kind + sessionId + operationId` key. Returns one of
233
+ // full `kind + sessionId + operationId + streamEpoch` key. Returns one of
232
234
  // `accepted` (retained receipt), `pending` (still-accepting claim),
233
235
  // `expired` (seen but retention gone — outcome unknown, never assume
234
236
  // success), or `unknown` (never seen in this retention window, evicted
235
237
  // tombstone pressure, post-restart, or rejected before Pi ran so nothing
236
238
  // executed). Never returns a receipt after expiry.
237
- const query = ({ kind, sessionId, operationId }) => {
239
+ const query = ({ kind, sessionId, operationId, streamEpoch: requestedEpoch }) => {
238
240
  evictExpired();
239
241
  if (typeof kind !== 'string' || kind.length === 0
240
242
  || typeof sessionId !== 'string' || sessionId.length === 0
241
- || typeof operationId !== 'string' || operationId.length === 0) {
243
+ || typeof operationId !== 'string' || operationId.length === 0
244
+ || !isValidStreamEpoch(requestedEpoch)) {
242
245
  return { status: 'unknown' };
243
246
  }
244
- const key = entryKey({ kind, sessionId, operationId });
247
+ const key = entryKey({ kind, sessionId, operationId, streamEpoch: requestedEpoch });
245
248
  const entry = entries.get(key);
246
249
  if (entry?.state === 'accepted') {
247
250
  return { status: 'accepted', receipt: entry.receipt, fingerprint: entry.fingerprint };
@@ -7,15 +7,18 @@ import {
7
7
  } from './send-operation-registry.js';
8
8
 
9
9
  describe('send operation registry', () => {
10
+ const streamEpoch = 'epoch-1';
11
+ const createRegistry = (options = {}) => createSendOperationRegistry({ streamEpoch, ...options });
10
12
  const baseClaim = {
11
13
  kind: 'prompt',
12
14
  sessionId: 'sess-1',
13
15
  operationId: 'op-1',
16
+ streamEpoch,
14
17
  fingerprint: '{"text":"hello"}',
15
18
  };
16
19
 
17
20
  it('accepts a new claim and settles the acceptance receipt', () => {
18
- const registry = createSendOperationRegistry();
21
+ const registry = createRegistry();
19
22
  const claim = registry.claim(baseClaim);
20
23
  expect(claim.outcome).toBe('new');
21
24
  claim.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
@@ -26,7 +29,7 @@ describe('send operation registry', () => {
26
29
  });
27
30
 
28
31
  it('shares the original receipt with a concurrent pending duplicate', async () => {
29
- const registry = createSendOperationRegistry();
32
+ const registry = createRegistry();
30
33
  const first = registry.claim(baseClaim);
31
34
  expect(first.outcome).toBe('new');
32
35
 
@@ -44,7 +47,7 @@ describe('send operation registry', () => {
44
47
  });
45
48
 
46
49
  it('shares the original rejection with a concurrent pending duplicate and frees the id', async () => {
47
- const registry = createSendOperationRegistry();
50
+ const registry = createRegistry();
48
51
  const first = registry.claim(baseClaim);
49
52
  const duplicate = registry.claim(baseClaim);
50
53
  expect(duplicate.outcome).toBe('pending');
@@ -55,8 +58,10 @@ describe('send operation registry', () => {
55
58
  expect(registry.claim(baseClaim).outcome).toBe('new');
56
59
  });
57
60
 
58
- it('rejects a payload mismatch for the same id', () => {
59
- const registry = createSendOperationRegistry();
61
+ it('rejects payload changes and retired epochs before claiming', () => {
62
+ const registry = createRegistry();
63
+ expect(registry.claim({ ...baseClaim, streamEpoch: 'epoch-retired' }).outcome).toBe('stale');
64
+ expect(registry.size).toBe(0);
60
65
  const first = registry.claim(baseClaim);
61
66
  first.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
62
67
  expect(registry.claim({ ...baseClaim, fingerprint: '{"text":"different"}' }).outcome).toBe('mismatch');
@@ -66,7 +71,7 @@ describe('send operation registry', () => {
66
71
 
67
72
  it('expires accepted receipts after the ttl so the same id can never auto-replay', () => {
68
73
  let time = 1_000;
69
- const registry = createSendOperationRegistry({ now: () => time, ttlMs: 50 });
74
+ const registry = createRegistry({ now: () => time, ttlMs: 50 });
70
75
  const claim = registry.claim(baseClaim);
71
76
  claim.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'msg-1' } });
72
77
  expect(registry.claim(baseClaim).outcome).toBe('accepted');
@@ -77,13 +82,13 @@ describe('send operation registry', () => {
77
82
  // Retention gone: the same id is rejected as expired (never a silent
78
83
  // re-execution). Callers must use a new operation id after expiry.
79
84
  expect(registry.claim(baseClaim).outcome).toBe('expired');
80
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1' }).status).toBe('expired');
85
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1', streamEpoch }).status).toBe('expired');
81
86
  // A distinct id is still a distinct intent and executes.
82
87
  expect(registry.claim({ ...baseClaim, operationId: 'op-2' }).outcome).toBe('new');
83
88
  });
84
89
 
85
90
  it('bounds retention by evicting the oldest accepted receipts', () => {
86
- const registry = createSendOperationRegistry({ maxEntries: 2 });
91
+ const registry = createRegistry({ maxEntries: 2 });
87
92
  const one = registry.claim({ ...baseClaim, operationId: 'op-1' });
88
93
  one.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm1' } });
89
94
  const two = registry.claim({ ...baseClaim, operationId: 'op-2' });
@@ -99,7 +104,7 @@ describe('send operation registry', () => {
99
104
  });
100
105
 
101
106
  it('never evicts a pending claim so concurrent duplicates keep sharing the outcome', () => {
102
- const registry = createSendOperationRegistry({ maxEntries: 2 });
107
+ const registry = createRegistry({ maxEntries: 2 });
103
108
  const pending = registry.claim({ ...baseClaim, operationId: 'op-pending' });
104
109
  expect(pending.outcome).toBe('new');
105
110
  for (let index = 0; index < 5; index += 1) {
@@ -130,11 +135,12 @@ describe('send operation registry', () => {
130
135
 
131
136
  it('query() distinguishes pending, accepted, unknown, and expired with no false acceptance', () => {
132
137
  let time = 1_000;
133
- const registry = createSendOperationRegistry({ now: () => time, ttlMs: 50, maxEntries: 10 });
134
- const key = { kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q' };
138
+ const registry = createRegistry({ now: () => time, ttlMs: 50, maxEntries: 10 });
139
+ const key = { kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', streamEpoch };
140
+ expect(registry.query({ ...key, streamEpoch: undefined }).status).toBe('unknown');
135
141
  expect(registry.query(key).status).toBe('unknown');
136
142
 
137
- const fresh = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', fingerprint: baseClaim.fingerprint });
143
+ const fresh = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', streamEpoch, fingerprint: baseClaim.fingerprint });
138
144
  expect(fresh.outcome).toBe('new');
139
145
  expect(registry.query(key).status).toBe('pending');
140
146
 
@@ -152,18 +158,18 @@ describe('send operation registry', () => {
152
158
  expect(registry.query(key).receipt).toBeUndefined();
153
159
  // A retry after expiry is rejected as expired — it must not
154
160
  // automatically re-execute. The caller needs a new operation id.
155
- const retry = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', fingerprint: baseClaim.fingerprint });
161
+ const retry = registry.claim({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-q', streamEpoch, fingerprint: baseClaim.fingerprint });
156
162
  expect(retry.outcome).toBe('expired');
157
163
  expect(registry.query(key).status).toBe('expired');
158
164
  expect(registry.query(key).receipt).toBeUndefined();
159
165
  });
160
166
 
161
167
  it('rejections before Pi leave no tombstone while evicted acceptances expire', () => {
162
- const registry = createSendOperationRegistry({ maxEntries: 2 });
168
+ const registry = createRegistry({ maxEntries: 2 });
163
169
  const rejected = registry.claim({ ...baseClaim, operationId: 'op-reject' });
164
170
  rejected.entry.settle({ accepted: false, error: new Error('busy') });
165
171
  // Nothing executed: unknown (reusable), not expired.
166
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-reject' }).status).toBe('unknown');
172
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-reject', streamEpoch }).status).toBe('unknown');
167
173
 
168
174
  const one = registry.claim({ ...baseClaim, operationId: 'op-1' });
169
175
  one.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm1' } });
@@ -172,13 +178,13 @@ describe('send operation registry', () => {
172
178
  const three = registry.claim({ ...baseClaim, operationId: 'op-3' });
173
179
  three.entry.settle({ accepted: true, receipt: { accepted: true, messageId: 'm3' } });
174
180
  // Oldest acceptance evicted: expired tombstone, never a false acceptance.
175
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1' }).status).toBe('expired');
176
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-2' }).status).toBe('accepted');
181
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-1', streamEpoch }).status).toBe('expired');
182
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-2', streamEpoch }).status).toBe('accepted');
177
183
  });
178
184
 
179
185
  it('never expires an active pending claim so duplicates cannot double-execute', async () => {
180
186
  let time = 1_000;
181
- const registry = createSendOperationRegistry({ now: () => time, pendingTtlMs: 20, maxEntries: 4, maxPending: 2 });
187
+ const registry = createRegistry({ now: () => time, pendingTtlMs: 20, maxEntries: 4, maxPending: 2 });
182
188
  const first = registry.claim({ ...baseClaim, operationId: 'op-leak-1' });
183
189
  const second = registry.claim({ ...baseClaim, operationId: 'op-leak-2' });
184
190
  expect(first.outcome).toBe('new');
@@ -189,7 +195,7 @@ describe('send operation registry', () => {
189
195
  // Active ownership survives past pendingTtlMs: expiring here would let a
190
196
  // duplicate re-execute the same operation, so duplicates still share.
191
197
  expect(registry.claim({ ...baseClaim, operationId: 'op-leak-1' }).outcome).toBe('pending');
192
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1' }).status).toBe('pending');
198
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1', streamEpoch }).status).toBe('pending');
193
199
  expect(registry.claim({ ...baseClaim, operationId: 'op-after' }).outcome).toBe('overloaded');
194
200
  // Settling frees the slot: a busy rejection shares with its duplicate
195
201
  // and leaves the id reusable (nothing executed).
@@ -197,7 +203,7 @@ describe('send operation registry', () => {
197
203
  expect(duplicate.outcome).toBe('pending');
198
204
  first.entry.settle({ accepted: false, error: Object.assign(new Error('busy'), { code: 'SESSION_BUSY' }) });
199
205
  await expect(duplicate.settled).rejects.toMatchObject({ code: 'SESSION_BUSY' });
200
- expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1' }).status).toBe('unknown');
206
+ expect(registry.query({ kind: 'prompt', sessionId: 'sess-1', operationId: 'op-leak-1', streamEpoch }).status).toBe('unknown');
201
207
  expect(registry.claim({ ...baseClaim, operationId: 'op-leak-1' }).outcome).toBe('new');
202
208
  expect(registry.pendingSize).toBeLessThanOrEqual(2);
203
209
  expect(registry.expiredSize).toBeLessThanOrEqual(4);