@pi-chamber/web 0.9.5 → 0.9.7

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 (104) hide show
  1. package/dist/assets/DiagramView-BvrCkm_z.js +1 -0
  2. package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
  3. package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
  4. package/dist/assets/FilesView-CNHu4RnC.js +6 -0
  5. package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
  6. package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
  8. package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
  12. package/dist/assets/SettingsView-hyAGp836.js +2 -0
  13. package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
  14. package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
  15. package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
  17. package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
  21. package/dist/assets/index-BXgR2dKM.css +1 -0
  22. package/dist/assets/index-BZpvAhrX.js +8 -0
  23. package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
  26. package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
  27. package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
  28. package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
  29. package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
  30. package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
  31. package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
  32. package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
  33. package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
  34. package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
  36. package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
  38. package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
  39. package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
  40. package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/index.js +17 -3
  46. package/server/lib/client-auth/DOCUMENTATION.md +184 -0
  47. package/server/lib/client-auth/live-revocation.test.js +567 -0
  48. package/server/lib/client-auth/principal-tracker.js +383 -0
  49. package/server/lib/client-auth/principal-tracker.test.js +321 -0
  50. package/server/lib/client-auth/remote-clients.js +31 -0
  51. package/server/lib/client-auth/remote-clients.test.js +44 -0
  52. package/server/lib/fs/DOCUMENTATION.md +15 -3
  53. package/server/lib/fs/routes.js +369 -51
  54. package/server/lib/fs/routes.test.js +565 -3
  55. package/server/lib/fs/search.js +74 -29
  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 +132 -28
  59. package/server/lib/pi/routes.test.js +213 -4
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -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-operations.test.js +9 -3
  64. package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
  65. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
  66. package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
  67. package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
  68. package/server/lib/pi/session-daemon/session-daemon-epoch.test.js +349 -0
  69. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
  70. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
  71. package/server/lib/pi/session-daemon/session-daemon.js +339 -37
  72. package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
  73. package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
  74. package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
  75. package/server/lib/pi/session-daemon/supervisor.js +30 -5
  76. package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
  77. package/server/lib/pi/ui-settings-store.js +1 -1
  78. package/server/lib/pi/ui-settings-store.test.js +3 -1
  79. package/server/lib/server/core-routes.js +11 -1
  80. package/server/lib/server/cors.js +6 -0
  81. package/server/lib/server/cors.test.js +3 -0
  82. package/server/lib/stt/DOCUMENTATION.md +2 -0
  83. package/server/lib/stt/runtime.js +39 -2
  84. package/server/lib/stt/runtime.test.js +53 -0
  85. package/server/lib/terminal/DOCUMENTATION.md +2 -0
  86. package/server/lib/terminal/runtime.js +48 -2
  87. package/server/lib/terminal/runtime.test.js +35 -0
  88. package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
  89. package/server/lib/ui-auth/ui-auth.js +98 -0
  90. package/server/lib/ui-auth/ui-auth.test.js +249 -0
  91. package/server/lib/workspace/host.js +9 -3
  92. package/server/lib/workspace/host.test.js +15 -0
  93. package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
  94. package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
  95. package/dist/assets/FilesView-CJytSUAX.js +0 -6
  96. package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
  97. package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
  98. package/dist/assets/index-DIF8b4bh.css +0 -1
  99. package/dist/assets/index-jrfQYSvP.js +0 -8
  100. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
  101. package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
  102. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
  103. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
  104. package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
@@ -0,0 +1,331 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { createConnection } from 'node:net';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { StringDecoder } from 'node:string_decoder';
7
+
8
+ import { createSessionDaemon as createSessionDaemonImpl } from './session-daemon.js';
9
+
10
+ const credential = 'a-private-daemon-credential';
11
+
12
+ function createSessionDaemon(options) {
13
+ return createSessionDaemonImpl({ ...options, agentDir: options.agentDir ?? options.cwd });
14
+ }
15
+
16
+ function testDaemonEndpoint(root) {
17
+ if (process.platform === 'win32') return `\\\\.\\pipe\\pichamber-send-dedup-${Date.now()}-${Math.random().toString(16).slice(2)}`;
18
+ return join(root, 'daemon.sock');
19
+ }
20
+
21
+ /**
22
+ * Minimal Pi session double: counts actual Pi invocations (`sent`) so the
23
+ * tests prove one intent executes at most once within the bounded retention
24
+ * window (not lifetime: tombstones are capped and restarts lose receipts).
25
+ */
26
+ class FakeSession {
27
+ constructor(sessionId, sessionFile) {
28
+ this.sessionId = sessionId;
29
+ this.sessionFile = sessionFile;
30
+ this.isStreaming = false;
31
+ this.listeners = new Set();
32
+ this.names = [];
33
+ this.entries = [];
34
+ this.sent = [];
35
+ this.aborted = 0;
36
+ this.model = { provider: 'test', id: 'model' };
37
+ this.thinkingLevel = 'low';
38
+ this.activationGate = null;
39
+ this.modelRuntime = {
40
+ getModel: (providerId, modelId) => providerId === 'test' ? { provider: providerId, id: modelId } : undefined,
41
+ getModels: () => [{ provider: 'test', id: 'model', name: 'Test model', contextWindow: 128_000, reasoning: true, thinkingLevelMap: { low: 1, high: null } }],
42
+ };
43
+ this.sessionManager = {
44
+ getSessionFile: () => sessionFile,
45
+ getHeader: () => ({ timestamp: '2026-01-01T00:00:00.000Z' }),
46
+ getEntries: () => this.entries,
47
+ getEntry: (id) => this.entries.find((entry) => entry.id === id),
48
+ getLeafId: () => 'fake-entry',
49
+ getTree: () => [{ entry: { id: 'fake-entry', parentId: undefined, timestamp: '2026-01-01T00:00:00.000Z' }, children: [] }],
50
+ appendSessionInfo: (name) => this.names.push(name),
51
+ getSessionName: () => this.names[this.names.length - 1],
52
+ };
53
+ }
54
+
55
+ subscribe(listener) {
56
+ this.listeners.add(listener);
57
+ return () => this.listeners.delete(listener);
58
+ }
59
+
60
+ async prompt(text, options) {
61
+ options?.preflightResult?.(true);
62
+ const deliverAs = options?.streamingBehavior;
63
+ this.sent.push({ text, options: deliverAs ? { deliverAs } : undefined });
64
+ }
65
+
66
+ async sendUserMessage(text, options) {
67
+ this.sent.push({ text, options });
68
+ }
69
+
70
+ async setModel(model) {
71
+ this.model = { provider: model.providerId ?? model.provider, id: model.modelId ?? model.id };
72
+ }
73
+
74
+ setThinkingLevel(thinking) { this.thinkingLevel = thinking; }
75
+
76
+ async abort() { this.aborted += 1; this.isStreaming = false; }
77
+
78
+ getSteeringMessages() { return []; }
79
+
80
+ getFollowUpMessages() { return []; }
81
+ }
82
+
83
+ class FakeRuntime {
84
+ constructor({ cwd, session }) {
85
+ this.cwd = cwd;
86
+ this.session = session;
87
+ this.disposed = false;
88
+ }
89
+ async dispose() { this.disposed = true; }
90
+ }
91
+
92
+ function connectClient(endpoint) {
93
+ const socket = createConnection({ path: endpoint });
94
+ const decoder = new StringDecoder('utf8');
95
+ let buffer = '';
96
+ const waiters = [];
97
+
98
+ const publish = (message) => {
99
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
100
+ const waiter = waiters[index];
101
+ if (waiter.predicate(message)) {
102
+ waiters.splice(index, 1);
103
+ waiter.resolve(message);
104
+ }
105
+ }
106
+ };
107
+
108
+ socket.on('data', (chunk) => {
109
+ buffer += decoder.write(chunk);
110
+ while (true) {
111
+ const newline = buffer.indexOf('\n');
112
+ if (newline === -1) break;
113
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
114
+ buffer = buffer.slice(newline + 1);
115
+ if (line) publish(JSON.parse(line));
116
+ }
117
+ });
118
+ socket.on('close', () => {
119
+ for (const waiter of waiters.splice(0)) waiter.reject(new Error('Daemon connection closed'));
120
+ });
121
+
122
+ const next = (predicate) => new Promise((resolve, reject) => {
123
+ const timer = setTimeout(() => {
124
+ const index = waiters.findIndex((waiter) => waiter.resolve === resolve);
125
+ if (index !== -1) waiters.splice(index, 1);
126
+ reject(new Error('Timed out waiting for daemon message'));
127
+ }, 2_000);
128
+ waiters.push({
129
+ predicate,
130
+ reject,
131
+ resolve: (message) => {
132
+ clearTimeout(timer);
133
+ resolve(message);
134
+ },
135
+ });
136
+ });
137
+
138
+ return {
139
+ async authenticate() {
140
+ await new Promise((resolve, reject) => {
141
+ socket.once('connect', resolve);
142
+ socket.once('error', reject);
143
+ });
144
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential })}\n`);
145
+ await next((message) => message.kind === 'authenticated');
146
+ },
147
+ request(command, payload = {}) {
148
+ const requestId = `request-${Math.random()}`;
149
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId, command, payload })}\n`);
150
+ return new Promise((resolve, reject) => {
151
+ next((message) => {
152
+ if (message.kind === 'error') {
153
+ const code = message.error?.code ?? 'DAEMON_REQUEST_FAILED';
154
+ reject(Object.assign(new Error(code), { code }));
155
+ return true;
156
+ }
157
+ return message.kind === 'response' && message.requestId === requestId;
158
+ }).then(resolve, reject);
159
+ });
160
+ },
161
+ next,
162
+ async close() {
163
+ if (!socket.destroyed) socket.destroy();
164
+ if (socket.destroyed) return;
165
+ await new Promise((resolve) => socket.once('close', resolve));
166
+ },
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Finding #3 only: stable operation identity, daemon dedup, exact receipt,
172
+ * and payload mismatch. No stream-epoch guard and no per-session
173
+ * send/config lock belong in this split.
174
+ */
175
+ describe('send dedup (finding #3)', () => {
176
+ const roots = [];
177
+ const daemons = [];
178
+ let client;
179
+ let currentEndpoint;
180
+
181
+ // The daemon destroys a request connection on a rejected command, so each
182
+ // send uses its own short-lived authenticated connection.
183
+ const send = async (command, payload) => {
184
+ const connection = connectClient(currentEndpoint);
185
+ await connection.authenticate();
186
+ try {
187
+ return await connection.request(command, payload);
188
+ } finally {
189
+ await connection.close().catch(() => {});
190
+ }
191
+ };
192
+
193
+ afterEach(async () => {
194
+ client = undefined;
195
+ await Promise.all(daemons.splice(0).map((daemon) => daemon.stop().catch(() => {})));
196
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
197
+ });
198
+
199
+ const startDaemonWithSession = async ({ ttlMs, openSession = true } = {}) => {
200
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-send-dedup-'));
201
+ roots.push(root);
202
+ const endpoint = testDaemonEndpoint(root);
203
+ const sessionFile = join(root, 'session-1.jsonl');
204
+ await writeFile(sessionFile, `{"type":"session","id":"session-1","cwd":"${root}"}\n`);
205
+ const session = new FakeSession('session-1', sessionFile);
206
+ const daemon = createSessionDaemon({
207
+ endpoint,
208
+ credential,
209
+ cwd: root,
210
+ ...(ttlMs !== undefined ? { sendOperationTtlMs: ttlMs } : {}),
211
+ createRuntime: async () => {
212
+ if (session.activationGate) await session.activationGate.released;
213
+ return new FakeRuntime({ cwd: root, session });
214
+ },
215
+ listSessions: async () => [
216
+ { path: sessionFile, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
217
+ ],
218
+ });
219
+ daemons.push(daemon);
220
+ await daemon.start();
221
+ currentEndpoint = endpoint;
222
+ client = connectClient(endpoint);
223
+ await client.authenticate();
224
+ if (openSession) await client.request('sessions.open', { sessionId: 'session-1' });
225
+ return { session, endpoint, root, sessionFile };
226
+ };
227
+
228
+ it.each([
229
+ ['sessions.prompt', 'prompt'],
230
+ ['sessions.steer', 'steer'],
231
+ ['sessions.followUp', 'followUp'],
232
+ ])('a lost-ack retry of the same operation id executes %s once and returns the original receipt', async (command) => {
233
+ const { session } = await startDaemonWithSession();
234
+ const payload = { sessionId: 'session-1', text: 'one intent', operationId: 'op-lost-ack' };
235
+
236
+ const first = await send(command, payload);
237
+ expect(first.result).toMatchObject({ accepted: true, messageId: 'fake-entry' });
238
+ expect(first.result.deduplicated).toBeUndefined();
239
+ expect(session.sent).toHaveLength(1);
240
+
241
+ const retry = await send(command, payload);
242
+ expect(retry.result).toMatchObject({ accepted: true, messageId: 'fake-entry', deduplicated: true });
243
+ expect(session.sent).toHaveLength(1);
244
+ });
245
+
246
+ it('rejects the same operation id with a different payload without invoking Pi', async () => {
247
+ const { session } = await startDaemonWithSession();
248
+ await expect(send('sessions.prompt', { sessionId: 'session-1', text: 'original', operationId: 'op-mismatch' }))
249
+ .resolves.toMatchObject({ result: { accepted: true } });
250
+ expect(session.sent).toHaveLength(1);
251
+
252
+ await expect(send('sessions.prompt', { sessionId: 'session-1', text: 'different', operationId: 'op-mismatch' }))
253
+ .rejects.toMatchObject({ code: 'OPERATION_PAYLOAD_MISMATCH' });
254
+ await expect(send('sessions.prompt', {
255
+ sessionId: 'session-1',
256
+ text: 'original',
257
+ operationId: 'op-mismatch',
258
+ model: { providerId: 'test', modelId: 'other-model' },
259
+ })).rejects.toMatchObject({ code: 'OPERATION_PAYLOAD_MISMATCH' });
260
+ expect(session.sent).toHaveLength(1);
261
+
262
+ await expect(send('sessions.prompt', { sessionId: 'session-1', text: 'original', operationId: 'op-other' }))
263
+ .resolves.toMatchObject({ result: { accepted: true } });
264
+ expect(session.sent).toHaveLength(2);
265
+ });
266
+
267
+ it('treats a daemon restart as the explicit crash window: a replayed id re-executes on the new daemon', async () => {
268
+ const first = await startDaemonWithSession();
269
+ const { sessionFile, root } = first;
270
+ const payload = { sessionId: 'session-1', text: 'across restart', operationId: 'op-restart' };
271
+ await expect(send('sessions.prompt', payload)).resolves.toMatchObject({ result: { accepted: true } });
272
+ expect(first.session.sent).toHaveLength(1);
273
+ await client.close();
274
+
275
+ await daemons.pop().stop();
276
+ const endpoint = testDaemonEndpoint(root);
277
+ currentEndpoint = endpoint;
278
+ const session = new FakeSession('session-1', sessionFile);
279
+ const daemon = createSessionDaemon({
280
+ endpoint,
281
+ credential,
282
+ cwd: root,
283
+ createRuntime: async () => new FakeRuntime({ cwd: root, session }),
284
+ listSessions: async () => [
285
+ { path: sessionFile, id: 'session-1', cwd: root, created: new Date(), modified: new Date(), messageCount: 0 },
286
+ ],
287
+ });
288
+ daemons.push(daemon);
289
+ await daemon.start();
290
+ client = connectClient(endpoint);
291
+ await client.authenticate();
292
+
293
+ await expect(send('sessions.prompt', payload)).resolves.toMatchObject({ result: { accepted: true } });
294
+ expect(session.sent).toHaveLength(1);
295
+ });
296
+
297
+ it('sessions.sendReceipt tracks pending then accepted then expired with no false guarantee', async () => {
298
+ const { session } = await startDaemonWithSession({ ttlMs: 30, openSession: false });
299
+ const gate = {};
300
+ gate.released = new Promise((resolve) => { gate.release = resolve; });
301
+ session.activationGate = gate;
302
+ const lookup = { kind: 'prompt', sessionId: 'session-1', operationId: 'op-receipt-lifecycle' };
303
+ const payload = { sessionId: 'session-1', text: 'lifecycle', operationId: 'op-receipt-lifecycle' };
304
+
305
+ const pendingSend = send('sessions.prompt', payload);
306
+ await new Promise((resolve) => setTimeout(resolve, 25));
307
+ await expect(send('sessions.sendReceipt', lookup)).resolves.toMatchObject({ result: { status: 'pending' } });
308
+ expect(session.sent).toHaveLength(0);
309
+
310
+ gate.release();
311
+ await expect(pendingSend).resolves.toMatchObject({ result: { accepted: true } });
312
+ expect(session.sent).toHaveLength(1);
313
+ await expect(send('sessions.sendReceipt', lookup))
314
+ .resolves.toMatchObject({ result: { status: 'accepted', receipt: { accepted: true } } });
315
+
316
+ await new Promise((resolve) => setTimeout(resolve, 60));
317
+ const expired = await send('sessions.sendReceipt', lookup);
318
+ expect(expired.result.status).toBe('expired');
319
+ expect(expired.result.receipt).toBeUndefined();
320
+
321
+ await expect(send('sessions.prompt', payload)).rejects.toMatchObject({ code: 'OPERATION_EXPIRED' });
322
+ expect(session.sent).toHaveLength(1);
323
+ const retryPayload = { ...payload, operationId: 'op-receipt-lifecycle-2' };
324
+ const retry = await send('sessions.prompt', retryPayload);
325
+ expect(retry.result).toMatchObject({ accepted: true });
326
+ expect(retry.result.deduplicated).toBeUndefined();
327
+ expect(session.sent).toHaveLength(2);
328
+ await expect(send('sessions.sendReceipt', { ...lookup, operationId: 'op-receipt-lifecycle-2' }))
329
+ .resolves.toMatchObject({ result: { status: 'accepted' } });
330
+ });
331
+ });
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Send-intent deduplication registry.
3
+ *
4
+ * Owns the authoritative execution boundary for prompt/steer/followUp sends
5
+ * (finding #3). A client labels every send intent with a stable
6
+ * `operationId`; the daemon claims the id here BEFORE activating Pi or
7
+ * consuming anything. The registry guarantees:
8
+ *
9
+ * - One intent executes at most once within the bounded retention window
10
+ * (`ttlMs` and `maxEntries`; tombstones are FIFO-capped at `maxEntries`
11
+ * so `expired` can degrade to `unknown` under pressure, and a restart
12
+ * loses all receipts). There is no lifetime at-most-once guarantee: after
13
+ * expiry/eviction pressure or a restart the same id may report `expired`
14
+ * or `unknown` and the caller must use a new operation id. A retry of
15
+ * the same intent inside the window (transport retry, manual
16
+ * confirmation, queue backoff) returns the original acceptance receipt
17
+ * instead of invoking Pi again.
18
+ * - Concurrent duplicates of a still-pending intent share the original
19
+ * outcome: they await the first execution's settlement instead of racing it.
20
+ * Pending claims are never evicted while their owner is still active:
21
+ * expiring a still-executing claim would let a duplicate re-execute the
22
+ * same operation, so pending entries stay until their owner settles and
23
+ * duplicates always share (never re-execute a pending-expired operation).
24
+ * - The same id with a different payload (text, model, thinking, message id,
25
+ * or attachments) is rejected as `OPERATION_PAYLOAD_MISMATCH` — a
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.
34
+ *
35
+ * Retention is bounded and explicit: accepted receipts are kept for `ttlMs`
36
+ * and at most `maxEntries` accepted receipts are retained (oldest evicted).
37
+ * Evicted or TTL-expired acceptances leave a bounded `expired` tombstone
38
+ * (capped at `maxEntries`) so `query()` can distinguish `expired` — "was
39
+ * seen but retention is gone, outcome unknown, never assume success" —
40
+ * from `unknown` — "never seen in this retention window (including tombstone
41
+ * pressure and post-restart)". A later retry
42
+ * with the same id after expiry is rejected as `expired` (OPERATION_EXPIRED),
43
+ * never an automatic re-execution: callers must treat the retention window
44
+ * as the only safe retry window and use a new operation id afterwards.
45
+ * Pending claims are bounded separately by `maxPending` entries: an unsettled
46
+ * pending entry is never evicted (its duplicates share the outcome), and a
47
+ * new distinct pending claim past the bound is rejected as `overloaded`
48
+ * (SESSION_BUSY, retry with backoff) so the map cannot grow without bound
49
+ * while active ownership is preserved. `pendingTtlMs` is retained as a
50
+ * constructor-validated bound for future waiter timeouts, but pending entries
51
+ * are not auto-expired: a leaked claim occupies one of `maxPending` slots
52
+ * until restart instead of risking a duplicate execution. The registry is
53
+ * 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
58
+ * gone: a retry with the same id is rejected as expired, never a silent
59
+ * deduplicated success nor an automatic re-execution — callers must treat
60
+ * the retention window as the only safe retry window and use a new
61
+ * operation id afterwards.
62
+ *
63
+ * Only acceptances are retained. Request-path rejections happen before Pi is
64
+ * invoked, so nothing executed and a later retry with the same id is safe;
65
+ * pending duplicates still share the original rejection so a concurrent
66
+ * duplicate never proceeds on its own. Every claim — including
67
+ * pending-overload (SESSION_BUSY) and validation rejections — must
68
+ * settle its entry; an unsettled pending entry is a hang, not a queue.
69
+ */
70
+
71
+ const SEND_OPERATION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
72
+
73
+ export const isValidSendOperationId = (value) => (
74
+ typeof value === 'string' && SEND_OPERATION_ID_PATTERN.test(value)
75
+ );
76
+
77
+ /** Deterministic stringify so payload fingerprints are order-independent. */
78
+ export const stableFingerprint = (value) => {
79
+ if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);
80
+ if (Array.isArray(value)) return `[${value.map(stableFingerprint).join(',')}]`;
81
+ const keys = Object.keys(value).filter((key) => value[key] !== undefined).sort();
82
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableFingerprint(value[key])}`).join(',')}}`;
83
+ };
84
+
85
+ const entryKey = ({ kind, sessionId, operationId }) => `${kind}\u0000${sessionId}\u0000${operationId}`;
86
+
87
+ export const createSendOperationRegistry = ({
88
+ now = () => Date.now(),
89
+ ttlMs = 10 * 60 * 1_000,
90
+ maxEntries = 1_024,
91
+ maxPending = 256,
92
+ pendingTtlMs = 30_000,
93
+ } = {}) => {
94
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error('send operation ttlMs must be positive');
95
+ if (!Number.isFinite(maxEntries) || maxEntries <= 0) throw new Error('send operation maxEntries must be positive');
96
+ if (!Number.isFinite(maxPending) || maxPending <= 0) throw new Error('send operation maxPending must be positive');
97
+ if (!Number.isFinite(pendingTtlMs) || pendingTtlMs <= 0) throw new Error('send operation pendingTtlMs must be positive');
98
+
99
+ const entries = new Map();
100
+ // Bounded tombstones for ids whose acceptance is gone (TTL expiry or
101
+ // oldest-evicted). Lets `query()` report `expired` instead of falsely
102
+ // implying `unknown`/safe-to-retry or `accepted`. Rejections before Pi ran
103
+ // leave no tombstone: nothing executed, so the id is `unknown`/reusable.
104
+ // A fresh claim clears its tombstone; tombstones are FIFO-capped at
105
+ // `maxEntries` so `expired` degrades to `unknown` under pressure — both
106
+ // mean "no guarantee, outcome unknown", never a false acceptance.
107
+ const expiredKeys = new Map();
108
+ const rememberExpired = (key) => {
109
+ expiredKeys.delete(key);
110
+ expiredKeys.set(key, now());
111
+ while (expiredKeys.size > maxEntries) {
112
+ const oldest = expiredKeys.keys().next();
113
+ if (oldest.done) break;
114
+ expiredKeys.delete(oldest.value);
115
+ }
116
+ };
117
+
118
+ const countPending = () => {
119
+ let count = 0;
120
+ for (const entry of entries.values()) if (entry.state === 'pending') count += 1;
121
+ return count;
122
+ };
123
+
124
+ // Expired accepted receipts become `expired` tombstones. Pending claims
125
+ // are never auto-expired: evicting a still-executing claim would let a
126
+ // duplicate re-execute the same operation, and rejecting its waiters as
127
+ // SESSION_BUSY would falsely imply nothing executed. Pending entries stay
128
+ // until their owner settles; `maxPending` bounds the map instead.
129
+ const evictExpired = () => {
130
+ const timestamp = now();
131
+ for (const [key, entry] of entries) {
132
+ if (entry.state === 'accepted' && timestamp >= entry.expiresAt) {
133
+ entries.delete(key);
134
+ rememberExpired(key);
135
+ }
136
+ }
137
+ };
138
+ const trimToBound = () => {
139
+ // The bound applies to retained receipts; pending claims are transient and
140
+ // must never evict an accepted receipt (their duplicates share the outcome).
141
+ while (entries.size > maxEntries) {
142
+ let accepted = 0;
143
+ let oldestAccepted;
144
+ for (const [key, entry] of entries) {
145
+ if (entry.state === 'accepted') {
146
+ accepted += 1;
147
+ if (!oldestAccepted) oldestAccepted = key;
148
+ }
149
+ }
150
+ if (accepted <= maxEntries) break;
151
+ entries.delete(oldestAccepted);
152
+ rememberExpired(oldestAccepted);
153
+ }
154
+ };
155
+
156
+ const claim = ({ kind, sessionId, operationId, fingerprint }) => {
157
+ const key = entryKey({ kind, sessionId, operationId });
158
+ evictExpired();
159
+ const existing = entries.get(key);
160
+ if (existing) {
161
+ if (existing.fingerprint !== fingerprint) return { outcome: 'mismatch' };
162
+ if (existing.state === 'accepted') {
163
+ return { outcome: 'accepted', receipt: existing.receipt, deduplicated: true };
164
+ }
165
+ // Still pending: the duplicate shares the original outcome, even past
166
+ // `pendingTtlMs`. Expiring here would let a still-executing operation
167
+ // duplicate, so pending never becomes `expired` while active.
168
+ return { outcome: 'pending', settled: existing.settled };
169
+ }
170
+ // After retention the same id must not automatically re-execute: the
171
+ // tombstone blocks reuse and the caller must use a new operation id.
172
+ if (expiredKeys.has(key)) return { outcome: 'expired' };
173
+ if (countPending() >= maxPending) return { outcome: 'overloaded' };
174
+ let settleWaiters;
175
+ let rejectWaiters;
176
+ const settled = new Promise((resolve, reject) => {
177
+ settleWaiters = resolve;
178
+ rejectWaiters = reject;
179
+ });
180
+ // A claim whose id is rejected usually has no duplicate awaiting it; mark
181
+ // the shared promise handled so the rejection reaches only real waiters.
182
+ settled.then(undefined, () => {});
183
+ const entry = {
184
+ state: 'pending',
185
+ fingerprint,
186
+ settled,
187
+ rejectWaiters,
188
+ pendingExpiresAt: now() + pendingTtlMs,
189
+ settle: (result) => {
190
+ if (entry.state !== 'pending') return;
191
+ if (result.accepted) {
192
+ entry.state = 'accepted';
193
+ entry.receipt = result.receipt;
194
+ entry.expiresAt = now() + ttlMs;
195
+ delete entry.pendingExpiresAt;
196
+ trimToBound();
197
+ settleWaiters(result);
198
+ return;
199
+ }
200
+ // A rejection happened before Pi ran: nothing executed, so forget
201
+ // the claim and let a later retry of the same id proceed.
202
+ entries.delete(key);
203
+ rejectWaiters(result.error);
204
+ },
205
+ };
206
+ entries.set(key, entry);
207
+ expiredKeys.delete(key);
208
+ trimToBound();
209
+ return { outcome: 'new', entry };
210
+ };
211
+
212
+ const getReceipt = ({ kind, sessionId, operationId }) => {
213
+ evictExpired();
214
+ if (typeof kind === 'string' && kind.length > 0) {
215
+ const entry = entries.get(entryKey({ kind, sessionId, operationId }));
216
+ if (entry?.state === 'accepted') return { receipt: entry.receipt, fingerprint: entry.fingerprint };
217
+ return undefined;
218
+ }
219
+ for (const [key, entry] of entries) {
220
+ 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
+ return { receipt: entry.receipt, fingerprint: entry.fingerprint, kind: key.slice(0, key.indexOf('\u0000')) };
225
+ }
226
+ }
227
+ return undefined;
228
+ };
229
+
230
+ // Exact-identity receipt lookup for `sessions.sendReceipt`: requires the
231
+ // full `kind + sessionId + operationId` key. Returns one of
232
+ // `accepted` (retained receipt), `pending` (still-accepting claim),
233
+ // `expired` (seen but retention gone — outcome unknown, never assume
234
+ // success), or `unknown` (never seen in this retention window, evicted
235
+ // tombstone pressure, post-restart, or rejected before Pi ran so nothing
236
+ // executed). Never returns a receipt after expiry.
237
+ const query = ({ kind, sessionId, operationId }) => {
238
+ evictExpired();
239
+ if (typeof kind !== 'string' || kind.length === 0
240
+ || typeof sessionId !== 'string' || sessionId.length === 0
241
+ || typeof operationId !== 'string' || operationId.length === 0) {
242
+ return { status: 'unknown' };
243
+ }
244
+ const key = entryKey({ kind, sessionId, operationId });
245
+ const entry = entries.get(key);
246
+ if (entry?.state === 'accepted') {
247
+ return { status: 'accepted', receipt: entry.receipt, fingerprint: entry.fingerprint };
248
+ }
249
+ if (entry?.state === 'pending') {
250
+ return { status: 'pending', fingerprint: entry.fingerprint };
251
+ }
252
+ if (expiredKeys.has(key)) return { status: 'expired' };
253
+ return { status: 'unknown' };
254
+ };
255
+
256
+ return {
257
+ claim,
258
+ getReceipt,
259
+ query,
260
+ get size() { return entries.size; },
261
+ get pendingSize() { return countPending(); },
262
+ get expiredSize() { return expiredKeys.size; },
263
+ };
264
+ };