pi-web-ui 0.114.2 → 0.115.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/CHANGELOG.md +55 -1
- package/bin/pi-web-ui.mjs +69 -7
- package/dist/server/agent-service-daemon.js +440 -32
- package/dist/server/agent-service.js +878 -383
- package/dist/server/canvas/canvas-dispatch.js +13 -1
- package/dist/server/client-state.js +25 -0
- package/dist/server/communicate-tool.js +2 -0
- package/dist/server/context-usage.js +105 -0
- package/dist/server/conversation-communication.js +14 -0
- package/dist/server/conversation-identity.js +27 -0
- package/dist/server/device-center/approval-summary.js +31 -0
- package/dist/server/device-center/bot-catalog.js +21 -7
- package/dist/server/device-center/bot-execution.js +72 -9
- package/dist/server/device-center/bot-presets.js +46 -0
- package/dist/server/device-center/collab-service.js +328 -10
- package/dist/server/device-center/collab-tool.js +738 -12
- package/dist/server/device-center/connector.js +359 -23
- package/dist/server/device-center/desktop-page.js +22 -16
- package/dist/server/device-center/device-integration.js +595 -0
- package/dist/server/device-center/execution-guides.js +32 -0
- package/dist/server/device-center/execution-instructions.js +19 -0
- package/dist/server/device-center/execution-settings.js +100 -0
- package/dist/server/device-center/execution-system-prompt.js +38 -0
- package/dist/server/device-center/execution-workspace.js +20 -0
- package/dist/server/device-center/executor.js +389 -40
- package/dist/server/device-center/file-sync-paths.js +171 -0
- package/dist/server/device-center/file-sync.js +180 -91
- package/dist/server/device-center/group-context-delta.js +37 -0
- package/dist/server/device-center/group-context-message.js +208 -0
- package/dist/server/device-center/group-context.js +109 -0
- package/dist/server/device-center/group-events.js +136 -0
- package/dist/server/device-center/group-plan-guard.js +138 -0
- package/dist/server/device-center/hub-conversations.js +178 -0
- package/dist/server/device-center/hub-deliveries.js +277 -0
- package/dist/server/device-center/hub-integration.js +451 -0
- package/dist/server/device-center/hub.js +1544 -80
- package/dist/server/device-center/human-interaction.js +232 -0
- package/dist/server/device-center/integration-errors.js +25 -0
- package/dist/server/device-center/local-hub.js +18 -0
- package/dist/server/device-center/local.js +356 -40
- package/dist/server/device-center/main.js +11 -1
- package/dist/server/device-center/path-portal.js +11 -3
- package/dist/server/device-center/relay.js +364 -35
- package/dist/server/device-center/report-metadata.js +66 -0
- package/dist/server/device-center/report-upload.js +63 -0
- package/dist/server/device-center/runtime.js +549 -41
- package/dist/server/device-center/store.js +66 -3
- package/dist/server/device-center/task-context-budget.js +161 -0
- package/dist/server/device-center/task-journal.js +385 -0
- package/dist/server/device-center/task-plan.js +33 -0
- package/dist/server/device-center/task-progress.js +141 -0
- package/dist/server/device-center/task-recovery.js +452 -0
- package/dist/server/device-center/task-report-outbox.js +216 -0
- package/dist/server/device-center/task-report.js +384 -0
- package/dist/server/device-center/task-scheduler.js +400 -0
- package/dist/server/device-center/task-state.js +333 -0
- package/dist/server/device-center/transfer-stream.js +1006 -0
- package/dist/server/device-center/transfers.js +815 -8
- package/dist/server/dispatch-domain-handlers.js +21 -3
- package/dist/server/dsh/dsh-agent-service.js +6 -0
- package/dist/server/goal-service.js +10 -5
- package/dist/server/index.js +89 -13
- package/dist/server/message-deletion.js +40 -0
- package/dist/server/message-window.js +9 -0
- package/dist/server/patch-executable-lookup.js +396 -0
- package/dist/server/payload-limits.js +2 -0
- package/dist/server/plugin-llm.js +100 -9
- package/dist/server/plugins.js +1 -0
- package/dist/server/preset-fields.js +24 -0
- package/dist/server/preset-share.js +2 -0
- package/dist/server/prompt-base-store.js +85 -0
- package/dist/server/prompt-composer.js +5 -2
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/protocol.js +2 -2
- package/dist/server/remote-ssh-service.js +22 -9
- package/dist/server/resolve-global-sdk.js +2 -0
- package/dist/server/session-search.js +1 -1
- package/dist/server/settings-service.js +90 -39
- package/dist/server/skill-content-filler.js +29 -8
- package/dist/server/skill-tool.js +12 -3
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagents.js +50 -36
- package/dist/server/tool-host-factories.js +1 -0
- package/dist/server/universal/universal-session.js +5 -0
- package/dist/server/webui-context.js +25 -5
- package/docs/README.md +94 -0
- package/docs/device-center.md +100 -12
- package/docs/dsh-engine.md +10 -10
- package/extensions/webui.ts +43 -1
- package/package.json +1 -1
- package/themes/aetheris.css +5 -0
- package/themes/ayu-light.css +6 -0
- package/themes/bases/flow-base.css +68 -68
- package/themes/catppuccin-latte.css +6 -0
- package/themes/catppuccin.css +6 -0
- package/themes/claude-code-dark.css +5 -0
- package/themes/codex.css +6 -0
- package/themes/cyberpunk.css +6 -0
- package/themes/dark-teal.css +6 -1
- package/themes/dazzle.css +6 -0
- package/themes/everforest-light.css +6 -0
- package/themes/flow-light.css +8 -1
- package/themes/flow.css +6 -1
- package/themes/geist.css +6 -0
- package/themes/gruvbox-light.css +6 -0
- package/themes/kanagawa-lotus.css +6 -0
- package/themes/md-preview.css +6 -0
- package/themes/mist.css +6 -0
- package/themes/nord.css +6 -0
- package/themes/one-dark.css +6 -0
- package/themes/paper.css +6 -0
- package/themes/rose-pine-dawn.css +6 -0
- package/themes/sakura.css +6 -0
- package/themes/solarized-light.css +6 -0
- package/themes/tokyo-night.css +6 -0
- package/themes/translucent.css +6 -0
- package/themes/transparent.css +6 -0
- package/themes/vs-code-dark.css +5 -0
- package/themes/wallpaper-flow.css +5 -1
- package/themes/wallpaper-obsidian.css +6 -0
- package/themes/white.css +6 -0
- package/themes/zhujian-dark.css +6 -1
- package/themes/zhujian.css +6 -1
- package/themes/zhupi-dark.css +6 -1
- package/themes/zhupi.css +6 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
- package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
- package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
- package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
- package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
- package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
- package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
- package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
- package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
- package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
- package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
- package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
- package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
- package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
- package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
- package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
- package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
- package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
- package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
- package/web/dist/assets/index-CsFs_HMb.css +1 -0
- package/web/dist/assets/index-DHeeHS_l.js +85 -0
- package/web/dist/assets/index-DTZch8uz.js +85 -0
- package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
- package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
- package/web/dist/assets/theme-BXGpyTMh.js +1 -0
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
- package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
- package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
- package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
- package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
- package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
- package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
- package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
- package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
- package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
- package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
- package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
- package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
- package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
- package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
- package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
- package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
- package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
- package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
- package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
- package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
- package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
- package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
- package/web/dist/assets/index-Cdh3sibd.js +0 -85
- package/web/dist/assets/index-DDZMv6LO.css +0 -1
- package/web/dist/assets/index-DWw_SxRq.js +0 -85
- package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
- package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
|
@@ -3,11 +3,13 @@ import { hostname } from "node:os";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { getLocalBotOptions } from "./bot-catalog.js";
|
|
6
|
-
import {
|
|
6
|
+
import { applyLocalBotPreset } from "./bot-presets.js";
|
|
7
7
|
import { installHubSetupRoutes } from "./hub-setup.js";
|
|
8
8
|
import { DeviceWorkspaceError } from "./workspaces.js";
|
|
9
9
|
import { createLocalDeviceHub } from "./local-hub.js";
|
|
10
10
|
import { createLocalBotRegistry } from "./bots.js";
|
|
11
|
+
import { loadExecutionSettings, saveExecutionSettings } from "./execution-settings.js";
|
|
12
|
+
import { hostWithoutPort, isLoopbackHost } from "../host-guard.js";
|
|
11
13
|
/** Hub enrollment accepts HTTP(S) origins, including public IP addresses. */
|
|
12
14
|
export function normalizeHubUrl(input) {
|
|
13
15
|
if (typeof input !== "string" || input.length > 2048)
|
|
@@ -22,37 +24,61 @@ export function normalizeHubUrl(input) {
|
|
|
22
24
|
throw new Error("Hub must use HTTP(S), without a path, query, fragment or credentials");
|
|
23
25
|
return url.origin;
|
|
24
26
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Hub failures reach the browser as a cause the user can act on, but never verbatim: the raw message
|
|
29
|
+
* may echo configured credentials or opaque tokens. Redact known secrets plus token-shaped runs.
|
|
30
|
+
*/
|
|
31
|
+
export function scrubHubMessage(message, secrets) {
|
|
32
|
+
let safe = message;
|
|
33
|
+
for (const secret of secrets)
|
|
34
|
+
if (secret && secret.length >= 6)
|
|
35
|
+
safe = safe.split(secret).join("[REDACTED]");
|
|
36
|
+
safe = safe
|
|
37
|
+
.replace(/((?:bearer|token|api[-_]?key|secret|password|passwd|credential|authorization)[\s:="']{1,4})[A-Za-z0-9_\-./+=]{8,}/gi, "$1[REDACTED]")
|
|
38
|
+
.replace(/[A-Za-z0-9_\-./+=]{32,}/g, (token) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(token) ? token : "[REDACTED]");
|
|
39
|
+
return safe.trim().slice(0, 300);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Local-only guard for the device center API: the peer must be loopback, and the
|
|
43
|
+
* Host must be loopback too — except for hostnames the operator explicitly declared
|
|
44
|
+
* in PI_WEB_ALLOW_HOSTS. Those domains are the ones a reverse proxy forwards; the
|
|
45
|
+
* global host guard already trusts them (and is in strict-whitelist mode once the
|
|
46
|
+
* list is non-empty), so extending that decision here keeps a proxied deployment
|
|
47
|
+
* usable without weakening DNS-rebinding protection.
|
|
48
|
+
*/
|
|
49
|
+
function localOnly(allowHosts) {
|
|
50
|
+
return (req, res, next) => {
|
|
51
|
+
const peer = req.socket.remoteAddress?.replace(/^::ffff:/, "");
|
|
52
|
+
if (!(peer === "::1" || peer?.startsWith("127."))) {
|
|
53
|
+
res.status(403).json({ code: "LOCAL_ONLY", error: "Configure devices from this computer's loopback address" });
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
let host;
|
|
44
57
|
try {
|
|
45
|
-
|
|
46
|
-
if (!["http:", "https:"].includes(origin.protocol) || origin.host !== req.headers.host)
|
|
47
|
-
throw new Error();
|
|
58
|
+
host = new URL(`http://${req.headers.host}`).hostname.replace(/^\[|\]$/g, "");
|
|
48
59
|
}
|
|
49
60
|
catch {
|
|
50
|
-
res.status(403).json({ code: "LOCAL_ONLY", error: "
|
|
61
|
+
res.status(403).json({ code: "LOCAL_ONLY", error: "Invalid host" });
|
|
51
62
|
return;
|
|
52
63
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
64
|
+
if (!isLoopbackHost(host) && !allowHosts.has(host)) {
|
|
65
|
+
res.status(403).json({ code: "LOCAL_ONLY", error: "Use localhost to configure device access" });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (!["GET", "HEAD"].includes(req.method)) {
|
|
69
|
+
try {
|
|
70
|
+
const origin = new URL(req.headers.origin ?? "");
|
|
71
|
+
if (!["http:", "https:"].includes(origin.protocol) || origin.host !== req.headers.host)
|
|
72
|
+
throw new Error();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
res.status(403).json({ code: "LOCAL_ONLY", error: "Same-origin request required" });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
res.setHeader("Cache-Control", "no-store");
|
|
80
|
+
next();
|
|
81
|
+
};
|
|
56
82
|
}
|
|
57
83
|
export async function installLocalDeviceCenter(options) {
|
|
58
84
|
const file = join(options.dataDir, "device-center.json");
|
|
@@ -133,9 +159,14 @@ export async function installLocalDeviceCenter(options) {
|
|
|
133
159
|
Authorization: `Bearer ${captured.credential}`,
|
|
134
160
|
},
|
|
135
161
|
body: JSON.stringify({
|
|
136
|
-
bots: bots
|
|
137
|
-
|
|
138
|
-
|
|
162
|
+
bots: bots.list().map(({ id, name, description, enabled, revision, tools }) => ({
|
|
163
|
+
id,
|
|
164
|
+
name,
|
|
165
|
+
description,
|
|
166
|
+
enabled,
|
|
167
|
+
revision,
|
|
168
|
+
tools,
|
|
169
|
+
})),
|
|
139
170
|
}),
|
|
140
171
|
});
|
|
141
172
|
await response.body?.cancel();
|
|
@@ -194,11 +225,15 @@ export async function installLocalDeviceCenter(options) {
|
|
|
194
225
|
if (error.code !== "ENOENT")
|
|
195
226
|
throw error;
|
|
196
227
|
}
|
|
228
|
+
// Hostnames the operator declared as legitimate entry points (reverse proxy);
|
|
229
|
+
// entries are normalised exactly like the global guard does.
|
|
230
|
+
const allowHosts = new Set((options.allowHosts ?? []).map((entry) => hostWithoutPort(String(entry))).filter(Boolean));
|
|
231
|
+
const guard = localOnly(allowHosts);
|
|
197
232
|
// Existing bookmarks now enter the native application view.
|
|
198
|
-
options.app.get("/devices",
|
|
233
|
+
options.app.get("/devices", guard, (_req, res) => {
|
|
199
234
|
res.redirect("./?view=devices");
|
|
200
235
|
});
|
|
201
|
-
options.app.use("/api/device-center",
|
|
236
|
+
options.app.use("/api/device-center", guard);
|
|
202
237
|
const hubSetup = installHubSetupRoutes(options.app, options.dataDir);
|
|
203
238
|
options.app.get("/api/device-center/status", (_req, res) => {
|
|
204
239
|
res.json({
|
|
@@ -209,6 +244,38 @@ export async function installLocalDeviceCenter(options) {
|
|
|
209
244
|
connected: connection?.isConnected?.() ?? false,
|
|
210
245
|
});
|
|
211
246
|
});
|
|
247
|
+
options.app.get("/api/device-center/execution-settings", (_req, res) => {
|
|
248
|
+
try {
|
|
249
|
+
const settings = loadExecutionSettings(options.dataDir);
|
|
250
|
+
res.json({ settings });
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
res.status(500).json({ error: error.message });
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
options.app.get("/api/device-center/execution-queue", (_req, res) => {
|
|
257
|
+
try {
|
|
258
|
+
const currentRuntime = connection?.runtime;
|
|
259
|
+
if (currentRuntime) {
|
|
260
|
+
res.json(currentRuntime.getSchedulerSnapshot());
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
const settings = loadExecutionSettings(options.dataDir);
|
|
264
|
+
res.json({
|
|
265
|
+
settings,
|
|
266
|
+
activeCount: 0,
|
|
267
|
+
waitingCount: 0,
|
|
268
|
+
blockedCount: 0,
|
|
269
|
+
running: [],
|
|
270
|
+
waiting: [],
|
|
271
|
+
blocked: [],
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
res.status(500).json({ error: error.message });
|
|
277
|
+
}
|
|
278
|
+
});
|
|
212
279
|
// Account chat discovery is safe to relay; local settings remain device-only.
|
|
213
280
|
options.app.get("/api/device-center/chat-status", async (_req, res) => {
|
|
214
281
|
try {
|
|
@@ -222,6 +289,78 @@ export async function installLocalDeviceCenter(options) {
|
|
|
222
289
|
});
|
|
223
290
|
const activeRequests = new Set();
|
|
224
291
|
let inFlight = 0;
|
|
292
|
+
let eventStreams = 0;
|
|
293
|
+
options.app.get("/api/device-center/rooms/:id/events", async (req, res) => {
|
|
294
|
+
try {
|
|
295
|
+
await serialize(ensureLocalHub);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
res.sendStatus(503);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const captured = activeConfig();
|
|
302
|
+
const capturedGeneration = generation;
|
|
303
|
+
if (!captured?.uiCredential) {
|
|
304
|
+
res.sendStatus(409);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (closed || eventStreams >= 8) {
|
|
308
|
+
res.sendStatus(429);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const controller = new AbortController();
|
|
312
|
+
activeRequests.add(controller);
|
|
313
|
+
eventStreams++;
|
|
314
|
+
const cancel = () => controller.abort();
|
|
315
|
+
res.once("close", cancel);
|
|
316
|
+
req.once("aborted", cancel);
|
|
317
|
+
try {
|
|
318
|
+
const upstream = await fetch(`${captured.hubUrl}/api/device-user/rooms/${encodeURIComponent(String(req.params.id))}/events`, {
|
|
319
|
+
redirect: "error",
|
|
320
|
+
signal: controller.signal,
|
|
321
|
+
headers: { "X-Device-Id": captured.deviceId, Authorization: `Bearer ${captured.uiCredential}` },
|
|
322
|
+
});
|
|
323
|
+
if (!upstream.ok || !upstream.body || !upstream.headers.get("content-type")?.startsWith("text/event-stream")) {
|
|
324
|
+
await upstream.body?.cancel();
|
|
325
|
+
res.sendStatus(502);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (closed || generation !== capturedGeneration || activeConfig() !== captured)
|
|
329
|
+
return;
|
|
330
|
+
res.set({ "Content-Type": "text/event-stream", "Cache-Control": "no-store", "X-Accel-Buffering": "no" });
|
|
331
|
+
res.flushHeaders();
|
|
332
|
+
const reader = upstream.body.getReader();
|
|
333
|
+
try {
|
|
334
|
+
for (;;) {
|
|
335
|
+
const chunk = await reader.read();
|
|
336
|
+
if (chunk.done)
|
|
337
|
+
break;
|
|
338
|
+
if (closed ||
|
|
339
|
+
controller.signal.aborted ||
|
|
340
|
+
generation !== capturedGeneration ||
|
|
341
|
+
activeConfig() !== captured ||
|
|
342
|
+
chunk.value.byteLength > 65536 ||
|
|
343
|
+
!res.write(chunk.value))
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
await reader.cancel();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
catch {
|
|
352
|
+
if (!res.headersSent && !res.destroyed)
|
|
353
|
+
res.sendStatus(502);
|
|
354
|
+
}
|
|
355
|
+
finally {
|
|
356
|
+
controller.abort();
|
|
357
|
+
activeRequests.delete(controller);
|
|
358
|
+
eventStreams--;
|
|
359
|
+
res.off("close", cancel);
|
|
360
|
+
req.off("aborted", cancel);
|
|
361
|
+
res.end();
|
|
362
|
+
}
|
|
363
|
+
});
|
|
225
364
|
function userRoute(method, path, fields) {
|
|
226
365
|
options.app[method](`/api/device-center/${path}`, async (req, res) => {
|
|
227
366
|
try {
|
|
@@ -258,8 +397,10 @@ export async function installLocalDeviceCenter(options) {
|
|
|
258
397
|
req.once("aborted", cancel);
|
|
259
398
|
res.once("close", cancel);
|
|
260
399
|
try {
|
|
261
|
-
const suffix = path.replace(
|
|
262
|
-
const
|
|
400
|
+
const suffix = path.replace(/:([A-Za-z]+)/g, (_match, key) => encodeURIComponent(String(req.params[key])));
|
|
401
|
+
const queryIndex = req.url.indexOf("?");
|
|
402
|
+
const queryStr = queryIndex >= 0 ? req.url.slice(queryIndex) : "";
|
|
403
|
+
const response = await fetch(`${captured.hubUrl}/api/device-user/${suffix}${queryStr}`, {
|
|
263
404
|
method: method.toUpperCase(),
|
|
264
405
|
redirect: "error",
|
|
265
406
|
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]),
|
|
@@ -292,16 +433,32 @@ export async function installLocalDeviceCenter(options) {
|
|
|
292
433
|
if (closed || activeConfig() !== captured || generation !== capturedGeneration)
|
|
293
434
|
return res.status(409).json({ code: "DEVICE_CHANGED", error: "Device binding changed; refresh" });
|
|
294
435
|
if (!response.ok) {
|
|
295
|
-
|
|
296
|
-
|
|
436
|
+
let failure = null;
|
|
437
|
+
try {
|
|
438
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
439
|
+
if (parsed && typeof parsed === "object")
|
|
440
|
+
failure = parsed;
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
failure = null;
|
|
444
|
+
}
|
|
445
|
+
const hubCode = typeof failure?.code === "string" && /^[A-Z0-9_]{1,40}$/.test(failure.code) ? failure.code : undefined;
|
|
446
|
+
const hubMessage = typeof failure?.error === "string" && failure.error.trim()
|
|
447
|
+
? scrubHubMessage(failure.error, [captured.uiCredential, captured.credential]) || undefined
|
|
448
|
+
: undefined;
|
|
449
|
+
if (response.status === 409 && (hubCode === "ACTIVE_TASKS" || hubMessage === "ACTIVE_TASKS"))
|
|
297
450
|
return res.status(409).json({
|
|
298
451
|
code: "ACTIVE_TASKS",
|
|
299
|
-
error: "Stop active tasks before removing members or deleting this group",
|
|
452
|
+
error: "Stop active tasks before removing members, clearing messages or deleting this group",
|
|
300
453
|
});
|
|
301
454
|
const status = [400, 401, 403, 404, 409, 429].includes(response.status) ? response.status : 502;
|
|
302
455
|
return res.status(status === 401 ? 409 : status).json({
|
|
303
456
|
code: status === 401 ? "REPAIR_REQUIRED" : status === 403 ? "HUB_FORBIDDEN" : "HUB_REJECTED",
|
|
304
|
-
|
|
457
|
+
// Forward the hub's own diagnosis: a fixed "rejected" string erases the real cause
|
|
458
|
+
// ("Task missing", "Plan conversation unavailable", …) and makes the UI undebuggable.
|
|
459
|
+
error: status === 401 ? "Pair this computer again" : (hubMessage ?? "Hub rejected group request"),
|
|
460
|
+
hubStatus: response.status,
|
|
461
|
+
...(hubCode ? { hubCode } : {}),
|
|
305
462
|
});
|
|
306
463
|
}
|
|
307
464
|
const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
@@ -324,6 +481,65 @@ export async function installLocalDeviceCenter(options) {
|
|
|
324
481
|
options.app.get("/api/device-center/local-bots", (_req, res) => {
|
|
325
482
|
res.json({ bots: bots.list() });
|
|
326
483
|
});
|
|
484
|
+
options.app.get("/api/device-center/local-bots/:id", (req, res) => {
|
|
485
|
+
res.setHeader("Cache-Control", "no-store");
|
|
486
|
+
const bot = bots.get(String(req.params.id));
|
|
487
|
+
if (!bot) {
|
|
488
|
+
res.status(404).json({ code: "BOT_MISSING", error: "Bot is not configured on this device" });
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
res.json({ bot });
|
|
492
|
+
});
|
|
493
|
+
options.app.post("/api/device-center/local-bots/:id/preset", (req, res) => {
|
|
494
|
+
const controller = new AbortController();
|
|
495
|
+
const cancel = () => {
|
|
496
|
+
if (!res.writableEnded)
|
|
497
|
+
controller.abort();
|
|
498
|
+
};
|
|
499
|
+
req.once("aborted", cancel);
|
|
500
|
+
res.once("close", cancel);
|
|
501
|
+
void serialize(async () => {
|
|
502
|
+
if (closed)
|
|
503
|
+
throw new DeviceWorkspaceError(409, "CLOSED", "Device center is shutting down");
|
|
504
|
+
const input = req.body;
|
|
505
|
+
if (!input ||
|
|
506
|
+
typeof input !== "object" ||
|
|
507
|
+
Array.isArray(input) ||
|
|
508
|
+
Object.keys(input).some((key) => !["revision", "preset"].includes(key)))
|
|
509
|
+
throw new DeviceWorkspaceError(400, "BOT_PRESET_INVALID", "Expected revision and preset");
|
|
510
|
+
const bot = bots.get(String(req.params.id));
|
|
511
|
+
if (!bot)
|
|
512
|
+
throw new DeviceWorkspaceError(404, "BOT_MISSING", "Bot is not configured on this device");
|
|
513
|
+
if (input.revision !== bot.revision)
|
|
514
|
+
throw new DeviceWorkspaceError(409, "BOT_STALE", "Reload the current Bot revision before saving");
|
|
515
|
+
const catalog = await getLocalBotOptions(options.botCatalog ?? { defaultCwd: process.cwd(), dataDir: options.dataDir }, bot.cwd, controller.signal);
|
|
516
|
+
const next = applyLocalBotPreset(bot, input.preset, catalog);
|
|
517
|
+
controller.signal.throwIfAborted();
|
|
518
|
+
const saved = await bots.upsert(next);
|
|
519
|
+
try {
|
|
520
|
+
await syncBots();
|
|
521
|
+
return { bot: saved, synced: true };
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
return { bot: saved, synced: false };
|
|
525
|
+
}
|
|
526
|
+
})
|
|
527
|
+
.then((data) => {
|
|
528
|
+
if (!controller.signal.aborted)
|
|
529
|
+
res.json(data);
|
|
530
|
+
}, (error) => {
|
|
531
|
+
if (controller.signal.aborted)
|
|
532
|
+
return;
|
|
533
|
+
const known = error instanceof DeviceWorkspaceError;
|
|
534
|
+
res
|
|
535
|
+
.status(known ? error.status : 500)
|
|
536
|
+
.json({ code: known ? error.code : "BOT_FAILED", error: known ? error.message : "Bot preset save failed" });
|
|
537
|
+
})
|
|
538
|
+
.finally(() => {
|
|
539
|
+
req.off("aborted", cancel);
|
|
540
|
+
res.off("close", cancel);
|
|
541
|
+
});
|
|
542
|
+
});
|
|
327
543
|
function botMutation(remove) {
|
|
328
544
|
return (req, res) => {
|
|
329
545
|
void serialize(async () => {
|
|
@@ -415,9 +631,86 @@ export async function installLocalDeviceCenter(options) {
|
|
|
415
631
|
userRoute("post", "devices/:id/open", []);
|
|
416
632
|
userRoute("get", "rooms", []);
|
|
417
633
|
userRoute("get", "rooms/:id", []);
|
|
418
|
-
userRoute("post", "rooms", ["
|
|
634
|
+
userRoute("post", "rooms/:id/canvas", ["binding"]);
|
|
635
|
+
userRoute("get", "rooms/:id/tasks/:taskId", []);
|
|
636
|
+
userRoute("get", "rooms/:id/tasks/:taskId/journal", []);
|
|
637
|
+
userRoute("get", "rooms/:id/tasks/:taskId/report", []);
|
|
638
|
+
userRoute("post", "rooms/:id/tasks/:taskId/report", [
|
|
639
|
+
"chunkIndex",
|
|
640
|
+
"totalChunks",
|
|
641
|
+
"text",
|
|
642
|
+
"attemptId",
|
|
643
|
+
"isFinal",
|
|
644
|
+
"sha256",
|
|
645
|
+
]);
|
|
646
|
+
userRoute("post", "rooms/:id/tasks/:taskId/approve-plan", []);
|
|
647
|
+
userRoute("get", "rooms/:id/interactions", []);
|
|
648
|
+
userRoute("post", "rooms/:id/interactions", [
|
|
649
|
+
"taskId",
|
|
650
|
+
"attemptId",
|
|
651
|
+
"interactionId",
|
|
652
|
+
"answers",
|
|
653
|
+
"cancelled",
|
|
654
|
+
"decision",
|
|
655
|
+
]);
|
|
656
|
+
userRoute("get", "rooms/:id/conversations", []);
|
|
657
|
+
userRoute("get", "rooms/:id/conversations/:conversationId", []);
|
|
658
|
+
userRoute("post", "rooms/:id/conversations", ["name", "targetBotId", "text", "idempotencyKey", "planOnly"]);
|
|
659
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/messages", [
|
|
660
|
+
"text",
|
|
661
|
+
"kind",
|
|
662
|
+
"requestId",
|
|
663
|
+
"attentionId",
|
|
664
|
+
"idempotencyKey",
|
|
665
|
+
"planOnly",
|
|
666
|
+
]);
|
|
667
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/deliveries", [
|
|
668
|
+
"repository",
|
|
669
|
+
"baseCommit",
|
|
670
|
+
"commit",
|
|
671
|
+
"branch",
|
|
672
|
+
"summary",
|
|
673
|
+
"checks",
|
|
674
|
+
"limitations",
|
|
675
|
+
"idempotencyKey",
|
|
676
|
+
]);
|
|
677
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/reviews", [
|
|
678
|
+
"deliveryId",
|
|
679
|
+
"commit",
|
|
680
|
+
"verdict",
|
|
681
|
+
"summary",
|
|
682
|
+
"idempotencyKey",
|
|
683
|
+
]);
|
|
684
|
+
userRoute("get", "rooms/:id/conversations/:conversationId/integrations", []);
|
|
685
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/integrations", [
|
|
686
|
+
"deliveryId",
|
|
687
|
+
"targetBotId",
|
|
688
|
+
"targetBranch",
|
|
689
|
+
"idempotencyKey",
|
|
690
|
+
]);
|
|
691
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", ["commands"]);
|
|
692
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", ["expectedTargetSha"]);
|
|
693
|
+
userRoute("post", "rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", []);
|
|
694
|
+
userRoute("get", "rooms/:id/transfers", []);
|
|
695
|
+
userRoute("post", "rooms/:id/transfers/start", [
|
|
696
|
+
"sourceBotId",
|
|
697
|
+
"targetBotId",
|
|
698
|
+
"paths",
|
|
699
|
+
"recursive",
|
|
700
|
+
"idempotencyKey",
|
|
701
|
+
]);
|
|
702
|
+
userRoute("get", "rooms/:id/transfers/:transferId/preview", []);
|
|
703
|
+
userRoute("post", "rooms/:id/transfers/:transferId/resume", [
|
|
704
|
+
"manifestHash",
|
|
705
|
+
"sourceBotRevision",
|
|
706
|
+
"targetBotRevision",
|
|
707
|
+
]);
|
|
708
|
+
userRoute("post", "rooms/:id/transfers/:transferId/apply", ["revision", "overwritePaths"]);
|
|
709
|
+
userRoute("post", "rooms/:id/transfers/:transferId/abort", []);
|
|
710
|
+
userRoute("post", "rooms", ["name", "botIds", "primaryBotId"]);
|
|
419
711
|
userRoute("post", "rooms/:id/rename", ["name"]);
|
|
420
|
-
userRoute("post", "rooms/:id/members", ["botIds"]);
|
|
712
|
+
userRoute("post", "rooms/:id/members", ["botIds", "primaryBotId"]);
|
|
713
|
+
userRoute("post", "rooms/:id/clear", []);
|
|
421
714
|
userRoute("post", "rooms/:id/delete", []);
|
|
422
715
|
userRoute("post", "rooms/:id/messages", [
|
|
423
716
|
"text",
|
|
@@ -426,6 +719,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
426
719
|
"idempotencyKey",
|
|
427
720
|
"handoff",
|
|
428
721
|
"parentTaskId",
|
|
722
|
+
"planOnly",
|
|
429
723
|
]);
|
|
430
724
|
function route(path, work) {
|
|
431
725
|
options.app.post(`/api/device-center/${path}`, (req, res) => {
|
|
@@ -493,6 +787,28 @@ export async function installLocalDeviceCenter(options) {
|
|
|
493
787
|
await reconnect();
|
|
494
788
|
return { saved: true };
|
|
495
789
|
});
|
|
790
|
+
route("execution-settings", async (req) => {
|
|
791
|
+
const boundConnection = connection;
|
|
792
|
+
// Persist first, then apply to captured active runtime
|
|
793
|
+
const saved = saveExecutionSettings(options.dataDir, req.body);
|
|
794
|
+
if (boundConnection?.runtime) {
|
|
795
|
+
boundConnection.runtime.updateExecutionSettings(saved);
|
|
796
|
+
}
|
|
797
|
+
return { settings: saved };
|
|
798
|
+
});
|
|
799
|
+
route("execution-queue/cancel", async (req) => {
|
|
800
|
+
const boundConnection = connection;
|
|
801
|
+
const taskId = req.body?.taskId;
|
|
802
|
+
const attemptId = req.body?.attemptId;
|
|
803
|
+
if (typeof taskId !== "string" || !taskId) {
|
|
804
|
+
throw new Error("taskId is required");
|
|
805
|
+
}
|
|
806
|
+
if (attemptId !== undefined && (typeof attemptId !== "string" || !attemptId)) {
|
|
807
|
+
throw new Error("attemptId must be a string");
|
|
808
|
+
}
|
|
809
|
+
const cancelled = boundConnection?.runtime?.cancelScheduledTask(taskId, attemptId) ?? false;
|
|
810
|
+
return { cancelled };
|
|
811
|
+
});
|
|
496
812
|
route("disconnect", async () => {
|
|
497
813
|
await persist(undefined);
|
|
498
814
|
generation++;
|
|
@@ -49,10 +49,18 @@ export async function startDeviceHub(env = process.env) {
|
|
|
49
49
|
authenticateDevice: (id, credential) => hub.store.authenticateDevice(id, credential),
|
|
50
50
|
getAccount: (req) => hub.getRelayAccount(req),
|
|
51
51
|
ownsDevice: (accountId, id) => hub.store.getDeviceOwner(id) === accountId,
|
|
52
|
+
getDeviceName: (id) => hub.store.getDevice(id)?.name,
|
|
52
53
|
onTaskEvent: (id, event) => hub.acceptTaskEvent(id, event).then(() => undefined),
|
|
54
|
+
onTaskInteractions: (id, event) => hub.acceptInteractions(id, event),
|
|
55
|
+
onTaskProgress: (id, event) => hub.acceptTaskProgress(id, event),
|
|
56
|
+
onTaskToolLifecycle: (id, frame) => hub.acceptTaskToolLifecycle(id, frame),
|
|
57
|
+
onTaskPlanReady: (id, frame) => hub.acceptTaskPlanReady(id, frame),
|
|
58
|
+
onTaskClaim: (id, claim) => hub.claimTask(id, claim),
|
|
59
|
+
onTaskLeaseRenew: (id, renew) => hub.renewTaskLease(id, renew),
|
|
60
|
+
onTaskDisconnect: (id, taskId, attemptId) => hub.onTaskDisconnect(id, taskId, attemptId),
|
|
53
61
|
});
|
|
54
62
|
hub.setRelay(relay);
|
|
55
|
-
await installDeviceTransfers({
|
|
63
|
+
const transfers = await installDeviceTransfers({
|
|
56
64
|
app: hub.app,
|
|
57
65
|
hub,
|
|
58
66
|
dataDir: resolve(env.PI_DEVICE_HUB_DATA_DIR ?? join(homedir(), ".pi-device-hub")),
|
|
@@ -91,6 +99,7 @@ export async function startDeviceHub(env = process.env) {
|
|
|
91
99
|
await listen(hub.server, port);
|
|
92
100
|
}
|
|
93
101
|
catch (error) {
|
|
102
|
+
await transfers.close();
|
|
94
103
|
relay.close();
|
|
95
104
|
await closePortals();
|
|
96
105
|
await hub.close();
|
|
@@ -110,6 +119,7 @@ export async function startDeviceHub(env = process.env) {
|
|
|
110
119
|
...hub,
|
|
111
120
|
portals,
|
|
112
121
|
async close() {
|
|
122
|
+
await transfers.close();
|
|
113
123
|
relay?.close();
|
|
114
124
|
await closePortals();
|
|
115
125
|
await hub.close();
|
|
@@ -32,12 +32,20 @@ export function portalHeaders(hub, base) {
|
|
|
32
32
|
"x-content-type-options": "nosniff",
|
|
33
33
|
};
|
|
34
34
|
}
|
|
35
|
-
export function wrapperHtml(base, initialPath = "") {
|
|
35
|
+
export function wrapperHtml(base, initialPath = "", desktopHub, deviceLabel = "Device") {
|
|
36
|
+
const title = `${deviceLabel} · pi-web-ui`.replace(/[&<>"']/g, (char) => {
|
|
37
|
+
return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[char];
|
|
38
|
+
});
|
|
36
39
|
const nonce = randomBytes(16).toString("hex");
|
|
37
|
-
|
|
40
|
+
// Desktop tickets may be embedded by a paired device UI on another origin.
|
|
41
|
+
// The device content remains in the opaque sandbox, even when this wrapper is embedded.
|
|
42
|
+
const frameBase = desktopHub ? new URL(base, desktopHub).href : base;
|
|
43
|
+
const frameSource = desktopHub ? `${desktopHub.origin}${base}` : "'self'";
|
|
44
|
+
const ancestors = desktopHub ? "http: https:" : "'self'";
|
|
45
|
+
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style nonce="${nonce}">html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block}body{background:#17181c;color:#eee;font:14px system-ui}#loading{position:fixed;inset:0;display:grid;place-content:center;text-align:center;gap:14px;background:#17181c}#loading[hidden]{display:none}button,a{padding:10px 16px;color:inherit;background:#303137;border:1px solid #555;border-radius:8px;text-decoration:none;cursor:pointer}p{color:#aaa;max-width:420px;line-height:1.7}</style></head><body><iframe sandbox="allow-scripts allow-forms allow-downloads" allowfullscreen referrerpolicy="no-referrer"></iframe><div id="loading"><strong id="title">正在连接设备… / Connecting…</strong><p id="hint">正在加载远程页面,请稍候。 / Loading the remote page.</p><div><button id="retry" type="button">重新连接 / Retry</button> <a href="/">返回设备中心 / Hub</a></div></div><script nonce="${nonce}">const frame=document.querySelector('iframe'),loading=document.getElementById('loading');let timer;const connect=()=>{loading.hidden=false;document.getElementById('title').textContent='正在连接设备… / Connecting…';frame.src=${JSON.stringify(frameBase + initialPath)}+location.hash;clearTimeout(timer);timer=setTimeout(()=>{document.getElementById('title').textContent='设备页面加载超时 / Connection timed out';document.getElementById('hint').textContent='请重试;若设备离线或入口已过期,请返回设备中心重新打开。 / Retry, or reopen the device from the Hub.';},20000)};document.getElementById('retry').onclick=connect;connect();addEventListener('message',event=>{if(event.source!==frame.contentWindow||event.origin!=='null')return;const data=event.data;if(data?.type==='device-portal-ready'){clearTimeout(timer);loading.hidden=true;return}if(!data||data.type!=='device-session-hash'||typeof data.hash!=='string'||!/^#s=[a-zA-Z0-9_-]{1,256}$/.test(data.hash))return;history.replaceState(null,'',location.pathname+data.hash)});</script></body></html>`;
|
|
38
46
|
return {
|
|
39
47
|
html,
|
|
40
|
-
csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; frame-src
|
|
48
|
+
csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; frame-src ${frameSource}; base-uri 'none'; form-action 'none'; frame-ancestors ${ancestors}`,
|
|
41
49
|
};
|
|
42
50
|
}
|
|
43
51
|
export function transformPortalHtml(html, base) {
|