@pi-chamber/web 0.9.1 → 0.9.4

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 (57) hide show
  1. package/README.md +2 -2
  2. package/bin/lib/cli-paths.js +22 -6
  3. package/dist/assets/{DiagramEditor-DoEOH0hY.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  4. package/dist/assets/{DiagramView-y9Ystuhv.js → DiagramView-CHy1Glsl.js} +1 -1
  5. package/dist/assets/{DiffView-ScM4XoqZ.js → DiffView-CBOrV4hS.js} +1 -1
  6. package/dist/assets/{FilesView-CjkhMFqJ.js → FilesView-CK2YVs_W.js} +1 -1
  7. package/dist/assets/{GitView-Bqi6H8I-.js → GitView-BEFLOv_7.js} +3 -3
  8. package/dist/assets/{JsonTreeView-DWhlH6NK.js → JsonTreeView-CKWGm5MS.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-CEOKZ1qH.js → MarkdownRendererImpl-hE_nmSqe.js} +1 -1
  10. package/dist/assets/{PatchDiff-ClnfJJ2J.js → PatchDiff-BagRxMON.js} +1 -1
  11. package/dist/assets/{SessionSwitcherContent-e6JzUXD_.js → SessionSwitcherContent-z9VYCXrT.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-C4etG8dv.js → SessionSwitcherDropdown-icxJk_lT.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-BVTSwRiG.js → SessionUnreadDot-Bv-5KguB.js} +1 -1
  14. package/dist/assets/SettingsView-Ck0qxtKP.js +2 -0
  15. package/dist/assets/{SettingsWindow-Cy9tmnMg.js → SettingsWindow-GQRL2CdD.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-Csrc0Uk2.js → ToolOutputDialog-CxJUXVZW.js} +1 -1
  17. package/dist/assets/{ToolPartDiffPreview-6oH6KD44.js → ToolPartDiffPreview-BXuLRWHT.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-DJNcTQNp.js → VirtualizedFileDiff-DfaXovGB.js} +1 -1
  19. package/dist/assets/{collapsible-DxgVLhi9.js → collapsible-szfZ0Syc.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-B-WoeBMW.js → computeVirtualFileMetrics-DG_E6iaN.js} +1 -1
  21. package/dist/assets/{contextFileOpenGuard-DQ4U9xRH.js → contextFileOpenGuard-DPBE3ELv.js} +1 -1
  22. package/dist/assets/{gitStatusPredicates-CIFSGjJs.js → gitStatusPredicates-OljV4Bb2.js} +1 -1
  23. package/dist/assets/{index-DmNPBaSo.js → index-DmexVlTQ.js} +1 -1
  24. package/dist/assets/{index-D2C3q2xD.js → index-KIdiBFJs.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-CrvpUauF.js → isDiffPlainText-aikgiqLb.js} +1 -1
  26. package/dist/assets/{isFilePlainText-CKvhS32g.js → isFilePlainText-D-Dl6LqX.js} +1 -1
  27. package/dist/assets/{main-CjM7g4Gq.js → main-BXdraZTZ.js} +3 -3
  28. package/dist/assets/{main-BFv8slLp.js → main-DG1oZ0Wj.js} +2 -2
  29. package/dist/assets/{markdownCore-DKrraAqT.js → markdownCore-DUjQU2i0.js} +1 -1
  30. package/dist/assets/{miniChat-hQnLS5mt.js → miniChat-BEAtOkr9.js} +2 -2
  31. package/dist/assets/{mobile-DuXOBGs_.js → mobile-DOFBBQg2.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-ClJBZVGy.js → renderElectronMiniChatApp-B0K72YnS.js} +2 -2
  33. package/dist/assets/{renderMobileApp-DofX2wjB.js → renderMobileApp-Ca_BO_s4.js} +3 -3
  34. package/dist/assets/{runtimeEndpointReset-BZeYg6eN.js → runtimeEndpointReset-Cx2tsgTo.js} +15 -15
  35. package/dist/assets/{runtimeSurface-C7CBxDbh.js → runtimeSurface-CySRuLbN.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-Cs0f1dKn.js → useAppFontEffects-C4JL1x7k.js} +85 -85
  37. package/dist/assets/{useFilesViewSearch-D1hcbBEc.js → useFilesViewSearch-Du0DnmKs.js} +1 -1
  38. package/dist/assets/{usePushVisibilityBeacon-DqHkuVS5.js → usePushVisibilityBeacon-BnHxIv4r.js} +1 -1
  39. package/dist/assets/{useSwitcherItems-BEoW7LlC.js → useSwitcherItems-C91mwPJD.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-language-data-B8Ac62S_.js → vendor-codemirror-language-data-C493X_9w.js} +2 -2
  41. package/dist/assets/{web-components-Dy-Tz_LJ.js → web-components-B2Rw__yK.js} +1 -1
  42. package/dist/index.html +3 -3
  43. package/dist/mini-chat.html +2 -2
  44. package/dist/mobile.html +2 -2
  45. package/package.json +1 -1
  46. package/server/lib/pi/routes.js +48 -4
  47. package/server/lib/pi/routes.test.js +108 -1
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -5
  49. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  50. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  51. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  52. package/server/lib/pi/session-daemon/prompt-operations.test.js +51 -0
  53. package/server/lib/pi/session-daemon/session-daemon.js +316 -80
  54. package/server/lib/pi/session-daemon/session-daemon.test.js +327 -0
  55. package/server/lib/pi/ui-settings-store.js +130 -25
  56. package/server/lib/pi/ui-settings-store.test.js +58 -7
  57. package/dist/assets/SettingsView-C0S0Sx-S.js +0 -2
@@ -45,10 +45,17 @@ const UNAVAILABLE_CODES = new Set([
45
45
  'ARCHIVE_METADATA_INVALID',
46
46
  ]);
47
47
 
48
+ const BAD_GATEWAY_CODES = new Set([
49
+ 'MALFORMED_DAEMON_RESPONSE',
50
+ 'DAEMON_RESPONSE_TOO_LARGE',
51
+ ]);
52
+
48
53
  const writeDaemonError = (res, error) => {
49
54
  const code = typeof error?.code === 'string' ? error.code : 'DAEMON_REQUEST_FAILED';
50
55
  const status = UNAVAILABLE_CODES.has(code)
51
56
  ? 503
57
+ : BAD_GATEWAY_CODES.has(code)
58
+ ? 502
52
59
  : code === 'INVALID_SESSION'
53
60
  ? 404
54
61
  : code === 'SESSION_IN_USE'
@@ -212,7 +219,8 @@ const projectFilePart = (part) => {
212
219
  };
213
220
 
214
221
  const projectSessionDetail = (value) => {
215
- if (!value || typeof value !== 'object' || !Array.isArray(value.messages) || !Number.isSafeInteger(value.lastSequence)) throw protocolMismatch();
222
+ if (!value || typeof value !== 'object' || !Array.isArray(value.messages) || !Number.isSafeInteger(value.lastSequence)
223
+ || (value.hasMoreBefore === true && (typeof value.beforeCursor !== 'string' || value.beforeCursor.length === 0))) throw protocolMismatch();
216
224
  const messages = value.messages.map((item) => {
217
225
  if (!item || typeof item !== 'object' || !item.message || !Array.isArray(item.parts)) throw protocolMismatch();
218
226
  const message = item.message;
@@ -270,6 +278,11 @@ const projectSessionDetail = (value) => {
270
278
  return {
271
279
  session: projectSession(value.session),
272
280
  messages,
281
+ ...(value.hasMoreBefore === true && typeof value.beforeCursor === 'string' && value.beforeCursor.length > 0
282
+ ? { hasMoreBefore: true, beforeCursor: value.beforeCursor }
283
+ : value.hasMoreBefore === false
284
+ ? { hasMoreBefore: false }
285
+ : {}),
273
286
  lastSequence: value.lastSequence,
274
287
  isStreaming,
275
288
  lifecycle,
@@ -309,7 +322,7 @@ const projectProviders = (value) => {
309
322
 
310
323
  const projectProviderConfig = (value) => {
311
324
  const config = value?.config;
312
- if (config === null) return { config: null };
325
+ if (config === null) return { config: null, ...(value?.deferred === true ? { deferred: true } : {}) };
313
326
  if (!config || typeof config !== 'object' || typeof config.providerId !== 'string' || typeof config.label !== 'string'
314
327
  || typeof config.baseUrl !== 'string' || typeof config.api !== 'string' || !Array.isArray(config.models)) throw protocolMismatch();
315
328
  return {
@@ -329,6 +342,7 @@ const projectProviderConfig = (value) => {
329
342
  };
330
343
  }),
331
344
  },
345
+ ...(value?.deferred === true ? { deferred: true } : {}),
332
346
  };
333
347
  };
334
348
 
@@ -377,7 +391,10 @@ const projectPiSettings = (value) => {
377
391
  ...(typeof settings.defaultThinking === 'string' ? { defaultThinking: settings.defaultThinking } : {}),
378
392
  ...(typeof settings.defaultProjectTrust === 'string' ? { defaultProjectTrust: settings.defaultProjectTrust } : {}),
379
393
  });
380
- return { pi: { global: copy(value.global), project: { trusted: project.trusted, ...(project.denied === true ? { denied: true } : {}), ...(project.requiresTrust === true ? { requiresTrust: true } : {}), ...copy(project) } } };
394
+ return {
395
+ pi: { global: copy(value.global), project: { trusted: project.trusted, ...(project.denied === true ? { denied: true } : {}), ...(project.requiresTrust === true ? { requiresTrust: true } : {}), ...copy(project) } },
396
+ ...(value.deferred === true ? { deferred: true } : {}),
397
+ };
381
398
  };
382
399
 
383
400
  const projectResources = (value) => {
@@ -398,7 +415,12 @@ const projectResources = (value) => {
398
415
  };
399
416
  });
400
417
  };
401
- return { skills: project(value.skills, 'skill'), prompts: project(value.prompts, 'prompt'), agents: project(value.agents, 'agents') };
418
+ return {
419
+ skills: project(value.skills, 'skill'),
420
+ prompts: project(value.prompts, 'prompt'),
421
+ agents: project(value.agents, 'agents'),
422
+ ...(value.deferred === true ? { deferred: true } : {}),
423
+ };
402
424
  };
403
425
 
404
426
  const projectSessionTree = (value) => {
@@ -610,6 +632,7 @@ export const projectEventFrame = (frame) => {
610
632
  ...(frame.payload.isError === true ? { isError: true } : {}),
611
633
  ...(Number.isFinite(frame.payload.startedAt) ? { startedAt: frame.payload.startedAt } : {}),
612
634
  ...(Number.isFinite(frame.payload.endedAt) ? { endedAt: frame.payload.endedAt } : {}),
635
+ ...(Number.isFinite(frame.payload.serverNow) ? { serverNow: frame.payload.serverNow } : {}),
613
636
  },
614
637
  };
615
638
  case 'extension.entry': {
@@ -1486,6 +1509,27 @@ export const registerPiRuntimeRoutes = (app, {
1486
1509
  app.get('/api/pi/sessions/:sessionId', sendSessionDetail);
1487
1510
  app.get('/api/pi/sessions/:sessionId/snapshot', sendSessionDetail);
1488
1511
 
1512
+ app.get('/api/pi/sessions/:sessionId/messages', async (req, res) => {
1513
+ const before = req.query?.before;
1514
+ const rawLimit = req.query?.limit;
1515
+ const limit = rawLimit === undefined ? undefined : Number(rawLimit);
1516
+ if ((before !== undefined && (typeof before !== 'string' || before.length === 0))
1517
+ || (rawLimit !== undefined && (typeof rawLimit !== 'string' || !Number.isSafeInteger(limit) || limit < 1 || limit > 100))) {
1518
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1519
+ return;
1520
+ }
1521
+ const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.messages', {
1522
+ ...(typeof before === 'string' ? { before } : {}),
1523
+ ...(limit !== undefined ? { limit } : {}),
1524
+ });
1525
+ if (result === undefined) return;
1526
+ try {
1527
+ res.json(projectSessionDetail(result));
1528
+ } catch (error) {
1529
+ writeDaemonError(res, error);
1530
+ }
1531
+ });
1532
+
1489
1533
  app.delete('/api/pi/sessions/:sessionId', async (req, res) => {
1490
1534
  const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.delete');
1491
1535
  if (result !== undefined) res.status(204).end();
@@ -258,6 +258,59 @@ describe('Pi runtime route', () => {
258
258
  ]);
259
259
  });
260
260
 
261
+ it('preserves deferred status for accepted Pi mutations', async () => {
262
+ const runtime = {
263
+ request: async (command) => {
264
+ if (command === 'settings.set') return { global: {}, project: { trusted: false }, deferred: true };
265
+ if (command === 'resources.update') return { skills: [], prompts: [], agents: [], deferred: true };
266
+ if (command === 'providers.models.set') return {
267
+ config: {
268
+ providerId: 'custom',
269
+ label: 'Custom',
270
+ baseUrl: 'https://api.example.test/v1',
271
+ api: 'openai-completions',
272
+ models: [],
273
+ },
274
+ deferred: true,
275
+ };
276
+ throw new Error(`Unexpected command ${command}`);
277
+ },
278
+ };
279
+ const app = express();
280
+ app.use(express.json());
281
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
282
+ server = await listen(app);
283
+ const base = `http://127.0.0.1:${server.address().port}/api/pi`;
284
+
285
+ await expect((await fetch(`${base}/settings/pi`, {
286
+ method: 'PUT',
287
+ headers: { 'Content-Type': 'application/json' },
288
+ body: JSON.stringify({ scope: 'global', defaultThinking: 'high' }),
289
+ })).json()).resolves.toEqual({
290
+ pi: { global: {}, project: { trusted: false } },
291
+ deferred: true,
292
+ });
293
+ await expect((await fetch(`${base}/resources/resource-1`, {
294
+ method: 'PUT',
295
+ headers: { 'Content-Type': 'application/json' },
296
+ body: JSON.stringify({ content: 'Updated' }),
297
+ })).json()).resolves.toEqual({ skills: [], prompts: [], agents: [], deferred: true });
298
+ await expect((await fetch(`${base}/providers/custom/models`, {
299
+ method: 'PUT',
300
+ headers: { 'Content-Type': 'application/json' },
301
+ body: JSON.stringify({ label: 'Custom', baseUrl: 'https://api.example.test/v1', models: [] }),
302
+ })).json()).resolves.toEqual({
303
+ config: {
304
+ providerId: 'custom',
305
+ label: 'Custom',
306
+ baseUrl: 'https://api.example.test/v1',
307
+ api: 'openai-completions',
308
+ models: [],
309
+ },
310
+ deferred: true,
311
+ });
312
+ });
313
+
261
314
  it('forwards provider login without returning API keys and projects only interactive login state', async () => {
262
315
  const calls = [];
263
316
  const runtime = {
@@ -582,6 +635,59 @@ describe('Pi runtime route', () => {
582
635
  ]);
583
636
  });
584
637
 
638
+ it('maps malformed and oversized daemon responses to distinct gateway errors', async () => {
639
+ for (const code of ['MALFORMED_DAEMON_RESPONSE', 'DAEMON_RESPONSE_TOO_LARGE']) {
640
+ const runtime = {
641
+ request: async () => {
642
+ const error = new Error(code);
643
+ error.code = code;
644
+ throw error;
645
+ },
646
+ };
647
+ const app = express();
648
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
649
+ server = await listen(app);
650
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/session-1`);
651
+ expect(response.status).toBe(502);
652
+ await expect(response.json()).resolves.toEqual({ error: { code } });
653
+ await close(server);
654
+ server = undefined;
655
+ }
656
+ });
657
+
658
+ it('validates and forwards older transcript page requests', async () => {
659
+ const calls = [];
660
+ const detail = {
661
+ session: { id: 'pi-session-pages', directory: '/workspace', createdAt: 1, updatedAt: 2 },
662
+ messages: [],
663
+ hasMoreBefore: false,
664
+ lastSequence: 5,
665
+ isStreaming: false,
666
+ lifecycle: 'idle',
667
+ };
668
+ const runtime = {
669
+ request: async (command, payload) => {
670
+ calls.push({ command, payload });
671
+ return detail;
672
+ },
673
+ };
674
+ const app = express();
675
+ app.use(express.json());
676
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) } });
677
+ server = await listen(app);
678
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-pages/messages`;
679
+
680
+ const response = await fetch(`${base}?directory=${encodeURIComponent('/workspace')}&before=entry-5&limit=25`);
681
+ expect(response.status).toBe(200);
682
+ await expect(response.json()).resolves.toMatchObject({ hasMoreBefore: false, messages: [] });
683
+ expect(calls).toEqual([{
684
+ command: 'sessions.messages',
685
+ payload: { sessionId: 'pi-session-pages', directory: '/workspace', before: 'entry-5', limit: 25 },
686
+ }]);
687
+ expect((await fetch(`${base}?limit=0`)).status).toBe(400);
688
+ expect((await fetch(`${base}?limit=101`)).status).toBe(400);
689
+ });
690
+
585
691
  it('adapts every path-selected session operation and archives without selecting a Pi runtime', async () => {
586
692
  const calls = [];
587
693
  const detail = { session: { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 }, messages: [], lastSequence: 5 };
@@ -736,7 +842,7 @@ describe('Pi runtime route', () => {
736
842
  onEvent({ protocolVersion: 1, kind: 'event', event: 'assistant.message.end', sequence: 6, payload: { sessionId: 'pi-session-5', directory: '/workspace', messageId: 'assistant-1', durationMs: 42, continuing: true, error: { code: 'ASSISTANT_ERROR', message: 'provider request timed out' } } });
737
843
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.lifecycle', sequence: 7, payload: { sessionId: 'pi-session-5', directory: '/workspace', state: 'retry', attempt: 2, next: 8_000, message: 'provider request timed out' } });
738
844
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.error', sequence: 8, payload: { sessionId: 'pi-session-5', directory: '/workspace', code: 'ASSISTANT_ERROR', message: 'provider request timed out' } });
739
- onEvent({ protocolVersion: 1, kind: 'event', event: 'session.tool.start', sequence: 9, payload: { sessionId: 'pi-session-5', directory: '/workspace', toolCallId: 'skill-read', partId: 'assistant-1:tool:skill-read', messageId: 'assistant-1', name: 'read', state: 'running', metadata: { pichamber: { skill: { name: 'review' } } }, privatePath: '/private/skill/SKILL.md' } });
845
+ onEvent({ protocolVersion: 1, kind: 'event', event: 'session.tool.start', sequence: 9, payload: { sessionId: 'pi-session-5', directory: '/workspace', toolCallId: 'skill-read', partId: 'assistant-1:tool:skill-read', messageId: 'assistant-1', name: 'read', state: 'running', metadata: { pichamber: { skill: { name: 'review' } } }, startedAt: 2_000, serverNow: 3_000, privatePath: '/private/skill/SKILL.md' } });
740
846
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.compaction', sequence: 10, payload: { sessionId: 'pi-session-5', directory: '/workspace', phase: 'completed', reason: 'overflow', startedAt: 3_000, completedAt: 9_000, tokensBefore: 120_000, estimatedTokensAfter: 24_000, willRetry: true, privateResult: 'hidden' } });
741
847
  return () => {};
742
848
  },
@@ -764,6 +870,7 @@ describe('Pi runtime route', () => {
764
870
  expect(text).toContain('"state":"retry","attempt":2,"next":8000,"message":"provider request timed out"');
765
871
  expect(text).toContain('"message":"provider request timed out"');
766
872
  expect(text).toContain('"metadata":{"pichamber":{"skill":{"name":"review"}}}');
873
+ expect(text).toContain('"startedAt":2000,"serverNow":3000');
767
874
  expect(text).toContain('"phase":"completed","reason":"overflow","startedAt":3000,"completedAt":9000,"tokensBefore":120000,"estimatedTokensAfter":24000,"willRetry":true');
768
875
  expect(text).not.toContain('privatePath');
769
876
  expect(text).not.toContain('privateResult');
@@ -20,7 +20,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
20
20
  - `../server/server-profile.js` derives one stable daemon profile per server: installed web is `web-p<port>`, development web is `web-dev-p<port>`, installed desktop is `desktop`, and development desktop is `desktop-dev`. `PICHAMBER_SERVER_PROFILE` overrides the derivation with a hashed `custom-<hash>` key so raw input never becomes a path, while preserving whether the launcher is a development build for stale-code replacement. The profile key is stable across restarts; the server instance id is a fresh UUID per launch. Development launchers (`scripts/dev-web-hmr.mjs`, `scripts/dev-web-full.mjs`, `cross-env` in the `dev:server` scripts, `PICHAMBER_ELECTRON_DEV`) explicitly mark themselves so stopping development can never terminate the installed daemon.
21
21
  - `../server/cross-process-lock.js` serializes critical sections across servers sharing one data directory (exclusive create, owner nonce, dead-pid steal, bounded wait). It backs the daemon operation lock pattern and every shared read-modify-write store below.
22
22
  - `session-lease.js` owns exclusive cross-daemon residency of one Pi session, keyed by canonical agent directory, cwd, and session id under `<agentDir>/.pichamber/locks/sessions/`. The lease is acquired before a resident `AgentSessionRuntime` is created and released after idle disposal, deletion, replacement, or daemon shutdown. Opening or deleting a session leased by another live daemon returns `SESSION_IN_USE` (HTTP 409) while the session stays visible in listings; different sessions remain fully concurrent. Lease files from different `PICHAMBER_DATA_DIR` values still coordinate because they live under the shared agent directory.
23
- - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
23
+ - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` owns portable PiChamber preferences at data-root `settings.json` and host, device, and secret-bearing values at `runtime-state.json`. `/api/pi/ui-settings` merges both views for existing clients and splits writes through explicit field allowlists. It migrates an unscoped flat file once; after the portable scope marker exists, local fields found in `settings.json` are ignored rather than applied to the host. The route is not available through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
24
24
  - `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
25
25
 
26
26
  ## Protocol and security invariants
@@ -30,12 +30,11 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
30
30
  - POSIX socket parent directories are mode `0700`; the socket is created mode `0600`. An existing endpoint fails startup rather than being unlinked without daemon-identity verification. Windows named-pipe ACLs are not yet equivalent owner-only OS permissions; credential authentication remains mandatory.
31
31
  - The daemon credential and non-secret state sidecars are mode `0600`; their per-profile parent directory and the operation lock serialize start/reuse/stop. Exclusive lock create writes the owner pid in the same step. A leftover empty or malformed lock, a dead owner pid, or Windows `EPERM`/`EACCES` on exclusive create is retried and stolen after a short freshness window instead of failing as `DAEMON_LOCK_UNAVAILABLE`. Sidecar `chmod` failures on Windows are ignored after the file exists so readiness is still recorded. Health identity includes the daemon PID, profile key, and daemon id, and all three must match the state sidecar before the supervisor reuses a process. Reuse also requires the ready-state `entrypoint` to equal this host's `daemon-process.js`; a missing or different path is not identity-compatible and is replaced after a claim.
32
32
  - Ownership transfers through authenticated `runtime.claim` only after the previous server PID is no longer live. The daemon persists the new `serverInstanceId` and `serverPid` to its state sidecar before acknowledging the claim, so its in-memory owner and discoverable owner cannot split. Shutdown goes through authenticated `runtime.shutdown` (profile, daemon id, and current owner instance must all match) before any signal; a stale server whose daemon was claimed receives `DAEMON_OWNERSHIP_MISMATCH` and terminates nothing. A direct signal is used only after authenticated health and ownership checks prove that the sidecar PID is this profile's daemon (or for a child the supervisor just spawned during failed startup).
33
- - Shared writable state is coordinated, not merely namespaced. Pi prompt, context, settings, and model writes serialize through `<agentDir>/.pichamber/locks/pi-config.lock`; `models.json` additionally serializes in its store. PiChamber data-root stores (`pi/settings.json`, `pi/snippets.json`, `pi/session-archive.json`, `pi/session-folders.json`, root `settings.json`, STT config, remote-client and pairing stores) serialize read-modify-write through per-file locks with atomic replace; `session-folders.json` additionally rejects a stale `updatedAt` snapshot as `SESSION_FOLDERS_STALE` (HTTP 409) instead of silently overwriting newer folders. Passkeys, the JWT secret (exclusive create with re-read), the tunnel token, and git identities use atomic replace. Cross-daemon config staleness is bounded by idle runtime disposal (five minutes), which recreates runtimes from disk; there is no cross-daemon live-reload generation yet.
33
+ - Shared writable state is coordinated, not merely namespaced. Pi prompt, context, settings, and model writes serialize through `<agentDir>/.pichamber/locks/pi-config.lock`; `models.json` additionally serializes in its store. PiChamber data-root stores (`pi/settings.json`, `pi/snippets.json`, `pi/session-archive.json`, `pi/session-folders.json`, root `settings.json` and `runtime-state.json`, STT config, remote-client and pairing stores) serialize read-modify-write through per-file locks with atomic replace; `session-folders.json` additionally rejects a stale `updatedAt` snapshot as `SESSION_FOLDERS_STALE` (HTTP 409) instead of silently overwriting newer folders. Passkeys, the JWT secret (exclusive create with re-read), the tunnel token, and git identities use atomic replace. Cross-daemon config staleness is bounded by idle runtime disposal (five minutes), which recreates runtimes from disk; there is no cross-daemon live-reload generation yet.
34
34
  - The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
35
35
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
36
- - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
37
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes remain rejected while the active session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
38
- - Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
36
+ - Frames are LF-delimited JSON. One frame has a 16 MiB maximum. Complete frames are parsed before the client bounds the remaining incomplete frame. Invalid JSON reports `MALFORMED_DAEMON_RESPONSE`; an oversized response reports `DAEMON_RESPONSE_TOO_LARGE`. A malformed, oversized, unauthenticated, or invalid request closes the connection.
37
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/messages/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, and roll back the destination when source removal fails. A committed prompt mutation never disposes a session runtime: affected idle sessions use Pi's identity-preserving `session.reload()`, while streaming, compacting, and extension-command sessions finish first and reload at their next safe lifecycle edge. Global prompts refresh every resident runtime; project prompts refresh only runtimes in that directory. Mutation responses merge freshly discovered editable prompts with live package/path/extension resources so the Settings page reflects the committed file even while runtime activation is deferred. Generic non-prompt resource writes share the serialized resource-mutation queue and commit through an atomic replace even while a session is active. The daemon returns `deferred: true` and recreates resident runtimes after they become idle; a new session reads the committed file immediately. If immediate recreation fails after a committed write, the response still reports deferred activation and the daemon keeps the recreation queued for a later safe edge. Project trust changes are persisted in Pi trust.json and use the same deferred runtime recreation; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` atomically persists Pi's `models.json`; a busy runtime returns `deferred: true` and is rehydrated after all active sessions are idle, while a new session sees the catalog immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. `sessions.open`, navigate, fork, and clone return a tail page bounded by both projected-message count and serialized bytes. `sessions.messages` reads older pages with an opaque before-cursor. A page that starts inside a tool loop repeats the owning user message as a grouping anchor; browser merging deduplicates that overlap. Persisted tool results are indexed across the active branch before paging, so a paged assistant tool call still receives its matching final result. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and server start/end timestamps plus a `serverNow` sample so clients with different clocks can normalize elapsed time. Active and recently completed tool parts retain their start timestamps in the daemon's bounded in-memory timing cache, so `getSession` hydration keeps timers consistent across clients and browser reloads until the daemon restarts. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.- Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
39
38
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
40
39
  - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata and adds it to the matching user start in send order. The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
41
40
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
@@ -2,8 +2,10 @@ import { randomUUID } from 'node:crypto';
2
2
  import { createConnection } from 'node:net';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
4
 
5
- const PROTOCOL_VERSION = 1;
6
- const MAX_FRAME_BYTES = 16 * 1024 * 1024;
5
+ import {
6
+ SESSION_DAEMON_MAX_FRAME_BYTES as MAX_FRAME_BYTES,
7
+ SESSION_DAEMON_PROTOCOL_VERSION as PROTOCOL_VERSION,
8
+ } from './ipc-protocol.js';
7
9
 
8
10
  export class SessionDaemonClientError extends Error {
9
11
  constructor(code, message = 'The Pi session daemon is unavailable.') {
@@ -41,17 +43,20 @@ export const requestSessionDaemon = ({ endpoint, credential, command, payload, t
41
43
  });
42
44
  socket.on('data', (chunk) => {
43
45
  buffer += decoder.write(chunk);
44
- if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
45
- fail('MALFORMED_DAEMON_RESPONSE');
46
- return;
47
- }
48
46
 
49
47
  while (true) {
50
48
  const newline = buffer.indexOf('\n');
51
- if (newline === -1) return;
49
+ if (newline === -1) {
50
+ if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) fail('DAEMON_RESPONSE_TOO_LARGE');
51
+ return;
52
+ }
52
53
  const line = buffer.slice(0, newline).replace(/\r$/, '');
53
54
  buffer = buffer.slice(newline + 1);
54
55
  if (!line) continue;
56
+ if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
57
+ fail('DAEMON_RESPONSE_TOO_LARGE');
58
+ return;
59
+ }
55
60
 
56
61
  let message;
57
62
  try {
@@ -113,13 +118,19 @@ export const subscribeSessionDaemon = ({ endpoint, credential, sessionId, fromSe
113
118
  });
114
119
  socket.on('data', (chunk) => {
115
120
  buffer += decoder.write(chunk);
116
- if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) return fail(new SessionDaemonClientError('MALFORMED_DAEMON_RESPONSE'));
117
121
  while (true) {
118
122
  const newline = buffer.indexOf('\n');
119
- if (newline === -1) return;
123
+ if (newline === -1) {
124
+ if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) fail(new SessionDaemonClientError('DAEMON_RESPONSE_TOO_LARGE'));
125
+ return;
126
+ }
120
127
  const line = buffer.slice(0, newline).replace(/\r$/, '');
121
128
  buffer = buffer.slice(newline + 1);
122
129
  if (!line) continue;
130
+ if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
131
+ fail(new SessionDaemonClientError('DAEMON_RESPONSE_TOO_LARGE'));
132
+ return;
133
+ }
123
134
  let message;
124
135
  try { message = JSON.parse(line); } catch { fail(new SessionDaemonClientError('MALFORMED_DAEMON_RESPONSE')); return; }
125
136
  if (message.protocolVersion !== PROTOCOL_VERSION) { fail(new SessionDaemonClientError('UNSUPPORTED_DAEMON_PROTOCOL')); return; }
@@ -0,0 +1,88 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { createServer } from 'node:net';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+
8
+ import { requestSessionDaemon } from './ipc-client.js';
9
+ import { SESSION_DAEMON_MAX_FRAME_BYTES } from './ipc-protocol.js';
10
+
11
+ const credential = 'test-private-credential';
12
+ const roots = [];
13
+ const servers = [];
14
+
15
+ const endpointFor = (root) => process.platform === 'win32'
16
+ ? `\\\\.\\pipe\\pichamber-ipc-test-${createHash('sha1').update(root).digest('hex').slice(0, 16)}`
17
+ : join(root, 'daemon.sock');
18
+
19
+ const startServer = async (respond) => {
20
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-ipc-client-'));
21
+ roots.push(root);
22
+ const endpoint = endpointFor(root);
23
+ const server = createServer((socket) => {
24
+ socket.on('error', () => {});
25
+ let buffer = '';
26
+ socket.on('data', (chunk) => {
27
+ buffer += chunk.toString('utf8');
28
+ while (buffer.includes('\n')) {
29
+ const newline = buffer.indexOf('\n');
30
+ const line = buffer.slice(0, newline);
31
+ buffer = buffer.slice(newline + 1);
32
+ if (!line) continue;
33
+ const frame = JSON.parse(line);
34
+ if (frame.kind === 'authenticate') {
35
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'authenticated' })}\n`);
36
+ } else if (frame.kind === 'request') {
37
+ respond(socket, frame);
38
+ }
39
+ }
40
+ });
41
+ });
42
+ servers.push(server);
43
+ await new Promise((resolve, reject) => {
44
+ server.once('error', reject);
45
+ server.listen({ path: endpoint }, resolve);
46
+ });
47
+ return endpoint;
48
+ };
49
+
50
+ afterEach(async () => {
51
+ await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));
52
+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
53
+ });
54
+
55
+ describe('session daemon IPC client framing', () => {
56
+ it('distinguishes malformed JSON from an oversized response frame', async () => {
57
+ const malformedEndpoint = await startServer((socket) => socket.end('{not-json}\n'));
58
+ await expect(requestSessionDaemon({
59
+ endpoint: malformedEndpoint,
60
+ credential,
61
+ command: 'runtime.health',
62
+ })).rejects.toMatchObject({ code: 'MALFORMED_DAEMON_RESPONSE' });
63
+
64
+ const oversizedEndpoint = await startServer((socket) => {
65
+ socket.end(`${'A'.repeat(SESSION_DAEMON_MAX_FRAME_BYTES + 1)}\n`);
66
+ });
67
+ await expect(requestSessionDaemon({
68
+ endpoint: oversizedEndpoint,
69
+ credential,
70
+ command: 'runtime.health',
71
+ })).rejects.toMatchObject({ code: 'DAEMON_RESPONSE_TOO_LARGE' });
72
+ }, 20_000);
73
+
74
+ it('parses complete frames before bounding the incomplete remainder', async () => {
75
+ const endpoint = await startServer((socket, request) => {
76
+ const response = JSON.stringify({
77
+ protocolVersion: 1,
78
+ kind: 'response',
79
+ requestId: request.requestId,
80
+ result: { ok: true },
81
+ });
82
+ socket.end(`${response}\n${'A'.repeat(SESSION_DAEMON_MAX_FRAME_BYTES)}`);
83
+ });
84
+
85
+ await expect(requestSessionDaemon({ endpoint, credential, command: 'runtime.health' }))
86
+ .resolves.toEqual({ ok: true });
87
+ });
88
+ });
@@ -0,0 +1,9 @@
1
+ export const SESSION_DAEMON_PROTOCOL_VERSION = 1;
2
+ export const SESSION_DAEMON_MAX_FRAME_BYTES = 16 * 1024 * 1024;
3
+
4
+ // Keep normal transcript pages well below the hard frame ceiling. The final
5
+ // encoded response contains protocol and session metadata in addition to the
6
+ // projected messages.
7
+ export const SESSION_DAEMON_MESSAGE_PAGE_TARGET_BYTES = 4 * 1024 * 1024;
8
+ export const SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT = 50;
9
+ export const SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT = 100;
@@ -310,6 +310,7 @@ describe('prompt template daemon operations', () => {
310
310
  name: 'during-run', description: 'During run', content: 'x', location: 'global', directory: ctx.cwd,
311
311
  });
312
312
  expect(created.prompts.some((prompt) => prompt.name === 'during-run')).toBe(true);
313
+ expect(created.deferred).toBe(true);
313
314
  expect(session.reloadCount).toBe(0);
314
315
  expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
315
316
 
@@ -329,6 +330,56 @@ describe('prompt template daemon operations', () => {
329
330
  expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
330
331
  });
331
332
 
333
+ it('commits generic resource changes while streaming and refreshes after settlement', async () => {
334
+ const session = new FakeSession();
335
+ const ctx = await startDaemon({ session });
336
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
337
+ const agents = listed.agents.find((agent) => agent.location === 'global');
338
+ expect(agents).toBeDefined();
339
+
340
+ session.isStreaming = true;
341
+ const updated = await ctx.request('resources.update', {
342
+ resourceId: agents.id,
343
+ content: '# Updated while running\\n',
344
+ directory: ctx.cwd,
345
+ });
346
+
347
+ expect(updated.deferred).toBe(true);
348
+ expect(updated.agents.find((agent) => agent.id === agents.id)).toMatchObject({
349
+ id: agents.id,
350
+ content: '# Updated while running\\n',
351
+ });
352
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
353
+ await expect(readFile(join(ctx.agentDir, 'AGENTS.md'), 'utf8')).resolves.toBe('# Updated while running\\n');
354
+
355
+ session.isStreaming = false;
356
+ session.emit({ type: 'agent_settled' });
357
+ await expect.poll(() => ctx.runtimeState.disposeCount).toBe(1);
358
+ expect(ctx.runtimeState.createCount).toBe(2);
359
+ });
360
+
361
+ it('waits for an accepted prompt to finish before recreating the runtime', async () => {
362
+ const session = new FakeSession();
363
+ let finishPrompt;
364
+ session.promptImpl = () => new Promise((resolve) => { finishPrompt = resolve; });
365
+ const ctx = await startDaemon({ session });
366
+ await ctx.request('resources.list', { directory: ctx.cwd });
367
+ await expect(ctx.request('sessions.prompt', { sessionId: session.sessionId, text: '/hold', directory: ctx.cwd })).resolves.toMatchObject({ accepted: true });
368
+
369
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
370
+ const agents = listed.agents.find((agent) => agent.location === 'global');
371
+ const updated = await ctx.request('resources.update', {
372
+ resourceId: agents.id,
373
+ content: '# Updated after prompt acceptance\\n',
374
+ directory: ctx.cwd,
375
+ });
376
+ expect(updated.deferred).toBe(true);
377
+ expect(ctx.runtimeState).toEqual({ createCount: 1, disposeCount: 0 });
378
+
379
+ finishPrompt();
380
+ await expect.poll(() => ctx.runtimeState.disposeCount).toBe(1);
381
+ });
382
+
332
383
  it('defers reload while a non-streaming slash command is still executing', async () => {
333
384
  const session = new FakeSession();
334
385
  let finishPrompt;