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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
1
2
|
import express from "express";
|
|
2
3
|
import { validInteractionAnswer, validInteractionProjection } from "./human-interaction.js";
|
|
3
4
|
import { createGroupEvents } from "./group-events.js";
|
|
@@ -12,10 +13,14 @@ import { createServer } from "node:http";
|
|
|
12
13
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
13
14
|
import { DeviceHubStore, hashSecret, isTerminal, taskPending, publicDevice, publicTask, secretMatches, } from "./store.js";
|
|
14
15
|
import { atomicApproveGroupPlan } from "./group-plan-guard.js";
|
|
16
|
+
import { computeAttenuatedTools } from "./bot-execution.js";
|
|
15
17
|
import { validateTaskPlan } from "./task-plan.js";
|
|
16
|
-
import {
|
|
18
|
+
import { ALLOWED_WEBHOOK_EVENTS, createWebhookToken, dispatchGroupWebhook, isIncomingWebhookRequest, secureCompareTokens, testOutgoingWebhook, validateWebhookInput, } from "./hub-webhooks.js";
|
|
19
|
+
import { GROUP_RETENTION_LIMIT, groupHistoryPage, groupMentionTargets, groupTaskContext, } from "./group-context.js";
|
|
20
|
+
import { createHubLockManager, validateResourceLocks } from "./hub-locks.js";
|
|
17
21
|
import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
|
|
18
|
-
import { establishConversation, advanceConversationTask, nextConversationTask, recordConversationTurn, conversationStatus, queueParentResult, conversationPage, trimConversationHistory, } from "./hub-conversations.js";
|
|
22
|
+
import { establishConversation, advanceConversationTask, nextConversationTask, recordConversationTurn, conversationStatus, queueParentResult, conversationPage, trimConversationHistory, conversationStale, conversationHasAuditRecords, dropConversationRecords, trimClosedConversations, trimRoomReceipts, } from "./hub-conversations.js";
|
|
23
|
+
import { DEFAULT_EXECUTION_SETTINGS } from "./execution-settings.js";
|
|
19
24
|
class HttpError extends Error {
|
|
20
25
|
status;
|
|
21
26
|
constructor(status, message) {
|
|
@@ -56,6 +61,10 @@ const token = () => randomBytes(32).toString("base64url");
|
|
|
56
61
|
const PAIR_TTL = 10 * 60 * 1000;
|
|
57
62
|
const HISTORY = GROUP_RETENTION_LIMIT;
|
|
58
63
|
export async function createDeviceHub(options) {
|
|
64
|
+
function currentSettings() {
|
|
65
|
+
return options.getSettings?.() ?? options.settings ?? DEFAULT_EXECUTION_SETTINGS;
|
|
66
|
+
}
|
|
67
|
+
const getHistoryLimit = () => currentSettings().groupRetentionLimit ?? GROUP_RETENTION_LIMIT;
|
|
59
68
|
const origin = new URL(options.publicUrl);
|
|
60
69
|
if (!["http:", "https:"].includes(origin.protocol) ||
|
|
61
70
|
origin.pathname !== "/" ||
|
|
@@ -124,20 +133,23 @@ export async function createDeviceHub(options) {
|
|
|
124
133
|
const suffix = req.path.slice("/api/device-user".length);
|
|
125
134
|
const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)?$/.test(suffix);
|
|
126
135
|
const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
|
|
136
|
+
const webhookRoute = /^\/rooms\/[^/]+\/(?:webhooks(?:\/[^/]+(?:\/(?:delete|regenerate-token|test))?)?|hub-relay)$/.test(suffix);
|
|
127
137
|
if (!((req.method === "GET" &&
|
|
128
138
|
(conversationRoute ||
|
|
129
139
|
taskRoute ||
|
|
130
|
-
|
|
140
|
+
webhookRoute ||
|
|
141
|
+
/^\/rooms\/[^/]+\/(?:events|interactions|transfers|locks|blackboard)$/.test(suffix) ||
|
|
131
142
|
/^\/rooms\/[^/]+\/transfers\/[^/]+\/preview$/.test(suffix) ||
|
|
132
143
|
["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
133
144
|
/^\/rooms\/[^/]+$/.test(suffix))) ||
|
|
134
|
-
(req.method
|
|
145
|
+
(["POST", "PUT"].includes(req.method) &&
|
|
135
146
|
(suffix === "/rooms" ||
|
|
136
147
|
conversationRoute ||
|
|
137
|
-
|
|
148
|
+
webhookRoute ||
|
|
149
|
+
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard)$/.test(suffix) ||
|
|
138
150
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
|
|
139
151
|
/^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
|
|
140
|
-
/^\/devices\/[^/]+\/open$/.test(suffix)))))
|
|
152
|
+
/^\/devices\/[^/]+\/(open|remark)$/.test(suffix)))))
|
|
141
153
|
fail(404, "User route missing");
|
|
142
154
|
users.set(req, { device, account: { id: owner.id, username: owner.username } });
|
|
143
155
|
req.url = req.url.replace("/api/device-user/", "/api/");
|
|
@@ -156,21 +168,23 @@ export async function createDeviceHub(options) {
|
|
|
156
168
|
const suffix = req.path.slice("/api/agent".length);
|
|
157
169
|
if ((req.method === "GET" &&
|
|
158
170
|
(["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
159
|
-
/^\/rooms\/[^/]+(?:\/history)?$/.test(suffix) ||
|
|
171
|
+
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard))?$/.test(suffix) ||
|
|
160
172
|
/^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
|
|
161
173
|
(req.method === "POST" &&
|
|
162
174
|
(suffix === "/rooms" ||
|
|
163
175
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(suffix) ||
|
|
164
|
-
/^\/rooms\/[^/]+\/(?:messages|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix)))
|
|
176
|
+
/^\/rooms\/[^/]+\/(?:messages|blackboard|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix))) ||
|
|
177
|
+
(req.method === "PUT" && /^\/rooms\/[^/]+\/blackboard$/.test(suffix)))
|
|
165
178
|
req.url = req.url.replace("/api/agent/", "/api/");
|
|
166
179
|
else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
|
|
167
180
|
fail(404, "Agent route missing");
|
|
168
181
|
next();
|
|
169
182
|
});
|
|
170
183
|
app.use((req, res, next) => {
|
|
171
|
-
if (req.headers.host !== origin.host)
|
|
184
|
+
if (!isIncomingWebhookRequest(req) && req.headers.host !== origin.host)
|
|
172
185
|
return res.status(421).json({ error: "Host rejected" });
|
|
173
|
-
if (!
|
|
186
|
+
if (!isIncomingWebhookRequest(req) &&
|
|
187
|
+
!agents.has(req) &&
|
|
174
188
|
!users.has(req) &&
|
|
175
189
|
!["GET", "HEAD", "OPTIONS"].includes(req.method) &&
|
|
176
190
|
req.headers.origin !== options.publicUrl)
|
|
@@ -178,6 +192,7 @@ export async function createDeviceHub(options) {
|
|
|
178
192
|
next();
|
|
179
193
|
});
|
|
180
194
|
const json = express.json({ limit: "32kb", strict: true });
|
|
195
|
+
const blackboardJson = express.json({ limit: "512kb", strict: true });
|
|
181
196
|
const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
|
|
182
197
|
const reportWrites = new HubRateLimiter(4096, 60000);
|
|
183
198
|
app.use((req, res, next) => {
|
|
@@ -188,6 +203,10 @@ export async function createDeviceHub(options) {
|
|
|
188
203
|
return res.status(429).json({ error: "Too many report chunks" });
|
|
189
204
|
return reportJson(req, res, next);
|
|
190
205
|
}
|
|
206
|
+
if ((req.method === "PUT" || req.method === "POST") &&
|
|
207
|
+
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard$/.test(req.path)) {
|
|
208
|
+
return blackboardJson(req, res, next);
|
|
209
|
+
}
|
|
191
210
|
json(req, res, next);
|
|
192
211
|
});
|
|
193
212
|
const loginLimit = new HubRateLimiter(10, 60000);
|
|
@@ -198,11 +217,17 @@ export async function createDeviceHub(options) {
|
|
|
198
217
|
if (value.expiresAt <= Date.now())
|
|
199
218
|
pairs.delete(key);
|
|
200
219
|
};
|
|
220
|
+
const lockManager = createHubLockManager({
|
|
221
|
+
autoCleanupIntervalMs: 60000,
|
|
222
|
+
defaultTtlMs: currentSettings().resourceLockDefaultTtlMs,
|
|
223
|
+
persistPath: options.dataDir ? join(options.dataDir, "hub-locks.json") : undefined,
|
|
224
|
+
});
|
|
201
225
|
const ip = (req) => req.socket.remoteAddress ?? "unknown";
|
|
202
226
|
const visibleDevice = (device) => ({
|
|
203
227
|
id: device.id,
|
|
204
228
|
accountId: device.accountId,
|
|
205
229
|
name: device.name,
|
|
230
|
+
remark: device.remark ?? null,
|
|
206
231
|
createdAt: device.createdAt,
|
|
207
232
|
online: options.isOnline?.(device.id) ?? false,
|
|
208
233
|
url: (options.pathAccess ? `${origin.origin}/device/${encodeURIComponent(device.id)}/` : undefined) ??
|
|
@@ -363,6 +388,14 @@ export async function createDeviceHub(options) {
|
|
|
363
388
|
if (room.primaryBotId && removedBots.has(room.primaryBotId))
|
|
364
389
|
delete room.primaryBotId;
|
|
365
390
|
}
|
|
391
|
+
// A revoked device can no longer continue its conversations: close them now so the next turn
|
|
392
|
+
// reports a reason instead of a late 409 against a Bot that no longer exists.
|
|
393
|
+
for (const conversation of draft.conversations)
|
|
394
|
+
if (!conversation.closed && removedBots.has(conversation.botId)) {
|
|
395
|
+
conversation.closed = true;
|
|
396
|
+
conversation.closedReason = "device_revoked";
|
|
397
|
+
conversation.updatedAt = Date.now();
|
|
398
|
+
}
|
|
366
399
|
for (const task of draft.tasks)
|
|
367
400
|
if (task.deviceId === id && !isTerminal(task.status)) {
|
|
368
401
|
task.status = "interrupted";
|
|
@@ -638,6 +671,456 @@ export async function createDeviceHub(options) {
|
|
|
638
671
|
app.get("/api/rooms/:id/events", (req, res) => {
|
|
639
672
|
groupEvents.connect(account(req).id, String(req.params.id), res, users.get(req)?.device.id);
|
|
640
673
|
});
|
|
674
|
+
app.get("/api/rooms/:id/locks", (req, res) => {
|
|
675
|
+
const state = store.snapshot();
|
|
676
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
|
|
677
|
+
if (!room ||
|
|
678
|
+
(agents.has(req) &&
|
|
679
|
+
!state.bots.some((b) => b.enabled &&
|
|
680
|
+
b.deviceId === agents.get(req).device.id &&
|
|
681
|
+
b.accountId === room.accountId &&
|
|
682
|
+
room.botIds.includes(b.id))))
|
|
683
|
+
fail(404, "Room missing");
|
|
684
|
+
res.json(lockManager.getRoomLockInfo(room.id));
|
|
685
|
+
});
|
|
686
|
+
app.get("/api/rooms/:id/blackboard", (req, res) => {
|
|
687
|
+
const owner = account(req);
|
|
688
|
+
const state = store.snapshot();
|
|
689
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
690
|
+
if (!room)
|
|
691
|
+
fail(404, "Room missing");
|
|
692
|
+
if (agents.has(req)) {
|
|
693
|
+
const agent = agents.get(req);
|
|
694
|
+
const sourceBotId = (req.query.sourceBotId ?? req.body?.sourceBotId);
|
|
695
|
+
if (!sourceBotId)
|
|
696
|
+
fail(403, "Source Bot required");
|
|
697
|
+
const source = state.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
698
|
+
if (!source)
|
|
699
|
+
fail(403, "Source Bot access denied");
|
|
700
|
+
if (!room.botIds.includes(source.id))
|
|
701
|
+
fail(403, "Source Bot is not a room member");
|
|
702
|
+
}
|
|
703
|
+
res.json({ blackboard: room.blackboard ?? null });
|
|
704
|
+
});
|
|
705
|
+
const handleBlackboardUpdate = async (req, res) => {
|
|
706
|
+
const owner = account(req);
|
|
707
|
+
const { content, expectedVersion, title } = req.body ?? {};
|
|
708
|
+
const settings = currentSettings();
|
|
709
|
+
if (typeof content !== "string" || !content.trim())
|
|
710
|
+
fail(400, "Content must be a nonempty string");
|
|
711
|
+
if (Buffer.byteLength(content, "utf8") > settings.blackboardMaxBytes)
|
|
712
|
+
fail(400, `Content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
713
|
+
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content))
|
|
714
|
+
fail(400, "Content must not contain control characters");
|
|
715
|
+
if (typeof expectedVersion !== "number" || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0) {
|
|
716
|
+
fail(400, "expectedVersion must be a non-negative safe integer");
|
|
717
|
+
}
|
|
718
|
+
if (title !== undefined) {
|
|
719
|
+
if (typeof title !== "string" || title.length > 200 || /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(title)) {
|
|
720
|
+
fail(400, "Invalid title");
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
let updatedBy;
|
|
724
|
+
const stateBefore = store.snapshot();
|
|
725
|
+
if (agents.has(req)) {
|
|
726
|
+
const agent = agents.get(req);
|
|
727
|
+
const sourceBotId = (req.body?.sourceBotId ?? req.query?.sourceBotId);
|
|
728
|
+
if (!sourceBotId)
|
|
729
|
+
fail(403, "Source Bot required");
|
|
730
|
+
const source = stateBefore.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
731
|
+
if (!source)
|
|
732
|
+
fail(403, "Source Bot access denied");
|
|
733
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
734
|
+
if (!preRoom)
|
|
735
|
+
fail(404, "Room missing");
|
|
736
|
+
if (!preRoom.botIds.includes(source.id))
|
|
737
|
+
fail(403, "Source Bot is not a room member");
|
|
738
|
+
updatedBy = { type: "bot", id: source.id, name: source.name };
|
|
739
|
+
}
|
|
740
|
+
else {
|
|
741
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
742
|
+
if (!preRoom)
|
|
743
|
+
fail(404, "Room missing");
|
|
744
|
+
updatedBy = { type: "human", id: owner.id, name: owner.username };
|
|
745
|
+
}
|
|
746
|
+
const updatedBlackboard = await store.transact((draft) => {
|
|
747
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
748
|
+
if (!room)
|
|
749
|
+
fail(404, "Room missing");
|
|
750
|
+
if (agents.has(req) && !room.botIds.includes(updatedBy.id))
|
|
751
|
+
fail(403, "Source Bot is not a room member");
|
|
752
|
+
const current = room.blackboard;
|
|
753
|
+
if (current) {
|
|
754
|
+
if (current.version !== expectedVersion)
|
|
755
|
+
fail(409, "Version conflict");
|
|
756
|
+
}
|
|
757
|
+
else {
|
|
758
|
+
if (expectedVersion !== 0)
|
|
759
|
+
fail(409, "Version conflict");
|
|
760
|
+
}
|
|
761
|
+
const nextVersion = current ? current.version + 1 : 1;
|
|
762
|
+
const nextBlackboard = {
|
|
763
|
+
version: nextVersion,
|
|
764
|
+
updatedAt: Date.now(),
|
|
765
|
+
updatedBy,
|
|
766
|
+
...(title?.trim() ? { title: title.trim() } : {}),
|
|
767
|
+
content,
|
|
768
|
+
};
|
|
769
|
+
room.blackboard = nextBlackboard;
|
|
770
|
+
return nextBlackboard;
|
|
771
|
+
});
|
|
772
|
+
groupEvents.invalidate(String(req.params.id));
|
|
773
|
+
res.json({ ok: true, blackboard: updatedBlackboard });
|
|
774
|
+
};
|
|
775
|
+
app.put("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
776
|
+
app.post("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
777
|
+
// === Group Webhooks ===
|
|
778
|
+
app.get("/api/rooms/:id/webhooks", (req, res) => {
|
|
779
|
+
const owner = account(req);
|
|
780
|
+
if (agents.has(req))
|
|
781
|
+
fail(403, "Webhook management requires a user session");
|
|
782
|
+
const state = store.snapshot();
|
|
783
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
784
|
+
if (!room)
|
|
785
|
+
fail(404, "Room missing");
|
|
786
|
+
res.setHeader("Cache-Control", "no-store");
|
|
787
|
+
res.json({ webhooks: room.webhooks ?? [] });
|
|
788
|
+
});
|
|
789
|
+
app.post("/api/rooms/:id/webhooks", async (req, res) => {
|
|
790
|
+
const owner = account(req);
|
|
791
|
+
if (agents.has(req))
|
|
792
|
+
fail(403, "Webhook management requires a user session");
|
|
793
|
+
const validated = validateWebhookInput(req.body, false);
|
|
794
|
+
let created;
|
|
795
|
+
await store.transact((state) => {
|
|
796
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
797
|
+
if (!room)
|
|
798
|
+
fail(404, "Room missing");
|
|
799
|
+
if (!room.webhooks)
|
|
800
|
+
room.webhooks = [];
|
|
801
|
+
if (room.webhooks.length >= 32)
|
|
802
|
+
fail(409, "Maximum webhooks limit reached");
|
|
803
|
+
const now = Date.now();
|
|
804
|
+
created = {
|
|
805
|
+
id: randomUUID(),
|
|
806
|
+
roomId: room.id,
|
|
807
|
+
name: validated.name,
|
|
808
|
+
type: validated.type,
|
|
809
|
+
enabled: validated.enabled ?? true,
|
|
810
|
+
createdAt: now,
|
|
811
|
+
updatedAt: now,
|
|
812
|
+
...(validated.type === "incoming"
|
|
813
|
+
? {
|
|
814
|
+
token: createWebhookToken(),
|
|
815
|
+
allowBotTrigger: validated.allowBotTrigger ?? true,
|
|
816
|
+
}
|
|
817
|
+
: {
|
|
818
|
+
url: validated.url,
|
|
819
|
+
secret: validated.secret,
|
|
820
|
+
events: validated.events ?? [...ALLOWED_WEBHOOK_EVENTS],
|
|
821
|
+
relayViaHub: validated.relayViaHub ?? true,
|
|
822
|
+
}),
|
|
823
|
+
};
|
|
824
|
+
room.webhooks.push(created);
|
|
825
|
+
});
|
|
826
|
+
groupEvents.invalidate(String(req.params.id));
|
|
827
|
+
res.json({ webhook: created });
|
|
828
|
+
});
|
|
829
|
+
const handleWebhookUpdate = async (req, res) => {
|
|
830
|
+
const owner = account(req);
|
|
831
|
+
if (agents.has(req))
|
|
832
|
+
fail(403, "Webhook management requires a user session");
|
|
833
|
+
const validated = validateWebhookInput(req.body, true);
|
|
834
|
+
let updated;
|
|
835
|
+
await store.transact((state) => {
|
|
836
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
837
|
+
if (!room)
|
|
838
|
+
fail(404, "Room missing");
|
|
839
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
840
|
+
if (!hook)
|
|
841
|
+
fail(404, "Webhook missing");
|
|
842
|
+
if (validated.name !== undefined)
|
|
843
|
+
hook.name = validated.name;
|
|
844
|
+
if (validated.enabled !== undefined)
|
|
845
|
+
hook.enabled = validated.enabled;
|
|
846
|
+
if (hook.type === "incoming") {
|
|
847
|
+
if (validated.allowBotTrigger !== undefined)
|
|
848
|
+
hook.allowBotTrigger = validated.allowBotTrigger;
|
|
849
|
+
}
|
|
850
|
+
else {
|
|
851
|
+
if (validated.url !== undefined)
|
|
852
|
+
hook.url = validated.url;
|
|
853
|
+
if (validated.secret !== undefined)
|
|
854
|
+
hook.secret = validated.secret;
|
|
855
|
+
if (validated.events !== undefined)
|
|
856
|
+
hook.events = validated.events;
|
|
857
|
+
if (validated.relayViaHub !== undefined)
|
|
858
|
+
hook.relayViaHub = validated.relayViaHub;
|
|
859
|
+
}
|
|
860
|
+
hook.updatedAt = Date.now();
|
|
861
|
+
updated = hook;
|
|
862
|
+
});
|
|
863
|
+
groupEvents.invalidate(String(req.params.id));
|
|
864
|
+
res.json({ webhook: updated });
|
|
865
|
+
};
|
|
866
|
+
app.put("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
|
|
867
|
+
app.post("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
|
|
868
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/regenerate-token", async (req, res) => {
|
|
869
|
+
const owner = account(req);
|
|
870
|
+
if (agents.has(req))
|
|
871
|
+
fail(403, "Webhook management requires a user session");
|
|
872
|
+
let updated;
|
|
873
|
+
await store.transact((state) => {
|
|
874
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
875
|
+
if (!room)
|
|
876
|
+
fail(404, "Room missing");
|
|
877
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
878
|
+
if (!hook)
|
|
879
|
+
fail(404, "Webhook missing");
|
|
880
|
+
if (hook.type !== "incoming")
|
|
881
|
+
fail(400, "Only incoming webhooks have tokens");
|
|
882
|
+
hook.token = createWebhookToken();
|
|
883
|
+
hook.updatedAt = Date.now();
|
|
884
|
+
updated = hook;
|
|
885
|
+
});
|
|
886
|
+
groupEvents.invalidate(String(req.params.id));
|
|
887
|
+
res.json({ webhook: updated });
|
|
888
|
+
});
|
|
889
|
+
const handleWebhookDelete = async (req, res) => {
|
|
890
|
+
const owner = account(req);
|
|
891
|
+
if (agents.has(req))
|
|
892
|
+
fail(403, "Webhook management requires a user session");
|
|
893
|
+
await store.transact((state) => {
|
|
894
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
895
|
+
if (!room)
|
|
896
|
+
fail(404, "Room missing");
|
|
897
|
+
if (!room.webhooks?.some((w) => w.id === req.params.webhookId))
|
|
898
|
+
fail(404, "Webhook missing");
|
|
899
|
+
room.webhooks = room.webhooks.filter((w) => w.id !== req.params.webhookId);
|
|
900
|
+
});
|
|
901
|
+
groupEvents.invalidate(String(req.params.id));
|
|
902
|
+
res.json({ deleted: true });
|
|
903
|
+
};
|
|
904
|
+
app.delete("/api/rooms/:id/webhooks/:webhookId", handleWebhookDelete);
|
|
905
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/delete", handleWebhookDelete);
|
|
906
|
+
app.post("/api/rooms/:id/hub-relay", async (req, res) => {
|
|
907
|
+
const owner = account(req);
|
|
908
|
+
if (agents.has(req))
|
|
909
|
+
fail(403, "Webhook management requires a user session");
|
|
910
|
+
const rawUrl = req.body?.hubRelayBaseUrl;
|
|
911
|
+
let baseUrl;
|
|
912
|
+
if (rawUrl !== undefined && rawUrl !== null && rawUrl !== "") {
|
|
913
|
+
if (typeof rawUrl !== "string")
|
|
914
|
+
fail(400, "Invalid hubRelayBaseUrl");
|
|
915
|
+
try {
|
|
916
|
+
const parsed = new URL(rawUrl.trim());
|
|
917
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
918
|
+
fail(400, "Invalid protocol");
|
|
919
|
+
baseUrl = parsed.origin;
|
|
920
|
+
}
|
|
921
|
+
catch {
|
|
922
|
+
fail(400, "hubRelayBaseUrl must be a valid HTTP(S) URL");
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
await store.transact((state) => {
|
|
926
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
927
|
+
if (!room)
|
|
928
|
+
fail(404, "Room missing");
|
|
929
|
+
room.hubRelayBaseUrl = baseUrl;
|
|
930
|
+
});
|
|
931
|
+
groupEvents.invalidate(String(req.params.id));
|
|
932
|
+
res.json({ hubRelayBaseUrl: baseUrl });
|
|
933
|
+
});
|
|
934
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/test", async (req, res) => {
|
|
935
|
+
const owner = account(req);
|
|
936
|
+
if (agents.has(req))
|
|
937
|
+
fail(403, "Webhook management requires a user session");
|
|
938
|
+
const state = store.snapshot();
|
|
939
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
940
|
+
if (!room)
|
|
941
|
+
fail(404, "Room missing");
|
|
942
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
943
|
+
if (!hook)
|
|
944
|
+
fail(404, "Webhook missing");
|
|
945
|
+
if (hook.type !== "outgoing") {
|
|
946
|
+
return res.json({ success: true, message: "Incoming webhook is active" });
|
|
947
|
+
}
|
|
948
|
+
if (!hook.url)
|
|
949
|
+
fail(400, "Webhook URL missing");
|
|
950
|
+
const result = await testOutgoingWebhook({ url: hook.url, secret: hook.secret });
|
|
951
|
+
res.json(result);
|
|
952
|
+
});
|
|
953
|
+
app.post("/api/rooms/:id/webhooks/incoming/:webhookId", async (req, res) => {
|
|
954
|
+
const roomId = String(req.params.id);
|
|
955
|
+
const webhookId = String(req.params.webhookId);
|
|
956
|
+
const snapshot = store.snapshot();
|
|
957
|
+
const room = snapshot.rooms.find((r) => r.id === roomId);
|
|
958
|
+
if (!room)
|
|
959
|
+
return res.status(404).json({ error: "Room missing" });
|
|
960
|
+
const webhook = room.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
|
|
961
|
+
if (!webhook || webhook.enabled === false)
|
|
962
|
+
return res.status(404).json({ error: "Webhook not found or disabled" });
|
|
963
|
+
const bearer = req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization.slice(7) : undefined;
|
|
964
|
+
const queryToken = typeof req.query?.token === "string" ? req.query.token : undefined;
|
|
965
|
+
const headerToken = typeof req.headers["x-webhook-token"] === "string" ? req.headers["x-webhook-token"] : undefined;
|
|
966
|
+
const bodyToken = typeof req.body?.token === "string" ? req.body.token : undefined;
|
|
967
|
+
const providedToken = queryToken ?? bearer ?? headerToken ?? bodyToken;
|
|
968
|
+
if (!providedToken || !webhook.token || !secureCompareTokens(providedToken, webhook.token)) {
|
|
969
|
+
return res.status(401).json({ error: "Invalid webhook token" });
|
|
970
|
+
}
|
|
971
|
+
const rawText = req.body?.text;
|
|
972
|
+
if (typeof rawText !== "string" || !rawText.trim()) {
|
|
973
|
+
return res.status(400).json({ error: "Missing or empty text" });
|
|
974
|
+
}
|
|
975
|
+
const content = text(rawText);
|
|
976
|
+
const senderName = typeof req.body?.senderName === "string" && req.body.senderName.trim()
|
|
977
|
+
? text(req.body.senderName.trim(), 80)
|
|
978
|
+
: webhook.name;
|
|
979
|
+
const replyToMessageId = typeof req.body?.replyToMessageId === "string" ? text(req.body.replyToMessageId, 128) : undefined;
|
|
980
|
+
const inputTargets = Array.isArray(req.body?.targetBotIds)
|
|
981
|
+
? req.body.targetBotIds.filter((id) => typeof id === "string")
|
|
982
|
+
: [];
|
|
983
|
+
const settings = currentSettings();
|
|
984
|
+
const key = randomUUID();
|
|
985
|
+
const fingerprint = hashSecret(JSON.stringify({
|
|
986
|
+
content,
|
|
987
|
+
senderName,
|
|
988
|
+
webhookId,
|
|
989
|
+
inputTargets,
|
|
990
|
+
replyToMessageId,
|
|
991
|
+
}));
|
|
992
|
+
const result = await store.transact((draft) => {
|
|
993
|
+
const activeRoom = draft.rooms.find((r) => r.id === roomId);
|
|
994
|
+
if (!activeRoom)
|
|
995
|
+
fail(404, "Room missing");
|
|
996
|
+
const activeWebhook = activeRoom.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
|
|
997
|
+
if (!activeWebhook || activeWebhook.enabled === false)
|
|
998
|
+
fail(404, "Webhook missing or disabled");
|
|
999
|
+
if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === activeRoom.id)) {
|
|
1000
|
+
fail(400, "Reply target message is not in this room");
|
|
1001
|
+
}
|
|
1002
|
+
const targets = [];
|
|
1003
|
+
const allowTrigger = activeWebhook.allowBotTrigger !== false;
|
|
1004
|
+
if (allowTrigger) {
|
|
1005
|
+
if (inputTargets.length > 0) {
|
|
1006
|
+
targets.push(...inputTargets);
|
|
1007
|
+
}
|
|
1008
|
+
else {
|
|
1009
|
+
if (settings.allowBotMentions) {
|
|
1010
|
+
targets.push(...groupMentionTargets(content, activeRoom, draft.bots, settings.botMentionBudgetPerTurn));
|
|
1011
|
+
}
|
|
1012
|
+
if (!targets.length && activeRoom.primaryBotId) {
|
|
1013
|
+
if (activeRoom.botIds.includes(activeRoom.primaryBotId) &&
|
|
1014
|
+
validBot(draft, activeRoom.primaryBotId, activeRoom.accountId)) {
|
|
1015
|
+
targets.push(activeRoom.primaryBotId);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
if (targets.some((id) => !activeRoom.botIds.includes(id) || !validBot(draft, id, activeRoom.accountId))) {
|
|
1021
|
+
fail(400, "Invalid target Bot");
|
|
1022
|
+
}
|
|
1023
|
+
const now = Date.now();
|
|
1024
|
+
const rootId = randomUUID();
|
|
1025
|
+
const tasks = targets.map((botId, index) => {
|
|
1026
|
+
const targetBot = validBot(draft, botId, activeRoom.accountId);
|
|
1027
|
+
return {
|
|
1028
|
+
id: index === 0 ? rootId : randomUUID(),
|
|
1029
|
+
rootTaskId: rootId,
|
|
1030
|
+
dispatchDepth: 0,
|
|
1031
|
+
...(index === 0 ? { dispatchCount: targets.length } : {}),
|
|
1032
|
+
attemptId: randomUUID(),
|
|
1033
|
+
roomId: activeRoom.id,
|
|
1034
|
+
accountId: activeRoom.accountId,
|
|
1035
|
+
botId,
|
|
1036
|
+
deviceId: targetBot.deviceId,
|
|
1037
|
+
botRevision: targetBot.revision,
|
|
1038
|
+
text: content,
|
|
1039
|
+
status: "queued",
|
|
1040
|
+
createdAt: now,
|
|
1041
|
+
updatedAt: now,
|
|
1042
|
+
};
|
|
1043
|
+
});
|
|
1044
|
+
for (const task of tasks) {
|
|
1045
|
+
task.kind = "message";
|
|
1046
|
+
const targetConv = draft.conversations
|
|
1047
|
+
.filter((entry) => entry.roomId === activeRoom.id &&
|
|
1048
|
+
entry.accountId === activeRoom.accountId &&
|
|
1049
|
+
entry.botId === task.botId &&
|
|
1050
|
+
!entry.closed &&
|
|
1051
|
+
entry.botRevision === task.botRevision &&
|
|
1052
|
+
entry.deviceId === task.deviceId)
|
|
1053
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)[0];
|
|
1054
|
+
if (targetConv) {
|
|
1055
|
+
task.conversationId = targetConv.id;
|
|
1056
|
+
task.resume = true;
|
|
1057
|
+
advanceConversationTask(draft, targetConv, task);
|
|
1058
|
+
targetConv.rootTaskId = task.rootTaskId;
|
|
1059
|
+
targetConv.updatedAt = now;
|
|
1060
|
+
targetConv.dispatchDepth = 0;
|
|
1061
|
+
}
|
|
1062
|
+
else {
|
|
1063
|
+
establishConversation(draft, task);
|
|
1064
|
+
}
|
|
1065
|
+
recordConversationTurn(draft, task, key, fingerprint);
|
|
1066
|
+
}
|
|
1067
|
+
const message = {
|
|
1068
|
+
id: randomUUID(),
|
|
1069
|
+
roomId: activeRoom.id,
|
|
1070
|
+
accountId: activeRoom.accountId,
|
|
1071
|
+
text: content,
|
|
1072
|
+
sender: {
|
|
1073
|
+
type: "webhook",
|
|
1074
|
+
id: activeWebhook.id,
|
|
1075
|
+
name: senderName,
|
|
1076
|
+
},
|
|
1077
|
+
createdAt: now,
|
|
1078
|
+
taskIds: tasks.map((t) => t.id),
|
|
1079
|
+
...(targets.length ? { targetBotIds: targets } : {}),
|
|
1080
|
+
...(replyToMessageId ? { replyToMessageId } : {}),
|
|
1081
|
+
...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
|
|
1082
|
+
...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
|
|
1083
|
+
};
|
|
1084
|
+
const context = tasks.length
|
|
1085
|
+
? groupTaskContext(activeRoom, draft.bots, draft.messages, settings.groupContextBytes)
|
|
1086
|
+
: undefined;
|
|
1087
|
+
draft.tasks.push(...tasks);
|
|
1088
|
+
draft.messages.push(message);
|
|
1089
|
+
draft.receipts.push({
|
|
1090
|
+
accountId: activeRoom.accountId,
|
|
1091
|
+
roomId: activeRoom.id,
|
|
1092
|
+
key,
|
|
1093
|
+
fingerprint,
|
|
1094
|
+
messageId: message.id,
|
|
1095
|
+
createdAt: message.createdAt,
|
|
1096
|
+
});
|
|
1097
|
+
const oldMessages = draft.messages.filter((m) => m.roomId === activeRoom.id).slice(0, -getHistoryLimit());
|
|
1098
|
+
const removed = new Set(oldMessages.map((m) => m.id));
|
|
1099
|
+
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
1100
|
+
trimRoomReceipts(draft, activeRoom.id);
|
|
1101
|
+
const oldTasks = new Set(draft.tasks
|
|
1102
|
+
.filter((t) => t.roomId === activeRoom.id &&
|
|
1103
|
+
isTerminal(t.status) &&
|
|
1104
|
+
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1105
|
+
.slice(0, -getHistoryLimit())
|
|
1106
|
+
.map((t) => t.id));
|
|
1107
|
+
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
1108
|
+
trimConversationHistory(draft, activeRoom.id);
|
|
1109
|
+
trimClosedConversations(draft, activeRoom.id);
|
|
1110
|
+
return { message, tasks, context, roomId: activeRoom.id };
|
|
1111
|
+
});
|
|
1112
|
+
for (const task of result.tasks) {
|
|
1113
|
+
if (task.status !== "waiting")
|
|
1114
|
+
await deliverTask(task, result.context);
|
|
1115
|
+
}
|
|
1116
|
+
groupEvents.invalidate(result.roomId);
|
|
1117
|
+
dispatchGroupWebhook(store, result.roomId, "message", result.message);
|
|
1118
|
+
res.json({
|
|
1119
|
+
success: true,
|
|
1120
|
+
message: result.message,
|
|
1121
|
+
tasks: result.tasks.map(publicTask),
|
|
1122
|
+
});
|
|
1123
|
+
});
|
|
641
1124
|
// === Task Details, Journal, and Reports ===
|
|
642
1125
|
app.get("/api/rooms/:id/tasks/:taskId", (req, res) => {
|
|
643
1126
|
const acc = account(req);
|
|
@@ -674,6 +1157,7 @@ export async function createDeviceHub(options) {
|
|
|
674
1157
|
parentTaskId: task.parentTaskId,
|
|
675
1158
|
conversationId: task.conversationId,
|
|
676
1159
|
report: task.report,
|
|
1160
|
+
...(task.attenuatedTools ? { attenuatedTools: task.attenuatedTools } : {}),
|
|
677
1161
|
},
|
|
678
1162
|
reportMeta,
|
|
679
1163
|
interactionCount: interactions.length,
|
|
@@ -759,6 +1243,8 @@ export async function createDeviceHub(options) {
|
|
|
759
1243
|
planOnly: false,
|
|
760
1244
|
resume: Boolean(conversation),
|
|
761
1245
|
...(conversation ? { conversationId: conversation.id } : {}),
|
|
1246
|
+
...(task.sourceBotId ? { sourceBotId: task.sourceBotId } : {}),
|
|
1247
|
+
...(task.attenuatedTools ? { attenuatedTools: [...task.attenuatedTools] } : {}),
|
|
762
1248
|
};
|
|
763
1249
|
draft.tasks.push(nextTask);
|
|
764
1250
|
if (conversation) {
|
|
@@ -790,6 +1276,49 @@ export async function createDeviceHub(options) {
|
|
|
790
1276
|
res.json({ ok: true, plan, nextTaskId: nextTask.id });
|
|
791
1277
|
void drainConversation(nextTask.conversationId).catch(() => { });
|
|
792
1278
|
});
|
|
1279
|
+
app.post("/api/rooms/:id/tasks/:taskId/steer", async (req, res) => {
|
|
1280
|
+
const acc = account(req);
|
|
1281
|
+
const roomId = String(req.params.id);
|
|
1282
|
+
const taskId = String(req.params.taskId);
|
|
1283
|
+
const instruction = text(req.body?.text);
|
|
1284
|
+
if (!instruction)
|
|
1285
|
+
fail(400, "Steering instruction required");
|
|
1286
|
+
const snapshot = store.snapshot();
|
|
1287
|
+
const room = snapshot.rooms.find((r) => r.id === roomId && r.accountId === acc.id);
|
|
1288
|
+
if (!room)
|
|
1289
|
+
fail(404, "Room missing");
|
|
1290
|
+
const task = snapshot.tasks.find((t) => t.id === taskId && t.roomId === roomId && t.accountId === acc.id);
|
|
1291
|
+
if (!task)
|
|
1292
|
+
fail(404, "Task missing");
|
|
1293
|
+
if (task.status !== "running")
|
|
1294
|
+
fail(409, "Steering is only allowed on running tasks");
|
|
1295
|
+
await taskJournalManager
|
|
1296
|
+
.append(task.id, {
|
|
1297
|
+
botId: task.botId,
|
|
1298
|
+
attemptId: task.attemptId,
|
|
1299
|
+
type: "progress",
|
|
1300
|
+
phase: "running",
|
|
1301
|
+
summary: `In-flight steering: ${instruction.slice(0, 100)}`,
|
|
1302
|
+
output: instruction,
|
|
1303
|
+
}, { roomId: task.roomId, accountId: task.accountId })
|
|
1304
|
+
.catch(() => { });
|
|
1305
|
+
await store.transact((draft) => {
|
|
1306
|
+
draft.messages.push({
|
|
1307
|
+
id: randomUUID(),
|
|
1308
|
+
roomId,
|
|
1309
|
+
accountId: acc.id,
|
|
1310
|
+
text: `🕹️ **[飞行中即时转向 / In-flight Steering]** @${task.botId}:\n> ${instruction}`,
|
|
1311
|
+
sender: { type: "human", id: acc.id, name: acc.username },
|
|
1312
|
+
createdAt: Date.now(),
|
|
1313
|
+
taskIds: [task.id],
|
|
1314
|
+
});
|
|
1315
|
+
});
|
|
1316
|
+
const steerRelay = options.onSteer ?? options.relay?.onSteer;
|
|
1317
|
+
if (steerRelay) {
|
|
1318
|
+
await steerRelay(task.deviceId, { taskId: task.id, botId: task.botId, text: instruction }).catch(() => { });
|
|
1319
|
+
}
|
|
1320
|
+
res.json({ success: true, taskId: task.id, steered: true });
|
|
1321
|
+
});
|
|
793
1322
|
app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
|
|
794
1323
|
const acc = account(req);
|
|
795
1324
|
const state = store.snapshot();
|
|
@@ -978,6 +1507,9 @@ export async function createDeviceHub(options) {
|
|
|
978
1507
|
}
|
|
979
1508
|
return { room };
|
|
980
1509
|
});
|
|
1510
|
+
if (operation === "delete" || operation === "clear") {
|
|
1511
|
+
lockManager.clearRoom(String(req.params.id));
|
|
1512
|
+
}
|
|
981
1513
|
res.json(result);
|
|
982
1514
|
});
|
|
983
1515
|
}
|
|
@@ -988,6 +1520,9 @@ export async function createDeviceHub(options) {
|
|
|
988
1520
|
const actor = { accountId: owner.id, bot: ownBot(req, draft) };
|
|
989
1521
|
return (kind === "deliveries" ? addDelivery : addReview)(draft, req.params.id, req.params.conversationId, actor, req.body);
|
|
990
1522
|
});
|
|
1523
|
+
if (kind === "deliveries") {
|
|
1524
|
+
dispatchGroupWebhook(store, req.params.id, "delivery", record);
|
|
1525
|
+
}
|
|
991
1526
|
res.json(kind === "deliveries" ? { delivery: record } : { review: record });
|
|
992
1527
|
});
|
|
993
1528
|
}
|
|
@@ -1054,10 +1589,11 @@ export async function createDeviceHub(options) {
|
|
|
1054
1589
|
if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
|
|
1055
1590
|
fail(403, "Bot may stop only its own conversation");
|
|
1056
1591
|
conversation.closed = true;
|
|
1592
|
+
conversation.closedReason = "stopped";
|
|
1057
1593
|
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id && taskPending(t));
|
|
1058
1594
|
for (const task of tasks) {
|
|
1059
1595
|
task.cancelRequested = true;
|
|
1060
|
-
if (task.status === "queued" && !deliveredTasks.has(task.id)) {
|
|
1596
|
+
if ((task.status === "queued" || task.status === "waiting") && !deliveredTasks.has(task.id)) {
|
|
1061
1597
|
task.stopConfirmed = true;
|
|
1062
1598
|
task.status = "interrupted";
|
|
1063
1599
|
task.updatedAt = Date.now();
|
|
@@ -1067,8 +1603,10 @@ export async function createDeviceHub(options) {
|
|
|
1067
1603
|
return tasks;
|
|
1068
1604
|
});
|
|
1069
1605
|
for (const task of pending) {
|
|
1070
|
-
if (task.stopConfirmed)
|
|
1606
|
+
if (task.stopConfirmed) {
|
|
1607
|
+
await releaseLocksAndWake(String(req.params.id), task.id);
|
|
1071
1608
|
continue;
|
|
1609
|
+
}
|
|
1072
1610
|
const confirmed = await options.relay
|
|
1073
1611
|
?.cancelTask?.(task.deviceId, task.id, task.attemptId)
|
|
1074
1612
|
.catch(() => ({ stopped: false }));
|
|
@@ -1083,12 +1621,36 @@ export async function createDeviceHub(options) {
|
|
|
1083
1621
|
current.updatedAt = Date.now();
|
|
1084
1622
|
current.report = "Conversation stopped.";
|
|
1085
1623
|
});
|
|
1624
|
+
await releaseLocksAndWake(String(req.params.id), task.id);
|
|
1086
1625
|
}
|
|
1087
1626
|
const remaining = store
|
|
1088
1627
|
.snapshot()
|
|
1089
1628
|
.tasks.filter((t) => t.conversationId === req.params.conversationId && taskPending(t));
|
|
1090
1629
|
res.json({ stopped: remaining.length === 0, pending: remaining.length });
|
|
1091
1630
|
});
|
|
1631
|
+
app.post("/api/rooms/:id/conversations/:conversationId/delete", async (req, res) => {
|
|
1632
|
+
const owner = account(req);
|
|
1633
|
+
if (agents.has(req))
|
|
1634
|
+
fail(403, "Conversation deletion requires a user session");
|
|
1635
|
+
const result = await store.transact((draft) => {
|
|
1636
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1637
|
+
const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1638
|
+
if (!room || !conversation)
|
|
1639
|
+
fail(404, "Conversation missing");
|
|
1640
|
+
if (draft.tasks.some((t) => t.conversationId === conversation.id && taskPending(t)))
|
|
1641
|
+
throw Object.assign(new Error("Stop the conversation before deleting it"), {
|
|
1642
|
+
status: 409,
|
|
1643
|
+
code: "ACTIVE_TASKS",
|
|
1644
|
+
});
|
|
1645
|
+
// Delivery/review records are the audit trail; deleting them is a separate, explicit decision.
|
|
1646
|
+
if (conversationHasAuditRecords(draft, conversation.id))
|
|
1647
|
+
fail(409, "Conversation has delivery history; audit records are retained");
|
|
1648
|
+
dropConversationRecords(draft, conversation.id);
|
|
1649
|
+
return { deleted: true };
|
|
1650
|
+
});
|
|
1651
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1652
|
+
res.json(result);
|
|
1653
|
+
});
|
|
1092
1654
|
app.post("/api/rooms/:id/conversations/:conversationId/attention", async (req, res) => {
|
|
1093
1655
|
const owner = account(req);
|
|
1094
1656
|
const question = text(req.body?.question, 2000);
|
|
@@ -1357,6 +1919,7 @@ export async function createDeviceHub(options) {
|
|
|
1357
1919
|
.map((c) => ({
|
|
1358
1920
|
...c,
|
|
1359
1921
|
status: conversationStatus(state, c),
|
|
1922
|
+
stale: conversationStale(state, c),
|
|
1360
1923
|
...deliverySummary(state, c.id, !req.params.conversationId),
|
|
1361
1924
|
}));
|
|
1362
1925
|
if (!req.params.conversationId)
|
|
@@ -1382,6 +1945,7 @@ export async function createDeviceHub(options) {
|
|
|
1382
1945
|
const conversationApi = req.path.includes("/conversations");
|
|
1383
1946
|
const conversationId = req.params.conversationId;
|
|
1384
1947
|
const kind = req.body?.kind ?? "message";
|
|
1948
|
+
const settings = currentSettings();
|
|
1385
1949
|
if (!["message", "request", "reply"].includes(kind))
|
|
1386
1950
|
fail(400, "Invalid message kind");
|
|
1387
1951
|
const requestId = req.body?.requestId === undefined
|
|
@@ -1397,6 +1961,17 @@ export async function createDeviceHub(options) {
|
|
|
1397
1961
|
const attentionId = req.body?.attentionId === undefined ? undefined : text(req.body.attentionId, 128);
|
|
1398
1962
|
const key = req.body?.idempotencyKey === undefined ? randomUUID() : text(req.body.idempotencyKey, 128);
|
|
1399
1963
|
const planOnly = req.body?.planOnly === true;
|
|
1964
|
+
const replyToMessageId = req.body?.replyToMessageId === undefined ? undefined : text(req.body.replyToMessageId, 128);
|
|
1965
|
+
const dependsOnTaskId = req.body?.dependsOnTaskId === undefined ? undefined : text(req.body.dependsOnTaskId, 128);
|
|
1966
|
+
let resourceLocks;
|
|
1967
|
+
try {
|
|
1968
|
+
if (req.body?.resourceLocks !== undefined) {
|
|
1969
|
+
resourceLocks = validateResourceLocks(req.body.resourceLocks);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
catch (err) {
|
|
1973
|
+
fail(400, err?.message ?? "Invalid resourceLocks");
|
|
1974
|
+
}
|
|
1400
1975
|
const fingerprint = hashSecret(JSON.stringify({
|
|
1401
1976
|
content,
|
|
1402
1977
|
attentionId,
|
|
@@ -1407,6 +1982,8 @@ export async function createDeviceHub(options) {
|
|
|
1407
1982
|
transfer,
|
|
1408
1983
|
parentTaskId,
|
|
1409
1984
|
planOnly,
|
|
1985
|
+
replyToMessageId,
|
|
1986
|
+
resourceLocks,
|
|
1410
1987
|
sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
|
|
1411
1988
|
sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
|
|
1412
1989
|
senderType: agents.has(req) ? "bot" : "human",
|
|
@@ -1432,6 +2009,17 @@ export async function createDeviceHub(options) {
|
|
|
1432
2009
|
}
|
|
1433
2010
|
if (source && !room.botIds.includes(source.id))
|
|
1434
2011
|
fail(403, "Source Bot is not a room member");
|
|
2012
|
+
if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === room.id))
|
|
2013
|
+
fail(400, "Reply target message is not in this room");
|
|
2014
|
+
if (dependsOnTaskId && !draft.tasks.some((m) => m.id === dependsOnTaskId && m.roomId === room.id))
|
|
2015
|
+
fail(400, "Dependency target task is not in this room");
|
|
2016
|
+
const depTask = dependsOnTaskId ? draft.tasks.find((t) => t.id === dependsOnTaskId) : undefined;
|
|
2017
|
+
const dependencyActive = Boolean(depTask && !isTerminal(depTask.status));
|
|
2018
|
+
// The Hub owns dispatch semantics: a human message that only names Bots in its text must not
|
|
2019
|
+
// silently fall back to the primary Bot just because a client did not pre-resolve the mentions.
|
|
2020
|
+
const canParseMentions = (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
|
|
2021
|
+
if (canParseMentions)
|
|
2022
|
+
targets.push(...groupMentionTargets(content, room, draft.bots, settings.botMentionBudgetPerTurn));
|
|
1435
2023
|
if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
|
|
1436
2024
|
fail(400, "Invalid target Bot");
|
|
1437
2025
|
if (source &&
|
|
@@ -1529,49 +2117,89 @@ export async function createDeviceHub(options) {
|
|
|
1529
2117
|
const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
|
|
1530
2118
|
if (planOnly && targets.some((id) => !validBot(draft, id, owner.id)?.tools?.includes("plan_update")))
|
|
1531
2119
|
fail(409, "Planning requires plan_update authorization in each Bot tool allowlist");
|
|
1532
|
-
if (targets.length && depth >
|
|
2120
|
+
if (targets.length && depth > settings.maxDispatchDepth)
|
|
1533
2121
|
fail(409, "Dispatch depth exhausted");
|
|
1534
|
-
if (targets.length && (root?.dispatchCount ?? 0) + targets.length >
|
|
2122
|
+
if (targets.length && (root?.dispatchCount ?? 0) + targets.length > settings.maxDispatchBudget)
|
|
1535
2123
|
fail(409, "Dispatch budget exhausted");
|
|
1536
2124
|
if (root && targets.length)
|
|
1537
2125
|
root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
|
|
1538
|
-
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
|
|
2126
|
+
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
|
|
2127
|
+
getHistoryLimit())
|
|
1539
2128
|
fail(409, "Too many active tasks");
|
|
1540
|
-
if (!conversation &&
|
|
1541
|
-
|
|
2129
|
+
if (!conversation &&
|
|
2130
|
+
draft.conversations.filter((c) => c.roomId === room.id && !c.closed).length + targets.length >
|
|
2131
|
+
getHistoryLimit())
|
|
2132
|
+
fail(409, "Too many open conversations; stop or delete conversations to free capacity");
|
|
1542
2133
|
const now = Date.now();
|
|
1543
2134
|
const rootId = root?.id ?? randomUUID();
|
|
1544
|
-
const tasks = targets.map((botId, index) =>
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2135
|
+
const tasks = targets.map((botId, index) => {
|
|
2136
|
+
const targetBot = validBot(draft, botId, owner.id);
|
|
2137
|
+
let attenuatedTools;
|
|
2138
|
+
if (source) {
|
|
2139
|
+
const rawSourceTools = source.tools ?? [];
|
|
2140
|
+
const sourceTools = parent?.attenuatedTools
|
|
2141
|
+
? rawSourceTools.filter((t) => !parent.attenuatedTools.includes(t))
|
|
2142
|
+
: rawSourceTools;
|
|
2143
|
+
const attenuated = computeAttenuatedTools(sourceTools, targetBot.tools ?? []);
|
|
2144
|
+
if (attenuated.length > 0) {
|
|
2145
|
+
attenuatedTools = attenuated;
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
return {
|
|
2149
|
+
id: !root && index === 0 ? rootId : randomUUID(),
|
|
2150
|
+
rootTaskId: rootId,
|
|
2151
|
+
dispatchDepth: depth,
|
|
2152
|
+
...(!root && index === 0 ? { dispatchCount: targets.length } : {}),
|
|
2153
|
+
attemptId: randomUUID(),
|
|
2154
|
+
roomId: room.id,
|
|
2155
|
+
accountId: owner.id,
|
|
2156
|
+
botId,
|
|
2157
|
+
deviceId: targetBot.deviceId,
|
|
2158
|
+
botRevision: targetBot.revision,
|
|
2159
|
+
...(source ? { sourceBotId: source.id } : {}),
|
|
2160
|
+
text: content,
|
|
2161
|
+
status: dependencyActive ? "waiting" : "queued",
|
|
2162
|
+
...(dependencyActive
|
|
2163
|
+
? {
|
|
2164
|
+
blockReason: "dependency_waiting",
|
|
2165
|
+
blockReasonDetail: `Waiting for dependency task ${dependsOnTaskId}`,
|
|
2166
|
+
dependsOnTaskId,
|
|
2167
|
+
}
|
|
2168
|
+
: dependsOnTaskId
|
|
2169
|
+
? { dependsOnTaskId }
|
|
2170
|
+
: {}),
|
|
2171
|
+
createdAt: now,
|
|
2172
|
+
updatedAt: now,
|
|
2173
|
+
...(resourceLocks && resourceLocks.length ? { resourceLocks } : {}),
|
|
2174
|
+
...(planOnly ? { planOnly: true, plan: { state: "draft", steps: [] } } : {}),
|
|
2175
|
+
...(transfer ? { handoff: transfer } : {}),
|
|
2176
|
+
...(parentTaskId ? { parentTaskId } : {}),
|
|
2177
|
+
...(attenuatedTools ? { attenuatedTools } : {}),
|
|
2178
|
+
};
|
|
2179
|
+
});
|
|
1564
2180
|
for (const task of tasks) {
|
|
1565
2181
|
task.kind = kind;
|
|
1566
2182
|
task.sourceConversationId = parent?.conversationId;
|
|
1567
2183
|
task.requestId = requestId;
|
|
1568
|
-
|
|
1569
|
-
|
|
2184
|
+
const targetConv = conversation && conversation.botId === task.botId
|
|
2185
|
+
? conversation
|
|
2186
|
+
: !source && !conversationApi && req.body?.newConversation !== true
|
|
2187
|
+
? draft.conversations
|
|
2188
|
+
.filter((entry) => entry.roomId === room.id &&
|
|
2189
|
+
entry.accountId === owner.id &&
|
|
2190
|
+
entry.botId === task.botId &&
|
|
2191
|
+
!entry.closed &&
|
|
2192
|
+
entry.botRevision === task.botRevision &&
|
|
2193
|
+
entry.deviceId === task.deviceId)
|
|
2194
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)[0]
|
|
2195
|
+
: undefined;
|
|
2196
|
+
if (targetConv) {
|
|
2197
|
+
task.conversationId = targetConv.id;
|
|
1570
2198
|
task.resume = true;
|
|
1571
|
-
advanceConversationTask(draft,
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
2199
|
+
advanceConversationTask(draft, targetConv, task);
|
|
2200
|
+
targetConv.rootTaskId = task.rootTaskId;
|
|
2201
|
+
targetConv.updatedAt = now;
|
|
2202
|
+
targetConv.dispatchDepth = depth;
|
|
1575
2203
|
}
|
|
1576
2204
|
else
|
|
1577
2205
|
establishConversation(draft, task);
|
|
@@ -1593,31 +2221,49 @@ export async function createDeviceHub(options) {
|
|
|
1593
2221
|
createdAt: now,
|
|
1594
2222
|
taskIds: tasks.map((t) => t.id),
|
|
1595
2223
|
targetBotIds: targets,
|
|
2224
|
+
...(replyToMessageId ? { replyToMessageId } : {}),
|
|
1596
2225
|
...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
|
|
1597
2226
|
...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
|
|
1598
2227
|
};
|
|
1599
2228
|
// Freeze shared context before any recipient starts. Parallel answers cannot leak into siblings.
|
|
1600
|
-
const context = tasks.length
|
|
2229
|
+
const context = tasks.length
|
|
2230
|
+
? groupTaskContext(room, draft.bots, draft.messages, settings.groupContextBytes)
|
|
2231
|
+
: undefined;
|
|
1601
2232
|
draft.tasks.push(...tasks);
|
|
1602
2233
|
draft.messages.push(message);
|
|
1603
|
-
draft.receipts.push({
|
|
1604
|
-
|
|
2234
|
+
draft.receipts.push({
|
|
2235
|
+
accountId: owner.id,
|
|
2236
|
+
roomId: room.id,
|
|
2237
|
+
key,
|
|
2238
|
+
fingerprint,
|
|
2239
|
+
messageId: message.id,
|
|
2240
|
+
createdAt: message.createdAt,
|
|
2241
|
+
});
|
|
2242
|
+
const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -getHistoryLimit());
|
|
1605
2243
|
const removed = new Set(oldMessages.map((m) => m.id));
|
|
2244
|
+
// Retention evicts messages, never the replay guard: a retry must not re-dispatch evicted work.
|
|
1606
2245
|
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
1607
|
-
draft
|
|
2246
|
+
trimRoomReceipts(draft, room.id);
|
|
1608
2247
|
const oldTasks = new Set(draft.tasks
|
|
1609
2248
|
.filter((t) => t.roomId === room.id &&
|
|
1610
2249
|
isTerminal(t.status) &&
|
|
1611
2250
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1612
|
-
.slice(0, -
|
|
2251
|
+
.slice(0, -getHistoryLimit())
|
|
1613
2252
|
.map((t) => t.id));
|
|
1614
2253
|
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
1615
2254
|
trimConversationHistory(draft, room.id);
|
|
2255
|
+
trimClosedConversations(draft, room.id);
|
|
1616
2256
|
return { message, tasks, duplicate: false, context };
|
|
1617
2257
|
});
|
|
1618
|
-
if (!result.duplicate)
|
|
1619
|
-
for (const task of result.tasks)
|
|
1620
|
-
|
|
2258
|
+
if (!result.duplicate) {
|
|
2259
|
+
for (const task of result.tasks) {
|
|
2260
|
+
if (task.status !== "waiting")
|
|
2261
|
+
await deliverTask(task, result.context);
|
|
2262
|
+
}
|
|
2263
|
+
if (result.message) {
|
|
2264
|
+
dispatchGroupWebhook(store, req.params.id, "message", result.message);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
1621
2267
|
const state = store.snapshot();
|
|
1622
2268
|
res.json({
|
|
1623
2269
|
...(conversationApi
|
|
@@ -1630,6 +2276,28 @@ export async function createDeviceHub(options) {
|
|
|
1630
2276
|
tasks: result.tasks.map((task) => publicTask(state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task)),
|
|
1631
2277
|
});
|
|
1632
2278
|
});
|
|
2279
|
+
app.post("/api/devices/:id/remark", async (req, res) => {
|
|
2280
|
+
const owner = account(req);
|
|
2281
|
+
const id = String(req.params.id);
|
|
2282
|
+
const rawRemark = req.body?.remark;
|
|
2283
|
+
if (rawRemark !== null && rawRemark !== undefined && typeof rawRemark !== "string") {
|
|
2284
|
+
fail(400, "Invalid remark");
|
|
2285
|
+
}
|
|
2286
|
+
const remark = typeof rawRemark === "string" ? rawRemark.trim().slice(0, 80) : "";
|
|
2287
|
+
const updated = await store.transact((draft) => {
|
|
2288
|
+
const target = draft.devices.find((d) => d.id === id && d.accountId === owner.id);
|
|
2289
|
+
if (!target)
|
|
2290
|
+
fail(404, "Device missing");
|
|
2291
|
+
if (remark) {
|
|
2292
|
+
target.remark = remark;
|
|
2293
|
+
}
|
|
2294
|
+
else {
|
|
2295
|
+
delete target.remark;
|
|
2296
|
+
}
|
|
2297
|
+
return target;
|
|
2298
|
+
});
|
|
2299
|
+
res.json({ device: visibleDevice(publicDevice(updated)) });
|
|
2300
|
+
});
|
|
1633
2301
|
for (const action of ["alias", "portal"])
|
|
1634
2302
|
app.post(`/api/devices/:id/${action}`, async (req, res) => {
|
|
1635
2303
|
const owner = account(req);
|
|
@@ -1723,6 +2391,46 @@ export async function createDeviceHub(options) {
|
|
|
1723
2391
|
});
|
|
1724
2392
|
// Accepted queued tasks remain in flight until a terminal event, including asynchronous relay delivery.
|
|
1725
2393
|
const deliveredTasks = new Set();
|
|
2394
|
+
async function releaseLocksAndWake(roomId, taskId) {
|
|
2395
|
+
const promoted = lockManager.releaseLocks(roomId, taskId);
|
|
2396
|
+
if (promoted.length > 0) {
|
|
2397
|
+
await handlePromotedTasks(roomId, promoted);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
async function handlePromotedTasks(roomId, promotedTaskIds) {
|
|
2401
|
+
for (const taskId of promotedTaskIds) {
|
|
2402
|
+
const state = store.snapshot();
|
|
2403
|
+
const task = state.tasks.find((t) => t.id === taskId);
|
|
2404
|
+
if (!task) {
|
|
2405
|
+
lockManager.releaseLocks(roomId, taskId);
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
if (task.cancelRequested || state.conversations.find((c) => c.id === task.conversationId)?.closed) {
|
|
2409
|
+
const nextPromoted = lockManager.releaseLocks(roomId, taskId);
|
|
2410
|
+
if (nextPromoted.length > 0) {
|
|
2411
|
+
await handlePromotedTasks(roomId, nextPromoted);
|
|
2412
|
+
}
|
|
2413
|
+
continue;
|
|
2414
|
+
}
|
|
2415
|
+
await store.transact((draft) => {
|
|
2416
|
+
const current = draft.tasks.find((t) => t.id === taskId);
|
|
2417
|
+
if (current && current.status === "waiting") {
|
|
2418
|
+
current.status = "queued";
|
|
2419
|
+
delete current.blockReason;
|
|
2420
|
+
delete current.blockReasonDetail;
|
|
2421
|
+
current.updatedAt = Date.now();
|
|
2422
|
+
}
|
|
2423
|
+
});
|
|
2424
|
+
const room = state.rooms.find((r) => r.id === roomId);
|
|
2425
|
+
const context = room
|
|
2426
|
+
? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes)
|
|
2427
|
+
: undefined;
|
|
2428
|
+
const updatedTask = store.snapshot().tasks.find((t) => t.id === taskId);
|
|
2429
|
+
if (updatedTask) {
|
|
2430
|
+
await deliverTask(updatedTask, context);
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
1726
2434
|
async function drainConversation(conversationId) {
|
|
1727
2435
|
if (!conversationId)
|
|
1728
2436
|
return;
|
|
@@ -1731,13 +2439,65 @@ export async function createDeviceHub(options) {
|
|
|
1731
2439
|
if (!next || deliveredTasks.has(next.id))
|
|
1732
2440
|
return;
|
|
1733
2441
|
const room = state.rooms.find((entry) => entry.id === next.roomId);
|
|
1734
|
-
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages) : undefined);
|
|
2442
|
+
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
2443
|
+
}
|
|
2444
|
+
async function wakeDependentTasks(roomId, completedTaskId, report) {
|
|
2445
|
+
const dependentTaskIds = [];
|
|
2446
|
+
await store.transact((draft) => {
|
|
2447
|
+
for (const t of draft.tasks) {
|
|
2448
|
+
if (t.roomId === roomId && t.status === "waiting" && t.dependsOnTaskId === completedTaskId) {
|
|
2449
|
+
t.status = "queued";
|
|
2450
|
+
delete t.blockReason;
|
|
2451
|
+
delete t.blockReasonDetail;
|
|
2452
|
+
t.updatedAt = Date.now();
|
|
2453
|
+
if (report) {
|
|
2454
|
+
const excerpt = report.length > 2000 ? report.slice(0, 2000) + "..." : report;
|
|
2455
|
+
t.text = `[前序任务输出:\n${excerpt}\n]\n\n${t.text}`;
|
|
2456
|
+
}
|
|
2457
|
+
dependentTaskIds.push(t.id);
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
});
|
|
2461
|
+
if (dependentTaskIds.length > 0) {
|
|
2462
|
+
const state = store.snapshot();
|
|
2463
|
+
const room = state.rooms.find((r) => r.id === roomId);
|
|
2464
|
+
const context = room
|
|
2465
|
+
? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes)
|
|
2466
|
+
: undefined;
|
|
2467
|
+
for (const id of dependentTaskIds) {
|
|
2468
|
+
const task = state.tasks.find((t) => t.id === id);
|
|
2469
|
+
if (task) {
|
|
2470
|
+
await deliverTask(task, context);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
1735
2474
|
}
|
|
1736
2475
|
async function deliverTask(task, context) {
|
|
1737
2476
|
if (deliveredTasks.has(task.id))
|
|
1738
2477
|
return;
|
|
1739
2478
|
if (task.conversationId && nextConversationTask(store.snapshot(), task.conversationId)?.id !== task.id)
|
|
1740
2479
|
return;
|
|
2480
|
+
if (task.resourceLocks && task.resourceLocks.length > 0) {
|
|
2481
|
+
const acquired = lockManager.acquireLocks({
|
|
2482
|
+
roomId: task.roomId,
|
|
2483
|
+
taskId: task.id,
|
|
2484
|
+
botId: task.botId,
|
|
2485
|
+
deviceId: task.deviceId,
|
|
2486
|
+
resourceLocks: task.resourceLocks,
|
|
2487
|
+
});
|
|
2488
|
+
if (!acquired.success) {
|
|
2489
|
+
await store.transact((draft) => {
|
|
2490
|
+
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
2491
|
+
if (current && !isTerminal(current.status)) {
|
|
2492
|
+
current.status = "waiting";
|
|
2493
|
+
current.blockReason = "resource_locked";
|
|
2494
|
+
current.blockReasonDetail = `Waiting for locks: ${acquired.conflictingLocks.join(", ")}`;
|
|
2495
|
+
current.updatedAt = Date.now();
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
return;
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
1741
2501
|
deliveredTasks.add(task.id);
|
|
1742
2502
|
const deliver = options.onTask ?? options.relay?.onTask;
|
|
1743
2503
|
try {
|
|
@@ -1798,8 +2558,10 @@ export async function createDeviceHub(options) {
|
|
|
1798
2558
|
createdAt: current.updatedAt,
|
|
1799
2559
|
});
|
|
1800
2560
|
const room = draft.rooms.find((r) => r.id === current.roomId);
|
|
1801
|
-
const context = room
|
|
1802
|
-
|
|
2561
|
+
const context = room
|
|
2562
|
+
? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
|
|
2563
|
+
: undefined;
|
|
2564
|
+
const wake = queueParentResult(draft, current, currentSettings());
|
|
1803
2565
|
draft.messages.push({
|
|
1804
2566
|
id: randomUUID(),
|
|
1805
2567
|
roomId: current.roomId,
|
|
@@ -1816,10 +2578,10 @@ export async function createDeviceHub(options) {
|
|
|
1816
2578
|
});
|
|
1817
2579
|
const remove = new Set(draft.messages
|
|
1818
2580
|
.filter((message) => message.roomId === current.roomId)
|
|
1819
|
-
.slice(0, -
|
|
2581
|
+
.slice(0, -getHistoryLimit())
|
|
1820
2582
|
.map((message) => message.id));
|
|
1821
2583
|
draft.messages = draft.messages.filter((message) => !remove.has(message.id));
|
|
1822
|
-
draft
|
|
2584
|
+
trimRoomReceipts(draft, current.roomId);
|
|
1823
2585
|
trimConversationHistory(draft, current.roomId);
|
|
1824
2586
|
return { wake, context };
|
|
1825
2587
|
});
|
|
@@ -1829,6 +2591,7 @@ export async function createDeviceHub(options) {
|
|
|
1829
2591
|
finally {
|
|
1830
2592
|
if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
|
|
1831
2593
|
deliveredTasks.delete(task.id);
|
|
2594
|
+
await releaseLocksAndWake(task.roomId, task.id);
|
|
1832
2595
|
await drainConversation(task.conversationId);
|
|
1833
2596
|
}
|
|
1834
2597
|
}
|
|
@@ -1924,14 +2687,14 @@ export async function createDeviceHub(options) {
|
|
|
1924
2687
|
});
|
|
1925
2688
|
const remove = new Set(draft.messages
|
|
1926
2689
|
.filter((m) => m.roomId === task.roomId)
|
|
1927
|
-
.slice(0, -
|
|
2690
|
+
.slice(0, -getHistoryLimit())
|
|
1928
2691
|
.map((m) => m.id));
|
|
1929
2692
|
draft.messages = draft.messages.filter((m) => !remove.has(m.id));
|
|
1930
|
-
draft
|
|
2693
|
+
trimRoomReceipts(draft, task.roomId);
|
|
1931
2694
|
}
|
|
1932
2695
|
const room = draft.rooms.find((r) => r.id === task.roomId);
|
|
1933
|
-
const context = groupTaskContext(room, draft.bots, draft.messages);
|
|
1934
|
-
const wake = queueParentResult(draft, task);
|
|
2696
|
+
const context = groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes);
|
|
2697
|
+
const wake = queueParentResult(draft, task, currentSettings());
|
|
1935
2698
|
trimConversationHistory(draft, task.roomId);
|
|
1936
2699
|
return { task, wake, context };
|
|
1937
2700
|
});
|
|
@@ -1949,8 +2712,36 @@ export async function createDeviceHub(options) {
|
|
|
1949
2712
|
console.warn(`[TaskJournal] Journal append failed for task ${result.task.id}:`, cause);
|
|
1950
2713
|
});
|
|
1951
2714
|
}
|
|
1952
|
-
if (isTerminal(result.task.status))
|
|
2715
|
+
if (isTerminal(result.task.status)) {
|
|
1953
2716
|
deliveredTasks.delete(result.task.id);
|
|
2717
|
+
await releaseLocksAndWake(result.task.roomId, result.task.id);
|
|
2718
|
+
if (result.task.status === "completed") {
|
|
2719
|
+
await wakeDependentTasks(result.task.roomId, result.task.id, report);
|
|
2720
|
+
dispatchGroupWebhook(store, result.task.roomId, "task_completed", {
|
|
2721
|
+
taskId: result.task.id,
|
|
2722
|
+
botId: result.task.botId,
|
|
2723
|
+
status: "completed",
|
|
2724
|
+
report: result.task.report,
|
|
2725
|
+
text: result.task.text,
|
|
2726
|
+
});
|
|
2727
|
+
}
|
|
2728
|
+
else if (result.task.status === "failed") {
|
|
2729
|
+
dispatchGroupWebhook(store, result.task.roomId, "task_failed", {
|
|
2730
|
+
taskId: result.task.id,
|
|
2731
|
+
botId: result.task.botId,
|
|
2732
|
+
status: "failed",
|
|
2733
|
+
report: result.task.report,
|
|
2734
|
+
text: result.task.text,
|
|
2735
|
+
});
|
|
2736
|
+
}
|
|
2737
|
+
if (report) {
|
|
2738
|
+
const state = store.snapshot();
|
|
2739
|
+
const msg = state.messages.find((m) => m.taskIds.includes(result.task.id) && m.sender.id === result.task.botId);
|
|
2740
|
+
if (msg) {
|
|
2741
|
+
dispatchGroupWebhook(store, result.task.roomId, "message", msg);
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
1954
2745
|
if (result.wake)
|
|
1955
2746
|
await deliverTask(result.wake, result.context);
|
|
1956
2747
|
await drainConversation(result.task.conversationId);
|
|
@@ -1999,20 +2790,36 @@ export async function createDeviceHub(options) {
|
|
|
1999
2790
|
: "Task lease expired due to prolonged inactivity.";
|
|
2000
2791
|
task.report = report;
|
|
2001
2792
|
const room = draft.rooms.find((r) => r.id === task.roomId);
|
|
2002
|
-
const context = room
|
|
2003
|
-
|
|
2793
|
+
const context = room
|
|
2794
|
+
? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
|
|
2795
|
+
: undefined;
|
|
2796
|
+
const wake = queueParentResult(draft, task, currentSettings());
|
|
2004
2797
|
trimConversationHistory(draft, task.roomId);
|
|
2005
|
-
settledWakes.push({
|
|
2798
|
+
settledWakes.push({
|
|
2799
|
+
wake,
|
|
2800
|
+
context,
|
|
2801
|
+
conversationId: task.conversationId,
|
|
2802
|
+
taskId: task.id,
|
|
2803
|
+
roomId: task.roomId,
|
|
2804
|
+
});
|
|
2006
2805
|
}
|
|
2007
2806
|
}
|
|
2008
2807
|
}
|
|
2009
2808
|
});
|
|
2010
2809
|
for (const item of settledWakes) {
|
|
2011
2810
|
deliveredTasks.delete(item.taskId);
|
|
2811
|
+
await releaseLocksAndWake(item.roomId, item.taskId);
|
|
2012
2812
|
if (item.wake)
|
|
2013
2813
|
await deliverTask(item.wake, item.context);
|
|
2014
2814
|
await drainConversation(item.conversationId);
|
|
2015
2815
|
}
|
|
2816
|
+
const expiredPromoted = lockManager.cleanupExpiredLocks();
|
|
2817
|
+
for (const pTaskId of expiredPromoted) {
|
|
2818
|
+
const pTask = store.snapshot().tasks.find((t) => t.id === pTaskId);
|
|
2819
|
+
if (pTask) {
|
|
2820
|
+
await handlePromotedTasks(pTask.roomId, [pTaskId]);
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2016
2823
|
}
|
|
2017
2824
|
catch {
|
|
2018
2825
|
console.warn("[HubRecovery] Sweep transaction failed");
|
|
@@ -2283,6 +3090,7 @@ export async function createDeviceHub(options) {
|
|
|
2283
3090
|
},
|
|
2284
3091
|
async close() {
|
|
2285
3092
|
clearInterval(recoverySweepTimer);
|
|
3093
|
+
lockManager.close();
|
|
2286
3094
|
await groupEvents.close();
|
|
2287
3095
|
await taskJournalManager.close();
|
|
2288
3096
|
pairs.clear();
|