pi-web-ui 0.115.0 → 0.116.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 +29 -0
- package/bin/pi-web-ui.mjs +21 -1
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +84 -2
- package/dist/server/agent-service.js +107 -26
- package/dist/server/client-state.js +17 -2
- package/dist/server/device-center/bot-execution.js +29 -1
- package/dist/server/device-center/collab-service.js +36 -5
- package/dist/server/device-center/collab-tool.js +90 -5
- package/dist/server/device-center/execution-guides.js +2 -2
- package/dist/server/device-center/execution-instructions.js +2 -1
- package/dist/server/device-center/execution-settings.js +138 -25
- package/dist/server/device-center/executor.js +4 -1
- package/dist/server/device-center/file-sync.js +14 -13
- package/dist/server/device-center/group-context-message.js +3 -1
- package/dist/server/device-center/group-context.js +73 -3
- package/dist/server/device-center/hub-conversations.js +58 -3
- package/dist/server/device-center/hub-locks.js +320 -0
- package/dist/server/device-center/hub-page.js +13 -33
- package/dist/server/device-center/hub-webhooks.js +165 -0
- package/dist/server/device-center/hub.js +872 -64
- package/dist/server/device-center/local-hub.js +2 -1
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +74 -1
- package/dist/server/device-center/partition-log.js +293 -0
- package/dist/server/device-center/runtime.js +49 -0
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +163 -64
- package/dist/server/device-center/task-scheduler.js +48 -3
- package/dist/server/device-center/transfers.js +41 -15
- package/dist/server/dispatch-domain-handlers.js +14 -3
- package/dist/server/durable/durable-capabilities.js +11 -0
- package/dist/server/engine-probe.js +112 -1
- package/dist/server/global-loader.js +119 -19
- package/dist/server/index.js +133 -16
- package/dist/server/managed.js +2 -0
- package/dist/server/markers/builtins/services.js +123 -0
- package/dist/server/markers/builtins/todo.js +189 -0
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/model-admin.js +48 -6
- package/dist/server/model-enrich.js +10 -1
- package/dist/server/orchestrator.js +109 -0
- package/dist/server/plugins.js +64 -7
- package/dist/server/prompt-composer.js +39 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/reasoning-registry.js +207 -0
- package/dist/server/startup-banner.js +35 -0
- package/dist/server/subagents.js +2 -1
- package/dist/server/system-prompt-soul.js +41 -0
- package/dist/server/tool-manager.js +17 -9
- package/dist/server/unauthorized-page.js +319 -0
- package/dist/server/univer-service.js +448 -0
- package/dist/server/universal/drivers/dsh-driver.js +379 -0
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/architecture-plugins.md +946 -0
- package/docs/device-center.md +6 -0
- package/package.json +2 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BDoOpj-F.js} +1 -1
- package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0i3O1FT.js} +1 -1
- package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-B8thymBN.js} +3 -3
- package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-zSxyIx1R.js} +3 -3
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
- package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-C4LIhshN.js} +1 -1
- package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
- package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
- package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BWgU8yPd.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-F7fNimKk.js} +1 -1
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
- package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-c6d0TJoh.js} +1 -1
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
- package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BmMrrgB9.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-BGSBIKD7.js} +1 -1
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
- package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
- package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
- package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-0CYvD72B.js} +2 -2
- package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-DDavKvFr.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-BsA-QTvN.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-DzoVQBuG.js} +1 -1
- package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
- package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-CUnXlQYX.js} +1 -1
- package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-aAKpvKJV.js} +1 -1
- package/web/dist/assets/index-C6DwztqE.css +1 -0
- package/web/dist/assets/index-CuN802Sj.js +93 -0
- package/web/dist/assets/index-EH5Fw9fa.js +93 -0
- package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-BRWib9DF.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-CfYSMEZg.js} +1 -1
- package/web/dist/assets/{theme-BXGpyTMh.js → theme-D2l_mLNo.js} +1 -1
- package/web/dist/index.html +10 -10
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
- package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
- package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
- package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
- package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
- package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
- package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
- package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
- package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
- package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
- package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
- package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
- package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
- package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
- package/web/dist/assets/index-CsFs_HMb.css +0 -1
- package/web/dist/assets/index-DHeeHS_l.js +0 -85
- package/web/dist/assets/index-DTZch8uz.js +0 -85
|
@@ -7,7 +7,7 @@ import { createDeviceRelay } from "./relay.js";
|
|
|
7
7
|
import { installDeviceTransfers } from "./transfers.js";
|
|
8
8
|
import { hashSecret } from "./store.js";
|
|
9
9
|
/** Private loopback Hub: uses the same authenticated Bot, room and task paths as a remote Hub. */
|
|
10
|
-
export async function createLocalDeviceHub(dataDir) {
|
|
10
|
+
export async function createLocalDeviceHub(dataDir, getSettings) {
|
|
11
11
|
const server = createServer();
|
|
12
12
|
await new Promise((resolve, reject) => {
|
|
13
13
|
server.once("error", reject);
|
|
@@ -28,6 +28,7 @@ export async function createLocalDeviceHub(dataDir) {
|
|
|
28
28
|
publicUrl: hubUrl,
|
|
29
29
|
server,
|
|
30
30
|
isOnline: (id) => relay?.isOnline(id) ?? false,
|
|
31
|
+
getSettings,
|
|
31
32
|
});
|
|
32
33
|
const credential = randomBytes(32).toString("hex");
|
|
33
34
|
const uiCredential = randomBytes(32).toString("hex");
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function renderLocalDevicePage() {
|
|
2
|
+
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>设备中心 · Device Center</title><style>
|
|
3
|
+
:root{color-scheme:dark;--bg:#15181f;--panel:#202632;--text:#edf1f8;--muted:#b9c4d5;--line:#526078;--accent:#83b5ff;--on-accent:#10223d}*{box-sizing:border-box}body{background:var(--bg);color:var(--text);font:15px/1.6 system-ui;margin:0;padding:24px}main{max-width:760px;margin:auto;min-width:0}section{background:var(--panel);padding:20px;border:1px solid var(--line);border-radius:12px;margin:16px 0;min-width:0;max-width:100%}label{display:block;margin:12px 0}input:not([type=checkbox]){width:100%;padding:10px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:6px}button,a{font:inherit}button{padding:9px 15px;border:0;border-radius:6px;background:var(--accent);color:var(--on-accent);cursor:pointer;margin:5px 6px 5px 0}a{color:var(--accent)}p,pre{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}small{color:var(--muted)}#error{color:#ffb6b6}button:disabled{opacity:.6;cursor:wait}</style></head><body><main>
|
|
4
|
+
<h1>设备中心 <small>Device Center</small></h1><p>绑定到你的设备中心,在群聊中用 @设备 分派跨平台任务。 / Bind this computer to your hub for remote access and group tasks.</p>
|
|
5
|
+
<section><h2>绑定本机 / Pair this computer</h2><form id="pair"><label>设备中心地址 / Hub URL<input id="hub" type="url" placeholder="https://console.example.com" required></label><label>本机名称 / Device name<input id="name" maxlength="80" required></label><button>获取配对码 / Get code</button></form><p id="pairing"></p><a id="approve" hidden target="_blank" rel="noopener noreferrer">打开设备中心确认绑定 / Approve in hub</a></section>
|
|
6
|
+
<section><h2>当前连接 / Connection</h2><pre id="status">加载中 / Loading…</pre><label><input id="execution" type="checkbox"> 允许群任务执行与文件同步导入 / Allow agent tasks and file imports</label><small>开启后,你的设备中心账号可向本机派发文件修改、命令和文件导入请求。智能体任务沿用本机审批,文件导入校验预览版本与覆盖清单。 / Allows agent tasks and file imports. Tasks retain local approvals; imports require a matching preview and explicit conflict overrides.</small><p><button id="save">保存执行权限 / Save permission</button><button id="disconnect">解除本机连接 / Disconnect locally</button></p><a id="open" hidden target="_blank" rel="noopener noreferrer">进入群聊与设备列表 / Open hub</a><p><small>本机断开不会删除中心设备记录;请到中心撤销设备授权。 / Local disconnect does not revoke the hub device record; revoke it in the hub.</small></p></section><p id="error" role="alert"></p><p><a href="./">返回 / Back</a></p>
|
|
7
|
+
<script type="module">
|
|
8
|
+
const api=new URL('./api/device-center/',location.href);const el=id=>document.getElementById(id);let generation=0;let polling=false;
|
|
9
|
+
async function request(path,body){const response=await fetch(new URL(path,api),{method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});const data=await response.json();if(!response.ok)throw new Error(data.error||String(response.status));return data}
|
|
10
|
+
function error(e){el('error').textContent=e.message||String(e)}
|
|
11
|
+
async function status(){const s=await request('status');el('status').textContent=s.deviceId? s.name+'\\n'+s.hubUrl+'\\n'+(s.connected?'已连接 / Connected':'正在连接 / Connecting'):'未绑定 / Not paired';el('execution').checked=s.allowExecution;el('open').hidden=!s.hubUrl;if(s.hubUrl)el('open').href=s.hubUrl;el('name').value ||= s.name;if(s.hubUrl)el('hub').value ||= s.hubUrl}
|
|
12
|
+
el('pair').onsubmit=async event=>{event.preventDefault();el('error').textContent='';const mine=++generation;try{const p=await request('pair',{hubUrl:el('hub').value,name:el('name').value});if(mine!==generation)return;el('pairing').textContent='配对码 / Code: '+p.code;el('approve').href=p.hubUrl;el('approve').hidden=false;polling=true;const poll=async()=>{if(mine!==generation)return;try{const result=await request('poll',{});if(mine!==generation)return;if(result.pending){setTimeout(poll,2000);return}polling=false;el('pairing').textContent='绑定完成 / Paired';el('approve').hidden=true;await status()}catch(e){polling=false;error(e)}};setTimeout(poll,1000)}catch(e){error(e)}};
|
|
13
|
+
el('save').onclick=async()=>{try{await request('execution',{allowExecution:el('execution').checked});await status()}catch(e){error(e)}};
|
|
14
|
+
el('disconnect').onclick=async()=>{if(!confirm('断开本机与设备中心的连接? / Disconnect this device?'))return;generation++;polling=false;try{await request('disconnect',{});el('pairing').textContent='';el('approve').hidden=true;await status()}catch(e){error(e)}};
|
|
15
|
+
status().catch(error);setInterval(()=>{if(!polling)status().catch(error)},5000);
|
|
16
|
+
</script></main></body></html>`;
|
|
17
|
+
}
|
|
@@ -93,7 +93,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
93
93
|
return;
|
|
94
94
|
if (!localStarting) {
|
|
95
95
|
localStarting = (async () => {
|
|
96
|
-
const hub = await createLocalDeviceHub(options.dataDir);
|
|
96
|
+
const hub = await createLocalDeviceHub(options.dataDir, () => loadExecutionSettings(options.dataDir));
|
|
97
97
|
try {
|
|
98
98
|
const { uiCredential: _uiCredential, ...agentConfig } = hub.config;
|
|
99
99
|
localHub = hub;
|
|
@@ -214,6 +214,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
214
214
|
typeof value.deviceId !== "string" ||
|
|
215
215
|
typeof value.credential !== "string" ||
|
|
216
216
|
typeof value.name !== "string" ||
|
|
217
|
+
(value.remark !== undefined && typeof value.remark !== "string") ||
|
|
217
218
|
typeof value.allowExecution !== "boolean" ||
|
|
218
219
|
(value.uiCredential !== undefined && typeof value.uiCredential !== "string"))
|
|
219
220
|
throw new Error("Invalid saved device configuration");
|
|
@@ -229,6 +230,32 @@ export async function installLocalDeviceCenter(options) {
|
|
|
229
230
|
// entries are normalised exactly like the global guard does.
|
|
230
231
|
const allowHosts = new Set((options.allowHosts ?? []).map((entry) => hostWithoutPort(String(entry))).filter(Boolean));
|
|
231
232
|
const guard = localOnly(allowHosts);
|
|
233
|
+
// Public incoming webhook forwarding (authenticates via webhook token inside hub)
|
|
234
|
+
options.app.post("/api/rooms/:id/webhooks/incoming/:webhookId", async (req, res) => {
|
|
235
|
+
const captured = activeConfig();
|
|
236
|
+
if (!captured)
|
|
237
|
+
return res.status(503).json({ error: "Device hub not paired" });
|
|
238
|
+
try {
|
|
239
|
+
const queryIndex = req.url.indexOf("?");
|
|
240
|
+
const queryStr = queryIndex >= 0 ? req.url.slice(queryIndex) : "";
|
|
241
|
+
const forwardUrl = `${captured.hubUrl}/api/rooms/${encodeURIComponent(String(req.params.id))}/webhooks/incoming/${encodeURIComponent(String(req.params.webhookId))}${queryStr}`;
|
|
242
|
+
const response = await fetch(forwardUrl, {
|
|
243
|
+
method: "POST",
|
|
244
|
+
headers: {
|
|
245
|
+
"Content-Type": "application/json",
|
|
246
|
+
...(req.headers.authorization ? { Authorization: req.headers.authorization } : {}),
|
|
247
|
+
...(req.headers["x-webhook-token"] ? { "x-webhook-token": String(req.headers["x-webhook-token"]) } : {}),
|
|
248
|
+
},
|
|
249
|
+
body: JSON.stringify(req.body ?? {}),
|
|
250
|
+
signal: AbortSignal.timeout(15000),
|
|
251
|
+
});
|
|
252
|
+
const data = await response.json().catch(() => ({}));
|
|
253
|
+
res.status(response.status).json(data);
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
res.status(502).json({ error: err?.message ?? "Failed to forward webhook to hub" });
|
|
257
|
+
}
|
|
258
|
+
});
|
|
232
259
|
// Existing bookmarks now enter the native application view.
|
|
233
260
|
options.app.get("/devices", guard, (_req, res) => {
|
|
234
261
|
res.redirect("./?view=devices");
|
|
@@ -238,6 +265,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
238
265
|
options.app.get("/api/device-center/status", (_req, res) => {
|
|
239
266
|
res.json({
|
|
240
267
|
name: config?.name ?? hostname(),
|
|
268
|
+
remark: config?.remark,
|
|
241
269
|
hubUrl: config?.hubUrl,
|
|
242
270
|
deviceId: config?.deviceId,
|
|
243
271
|
allowExecution: config?.allowExecution ?? false,
|
|
@@ -462,6 +490,14 @@ export async function installLocalDeviceCenter(options) {
|
|
|
462
490
|
});
|
|
463
491
|
}
|
|
464
492
|
const data = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
493
|
+
if (path === "devices/:id/remark" &&
|
|
494
|
+
String(req.params.id) === captured.deviceId &&
|
|
495
|
+
config) {
|
|
496
|
+
const rawRemark = req.body?.remark;
|
|
497
|
+
const remark = typeof rawRemark === "string" ? rawRemark.trim().slice(0, 80) : "";
|
|
498
|
+
config = { ...config, remark: remark || undefined };
|
|
499
|
+
void persist(config);
|
|
500
|
+
}
|
|
465
501
|
res.status(response.status).json(data);
|
|
466
502
|
}
|
|
467
503
|
catch {
|
|
@@ -629,6 +665,7 @@ export async function installLocalDeviceCenter(options) {
|
|
|
629
665
|
userRoute("get", "bots", []);
|
|
630
666
|
userRoute("get", "devices", []);
|
|
631
667
|
userRoute("post", "devices/:id/open", []);
|
|
668
|
+
userRoute("post", "devices/:id/remark", ["remark"]);
|
|
632
669
|
userRoute("get", "rooms", []);
|
|
633
670
|
userRoute("get", "rooms/:id", []);
|
|
634
671
|
userRoute("post", "rooms/:id/canvas", ["binding"]);
|
|
@@ -721,6 +758,30 @@ export async function installLocalDeviceCenter(options) {
|
|
|
721
758
|
"parentTaskId",
|
|
722
759
|
"planOnly",
|
|
723
760
|
]);
|
|
761
|
+
userRoute("get", "rooms/:id/webhooks", []);
|
|
762
|
+
userRoute("post", "rooms/:id/webhooks", [
|
|
763
|
+
"name",
|
|
764
|
+
"type",
|
|
765
|
+
"enabled",
|
|
766
|
+
"allowBotTrigger",
|
|
767
|
+
"url",
|
|
768
|
+
"secret",
|
|
769
|
+
"events",
|
|
770
|
+
"relayViaHub",
|
|
771
|
+
]);
|
|
772
|
+
userRoute("post", "rooms/:id/webhooks/:webhookId", [
|
|
773
|
+
"name",
|
|
774
|
+
"enabled",
|
|
775
|
+
"allowBotTrigger",
|
|
776
|
+
"url",
|
|
777
|
+
"secret",
|
|
778
|
+
"events",
|
|
779
|
+
"relayViaHub",
|
|
780
|
+
]);
|
|
781
|
+
userRoute("post", "rooms/:id/webhooks/:webhookId/regenerate-token", []);
|
|
782
|
+
userRoute("post", "rooms/:id/webhooks/:webhookId/delete", []);
|
|
783
|
+
userRoute("post", "rooms/:id/webhooks/:webhookId/test", []);
|
|
784
|
+
userRoute("post", "rooms/:id/hub-relay", ["hubRelayBaseUrl"]);
|
|
724
785
|
function route(path, work) {
|
|
725
786
|
options.app.post(`/api/device-center/${path}`, (req, res) => {
|
|
726
787
|
void serialize(async () => {
|
|
@@ -787,6 +848,18 @@ export async function installLocalDeviceCenter(options) {
|
|
|
787
848
|
await reconnect();
|
|
788
849
|
return { saved: true };
|
|
789
850
|
});
|
|
851
|
+
route("remark", async (req) => {
|
|
852
|
+
if (!config)
|
|
853
|
+
throw new Error("Pair this computer first");
|
|
854
|
+
const rawRemark = req.body?.remark;
|
|
855
|
+
if (rawRemark !== null && rawRemark !== undefined && typeof rawRemark !== "string")
|
|
856
|
+
throw new Error("Invalid remark");
|
|
857
|
+
const remark = typeof rawRemark === "string" ? rawRemark.trim().slice(0, 80) : "";
|
|
858
|
+
const next = { ...config, remark: remark || undefined };
|
|
859
|
+
await persist(next);
|
|
860
|
+
config = next;
|
|
861
|
+
return { saved: true, remark: next.remark };
|
|
862
|
+
});
|
|
790
863
|
route("execution-settings", async (req) => {
|
|
791
864
|
const boundConnection = connection;
|
|
792
865
|
// Persist first, then apply to captured active runtime
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, open, readFile, readdir, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/**
|
|
5
|
+
* Append-only partitioned log for collections that dominate Hub state size.
|
|
6
|
+
*
|
|
7
|
+
* One file per partition (room or conversation), one JSON object per line:
|
|
8
|
+
* {"v":1,"op":"upsert","value":{...}}
|
|
9
|
+
* {"v":1,"op":"del","ids":["..."]}
|
|
10
|
+
*
|
|
11
|
+
* Durability model: the owner persists its index file first and calls `commit` afterwards, so a log
|
|
12
|
+
* entry always describes state that is already durable. Deletions are appended as tombstones and
|
|
13
|
+
* compacted away once they outnumber live rows, which keeps steady-state growth O(1) per mutation.
|
|
14
|
+
* A crash can only leave a partial trailing line (repaired on load) or un-tombstoned rows (trimmed
|
|
15
|
+
* by the caller's retention on load), never a torn index file.
|
|
16
|
+
*/
|
|
17
|
+
const PARTITION = /^[A-Za-z0-9_-]{1,128}$/;
|
|
18
|
+
const PARTITION_SUFFIX = ".jsonl";
|
|
19
|
+
export const LOG_MAX_DELETES = 200;
|
|
20
|
+
export class PartitionedAppendLog {
|
|
21
|
+
dir;
|
|
22
|
+
partitionOf;
|
|
23
|
+
idOf;
|
|
24
|
+
retention;
|
|
25
|
+
protect;
|
|
26
|
+
maxDeletes;
|
|
27
|
+
/** Digest of the rows already written, so a commit only serializes what changed. */
|
|
28
|
+
cache = new Map();
|
|
29
|
+
deletes = new Map();
|
|
30
|
+
lines = new Map();
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.dir = options.dir;
|
|
33
|
+
this.partitionOf = options.partition;
|
|
34
|
+
this.idOf = options.id;
|
|
35
|
+
this.retention = options.retention;
|
|
36
|
+
this.protect = options.protect;
|
|
37
|
+
this.maxDeletes = options.maxDeletes ?? LOG_MAX_DELETES;
|
|
38
|
+
}
|
|
39
|
+
file(partition) {
|
|
40
|
+
return PARTITION.test(partition) ? join(this.dir, `${partition}${PARTITION_SUFFIX}`) : null;
|
|
41
|
+
}
|
|
42
|
+
digest(value) {
|
|
43
|
+
return createHash("sha1").update(JSON.stringify(value)).digest("hex");
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Load every existing partition in the given parent set; rows of removed parents are ignored.
|
|
47
|
+
* `sweep` removes log files whose parent no longer exists (crash leftovers); read-only callers skip it.
|
|
48
|
+
*/
|
|
49
|
+
async load(partitions, options = {}) {
|
|
50
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
|
51
|
+
const existing = new Set();
|
|
52
|
+
for (const partition of partitions)
|
|
53
|
+
if (PARTITION.test(partition))
|
|
54
|
+
existing.add(partition);
|
|
55
|
+
// Files whose parent was removed by a committed transaction (crash between the two writes).
|
|
56
|
+
for (const entry of options.sweep === false ? [] : await readdir(this.dir)) {
|
|
57
|
+
const partition = entry.endsWith(PARTITION_SUFFIX) ? entry.slice(0, -PARTITION_SUFFIX.length) : "";
|
|
58
|
+
if (!partition || !PARTITION.test(partition) || existing.has(partition))
|
|
59
|
+
continue;
|
|
60
|
+
await unlink(join(this.dir, entry)).catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
const rows = [];
|
|
63
|
+
for (const partition of existing) {
|
|
64
|
+
const loaded = await this.readPartition(partition);
|
|
65
|
+
if (!loaded)
|
|
66
|
+
continue;
|
|
67
|
+
rows.push(...loaded.values);
|
|
68
|
+
// Repair a partition left oversized by a lost tombstone/compaction.
|
|
69
|
+
const overRetention = this.retention !== undefined && loaded.rawRows > this.retention;
|
|
70
|
+
if (loaded.needsRepair || overRetention || loaded.deletes > this.maxDeletes)
|
|
71
|
+
await this.rewrite(partition, loaded.values);
|
|
72
|
+
}
|
|
73
|
+
return rows;
|
|
74
|
+
}
|
|
75
|
+
withRetention(values) {
|
|
76
|
+
if (this.retention === undefined || values.length <= this.retention)
|
|
77
|
+
return values;
|
|
78
|
+
const kept = new Set();
|
|
79
|
+
const protectedRows = this.protect ? values.filter((value) => this.protect(value)) : [];
|
|
80
|
+
for (const row of protectedRows)
|
|
81
|
+
kept.add(this.idOf(row));
|
|
82
|
+
const rest = values.filter((value) => !kept.has(this.idOf(value)));
|
|
83
|
+
const remaining = Math.max(0, this.retention - kept.size);
|
|
84
|
+
// slice(-0) would return the whole array, so only take a window when there is room left.
|
|
85
|
+
for (const row of remaining > 0 ? rest.slice(-remaining) : [])
|
|
86
|
+
kept.add(this.idOf(row));
|
|
87
|
+
return values.filter((value) => kept.has(this.idOf(value)));
|
|
88
|
+
}
|
|
89
|
+
async readPartition(partition) {
|
|
90
|
+
const file = this.file(partition);
|
|
91
|
+
if (!file)
|
|
92
|
+
return null;
|
|
93
|
+
let raw;
|
|
94
|
+
try {
|
|
95
|
+
raw = await readFile(file, "utf8");
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code === "ENOENT")
|
|
99
|
+
return null;
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
let complete = raw;
|
|
103
|
+
let needsRepair = false;
|
|
104
|
+
// A crash during append can leave a partial last line; ignore and truncate it before appending.
|
|
105
|
+
if (raw.length && !raw.endsWith("\n")) {
|
|
106
|
+
const cut = raw.lastIndexOf("\n");
|
|
107
|
+
complete = cut >= 0 ? raw.slice(0, cut + 1) : "";
|
|
108
|
+
needsRepair = true;
|
|
109
|
+
}
|
|
110
|
+
const live = new Map();
|
|
111
|
+
let deletes = 0;
|
|
112
|
+
let lines = 0;
|
|
113
|
+
for (const line of complete.split("\n")) {
|
|
114
|
+
if (!line)
|
|
115
|
+
continue;
|
|
116
|
+
lines++;
|
|
117
|
+
let parsed;
|
|
118
|
+
try {
|
|
119
|
+
parsed = JSON.parse(line);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// Only a torn tail is expected; anything else is corruption and is skipped explicitly.
|
|
123
|
+
needsRepair = true;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (!parsed || parsed.v !== 1) {
|
|
127
|
+
needsRepair = true;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (parsed.op === "del" && Array.isArray(parsed.ids)) {
|
|
131
|
+
deletes += parsed.ids.length;
|
|
132
|
+
for (const id of parsed.ids)
|
|
133
|
+
if (typeof id === "string")
|
|
134
|
+
live.delete(id);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (parsed.op === "upsert" && parsed.value && typeof parsed.value === "object") {
|
|
138
|
+
const id = this.idOf(parsed.value);
|
|
139
|
+
if (typeof id !== "string" || !id) {
|
|
140
|
+
needsRepair = true;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
live.set(id, parsed.value);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
needsRepair = true;
|
|
147
|
+
}
|
|
148
|
+
const rawValues = [...live.values()];
|
|
149
|
+
const values = this.withRetention(rawValues);
|
|
150
|
+
const cache = new Map();
|
|
151
|
+
for (const value of values)
|
|
152
|
+
cache.set(this.idOf(value), this.digest(value));
|
|
153
|
+
this.cache.set(partition, cache);
|
|
154
|
+
this.deletes.set(partition, deletes);
|
|
155
|
+
this.lines.set(partition, lines);
|
|
156
|
+
return { values, rawRows: rawValues.length, deletes, needsRepair };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Apply the diff between what is on disk (cache) and `next`. Partitions that no longer exist are
|
|
160
|
+
* removed. When the write fails partway, each touched file is truncated back to its previous size
|
|
161
|
+
* so a rejected transaction cannot leave phantom rows behind.
|
|
162
|
+
*/
|
|
163
|
+
async commit(next, partitions) {
|
|
164
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
|
165
|
+
const grouped = new Map();
|
|
166
|
+
for (const value of next) {
|
|
167
|
+
const partition = this.partitionOf(value);
|
|
168
|
+
if (!partitions.has(partition) || !PARTITION.test(partition))
|
|
169
|
+
continue;
|
|
170
|
+
const bucket = grouped.get(partition) ?? [];
|
|
171
|
+
bucket.push({ value, digest: this.digest(value) });
|
|
172
|
+
grouped.set(partition, bucket);
|
|
173
|
+
}
|
|
174
|
+
const removedPartitions = [...this.cache.keys()].filter((partition) => !partitions.has(partition) && PARTITION.test(partition));
|
|
175
|
+
// Partitions whose rows were all removed may have no `grouped` bucket; they still need tombstones.
|
|
176
|
+
const touched = new Set([...grouped.keys(), ...this.cache.keys(), ...removedPartitions]);
|
|
177
|
+
// Pre-append sizes so a rejected transaction cannot leave phantom rows behind.
|
|
178
|
+
const rollback = new Map();
|
|
179
|
+
try {
|
|
180
|
+
for (const partition of removedPartitions) {
|
|
181
|
+
const file = this.file(partition);
|
|
182
|
+
if (file)
|
|
183
|
+
await unlink(file).catch(() => { });
|
|
184
|
+
this.cache.delete(partition);
|
|
185
|
+
this.deletes.delete(partition);
|
|
186
|
+
this.lines.delete(partition);
|
|
187
|
+
}
|
|
188
|
+
for (const partition of [...touched].sort()) {
|
|
189
|
+
const file = this.file(partition);
|
|
190
|
+
if (!file || removedPartitions.includes(partition))
|
|
191
|
+
continue;
|
|
192
|
+
const previous = this.cache.get(partition) ?? new Map();
|
|
193
|
+
const bucket = grouped.get(partition) ?? [];
|
|
194
|
+
const present = new Set(bucket.map((entry) => this.idOf(entry.value)));
|
|
195
|
+
const added = bucket.filter((entry) => previous.get(this.idOf(entry.value)) !== entry.digest);
|
|
196
|
+
const removed = [...previous.keys()].filter((id) => !present.has(id));
|
|
197
|
+
if (!added.length && !removed.length)
|
|
198
|
+
continue;
|
|
199
|
+
rollback.set(file, await this.size(file));
|
|
200
|
+
const handle = await open(file, "a");
|
|
201
|
+
try {
|
|
202
|
+
let payload = "";
|
|
203
|
+
for (const entry of added)
|
|
204
|
+
payload += `${JSON.stringify({ v: 1, op: "upsert", value: entry.value })}\n`;
|
|
205
|
+
if (removed.length)
|
|
206
|
+
payload += `${JSON.stringify({ v: 1, op: "del", ids: removed })}\n`;
|
|
207
|
+
await handle.writeFile(payload);
|
|
208
|
+
await handle.sync();
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
await handle.close();
|
|
212
|
+
}
|
|
213
|
+
const cache = new Map();
|
|
214
|
+
for (const entry of bucket)
|
|
215
|
+
cache.set(this.idOf(entry.value), entry.digest);
|
|
216
|
+
this.cache.set(partition, cache);
|
|
217
|
+
const deletes = (this.deletes.get(partition) ?? 0) + removed.length;
|
|
218
|
+
const lines = (this.lines.get(partition) ?? previous.size) + added.length + (removed.length ? 1 : 0);
|
|
219
|
+
this.deletes.set(partition, deletes);
|
|
220
|
+
this.lines.set(partition, lines);
|
|
221
|
+
if (deletes >= this.maxDeletes || (this.retention && lines > this.retention * 2)) {
|
|
222
|
+
await this.rewrite(partition, bucket.map((entry) => entry.value));
|
|
223
|
+
this.deletes.set(partition, 0);
|
|
224
|
+
this.lines.set(partition, bucket.length);
|
|
225
|
+
// The file is a full snapshot now; rollback must not truncate it to the old append offset.
|
|
226
|
+
rollback.set(file, await this.size(file));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
for (const [file, size] of rollback)
|
|
232
|
+
await this.truncate(file, size).catch(() => { });
|
|
233
|
+
this.cache.clear();
|
|
234
|
+
this.deletes.clear();
|
|
235
|
+
this.lines.clear();
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async size(file) {
|
|
240
|
+
try {
|
|
241
|
+
const handle = await open(file, "r");
|
|
242
|
+
try {
|
|
243
|
+
return (await handle.stat()).size;
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
await handle.close();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
if (error.code === "ENOENT")
|
|
251
|
+
return 0;
|
|
252
|
+
throw error;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
async truncate(file, size) {
|
|
256
|
+
const handle = await open(file, "r+");
|
|
257
|
+
try {
|
|
258
|
+
await handle.truncate(size);
|
|
259
|
+
await handle.sync();
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
await handle.close();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async rewrite(partition, values) {
|
|
266
|
+
const file = this.file(partition);
|
|
267
|
+
if (!file)
|
|
268
|
+
return;
|
|
269
|
+
const temporary = `${file}.${createHash("sha1").update(`${Date.now()}:${Math.random()}`).digest("hex")}.tmp`;
|
|
270
|
+
const payload = values.map((value) => `${JSON.stringify({ v: 1, op: "upsert", value })}\n`).join("");
|
|
271
|
+
const handle = await open(temporary, "w", 0o600);
|
|
272
|
+
try {
|
|
273
|
+
await handle.writeFile(payload);
|
|
274
|
+
await handle.sync();
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
await handle.close();
|
|
278
|
+
}
|
|
279
|
+
await rename(temporary, file);
|
|
280
|
+
const cache = new Map();
|
|
281
|
+
for (const value of values)
|
|
282
|
+
cache.set(this.idOf(value), this.digest(value));
|
|
283
|
+
this.cache.set(partition, cache);
|
|
284
|
+
}
|
|
285
|
+
/** Re-read a partition after an external change (used by tests and failure recovery). */
|
|
286
|
+
async reload(partitions) {
|
|
287
|
+
for (const partition of partitions) {
|
|
288
|
+
this.cache.delete(partition);
|
|
289
|
+
this.deletes.delete(partition);
|
|
290
|
+
this.lines.delete(partition);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
@@ -44,8 +44,47 @@ export function createDeviceRuntime(options) {
|
|
|
44
44
|
hubUrl: config.hubUrl,
|
|
45
45
|
});
|
|
46
46
|
const reportOutbox = createTaskReportOutbox(options.dataDir, config.deviceId, config.hubUrl);
|
|
47
|
+
const schedulerFile = options.dataDir ? join(options.dataDir, "task-scheduler-state.json") : undefined;
|
|
48
|
+
let schedulerSaveTimer;
|
|
49
|
+
let schedulerStatePending = false;
|
|
50
|
+
function loadSchedulerState() {
|
|
51
|
+
if (!schedulerFile)
|
|
52
|
+
return undefined;
|
|
53
|
+
try {
|
|
54
|
+
return JSON.parse(readFileSync(schedulerFile, "utf8"));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// Corrupt or missing fairness state only means a restart starts with neutral fairness.
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function flushSchedulerState() {
|
|
62
|
+
if (!schedulerFile || !schedulerStatePending)
|
|
63
|
+
return;
|
|
64
|
+
schedulerStatePending = false;
|
|
65
|
+
try {
|
|
66
|
+
writeJsonAtomicSync(schedulerFile, scheduler.snapshotState());
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
/* fairness state is best-effort; never fail dispatch on persistence */
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function scheduleSchedulerStateSave() {
|
|
73
|
+
if (!schedulerFile)
|
|
74
|
+
return;
|
|
75
|
+
schedulerStatePending = true;
|
|
76
|
+
if (schedulerSaveTimer)
|
|
77
|
+
return;
|
|
78
|
+
schedulerSaveTimer = setTimeout(() => {
|
|
79
|
+
schedulerSaveTimer = undefined;
|
|
80
|
+
flushSchedulerState();
|
|
81
|
+
}, 250);
|
|
82
|
+
schedulerSaveTimer.unref?.();
|
|
83
|
+
}
|
|
47
84
|
const scheduler = new DeviceTaskScheduler({
|
|
48
85
|
initialSettings: loadExecutionSettings(options.dataDir),
|
|
86
|
+
persistedState: loadSchedulerState(),
|
|
87
|
+
onChange: scheduleSchedulerStateSave,
|
|
49
88
|
});
|
|
50
89
|
const conflicts = (a, b) => a.botId === b.botId || executionRootsOverlap(a.root, b.root);
|
|
51
90
|
function drain() {
|
|
@@ -126,6 +165,7 @@ export function createDeviceRuntime(options) {
|
|
|
126
165
|
.digest("hex")
|
|
127
166
|
.slice(0, 32);
|
|
128
167
|
const scopedDataDir = join(options.dataDir, "scoped-transfers", scopeToken);
|
|
168
|
+
const currentSettings = scheduler.getSettings();
|
|
129
169
|
entry = {
|
|
130
170
|
roomId,
|
|
131
171
|
botId,
|
|
@@ -134,6 +174,11 @@ export function createDeviceRuntime(options) {
|
|
|
134
174
|
root: lease.root,
|
|
135
175
|
dataDir: scopedDataDir,
|
|
136
176
|
allowReceive: config.allowExecution,
|
|
177
|
+
limits: {
|
|
178
|
+
bytes: currentSettings.fileSyncMaxBytes,
|
|
179
|
+
files: currentSettings.fileSyncMaxFiles,
|
|
180
|
+
stagedBytes: currentSettings.fileSyncStagedBytes,
|
|
181
|
+
},
|
|
137
182
|
}),
|
|
138
183
|
};
|
|
139
184
|
files.set(key, entry);
|
|
@@ -752,6 +797,10 @@ export function createDeviceRuntime(options) {
|
|
|
752
797
|
onDisconnect,
|
|
753
798
|
async close() {
|
|
754
799
|
closed = true;
|
|
800
|
+
if (schedulerSaveTimer)
|
|
801
|
+
clearTimeout(schedulerSaveTimer);
|
|
802
|
+
schedulerSaveTimer = undefined;
|
|
803
|
+
flushSchedulerState();
|
|
755
804
|
await onDisconnect({ abortTasks: true });
|
|
756
805
|
await Promise.allSettled([...files.values()].map((entry) => entry.files.close()));
|
|
757
806
|
files.clear();
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Temporary local preview runner; removed after browser validation.
|
|
2
|
+
import { startDeviceHub } from "./main.js";
|
|
3
|
+
await startDeviceHub({ ...process.env, PI_DEVICE_HUB_PUBLIC_URL: "http://127.0.0.1:18970", PI_DEVICE_HUB_DEVICE_DOMAIN: "devices.localhost:18970", PI_DEVICE_HUB_PORT: "18970", PI_DEVICE_HUB_DATA_DIR: process.env.TEMP + "/pi-device-hub-browser-preview", PI_DEVICE_HUB_ALLOW_REGISTRATION: "1" });
|