@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
@@ -26,6 +26,13 @@ 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';
@@ -41,8 +48,6 @@ import {
41
48
  } from './session-jsonl.js';
42
49
  import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
43
50
 
44
- const PROTOCOL_VERSION = 1;
45
-
46
51
  const textFromContent = (content) => (
47
52
  Array.isArray(content)
48
53
  ? content.filter((part) => part?.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('')
@@ -87,8 +92,6 @@ try {
87
92
  }
88
93
  } catch {}
89
94
 
90
- const MAX_FRAME_BYTES = 16 * 1024 * 1024;
91
-
92
95
  class SessionDaemonProtocolError extends Error {
93
96
  constructor(code, message) {
94
97
  super(message);
@@ -255,6 +258,35 @@ export function createSessionDaemon({
255
258
  const latestAssistantMessageIds = new Map();
256
259
  const messageStartedAt = new Map();
257
260
  const toolStartedAt = new Map();
261
+ // Keep recent starts long enough for a second client or a browser reload to
262
+ // hydrate a just-finished tool, but do not let a long-lived daemon grow with
263
+ // every tool call.
264
+ const completedToolTimings = new Map();
265
+ const MAX_COMPLETED_TOOL_TIMINGS = 2048;
266
+ const toolTimingKey = (sessionId, toolCallId) => `${sessionId}\u0000${toolCallId}`;
267
+ const clearToolTimingsForSession = (sessionId, { keepCompleted = false } = {}) => {
268
+ const prefix = `${sessionId}\u0000`;
269
+ for (const key of toolStartedAt.keys()) {
270
+ if (key.startsWith(prefix)) toolStartedAt.delete(key);
271
+ }
272
+ if (!keepCompleted) {
273
+ for (const key of completedToolTimings.keys()) {
274
+ if (key.startsWith(prefix)) completedToolTimings.delete(key);
275
+ }
276
+ }
277
+ };
278
+ const rememberCompletedToolTiming = (sessionId, toolCallId, startedAt, endedAt) => {
279
+ if (!Number.isFinite(startedAt)) return;
280
+ completedToolTimings.set(toolTimingKey(sessionId, toolCallId), {
281
+ startedAt,
282
+ ...(Number.isFinite(endedAt) ? { endedAt } : {}),
283
+ });
284
+ while (completedToolTimings.size > MAX_COMPLETED_TOOL_TIMINGS) {
285
+ const oldest = completedToolTimings.keys().next();
286
+ if (oldest.done) break;
287
+ completedToolTimings.delete(oldest.value);
288
+ }
289
+ };
258
290
  const toolInputBySession = new Map();
259
291
  const latestUserMessageIds = new Map();
260
292
  const retryStateBySession = new Map();
@@ -264,11 +296,19 @@ export function createSessionDaemon({
264
296
  const settledSendGenerationBySession = new Map();
265
297
  // Pi's reload() is identity-preserving but is not safe during a turn,
266
298
  // compaction, or an extension command. Prompt writes mark affected busy
267
- // runtimes dirty and reload them at the next safe lifecycle edge.
299
+ // runtimes dirty and reload them at the next safe lifecycle edge. Other
300
+ // Pi configuration writes queue resident-runtime recreation at that edge.
268
301
  const activeSessionInputs = new Map();
269
302
  const pendingResourceReloads = new Set();
270
303
  const resourceReloadsByRuntime = new Map();
271
304
  let resourceReloadQueue = Promise.resolve();
305
+ // File-backed Pi configuration can be committed while a session is busy,
306
+ // but replacing all resident runtimes must wait until every active runtime
307
+ // is idle. The revision lets a second write that arrives during a rebuild
308
+ // trigger one more rebuild instead of being lost behind the first one.
309
+ let pendingRuntimeRecreation = false;
310
+ let runtimeRecreationRevision = 0;
311
+ let runtimeRecreationTask = null;
272
312
  // Pi emits each user message start before its persisted entry is readable.
273
313
  // Keep prompt metadata in send order so queued follow-ups cannot attach the
274
314
  // next prompt's files to an earlier user message.
@@ -506,8 +546,7 @@ export function createSessionDaemon({
506
546
  const retry = session.sessionId ? retryStateBySession.get(session.sessionId) : undefined;
507
547
  const compaction = compactionStateFor(activeSession);
508
548
  const targetDirectory = targetRuntime?.cwd || activeDirectory || cwd;
509
- const messages = activeSession ? projectMessageEntries(targetRuntime || runtime, targetDirectory) : [];
510
- const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
549
+ const lastAssistant = activeSession ? projectLatestAssistantMessage(targetRuntime || runtime) : undefined;
511
550
  const model = activeSession?.model;
512
551
  const snapshotSequence = ++sequence;
513
552
  // Snapshot must carry enough extension live state for a reconnect that
@@ -657,6 +696,60 @@ export function createSessionDaemon({
657
696
  );
658
697
  };
659
698
 
699
+ const activeRuntimes = () => {
700
+ const runtimes = new Set(runtimeRegistry?.listAll?.() ?? []);
701
+ if (runtime) runtimes.add(runtime);
702
+ return [...runtimes];
703
+ };
704
+
705
+ const hasUnsafeRuntime = () => activeRuntimes().some((targetRuntime) => !isRuntimeReloadSafe(targetRuntime));
706
+
707
+ const flushPendingRuntimeRecreation = () => {
708
+ if (!pendingRuntimeRecreation || hasUnsafeRuntime()) return Promise.resolve(false);
709
+ if (runtimeRecreationTask) return runtimeRecreationTask;
710
+
711
+ const task = (async () => {
712
+ let recreated = false;
713
+ while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
714
+ const revision = runtimeRecreationRevision;
715
+ servicesCache.clear();
716
+ await disposeRuntime();
717
+ if (!pendingRuntimeRecreation) break;
718
+ await ensureRuntime();
719
+ recreated = true;
720
+ if (revision === runtimeRecreationRevision) pendingRuntimeRecreation = false;
721
+ }
722
+ return recreated;
723
+ })();
724
+ const tracked = task.finally(() => {
725
+ if (runtimeRecreationTask === tracked) runtimeRecreationTask = null;
726
+ });
727
+ runtimeRecreationTask = tracked;
728
+ return tracked;
729
+ };
730
+
731
+ const scheduleRuntimeRecreation = async () => {
732
+ const deferred = hasUnsafeRuntime();
733
+ pendingRuntimeRecreation = true;
734
+ runtimeRecreationRevision += 1;
735
+ if (deferred) {
736
+ void flushPendingRuntimeRecreation().catch(() => {});
737
+ return true;
738
+ }
739
+ try {
740
+ await flushPendingRuntimeRecreation();
741
+ while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
742
+ await flushPendingRuntimeRecreation();
743
+ }
744
+ } catch {
745
+ // The file write has already committed. Keep the recreation pending so a
746
+ // later lifecycle edge can retry, and report delayed activation instead
747
+ // of misreporting the mutation itself as failed.
748
+ return true;
749
+ }
750
+ return pendingRuntimeRecreation;
751
+ };
752
+
660
753
  const reloadRuntimeResources = (targetRuntime) => {
661
754
  const existing = resourceReloadsByRuntime.get(targetRuntime);
662
755
  if (existing) return existing;
@@ -706,6 +799,7 @@ export function createSessionDaemon({
706
799
  pendingResourceReloads.add(targetRuntime);
707
800
  await flushPendingResourceReload(targetRuntime);
708
801
  }));
802
+ return [...candidates].some((targetRuntime) => pendingResourceReloads.has(targetRuntime));
709
803
  };
710
804
 
711
805
  const disposeIdleSessionRuntime = async (sessionId) => {
@@ -1072,6 +1166,24 @@ export function createSessionDaemon({
1072
1166
  return entries;
1073
1167
  };
1074
1168
 
1169
+ const projectLatestAssistantMessage = (activeRuntime) => {
1170
+ const session = activeRuntime?.session;
1171
+ const persisted = session?.sessionManager?.getBranch?.() ?? session?.sessionManager?.getEntries?.();
1172
+ const entries = liveProjectionEntries(session, Array.isArray(persisted) ? persisted : []);
1173
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
1174
+ const message = entries[index]?.message;
1175
+ if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;
1176
+ return {
1177
+ text: redactAttachmentPaths(textFromContent(message.content)),
1178
+ thinking: redactAttachmentPaths(message.content
1179
+ .filter((part) => part?.type === 'thinking')
1180
+ .map((part) => part.thinking)
1181
+ .join('')),
1182
+ };
1183
+ }
1184
+ return undefined;
1185
+ };
1186
+
1075
1187
  const projectMessageEntries = (activeRuntime, targetDir = activeDirectory || cwd) => {
1076
1188
  const session = activeRuntime?.session;
1077
1189
  // Use the active branch, not the full file. `getEntries()` returns every
@@ -1185,6 +1297,10 @@ export function createSessionDaemon({
1185
1297
  if (part?.type === 'thinking') return [{ type: 'thinking', id: `${entry.id}:thinking:${index}`, index, text: redactAttachmentPaths(part.thinking) }];
1186
1298
  if (part?.type === 'toolCall') {
1187
1299
  const result = toolResults.get(part.id);
1300
+ const timingKey = toolTimingKey(session.sessionId, part.id);
1301
+ const activeStartedAt = toolStartedAt.get(timingKey);
1302
+ const completedTiming = completedToolTimings.get(timingKey);
1303
+ const startedAt = activeStartedAt ?? completedTiming?.startedAt;
1188
1304
  const running = streaming && !result;
1189
1305
  const interrupted = !running && !result;
1190
1306
  const metadata = mergeToolPresentationMetadata(result?.metadata, activeRuntime, targetDir, part.name, part.arguments);
@@ -1204,11 +1320,14 @@ export function createSessionDaemon({
1204
1320
  : {}),
1205
1321
  ...(result?.isError || interrupted ? { isError: true } : {}),
1206
1322
  ...(metadata ? { metadata } : {}),
1323
+ ...(Number.isFinite(startedAt) ? { startedAt } : {}),
1207
1324
  ...(Number.isFinite(result?.endedAt)
1208
1325
  ? { endedAt: result.endedAt }
1209
- : interrupted
1210
- ? { endedAt: createdAt }
1211
- : {}),
1326
+ : Number.isFinite(completedTiming?.endedAt)
1327
+ ? { endedAt: completedTiming.endedAt }
1328
+ : interrupted
1329
+ ? { endedAt: createdAt }
1330
+ : {}),
1212
1331
  }];
1213
1332
  }
1214
1333
  return [];
@@ -1227,7 +1346,67 @@ export function createSessionDaemon({
1227
1346
  });
1228
1347
  };
1229
1348
 
1230
- const projectActiveSession = (activeRuntime = runtime, targetDir = activeRuntime?.cwd || activeDirectory || cwd) => {
1349
+ const projectMessagePage = (messages, options = {}) => {
1350
+ const requestedLimit = options.limit ?? SESSION_DAEMON_DEFAULT_MESSAGE_PAGE_LIMIT;
1351
+ if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 1 || requestedLimit > SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT) {
1352
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', `The message page limit must be between 1 and ${SESSION_DAEMON_MAX_MESSAGE_PAGE_LIMIT}.`);
1353
+ }
1354
+ let end = messages.length;
1355
+ if (options.before !== undefined) {
1356
+ if (typeof options.before !== 'string' || options.before.length === 0) {
1357
+ throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The message page cursor is invalid.');
1358
+ }
1359
+ end = messages.findIndex((entry) => entry?.message?.id === options.before);
1360
+ if (end < 0) throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The message page cursor is stale.');
1361
+ }
1362
+
1363
+ let start = end;
1364
+ let pageBytes = 2;
1365
+ while (start > 0 && end - start < requestedLimit) {
1366
+ const candidate = messages[start - 1];
1367
+ const candidateBytes = Buffer.byteLength(JSON.stringify(candidate));
1368
+ if (start < end && pageBytes + candidateBytes + 1 > SESSION_DAEMON_MESSAGE_PAGE_TARGET_BYTES) break;
1369
+ start -= 1;
1370
+ pageBytes += candidateBytes + (start + 1 < end ? 1 : 0);
1371
+ }
1372
+ const selected = messages.slice(start, end);
1373
+ let anchorIndex = -1;
1374
+ const firstMessage = selected[0]?.message;
1375
+ if (firstMessage?.role === 'assistant' && typeof firstMessage.parentId === 'string') {
1376
+ anchorIndex = messages.findIndex((entry, index) => index < start && entry?.message?.id === firstMessage.parentId);
1377
+ if (anchorIndex >= 0) selected.unshift(messages[anchorIndex]);
1378
+ }
1379
+ const beginsAtAdjacentAnchor = anchorIndex === start - 1;
1380
+ const cursorIndex = beginsAtAdjacentAnchor ? anchorIndex : start;
1381
+ const hasMoreBefore = cursorIndex > 0;
1382
+ return {
1383
+ messages: selected,
1384
+ hasMoreBefore,
1385
+ ...(hasMoreBefore ? { beforeCursor: messages[cursorIndex]?.message?.id } : {}),
1386
+ };
1387
+ };
1388
+
1389
+ const writeDetailResponse = (socket, requestId, detail) => {
1390
+ const frame = {
1391
+ protocolVersion: PROTOCOL_VERSION,
1392
+ kind: 'response',
1393
+ requestId,
1394
+ result: detail,
1395
+ };
1396
+ if (Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES) {
1397
+ throw new SessionDaemonProtocolError(
1398
+ 'DAEMON_RESPONSE_TOO_LARGE',
1399
+ 'The daemon response exceeds the IPC frame limit.',
1400
+ );
1401
+ }
1402
+ writeFrame(socket, frame);
1403
+ };
1404
+
1405
+ const projectActiveSession = (
1406
+ activeRuntime = runtime,
1407
+ targetDir = activeRuntime?.cwd || activeDirectory || cwd,
1408
+ pageOptions = {},
1409
+ ) => {
1231
1410
  const session = activeRuntime?.session;
1232
1411
  const manager = session?.sessionManager;
1233
1412
  const header = manager?.getHeader?.();
@@ -1236,8 +1415,16 @@ export function createSessionDaemon({
1236
1415
  throw new SessionDaemonProtocolError('INVALID_SESSION', 'Pi returned an invalid active session.');
1237
1416
  }
1238
1417
  const model = session.model;
1239
- const messages = projectMessageEntries(activeRuntime, targetDir);
1240
- const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
1418
+ const allMessages = projectMessageEntries(activeRuntime, targetDir);
1419
+ const page = projectMessagePage(allMessages, pageOptions);
1420
+ let lastAssistant;
1421
+ for (let index = allMessages.length - 1; index >= 0; index -= 1) {
1422
+ const candidate = allMessages[index]?.message;
1423
+ if (candidate?.role === 'assistant') {
1424
+ lastAssistant = candidate;
1425
+ break;
1426
+ }
1427
+ }
1241
1428
  const sessionModel = lastAssistant?.model
1242
1429
  ?? (model?.provider && model?.id ? { providerId: model.provider, modelId: model.id } : undefined);
1243
1430
  const sessionThinking = lastAssistant?.thinkingLevel || session.thinkingLevel;
@@ -1251,9 +1438,10 @@ export function createSessionDaemon({
1251
1438
  ...(session.sessionName ? { title: session.sessionName } : {}),
1252
1439
  ...(sessionModel ? { model: sessionModel } : {}),
1253
1440
  ...(sessionThinking ? { thinking: sessionThinking } : {}),
1254
- messageCount: messages.length,
1441
+ messageCount: allMessages.length,
1255
1442
  },
1256
- messages,
1443
+ messages: page.messages,
1444
+ ...(page.hasMoreBefore ? { hasMoreBefore: true, beforeCursor: page.beforeCursor } : {}),
1257
1445
  lastSequence: sequence,
1258
1446
  isStreaming,
1259
1447
  lifecycle: retry ? 'retry' : isStreaming ? 'busy' : 'idle',
@@ -1282,6 +1470,13 @@ export function createSessionDaemon({
1282
1470
  || (payload.model !== undefined && (!payload.model || typeof payload.model.providerId !== 'string' || typeof payload.model.modelId !== 'string'))) {
1283
1471
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The requested session creation options are invalid.');
1284
1472
  }
1473
+ try {
1474
+ await flushPendingRuntimeRecreation();
1475
+ } catch {
1476
+ // A committed write already queued recreation for a later edge. A
1477
+ // failed rebuild must not fail session creation; creation below
1478
+ // retries runtime startup directly.
1479
+ }
1285
1480
  const targetCwd = await resolveDirectory(payload.cwd);
1286
1481
  await validatePiSessionJsonlDirectory({ cwd: targetCwd, agentDir });
1287
1482
  const parent = payload.parentId === undefined ? undefined : (await findPersistedSession(payload.parentId, targetCwd)).target;
@@ -1357,6 +1552,11 @@ export function createSessionDaemon({
1357
1552
  };
1358
1553
 
1359
1554
  const listProviders = async (requestedDirectory) => {
1555
+ try {
1556
+ await flushPendingRuntimeRecreation();
1557
+ } catch {
1558
+ // A failed rebuild stays queued for a later edge; the ensure below retries startup.
1559
+ }
1360
1560
  const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1361
1561
  const activeRuntime = await ensureRuntime(targetDir);
1362
1562
  const modelRuntime = activeRuntime.session?.modelRuntime;
@@ -1387,6 +1587,11 @@ export function createSessionDaemon({
1387
1587
 
1388
1588
  let refreshProvidersInflight = null;
1389
1589
  const refreshProviders = async (requestedDirectory) => {
1590
+ try {
1591
+ await flushPendingRuntimeRecreation();
1592
+ } catch {
1593
+ // A failed rebuild stays queued for a later edge; the catalog refresh below retries startup.
1594
+ }
1390
1595
  if (refreshProvidersInflight) return refreshProvidersInflight;
1391
1596
  const task = (async () => {
1392
1597
  const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(15_000) : undefined;
@@ -1483,9 +1688,6 @@ export function createSessionDaemon({
1483
1688
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider configuration is invalid.');
1484
1689
  }
1485
1690
  const activeRuntime = await ensureRuntime();
1486
- if (activeRuntime?.session?.isStreaming) {
1487
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Provider configuration cannot change while a session is streaming.');
1488
- }
1489
1691
  if (typeof activeRuntime?.session?.modelRuntime?.getError?.() === 'string') {
1490
1692
  throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
1491
1693
  }
@@ -1498,15 +1700,10 @@ export function createSessionDaemon({
1498
1700
  }
1499
1701
  throw error;
1500
1702
  }
1501
- // ModelRuntime snapshots models.json at construction. Rehydrate only while
1502
- // idle so catalog changes are authoritative immediately and never race a turn.
1503
- servicesCache.clear();
1504
- if (activeRuntime) {
1505
- rememberRuntimeSession();
1506
- await disposeRuntime();
1507
- await ensureRuntime();
1508
- }
1509
- return { config };
1703
+ // ModelRuntime snapshots models.json at construction. Persist the new
1704
+ // catalog now, then recreate resident runtimes only at a safe edge.
1705
+ const deferred = await scheduleRuntimeRecreation();
1706
+ return { config, ...(deferred ? { deferred: true } : {}) };
1510
1707
  };
1511
1708
 
1512
1709
  const providerStatus = async (providerId) => {
@@ -1696,15 +1893,6 @@ export function createSessionDaemon({
1696
1893
  if (hasTrust && payload.trust !== null && typeof payload.trust !== 'boolean') {
1697
1894
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The project trust decision is invalid.');
1698
1895
  }
1699
- if (hasTrust) {
1700
- const targetRuntimes = runtimeRegistry?.listByDirectory?.(targetDir) ?? [];
1701
- const inheritsActive = runtime && runtime.cwd === targetDir ? [runtime] : [];
1702
- const allTarget = targetRuntimes.length > 0 ? targetRuntimes : inheritsActive;
1703
- const isTargetStreaming = allTarget.some((r) => r.session?.isStreaming);
1704
- if (isTargetStreaming) {
1705
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Project trust cannot change during an active session.');
1706
- }
1707
- }
1708
1896
  // Pi settings and trust live under the shared agent directory: read the
1709
1897
  // current files and commit inside the shared lock so concurrent daemons
1710
1898
  // cannot interleave read-modify-write cycles.
@@ -1741,11 +1929,13 @@ export function createSessionDaemon({
1741
1929
  }
1742
1930
  return isTrusted;
1743
1931
  });
1744
- if (hasTrust && runtime) {
1745
- await disposeRuntime();
1746
- await ensureRuntime();
1747
- }
1748
- return readPiSettings(targetDir);
1932
+ const deferred = hasTrust && activeRuntimes().length > 0
1933
+ ? await scheduleRuntimeRecreation()
1934
+ : false;
1935
+ return {
1936
+ ...readPiSettings(targetDir),
1937
+ ...(deferred ? { deferred: true } : {}),
1938
+ };
1749
1939
  };
1750
1940
 
1751
1941
  const resourceId = (kind, filePath) => `${kind}:${createHash('sha256').update(filePath).digest('base64url')}`;
@@ -1772,6 +1962,14 @@ export function createSessionDaemon({
1772
1962
 
1773
1963
  const resourceCatalog = async (requestedDirectory) => {
1774
1964
  const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
1965
+ // A settings page may be the first caller after a turn settles without a
1966
+ // lifecycle event reaching this daemon, so give queued configuration a
1967
+ // chance to activate before reading the catalog.
1968
+ try {
1969
+ await flushPendingRuntimeRecreation();
1970
+ } catch {
1971
+ // A failed rebuild stays queued for a later edge; ensureRuntime below retries startup.
1972
+ }
1775
1973
  const activeRuntime = await ensureRuntime(targetDir);
1776
1974
  const loader = activeRuntime?.services?.resourceLoader;
1777
1975
  if (!loader || typeof loader.getSkills !== 'function' || typeof loader.getPrompts !== 'function' || typeof loader.getAgentsFiles !== 'function') {
@@ -1835,14 +2033,19 @@ export function createSessionDaemon({
1835
2033
 
1836
2034
  const finishPromptMutation = async (locations, targetDir) => {
1837
2035
  servicesCache.delete(targetDir);
1838
- await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
1839
- return resourcesAfterPromptMutation(targetDir);
2036
+ const deferred = await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
2037
+ const resources = await resourcesAfterPromptMutation(targetDir);
2038
+ return { ...resources, ...(deferred ? { deferred: true } : {}) };
1840
2039
  };
1841
2040
 
1842
- const requireIdleResourceMutation = () => {
1843
- if (runtime?.session?.isStreaming || runtime?.session?.isCompacting) {
1844
- throw new SessionDaemonProtocolError('SESSION_BUSY', 'Resources cannot change during an active session.');
1845
- }
2041
+ const resourcesWithUpdatedContent = (catalog, resource, content) => {
2042
+ const resources = publicResources(catalog);
2043
+ const key = resource.kind === 'agents' ? 'agents' : 'prompts';
2044
+ return {
2045
+ ...resources,
2046
+ [key]: resources[key].map((item) => item.id === resource.id ? { ...item, content } : item),
2047
+ deferred: true,
2048
+ };
1846
2049
  };
1847
2050
 
1848
2051
  let resourceMutation = Promise.resolve();
@@ -1889,16 +2092,7 @@ export function createSessionDaemon({
1889
2092
  await rm(temporary, { force: true }).catch(() => {});
1890
2093
  });
1891
2094
 
1892
- const refreshResources = async (targetDir) => {
1893
- servicesCache.delete(targetDir || activeDirectory || cwd);
1894
- if (runtime) {
1895
- await disposeRuntime();
1896
- await ensureRuntime();
1897
- }
1898
- return publicResources(await resourceCatalog(targetDir));
1899
- };
1900
-
1901
- const updateResource = async (payload) => {
2095
+ const updateResource = (payload) => transactResourceMutation(async () => {
1902
2096
  if (!payload || typeof payload.resourceId !== 'string' || typeof payload.content !== 'string' || payload.content.length > 200_000) {
1903
2097
  throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi resource update is invalid.');
1904
2098
  }
@@ -1906,7 +2100,6 @@ export function createSessionDaemon({
1906
2100
  const catalog = await resourceCatalog(targetDir);
1907
2101
  const resource = [...catalog.prompts, ...catalog.agents].find((item) => item.id === payload.resourceId && item.editable === true);
1908
2102
  if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi resource is not editable.');
1909
- if (resource.kind !== 'prompt') requireIdleResourceMutation();
1910
2103
  let content = payload.content;
1911
2104
  if (resource.kind === 'prompt') {
1912
2105
  const previous = await readFile(resource.filePath, 'utf8').catch((error) => error?.code === 'ENOENT' ? '' : Promise.reject(error));
@@ -1915,8 +2108,11 @@ export function createSessionDaemon({
1915
2108
  }
1916
2109
  await writeResourceFile(resource.filePath, content);
1917
2110
  if (resource.kind === 'prompt') return finishPromptMutation([resource.location], targetDir);
1918
- return refreshResources(targetDir);
1919
- };
2111
+
2112
+ const deferred = await scheduleRuntimeRecreation();
2113
+ if (deferred) return resourcesWithUpdatedContent(catalog, resource, content);
2114
+ return publicResources(await resourceCatalog(targetDir));
2115
+ });
1920
2116
 
1921
2117
  const createPrompt = (payload) => transactResourceMutation(async () => {
1922
2118
  if (!payload || !['global', 'project'].includes(payload.location) || typeof payload.name !== 'string' || typeof payload.content !== 'string'
@@ -2359,7 +2555,16 @@ export function createSessionDaemon({
2359
2555
  throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
2360
2556
  }
2361
2557
  if (payload.thinking !== undefined) validateThinking(payload.thinking);
2362
- const activeRuntime = await activateSession(payload.sessionId, payload.directory);
2558
+ let activeRuntime = await activateSession(payload.sessionId, payload.directory);
2559
+ let recreated = false;
2560
+ try {
2561
+ recreated = await flushPendingRuntimeRecreation();
2562
+ } catch {
2563
+ // A failed rebuild stays queued for a later edge. Re-resolve the session so a
2564
+ // disposed runtime is retried instead of prompting on a stale handle.
2565
+ activeRuntime = await activateSession(payload.sessionId, payload.directory);
2566
+ }
2567
+ if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
2363
2568
  await flushPendingResourceReload(activeRuntime);
2364
2569
  // After a provider stream dies, Pi can report idle while the UI still
2365
2570
  // retries as steer/follow-up. Start a new turn instead of rejecting.
@@ -2483,11 +2688,13 @@ export function createSessionDaemon({
2483
2688
  scheduleIdleDisposal(payload.sessionId);
2484
2689
  }
2485
2690
  });
2691
+ void flushPendingRuntimeRecreation().catch(() => {});
2486
2692
  });
2487
2693
  return { accepted: true, messageId };
2488
2694
  } catch (error) {
2489
2695
  endSessionInput(activeRuntime);
2490
2696
  void flushPendingResourceReload(activeRuntime);
2697
+ void flushPendingRuntimeRecreation().catch(() => {});
2491
2698
  throw error;
2492
2699
  }
2493
2700
  };
@@ -2542,6 +2749,7 @@ export function createSessionDaemon({
2542
2749
  latestUserMessageIds.delete(sessionId);
2543
2750
  latestAssistantMessageIds.delete(sessionId);
2544
2751
  toolInputBySession.delete(sessionId);
2752
+ clearToolTimingsForSession(sessionId);
2545
2753
  publish('session.lifecycle', { state: 'idle', deleted: true, serverNow: Date.now() }, sessionId, targetDir);
2546
2754
  };
2547
2755
 
@@ -2677,7 +2885,7 @@ export function createSessionDaemon({
2677
2885
  const startedAt = Date.now();
2678
2886
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2679
2887
  const metadata = mergeToolPresentationMetadata(undefined, activeRuntime, directory, event.toolName, event.args);
2680
- toolStartedAt.set(event.toolCallId, startedAt);
2888
+ toolStartedAt.set(toolTimingKey(sessionId, event.toolCallId), startedAt);
2681
2889
  rememberToolInput(sessionId, event.toolCallId, event.args);
2682
2890
  publish('session.tool.start', {
2683
2891
  toolCallId: event.toolCallId,
@@ -2689,11 +2897,14 @@ export function createSessionDaemon({
2689
2897
  ...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
2690
2898
  ...(metadata ? { metadata } : {}),
2691
2899
  startedAt,
2900
+ serverNow: startedAt,
2692
2901
  }, sessionId, directory);
2693
2902
  break;
2694
2903
  }
2695
2904
  case 'tool_execution_update': {
2696
2905
  const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
2906
+ const startedAt = toolStartedAt.get(toolTimingKey(sessionId, event.toolCallId));
2907
+ const serverNow = Date.now();
2697
2908
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2698
2909
  const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
2699
2910
  const projected = projectToolResult(event.partialResult, false);
@@ -2708,14 +2919,19 @@ export function createSessionDaemon({
2708
2919
  ...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
2709
2920
  ...projected,
2710
2921
  ...(metadata ? { metadata } : {}),
2922
+ ...(Number.isFinite(startedAt) ? { startedAt } : {}),
2923
+ serverNow,
2711
2924
  }, sessionId, directory);
2712
2925
  break;
2713
2926
  }
2714
2927
  case 'tool_execution_end': {
2715
2928
  const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
2716
- const startedAt = toolStartedAt.get(event.toolCallId);
2929
+ const timingKey = toolTimingKey(sessionId, event.toolCallId);
2930
+ const startedAt = toolStartedAt.get(timingKey);
2931
+ const endedAt = Date.now();
2717
2932
  const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
2718
- toolStartedAt.delete(event.toolCallId);
2933
+ rememberCompletedToolTiming(sessionId, event.toolCallId, startedAt, endedAt);
2934
+ toolStartedAt.delete(timingKey);
2719
2935
  forgetToolInput(sessionId, event.toolCallId);
2720
2936
  const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
2721
2937
  const projected = projectToolResult(event.result, event.isError === true);
@@ -2731,7 +2947,8 @@ export function createSessionDaemon({
2731
2947
  ...projected,
2732
2948
  ...(metadata ? { metadata } : {}),
2733
2949
  ...(Number.isFinite(startedAt) ? { startedAt } : {}),
2734
- endedAt: Date.now(),
2950
+ endedAt,
2951
+ serverNow: endedAt,
2735
2952
  }, sessionId, directory);
2736
2953
  break;
2737
2954
  }
@@ -2774,12 +2991,14 @@ export function createSessionDaemon({
2774
2991
  latestUserMessageIds.delete(sessionId);
2775
2992
  latestAssistantMessageIds.delete(sessionId);
2776
2993
  toolInputBySession.delete(sessionId);
2994
+ clearToolTimingsForSession(sessionId, { keepCompleted: true });
2777
2995
  publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, sessionId, directory);
2778
2996
  if (!completeRequestedShutdown(sessionId)) {
2779
2997
  void flushPendingResourceReload(owningRuntime).then(() => {
2780
2998
  if (!shutdownRequestedBySession.has(sessionId)) scheduleIdleDisposal(sessionId);
2781
2999
  });
2782
3000
  }
3001
+ void flushPendingRuntimeRecreation().catch(() => {});
2783
3002
  break;
2784
3003
  case 'session_info_changed': {
2785
3004
  const title = typeof event.name === 'string' ? event.name.trim() : '';
@@ -2849,6 +3068,7 @@ export function createSessionDaemon({
2849
3068
  if (!event.willRetry) {
2850
3069
  void flushPendingResourceReload(owningRuntime).then(() => scheduleIdleDisposal(sessionId));
2851
3070
  }
3071
+ void flushPendingRuntimeRecreation().catch(() => {});
2852
3072
  break;
2853
3073
  }
2854
3074
  default:
@@ -2873,7 +3093,7 @@ export function createSessionDaemon({
2873
3093
  lastSequence: sequence,
2874
3094
  capabilities: [
2875
3095
  'runtime.claim', 'runtime.shutdown',
2876
- 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.rename', 'sessions.delete',
3096
+ 'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
2877
3097
  'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
2878
3098
  'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
2879
3099
  'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
@@ -3098,7 +3318,19 @@ export function createSessionDaemon({
3098
3318
  }
3099
3319
  case 'sessions.open': {
3100
3320
  const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
3101
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: projectActiveSession(activeRuntime, activeRuntime.cwd) });
3321
+ writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit }));
3322
+ return;
3323
+ }
3324
+ case 'sessions.messages': {
3325
+ const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
3326
+ const detail = projectActiveSession(activeRuntime, activeRuntime.cwd, {
3327
+ before: message.payload?.before,
3328
+ limit: message.payload?.limit,
3329
+ });
3330
+ writeDetailResponse(socket, message.requestId, {
3331
+ ...detail,
3332
+ hasMoreBefore: detail.hasMoreBefore === true,
3333
+ });
3102
3334
  return;
3103
3335
  }
3104
3336
  case 'sessions.rename': {
@@ -3136,7 +3368,7 @@ export function createSessionDaemon({
3136
3368
  newLeafId: typeof newLeafId === 'string' ? newLeafId : null,
3137
3369
  ...(typeof result?.editorText === 'string' && result.editorText.length > 0 ? { editorText: result.editorText } : {}),
3138
3370
  };
3139
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { ...projectActiveSession(activeRuntime, activeRuntime.cwd), navigation } });
3371
+ writeDetailResponse(socket, message.requestId, { ...projectActiveSession(activeRuntime, activeRuntime.cwd), navigation });
3140
3372
  return;
3141
3373
  }
3142
3374
  case 'sessions.fork':
@@ -3158,17 +3390,12 @@ export function createSessionDaemon({
3158
3390
  await acquireResidentLease({ cwd: activeRuntime.cwd, sessionId: activeRuntime.session.sessionId });
3159
3391
  }
3160
3392
  rememberRuntimeSession();
3161
- writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: projectActiveSession(activeRuntime, activeRuntime.cwd) });
3393
+ writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd));
3162
3394
  return;
3163
3395
  }
3164
3396
  case 'sessions.create': {
3165
3397
  const result = await createSession(message.payload);
3166
- writeFrame(socket, {
3167
- protocolVersion: PROTOCOL_VERSION,
3168
- kind: 'response',
3169
- requestId: message.requestId,
3170
- result,
3171
- });
3398
+ writeDetailResponse(socket, message.requestId, result);
3172
3399
  return;
3173
3400
  }
3174
3401
  case 'sessions.prompt':
@@ -3260,17 +3487,22 @@ export function createSessionDaemon({
3260
3487
 
3261
3488
  socket.on('data', (chunk) => {
3262
3489
  buffer += decoder.write(chunk);
3263
- if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
3264
- reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3265
- return;
3266
- }
3267
3490
 
3268
3491
  while (true) {
3269
3492
  const newline = buffer.indexOf('\n');
3270
- if (newline === -1) break;
3493
+ if (newline === -1) {
3494
+ if (Buffer.byteLength(buffer) > MAX_FRAME_BYTES) {
3495
+ reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3496
+ }
3497
+ break;
3498
+ }
3271
3499
  const line = buffer.slice(0, newline).replace(/\r$/, '');
3272
3500
  buffer = buffer.slice(newline + 1);
3273
3501
  if (line.length === 0) continue;
3502
+ if (Buffer.byteLength(line) > MAX_FRAME_BYTES) {
3503
+ reject(new SessionDaemonProtocolError('FRAME_TOO_LARGE', 'The daemon frame is too large.'));
3504
+ return;
3505
+ }
3274
3506
 
3275
3507
  try {
3276
3508
  const message = JSON.parse(line);
@@ -3361,6 +3593,8 @@ export function createSessionDaemon({
3361
3593
  retryStateBySession.clear();
3362
3594
  compactionStateBySession.clear();
3363
3595
  activeRunStartedAt.clear();
3596
+ toolStartedAt.clear();
3597
+ completedToolTimings.clear();
3364
3598
  shutdownRequestedBySession.clear();
3365
3599
  disposingSessionIds.clear();
3366
3600
  sendGenerationBySession.clear();
@@ -3374,6 +3608,8 @@ export function createSessionDaemon({
3374
3608
  await new Promise((resolve, reject) => {
3375
3609
  server.close((error) => error ? reject(error) : resolve());
3376
3610
  });
3611
+ pendingRuntimeRecreation = false;
3612
+ runtimeRecreationRevision += 1;
3377
3613
  await disposeRuntime();
3378
3614
  server = undefined;
3379
3615
  started = false;