@pi-chamber/web 1.0.8-rc.1 → 1.0.8-rc.2
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/{AgentsSurface-BmHImX8m.js → AgentsSurface-CcWBqAWV.js} +1 -1
- package/dist/assets/{ChoicesArtifact-C71fGOm2.js → ChoicesArtifact-Kk-qvrSB.js} +1 -1
- package/dist/assets/{DiagramView-BZQxoiZu.js → DiagramView-DZUBo1uP.js} +1 -1
- package/dist/assets/{DiffView-C70pbgk-.js → DiffView-CiZy4jFA.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-Cu8c3gBV.js → FileSaveConflictDialog-DZ9NDwOO.js} +1 -1
- package/dist/assets/{FilesView-nFJYEdRw.js → FilesView-DqiZ9kw9.js} +1 -1
- package/dist/assets/{GitHubDetailScaffold-Jvv_tgbl.js → GitHubDetailScaffold-DM2DH7o8.js} +1 -1
- package/dist/assets/{GitHubLinkPicker-BXD2ODRi.js → GitHubLinkPicker-ChB8NZ1h.js} +1 -1
- package/dist/assets/{GitHubListPrimitives-BWI706F0.js → GitHubListPrimitives-CibDiJGq.js} +1 -1
- package/dist/assets/{GitView-MIDG5RYW.js → GitView--EaZQrBr.js} +5 -5
- package/dist/assets/{IssuesSurface-uNlozeu0.js → IssuesSurface-CySTpaD1.js} +3 -3
- package/dist/assets/{JsonTreeView-CSLsTriz.js → JsonTreeView-_yMHKKQZ.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Cs-7BfWi.js → MarkdownRendererImpl-D_-2fQw0.js} +1 -1
- package/dist/assets/{PatchDiff-axbsnbTJ.js → PatchDiff-bHObDlhD.js} +1 -1
- package/dist/assets/{PierreDiffViewer-lwn6w_5w.js → PierreDiffViewer-UY7Cse-s.js} +1 -1
- package/dist/assets/{PullRequestsSurface-o_AXDjbO.js → PullRequestsSurface-iXy6chwc.js} +2 -2
- package/dist/assets/{SessionSwitcherContent-C4CMlcbv.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DCBVuCoo.js → SessionSwitcherDropdown-CDOX-5Y2.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DyeIrsro.js → SessionUnreadDot-Dwc3MdvA.js} +1 -1
- package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
- package/dist/assets/{SettingsWindow-Cb4st5y5.js → SettingsWindow-CUg49Mfh.js} +1 -1
- package/dist/assets/{SubagentsArtifact-BzeMEoFP.js → SubagentsArtifact-DUZX9tDe.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BP2mOWdV.js → ToolOutputDialog-BuZZaRw4.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-D49XBR9b.js → ToolPartDiffPreview-CKncG6i2.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CLgDONEQ.js → VirtualizedFileDiff-BGZiLPe_.js} +1 -1
- package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
- package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
- package/dist/assets/{collapsible-BeyKtQGB.js → collapsible-Bro9KrfM.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-DmO6H8u6.js → computeVirtualFileMetrics-DJQqK49u.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-DOK251YW.js → contextFileOpenGuard-ByWK3Sru.js} +1 -1
- package/dist/assets/{fileTreeStatus-CnzR7kxA.js → fileTreeStatus-CyJ3TOYD.js} +1 -1
- package/dist/assets/{gitStatusPredicates-4kPg2t6j.js → gitStatusPredicates-BsXrwngT.js} +1 -1
- package/dist/assets/{githubLink-QvaLfNNT.js → githubLink-g2bmC0qi.js} +1 -1
- package/dist/assets/index-B_L9GVYw.css +1 -0
- package/dist/assets/{index-DMX9wT1Z.js → index-C9rUUQ_Y.js} +1 -1
- package/dist/assets/index-CKKWVoND.js +11 -0
- package/dist/assets/{main-BW9J3Y72.js → main-DT-4_fhe.js} +2 -2
- package/dist/assets/{main-BirYxac2.js → main-DsLMU9CT.js} +4 -4
- package/dist/assets/{markdownCore-CxmcPur8.js → markdownCore-QmM_aOnZ.js} +1 -1
- package/dist/assets/{miniChat-BRB11eEs.js → miniChat-BqGslD2z.js} +2 -2
- package/dist/assets/{mobile-DJZYYCuB.js → mobile-C5JOcDIC.js} +2 -2
- package/dist/assets/{nativeFileSave-B6QpoPRn.js → nativeFileSave-DSMsJqXM.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-PWoh3LNA.js → pi-session-focus-preference-Cc_S4zi1.js} +1 -1
- package/dist/assets/{renderDiffWithHighlighter-C48T6YFJ.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-N-BQdJl0.js → renderElectronMiniChatApp-CiSkecEE.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-8Kt2MyTN.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
- package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
- package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
- package/dist/assets/{runtimeSurface-kIEoYsPP.js → runtimeSurface-0K7vuUpd.js} +1 -1
- package/dist/assets/{selection-BTEdLRVK.js → selection-CnYkEsu_.js} +1 -1
- package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
- package/dist/assets/{useGitHubRemoteSearch-DIBHNu8r.js → useGitHubRemoteSearch-CgP-zEBj.js} +1 -1
- package/dist/assets/{useSwitcherItems-DfLbfX37.js → useSwitcherItems-C8G5F0hs.js} +1 -1
- package/dist/assets/{web-components-C_DsTJis.js → web-components-BpncHjnV.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/plugins/featured.json +12 -0
- package/plugins/subagents/package.json +1 -1
- package/plugins/visuals/extension.js +7 -4
- package/plugins/visuals/package.json +1 -1
- package/server/index.js +86 -27
- package/server/lib/git/DOCUMENTATION.md +4 -0
- package/server/lib/git/service.js +70 -5
- package/server/lib/git/service.test.js +179 -0
- package/server/lib/github/DOCUMENTATION.md +2 -0
- package/server/lib/marketplace/DOCUMENTATION.md +95 -0
- package/server/lib/marketplace/featured.js +176 -0
- package/server/lib/marketplace/featured.test.js +207 -0
- package/server/lib/marketplace/npm-registry.js +255 -0
- package/server/lib/marketplace/npm-registry.test.js +227 -0
- package/server/lib/marketplace/routes.js +64 -0
- package/server/lib/marketplace/routes.test.js +119 -0
- package/server/lib/marketplace/service.js +225 -0
- package/server/lib/marketplace/service.test.js +174 -0
- package/server/lib/notifications/DOCUMENTATION.md +10 -4
- package/server/lib/notifications/pi-notification-watcher.js +92 -33
- package/server/lib/notifications/pi-notification-watcher.test.js +79 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -0
- package/server/lib/pi/merged-event-stream.js +316 -0
- package/server/lib/pi/merged-event-stream.test.js +95 -0
- package/server/lib/pi/routes-daemon-pool.test.js +348 -0
- package/server/lib/pi/routes-merged-events.test.js +327 -0
- package/server/lib/pi/routes-sandbox.test.js +1684 -0
- package/server/lib/pi/routes.js +491 -90
- package/server/lib/pi/routes.test.js +87 -2
- package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
- package/server/lib/pi/sandbox/launcher.js +122 -0
- package/server/lib/pi/sandbox/launcher.test.js +91 -0
- package/server/lib/pi/sandbox/nono-launcher.js +455 -0
- package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
- package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
- package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
- package/server/lib/pi/sandbox/nono-profile.json +22 -0
- package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
- package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
- package/server/lib/pi/sandbox/project-sandbox.js +207 -0
- package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
- package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
- package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
- package/server/lib/pi/sandbox/trust-ask.js +135 -0
- package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
- package/server/lib/pi/sandbox/worktree-ids.js +96 -0
- package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +26 -6
- package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
- package/server/lib/pi/session-daemon/daemon-process.js +10 -1
- package/server/lib/pi/session-daemon/extension-config.js +206 -23
- package/server/lib/pi/session-daemon/extension-config.test.js +180 -0
- package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
- package/server/lib/pi/session-daemon/session-daemon.js +368 -56
- package/server/lib/pi/session-daemon/session-daemon.test.js +227 -0
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
- package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
- package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
- package/server/lib/pi/session-daemon/session-lease.js +93 -15
- package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
- package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
- package/server/lib/pi/session-daemon/supervisor.js +386 -35
- package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
- package/server/lib/pi/ui-settings-store.js +88 -2
- package/server/lib/pi/ui-settings-store.test.js +118 -0
- package/server/lib/plugins/DOCUMENTATION.md +17 -5
- package/server/lib/plugins/daemon-sync.js +16 -6
- package/server/lib/plugins/daemon-sync.test.js +12 -0
- package/server/lib/plugins/impact.test.js +2 -1
- package/server/lib/plugins/manifest.js +25 -0
- package/server/lib/plugins/manifest.test.js +9 -0
- package/server/lib/plugins/routes.test.js +28 -0
- package/server/lib/plugins/service.js +24 -2
- package/server/lib/server/cross-process-lock.js +28 -3
- package/dist/assets/SettingsView-BHBpt2Um.js +0 -7
- package/dist/assets/VisualFrame-CJrAvWSo.js +0 -22
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +0 -1
- package/dist/assets/index-B2v0_mez.js +0 -11
- package/dist/assets/index-D3F4JrPN.css +0 -1
- package/dist/assets/renderMobileApp-B7cT7m5b.js +0 -11
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +0 -62
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +0 -225
package/server/lib/pi/routes.js
CHANGED
|
@@ -35,6 +35,9 @@ import { createPiSnippetsStore } from './snippets-store.js';
|
|
|
35
35
|
import { isValidSendOperationId, isValidStreamEpoch } from './session-daemon/send-operation-registry.js';
|
|
36
36
|
import { ENGINE_HANDLER_COMMANDS, ENGINE_UNSUPPORTED_OPERATION, isValidEngineId } from './session-daemon/session-engines.js';
|
|
37
37
|
import { normalizeOpenRequestUrl } from './session-daemon/open-request.js';
|
|
38
|
+
import { createPiDaemonPool, MAIN_DAEMON_KEY, publicDaemonStreamId } from './session-daemon/daemon-pool.js';
|
|
39
|
+
import { decodePiEventCursor, subscribeMergedPiEvents } from './merged-event-stream.js';
|
|
40
|
+
import { registerPiSandboxRoutes } from './sandbox/sandbox-routes.js';
|
|
38
41
|
import { MAX_CONTROLS_PER_SESSION, parseComposerControl } from './session-daemon/extension-controls.js';
|
|
39
42
|
import {
|
|
40
43
|
DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
@@ -44,6 +47,7 @@ import {
|
|
|
44
47
|
|
|
45
48
|
const UNAVAILABLE_CODES = new Set([
|
|
46
49
|
'DAEMON_UNAVAILABLE',
|
|
50
|
+
'SANDBOX_UNAVAILABLE',
|
|
47
51
|
'DAEMON_AUTH_FAILED',
|
|
48
52
|
'DAEMON_REQUEST_FAILED',
|
|
49
53
|
'DAEMON_TIMEOUT',
|
|
@@ -73,16 +77,23 @@ const BAD_GATEWAY_CODES = new Set([
|
|
|
73
77
|
'DAEMON_RESPONSE_TOO_LARGE',
|
|
74
78
|
]);
|
|
75
79
|
|
|
80
|
+
// npm or git failed for a package install or update.
|
|
81
|
+
const PACKAGE_UPSTREAM_FAILURE_CODES = new Set([
|
|
82
|
+
'PACKAGE_INSTALL_FAILED',
|
|
83
|
+
'PACKAGE_UPDATE_FAILED',
|
|
84
|
+
]);
|
|
85
|
+
|
|
76
86
|
const writeDaemonError = (res, error) => {
|
|
77
87
|
const code = typeof error?.code === 'string' ? error.code : 'DAEMON_REQUEST_FAILED';
|
|
78
88
|
const status = UNAVAILABLE_CODES.has(code)
|
|
79
89
|
? 503
|
|
80
|
-
: BAD_GATEWAY_CODES.has(code)
|
|
90
|
+
: BAD_GATEWAY_CODES.has(code) || PACKAGE_UPSTREAM_FAILURE_CODES.has(code)
|
|
81
91
|
? 502
|
|
82
92
|
: code === 'INVALID_SESSION'
|
|
83
93
|
? 404
|
|
84
94
|
: code === 'SESSION_IN_USE' || code === 'OPERATION_PAYLOAD_MISMATCH' || code === 'STALE_STREAM_EPOCH'
|
|
85
95
|
|| code === ENGINE_UNSUPPORTED_OPERATION || code === 'CONTROL_UNAVAILABLE'
|
|
96
|
+
|| code === 'PACKAGE_ALREADY_INSTALLED' || code === 'PACKAGE_PINNED'
|
|
86
97
|
? 409
|
|
87
98
|
: code === 'OPERATION_EXPIRED'
|
|
88
99
|
? 410
|
|
@@ -93,11 +104,18 @@ const writeDaemonError = (res, error) => {
|
|
|
93
104
|
: code === 'ATTACHMENT_MISSING'
|
|
94
105
|
? 410
|
|
95
106
|
: 400;
|
|
96
|
-
|
|
107
|
+
// A sandbox failure carries the launcher's stable reason code (for
|
|
108
|
+
// example NO_LANDLOCK); never a path or raw launcher output.
|
|
109
|
+
// A session refused while it finishes a turn before changing daemons says
|
|
110
|
+
// so (`SESSION_SWITCHING`), since `SESSION_IN_USE` otherwise means another
|
|
111
|
+
// PiChamber instance holds it.
|
|
112
|
+
const reason = (code === 'SANDBOX_UNAVAILABLE' || code === 'SESSION_IN_USE') && typeof error?.reason === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(error.reason)
|
|
113
|
+
? error.reason
|
|
114
|
+
: undefined;
|
|
115
|
+
res.status(status).json({ error: { code, ...(reason ? { reason } : {}) } });
|
|
97
116
|
};
|
|
98
117
|
|
|
99
|
-
const
|
|
100
|
-
const runtime = getPiSessionDaemonRuntime();
|
|
118
|
+
const requireDaemon = (runtime) => {
|
|
101
119
|
if (!runtime) {
|
|
102
120
|
const error = new Error('The Pi session daemon is unavailable.');
|
|
103
121
|
error.code = 'DAEMON_UNAVAILABLE';
|
|
@@ -161,6 +179,36 @@ const projectListLiveStatus = (value) => {
|
|
|
161
179
|
};
|
|
162
180
|
};
|
|
163
181
|
|
|
182
|
+
// Fill in live state the owning daemon lacks from daemons still draining
|
|
183
|
+
// sessions for the same folder, matched by session id. Membership and every
|
|
184
|
+
// other field stay the owner's.
|
|
185
|
+
// Live state (`live`, `inputState`) another daemon samples for rows the
|
|
186
|
+
// list's own daemon lacks, merged by session id. Its sequences belong to
|
|
187
|
+
// that daemon's stream, so a merged row says which: `stream` (`main` for
|
|
188
|
+
// the main daemon) and that daemon's `streamEpoch`. `others` is a list of
|
|
189
|
+
// `{ stream, streamEpoch, items }`.
|
|
190
|
+
const mergeOtherDaemonsLiveState = (items, others) => {
|
|
191
|
+
if (others.length === 0) return items;
|
|
192
|
+
const byId = new Map();
|
|
193
|
+
for (const other of others) {
|
|
194
|
+
for (const item of other.items) {
|
|
195
|
+
if (!item.live && !item.inputState) continue;
|
|
196
|
+
if (!byId.get(item.session.id)?.item.live) byId.set(item.session.id, { other, item });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return items.map((item) => {
|
|
200
|
+
const found = byId.get(item.session.id);
|
|
201
|
+
if (!found || item.live || item.inputState) return item;
|
|
202
|
+
return {
|
|
203
|
+
...item,
|
|
204
|
+
...(found.item.live ? { live: found.item.live } : {}),
|
|
205
|
+
...(found.item.inputState ? { inputState: found.item.inputState } : {}),
|
|
206
|
+
stream: found.other.stream,
|
|
207
|
+
...(found.other.streamEpoch ? { streamEpoch: found.other.streamEpoch } : {}),
|
|
208
|
+
};
|
|
209
|
+
});
|
|
210
|
+
};
|
|
211
|
+
|
|
164
212
|
const projectSessionList = (sessions) => {
|
|
165
213
|
if (!Array.isArray(sessions)) throw protocolMismatch();
|
|
166
214
|
return sessions.map((item) => {
|
|
@@ -434,6 +482,13 @@ const projectSessionDetail = (value) => {
|
|
|
434
482
|
lastSequence: value.lastSequence,
|
|
435
483
|
isStreaming,
|
|
436
484
|
lifecycle,
|
|
485
|
+
// Read from the transcript on disk while the session's sandbox cannot
|
|
486
|
+
// run: history only, no live state (see the project sandbox manager).
|
|
487
|
+
// `readOnlyReason` is why the sandbox cannot run (a stable code).
|
|
488
|
+
...(value.readOnly === true ? {
|
|
489
|
+
readOnly: true,
|
|
490
|
+
...(typeof value.readOnlyReason === 'string' && /^[A-Z][A-Z0-9_]{1,63}$/.test(value.readOnlyReason) ? { readOnlyReason: value.readOnlyReason } : {}),
|
|
491
|
+
} : {}),
|
|
437
492
|
...projectRunningCommand(lifecycle, value.command),
|
|
438
493
|
...(retry ? { retry } : {}),
|
|
439
494
|
...(compaction ? { compaction } : {}),
|
|
@@ -709,6 +764,13 @@ export const projectExtensionList = (result) => {
|
|
|
709
764
|
// daemon already made path-free, re-checked here so nothing path-like or
|
|
710
765
|
// unexpected crosses.
|
|
711
766
|
const EXTENSION_CONFIG_ID_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
767
|
+
// The same rules as the daemon's `isValidNpmPackageName` (extension-config.js).
|
|
768
|
+
const NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9~-][a-z0-9._~-]*\/)?[a-z0-9~-][a-z0-9._~-]*$/;
|
|
769
|
+
const isNpmPackageName = (value) => typeof value === 'string' && value.length > 0 && value.length <= 214
|
|
770
|
+
&& NPM_PACKAGE_NAME_PATTERN.test(value);
|
|
771
|
+
const PACKAGE_VERSION_PATTERN = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
772
|
+
// npm install / update can take minutes.
|
|
773
|
+
const PACKAGE_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
|
|
712
774
|
const EXTENSION_CONFIG_OVERRIDE_STATES = new Set(['inherit', 'load', 'unload']);
|
|
713
775
|
const EXTENSION_CONFIG_GROUPS = new Set(['package', 'auto', 'settings', 'builtin']);
|
|
714
776
|
const EXTENSION_CONFIG_SCOPES = new Set(['user', 'project']);
|
|
@@ -758,7 +820,19 @@ const projectExtensionConfig = (result) => {
|
|
|
758
820
|
if (!pkg || typeof pkg !== 'object' || typeof pkg.id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(pkg.id)
|
|
759
821
|
|| !EXTENSION_CONFIG_SCOPES.has(pkg.scope) || !EXTENSION_CONFIG_PACKAGE_KINDS.has(pkg.kind)
|
|
760
822
|
|| (pkg.kind === 'local' ? !isDisplayText(pkg.source) || pkg.source.includes('/') : !isDisplayText(pkg.source))) throw protocolMismatch();
|
|
761
|
-
|
|
823
|
+
// Read from the package's own package.json; a bad value is dropped.
|
|
824
|
+
return {
|
|
825
|
+
id: pkg.id,
|
|
826
|
+
source: pkg.source,
|
|
827
|
+
scope: pkg.scope,
|
|
828
|
+
kind: pkg.kind,
|
|
829
|
+
installed: pkg.installed === true,
|
|
830
|
+
filtered: pkg.filtered === true,
|
|
831
|
+
...(isNpmPackageName(pkg.name) ? { name: pkg.name } : {}),
|
|
832
|
+
...(typeof pkg.version === 'string' && PACKAGE_VERSION_PATTERN.test(pkg.version) ? { version: pkg.version } : {}),
|
|
833
|
+
...(pkg.pichamber === true ? { pichamber: true } : {}),
|
|
834
|
+
...(pkg.pinned === true && pkg.kind === 'npm' ? { pinned: true } : {}),
|
|
835
|
+
};
|
|
762
836
|
});
|
|
763
837
|
const packageIds = new Set(packages.map((pkg) => pkg.id));
|
|
764
838
|
const extensions = result.extensions.map((extension) => {
|
|
@@ -1250,20 +1324,78 @@ export const projectEventFrame = (frame) => {
|
|
|
1250
1324
|
}
|
|
1251
1325
|
};
|
|
1252
1326
|
|
|
1253
|
-
const
|
|
1327
|
+
const sessionOperationDirectory = (req) => (typeof req.query?.directory === 'string' && req.query.directory.length > 0
|
|
1328
|
+
? req.query.directory
|
|
1329
|
+
: (typeof req.body?.directory === 'string' && req.body.directory.length > 0
|
|
1330
|
+
? req.body.directory
|
|
1331
|
+
: (typeof req.body?.cwd === 'string' && req.body.cwd.length > 0 ? req.body.cwd : undefined)));
|
|
1332
|
+
|
|
1333
|
+
// The folder a session operation was routed by: the request's own, or the
|
|
1334
|
+
// transcript's when `requestSessionOperation` looked it up. Stream stamps
|
|
1335
|
+
// use it so a response names the daemon that actually served it.
|
|
1336
|
+
const sessionRouteDirectory = (req, res) => res.locals?.piRouteDirectory ?? sessionOperationDirectory(req);
|
|
1337
|
+
|
|
1338
|
+
// Commands that let a session waiting to switch daemons finish its turn
|
|
1339
|
+
// (or be read) where it runs now. Anything else would start new work in the
|
|
1340
|
+
// old daemon, so it is refused until the session has moved.
|
|
1341
|
+
const DRAINING_SESSION_COMMANDS = new Set([
|
|
1342
|
+
'sessions.open', 'sessions.messages', 'sessions.tree', 'sessions.abort', 'sessions.abortBash', 'sessions.steer',
|
|
1343
|
+
'sessions.sendReceipt', 'extensions.draft', 'sessions.discardDraft',
|
|
1344
|
+
'extensions.custom.input', 'extensions.custom.viewport', 'extensions.custom.close', 'extensions.custom.focus', 'extensions.custom.refresh',
|
|
1345
|
+
]);
|
|
1346
|
+
|
|
1347
|
+
const sessionInUse = () => Object.assign(new Error('The session is finishing a turn before it switches.'), { code: 'SESSION_IN_USE', reason: 'SESSION_SWITCHING' });
|
|
1348
|
+
|
|
1349
|
+
// The daemon still running a session that waits to switch, or undefined.
|
|
1350
|
+
// Marks the response so its stream stamp names that daemon.
|
|
1351
|
+
const drainingSessionRuntime = (res, sandboxManager, sessionId, command) => {
|
|
1352
|
+
const draining = sandboxManager?.drainingSession?.(sessionId);
|
|
1353
|
+
if (!draining) return undefined;
|
|
1354
|
+
if (!DRAINING_SESSION_COMMANDS.has(command)) throw sessionInUse();
|
|
1355
|
+
if (res.locals) res.locals.piDrainingStream = { stream: draining.stream };
|
|
1356
|
+
return draining.runtime;
|
|
1357
|
+
};
|
|
1358
|
+
|
|
1359
|
+
// The folder that picks the daemon for a session operation. A daemon finds a
|
|
1360
|
+
// session by id wherever it lives, so the client's folder (its current one,
|
|
1361
|
+
// which a deep link can get wrong) or no folder at all could send a sandboxed
|
|
1362
|
+
// project's session to the main daemon and run its agent unsandboxed. While
|
|
1363
|
+
// any project is sandboxed, the session's transcript decides (the folder it
|
|
1364
|
+
// is stored under, then the folder in its header; see the manager's
|
|
1365
|
+
// `directoryForSession`); the client's folder applies only to a session not
|
|
1366
|
+
// yet written to disk. The daemon payload keeps the client's folder.
|
|
1367
|
+
const sessionDaemonDirectory = async (res, sandboxManager, sessionId, directory) => {
|
|
1368
|
+
if (!sandboxManager?.hasSandboxedProjects()) return directory;
|
|
1369
|
+
const transcriptDirectory = await sandboxManager.directoryForSession(sessionId);
|
|
1370
|
+
if (!transcriptDirectory) return sandboxManager.routeDirectory(directory);
|
|
1371
|
+
const routed = await sandboxManager.routeDirectory(transcriptDirectory);
|
|
1372
|
+
if (res.locals) res.locals.piRouteDirectory = routed;
|
|
1373
|
+
return routed;
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
const requestSessionOperation = async (req, res, daemonPool, command, payload = {}, sandboxManager) => {
|
|
1254
1377
|
const sessionId = sessionIdFrom(req);
|
|
1255
1378
|
if (!sessionId) {
|
|
1256
1379
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
1257
1380
|
return undefined;
|
|
1258
1381
|
}
|
|
1259
|
-
const directory =
|
|
1260
|
-
? req.query.directory
|
|
1261
|
-
: (typeof req.body?.directory === 'string' && req.body.directory.length > 0
|
|
1262
|
-
? req.body.directory
|
|
1263
|
-
: (typeof req.body?.cwd === 'string' && req.body.cwd.length > 0 ? req.body.cwd : undefined));
|
|
1382
|
+
const directory = sessionOperationDirectory(req);
|
|
1264
1383
|
try {
|
|
1265
|
-
|
|
1266
|
-
|
|
1384
|
+
const draining = drainingSessionRuntime(res, sandboxManager, sessionId, command);
|
|
1385
|
+
if (draining) {
|
|
1386
|
+
return await draining.request(command, { ...payload, sessionId, ...(directory ? { directory } : {}) });
|
|
1387
|
+
}
|
|
1388
|
+
const routeDirectory = await sessionDaemonDirectory(res, sandboxManager, sessionId, directory);
|
|
1389
|
+
const runtime = requireDaemon(daemonPool.forDirectory(routeDirectory));
|
|
1390
|
+
// The stream of the daemon this request goes to, taken now: the folder
|
|
1391
|
+
// may have another owner by the time the response is stamped.
|
|
1392
|
+
if (res.locals) res.locals.piServedStream = { stream: daemonPool.streamFor(routeDirectory) };
|
|
1393
|
+
// A send made with the old daemon's epoch right after the session moved.
|
|
1394
|
+
const sendPayload = typeof payload.streamEpoch === 'string' && sandboxManager?.sendEpochFor
|
|
1395
|
+
? { ...payload, streamEpoch: await sandboxManager.sendEpochFor(sessionId, payload.streamEpoch, runtime) }
|
|
1396
|
+
: payload;
|
|
1397
|
+
return await runtime.request(command, {
|
|
1398
|
+
...sendPayload,
|
|
1267
1399
|
sessionId,
|
|
1268
1400
|
...(directory ? { directory } : {}),
|
|
1269
1401
|
});
|
|
@@ -1280,6 +1412,16 @@ const requestSessionOperation = async (req, res, getPiSessionDaemonRuntime, comm
|
|
|
1280
1412
|
*/
|
|
1281
1413
|
export const registerPiRuntimeRoutes = (app, {
|
|
1282
1414
|
getPiSessionDaemonRuntime,
|
|
1415
|
+
// Which daemon serves a request (session-daemon/daemon-pool.js). Without
|
|
1416
|
+
// one, the single runtime from `getPiSessionDaemonRuntime` is the main
|
|
1417
|
+
// daemon and owns every directory.
|
|
1418
|
+
daemonPool = createPiDaemonPool({ getMainRuntime: getPiSessionDaemonRuntime }),
|
|
1419
|
+
// Sandboxed projects (sandbox/project-sandbox-manager.js). Without one no
|
|
1420
|
+
// project is sandboxed and no sandbox route exists.
|
|
1421
|
+
sandboxManager,
|
|
1422
|
+
// Folders whose trust must stay "ask" after a sandbox was turned off
|
|
1423
|
+
// (sandbox/trust-ask.js); an explicit trust decision clears one.
|
|
1424
|
+
trustAsk,
|
|
1283
1425
|
archiveStore = createPiArchiveStore(),
|
|
1284
1426
|
attachmentStore = createPiAttachmentStore(),
|
|
1285
1427
|
settingsStore = createPiSettingsStore(),
|
|
@@ -1296,11 +1438,76 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1296
1438
|
smallModelGenerator = async (input) => (await import('./small-model-generation.js')).generateWithSmallModel(input),
|
|
1297
1439
|
eventHeartbeatMs = 15_000,
|
|
1298
1440
|
eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
1441
|
+
eventStreamRetryBaseMs,
|
|
1299
1442
|
// Called with the id after a session is deleted, for PiChamber state kept
|
|
1300
1443
|
// per session elsewhere (plugin switches). Must not throw.
|
|
1301
1444
|
onSessionDeleted = () => {},
|
|
1302
1445
|
}) => {
|
|
1303
1446
|
const eventStreamRegistry = createPiEventStreamRegistry();
|
|
1447
|
+
// Directory-less commands (providers, settings, projects, engines,
|
|
1448
|
+
// provider login, the extension palette) and resource writes always run on
|
|
1449
|
+
// the main daemon: they write Pi's own config and credentials, which a
|
|
1450
|
+
// project daemon may only read. Everything scoped to a directory runs on
|
|
1451
|
+
// the daemon that owns it.
|
|
1452
|
+
const mainDaemon = () => requireDaemon(daemonPool.main());
|
|
1453
|
+
// Sessions run by a sandbox daemon say so, and a session waiting to
|
|
1454
|
+
// switch modes after its turn says where to; other rows are unchanged.
|
|
1455
|
+
const withSandbox = (item) => {
|
|
1456
|
+
if (!sandboxManager || !item?.session) return item;
|
|
1457
|
+
const state = sandboxManager.sessionState(item.session.id, item.session.directory);
|
|
1458
|
+
if (!state.sandboxed && !state.pendingSwitch) return item;
|
|
1459
|
+
return {
|
|
1460
|
+
...item,
|
|
1461
|
+
session: {
|
|
1462
|
+
...item.session,
|
|
1463
|
+
...(state.sandboxed ? { sandboxed: true } : {}),
|
|
1464
|
+
...(state.pendingSwitch ? { pendingSwitch: state.pendingSwitch } : {}),
|
|
1465
|
+
},
|
|
1466
|
+
};
|
|
1467
|
+
};
|
|
1468
|
+
// PiChamber changed Pi's config files: running sandbox daemons are
|
|
1469
|
+
// replaced at their next idle edge. Never fails the write.
|
|
1470
|
+
const piConfigChanged = () => {
|
|
1471
|
+
sandboxManager?.configChanged().catch((error) => console.warn('[pi-sandbox] config change handling failed', error?.code ?? error));
|
|
1472
|
+
};
|
|
1473
|
+
// The pool owns sandboxed projects only after a reconcile has read the
|
|
1474
|
+
// settings. While the last one failed (unreadable settings at start, or a
|
|
1475
|
+
// failed apply after a save), try again before anything can route; if it
|
|
1476
|
+
// still fails, every Pi route is refused rather than run on the main
|
|
1477
|
+
// daemon. Settings and sandbox routes stay open so the cause can be fixed,
|
|
1478
|
+
// and so does the event stream, which starts nothing.
|
|
1479
|
+
if (sandboxManager) {
|
|
1480
|
+
const OPEN_WHILE_UNKNOWN = /^\/(?:ui-settings|sandbox(?:\/|$)|events(?:\/|$))/;
|
|
1481
|
+
app.use('/api/pi', async (req, res, next) => {
|
|
1482
|
+
if (!sandboxManager.needsReconcile()) return next();
|
|
1483
|
+
try {
|
|
1484
|
+
await sandboxManager.reconcile();
|
|
1485
|
+
return next();
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
if (OPEN_WHILE_UNKNOWN.test(req.path)) return next();
|
|
1488
|
+
console.warn('[pi-sandbox] sandbox settings are unreadable; refusing Pi requests', error?.code ?? '');
|
|
1489
|
+
return res.status(503).json({ error: { code: 'SANDBOX_UNAVAILABLE', reason: 'SANDBOX_SETTINGS_UNREADABLE' } });
|
|
1490
|
+
}
|
|
1491
|
+
});
|
|
1492
|
+
registerPiSandboxRoutes(app, { sandboxManager });
|
|
1493
|
+
}
|
|
1494
|
+
const daemonFor = (directory) => requireDaemon(daemonPool.forDirectory(directory));
|
|
1495
|
+
// The daemon for a folder a client named. While a project is sandboxed
|
|
1496
|
+
// the folder is first spelled the way the daemon reads it, so a padded or
|
|
1497
|
+
// symlinked path to a sandboxed project cannot reach the main daemon.
|
|
1498
|
+
const routeDirectoryFor = async (directory) => (sandboxManager ? sandboxManager.routeDirectory(directory) : directory);
|
|
1499
|
+
const daemonForClientDirectory = async (directory) => daemonFor(await routeDirectoryFor(directory));
|
|
1500
|
+
// A stamped response (`streamEpoch`, sequences) from a project daemon says
|
|
1501
|
+
// which daemon stream its sequences belong to; main responses are
|
|
1502
|
+
// unchanged.
|
|
1503
|
+
// A response served by a daemon draining the session (see
|
|
1504
|
+
// `drainingSessionRuntime`) names that daemon instead of the owner.
|
|
1505
|
+
const withStream = (body, directory, res) => {
|
|
1506
|
+
const draining = res?.locals?.piDrainingStream;
|
|
1507
|
+
const served = res?.locals?.piServedStream;
|
|
1508
|
+
const stream = draining ? draining.stream : served ? served.stream : daemonPool.streamFor(directory);
|
|
1509
|
+
return stream ? { ...body, stream } : body;
|
|
1510
|
+
};
|
|
1304
1511
|
// Tell every device an archive mark changed (a `session.archive` event on
|
|
1305
1512
|
// the session's stream) so other clients re-list that folder. The change is
|
|
1306
1513
|
// already saved, so this never delays or fails the request: an older
|
|
@@ -1309,7 +1516,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1309
1516
|
const publishArchiveChange = (sessionId, archived, directory) => {
|
|
1310
1517
|
void (async () => {
|
|
1311
1518
|
try {
|
|
1312
|
-
await
|
|
1519
|
+
await daemonFor(directory).request('archive.publish', {
|
|
1313
1520
|
sessionId,
|
|
1314
1521
|
archived,
|
|
1315
1522
|
...(typeof directory === 'string' && directory.length > 0 ? { directory } : {}),
|
|
@@ -1347,7 +1554,10 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1347
1554
|
|
|
1348
1555
|
app.put('/api/pi/ui-settings', async (req, res) => {
|
|
1349
1556
|
try {
|
|
1350
|
-
|
|
1557
|
+
const saved = await uiSettingsStore.write(req.body);
|
|
1558
|
+
// A removed sandboxed project releases its daemon.
|
|
1559
|
+
await sandboxManager?.reconcile().catch((error) => console.warn('[pi-sandbox] reconcile failed', error?.code ?? error));
|
|
1560
|
+
res.json(saved);
|
|
1351
1561
|
} catch {
|
|
1352
1562
|
res.status(400).json({ error: 'Invalid UI settings' });
|
|
1353
1563
|
}
|
|
@@ -1476,7 +1686,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1476
1686
|
});
|
|
1477
1687
|
|
|
1478
1688
|
app.get('/api/pi/runtime', async (_req, res) => {
|
|
1479
|
-
const runtime =
|
|
1689
|
+
const runtime = daemonPool.main();
|
|
1480
1690
|
if (!runtime) {
|
|
1481
1691
|
res.status(503).json({
|
|
1482
1692
|
protocolVersion: 1,
|
|
@@ -1509,7 +1719,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1509
1719
|
|
|
1510
1720
|
app.get('/api/pi/projects', async (_req, res) => {
|
|
1511
1721
|
try {
|
|
1512
|
-
const result = await
|
|
1722
|
+
const result = await mainDaemon().request('projects.list');
|
|
1513
1723
|
if (!Array.isArray(result?.projects) || result.projects.some((project) => !project || typeof project.directory !== 'string' || typeof project.selected !== 'boolean')) throw protocolMismatch();
|
|
1514
1724
|
res.json({ projects: result.projects.map((project) => ({ directory: project.directory, selected: project.selected })) });
|
|
1515
1725
|
} catch (error) {
|
|
@@ -1524,7 +1734,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1524
1734
|
return;
|
|
1525
1735
|
}
|
|
1526
1736
|
try {
|
|
1527
|
-
const result = await
|
|
1737
|
+
const result = await mainDaemon().request('projects.select', { directory });
|
|
1528
1738
|
if (typeof result?.directory !== 'string') throw protocolMismatch();
|
|
1529
1739
|
res.json({ directory: result.directory });
|
|
1530
1740
|
} catch (error) {
|
|
@@ -1534,7 +1744,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1534
1744
|
|
|
1535
1745
|
app.get('/api/pi/providers', async (_req, res) => {
|
|
1536
1746
|
try {
|
|
1537
|
-
const result = await
|
|
1747
|
+
const result = await mainDaemon().request('providers.list');
|
|
1538
1748
|
res.json(projectProviders(result));
|
|
1539
1749
|
} catch (error) {
|
|
1540
1750
|
writeDaemonError(res, error);
|
|
@@ -1543,7 +1753,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1543
1753
|
|
|
1544
1754
|
app.get('/api/pi/engines', async (_req, res) => {
|
|
1545
1755
|
try {
|
|
1546
|
-
const result = await
|
|
1756
|
+
const result = await mainDaemon().request('engines.list');
|
|
1547
1757
|
res.json(projectEngines(result));
|
|
1548
1758
|
} catch (error) {
|
|
1549
1759
|
writeDaemonError(res, error);
|
|
@@ -1553,7 +1763,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1553
1763
|
app.post('/api/pi/providers/refresh', async (req, res) => {
|
|
1554
1764
|
const directory = typeof req.body?.directory === 'string' && req.body.directory.length > 0 ? req.body.directory : undefined;
|
|
1555
1765
|
try {
|
|
1556
|
-
const result = await
|
|
1766
|
+
const result = await mainDaemon().request('providers.refresh', directory ? { directory } : undefined);
|
|
1557
1767
|
res.json(projectProviders(result));
|
|
1558
1768
|
} catch (error) {
|
|
1559
1769
|
writeDaemonError(res, error);
|
|
@@ -1567,7 +1777,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1567
1777
|
return;
|
|
1568
1778
|
}
|
|
1569
1779
|
try {
|
|
1570
|
-
const result = await
|
|
1780
|
+
const result = await mainDaemon().request('providers.config.get', { providerId });
|
|
1571
1781
|
res.json(projectProviderConfig(result));
|
|
1572
1782
|
} catch (error) {
|
|
1573
1783
|
writeDaemonError(res, error);
|
|
@@ -1582,7 +1792,8 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1582
1792
|
return;
|
|
1583
1793
|
}
|
|
1584
1794
|
try {
|
|
1585
|
-
const result = await
|
|
1795
|
+
const result = await mainDaemon().request('providers.models.set', { ...payload, providerId });
|
|
1796
|
+
piConfigChanged();
|
|
1586
1797
|
res.json(projectProviderConfig(result));
|
|
1587
1798
|
} catch (error) {
|
|
1588
1799
|
writeDaemonError(res, error);
|
|
@@ -1609,7 +1820,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1609
1820
|
return;
|
|
1610
1821
|
}
|
|
1611
1822
|
try {
|
|
1612
|
-
const result = await
|
|
1823
|
+
const result = await mainDaemon().request('providers.models.add', {
|
|
1613
1824
|
providerId,
|
|
1614
1825
|
model: {
|
|
1615
1826
|
id,
|
|
@@ -1621,6 +1832,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1621
1832
|
...(maxTokens !== undefined ? { maxTokens } : {}),
|
|
1622
1833
|
},
|
|
1623
1834
|
});
|
|
1835
|
+
piConfigChanged();
|
|
1624
1836
|
res.status(201).json(projectProviderConfig(result));
|
|
1625
1837
|
} catch (error) {
|
|
1626
1838
|
writeDaemonError(res, error);
|
|
@@ -1634,7 +1846,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1634
1846
|
return;
|
|
1635
1847
|
}
|
|
1636
1848
|
try {
|
|
1637
|
-
const result = await
|
|
1849
|
+
const result = await mainDaemon().request('providers.status', { providerId });
|
|
1638
1850
|
res.json(projectProviderStatus(result));
|
|
1639
1851
|
} catch (error) {
|
|
1640
1852
|
writeDaemonError(res, error);
|
|
@@ -1651,10 +1863,12 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1651
1863
|
return;
|
|
1652
1864
|
}
|
|
1653
1865
|
try {
|
|
1654
|
-
const result = await
|
|
1866
|
+
const result = await mainDaemon().request('providers.login', {
|
|
1655
1867
|
providerId, type, ...(typeof apiKey === 'string' ? { apiKey } : {}),
|
|
1656
1868
|
});
|
|
1657
|
-
|
|
1869
|
+
const login = projectProviderLogin(result);
|
|
1870
|
+
if (login.state === 'complete') piConfigChanged();
|
|
1871
|
+
res.status(202).json(login);
|
|
1658
1872
|
} catch (error) {
|
|
1659
1873
|
writeDaemonError(res, error);
|
|
1660
1874
|
}
|
|
@@ -1668,8 +1882,10 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1668
1882
|
return;
|
|
1669
1883
|
}
|
|
1670
1884
|
try {
|
|
1671
|
-
const result = await
|
|
1672
|
-
|
|
1885
|
+
const result = await mainDaemon().request('providers.login.status', { providerId, loginId });
|
|
1886
|
+
const login = projectProviderLogin(result);
|
|
1887
|
+
if (login.state === 'complete') piConfigChanged();
|
|
1888
|
+
res.json(login);
|
|
1673
1889
|
} catch (error) {
|
|
1674
1890
|
writeDaemonError(res, error);
|
|
1675
1891
|
}
|
|
@@ -1684,8 +1900,10 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1684
1900
|
return;
|
|
1685
1901
|
}
|
|
1686
1902
|
try {
|
|
1687
|
-
const result = await
|
|
1688
|
-
|
|
1903
|
+
const result = await mainDaemon().request('providers.login.respond', { providerId, loginId, value });
|
|
1904
|
+
const login = projectProviderLogin(result);
|
|
1905
|
+
if (login.state === 'complete') piConfigChanged();
|
|
1906
|
+
res.json(login);
|
|
1689
1907
|
} catch (error) {
|
|
1690
1908
|
writeDaemonError(res, error);
|
|
1691
1909
|
}
|
|
@@ -1698,7 +1916,8 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1698
1916
|
return;
|
|
1699
1917
|
}
|
|
1700
1918
|
try {
|
|
1701
|
-
const result = await
|
|
1919
|
+
const result = await mainDaemon().request('providers.logout', { providerId });
|
|
1920
|
+
piConfigChanged();
|
|
1702
1921
|
res.json(projectProviderStatus(result));
|
|
1703
1922
|
} catch (error) {
|
|
1704
1923
|
writeDaemonError(res, error);
|
|
@@ -1737,7 +1956,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1737
1956
|
|
|
1738
1957
|
app.get('/api/pi/settings', async (_req, res) => {
|
|
1739
1958
|
try {
|
|
1740
|
-
const pi = projectPiSettings(await
|
|
1959
|
+
const pi = projectPiSettings(await mainDaemon().request('settings.get'));
|
|
1741
1960
|
const pichamber = await settingsStore.read();
|
|
1742
1961
|
res.json({ ...pi, pichamber });
|
|
1743
1962
|
} catch (error) {
|
|
@@ -1748,7 +1967,11 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1748
1967
|
app.put('/api/pi/settings/pi', async (req, res) => {
|
|
1749
1968
|
const payload = req.body;
|
|
1750
1969
|
try {
|
|
1751
|
-
const result = await
|
|
1970
|
+
const result = await mainDaemon().request('settings.set', payload);
|
|
1971
|
+
if (typeof payload?.trust === 'boolean' && typeof payload.directory === 'string') {
|
|
1972
|
+
await trustAsk?.remove(payload.directory).catch((error) => console.warn('[pi-sandbox] could not clear a trust reset', error?.code ?? error));
|
|
1973
|
+
}
|
|
1974
|
+
piConfigChanged();
|
|
1752
1975
|
res.json(projectPiSettings(result));
|
|
1753
1976
|
} catch (error) {
|
|
1754
1977
|
writeDaemonError(res, error);
|
|
@@ -1769,7 +1992,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1769
1992
|
? req.query.directory
|
|
1770
1993
|
: undefined;
|
|
1771
1994
|
try {
|
|
1772
|
-
res.json(projectResources(await
|
|
1995
|
+
res.json(projectResources(await (await daemonForClientDirectory(directory)).request(
|
|
1773
1996
|
'resources.list',
|
|
1774
1997
|
directory ? { directory } : undefined,
|
|
1775
1998
|
)));
|
|
@@ -1783,7 +2006,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1783
2006
|
? req.query.directory
|
|
1784
2007
|
: undefined;
|
|
1785
2008
|
try {
|
|
1786
|
-
const runtime =
|
|
2009
|
+
const runtime = await daemonForClientDirectory(directory);
|
|
1787
2010
|
const [resources, extensionList] = await Promise.all([
|
|
1788
2011
|
runtime.request('resources.list', { ...(directory ? { directory } : {}) }),
|
|
1789
2012
|
runtime.request('extensions.list', { ...(directory ? { directory } : {}) }),
|
|
@@ -1966,6 +2189,14 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1966
2189
|
return queryDirectory ?? bodyDirectory;
|
|
1967
2190
|
};
|
|
1968
2191
|
|
|
2192
|
+
// A project's own prompts and instruction files are changed by the daemon
|
|
2193
|
+
// that runs the project: for a sandboxed project that is its sandbox
|
|
2194
|
+
// daemon, since the main daemon never loads that project. Resources in
|
|
2195
|
+
// Pi's agent folder stay with the main daemon; a sandbox cannot write them.
|
|
2196
|
+
const resourceDaemon = async (directory, location) => (directory && location !== 'global'
|
|
2197
|
+
? daemonForClientDirectory(directory)
|
|
2198
|
+
: mainDaemon());
|
|
2199
|
+
|
|
1969
2200
|
app.put('/api/pi/resources/:resourceId', async (req, res) => {
|
|
1970
2201
|
const resourceId = req.params.resourceId;
|
|
1971
2202
|
const content = req.body?.content;
|
|
@@ -1975,7 +2206,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1975
2206
|
}
|
|
1976
2207
|
const directory = resourceDirectoryFrom(req);
|
|
1977
2208
|
try {
|
|
1978
|
-
res.json(projectResources(await
|
|
2209
|
+
res.json(projectResources(await (await resourceDaemon(directory)).request('resources.update', { resourceId, content, ...(directory ? { directory } : {}) })));
|
|
1979
2210
|
} catch (error) {
|
|
1980
2211
|
writeDaemonError(res, error);
|
|
1981
2212
|
}
|
|
@@ -1993,7 +2224,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1993
2224
|
}
|
|
1994
2225
|
const directory = resourceDirectoryFrom(req);
|
|
1995
2226
|
try {
|
|
1996
|
-
res.status(201).json(projectResources(await
|
|
2227
|
+
res.status(201).json(projectResources(await (await resourceDaemon(directory, location)).request('resources.prompts.create', { name, description, content, location, ...(directory ? { directory } : {}) })));
|
|
1997
2228
|
} catch (error) {
|
|
1998
2229
|
writeDaemonError(res, error);
|
|
1999
2230
|
}
|
|
@@ -2023,7 +2254,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2023
2254
|
}
|
|
2024
2255
|
const directory = resourceDirectoryFrom(req);
|
|
2025
2256
|
try {
|
|
2026
|
-
res.json(projectResources(await
|
|
2257
|
+
res.json(projectResources(await (await resourceDaemon(directory)).request('resources.prompts.update', {
|
|
2027
2258
|
resourceId,
|
|
2028
2259
|
...(directory ? { directory } : {}),
|
|
2029
2260
|
...(name !== undefined ? { name } : {}),
|
|
@@ -2044,7 +2275,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2044
2275
|
}
|
|
2045
2276
|
const directory = resourceDirectoryFrom(req);
|
|
2046
2277
|
try {
|
|
2047
|
-
res.json(projectResources(await
|
|
2278
|
+
res.json(projectResources(await (await resourceDaemon(directory)).request('resources.prompts.delete', { resourceId, ...(directory ? { directory } : {}) })));
|
|
2048
2279
|
} catch (error) {
|
|
2049
2280
|
writeDaemonError(res, error);
|
|
2050
2281
|
}
|
|
@@ -2084,8 +2315,20 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2084
2315
|
res.status(400).json({ error: { code: 'DAEMON_PROTOCOL_MISMATCH' } });
|
|
2085
2316
|
return;
|
|
2086
2317
|
}
|
|
2318
|
+
// Opaque resume position of every project daemon (merged-event-stream.js).
|
|
2319
|
+
// Only epoch-aware clients receive one, so it requires the same marker.
|
|
2320
|
+
const rawEventCursor = req.query.cursor;
|
|
2321
|
+
const eventCursor = rawEventCursor === undefined ? undefined : decodePiEventCursor(rawEventCursor);
|
|
2322
|
+
if (eventCursor === null) {
|
|
2323
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
if (eventCursor !== undefined && !hasEpochCapability) {
|
|
2327
|
+
res.status(400).json({ error: { code: 'DAEMON_PROTOCOL_MISMATCH' } });
|
|
2328
|
+
return;
|
|
2329
|
+
}
|
|
2087
2330
|
try {
|
|
2088
|
-
const runtime =
|
|
2331
|
+
const runtime = mainDaemon();
|
|
2089
2332
|
if (typeof runtime.subscribe !== 'function') throw protocolMismatch();
|
|
2090
2333
|
res.status(200).set({
|
|
2091
2334
|
'Content-Type': 'text/event-stream',
|
|
@@ -2100,8 +2343,21 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2100
2343
|
openPiEventStream({
|
|
2101
2344
|
req,
|
|
2102
2345
|
res,
|
|
2103
|
-
|
|
2104
|
-
|
|
2346
|
+
// Every live daemon's stream, merged. Frames arrive projected.
|
|
2347
|
+
subscribe: (handlers) => subscribeMergedPiEvents({
|
|
2348
|
+
pool: daemonPool,
|
|
2349
|
+
projectFrame: projectEventFrame,
|
|
2350
|
+
sessionId,
|
|
2351
|
+
directory,
|
|
2352
|
+
fromSequence,
|
|
2353
|
+
streamEpoch,
|
|
2354
|
+
cursor: eventCursor,
|
|
2355
|
+
...(eventStreamRetryBaseMs !== undefined ? { retryBaseMs: eventStreamRetryBaseMs } : {}),
|
|
2356
|
+
// A sandbox daemon only reports on its own project's sessions.
|
|
2357
|
+
...(sandboxManager?.sessionOnDaemon ? { ownsSession: sandboxManager.sessionOnDaemon } : {}),
|
|
2358
|
+
...handlers,
|
|
2359
|
+
}),
|
|
2360
|
+
projectFrame: (event) => event,
|
|
2105
2361
|
heartbeatMs: eventHeartbeatMs,
|
|
2106
2362
|
maxBufferedBytes: eventStreamMaxBufferedBytes,
|
|
2107
2363
|
registry: eventStreamRegistry,
|
|
@@ -2124,20 +2380,42 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2124
2380
|
}
|
|
2125
2381
|
|
|
2126
2382
|
try {
|
|
2127
|
-
const
|
|
2128
|
-
|
|
2129
|
-
|
|
2383
|
+
const payload = typeof directory === 'string' ? { directory } : {};
|
|
2384
|
+
// The owner's rows are the list (JSONL is the authority). Other
|
|
2385
|
+
// daemons only fill in `live`/`inputState` the owner lacks: daemons
|
|
2386
|
+
// still draining this folder after a switch, or, for the all-sessions
|
|
2387
|
+
// list, every project daemon (the main daemon lists every folder but
|
|
2388
|
+
// only knows its own residents). A failed other daemon leaves those
|
|
2389
|
+
// rows unknown.
|
|
2390
|
+
// Stamped with the stream of the daemon asked, under the folder's
|
|
2391
|
+
// routed spelling, taken before the request.
|
|
2392
|
+
const listDirectory = await routeDirectoryFor(directory);
|
|
2393
|
+
const others = typeof directory === 'string'
|
|
2394
|
+
? daemonPool.drainingFor(listDirectory)
|
|
2395
|
+
: daemonPool.live().filter((item) => item.key !== MAIN_DAEMON_KEY);
|
|
2396
|
+
const owner = daemonFor(listDirectory);
|
|
2397
|
+
res.locals.piServedStream = { stream: daemonPool.streamFor(listDirectory) };
|
|
2398
|
+
const [result, ...otherLists] = await Promise.all([
|
|
2399
|
+
owner.request('sessions.list', payload),
|
|
2400
|
+
...others.map(({ key, runtime }) => runtime.request('sessions.list', payload)
|
|
2401
|
+
.then((value) => ({
|
|
2402
|
+
stream: publicDaemonStreamId(key),
|
|
2403
|
+
...(isValidStreamEpoch(value?.streamEpoch) ? { streamEpoch: value.streamEpoch } : {}),
|
|
2404
|
+
items: projectSessionList(value?.sessions),
|
|
2405
|
+
}))
|
|
2406
|
+
.catch(() => ({ stream: publicDaemonStreamId(key), items: [] }))),
|
|
2407
|
+
]);
|
|
2130
2408
|
const archived = await archiveStore.read();
|
|
2131
2409
|
const incompleteEngines = Array.isArray(result?.incompleteEngines)
|
|
2132
2410
|
? result.incompleteEngines.filter((engineId) => isValidEngineId(engineId))
|
|
2133
2411
|
: [];
|
|
2134
|
-
res.json({
|
|
2412
|
+
res.json(withStream({
|
|
2135
2413
|
...(typeof result?.streamEpoch === 'string' && result.streamEpoch ? { streamEpoch: result.streamEpoch } : {}),
|
|
2136
2414
|
...(incompleteEngines.length > 0 ? { incompleteEngines } : {}),
|
|
2137
|
-
sessions: projectSessionList(result?.sessions).map((item) => archived[item.session.id]
|
|
2415
|
+
sessions: mergeOtherDaemonsLiveState(projectSessionList(result?.sessions), otherLists).map(withSandbox).map((item) => archived[item.session.id]
|
|
2138
2416
|
? { ...item, session: { ...item.session, archived: true, timeArchived: archived[item.session.id] } }
|
|
2139
2417
|
: item),
|
|
2140
|
-
});
|
|
2418
|
+
}, listDirectory, res));
|
|
2141
2419
|
} catch (error) {
|
|
2142
2420
|
writeDaemonError(res, error);
|
|
2143
2421
|
}
|
|
@@ -2147,8 +2425,43 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2147
2425
|
// is not captured as a session id.
|
|
2148
2426
|
app.get('/api/pi/sessions/pending-input', async (_req, res) => {
|
|
2149
2427
|
try {
|
|
2150
|
-
|
|
2151
|
-
|
|
2428
|
+
// Fan out to every live daemon. One failed (or malformed) daemon
|
|
2429
|
+
// must not empty the others' lists; the response then says
|
|
2430
|
+
// `incomplete` so clients do not treat its absent rows as cleared.
|
|
2431
|
+
// Each daemon numbers its own stream: the top-level cursor is the
|
|
2432
|
+
// main daemon's (absent when it failed), and a project daemon's
|
|
2433
|
+
// entries carry `stream`, with its cursor under `streams[stream]`.
|
|
2434
|
+
const daemons = daemonPool.live();
|
|
2435
|
+
if (daemons.length === 0) requireDaemon(null);
|
|
2436
|
+
const settled = await Promise.allSettled(daemons.map(async ({ runtime }) => (
|
|
2437
|
+
projectPendingInputList(await runtime.request('sessions.pendingInput'))
|
|
2438
|
+
)));
|
|
2439
|
+
if (!settled.some((item) => item.status === 'fulfilled')) throw settled[0].reason;
|
|
2440
|
+
let mainList = null;
|
|
2441
|
+
const sessions = [];
|
|
2442
|
+
const streams = {};
|
|
2443
|
+
settled.forEach((item, index) => {
|
|
2444
|
+
if (item.status !== 'fulfilled') return;
|
|
2445
|
+
const { key } = daemons[index];
|
|
2446
|
+
if (key === MAIN_DAEMON_KEY) {
|
|
2447
|
+
mainList = item.value;
|
|
2448
|
+
sessions.push(...item.value.sessions);
|
|
2449
|
+
return;
|
|
2450
|
+
}
|
|
2451
|
+
const stream = publicDaemonStreamId(key);
|
|
2452
|
+
streams[stream] = {
|
|
2453
|
+
sequence: item.value.sequence,
|
|
2454
|
+
...(item.value.streamEpoch ? { streamEpoch: item.value.streamEpoch } : {}),
|
|
2455
|
+
};
|
|
2456
|
+
for (const entry of item.value.sessions) sessions.push({ ...entry, stream });
|
|
2457
|
+
});
|
|
2458
|
+
res.json({
|
|
2459
|
+
sessions,
|
|
2460
|
+
...(mainList ? { sequence: mainList.sequence } : {}),
|
|
2461
|
+
...(mainList?.streamEpoch ? { streamEpoch: mainList.streamEpoch } : {}),
|
|
2462
|
+
...(Object.keys(streams).length > 0 ? { streams } : {}),
|
|
2463
|
+
...(settled.some((item) => item.status !== 'fulfilled') ? { incomplete: true } : {}),
|
|
2464
|
+
});
|
|
2152
2465
|
} catch (error) {
|
|
2153
2466
|
writeDaemonError(res, error);
|
|
2154
2467
|
}
|
|
@@ -2166,7 +2479,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2166
2479
|
}
|
|
2167
2480
|
|
|
2168
2481
|
try {
|
|
2169
|
-
await
|
|
2482
|
+
await daemonFor(await sessionDaemonDirectory(res, sandboxManager, sessionId, directory)).request('sessions.rename', {
|
|
2170
2483
|
sessionId,
|
|
2171
2484
|
title,
|
|
2172
2485
|
...(directory ? { directory } : {}),
|
|
@@ -2178,14 +2491,14 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2178
2491
|
});
|
|
2179
2492
|
|
|
2180
2493
|
const sendSessionDetail = async (req, res) => {
|
|
2181
|
-
const result = await requestSessionOperation(req, res,
|
|
2494
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.open', {}, sandboxManager);
|
|
2182
2495
|
if (result === undefined) return;
|
|
2183
2496
|
try {
|
|
2184
|
-
const detail = projectSessionDetail(result);
|
|
2497
|
+
const detail = withSandbox(projectSessionDetail(result));
|
|
2185
2498
|
const archived = await archiveStore.read();
|
|
2186
|
-
res.json(archived[detail.session.id]
|
|
2499
|
+
res.json(withStream(archived[detail.session.id]
|
|
2187
2500
|
? { ...detail, session: { ...detail.session, archived: true, timeArchived: archived[detail.session.id] } }
|
|
2188
|
-
: detail);
|
|
2501
|
+
: detail, sessionRouteDirectory(req, res), res));
|
|
2189
2502
|
} catch (error) {
|
|
2190
2503
|
writeDaemonError(res, error);
|
|
2191
2504
|
}
|
|
@@ -2203,13 +2516,13 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2203
2516
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2204
2517
|
return;
|
|
2205
2518
|
}
|
|
2206
|
-
const result = await requestSessionOperation(req, res,
|
|
2519
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.messages', {
|
|
2207
2520
|
...(typeof before === 'string' ? { before } : {}),
|
|
2208
2521
|
...(limit !== undefined ? { limit } : {}),
|
|
2209
|
-
});
|
|
2522
|
+
}, sandboxManager);
|
|
2210
2523
|
if (result === undefined) return;
|
|
2211
2524
|
try {
|
|
2212
|
-
res.json(projectSessionDetail(result));
|
|
2525
|
+
res.json(withStream(projectSessionDetail(result), sessionRouteDirectory(req, res), res));
|
|
2213
2526
|
} catch (error) {
|
|
2214
2527
|
writeDaemonError(res, error);
|
|
2215
2528
|
}
|
|
@@ -2218,13 +2531,13 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2218
2531
|
// Stop a draft session's runtime when its draft closes. Only a draft can be
|
|
2219
2532
|
// discarded; any other session answers `{ discarded: false }` untouched.
|
|
2220
2533
|
app.post('/api/pi/sessions/:sessionId/discard-draft', async (req, res) => {
|
|
2221
|
-
const result = await requestSessionOperation(req, res,
|
|
2534
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.discardDraft', {}, sandboxManager);
|
|
2222
2535
|
if (result === undefined) return;
|
|
2223
2536
|
res.json({ discarded: result?.discarded === true });
|
|
2224
2537
|
});
|
|
2225
2538
|
|
|
2226
2539
|
app.delete('/api/pi/sessions/:sessionId', async (req, res) => {
|
|
2227
|
-
const result = await requestSessionOperation(req, res,
|
|
2540
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.delete', {}, sandboxManager);
|
|
2228
2541
|
if (result === undefined) return;
|
|
2229
2542
|
try {
|
|
2230
2543
|
await sessionShelfStore.remove(req.params.sessionId);
|
|
@@ -2266,7 +2579,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2266
2579
|
try {
|
|
2267
2580
|
// Same membership check as archive: shelf state is PiChamber metadata
|
|
2268
2581
|
// for a session that exists, not a Pi session mutation.
|
|
2269
|
-
const result = await
|
|
2582
|
+
const result = await (await daemonForClientDirectory(directory)).request(
|
|
2270
2583
|
'sessions.list',
|
|
2271
2584
|
directory ? { directory } : undefined,
|
|
2272
2585
|
);
|
|
@@ -2301,7 +2614,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2301
2614
|
try {
|
|
2302
2615
|
// Confirm membership without selecting/replacing the daemon's active
|
|
2303
2616
|
// runtime: archive is PiChamber metadata, not a Pi session mutation.
|
|
2304
|
-
const result = await
|
|
2617
|
+
const result = await (await daemonForClientDirectory(directory)).request(
|
|
2305
2618
|
'sessions.list',
|
|
2306
2619
|
directory ? { directory } : undefined,
|
|
2307
2620
|
);
|
|
@@ -2328,7 +2641,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2328
2641
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2329
2642
|
return;
|
|
2330
2643
|
}
|
|
2331
|
-
const result = await requestSessionOperation(req, res,
|
|
2644
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'extensions.draft', { text, revision }, sandboxManager);
|
|
2332
2645
|
if (result !== undefined) {
|
|
2333
2646
|
res.status(204).end();
|
|
2334
2647
|
}
|
|
@@ -2341,7 +2654,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2341
2654
|
return;
|
|
2342
2655
|
}
|
|
2343
2656
|
try {
|
|
2344
|
-
const result = await
|
|
2657
|
+
const result = await (await daemonForClientDirectory(directory)).request('extensions.list', {
|
|
2345
2658
|
...(typeof directory === 'string' && directory.length > 0 ? { directory } : {}),
|
|
2346
2659
|
});
|
|
2347
2660
|
res.json(projectExtensionList(result));
|
|
@@ -2353,6 +2666,11 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2353
2666
|
// Extension config (`pi config`, `pi list`, `pi remove`). Toggles and
|
|
2354
2667
|
// removal change what code runs on this server; the daemon re-resolves
|
|
2355
2668
|
// every id and enforces trust (session-daemon/extension-config.js).
|
|
2669
|
+
// Like resources, a project's own view and choices go to the daemon that
|
|
2670
|
+
// runs the project, so a sandboxed project is read by its sandbox daemon
|
|
2671
|
+
// and the main daemon never resolves it. Global choices and package removal
|
|
2672
|
+
// write Pi's agent folder, which a sandbox cannot write, so they stay with
|
|
2673
|
+
// the main daemon.
|
|
2356
2674
|
const extensionConfigDirectory = (value) => {
|
|
2357
2675
|
if (value === undefined) return { ok: true };
|
|
2358
2676
|
if (typeof value !== 'string' || value.length > 4096) return { ok: false };
|
|
@@ -2366,7 +2684,8 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2366
2684
|
return;
|
|
2367
2685
|
}
|
|
2368
2686
|
try {
|
|
2369
|
-
const
|
|
2687
|
+
const daemon = target.directory ? await daemonForClientDirectory(target.directory) : mainDaemon();
|
|
2688
|
+
const result = await daemon.request('extensions.config.list', {
|
|
2370
2689
|
...(target.directory ? { directory: target.directory } : {}),
|
|
2371
2690
|
});
|
|
2372
2691
|
res.json(projectExtensionConfig(result));
|
|
@@ -2400,7 +2719,56 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2400
2719
|
return;
|
|
2401
2720
|
}
|
|
2402
2721
|
try {
|
|
2403
|
-
|
|
2722
|
+
const daemon = payload.scope === 'project' ? await daemonForClientDirectory(payload.directory) : mainDaemon();
|
|
2723
|
+
res.json(projectExtensionConfig(await daemon.request('extensions.config.set', payload)));
|
|
2724
|
+
} catch (error) {
|
|
2725
|
+
writeDaemonError(res, error);
|
|
2726
|
+
}
|
|
2727
|
+
});
|
|
2728
|
+
|
|
2729
|
+
// `pi install npm:<name>`: a bare npm name only, in user or project scope.
|
|
2730
|
+
app.post('/api/pi/extensions/packages', async (req, res) => {
|
|
2731
|
+
const body = req.body;
|
|
2732
|
+
let payload = null;
|
|
2733
|
+
if (body && typeof body === 'object' && !Array.isArray(body)
|
|
2734
|
+
&& Object.keys(body).every((key) => ['name', 'scope', 'directory'].includes(key))
|
|
2735
|
+
&& isNpmPackageName(body.name) && (body.scope === 'user' || body.scope === 'project')) {
|
|
2736
|
+
const target = extensionConfigDirectory(body.directory);
|
|
2737
|
+
if (target.ok && (body.scope === 'user' || target.directory)) {
|
|
2738
|
+
payload = { name: body.name, scope: body.scope, ...(target.directory ? { directory: target.directory } : {}) };
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
if (!payload) {
|
|
2742
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2743
|
+
return;
|
|
2744
|
+
}
|
|
2745
|
+
try {
|
|
2746
|
+
const result = await mainDaemon()
|
|
2747
|
+
.request('extensions.packages.install', payload, { timeoutMs: PACKAGE_INSTALL_TIMEOUT_MS });
|
|
2748
|
+
res.json({
|
|
2749
|
+
...projectExtensionConfig(result),
|
|
2750
|
+
...(typeof result?.installedId === 'string' && EXTENSION_CONFIG_ID_PATTERN.test(result.installedId)
|
|
2751
|
+
? { installedId: result.installedId }
|
|
2752
|
+
: {}),
|
|
2753
|
+
});
|
|
2754
|
+
} catch (error) {
|
|
2755
|
+
writeDaemonError(res, error);
|
|
2756
|
+
}
|
|
2757
|
+
});
|
|
2758
|
+
|
|
2759
|
+
// `pi update <source>` for one configured npm or git package.
|
|
2760
|
+
app.post('/api/pi/extensions/packages/:id/update', async (req, res) => {
|
|
2761
|
+
const id = req.params.id;
|
|
2762
|
+
const target = extensionConfigDirectory(req.query?.directory);
|
|
2763
|
+
if (typeof id !== 'string' || !EXTENSION_CONFIG_ID_PATTERN.test(id) || !target.ok) {
|
|
2764
|
+
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2765
|
+
return;
|
|
2766
|
+
}
|
|
2767
|
+
try {
|
|
2768
|
+
res.json(projectExtensionConfig(await mainDaemon().request('extensions.packages.update', {
|
|
2769
|
+
id,
|
|
2770
|
+
...(target.directory ? { directory: target.directory } : {}),
|
|
2771
|
+
}, { timeoutMs: PACKAGE_INSTALL_TIMEOUT_MS })));
|
|
2404
2772
|
} catch (error) {
|
|
2405
2773
|
writeDaemonError(res, error);
|
|
2406
2774
|
}
|
|
@@ -2414,7 +2782,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2414
2782
|
return;
|
|
2415
2783
|
}
|
|
2416
2784
|
try {
|
|
2417
|
-
res.json(projectExtensionConfig(await
|
|
2785
|
+
res.json(projectExtensionConfig(await mainDaemon().request('extensions.packages.remove', {
|
|
2418
2786
|
id,
|
|
2419
2787
|
...(target.directory ? { directory: target.directory } : {}),
|
|
2420
2788
|
})));
|
|
@@ -2432,7 +2800,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2432
2800
|
return;
|
|
2433
2801
|
}
|
|
2434
2802
|
try {
|
|
2435
|
-
const result = await
|
|
2803
|
+
const result = await mainDaemon().request('extensions.palette', { terminal });
|
|
2436
2804
|
const palette = projectExtensionPalette(result);
|
|
2437
2805
|
if (!palette) {
|
|
2438
2806
|
res.status(502).json({ error: { code: 'MALFORMED_DAEMON_RESPONSE' } });
|
|
@@ -2471,7 +2839,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2471
2839
|
}
|
|
2472
2840
|
}
|
|
2473
2841
|
try {
|
|
2474
|
-
const
|
|
2842
|
+
const respondPayload = {
|
|
2475
2843
|
requestId: body.requestId,
|
|
2476
2844
|
...(typeof body.directory === 'string' && body.directory.length > 0 ? { directory: body.directory } : {}),
|
|
2477
2845
|
...(body.cancelled === true ? { cancelled: true } : {}),
|
|
@@ -2479,7 +2847,20 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2479
2847
|
...(typeof body.value === 'string' ? { value: body.value } : {}),
|
|
2480
2848
|
...(typeof body.note === 'string' ? { note: body.note } : {}),
|
|
2481
2849
|
...(values ? { values } : {}),
|
|
2482
|
-
}
|
|
2850
|
+
};
|
|
2851
|
+
// A dialog from a session still finishing its turn in a daemon that
|
|
2852
|
+
// drains this folder is answered there, and those daemons are asked
|
|
2853
|
+
// first: the folder's new owner may be a sandbox that is not running
|
|
2854
|
+
// (or cannot start), and it holds no dialog of that session. Request
|
|
2855
|
+
// ids are unique, so asking each in turn cannot answer the wrong
|
|
2856
|
+
// dialog.
|
|
2857
|
+
const respondDirectory = await routeDirectoryFor(body.directory);
|
|
2858
|
+
let result = null;
|
|
2859
|
+
for (const { runtime } of typeof respondDirectory === 'string' ? daemonPool.drainingFor(respondDirectory) : []) {
|
|
2860
|
+
result = await runtime.request('extensions.respond', respondPayload).catch(() => null);
|
|
2861
|
+
if (result?.resolved === true) break;
|
|
2862
|
+
}
|
|
2863
|
+
if (result?.resolved !== true) result = await daemonFor(respondDirectory).request('extensions.respond', respondPayload);
|
|
2483
2864
|
if (!result || typeof result !== 'object' || result.resolved !== true) {
|
|
2484
2865
|
res.status(404).json({ error: { code: 'EXTENSION_DIALOG_NOT_PENDING' } });
|
|
2485
2866
|
return;
|
|
@@ -2499,12 +2880,20 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2499
2880
|
|| typeof body.sessionId !== 'string' || body.sessionId.length === 0 || body.sessionId.length > 256
|
|
2500
2881
|
|| typeof body.id !== 'string' || body.id.length === 0 || body.id.length > 64
|
|
2501
2882
|
|| (body.value !== undefined && typeof body.value !== 'boolean' && (typeof body.value !== 'string' || body.value.length > 64))
|
|
2502
|
-
|| (body.clientId !== undefined && (typeof body.clientId !== 'string' || body.clientId.length > 128))
|
|
2883
|
+
|| (body.clientId !== undefined && (typeof body.clientId !== 'string' || body.clientId.length > 128))
|
|
2884
|
+
|| (body.directory !== undefined && (typeof body.directory !== 'string' || body.directory.length > 4096))) {
|
|
2503
2885
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2504
2886
|
return;
|
|
2505
2887
|
}
|
|
2506
2888
|
try {
|
|
2507
|
-
|
|
2889
|
+
// Routed like any session operation: by the transcript's folder, or
|
|
2890
|
+
// for a draft (nothing on disk yet) by the folder the client names.
|
|
2891
|
+
// A control runs a command, so a session waiting to switch daemons
|
|
2892
|
+
// refuses it until it has moved.
|
|
2893
|
+
drainingSessionRuntime(res, sandboxManager, body.sessionId, 'extensions.control');
|
|
2894
|
+
const directory = typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined;
|
|
2895
|
+
const routeDirectory = await sessionDaemonDirectory(res, sandboxManager, body.sessionId, directory);
|
|
2896
|
+
const result = await daemonFor(routeDirectory).request('extensions.control', {
|
|
2508
2897
|
sessionId: body.sessionId,
|
|
2509
2898
|
id: body.id,
|
|
2510
2899
|
...(body.value !== undefined ? { value: body.value } : {}),
|
|
@@ -2555,13 +2944,13 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2555
2944
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2556
2945
|
return;
|
|
2557
2946
|
}
|
|
2558
|
-
const result = await requestSessionOperation(req, res,
|
|
2947
|
+
const result = await requestSessionOperation(req, res, daemonPool, command, {
|
|
2559
2948
|
...(surfaceId ? { surfaceId } : {}),
|
|
2560
2949
|
...(clientId ? { clientId } : {}),
|
|
2561
2950
|
...(viewport ? { viewport } : {}),
|
|
2562
2951
|
...(items ? { items } : {}),
|
|
2563
2952
|
...(body.claim === true ? { claim: true } : {}),
|
|
2564
|
-
});
|
|
2953
|
+
}, sandboxManager);
|
|
2565
2954
|
if (result === undefined) return;
|
|
2566
2955
|
const ok = result && typeof result === 'object'
|
|
2567
2956
|
&& (result.accepted === true || result.closed === true || result.focused === true || result.refreshed === true);
|
|
@@ -2573,23 +2962,23 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2573
2962
|
});
|
|
2574
2963
|
|
|
2575
2964
|
app.get('/api/pi/sessions/:sessionId/tree', async (req, res) => {
|
|
2576
|
-
const result = await requestSessionOperation(req, res,
|
|
2965
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.tree', {}, sandboxManager);
|
|
2577
2966
|
if (result !== undefined) res.json(projectSessionTree(result));
|
|
2578
2967
|
});
|
|
2579
2968
|
|
|
2580
2969
|
app.post('/api/pi/sessions/:sessionId/navigate', async (req, res) => {
|
|
2581
|
-
const result = await requestSessionOperation(req, res,
|
|
2970
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.navigate', { messageId: req.body?.messageId }, sandboxManager);
|
|
2582
2971
|
if (result === undefined) return;
|
|
2583
2972
|
const detail = projectSessionDetail(result);
|
|
2584
2973
|
const navigation = sanitizeNavigation(result.navigation);
|
|
2585
2974
|
if (navigation) detail.navigation = navigation;
|
|
2586
|
-
res.json(detail);
|
|
2975
|
+
res.json(withStream(detail, sessionRouteDirectory(req, res), res));
|
|
2587
2976
|
});
|
|
2588
2977
|
|
|
2589
2978
|
for (const [suffix, command] of [['fork', 'sessions.fork'], ['clone', 'sessions.clone']]) {
|
|
2590
2979
|
app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
|
|
2591
|
-
const result = await requestSessionOperation(req, res,
|
|
2592
|
-
if (result !== undefined) res.status(201).json(projectSessionDetail(result));
|
|
2980
|
+
const result = await requestSessionOperation(req, res, daemonPool, command, req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
|
|
2981
|
+
if (result !== undefined) res.status(201).json(withStream(withSandbox(projectSessionDetail(result)), sessionRouteDirectory(req, res), res));
|
|
2593
2982
|
});
|
|
2594
2983
|
}
|
|
2595
2984
|
|
|
@@ -2620,7 +3009,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2620
3009
|
writeDaemonError(res, error);
|
|
2621
3010
|
return;
|
|
2622
3011
|
}
|
|
2623
|
-
const result = await requestSessionOperation(req, res,
|
|
3012
|
+
const result = await requestSessionOperation(req, res, daemonPool, command, payload, sandboxManager);
|
|
2624
3013
|
if (result !== undefined) {
|
|
2625
3014
|
if (!result || result.accepted !== true || typeof result.messageId !== 'string') {
|
|
2626
3015
|
writeDaemonError(res, protocolMismatch());
|
|
@@ -2659,11 +3048,21 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2659
3048
|
return;
|
|
2660
3049
|
}
|
|
2661
3050
|
try {
|
|
2662
|
-
const
|
|
3051
|
+
const directory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
|
|
3052
|
+
? req.query.directory
|
|
3053
|
+
: (typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined);
|
|
3054
|
+
// A session still finishing its turn in a draining daemon has its
|
|
3055
|
+
// receipts there; one that just moved may still name the old epoch.
|
|
3056
|
+
const runtime = drainingSessionRuntime(res, sandboxManager, sessionId, 'sessions.sendReceipt')
|
|
3057
|
+
?? daemonFor(await sessionDaemonDirectory(res, sandboxManager, sessionId, directory));
|
|
3058
|
+
const receiptEpoch = streamEpoch !== undefined && !res.locals?.piDrainingStream && sandboxManager?.sendEpochFor
|
|
3059
|
+
? await sandboxManager.sendEpochFor(sessionId, streamEpoch, runtime)
|
|
3060
|
+
: streamEpoch;
|
|
3061
|
+
const result = await runtime.request('sessions.sendReceipt', {
|
|
2663
3062
|
kind,
|
|
2664
3063
|
sessionId,
|
|
2665
3064
|
operationId,
|
|
2666
|
-
...(
|
|
3065
|
+
...(receiptEpoch !== undefined ? { streamEpoch: receiptEpoch } : {}),
|
|
2667
3066
|
});
|
|
2668
3067
|
if (!result || typeof result !== 'object' || !['accepted', 'pending', 'expired', 'unknown'].includes(result.status)) {
|
|
2669
3068
|
throw protocolMismatch();
|
|
@@ -2679,7 +3078,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2679
3078
|
|
|
2680
3079
|
for (const [suffix, command] of [['abort', 'sessions.abort'], ['model', 'sessions.setModel'], ['thinking', 'sessions.setThinking']]) {
|
|
2681
3080
|
app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
|
|
2682
|
-
const result = await requestSessionOperation(req, res,
|
|
3081
|
+
const result = await requestSessionOperation(req, res, daemonPool, command, req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
|
|
2683
3082
|
if (result !== undefined) res.status(204).end();
|
|
2684
3083
|
});
|
|
2685
3084
|
}
|
|
@@ -2694,11 +3093,11 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2694
3093
|
return;
|
|
2695
3094
|
}
|
|
2696
3095
|
const clientId = typeof body.clientId === 'string' && body.clientId.length > 0 && body.clientId.length <= 128 ? body.clientId : undefined;
|
|
2697
|
-
const result = await requestSessionOperation(req, res,
|
|
3096
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.bash', {
|
|
2698
3097
|
command: body.command,
|
|
2699
3098
|
...(body.excludeFromContext === true ? { excludeFromContext: true } : {}),
|
|
2700
3099
|
...(clientId ? { clientId } : {}),
|
|
2701
|
-
});
|
|
3100
|
+
}, sandboxManager);
|
|
2702
3101
|
if (result === undefined) return;
|
|
2703
3102
|
if (!result || result.accepted !== true || typeof result.id !== 'string') {
|
|
2704
3103
|
writeDaemonError(res, protocolMismatch());
|
|
@@ -2709,12 +3108,12 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2709
3108
|
});
|
|
2710
3109
|
|
|
2711
3110
|
app.post('/api/pi/sessions/:sessionId/bash/abort', async (req, res) => {
|
|
2712
|
-
const result = await requestSessionOperation(req, res,
|
|
3111
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.abortBash', {}, sandboxManager);
|
|
2713
3112
|
if (result !== undefined) res.status(204).end();
|
|
2714
3113
|
});
|
|
2715
3114
|
|
|
2716
3115
|
app.post('/api/pi/sessions/:sessionId/compact', async (req, res) => {
|
|
2717
|
-
const result = await requestSessionOperation(req, res,
|
|
3116
|
+
const result = await requestSessionOperation(req, res, daemonPool, 'sessions.compact', req.body && typeof req.body === 'object' ? req.body : {}, sandboxManager);
|
|
2718
3117
|
if (result === undefined) return;
|
|
2719
3118
|
if (!result || result.accepted !== true) {
|
|
2720
3119
|
writeDaemonError(res, protocolMismatch());
|
|
@@ -2776,12 +3175,14 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2776
3175
|
}
|
|
2777
3176
|
|
|
2778
3177
|
try {
|
|
2779
|
-
const
|
|
3178
|
+
const routeCwd = await routeDirectoryFor(cwd);
|
|
3179
|
+
res.locals.piServedStream = { stream: daemonPool.streamFor(routeCwd) };
|
|
3180
|
+
const result = await daemonFor(routeCwd).request('sessions.create', { ...input, cwd });
|
|
2780
3181
|
// A fresh session is not necessarily empty: extensions may append
|
|
2781
3182
|
// entries or messages from `session_start`. Project it exactly like a
|
|
2782
3183
|
// session read so those items, the stream epoch, and extension UI state
|
|
2783
3184
|
// reach the client instead of failing creation.
|
|
2784
|
-
res.status(201).json(projectSessionDetail(result));
|
|
3185
|
+
res.status(201).json(withStream(withSandbox(projectSessionDetail(result)), routeCwd, res));
|
|
2785
3186
|
} catch (error) {
|
|
2786
3187
|
writeDaemonError(res, error);
|
|
2787
3188
|
}
|