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
|
@@ -8,6 +8,7 @@ function project(message, start = 0, end = message.text.length) {
|
|
|
8
8
|
sender: { type: message.sender.type, id: message.sender.id, name: message.sender.name },
|
|
9
9
|
createdAt: message.createdAt,
|
|
10
10
|
...(message.targetBotIds ? { targetBotIds: message.targetBotIds } : {}),
|
|
11
|
+
...(message.replyToMessageId ? { replyToMessageId: message.replyToMessageId } : {}),
|
|
11
12
|
textStart: start,
|
|
12
13
|
textEnd: end,
|
|
13
14
|
fullTextLength: message.text.length,
|
|
@@ -95,8 +96,67 @@ export function groupHistoryPage(roomId, messages, before, budget = PAGE_BYTES)
|
|
|
95
96
|
}
|
|
96
97
|
return page;
|
|
97
98
|
}
|
|
99
|
+
/** Mention tokens look like `@Name` or `@Name(<uuid>)`; the canonical id form wins over a bare name. */
|
|
100
|
+
const MENTION = /@([^\s()@]+)(?:\(([A-Za-z0-9-]{8,})\))?/g;
|
|
101
|
+
/**
|
|
102
|
+
* Resolve human @mentions against current room membership. The Hub owns dispatch semantics: clients may
|
|
103
|
+
* send explicit target ids, but a message that only names Bots in its text must not silently fall back to
|
|
104
|
+
* the primary Bot. Ambiguous names (two members sharing one) are ignored rather than guessed.
|
|
105
|
+
*/
|
|
106
|
+
export function groupMentionTargets(text, room, bots, limit) {
|
|
107
|
+
const members = room.botIds
|
|
108
|
+
.map((id) => ({ id, name: bots.find((bot) => bot.id === id)?.name?.trim() ?? "" }))
|
|
109
|
+
.filter((member) => member.name.length > 0);
|
|
110
|
+
if (!members.length)
|
|
111
|
+
return [];
|
|
112
|
+
const hits = [];
|
|
113
|
+
for (const match of text.matchAll(MENTION)) {
|
|
114
|
+
const id = match[2];
|
|
115
|
+
const name = match[1];
|
|
116
|
+
const resolved = id
|
|
117
|
+
? members.find((member) => member.id === id)
|
|
118
|
+
: (() => {
|
|
119
|
+
const named = members.filter((member) => member.name === name);
|
|
120
|
+
return named.length === 1 ? named[0] : undefined;
|
|
121
|
+
})();
|
|
122
|
+
if (resolved && !hits.some((hit) => hit.id === resolved.id))
|
|
123
|
+
hits.push({ index: match.index ?? 0, id: resolved.id });
|
|
124
|
+
}
|
|
125
|
+
const sorted = hits.sort((a, b) => a.index - b.index).map((hit) => hit.id);
|
|
126
|
+
return limit && limit > 0 ? sorted.slice(0, limit) : sorted;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Compact verbose technical execution errors and internal stack traces to free up valuable context budget.
|
|
130
|
+
*/
|
|
131
|
+
export function compactHistoryNoise(text) {
|
|
132
|
+
if (!text.includes("Device task failed") && !text.includes("Error:") && !text.includes(" at ")) {
|
|
133
|
+
return text;
|
|
134
|
+
}
|
|
135
|
+
// Extract structured summary from Device task failed reports, stripping giant Node/V8 stack traces
|
|
136
|
+
const failMatch = text.match(/Device task failed\s*\[phase=([^;]+);\s*category=([^\]]+)\]\.\s*(.*)/s);
|
|
137
|
+
if (failMatch) {
|
|
138
|
+
const [, phase, category, detail] = failMatch;
|
|
139
|
+
// Keep up to first 300 chars of detail, stripping stack frames
|
|
140
|
+
const cleanDetail = detail
|
|
141
|
+
.split("\n")
|
|
142
|
+
.filter((line) => !line.trim().startsWith("at ") && !line.includes("node:internal"))
|
|
143
|
+
.join(" ")
|
|
144
|
+
.trim()
|
|
145
|
+
.slice(0, 300);
|
|
146
|
+
return `[Device task failed: phase=${phase}, category=${category}] ${cleanDetail || "Remote execution failed."}`;
|
|
147
|
+
}
|
|
148
|
+
// Strip giant stack frames from generic error logs in context
|
|
149
|
+
if (text.includes(" at ")) {
|
|
150
|
+
const lines = text.split("\n");
|
|
151
|
+
const filtered = lines.filter((l) => !l.trim().startsWith("at ") && !l.includes("node:internal"));
|
|
152
|
+
if (filtered.length < lines.length) {
|
|
153
|
+
return filtered.join("\n").trim();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return text;
|
|
157
|
+
}
|
|
98
158
|
/** Captured at dispatch, before any parallel recipient can publish a response. */
|
|
99
|
-
export function groupTaskContext(room, bots, messages) {
|
|
159
|
+
export function groupTaskContext(room, bots, messages, budget = GROUP_CONTEXT_BYTES) {
|
|
100
160
|
const members = room.botIds.map((id) => ({ id, name: bots.find((bot) => bot.id === id)?.name ?? id }));
|
|
101
161
|
const metadata = {
|
|
102
162
|
roomName: room.name,
|
|
@@ -104,6 +164,16 @@ export function groupTaskContext(room, bots, messages) {
|
|
|
104
164
|
members,
|
|
105
165
|
throughMessageId: messages.filter((message) => message.roomId === room.id).at(-1)?.id ?? null,
|
|
106
166
|
};
|
|
107
|
-
const
|
|
108
|
-
|
|
167
|
+
const blackboardPayload = room.blackboard ? { blackboard: room.blackboard } : {};
|
|
168
|
+
// Allocate budget hierarchically: reserve space for metadata and blackboard consensus first.
|
|
169
|
+
const nonHistoryBytes = Buffer.byteLength(JSON.stringify({ ...metadata, ...blackboardPayload })) + 64;
|
|
170
|
+
const historyBudget = Math.max(512, budget - nonHistoryBytes);
|
|
171
|
+
let page = groupHistoryPage(room.id, messages, undefined, historyBudget);
|
|
172
|
+
let result = { ...page, ...metadata, ...blackboardPayload };
|
|
173
|
+
// Ensure absolute compliance with the total budget ceiling even with JSON structure serialization overhead
|
|
174
|
+
while (Buffer.byteLength(JSON.stringify(result)) > budget && page.messages.length > 0) {
|
|
175
|
+
page = { ...page, messages: page.messages.slice(1), truncated: true };
|
|
176
|
+
result = { ...page, ...metadata, ...blackboardPayload };
|
|
177
|
+
}
|
|
178
|
+
return result;
|
|
109
179
|
}
|
|
@@ -1,5 +1,59 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { isTerminal, taskPending } from "./store.js";
|
|
3
|
+
/** Closed conversations kept per room for reading history; open ones are capacity, closed ones are archive. */
|
|
4
|
+
export const CLOSED_CONVERSATION_RETENTION = 200;
|
|
5
|
+
/** Idempotency receipts outlive message retention; replay must never re-dispatch evicted messages. */
|
|
6
|
+
export const ROOM_RECEIPT_RETENTION = 2000;
|
|
7
|
+
export const RECEIPT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
8
|
+
/** A conversation whose Bot registration no longer matches cannot continue; report it instead of a late 409. */
|
|
9
|
+
export function conversationStale(state, conversation) {
|
|
10
|
+
const bot = state.bots.find((b) => b.id === conversation.botId && b.accountId === conversation.accountId);
|
|
11
|
+
if (!bot || !bot.enabled || bot.revision !== conversation.botRevision || bot.deviceId !== conversation.deviceId)
|
|
12
|
+
return true;
|
|
13
|
+
const room = state.rooms.find((r) => r.id === conversation.roomId && r.accountId === conversation.accountId);
|
|
14
|
+
return !room || !room.botIds.includes(bot.id);
|
|
15
|
+
}
|
|
16
|
+
/** Delivery/review records are the audit trail; a conversation carrying them is never silently dropped. */
|
|
17
|
+
export function conversationHasAuditRecords(state, conversationId) {
|
|
18
|
+
return (state.deliveries.some((delivery) => delivery.conversationId === conversationId) ||
|
|
19
|
+
state.reviews.some((review) => review.conversationId === conversationId) ||
|
|
20
|
+
state.integrations.some((integration) => integration.conversationId === conversationId));
|
|
21
|
+
}
|
|
22
|
+
/** Delete every record scoped to one conversation. Never called for conversations with audit records. */
|
|
23
|
+
export function dropConversationRecords(state, conversationId) {
|
|
24
|
+
const taskIds = new Set(state.tasks.filter((task) => task.conversationId === conversationId).map((task) => task.id));
|
|
25
|
+
state.conversations = state.conversations.filter((conversation) => conversation.id !== conversationId);
|
|
26
|
+
state.tasks = state.tasks.filter((task) => !taskIds.has(task.id));
|
|
27
|
+
state.conversationMessages = state.conversationMessages.filter((message) => message.conversationId !== conversationId);
|
|
28
|
+
state.deliveryReceipts = state.deliveryReceipts.filter((receipt) => receipt.conversationId !== conversationId);
|
|
29
|
+
state.integrations = state.integrations.filter((integration) => integration.conversationId !== conversationId);
|
|
30
|
+
}
|
|
31
|
+
/** Bound the closed-conversation archive per room without touching auditable or still-running work. */
|
|
32
|
+
export function trimClosedConversations(state, roomId, limit = CLOSED_CONVERSATION_RETENTION) {
|
|
33
|
+
const closed = state.conversations
|
|
34
|
+
.filter((conversation) => conversation.roomId === roomId && conversation.closed)
|
|
35
|
+
.sort((a, b) => a.updatedAt - b.updatedAt);
|
|
36
|
+
if (closed.length <= limit)
|
|
37
|
+
return;
|
|
38
|
+
for (const conversation of closed.slice(0, closed.length - limit))
|
|
39
|
+
if (!conversationHasAuditRecords(state, conversation.id) &&
|
|
40
|
+
!state.tasks.some((task) => task.conversationId === conversation.id && taskPending(task)))
|
|
41
|
+
dropConversationRecords(state, conversation.id);
|
|
42
|
+
}
|
|
43
|
+
/** Receipts are the replay guard, so they must not be evicted by message retention. */
|
|
44
|
+
export function trimRoomReceipts(state, roomId, limit = ROOM_RECEIPT_RETENTION) {
|
|
45
|
+
const cutoff = Date.now() - RECEIPT_TTL_MS;
|
|
46
|
+
const stale = new Set(state.receipts
|
|
47
|
+
.filter((receipt) => receipt.roomId === roomId && receipt.createdAt !== undefined && receipt.createdAt < cutoff)
|
|
48
|
+
.map((receipt) => receipt.key));
|
|
49
|
+
if (stale.size)
|
|
50
|
+
state.receipts = state.receipts.filter((receipt) => !(receipt.roomId === roomId && stale.has(receipt.key)));
|
|
51
|
+
const room = state.receipts.filter((receipt) => receipt.roomId === roomId);
|
|
52
|
+
if (room.length <= limit)
|
|
53
|
+
return;
|
|
54
|
+
const drop = new Set(room.slice(0, room.length - limit));
|
|
55
|
+
state.receipts = state.receipts.filter((receipt) => !drop.has(receipt));
|
|
56
|
+
}
|
|
3
57
|
export function trimConversationHistory(state, roomId, limit = 500) {
|
|
4
58
|
const protectedIds = new Set();
|
|
5
59
|
for (const task of state.tasks.filter((t) => t.roomId === roomId && taskPending(t))) {
|
|
@@ -117,7 +171,7 @@ export function recordConversationTurn(state, task, key, fingerprint) {
|
|
|
117
171
|
});
|
|
118
172
|
}
|
|
119
173
|
/** A terminal child result creates one durable continuation. Its task is the delivery receipt. */
|
|
120
|
-
export function queueParentResult(state, child) {
|
|
174
|
+
export function queueParentResult(state, child, limits) {
|
|
121
175
|
if (child.cancelRequested ||
|
|
122
176
|
!isTerminal(child.status) ||
|
|
123
177
|
child.kind === "result" ||
|
|
@@ -143,8 +197,8 @@ export function queueParentResult(state, child) {
|
|
|
143
197
|
bot.deviceId !== conversation.deviceId ||
|
|
144
198
|
bot.revision !== conversation.botRevision ||
|
|
145
199
|
!state.rooms.some((room) => room.id === child.roomId && room.botIds.includes(bot.id)) ||
|
|
146
|
-
(root.dispatchCount ?? 0) >= 16 ||
|
|
147
|
-
(child.dispatchDepth ?? 0) >= 8)
|
|
200
|
+
(root.dispatchCount ?? 0) >= (limits?.maxDispatchBudget ?? 16) ||
|
|
201
|
+
(child.dispatchDepth ?? 0) >= (limits?.maxDispatchDepth ?? 8))
|
|
148
202
|
return;
|
|
149
203
|
root.dispatchCount = (root.dispatchCount ?? 0) + 1;
|
|
150
204
|
const now = Date.now();
|
|
@@ -169,6 +223,7 @@ export function queueParentResult(state, child) {
|
|
|
169
223
|
status: "queued",
|
|
170
224
|
createdAt: now,
|
|
171
225
|
updatedAt: now,
|
|
226
|
+
...(parent.attenuatedTools ? { attenuatedTools: [...parent.attenuatedTools] } : {}),
|
|
172
227
|
};
|
|
173
228
|
state.tasks.push(task);
|
|
174
229
|
advanceConversationTask(state, conversation, task);
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { writeJsonAtomicSync } from "../atomic-file.js";
|
|
3
|
+
import {} from "../protocol.js";
|
|
4
|
+
export const RESOURCE_LOCK_KEY_PATTERN = /^[a-zA-Z0-9_.:/-]+$/;
|
|
5
|
+
export const MAX_RESOURCE_LOCKS_PER_TASK = 10;
|
|
6
|
+
export const MAX_RESOURCE_LOCK_KEY_LENGTH = 256;
|
|
7
|
+
export const DEFAULT_RESOURCE_LOCK_TTL_MS = 10 * 60 * 1000;
|
|
8
|
+
export function isValidLockKey(key) {
|
|
9
|
+
if (typeof key !== "string")
|
|
10
|
+
return false;
|
|
11
|
+
const trimmed = key.trim();
|
|
12
|
+
if (trimmed.length < 1 || trimmed.length > MAX_RESOURCE_LOCK_KEY_LENGTH)
|
|
13
|
+
return false;
|
|
14
|
+
if (trimmed !== key)
|
|
15
|
+
return false;
|
|
16
|
+
return RESOURCE_LOCK_KEY_PATTERN.test(key);
|
|
17
|
+
}
|
|
18
|
+
export function validateResourceLocks(locks, maxLocks = MAX_RESOURCE_LOCKS_PER_TASK) {
|
|
19
|
+
if (locks === undefined || locks === null)
|
|
20
|
+
return [];
|
|
21
|
+
if (!Array.isArray(locks)) {
|
|
22
|
+
throw new Error("resourceLocks must be an array of strings");
|
|
23
|
+
}
|
|
24
|
+
if (locks.length > maxLocks) {
|
|
25
|
+
throw new Error(`resourceLocks cannot exceed ${maxLocks} items`);
|
|
26
|
+
}
|
|
27
|
+
const result = [];
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
for (const item of locks) {
|
|
30
|
+
if (typeof item !== "string" || !isValidLockKey(item)) {
|
|
31
|
+
throw new Error(`Invalid resource lock key: "${typeof item === "string" ? item : String(item)}". Lock key must be 1-256 characters matching ^[a-zA-Z0-9_.:/-]+$`);
|
|
32
|
+
}
|
|
33
|
+
if (!seen.has(item)) {
|
|
34
|
+
seen.add(item);
|
|
35
|
+
result.push(item);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
export class HubLockManager {
|
|
41
|
+
rooms = new Map();
|
|
42
|
+
defaultTtlMs;
|
|
43
|
+
persistPath;
|
|
44
|
+
timer;
|
|
45
|
+
constructor(options = {}) {
|
|
46
|
+
this.defaultTtlMs = options.defaultTtlMs ?? DEFAULT_RESOURCE_LOCK_TTL_MS;
|
|
47
|
+
this.persistPath = options.persistPath;
|
|
48
|
+
if (this.persistPath) {
|
|
49
|
+
this.loadFromDisk();
|
|
50
|
+
}
|
|
51
|
+
if (options.autoCleanupIntervalMs && options.autoCleanupIntervalMs > 0) {
|
|
52
|
+
this.timer = setInterval(() => {
|
|
53
|
+
this.cleanupExpiredLocks();
|
|
54
|
+
}, options.autoCleanupIntervalMs);
|
|
55
|
+
if (typeof this.timer.unref === "function") {
|
|
56
|
+
this.timer.unref();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
loadFromDisk() {
|
|
61
|
+
if (!this.persistPath)
|
|
62
|
+
return;
|
|
63
|
+
try {
|
|
64
|
+
const raw = readFileSync(this.persistPath, "utf8");
|
|
65
|
+
const parsed = JSON.parse(raw);
|
|
66
|
+
if (parsed && typeof parsed === "object" && parsed.rooms) {
|
|
67
|
+
const now = Date.now();
|
|
68
|
+
for (const [roomId, serialized] of Object.entries(parsed.rooms)) {
|
|
69
|
+
const roomState = {
|
|
70
|
+
activeLocks: new Map(),
|
|
71
|
+
taskLocks: new Map(),
|
|
72
|
+
waitingQueue: Array.isArray(serialized.waitingQueue) ? serialized.waitingQueue : [],
|
|
73
|
+
};
|
|
74
|
+
if (Array.isArray(serialized.activeLocks)) {
|
|
75
|
+
for (const lock of serialized.activeLocks) {
|
|
76
|
+
if (lock && lock.lockKey && lock.expiresAt > now) {
|
|
77
|
+
roomState.activeLocks.set(lock.lockKey, lock);
|
|
78
|
+
let taskHeld = roomState.taskLocks.get(lock.taskId);
|
|
79
|
+
if (!taskHeld) {
|
|
80
|
+
taskHeld = new Set();
|
|
81
|
+
roomState.taskLocks.set(lock.taskId, taskHeld);
|
|
82
|
+
}
|
|
83
|
+
taskHeld.add(lock.lockKey);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
this.rooms.set(roomId, roomState);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code !== "ENOENT") {
|
|
93
|
+
// Ignore parse error on corrupt file, start fresh
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
saveToDisk() {
|
|
98
|
+
if (!this.persistPath)
|
|
99
|
+
return;
|
|
100
|
+
try {
|
|
101
|
+
const serializedRooms = {};
|
|
102
|
+
for (const [roomId, state] of this.rooms.entries()) {
|
|
103
|
+
if (state.activeLocks.size > 0 || state.waitingQueue.length > 0) {
|
|
104
|
+
serializedRooms[roomId] = {
|
|
105
|
+
activeLocks: Array.from(state.activeLocks.values()),
|
|
106
|
+
waitingQueue: [...state.waitingQueue],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
writeJsonAtomicSync(this.persistPath, { version: 1, updatedAt: Date.now(), rooms: serializedRooms });
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// Best-effort atomic persist
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
getOrCreateRoom(roomId) {
|
|
117
|
+
let state = this.rooms.get(roomId);
|
|
118
|
+
if (!state) {
|
|
119
|
+
state = {
|
|
120
|
+
activeLocks: new Map(),
|
|
121
|
+
taskLocks: new Map(),
|
|
122
|
+
waitingQueue: [],
|
|
123
|
+
};
|
|
124
|
+
this.rooms.set(roomId, state);
|
|
125
|
+
}
|
|
126
|
+
return state;
|
|
127
|
+
}
|
|
128
|
+
acquireLocks(options) {
|
|
129
|
+
const now = options.now ?? Date.now();
|
|
130
|
+
const ttlMs = options.ttlMs ?? this.defaultTtlMs;
|
|
131
|
+
const locks = validateResourceLocks(options.resourceLocks);
|
|
132
|
+
if (locks.length === 0) {
|
|
133
|
+
return { success: true, conflictingLocks: [], holderTaskIds: [] };
|
|
134
|
+
}
|
|
135
|
+
this.cleanupExpiredLocks(options.roomId, now);
|
|
136
|
+
const roomState = this.getOrCreateRoom(options.roomId);
|
|
137
|
+
const conflictingLocks = [];
|
|
138
|
+
const holderTaskIds = new Set();
|
|
139
|
+
for (const key of locks) {
|
|
140
|
+
const held = roomState.activeLocks.get(key);
|
|
141
|
+
if (held && held.expiresAt > now && held.taskId !== options.taskId) {
|
|
142
|
+
conflictingLocks.push(key);
|
|
143
|
+
holderTaskIds.add(held.taskId);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (conflictingLocks.length > 0) {
|
|
147
|
+
const existingIndex = roomState.waitingQueue.findIndex((w) => w.taskId === options.taskId);
|
|
148
|
+
if (existingIndex >= 0) {
|
|
149
|
+
roomState.waitingQueue[existingIndex].lockKeys = locks;
|
|
150
|
+
roomState.waitingQueue[existingIndex].botId = options.botId;
|
|
151
|
+
}
|
|
152
|
+
else {
|
|
153
|
+
roomState.waitingQueue.push({
|
|
154
|
+
taskId: options.taskId,
|
|
155
|
+
roomId: options.roomId,
|
|
156
|
+
botId: options.botId,
|
|
157
|
+
lockKeys: locks,
|
|
158
|
+
queuedAt: now,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
this.saveToDisk();
|
|
162
|
+
return {
|
|
163
|
+
success: false,
|
|
164
|
+
conflictingLocks,
|
|
165
|
+
holderTaskIds: Array.from(holderTaskIds),
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
// No conflicts: acquire locks
|
|
169
|
+
const waiterIndex = roomState.waitingQueue.findIndex((w) => w.taskId === options.taskId);
|
|
170
|
+
if (waiterIndex >= 0) {
|
|
171
|
+
roomState.waitingQueue.splice(waiterIndex, 1);
|
|
172
|
+
}
|
|
173
|
+
let taskHeld = roomState.taskLocks.get(options.taskId);
|
|
174
|
+
if (!taskHeld) {
|
|
175
|
+
taskHeld = new Set();
|
|
176
|
+
roomState.taskLocks.set(options.taskId, taskHeld);
|
|
177
|
+
}
|
|
178
|
+
for (const key of locks) {
|
|
179
|
+
const activeLock = {
|
|
180
|
+
lockKey: key,
|
|
181
|
+
roomId: options.roomId,
|
|
182
|
+
taskId: options.taskId,
|
|
183
|
+
botId: options.botId,
|
|
184
|
+
...(options.deviceId ? { deviceId: options.deviceId } : {}),
|
|
185
|
+
acquiredAt: now,
|
|
186
|
+
expiresAt: now + ttlMs,
|
|
187
|
+
};
|
|
188
|
+
roomState.activeLocks.set(key, activeLock);
|
|
189
|
+
taskHeld.add(key);
|
|
190
|
+
}
|
|
191
|
+
this.saveToDisk();
|
|
192
|
+
return { success: true, conflictingLocks: [], holderTaskIds: [] };
|
|
193
|
+
}
|
|
194
|
+
releaseLocks(roomId, taskId, now = Date.now()) {
|
|
195
|
+
const roomState = this.rooms.get(roomId);
|
|
196
|
+
if (!roomState)
|
|
197
|
+
return [];
|
|
198
|
+
const heldKeys = roomState.taskLocks.get(taskId);
|
|
199
|
+
if (heldKeys) {
|
|
200
|
+
for (const key of heldKeys) {
|
|
201
|
+
const current = roomState.activeLocks.get(key);
|
|
202
|
+
if (current?.taskId === taskId) {
|
|
203
|
+
roomState.activeLocks.delete(key);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
roomState.taskLocks.delete(taskId);
|
|
207
|
+
}
|
|
208
|
+
const waiterIndex = roomState.waitingQueue.findIndex((w) => w.taskId === taskId);
|
|
209
|
+
if (waiterIndex >= 0) {
|
|
210
|
+
roomState.waitingQueue.splice(waiterIndex, 1);
|
|
211
|
+
}
|
|
212
|
+
const promoted = this.promoteWaitingTasks(roomId, now);
|
|
213
|
+
this.saveToDisk();
|
|
214
|
+
return promoted;
|
|
215
|
+
}
|
|
216
|
+
removeWaiter(roomId, taskId) {
|
|
217
|
+
const roomState = this.rooms.get(roomId);
|
|
218
|
+
if (!roomState)
|
|
219
|
+
return false;
|
|
220
|
+
const index = roomState.waitingQueue.findIndex((w) => w.taskId === taskId);
|
|
221
|
+
if (index >= 0) {
|
|
222
|
+
roomState.waitingQueue.splice(index, 1);
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
cleanupExpiredLocks(roomId, now = Date.now()) {
|
|
228
|
+
const promotedAll = [];
|
|
229
|
+
const roomIds = roomId ? [roomId] : Array.from(this.rooms.keys());
|
|
230
|
+
for (const rId of roomIds) {
|
|
231
|
+
const roomState = this.rooms.get(rId);
|
|
232
|
+
if (!roomState)
|
|
233
|
+
continue;
|
|
234
|
+
let expiredAny = false;
|
|
235
|
+
for (const [key, lock] of Array.from(roomState.activeLocks.entries())) {
|
|
236
|
+
if (lock.expiresAt <= now) {
|
|
237
|
+
roomState.activeLocks.delete(key);
|
|
238
|
+
const taskHeld = roomState.taskLocks.get(lock.taskId);
|
|
239
|
+
if (taskHeld) {
|
|
240
|
+
taskHeld.delete(key);
|
|
241
|
+
if (taskHeld.size === 0) {
|
|
242
|
+
roomState.taskLocks.delete(lock.taskId);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
expiredAny = true;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (expiredAny) {
|
|
249
|
+
const promoted = this.promoteWaitingTasks(rId, now);
|
|
250
|
+
promotedAll.push(...promoted);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return promotedAll;
|
|
254
|
+
}
|
|
255
|
+
promoteWaitingTasks(roomId, now = Date.now()) {
|
|
256
|
+
const roomState = this.rooms.get(roomId);
|
|
257
|
+
if (!roomState || roomState.waitingQueue.length === 0)
|
|
258
|
+
return [];
|
|
259
|
+
const promoted = [];
|
|
260
|
+
const remainingWaiters = [];
|
|
261
|
+
for (const waiter of roomState.waitingQueue) {
|
|
262
|
+
let canAcquire = true;
|
|
263
|
+
for (const key of waiter.lockKeys) {
|
|
264
|
+
const held = roomState.activeLocks.get(key);
|
|
265
|
+
if (held && held.expiresAt > now && held.taskId !== waiter.taskId) {
|
|
266
|
+
canAcquire = false;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
if (canAcquire) {
|
|
271
|
+
let taskHeld = roomState.taskLocks.get(waiter.taskId);
|
|
272
|
+
if (!taskHeld) {
|
|
273
|
+
taskHeld = new Set();
|
|
274
|
+
roomState.taskLocks.set(waiter.taskId, taskHeld);
|
|
275
|
+
}
|
|
276
|
+
for (const key of waiter.lockKeys) {
|
|
277
|
+
const activeLock = {
|
|
278
|
+
lockKey: key,
|
|
279
|
+
roomId,
|
|
280
|
+
taskId: waiter.taskId,
|
|
281
|
+
botId: waiter.botId,
|
|
282
|
+
acquiredAt: now,
|
|
283
|
+
expiresAt: now + this.defaultTtlMs,
|
|
284
|
+
};
|
|
285
|
+
roomState.activeLocks.set(key, activeLock);
|
|
286
|
+
taskHeld.add(key);
|
|
287
|
+
}
|
|
288
|
+
promoted.push(waiter.taskId);
|
|
289
|
+
}
|
|
290
|
+
else {
|
|
291
|
+
remainingWaiters.push(waiter);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
roomState.waitingQueue = remainingWaiters;
|
|
295
|
+
return promoted;
|
|
296
|
+
}
|
|
297
|
+
clearRoom(roomId) {
|
|
298
|
+
this.rooms.delete(roomId);
|
|
299
|
+
this.saveToDisk();
|
|
300
|
+
}
|
|
301
|
+
getRoomLockInfo(roomId, now = Date.now()) {
|
|
302
|
+
this.cleanupExpiredLocks(roomId, now);
|
|
303
|
+
const roomState = this.rooms.get(roomId);
|
|
304
|
+
return {
|
|
305
|
+
roomId,
|
|
306
|
+
activeLocks: roomState ? Array.from(roomState.activeLocks.values()) : [],
|
|
307
|
+
waitingQueue: roomState ? [...roomState.waitingQueue] : [],
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
close() {
|
|
311
|
+
if (this.timer) {
|
|
312
|
+
clearInterval(this.timer);
|
|
313
|
+
this.timer = undefined;
|
|
314
|
+
}
|
|
315
|
+
this.rooms.clear();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
export function createHubLockManager(options) {
|
|
319
|
+
return new HubLockManager(options);
|
|
320
|
+
}
|