@pi-chamber/web 0.9.5 → 0.9.7
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/dist/assets/DiagramView-BvrCkm_z.js +1 -0
- package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DMvRLRN1.js} +1 -1
- package/dist/assets/FileSaveConflictDialog-DGa9u43J.js +3 -0
- package/dist/assets/FilesView-CNHu4RnC.js +6 -0
- package/dist/assets/{GitView-BNkzec7G.js → GitView-Cbepz-bR.js} +3 -3
- package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-C2X5oXQm.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-BanSCkPy.js} +2 -2
- package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-i_9BIlgo.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DxS_rFuS.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-AVghToww.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-CDRZswx-.js} +1 -1
- package/dist/assets/SettingsView-hyAGp836.js +2 -0
- package/dist/assets/SettingsWindow-BfPUzBbq.js +1 -0
- package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-CJ87b80H.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-bF486Lz1.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-CFpvcZ1g.js} +1 -1
- package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-DesjbW8a.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-CsAu9rOt.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-rILslsBJ.js} +1 -1
- package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-D_31YElh.js} +1 -1
- package/dist/assets/index-BXgR2dKM.css +1 -0
- package/dist/assets/index-BZpvAhrX.js +8 -0
- package/dist/assets/{index-B8Wt2aN3.js → index-CXLVW_GG.js} +1 -1
- package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-BX609Lau.js} +1 -1
- package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-FgBWqu9b.js} +1 -1
- package/dist/assets/{main-DCK6lLCo.js → main-C_pL2r_k.js} +2 -2
- package/dist/assets/{main-C1OSzD-E.js → main-tv2uysSs.js} +7 -7
- package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-D3Ibaffd.js} +1 -1
- package/dist/assets/{miniChat-CXiSlptL.js → miniChat-B0xQlBzZ.js} +2 -2
- package/dist/assets/{mobile-D0HVxiyJ.js → mobile-BmSlVuhn.js} +2 -2
- package/dist/assets/renderElectronMiniChatApp-C4xZzAnn.js +2 -0
- package/dist/assets/renderMobileApp-Bi8wTGd5.js +11 -0
- package/dist/assets/runtimeEndpointReset-B6_gFvBD.js +53 -0
- package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-egSD9pqj.js} +1 -1
- package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-C9QQrBIx.js} +104 -104
- package/dist/assets/useFilesViewSearch-BTZutbn-.js +7 -0
- package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-BZcHxSo-.js} +1 -1
- package/dist/assets/useSwitcherItems-Dw5tHQh8.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-0f_rLdj_.js} +2 -2
- package/dist/assets/{web-components-B5sMa_kC.js → web-components-CYngz9Ml.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/index.js +17 -3
- package/server/lib/client-auth/DOCUMENTATION.md +184 -0
- package/server/lib/client-auth/live-revocation.test.js +567 -0
- package/server/lib/client-auth/principal-tracker.js +383 -0
- package/server/lib/client-auth/principal-tracker.test.js +321 -0
- package/server/lib/client-auth/remote-clients.js +31 -0
- package/server/lib/client-auth/remote-clients.test.js +44 -0
- 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/event-stream.js +269 -0
- package/server/lib/pi/event-stream.test.js +776 -0
- package/server/lib/pi/routes.js +132 -28
- package/server/lib/pi/routes.test.js +213 -4
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +6 -4
- package/server/lib/pi/session-daemon/ipc-client.js +19 -15
- package/server/lib/pi/session-daemon/ipc-client.test.js +113 -1
- package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
- package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -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-epoch.test.js +349 -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 +339 -37
- package/server/lib/pi/session-daemon/session-daemon.test.js +47 -17
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
- package/server/lib/pi/session-daemon/session-replay.test.js +11 -4
- package/server/lib/pi/session-daemon/supervisor.js +30 -5
- package/server/lib/pi/session-daemon/supervisor.test.js +4 -3
- package/server/lib/pi/ui-settings-store.js +1 -1
- package/server/lib/pi/ui-settings-store.test.js +3 -1
- package/server/lib/server/core-routes.js +11 -1
- package/server/lib/server/cors.js +6 -0
- package/server/lib/server/cors.test.js +3 -0
- package/server/lib/stt/DOCUMENTATION.md +2 -0
- package/server/lib/stt/runtime.js +39 -2
- package/server/lib/stt/runtime.test.js +53 -0
- package/server/lib/terminal/DOCUMENTATION.md +2 -0
- package/server/lib/terminal/runtime.js +48 -2
- package/server/lib/terminal/runtime.test.js +35 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +13 -4
- package/server/lib/ui-auth/ui-auth.js +98 -0
- package/server/lib/ui-auth/ui-auth.test.js +249 -0
- package/server/lib/workspace/host.js +9 -3
- package/server/lib/workspace/host.test.js +15 -0
- package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
- package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
- package/dist/assets/FilesView-CJytSUAX.js +0 -6
- package/dist/assets/SettingsView-z8uf0XyM.js +0 -2
- package/dist/assets/SettingsWindow-CPDmgNg2.js +0 -1
- package/dist/assets/index-DIF8b4bh.css +0 -1
- package/dist/assets/index-jrfQYSvP.js +0 -8
- package/dist/assets/renderElectronMiniChatApp-BcG209a4.js +0 -2
- package/dist/assets/renderMobileApp-B5x_PWlc.js +0 -11
- package/dist/assets/runtimeEndpointReset-CUiPe6dQ.js +0 -53
- package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
- package/dist/assets/useSwitcherItems-_RSo3F-A.js +0 -1
|
@@ -35,6 +35,11 @@ import {
|
|
|
35
35
|
} from './ipc-protocol.js';
|
|
36
36
|
import { createMessageEntryAliases } from './message-entry-aliases.js';
|
|
37
37
|
import { createSessionReplayLog } from './session-replay.js';
|
|
38
|
+
import {
|
|
39
|
+
createSendOperationRegistry,
|
|
40
|
+
isValidSendOperationId,
|
|
41
|
+
stableFingerprint,
|
|
42
|
+
} from './send-operation-registry.js';
|
|
38
43
|
import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
|
|
39
44
|
import { createSkillReadClassifier } from './skill-read-classifier.js';
|
|
40
45
|
import { createSessionRuntimeRegistry } from './runtime-registry.js';
|
|
@@ -164,6 +169,7 @@ export function createSessionDaemon({
|
|
|
164
169
|
onOwnershipClaim,
|
|
165
170
|
onShutdown,
|
|
166
171
|
idleTimeoutMs = 5 * 60 * 1_000,
|
|
172
|
+
sendOperationTtlMs = 10 * 60 * 1_000,
|
|
167
173
|
listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
|
|
168
174
|
cwd: sessionCwd,
|
|
169
175
|
agentDir: sessionAgentDir,
|
|
@@ -201,6 +207,9 @@ export function createSessionDaemon({
|
|
|
201
207
|
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs < 0) {
|
|
202
208
|
throw new SessionDaemonProtocolError('INVALID_IDLE_TIMEOUT', 'The session daemon idle timeout is invalid.');
|
|
203
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
|
+
}
|
|
204
213
|
|
|
205
214
|
let server;
|
|
206
215
|
let runtime;
|
|
@@ -248,6 +257,13 @@ export function createSessionDaemon({
|
|
|
248
257
|
let idleDisposeTimer;
|
|
249
258
|
let dormantSession;
|
|
250
259
|
let sequence = 0;
|
|
260
|
+
// Opaque, random, public stream-lifetime identifier. It regenerates on every
|
|
261
|
+
// daemon process start (restart, crash, or replacement), so clients can
|
|
262
|
+
// distinguish "same daemon, contiguous sequence" from "new daemon, sequence
|
|
263
|
+
// restarted from zero". It is deliberately NOT derived from the daemon id,
|
|
264
|
+
// profile key, pid, or any other private identity: it exists only to be
|
|
265
|
+
// compared for equality on the public wire.
|
|
266
|
+
const streamEpoch = randomUUID().replace(/-/g, '');
|
|
251
267
|
let started = false;
|
|
252
268
|
let stopping = false;
|
|
253
269
|
const knownDirectories = new Set([cwd]);
|
|
@@ -304,6 +320,16 @@ export function createSessionDaemon({
|
|
|
304
320
|
// runtimes dirty and reload them at the next safe lifecycle edge. Other
|
|
305
321
|
// Pi configuration writes queue resident-runtime recreation at that edge.
|
|
306
322
|
const activeSessionInputs = new Map();
|
|
323
|
+
// Send-intent deduplication (finding #3): one stable operation id per send
|
|
324
|
+
// intent; the registry is the authoritative execution boundary before Pi.
|
|
325
|
+
// Identity is `kind + sessionId + operationId`: the same id on a different
|
|
326
|
+
// kind or session is a different intent, never a payload mismatch.
|
|
327
|
+
// Retention is bounded (ttlMs/maxEntries, tombstones capped) and in-memory
|
|
328
|
+
// per daemon process — a restart loses receipts, which is the documented
|
|
329
|
+
// crash window. This split performs no stream-epoch guard and no
|
|
330
|
+
// per-session config/acceptance lock; every claim settles so pending
|
|
331
|
+
// duplicates never hang.
|
|
332
|
+
const sendOperations = createSendOperationRegistry({ ttlMs: sendOperationTtlMs });
|
|
307
333
|
const pendingResourceReloads = new Set();
|
|
308
334
|
const resourceReloadsByRuntime = new Map();
|
|
309
335
|
let resourceReloadQueue = Promise.resolve();
|
|
@@ -315,26 +341,70 @@ export function createSessionDaemon({
|
|
|
315
341
|
let runtimeRecreationRevision = 0;
|
|
316
342
|
let runtimeRecreationTask = null;
|
|
317
343
|
// Pi emits each user message start before its persisted entry is readable.
|
|
318
|
-
// Keep prompt metadata
|
|
319
|
-
//
|
|
344
|
+
// Keep prompt file metadata keyed by delivery kind so a queued followUp
|
|
345
|
+
// that a later steer overtakes cannot swap attachment footers. Steering
|
|
346
|
+
// drains before followUp in the SDK loop regardless of send order, so a
|
|
347
|
+
// single FIFO would attach the wrong files. SDK `queue_update` is the
|
|
348
|
+
// authoritative ownership signal: the queue that shrank owns the next
|
|
349
|
+
// user start. Direct (non-queued) starts emit no shrink and fall back to
|
|
350
|
+
// oldest-by-generation across kinds. No text/content heuristics are used.
|
|
320
351
|
const pendingUserStartsBySession = new Map();
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
pendingUserStartsBySession.
|
|
352
|
+
const queueSizesBySession = new Map();
|
|
353
|
+
const queueShrinkBySession = new Map();
|
|
354
|
+
const pendingBucketsFor = (sessionId) => {
|
|
355
|
+
let buckets = pendingUserStartsBySession.get(sessionId);
|
|
356
|
+
if (!buckets) {
|
|
357
|
+
buckets = { prompt: [], steer: [], followUp: [] };
|
|
358
|
+
pendingUserStartsBySession.set(sessionId, buckets);
|
|
359
|
+
}
|
|
360
|
+
return buckets;
|
|
361
|
+
};
|
|
362
|
+
const hasPendingUserStarts = (buckets) => (
|
|
363
|
+
buckets.prompt.length > 0 || buckets.steer.length > 0 || buckets.followUp.length > 0
|
|
364
|
+
);
|
|
365
|
+
const enqueueUserStart = (sessionId, generation, files, deliveryKind) => {
|
|
366
|
+
const buckets = pendingBucketsFor(sessionId);
|
|
367
|
+
const bucket = deliveryKind === 'steer' || deliveryKind === 'followUp' ? deliveryKind : 'prompt';
|
|
368
|
+
buckets[bucket].push({ generation, files, deliveryKind: bucket });
|
|
369
|
+
};
|
|
370
|
+
const takeOldestUserStart = (buckets) => {
|
|
371
|
+
let oldestBucket;
|
|
372
|
+
let oldestGeneration = Infinity;
|
|
373
|
+
for (const bucket of ['prompt', 'steer', 'followUp']) {
|
|
374
|
+
const first = buckets[bucket][0];
|
|
375
|
+
if (first && first.generation < oldestGeneration) {
|
|
376
|
+
oldestGeneration = first.generation;
|
|
377
|
+
oldestBucket = bucket;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (!oldestBucket) return undefined;
|
|
381
|
+
const next = buckets[oldestBucket].shift();
|
|
382
|
+
return next;
|
|
325
383
|
};
|
|
326
384
|
const takeUserStart = (sessionId) => {
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
385
|
+
const buckets = pendingUserStartsBySession.get(sessionId);
|
|
386
|
+
if (!buckets) return undefined;
|
|
387
|
+
const shrink = queueShrinkBySession.get(sessionId);
|
|
388
|
+
queueShrinkBySession.delete(sessionId);
|
|
389
|
+
let next;
|
|
390
|
+
if ((shrink === 'steer' || shrink === 'followUp') && buckets[shrink].length > 0) {
|
|
391
|
+
next = buckets[shrink].shift();
|
|
392
|
+
} else {
|
|
393
|
+
next = takeOldestUserStart(buckets);
|
|
394
|
+
}
|
|
395
|
+
if (!hasPendingUserStarts(buckets)) {
|
|
396
|
+
pendingUserStartsBySession.delete(sessionId);
|
|
397
|
+
}
|
|
330
398
|
return next;
|
|
331
399
|
};
|
|
332
400
|
const removeUserStart = (sessionId, generation) => {
|
|
333
|
-
const
|
|
334
|
-
if (!
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
|
|
401
|
+
const buckets = pendingUserStartsBySession.get(sessionId);
|
|
402
|
+
if (!buckets) return;
|
|
403
|
+
for (const bucket of ['prompt', 'steer', 'followUp']) {
|
|
404
|
+
const filtered = buckets[bucket].filter((entry) => entry.generation !== generation);
|
|
405
|
+
buckets[bucket] = filtered;
|
|
406
|
+
}
|
|
407
|
+
if (!hasPendingUserStarts(buckets)) pendingUserStartsBySession.delete(sessionId);
|
|
338
408
|
};
|
|
339
409
|
const shutdownRequestedBySession = new Set();
|
|
340
410
|
const disposingSessionIds = new Set();
|
|
@@ -468,6 +538,7 @@ export function createSessionDaemon({
|
|
|
468
538
|
protocolVersion: PROTOCOL_VERSION,
|
|
469
539
|
kind: 'event',
|
|
470
540
|
event,
|
|
541
|
+
streamEpoch,
|
|
471
542
|
sequence: ++sequence,
|
|
472
543
|
payload: {
|
|
473
544
|
sessionId,
|
|
@@ -544,7 +615,7 @@ export function createSessionDaemon({
|
|
|
544
615
|
};
|
|
545
616
|
};
|
|
546
617
|
|
|
547
|
-
const publishSnapshot = (socket, requestedSessionId) => {
|
|
618
|
+
const publishSnapshot = (socket, requestedSessionId, { resync = false } = {}) => {
|
|
548
619
|
const targetRuntime = requestedSessionId ? runtimeRegistry?.findBySessionId(requestedSessionId) : runtime;
|
|
549
620
|
const session = targetRuntime?.session
|
|
550
621
|
? { sessionId: targetRuntime.session.sessionId, isStreaming: targetRuntime.session.isStreaming }
|
|
@@ -566,10 +637,15 @@ export function createSessionDaemon({
|
|
|
566
637
|
protocolVersion: PROTOCOL_VERSION,
|
|
567
638
|
kind: 'event',
|
|
568
639
|
event: 'session.snapshot',
|
|
640
|
+
streamEpoch,
|
|
569
641
|
sequence: snapshotSequence,
|
|
570
642
|
payload: {
|
|
571
643
|
...(session.sessionId ? { sessionId: session.sessionId } : {}),
|
|
572
644
|
directory: targetDirectory,
|
|
645
|
+
// `resync` tells the client the requested cursor could not be replayed
|
|
646
|
+
// (replay window expired or a daemon restart reset the sequence), so
|
|
647
|
+
// this snapshot is a recovery baseline rather than a routine attach.
|
|
648
|
+
...(resync ? { resync: true } : {}),
|
|
573
649
|
isStreaming: session.isStreaming ?? false,
|
|
574
650
|
lifecycle: retry ? 'retry' : session.isStreaming ? 'busy' : 'idle',
|
|
575
651
|
...(retry ? { retry } : {}),
|
|
@@ -1501,7 +1577,10 @@ export function createSessionDaemon({
|
|
|
1501
1577
|
protocolVersion: PROTOCOL_VERSION,
|
|
1502
1578
|
kind: 'response',
|
|
1503
1579
|
requestId,
|
|
1504
|
-
|
|
1580
|
+
// Stamp the stream lifetime so a client can reject a detail response
|
|
1581
|
+
// that was generated by a previous daemon process (stale sequence
|
|
1582
|
+
// space) after observing an epoch change.
|
|
1583
|
+
result: { ...detail, streamEpoch },
|
|
1505
1584
|
};
|
|
1506
1585
|
if (Buffer.byteLength(JSON.stringify(frame)) > MAX_FRAME_BYTES) {
|
|
1507
1586
|
throw new SessionDaemonProtocolError(
|
|
@@ -2658,7 +2737,75 @@ export function createSessionDaemon({
|
|
|
2658
2737
|
return { text: text.join('\n'), images, files };
|
|
2659
2738
|
};
|
|
2660
2739
|
|
|
2740
|
+
const sendOperationFingerprint = ({ kind, payload }) => ({
|
|
2741
|
+
kind,
|
|
2742
|
+
text: payload.text,
|
|
2743
|
+
model: payload.model ?? null,
|
|
2744
|
+
thinking: payload.thinking ?? null,
|
|
2745
|
+
messageId: payload.messageId ?? null,
|
|
2746
|
+
attachments: Array.isArray(payload.attachments)
|
|
2747
|
+
? payload.attachments.map((attachment) => ({
|
|
2748
|
+
id: attachment?.id ?? null,
|
|
2749
|
+
name: attachment?.name ?? null,
|
|
2750
|
+
mime: attachment?.mime ?? null,
|
|
2751
|
+
size: attachment?.size ?? null,
|
|
2752
|
+
}))
|
|
2753
|
+
: null,
|
|
2754
|
+
});
|
|
2755
|
+
|
|
2661
2756
|
const sessionInput = async (payload, delivery) => {
|
|
2757
|
+
if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
|
|
2758
|
+
|| typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
|
|
2759
|
+
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
|
|
2760
|
+
}
|
|
2761
|
+
if (payload.thinking !== undefined) validateThinking(payload.thinking);
|
|
2762
|
+
const kind = delivery ?? 'prompt';
|
|
2763
|
+
// Finding #3: claim the stable operation id at the authoritative
|
|
2764
|
+
// execution boundary — before Pi activation and before any attachment
|
|
2765
|
+
// side effect. A duplicate returns the original receipt; a payload
|
|
2766
|
+
// mismatch (same kind + session + id, different text/model/thinking/
|
|
2767
|
+
// message/attachments) rejects. A different kind or session is a
|
|
2768
|
+
// different intent, never a mismatch. Every claim settles so pending
|
|
2769
|
+
// duplicates never hang: acceptance retains the receipt, request-path
|
|
2770
|
+
// rejection frees the id (nothing executed).
|
|
2771
|
+
let claimEntry = null;
|
|
2772
|
+
if (payload.operationId !== undefined) {
|
|
2773
|
+
if (!isValidSendOperationId(payload.operationId)) {
|
|
2774
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send operation id is invalid.');
|
|
2775
|
+
}
|
|
2776
|
+
const claimed = sendOperations.claim({
|
|
2777
|
+
kind,
|
|
2778
|
+
sessionId: payload.sessionId,
|
|
2779
|
+
operationId: payload.operationId,
|
|
2780
|
+
fingerprint: stableFingerprint(sendOperationFingerprint({ kind, payload })),
|
|
2781
|
+
});
|
|
2782
|
+
if (claimed.outcome === 'mismatch') {
|
|
2783
|
+
throw new SessionDaemonProtocolError('OPERATION_PAYLOAD_MISMATCH', 'This operation id was already used with a different payload.');
|
|
2784
|
+
}
|
|
2785
|
+
if (claimed.outcome === 'expired') {
|
|
2786
|
+
throw new SessionDaemonProtocolError('OPERATION_EXPIRED', 'This operation id expired after the retention window; retry with a new operation id.');
|
|
2787
|
+
}
|
|
2788
|
+
if (claimed.outcome === 'overloaded') {
|
|
2789
|
+
throw new SessionDaemonProtocolError('SESSION_BUSY', 'The daemon is accepting too many sends; retry with backoff.');
|
|
2790
|
+
}
|
|
2791
|
+
if (claimed.outcome === 'accepted') return { ...claimed.receipt, deduplicated: true };
|
|
2792
|
+
if (claimed.outcome === 'pending') {
|
|
2793
|
+
const shared = await claimed.settled;
|
|
2794
|
+
return { ...shared.receipt, deduplicated: true };
|
|
2795
|
+
}
|
|
2796
|
+
claimEntry = claimed.entry;
|
|
2797
|
+
}
|
|
2798
|
+
try {
|
|
2799
|
+
const result = await runSessionInput(payload, delivery);
|
|
2800
|
+
claimEntry?.settle({ accepted: true, receipt: { accepted: true, messageId: result.messageId } });
|
|
2801
|
+
return result;
|
|
2802
|
+
} catch (error) {
|
|
2803
|
+
claimEntry?.settle({ accepted: false, error });
|
|
2804
|
+
throw error;
|
|
2805
|
+
}
|
|
2806
|
+
};
|
|
2807
|
+
|
|
2808
|
+
const runSessionInput = async (payload, delivery) => {
|
|
2662
2809
|
if (!payload || typeof payload !== 'object' || typeof payload.sessionId !== 'string'
|
|
2663
2810
|
|| typeof payload.text !== 'string' || payload.text.length === 0 || Buffer.byteLength(payload.text) > 64 * 1024) {
|
|
2664
2811
|
throw new SessionDaemonProtocolError('INVALID_PROMPT', 'The session prompt is invalid.');
|
|
@@ -2678,10 +2825,15 @@ export function createSessionDaemon({
|
|
|
2678
2825
|
}
|
|
2679
2826
|
if (recreated) activeRuntime = await activateSession(payload.sessionId, payload.directory);
|
|
2680
2827
|
await flushPendingResourceReload(activeRuntime);
|
|
2828
|
+
// Requested delivery always travels as SDK `streamingBehavior`; the SDK
|
|
2829
|
+
// ignores it while idle and queues while streaming. Sampling
|
|
2830
|
+
// `isStreaming` before the model/attachment awaits would drop a queued
|
|
2831
|
+
// followUp/steer that arrives idle but races another sender that starts
|
|
2832
|
+
// during those awaits, so never gate the option on that early sample.
|
|
2681
2833
|
// After a provider stream dies, Pi can report idle while the UI still
|
|
2682
2834
|
// retries as steer/follow-up. Start a new turn instead of rejecting.
|
|
2683
|
-
const
|
|
2684
|
-
if (!
|
|
2835
|
+
const requestedDelivery = delivery ?? undefined;
|
|
2836
|
+
if (!requestedDelivery && activeRuntime.session.isStreaming) {
|
|
2685
2837
|
throw new SessionDaemonProtocolError('SESSION_BUSY', 'The Pi session already has an active run.');
|
|
2686
2838
|
}
|
|
2687
2839
|
beginSessionInput(activeRuntime);
|
|
@@ -2723,9 +2875,8 @@ export function createSessionDaemon({
|
|
|
2723
2875
|
|
|
2724
2876
|
const attachments = await prepareAttachmentContent(payload.attachments);
|
|
2725
2877
|
const text = [payload.text, attachments.text].filter(Boolean).join('\n\n');
|
|
2726
|
-
const
|
|
2727
|
-
|
|
2728
|
-
: text;
|
|
2878
|
+
const images = attachments.images.length > 0 ? attachments.images : undefined;
|
|
2879
|
+
const isSlashPrompt = typeof text === 'string' && text.startsWith('/');
|
|
2729
2880
|
const messageId = typeof payload.messageId === 'string' && payload.messageId.length > 0
|
|
2730
2881
|
? payload.messageId
|
|
2731
2882
|
: activeRuntime.session.sessionManager?.getLeafId?.() ?? `msg_${randomUUID()}`;
|
|
@@ -2736,9 +2887,11 @@ export function createSessionDaemon({
|
|
|
2736
2887
|
const generation = (sendGenerationBySession.get(payload.sessionId) ?? 0) + 1;
|
|
2737
2888
|
sendGenerationBySession.set(payload.sessionId, generation);
|
|
2738
2889
|
// Slash-prefixed input dispatches extension commands and skill/template
|
|
2739
|
-
// expansion exactly like the pi CLI and RPC modes; plain text
|
|
2740
|
-
//
|
|
2741
|
-
|
|
2890
|
+
// expansion exactly like the pi CLI and RPC modes; plain text uses
|
|
2891
|
+
// prompt() with template expansion disabled and source "extension",
|
|
2892
|
+
// matching sendUserMessage() semantics while exposing the SDK
|
|
2893
|
+
// preflightResult acceptance signal.
|
|
2894
|
+
enqueueUserStart(payload.sessionId, generation, attachments.files, requestedDelivery);
|
|
2742
2895
|
// Pi's `session.setModel()` notifies extensions (`model_select`) but not
|
|
2743
2896
|
// session subscribers, so an extension-driven model switch would otherwise
|
|
2744
2897
|
// never publish `session.model`. Snapshot the live model to reconcile
|
|
@@ -2747,20 +2900,81 @@ export function createSessionDaemon({
|
|
|
2747
2900
|
const prevModel = activeRuntime.session?.model
|
|
2748
2901
|
? { provider: activeRuntime.session.model.provider, id: activeRuntime.session.model.id }
|
|
2749
2902
|
: null;
|
|
2750
|
-
let
|
|
2903
|
+
let promptPromise;
|
|
2904
|
+
// True SDK acceptance: await the prompt preflight signal, not the full
|
|
2905
|
+
// agent turn. preflightResult(true) means accepted, queued, or handled;
|
|
2906
|
+
// preflightResult(false) is followed by a prompt rejection that must
|
|
2907
|
+
// propagate to the caller so dedup does not cache it as accepted.
|
|
2908
|
+
let preflightOutcome = null;
|
|
2909
|
+
let notifyPreflight;
|
|
2910
|
+
const preflightGate = new Promise((resolve) => { notifyPreflight = resolve; });
|
|
2911
|
+
const onPreflightResult = (accepted) => {
|
|
2912
|
+
if (preflightOutcome !== null) return;
|
|
2913
|
+
preflightOutcome = accepted === true;
|
|
2914
|
+
notifyPreflight(preflightOutcome);
|
|
2915
|
+
};
|
|
2751
2916
|
try {
|
|
2752
|
-
|
|
2753
|
-
? activeRuntime.session.prompt(
|
|
2917
|
+
promptPromise = isSlashPrompt
|
|
2918
|
+
? activeRuntime.session.prompt(text, {
|
|
2754
2919
|
source: 'rpc',
|
|
2755
|
-
...(
|
|
2920
|
+
...(images ? { images } : {}),
|
|
2921
|
+
...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
|
|
2922
|
+
preflightResult: onPreflightResult,
|
|
2756
2923
|
})
|
|
2757
|
-
: activeRuntime.session.
|
|
2924
|
+
: activeRuntime.session.prompt(text, {
|
|
2925
|
+
expandPromptTemplates: false,
|
|
2926
|
+
source: 'extension',
|
|
2927
|
+
...(images ? { images } : {}),
|
|
2928
|
+
...(requestedDelivery ? { streamingBehavior: requestedDelivery } : {}),
|
|
2929
|
+
preflightResult: onPreflightResult,
|
|
2930
|
+
});
|
|
2758
2931
|
} catch (error) {
|
|
2759
2932
|
removeUserStart(payload.sessionId, generation);
|
|
2760
2933
|
throw error;
|
|
2761
2934
|
}
|
|
2762
|
-
|
|
2935
|
+
// A settlement without a preflight signal resolves the gate so a missing
|
|
2936
|
+
// callback cannot hang acceptance. Resolve implies acceptance; reject
|
|
2937
|
+
// implies preflight failure whose real error is propagated below. The
|
|
2938
|
+
// installed SDK always signals, so this only covers test doubles.
|
|
2939
|
+
Promise.resolve(promptPromise).then(
|
|
2940
|
+
() => { if (preflightOutcome === null) { preflightOutcome = true; notifyPreflight(true); } },
|
|
2941
|
+
() => { if (preflightOutcome === null) { preflightOutcome = false; notifyPreflight(false); } },
|
|
2942
|
+
);
|
|
2943
|
+
const preflightAccepted = await preflightGate;
|
|
2944
|
+
if (!preflightAccepted) {
|
|
2945
|
+
let preflightError;
|
|
2946
|
+
try {
|
|
2947
|
+
await promptPromise;
|
|
2948
|
+
preflightError = new Error('The Pi session rejected the prompt before acceptance.');
|
|
2949
|
+
} catch (error) {
|
|
2950
|
+
preflightError = error;
|
|
2951
|
+
}
|
|
2763
2952
|
removeUserStart(payload.sessionId, generation);
|
|
2953
|
+
throw preflightError;
|
|
2954
|
+
}
|
|
2955
|
+
Promise.resolve(promptPromise).then(() => {
|
|
2956
|
+
// Queued sends resolve on queueing, before the queued user message
|
|
2957
|
+
// starts. Keep that file metadata until the per-delivery
|
|
2958
|
+
// `message_start` consumes it. Retention is decided at resolution
|
|
2959
|
+
// time from authoritative runtime state, not from the early
|
|
2960
|
+
// `requestedDelivery` flag alone: an idle followUp/steer that the SDK
|
|
2961
|
+
// ignored (new turn, no queue) and any handled extension command
|
|
2962
|
+
// (never emits a user start) must not retain forever. Only a still-
|
|
2963
|
+
// streaming session or a non-empty SDK queue proves the send is
|
|
2964
|
+
// queued; handled extension commands never retain even while
|
|
2965
|
+
// streaming.
|
|
2966
|
+
const stillStreaming = Boolean(activeRuntime.session?.isStreaming);
|
|
2967
|
+
let hasQueuedMessages = false;
|
|
2968
|
+
try {
|
|
2969
|
+
hasQueuedMessages = (activeRuntime.session?.getSteeringMessages?.().length ?? 0) > 0
|
|
2970
|
+
|| (activeRuntime.session?.getFollowUpMessages?.().length ?? 0) > 0;
|
|
2971
|
+
} catch {
|
|
2972
|
+
hasQueuedMessages = false;
|
|
2973
|
+
}
|
|
2974
|
+
const shouldRetain = !isExtensionCommand && (stillStreaming || hasQueuedMessages);
|
|
2975
|
+
if (!shouldRetain) {
|
|
2976
|
+
removeUserStart(payload.sessionId, generation);
|
|
2977
|
+
}
|
|
2764
2978
|
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
2765
2979
|
if (settledSendGenerationBySession.get(payload.sessionId) === generation) return;
|
|
2766
2980
|
const curModel = activeRuntime.session?.model;
|
|
@@ -2865,11 +3079,16 @@ export function createSessionDaemon({
|
|
|
2865
3079
|
sendGenerationBySession.delete(sessionId);
|
|
2866
3080
|
settledSendGenerationBySession.delete(sessionId);
|
|
2867
3081
|
pendingUserStartsBySession.delete(sessionId);
|
|
3082
|
+
queueSizesBySession.delete(sessionId);
|
|
3083
|
+
queueShrinkBySession.delete(sessionId);
|
|
2868
3084
|
latestUserMessageIds.delete(sessionId);
|
|
2869
3085
|
latestAssistantMessageIds.delete(sessionId);
|
|
2870
3086
|
toolInputBySession.delete(sessionId);
|
|
2871
3087
|
clearToolTimingsForSession(sessionId);
|
|
2872
|
-
|
|
3088
|
+
// Explicit typed deletion: every connected and replaying client drops
|
|
3089
|
+
// catalog, transcript, activity, and caches. Archive and directory moves
|
|
3090
|
+
// keep the session id and never publish this event.
|
|
3091
|
+
publish('session.deleted', {}, sessionId, targetDir);
|
|
2873
3092
|
};
|
|
2874
3093
|
|
|
2875
3094
|
const publishSessionEvent = (sessionId, event, directory = activeDirectory || cwd) => {
|
|
@@ -3071,9 +3290,24 @@ export function createSessionDaemon({
|
|
|
3071
3290
|
}, sessionId, directory);
|
|
3072
3291
|
break;
|
|
3073
3292
|
}
|
|
3074
|
-
case 'queue_update':
|
|
3075
|
-
|
|
3293
|
+
case 'queue_update': {
|
|
3294
|
+
const steeringLength = Array.isArray(event.steering) ? event.steering.length : 0;
|
|
3295
|
+
const followUpLength = Array.isArray(event.followUp) ? event.followUp.length : 0;
|
|
3296
|
+
// Authoritative ownership for the next user start: only a shrink
|
|
3297
|
+
// tells which SDK queue owns it. Enqueues grow; dequeues shrink
|
|
3298
|
+
// immediately before their `message_start`. No text matching.
|
|
3299
|
+
const previous = queueSizesBySession.get(sessionId);
|
|
3300
|
+
if (previous) {
|
|
3301
|
+
const steeringShrank = steeringLength < previous.steering;
|
|
3302
|
+
const followUpShrank = followUpLength < previous.followUp;
|
|
3303
|
+
if (steeringShrank && !followUpShrank) queueShrinkBySession.set(sessionId, 'steer');
|
|
3304
|
+
else if (followUpShrank && !steeringShrank) queueShrinkBySession.set(sessionId, 'followUp');
|
|
3305
|
+
else if (steeringShrank || followUpShrank) queueShrinkBySession.delete(sessionId);
|
|
3306
|
+
}
|
|
3307
|
+
queueSizesBySession.set(sessionId, { steering: steeringLength, followUp: followUpLength });
|
|
3308
|
+
publish('session.queue', { steering: steeringLength, followUp: followUpLength }, sessionId, directory);
|
|
3076
3309
|
break;
|
|
3310
|
+
}
|
|
3077
3311
|
case 'agent_start':
|
|
3078
3312
|
clearIdleDisposal(sessionId);
|
|
3079
3313
|
retryStateBySession.delete(sessionId);
|
|
@@ -3218,11 +3452,16 @@ export function createSessionDaemon({
|
|
|
3218
3452
|
state: 'ready',
|
|
3219
3453
|
sessionId: getSessionState().sessionId,
|
|
3220
3454
|
lastSequence: sequence,
|
|
3455
|
+
streamEpoch,
|
|
3221
3456
|
capabilities: [
|
|
3457
|
+
// Public stream-lifetime identification: every event, snapshot,
|
|
3458
|
+
// and health result carries `streamEpoch`, and session read
|
|
3459
|
+
// responses stamp it so clients can reject stale-epoch data.
|
|
3460
|
+
'events.streamEpoch',
|
|
3222
3461
|
'runtime.claim', 'runtime.shutdown',
|
|
3223
3462
|
'projects.list', 'projects.select', 'sessions.list', 'sessions.create', 'sessions.open', 'sessions.messages', 'sessions.rename', 'sessions.delete',
|
|
3224
3463
|
'sessions.tree', 'sessions.navigate', 'sessions.fork', 'sessions.clone', 'sessions.prompt',
|
|
3225
|
-
'sessions.steer', 'sessions.followUp', 'sessions.abort', 'sessions.setModel',
|
|
3464
|
+
'sessions.steer', 'sessions.followUp', 'sessions.sendReceipt', 'sessions.abort', 'sessions.setModel',
|
|
3226
3465
|
'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
|
|
3227
3466
|
'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
|
|
3228
3467
|
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
|
|
@@ -3439,7 +3678,9 @@ export function createSessionDaemon({
|
|
|
3439
3678
|
protocolVersion: PROTOCOL_VERSION,
|
|
3440
3679
|
kind: 'response',
|
|
3441
3680
|
requestId: message.requestId,
|
|
3442
|
-
|
|
3681
|
+
// Stamp the stream lifetime so clients can reject a listing that a
|
|
3682
|
+
// previous daemon process generated after an epoch change.
|
|
3683
|
+
result: { sessions, streamEpoch },
|
|
3443
3684
|
});
|
|
3444
3685
|
return;
|
|
3445
3686
|
}
|
|
@@ -3539,6 +3780,42 @@ export function createSessionDaemon({
|
|
|
3539
3780
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
3540
3781
|
return;
|
|
3541
3782
|
}
|
|
3783
|
+
case 'sessions.sendReceipt': {
|
|
3784
|
+
// Exact read-only receipt lookup for an uncertain send. Requires the
|
|
3785
|
+
// full `kind + sessionId + operationId` identity; never invokes Pi,
|
|
3786
|
+
// never mutates the registry except bounded expiry eviction inside
|
|
3787
|
+
// `query()`. Returns `accepted` (retained receipt), `pending`
|
|
3788
|
+
// (still-accepting claim), `expired` (seen but retention gone —
|
|
3789
|
+
// outcome unknown, never assume success), or `unknown` (never seen
|
|
3790
|
+
// in this retention window, tombstone pressure, post-restart, or
|
|
3791
|
+
// rejected before Pi ran so nothing executed).
|
|
3792
|
+
const payload = message.payload ?? {};
|
|
3793
|
+
const kind = payload.kind;
|
|
3794
|
+
const sessionId = payload.sessionId;
|
|
3795
|
+
const operationId = payload.operationId;
|
|
3796
|
+
if ((kind !== 'prompt' && kind !== 'steer' && kind !== 'followUp')
|
|
3797
|
+
|| typeof sessionId !== 'string' || sessionId.length === 0
|
|
3798
|
+
|| !isValidSendOperationId(operationId)) {
|
|
3799
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The send receipt lookup is invalid.');
|
|
3800
|
+
}
|
|
3801
|
+
const lookup = sendOperations.query({ kind, sessionId, operationId });
|
|
3802
|
+
if (lookup.status === 'accepted') {
|
|
3803
|
+
writeFrame(socket, {
|
|
3804
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
3805
|
+
kind: 'response',
|
|
3806
|
+
requestId: message.requestId,
|
|
3807
|
+
result: { status: 'accepted', receipt: lookup.receipt },
|
|
3808
|
+
});
|
|
3809
|
+
return;
|
|
3810
|
+
}
|
|
3811
|
+
writeFrame(socket, {
|
|
3812
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
3813
|
+
kind: 'response',
|
|
3814
|
+
requestId: message.requestId,
|
|
3815
|
+
result: { status: lookup.status },
|
|
3816
|
+
});
|
|
3817
|
+
return;
|
|
3818
|
+
}
|
|
3542
3819
|
case 'sessions.abort': {
|
|
3543
3820
|
const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
|
|
3544
3821
|
const streaming = activeRuntime.session.isStreaming;
|
|
@@ -3651,14 +3928,37 @@ export function createSessionDaemon({
|
|
|
3651
3928
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'authenticated' });
|
|
3652
3929
|
const requestedSessionId = typeof message.sessionId === 'string' && message.sessionId.length > 0 ? message.sessionId : undefined;
|
|
3653
3930
|
const fromSequence = Number.isSafeInteger(message.fromSequence) && message.fromSequence >= 0 ? message.fromSequence : undefined;
|
|
3931
|
+
// Stream-lifetime identity the client's cursor was established
|
|
3932
|
+
// under (capability negotiation). A cursor stamped with a
|
|
3933
|
+
// different epoch belongs to a retired sequence space: even when
|
|
3934
|
+
// this daemon's sequence numerically overtook it, replaying from
|
|
3935
|
+
// it would silently skip the head of the new sequence space.
|
|
3936
|
+
// Subscribers without the marker cannot prove which sequence
|
|
3937
|
+
// space their cursor belongs to. Reject that shape instead of
|
|
3938
|
+
// silently treating it as a valid resume.
|
|
3939
|
+
const requestedEpoch = typeof message.streamEpoch === 'string' && message.streamEpoch.length > 0 && message.streamEpoch.length <= 128
|
|
3940
|
+
? message.streamEpoch
|
|
3941
|
+
: undefined;
|
|
3942
|
+
if (fromSequence !== undefined && requestedEpoch === undefined) {
|
|
3943
|
+
throw new SessionDaemonProtocolError(
|
|
3944
|
+
'DAEMON_PROTOCOL_MISMATCH',
|
|
3945
|
+
'A replay cursor requires its stream epoch.',
|
|
3946
|
+
);
|
|
3947
|
+
}
|
|
3948
|
+
const epochMismatch = requestedEpoch !== undefined && requestedEpoch !== streamEpoch;
|
|
3654
3949
|
// Contiguity is judged on the global retained suffix while delivery
|
|
3655
3950
|
// stays session-filtered, so a filtered client never replays through
|
|
3656
3951
|
// a gap left by eviction, an oversized event, an empty ring, or a
|
|
3657
3952
|
// future cursor: all of those take the snapshot fallback below.
|
|
3658
|
-
|
|
3953
|
+
// Replay additionally requires the epoch marker. The validation
|
|
3954
|
+
// above rejects a cursor that cannot be tied to an epoch.
|
|
3955
|
+
if (fromSequence !== undefined && requestedEpoch !== undefined && !epochMismatch && replayLog.canReplay(fromSequence, sequence)) {
|
|
3659
3956
|
for (const cachedLine of replayLog.linesAfter(fromSequence, requestedSessionId)) writeLine(socket, cachedLine);
|
|
3660
3957
|
} else {
|
|
3661
|
-
|
|
3958
|
+
// A supplied cursor that cannot be replayed is a resync: the
|
|
3959
|
+
// snapshot is the client's recovery baseline for a missed replay
|
|
3960
|
+
// window, a daemon restart, or a cursor from a retired epoch.
|
|
3961
|
+
publishSnapshot(socket, requestedSessionId, { resync: fromSequence !== undefined || epochMismatch === true });
|
|
3662
3962
|
}
|
|
3663
3963
|
continue;
|
|
3664
3964
|
}
|
|
@@ -3739,6 +4039,8 @@ export function createSessionDaemon({
|
|
|
3739
4039
|
sendGenerationBySession.clear();
|
|
3740
4040
|
settledSendGenerationBySession.clear();
|
|
3741
4041
|
pendingUserStartsBySession.clear();
|
|
4042
|
+
queueSizesBySession.clear();
|
|
4043
|
+
queueShrinkBySession.clear();
|
|
3742
4044
|
latestUserMessageIds.clear();
|
|
3743
4045
|
latestAssistantMessageIds.clear();
|
|
3744
4046
|
for (const client of clients) client.destroy();
|