@pi-chamber/web 0.9.4 → 0.9.5

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 (89) hide show
  1. package/README.md +15 -0
  2. package/dist/assets/{DiagramEditor-DuGmiPZ5.js → DiagramEditor-BPDkGHsj.js} +1 -1
  3. package/dist/assets/DiagramView-D_EfDz2d.js +1 -0
  4. package/dist/assets/{DiffView-CBOrV4hS.js → DiffView-BmIVvheE.js} +2 -2
  5. package/dist/assets/FilesView-CJytSUAX.js +6 -0
  6. package/dist/assets/GitView-BNkzec7G.js +8 -0
  7. package/dist/assets/{JsonTreeView-CKWGm5MS.js → JsonTreeView-C1Kzaybf.js} +1 -1
  8. package/dist/assets/MarkdownRendererImpl-qmKiFVpO.js +12 -0
  9. package/dist/assets/PatchDiff-D9JesZL1.js +1 -0
  10. package/dist/assets/{SessionSwitcherContent-z9VYCXrT.js → SessionSwitcherContent-DplV_ApH.js} +1 -1
  11. package/dist/assets/SessionSwitcherDropdown-DdgDKT6K.js +2 -0
  12. package/dist/assets/SessionUnreadDot-BdSDgvhC.js +1 -0
  13. package/dist/assets/SettingsView-z8uf0XyM.js +2 -0
  14. package/dist/assets/SettingsWindow-CPDmgNg2.js +1 -0
  15. package/dist/assets/ToolOutputDialog-DaF1xcM0.js +8 -0
  16. package/dist/assets/ToolPartDiffPreview-Di6Uo0Dt.js +1 -0
  17. package/dist/assets/{VirtualizedFileDiff-DfaXovGB.js → VirtualizedFileDiff-wqcrY0yr.js} +3 -3
  18. package/dist/assets/collapsible-DBQnXTNm.js +1 -0
  19. package/dist/assets/computeVirtualFileMetrics-Cr3jh0d6.js +3 -0
  20. package/dist/assets/contextFileOpenGuard-C_AOTYQD.js +1 -0
  21. package/dist/assets/gitStatusPredicates-BvPOjeOy.js +134 -0
  22. package/dist/assets/index-B8Wt2aN3.js +1 -0
  23. package/dist/assets/index-DIF8b4bh.css +1 -0
  24. package/dist/assets/index-jrfQYSvP.js +8 -0
  25. package/dist/assets/isDiffPlainText-L9uvgz2F.js +1 -0
  26. package/dist/assets/isFilePlainText-C4yk5BOo.js +1 -0
  27. package/dist/assets/main-C1OSzD-E.js +135 -0
  28. package/dist/assets/{main-DG1oZ0Wj.js → main-DCK6lLCo.js} +2 -2
  29. package/dist/assets/{markdownCore-DUjQU2i0.js → markdownCore-Czb_lINQ.js} +2 -2
  30. package/dist/assets/{miniChat-BEAtOkr9.js → miniChat-CXiSlptL.js} +2 -2
  31. package/dist/assets/{mobile-DOFBBQg2.js → mobile-D0HVxiyJ.js} +2 -2
  32. package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +2 -0
  33. package/dist/assets/renderMobileApp-B5x_PWlc.js +11 -0
  34. package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +53 -0
  35. package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-vilE4xyj.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-C4JL1x7k.js → useAppFontEffects-BP07Vl6M.js} +102 -103
  37. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +7 -0
  38. package/dist/assets/usePushVisibilityBeacon-CChMvoTL.js +10 -0
  39. package/dist/assets/useSwitcherItems-_RSo3F-A.js +1 -0
  40. package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
  41. package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
  42. package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
  43. package/dist/assets/{vendor-codemirror-language-data-C493X_9w.js → vendor-codemirror-language-data-BJrrV83E.js} +2 -2
  44. package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
  45. package/dist/assets/{web-components-B2Rw__yK.js → web-components-B5sMa_kC.js} +3 -3
  46. package/dist/index.html +4 -4
  47. package/dist/mini-chat.html +3 -3
  48. package/dist/mobile.html +3 -3
  49. package/package.json +2 -2
  50. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -5
  51. package/server/lib/pi/session-daemon/prompt-operations.test.js +142 -0
  52. package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
  53. package/server/lib/pi/session-daemon/session-daemon.js +230 -76
  54. package/server/lib/pi/session-daemon/session-idle-residency.test.js +742 -0
  55. package/server/lib/pi/session-daemon/session-replay.js +98 -0
  56. package/server/lib/pi/session-daemon/session-replay.test.js +626 -0
  57. package/server/lib/pi/ui-settings-store.js +16 -10
  58. package/server/lib/pi/ui-settings-store.test.js +91 -0
  59. package/server/lib/stt/DOCUMENTATION.md +1 -1
  60. package/server/lib/stt/local/worker-client.js +11 -3
  61. package/server/lib/stt/local/worker-client.test.js +255 -0
  62. package/dist/assets/DiagramView-CHy1Glsl.js +0 -1
  63. package/dist/assets/FilesView-CK2YVs_W.js +0 -6
  64. package/dist/assets/GitView-BEFLOv_7.js +0 -8
  65. package/dist/assets/MarkdownRendererImpl-hE_nmSqe.js +0 -12
  66. package/dist/assets/PatchDiff-BagRxMON.js +0 -1
  67. package/dist/assets/SessionSwitcherDropdown-icxJk_lT.js +0 -2
  68. package/dist/assets/SessionUnreadDot-Bv-5KguB.js +0 -1
  69. package/dist/assets/SettingsView-Ck0qxtKP.js +0 -2
  70. package/dist/assets/SettingsWindow-GQRL2CdD.js +0 -1
  71. package/dist/assets/ToolOutputDialog-CxJUXVZW.js +0 -8
  72. package/dist/assets/ToolPartDiffPreview-BXuLRWHT.js +0 -1
  73. package/dist/assets/collapsible-szfZ0Syc.js +0 -1
  74. package/dist/assets/computeVirtualFileMetrics-DG_E6iaN.js +0 -3
  75. package/dist/assets/contextFileOpenGuard-DPBE3ELv.js +0 -1
  76. package/dist/assets/gitStatusPredicates-OljV4Bb2.js +0 -134
  77. package/dist/assets/index-DNoEeZ2U.css +0 -1
  78. package/dist/assets/index-DmexVlTQ.js +0 -1
  79. package/dist/assets/index-KIdiBFJs.js +0 -8
  80. package/dist/assets/isDiffPlainText-aikgiqLb.js +0 -1
  81. package/dist/assets/isFilePlainText-D-Dl6LqX.js +0 -1
  82. package/dist/assets/main-BXdraZTZ.js +0 -135
  83. package/dist/assets/renderElectronMiniChatApp-B0K72YnS.js +0 -2
  84. package/dist/assets/renderMobileApp-Ca_BO_s4.js +0 -11
  85. package/dist/assets/runtimeEndpointReset-Cx2tsgTo.js +0 -54
  86. package/dist/assets/useFilesViewSearch-Du0DnmKs.js +0 -7
  87. package/dist/assets/usePushVisibilityBeacon-BnHxIv4r.js +0 -10
  88. package/dist/assets/useSwitcherItems-C91mwPJD.js +0 -1
  89. package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
@@ -34,6 +34,7 @@ import {
34
34
  SESSION_DAEMON_PROTOCOL_VERSION as PROTOCOL_VERSION,
35
35
  } from './ipc-protocol.js';
36
36
  import { createMessageEntryAliases } from './message-entry-aliases.js';
37
+ import { createSessionReplayLog } from './session-replay.js';
37
38
  import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
38
39
  import { createSkillReadClassifier } from './skill-read-classifier.js';
39
40
  import { createSessionRuntimeRegistry } from './runtime-registry.js';
@@ -152,6 +153,7 @@ export function createSessionDaemon({
152
153
  cwd,
153
154
  agentDir = getAgentDir(),
154
155
  createRuntime: injectCreateRuntime,
156
+ createServices: injectCreateServices = createAgentSessionServices,
155
157
  healthMetadata = {},
156
158
  profileKey,
157
159
  serverInstanceId,
@@ -247,13 +249,16 @@ export function createSessionDaemon({
247
249
  let dormantSession;
248
250
  let sequence = 0;
249
251
  let started = false;
252
+ let stopping = false;
250
253
  const knownDirectories = new Set([cwd]);
251
254
  let activeDirectory = cwd;
252
- const servicesCache = new Map();
253
255
  const clients = new Set();
254
- // A reconnect replays only a contiguous retained gap; otherwise it receives
255
- // a new authoritative snapshot before later events can arrive.
256
- const eventLog = [];
256
+ // A reconnect replays only a contiguous retained suffix; otherwise it receives
257
+ // a new authoritative snapshot before later events can arrive. The suffix is
258
+ // bounded by both event count and serialized wire bytes (see
259
+ // session-replay.js); each event is serialized once and the cached line is
260
+ // reused for live broadcast and replay.
261
+ const replayLog = createSessionReplayLog();
257
262
  const streamingMessageIds = new Map();
258
263
  const latestAssistantMessageIds = new Map();
259
264
  const messageStartedAt = new Map();
@@ -340,7 +345,6 @@ export function createSessionDaemon({
340
345
  // reconstruct the current UI without requiring the extension to re-emit.
341
346
  const messageEntryAliases = createMessageEntryAliases();
342
347
  const skillReadClassifierByRuntime = new WeakMap();
343
- const MAX_REPLAY_EVENTS = 1_024;
344
348
 
345
349
  const skillReadClassifierFor = (activeRuntime, directory) => {
346
350
  if (!activeRuntime || typeof activeRuntime !== 'object') return undefined;
@@ -443,17 +447,19 @@ export function createSessionDaemon({
443
447
  return title;
444
448
  };
445
449
 
446
- const getServices = async (targetCwd = activeDirectory || cwd) => {
447
- const existing = servicesCache.get(targetCwd);
448
- if (existing) return existing;
449
- const services = await createAgentSessionServices({
450
- cwd: targetCwd,
451
- agentDir,
452
- resourceLoaderOptions: {},
453
- });
454
- servicesCache.set(targetCwd, services);
455
- return services;
456
- };
450
+ // Prompt-mutation responses need a fresh standalone loader so the committed
451
+ // file is reflected even while a busy runtime keeps its current loader.
452
+ // Services are transient per mutation and never retained: the SDK exposes no
453
+ // dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager
454
+ // (verified against pi 0.84.1: file reads plus a cleared create-time timeout,
455
+ // no watchers, intervals, or listeners), so dropping the reference lets GC
456
+ // reclaim it. Retaining them only grew the daemon and fanned provider
457
+ // refreshes out to orphan ModelRuntimes whose catalogs are never read.
458
+ const createFreshPromptServices = async (targetCwd = activeDirectory || cwd) => injectCreateServices({
459
+ cwd: targetCwd,
460
+ agentDir,
461
+ resourceLoaderOptions: {},
462
+ });
457
463
 
458
464
  const publish = (event, payload, sessionId = runtime?.session?.sessionId, directory) => {
459
465
  if (typeof sessionId !== 'string' || sessionId.length === 0) return;
@@ -469,9 +475,11 @@ export function createSessionDaemon({
469
475
  ...payload,
470
476
  },
471
477
  };
472
- eventLog.push(message);
473
- if (eventLog.length > MAX_REPLAY_EVENTS) eventLog.shift();
474
- for (const client of clients) writeFrame(client, message);
478
+ const line = `${JSON.stringify(message)}\n`;
479
+ // Live delivery stays full-fidelity even when the event is too large to
480
+ // retain: retention evicts whole oldest events and never truncates content.
481
+ replayLog.append(message.sequence, sessionId, line);
482
+ for (const client of clients) writeLine(client, line);
475
483
  };
476
484
 
477
485
  const extensionBridge = createExtensionBridge({
@@ -588,20 +596,24 @@ export function createSessionDaemon({
588
596
  };
589
597
 
590
598
  const idleDisposeTimers = new Map();
599
+ const activeSessionRequests = new Map();
600
+
601
+ const isValidIdleSessionId = (sessionId) => typeof sessionId === 'string' && sessionId.length > 0;
591
602
 
592
603
  const clearIdleDisposal = (sessionId) => {
593
- if (sessionId) {
594
- const timer = idleDisposeTimers.get(sessionId);
595
- if (timer) clearTimeout(timer);
596
- idleDisposeTimers.delete(sessionId);
597
- } else {
598
- for (const timer of idleDisposeTimers.values()) clearTimeout(timer);
599
- idleDisposeTimers.clear();
600
- }
604
+ if (!isValidIdleSessionId(sessionId)) return;
605
+ const timer = idleDisposeTimers.get(sessionId);
606
+ if (timer) clearTimeout(timer);
607
+ idleDisposeTimers.delete(sessionId);
608
+ };
609
+
610
+ const clearAllIdleDisposals = () => {
611
+ for (const timer of idleDisposeTimers.values()) clearTimeout(timer);
612
+ idleDisposeTimers.clear();
601
613
  };
602
614
 
603
615
  const disposeRuntime = async () => {
604
- clearIdleDisposal();
616
+ clearAllIdleDisposals();
605
617
  activeSessionInputs.clear();
606
618
  pendingResourceReloads.clear();
607
619
  await resourceReloadQueue.catch(() => {});
@@ -712,7 +724,6 @@ export function createSessionDaemon({
712
724
  let recreated = false;
713
725
  while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
714
726
  const revision = runtimeRecreationRevision;
715
- servicesCache.clear();
716
727
  await disposeRuntime();
717
728
  if (!pendingRuntimeRecreation) break;
718
729
  await ensureRuntime();
@@ -802,38 +813,62 @@ export function createSessionDaemon({
802
813
  return [...candidates].some((targetRuntime) => pendingResourceReloads.has(targetRuntime));
803
814
  };
804
815
 
805
- const disposeIdleSessionRuntime = async (sessionId) => {
806
- if (disposingSessionIds.has(sessionId)) return;
816
+ // In-flight idle disposals by session id. A read or prompt that arrives
817
+ // while disposal is running waits for it and then reopens from JSONL
818
+ // instead of adopting a runtime that is about to be disposed.
819
+ const disposingSessionPromises = new Map();
820
+
821
+ const isIdleDisposalSafe = (sessionId, targetRuntime) => {
822
+ if (!targetRuntime) return false;
823
+ if (isValidIdleSessionId(sessionId) && (activeSessionRequests.get(sessionId) ?? 0) > 0) return false;
824
+ if (targetRuntime.session?.isStreaming || targetRuntime.session?.isCompacting) return false;
825
+ if (activeSessionInputs.has(targetRuntime)) return false;
826
+ if (pendingResourceReloads.has(targetRuntime) || resourceReloadsByRuntime.has(targetRuntime)) return false;
827
+ // A scheduled provider retry is still live work: agent_settled remains
828
+ // the authoritative idle boundary after retry success, exhaustion, or
829
+ // cancellation.
830
+ if (retryStateBySession.has(sessionId)) return false;
831
+ const compaction = compactionStateBySession.get(sessionId);
832
+ if (compaction && (compaction.phase === 'running' || compaction.phase === 'retrying')) return false;
833
+ return true;
834
+ };
835
+
836
+ const disposeIdleSessionRuntime = (sessionId) => {
837
+ if (disposingSessionIds.has(sessionId)) return disposingSessionPromises.get(sessionId) ?? Promise.resolve();
807
838
  const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
808
839
  if (!targetRuntime) {
809
840
  shutdownRequestedBySession.delete(sessionId);
810
- return;
841
+ return Promise.resolve();
811
842
  }
812
- if (
813
- targetRuntime.session?.isStreaming
814
- || targetRuntime.session?.isCompacting
815
- || activeSessionInputs.has(targetRuntime)
816
- || pendingResourceReloads.has(targetRuntime)
817
- || resourceReloadsByRuntime.has(targetRuntime)
818
- ) return;
843
+ if (!isIdleDisposalSafe(sessionId, targetRuntime)) return Promise.resolve();
819
844
  disposingSessionIds.add(sessionId);
820
845
  clearIdleDisposal(sessionId);
821
846
  activeSessionInputs.delete(targetRuntime);
822
847
  pendingResourceReloads.delete(targetRuntime);
823
848
  resourceReloadsByRuntime.delete(targetRuntime);
824
- try {
825
- if (targetRuntime === runtime) rememberRuntimeSession();
826
- clearExtensionState(sessionId);
827
- await runtimeRegistry.dispose(targetRuntime);
828
- await releaseResidentLease({ cwd: targetRuntime.cwd || activeDirectory || cwd, sessionId });
829
- shutdownRequestedBySession.delete(sessionId);
830
- compactionStateBySession.delete(sessionId);
831
- if (targetRuntime === runtime) runtime = undefined;
832
- } catch {
833
- publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
834
- } finally {
835
- disposingSessionIds.delete(sessionId);
836
- }
849
+ const tracked = (async () => {
850
+ try {
851
+ if (targetRuntime === runtime) rememberRuntimeSession();
852
+ // Pending extension dialogs are cancelled with an authoritative
853
+ // dismiss event so no extension thread blocks forever on a
854
+ // disposed runtime.
855
+ clearExtensionState(sessionId);
856
+ await runtimeRegistry.dispose(targetRuntime);
857
+ await releaseResidentLease({ cwd: targetRuntime.cwd || activeDirectory || cwd, sessionId });
858
+ shutdownRequestedBySession.delete(sessionId);
859
+ compactionStateBySession.delete(sessionId);
860
+ if (targetRuntime === runtime) runtime = undefined;
861
+ } catch {
862
+ publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
863
+ } finally {
864
+ disposingSessionIds.delete(sessionId);
865
+ }
866
+ })();
867
+ disposingSessionPromises.set(sessionId, tracked);
868
+ tracked.finally(() => {
869
+ if (disposingSessionPromises.get(sessionId) === tracked) disposingSessionPromises.delete(sessionId);
870
+ });
871
+ return tracked;
837
872
  };
838
873
 
839
874
  const completeRequestedShutdown = (sessionId) => {
@@ -843,6 +878,7 @@ export function createSessionDaemon({
843
878
  };
844
879
 
845
880
  const scheduleIdleDisposal = (sessionId) => {
881
+ if (!started || stopping || !isValidIdleSessionId(sessionId)) return;
846
882
  clearIdleDisposal(sessionId);
847
883
  const timer = setTimeout(() => {
848
884
  idleDisposeTimers.delete(sessionId);
@@ -851,6 +887,75 @@ export function createSessionDaemon({
851
887
  idleDisposeTimers.set(sessionId, timer);
852
888
  };
853
889
 
890
+ // Re-arm the idle lifetime after a view-only access. Clears first so the
891
+ // timer cannot fire mid-read, then schedules only when the session is
892
+ // resident and idle-safe; a busy session is left unarmed for its lifecycle
893
+ // edge (agent_settled, terminal compaction, prompt settlement) to arm.
894
+ // Never arms a timer for a non-resident session and never evicts on the
895
+ // acquisition path: capacity pressure alone must not dispose entries that
896
+ // are actively mounting.
897
+ const touchIdleDisposal = (sessionId) => {
898
+ clearIdleDisposal(sessionId);
899
+ if (!isValidIdleSessionId(sessionId)) return;
900
+ if (disposingSessionIds.has(sessionId)) return;
901
+ const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
902
+ if (!isIdleDisposalSafe(sessionId, targetRuntime)) return;
903
+ scheduleIdleDisposal(sessionId);
904
+ };
905
+
906
+ // Narrow session-access guard for request dispatch. Each in-flight
907
+ // session-scoped command holds one refcount while it activates and uses
908
+ // the runtime; the idle timer stays cleared until the last holder
909
+ // releases, and the release re-arms only when idle-safe (even after
910
+ // failure) so a failed read cannot leak the runtime. Prompt acceptance
911
+ // extends protection through activeSessionInputs and retry/compaction
912
+ // state, with async completion edges re-arming separately.
913
+ const acquireSessionAccess = (sessionId) => {
914
+ if (!isValidIdleSessionId(sessionId)) return undefined;
915
+ activeSessionRequests.set(sessionId, (activeSessionRequests.get(sessionId) ?? 0) + 1);
916
+ clearIdleDisposal(sessionId);
917
+ return sessionId;
918
+ };
919
+
920
+ const releaseSessionAccess = (sessionId) => {
921
+ if (!isValidIdleSessionId(sessionId)) return;
922
+ const remaining = (activeSessionRequests.get(sessionId) ?? 1) - 1;
923
+ if (remaining > 0) {
924
+ activeSessionRequests.set(sessionId, remaining);
925
+ return;
926
+ }
927
+ activeSessionRequests.delete(sessionId);
928
+ touchIdleDisposal(sessionId);
929
+ };
930
+
931
+ const sessionIdForIdleGuard = (message) => {
932
+ switch (message?.command) {
933
+ case 'sessions.open':
934
+ case 'sessions.messages':
935
+ case 'sessions.tree':
936
+ case 'sessions.navigate':
937
+ case 'sessions.fork':
938
+ case 'sessions.clone':
939
+ case 'sessions.abort':
940
+ case 'sessions.setModel':
941
+ case 'sessions.setThinking':
942
+ case 'sessions.compact':
943
+ case 'sessions.delete':
944
+ case 'sessions.rename': {
945
+ const candidate = message?.payload?.sessionId;
946
+ return isValidIdleSessionId(candidate) ? candidate : undefined;
947
+ }
948
+ case 'sessions.prompt':
949
+ case 'sessions.steer':
950
+ case 'sessions.followUp': {
951
+ const candidate = message?.payload?.sessionId ?? getSessionState().sessionId;
952
+ return isValidIdleSessionId(candidate) ? candidate : undefined;
953
+ }
954
+ default:
955
+ return undefined;
956
+ }
957
+ };
958
+
854
959
  const listInflightByDirectory = new Map();
855
960
  const listSessionItemsUnshared = async (targetDir) => {
856
961
  const sessions = await listSessions({ cwd: targetDir, agentDir });
@@ -1052,6 +1157,11 @@ export function createSessionDaemon({
1052
1157
 
1053
1158
  const activateInflightBySessionId = new Map();
1054
1159
  const activateSessionUnshared = async (sessionId, requestedDirectory) => {
1160
+ // A concurrent idle disposal owns the registry entry until it settles.
1161
+ // Wait for it so this caller reopens from JSONL instead of adopting a
1162
+ // runtime that disposal is about to tear down.
1163
+ const racingDisposal = disposingSessionPromises.get(sessionId);
1164
+ if (racingDisposal) await racingDisposal.catch(() => {});
1055
1165
  if (!runtimeRegistry) {
1056
1166
  runtimeRegistry = createSessionRuntimeRegistry({
1057
1167
  onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
@@ -1595,11 +1705,10 @@ export function createSessionDaemon({
1595
1705
  if (refreshProvidersInflight) return refreshProvidersInflight;
1596
1706
  const task = (async () => {
1597
1707
  const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(15_000) : undefined;
1708
+ // Refresh only live runtimes. Transient prompt-mutation services are never
1709
+ // retained, so there are no orphan ModelRuntimes to refresh here; the
1710
+ // returned catalog always comes from the active runtime via listProviders.
1598
1711
  const runtimes = new Set();
1599
- for (const services of servicesCache.values()) {
1600
- const mr = services?.modelRuntime;
1601
- if (mr) runtimes.add(mr);
1602
- }
1603
1712
  if (runtime?.session?.modelRuntime) runtimes.add(runtime.session.modelRuntime);
1604
1713
  if (runtime?.services?.modelRuntime) runtimes.add(runtime.services.modelRuntime);
1605
1714
  if (runtimeRegistry?.listAll) {
@@ -2014,12 +2123,13 @@ export function createSessionDaemon({
2014
2123
 
2015
2124
  // A busy session keeps its current Pi resource loader until its turn settles.
2016
2125
  // Mutation responses still need to reflect the committed file immediately,
2017
- // so replace only editable top-level prompts from a fresh standalone loader.
2126
+ // so replace only editable top-level prompts from a fresh transient loader.
2018
2127
  // Package/path/extension-contributed resources remain owned by the live session.
2128
+ // The transient services are dropped after use (no retention, no dispose hook
2129
+ // in the SDK) so repeated mutations cannot grow the daemon.
2019
2130
  const resourcesAfterPromptMutation = async (targetDir) => {
2020
2131
  const current = await resourceCatalog(targetDir);
2021
- servicesCache.delete(targetDir);
2022
- const freshServices = await getServices(targetDir);
2132
+ const freshServices = await createFreshPromptServices(targetDir);
2023
2133
  const freshEditable = promptResourcesFromLoader(freshServices.resourceLoader)
2024
2134
  .filter((prompt) => prompt.editable === true);
2025
2135
  return publicResources({
@@ -2032,7 +2142,6 @@ export function createSessionDaemon({
2032
2142
  };
2033
2143
 
2034
2144
  const finishPromptMutation = async (locations, targetDir) => {
2035
- servicesCache.delete(targetDir);
2036
2145
  const deferred = await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
2037
2146
  const resources = await resourcesAfterPromptMutation(targetDir);
2038
2147
  return { ...resources, ...(deferred ? { deferred: true } : {}) };
@@ -2555,6 +2664,9 @@ export function createSessionDaemon({
2555
2664
  throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
2556
2665
  }
2557
2666
  if (payload.thinking !== undefined) validateThinking(payload.thinking);
2667
+ // Idle protection is owned by the request-dispatch guard: it holds the
2668
+ // session refcount across activation/acceptance, agent_start clears once
2669
+ // the turn is live, and settlement re-arms.
2558
2670
  let activeRuntime = await activateSession(payload.sessionId, payload.directory);
2559
2671
  let recreated = false;
2560
2672
  try {
@@ -2683,9 +2795,12 @@ export function createSessionDaemon({
2683
2795
  Promise.resolve(activeRuntime.session.abort()).catch(() => {});
2684
2796
  }).finally(() => {
2685
2797
  endSessionInput(activeRuntime);
2686
- void flushPendingResourceReload(activeRuntime).then((reloaded) => {
2687
- if (reloaded && !shutdownRequestedBySession.has(payload.sessionId)) {
2688
- scheduleIdleDisposal(payload.sessionId);
2798
+ void flushPendingResourceReload(activeRuntime).then(() => {
2799
+ // Re-arm whenever the settlement left the session idle: this covers
2800
+ // extension commands that resolve without starting an agent turn
2801
+ // (no agent_settled follows) as well as ordinary turn completion.
2802
+ if (!shutdownRequestedBySession.has(payload.sessionId)) {
2803
+ touchIdleDisposal(payload.sessionId);
2689
2804
  }
2690
2805
  });
2691
2806
  void flushPendingRuntimeRecreation().catch(() => {});
@@ -2700,6 +2815,8 @@ export function createSessionDaemon({
2700
2815
  };
2701
2816
 
2702
2817
  const treeForSession = async (sessionId, requestedDirectory) => {
2818
+ // Idle protection is owned by the request-dispatch guard; the release
2819
+ // re-arms even when projection below throws.
2703
2820
  const activeRuntime = await activateSession(sessionId, requestedDirectory);
2704
2821
  const nodes = activeRuntime.session.sessionManager?.getTree?.();
2705
2822
  if (!Array.isArray(nodes)) throw new SessionDaemonProtocolError('SESSION_TREE_NOT_FOUND', 'Pi returned an invalid session tree.');
@@ -2716,6 +2833,8 @@ export function createSessionDaemon({
2716
2833
  };
2717
2834
 
2718
2835
  const deleteSession = async (sessionId, requestedDirectory) => {
2836
+ // Idle protection is owned by the request-dispatch guard. The release
2837
+ // touch is a no-op once the runtime is gone, so deletion never re-arms.
2719
2838
  const active = runtimeRegistry?.findBySessionId(sessionId);
2720
2839
  let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
2721
2840
  const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
@@ -3081,7 +3200,15 @@ export function createSessionDaemon({
3081
3200
  throw new SessionDaemonProtocolError('INVALID_REQUEST', 'The daemon request is invalid.');
3082
3201
  }
3083
3202
 
3084
- switch (message.command) {
3203
+ // Central idle-lifetime guard: hold one session refcount across the
3204
+ // whole dispatch so a concurrent short read cannot re-arm (or a timer
3205
+ // fire and dispose) while a longer operation on the same session is
3206
+ // still using its runtime. The release re-arms when idle-safe even
3207
+ // after failure, so failed reads cannot leak. Invalid ids never clear.
3208
+ const guardedSessionId = sessionIdForIdleGuard(message);
3209
+ const guard = acquireSessionAccess(guardedSessionId);
3210
+ try {
3211
+ switch (message.command) {
3085
3212
  case 'runtime.health':
3086
3213
  writeFrame(socket, {
3087
3214
  protocolVersion: PROTOCOL_VERSION,
@@ -3318,7 +3445,8 @@ export function createSessionDaemon({
3318
3445
  }
3319
3446
  case 'sessions.open': {
3320
3447
  const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
3321
- writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit }));
3448
+ const detail = projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit });
3449
+ writeDetailResponse(socket, message.requestId, detail);
3322
3450
  return;
3323
3451
  }
3324
3452
  case 'sessions.messages': {
@@ -3368,7 +3496,8 @@ export function createSessionDaemon({
3368
3496
  newLeafId: typeof newLeafId === 'string' ? newLeafId : null,
3369
3497
  ...(typeof result?.editorText === 'string' && result.editorText.length > 0 ? { editorText: result.editorText } : {}),
3370
3498
  };
3371
- writeDetailResponse(socket, message.requestId, { ...projectActiveSession(activeRuntime, activeRuntime.cwd), navigation });
3499
+ const navigateDetail = projectActiveSession(activeRuntime, activeRuntime.cwd);
3500
+ writeDetailResponse(socket, message.requestId, { ...navigateDetail, navigation });
3372
3501
  return;
3373
3502
  }
3374
3503
  case 'sessions.fork':
@@ -3390,7 +3519,11 @@ export function createSessionDaemon({
3390
3519
  await acquireResidentLease({ cwd: activeRuntime.cwd, sessionId: activeRuntime.session.sessionId });
3391
3520
  }
3392
3521
  rememberRuntimeSession();
3393
- writeDetailResponse(socket, message.requestId, projectActiveSession(activeRuntime, activeRuntime.cwd));
3522
+ const forkedDetail = projectActiveSession(activeRuntime, activeRuntime.cwd);
3523
+ // The guard re-arms the source session on release; arm the forked
3524
+ // identity explicitly since it was created inside this dispatch.
3525
+ touchIdleDisposal(activeRuntime.session?.sessionId);
3526
+ writeDetailResponse(socket, message.requestId, forkedDetail);
3394
3527
  return;
3395
3528
  }
3396
3529
  case 'sessions.create': {
@@ -3458,7 +3591,7 @@ export function createSessionDaemon({
3458
3591
  };
3459
3592
  compactionStateBySession.set(message.payload.sessionId, compaction);
3460
3593
  publish('session.compaction', compaction, message.payload.sessionId, activeRuntime.cwd);
3461
- scheduleIdleDisposal(message.payload.sessionId);
3594
+ touchIdleDisposal(message.payload.sessionId);
3462
3595
  });
3463
3596
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { accepted: true } });
3464
3597
  return;
@@ -3466,6 +3599,9 @@ export function createSessionDaemon({
3466
3599
  default:
3467
3600
  throw new SessionDaemonProtocolError('UNKNOWN_COMMAND', 'The daemon command is not supported.');
3468
3601
  }
3602
+ } finally {
3603
+ if (guard !== undefined) releaseSessionAccess(guard);
3604
+ }
3469
3605
  };
3470
3606
 
3471
3607
  const onConnection = (socket) => {
@@ -3515,13 +3651,12 @@ export function createSessionDaemon({
3515
3651
  writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'authenticated' });
3516
3652
  const requestedSessionId = typeof message.sessionId === 'string' && message.sessionId.length > 0 ? message.sessionId : undefined;
3517
3653
  const fromSequence = Number.isSafeInteger(message.fromSequence) && message.fromSequence >= 0 ? message.fromSequence : undefined;
3518
- const oldestRetainedSequence = eventLog[0]?.sequence;
3519
- const canReplay = fromSequence !== undefined && Number.isSafeInteger(oldestRetainedSequence)
3520
- && fromSequence >= oldestRetainedSequence - 1;
3521
- if (canReplay) {
3522
- for (const event of eventLog) {
3523
- if (event.sequence > fromSequence && (!requestedSessionId || event.payload.sessionId === requestedSessionId)) writeFrame(socket, event);
3524
- }
3654
+ // Contiguity is judged on the global retained suffix while delivery
3655
+ // stays session-filtered, so a filtered client never replays through
3656
+ // a gap left by eviction, an oversized event, an empty ring, or a
3657
+ // future cursor: all of those take the snapshot fallback below.
3658
+ if (fromSequence !== undefined && replayLog.canReplay(fromSequence, sequence)) {
3659
+ for (const cachedLine of replayLog.linesAfter(fromSequence, requestedSessionId)) writeLine(socket, cachedLine);
3525
3660
  } else {
3526
3661
  publishSnapshot(socket, requestedSessionId);
3527
3662
  }
@@ -3548,6 +3683,7 @@ export function createSessionDaemon({
3548
3683
  },
3549
3684
  async start() {
3550
3685
  if (started) return;
3686
+ stopping = false;
3551
3687
  await validatePiSessionJsonlDirectory({ cwd, agentDir });
3552
3688
  runtimeRegistry = createSessionRuntimeRegistry({
3553
3689
  onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
@@ -3584,6 +3720,10 @@ export function createSessionDaemon({
3584
3720
  },
3585
3721
  async stop() {
3586
3722
  if (!started) return;
3723
+ // Async request and reload completions may still release their guards
3724
+ // while teardown awaits sockets/disposal. They must not arm new timers.
3725
+ stopping = true;
3726
+ clearAllIdleDisposals();
3587
3727
  for (const attempt of loginAttempts.values()) {
3588
3728
  attempt.controller.abort();
3589
3729
  attempt.rejectPrompt?.(new Error('Provider login cancelled.'));
@@ -3596,7 +3736,6 @@ export function createSessionDaemon({
3596
3736
  toolStartedAt.clear();
3597
3737
  completedToolTimings.clear();
3598
3738
  shutdownRequestedBySession.clear();
3599
- disposingSessionIds.clear();
3600
3739
  sendGenerationBySession.clear();
3601
3740
  settledSendGenerationBySession.clear();
3602
3741
  pendingUserStartsBySession.clear();
@@ -3608,6 +3747,17 @@ export function createSessionDaemon({
3608
3747
  await new Promise((resolve, reject) => {
3609
3748
  server.close((error) => error ? reject(error) : resolve());
3610
3749
  });
3750
+ // Teardown must not double-dispose a runtime with an in-flight idle
3751
+ // disposal or release its lease twice: stop new timers, wait for the
3752
+ // racing disposal, then dispose what remains.
3753
+ clearAllIdleDisposals();
3754
+ activeSessionRequests.clear();
3755
+ const inFlightIdleDisposals = [...disposingSessionPromises.values()];
3756
+ if (inFlightIdleDisposals.length > 0) {
3757
+ await Promise.allSettled(inFlightIdleDisposals);
3758
+ }
3759
+ disposingSessionPromises.clear();
3760
+ disposingSessionIds.clear();
3611
3761
  pendingRuntimeRecreation = false;
3612
3762
  runtimeRecreationRevision += 1;
3613
3763
  await disposeRuntime();
@@ -3622,3 +3772,7 @@ function writeFrame(socket, frame) {
3622
3772
  if (!socket.destroyed) socket.write(`${JSON.stringify(frame)}\n`);
3623
3773
  }
3624
3774
 
3775
+ function writeLine(socket, line) {
3776
+ if (!socket.destroyed) socket.write(line);
3777
+ }
3778
+