@pi-chamber/web 0.9.0 → 0.9.3

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 (106) hide show
  1. package/README.md +24 -8
  2. package/bin/cli.js +11 -1
  3. package/bin/cli.test.js +18 -0
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +7 -3
  6. package/bin/lib/cli-lifecycle.js +3 -0
  7. package/bin/lib/cli-paths.js +28 -6
  8. package/bin/lib/cli-process.js +1 -0
  9. package/bin/lib/cli-tunnel-profiles.js +15 -10
  10. package/bin/lib/commands-connect-url.js +9 -1
  11. package/bin/lib/commands-logs.js +22 -4
  12. package/bin/lib/commands-serve.js +10 -2
  13. package/bin/lib/commands-tunnel.js +14 -0
  14. package/bin/lib/commands-update.js +18 -14
  15. package/bin/lib/commands-update.test.js +2 -1
  16. package/dist/assets/{DiagramEditor-CcbnMl1H.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  17. package/dist/assets/{DiagramView-DTW5jwK3.js → DiagramView-CV-iReyY.js} +1 -1
  18. package/dist/assets/{DiffView-CZyHHAOB.js → DiffView-DVd1MLPB.js} +6 -6
  19. package/dist/assets/{FilesView-BJYLFR3H.js → FilesView-CPnW4I90.js} +1 -1
  20. package/dist/assets/{GitView-Cg_5UU7E.js → GitView-Dj_7hgX_.js} +3 -3
  21. package/dist/assets/JsonTreeView-Cyy0lEZR.js +1 -0
  22. package/dist/assets/{MarkdownRendererImpl-WqBwxlso.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  23. package/dist/assets/{PatchDiff-BRi23N1l.js → PatchDiff-C7dA3U29.js} +1 -1
  24. package/dist/assets/{SessionSwitcherContent-7VAU5pwZ.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  25. package/dist/assets/{SessionSwitcherDropdown-BslRtccE.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  26. package/dist/assets/{SessionUnreadDot-1nV0Z2ZA.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  27. package/dist/assets/SettingsView-C57uV1YS.js +2 -0
  28. package/dist/assets/{SettingsWindow-D4jZHl8X.js → SettingsWindow-Bbay2W76.js} +1 -1
  29. package/dist/assets/ToolOutputDialog-CRTiN1CH.js +8 -0
  30. package/dist/assets/{ToolPartDiffPreview-9FLv2fWD.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  31. package/dist/assets/{VirtualizedFileDiff-ywmPBXAG.js → VirtualizedFileDiff-iqwryMNU.js} +3 -3
  32. package/dist/assets/{collapsible-6mCYf7Ky.js → collapsible-szfZ0Syc.js} +1 -1
  33. package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +3 -0
  34. package/dist/assets/{contextFileOpenGuard-CKyf-TZ7.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  35. package/dist/assets/{gitStatusPredicates-UsytDMy_.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  36. package/dist/assets/{index-C8NYcA8-.css → index-DNoEeZ2U.css} +1 -1
  37. package/dist/assets/{index-yWgKW2Fx.js → index-KIdiBFJs.js} +4 -4
  38. package/dist/assets/{index-D1IaU-Q7.js → index-v6K3L94m.js} +1 -1
  39. package/dist/assets/{isDiffPlainText-DPCilEx_.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  40. package/dist/assets/{isFilePlainText-XdCAgm8R.js → isFilePlainText-CbrmvrM6.js} +1 -1
  41. package/dist/assets/{main-DcAMXRSi.js → main-4PkIvzf4.js} +7 -7
  42. package/dist/assets/{main-DhvLreEl.js → main-DMyWi0qs.js} +2 -2
  43. package/dist/assets/{markdownCore-BF0Dqwm4.js → markdownCore-BD5WkOKU.js} +1 -1
  44. package/dist/assets/{miniChat-DsCx0dsW.js → miniChat-CLMNhna4.js} +2 -2
  45. package/dist/assets/{mobile-C-IN49xX.js → mobile-rWMDwhtQ.js} +2 -2
  46. package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +2 -0
  47. package/dist/assets/{renderMobileApp-xCdVzvyf.js → renderMobileApp-DLy2YoQg.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-CT3WShpj.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  49. package/dist/assets/{runtimeSurface-C_3mcJ01.js → runtimeSurface-CySRuLbN.js} +1 -1
  50. package/dist/assets/{useAppFontEffects-BgK55NDM.js → useAppFontEffects-DfuJVB15.js} +102 -102
  51. package/dist/assets/{useFilesViewSearch-CWx24PZg.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  52. package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +10 -0
  53. package/dist/assets/{useSwitcherItems-CrS-F6DY.js → useSwitcherItems-jITqE8PV.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-language-data-BzeePAPn.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  55. package/dist/assets/{web-components-DAkBDXRk.js → web-components-C9wXMuCp.js} +2 -2
  56. package/dist/index.html +4 -4
  57. package/dist/mini-chat.html +3 -3
  58. package/dist/mobile.html +3 -3
  59. package/package.json +3 -3
  60. package/server/index.js +26 -7
  61. package/server/lib/client-auth/pairing.js +13 -2
  62. package/server/lib/client-auth/remote-clients.js +13 -2
  63. package/server/lib/fs/DOCUMENTATION.md +3 -1
  64. package/server/lib/fs/routes.test.js +74 -0
  65. package/server/lib/git/DOCUMENTATION.md +1 -1
  66. package/server/lib/git/identity-storage.js +10 -1
  67. package/server/lib/package-manager.js +1 -1
  68. package/server/lib/package-manager.test.js +11 -0
  69. package/server/lib/pi/archive-store.js +3 -2
  70. package/server/lib/pi/model-config-store.js +6 -2
  71. package/server/lib/pi/routes.js +46 -3
  72. package/server/lib/pi/routes.test.js +53 -0
  73. package/server/lib/pi/session-daemon/DOCUMENTATION.md +15 -9
  74. package/server/lib/pi/session-daemon/daemon-process.js +48 -13
  75. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  76. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  77. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  78. package/server/lib/pi/session-daemon/session-daemon.js +353 -66
  79. package/server/lib/pi/session-daemon/session-daemon.test.js +348 -0
  80. package/server/lib/pi/session-daemon/session-lease.js +151 -0
  81. package/server/lib/pi/session-daemon/session-lease.test.js +108 -0
  82. package/server/lib/pi/session-daemon/supervisor.js +244 -54
  83. package/server/lib/pi/session-daemon/supervisor.test.js +202 -6
  84. package/server/lib/pi/session-folders-store.js +20 -2
  85. package/server/lib/pi/session-folders-store.test.js +17 -0
  86. package/server/lib/pi/settings-store.js +3 -2
  87. package/server/lib/pi/snippets-store.js +4 -1
  88. package/server/lib/pi/ui-settings-store.js +130 -24
  89. package/server/lib/pi/ui-settings-store.test.js +58 -7
  90. package/server/lib/server/cross-process-lock.js +112 -0
  91. package/server/lib/server/cross-process-lock.test.js +70 -0
  92. package/server/lib/server/server-profile.js +110 -0
  93. package/server/lib/server/server-profile.test.js +58 -0
  94. package/server/lib/server/tunnel-service.DOCUMENTATION.md +7 -8
  95. package/server/lib/server/tunnel-service.js +8 -1
  96. package/server/lib/stt/config-store.js +3 -2
  97. package/server/lib/terminal/DOCUMENTATION.md +1 -1
  98. package/server/lib/tunnels/DOCUMENTATION.md +38 -18
  99. package/server/lib/ui-auth/ui-auth.js +9 -2
  100. package/server/lib/ui-auth/ui-passkeys.js +9 -1
  101. package/dist/assets/JsonTreeView-GTdKGEdy.js +0 -1
  102. package/dist/assets/SettingsView-UIaAyjTo.js +0 -2
  103. package/dist/assets/ToolOutputDialog-BoeJONiR.js +0 -8
  104. package/dist/assets/computeVirtualFileMetrics-3H6mg13G.js +0 -3
  105. package/dist/assets/renderElectronMiniChatApp-C13HXGZL.js +0 -2
  106. package/dist/assets/usePushVisibilityBeacon-swMQLm-i.js +0 -10
@@ -26,10 +26,19 @@ import {
26
26
  import { createPiModelConfigStore } from '../model-config-store.js';
27
27
  import { clampThinkingLevel, getSupportedThinkingLevels, isPiThinkingLevel } from '../thinking-levels.js';
28
28
  import { createExtensionBridge } from './extension-bridge.js';
29
+ import {
30
+ SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT,
31
+ SESSION_DAEMON_MAX_FRAME_BYTES as MAX_FRAME_BYTES,
32
+ SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT,
33
+ SESSION_DAEMON_MESSAGE_PAGE_TARGET_BYTES,
34
+ SESSION_DAEMON_PROTOCOL_VERSION as PROTOCOL_VERSION,
35
+ } from './ipc-protocol.js';
29
36
  import { createMessageEntryAliases } from './message-entry-aliases.js';
30
37
  import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
31
38
  import { createSkillReadClassifier } from './skill-read-classifier.js';
32
39
  import { createSessionRuntimeRegistry } from './runtime-registry.js';
40
+ import { acquireSessionLease, releaseSessionLease } from './session-lease.js';
41
+ import { withCrossProcessLock } from '../../server/cross-process-lock.js';
33
42
  import {
34
43
  findPiSessionJsonlById,
35
44
  getPiSessionDirectory,
@@ -39,8 +48,6 @@ import {
39
48
  } from './session-jsonl.js';
40
49
  import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
41
50
 
42
- const PROTOCOL_VERSION = 1;
43
-
44
51
  const textFromContent = (content) => (
45
52
  Array.isArray(content)
46
53
  ? content.filter((part) => part?.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('')
@@ -85,8 +92,6 @@ try {
85
92
  }
86
93
  } catch {}
87
94
 
88
- const MAX_FRAME_BYTES = 16 * 1024 * 1024;
89
-
90
95
  class SessionDaemonProtocolError extends Error {
91
96
  constructor(code, message) {
92
97
  super(message);
@@ -148,6 +153,14 @@ export function createSessionDaemon({
148
153
  agentDir = getAgentDir(),
149
154
  createRuntime: injectCreateRuntime,
150
155
  healthMetadata = {},
156
+ profileKey,
157
+ serverInstanceId,
158
+ serverPid,
159
+ daemonId,
160
+ daemonRuntime,
161
+ buildId,
162
+ onOwnershipClaim,
163
+ onShutdown,
151
164
  idleTimeoutMs = 5 * 60 * 1_000,
152
165
  listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
153
166
  cwd: sessionCwd,
@@ -165,6 +178,14 @@ export function createSessionDaemon({
165
178
  manager.appendSessionInfo(title);
166
179
  },
167
180
  platform = process.platform,
181
+ isServerProcessAlive = (pid) => {
182
+ try {
183
+ process.kill(pid, 0);
184
+ return true;
185
+ } catch (error) {
186
+ return error?.code === 'EPERM';
187
+ }
188
+ },
168
189
  } = {}) {
169
190
  if (!isLocalSessionDaemonEndpoint(endpoint, platform)) {
170
191
  throw new SessionDaemonProtocolError('INVALID_ENDPOINT', 'The session daemon endpoint must be local.');
@@ -181,6 +202,45 @@ export function createSessionDaemon({
181
202
 
182
203
  let server;
183
204
  let runtime;
205
+ let ownerServerInstanceId = typeof serverInstanceId === 'string' && serverInstanceId.length > 0 ? serverInstanceId : null;
206
+ let ownerServerPid = Number.isInteger(serverPid) && serverPid > 0 ? serverPid : null;
207
+ const leaseOwner = () => {
208
+ if (typeof profileKey !== 'string' || profileKey.length === 0) return null;
209
+ if (typeof daemonId !== 'string' || daemonId.length === 0) return null;
210
+ if (typeof ownerServerInstanceId !== 'string' || ownerServerInstanceId.length === 0) return null;
211
+ return {
212
+ profileKey,
213
+ serverInstanceId: ownerServerInstanceId,
214
+ daemonId,
215
+ daemonPid: process.pid,
216
+ };
217
+ };
218
+ // Exclusive cross-daemon ownership of one resident session. The session
219
+ // stays visible in listings; contention reports SESSION_IN_USE instead of
220
+ // pretending the session is absent or idle.
221
+ const acquireResidentLease = async ({ cwd: leaseCwd, sessionId }) => {
222
+ const owner = leaseOwner();
223
+ if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return;
224
+ let result;
225
+ try {
226
+ result = await acquireSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
227
+ } catch (error) {
228
+ throw new SessionDaemonProtocolError('SESSION_LEASE_UNAVAILABLE', 'The session ownership check is temporarily unavailable.');
229
+ }
230
+ if (!result.acquired) {
231
+ throw new SessionDaemonProtocolError('SESSION_IN_USE', 'Another PiChamber instance is currently using this session.');
232
+ }
233
+ };
234
+ const releaseResidentLease = async ({ cwd: leaseCwd, sessionId }) => {
235
+ const owner = leaseOwner();
236
+ if (!owner || typeof sessionId !== 'string' || sessionId.length === 0) return;
237
+ try {
238
+ await releaseSessionLease({ agentDir, cwd: leaseCwd, sessionId, owner });
239
+ } catch {
240
+ // Lease release is best-effort; a stale lease is reclaimable by the
241
+ // next owner once this daemon pid is dead.
242
+ }
243
+ };
184
244
  let runtimeRegistry;
185
245
  let runtimeStartPromise;
186
246
  let idleDisposeTimer;
@@ -435,6 +495,7 @@ export function createSessionDaemon({
435
495
  dormantSession = {
436
496
  sessionId,
437
497
  sessionFile: runtime.session.sessionManager?.getSessionFile?.(),
498
+ cwd: runtime.cwd || activeDirectory || cwd,
438
499
  };
439
500
  };
440
501
 
@@ -448,8 +509,7 @@ export function createSessionDaemon({
448
509
  const retry = session.sessionId ? retryStateBySession.get(session.sessionId) : undefined;
449
510
  const compaction = compactionStateFor(activeSession);
450
511
  const targetDirectory = targetRuntime?.cwd || activeDirectory || cwd;
451
- const messages = activeSession ? projectMessageEntries(targetRuntime || runtime, targetDirectory) : [];
452
- const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
512
+ const lastAssistant = activeSession ? projectLatestAssistantMessage(targetRuntime || runtime) : undefined;
453
513
  const model = activeSession?.model;
454
514
  const snapshotSequence = ++sequence;
455
515
  // Snapshot must carry enough extension live state for a reconnect that
@@ -510,6 +570,19 @@ export function createSessionDaemon({
510
570
  await resourceReloadQueue.catch(() => {});
511
571
  resourceReloadsByRuntime.clear();
512
572
  clearExtensionState(undefined);
573
+ const leased = [];
574
+ try {
575
+ for (const tracked of runtimeRegistry?.listAll?.() ?? []) {
576
+ if (typeof tracked?.session?.sessionId === 'string') {
577
+ leased.push({ cwd: tracked.cwd || activeDirectory || cwd, sessionId: tracked.session.sessionId });
578
+ }
579
+ }
580
+ } catch {
581
+ // Registry enumeration must never block teardown.
582
+ }
583
+ if (runtime && typeof runtime.session?.sessionId === 'string') {
584
+ leased.push({ cwd: runtime.cwd || activeDirectory || cwd, sessionId: runtime.session.sessionId });
585
+ }
513
586
  if (runtimeRegistry) {
514
587
  const hadTrackedRuntime = runtimeRegistry.size > 0;
515
588
  await runtimeRegistry.disposeAll();
@@ -519,22 +592,39 @@ export function createSessionDaemon({
519
592
  await runtime?.dispose?.();
520
593
  }
521
594
  runtime = undefined;
595
+ for (const lease of leased) {
596
+ await releaseResidentLease(lease);
597
+ }
522
598
  };
523
599
 
524
600
  const startRuntime = async ({ cwd: runtimeCwd = activeDirectory || cwd, sessionFile } = {}) => {
525
601
  if (sessionFile) await validatePiSessionJsonlFile(sessionFile);
526
- const newRuntime = await createRuntime({ cwd: runtimeCwd, agentDir, ...(sessionFile ? { sessionFile } : {}) });
602
+ const canonicalRuntimeCwd = sessionFile && dormantSession?.cwd
603
+ ? dormantSession.cwd
604
+ : runtimeCwd;
605
+ if (sessionFile && dormantSession?.sessionId) {
606
+ await acquireResidentLease({ cwd: canonicalRuntimeCwd, sessionId: dormantSession.sessionId });
607
+ }
608
+ let newRuntime;
609
+ try {
610
+ newRuntime = await createRuntime({ cwd: canonicalRuntimeCwd, agentDir, ...(sessionFile ? { sessionFile } : {}) });
611
+ } catch (error) {
612
+ if (sessionFile && dormantSession?.sessionId) {
613
+ await releaseResidentLease({ cwd: canonicalRuntimeCwd, sessionId: dormantSession.sessionId });
614
+ }
615
+ throw error;
616
+ }
527
617
  if (!newRuntime.cwd) {
528
- newRuntime.cwd = runtimeCwd;
618
+ newRuntime.cwd = canonicalRuntimeCwd;
529
619
  }
530
620
  if (!runtimeRegistry) {
531
621
  runtimeRegistry = createSessionRuntimeRegistry({
532
622
  onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
533
623
  });
534
624
  }
535
- runtimeRegistry.register(newRuntime, { cwd: runtimeCwd });
625
+ runtimeRegistry.register(newRuntime, { cwd: canonicalRuntimeCwd });
536
626
  runtime = newRuntime;
537
- activeDirectory = runtimeCwd;
627
+ activeDirectory = canonicalRuntimeCwd;
538
628
  rememberRuntimeSession();
539
629
  return newRuntime;
540
630
  };
@@ -643,6 +733,7 @@ export function createSessionDaemon({
643
733
  if (targetRuntime === runtime) rememberRuntimeSession();
644
734
  clearExtensionState(sessionId);
645
735
  await runtimeRegistry.dispose(targetRuntime);
736
+ await releaseResidentLease({ cwd: targetRuntime.cwd || activeDirectory || cwd, sessionId });
646
737
  shutdownRequestedBySession.delete(sessionId);
647
738
  compactionStateBySession.delete(sessionId);
648
739
  if (targetRuntime === runtime) runtime = undefined;
@@ -892,10 +983,17 @@ export function createSessionDaemon({
892
983
  return existingAnywhere;
893
984
  }
894
985
  const { target, directory } = await findPersistedSession(sessionId, requestedDirectory);
895
- const newRuntime = await createRuntime({ cwd: directory, agentDir, sessionFile: target.path });
896
- if (!newRuntime.cwd) newRuntime.cwd = directory;
897
- if (newRuntime.session?.sessionId !== sessionId && typeof newRuntime.switchSession === 'function') {
898
- await newRuntime.switchSession(target.path);
986
+ await acquireResidentLease({ cwd: directory, sessionId });
987
+ let newRuntime;
988
+ try {
989
+ newRuntime = await createRuntime({ cwd: directory, agentDir, sessionFile: target.path });
990
+ if (!newRuntime.cwd) newRuntime.cwd = directory;
991
+ if (newRuntime.session?.sessionId !== sessionId && typeof newRuntime.switchSession === 'function') {
992
+ await newRuntime.switchSession(target.path);
993
+ }
994
+ } catch (error) {
995
+ await releaseResidentLease({ cwd: directory, sessionId });
996
+ throw error;
899
997
  }
900
998
  const raced = runtimeRegistry.findBySessionId(sessionId);
901
999
  if (raced) {
@@ -917,6 +1015,7 @@ export function createSessionDaemon({
917
1015
  return winner;
918
1016
  }
919
1017
  }
1018
+ await releaseResidentLease({ cwd: directory, sessionId });
920
1019
  throw error;
921
1020
  }
922
1021
  runtime = newRuntime;
@@ -975,6 +1074,24 @@ export function createSessionDaemon({
975
1074
  return entries;
976
1075
  };
977
1076
 
1077
+ const projectLatestAssistantMessage = (activeRuntime) => {
1078
+ const session = activeRuntime?.session;
1079
+ const persisted = session?.sessionManager?.getBranch?.() ?? session?.sessionManager?.getEntries?.();
1080
+ const entries = liveProjectionEntries(session, Array.isArray(persisted) ? persisted : []);
1081
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1082
+ const message = entries[index]?.message;
1083
+ if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;
1084
+ return {
1085
+ text: redactAttachmentPaths(textFromContent(message.content)),
1086
+ thinking: redactAttachmentPaths(message.content
1087
+ .filter((part) => part?.type === 'thinking')
1088
+ .map((part) => part.thinking)
1089
+ .join('')),
1090
+ };
1091
+ }
1092
+ return undefined;
1093
+ };
1094
+
978
1095
  const projectMessageEntries = (activeRuntime, targetDir = activeDirectory || cwd) => {
979
1096
  const session = activeRuntime?.session;
980
1097
  // Use the active branch, not the full file. `getEntries()` returns every
@@ -1130,7 +1247,67 @@ export function createSessionDaemon({
1130
1247
  });
1131
1248
  };
1132
1249
 
1133
- const projectActiveSession = (activeRuntime = runtime, targetDir = activeRuntime?.cwd || activeDirectory || cwd) => {
1250
+ const projectMessagePage = (messages, options = {}) => {
1251
+ const requestedLimit = options.limit ?? SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT;
1252
+ if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || requestedLimit > SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT) {
1253
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', `The message page limit must be between 1 and ${SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT}.`);
1254
+ }
1255
+ let end = messages.length;
1256
+ if (options.before !== undefined) {
1257
+ if (typeof options.before !== 'string' || options.before.length === 0) {
1258
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The message page cursor is invalid.');
1259
+ }
1260
+ end = messages.findIndex((entry) => entry?.message?.id === options.before);
1261
+ if (end < 0) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The message page cursor is stale.');
1262
+ }
1263
+
1264
+ let start = end;
1265
+ let pageBytes = 2;
1266
+ while (start > 0 && end - start < requestedLimit) {
1267
+ const candidate = messages[start - 1];
1268
+ const candidateBytes = Buffer.byteLength(JSON.stringify(candidate));
1269
+ if (start < end && pageBytes + candidateBytes + 1 > SESSION_DAEMON_MESSAGE_PAGE_TARGET_BYTES) break;
1270
+ start -= 1;
1271
+ pageBytes += candidateBytes + (start + 1 < end ? 1 : 0);
1272
+ }
1273
+ const selected = messages.slice(start, end);
1274
+ let anchorIndex = -1;
1275
+ const firstMessage = selected[0]?.message;
1276
+ if (firstMessage?.role === 'assistant' && typeof firstMessage.parentId === 'string') {
1277
+ anchorIndex = messages.findIndex((entry, index) => index < start && entry?.message?.id === firstMessage.parentId);
1278
+ if (anchorIndex >= 0) selected.unshift(messages[anchorIndex]);
1279
+ }
1280
+ const beginsAtAdjacentAnchor = anchorIndex === start - 1;
1281
+ const cursorIndex = beginsAtAdjacentAnchor ? anchorIndex : start;
1282
+ const hasMoreBefore = cursorIndex > 0;
1283
+ return {
1284
+ messages: selected,
1285
+ hasMoreBefore,
1286
+ ...(hasMoreBefore ? { beforeCursor: messages[cursorIndex]?.message?.id } : {}),
1287
+ };
1288
+ };
1289
+
1290
+ const writeDetailResponse = (socket, requestId, detail) => {
1291
+ const frame = {
1292
+ protocolVersion: PROTOCOL_VERSION,
1293
+ kind: 'response',
1294
+ requestId,
1295
+ result: detail,
1296
+ };
1297
+ if (Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES) {
1298
+ throw new SessionDaemonProtocolError(
1299
+ 'DAEMON_RESPONSE_TOO_LARGE',
1300
+ 'The daemon response exceeds the IPC frame limit.',
1301
+ );
1302
+ }
1303
+ writeFrame(socket, frame);
1304
+ };
1305
+
1306
+ const projectActiveSession = (
1307
+ activeRuntime = runtime,
1308
+ targetDir = activeRuntime?.cwd || activeDirectory || cwd,
1309
+ pageOptions = {},
1310
+ ) => {
1134
1311
  const session = activeRuntime?.session;
1135
1312
  const manager = session?.sessionManager;
1136
1313
  const header = manager?.getHeader?.();
@@ -1139,8 +1316,16 @@ export function createSessionDaemon({
1139
1316
  throw new SessionDaemonProtocolError('INVALID_SESSION', 'Pi returned an invalid active session.');
1140
1317
  }
1141
1318
  const model = session.model;
1142
- const messages = projectMessageEntries(activeRuntime, targetDir);
1143
- const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
1319
+ const allMessages = projectMessageEntries(activeRuntime, targetDir);
1320
+ const page = projectMessagePage(allMessages, pageOptions);
1321
+ let lastAssistant;
1322
+ for (let index = allMessages.length - 1; index >= 0; index -= 1) {
1323
+ const candidate = allMessages[index]?.message;
1324
+ if (candidate?.role === 'assistant') {
1325
+ lastAssistant = candidate;
1326
+ break;
1327
+ }
1328
+ }
1144
1329
  const sessionModel = lastAssistant?.model
1145
1330
  ?? (model?.provider && model?.id ? { providerId: model.provider, modelId: model.id } : undefined);
1146
1331
  const sessionThinking = lastAssistant?.thinkingLevel || session.thinkingLevel;
@@ -1154,9 +1339,10 @@ export function createSessionDaemon({
1154
1339
  ...(session.sessionName ? { title: session.sessionName } : {}),
1155
1340
  ...(sessionModel ? { model: sessionModel } : {}),
1156
1341
  ...(sessionThinking ? { thinking: sessionThinking } : {}),
1157
- messageCount: messages.length,
1342
+ messageCount: allMessages.length,
1158
1343
  },
1159
- messages,
1344
+ messages: page.messages,
1345
+ ...(page.hasMoreBefore ? { hasMoreBefore: true, beforeCursor: page.beforeCursor } : {}),
1160
1346
  lastSequence: sequence,
1161
1347
  isStreaming,
1162
1348
  lifecycle: retry ? 'retry' : isStreaming ? 'busy' : 'idle',
@@ -1232,6 +1418,12 @@ export function createSessionDaemon({
1232
1418
  newRuntime.session.sessionManager.appendSessionInfo(payload.title.trim());
1233
1419
  }
1234
1420
  if (result?.cancelled) throw new SessionDaemonProtocolError('SESSION_CREATE_CANCELLED', 'Pi cancelled session creation.');
1421
+ try {
1422
+ await acquireResidentLease({ cwd: targetCwd, sessionId: newRuntime.session.sessionId });
1423
+ } catch (error) {
1424
+ try { await newRuntime.dispose?.(); } catch { /* the failed create owns nothing */ }
1425
+ throw error;
1426
+ }
1235
1427
  if (payload.model) {
1236
1428
  await setSessionModel(newRuntime, payload.model);
1237
1429
  publishSessionModel(newRuntime.session, newRuntime.session.sessionId, targetCwd);
@@ -1602,36 +1794,42 @@ export function createSessionDaemon({
1602
1794
  throw new SessionDaemonProtocolError('SESSION_BUSY', 'Project trust cannot change during an active session.');
1603
1795
  }
1604
1796
  }
1605
- const trustStore = createTrustStore(agentDir);
1606
- if (hasTrust) trustStore.set(targetDir, payload.trust);
1607
- const trusted = trustStore.get(targetDir) === true;
1608
- if (payload.scope === 'project' && !trusted && (hasModel || hasThinking)) {
1609
- throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
1610
- }
1611
- if (hasModel || hasThinking) {
1612
- const manager = createSettingsManager({ cwd: targetDir, agentDir, projectTrusted: trusted });
1613
- if (payload.scope === 'global') {
1614
- if (hasModel) manager.setDefaultModelAndProvider(payload.defaultModel?.providerId, payload.defaultModel?.modelId);
1615
- if (hasThinking) manager.setDefaultThinkingLevel(payload.defaultThinking ?? undefined);
1616
- } else {
1617
- if (hasModel) {
1618
- manager.updateProjectSettings('defaultProvider', (settings) => {
1619
- if (payload.defaultModel === null) delete settings.defaultProvider;
1620
- else settings.defaultProvider = payload.defaultModel.providerId;
1621
- });
1622
- manager.updateProjectSettings('defaultModel', (settings) => {
1623
- if (payload.defaultModel === null) delete settings.defaultModel;
1624
- else settings.defaultModel = payload.defaultModel.modelId;
1797
+ // Pi settings and trust live under the shared agent directory: read the
1798
+ // current files and commit inside the shared lock so concurrent daemons
1799
+ // cannot interleave read-modify-write cycles.
1800
+ const trusted = await withSharedPiConfigLock(async () => {
1801
+ const trustStore = createTrustStore(agentDir);
1802
+ if (hasTrust) trustStore.set(targetDir, payload.trust);
1803
+ const isTrusted = trustStore.get(targetDir) === true;
1804
+ if (payload.scope === 'project' && !isTrusted && (hasModel || hasThinking)) {
1805
+ throw new SessionDaemonProtocolError('PROJECT_UNTRUSTED', 'The project is not trusted.');
1806
+ }
1807
+ if (hasModel || hasThinking) {
1808
+ const manager = createSettingsManager({ cwd: targetDir, agentDir, projectTrusted: isTrusted });
1809
+ if (payload.scope === 'global') {
1810
+ if (hasModel) manager.setDefaultModelAndProvider(payload.defaultModel?.providerId, payload.defaultModel?.modelId);
1811
+ if (hasThinking) manager.setDefaultThinkingLevel(payload.defaultThinking ?? undefined);
1812
+ } else {
1813
+ if (hasModel) {
1814
+ manager.updateProjectSettings('defaultProvider', (settings) => {
1815
+ if (payload.defaultModel === null) delete settings.defaultProvider;
1816
+ else settings.defaultProvider = payload.defaultModel.providerId;
1817
+ });
1818
+ manager.updateProjectSettings('defaultModel', (settings) => {
1819
+ if (payload.defaultModel === null) delete settings.defaultModel;
1820
+ else settings.defaultModel = payload.defaultModel.modelId;
1821
+ });
1822
+ }
1823
+ if (hasThinking) manager.updateProjectSettings('defaultThinkingLevel', (settings) => {
1824
+ if (payload.defaultThinking === null) delete settings.defaultThinkingLevel;
1825
+ else settings.defaultThinkingLevel = payload.defaultThinking;
1625
1826
  });
1626
1827
  }
1627
- if (hasThinking) manager.updateProjectSettings('defaultThinkingLevel', (settings) => {
1628
- if (payload.defaultThinking === null) delete settings.defaultThinkingLevel;
1629
- else settings.defaultThinkingLevel = payload.defaultThinking;
1630
- });
1828
+ await manager.flush();
1829
+ if (manager.drainErrors().length > 0) throw new SessionDaemonProtocolError('PI_SETTINGS_INVALID', 'Pi settings could not be written.');
1631
1830
  }
1632
- await manager.flush();
1633
- if (manager.drainErrors().length > 0) throw new SessionDaemonProtocolError('PI_SETTINGS_INVALID', 'Pi settings could not be written.');
1634
- }
1831
+ return isTrusted;
1832
+ });
1635
1833
  if (hasTrust && runtime) {
1636
1834
  await disposeRuntime();
1637
1835
  await ensureRuntime();
@@ -1743,7 +1941,16 @@ export function createSessionDaemon({
1743
1941
  return pending;
1744
1942
  };
1745
1943
 
1746
- const writeResourceFile = async (filePath, content) => {
1944
+ // Pi prompt and context files live under the shared agent directory (or a
1945
+ // shared project directory), so concurrent daemons serialize here rather
1946
+ // than in-process only. The lock is deliberately coarse: resource edits
1947
+ // are rare user-driven writes, never streaming hot paths.
1948
+ const withSharedPiConfigLock = (operation) => withCrossProcessLock(
1949
+ join(agentDir, '.pichamber', 'locks', 'pi-config.lock'),
1950
+ operation,
1951
+ );
1952
+
1953
+ const writeResourceFile = async (filePath, content) => withSharedPiConfigLock(async () => {
1747
1954
  const temporary = `${filePath}.${randomUUID()}.tmp`;
1748
1955
  await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });
1749
1956
  try {
@@ -1753,9 +1960,9 @@ export function createSessionDaemon({
1753
1960
  await rm(temporary, { force: true }).catch(() => {});
1754
1961
  throw error;
1755
1962
  }
1756
- };
1963
+ });
1757
1964
 
1758
- const writeNewResourceFile = async (filePath, content) => {
1965
+ const writeNewResourceFile = async (filePath, content) => withSharedPiConfigLock(async () => {
1759
1966
  const temporary = `${filePath}.${randomUUID()}.tmp`;
1760
1967
  await mkdir(dirname(filePath), { recursive: true, mode: 0o700 });
1761
1968
  try {
@@ -1769,7 +1976,7 @@ export function createSessionDaemon({
1769
1976
  throw error;
1770
1977
  }
1771
1978
  await rm(temporary, { force: true }).catch(() => {});
1772
- };
1979
+ });
1773
1980
 
1774
1981
  const refreshResources = async (targetDir) => {
1775
1982
  servicesCache.delete(targetDir || activeDirectory || cwd);
@@ -2404,9 +2611,16 @@ export function createSessionDaemon({
2404
2611
  } else if (!active) {
2405
2612
  const { target, directory } = await findPersistedSession(sessionId, targetDir);
2406
2613
  targetDir = directory;
2407
- await rm(target.path, { force: false });
2614
+ await acquireResidentLease({ cwd: targetDir, sessionId });
2615
+ try {
2616
+ await rm(target.path, { force: false });
2617
+ } catch (error) {
2618
+ await releaseResidentLease({ cwd: targetDir, sessionId });
2619
+ throw error;
2620
+ }
2408
2621
  }
2409
2622
  messageEntryAliases.clearSession({ cwd: active?.cwd || targetDir, sessionId });
2623
+ await releaseResidentLease({ cwd: active?.cwd || targetDir, sessionId });
2410
2624
  retryStateBySession.delete(sessionId);
2411
2625
  compactionStateBySession.delete(sessionId);
2412
2626
  activeRunStartedAt.delete(sessionId);
@@ -2747,7 +2961,8 @@ export function createSessionDaemon({
2747
2961
  sessionId: getSessionState().sessionId,
2748
2962
  lastSequence: sequence,
2749
2963
  capabilities: [
2750
- 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.rename', 'sessions.delete',
2964
+ 'runtime.claim', 'runtime.shutdown',
2965
+ 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
2751
2966
  'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
2752
2967
  'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
2753
2968
  'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
@@ -2756,9 +2971,66 @@ export function createSessionDaemon({
2756
2971
  'extensions.list', 'extensions.respond',
2757
2972
  ],
2758
2973
  ...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
2974
+ ...(typeof profileKey === 'string' && profileKey.length > 0 ? { profileKey } : {}),
2975
+ ...(typeof daemonId === 'string' && daemonId.length > 0 ? { daemonId } : {}),
2976
+ ...(typeof ownerServerInstanceId === 'string' && ownerServerInstanceId.length > 0 ? { serverInstanceId: ownerServerInstanceId } : {}),
2977
+ ...(Number.isInteger(ownerServerPid) && ownerServerPid > 0 ? { serverPid: ownerServerPid } : {}),
2978
+ ...(typeof daemonRuntime === 'string' && daemonRuntime.length > 0 ? { runtime: daemonRuntime } : {}),
2979
+ ...(typeof buildId === 'string' && buildId.length > 0 ? { buildId } : {}),
2759
2980
  },
2760
2981
  });
2761
2982
  return;
2983
+ case 'runtime.claim': {
2984
+ const nextOwner = message.payload?.serverInstanceId;
2985
+ const nextServerPid = message.payload?.serverPid;
2986
+ if (typeof nextOwner !== 'string' || nextOwner.length === 0
2987
+ || !Number.isInteger(nextServerPid) || nextServerPid <= 0) {
2988
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The claiming server instance is invalid.');
2989
+ }
2990
+ if (ownerServerInstanceId !== null && nextOwner !== ownerServerInstanceId
2991
+ && ownerServerPid !== null && isServerProcessAlive(ownerServerPid)) {
2992
+ throw new SessionDaemonProtocolError('OWNERSHIP_CONFLICT', 'The current server still owns this daemon.');
2993
+ }
2994
+ await onOwnershipClaim?.({ serverInstanceId: nextOwner, serverPid: nextServerPid });
2995
+ ownerServerInstanceId = nextOwner;
2996
+ ownerServerPid = nextServerPid;
2997
+ writeFrame(socket, {
2998
+ protocolVersion: PROTOCOL_VERSION,
2999
+ kind: 'response',
3000
+ requestId: message.requestId,
3001
+ result: { claimed: true, serverInstanceId: ownerServerInstanceId, serverPid: ownerServerPid },
3002
+ });
3003
+ return;
3004
+ }
3005
+ case 'runtime.shutdown': {
3006
+ const caller = message.payload?.serverInstanceId;
3007
+ const callerDaemon = message.payload?.daemonId;
3008
+ if (typeof caller !== 'string' || caller.length === 0) {
3009
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The shutting-down server instance is invalid.');
3010
+ }
3011
+ if ((ownerServerInstanceId !== null && caller !== ownerServerInstanceId)
3012
+ || (typeof daemonId === 'string' && daemonId.length > 0 && callerDaemon !== daemonId)) {
3013
+ throw new SessionDaemonProtocolError('OWNERSHIP_MISMATCH', 'The daemon is owned by another server instance.');
3014
+ }
3015
+ writeFrame(socket, {
3016
+ protocolVersion: PROTOCOL_VERSION,
3017
+ kind: 'response',
3018
+ requestId: message.requestId,
3019
+ result: { shutdown: true },
3020
+ });
3021
+ if (typeof onShutdown === 'function') {
3022
+ const shutdownHook = onShutdown;
3023
+ setImmediate(() => {
3024
+ try {
3025
+ shutdownHook();
3026
+ } catch {
3027
+ // Shutdown hooks own their own error handling; the response
3028
+ // has already been delivered.
3029
+ }
3030
+ });
3031
+ }
3032
+ return;
3033
+ }
2762
3034
  case 'projects.list':
2763
3035
  writeFrame(socket, {
2764
3036
  protocolVersion: PROTOCOL_VERSION,
@@ -2915,7 +3187,19 @@ export function createSessionDaemon({
2915
3187
  }
2916
3188
  case 'sessions.open': {
2917
3189
  const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
2918
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: projectActiveSession(activeRuntime, activeRuntime.cwd) });
3190
+ writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit }));
3191
+ return;
3192
+ }
3193
+ case 'sessions.messages': {
3194
+ const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
3195
+ const detail = projectActiveSession(activeRuntime, activeRuntime.cwd, {
3196
+ before: message.payload?.before,
3197
+ limit: message.payload?.limit,
3198
+ });
3199
+ writeDetailResponse(socket, message.requestId, {
3200
+ ...detail,
3201
+ hasMoreBefore: detail.hasMoreBefore === true,
3202
+ });
2919
3203
  return;
2920
3204
  }
2921
3205
  case 'sessions.rename': {
@@ -2953,7 +3237,7 @@ export function createSessionDaemon({
2953
3237
  newLeafId: typeof newLeafId === 'string' ? newLeafId : null,
2954
3238
  ...(typeof result?.editorText === 'string' && result.editorText.length > 0 ? { editorText: result.editorText } : {}),
2955
3239
  };
2956
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { ...projectActiveSession(activeRuntime, activeRuntime.cwd), navigation } });
3240
+ writeDetailResponse(socket, message.requestId, { ...projectActiveSession(activeRuntime, activeRuntime.cwd), navigation });
2957
3241
  return;
2958
3242
  }
2959
3243
  case 'sessions.fork':
@@ -2971,18 +3255,16 @@ export function createSessionDaemon({
2971
3255
  : requestedId;
2972
3256
  const result = await activeRuntime.fork(entryId, { position: 'at' });
2973
3257
  if (result.cancelled) throw new SessionDaemonProtocolError('SESSION_CREATE_CANCELLED', 'Pi cancelled session creation.');
3258
+ if (typeof activeRuntime.session?.sessionId === 'string') {
3259
+ await acquireResidentLease({ cwd: activeRuntime.cwd, sessionId: activeRuntime.session.sessionId });
3260
+ }
2974
3261
  rememberRuntimeSession();
2975
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: projectActiveSession(activeRuntime, activeRuntime.cwd) });
3262
+ writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd));
2976
3263
  return;
2977
3264
  }
2978
3265
  case 'sessions.create': {
2979
3266
  const result = await createSession(message.payload);
2980
- writeFrame(socket, {
2981
- protocolVersion: PROTOCOL_VERSION,
2982
- kind: 'response',
2983
- requestId: message.requestId,
2984
- result,
2985
- });
3267
+ writeDetailResponse(socket, message.requestId, result);
2986
3268
  return;
2987
3269
  }
2988
3270
  case 'sessions.prompt':
@@ -3074,17 +3356,22 @@ export function createSessionDaemon({
3074
3356
 
3075
3357
  socket.on('data', (chunk) => {
3076
3358
  buffer += decoder.write(chunk);
3077
- if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
3078
- reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3079
- return;
3080
- }
3081
3359
 
3082
3360
  while (true) {
3083
3361
  const newline = buffer.indexOf('\n');
3084
- if (newline === -1) break;
3362
+ if (newline === -1) {
3363
+ if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
3364
+ reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3365
+ }
3366
+ break;
3367
+ }
3085
3368
  const line = buffer.slice(0, newline).replace(/\r$/, '');
3086
3369
  buffer = buffer.slice(newline + 1);
3087
3370
  if (line.length === 0) continue;
3371
+ if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
3372
+ reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3373
+ return;
3374
+ }
3088
3375
 
3089
3376
  try {
3090
3377
  const message = JSON.parse(line);