@pi-chamber/web 0.9.3 → 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.
- package/README.md +16 -1
- package/dist/assets/{DiagramEditor-DuGmiPZ5.js → DiagramEditor-BPDkGHsj.js} +1 -1
- package/dist/assets/DiagramView-D_EfDz2d.js +1 -0
- package/dist/assets/{DiffView-DVd1MLPB.js → DiffView-BmIVvheE.js} +2 -2
- package/dist/assets/FilesView-CJytSUAX.js +6 -0
- package/dist/assets/GitView-BNkzec7G.js +8 -0
- package/dist/assets/{JsonTreeView-Cyy0lEZR.js → JsonTreeView-C1Kzaybf.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-qmKiFVpO.js +12 -0
- package/dist/assets/PatchDiff-D9JesZL1.js +1 -0
- package/dist/assets/{SessionSwitcherContent-dr3g9DR7.js → SessionSwitcherContent-DplV_ApH.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DdgDKT6K.js +2 -0
- package/dist/assets/SessionUnreadDot-BdSDgvhC.js +1 -0
- package/dist/assets/SettingsView-z8uf0XyM.js +2 -0
- package/dist/assets/SettingsWindow-CPDmgNg2.js +1 -0
- package/dist/assets/ToolOutputDialog-DaF1xcM0.js +8 -0
- package/dist/assets/ToolPartDiffPreview-Di6Uo0Dt.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-iqwryMNU.js → VirtualizedFileDiff-wqcrY0yr.js} +3 -3
- package/dist/assets/collapsible-DBQnXTNm.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-Cr3jh0d6.js +3 -0
- package/dist/assets/contextFileOpenGuard-C_AOTYQD.js +1 -0
- package/dist/assets/gitStatusPredicates-BvPOjeOy.js +134 -0
- package/dist/assets/index-B8Wt2aN3.js +1 -0
- package/dist/assets/index-DIF8b4bh.css +1 -0
- package/dist/assets/index-jrfQYSvP.js +8 -0
- package/dist/assets/isDiffPlainText-L9uvgz2F.js +1 -0
- package/dist/assets/isFilePlainText-C4yk5BOo.js +1 -0
- package/dist/assets/main-C1OSzD-E.js +135 -0
- package/dist/assets/{main-DMyWi0qs.js → main-DCK6lLCo.js} +2 -2
- package/dist/assets/{markdownCore-BD5WkOKU.js → markdownCore-Czb_lINQ.js} +2 -2
- package/dist/assets/{miniChat-CLMNhna4.js → miniChat-CXiSlptL.js} +2 -2
- package/dist/assets/{mobile-rWMDwhtQ.js → mobile-D0HVxiyJ.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +2 -0
- package/dist/assets/renderMobileApp-B5x_PWlc.js +11 -0
- package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +53 -0
- package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-vilE4xyj.js} +1 -1
- package/dist/assets/{useAppFontEffects-DfuJVB15.js → useAppFontEffects-BP07Vl6M.js} +102 -103
- package/dist/assets/useFilesViewSearch-oxIKk-ea.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-CChMvoTL.js +10 -0
- package/dist/assets/useSwitcherItems-_RSo3F-A.js +1 -0
- package/dist/assets/{vendor-base-ui-vkqQ2P9o.js → vendor-base-ui-CdaWtC7e.js} +1 -1
- package/dist/assets/vendor-beautiful-mermaid-D3YCkKz7.js +111 -0
- package/dist/assets/{vendor-codemirror-commands-DYppkHEk.js → vendor-codemirror-commands-CNlncqrr.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-CDdfwzlS.js → vendor-codemirror-language-data-BJrrV83E.js} +2 -2
- package/dist/assets/{vendor-replit-codemirror-vim-CGHHNQxC.js → vendor-replit-codemirror-vim-DaSwPsXt.js} +1 -1
- package/dist/assets/{web-components-C9wXMuCp.js → web-components-B5sMa_kC.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -2
- package/server/lib/pi/routes.js +13 -3
- package/server/lib/pi/routes.test.js +55 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -6
- package/server/lib/pi/session-daemon/prompt-operations.test.js +193 -0
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
- package/server/lib/pi/session-daemon/session-daemon.js +418 -129
- package/server/lib/pi/session-daemon/session-daemon.test.js +186 -0
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +742 -0
- package/server/lib/pi/session-daemon/session-replay.js +98 -0
- package/server/lib/pi/session-daemon/session-replay.test.js +626 -0
- package/server/lib/pi/ui-settings-store.js +16 -10
- package/server/lib/pi/ui-settings-store.test.js +91 -0
- package/server/lib/stt/DOCUMENTATION.md +1 -1
- package/server/lib/stt/local/worker-client.js +11 -3
- package/server/lib/stt/local/worker-client.test.js +255 -0
- package/dist/assets/DiagramView-CV-iReyY.js +0 -1
- package/dist/assets/FilesView-CPnW4I90.js +0 -6
- package/dist/assets/GitView-Dj_7hgX_.js +0 -8
- package/dist/assets/MarkdownRendererImpl-BXN78Wu_.js +0 -12
- package/dist/assets/PatchDiff-C7dA3U29.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-C3zdd82V.js +0 -2
- package/dist/assets/SessionUnreadDot-qeik5qtT.js +0 -1
- package/dist/assets/SettingsView-C57uV1YS.js +0 -2
- package/dist/assets/SettingsWindow-Bbay2W76.js +0 -1
- package/dist/assets/ToolOutputDialog-CRTiN1CH.js +0 -8
- package/dist/assets/ToolPartDiffPreview-CqnNcLPk.js +0 -1
- package/dist/assets/collapsible-szfZ0Syc.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-Bbugxxtp.js +0 -3
- package/dist/assets/contextFileOpenGuard-BC3ie230.js +0 -1
- package/dist/assets/gitStatusPredicates-DbThKVSf.js +0 -134
- package/dist/assets/index-DNoEeZ2U.css +0 -1
- package/dist/assets/index-KIdiBFJs.js +0 -8
- package/dist/assets/index-v6K3L94m.js +0 -1
- package/dist/assets/isDiffPlainText-Dl0RBjPZ.js +0 -1
- package/dist/assets/isFilePlainText-CbrmvrM6.js +0 -1
- package/dist/assets/main-4PkIvzf4.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-BRhGNRJ8.js +0 -2
- package/dist/assets/renderMobileApp-DLy2YoQg.js +0 -11
- package/dist/assets/runtimeEndpointReset-Z9YtcHxZ.js +0 -54
- package/dist/assets/useFilesViewSearch-BZBHrZ90.js +0 -7
- package/dist/assets/usePushVisibilityBeacon-BxTkEajM.js +0 -10
- package/dist/assets/useSwitcherItems-jITqE8PV.js +0 -1
- 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,17 +249,49 @@ 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
|
|
255
|
-
// a new authoritative snapshot before later events can arrive.
|
|
256
|
-
|
|
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();
|
|
260
265
|
const toolStartedAt = new Map();
|
|
266
|
+
// Keep recent starts long enough for a second client or a browser reload to
|
|
267
|
+
// hydrate a just-finished tool, but do not let a long-lived daemon grow with
|
|
268
|
+
// every tool call.
|
|
269
|
+
const completedToolTimings = new Map();
|
|
270
|
+
const MAX_COMPLETED_TOOL_TIMINGS = 2048;
|
|
271
|
+
const toolTimingKey = (sessionId, toolCallId) => `${sessionId}\u0000${toolCallId}`;
|
|
272
|
+
const clearToolTimingsForSession = (sessionId, { keepCompleted = false } = {}) => {
|
|
273
|
+
const prefix = `${sessionId}\u0000`;
|
|
274
|
+
for (const key of toolStartedAt.keys()) {
|
|
275
|
+
if (key.startsWith(prefix)) toolStartedAt.delete(key);
|
|
276
|
+
}
|
|
277
|
+
if (!keepCompleted) {
|
|
278
|
+
for (const key of completedToolTimings.keys()) {
|
|
279
|
+
if (key.startsWith(prefix)) completedToolTimings.delete(key);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
const rememberCompletedToolTiming = (sessionId, toolCallId, startedAt, endedAt) => {
|
|
284
|
+
if (!Number.isFinite(startedAt)) return;
|
|
285
|
+
completedToolTimings.set(toolTimingKey(sessionId, toolCallId), {
|
|
286
|
+
startedAt,
|
|
287
|
+
...(Number.isFinite(endedAt) ? { endedAt } : {}),
|
|
288
|
+
});
|
|
289
|
+
while (completedToolTimings.size > MAX_COMPLETED_TOOL_TIMINGS) {
|
|
290
|
+
const oldest = completedToolTimings.keys().next();
|
|
291
|
+
if (oldest.done) break;
|
|
292
|
+
completedToolTimings.delete(oldest.value);
|
|
293
|
+
}
|
|
294
|
+
};
|
|
261
295
|
const toolInputBySession = new Map();
|
|
262
296
|
const latestUserMessageIds = new Map();
|
|
263
297
|
const retryStateBySession = new Map();
|
|
@@ -267,11 +301,19 @@ export function createSessionDaemon({
|
|
|
267
301
|
const settledSendGenerationBySession = new Map();
|
|
268
302
|
// Pi's reload() is identity-preserving but is not safe during a turn,
|
|
269
303
|
// compaction, or an extension command. Prompt writes mark affected busy
|
|
270
|
-
// runtimes dirty and reload them at the next safe lifecycle edge.
|
|
304
|
+
// runtimes dirty and reload them at the next safe lifecycle edge. Other
|
|
305
|
+
// Pi configuration writes queue resident-runtime recreation at that edge.
|
|
271
306
|
const activeSessionInputs = new Map();
|
|
272
307
|
const pendingResourceReloads = new Set();
|
|
273
308
|
const resourceReloadsByRuntime = new Map();
|
|
274
309
|
let resourceReloadQueue = Promise.resolve();
|
|
310
|
+
// File-backed Pi configuration can be committed while a session is busy,
|
|
311
|
+
// but replacing all resident runtimes must wait until every active runtime
|
|
312
|
+
// is idle. The revision lets a second write that arrives during a rebuild
|
|
313
|
+
// trigger one more rebuild instead of being lost behind the first one.
|
|
314
|
+
let pendingRuntimeRecreation = false;
|
|
315
|
+
let runtimeRecreationRevision = 0;
|
|
316
|
+
let runtimeRecreationTask = null;
|
|
275
317
|
// Pi emits each user message start before its persisted entry is readable.
|
|
276
318
|
// Keep prompt metadata in send order so queued follow-ups cannot attach the
|
|
277
319
|
// next prompt's files to an earlier user message.
|
|
@@ -303,7 +345,6 @@ export function createSessionDaemon({
|
|
|
303
345
|
// reconstruct the current UI without requiring the extension to re-emit.
|
|
304
346
|
const messageEntryAliases = createMessageEntryAliases();
|
|
305
347
|
const skillReadClassifierByRuntime = new WeakMap();
|
|
306
|
-
const MAX_REPLAY_EVENTS = 1_024;
|
|
307
348
|
|
|
308
349
|
const skillReadClassifierFor = (activeRuntime, directory) => {
|
|
309
350
|
if (!activeRuntime || typeof activeRuntime !== 'object') return undefined;
|
|
@@ -406,17 +447,19 @@ export function createSessionDaemon({
|
|
|
406
447
|
return title;
|
|
407
448
|
};
|
|
408
449
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
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
|
+
});
|
|
420
463
|
|
|
421
464
|
const publish = (event, payload, sessionId = runtime?.session?.sessionId, directory) => {
|
|
422
465
|
if (typeof sessionId !== 'string' || sessionId.length === 0) return;
|
|
@@ -432,9 +475,11 @@ export function createSessionDaemon({
|
|
|
432
475
|
...payload,
|
|
433
476
|
},
|
|
434
477
|
};
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
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);
|
|
438
483
|
};
|
|
439
484
|
|
|
440
485
|
const extensionBridge = createExtensionBridge({
|
|
@@ -551,20 +596,24 @@ export function createSessionDaemon({
|
|
|
551
596
|
};
|
|
552
597
|
|
|
553
598
|
const idleDisposeTimers = new Map();
|
|
599
|
+
const activeSessionRequests = new Map();
|
|
600
|
+
|
|
601
|
+
const isValidIdleSessionId = (sessionId) => typeof sessionId === 'string' && sessionId.length > 0;
|
|
554
602
|
|
|
555
603
|
const clearIdleDisposal = (sessionId) => {
|
|
556
|
-
if (sessionId)
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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();
|
|
564
613
|
};
|
|
565
614
|
|
|
566
615
|
const disposeRuntime = async () => {
|
|
567
|
-
|
|
616
|
+
clearAllIdleDisposals();
|
|
568
617
|
activeSessionInputs.clear();
|
|
569
618
|
pendingResourceReloads.clear();
|
|
570
619
|
await resourceReloadQueue.catch(() => {});
|
|
@@ -659,6 +708,59 @@ export function createSessionDaemon({
|
|
|
659
708
|
);
|
|
660
709
|
};
|
|
661
710
|
|
|
711
|
+
const activeRuntimes = () => {
|
|
712
|
+
const runtimes = new Set(runtimeRegistry?.listAll?.() ?? []);
|
|
713
|
+
if (runtime) runtimes.add(runtime);
|
|
714
|
+
return [...runtimes];
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
const hasUnsafeRuntime = () => activeRuntimes().some((targetRuntime) => !isRuntimeReloadSafe(targetRuntime));
|
|
718
|
+
|
|
719
|
+
const flushPendingRuntimeRecreation = () => {
|
|
720
|
+
if (!pendingRuntimeRecreation || hasUnsafeRuntime()) return Promise.resolve(false);
|
|
721
|
+
if (runtimeRecreationTask) return runtimeRecreationTask;
|
|
722
|
+
|
|
723
|
+
const task = (async () => {
|
|
724
|
+
let recreated = false;
|
|
725
|
+
while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
|
|
726
|
+
const revision = runtimeRecreationRevision;
|
|
727
|
+
await disposeRuntime();
|
|
728
|
+
if (!pendingRuntimeRecreation) break;
|
|
729
|
+
await ensureRuntime();
|
|
730
|
+
recreated = true;
|
|
731
|
+
if (revision === runtimeRecreationRevision) pendingRuntimeRecreation = false;
|
|
732
|
+
}
|
|
733
|
+
return recreated;
|
|
734
|
+
})();
|
|
735
|
+
const tracked = task.finally(() => {
|
|
736
|
+
if (runtimeRecreationTask === tracked) runtimeRecreationTask = null;
|
|
737
|
+
});
|
|
738
|
+
runtimeRecreationTask = tracked;
|
|
739
|
+
return tracked;
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
const scheduleRuntimeRecreation = async () => {
|
|
743
|
+
const deferred = hasUnsafeRuntime();
|
|
744
|
+
pendingRuntimeRecreation = true;
|
|
745
|
+
runtimeRecreationRevision += 1;
|
|
746
|
+
if (deferred) {
|
|
747
|
+
void flushPendingRuntimeRecreation().catch(() => {});
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
try {
|
|
751
|
+
await flushPendingRuntimeRecreation();
|
|
752
|
+
while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
|
|
753
|
+
await flushPendingRuntimeRecreation();
|
|
754
|
+
}
|
|
755
|
+
} catch {
|
|
756
|
+
// The file write has already committed. Keep the recreation pending so a
|
|
757
|
+
// later lifecycle edge can retry, and report delayed activation instead
|
|
758
|
+
// of misreporting the mutation itself as failed.
|
|
759
|
+
return true;
|
|
760
|
+
}
|
|
761
|
+
return pendingRuntimeRecreation;
|
|
762
|
+
};
|
|
763
|
+
|
|
662
764
|
const reloadRuntimeResources = (targetRuntime) => {
|
|
663
765
|
const existing = resourceReloadsByRuntime.get(targetRuntime);
|
|
664
766
|
if (existing) return existing;
|
|
@@ -708,40 +810,65 @@ export function createSessionDaemon({
|
|
|
708
810
|
pendingResourceReloads.add(targetRuntime);
|
|
709
811
|
await flushPendingResourceReload(targetRuntime);
|
|
710
812
|
}));
|
|
813
|
+
return [...candidates].some((targetRuntime) => pendingResourceReloads.has(targetRuntime));
|
|
814
|
+
};
|
|
815
|
+
|
|
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;
|
|
711
834
|
};
|
|
712
835
|
|
|
713
|
-
const disposeIdleSessionRuntime =
|
|
714
|
-
if (disposingSessionIds.has(sessionId)) return;
|
|
836
|
+
const disposeIdleSessionRuntime = (sessionId) => {
|
|
837
|
+
if (disposingSessionIds.has(sessionId)) return disposingSessionPromises.get(sessionId) ?? Promise.resolve();
|
|
715
838
|
const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
|
|
716
839
|
if (!targetRuntime) {
|
|
717
840
|
shutdownRequestedBySession.delete(sessionId);
|
|
718
|
-
return;
|
|
841
|
+
return Promise.resolve();
|
|
719
842
|
}
|
|
720
|
-
if (
|
|
721
|
-
targetRuntime.session?.isStreaming
|
|
722
|
-
|| targetRuntime.session?.isCompacting
|
|
723
|
-
|| activeSessionInputs.has(targetRuntime)
|
|
724
|
-
|| pendingResourceReloads.has(targetRuntime)
|
|
725
|
-
|| resourceReloadsByRuntime.has(targetRuntime)
|
|
726
|
-
) return;
|
|
843
|
+
if (!isIdleDisposalSafe(sessionId, targetRuntime)) return Promise.resolve();
|
|
727
844
|
disposingSessionIds.add(sessionId);
|
|
728
845
|
clearIdleDisposal(sessionId);
|
|
729
846
|
activeSessionInputs.delete(targetRuntime);
|
|
730
847
|
pendingResourceReloads.delete(targetRuntime);
|
|
731
848
|
resourceReloadsByRuntime.delete(targetRuntime);
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
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;
|
|
745
872
|
};
|
|
746
873
|
|
|
747
874
|
const completeRequestedShutdown = (sessionId) => {
|
|
@@ -751,6 +878,7 @@ export function createSessionDaemon({
|
|
|
751
878
|
};
|
|
752
879
|
|
|
753
880
|
const scheduleIdleDisposal = (sessionId) => {
|
|
881
|
+
if (!started || stopping || !isValidIdleSessionId(sessionId)) return;
|
|
754
882
|
clearIdleDisposal(sessionId);
|
|
755
883
|
const timer = setTimeout(() => {
|
|
756
884
|
idleDisposeTimers.delete(sessionId);
|
|
@@ -759,6 +887,75 @@ export function createSessionDaemon({
|
|
|
759
887
|
idleDisposeTimers.set(sessionId, timer);
|
|
760
888
|
};
|
|
761
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
|
+
|
|
762
959
|
const listInflightByDirectory = new Map();
|
|
763
960
|
const listSessionItemsUnshared = async (targetDir) => {
|
|
764
961
|
const sessions = await listSessions({ cwd: targetDir, agentDir });
|
|
@@ -960,6 +1157,11 @@ export function createSessionDaemon({
|
|
|
960
1157
|
|
|
961
1158
|
const activateInflightBySessionId = new Map();
|
|
962
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(() => {});
|
|
963
1165
|
if (!runtimeRegistry) {
|
|
964
1166
|
runtimeRegistry = createSessionRuntimeRegistry({
|
|
965
1167
|
onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
|
|
@@ -1205,6 +1407,10 @@ export function createSessionDaemon({
|
|
|
1205
1407
|
if (part?.type === 'thinking') return [{ type: 'thinking', id: `${entry.id}:thinking:${index}`, index, text: redactAttachmentPaths(part.thinking) }];
|
|
1206
1408
|
if (part?.type === 'toolCall') {
|
|
1207
1409
|
const result = toolResults.get(part.id);
|
|
1410
|
+
const timingKey = toolTimingKey(session.sessionId, part.id);
|
|
1411
|
+
const activeStartedAt = toolStartedAt.get(timingKey);
|
|
1412
|
+
const completedTiming = completedToolTimings.get(timingKey);
|
|
1413
|
+
const startedAt = activeStartedAt ?? completedTiming?.startedAt;
|
|
1208
1414
|
const running = streaming && !result;
|
|
1209
1415
|
const interrupted = !running && !result;
|
|
1210
1416
|
const metadata = mergeToolPresentationMetadata(result?.metadata, activeRuntime, targetDir, part.name, part.arguments);
|
|
@@ -1224,11 +1430,14 @@ export function createSessionDaemon({
|
|
|
1224
1430
|
: {}),
|
|
1225
1431
|
...(result?.isError || interrupted ? { isError: true } : {}),
|
|
1226
1432
|
...(metadata ? { metadata } : {}),
|
|
1433
|
+
...(Number.isFinite(startedAt) ? { startedAt } : {}),
|
|
1227
1434
|
...(Number.isFinite(result?.endedAt)
|
|
1228
1435
|
? { endedAt: result.endedAt }
|
|
1229
|
-
:
|
|
1230
|
-
? { endedAt:
|
|
1231
|
-
:
|
|
1436
|
+
: Number.isFinite(completedTiming?.endedAt)
|
|
1437
|
+
? { endedAt: completedTiming.endedAt }
|
|
1438
|
+
: interrupted
|
|
1439
|
+
? { endedAt: createdAt }
|
|
1440
|
+
: {}),
|
|
1232
1441
|
}];
|
|
1233
1442
|
}
|
|
1234
1443
|
return [];
|
|
@@ -1371,6 +1580,13 @@ export function createSessionDaemon({
|
|
|
1371
1580
|
|| (payload.model !== undefined && (!payload.model || typeof payload.model.providerId !== 'string' || typeof payload.model.modelId !== 'string'))) {
|
|
1372
1581
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The requested session creation options are invalid.');
|
|
1373
1582
|
}
|
|
1583
|
+
try {
|
|
1584
|
+
await flushPendingRuntimeRecreation();
|
|
1585
|
+
} catch {
|
|
1586
|
+
// A committed write already queued recreation for a later edge. A
|
|
1587
|
+
// failed rebuild must not fail session creation; creation below
|
|
1588
|
+
// retries runtime startup directly.
|
|
1589
|
+
}
|
|
1374
1590
|
const targetCwd = await resolveDirectory(payload.cwd);
|
|
1375
1591
|
await validatePiSessionJsonlDirectory({ cwd: targetCwd, agentDir });
|
|
1376
1592
|
const parent = payload.parentId === undefined ? undefined : (await findPersistedSession(payload.parentId, targetCwd)).target;
|
|
@@ -1446,6 +1662,11 @@ export function createSessionDaemon({
|
|
|
1446
1662
|
};
|
|
1447
1663
|
|
|
1448
1664
|
const listProviders = async (requestedDirectory) => {
|
|
1665
|
+
try {
|
|
1666
|
+
await flushPendingRuntimeRecreation();
|
|
1667
|
+
} catch {
|
|
1668
|
+
// A failed rebuild stays queued for a later edge; the ensure below retries startup.
|
|
1669
|
+
}
|
|
1449
1670
|
const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
|
|
1450
1671
|
const activeRuntime = await ensureRuntime(targetDir);
|
|
1451
1672
|
const modelRuntime = activeRuntime.session?.modelRuntime;
|
|
@@ -1476,14 +1697,18 @@ export function createSessionDaemon({
|
|
|
1476
1697
|
|
|
1477
1698
|
let refreshProvidersInflight = null;
|
|
1478
1699
|
const refreshProviders = async (requestedDirectory) => {
|
|
1700
|
+
try {
|
|
1701
|
+
await flushPendingRuntimeRecreation();
|
|
1702
|
+
} catch {
|
|
1703
|
+
// A failed rebuild stays queued for a later edge; the catalog refresh below retries startup.
|
|
1704
|
+
}
|
|
1479
1705
|
if (refreshProvidersInflight) return refreshProvidersInflight;
|
|
1480
1706
|
const task = (async () => {
|
|
1481
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.
|
|
1482
1711
|
const runtimes = new Set();
|
|
1483
|
-
for (const services of servicesCache.values()) {
|
|
1484
|
-
const mr = services?.modelRuntime;
|
|
1485
|
-
if (mr) runtimes.add(mr);
|
|
1486
|
-
}
|
|
1487
1712
|
if (runtime?.session?.modelRuntime) runtimes.add(runtime.session.modelRuntime);
|
|
1488
1713
|
if (runtime?.services?.modelRuntime) runtimes.add(runtime.services.modelRuntime);
|
|
1489
1714
|
if (runtimeRegistry?.listAll) {
|
|
@@ -1572,9 +1797,6 @@ export function createSessionDaemon({
|
|
|
1572
1797
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The provider configuration is invalid.');
|
|
1573
1798
|
}
|
|
1574
1799
|
const activeRuntime = await ensureRuntime();
|
|
1575
|
-
if (activeRuntime?.session?.isStreaming) {
|
|
1576
|
-
throw new SessionDaemonProtocolError('SESSION_BUSY', 'Provider configuration cannot change while a session is streaming.');
|
|
1577
|
-
}
|
|
1578
1800
|
if (typeof activeRuntime?.session?.modelRuntime?.getError?.() === 'string') {
|
|
1579
1801
|
throw new SessionDaemonProtocolError('PI_MODEL_CONFIG_INVALID', 'Pi models configuration is invalid.');
|
|
1580
1802
|
}
|
|
@@ -1587,15 +1809,10 @@ export function createSessionDaemon({
|
|
|
1587
1809
|
}
|
|
1588
1810
|
throw error;
|
|
1589
1811
|
}
|
|
1590
|
-
// ModelRuntime snapshots models.json at construction.
|
|
1591
|
-
//
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
rememberRuntimeSession();
|
|
1595
|
-
await disposeRuntime();
|
|
1596
|
-
await ensureRuntime();
|
|
1597
|
-
}
|
|
1598
|
-
return { config };
|
|
1812
|
+
// ModelRuntime snapshots models.json at construction. Persist the new
|
|
1813
|
+
// catalog now, then recreate resident runtimes only at a safe edge.
|
|
1814
|
+
const deferred = await scheduleRuntimeRecreation();
|
|
1815
|
+
return { config, ...(deferred ? { deferred: true } : {}) };
|
|
1599
1816
|
};
|
|
1600
1817
|
|
|
1601
1818
|
const providerStatus = async (providerId) => {
|
|
@@ -1785,15 +2002,6 @@ export function createSessionDaemon({
|
|
|
1785
2002
|
if (hasTrust && payload.trust !== null && typeof payload.trust !== 'boolean') {
|
|
1786
2003
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The project trust decision is invalid.');
|
|
1787
2004
|
}
|
|
1788
|
-
if (hasTrust) {
|
|
1789
|
-
const targetRuntimes = runtimeRegistry?.listByDirectory?.(targetDir) ?? [];
|
|
1790
|
-
const inheritsActive = runtime && runtime.cwd === targetDir ? [runtime] : [];
|
|
1791
|
-
const allTarget = targetRuntimes.length > 0 ? targetRuntimes : inheritsActive;
|
|
1792
|
-
const isTargetStreaming = allTarget.some((r) => r.session?.isStreaming);
|
|
1793
|
-
if (isTargetStreaming) {
|
|
1794
|
-
throw new SessionDaemonProtocolError('SESSION_BUSY', 'Project trust cannot change during an active session.');
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
2005
|
// Pi settings and trust live under the shared agent directory: read the
|
|
1798
2006
|
// current files and commit inside the shared lock so concurrent daemons
|
|
1799
2007
|
// cannot interleave read-modify-write cycles.
|
|
@@ -1830,11 +2038,13 @@ export function createSessionDaemon({
|
|
|
1830
2038
|
}
|
|
1831
2039
|
return isTrusted;
|
|
1832
2040
|
});
|
|
1833
|
-
|
|
1834
|
-
await
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
2041
|
+
const deferred = hasTrust && activeRuntimes().length > 0
|
|
2042
|
+
? await scheduleRuntimeRecreation()
|
|
2043
|
+
: false;
|
|
2044
|
+
return {
|
|
2045
|
+
...readPiSettings(targetDir),
|
|
2046
|
+
...(deferred ? { deferred: true } : {}),
|
|
2047
|
+
};
|
|
1838
2048
|
};
|
|
1839
2049
|
|
|
1840
2050
|
const resourceId = (kind, filePath) => `${kind}:${createHash('sha256').update(filePath).digest('base64url')}`;
|
|
@@ -1861,6 +2071,14 @@ export function createSessionDaemon({
|
|
|
1861
2071
|
|
|
1862
2072
|
const resourceCatalog = async (requestedDirectory) => {
|
|
1863
2073
|
const targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : (activeDirectory || cwd);
|
|
2074
|
+
// A settings page may be the first caller after a turn settles without a
|
|
2075
|
+
// lifecycle event reaching this daemon, so give queued configuration a
|
|
2076
|
+
// chance to activate before reading the catalog.
|
|
2077
|
+
try {
|
|
2078
|
+
await flushPendingRuntimeRecreation();
|
|
2079
|
+
} catch {
|
|
2080
|
+
// A failed rebuild stays queued for a later edge; ensureRuntime below retries startup.
|
|
2081
|
+
}
|
|
1864
2082
|
const activeRuntime = await ensureRuntime(targetDir);
|
|
1865
2083
|
const loader = activeRuntime?.services?.resourceLoader;
|
|
1866
2084
|
if (!loader || typeof loader.getSkills !== 'function' || typeof loader.getPrompts !== 'function' || typeof loader.getAgentsFiles !== 'function') {
|
|
@@ -1905,12 +2123,13 @@ export function createSessionDaemon({
|
|
|
1905
2123
|
|
|
1906
2124
|
// A busy session keeps its current Pi resource loader until its turn settles.
|
|
1907
2125
|
// Mutation responses still need to reflect the committed file immediately,
|
|
1908
|
-
// so replace only editable top-level prompts from a fresh
|
|
2126
|
+
// so replace only editable top-level prompts from a fresh transient loader.
|
|
1909
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.
|
|
1910
2130
|
const resourcesAfterPromptMutation = async (targetDir) => {
|
|
1911
2131
|
const current = await resourceCatalog(targetDir);
|
|
1912
|
-
|
|
1913
|
-
const freshServices = await getServices(targetDir);
|
|
2132
|
+
const freshServices = await createFreshPromptServices(targetDir);
|
|
1914
2133
|
const freshEditable = promptResourcesFromLoader(freshServices.resourceLoader)
|
|
1915
2134
|
.filter((prompt) => prompt.editable === true);
|
|
1916
2135
|
return publicResources({
|
|
@@ -1923,15 +2142,19 @@ export function createSessionDaemon({
|
|
|
1923
2142
|
};
|
|
1924
2143
|
|
|
1925
2144
|
const finishPromptMutation = async (locations, targetDir) => {
|
|
1926
|
-
|
|
1927
|
-
await
|
|
1928
|
-
return
|
|
2145
|
+
const deferred = await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
|
|
2146
|
+
const resources = await resourcesAfterPromptMutation(targetDir);
|
|
2147
|
+
return { ...resources, ...(deferred ? { deferred: true } : {}) };
|
|
1929
2148
|
};
|
|
1930
2149
|
|
|
1931
|
-
const
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
2150
|
+
const resourcesWithUpdatedContent = (catalog, resource, content) => {
|
|
2151
|
+
const resources = publicResources(catalog);
|
|
2152
|
+
const key = resource.kind === 'agents' ? 'agents' : 'prompts';
|
|
2153
|
+
return {
|
|
2154
|
+
...resources,
|
|
2155
|
+
[key]: resources[key].map((item) => item.id === resource.id ? { ...item, content } : item),
|
|
2156
|
+
deferred: true,
|
|
2157
|
+
};
|
|
1935
2158
|
};
|
|
1936
2159
|
|
|
1937
2160
|
let resourceMutation = Promise.resolve();
|
|
@@ -1978,16 +2201,7 @@ export function createSessionDaemon({
|
|
|
1978
2201
|
await rm(temporary, { force: true }).catch(() => {});
|
|
1979
2202
|
});
|
|
1980
2203
|
|
|
1981
|
-
const
|
|
1982
|
-
servicesCache.delete(targetDir || activeDirectory || cwd);
|
|
1983
|
-
if (runtime) {
|
|
1984
|
-
await disposeRuntime();
|
|
1985
|
-
await ensureRuntime();
|
|
1986
|
-
}
|
|
1987
|
-
return publicResources(await resourceCatalog(targetDir));
|
|
1988
|
-
};
|
|
1989
|
-
|
|
1990
|
-
const updateResource = async (payload) => {
|
|
2204
|
+
const updateResource = (payload) => transactResourceMutation(async () => {
|
|
1991
2205
|
if (!payload || typeof payload.resourceId !== 'string' || typeof payload.content !== 'string' || payload.content.length > 200_000) {
|
|
1992
2206
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The Pi resource update is invalid.');
|
|
1993
2207
|
}
|
|
@@ -1995,7 +2209,6 @@ export function createSessionDaemon({
|
|
|
1995
2209
|
const catalog = await resourceCatalog(targetDir);
|
|
1996
2210
|
const resource = [...catalog.prompts, ...catalog.agents].find((item) => item.id === payload.resourceId && item.editable === true);
|
|
1997
2211
|
if (!resource?.filePath) throw new SessionDaemonProtocolError('RESOURCE_NOT_FOUND', 'The requested Pi resource is not editable.');
|
|
1998
|
-
if (resource.kind !== 'prompt') requireIdleResourceMutation();
|
|
1999
2212
|
let content = payload.content;
|
|
2000
2213
|
if (resource.kind === 'prompt') {
|
|
2001
2214
|
const previous = await readFile(resource.filePath, 'utf8').catch((error) => error?.code === 'ENOENT' ? '' : Promise.reject(error));
|
|
@@ -2004,8 +2217,11 @@ export function createSessionDaemon({
|
|
|
2004
2217
|
}
|
|
2005
2218
|
await writeResourceFile(resource.filePath, content);
|
|
2006
2219
|
if (resource.kind === 'prompt') return finishPromptMutation([resource.location], targetDir);
|
|
2007
|
-
|
|
2008
|
-
|
|
2220
|
+
|
|
2221
|
+
const deferred = await scheduleRuntimeRecreation();
|
|
2222
|
+
if (deferred) return resourcesWithUpdatedContent(catalog, resource, content);
|
|
2223
|
+
return publicResources(await resourceCatalog(targetDir));
|
|
2224
|
+
});
|
|
2009
2225
|
|
|
2010
2226
|
const createPrompt = (payload) => transactResourceMutation(async () => {
|
|
2011
2227
|
if (!payload || !['global', 'project'].includes(payload.location) || typeof payload.name !== 'string' || typeof payload.content !== 'string'
|
|
@@ -2448,7 +2664,19 @@ export function createSessionDaemon({
|
|
|
2448
2664
|
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
|
|
2449
2665
|
}
|
|
2450
2666
|
if (payload.thinking !== undefined) validateThinking(payload.thinking);
|
|
2451
|
-
|
|
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.
|
|
2670
|
+
let activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2671
|
+
let recreated = false;
|
|
2672
|
+
try {
|
|
2673
|
+
recreated = await flushPendingRuntimeRecreation();
|
|
2674
|
+
} catch {
|
|
2675
|
+
// A failed rebuild stays queued for a later edge. Re-resolve the session so a
|
|
2676
|
+
// disposed runtime is retried instead of prompting on a stale handle.
|
|
2677
|
+
activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2678
|
+
}
|
|
2679
|
+
if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2452
2680
|
await flushPendingResourceReload(activeRuntime);
|
|
2453
2681
|
// After a provider stream dies, Pi can report idle while the UI still
|
|
2454
2682
|
// retries as steer/follow-up. Start a new turn instead of rejecting.
|
|
@@ -2567,21 +2795,28 @@ export function createSessionDaemon({
|
|
|
2567
2795
|
Promise.resolve(activeRuntime.session.abort()).catch(() => {});
|
|
2568
2796
|
}).finally(() => {
|
|
2569
2797
|
endSessionInput(activeRuntime);
|
|
2570
|
-
void flushPendingResourceReload(activeRuntime).then((
|
|
2571
|
-
|
|
2572
|
-
|
|
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);
|
|
2573
2804
|
}
|
|
2574
2805
|
});
|
|
2806
|
+
void flushPendingRuntimeRecreation().catch(() => {});
|
|
2575
2807
|
});
|
|
2576
2808
|
return { accepted: true, messageId };
|
|
2577
2809
|
} catch (error) {
|
|
2578
2810
|
endSessionInput(activeRuntime);
|
|
2579
2811
|
void flushPendingResourceReload(activeRuntime);
|
|
2812
|
+
void flushPendingRuntimeRecreation().catch(() => {});
|
|
2580
2813
|
throw error;
|
|
2581
2814
|
}
|
|
2582
2815
|
};
|
|
2583
2816
|
|
|
2584
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.
|
|
2585
2820
|
const activeRuntime = await activateSession(sessionId, requestedDirectory);
|
|
2586
2821
|
const nodes = activeRuntime.session.sessionManager?.getTree?.();
|
|
2587
2822
|
if (!Array.isArray(nodes)) throw new SessionDaemonProtocolError('SESSION_TREE_NOT_FOUND', 'Pi returned an invalid session tree.');
|
|
@@ -2598,6 +2833,8 @@ export function createSessionDaemon({
|
|
|
2598
2833
|
};
|
|
2599
2834
|
|
|
2600
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.
|
|
2601
2838
|
const active = runtimeRegistry?.findBySessionId(sessionId);
|
|
2602
2839
|
let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
|
|
2603
2840
|
const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
|
|
@@ -2631,6 +2868,7 @@ export function createSessionDaemon({
|
|
|
2631
2868
|
latestUserMessageIds.delete(sessionId);
|
|
2632
2869
|
latestAssistantMessageIds.delete(sessionId);
|
|
2633
2870
|
toolInputBySession.delete(sessionId);
|
|
2871
|
+
clearToolTimingsForSession(sessionId);
|
|
2634
2872
|
publish('session.lifecycle', { state: 'idle', deleted: true, serverNow: Date.now() }, sessionId, targetDir);
|
|
2635
2873
|
};
|
|
2636
2874
|
|
|
@@ -2766,7 +3004,7 @@ export function createSessionDaemon({
|
|
|
2766
3004
|
const startedAt = Date.now();
|
|
2767
3005
|
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
2768
3006
|
const metadata = mergeToolPresentationMetadata(undefined, activeRuntime, directory, event.toolName, event.args);
|
|
2769
|
-
toolStartedAt.set(event.toolCallId, startedAt);
|
|
3007
|
+
toolStartedAt.set(toolTimingKey(sessionId, event.toolCallId), startedAt);
|
|
2770
3008
|
rememberToolInput(sessionId, event.toolCallId, event.args);
|
|
2771
3009
|
publish('session.tool.start', {
|
|
2772
3010
|
toolCallId: event.toolCallId,
|
|
@@ -2778,11 +3016,14 @@ export function createSessionDaemon({
|
|
|
2778
3016
|
...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
|
|
2779
3017
|
...(metadata ? { metadata } : {}),
|
|
2780
3018
|
startedAt,
|
|
3019
|
+
serverNow: startedAt,
|
|
2781
3020
|
}, sessionId, directory);
|
|
2782
3021
|
break;
|
|
2783
3022
|
}
|
|
2784
3023
|
case 'tool_execution_update': {
|
|
2785
3024
|
const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
|
|
3025
|
+
const startedAt = toolStartedAt.get(toolTimingKey(sessionId, event.toolCallId));
|
|
3026
|
+
const serverNow = Date.now();
|
|
2786
3027
|
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
2787
3028
|
const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
|
|
2788
3029
|
const projected = projectToolResult(event.partialResult, false);
|
|
@@ -2797,14 +3038,19 @@ export function createSessionDaemon({
|
|
|
2797
3038
|
...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
|
|
2798
3039
|
...projected,
|
|
2799
3040
|
...(metadata ? { metadata } : {}),
|
|
3041
|
+
...(Number.isFinite(startedAt) ? { startedAt } : {}),
|
|
3042
|
+
serverNow,
|
|
2800
3043
|
}, sessionId, directory);
|
|
2801
3044
|
break;
|
|
2802
3045
|
}
|
|
2803
3046
|
case 'tool_execution_end': {
|
|
2804
3047
|
const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
|
|
2805
|
-
const
|
|
3048
|
+
const timingKey = toolTimingKey(sessionId, event.toolCallId);
|
|
3049
|
+
const startedAt = toolStartedAt.get(timingKey);
|
|
3050
|
+
const endedAt = Date.now();
|
|
2806
3051
|
const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
|
|
2807
|
-
|
|
3052
|
+
rememberCompletedToolTiming(sessionId, event.toolCallId, startedAt, endedAt);
|
|
3053
|
+
toolStartedAt.delete(timingKey);
|
|
2808
3054
|
forgetToolInput(sessionId, event.toolCallId);
|
|
2809
3055
|
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
2810
3056
|
const projected = projectToolResult(event.result, event.isError === true);
|
|
@@ -2820,7 +3066,8 @@ export function createSessionDaemon({
|
|
|
2820
3066
|
...projected,
|
|
2821
3067
|
...(metadata ? { metadata } : {}),
|
|
2822
3068
|
...(Number.isFinite(startedAt) ? { startedAt } : {}),
|
|
2823
|
-
endedAt
|
|
3069
|
+
endedAt,
|
|
3070
|
+
serverNow: endedAt,
|
|
2824
3071
|
}, sessionId, directory);
|
|
2825
3072
|
break;
|
|
2826
3073
|
}
|
|
@@ -2863,12 +3110,14 @@ export function createSessionDaemon({
|
|
|
2863
3110
|
latestUserMessageIds.delete(sessionId);
|
|
2864
3111
|
latestAssistantMessageIds.delete(sessionId);
|
|
2865
3112
|
toolInputBySession.delete(sessionId);
|
|
3113
|
+
clearToolTimingsForSession(sessionId, { keepCompleted: true });
|
|
2866
3114
|
publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, sessionId, directory);
|
|
2867
3115
|
if (!completeRequestedShutdown(sessionId)) {
|
|
2868
3116
|
void flushPendingResourceReload(owningRuntime).then(() => {
|
|
2869
3117
|
if (!shutdownRequestedBySession.has(sessionId)) scheduleIdleDisposal(sessionId);
|
|
2870
3118
|
});
|
|
2871
3119
|
}
|
|
3120
|
+
void flushPendingRuntimeRecreation().catch(() => {});
|
|
2872
3121
|
break;
|
|
2873
3122
|
case 'session_info_changed': {
|
|
2874
3123
|
const title = typeof event.name === 'string' ? event.name.trim() : '';
|
|
@@ -2938,6 +3187,7 @@ export function createSessionDaemon({
|
|
|
2938
3187
|
if (!event.willRetry) {
|
|
2939
3188
|
void flushPendingResourceReload(owningRuntime).then(() => scheduleIdleDisposal(sessionId));
|
|
2940
3189
|
}
|
|
3190
|
+
void flushPendingRuntimeRecreation().catch(() => {});
|
|
2941
3191
|
break;
|
|
2942
3192
|
}
|
|
2943
3193
|
default:
|
|
@@ -2950,7 +3200,15 @@ export function createSessionDaemon({
|
|
|
2950
3200
|
throw new SessionDaemonProtocolError('INVALID_REQUEST', 'The daemon request is invalid.');
|
|
2951
3201
|
}
|
|
2952
3202
|
|
|
2953
|
-
|
|
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) {
|
|
2954
3212
|
case 'runtime.health':
|
|
2955
3213
|
writeFrame(socket, {
|
|
2956
3214
|
protocolVersion: PROTOCOL_VERSION,
|
|
@@ -3187,7 +3445,8 @@ export function createSessionDaemon({
|
|
|
3187
3445
|
}
|
|
3188
3446
|
case 'sessions.open': {
|
|
3189
3447
|
const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
|
|
3190
|
-
|
|
3448
|
+
const detail = projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit });
|
|
3449
|
+
writeDetailResponse(socket, message.requestId, detail);
|
|
3191
3450
|
return;
|
|
3192
3451
|
}
|
|
3193
3452
|
case 'sessions.messages': {
|
|
@@ -3237,7 +3496,8 @@ export function createSessionDaemon({
|
|
|
3237
3496
|
newLeafId: typeof newLeafId === 'string' ? newLeafId : null,
|
|
3238
3497
|
...(typeof result?.editorText === 'string' && result.editorText.length > 0 ? { editorText: result.editorText } : {}),
|
|
3239
3498
|
};
|
|
3240
|
-
|
|
3499
|
+
const navigateDetail = projectActiveSession(activeRuntime, activeRuntime.cwd);
|
|
3500
|
+
writeDetailResponse(socket, message.requestId, { ...navigateDetail, navigation });
|
|
3241
3501
|
return;
|
|
3242
3502
|
}
|
|
3243
3503
|
case 'sessions.fork':
|
|
@@ -3259,7 +3519,11 @@ export function createSessionDaemon({
|
|
|
3259
3519
|
await acquireResidentLease({ cwd: activeRuntime.cwd, sessionId: activeRuntime.session.sessionId });
|
|
3260
3520
|
}
|
|
3261
3521
|
rememberRuntimeSession();
|
|
3262
|
-
|
|
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);
|
|
3263
3527
|
return;
|
|
3264
3528
|
}
|
|
3265
3529
|
case 'sessions.create': {
|
|
@@ -3327,7 +3591,7 @@ export function createSessionDaemon({
|
|
|
3327
3591
|
};
|
|
3328
3592
|
compactionStateBySession.set(message.payload.sessionId, compaction);
|
|
3329
3593
|
publish('session.compaction', compaction, message.payload.sessionId, activeRuntime.cwd);
|
|
3330
|
-
|
|
3594
|
+
touchIdleDisposal(message.payload.sessionId);
|
|
3331
3595
|
});
|
|
3332
3596
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { accepted: true } });
|
|
3333
3597
|
return;
|
|
@@ -3335,6 +3599,9 @@ export function createSessionDaemon({
|
|
|
3335
3599
|
default:
|
|
3336
3600
|
throw new SessionDaemonProtocolError('UNKNOWN_COMMAND', 'The daemon command is not supported.');
|
|
3337
3601
|
}
|
|
3602
|
+
} finally {
|
|
3603
|
+
if (guard !== undefined) releaseSessionAccess(guard);
|
|
3604
|
+
}
|
|
3338
3605
|
};
|
|
3339
3606
|
|
|
3340
3607
|
const onConnection = (socket) => {
|
|
@@ -3384,13 +3651,12 @@ export function createSessionDaemon({
|
|
|
3384
3651
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'authenticated' });
|
|
3385
3652
|
const requestedSessionId = typeof message.sessionId === 'string' && message.sessionId.length > 0 ? message.sessionId : undefined;
|
|
3386
3653
|
const fromSequence = Number.isSafeInteger(message.fromSequence) && message.fromSequence >= 0 ? message.fromSequence : undefined;
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
|
|
3393
|
-
}
|
|
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);
|
|
3394
3660
|
} else {
|
|
3395
3661
|
publishSnapshot(socket, requestedSessionId);
|
|
3396
3662
|
}
|
|
@@ -3417,6 +3683,7 @@ export function createSessionDaemon({
|
|
|
3417
3683
|
},
|
|
3418
3684
|
async start() {
|
|
3419
3685
|
if (started) return;
|
|
3686
|
+
stopping = false;
|
|
3420
3687
|
await validatePiSessionJsonlDirectory({ cwd, agentDir });
|
|
3421
3688
|
runtimeRegistry = createSessionRuntimeRegistry({
|
|
3422
3689
|
onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
|
|
@@ -3453,6 +3720,10 @@ export function createSessionDaemon({
|
|
|
3453
3720
|
},
|
|
3454
3721
|
async stop() {
|
|
3455
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();
|
|
3456
3727
|
for (const attempt of loginAttempts.values()) {
|
|
3457
3728
|
attempt.controller.abort();
|
|
3458
3729
|
attempt.rejectPrompt?.(new Error('Provider login cancelled.'));
|
|
@@ -3462,8 +3733,9 @@ export function createSessionDaemon({
|
|
|
3462
3733
|
retryStateBySession.clear();
|
|
3463
3734
|
compactionStateBySession.clear();
|
|
3464
3735
|
activeRunStartedAt.clear();
|
|
3736
|
+
toolStartedAt.clear();
|
|
3737
|
+
completedToolTimings.clear();
|
|
3465
3738
|
shutdownRequestedBySession.clear();
|
|
3466
|
-
disposingSessionIds.clear();
|
|
3467
3739
|
sendGenerationBySession.clear();
|
|
3468
3740
|
settledSendGenerationBySession.clear();
|
|
3469
3741
|
pendingUserStartsBySession.clear();
|
|
@@ -3475,6 +3747,19 @@ export function createSessionDaemon({
|
|
|
3475
3747
|
await new Promise((resolve, reject) => {
|
|
3476
3748
|
server.close((error) => error ? reject(error) : resolve());
|
|
3477
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();
|
|
3761
|
+
pendingRuntimeRecreation = false;
|
|
3762
|
+
runtimeRecreationRevision += 1;
|
|
3478
3763
|
await disposeRuntime();
|
|
3479
3764
|
server = undefined;
|
|
3480
3765
|
started = false;
|
|
@@ -3487,3 +3772,7 @@ function writeFrame(socket, frame) {
|
|
|
3487
3772
|
if (!socket.destroyed) socket.write(`${JSON.stringify(frame)}\n`);
|
|
3488
3773
|
}
|
|
3489
3774
|
|
|
3775
|
+
function writeLine(socket, line) {
|
|
3776
|
+
if (!socket.destroyed) socket.write(line);
|
|
3777
|
+
}
|
|
3778
|
+
|