@pi-chamber/web 0.9.4 → 0.9.6
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 +15 -0
- package/dist/assets/DiagramView-0Iq1ak1I.js +1 -0
- package/dist/assets/{DiffView-CBOrV4hS.js → DiffView-DD1AFRi3.js} +2 -2
- package/dist/assets/FileSaveConflictDialog-CoKwDovb.js +3 -0
- package/dist/assets/FilesView-B_BF39ef.js +6 -0
- package/dist/assets/GitView-LFEpCasf.js +8 -0
- package/dist/assets/{JsonTreeView-CKWGm5MS.js → JsonTreeView-Cwjgvh4g.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-_7kV1yNw.js +12 -0
- package/dist/assets/PatchDiff-DG43C1HW.js +1 -0
- package/dist/assets/{SessionSwitcherContent-z9VYCXrT.js → SessionSwitcherContent-DCFXPY3d.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-QY7FKuEQ.js +2 -0
- package/dist/assets/SessionUnreadDot-DGT31A3z.js +1 -0
- package/dist/assets/SettingsView-eG-wN-yY.js +2 -0
- package/dist/assets/SettingsWindow-Dvnp8YrA.js +1 -0
- package/dist/assets/ToolOutputDialog-IlCrS6BR.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D68JV0rR.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-DfaXovGB.js → VirtualizedFileDiff-Bl-rAYeh.js} +3 -3
- package/dist/assets/collapsible-BjniCdZ5.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-FSOm2VrW.js +3 -0
- package/dist/assets/contextFileOpenGuard-Bxb6AIPa.js +1 -0
- package/dist/assets/gitStatusPredicates-DxolDpMd.js +134 -0
- package/dist/assets/index-BpmGBboM.css +1 -0
- package/dist/assets/index-DZnzXhTs.js +8 -0
- package/dist/assets/index-Dh58uD3I.js +1 -0
- package/dist/assets/isDiffPlainText-D3_04XCh.js +1 -0
- package/dist/assets/isFilePlainText-CHouYQhH.js +1 -0
- package/dist/assets/{main-DG1oZ0Wj.js → main-CH3EqGJI.js} +2 -2
- package/dist/assets/main-HzTrVvbB.js +135 -0
- package/dist/assets/{markdownCore-DUjQU2i0.js → markdownCore-DJU4KvHP.js} +2 -2
- package/dist/assets/{miniChat-BEAtOkr9.js → miniChat-Ca3TpaaA.js} +2 -2
- package/dist/assets/{mobile-DOFBBQg2.js → mobile-lj4gpGsO.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-rUFfaD-T.js +2 -0
- package/dist/assets/renderMobileApp-CcWQ1sCf.js +11 -0
- package/dist/assets/runtimeEndpointReset-D2MmSbDk.js +53 -0
- package/dist/assets/{runtimeSurface-CySRuLbN.js → runtimeSurface-CE_VNjdH.js} +1 -1
- package/dist/assets/{useAppFontEffects-C4JL1x7k.js → useAppFontEffects-BvFAP9zG.js} +102 -103
- package/dist/assets/useFilesViewSearch-BD79p3A2.js +7 -0
- package/dist/assets/usePushVisibilityBeacon-CWg0j-Wg.js +10 -0
- package/dist/assets/useSwitcherItems-CazJ6Yox.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-C493X_9w.js → vendor-codemirror-language-data-CP3j3-xu.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-B2Rw__yK.js → web-components-DWuadqra.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/fs/DOCUMENTATION.md +15 -3
- package/server/lib/fs/routes.js +369 -51
- package/server/lib/fs/routes.test.js +565 -3
- package/server/lib/fs/search.js +74 -29
- package/server/lib/pi/routes.js +56 -3
- package/server/lib/pi/routes.test.js +165 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +19 -6
- package/server/lib/pi/session-daemon/prompt-operations.test.js +151 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
- package/server/lib/pi/session-daemon/sdk-upgrade.test.js +157 -0
- package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
- package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
- package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
- package/server/lib/pi/session-daemon/session-daemon.js +514 -107
- package/server/lib/pi/session-daemon/session-daemon.test.js +37 -13
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +749 -0
- package/server/lib/pi/session-daemon/session-replay.js +98 -0
- package/server/lib/pi/session-daemon/session-replay.test.js +628 -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/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -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/server/lib/workspace/host.js +6 -2
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-DuGmiPZ5.js +0 -1
- package/dist/assets/DiagramView-CHy1Glsl.js +0 -1
- package/dist/assets/FilesView-CK2YVs_W.js +0 -6
- package/dist/assets/GitView-BEFLOv_7.js +0 -8
- package/dist/assets/MarkdownRendererImpl-hE_nmSqe.js +0 -12
- package/dist/assets/PatchDiff-BagRxMON.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-icxJk_lT.js +0 -2
- package/dist/assets/SessionUnreadDot-Bv-5KguB.js +0 -1
- package/dist/assets/SettingsView-Ck0qxtKP.js +0 -2
- package/dist/assets/SettingsWindow-GQRL2CdD.js +0 -1
- package/dist/assets/ToolOutputDialog-CxJUXVZW.js +0 -8
- package/dist/assets/ToolPartDiffPreview-BXuLRWHT.js +0 -1
- package/dist/assets/collapsible-szfZ0Syc.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DG_E6iaN.js +0 -3
- package/dist/assets/contextFileOpenGuard-DPBE3ELv.js +0 -1
- package/dist/assets/gitStatusPredicates-OljV4Bb2.js +0 -134
- package/dist/assets/index-DNoEeZ2U.css +0 -1
- package/dist/assets/index-DmexVlTQ.js +0 -1
- package/dist/assets/index-KIdiBFJs.js +0 -8
- package/dist/assets/isDiffPlainText-aikgiqLb.js +0 -1
- package/dist/assets/isFilePlainText-D-Dl6LqX.js +0 -1
- package/dist/assets/main-BXdraZTZ.js +0 -135
- package/dist/assets/renderElectronMiniChatApp-B0K72YnS.js +0 -2
- package/dist/assets/renderMobileApp-Ca_BO_s4.js +0 -11
- package/dist/assets/runtimeEndpointReset-Cx2tsgTo.js +0 -54
- package/dist/assets/useFilesViewSearch-Du0DnmKs.js +0 -7
- package/dist/assets/usePushVisibilityBeacon-BnHxIv4r.js +0 -10
- package/dist/assets/useSwitcherItems-C91mwPJD.js +0 -1
- package/dist/assets/vendor-beautiful-mermaid-DneUawHp.js +0 -119
|
@@ -34,6 +34,12 @@ 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';
|
|
38
|
+
import {
|
|
39
|
+
createSendOperationRegistry,
|
|
40
|
+
isValidSendOperationId,
|
|
41
|
+
stableFingerprint,
|
|
42
|
+
} from './send-operation-registry.js';
|
|
37
43
|
import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
|
|
38
44
|
import { createSkillReadClassifier } from './skill-read-classifier.js';
|
|
39
45
|
import { createSessionRuntimeRegistry } from './runtime-registry.js';
|
|
@@ -152,6 +158,7 @@ export function createSessionDaemon({
|
|
|
152
158
|
cwd,
|
|
153
159
|
agentDir = getAgentDir(),
|
|
154
160
|
createRuntime: injectCreateRuntime,
|
|
161
|
+
createServices: injectCreateServices = createAgentSessionServices,
|
|
155
162
|
healthMetadata = {},
|
|
156
163
|
profileKey,
|
|
157
164
|
serverInstanceId,
|
|
@@ -162,6 +169,7 @@ export function createSessionDaemon({
|
|
|
162
169
|
onOwnershipClaim,
|
|
163
170
|
onShutdown,
|
|
164
171
|
idleTimeoutMs = 5 * 60 * 1_000,
|
|
172
|
+
sendOperationTtlMs = 10 * 60 * 1_000,
|
|
165
173
|
listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
|
|
166
174
|
cwd: sessionCwd,
|
|
167
175
|
agentDir: sessionAgentDir,
|
|
@@ -199,6 +207,9 @@ export function createSessionDaemon({
|
|
|
199
207
|
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs < 0) {
|
|
200
208
|
throw new SessionDaemonProtocolError('INVALID_IDLE_TIMEOUT', 'The session daemon idle timeout is invalid.');
|
|
201
209
|
}
|
|
210
|
+
if (!Number.isFinite(sendOperationTtlMs) || sendOperationTtlMs <= 0) {
|
|
211
|
+
throw new SessionDaemonProtocolError('INVALID_SEND_OPERATION_TTL', 'The session daemon send operation ttl is invalid.');
|
|
212
|
+
}
|
|
202
213
|
|
|
203
214
|
let server;
|
|
204
215
|
let runtime;
|
|
@@ -247,13 +258,16 @@ export function createSessionDaemon({
|
|
|
247
258
|
let dormantSession;
|
|
248
259
|
let sequence = 0;
|
|
249
260
|
let started = false;
|
|
261
|
+
let stopping = false;
|
|
250
262
|
const knownDirectories = new Set([cwd]);
|
|
251
263
|
let activeDirectory = cwd;
|
|
252
|
-
const servicesCache = new Map();
|
|
253
264
|
const clients = new Set();
|
|
254
|
-
// A reconnect replays only a contiguous retained
|
|
255
|
-
// a new authoritative snapshot before later events can arrive.
|
|
256
|
-
|
|
265
|
+
// A reconnect replays only a contiguous retained suffix; otherwise it receives
|
|
266
|
+
// a new authoritative snapshot before later events can arrive. The suffix is
|
|
267
|
+
// bounded by both event count and serialized wire bytes (see
|
|
268
|
+
// session-replay.js); each event is serialized once and the cached line is
|
|
269
|
+
// reused for live broadcast and replay.
|
|
270
|
+
const replayLog = createSessionReplayLog();
|
|
257
271
|
const streamingMessageIds = new Map();
|
|
258
272
|
const latestAssistantMessageIds = new Map();
|
|
259
273
|
const messageStartedAt = new Map();
|
|
@@ -299,6 +313,16 @@ export function createSessionDaemon({
|
|
|
299
313
|
// runtimes dirty and reload them at the next safe lifecycle edge. Other
|
|
300
314
|
// Pi configuration writes queue resident-runtime recreation at that edge.
|
|
301
315
|
const activeSessionInputs = new Map();
|
|
316
|
+
// Send-intent deduplication (finding #3): one stable operation id per send
|
|
317
|
+
// intent; the registry is the authoritative execution boundary before Pi.
|
|
318
|
+
// Identity is `kind + sessionId + operationId`: the same id on a different
|
|
319
|
+
// kind or session is a different intent, never a payload mismatch.
|
|
320
|
+
// Retention is bounded (ttlMs/maxEntries, tombstones capped) and in-memory
|
|
321
|
+
// per daemon process — a restart loses receipts, which is the documented
|
|
322
|
+
// crash window. This split performs no stream-epoch guard and no
|
|
323
|
+
// per-session config/acceptance lock; every claim settles so pending
|
|
324
|
+
// duplicates never hang.
|
|
325
|
+
const sendOperations = createSendOperationRegistry({ ttlMs: sendOperationTtlMs });
|
|
302
326
|
const pendingResourceReloads = new Set();
|
|
303
327
|
const resourceReloadsByRuntime = new Map();
|
|
304
328
|
let resourceReloadQueue = Promise.resolve();
|
|
@@ -310,26 +334,70 @@ export function createSessionDaemon({
|
|
|
310
334
|
let runtimeRecreationRevision = 0;
|
|
311
335
|
let runtimeRecreationTask = null;
|
|
312
336
|
// Pi emits each user message start before its persisted entry is readable.
|
|
313
|
-
// Keep prompt metadata
|
|
314
|
-
//
|
|
337
|
+
// Keep prompt file metadata keyed by delivery kind so a queued followUp
|
|
338
|
+
// that a later steer overtakes cannot swap attachment footers. Steering
|
|
339
|
+
// drains before followUp in the SDK loop regardless of send order, so a
|
|
340
|
+
// single FIFO would attach the wrong files. SDK `queue_update` is the
|
|
341
|
+
// authoritative ownership signal: the queue that shrank owns the next
|
|
342
|
+
// user start. Direct (non-queued) starts emit no shrink and fall back to
|
|
343
|
+
// oldest-by-generation across kinds. No text/content heuristics are used.
|
|
315
344
|
const pendingUserStartsBySession = new Map();
|
|
316
|
-
const
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
pendingUserStartsBySession.
|
|
345
|
+
const queueSizesBySession = new Map();
|
|
346
|
+
const queueShrinkBySession = new Map();
|
|
347
|
+
const pendingBucketsFor = (sessionId) => {
|
|
348
|
+
let buckets = pendingUserStartsBySession.get(sessionId);
|
|
349
|
+
if (!buckets) {
|
|
350
|
+
buckets = { prompt: [], steer: [], followUp: [] };
|
|
351
|
+
pendingUserStartsBySession.set(sessionId, buckets);
|
|
352
|
+
}
|
|
353
|
+
return buckets;
|
|
354
|
+
};
|
|
355
|
+
const hasPendingUserStarts = (buckets) => (
|
|
356
|
+
buckets.prompt.length > 0 || buckets.steer.length > 0 || buckets.followUp.length > 0
|
|
357
|
+
);
|
|
358
|
+
const enqueueUserStart = (sessionId, generation, files, deliveryKind) => {
|
|
359
|
+
const buckets = pendingBucketsFor(sessionId);
|
|
360
|
+
const bucket = deliveryKind === 'steer' || deliveryKind === 'followUp' ? deliveryKind : 'prompt';
|
|
361
|
+
buckets[bucket].push({ generation, files, deliveryKind: bucket });
|
|
362
|
+
};
|
|
363
|
+
const takeOldestUserStart = (buckets) => {
|
|
364
|
+
let oldestBucket;
|
|
365
|
+
let oldestGeneration = Infinity;
|
|
366
|
+
for (const bucket of ['prompt', 'steer', 'followUp']) {
|
|
367
|
+
const first = buckets[bucket][0];
|
|
368
|
+
if (first && first.generation < oldestGeneration) {
|
|
369
|
+
oldestGeneration = first.generation;
|
|
370
|
+
oldestBucket = bucket;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (!oldestBucket) return undefined;
|
|
374
|
+
const next = buckets[oldestBucket].shift();
|
|
375
|
+
return next;
|
|
320
376
|
};
|
|
321
377
|
const takeUserStart = (sessionId) => {
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
378
|
+
const buckets = pendingUserStartsBySession.get(sessionId);
|
|
379
|
+
if (!buckets) return undefined;
|
|
380
|
+
const shrink = queueShrinkBySession.get(sessionId);
|
|
381
|
+
queueShrinkBySession.delete(sessionId);
|
|
382
|
+
let next;
|
|
383
|
+
if ((shrink === 'steer' || shrink === 'followUp') && buckets[shrink].length > 0) {
|
|
384
|
+
next = buckets[shrink].shift();
|
|
385
|
+
} else {
|
|
386
|
+
next = takeOldestUserStart(buckets);
|
|
387
|
+
}
|
|
388
|
+
if (!hasPendingUserStarts(buckets)) {
|
|
389
|
+
pendingUserStartsBySession.delete(sessionId);
|
|
390
|
+
}
|
|
325
391
|
return next;
|
|
326
392
|
};
|
|
327
393
|
const removeUserStart = (sessionId, generation) => {
|
|
328
|
-
const
|
|
329
|
-
if (!
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
394
|
+
const buckets = pendingUserStartsBySession.get(sessionId);
|
|
395
|
+
if (!buckets) return;
|
|
396
|
+
for (const bucket of ['prompt', 'steer', 'followUp']) {
|
|
397
|
+
const filtered = buckets[bucket].filter((entry) => entry.generation !== generation);
|
|
398
|
+
buckets[bucket] = filtered;
|
|
399
|
+
}
|
|
400
|
+
if (!hasPendingUserStarts(buckets)) pendingUserStartsBySession.delete(sessionId);
|
|
333
401
|
};
|
|
334
402
|
const shutdownRequestedBySession = new Set();
|
|
335
403
|
const disposingSessionIds = new Set();
|
|
@@ -340,7 +408,6 @@ export function createSessionDaemon({
|
|
|
340
408
|
// reconstruct the current UI without requiring the extension to re-emit.
|
|
341
409
|
const messageEntryAliases = createMessageEntryAliases();
|
|
342
410
|
const skillReadClassifierByRuntime = new WeakMap();
|
|
343
|
-
const MAX_REPLAY_EVENTS = 1_024;
|
|
344
411
|
|
|
345
412
|
const skillReadClassifierFor = (activeRuntime, directory) => {
|
|
346
413
|
if (!activeRuntime || typeof activeRuntime !== 'object') return undefined;
|
|
@@ -443,17 +510,19 @@ export function createSessionDaemon({
|
|
|
443
510
|
return title;
|
|
444
511
|
};
|
|
445
512
|
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
513
|
+
// Prompt-mutation responses need a fresh standalone loader so the committed
|
|
514
|
+
// file is reflected even while a busy runtime keeps its current loader.
|
|
515
|
+
// Services are transient per mutation and never retained: the SDK exposes no
|
|
516
|
+
// dispose on AgentSessionServices/ModelRuntime/ResourceLoader/SettingsManager
|
|
517
|
+
// (verified against pi 0.84.1: file reads plus a cleared create-time timeout,
|
|
518
|
+
// no watchers, intervals, or listeners), so dropping the reference lets GC
|
|
519
|
+
// reclaim it. Retaining them only grew the daemon and fanned provider
|
|
520
|
+
// refreshes out to orphan ModelRuntimes whose catalogs are never read.
|
|
521
|
+
const createFreshPromptServices = async (targetCwd = activeDirectory || cwd) => injectCreateServices({
|
|
522
|
+
cwd: targetCwd,
|
|
523
|
+
agentDir,
|
|
524
|
+
resourceLoaderOptions: {},
|
|
525
|
+
});
|
|
457
526
|
|
|
458
527
|
const publish = (event, payload, sessionId = runtime?.session?.sessionId, directory) => {
|
|
459
528
|
if (typeof sessionId !== 'string' || sessionId.length === 0) return;
|
|
@@ -469,9 +538,11 @@ export function createSessionDaemon({
|
|
|
469
538
|
...payload,
|
|
470
539
|
},
|
|
471
540
|
};
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
541
|
+
const line = `${JSON.stringify(message)}\n`;
|
|
542
|
+
// Live delivery stays full-fidelity even when the event is too large to
|
|
543
|
+
// retain: retention evicts whole oldest events and never truncates content.
|
|
544
|
+
replayLog.append(message.sequence, sessionId, line);
|
|
545
|
+
for (const client of clients) writeLine(client, line);
|
|
475
546
|
};
|
|
476
547
|
|
|
477
548
|
const extensionBridge = createExtensionBridge({
|
|
@@ -588,20 +659,24 @@ export function createSessionDaemon({
|
|
|
588
659
|
};
|
|
589
660
|
|
|
590
661
|
const idleDisposeTimers = new Map();
|
|
662
|
+
const activeSessionRequests = new Map();
|
|
663
|
+
|
|
664
|
+
const isValidIdleSessionId = (sessionId) => typeof sessionId === 'string' && sessionId.length > 0;
|
|
591
665
|
|
|
592
666
|
const clearIdleDisposal = (sessionId) => {
|
|
593
|
-
if (sessionId)
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
667
|
+
if (!isValidIdleSessionId(sessionId)) return;
|
|
668
|
+
const timer = idleDisposeTimers.get(sessionId);
|
|
669
|
+
if (timer) clearTimeout(timer);
|
|
670
|
+
idleDisposeTimers.delete(sessionId);
|
|
671
|
+
};
|
|
672
|
+
|
|
673
|
+
const clearAllIdleDisposals = () => {
|
|
674
|
+
for (const timer of idleDisposeTimers.values()) clearTimeout(timer);
|
|
675
|
+
idleDisposeTimers.clear();
|
|
601
676
|
};
|
|
602
677
|
|
|
603
678
|
const disposeRuntime = async () => {
|
|
604
|
-
|
|
679
|
+
clearAllIdleDisposals();
|
|
605
680
|
activeSessionInputs.clear();
|
|
606
681
|
pendingResourceReloads.clear();
|
|
607
682
|
await resourceReloadQueue.catch(() => {});
|
|
@@ -712,7 +787,6 @@ export function createSessionDaemon({
|
|
|
712
787
|
let recreated = false;
|
|
713
788
|
while (pendingRuntimeRecreation && !hasUnsafeRuntime()) {
|
|
714
789
|
const revision = runtimeRecreationRevision;
|
|
715
|
-
servicesCache.clear();
|
|
716
790
|
await disposeRuntime();
|
|
717
791
|
if (!pendingRuntimeRecreation) break;
|
|
718
792
|
await ensureRuntime();
|
|
@@ -802,38 +876,62 @@ export function createSessionDaemon({
|
|
|
802
876
|
return [...candidates].some((targetRuntime) => pendingResourceReloads.has(targetRuntime));
|
|
803
877
|
};
|
|
804
878
|
|
|
805
|
-
|
|
806
|
-
|
|
879
|
+
// In-flight idle disposals by session id. A read or prompt that arrives
|
|
880
|
+
// while disposal is running waits for it and then reopens from JSONL
|
|
881
|
+
// instead of adopting a runtime that is about to be disposed.
|
|
882
|
+
const disposingSessionPromises = new Map();
|
|
883
|
+
|
|
884
|
+
const isIdleDisposalSafe = (sessionId, targetRuntime) => {
|
|
885
|
+
if (!targetRuntime) return false;
|
|
886
|
+
if (isValidIdleSessionId(sessionId) && (activeSessionRequests.get(sessionId) ?? 0) > 0) return false;
|
|
887
|
+
if (targetRuntime.session?.isStreaming || targetRuntime.session?.isCompacting) return false;
|
|
888
|
+
if (activeSessionInputs.has(targetRuntime)) return false;
|
|
889
|
+
if (pendingResourceReloads.has(targetRuntime) || resourceReloadsByRuntime.has(targetRuntime)) return false;
|
|
890
|
+
// A scheduled provider retry is still live work: agent_settled remains
|
|
891
|
+
// the authoritative idle boundary after retry success, exhaustion, or
|
|
892
|
+
// cancellation.
|
|
893
|
+
if (retryStateBySession.has(sessionId)) return false;
|
|
894
|
+
const compaction = compactionStateBySession.get(sessionId);
|
|
895
|
+
if (compaction && (compaction.phase === 'running' || compaction.phase === 'retrying')) return false;
|
|
896
|
+
return true;
|
|
897
|
+
};
|
|
898
|
+
|
|
899
|
+
const disposeIdleSessionRuntime = (sessionId) => {
|
|
900
|
+
if (disposingSessionIds.has(sessionId)) return disposingSessionPromises.get(sessionId) ?? Promise.resolve();
|
|
807
901
|
const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
|
|
808
902
|
if (!targetRuntime) {
|
|
809
903
|
shutdownRequestedBySession.delete(sessionId);
|
|
810
|
-
return;
|
|
904
|
+
return Promise.resolve();
|
|
811
905
|
}
|
|
812
|
-
if (
|
|
813
|
-
targetRuntime.session?.isStreaming
|
|
814
|
-
|| targetRuntime.session?.isCompacting
|
|
815
|
-
|| activeSessionInputs.has(targetRuntime)
|
|
816
|
-
|| pendingResourceReloads.has(targetRuntime)
|
|
817
|
-
|| resourceReloadsByRuntime.has(targetRuntime)
|
|
818
|
-
) return;
|
|
906
|
+
if (!isIdleDisposalSafe(sessionId, targetRuntime)) return Promise.resolve();
|
|
819
907
|
disposingSessionIds.add(sessionId);
|
|
820
908
|
clearIdleDisposal(sessionId);
|
|
821
909
|
activeSessionInputs.delete(targetRuntime);
|
|
822
910
|
pendingResourceReloads.delete(targetRuntime);
|
|
823
911
|
resourceReloadsByRuntime.delete(targetRuntime);
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
912
|
+
const tracked = (async () => {
|
|
913
|
+
try {
|
|
914
|
+
if (targetRuntime === runtime) rememberRuntimeSession();
|
|
915
|
+
// Pending extension dialogs are cancelled with an authoritative
|
|
916
|
+
// dismiss event so no extension thread blocks forever on a
|
|
917
|
+
// disposed runtime.
|
|
918
|
+
clearExtensionState(sessionId);
|
|
919
|
+
await runtimeRegistry.dispose(targetRuntime);
|
|
920
|
+
await releaseResidentLease({ cwd: targetRuntime.cwd || activeDirectory || cwd, sessionId });
|
|
921
|
+
shutdownRequestedBySession.delete(sessionId);
|
|
922
|
+
compactionStateBySession.delete(sessionId);
|
|
923
|
+
if (targetRuntime === runtime) runtime = undefined;
|
|
924
|
+
} catch {
|
|
925
|
+
publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
|
|
926
|
+
} finally {
|
|
927
|
+
disposingSessionIds.delete(sessionId);
|
|
928
|
+
}
|
|
929
|
+
})();
|
|
930
|
+
disposingSessionPromises.set(sessionId, tracked);
|
|
931
|
+
tracked.finally(() => {
|
|
932
|
+
if (disposingSessionPromises.get(sessionId) === tracked) disposingSessionPromises.delete(sessionId);
|
|
933
|
+
});
|
|
934
|
+
return tracked;
|
|
837
935
|
};
|
|
838
936
|
|
|
839
937
|
const completeRequestedShutdown = (sessionId) => {
|
|
@@ -843,6 +941,7 @@ export function createSessionDaemon({
|
|
|
843
941
|
};
|
|
844
942
|
|
|
845
943
|
const scheduleIdleDisposal = (sessionId) => {
|
|
944
|
+
if (!started || stopping || !isValidIdleSessionId(sessionId)) return;
|
|
846
945
|
clearIdleDisposal(sessionId);
|
|
847
946
|
const timer = setTimeout(() => {
|
|
848
947
|
idleDisposeTimers.delete(sessionId);
|
|
@@ -851,6 +950,75 @@ export function createSessionDaemon({
|
|
|
851
950
|
idleDisposeTimers.set(sessionId, timer);
|
|
852
951
|
};
|
|
853
952
|
|
|
953
|
+
// Re-arm the idle lifetime after a view-only access. Clears first so the
|
|
954
|
+
// timer cannot fire mid-read, then schedules only when the session is
|
|
955
|
+
// resident and idle-safe; a busy session is left unarmed for its lifecycle
|
|
956
|
+
// edge (agent_settled, terminal compaction, prompt settlement) to arm.
|
|
957
|
+
// Never arms a timer for a non-resident session and never evicts on the
|
|
958
|
+
// acquisition path: capacity pressure alone must not dispose entries that
|
|
959
|
+
// are actively mounting.
|
|
960
|
+
const touchIdleDisposal = (sessionId) => {
|
|
961
|
+
clearIdleDisposal(sessionId);
|
|
962
|
+
if (!isValidIdleSessionId(sessionId)) return;
|
|
963
|
+
if (disposingSessionIds.has(sessionId)) return;
|
|
964
|
+
const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
|
|
965
|
+
if (!isIdleDisposalSafe(sessionId, targetRuntime)) return;
|
|
966
|
+
scheduleIdleDisposal(sessionId);
|
|
967
|
+
};
|
|
968
|
+
|
|
969
|
+
// Narrow session-access guard for request dispatch. Each in-flight
|
|
970
|
+
// session-scoped command holds one refcount while it activates and uses
|
|
971
|
+
// the runtime; the idle timer stays cleared until the last holder
|
|
972
|
+
// releases, and the release re-arms only when idle-safe (even after
|
|
973
|
+
// failure) so a failed read cannot leak the runtime. Prompt acceptance
|
|
974
|
+
// extends protection through activeSessionInputs and retry/compaction
|
|
975
|
+
// state, with async completion edges re-arming separately.
|
|
976
|
+
const acquireSessionAccess = (sessionId) => {
|
|
977
|
+
if (!isValidIdleSessionId(sessionId)) return undefined;
|
|
978
|
+
activeSessionRequests.set(sessionId, (activeSessionRequests.get(sessionId) ?? 0) + 1);
|
|
979
|
+
clearIdleDisposal(sessionId);
|
|
980
|
+
return sessionId;
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
const releaseSessionAccess = (sessionId) => {
|
|
984
|
+
if (!isValidIdleSessionId(sessionId)) return;
|
|
985
|
+
const remaining = (activeSessionRequests.get(sessionId) ?? 1) - 1;
|
|
986
|
+
if (remaining > 0) {
|
|
987
|
+
activeSessionRequests.set(sessionId, remaining);
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
activeSessionRequests.delete(sessionId);
|
|
991
|
+
touchIdleDisposal(sessionId);
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
const sessionIdForIdleGuard = (message) => {
|
|
995
|
+
switch (message?.command) {
|
|
996
|
+
case 'sessions.open':
|
|
997
|
+
case 'sessions.messages':
|
|
998
|
+
case 'sessions.tree':
|
|
999
|
+
case 'sessions.navigate':
|
|
1000
|
+
case 'sessions.fork':
|
|
1001
|
+
case 'sessions.clone':
|
|
1002
|
+
case 'sessions.abort':
|
|
1003
|
+
case 'sessions.setModel':
|
|
1004
|
+
case 'sessions.setThinking':
|
|
1005
|
+
case 'sessions.compact':
|
|
1006
|
+
case 'sessions.delete':
|
|
1007
|
+
case 'sessions.rename': {
|
|
1008
|
+
const candidate = message?.payload?.sessionId;
|
|
1009
|
+
return isValidIdleSessionId(candidate) ? candidate : undefined;
|
|
1010
|
+
}
|
|
1011
|
+
case 'sessions.prompt':
|
|
1012
|
+
case 'sessions.steer':
|
|
1013
|
+
case 'sessions.followUp': {
|
|
1014
|
+
const candidate = message?.payload?.sessionId ?? getSessionState().sessionId;
|
|
1015
|
+
return isValidIdleSessionId(candidate) ? candidate : undefined;
|
|
1016
|
+
}
|
|
1017
|
+
default:
|
|
1018
|
+
return undefined;
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
|
|
854
1022
|
const listInflightByDirectory = new Map();
|
|
855
1023
|
const listSessionItemsUnshared = async (targetDir) => {
|
|
856
1024
|
const sessions = await listSessions({ cwd: targetDir, agentDir });
|
|
@@ -1052,6 +1220,11 @@ export function createSessionDaemon({
|
|
|
1052
1220
|
|
|
1053
1221
|
const activateInflightBySessionId = new Map();
|
|
1054
1222
|
const activateSessionUnshared = async (sessionId, requestedDirectory) => {
|
|
1223
|
+
// A concurrent idle disposal owns the registry entry until it settles.
|
|
1224
|
+
// Wait for it so this caller reopens from JSONL instead of adopting a
|
|
1225
|
+
// runtime that disposal is about to tear down.
|
|
1226
|
+
const racingDisposal = disposingSessionPromises.get(sessionId);
|
|
1227
|
+
if (racingDisposal) await racingDisposal.catch(() => {});
|
|
1055
1228
|
if (!runtimeRegistry) {
|
|
1056
1229
|
runtimeRegistry = createSessionRuntimeRegistry({
|
|
1057
1230
|
onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
|
|
@@ -1595,11 +1768,10 @@ export function createSessionDaemon({
|
|
|
1595
1768
|
if (refreshProvidersInflight) return refreshProvidersInflight;
|
|
1596
1769
|
const task = (async () => {
|
|
1597
1770
|
const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(15_000) : undefined;
|
|
1771
|
+
// Refresh only live runtimes. Transient prompt-mutation services are never
|
|
1772
|
+
// retained, so there are no orphan ModelRuntimes to refresh here; the
|
|
1773
|
+
// returned catalog always comes from the active runtime via listProviders.
|
|
1598
1774
|
const runtimes = new Set();
|
|
1599
|
-
for (const services of servicesCache.values()) {
|
|
1600
|
-
const mr = services?.modelRuntime;
|
|
1601
|
-
if (mr) runtimes.add(mr);
|
|
1602
|
-
}
|
|
1603
1775
|
if (runtime?.session?.modelRuntime) runtimes.add(runtime.session.modelRuntime);
|
|
1604
1776
|
if (runtime?.services?.modelRuntime) runtimes.add(runtime.services.modelRuntime);
|
|
1605
1777
|
if (runtimeRegistry?.listAll) {
|
|
@@ -2014,12 +2186,13 @@ export function createSessionDaemon({
|
|
|
2014
2186
|
|
|
2015
2187
|
// A busy session keeps its current Pi resource loader until its turn settles.
|
|
2016
2188
|
// Mutation responses still need to reflect the committed file immediately,
|
|
2017
|
-
// so replace only editable top-level prompts from a fresh
|
|
2189
|
+
// so replace only editable top-level prompts from a fresh transient loader.
|
|
2018
2190
|
// Package/path/extension-contributed resources remain owned by the live session.
|
|
2191
|
+
// The transient services are dropped after use (no retention, no dispose hook
|
|
2192
|
+
// in the SDK) so repeated mutations cannot grow the daemon.
|
|
2019
2193
|
const resourcesAfterPromptMutation = async (targetDir) => {
|
|
2020
2194
|
const current = await resourceCatalog(targetDir);
|
|
2021
|
-
|
|
2022
|
-
const freshServices = await getServices(targetDir);
|
|
2195
|
+
const freshServices = await createFreshPromptServices(targetDir);
|
|
2023
2196
|
const freshEditable = promptResourcesFromLoader(freshServices.resourceLoader)
|
|
2024
2197
|
.filter((prompt) => prompt.editable === true);
|
|
2025
2198
|
return publicResources({
|
|
@@ -2032,7 +2205,6 @@ export function createSessionDaemon({
|
|
|
2032
2205
|
};
|
|
2033
2206
|
|
|
2034
2207
|
const finishPromptMutation = async (locations, targetDir) => {
|
|
2035
|
-
servicesCache.delete(targetDir);
|
|
2036
2208
|
const deferred = await refreshAffectedPromptRuntimes([...new Set(locations)], targetDir);
|
|
2037
2209
|
const resources = await resourcesAfterPromptMutation(targetDir);
|
|
2038
2210
|
return { ...resources, ...(deferred ? { deferred: true } : {}) };
|
|
@@ -2549,12 +2721,83 @@ export function createSessionDaemon({
|
|
|
2549
2721
|
return { text: text.join('\n'), images, files };
|
|
2550
2722
|
};
|
|
2551
2723
|
|
|
2724
|
+
const sendOperationFingerprint = ({ kind, payload }) => ({
|
|
2725
|
+
kind,
|
|
2726
|
+
text: payload.text,
|
|
2727
|
+
model: payload.model ?? null,
|
|
2728
|
+
thinking: payload.thinking ?? null,
|
|
2729
|
+
messageId: payload.messageId ?? null,
|
|
2730
|
+
attachments: Array.isArray(payload.attachments)
|
|
2731
|
+
? payload.attachments.map((attachment) => ({
|
|
2732
|
+
id: attachment?.id ?? null,
|
|
2733
|
+
name: attachment?.name ?? null,
|
|
2734
|
+
mime: attachment?.mime ?? null,
|
|
2735
|
+
size: attachment?.size ?? null,
|
|
2736
|
+
}))
|
|
2737
|
+
: null,
|
|
2738
|
+
});
|
|
2739
|
+
|
|
2552
2740
|
const sessionInput = async (payload, delivery) => {
|
|
2553
2741
|
if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
|
|
2554
2742
|
|| typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
|
|
2555
2743
|
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
|
|
2556
2744
|
}
|
|
2557
2745
|
if (payload.thinking !== undefined) validateThinking(payload.thinking);
|
|
2746
|
+
const kind = delivery ?? 'prompt';
|
|
2747
|
+
// Finding #3: claim the stable operation id at the authoritative
|
|
2748
|
+
// execution boundary — before Pi activation and before any attachment
|
|
2749
|
+
// side effect. A duplicate returns the original receipt; a payload
|
|
2750
|
+
// mismatch (same kind + session + id, different text/model/thinking/
|
|
2751
|
+
// message/attachments) rejects. A different kind or session is a
|
|
2752
|
+
// different intent, never a mismatch. Every claim settles so pending
|
|
2753
|
+
// duplicates never hang: acceptance retains the receipt, request-path
|
|
2754
|
+
// rejection frees the id (nothing executed).
|
|
2755
|
+
let claimEntry = null;
|
|
2756
|
+
if (payload.operationId !== undefined) {
|
|
2757
|
+
if (!isValidSendOperationId(payload.operationId)) {
|
|
2758
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send operation id is invalid.');
|
|
2759
|
+
}
|
|
2760
|
+
const claimed = sendOperations.claim({
|
|
2761
|
+
kind,
|
|
2762
|
+
sessionId: payload.sessionId,
|
|
2763
|
+
operationId: payload.operationId,
|
|
2764
|
+
fingerprint: stableFingerprint(sendOperationFingerprint({ kind, payload })),
|
|
2765
|
+
});
|
|
2766
|
+
if (claimed.outcome === 'mismatch') {
|
|
2767
|
+
throw new SessionDaemonProtocolError('OPERATION_PAYLOAD_MISMATCH', 'This operation id was already used with a different payload.');
|
|
2768
|
+
}
|
|
2769
|
+
if (claimed.outcome === 'expired') {
|
|
2770
|
+
throw new SessionDaemonProtocolError('OPERATION_EXPIRED', 'This operation id expired after the retention window; retry with a new operation id.');
|
|
2771
|
+
}
|
|
2772
|
+
if (claimed.outcome === 'overloaded') {
|
|
2773
|
+
throw new SessionDaemonProtocolError('SESSION_BUSY', 'The daemon is accepting too many sends; retry with backoff.');
|
|
2774
|
+
}
|
|
2775
|
+
if (claimed.outcome === 'accepted') return { ...claimed.receipt, deduplicated: true };
|
|
2776
|
+
if (claimed.outcome === 'pending') {
|
|
2777
|
+
const shared = await claimed.settled;
|
|
2778
|
+
return { ...shared.receipt, deduplicated: true };
|
|
2779
|
+
}
|
|
2780
|
+
claimEntry = claimed.entry;
|
|
2781
|
+
}
|
|
2782
|
+
try {
|
|
2783
|
+
const result = await runSessionInput(payload, delivery);
|
|
2784
|
+
claimEntry?.settle({ accepted: true, receipt: { accepted: true, messageId: result.messageId } });
|
|
2785
|
+
return result;
|
|
2786
|
+
} catch (error) {
|
|
2787
|
+
claimEntry?.settle({ accepted: false, error });
|
|
2788
|
+
throw error;
|
|
2789
|
+
}
|
|
2790
|
+
};
|
|
2791
|
+
|
|
2792
|
+
const runSessionInput = async (payload, delivery) => {
|
|
2793
|
+
if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
|
|
2794
|
+
|| typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
|
|
2795
|
+
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
|
|
2796
|
+
}
|
|
2797
|
+
if (payload.thinking !== undefined) validateThinking(payload.thinking);
|
|
2798
|
+
// Idle protection is owned by the request-dispatch guard: it holds the
|
|
2799
|
+
// session refcount across activation/acceptance, agent_start clears once
|
|
2800
|
+
// the turn is live, and settlement re-arms.
|
|
2558
2801
|
let activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2559
2802
|
let recreated = false;
|
|
2560
2803
|
try {
|
|
@@ -2566,10 +2809,15 @@ export function createSessionDaemon({
|
|
|
2566
2809
|
}
|
|
2567
2810
|
if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2568
2811
|
await flushPendingResourceReload(activeRuntime);
|
|
2812
|
+
// Requested delivery always travels as SDK `streamingBehavior`; the SDK
|
|
2813
|
+
// ignores it while idle and queues while streaming. Sampling
|
|
2814
|
+
// `isStreaming` before the model/attachment awaits would drop a queued
|
|
2815
|
+
// followUp/steer that arrives idle but races another sender that starts
|
|
2816
|
+
// during those awaits, so never gate the option on that early sample.
|
|
2569
2817
|
// After a provider stream dies, Pi can report idle while the UI still
|
|
2570
2818
|
// retries as steer/follow-up. Start a new turn instead of rejecting.
|
|
2571
|
-
const
|
|
2572
|
-
if (!
|
|
2819
|
+
const requestedDelivery = delivery ?? undefined;
|
|
2820
|
+
if (!requestedDelivery && activeRuntime.session.isStreaming) {
|
|
2573
2821
|
throw new SessionDaemonProtocolError('SESSION_BUSY', 'The Pi session already has an active run.');
|
|
2574
2822
|
}
|
|
2575
2823
|
beginSessionInput(activeRuntime);
|
|
@@ -2611,9 +2859,8 @@ export function createSessionDaemon({
|
|
|
2611
2859
|
|
|
2612
2860
|
const attachments = await prepareAttachmentContent(payload.attachments);
|
|
2613
2861
|
const text = [payload.text, attachments.text].filter(Boolean).join('\n\n');
|
|
2614
|
-
const
|
|
2615
|
-
|
|
2616
|
-
: text;
|
|
2862
|
+
const images = attachments.images.length > 0 ? attachments.images : undefined;
|
|
2863
|
+
const isSlashPrompt = typeof text === 'string' && text.startsWith('/');
|
|
2617
2864
|
const messageId = typeof payload.messageId === 'string' && payload.messageId.length > 0
|
|
2618
2865
|
? payload.messageId
|
|
2619
2866
|
: activeRuntime.session.sessionManager?.getLeafId?.() ?? `msg_${randomUUID()}`;
|
|
@@ -2624,9 +2871,11 @@ export function createSessionDaemon({
|
|
|
2624
2871
|
const generation = (sendGenerationBySession.get(payload.sessionId) ?? 0) + 1;
|
|
2625
2872
|
sendGenerationBySession.set(payload.sessionId, generation);
|
|
2626
2873
|
// Slash-prefixed input dispatches extension commands and skill/template
|
|
2627
|
-
// expansion exactly like the pi CLI and RPC modes; plain text
|
|
2628
|
-
//
|
|
2629
|
-
|
|
2874
|
+
// expansion exactly like the pi CLI and RPC modes; plain text uses
|
|
2875
|
+
// prompt() with template expansion disabled and source "extension",
|
|
2876
|
+
// matching sendUserMessage() semantics while exposing the SDK
|
|
2877
|
+
// preflightResult acceptance signal.
|
|
2878
|
+
enqueueUserStart(payload.sessionId, generation, attachments.files, requestedDelivery);
|
|
2630
2879
|
// Pi's `session.setModel()` notifies extensions (`model_select`) but not
|
|
2631
2880
|
// session subscribers, so an extension-driven model switch would otherwise
|
|
2632
2881
|
// never publish `session.model`. Snapshot the live model to reconcile
|
|
@@ -2635,20 +2884,81 @@ export function createSessionDaemon({
|
|
|
2635
2884
|
const prevModel = activeRuntime.session?.model
|
|
2636
2885
|
? { provider: activeRuntime.session.model.provider, id: activeRuntime.session.model.id }
|
|
2637
2886
|
: null;
|
|
2638
|
-
let
|
|
2887
|
+
let promptPromise;
|
|
2888
|
+
// True SDK acceptance: await the prompt preflight signal, not the full
|
|
2889
|
+
// agent turn. preflightResult(true) means accepted, queued, or handled;
|
|
2890
|
+
// preflightResult(false) is followed by a prompt rejection that must
|
|
2891
|
+
// propagate to the caller so dedup does not cache it as accepted.
|
|
2892
|
+
let preflightOutcome = null;
|
|
2893
|
+
let notifyPreflight;
|
|
2894
|
+
const preflightGate = new Promise((resolve) => { notifyPreflight = resolve; });
|
|
2895
|
+
const onPreflightResult = (accepted) => {
|
|
2896
|
+
if (preflightOutcome !== null) return;
|
|
2897
|
+
preflightOutcome = accepted === true;
|
|
2898
|
+
notifyPreflight(preflightOutcome);
|
|
2899
|
+
};
|
|
2639
2900
|
try {
|
|
2640
|
-
|
|
2641
|
-
? activeRuntime.session.prompt(
|
|
2901
|
+
promptPromise = isSlashPrompt
|
|
2902
|
+
? activeRuntime.session.prompt(text, {
|
|
2642
2903
|
source: 'rpc',
|
|
2643
|
-
...(
|
|
2904
|
+
...(images ? { images } : {}),
|
|
2905
|
+
...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
|
|
2906
|
+
preflightResult: onPreflightResult,
|
|
2644
2907
|
})
|
|
2645
|
-
: activeRuntime.session.
|
|
2908
|
+
: activeRuntime.session.prompt(text, {
|
|
2909
|
+
expandPromptTemplates: false,
|
|
2910
|
+
source: 'extension',
|
|
2911
|
+
...(images ? { images } : {}),
|
|
2912
|
+
...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
|
|
2913
|
+
preflightResult: onPreflightResult,
|
|
2914
|
+
});
|
|
2646
2915
|
} catch (error) {
|
|
2647
2916
|
removeUserStart(payload.sessionId, generation);
|
|
2648
2917
|
throw error;
|
|
2649
2918
|
}
|
|
2650
|
-
|
|
2919
|
+
// A settlement without a preflight signal resolves the gate so a missing
|
|
2920
|
+
// callback cannot hang acceptance. Resolve implies acceptance; reject
|
|
2921
|
+
// implies preflight failure whose real error is propagated below. The
|
|
2922
|
+
// installed SDK always signals, so this only covers test doubles.
|
|
2923
|
+
Promise.resolve(promptPromise).then(
|
|
2924
|
+
() => { if (preflightOutcome === null) { preflightOutcome = true; notifyPreflight(true); } },
|
|
2925
|
+
() => { if (preflightOutcome === null) { preflightOutcome = false; notifyPreflight(false); } },
|
|
2926
|
+
);
|
|
2927
|
+
const preflightAccepted = await preflightGate;
|
|
2928
|
+
if (!preflightAccepted) {
|
|
2929
|
+
let preflightError;
|
|
2930
|
+
try {
|
|
2931
|
+
await promptPromise;
|
|
2932
|
+
preflightError = new Error('The Pi session rejected the prompt before acceptance.');
|
|
2933
|
+
} catch (error) {
|
|
2934
|
+
preflightError = error;
|
|
2935
|
+
}
|
|
2651
2936
|
removeUserStart(payload.sessionId, generation);
|
|
2937
|
+
throw preflightError;
|
|
2938
|
+
}
|
|
2939
|
+
Promise.resolve(promptPromise).then(() => {
|
|
2940
|
+
// Queued sends resolve on queueing, before the queued user message
|
|
2941
|
+
// starts. Keep that file metadata until the per-delivery
|
|
2942
|
+
// `message_start` consumes it. Retention is decided at resolution
|
|
2943
|
+
// time from authoritative runtime state, not from the early
|
|
2944
|
+
// `requestedDelivery` flag alone: an idle followUp/steer that the SDK
|
|
2945
|
+
// ignored (new turn, no queue) and any handled extension command
|
|
2946
|
+
// (never emits a user start) must not retain forever. Only a still-
|
|
2947
|
+
// streaming session or a non-empty SDK queue proves the send is
|
|
2948
|
+
// queued; handled extension commands never retain even while
|
|
2949
|
+
// streaming.
|
|
2950
|
+
const stillStreaming = Boolean(activeRuntime.session?.isStreaming);
|
|
2951
|
+
let hasQueuedMessages = false;
|
|
2952
|
+
try {
|
|
2953
|
+
hasQueuedMessages = (activeRuntime.session?.getSteeringMessages?.().length ?? 0) > 0
|
|
2954
|
+
|| (activeRuntime.session?.getFollowUpMessages?.().length ?? 0) > 0;
|
|
2955
|
+
} catch {
|
|
2956
|
+
hasQueuedMessages = false;
|
|
2957
|
+
}
|
|
2958
|
+
const shouldRetain = !isExtensionCommand && (stillStreaming || hasQueuedMessages);
|
|
2959
|
+
if (!shouldRetain) {
|
|
2960
|
+
removeUserStart(payload.sessionId, generation);
|
|
2961
|
+
}
|
|
2652
2962
|
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
2653
2963
|
if (settledSendGenerationBySession.get(payload.sessionId) === generation) return;
|
|
2654
2964
|
const curModel = activeRuntime.session?.model;
|
|
@@ -2683,9 +2993,12 @@ export function createSessionDaemon({
|
|
|
2683
2993
|
Promise.resolve(activeRuntime.session.abort()).catch(() => {});
|
|
2684
2994
|
}).finally(() => {
|
|
2685
2995
|
endSessionInput(activeRuntime);
|
|
2686
|
-
void flushPendingResourceReload(activeRuntime).then((
|
|
2687
|
-
|
|
2688
|
-
|
|
2996
|
+
void flushPendingResourceReload(activeRuntime).then(() => {
|
|
2997
|
+
// Re-arm whenever the settlement left the session idle: this covers
|
|
2998
|
+
// extension commands that resolve without starting an agent turn
|
|
2999
|
+
// (no agent_settled follows) as well as ordinary turn completion.
|
|
3000
|
+
if (!shutdownRequestedBySession.has(payload.sessionId)) {
|
|
3001
|
+
touchIdleDisposal(payload.sessionId);
|
|
2689
3002
|
}
|
|
2690
3003
|
});
|
|
2691
3004
|
void flushPendingRuntimeRecreation().catch(() => {});
|
|
@@ -2700,6 +3013,8 @@ export function createSessionDaemon({
|
|
|
2700
3013
|
};
|
|
2701
3014
|
|
|
2702
3015
|
const treeForSession = async (sessionId, requestedDirectory) => {
|
|
3016
|
+
// Idle protection is owned by the request-dispatch guard; the release
|
|
3017
|
+
// re-arms even when projection below throws.
|
|
2703
3018
|
const activeRuntime = await activateSession(sessionId, requestedDirectory);
|
|
2704
3019
|
const nodes = activeRuntime.session.sessionManager?.getTree?.();
|
|
2705
3020
|
if (!Array.isArray(nodes)) throw new SessionDaemonProtocolError('SESSION_TREE_NOT_FOUND', 'Pi returned an invalid session tree.');
|
|
@@ -2716,6 +3031,8 @@ export function createSessionDaemon({
|
|
|
2716
3031
|
};
|
|
2717
3032
|
|
|
2718
3033
|
const deleteSession = async (sessionId, requestedDirectory) => {
|
|
3034
|
+
// Idle protection is owned by the request-dispatch guard. The release
|
|
3035
|
+
// touch is a no-op once the runtime is gone, so deletion never re-arms.
|
|
2719
3036
|
const active = runtimeRegistry?.findBySessionId(sessionId);
|
|
2720
3037
|
let targetDir = requestedDirectory ? await resolveDirectory(requestedDirectory) : active?.cwd || activeDirectory || cwd;
|
|
2721
3038
|
const activeSessionFile = active?.session?.sessionManager?.getSessionFile?.();
|
|
@@ -2746,6 +3063,8 @@ export function createSessionDaemon({
|
|
|
2746
3063
|
sendGenerationBySession.delete(sessionId);
|
|
2747
3064
|
settledSendGenerationBySession.delete(sessionId);
|
|
2748
3065
|
pendingUserStartsBySession.delete(sessionId);
|
|
3066
|
+
queueSizesBySession.delete(sessionId);
|
|
3067
|
+
queueShrinkBySession.delete(sessionId);
|
|
2749
3068
|
latestUserMessageIds.delete(sessionId);
|
|
2750
3069
|
latestAssistantMessageIds.delete(sessionId);
|
|
2751
3070
|
toolInputBySession.delete(sessionId);
|
|
@@ -2952,9 +3271,24 @@ export function createSessionDaemon({
|
|
|
2952
3271
|
}, sessionId, directory);
|
|
2953
3272
|
break;
|
|
2954
3273
|
}
|
|
2955
|
-
case 'queue_update':
|
|
2956
|
-
|
|
3274
|
+
case 'queue_update': {
|
|
3275
|
+
const steeringLength = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
3276
|
+
const followUpLength = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
3277
|
+
// Authoritative ownership for the next user start: only a shrink
|
|
3278
|
+
// tells which SDK queue owns it. Enqueues grow; dequeues shrink
|
|
3279
|
+
// immediately before their `message_start`. No text matching.
|
|
3280
|
+
const previous = queueSizesBySession.get(sessionId);
|
|
3281
|
+
if (previous) {
|
|
3282
|
+
const steeringShrank = steeringLength < previous.steering;
|
|
3283
|
+
const followUpShrank = followUpLength < previous.followUp;
|
|
3284
|
+
if (steeringShrank && !followUpShrank) queueShrinkBySession.set(sessionId, 'steer');
|
|
3285
|
+
else if (followUpShrank && !steeringShrank) queueShrinkBySession.set(sessionId, 'followUp');
|
|
3286
|
+
else if (steeringShrank || followUpShrank) queueShrinkBySession.delete(sessionId);
|
|
3287
|
+
}
|
|
3288
|
+
queueSizesBySession.set(sessionId, { steering: steeringLength, followUp: followUpLength });
|
|
3289
|
+
publish('session.queue', { steering: steeringLength, followUp: followUpLength }, sessionId, directory);
|
|
2957
3290
|
break;
|
|
3291
|
+
}
|
|
2958
3292
|
case 'agent_start':
|
|
2959
3293
|
clearIdleDisposal(sessionId);
|
|
2960
3294
|
retryStateBySession.delete(sessionId);
|
|
@@ -3081,7 +3415,15 @@ export function createSessionDaemon({
|
|
|
3081
3415
|
throw new SessionDaemonProtocolError('INVALID_REQUEST', 'The daemon request is invalid.');
|
|
3082
3416
|
}
|
|
3083
3417
|
|
|
3084
|
-
|
|
3418
|
+
// Central idle-lifetime guard: hold one session refcount across the
|
|
3419
|
+
// whole dispatch so a concurrent short read cannot re-arm (or a timer
|
|
3420
|
+
// fire and dispose) while a longer operation on the same session is
|
|
3421
|
+
// still using its runtime. The release re-arms when idle-safe even
|
|
3422
|
+
// after failure, so failed reads cannot leak. Invalid ids never clear.
|
|
3423
|
+
const guardedSessionId = sessionIdForIdleGuard(message);
|
|
3424
|
+
const guard = acquireSessionAccess(guardedSessionId);
|
|
3425
|
+
try {
|
|
3426
|
+
switch (message.command) {
|
|
3085
3427
|
case 'runtime.health':
|
|
3086
3428
|
writeFrame(socket, {
|
|
3087
3429
|
protocolVersion: PROTOCOL_VERSION,
|
|
@@ -3095,7 +3437,7 @@ export function createSessionDaemon({
|
|
|
3095
3437
|
'runtime.claim', 'runtime.shutdown',
|
|
3096
3438
|
'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
|
|
3097
3439
|
'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
|
|
3098
|
-
'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
|
|
3440
|
+
'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt', 'sessions.abort', 'sessions.setModel',
|
|
3099
3441
|
'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
|
|
3100
3442
|
'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
|
|
3101
3443
|
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
|
|
@@ -3318,7 +3660,8 @@ export function createSessionDaemon({
|
|
|
3318
3660
|
}
|
|
3319
3661
|
case 'sessions.open': {
|
|
3320
3662
|
const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
|
|
3321
|
-
|
|
3663
|
+
const detail = projectActiveSession(activeRuntime, activeRuntime.cwd, { limit: message.payload?.limit });
|
|
3664
|
+
writeDetailResponse(socket, message.requestId, detail);
|
|
3322
3665
|
return;
|
|
3323
3666
|
}
|
|
3324
3667
|
case 'sessions.messages': {
|
|
@@ -3368,7 +3711,8 @@ export function createSessionDaemon({
|
|
|
3368
3711
|
newLeafId: typeof newLeafId === 'string' ? newLeafId : null,
|
|
3369
3712
|
...(typeof result?.editorText === 'string' && result.editorText.length > 0 ? { editorText: result.editorText } : {}),
|
|
3370
3713
|
};
|
|
3371
|
-
|
|
3714
|
+
const navigateDetail = projectActiveSession(activeRuntime, activeRuntime.cwd);
|
|
3715
|
+
writeDetailResponse(socket, message.requestId, { ...navigateDetail, navigation });
|
|
3372
3716
|
return;
|
|
3373
3717
|
}
|
|
3374
3718
|
case 'sessions.fork':
|
|
@@ -3390,7 +3734,11 @@ export function createSessionDaemon({
|
|
|
3390
3734
|
await acquireResidentLease({ cwd: activeRuntime.cwd, sessionId: activeRuntime.session.sessionId });
|
|
3391
3735
|
}
|
|
3392
3736
|
rememberRuntimeSession();
|
|
3393
|
-
|
|
3737
|
+
const forkedDetail = projectActiveSession(activeRuntime, activeRuntime.cwd);
|
|
3738
|
+
// The guard re-arms the source session on release; arm the forked
|
|
3739
|
+
// identity explicitly since it was created inside this dispatch.
|
|
3740
|
+
touchIdleDisposal(activeRuntime.session?.sessionId);
|
|
3741
|
+
writeDetailResponse(socket, message.requestId, forkedDetail);
|
|
3394
3742
|
return;
|
|
3395
3743
|
}
|
|
3396
3744
|
case 'sessions.create': {
|
|
@@ -3406,6 +3754,42 @@ export function createSessionDaemon({
|
|
|
3406
3754
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
3407
3755
|
return;
|
|
3408
3756
|
}
|
|
3757
|
+
case 'sessions.sendReceipt': {
|
|
3758
|
+
// Exact read-only receipt lookup for an uncertain send. Requires the
|
|
3759
|
+
// full `kind + sessionId + operationId` identity; never invokes Pi,
|
|
3760
|
+
// never mutates the registry except bounded expiry eviction inside
|
|
3761
|
+
// `query()`. Returns `accepted` (retained receipt), `pending`
|
|
3762
|
+
// (still-accepting claim), `expired` (seen but retention gone —
|
|
3763
|
+
// outcome unknown, never assume success), or `unknown` (never seen
|
|
3764
|
+
// in this retention window, tombstone pressure, post-restart, or
|
|
3765
|
+
// rejected before Pi ran so nothing executed).
|
|
3766
|
+
const payload = message.payload ?? {};
|
|
3767
|
+
const kind = payload.kind;
|
|
3768
|
+
const sessionId = payload.sessionId;
|
|
3769
|
+
const operationId = payload.operationId;
|
|
3770
|
+
if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp')
|
|
3771
|
+
|| typeof sessionId !== 'string' || sessionId.length === 0
|
|
3772
|
+
|| !isValidSendOperationId(operationId)) {
|
|
3773
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send receipt lookup is invalid.');
|
|
3774
|
+
}
|
|
3775
|
+
const lookup = sendOperations.query({ kind, sessionId, operationId });
|
|
3776
|
+
if (lookup.status === 'accepted') {
|
|
3777
|
+
writeFrame(socket, {
|
|
3778
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
3779
|
+
kind: 'response',
|
|
3780
|
+
requestId: message.requestId,
|
|
3781
|
+
result: { status: 'accepted', receipt: lookup.receipt },
|
|
3782
|
+
});
|
|
3783
|
+
return;
|
|
3784
|
+
}
|
|
3785
|
+
writeFrame(socket, {
|
|
3786
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
3787
|
+
kind: 'response',
|
|
3788
|
+
requestId: message.requestId,
|
|
3789
|
+
result: { status: lookup.status },
|
|
3790
|
+
});
|
|
3791
|
+
return;
|
|
3792
|
+
}
|
|
3409
3793
|
case 'sessions.abort': {
|
|
3410
3794
|
const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
|
|
3411
3795
|
const streaming = activeRuntime.session.isStreaming;
|
|
@@ -3458,7 +3842,7 @@ export function createSessionDaemon({
|
|
|
3458
3842
|
};
|
|
3459
3843
|
compactionStateBySession.set(message.payload.sessionId, compaction);
|
|
3460
3844
|
publish('session.compaction', compaction, message.payload.sessionId, activeRuntime.cwd);
|
|
3461
|
-
|
|
3845
|
+
touchIdleDisposal(message.payload.sessionId);
|
|
3462
3846
|
});
|
|
3463
3847
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { accepted: true } });
|
|
3464
3848
|
return;
|
|
@@ -3466,6 +3850,9 @@ export function createSessionDaemon({
|
|
|
3466
3850
|
default:
|
|
3467
3851
|
throw new SessionDaemonProtocolError('UNKNOWN_COMMAND', 'The daemon command is not supported.');
|
|
3468
3852
|
}
|
|
3853
|
+
} finally {
|
|
3854
|
+
if (guard !== undefined) releaseSessionAccess(guard);
|
|
3855
|
+
}
|
|
3469
3856
|
};
|
|
3470
3857
|
|
|
3471
3858
|
const onConnection = (socket) => {
|
|
@@ -3515,13 +3902,12 @@ export function createSessionDaemon({
|
|
|
3515
3902
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'authenticated' });
|
|
3516
3903
|
const requestedSessionId = typeof message.sessionId === 'string' && message.sessionId.length > 0 ? message.sessionId : undefined;
|
|
3517
3904
|
const fromSequence = Number.isSafeInteger(message.fromSequence) && message.fromSequence >= 0 ? message.fromSequence : undefined;
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
}
|
|
3905
|
+
// Contiguity is judged on the global retained suffix while delivery
|
|
3906
|
+
// stays session-filtered, so a filtered client never replays through
|
|
3907
|
+
// a gap left by eviction, an oversized event, an empty ring, or a
|
|
3908
|
+
// future cursor: all of those take the snapshot fallback below.
|
|
3909
|
+
if (fromSequence !== undefined && replayLog.canReplay(fromSequence, sequence)) {
|
|
3910
|
+
for (const cachedLine of replayLog.linesAfter(fromSequence, requestedSessionId)) writeLine(socket, cachedLine);
|
|
3525
3911
|
} else {
|
|
3526
3912
|
publishSnapshot(socket, requestedSessionId);
|
|
3527
3913
|
}
|
|
@@ -3548,6 +3934,7 @@ export function createSessionDaemon({
|
|
|
3548
3934
|
},
|
|
3549
3935
|
async start() {
|
|
3550
3936
|
if (started) return;
|
|
3937
|
+
stopping = false;
|
|
3551
3938
|
await validatePiSessionJsonlDirectory({ cwd, agentDir });
|
|
3552
3939
|
runtimeRegistry = createSessionRuntimeRegistry({
|
|
3553
3940
|
onSessionEvent: ({ cwd: eventCwd, sessionId: eventSessionId }, event) => publishSessionEvent(eventSessionId, event, eventCwd),
|
|
@@ -3584,6 +3971,10 @@ export function createSessionDaemon({
|
|
|
3584
3971
|
},
|
|
3585
3972
|
async stop() {
|
|
3586
3973
|
if (!started) return;
|
|
3974
|
+
// Async request and reload completions may still release their guards
|
|
3975
|
+
// while teardown awaits sockets/disposal. They must not arm new timers.
|
|
3976
|
+
stopping = true;
|
|
3977
|
+
clearAllIdleDisposals();
|
|
3587
3978
|
for (const attempt of loginAttempts.values()) {
|
|
3588
3979
|
attempt.controller.abort();
|
|
3589
3980
|
attempt.rejectPrompt?.(new Error('Provider login cancelled.'));
|
|
@@ -3596,10 +3987,11 @@ export function createSessionDaemon({
|
|
|
3596
3987
|
toolStartedAt.clear();
|
|
3597
3988
|
completedToolTimings.clear();
|
|
3598
3989
|
shutdownRequestedBySession.clear();
|
|
3599
|
-
disposingSessionIds.clear();
|
|
3600
3990
|
sendGenerationBySession.clear();
|
|
3601
3991
|
settledSendGenerationBySession.clear();
|
|
3602
3992
|
pendingUserStartsBySession.clear();
|
|
3993
|
+
queueSizesBySession.clear();
|
|
3994
|
+
queueShrinkBySession.clear();
|
|
3603
3995
|
latestUserMessageIds.clear();
|
|
3604
3996
|
latestAssistantMessageIds.clear();
|
|
3605
3997
|
for (const client of clients) client.destroy();
|
|
@@ -3608,6 +4000,17 @@ export function createSessionDaemon({
|
|
|
3608
4000
|
await new Promise((resolve, reject) => {
|
|
3609
4001
|
server.close((error) => error ? reject(error) : resolve());
|
|
3610
4002
|
});
|
|
4003
|
+
// Teardown must not double-dispose a runtime with an in-flight idle
|
|
4004
|
+
// disposal or release its lease twice: stop new timers, wait for the
|
|
4005
|
+
// racing disposal, then dispose what remains.
|
|
4006
|
+
clearAllIdleDisposals();
|
|
4007
|
+
activeSessionRequests.clear();
|
|
4008
|
+
const inFlightIdleDisposals = [...disposingSessionPromises.values()];
|
|
4009
|
+
if (inFlightIdleDisposals.length > 0) {
|
|
4010
|
+
await Promise.allSettled(inFlightIdleDisposals);
|
|
4011
|
+
}
|
|
4012
|
+
disposingSessionPromises.clear();
|
|
4013
|
+
disposingSessionIds.clear();
|
|
3611
4014
|
pendingRuntimeRecreation = false;
|
|
3612
4015
|
runtimeRecreationRevision += 1;
|
|
3613
4016
|
await disposeRuntime();
|
|
@@ -3622,3 +4025,7 @@ function writeFrame(socket, frame) {
|
|
|
3622
4025
|
if (!socket.destroyed) socket.write(`${JSON.stringify(frame)}\n`);
|
|
3623
4026
|
}
|
|
3624
4027
|
|
|
4028
|
+
function writeLine(socket, line) {
|
|
4029
|
+
if (!socket.destroyed) socket.write(line);
|
|
4030
|
+
}
|
|
4031
|
+
|