@pi-chamber/web 0.9.6 → 0.9.8-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramView-0Iq1ak1I.js → DiagramView-BMBrrFLy.js} +1 -1
  3. package/dist/assets/{DiffView-DD1AFRi3.js → DiffView-yVBxHkBI.js} +1 -1
  4. package/dist/assets/{FileSaveConflictDialog-CoKwDovb.js → FileSaveConflictDialog-D0siEm8l.js} +1 -1
  5. package/dist/assets/FilesView-CkcKBKkT.js +6 -0
  6. package/dist/assets/{GitView-LFEpCasf.js → GitView-CfuhQOfc.js} +3 -3
  7. package/dist/assets/{JsonTreeView-Cwjgvh4g.js → JsonTreeView-6kRdE1BO.js} +1 -1
  8. package/dist/assets/{MarkdownRendererImpl-_7kV1yNw.js → MarkdownRendererImpl-CRWbN_Jc.js} +2 -2
  9. package/dist/assets/{PatchDiff-DG43C1HW.js → PatchDiff-B0ssv8Aw.js} +1 -1
  10. package/dist/assets/{SessionSwitcherContent-DCFXPY3d.js → SessionSwitcherContent-NmfI4B0Z.js} +1 -1
  11. package/dist/assets/{SessionSwitcherDropdown-QY7FKuEQ.js → SessionSwitcherDropdown-DmE2hYTN.js} +2 -2
  12. package/dist/assets/SessionUnreadDot-LDTswryg.js +1 -0
  13. package/dist/assets/SettingsView-D0iw6y_H.js +2 -0
  14. package/dist/assets/SettingsWindow-BT2TzUBK.js +1 -0
  15. package/dist/assets/{ToolOutputDialog-IlCrS6BR.js → ToolOutputDialog-Bnl51bva.js} +4 -4
  16. package/dist/assets/{ToolPartDiffPreview-D68JV0rR.js → ToolPartDiffPreview-DgPtLS_h.js} +1 -1
  17. package/dist/assets/{VirtualizedFileDiff-Bl-rAYeh.js → VirtualizedFileDiff-D3zBpYIS.js} +4 -4
  18. package/dist/assets/collapsible-_urywMu5.js +1 -0
  19. package/dist/assets/{computeVirtualFileMetrics-FSOm2VrW.js → computeVirtualFileMetrics-y2AJzpKw.js} +2 -2
  20. package/dist/assets/{contextFileOpenGuard-Bxb6AIPa.js → contextFileOpenGuard-DYUFkrPT.js} +1 -1
  21. package/dist/assets/{gitStatusPredicates-DxolDpMd.js → gitStatusPredicates-CbFfOlbV.js} +1 -1
  22. package/dist/assets/index-BXgR2dKM.css +1 -0
  23. package/dist/assets/index-CrqlVJXp.js +8 -0
  24. package/dist/assets/{index-Dh58uD3I.js → index-DwJJarzh.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-D3_04XCh.js → isDiffPlainText-kXPOivsq.js} +1 -1
  26. package/dist/assets/{isFilePlainText-CHouYQhH.js → isFilePlainText-BBIPqnLo.js} +1 -1
  27. package/dist/assets/{main-HzTrVvbB.js → main-BshSYpnV.js} +7 -7
  28. package/dist/assets/{main-CH3EqGJI.js → main-RrPyfmCA.js} +2 -2
  29. package/dist/assets/{markdownCore-DJU4KvHP.js → markdownCore-BxXmpZtB.js} +1 -1
  30. package/dist/assets/{miniChat-Ca3TpaaA.js → miniChat-DRNgmC-q.js} +2 -2
  31. package/dist/assets/{mobile-lj4gpGsO.js → mobile-CdmgVKW4.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-B80Jqq8b.js +2 -0
  33. package/dist/assets/renderMobileApp-CLcBvRiy.js +11 -0
  34. package/dist/assets/runtimeEndpointReset-DHHCemOu.js +53 -0
  35. package/dist/assets/{runtimeSurface-CE_VNjdH.js → runtimeSurface-C9kx2zfD.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-BvFAP9zG.js → useAppFontEffects-Dp6vM-Zr.js} +104 -104
  37. package/dist/assets/{useFilesViewSearch-BD79p3A2.js → useFilesViewSearch-Bc8PTYrg.js} +2 -2
  38. package/dist/assets/{usePushVisibilityBeacon-CWg0j-Wg.js → usePushVisibilityBeacon-DMcKyNtE.js} +1 -1
  39. package/dist/assets/{useSwitcherItems-CazJ6Yox.js → useSwitcherItems-DEvsORZ_.js} +1 -1
  40. package/dist/assets/{vendor-base-ui-CdaWtC7e.js → vendor-base-ui-C60wdVnS.js} +1 -1
  41. package/dist/assets/{vendor-codemirror-language-data-CP3j3-xu.js → vendor-codemirror-language-data-DLimsiRH.js} +2 -2
  42. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-Bkw82kL9.js} +1 -1
  43. package/dist/assets/{vendor-floating-ui-react-dom-BZOGXAGe.js → vendor-floating-ui-react-dom-KLmnYDaG.js} +1 -1
  44. package/dist/assets/{web-components-DWuadqra.js → web-components-05Oa3k7a.js} +3 -3
  45. package/dist/index.html +4 -4
  46. package/dist/mini-chat.html +3 -3
  47. package/dist/mobile.html +3 -3
  48. package/package.json +1 -1
  49. package/server/index.js +17 -3
  50. package/server/lib/client-auth/DOCUMENTATION.md +184 -0
  51. package/server/lib/client-auth/live-revocation.test.js +567 -0
  52. package/server/lib/client-auth/principal-tracker.js +383 -0
  53. package/server/lib/client-auth/principal-tracker.test.js +321 -0
  54. package/server/lib/client-auth/remote-clients.js +31 -0
  55. package/server/lib/client-auth/remote-clients.test.js +44 -0
  56. package/server/lib/pi/event-stream.js +269 -0
  57. package/server/lib/pi/event-stream.test.js +776 -0
  58. package/server/lib/pi/routes.js +88 -31
  59. package/server/lib/pi/routes.test.js +92 -20
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -4
  61. package/server/lib/pi/session-daemon/ipc-client.js +19 -15
  62. package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
  63. package/server/lib/pi/session-daemon/prompt-preflight.test.js +5 -1
  64. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +15 -5
  65. package/server/lib/pi/session-daemon/send-operation-registry.js +26 -23
  66. package/server/lib/pi/session-daemon/send-operation-registry.test.js +26 -20
  67. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  68. package/server/lib/pi/session-daemon/session-daemon.js +79 -18
  69. package/server/lib/pi/session-daemon/session-daemon.test.js +10 -4
  70. package/server/lib/pi/session-daemon/session-replay.test.js +8 -3
  71. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  72. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  73. package/server/lib/pi/ui-settings-store.js +7 -1
  74. package/server/lib/pi/ui-settings-store.test.js +19 -1
  75. package/server/lib/server/core-routes.js +11 -1
  76. package/server/lib/stt/DOCUMENTATION.md +2 -0
  77. package/server/lib/stt/runtime.js +39 -2
  78. package/server/lib/stt/runtime.test.js +53 -0
  79. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  80. package/server/lib/terminal/runtime.js +48 -2
  81. package/server/lib/terminal/runtime.test.js +35 -0
  82. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  83. package/server/lib/ui-auth/ui-auth.js +98 -0
  84. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  85. package/server/lib/workspace/host.js +3 -1
  86. package/dist/assets/FilesView-B_BF39ef.js +0 -6
  87. package/dist/assets/SessionUnreadDot-DGT31A3z.js +0 -1
  88. package/dist/assets/SettingsView-eG-wN-yY.js +0 -2
  89. package/dist/assets/SettingsWindow-Dvnp8YrA.js +0 -1
  90. package/dist/assets/collapsible-BjniCdZ5.js +0 -1
  91. package/dist/assets/index-BpmGBboM.css +0 -1
  92. package/dist/assets/index-DZnzXhTs.js +0 -8
  93. package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +0 -2
  94. package/dist/assets/renderMobileApp-CcWQ1sCf.js +0 -11
  95. package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +0 -53
@@ -94,27 +94,35 @@ export const requestSessionDaemon = ({ endpoint, credential, command, payload, t
94
94
  * Open an authenticated server-only event subscription. The caller owns the
95
95
  * returned close function and must relay only projected frames to browsers.
96
96
  */
97
- export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSequence, onEvent, onError, timeoutMs = 30_000 }) => {
97
+ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSequence, streamEpoch, onEvent, onError, signal, timeoutMs = 30_000 }) => {
98
98
  const decoder = new StringDecoder('utf8');
99
99
  let buffer = '';
100
100
  let authenticated = false;
101
101
  let closed = false;
102
102
  const socket = createConnection({ path: endpoint });
103
- const timer = setTimeout(() => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')), timeoutMs);
104
- const finish = () => {
103
+ let timer;
104
+ function finish() {
105
105
  clearTimeout(timer);
106
- if (!closed) socket.destroy();
107
- };
108
- const fail = (error) => {
106
+ signal?.removeEventListener('abort', abort);
107
+ socket.destroy();
108
+ }
109
+ function fail(error) {
109
110
  if (closed) return;
110
111
  closed = true;
111
- clearTimeout(timer);
112
- socket.destroy();
112
+ finish();
113
113
  onError?.(error);
114
- };
114
+ }
115
+ function abort() {
116
+ if (closed) return;
117
+ closed = true;
118
+ finish();
119
+ }
120
+ timer = setTimeout(() => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')), timeoutMs);
121
+ if (signal?.aborted) abort();
122
+ else signal?.addEventListener('abort', abort, { once: true });
115
123
  socket.once('error', () => fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE')));
116
124
  socket.on('connect', () => {
117
- socket.write(`${JSON.stringify({ kind: 'authenticate', credential, ...(sessionId ? { sessionId } : {}), ...(Number.isSafeInteger(fromSequence) && fromSequence >= 0 ? { fromSequence } : {}) })}\n`);
125
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential, ...(sessionId ? { sessionId } : {}), ...(Number.isSafeInteger(fromSequence) && fromSequence >= 0 ? { fromSequence } : {}), ...(typeof streamEpoch === 'string' && streamEpoch.length > 0 ? { streamEpoch } : {}) })}\n`);
118
126
  });
119
127
  socket.on('data', (chunk) => {
120
128
  buffer += decoder.write(chunk);
@@ -147,9 +155,5 @@ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSe
147
155
  socket.on('close', () => {
148
156
  if (!closed) fail(new SessionDaemonClientError('DAEMON_UNAVAILABLE'));
149
157
  });
150
- return () => {
151
- if (closed) return;
152
- closed = true;
153
- finish();
154
- };
158
+ return abort;
155
159
  };
@@ -5,7 +5,7 @@ import { createHash } from 'node:crypto';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
 
8
- import { requestSessionDaemon } from './ipc-client.js';
8
+ import { requestSessionDaemon, subscribeSessionDaemon } from './ipc-client.js';
9
9
  import { SESSION_DAEMON_MAX_FRAME_BYTES } from './ipc-protocol.js';
10
10
 
11
11
  const credential = 'test-private-credential';
@@ -85,4 +85,116 @@ describe('session daemon IPC client framing', () => {
85
85
  await expect(requestSessionDaemon({ endpoint, credential, command: 'runtime.health' }))
86
86
  .resolves.toEqual({ ok: true });
87
87
  });
88
+
89
+ it('stamps the subscribe authenticate frame with the cursor streamEpoch', async () => {
90
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
91
+ roots.push(root);
92
+ const endpoint = endpointFor(root);
93
+ let seenAuthenticate;
94
+ const peers = new Set();
95
+ const server = createServer((socket) => {
96
+ peers.add(socket);
97
+ socket.on('error', () => {});
98
+ socket.on('close', () => peers.delete(socket));
99
+ let buffer = '';
100
+ socket.on('data', (chunk) => {
101
+ buffer += chunk.toString('utf8');
102
+ while (buffer.includes('\n')) {
103
+ const newline = buffer.indexOf('\n');
104
+ const line = buffer.slice(0, newline);
105
+ buffer = buffer.slice(newline + 1);
106
+ if (!line) continue;
107
+ const frame = JSON.parse(line);
108
+ if (frame.kind === 'authenticate') {
109
+ seenAuthenticate = frame;
110
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'authenticated' })}\n`);
111
+ socket.write(`${JSON.stringify({
112
+ protocolVersion: 1,
113
+ kind: 'event',
114
+ event: 'session.snapshot',
115
+ sequence: 0,
116
+ streamEpoch: 'epoch-abc123',
117
+ })}\n`);
118
+ }
119
+ }
120
+ });
121
+ });
122
+ servers.push(server);
123
+ await new Promise((resolve, reject) => {
124
+ server.once('error', reject);
125
+ server.listen({ path: endpoint }, resolve);
126
+ });
127
+
128
+ const events = [];
129
+ let closeCalled = false;
130
+ const close = subscribeSessionDaemon({
131
+ endpoint,
132
+ credential,
133
+ sessionId: 'pi-session-1',
134
+ fromSequence: 7,
135
+ streamEpoch: 'epoch-abc123',
136
+ onEvent: (event) => events.push(event),
137
+ onError: () => {},
138
+ });
139
+ try {
140
+ for (let attempt = 0; attempt < 50 && events.length === 0; attempt += 1) {
141
+ await new Promise((resolve) => setTimeout(resolve, 20));
142
+ }
143
+ expect(seenAuthenticate).toMatchObject({
144
+ credential,
145
+ sessionId: 'pi-session-1',
146
+ fromSequence: 7,
147
+ streamEpoch: 'epoch-abc123',
148
+ });
149
+ expect(events[0]).toMatchObject({ kind: 'event', streamEpoch: 'epoch-abc123' });
150
+ close();
151
+ closeCalled = true;
152
+ for (let attempt = 0; attempt < 50 && peers.size > 0; attempt += 1) {
153
+ await new Promise((resolve) => setTimeout(resolve, 10));
154
+ }
155
+ expect(peers.size).toBe(0);
156
+ } finally {
157
+ if (!closeCalled) close();
158
+ for (const peer of peers) peer.destroy();
159
+ }
160
+ }, 20_000);
161
+
162
+ it('aborts an opening subscription without reporting a transport error', async () => {
163
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
164
+ roots.push(root);
165
+ const endpoint = endpointFor(root);
166
+ const peers = new Set();
167
+ const server = createServer((socket) => {
168
+ peers.add(socket);
169
+ socket.on('error', () => {});
170
+ socket.on('close', () => peers.delete(socket));
171
+ socket.resume();
172
+ // Deliberately never authenticate. The AbortSignal must close this
173
+ // opening socket instead of waiting for the 30-second setup timeout.
174
+ });
175
+ servers.push(server);
176
+ await new Promise((resolve, reject) => {
177
+ server.once('error', reject);
178
+ server.listen({ path: endpoint }, resolve);
179
+ });
180
+
181
+ const controller = new AbortController();
182
+ const errors = [];
183
+ subscribeSessionDaemon({
184
+ endpoint,
185
+ credential,
186
+ signal: controller.signal,
187
+ onError: (error) => errors.push(error),
188
+ });
189
+ for (let attempt = 0; attempt < 50 && peers.size === 0; attempt += 1) {
190
+ await new Promise((resolve) => setTimeout(resolve, 10));
191
+ }
192
+ expect(peers.size).toBe(1);
193
+ controller.abort();
194
+ for (let attempt = 0; attempt < 50 && peers.size > 0; attempt += 1) {
195
+ await new Promise((resolve) => setTimeout(resolve, 10));
196
+ }
197
+ expect(peers.size).toBe(0);
198
+ expect(errors).toEqual([]);
199
+ });
88
200
  });
@@ -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);