@pi-chamber/web 0.3.3 → 0.5.0
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 +1 -0
- package/bin/lib/cli-startup.js +1 -0
- package/dist/assets/CommitSection-Cz-ACBaD.js +1 -0
- package/dist/assets/DiagramEditor-BNUOrd9m.js +1 -0
- package/dist/assets/DiagramView-D4YR9YRt.js +1 -0
- package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-DPW8dcg_.js} +3 -3
- package/dist/assets/FilesView-BFGIdY6b.js +14 -0
- package/dist/assets/GitView-CKtiKOfJ.js +6 -0
- package/dist/assets/JsonTreeView-c-UJUw3D.js +1 -0
- package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-CvC9eXoa.js} +2 -2
- package/dist/assets/PatchDiff-YGHsZUIR.js +1 -0
- package/dist/assets/PierreDiffViewer-CoXa-JJK.js +136 -0
- package/dist/assets/SessionSwitcherContent-B7eep3dO.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CZOFeJHH.js +2 -0
- package/dist/assets/SessionUnreadDot-ClpeYFPz.js +1 -0
- package/dist/assets/SettingsView-CPmHHDbQ.js +4 -0
- package/dist/assets/SettingsWindow-2CBpoJ8H.js +1 -0
- package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-HMW-Kh19.js} +6 -6
- package/dist/assets/ToolPartDiffPreview-C3nbNbxk.js +8 -0
- package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-DEX83nQ0.js} +3 -3
- package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-PPk5H89-.js} +172 -118
- package/dist/assets/collapsible-Dux-9hAC.js +1 -0
- package/dist/assets/computeVirtualFileMetrics-Cy0nxMJB.js +3 -0
- package/dist/assets/contextFileOpenGuard-Dn_38hd9.js +1 -0
- package/dist/assets/index--zDkVFU6.css +1 -0
- package/dist/assets/index-DU2OBBy5.js +8 -0
- package/dist/assets/index-EN7MioVf.js +1 -0
- package/dist/assets/isDiffPlainText-DSWRVq-W.js +1 -0
- package/dist/assets/isFilePlainText-7RAjjrQ5.js +1 -0
- package/dist/assets/{main-CmkRaMOR.js → main-BGKjg-qW.js} +8 -8
- package/dist/assets/main-DGHrBx_u.js +2 -0
- package/dist/assets/markdownCore-BYPqQtbE.js +3 -0
- package/dist/assets/miniChat-DW2PVX49.js +2 -0
- package/dist/assets/mobile-0Gxc02iO.js +2 -0
- package/dist/assets/renderElectronMiniChatApp-C-qpqp1i.js +2 -0
- package/dist/assets/renderMobileApp-UB9bhC1x.js +14 -0
- package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-DefD-2Iv.js} +1 -1
- package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-B8p2XwXA.js} +2 -2
- package/dist/assets/usePanelSlide-CbqVf-y8.js +56 -0
- package/dist/assets/usePushVisibilityBeacon-CvjN-47R.js +10 -0
- package/dist/assets/useSwitcherItems-B6_F-J-z.js +1 -0
- package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-BhBdEPsJ.js} +2 -2
- package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
- package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
- package/dist/assets/{web-components-Cct1r-wn.js → web-components-C9yVPsWN.js} +2 -2
- package/dist/index.html +8 -5
- package/dist/mini-chat.html +7 -4
- package/dist/mobile.html +7 -4
- package/dist/sw.js +1 -1
- package/package.json +1 -1
- package/server/index.js +27 -5
- package/server/lib/fs/routes.js +0 -21
- package/server/lib/git/DOCUMENTATION.md +15 -5
- package/server/lib/git/issue-2746-longpaths.test.js +11 -11
- package/server/lib/git/routes.js +80 -4
- package/server/lib/git/routes.test.js +135 -0
- package/server/lib/git/service.js +144 -82
- package/server/lib/git/service.test.js +182 -36
- package/server/lib/pi/extension-protocol.js +62 -0
- package/server/lib/pi/extension-protocol.test.js +34 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +251 -0
- package/server/lib/pi/routes-extension-events.test.js +152 -0
- package/server/lib/pi/routes.js +345 -7
- package/server/lib/pi/routes.test.js +43 -28
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +8 -5
- package/server/lib/pi/session-daemon/extension-bridge.js +488 -0
- package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
- package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +215 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +559 -0
- package/server/lib/pi/session-daemon/session-daemon.js +483 -54
- package/server/lib/pi/session-daemon/session-daemon.test.js +212 -4
- package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
- package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
- package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
- package/server/lib/pi/session-daemon/supervisor.js +3 -0
- package/server/lib/pi/small-model-generation.js +104 -0
- package/server/lib/pi/small-model-generation.test.js +66 -0
- package/server/lib/preview/proxy-runtime.js +11 -1
- package/server/lib/preview/proxy-runtime.test.js +3 -0
- package/server/lib/relay/tunnel-host.js +1 -0
- package/server/lib/server/cors.js +0 -2
- package/server/lib/server/cors.test.js +4 -4
- package/server/lib/stt/DOCUMENTATION.md +38 -0
- package/server/lib/stt/audio.js +47 -0
- package/server/lib/stt/config-store.js +81 -0
- package/server/lib/stt/config-store.test.js +36 -0
- package/server/lib/stt/local/model-catalog.js +57 -0
- package/server/lib/stt/local/model-downloader.js +127 -0
- package/server/lib/stt/local/recognizer.js +64 -0
- package/server/lib/stt/local/sherpa-loader.js +43 -0
- package/server/lib/stt/local/worker-client.js +115 -0
- package/server/lib/stt/local/worker-process.js +64 -0
- package/server/lib/stt/protocol.js +38 -0
- package/server/lib/stt/protocol.test.js +17 -0
- package/server/lib/stt/providers/local-worker-provider.js +11 -0
- package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
- package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
- package/server/lib/stt/runtime.js +111 -0
- package/server/lib/stt/service.js +106 -0
- package/server/lib/stt/stream-manager.js +188 -0
- package/server/lib/stt/stream-manager.test.js +64 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
- package/server/lib/ui-auth/ui-auth.js +8 -3
- package/server/lib/ui-auth/ui-auth.test.js +8 -0
- package/server/lib/workspace/host.js +19 -3
- package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
- package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
- package/dist/assets/DiagramView-CAlJiG11.js +0 -1
- package/dist/assets/FilesView-DB5VI7EN.js +0 -14
- package/dist/assets/GitView-CFlPcSn9.js +0 -6
- package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
- package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
- package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
- package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
- package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
- package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
- package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
- package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
- package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
- package/dist/assets/index-BAqpUCjs.js +0 -8
- package/dist/assets/index-CuSNEV7s.js +0 -1
- package/dist/assets/index-riABQmQ_.css +0 -1
- package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
- package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
- package/dist/assets/main-By_pvk90.js +0 -2
- package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
- package/dist/assets/miniChat-_XK2gGZE.js +0 -2
- package/dist/assets/mobile-B4E4JqAf.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
- package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
- package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
- package/dist/assets/useWindowTitle-DoHrUC5r.js +0 -10
- package/server/lib/pi/legacy-ui-model-defaults.js +0 -57
- package/server/lib/pi/legacy-ui-model-defaults.test.js +0 -65
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { createServer } from 'node:net';
|
|
3
3
|
import { chmod, mkdir, lstat, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
4
|
-
import { createReadStream } from 'node:fs';
|
|
4
|
+
import { createReadStream, existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { createInterface } from 'node:readline';
|
|
6
7
|
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
7
8
|
import { hasTrustRequiringProjectResources } from '@earendil-works/pi-coding-agent';
|
|
@@ -16,9 +17,17 @@ import {
|
|
|
16
17
|
SettingsManager,
|
|
17
18
|
} from '@earendil-works/pi-coding-agent';
|
|
18
19
|
|
|
20
|
+
import {
|
|
21
|
+
MAX_EXTENSION_APP_HTML_CHARS,
|
|
22
|
+
sanitizeExtensionFormFields,
|
|
23
|
+
validateExtensionFormValues,
|
|
24
|
+
} from '../extension-protocol.js';
|
|
19
25
|
import { createPiModelConfigStore } from '../model-config-store.js';
|
|
20
26
|
import { clampThinkingLevel, getSupportedThinkingLevels, isPiThinkingLevel } from '../thinking-levels.js';
|
|
27
|
+
import { createExtensionBridge } from './extension-bridge.js';
|
|
21
28
|
import { createMessageEntryAliases } from './message-entry-aliases.js';
|
|
29
|
+
import { resolveEffectiveRetryLimitFromDataDir as resolveEffectiveRetryLimit } from './session-retry-limits.js';
|
|
30
|
+
import { createSkillReadClassifier } from './skill-read-classifier.js';
|
|
22
31
|
import { createSessionRuntimeRegistry } from './runtime-registry.js';
|
|
23
32
|
import {
|
|
24
33
|
findPiSessionJsonlById,
|
|
@@ -30,6 +39,51 @@ import {
|
|
|
30
39
|
import { resolvePiChamberDataDir } from '../../pichamber-data-dir.js';
|
|
31
40
|
|
|
32
41
|
const PROTOCOL_VERSION = 1;
|
|
42
|
+
|
|
43
|
+
const textFromContent = (content) => (
|
|
44
|
+
Array.isArray(content)
|
|
45
|
+
? content.filter((part) => part?.type === 'text' && typeof part.text === 'string').map((part) => part.text).join('')
|
|
46
|
+
: ''
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
// Marker so pi extensions can detect PiChamber without an extra dependency.
|
|
50
|
+
// Extensions should use optional detection, e.g.:
|
|
51
|
+
// const chamber = (globalThis as any).__PICHAMBER__;
|
|
52
|
+
// or `process.env.PICHAMBER === "1"`. The object is frozen and versioned.
|
|
53
|
+
if (!globalThis.__PICHAMBER__) {
|
|
54
|
+
try {
|
|
55
|
+
globalThis.__PICHAMBER__ = Object.freeze({
|
|
56
|
+
version: 1,
|
|
57
|
+
protocol: 'pichamber-extension-ui',
|
|
58
|
+
mode: 'rpc',
|
|
59
|
+
});
|
|
60
|
+
} catch {}
|
|
61
|
+
}
|
|
62
|
+
if (!process.env.PICHAMBER) {
|
|
63
|
+
try { process.env.PICHAMBER = '1'; } catch {}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Extensions that spawn the pi CLI as a child process (subagent runners,
|
|
67
|
+
// task delegators) locate it through `process.argv[1]`. Inside this detached
|
|
68
|
+
// daemon that path is daemon-process.js — a bare invocation exits 64 with no
|
|
69
|
+
// output, which the extension then reports as "failed (no output)". Re-point
|
|
70
|
+
// argv at the installed pi CLI entry before any extension loads so child
|
|
71
|
+
// spawns run the real CLI. Scoped to the detached entrypoint so tests and
|
|
72
|
+
// in-process hosts keep their own argv.
|
|
73
|
+
try {
|
|
74
|
+
if (process.argv[1]?.endsWith('daemon-process.js')) {
|
|
75
|
+
// The SDK is ESM-only, so resolve through import.meta rather than require.
|
|
76
|
+
const mainEntry = fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'));
|
|
77
|
+
const packageRoot = dirname(dirname(mainEntry));
|
|
78
|
+
const pkg = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
|
|
79
|
+
const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin?.pi;
|
|
80
|
+
if (bin) {
|
|
81
|
+
const cliEntry = join(packageRoot, bin);
|
|
82
|
+
if (existsSync(cliEntry)) process.argv[1] = cliEntry;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
} catch {}
|
|
86
|
+
|
|
33
87
|
const MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
34
88
|
|
|
35
89
|
class SessionDaemonProtocolError extends Error {
|
|
@@ -49,18 +103,18 @@ export function isLocalSessionDaemonEndpoint(endpoint, platform = process.platfo
|
|
|
49
103
|
return isAbsolute(endpoint);
|
|
50
104
|
}
|
|
51
105
|
|
|
52
|
-
|
|
106
|
+
// Hooks let the daemon thread extension bindings into every Pi runtime
|
|
107
|
+
// creation (initial, new/resume/fork replacement) without coupling this
|
|
108
|
+
// factory to daemon socket state.
|
|
109
|
+
export async function createPiSessionRuntime({ cwd, agentDir = getAgentDir(), sessionFile }, hooks) {
|
|
53
110
|
const createRuntime = async ({ cwd: runtimeCwd, agentDir: runtimeAgentDir, sessionManager, sessionStartEvent }) => {
|
|
54
111
|
const services = await createAgentSessionServices({
|
|
55
112
|
cwd: runtimeCwd,
|
|
56
113
|
agentDir: runtimeAgentDir,
|
|
57
|
-
resourceLoaderOptions: {
|
|
58
|
-
// Third-party native extensions are intentionally disabled for the Pi core milestone.
|
|
59
|
-
noExtensions: true,
|
|
60
|
-
},
|
|
114
|
+
resourceLoaderOptions: {},
|
|
61
115
|
});
|
|
62
116
|
|
|
63
|
-
|
|
117
|
+
const result = {
|
|
64
118
|
...(await createAgentSessionFromServices({
|
|
65
119
|
services,
|
|
66
120
|
sessionManager,
|
|
@@ -69,6 +123,12 @@ async function createPiSessionRuntime({ cwd, agentDir = getAgentDir(), sessionFi
|
|
|
69
123
|
services,
|
|
70
124
|
diagnostics: services.diagnostics,
|
|
71
125
|
};
|
|
126
|
+
|
|
127
|
+
if (hooks?.createExtensionBindings && typeof result.session?.bindExtensions === 'function') {
|
|
128
|
+
await result.session.bindExtensions(hooks.createExtensionBindings(result.session));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return result;
|
|
72
132
|
};
|
|
73
133
|
|
|
74
134
|
return createAgentSessionRuntime(createRuntime, {
|
|
@@ -85,7 +145,7 @@ export function createSessionDaemon({
|
|
|
85
145
|
credential,
|
|
86
146
|
cwd,
|
|
87
147
|
agentDir = getAgentDir(),
|
|
88
|
-
createRuntime
|
|
148
|
+
createRuntime: injectCreateRuntime,
|
|
89
149
|
healthMetadata = {},
|
|
90
150
|
idleTimeoutMs = 5 * 60 * 1_000,
|
|
91
151
|
listSessions = ({ cwd: sessionCwd, agentDir: sessionAgentDir = agentDir }) => listPiSessionJsonlDirectory({
|
|
@@ -137,15 +197,70 @@ export function createSessionDaemon({
|
|
|
137
197
|
const latestAssistantMessageIds = new Map();
|
|
138
198
|
const messageStartedAt = new Map();
|
|
139
199
|
const toolStartedAt = new Map();
|
|
200
|
+
const toolInputBySession = new Map();
|
|
140
201
|
const latestUserMessageIds = new Map();
|
|
141
202
|
const retryStateBySession = new Map();
|
|
203
|
+
const compactionStateBySession = new Map();
|
|
142
204
|
const activeRunStartedAt = new Map();
|
|
143
205
|
const sendGenerationBySession = new Map();
|
|
206
|
+
const settledSendGenerationBySession = new Map();
|
|
207
|
+
const shutdownRequestedBySession = new Set();
|
|
208
|
+
const disposingSessionIds = new Set();
|
|
144
209
|
const streamingRedactionBuffers = new Map();
|
|
145
210
|
const loginAttempts = new Map();
|
|
211
|
+
// Server-side normalized extension live state: statuses, widgets, panels,
|
|
212
|
+
// apps, and pending dialogs are kept per session so a reconnect can
|
|
213
|
+
// reconstruct the current UI without requiring the extension to re-emit.
|
|
146
214
|
const messageEntryAliases = createMessageEntryAliases();
|
|
215
|
+
const skillReadClassifierByRuntime = new WeakMap();
|
|
147
216
|
const MAX_REPLAY_EVENTS = 1_024;
|
|
148
217
|
|
|
218
|
+
const skillReadClassifierFor = (activeRuntime, directory) => {
|
|
219
|
+
if (!activeRuntime || typeof activeRuntime !== 'object') return undefined;
|
|
220
|
+
const classifierCwd = activeRuntime.cwd || directory || activeDirectory || cwd;
|
|
221
|
+
const cached = skillReadClassifierByRuntime.get(activeRuntime);
|
|
222
|
+
if (cached?.cwd === classifierCwd) return cached.classifier;
|
|
223
|
+
const loader = activeRuntime.services?.resourceLoader;
|
|
224
|
+
const discovered = loader?.getSkills?.();
|
|
225
|
+
const classifier = createSkillReadClassifier({
|
|
226
|
+
cwd: classifierCwd,
|
|
227
|
+
skills: discovered?.skills,
|
|
228
|
+
platform,
|
|
229
|
+
});
|
|
230
|
+
skillReadClassifierByRuntime.set(activeRuntime, { cwd: classifierCwd, classifier });
|
|
231
|
+
return classifier;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
const rememberToolInput = (sessionId, toolCallId, args) => {
|
|
235
|
+
const inputs = toolInputBySession.get(sessionId) ?? new Map();
|
|
236
|
+
inputs.set(toolCallId, args);
|
|
237
|
+
toolInputBySession.set(sessionId, inputs);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
const getToolInput = (sessionId, toolCallId) => toolInputBySession.get(sessionId)?.get(toolCallId);
|
|
241
|
+
|
|
242
|
+
const forgetToolInput = (sessionId, toolCallId) => {
|
|
243
|
+
const inputs = toolInputBySession.get(sessionId);
|
|
244
|
+
if (!inputs) return;
|
|
245
|
+
inputs.delete(toolCallId);
|
|
246
|
+
if (inputs.size === 0) toolInputBySession.delete(sessionId);
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const mergeToolPresentationMetadata = (metadata, activeRuntime, directory, toolName, args) => {
|
|
250
|
+
const skill = skillReadClassifierFor(activeRuntime, directory)?.(toolName, args);
|
|
251
|
+
if (!skill) return metadata;
|
|
252
|
+
const currentPiChamberMetadata = metadata?.pichamber && typeof metadata.pichamber === 'object'
|
|
253
|
+
? metadata.pichamber
|
|
254
|
+
: {};
|
|
255
|
+
return {
|
|
256
|
+
...(metadata ?? {}),
|
|
257
|
+
pichamber: {
|
|
258
|
+
...currentPiChamberMetadata,
|
|
259
|
+
skill,
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
|
|
149
264
|
const validateDirectoryPath = async (dir) => {
|
|
150
265
|
if (typeof dir !== 'string' || dir.trim().length === 0) {
|
|
151
266
|
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'The directory path is required.');
|
|
@@ -198,7 +313,7 @@ export function createSessionDaemon({
|
|
|
198
313
|
const services = await createAgentSessionServices({
|
|
199
314
|
cwd: targetCwd,
|
|
200
315
|
agentDir,
|
|
201
|
-
resourceLoaderOptions: {
|
|
316
|
+
resourceLoaderOptions: {},
|
|
202
317
|
});
|
|
203
318
|
servicesCache.set(targetCwd, services);
|
|
204
319
|
return services;
|
|
@@ -223,10 +338,57 @@ export function createSessionDaemon({
|
|
|
223
338
|
for (const client of clients) writeFrame(client, message);
|
|
224
339
|
};
|
|
225
340
|
|
|
341
|
+
const extensionBridge = createExtensionBridge({
|
|
342
|
+
publish,
|
|
343
|
+
resolveDirectory,
|
|
344
|
+
redactAttachmentPaths: (value) => redactAttachmentPaths(value),
|
|
345
|
+
redactAttachmentValues: (value) => redactAttachmentValues(value),
|
|
346
|
+
findRuntimeBySessionId: (sessionId) => runtimeRegistry?.findBySessionId(sessionId)
|
|
347
|
+
|| (runtime?.session?.sessionId === sessionId ? runtime : undefined),
|
|
348
|
+
getDefaultDirectory: () => activeDirectory || cwd,
|
|
349
|
+
getSequence: () => sequence,
|
|
350
|
+
protocolError: (code, message) => new SessionDaemonProtocolError(code, message),
|
|
351
|
+
requestSessionShutdown: (sessionId) => shutdownRequestedBySession.add(sessionId),
|
|
352
|
+
});
|
|
353
|
+
const {
|
|
354
|
+
buildExtensionBindings,
|
|
355
|
+
clearExtensionState,
|
|
356
|
+
mirrorExtensionApp,
|
|
357
|
+
mirrorExtensionPanel,
|
|
358
|
+
publishExtensionCustomMessage,
|
|
359
|
+
resolveExtensionDialog,
|
|
360
|
+
} = extensionBridge;
|
|
361
|
+
|
|
362
|
+
// Thread extension hooks through our own default factory. Injected test or
|
|
363
|
+
// host factories keep their single-argument contract and ignore the hooks.
|
|
364
|
+
const baseCreateRuntime = injectCreateRuntime
|
|
365
|
+
?? ((runtimeOptions, runtimeHooks) => createPiSessionRuntime(runtimeOptions, runtimeHooks));
|
|
366
|
+
const createRuntime = (runtimeOptions) => baseCreateRuntime(runtimeOptions, {
|
|
367
|
+
createExtensionBindings: buildExtensionBindings,
|
|
368
|
+
});
|
|
369
|
+
|
|
226
370
|
const getSessionState = () => runtime
|
|
227
371
|
? { sessionId: runtime.session.sessionId, isStreaming: runtime.session.isStreaming }
|
|
228
372
|
: { sessionId: dormantSession?.sessionId, isStreaming: false };
|
|
229
373
|
|
|
374
|
+
const persistedCompactionState = (session) => {
|
|
375
|
+
const entries = session?.sessionManager?.getBranch?.() ?? session?.sessionManager?.getEntries?.();
|
|
376
|
+
if (!Array.isArray(entries)) return undefined;
|
|
377
|
+
const entry = [...entries].reverse().find((candidate) => candidate?.type === 'compaction');
|
|
378
|
+
if (!entry) return undefined;
|
|
379
|
+
const completedAt = typeof entry.timestamp === 'number' ? entry.timestamp : Date.parse(entry.timestamp);
|
|
380
|
+
return {
|
|
381
|
+
phase: 'completed',
|
|
382
|
+
...(Number.isFinite(completedAt) ? { completedAt } : {}),
|
|
383
|
+
...(Number.isFinite(entry.tokensBefore) && entry.tokensBefore >= 0 ? { tokensBefore: entry.tokensBefore } : {}),
|
|
384
|
+
};
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
const compactionStateFor = (session) => {
|
|
388
|
+
if (!session?.sessionId) return undefined;
|
|
389
|
+
return compactionStateBySession.get(session.sessionId) ?? persistedCompactionState(session);
|
|
390
|
+
};
|
|
391
|
+
|
|
230
392
|
const rememberRuntimeSession = () => {
|
|
231
393
|
const sessionId = runtime?.session?.sessionId;
|
|
232
394
|
if (typeof sessionId !== 'string' || sessionId.length === 0) return;
|
|
@@ -244,11 +406,17 @@ export function createSessionDaemon({
|
|
|
244
406
|
if (requestedSessionId && requestedSessionId !== session.sessionId) return;
|
|
245
407
|
const activeSession = targetRuntime?.session || runtime?.session;
|
|
246
408
|
const retry = session.sessionId ? retryStateBySession.get(session.sessionId) : undefined;
|
|
409
|
+
const compaction = compactionStateFor(activeSession);
|
|
247
410
|
const targetDirectory = targetRuntime?.cwd || activeDirectory || cwd;
|
|
248
|
-
const messages = activeSession ? projectMessageEntries(
|
|
411
|
+
const messages = activeSession ? projectMessageEntries(targetRuntime || runtime, targetDirectory) : [];
|
|
249
412
|
const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
|
|
250
413
|
const model = activeSession?.model;
|
|
251
414
|
const snapshotSequence = ++sequence;
|
|
415
|
+
// Snapshot must carry enough extension live state for a reconnect that
|
|
416
|
+
// missed the gap: statuses, widgets, and pending blocking dialogs per
|
|
417
|
+
// session. Without it, a phone that reconnects after the 1k replay
|
|
418
|
+
// window would lose its sub-agent panel or approval prompt.
|
|
419
|
+
const extensionSnapshot = extensionBridge.getSnapshotState(session.sessionId);
|
|
252
420
|
writeFrame(socket, {
|
|
253
421
|
protocolVersion: PROTOCOL_VERSION,
|
|
254
422
|
kind: 'event',
|
|
@@ -260,6 +428,7 @@ export function createSessionDaemon({
|
|
|
260
428
|
isStreaming: session.isStreaming ?? false,
|
|
261
429
|
lifecycle: retry ? 'retry' : session.isStreaming ? 'busy' : 'idle',
|
|
262
430
|
...(retry ? { retry } : {}),
|
|
431
|
+
...(compaction ? { compaction } : {}),
|
|
263
432
|
queue: activeSession ? {
|
|
264
433
|
steering: activeSession.getSteeringMessages?.().length ?? 0,
|
|
265
434
|
followUp: activeSession.getFollowUpMessages?.().length ?? 0,
|
|
@@ -271,6 +440,12 @@ export function createSessionDaemon({
|
|
|
271
440
|
...(session.sessionId && activeRunStartedAt.has(session.sessionId) ? { runStartedAt: activeRunStartedAt.get(session.sessionId) } : {}),
|
|
272
441
|
serverNow: Date.now(),
|
|
273
442
|
lastSequence: snapshotSequence,
|
|
443
|
+
...(extensionSnapshot.statuses ? { extensionStatuses: extensionSnapshot.statuses } : {}),
|
|
444
|
+
...(extensionSnapshot.widgets ? { extensionWidgets: extensionSnapshot.widgets } : {}),
|
|
445
|
+
...(extensionSnapshot.dialogs ? { extensionDialogs: extensionSnapshot.dialogs } : {}),
|
|
446
|
+
...(extensionSnapshot.panels ? { extensionPanels: extensionSnapshot.panels } : {}),
|
|
447
|
+
...(extensionSnapshot.apps ? { extensionApps: extensionSnapshot.apps } : {}),
|
|
448
|
+
...(extensionSnapshot.title ? { extensionTitle: extensionSnapshot.title } : {}),
|
|
274
449
|
},
|
|
275
450
|
});
|
|
276
451
|
};
|
|
@@ -290,6 +465,7 @@ export function createSessionDaemon({
|
|
|
290
465
|
|
|
291
466
|
const disposeRuntime = async () => {
|
|
292
467
|
clearIdleDisposal();
|
|
468
|
+
clearExtensionState(undefined);
|
|
293
469
|
if (runtimeRegistry) {
|
|
294
470
|
const hadTrackedRuntime = runtimeRegistry.size > 0;
|
|
295
471
|
await runtimeRegistry.disposeAll();
|
|
@@ -329,23 +505,41 @@ export function createSessionDaemon({
|
|
|
329
505
|
return runtimeStartPromise;
|
|
330
506
|
};
|
|
331
507
|
|
|
508
|
+
const disposeIdleSessionRuntime = async (sessionId) => {
|
|
509
|
+
if (disposingSessionIds.has(sessionId)) return;
|
|
510
|
+
const targetRuntime = runtimeRegistry?.findBySessionId(sessionId);
|
|
511
|
+
if (!targetRuntime) {
|
|
512
|
+
shutdownRequestedBySession.delete(sessionId);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (targetRuntime.session?.isStreaming || targetRuntime.session?.isCompacting) return;
|
|
516
|
+
disposingSessionIds.add(sessionId);
|
|
517
|
+
clearIdleDisposal(sessionId);
|
|
518
|
+
try {
|
|
519
|
+
if (targetRuntime === runtime) rememberRuntimeSession();
|
|
520
|
+
clearExtensionState(sessionId);
|
|
521
|
+
await runtimeRegistry.dispose(targetRuntime);
|
|
522
|
+
shutdownRequestedBySession.delete(sessionId);
|
|
523
|
+
compactionStateBySession.delete(sessionId);
|
|
524
|
+
if (targetRuntime === runtime) runtime = undefined;
|
|
525
|
+
} catch {
|
|
526
|
+
publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId, targetRuntime.cwd);
|
|
527
|
+
} finally {
|
|
528
|
+
disposingSessionIds.delete(sessionId);
|
|
529
|
+
}
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
const completeRequestedShutdown = (sessionId) => {
|
|
533
|
+
if (!shutdownRequestedBySession.has(sessionId)) return false;
|
|
534
|
+
void disposeIdleSessionRuntime(sessionId);
|
|
535
|
+
return true;
|
|
536
|
+
};
|
|
537
|
+
|
|
332
538
|
const scheduleIdleDisposal = (sessionId) => {
|
|
333
539
|
clearIdleDisposal(sessionId);
|
|
334
|
-
const timer = setTimeout(
|
|
540
|
+
const timer = setTimeout(() => {
|
|
335
541
|
idleDisposeTimers.delete(sessionId);
|
|
336
|
-
|
|
337
|
-
if (!targetRuntime || targetRuntime.session?.isStreaming) return;
|
|
338
|
-
try {
|
|
339
|
-
if (targetRuntime === runtime) {
|
|
340
|
-
rememberRuntimeSession();
|
|
341
|
-
}
|
|
342
|
-
await runtimeRegistry.dispose(targetRuntime);
|
|
343
|
-
if (targetRuntime === runtime) {
|
|
344
|
-
runtime = undefined;
|
|
345
|
-
}
|
|
346
|
-
} catch {
|
|
347
|
-
publish('session.error', { code: 'RUNTIME_DISPOSAL_FAILED' }, sessionId);
|
|
348
|
-
}
|
|
542
|
+
void disposeIdleSessionRuntime(sessionId);
|
|
349
543
|
}, idleTimeoutMs);
|
|
350
544
|
idleDisposeTimers.set(sessionId, timer);
|
|
351
545
|
};
|
|
@@ -639,7 +833,8 @@ export function createSessionDaemon({
|
|
|
639
833
|
return entries;
|
|
640
834
|
};
|
|
641
835
|
|
|
642
|
-
const projectMessageEntries = (
|
|
836
|
+
const projectMessageEntries = (activeRuntime, targetDir = activeDirectory || cwd) => {
|
|
837
|
+
const session = activeRuntime?.session;
|
|
643
838
|
// Use the active branch, not the full file. `getEntries()` returns every
|
|
644
839
|
// entry ever written, so a bare `branch()`/`resetLeaf()` would appear to
|
|
645
840
|
// do nothing. `getBranch()` follows the current leaf and is what
|
|
@@ -659,6 +854,42 @@ export function createSessionDaemon({
|
|
|
659
854
|
}
|
|
660
855
|
let latestUserMessageId;
|
|
661
856
|
return entries.flatMap((entry) => {
|
|
857
|
+
// Extension-authored content: custom entries (`appendEntry`) and custom
|
|
858
|
+
// messages (`sendMessage`) both surface as extension-role items so the
|
|
859
|
+
// UI can render them through its extension renderer registry.
|
|
860
|
+
if (entry?.type === 'custom') {
|
|
861
|
+
if (typeof entry.customType !== 'string' || entry.customType.length === 0 || typeof entry.id !== 'string') return [];
|
|
862
|
+
const timestamp = Date.parse(entry.timestamp);
|
|
863
|
+
return [{
|
|
864
|
+
message: {
|
|
865
|
+
id: entry.id, sessionId: session.sessionId, directory: targetDir, role: 'extension',
|
|
866
|
+
customType: entry.customType,
|
|
867
|
+
createdAt: Number.isFinite(timestamp) ? timestamp : 0,
|
|
868
|
+
...(entry.data !== undefined ? { data: redactAttachmentValues(entry.data) } : {}),
|
|
869
|
+
},
|
|
870
|
+
parts: [],
|
|
871
|
+
}];
|
|
872
|
+
}
|
|
873
|
+
if (entry?.type === 'custom_message') {
|
|
874
|
+
if (typeof entry.customType !== 'string' || entry.customType.length === 0 || typeof entry.id !== 'string') return [];
|
|
875
|
+
if (entry.display === false) return [];
|
|
876
|
+
const timestamp = Date.parse(entry.timestamp);
|
|
877
|
+
const text = typeof entry.content === 'string'
|
|
878
|
+
? entry.content
|
|
879
|
+
: Array.isArray(entry.content)
|
|
880
|
+
? textFromContent(entry.content)
|
|
881
|
+
: '';
|
|
882
|
+
return [{
|
|
883
|
+
message: {
|
|
884
|
+
id: entry.id, sessionId: session.sessionId, directory: targetDir, role: 'extension',
|
|
885
|
+
customType: entry.customType,
|
|
886
|
+
text: redactAttachmentPaths(text),
|
|
887
|
+
createdAt: Number.isFinite(timestamp) ? timestamp : 0,
|
|
888
|
+
...(entry.details !== undefined ? { details: redactAttachmentValues(entry.details) } : {}),
|
|
889
|
+
},
|
|
890
|
+
parts: [],
|
|
891
|
+
}];
|
|
892
|
+
}
|
|
662
893
|
if (entry?.type !== 'message' || !entry.message || typeof entry.id !== 'string') return [];
|
|
663
894
|
const timestamp = Date.parse(entry.timestamp);
|
|
664
895
|
const createdAt = Number.isFinite(timestamp) ? timestamp : 0;
|
|
@@ -666,13 +897,13 @@ export function createSessionDaemon({
|
|
|
666
897
|
const text = redactAttachmentPaths(typeof entry.message.content === 'string'
|
|
667
898
|
? entry.message.content
|
|
668
899
|
: Array.isArray(entry.message.content)
|
|
669
|
-
? entry.message.content
|
|
900
|
+
? textFromContent(entry.message.content)
|
|
670
901
|
: '');
|
|
671
902
|
latestUserMessageId = entry.id;
|
|
672
903
|
return [{ message: { id: entry.id, sessionId: session.sessionId, directory: targetDir, role: 'user', text, createdAt }, parts: [] }];
|
|
673
904
|
}
|
|
674
905
|
if (entry.message.role !== 'assistant' || !Array.isArray(entry.message.content)) return [];
|
|
675
|
-
const text = redactAttachmentPaths(entry.message.content
|
|
906
|
+
const text = redactAttachmentPaths(textFromContent(entry.message.content));
|
|
676
907
|
const thinking = redactAttachmentPaths(entry.message.content.filter((part) => part?.type === 'thinking').map((part) => part.thinking).join(''));
|
|
677
908
|
const usage = projectUsage(entry.message.usage);
|
|
678
909
|
const parts = entry.message.content.flatMap((part, index) => {
|
|
@@ -682,6 +913,7 @@ export function createSessionDaemon({
|
|
|
682
913
|
const result = toolResults.get(part.id);
|
|
683
914
|
const running = streaming && !result;
|
|
684
915
|
const interrupted = !running && !result;
|
|
916
|
+
const metadata = mergeToolPresentationMetadata(result?.metadata, activeRuntime, targetDir, part.name, part.arguments);
|
|
685
917
|
return [{
|
|
686
918
|
type: 'tool',
|
|
687
919
|
id: `${entry.id}:tool:${part.id}`,
|
|
@@ -697,7 +929,7 @@ export function createSessionDaemon({
|
|
|
697
929
|
? { error: 'Tool was interrupted before completion.' }
|
|
698
930
|
: {}),
|
|
699
931
|
...(result?.isError || interrupted ? { isError: true } : {}),
|
|
700
|
-
...(
|
|
932
|
+
...(metadata ? { metadata } : {}),
|
|
701
933
|
...(Number.isFinite(result?.endedAt)
|
|
702
934
|
? { endedAt: result.endedAt }
|
|
703
935
|
: interrupted
|
|
@@ -730,13 +962,14 @@ export function createSessionDaemon({
|
|
|
730
962
|
throw new SessionDaemonProtocolError('INVALID_SESSION', 'Pi returned an invalid active session.');
|
|
731
963
|
}
|
|
732
964
|
const model = session.model;
|
|
733
|
-
const messages = projectMessageEntries(
|
|
965
|
+
const messages = projectMessageEntries(activeRuntime, targetDir);
|
|
734
966
|
const lastAssistant = [...messages].reverse().find((entry) => entry.message.role === 'assistant')?.message;
|
|
735
967
|
const sessionModel = lastAssistant?.model
|
|
736
968
|
?? (model?.provider && model?.id ? { providerId: model.provider, modelId: model.id } : undefined);
|
|
737
969
|
const sessionThinking = lastAssistant?.thinkingLevel || session.thinkingLevel;
|
|
738
970
|
const isStreaming = session.isStreaming === true;
|
|
739
971
|
const retry = retryStateBySession.get(session.sessionId);
|
|
972
|
+
const compaction = compactionStateFor(session);
|
|
740
973
|
return {
|
|
741
974
|
session: {
|
|
742
975
|
id: session.sessionId, directory: targetDir, createdAt, updatedAt: createdAt,
|
|
@@ -750,6 +983,7 @@ export function createSessionDaemon({
|
|
|
750
983
|
isStreaming,
|
|
751
984
|
lifecycle: retry ? 'retry' : isStreaming ? 'busy' : 'idle',
|
|
752
985
|
...(retry ? { retry } : {}),
|
|
986
|
+
...(compaction ? { compaction } : {}),
|
|
753
987
|
...(activeRunStartedAt.has(session.sessionId) ? { runStartedAt: activeRunStartedAt.get(session.sessionId) } : {}),
|
|
754
988
|
serverNow: Date.now(),
|
|
755
989
|
};
|
|
@@ -782,24 +1016,21 @@ export function createSessionDaemon({
|
|
|
782
1016
|
});
|
|
783
1017
|
if (!newRuntime.cwd) newRuntime.cwd = targetCwd;
|
|
784
1018
|
// Apply default retry limit for new sessions. Explicit per-run overrides win.
|
|
1019
|
+
// With no PiChamber override configured, Pi's own retry settings stay
|
|
1020
|
+
// authoritative — the runtime default (3) already matches, so nothing is
|
|
1021
|
+
// applied and a user's Pi-native maxRetries value is never stomped.
|
|
785
1022
|
try {
|
|
786
1023
|
const settingsManager = newRuntime.services?.settingsManager;
|
|
787
1024
|
if (settingsManager && typeof settingsManager.getRetrySettings === 'function') {
|
|
788
|
-
|
|
789
|
-
if (effective
|
|
790
|
-
try {
|
|
791
|
-
const raw = await readFile(join(resolvePiChamberDataDir(), 'pi', 'settings.json'), 'utf8');
|
|
792
|
-
const parsed = JSON.parse(raw);
|
|
793
|
-
if (Number.isInteger(parsed?.defaultRetryLimit)) effective = parsed.defaultRetryLimit;
|
|
794
|
-
} catch {}
|
|
795
|
-
if (effective === undefined) effective = 3;
|
|
796
|
-
}
|
|
797
|
-
if (Number.isInteger(effective) && effective >= 0 && effective <= 10) {
|
|
1025
|
+
const effective = await resolveEffectiveRetryLimit({ payloadRetryLimit: explicitRetryLimit, dataDir: resolvePiChamberDataDir() });
|
|
1026
|
+
if (effective !== undefined) {
|
|
798
1027
|
const current = settingsManager.getRetrySettings().maxRetries;
|
|
799
1028
|
if (current !== effective) {
|
|
800
1029
|
if (typeof settingsManager.applyOverrides === 'function') {
|
|
1030
|
+
// In-memory only: applyOverrides never queues a write, so this
|
|
1031
|
+
// scopes the limit to sessions created on this runtime without
|
|
1032
|
+
// touching Pi's own settings files.
|
|
801
1033
|
settingsManager.applyOverrides({ retry: { maxRetries: effective } });
|
|
802
|
-
if (explicitRetryLimit === undefined) await settingsManager.flush().catch(() => {});
|
|
803
1034
|
} else if (settingsManager.globalSettings) {
|
|
804
1035
|
settingsManager.globalSettings.retry = { ...(settingsManager.globalSettings.retry ?? {}), maxRetries: effective };
|
|
805
1036
|
}
|
|
@@ -1474,7 +1705,7 @@ export function createSessionDaemon({
|
|
|
1474
1705
|
*/
|
|
1475
1706
|
const projectToolResult = (result, isError) => {
|
|
1476
1707
|
const content = result && typeof result === 'object' && Array.isArray(result.content) ? result.content : [];
|
|
1477
|
-
const output = redactAttachmentPaths(content
|
|
1708
|
+
const output = redactAttachmentPaths(textFromContent(content));
|
|
1478
1709
|
let metadata;
|
|
1479
1710
|
if (result && typeof result === 'object' && result.details && typeof result.details === 'object') {
|
|
1480
1711
|
const details = redactAttachmentValues(result.details);
|
|
@@ -1660,9 +1891,26 @@ export function createSessionDaemon({
|
|
|
1660
1891
|
// report asynchronous failure through the existing session event channel.
|
|
1661
1892
|
const generation = (sendGenerationBySession.get(payload.sessionId) ?? 0) + 1;
|
|
1662
1893
|
sendGenerationBySession.set(payload.sessionId, generation);
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1894
|
+
// Slash-prefixed input dispatches extension commands and skill/template
|
|
1895
|
+
// expansion exactly like the pi CLI and RPC modes; plain text keeps the
|
|
1896
|
+
// sendUserMessage path so it is never expanded.
|
|
1897
|
+
const sendCall = content.startsWith('/')
|
|
1898
|
+
? activeRuntime.session.prompt(content, {
|
|
1899
|
+
source: 'rpc',
|
|
1900
|
+
...(deliverAs ? { streamingBehavior: deliverAs } : {}),
|
|
1901
|
+
})
|
|
1902
|
+
: activeRuntime.session.sendUserMessage(content, deliverAs ? { deliverAs } : undefined);
|
|
1903
|
+
Promise.resolve(sendCall).then(() => {
|
|
1904
|
+
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
1905
|
+
if (settledSendGenerationBySession.get(payload.sessionId) === generation) return;
|
|
1906
|
+
if (activeRuntime.session?.isStreaming) return;
|
|
1907
|
+
settledSendGenerationBySession.set(payload.sessionId, generation);
|
|
1908
|
+
// Extension commands can complete without starting an agent turn, so Pi
|
|
1909
|
+
// emits no agent_settled event. Close the optimistic browser lifecycle
|
|
1910
|
+
// when the command promise itself is the authoritative completion edge.
|
|
1911
|
+
publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, payload.sessionId, activeRuntime.cwd);
|
|
1912
|
+
completeRequestedShutdown(payload.sessionId);
|
|
1913
|
+
}).catch((error) => {
|
|
1666
1914
|
if (sendGenerationBySession.get(payload.sessionId) !== generation) return;
|
|
1667
1915
|
publish('session.error', {
|
|
1668
1916
|
code: 'ASSISTANT_ERROR',
|
|
@@ -1670,7 +1918,10 @@ export function createSessionDaemon({
|
|
|
1670
1918
|
? { message: redactAttachmentPaths(error.message) }
|
|
1671
1919
|
: {}),
|
|
1672
1920
|
}, payload.sessionId, activeRuntime.cwd);
|
|
1673
|
-
if (!activeRuntime.session?.isStreaming)
|
|
1921
|
+
if (!activeRuntime.session?.isStreaming) {
|
|
1922
|
+
completeRequestedShutdown(payload.sessionId);
|
|
1923
|
+
return;
|
|
1924
|
+
}
|
|
1674
1925
|
Promise.resolve(activeRuntime.session.abort()).catch(() => {});
|
|
1675
1926
|
});
|
|
1676
1927
|
return { accepted: true, messageId };
|
|
@@ -1684,6 +1935,8 @@ export function createSessionDaemon({
|
|
|
1684
1935
|
entryId: node.entry.id,
|
|
1685
1936
|
parentId: node.entry.parentId,
|
|
1686
1937
|
...(node.entry.type === 'session_info' && typeof node.entry.name === 'string' ? { title: node.entry.name } : {}),
|
|
1938
|
+
...(typeof node.label === 'string' && node.label.length > 0 ? { label: node.label.slice(0, 256) } : {}),
|
|
1939
|
+
...(typeof node.labelTimestamp === 'string' ? { labelTimestamp: node.labelTimestamp } : {}),
|
|
1687
1940
|
updatedAt: Date.parse(node.entry.timestamp) || 0,
|
|
1688
1941
|
children: node.children.map(project),
|
|
1689
1942
|
});
|
|
@@ -1708,9 +1961,14 @@ export function createSessionDaemon({
|
|
|
1708
1961
|
}
|
|
1709
1962
|
messageEntryAliases.clearSession({ cwd: active?.cwd || targetDir, sessionId });
|
|
1710
1963
|
retryStateBySession.delete(sessionId);
|
|
1964
|
+
compactionStateBySession.delete(sessionId);
|
|
1711
1965
|
activeRunStartedAt.delete(sessionId);
|
|
1966
|
+
shutdownRequestedBySession.delete(sessionId);
|
|
1967
|
+
sendGenerationBySession.delete(sessionId);
|
|
1968
|
+
settledSendGenerationBySession.delete(sessionId);
|
|
1712
1969
|
latestUserMessageIds.delete(sessionId);
|
|
1713
1970
|
latestAssistantMessageIds.delete(sessionId);
|
|
1971
|
+
toolInputBySession.delete(sessionId);
|
|
1714
1972
|
publish('session.lifecycle', { state: 'idle', deleted: true, serverNow: Date.now() }, sessionId, targetDir);
|
|
1715
1973
|
};
|
|
1716
1974
|
|
|
@@ -1722,7 +1980,7 @@ export function createSessionDaemon({
|
|
|
1722
1980
|
const text = redactAttachmentPaths(typeof content === 'string'
|
|
1723
1981
|
? content
|
|
1724
1982
|
: Array.isArray(content)
|
|
1725
|
-
? content
|
|
1983
|
+
? textFromContent(content)
|
|
1726
1984
|
: '');
|
|
1727
1985
|
const messageId = `user-${sessionId}-${sequence + 1}`;
|
|
1728
1986
|
messageEntryAliases.retain({ cwd: directory, sessionId, syntheticMessageId: messageId, message: event.message });
|
|
@@ -1786,7 +2044,7 @@ export function createSessionDaemon({
|
|
|
1786
2044
|
const usage = projectUsage(event.message.usage);
|
|
1787
2045
|
publish('assistant.message.end', {
|
|
1788
2046
|
messageId,
|
|
1789
|
-
text: redactAttachmentPaths(content
|
|
2047
|
+
text: redactAttachmentPaths(textFromContent(content)),
|
|
1790
2048
|
thinking: redactAttachmentPaths(content.filter((part) => part?.type === 'thinking').map((part) => part.thinking).join('')),
|
|
1791
2049
|
durationMs,
|
|
1792
2050
|
...(content.some((part) => part?.type === 'toolCall') ? { continuing: true } : {}),
|
|
@@ -1795,13 +2053,44 @@ export function createSessionDaemon({
|
|
|
1795
2053
|
}, sessionId, directory);
|
|
1796
2054
|
streamingMessageIds.delete(sessionId);
|
|
1797
2055
|
clearStreamingRedactionBuffers(sessionId);
|
|
2056
|
+
} else if (event.message?.role === 'custom') {
|
|
2057
|
+
publishExtensionCustomMessage(sessionId, event.message, directory);
|
|
2058
|
+
}
|
|
2059
|
+
break;
|
|
2060
|
+
}
|
|
2061
|
+
case 'entry_appended': {
|
|
2062
|
+
const entry = event.entry;
|
|
2063
|
+
if (entry?.type !== 'custom' || typeof entry.customType !== 'string') break;
|
|
2064
|
+
const timestamp = Date.parse(entry.timestamp);
|
|
2065
|
+
publish('extension.entry', {
|
|
2066
|
+
id: typeof entry.id === 'string' ? entry.id : `ext-${sessionId}-${sequence + 1}`,
|
|
2067
|
+
customType: entry.customType,
|
|
2068
|
+
...(entry.data !== undefined ? { data: redactAttachmentValues(entry.data) } : {}),
|
|
2069
|
+
createdAt: Number.isFinite(timestamp) ? timestamp : Date.now(),
|
|
2070
|
+
}, sessionId, directory);
|
|
2071
|
+
// Declarative GUI payloads are additionally mirrored into normalized
|
|
2072
|
+
// live state so panels/apps update in place and survive reconnects.
|
|
2073
|
+
if (entry.customType === 'pichamber.ui' || entry.customType.startsWith('pichamber.')) {
|
|
2074
|
+
const descriptor = entry.data && typeof entry.data === 'object' && !Array.isArray(entry.data)
|
|
2075
|
+
? (entry.data.ui && typeof entry.data.ui === 'object' && !Array.isArray(entry.data.ui) ? entry.data.ui : entry.data)
|
|
2076
|
+
: undefined;
|
|
2077
|
+
if (descriptor) {
|
|
2078
|
+
if (entry.customType === 'pichamber.app') {
|
|
2079
|
+
mirrorExtensionApp(sessionId, descriptor, directory);
|
|
2080
|
+
} else {
|
|
2081
|
+
mirrorExtensionPanel(sessionId, descriptor, directory);
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
1798
2084
|
}
|
|
1799
2085
|
break;
|
|
1800
2086
|
}
|
|
1801
2087
|
case 'tool_execution_start': {
|
|
1802
2088
|
const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
|
|
1803
2089
|
const startedAt = Date.now();
|
|
2090
|
+
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
2091
|
+
const metadata = mergeToolPresentationMetadata(undefined, activeRuntime, directory, event.toolName, event.args);
|
|
1804
2092
|
toolStartedAt.set(event.toolCallId, startedAt);
|
|
2093
|
+
rememberToolInput(sessionId, event.toolCallId, event.args);
|
|
1805
2094
|
publish('session.tool.start', {
|
|
1806
2095
|
toolCallId: event.toolCallId,
|
|
1807
2096
|
partId: `${messageId}:tool:${event.toolCallId}`,
|
|
@@ -1810,13 +2099,17 @@ export function createSessionDaemon({
|
|
|
1810
2099
|
toolName: event.toolName,
|
|
1811
2100
|
state: 'running',
|
|
1812
2101
|
...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
|
|
2102
|
+
...(metadata ? { metadata } : {}),
|
|
1813
2103
|
startedAt,
|
|
1814
2104
|
}, sessionId, directory);
|
|
1815
2105
|
break;
|
|
1816
2106
|
}
|
|
1817
2107
|
case 'tool_execution_update': {
|
|
1818
2108
|
const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
|
|
2109
|
+
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
2110
|
+
const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
|
|
1819
2111
|
const projected = projectToolResult(event.partialResult, false);
|
|
2112
|
+
const metadata = mergeToolPresentationMetadata(projected.metadata, activeRuntime, directory, event.toolName, toolArgs);
|
|
1820
2113
|
publish('session.tool.update', {
|
|
1821
2114
|
toolCallId: event.toolCallId,
|
|
1822
2115
|
partId: `${messageId}:tool:${event.toolCallId}`,
|
|
@@ -1826,14 +2119,19 @@ export function createSessionDaemon({
|
|
|
1826
2119
|
state: 'running',
|
|
1827
2120
|
...(event.args !== undefined ? { input: redactAttachmentValues(event.args) } : {}),
|
|
1828
2121
|
...projected,
|
|
2122
|
+
...(metadata ? { metadata } : {}),
|
|
1829
2123
|
}, sessionId, directory);
|
|
1830
2124
|
break;
|
|
1831
2125
|
}
|
|
1832
2126
|
case 'tool_execution_end': {
|
|
1833
2127
|
const messageId = streamingMessageIds.get(sessionId) ?? latestAssistantMessageIds.get(sessionId) ?? `assistant-${sessionId}`;
|
|
1834
2128
|
const startedAt = toolStartedAt.get(event.toolCallId);
|
|
2129
|
+
const toolArgs = event.args ?? getToolInput(sessionId, event.toolCallId);
|
|
1835
2130
|
toolStartedAt.delete(event.toolCallId);
|
|
2131
|
+
forgetToolInput(sessionId, event.toolCallId);
|
|
2132
|
+
const activeRuntime = runtimeRegistry?.get({ cwd: directory, sessionId }) || runtime;
|
|
1836
2133
|
const projected = projectToolResult(event.result, event.isError === true);
|
|
2134
|
+
const metadata = mergeToolPresentationMetadata(projected.metadata, activeRuntime, directory, event.toolName, toolArgs);
|
|
1837
2135
|
publish('session.tool.end', {
|
|
1838
2136
|
toolCallId: event.toolCallId,
|
|
1839
2137
|
partId: `${messageId}:tool:${event.toolCallId}`,
|
|
@@ -1843,6 +2141,7 @@ export function createSessionDaemon({
|
|
|
1843
2141
|
state: event.isError ? 'error' : 'completed',
|
|
1844
2142
|
isError: event.isError === true,
|
|
1845
2143
|
...projected,
|
|
2144
|
+
...(metadata ? { metadata } : {}),
|
|
1846
2145
|
...(Number.isFinite(startedAt) ? { startedAt } : {}),
|
|
1847
2146
|
endedAt: Date.now(),
|
|
1848
2147
|
}, sessionId, directory);
|
|
@@ -1883,20 +2182,81 @@ export function createSessionDaemon({
|
|
|
1883
2182
|
case 'agent_settled':
|
|
1884
2183
|
retryStateBySession.delete(sessionId);
|
|
1885
2184
|
activeRunStartedAt.delete(sessionId);
|
|
2185
|
+
settledSendGenerationBySession.set(sessionId, sendGenerationBySession.get(sessionId) ?? 0);
|
|
1886
2186
|
latestUserMessageIds.delete(sessionId);
|
|
1887
2187
|
latestAssistantMessageIds.delete(sessionId);
|
|
2188
|
+
toolInputBySession.delete(sessionId);
|
|
1888
2189
|
publish('session.lifecycle', { state: 'idle', serverNow: Date.now() }, sessionId, directory);
|
|
1889
|
-
scheduleIdleDisposal(sessionId);
|
|
2190
|
+
if (!completeRequestedShutdown(sessionId)) scheduleIdleDisposal(sessionId);
|
|
2191
|
+
break;
|
|
2192
|
+
case 'session_info_changed': {
|
|
2193
|
+
const title = typeof event.name === 'string' ? event.name.trim() : '';
|
|
2194
|
+
if (title) publish('session.updated', { title: redactAttachmentPaths(title).slice(0, 256) }, sessionId, directory);
|
|
2195
|
+
break;
|
|
2196
|
+
}
|
|
2197
|
+
case 'model_select':
|
|
2198
|
+
if (event.model?.provider && event.model?.id) {
|
|
2199
|
+
publish('session.model', {
|
|
2200
|
+
model: { providerId: event.model.provider, modelId: event.model.id },
|
|
2201
|
+
}, sessionId, directory);
|
|
2202
|
+
}
|
|
1890
2203
|
break;
|
|
1891
2204
|
case 'thinking_level_changed':
|
|
1892
2205
|
publish('session.thinking', { thinking: event.level }, sessionId, directory);
|
|
1893
2206
|
break;
|
|
1894
|
-
case 'compaction_start':
|
|
1895
|
-
|
|
2207
|
+
case 'compaction_start': {
|
|
2208
|
+
clearIdleDisposal(sessionId);
|
|
2209
|
+
const compaction = { phase: 'running', reason: event.reason, startedAt: Date.now() };
|
|
2210
|
+
compactionStateBySession.set(sessionId, compaction);
|
|
2211
|
+
publish('session.compaction', compaction, sessionId, directory);
|
|
2212
|
+
break;
|
|
2213
|
+
}
|
|
2214
|
+
case 'summarization_retry_scheduled': {
|
|
2215
|
+
const current = compactionStateBySession.get(sessionId);
|
|
2216
|
+
if (!current || (current.phase !== 'running' && current.phase !== 'retrying')) break;
|
|
2217
|
+
const compaction = {
|
|
2218
|
+
...current,
|
|
2219
|
+
phase: 'retrying',
|
|
2220
|
+
attempt: event.attempt,
|
|
2221
|
+
maxAttempts: event.maxAttempts,
|
|
2222
|
+
next: Date.now() + event.delayMs,
|
|
2223
|
+
message: redactAttachmentPaths(event.errorMessage),
|
|
2224
|
+
};
|
|
2225
|
+
compactionStateBySession.set(sessionId, compaction);
|
|
2226
|
+
publish('session.compaction', compaction, sessionId, directory);
|
|
2227
|
+
break;
|
|
2228
|
+
}
|
|
2229
|
+
case 'summarization_retry_attempt_start': {
|
|
2230
|
+
if (event.source !== 'compaction') break;
|
|
2231
|
+
const current = compactionStateBySession.get(sessionId);
|
|
2232
|
+
if (!current) break;
|
|
2233
|
+
const compaction = { ...current, phase: 'running' };
|
|
2234
|
+
compactionStateBySession.set(sessionId, compaction);
|
|
2235
|
+
publish('session.compaction', compaction, sessionId, directory);
|
|
1896
2236
|
break;
|
|
1897
|
-
|
|
1898
|
-
|
|
2237
|
+
}
|
|
2238
|
+
case 'compaction_end': {
|
|
2239
|
+
const current = compactionStateBySession.get(sessionId);
|
|
2240
|
+
const phase = event.aborted ? 'aborted' : event.result ? 'completed' : 'failed';
|
|
2241
|
+
const compaction = {
|
|
2242
|
+
phase,
|
|
2243
|
+
...(event.reason ? { reason: event.reason } : {}),
|
|
2244
|
+
...(current?.startedAt ? { startedAt: current.startedAt } : {}),
|
|
2245
|
+
completedAt: Date.now(),
|
|
2246
|
+
...(event.result && Number.isFinite(event.result.tokensBefore) && event.result.tokensBefore >= 0
|
|
2247
|
+
? { tokensBefore: event.result.tokensBefore }
|
|
2248
|
+
: {}),
|
|
2249
|
+
...(event.result && Number.isFinite(event.result.estimatedTokensAfter) && event.result.estimatedTokensAfter >= 0
|
|
2250
|
+
? { estimatedTokensAfter: event.result.estimatedTokensAfter }
|
|
2251
|
+
: {}),
|
|
2252
|
+
willRetry: event.willRetry === true,
|
|
2253
|
+
...(typeof event.errorMessage === 'string' ? { message: redactAttachmentPaths(event.errorMessage) } : {}),
|
|
2254
|
+
};
|
|
2255
|
+
compactionStateBySession.set(sessionId, compaction);
|
|
2256
|
+
publish('session.compaction', compaction, sessionId, directory);
|
|
2257
|
+
if (!event.willRetry) scheduleIdleDisposal(sessionId);
|
|
1899
2258
|
break;
|
|
2259
|
+
}
|
|
1900
2260
|
default:
|
|
1901
2261
|
break;
|
|
1902
2262
|
}
|
|
@@ -1924,6 +2284,7 @@ export function createSessionDaemon({
|
|
|
1924
2284
|
'sessions.setThinking', 'sessions.compact', 'providers.list', 'providers.refresh', 'providers.config.get', 'providers.models.set', 'providers.status', 'providers.login',
|
|
1925
2285
|
'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
|
|
1926
2286
|
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.delete',
|
|
2287
|
+
'extensions.list', 'extensions.respond',
|
|
1927
2288
|
],
|
|
1928
2289
|
...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
|
|
1929
2290
|
},
|
|
@@ -2027,6 +2388,47 @@ export function createSessionDaemon({
|
|
|
2027
2388
|
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result });
|
|
2028
2389
|
return;
|
|
2029
2390
|
}
|
|
2391
|
+
case 'extensions.respond': {
|
|
2392
|
+
const resolution = await resolveExtensionDialog(message.payload);
|
|
2393
|
+
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: resolution });
|
|
2394
|
+
return;
|
|
2395
|
+
}
|
|
2396
|
+
case 'extensions.list': {
|
|
2397
|
+
const requestedExtensionsDir = message.payload?.directory || message.payload?.cwd;
|
|
2398
|
+
const activeRuntime = await ensureRuntime(requestedExtensionsDir ? await resolveDirectory(requestedExtensionsDir) : undefined);
|
|
2399
|
+
const extensionSession = activeRuntime.session;
|
|
2400
|
+
const extensionPaths = typeof extensionSession?.extensionRunner?.getExtensionPaths === 'function'
|
|
2401
|
+
? extensionSession.extensionRunner.getExtensionPaths()
|
|
2402
|
+
: [];
|
|
2403
|
+
const registeredCommands = typeof extensionSession?.extensionRunner?.getRegisteredCommands === 'function'
|
|
2404
|
+
? extensionSession.extensionRunner.getRegisteredCommands()
|
|
2405
|
+
: [];
|
|
2406
|
+
writeFrame(socket, {
|
|
2407
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
2408
|
+
kind: 'response',
|
|
2409
|
+
requestId: message.requestId,
|
|
2410
|
+
result: {
|
|
2411
|
+
directory: activeRuntime.cwd,
|
|
2412
|
+
extensions: (Array.isArray(extensionPaths) ? extensionPaths : [])
|
|
2413
|
+
.filter((extensionPath) => typeof extensionPath === 'string' && extensionPath.length > 0)
|
|
2414
|
+
// Opaque id only: server filesystem paths must never reach the
|
|
2415
|
+
// browser (see DOCUMENTATION.md route invariants).
|
|
2416
|
+
.map((extensionPath) => ({
|
|
2417
|
+
id: createHash('sha256').update(extensionPath).digest('hex').slice(0, 16),
|
|
2418
|
+
name: basename(extensionPath).replace(/\.(ts|js)$/, ''),
|
|
2419
|
+
})),
|
|
2420
|
+
commands: (Array.isArray(registeredCommands) ? registeredCommands : [])
|
|
2421
|
+
.filter((command) => command && typeof command.invocationName === 'string')
|
|
2422
|
+
.map((command) => ({
|
|
2423
|
+
name: command.invocationName,
|
|
2424
|
+
...(typeof command.description === 'string' ? { description: command.description } : {}),
|
|
2425
|
+
source: 'extension',
|
|
2426
|
+
...(typeof command.sourceInfo?.scope === 'string' ? { scope: command.sourceInfo.scope } : {}),
|
|
2427
|
+
})),
|
|
2428
|
+
},
|
|
2429
|
+
});
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
2030
2432
|
case 'sessions.list': {
|
|
2031
2433
|
const sessions = await listSessionItems(message.payload?.directory || message.payload?.cwd);
|
|
2032
2434
|
writeFrame(socket, {
|
|
@@ -2140,7 +2542,15 @@ export function createSessionDaemon({
|
|
|
2140
2542
|
}
|
|
2141
2543
|
case 'sessions.compact': {
|
|
2142
2544
|
if (message.payload?.thinking !== undefined) validateThinking(message.payload.thinking);
|
|
2545
|
+
if (message.payload?.customInstructions !== undefined
|
|
2546
|
+
&& (typeof message.payload.customInstructions !== 'string' || message.payload.customInstructions.length > 20_000)) {
|
|
2547
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'Compaction instructions must be a string no longer than 20,000 characters.');
|
|
2548
|
+
}
|
|
2143
2549
|
const activeRuntime = await activateSession(message.payload?.sessionId, message.payload?.directory || message.payload?.cwd);
|
|
2550
|
+
const currentCompaction = compactionStateBySession.get(message.payload.sessionId);
|
|
2551
|
+
if (activeRuntime.session.isCompacting || currentCompaction?.phase === 'running' || currentCompaction?.phase === 'retrying') {
|
|
2552
|
+
throw new SessionDaemonProtocolError('SESSION_BUSY', 'This session is already compacting.');
|
|
2553
|
+
}
|
|
2144
2554
|
if (message.payload?.model !== undefined) {
|
|
2145
2555
|
await setSessionModel(activeRuntime, message.payload.model);
|
|
2146
2556
|
publishSessionModel(activeRuntime.session, message.payload.sessionId, activeRuntime.cwd);
|
|
@@ -2148,8 +2558,22 @@ export function createSessionDaemon({
|
|
|
2148
2558
|
if (message.payload?.thinking !== undefined) {
|
|
2149
2559
|
applyThinking(activeRuntime, message.payload.thinking, message.payload.sessionId, activeRuntime.cwd);
|
|
2150
2560
|
}
|
|
2151
|
-
|
|
2152
|
-
|
|
2561
|
+
Promise.resolve(activeRuntime.session.compact(message.payload?.customInstructions)).catch((error) => {
|
|
2562
|
+
const current = compactionStateBySession.get(message.payload.sessionId);
|
|
2563
|
+
if (current?.phase === 'completed' || current?.phase === 'failed' || current?.phase === 'aborted') return;
|
|
2564
|
+
const compaction = {
|
|
2565
|
+
phase: 'failed',
|
|
2566
|
+
reason: 'manual',
|
|
2567
|
+
...(current?.startedAt ? { startedAt: current.startedAt } : {}),
|
|
2568
|
+
completedAt: Date.now(),
|
|
2569
|
+
message: redactAttachmentPaths(error instanceof Error ? error.message : 'Compaction failed.'),
|
|
2570
|
+
willRetry: false,
|
|
2571
|
+
};
|
|
2572
|
+
compactionStateBySession.set(message.payload.sessionId, compaction);
|
|
2573
|
+
publish('session.compaction', compaction, message.payload.sessionId, activeRuntime.cwd);
|
|
2574
|
+
scheduleIdleDisposal(message.payload.sessionId);
|
|
2575
|
+
});
|
|
2576
|
+
writeFrame(socket, { protocolVersion: PROTOCOL_VERSION, kind: 'response', requestId: message.requestId, result: { accepted: true } });
|
|
2153
2577
|
return;
|
|
2154
2578
|
}
|
|
2155
2579
|
default:
|
|
@@ -2275,7 +2699,12 @@ export function createSessionDaemon({
|
|
|
2275
2699
|
}
|
|
2276
2700
|
loginAttempts.clear();
|
|
2277
2701
|
retryStateBySession.clear();
|
|
2702
|
+
compactionStateBySession.clear();
|
|
2278
2703
|
activeRunStartedAt.clear();
|
|
2704
|
+
shutdownRequestedBySession.clear();
|
|
2705
|
+
disposingSessionIds.clear();
|
|
2706
|
+
sendGenerationBySession.clear();
|
|
2707
|
+
settledSendGenerationBySession.clear();
|
|
2279
2708
|
latestUserMessageIds.clear();
|
|
2280
2709
|
latestAssistantMessageIds.clear();
|
|
2281
2710
|
for (const client of clients) client.destroy();
|