@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
@@ -20,6 +20,12 @@ import {
20
20
  } from './extension-protocol.js';
21
21
  import { createPiUiSettingsStore } from './ui-settings-store.js';
22
22
  import { createPiSnippetsStore } from './snippets-store.js';
23
+ import { isValidSendOperationId } from './session-daemon/send-operation-registry.js';
24
+ import {
25
+ DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
26
+ createPiEventStreamRegistry,
27
+ openPiEventStream,
28
+ } from './event-stream.js';
23
29
 
24
30
  const UNAVAILABLE_CODES = new Set([
25
31
  'DAEMON_UNAVAILABLE',
@@ -58,9 +64,11 @@ const writeDaemonError = (res, error) => {
58
64
  ? 502
59
65
  : code === 'INVALID_SESSION'
60
66
  ? 404
61
- : code === 'SESSION_IN_USE'
67
+ : code === 'SESSION_IN_USE' || code === 'OPERATION_PAYLOAD_MISMATCH'
62
68
  ? 409
63
- : code === 'ATTACHMENT_TOO_LARGE'
69
+ : code === 'OPERATION_EXPIRED'
70
+ ? 410
71
+ : code === 'ATTACHMENT_TOO_LARGE'
64
72
  ? 413
65
73
  : code === 'ATTACHMENT_LIMIT_REACHED'
66
74
  ? 429
@@ -290,6 +298,9 @@ const projectSessionDetail = (value) => {
290
298
  ...(compaction ? { compaction } : {}),
291
299
  ...(Number.isFinite(value.runStartedAt) ? { runStartedAt: Math.floor(value.runStartedAt) } : {}),
292
300
  ...(Number.isFinite(value.serverNow) ? { serverNow: Math.floor(value.serverNow) } : {}),
301
+ ...(typeof value.streamEpoch === 'string' && value.streamEpoch.length > 0 && value.streamEpoch.length <= 128
302
+ ? { streamEpoch: value.streamEpoch }
303
+ : {}),
293
304
  ...projectExtensionSnapshotState(value),
294
305
  };
295
306
  };
@@ -539,7 +550,13 @@ export const projectEventFrame = (frame) => {
539
550
  if (!frame || frame.kind !== 'event' || typeof frame.event !== 'string' || !Number.isSafeInteger(frame.sequence)
540
551
  || !frame.payload || typeof frame.payload.sessionId !== 'string' || typeof frame.payload.directory !== 'string') return null;
541
552
  const { sessionId, directory } = frame.payload;
542
- const common = { protocolVersion: 1, kind: 'event', name: frame.event, sequence: frame.sequence, sessionId, directory };
553
+ // The daemon's opaque stream-lifetime id. Passed through verbatim so clients
554
+ // can detect a daemon restart (sequence space reset) and reject stale-epoch
555
+ // events; old daemons omit it and the field stays undefined.
556
+ const streamEpoch = typeof frame.streamEpoch === 'string' && frame.streamEpoch.length > 0 && frame.streamEpoch.length <= 128
557
+ ? frame.streamEpoch
558
+ : undefined;
559
+ const common = { protocolVersion: 1, kind: 'event', name: frame.event, sequence: frame.sequence, sessionId, directory, ...(streamEpoch ? { streamEpoch } : {}) };
543
560
  switch (frame.event) {
544
561
  case 'session.snapshot': {
545
562
  const snapshot = frame.payload;
@@ -560,13 +577,21 @@ export const projectEventFrame = (frame) => {
560
577
  ...(Number.isFinite(snapshot.runStartedAt) ? { runStartedAt: Math.floor(snapshot.runStartedAt) } : {}),
561
578
  ...(Number.isFinite(snapshot.serverNow) ? { serverNow: Math.floor(snapshot.serverNow) } : {}),
562
579
  lastSequence: Number.isSafeInteger(snapshot.lastSequence) ? snapshot.lastSequence : frame.sequence,
580
+ ...(snapshot.resync === true ? { resync: true } : {}),
563
581
  ...extensionSnapshot,
564
582
  } } };
565
583
  }
566
584
  case 'session.lifecycle': {
585
+ // Legacy daemons published deletion as `lifecycle idle + deleted:true`.
586
+ // Project it as the explicit typed deletion so old hosts still clean
587
+ // every client. Current daemons publish `session.deleted` directly.
588
+ if (frame.payload && frame.payload.deleted === true) {
589
+ return { ...common, name: 'session.deleted', payload: {} };
590
+ }
567
591
  const retry = frame.payload.state === 'retry' ? projectRetryInfo(frame.payload) : null;
568
592
  return { ...common, payload: { state: frame.payload.state, ...(retry ?? {}), ...(Number.isFinite(frame.payload.runStartedAt) ? { runStartedAt: Math.floor(frame.payload.runStartedAt) } : {}), ...(Number.isFinite(frame.payload.serverNow) ? { serverNow: Math.floor(frame.payload.serverNow) } : {}) } };
569
593
  }
594
+ case 'session.deleted': return { ...common, payload: {} };
570
595
  case 'session.updated': {
571
596
  if (typeof frame.payload.title !== 'string') return null;
572
597
  const title = frame.payload.title.trim();
@@ -801,7 +826,9 @@ export const registerPiRuntimeRoutes = (app, {
801
826
  resolveUpdatePackageManager = resolveTrustedUpdatePackageManager,
802
827
  smallModelGenerator = async (input) => (await import('./small-model-generation.js')).generateWithSmallModel(input),
803
828
  eventHeartbeatMs = 15_000,
829
+ eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
804
830
  }) => {
831
+ const eventStreamRegistry = createPiEventStreamRegistry();
805
832
  app.get('/api/pi/ui-settings', async (_req, res) => {
806
833
  try {
807
834
  res.json(await uiSettingsStore.read());
@@ -902,6 +929,7 @@ export const registerPiRuntimeRoutes = (app, {
902
929
  protocolVersion: health.protocolVersion,
903
930
  state: 'ready',
904
931
  capabilities: Array.isArray(health.capabilities) ? health.capabilities : [],
932
+ ...(typeof health.streamEpoch === 'string' && health.streamEpoch ? { streamEpoch: health.streamEpoch } : {}),
905
933
  });
906
934
  } catch {
907
935
  res.status(503).json({ protocolVersion: 1, state: 'unavailable', error: { code: 'DAEMON_UNAVAILABLE' } });
@@ -1402,7 +1430,7 @@ export const registerPiRuntimeRoutes = (app, {
1402
1430
  }
1403
1431
  });
1404
1432
 
1405
- app.get('/api/pi/events', async (req, res) => {
1433
+ app.get('/api/pi/events', (req, res) => {
1406
1434
  const sessionId = typeof req.query.sessionId === 'string' && req.query.sessionId.length > 0 ? req.query.sessionId : undefined;
1407
1435
  const directory = typeof req.query.directory === 'string' && req.query.directory.length > 0 ? req.query.directory : undefined;
1408
1436
  const rawCursor = req.query.fromSequence;
@@ -1411,7 +1439,31 @@ export const registerPiRuntimeRoutes = (app, {
1411
1439
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1412
1440
  return;
1413
1441
  }
1414
- let close;
1442
+ // Stream-lifetime identity of the replay cursor (capability negotiation).
1443
+ // Epoch-aware clients stamp their subscribe with the epoch the cursor was
1444
+ // established under; the daemon refuses to replay a cursor from a retired
1445
+ // epoch even when its own sequence numerically overtook it. A marker-less
1446
+ // legacy client without a cursor gets the snapshot baseline (initial
1447
+ // attach with no replay to verify). A legacy client that supplies a
1448
+ // cursor cannot be epoch-verified, so its cursor is rejected fail-visible
1449
+ // instead of claiming a snapshot fallback is safe.
1450
+ const rawStreamEpoch = req.query.streamEpoch;
1451
+ const streamEpoch = typeof rawStreamEpoch === 'string' && rawStreamEpoch.length > 0 && rawStreamEpoch.length <= 128
1452
+ ? rawStreamEpoch
1453
+ : undefined;
1454
+ if (rawStreamEpoch !== undefined && streamEpoch === undefined) {
1455
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1456
+ return;
1457
+ }
1458
+ const rawCapabilities = req.query.capabilities;
1459
+ const capabilities = typeof rawCapabilities === 'string' ? rawCapabilities.split(',').map((s) => s.trim()).filter(Boolean)
1460
+ : Array.isArray(rawCapabilities) ? rawCapabilities.flatMap((v) => String(v).split(',').map((s) => s.trim())).filter(Boolean)
1461
+ : [];
1462
+ const hasEpochCapability = capabilities.includes('events.streamEpoch');
1463
+ if (fromSequence !== undefined && (!hasEpochCapability || streamEpoch === undefined)) {
1464
+ res.status(400).json({ error: { code: 'DAEMON_PROTOCOL_MISMATCH' } });
1465
+ return;
1466
+ }
1415
1467
  try {
1416
1468
  const runtime = getDaemonRuntime(getPiSessionDaemonRuntime);
1417
1469
  if (typeof runtime.subscribe !== 'function') throw protocolMismatch();
@@ -1421,29 +1473,26 @@ export const registerPiRuntimeRoutes = (app, {
1421
1473
  Connection: 'keep-alive',
1422
1474
  });
1423
1475
  res.flushHeaders?.();
1424
- const send = (frame) => {
1425
- const event = projectEventFrame(frame);
1426
- if (event) res.write(`data: ${JSON.stringify(event)}\n\n`);
1427
- };
1428
- close = await runtime.subscribe({ sessionId, directory, fromSequence, onEvent: send, onError: () => res.end() });
1429
- // Named heartbeat events are visible to native EventSource clients.
1430
- // Comment-only SSE heartbeats keep proxies open but are hidden from the
1431
- // EventSource API, so WKWebView cannot use them to detect a silent link.
1432
- // Send one immediately so an empty replay still proves the connection is
1433
- // healthy before the client resets its reconnect backoff.
1434
- const sendHeartbeat = () => res.write('event: heartbeat\ndata: {}\n\n');
1435
- sendHeartbeat();
1436
- const heartbeat = setInterval(sendHeartbeat, eventHeartbeatMs);
1437
- const cleanup = () => {
1438
- clearInterval(heartbeat);
1439
- close?.();
1440
- };
1441
- req.once('close', cleanup);
1442
- res.once('close', cleanup);
1476
+ // event-stream.js owns the connection lifecycle: cleanup installed before
1477
+ // subscribe opens, idempotent close on disconnect/error/shutdown, bounded
1478
+ // socket buffering with a recoverable disconnect, and heartbeat
1479
+ // suppression on dead responses.
1480
+ openPiEventStream({
1481
+ req,
1482
+ res,
1483
+ subscribe: (handlers) => runtime.subscribe({ sessionId, directory, fromSequence, streamEpoch, ...handlers }),
1484
+ projectFrame: projectEventFrame,
1485
+ heartbeatMs: eventHeartbeatMs,
1486
+ maxBufferedBytes: eventStreamMaxBufferedBytes,
1487
+ registry: eventStreamRegistry,
1488
+ respondWithError: (error) => {
1489
+ if (!res.headersSent) writeDaemonError(res, error);
1490
+ else if (!res.writableEnded && !res.destroyed) res.end();
1491
+ },
1492
+ });
1443
1493
  } catch (error) {
1444
1494
  if (!res.headersSent) writeDaemonError(res, error);
1445
- else res.end();
1446
- close?.();
1495
+ else if (!res.writableEnded && !res.destroyed) res.end();
1447
1496
  }
1448
1497
  });
1449
1498
 
@@ -1460,6 +1509,7 @@ export const registerPiRuntimeRoutes = (app, {
1460
1509
  });
1461
1510
  const archived = await archiveStore.read();
1462
1511
  res.json({
1512
+ ...(typeof result?.streamEpoch === 'string' && result.streamEpoch ? { streamEpoch: result.streamEpoch } : {}),
1463
1513
  sessions: projectSessionList(result?.sessions).map((item) => archived[item.session.id]
1464
1514
  ? { ...item, session: { ...item.session, archived: true, timeArchived: archived[item.session.id] } }
1465
1515
  : item),
@@ -1645,11 +1695,22 @@ export const registerPiRuntimeRoutes = (app, {
1645
1695
  for (const [suffix, command] of [['prompt', 'sessions.prompt'], ['steer', 'sessions.steer'], ['follow-up', 'sessions.followUp']]) {
1646
1696
  app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
1647
1697
  let payload = req.body && typeof req.body === 'object' ? req.body : {};
1698
+ if (payload.operationId !== undefined && !isValidSendOperationId(payload.operationId)) {
1699
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1700
+ return;
1701
+ }
1702
+ if (payload.messageId !== undefined && (typeof payload.messageId !== 'string' || payload.messageId.length === 0 || payload.messageId.length > 512)) {
1703
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1704
+ return;
1705
+ }
1648
1706
  let attachmentIds = [];
1649
1707
  try {
1650
1708
  if (payload.attachments !== undefined) {
1651
1709
  if (!Array.isArray(payload.attachments) || payload.attachments.some((attachment) => !attachment || typeof attachment.id !== 'string')) throw protocolMismatch();
1652
1710
  attachmentIds = payload.attachments.map((attachment) => attachment.id);
1711
+ // Resolve happens before the daemon call; consume below is
1712
+ // idempotent (retired entries resolve), so a deduplicated replay
1713
+ // of an already-consumed attachment still returns the receipt.
1653
1714
  const attachments = await attachmentStore.resolve(attachmentIds);
1654
1715
  payload = { ...payload, attachments };
1655
1716
  }
@@ -1664,11 +1725,50 @@ export const registerPiRuntimeRoutes = (app, {
1664
1725
  return;
1665
1726
  }
1666
1727
  await attachmentStore.consume?.(attachmentIds);
1667
- res.status(202).json({ accepted: true, messageId: result.messageId });
1728
+ res.status(202).json({
1729
+ accepted: true,
1730
+ messageId: result.messageId,
1731
+ ...(result.deduplicated === true ? { deduplicated: true } : {}),
1732
+ });
1668
1733
  }
1669
1734
  });
1670
1735
  }
1671
1736
 
1737
+ // Exact read-only receipt lookup for an uncertain send. The client passes
1738
+ // the full `kind + sessionId + operationId` identity; the daemon never
1739
+ // invokes Pi and never mutates the registry except bounded expiry
1740
+ // eviction. No epoch is required in this split (see stream-epoch branch).
1741
+ app.post('/api/pi/sessions/:sessionId/send-receipt', async (req, res) => {
1742
+ const sessionId = sessionIdFrom(req);
1743
+ if (!sessionId) {
1744
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1745
+ return;
1746
+ }
1747
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
1748
+ const kind = body.kind;
1749
+ const operationId = body.operationId;
1750
+ if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp') || !isValidSendOperationId(operationId)) {
1751
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1752
+ return;
1753
+ }
1754
+ try {
1755
+ const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request('sessions.sendReceipt', {
1756
+ kind,
1757
+ sessionId,
1758
+ operationId,
1759
+ });
1760
+ if (!result || typeof result !== 'object' || !['accepted', 'pending', 'expired', 'unknown'].includes(result.status)) {
1761
+ throw protocolMismatch();
1762
+ }
1763
+ res.json({
1764
+ status: result.status,
1765
+ ...(result.status === 'accepted' && result.receipt && typeof result.receipt === 'object' ? { receipt: result.receipt } : {}),
1766
+ });
1767
+ } catch (error) {
1768
+ writeDaemonError(res, error);
1769
+ }
1770
+ });
1771
+
1672
1772
  for (const [suffix, command] of [['abort', 'sessions.abort'], ['model', 'sessions.setModel'], ['thinking', 'sessions.setThinking']]) {
1673
1773
  app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
1674
1774
  const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, command, req.body && typeof req.body === 'object' ? req.body : {});
@@ -1755,5 +1855,9 @@ export const registerPiRuntimeRoutes = (app, {
1755
1855
  }
1756
1856
  });
1757
1857
 
1758
- return { dispose: () => attachmentStore.dispose?.() };
1858
+ return {
1859
+ dispose: () => attachmentStore.dispose?.(),
1860
+ /** End every live event stream (active or still opening) during shutdown. */
1861
+ closeEventStreams: () => eventStreamRegistry.closeAll(),
1862
+ };
1759
1863
  };
@@ -55,6 +55,26 @@ describe('Pi runtime route', () => {
55
55
  });
56
56
  });
57
57
 
58
+ it('projects explicit and legacy deletion frames as session.deleted', () => {
59
+ const common = {
60
+ protocolVersion: 1,
61
+ kind: 'event',
62
+ sequence: 9,
63
+ payload: { sessionId: 'pi-session-deleted', directory: '/workspace' },
64
+ };
65
+ expect(projectEventFrame({ ...common, event: 'session.deleted' })).toMatchObject({
66
+ name: 'session.deleted',
67
+ sessionId: 'pi-session-deleted',
68
+ directory: '/workspace',
69
+ payload: {},
70
+ });
71
+ expect(projectEventFrame({
72
+ ...common,
73
+ event: 'session.lifecycle',
74
+ payload: { ...common.payload, state: 'idle', deleted: true },
75
+ })).toMatchObject({ name: 'session.deleted', payload: {} });
76
+ });
77
+
58
78
  afterEach(async () => {
59
79
  await close(server);
60
80
  server = undefined;
@@ -438,6 +458,171 @@ describe('Pi runtime route', () => {
438
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' }] } }]);
439
459
  });
440
460
 
461
+ it('forwards the send operation id and reports a deduplicated receipt with consumed attachments', async () => {
462
+ const calls = [];
463
+ const consumed = [];
464
+ const attachmentStore = {
465
+ resolve: async (ids) => ids.map((id) => ({ id, name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' })),
466
+ consume: async (ids) => consumed.push(...ids),
467
+ };
468
+ const runtime = {
469
+ request: async (command, payload) => {
470
+ calls.push({ command, payload });
471
+ // The daemon deduplicates: the second identical send returns the
472
+ // original receipt with deduplicated: true and never executes.
473
+ return { accepted: true, messageId: 'message-1', ...(calls.length > 1 ? { deduplicated: true } : {}) };
474
+ },
475
+ };
476
+ const app = express();
477
+ app.use(express.json());
478
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, attachmentStore });
479
+ server = await listen(app);
480
+ const base = `http://127.0.0.1:${server.address().port}/api/pi`;
481
+
482
+ const send = () => fetch(`${base}/sessions/session-1/prompt`, {
483
+ method: 'POST',
484
+ headers: { 'Content-Type': 'application/json' },
485
+ body: JSON.stringify({ text: 'one intent', operationId: 'op-1', attachments: [{ id: 'attachment-1' }] }),
486
+ });
487
+ const first = await send();
488
+ expect(first.status).toBe(202);
489
+ await expect(first.json()).resolves.toEqual({ accepted: true, messageId: 'message-1' });
490
+ const duplicate = await send();
491
+ expect(duplicate.status).toBe(202);
492
+ await expect(duplicate.json()).resolves.toEqual({ accepted: true, messageId: 'message-1', deduplicated: true });
493
+ // Attachments resolve on both sends (retired entries resolve) and
494
+ // consumption stays idempotent.
495
+ expect(consumed).toEqual(['attachment-1', 'attachment-1']);
496
+ expect(calls).toHaveLength(2);
497
+ expect(calls[1].payload.operationId).toBe('op-1');
498
+ });
499
+
500
+ it('rejects invalid send ids and maps payload mismatch (409) and expiry (410)', async () => {
501
+ const runtime = {
502
+ request: async (_command, payload) => {
503
+ if (payload.operationId === 'op-mismatch') {
504
+ const error = new Error('mismatch');
505
+ error.code = 'OPERATION_PAYLOAD_MISMATCH';
506
+ throw error;
507
+ }
508
+ if (payload.operationId === 'op-expired') {
509
+ const error = new Error('expired');
510
+ error.code = 'OPERATION_EXPIRED';
511
+ throw error;
512
+ }
513
+ return { accepted: true, messageId: 'message-1' };
514
+ },
515
+ };
516
+ const app = express();
517
+ app.use(express.json());
518
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
519
+ server = await listen(app);
520
+ const base = `http://127.0.0.1:${server.address().port}/api/pi`;
521
+
522
+ const invalid = await fetch(`${base}/sessions/session-1/prompt`, {
523
+ method: 'POST',
524
+ headers: { 'Content-Type': 'application/json' },
525
+ body: JSON.stringify({ text: 'hello', operationId: 'bad id with spaces' }),
526
+ });
527
+ expect(invalid.status).toBe(400);
528
+ await expect(invalid.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
529
+
530
+ const invalidMessage = await fetch(`${base}/sessions/session-1/prompt`, {
531
+ method: 'POST',
532
+ headers: { 'Content-Type': 'application/json' },
533
+ body: JSON.stringify({ text: 'hello', messageId: '' }),
534
+ });
535
+ expect(invalidMessage.status).toBe(400);
536
+ await expect(invalidMessage.json()).resolves.toEqual({ error: { code: 'INVALID_ARGUMENT' } });
537
+
538
+ const mismatch = await fetch(`${base}/sessions/session-1/prompt`, {
539
+ method: 'POST',
540
+ headers: { 'Content-Type': 'application/json' },
541
+ body: JSON.stringify({ text: 'hello', operationId: 'op-mismatch' }),
542
+ });
543
+ expect(mismatch.status).toBe(409);
544
+ await expect(mismatch.json()).resolves.toEqual({ error: { code: 'OPERATION_PAYLOAD_MISMATCH' } });
545
+
546
+ const expired = await fetch(`${base}/sessions/session-1/prompt`, {
547
+ method: 'POST',
548
+ headers: { 'Content-Type': 'application/json' },
549
+ body: JSON.stringify({ text: 'hello', operationId: 'op-expired' }),
550
+ });
551
+ expect(expired.status).toBe(410);
552
+ await expect(expired.json()).resolves.toEqual({ error: { code: 'OPERATION_EXPIRED' } });
553
+ });
554
+
555
+ it('exposes an exact send-receipt lookup without invoking Pi', async () => {
556
+ const calls = [];
557
+ const runtime = {
558
+ request: async (command, payload) => {
559
+ calls.push({ command, payload });
560
+ if (command === 'sessions.sendReceipt') {
561
+ if (payload.operationId === 'op-accepted') {
562
+ return { status: 'accepted', receipt: { accepted: true, messageId: 'message-1' } };
563
+ }
564
+ return { status: payload.operationId === 'op-pending' ? 'pending' : payload.operationId === 'op-expired' ? 'expired' : 'unknown' };
565
+ }
566
+ return { accepted: true, messageId: 'message-1' };
567
+ },
568
+ };
569
+ const app = express();
570
+ app.use(express.json());
571
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
572
+ server = await listen(app);
573
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/sessions/session-1/send-receipt`;
574
+
575
+ const accepted = await fetch(base, {
576
+ method: 'POST',
577
+ headers: { 'Content-Type': 'application/json' },
578
+ body: JSON.stringify({ kind: 'prompt', operationId: 'op-accepted' }),
579
+ });
580
+ expect(accepted.status).toBe(200);
581
+ await expect(accepted.json()).resolves.toEqual({ status: 'accepted', receipt: { accepted: true, messageId: 'message-1' } });
582
+
583
+ const pending = await fetch(base, {
584
+ method: 'POST',
585
+ headers: { 'Content-Type': 'application/json' },
586
+ body: JSON.stringify({ kind: 'steer', operationId: 'op-pending' }),
587
+ });
588
+ expect(pending.status).toBe(200);
589
+ // Pending carries no receipt: the outcome is still being accepted.
590
+ await expect(pending.json()).resolves.toEqual({ status: 'pending' });
591
+
592
+ const expired = await fetch(base, {
593
+ method: 'POST',
594
+ headers: { 'Content-Type': 'application/json' },
595
+ body: JSON.stringify({ kind: 'prompt', operationId: 'op-expired' }),
596
+ });
597
+ expect(expired.status).toBe(200);
598
+ await expect(expired.json()).resolves.toEqual({ status: 'expired' });
599
+
600
+ const unknown = await fetch(base, {
601
+ method: 'POST',
602
+ headers: { 'Content-Type': 'application/json' },
603
+ body: JSON.stringify({ kind: 'followUp', operationId: 'op-unknown' }),
604
+ });
605
+ expect(unknown.status).toBe(200);
606
+ await expect(unknown.json()).resolves.toEqual({ status: 'unknown' });
607
+
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' });
610
+
611
+ const invalidKind = await fetch(base, {
612
+ method: 'POST',
613
+ headers: { 'Content-Type': 'application/json' },
614
+ body: JSON.stringify({ kind: 'promptx', operationId: 'op-accepted' }),
615
+ });
616
+ expect(invalidKind.status).toBe(400);
617
+
618
+ const invalidId = await fetch(base, {
619
+ method: 'POST',
620
+ headers: { 'Content-Type': 'application/json' },
621
+ body: JSON.stringify({ kind: 'prompt', operationId: 'bad id' }),
622
+ });
623
+ expect(invalidId.status).toBe(400);
624
+ });
625
+
441
626
  it('streams binary attachments with bounded metadata and deletes unused uploads', async () => {
442
627
  const calls = [];
443
628
  const attachmentStore = {
@@ -850,7 +1035,7 @@ describe('Pi runtime route', () => {
850
1035
  const app = express();
851
1036
  registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
852
1037
  server = await listen(app);
853
- const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-5&fromSequence=3`);
1038
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-5&fromSequence=3&capabilities=events.streamEpoch&streamEpoch=epoch-test`);
854
1039
  const reader = response.body.getReader();
855
1040
  const first = await reader.read();
856
1041
  let text = new TextDecoder().decode(first.value);
@@ -901,6 +1086,30 @@ describe('Pi runtime route', () => {
901
1086
  expect(text).toContain('event: heartbeat\ndata: {}\n\n');
902
1087
  });
903
1088
 
1089
+ it('carries the streamEpoch subscribe marker end-to-end and rejects malformed values', async () => {
1090
+ const seen = [];
1091
+ const runtime = {
1092
+ health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: ['events.streamEpoch'] }),
1093
+ subscribe: async (options) => {
1094
+ seen.push({ streamEpoch: options.streamEpoch, fromSequence: options.fromSequence });
1095
+ return () => {};
1096
+ },
1097
+ };
1098
+ const app = express();
1099
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
1100
+ server = await listen(app);
1101
+
1102
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/events`;
1103
+ const ok = await fetch(`${base}?sessionId=pi-session-5&fromSequence=7&streamEpoch=epoch-abc123&capabilities=events.streamEpoch`);
1104
+ await ok.body.cancel();
1105
+ expect(ok.status).toBe(200);
1106
+ expect(seen[0]).toEqual({ streamEpoch: 'epoch-abc123', fromSequence: 7 });
1107
+
1108
+ const malformed = await fetch(`${base}?streamEpoch=${'x'.repeat(129)}`);
1109
+ expect(malformed.status).toBe(400);
1110
+ expect((await malformed.json()).error?.code).toBe('INVALID_ARGUMENT');
1111
+ });
1112
+
904
1113
  it('projects session.updated titles onto the public event stream', async () => {
905
1114
  const runtime = {
906
1115
  health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
@@ -918,7 +1127,7 @@ describe('Pi runtime route', () => {
918
1127
  const app = express();
919
1128
  registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
920
1129
  server = await listen(app);
921
- const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-5&fromSequence=7`);
1130
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-5&fromSequence=7&capabilities=events.streamEpoch&streamEpoch=epoch-test`);
922
1131
  const reader = response.body.getReader();
923
1132
  const first = await reader.read();
924
1133
  let text = new TextDecoder().decode(first.value);
@@ -975,7 +1184,7 @@ describe('Pi runtime route', () => {
975
1184
  const detailBody = await detail.json();
976
1185
  expect(detailBody.messages[0].message.usage).toEqual(sampleUsage);
977
1186
 
978
- const events = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-usage&fromSequence=0`);
1187
+ const events = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-usage&fromSequence=0&capabilities=events.streamEpoch&streamEpoch=epoch-test`);
979
1188
  const reader = events.body.getReader();
980
1189
  const first = await reader.read();
981
1190
  const text = new TextDecoder().decode(first.value);
@@ -1036,7 +1245,7 @@ describe('Pi runtime route', () => {
1036
1245
  expect(detailBody.messages[0].message.usage).toBeUndefined();
1037
1246
  expect(detailBody.messages[1].message.usage).toBeUndefined();
1038
1247
 
1039
- const events = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-usage-malformed&fromSequence=0`);
1248
+ const events = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/events?sessionId=pi-session-usage-malformed&fromSequence=0&capabilities=events.streamEpoch&streamEpoch=epoch-test`);
1040
1249
  const reader = events.body.getReader();
1041
1250
  const first = await reader.read();
1042
1251
  const text = new TextDecoder().decode(first.value);