pi-web-ui 0.115.0 → 0.117.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 +65 -2
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +159 -71
- package/dist/server/agent-service-daemon.js +136 -8
- package/dist/server/agent-service.js +594 -159
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +52 -8
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +77 -2
- package/dist/server/device-center/collab-service.js +61 -12
- package/dist/server/device-center/collab-tool.js +482 -21
- package/dist/server/device-center/connector.js +107 -37
- package/dist/server/device-center/delivery-authority.js +98 -0
- package/dist/server/device-center/delivery-subject.js +30 -0
- package/dist/server/device-center/device-integration.js +453 -183
- package/dist/server/device-center/execution-guides.js +17 -7
- 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 +51 -6
- 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 +71 -6
- package/dist/server/device-center/hub-deliveries.js +120 -15
- package/dist/server/device-center/hub-integration.js +655 -334
- package/dist/server/device-center/hub-locks.js +320 -0
- package/dist/server/device-center/hub-page.js +16 -35
- package/dist/server/device-center/hub-setup.js +23 -1
- package/dist/server/device-center/hub-transaction-log.js +197 -0
- package/dist/server/device-center/hub-webhooks.js +165 -0
- package/dist/server/device-center/hub.js +1531 -305
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +8 -3
- package/dist/server/device-center/local-publication.js +423 -0
- package/dist/server/device-center/local-verification-job.js +97 -0
- package/dist/server/device-center/local-verification.js +274 -0
- package/dist/server/device-center/local.js +181 -13
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +330 -0
- package/dist/server/device-center/publication-journal.js +312 -0
- package/dist/server/device-center/publish-intent.js +379 -0
- package/dist/server/device-center/relay.js +134 -24
- package/dist/server/device-center/runtime.js +475 -42
- package/dist/server/device-center/store.js +366 -89
- package/dist/server/device-center/task-outcome.js +81 -0
- package/dist/server/device-center/task-recovery.js +603 -178
- package/dist/server/device-center/task-scheduler.js +48 -3
- package/dist/server/device-center/task-settlement.js +353 -0
- package/dist/server/device-center/task-workspace.js +443 -0
- package/dist/server/device-center/transfers.js +41 -15
- package/dist/server/device-center/verification-limits.js +10 -0
- package/dist/server/device-center/work-contract.js +995 -0
- package/dist/server/dispatch-domain-handlers.js +29 -3
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/engine-probe.js +112 -1
- package/dist/server/global-loader.js +119 -19
- package/dist/server/index.js +159 -17
- package/dist/server/managed.js +2 -0
- package/dist/server/model-admin.js +48 -6
- package/dist/server/model-enrich.js +10 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/plugins.js +64 -7
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -0
- package/dist/server/prompt-composer.js +39 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/quick-ask-settings.js +28 -0
- package/dist/server/quick-ask.js +164 -0
- package/dist/server/reasoning-registry.js +207 -0
- package/dist/server/resolve-global-sdk.js +61 -11
- package/dist/server/scheduler-tasks.js +35 -8
- package/dist/server/session-list-scan.js +223 -0
- package/dist/server/session-open.js +93 -0
- package/dist/server/session-parser.js +4 -0
- package/dist/server/session-scan.js +90 -38
- package/dist/server/settings-service.js +9 -1
- package/dist/server/soft-cap.js +5 -0
- package/dist/server/startup-banner.js +35 -0
- package/dist/server/subagents.js +2 -1
- package/dist/server/tool-manager.js +17 -9
- package/dist/server/transcript-prepare.js +73 -0
- package/dist/server/unauthorized-page.js +319 -0
- package/dist/server/universal/drivers/claude-code.js +98 -34
- package/dist/server/universal/universal-session.js +4 -0
- package/dist/server/workspace-handle.js +428 -0
- package/docs/architecture-plugins.md +959 -0
- package/docs/device-center.md +34 -20
- package/package.json +4 -4
- package/plugin-sdk/README.md +16 -8
- package/plugin-sdk/client.d.ts +27 -0
- package/plugin-sdk/client.mjs +82 -0
- package/plugin-sdk/index.d.ts +10 -0
- package/plugin-sdk/index.mjs +4 -683
- package/plugin-sdk/package.json +15 -4
- package/plugin-sdk/testing.d.ts +10 -0
- package/plugin-sdk/testing.mjs +566 -0
- package/themes/flow-cristallo.css +168 -0
- package/themes/flow-ink.css +169 -0
- package/themes/flow-obsidian.css +169 -0
- package/themes/flow-zurich.css +169 -0
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
- package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
- package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
- package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
- package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
- package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
- package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
- package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
- package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
- package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
- package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
- package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
- package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
- package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
- package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
- package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
- package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
- package/web/dist/assets/index-BawF7ZP5.js +397 -0
- package/web/dist/assets/index-BoGCoq5X.js +397 -0
- package/web/dist/assets/index-CVW9FoY2.css +1 -0
- package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/server/patch-turn-end-boundary.js +0 -77
- 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,21 +1,31 @@
|
|
|
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";
|
|
4
5
|
import { createTaskJournalManager } from "./task-journal.js";
|
|
5
6
|
import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
|
|
6
7
|
import { TASK_REPORT_UPLOAD_JSON_BYTES } from "../payload-limits.js";
|
|
7
|
-
import { parseReportMetadata, mergeTaskReportMetadata
|
|
8
|
+
import { parseReportMetadata, mergeTaskReportMetadata } from "./report-metadata.js";
|
|
8
9
|
import { buildDeterministicTaskSummary, queryTaskReportChunk } from "./task-state.js";
|
|
9
10
|
import { addDelivery, addReview, deliveryHistory, deliverySummary } from "./hub-deliveries.js";
|
|
10
|
-
import {
|
|
11
|
+
import { assertNoApplyingIntegration, deriveArtifactSubject } from "./delivery-authority.js";
|
|
12
|
+
import { artifactRefsMatch } from "./delivery-subject.js";
|
|
13
|
+
import { hubPrepareIntegration, hubVerifyIntegration, hubConfirmIntegration, hubCancelIntegration, hubReconcileIntegration, hubResumeIntegration, reconcilePendingIntegrations, listIntegrations, } from "./hub-integration.js";
|
|
11
14
|
import { createServer } from "node:http";
|
|
12
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
13
|
-
import { DeviceHubStore, hashSecret, isTerminal, taskPending, publicDevice, publicTask, secretMatches, } from "./store.js";
|
|
15
|
+
import { randomBytes, randomUUID, createHash } from "node:crypto";
|
|
16
|
+
import { DeviceHubStore, hashSecret, isTerminal, taskPending, taskHasImmutableEvidence, publicDevice, publicTask, secretMatches, } from "./store.js";
|
|
14
17
|
import { atomicApproveGroupPlan } from "./group-plan-guard.js";
|
|
18
|
+
import { computeAttenuatedTools } from "./bot-execution.js";
|
|
15
19
|
import { validateTaskPlan } from "./task-plan.js";
|
|
16
|
-
import {
|
|
20
|
+
import { ALLOWED_WEBHOOK_EVENTS, createWebhookToken, dispatchGroupWebhook, isIncomingWebhookRequest, secureCompareTokens, testOutgoingWebhook, validateWebhookInput, } from "./hub-webhooks.js";
|
|
21
|
+
import { GROUP_RETENTION_LIMIT, groupHistoryPage, groupMentionTargets, groupTaskContext, } from "./group-context.js";
|
|
22
|
+
import { createWorkContract, createContextManifest, contractInputReferences, MAX_CONTRACT_REQUEST_BYTES, validateCodeArtifactOutcome, validateWorkContract, canonicalizeJson, } from "./work-contract.js";
|
|
23
|
+
import { createHubLockManager, validateResourceLocks } from "./hub-locks.js";
|
|
17
24
|
import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
|
|
18
|
-
import { establishConversation, advanceConversationTask,
|
|
25
|
+
import { establishConversation, advanceConversationTask, recordConversationTurn, conversationStatus, conversationPage, trimConversationHistory, conversationStale, conversationHasAuditRecords, dropConversationRecords, trimClosedConversations, trimRoomReceipts, } from "./hub-conversations.js";
|
|
26
|
+
import { DEFAULT_EXECUTION_SETTINGS } from "./execution-settings.js";
|
|
27
|
+
import { hasTaskLease, isRecoveringTask, recordTaskOutcome, settleTaskDependencies, settleTaskTerminalOutcome, rescanReadyTasksOnRecovery, sweepExpiredRecoveryLeases, } from "./task-settlement.js";
|
|
28
|
+
import { RELAY_LIMITS } from "./relay.js";
|
|
19
29
|
class HttpError extends Error {
|
|
20
30
|
status;
|
|
21
31
|
constructor(status, message) {
|
|
@@ -56,6 +66,10 @@ const token = () => randomBytes(32).toString("base64url");
|
|
|
56
66
|
const PAIR_TTL = 10 * 60 * 1000;
|
|
57
67
|
const HISTORY = GROUP_RETENTION_LIMIT;
|
|
58
68
|
export async function createDeviceHub(options) {
|
|
69
|
+
function currentSettings() {
|
|
70
|
+
return options.getSettings?.() ?? options.settings ?? DEFAULT_EXECUTION_SETTINGS;
|
|
71
|
+
}
|
|
72
|
+
const getHistoryLimit = () => currentSettings().groupRetentionLimit ?? GROUP_RETENTION_LIMIT;
|
|
59
73
|
const origin = new URL(options.publicUrl);
|
|
60
74
|
if (!["http:", "https:"].includes(origin.protocol) ||
|
|
61
75
|
origin.pathname !== "/" ||
|
|
@@ -76,7 +90,7 @@ export async function createDeviceHub(options) {
|
|
|
76
90
|
domain.hostname.endsWith(`.${origin.hostname}`))
|
|
77
91
|
throw new Error("Device domain must be independent of hub domain");
|
|
78
92
|
}
|
|
79
|
-
const store = await DeviceHubStore.open(options.dataDir);
|
|
93
|
+
const store = await DeviceHubStore.open(options.dataDir, { retainUnleasedQueued: true });
|
|
80
94
|
const taskJournalManager = createTaskJournalManager(options.dataDir);
|
|
81
95
|
const taskReportStore = createTaskReportStore(options.dataDir, "hub");
|
|
82
96
|
const groupEvents = createGroupEvents(store, taskJournalManager);
|
|
@@ -122,22 +136,25 @@ export async function createDeviceHub(options) {
|
|
|
122
136
|
if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
|
|
123
137
|
fail(429, "Too many user writes");
|
|
124
138
|
const suffix = req.path.slice("/api/device-user".length);
|
|
125
|
-
const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)?$/.test(suffix);
|
|
139
|
+
const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel|reconcile|resume))?)?))?)?$/.test(suffix);
|
|
126
140
|
const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
|
|
141
|
+
const webhookRoute = /^\/rooms\/[^/]+\/(?:webhooks(?:\/[^/]+(?:\/(?:delete|regenerate-token|test))?)?|hub-relay)$/.test(suffix);
|
|
127
142
|
if (!((req.method === "GET" &&
|
|
128
143
|
(conversationRoute ||
|
|
129
144
|
taskRoute ||
|
|
130
|
-
|
|
145
|
+
webhookRoute ||
|
|
146
|
+
/^\/rooms\/[^/]+\/(?:events|interactions|transfers|locks|blackboard)$/.test(suffix) ||
|
|
131
147
|
/^\/rooms\/[^/]+\/transfers\/[^/]+\/preview$/.test(suffix) ||
|
|
132
148
|
["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
133
149
|
/^\/rooms\/[^/]+$/.test(suffix))) ||
|
|
134
|
-
(req.method
|
|
150
|
+
(["POST", "PUT"].includes(req.method) &&
|
|
135
151
|
(suffix === "/rooms" ||
|
|
136
152
|
conversationRoute ||
|
|
137
|
-
|
|
153
|
+
webhookRoute ||
|
|
154
|
+
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard(?:\/sections\/[^/]+)?)$/.test(suffix) ||
|
|
138
155
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
|
|
139
156
|
/^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
|
|
140
|
-
/^\/devices\/[^/]+\/open$/.test(suffix)))))
|
|
157
|
+
/^\/devices\/[^/]+\/(open|remark)$/.test(suffix)))))
|
|
141
158
|
fail(404, "User route missing");
|
|
142
159
|
users.set(req, { device, account: { id: owner.id, username: owner.username } });
|
|
143
160
|
req.url = req.url.replace("/api/device-user/", "/api/");
|
|
@@ -156,21 +173,23 @@ export async function createDeviceHub(options) {
|
|
|
156
173
|
const suffix = req.path.slice("/api/agent".length);
|
|
157
174
|
if ((req.method === "GET" &&
|
|
158
175
|
(["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
159
|
-
/^\/rooms\/[^/]+(?:\/history)?$/.test(suffix) ||
|
|
176
|
+
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard(?:\/sections\/[^/]+)?))?$/.test(suffix) ||
|
|
160
177
|
/^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
|
|
161
178
|
(req.method === "POST" &&
|
|
162
179
|
(suffix === "/rooms" ||
|
|
163
180
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(suffix) ||
|
|
164
|
-
/^\/rooms\/[^/]+\/(?:messages|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix)))
|
|
181
|
+
/^\/rooms\/[^/]+\/(?:messages|blackboard|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel|reconcile|resume))?)?))?)$/.test(suffix))) ||
|
|
182
|
+
(req.method === "PUT" && /^\/rooms\/[^/]+\/blackboard(?:\/sections\/[^/]+)?$/.test(suffix)))
|
|
165
183
|
req.url = req.url.replace("/api/agent/", "/api/");
|
|
166
184
|
else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
|
|
167
185
|
fail(404, "Agent route missing");
|
|
168
186
|
next();
|
|
169
187
|
});
|
|
170
188
|
app.use((req, res, next) => {
|
|
171
|
-
if (req.headers.host !== origin.host)
|
|
189
|
+
if (!isIncomingWebhookRequest(req) && req.headers.host !== origin.host)
|
|
172
190
|
return res.status(421).json({ error: "Host rejected" });
|
|
173
|
-
if (!
|
|
191
|
+
if (!isIncomingWebhookRequest(req) &&
|
|
192
|
+
!agents.has(req) &&
|
|
174
193
|
!users.has(req) &&
|
|
175
194
|
!["GET", "HEAD", "OPTIONS"].includes(req.method) &&
|
|
176
195
|
req.headers.origin !== options.publicUrl)
|
|
@@ -178,16 +197,25 @@ export async function createDeviceHub(options) {
|
|
|
178
197
|
next();
|
|
179
198
|
});
|
|
180
199
|
const json = express.json({ limit: "32kb", strict: true });
|
|
200
|
+
const contractJson = express.json({ limit: MAX_CONTRACT_REQUEST_BYTES, strict: true });
|
|
201
|
+
const blackboardJson = express.json({ limit: "512kb", strict: true });
|
|
181
202
|
const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
|
|
182
203
|
const reportWrites = new HubRateLimiter(4096, 60000);
|
|
183
204
|
app.use((req, res, next) => {
|
|
184
205
|
if (agents.has(req) && req.path === "/api/agent/transfers")
|
|
185
206
|
return next();
|
|
207
|
+
if (req.method === "POST" &&
|
|
208
|
+
/^\/api\/rooms\/[^/]+\/(?:messages|tasks|conversations(?:\/[^/]+\/messages)?)$/.test(req.path))
|
|
209
|
+
return contractJson(req, res, next);
|
|
186
210
|
if (agents.has(req) && req.method === "POST" && /^\/api\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path)) {
|
|
187
211
|
if (!reportWrites.allow(agents.get(req).device.id))
|
|
188
212
|
return res.status(429).json({ error: "Too many report chunks" });
|
|
189
213
|
return reportJson(req, res, next);
|
|
190
214
|
}
|
|
215
|
+
if ((req.method === "PUT" || req.method === "POST") &&
|
|
216
|
+
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard(?:\/sections\/[^/]+)?$/.test(req.path)) {
|
|
217
|
+
return blackboardJson(req, res, next);
|
|
218
|
+
}
|
|
191
219
|
json(req, res, next);
|
|
192
220
|
});
|
|
193
221
|
const loginLimit = new HubRateLimiter(10, 60000);
|
|
@@ -198,11 +226,17 @@ export async function createDeviceHub(options) {
|
|
|
198
226
|
if (value.expiresAt <= Date.now())
|
|
199
227
|
pairs.delete(key);
|
|
200
228
|
};
|
|
229
|
+
const lockManager = createHubLockManager({
|
|
230
|
+
autoCleanupIntervalMs: 60000,
|
|
231
|
+
defaultTtlMs: currentSettings().resourceLockDefaultTtlMs,
|
|
232
|
+
persistPath: options.dataDir ? join(options.dataDir, "hub-locks.json") : undefined,
|
|
233
|
+
});
|
|
201
234
|
const ip = (req) => req.socket.remoteAddress ?? "unknown";
|
|
202
235
|
const visibleDevice = (device) => ({
|
|
203
236
|
id: device.id,
|
|
204
237
|
accountId: device.accountId,
|
|
205
238
|
name: device.name,
|
|
239
|
+
remark: device.remark ?? null,
|
|
206
240
|
createdAt: device.createdAt,
|
|
207
241
|
online: options.isOnline?.(device.id) ?? false,
|
|
208
242
|
url: (options.pathAccess ? `${origin.origin}/device/${encodeURIComponent(device.id)}/` : undefined) ??
|
|
@@ -267,6 +301,37 @@ export async function createDeviceHub(options) {
|
|
|
267
301
|
res.setHeader("Set-Cookie", auth.cookie("", true));
|
|
268
302
|
res.json({ ok: true });
|
|
269
303
|
});
|
|
304
|
+
app.post("/api/system/upgrade", async (req, res) => {
|
|
305
|
+
let current;
|
|
306
|
+
try {
|
|
307
|
+
current = account(req);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
const agent = await authenticateAgent(req);
|
|
311
|
+
if (agent)
|
|
312
|
+
current = agent.account;
|
|
313
|
+
}
|
|
314
|
+
if (!current)
|
|
315
|
+
fail(401, "Unauthorized");
|
|
316
|
+
res.json({ ok: true, message: "Hub upgrade initiated" });
|
|
317
|
+
setTimeout(async () => {
|
|
318
|
+
try {
|
|
319
|
+
const { spawn } = await import("node:child_process");
|
|
320
|
+
const { join } = await import("node:path");
|
|
321
|
+
const { getPkgRoot } = await import("../pkg-info.js");
|
|
322
|
+
const cliPath = join(getPkgRoot(), "bin", "pi-web-ui.mjs");
|
|
323
|
+
const child = spawn(process.execPath, [cliPath, "hub", "update"], {
|
|
324
|
+
detached: true,
|
|
325
|
+
stdio: "ignore",
|
|
326
|
+
windowsHide: true,
|
|
327
|
+
});
|
|
328
|
+
child.unref();
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
/* ignore */
|
|
332
|
+
}
|
|
333
|
+
}, 500);
|
|
334
|
+
});
|
|
270
335
|
app.post("/api/pair/start", (req, res) => {
|
|
271
336
|
if (!pairLimit.allow(ip(req)))
|
|
272
337
|
fail(429, "Too many attempts");
|
|
@@ -335,7 +400,12 @@ export async function createDeviceHub(options) {
|
|
|
335
400
|
fail(404, "Device revoked");
|
|
336
401
|
}
|
|
337
402
|
pairs.delete(key);
|
|
338
|
-
res.json({
|
|
403
|
+
res.json({
|
|
404
|
+
deviceId: pair.deviceId,
|
|
405
|
+
accountId: pair.accountId,
|
|
406
|
+
credential: pair.credential,
|
|
407
|
+
uiCredential: pair.uiCredential,
|
|
408
|
+
});
|
|
339
409
|
});
|
|
340
410
|
app.get("/api/info", (_req, res) => {
|
|
341
411
|
res.json({
|
|
@@ -352,7 +422,7 @@ export async function createDeviceHub(options) {
|
|
|
352
422
|
app.post("/api/devices/:id/revoke", async (req, res) => {
|
|
353
423
|
const owner = account(req);
|
|
354
424
|
const id = String(req.params.id);
|
|
355
|
-
await store.transact((draft) => {
|
|
425
|
+
const settlement = await store.transact((draft) => {
|
|
356
426
|
if (!draft.devices.some((device) => device.id === id && device.accountId === owner.id))
|
|
357
427
|
fail(404, "Device missing");
|
|
358
428
|
draft.devices = draft.devices.filter((device) => device.id !== id);
|
|
@@ -363,12 +433,28 @@ export async function createDeviceHub(options) {
|
|
|
363
433
|
if (room.primaryBotId && removedBots.has(room.primaryBotId))
|
|
364
434
|
delete room.primaryBotId;
|
|
365
435
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
436
|
+
// A revoked device can no longer continue its conversations: close them now so the next turn
|
|
437
|
+
// reports a reason instead of a late 409 against a Bot that no longer exists.
|
|
438
|
+
for (const conversation of draft.conversations)
|
|
439
|
+
if (!conversation.closed && removedBots.has(conversation.botId)) {
|
|
440
|
+
conversation.closed = true;
|
|
441
|
+
conversation.closedReason = "device_revoked";
|
|
442
|
+
conversation.updatedAt = Date.now();
|
|
370
443
|
}
|
|
444
|
+
const notices = [];
|
|
445
|
+
for (const task of [...draft.tasks]) {
|
|
446
|
+
if (task.deviceId !== id || (isTerminal(task.status) && !task.recoveryUntil))
|
|
447
|
+
continue;
|
|
448
|
+
task.cancelRequested = true;
|
|
449
|
+
const notice = recordTaskOutcome(draft, task, { status: "interrupted", report: "Device revoked; task interrupted." }, settlementContext());
|
|
450
|
+
if (notice)
|
|
451
|
+
notices.push(notice);
|
|
452
|
+
}
|
|
453
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
454
|
+
result.settledWakes.unshift(...notices);
|
|
455
|
+
return result;
|
|
371
456
|
});
|
|
457
|
+
await publishSettlementEffects(settlement);
|
|
372
458
|
for (const [key, pair] of pairs)
|
|
373
459
|
if (pair.deviceId === id)
|
|
374
460
|
pairs.delete(key);
|
|
@@ -436,6 +522,20 @@ export async function createDeviceHub(options) {
|
|
|
436
522
|
const bots = await store.transact((draft) => {
|
|
437
523
|
if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
|
|
438
524
|
fail(401, "Device revoked");
|
|
525
|
+
const changedBotIds = new Set(draft.bots
|
|
526
|
+
.filter((bot) => {
|
|
527
|
+
if (bot.accountId !== owner.id || bot.deviceId !== device.id)
|
|
528
|
+
return false;
|
|
529
|
+
const next = incoming.find((row) => row.id === bot.id);
|
|
530
|
+
return (!next ||
|
|
531
|
+
next.revision !== bot.revision ||
|
|
532
|
+
next.enabled !== bot.enabled ||
|
|
533
|
+
(next.tools !== undefined && JSON.stringify(next.tools) !== JSON.stringify(bot.tools)));
|
|
534
|
+
})
|
|
535
|
+
.map((bot) => bot.id));
|
|
536
|
+
for (const room of draft.rooms)
|
|
537
|
+
if (room.accountId === owner.id && room.botIds.some((id) => changedBotIds.has(id)))
|
|
538
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
439
539
|
if (draft.tasks.some((task) => task.deviceId === device.id &&
|
|
440
540
|
!isTerminal(task.status) &&
|
|
441
541
|
!incoming.some((bot) => bot.id === task.botId && bot.enabled && bot.revision === task.botRevision)))
|
|
@@ -473,7 +573,7 @@ export async function createDeviceHub(options) {
|
|
|
473
573
|
}
|
|
474
574
|
return draft.bots.filter((b) => b.deviceId === device.id);
|
|
475
575
|
});
|
|
476
|
-
res.json({ bots });
|
|
576
|
+
res.json({ bots, accountId: owner.id });
|
|
477
577
|
});
|
|
478
578
|
app.get("/api/rooms", (req, res) => res.json({
|
|
479
579
|
rooms: store
|
|
@@ -638,6 +738,569 @@ export async function createDeviceHub(options) {
|
|
|
638
738
|
app.get("/api/rooms/:id/events", (req, res) => {
|
|
639
739
|
groupEvents.connect(account(req).id, String(req.params.id), res, users.get(req)?.device.id);
|
|
640
740
|
});
|
|
741
|
+
app.get("/api/rooms/:id/locks", (req, res) => {
|
|
742
|
+
const state = store.snapshot();
|
|
743
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === account(req).id);
|
|
744
|
+
if (!room ||
|
|
745
|
+
(agents.has(req) &&
|
|
746
|
+
!state.bots.some((b) => b.enabled &&
|
|
747
|
+
b.deviceId === agents.get(req).device.id &&
|
|
748
|
+
b.accountId === room.accountId &&
|
|
749
|
+
room.botIds.includes(b.id))))
|
|
750
|
+
fail(404, "Room missing");
|
|
751
|
+
res.json(lockManager.getRoomLockInfo(room.id));
|
|
752
|
+
});
|
|
753
|
+
app.get("/api/rooms/:id/blackboard", (req, res) => {
|
|
754
|
+
const owner = account(req);
|
|
755
|
+
const state = store.snapshot();
|
|
756
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
757
|
+
if (!room)
|
|
758
|
+
fail(404, "Room missing");
|
|
759
|
+
if (agents.has(req)) {
|
|
760
|
+
const agent = agents.get(req);
|
|
761
|
+
const sourceBotId = (req.query.sourceBotId ?? req.body?.sourceBotId);
|
|
762
|
+
if (!sourceBotId)
|
|
763
|
+
fail(403, "Source Bot required");
|
|
764
|
+
const source = state.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
765
|
+
if (!source)
|
|
766
|
+
fail(403, "Source Bot access denied");
|
|
767
|
+
if (!room.botIds.includes(source.id))
|
|
768
|
+
fail(403, "Source Bot is not a room member");
|
|
769
|
+
}
|
|
770
|
+
res.json({ blackboard: room.blackboard ?? null });
|
|
771
|
+
});
|
|
772
|
+
const handleBlackboardUpdate = async (req, res) => {
|
|
773
|
+
const owner = account(req);
|
|
774
|
+
const { content, expectedVersion, title } = req.body ?? {};
|
|
775
|
+
const settings = currentSettings();
|
|
776
|
+
if (typeof content !== "string" || !content.trim())
|
|
777
|
+
fail(400, "Content must be a nonempty string");
|
|
778
|
+
if (Buffer.byteLength(content, "utf8") > settings.blackboardMaxBytes)
|
|
779
|
+
fail(400, `Content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
780
|
+
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content))
|
|
781
|
+
fail(400, "Content must not contain control characters");
|
|
782
|
+
if (typeof expectedVersion !== "number" || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0) {
|
|
783
|
+
fail(400, "expectedVersion must be a non-negative safe integer");
|
|
784
|
+
}
|
|
785
|
+
if (title !== undefined) {
|
|
786
|
+
if (typeof title !== "string" || title.length > 200 || /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(title)) {
|
|
787
|
+
fail(400, "Invalid title");
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
let updatedBy;
|
|
791
|
+
const stateBefore = store.snapshot();
|
|
792
|
+
if (agents.has(req)) {
|
|
793
|
+
const agent = agents.get(req);
|
|
794
|
+
const sourceBotId = (req.body?.sourceBotId ?? req.query?.sourceBotId);
|
|
795
|
+
if (!sourceBotId)
|
|
796
|
+
fail(403, "Source Bot required");
|
|
797
|
+
const source = stateBefore.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
798
|
+
if (!source)
|
|
799
|
+
fail(403, "Source Bot access denied");
|
|
800
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
801
|
+
if (!preRoom)
|
|
802
|
+
fail(404, "Room missing");
|
|
803
|
+
if (!preRoom.botIds.includes(source.id))
|
|
804
|
+
fail(403, "Source Bot is not a room member");
|
|
805
|
+
updatedBy = { type: "bot", id: source.id, name: source.name };
|
|
806
|
+
}
|
|
807
|
+
else {
|
|
808
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
809
|
+
if (!preRoom)
|
|
810
|
+
fail(404, "Room missing");
|
|
811
|
+
updatedBy = { type: "human", id: owner.id, name: owner.username };
|
|
812
|
+
}
|
|
813
|
+
const updatedBlackboard = await store.transact((draft) => {
|
|
814
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
815
|
+
if (!room)
|
|
816
|
+
fail(404, "Room missing");
|
|
817
|
+
if (agents.has(req) && !room.botIds.includes(updatedBy.id))
|
|
818
|
+
fail(403, "Source Bot is not a room member");
|
|
819
|
+
const current = room.blackboard;
|
|
820
|
+
if (current) {
|
|
821
|
+
if (current.version !== expectedVersion)
|
|
822
|
+
fail(409, "Version conflict");
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
if (expectedVersion !== 0)
|
|
826
|
+
fail(409, "Version conflict");
|
|
827
|
+
}
|
|
828
|
+
const nextVersion = current ? current.version + 1 : 1;
|
|
829
|
+
const nextBlackboard = {
|
|
830
|
+
version: nextVersion,
|
|
831
|
+
updatedAt: Date.now(),
|
|
832
|
+
updatedBy,
|
|
833
|
+
...(title?.trim() ? { title: title.trim() } : {}),
|
|
834
|
+
content,
|
|
835
|
+
...(req.body?.sections && typeof req.body.sections === "object" ? { sections: req.body.sections } : {}),
|
|
836
|
+
};
|
|
837
|
+
room.blackboard = nextBlackboard;
|
|
838
|
+
return nextBlackboard;
|
|
839
|
+
});
|
|
840
|
+
groupEvents.invalidate(String(req.params.id));
|
|
841
|
+
res.json({ ok: true, blackboard: updatedBlackboard });
|
|
842
|
+
};
|
|
843
|
+
app.put("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
844
|
+
app.post("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
845
|
+
const handleBlackboardSectionUpdate = async (req, res) => {
|
|
846
|
+
const owner = account(req);
|
|
847
|
+
const roomId = String(req.params.id);
|
|
848
|
+
const rawSectionId = String(req.params.sectionId || "").trim();
|
|
849
|
+
if (!rawSectionId || rawSectionId.length > 100 || /[\x00-\x1F\x7F]/.test(rawSectionId)) {
|
|
850
|
+
fail(400, "Invalid sectionId");
|
|
851
|
+
}
|
|
852
|
+
const sectionId = rawSectionId;
|
|
853
|
+
const { content, expectedVersion, title } = req.body ?? {};
|
|
854
|
+
const settings = currentSettings();
|
|
855
|
+
if (typeof content !== "string" || !content.trim())
|
|
856
|
+
fail(400, "Content must be a nonempty string");
|
|
857
|
+
if (Buffer.byteLength(content, "utf8") > settings.blackboardMaxBytes)
|
|
858
|
+
fail(400, `Content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
859
|
+
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content))
|
|
860
|
+
fail(400, "Content must not contain control characters");
|
|
861
|
+
if (expectedVersion !== undefined) {
|
|
862
|
+
if (typeof expectedVersion !== "number" || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0) {
|
|
863
|
+
fail(400, "expectedVersion must be a non-negative safe integer");
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
if (title !== undefined) {
|
|
867
|
+
if (typeof title !== "string" || title.length > 200 || /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(title)) {
|
|
868
|
+
fail(400, "Invalid title");
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
let updatedBy;
|
|
872
|
+
const stateBefore = store.snapshot();
|
|
873
|
+
if (agents.has(req)) {
|
|
874
|
+
const agent = agents.get(req);
|
|
875
|
+
const sourceBotId = (req.body?.sourceBotId ?? req.query?.sourceBotId);
|
|
876
|
+
if (!sourceBotId)
|
|
877
|
+
fail(403, "Source Bot required");
|
|
878
|
+
const source = stateBefore.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
879
|
+
if (!source)
|
|
880
|
+
fail(403, "Source Bot access denied");
|
|
881
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
882
|
+
if (!preRoom)
|
|
883
|
+
fail(404, "Room missing");
|
|
884
|
+
if (!preRoom.botIds.includes(source.id))
|
|
885
|
+
fail(403, "Source Bot is not a room member");
|
|
886
|
+
updatedBy = { type: "bot", id: source.id, name: source.name };
|
|
887
|
+
}
|
|
888
|
+
else {
|
|
889
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
890
|
+
if (!preRoom)
|
|
891
|
+
fail(404, "Room missing");
|
|
892
|
+
updatedBy = { type: "human", id: owner.id, name: owner.username };
|
|
893
|
+
}
|
|
894
|
+
const updatedBlackboard = await store.transact((draft) => {
|
|
895
|
+
const room = draft.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
896
|
+
if (!room)
|
|
897
|
+
fail(404, "Room missing");
|
|
898
|
+
if (agents.has(req) && !room.botIds.includes(updatedBy.id))
|
|
899
|
+
fail(403, "Source Bot is not a room member");
|
|
900
|
+
const current = room.blackboard;
|
|
901
|
+
if (expectedVersion !== undefined) {
|
|
902
|
+
if (current) {
|
|
903
|
+
if (current.version !== expectedVersion)
|
|
904
|
+
fail(409, "Version conflict");
|
|
905
|
+
}
|
|
906
|
+
else {
|
|
907
|
+
if (expectedVersion !== 0)
|
|
908
|
+
fail(409, "Version conflict");
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
const sections = current?.sections
|
|
912
|
+
? { ...current.sections }
|
|
913
|
+
: {};
|
|
914
|
+
if (Object.keys(sections).length === 0 && current?.content?.trim()) {
|
|
915
|
+
sections["main"] = {
|
|
916
|
+
id: "main",
|
|
917
|
+
title: current.title || "Main",
|
|
918
|
+
content: current.content,
|
|
919
|
+
updatedAt: current.updatedAt,
|
|
920
|
+
updatedBy: current.updatedBy,
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
const prevSection = sections[sectionId];
|
|
924
|
+
const sectionTitle = title?.trim() || prevSection?.title || sectionId;
|
|
925
|
+
const sectionUpdatedAt = Date.now();
|
|
926
|
+
sections[sectionId] = {
|
|
927
|
+
id: sectionId,
|
|
928
|
+
title: sectionTitle,
|
|
929
|
+
content,
|
|
930
|
+
updatedAt: sectionUpdatedAt,
|
|
931
|
+
updatedBy,
|
|
932
|
+
};
|
|
933
|
+
const compiledContent = Object.values(sections)
|
|
934
|
+
.map((sec) => `## ${sec.title}\n\n${sec.content}`)
|
|
935
|
+
.join("\n\n");
|
|
936
|
+
if (Buffer.byteLength(compiledContent, "utf8") > settings.blackboardMaxBytes) {
|
|
937
|
+
fail(400, `Aggregated blackboard content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
938
|
+
}
|
|
939
|
+
const nextVersion = current ? current.version + 1 : 1;
|
|
940
|
+
const nextBlackboard = {
|
|
941
|
+
version: nextVersion,
|
|
942
|
+
updatedAt: sectionUpdatedAt,
|
|
943
|
+
updatedBy,
|
|
944
|
+
...(current?.title ? { title: current.title } : {}),
|
|
945
|
+
content: compiledContent,
|
|
946
|
+
sections,
|
|
947
|
+
};
|
|
948
|
+
room.blackboard = nextBlackboard;
|
|
949
|
+
return nextBlackboard;
|
|
950
|
+
});
|
|
951
|
+
groupEvents.invalidate(roomId);
|
|
952
|
+
res.json({ ok: true, blackboard: updatedBlackboard });
|
|
953
|
+
};
|
|
954
|
+
app.put("/api/rooms/:id/blackboard/sections/:sectionId", handleBlackboardSectionUpdate);
|
|
955
|
+
app.post("/api/rooms/:id/blackboard/sections/:sectionId", handleBlackboardSectionUpdate);
|
|
956
|
+
// === Group Webhooks ===
|
|
957
|
+
app.get("/api/rooms/:id/webhooks", (req, res) => {
|
|
958
|
+
const owner = account(req);
|
|
959
|
+
if (agents.has(req))
|
|
960
|
+
fail(403, "Webhook management requires a user session");
|
|
961
|
+
const state = store.snapshot();
|
|
962
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
963
|
+
if (!room)
|
|
964
|
+
fail(404, "Room missing");
|
|
965
|
+
res.setHeader("Cache-Control", "no-store");
|
|
966
|
+
res.json({ webhooks: room.webhooks ?? [] });
|
|
967
|
+
});
|
|
968
|
+
app.post("/api/rooms/:id/webhooks", async (req, res) => {
|
|
969
|
+
const owner = account(req);
|
|
970
|
+
if (agents.has(req))
|
|
971
|
+
fail(403, "Webhook management requires a user session");
|
|
972
|
+
const validated = validateWebhookInput(req.body, false);
|
|
973
|
+
let created;
|
|
974
|
+
await store.transact((state) => {
|
|
975
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
976
|
+
if (!room)
|
|
977
|
+
fail(404, "Room missing");
|
|
978
|
+
if (!room.webhooks)
|
|
979
|
+
room.webhooks = [];
|
|
980
|
+
if (room.webhooks.length >= 32)
|
|
981
|
+
fail(409, "Maximum webhooks limit reached");
|
|
982
|
+
const now = Date.now();
|
|
983
|
+
created = {
|
|
984
|
+
id: randomUUID(),
|
|
985
|
+
roomId: room.id,
|
|
986
|
+
name: validated.name,
|
|
987
|
+
type: validated.type,
|
|
988
|
+
enabled: validated.enabled ?? true,
|
|
989
|
+
createdAt: now,
|
|
990
|
+
updatedAt: now,
|
|
991
|
+
...(validated.type === "incoming"
|
|
992
|
+
? {
|
|
993
|
+
token: createWebhookToken(),
|
|
994
|
+
allowBotTrigger: validated.allowBotTrigger ?? true,
|
|
995
|
+
}
|
|
996
|
+
: {
|
|
997
|
+
url: validated.url,
|
|
998
|
+
secret: validated.secret,
|
|
999
|
+
events: validated.events ?? [...ALLOWED_WEBHOOK_EVENTS],
|
|
1000
|
+
relayViaHub: validated.relayViaHub ?? true,
|
|
1001
|
+
}),
|
|
1002
|
+
};
|
|
1003
|
+
room.webhooks.push(created);
|
|
1004
|
+
});
|
|
1005
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1006
|
+
res.json({ webhook: created });
|
|
1007
|
+
});
|
|
1008
|
+
const handleWebhookUpdate = async (req, res) => {
|
|
1009
|
+
const owner = account(req);
|
|
1010
|
+
if (agents.has(req))
|
|
1011
|
+
fail(403, "Webhook management requires a user session");
|
|
1012
|
+
const validated = validateWebhookInput(req.body, true);
|
|
1013
|
+
let updated;
|
|
1014
|
+
await store.transact((state) => {
|
|
1015
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1016
|
+
if (!room)
|
|
1017
|
+
fail(404, "Room missing");
|
|
1018
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
1019
|
+
if (!hook)
|
|
1020
|
+
fail(404, "Webhook missing");
|
|
1021
|
+
if (validated.name !== undefined)
|
|
1022
|
+
hook.name = validated.name;
|
|
1023
|
+
if (validated.enabled !== undefined)
|
|
1024
|
+
hook.enabled = validated.enabled;
|
|
1025
|
+
if (hook.type === "incoming") {
|
|
1026
|
+
if (validated.allowBotTrigger !== undefined)
|
|
1027
|
+
hook.allowBotTrigger = validated.allowBotTrigger;
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
if (validated.url !== undefined)
|
|
1031
|
+
hook.url = validated.url;
|
|
1032
|
+
if (validated.secret !== undefined)
|
|
1033
|
+
hook.secret = validated.secret;
|
|
1034
|
+
if (validated.events !== undefined)
|
|
1035
|
+
hook.events = validated.events;
|
|
1036
|
+
if (validated.relayViaHub !== undefined)
|
|
1037
|
+
hook.relayViaHub = validated.relayViaHub;
|
|
1038
|
+
}
|
|
1039
|
+
hook.updatedAt = Date.now();
|
|
1040
|
+
updated = hook;
|
|
1041
|
+
});
|
|
1042
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1043
|
+
res.json({ webhook: updated });
|
|
1044
|
+
};
|
|
1045
|
+
app.put("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
|
|
1046
|
+
app.post("/api/rooms/:id/webhooks/:webhookId", handleWebhookUpdate);
|
|
1047
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/regenerate-token", async (req, res) => {
|
|
1048
|
+
const owner = account(req);
|
|
1049
|
+
if (agents.has(req))
|
|
1050
|
+
fail(403, "Webhook management requires a user session");
|
|
1051
|
+
let updated;
|
|
1052
|
+
await store.transact((state) => {
|
|
1053
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1054
|
+
if (!room)
|
|
1055
|
+
fail(404, "Room missing");
|
|
1056
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
1057
|
+
if (!hook)
|
|
1058
|
+
fail(404, "Webhook missing");
|
|
1059
|
+
if (hook.type !== "incoming")
|
|
1060
|
+
fail(400, "Only incoming webhooks have tokens");
|
|
1061
|
+
hook.token = createWebhookToken();
|
|
1062
|
+
hook.updatedAt = Date.now();
|
|
1063
|
+
updated = hook;
|
|
1064
|
+
});
|
|
1065
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1066
|
+
res.json({ webhook: updated });
|
|
1067
|
+
});
|
|
1068
|
+
const handleWebhookDelete = async (req, res) => {
|
|
1069
|
+
const owner = account(req);
|
|
1070
|
+
if (agents.has(req))
|
|
1071
|
+
fail(403, "Webhook management requires a user session");
|
|
1072
|
+
await store.transact((state) => {
|
|
1073
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1074
|
+
if (!room)
|
|
1075
|
+
fail(404, "Room missing");
|
|
1076
|
+
if (!room.webhooks?.some((w) => w.id === req.params.webhookId))
|
|
1077
|
+
fail(404, "Webhook missing");
|
|
1078
|
+
room.webhooks = room.webhooks.filter((w) => w.id !== req.params.webhookId);
|
|
1079
|
+
});
|
|
1080
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1081
|
+
res.json({ deleted: true });
|
|
1082
|
+
};
|
|
1083
|
+
app.delete("/api/rooms/:id/webhooks/:webhookId", handleWebhookDelete);
|
|
1084
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/delete", handleWebhookDelete);
|
|
1085
|
+
app.post("/api/rooms/:id/hub-relay", async (req, res) => {
|
|
1086
|
+
const owner = account(req);
|
|
1087
|
+
if (agents.has(req))
|
|
1088
|
+
fail(403, "Webhook management requires a user session");
|
|
1089
|
+
const rawUrl = req.body?.hubRelayBaseUrl;
|
|
1090
|
+
let baseUrl;
|
|
1091
|
+
if (rawUrl !== undefined && rawUrl !== null && rawUrl !== "") {
|
|
1092
|
+
if (typeof rawUrl !== "string")
|
|
1093
|
+
fail(400, "Invalid hubRelayBaseUrl");
|
|
1094
|
+
try {
|
|
1095
|
+
const parsed = new URL(rawUrl.trim());
|
|
1096
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
|
|
1097
|
+
fail(400, "Invalid protocol");
|
|
1098
|
+
baseUrl = parsed.origin;
|
|
1099
|
+
}
|
|
1100
|
+
catch {
|
|
1101
|
+
fail(400, "hubRelayBaseUrl must be a valid HTTP(S) URL");
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
await store.transact((state) => {
|
|
1105
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1106
|
+
if (!room)
|
|
1107
|
+
fail(404, "Room missing");
|
|
1108
|
+
room.hubRelayBaseUrl = baseUrl;
|
|
1109
|
+
});
|
|
1110
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1111
|
+
res.json({ hubRelayBaseUrl: baseUrl });
|
|
1112
|
+
});
|
|
1113
|
+
app.post("/api/rooms/:id/webhooks/:webhookId/test", async (req, res) => {
|
|
1114
|
+
const owner = account(req);
|
|
1115
|
+
if (agents.has(req))
|
|
1116
|
+
fail(403, "Webhook management requires a user session");
|
|
1117
|
+
const state = store.snapshot();
|
|
1118
|
+
const room = state.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1119
|
+
if (!room)
|
|
1120
|
+
fail(404, "Room missing");
|
|
1121
|
+
const hook = room.webhooks?.find((w) => w.id === req.params.webhookId);
|
|
1122
|
+
if (!hook)
|
|
1123
|
+
fail(404, "Webhook missing");
|
|
1124
|
+
if (hook.type !== "outgoing") {
|
|
1125
|
+
return res.json({ success: true, message: "Incoming webhook is active" });
|
|
1126
|
+
}
|
|
1127
|
+
if (!hook.url)
|
|
1128
|
+
fail(400, "Webhook URL missing");
|
|
1129
|
+
const result = await testOutgoingWebhook({ url: hook.url, secret: hook.secret });
|
|
1130
|
+
res.json(result);
|
|
1131
|
+
});
|
|
1132
|
+
app.post("/api/rooms/:id/webhooks/incoming/:webhookId", async (req, res) => {
|
|
1133
|
+
const roomId = String(req.params.id);
|
|
1134
|
+
const webhookId = String(req.params.webhookId);
|
|
1135
|
+
const snapshot = store.snapshot();
|
|
1136
|
+
const room = snapshot.rooms.find((r) => r.id === roomId);
|
|
1137
|
+
if (!room)
|
|
1138
|
+
return res.status(404).json({ error: "Room missing" });
|
|
1139
|
+
const webhook = room.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
|
|
1140
|
+
if (!webhook || webhook.enabled === false)
|
|
1141
|
+
return res.status(404).json({ error: "Webhook not found or disabled" });
|
|
1142
|
+
const bearer = req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization.slice(7) : undefined;
|
|
1143
|
+
const queryToken = typeof req.query?.token === "string" ? req.query.token : undefined;
|
|
1144
|
+
const headerToken = typeof req.headers["x-webhook-token"] === "string" ? req.headers["x-webhook-token"] : undefined;
|
|
1145
|
+
const bodyToken = typeof req.body?.token === "string" ? req.body.token : undefined;
|
|
1146
|
+
const providedToken = queryToken ?? bearer ?? headerToken ?? bodyToken;
|
|
1147
|
+
if (!providedToken || !webhook.token || !secureCompareTokens(providedToken, webhook.token)) {
|
|
1148
|
+
return res.status(401).json({ error: "Invalid webhook token" });
|
|
1149
|
+
}
|
|
1150
|
+
const rawText = req.body?.text;
|
|
1151
|
+
if (typeof rawText !== "string" || !rawText.trim()) {
|
|
1152
|
+
return res.status(400).json({ error: "Missing or empty text" });
|
|
1153
|
+
}
|
|
1154
|
+
const content = text(rawText);
|
|
1155
|
+
const senderName = typeof req.body?.senderName === "string" && req.body.senderName.trim()
|
|
1156
|
+
? text(req.body.senderName.trim(), 80)
|
|
1157
|
+
: webhook.name;
|
|
1158
|
+
const replyToMessageId = typeof req.body?.replyToMessageId === "string" ? text(req.body.replyToMessageId, 128) : undefined;
|
|
1159
|
+
const inputTargets = Array.isArray(req.body?.targetBotIds)
|
|
1160
|
+
? req.body.targetBotIds.filter((id) => typeof id === "string")
|
|
1161
|
+
: [];
|
|
1162
|
+
const settings = currentSettings();
|
|
1163
|
+
const key = randomUUID();
|
|
1164
|
+
const fingerprint = hashSecret(JSON.stringify({
|
|
1165
|
+
content,
|
|
1166
|
+
senderName,
|
|
1167
|
+
webhookId,
|
|
1168
|
+
inputTargets,
|
|
1169
|
+
replyToMessageId,
|
|
1170
|
+
}));
|
|
1171
|
+
const result = await store.transact((draft) => {
|
|
1172
|
+
const activeRoom = draft.rooms.find((r) => r.id === roomId);
|
|
1173
|
+
if (!activeRoom)
|
|
1174
|
+
fail(404, "Room missing");
|
|
1175
|
+
const activeWebhook = activeRoom.webhooks?.find((w) => w.id === webhookId && w.type === "incoming");
|
|
1176
|
+
if (!activeWebhook || activeWebhook.enabled === false)
|
|
1177
|
+
fail(404, "Webhook missing or disabled");
|
|
1178
|
+
if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === activeRoom.id)) {
|
|
1179
|
+
fail(400, "Reply target message is not in this room");
|
|
1180
|
+
}
|
|
1181
|
+
const targets = [];
|
|
1182
|
+
const allowTrigger = activeWebhook.allowBotTrigger !== false;
|
|
1183
|
+
if (allowTrigger) {
|
|
1184
|
+
if (inputTargets.length > 0) {
|
|
1185
|
+
targets.push(...inputTargets);
|
|
1186
|
+
}
|
|
1187
|
+
else {
|
|
1188
|
+
if (settings.allowBotMentions) {
|
|
1189
|
+
targets.push(...groupMentionTargets(content, activeRoom, draft.bots, settings.botMentionBudgetPerTurn));
|
|
1190
|
+
}
|
|
1191
|
+
if (!targets.length && activeRoom.primaryBotId) {
|
|
1192
|
+
if (activeRoom.botIds.includes(activeRoom.primaryBotId) &&
|
|
1193
|
+
validBot(draft, activeRoom.primaryBotId, activeRoom.accountId)) {
|
|
1194
|
+
targets.push(activeRoom.primaryBotId);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
if (targets.some((id) => !activeRoom.botIds.includes(id) || !validBot(draft, id, activeRoom.accountId))) {
|
|
1200
|
+
fail(400, "Invalid target Bot");
|
|
1201
|
+
}
|
|
1202
|
+
const now = Date.now();
|
|
1203
|
+
const rootId = randomUUID();
|
|
1204
|
+
const tasks = targets.map((botId, index) => {
|
|
1205
|
+
const targetBot = validBot(draft, botId, activeRoom.accountId);
|
|
1206
|
+
return {
|
|
1207
|
+
id: index === 0 ? rootId : randomUUID(),
|
|
1208
|
+
rootTaskId: rootId,
|
|
1209
|
+
dispatchDepth: 0,
|
|
1210
|
+
...(index === 0 ? { dispatchCount: targets.length } : {}),
|
|
1211
|
+
attemptId: randomUUID(),
|
|
1212
|
+
roomId: activeRoom.id,
|
|
1213
|
+
accountId: activeRoom.accountId,
|
|
1214
|
+
botId,
|
|
1215
|
+
deviceId: targetBot.deviceId,
|
|
1216
|
+
botRevision: targetBot.revision,
|
|
1217
|
+
text: content,
|
|
1218
|
+
status: "queued",
|
|
1219
|
+
createdAt: now,
|
|
1220
|
+
updatedAt: now,
|
|
1221
|
+
};
|
|
1222
|
+
});
|
|
1223
|
+
for (const task of tasks) {
|
|
1224
|
+
task.kind = "message";
|
|
1225
|
+
const targetConv = draft.conversations
|
|
1226
|
+
.filter((entry) => entry.roomId === activeRoom.id &&
|
|
1227
|
+
entry.accountId === activeRoom.accountId &&
|
|
1228
|
+
entry.botId === task.botId &&
|
|
1229
|
+
!entry.closed &&
|
|
1230
|
+
entry.botRevision === task.botRevision &&
|
|
1231
|
+
entry.deviceId === task.deviceId)
|
|
1232
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)[0];
|
|
1233
|
+
if (targetConv) {
|
|
1234
|
+
task.conversationId = targetConv.id;
|
|
1235
|
+
task.resume = true;
|
|
1236
|
+
advanceConversationTask(draft, targetConv, task);
|
|
1237
|
+
targetConv.rootTaskId = task.rootTaskId;
|
|
1238
|
+
targetConv.updatedAt = now;
|
|
1239
|
+
targetConv.dispatchDepth = 0;
|
|
1240
|
+
}
|
|
1241
|
+
else {
|
|
1242
|
+
establishConversation(draft, task);
|
|
1243
|
+
}
|
|
1244
|
+
recordConversationTurn(draft, task, key, fingerprint);
|
|
1245
|
+
}
|
|
1246
|
+
const message = {
|
|
1247
|
+
id: randomUUID(),
|
|
1248
|
+
roomId: activeRoom.id,
|
|
1249
|
+
accountId: activeRoom.accountId,
|
|
1250
|
+
text: content,
|
|
1251
|
+
sender: {
|
|
1252
|
+
type: "webhook",
|
|
1253
|
+
id: activeWebhook.id,
|
|
1254
|
+
name: senderName,
|
|
1255
|
+
},
|
|
1256
|
+
createdAt: now,
|
|
1257
|
+
taskIds: tasks.map((t) => t.id),
|
|
1258
|
+
...(targets.length ? { targetBotIds: targets } : {}),
|
|
1259
|
+
...(replyToMessageId ? { replyToMessageId } : {}),
|
|
1260
|
+
...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
|
|
1261
|
+
...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
|
|
1262
|
+
};
|
|
1263
|
+
const context = tasks.length
|
|
1264
|
+
? groupTaskContext(activeRoom, draft.bots, draft.messages, settings.groupContextBytes)
|
|
1265
|
+
: undefined;
|
|
1266
|
+
draft.tasks.push(...tasks);
|
|
1267
|
+
draft.messages.push(message);
|
|
1268
|
+
draft.receipts.push({
|
|
1269
|
+
accountId: activeRoom.accountId,
|
|
1270
|
+
roomId: activeRoom.id,
|
|
1271
|
+
key,
|
|
1272
|
+
fingerprint,
|
|
1273
|
+
messageId: message.id,
|
|
1274
|
+
createdAt: message.createdAt,
|
|
1275
|
+
});
|
|
1276
|
+
const oldMessages = draft.messages.filter((m) => m.roomId === activeRoom.id).slice(0, -getHistoryLimit());
|
|
1277
|
+
const removed = new Set(oldMessages.map((m) => m.id));
|
|
1278
|
+
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
1279
|
+
trimRoomReceipts(draft, activeRoom.id);
|
|
1280
|
+
const oldTasks = new Set(draft.tasks
|
|
1281
|
+
.filter((t) => t.roomId === activeRoom.id &&
|
|
1282
|
+
isTerminal(t.status) &&
|
|
1283
|
+
!taskHasImmutableEvidence(t) &&
|
|
1284
|
+
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1285
|
+
.slice(0, -getHistoryLimit())
|
|
1286
|
+
.map((t) => t.id));
|
|
1287
|
+
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
1288
|
+
trimConversationHistory(draft, activeRoom.id);
|
|
1289
|
+
trimClosedConversations(draft, activeRoom.id);
|
|
1290
|
+
return { message, tasks, context, roomId: activeRoom.id };
|
|
1291
|
+
});
|
|
1292
|
+
for (const task of result.tasks) {
|
|
1293
|
+
if (task.status !== "waiting")
|
|
1294
|
+
await deliverTask(task, result.context);
|
|
1295
|
+
}
|
|
1296
|
+
groupEvents.invalidate(result.roomId);
|
|
1297
|
+
dispatchGroupWebhook(store, result.roomId, "message", result.message);
|
|
1298
|
+
res.json({
|
|
1299
|
+
success: true,
|
|
1300
|
+
message: result.message,
|
|
1301
|
+
tasks: result.tasks.map(publicTask),
|
|
1302
|
+
});
|
|
1303
|
+
});
|
|
641
1304
|
// === Task Details, Journal, and Reports ===
|
|
642
1305
|
app.get("/api/rooms/:id/tasks/:taskId", (req, res) => {
|
|
643
1306
|
const acc = account(req);
|
|
@@ -654,9 +1317,9 @@ export async function createDeviceHub(options) {
|
|
|
654
1317
|
const interactions = state.interactions
|
|
655
1318
|
? state.interactions.filter((i) => i.taskId === task.id)
|
|
656
1319
|
: [];
|
|
657
|
-
const deliveries = state.deliveries
|
|
658
|
-
|
|
659
|
-
|
|
1320
|
+
const deliveries = state.deliveries.filter((d) => d.accountId === acc.id &&
|
|
1321
|
+
d.roomId === room.id &&
|
|
1322
|
+
(d.taskId === task.id || d.artifactRef?.artifactTaskId === task.id));
|
|
660
1323
|
res.json({
|
|
661
1324
|
task: {
|
|
662
1325
|
id: task.id,
|
|
@@ -674,6 +1337,13 @@ export async function createDeviceHub(options) {
|
|
|
674
1337
|
parentTaskId: task.parentTaskId,
|
|
675
1338
|
conversationId: task.conversationId,
|
|
676
1339
|
report: task.report,
|
|
1340
|
+
...(task.attenuatedTools ? { attenuatedTools: task.attenuatedTools } : {}),
|
|
1341
|
+
...(task.executionMode ? { executionMode: task.executionMode } : {}),
|
|
1342
|
+
...(task.contract ? { contract: task.contract } : {}),
|
|
1343
|
+
...(task.contextManifest ? { contextManifest: task.contextManifest } : {}),
|
|
1344
|
+
...(task.artifact ? { artifact: task.artifact } : {}),
|
|
1345
|
+
...(task.executionCompleted !== undefined ? { executionCompleted: task.executionCompleted } : {}),
|
|
1346
|
+
...(task.artifactProduced !== undefined ? { artifactProduced: task.artifactProduced } : {}),
|
|
677
1347
|
},
|
|
678
1348
|
reportMeta,
|
|
679
1349
|
interactionCount: interactions.length,
|
|
@@ -688,9 +1358,11 @@ export async function createDeviceHub(options) {
|
|
|
688
1358
|
deliveries: deliveries.map((d) => ({
|
|
689
1359
|
id: d.id,
|
|
690
1360
|
commit: d.commit,
|
|
1361
|
+
artifactRef: d.artifactRef,
|
|
691
1362
|
branch: d.branch,
|
|
692
1363
|
summary: d.summary,
|
|
693
|
-
|
|
1364
|
+
reportedCheckCount: d.checks.length,
|
|
1365
|
+
passed: d.checks.length > 0 && d.checks.every((c) => c.status === "passed"),
|
|
694
1366
|
})),
|
|
695
1367
|
});
|
|
696
1368
|
});
|
|
@@ -759,6 +1431,8 @@ export async function createDeviceHub(options) {
|
|
|
759
1431
|
planOnly: false,
|
|
760
1432
|
resume: Boolean(conversation),
|
|
761
1433
|
...(conversation ? { conversationId: conversation.id } : {}),
|
|
1434
|
+
...(task.sourceBotId ? { sourceBotId: task.sourceBotId } : {}),
|
|
1435
|
+
...(task.attenuatedTools ? { attenuatedTools: [...task.attenuatedTools] } : {}),
|
|
762
1436
|
};
|
|
763
1437
|
draft.tasks.push(nextTask);
|
|
764
1438
|
if (conversation) {
|
|
@@ -790,6 +1464,52 @@ export async function createDeviceHub(options) {
|
|
|
790
1464
|
res.json({ ok: true, plan, nextTaskId: nextTask.id });
|
|
791
1465
|
void drainConversation(nextTask.conversationId).catch(() => { });
|
|
792
1466
|
});
|
|
1467
|
+
app.post("/api/rooms/:id/tasks/:taskId/steer", async (req, res) => {
|
|
1468
|
+
const acc = account(req);
|
|
1469
|
+
const roomId = String(req.params.id);
|
|
1470
|
+
const taskId = String(req.params.taskId);
|
|
1471
|
+
const instruction = text(req.body?.text);
|
|
1472
|
+
if (!instruction)
|
|
1473
|
+
fail(400, "Steering instruction required");
|
|
1474
|
+
const snapshot = store.snapshot();
|
|
1475
|
+
const room = snapshot.rooms.find((r) => r.id === roomId && r.accountId === acc.id);
|
|
1476
|
+
if (!room)
|
|
1477
|
+
fail(404, "Room missing");
|
|
1478
|
+
const task = snapshot.tasks.find((t) => t.id === taskId && t.roomId === roomId && t.accountId === acc.id);
|
|
1479
|
+
if (!task)
|
|
1480
|
+
fail(404, "Task missing");
|
|
1481
|
+
if (task.status !== "running")
|
|
1482
|
+
fail(409, "Steering is only allowed on running tasks");
|
|
1483
|
+
await taskJournalManager
|
|
1484
|
+
.append(task.id, {
|
|
1485
|
+
botId: task.botId,
|
|
1486
|
+
attemptId: task.attemptId,
|
|
1487
|
+
type: "progress",
|
|
1488
|
+
phase: "running",
|
|
1489
|
+
summary: `In-flight steering: ${instruction.slice(0, 100)}`,
|
|
1490
|
+
output: instruction,
|
|
1491
|
+
}, { roomId: task.roomId, accountId: task.accountId })
|
|
1492
|
+
.catch(() => { });
|
|
1493
|
+
await store.transact((draft) => {
|
|
1494
|
+
draft.messages.push({
|
|
1495
|
+
id: randomUUID(),
|
|
1496
|
+
roomId,
|
|
1497
|
+
accountId: acc.id,
|
|
1498
|
+
text: `🕹️ **[飞行中即时转向 / In-flight Steering]** @${task.botId}:\n> ${instruction}`,
|
|
1499
|
+
sender: { type: "human", id: acc.id, name: acc.username },
|
|
1500
|
+
createdAt: Date.now(),
|
|
1501
|
+
taskIds: [task.id],
|
|
1502
|
+
});
|
|
1503
|
+
});
|
|
1504
|
+
let steered = false;
|
|
1505
|
+
if (options.relay?.steerTask) {
|
|
1506
|
+
const relayResult = await options.relay
|
|
1507
|
+
.steerTask(task.deviceId, task.id, task.attemptId, instruction)
|
|
1508
|
+
.catch(() => ({ steered: false }));
|
|
1509
|
+
steered = relayResult.steered;
|
|
1510
|
+
}
|
|
1511
|
+
res.json({ success: true, taskId: task.id, steered });
|
|
1512
|
+
});
|
|
793
1513
|
app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
|
|
794
1514
|
const acc = account(req);
|
|
795
1515
|
const state = store.snapshot();
|
|
@@ -934,6 +1654,8 @@ export async function createDeviceHub(options) {
|
|
|
934
1654
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
935
1655
|
if (!room)
|
|
936
1656
|
fail(404, "Room missing");
|
|
1657
|
+
if (operation !== "rename")
|
|
1658
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
937
1659
|
if (operation === "rename")
|
|
938
1660
|
room.name = text(req.body?.name, 128);
|
|
939
1661
|
if (operation === "members") {
|
|
@@ -978,6 +1700,9 @@ export async function createDeviceHub(options) {
|
|
|
978
1700
|
}
|
|
979
1701
|
return { room };
|
|
980
1702
|
});
|
|
1703
|
+
if (operation === "delete" || operation === "clear") {
|
|
1704
|
+
lockManager.clearRoom(String(req.params.id));
|
|
1705
|
+
}
|
|
981
1706
|
res.json(result);
|
|
982
1707
|
});
|
|
983
1708
|
}
|
|
@@ -988,6 +1713,9 @@ export async function createDeviceHub(options) {
|
|
|
988
1713
|
const actor = { accountId: owner.id, bot: ownBot(req, draft) };
|
|
989
1714
|
return (kind === "deliveries" ? addDelivery : addReview)(draft, req.params.id, req.params.conversationId, actor, req.body);
|
|
990
1715
|
});
|
|
1716
|
+
if (kind === "deliveries") {
|
|
1717
|
+
dispatchGroupWebhook(store, req.params.id, "delivery", record);
|
|
1718
|
+
}
|
|
991
1719
|
res.json(kind === "deliveries" ? { delivery: record } : { review: record });
|
|
992
1720
|
});
|
|
993
1721
|
}
|
|
@@ -997,11 +1725,14 @@ export async function createDeviceHub(options) {
|
|
|
997
1725
|
const conversation = snapshot.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
998
1726
|
if (!conversation)
|
|
999
1727
|
fail(404, "Conversation missing");
|
|
1000
|
-
res.json({
|
|
1728
|
+
res.json({
|
|
1729
|
+
integrations: listIntegrations(snapshot, req.params.conversationId),
|
|
1730
|
+
canResumePublication: !agents.has(req) && conversation.accountId === owner.id,
|
|
1731
|
+
});
|
|
1001
1732
|
});
|
|
1002
1733
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations", async (req, res) => {
|
|
1003
1734
|
const owner = account(req);
|
|
1004
|
-
const actor = { accountId: owner.id };
|
|
1735
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1005
1736
|
if (!options.relay?.callDevice)
|
|
1006
1737
|
fail(503, "Device relay unavailable");
|
|
1007
1738
|
const driver = {
|
|
@@ -1012,7 +1743,7 @@ export async function createDeviceHub(options) {
|
|
|
1012
1743
|
});
|
|
1013
1744
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", async (req, res) => {
|
|
1014
1745
|
const owner = account(req);
|
|
1015
|
-
const actor = { accountId: owner.id };
|
|
1746
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1016
1747
|
if (!options.relay?.callDevice)
|
|
1017
1748
|
fail(503, "Device relay unavailable");
|
|
1018
1749
|
const driver = {
|
|
@@ -1023,7 +1754,7 @@ export async function createDeviceHub(options) {
|
|
|
1023
1754
|
});
|
|
1024
1755
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", async (req, res) => {
|
|
1025
1756
|
const owner = account(req);
|
|
1026
|
-
const actor = { accountId: owner.id };
|
|
1757
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1027
1758
|
if (!options.relay?.callDevice)
|
|
1028
1759
|
fail(503, "Device relay unavailable");
|
|
1029
1760
|
const driver = {
|
|
@@ -1032,9 +1763,43 @@ export async function createDeviceHub(options) {
|
|
|
1032
1763
|
const result = await hubConfirmIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
|
|
1033
1764
|
res.json({ integration: result });
|
|
1034
1765
|
});
|
|
1766
|
+
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/reconcile", async (req, res) => {
|
|
1767
|
+
const owner = account(req);
|
|
1768
|
+
const agent = agents.get(req);
|
|
1769
|
+
// Historical queries keep the authenticated Bot identity even after its registry entry is disabled/deleted.
|
|
1770
|
+
const actor = {
|
|
1771
|
+
accountId: owner.id,
|
|
1772
|
+
...(agent
|
|
1773
|
+
? { originalBot: { id: req.body?.sourceBotId, accountId: agent.account.id, deviceId: agent.device.id } }
|
|
1774
|
+
: {}),
|
|
1775
|
+
};
|
|
1776
|
+
if (agent && (typeof actor.originalBot?.id !== "string" || !actor.originalBot.id))
|
|
1777
|
+
fail(403, "Source Bot access denied");
|
|
1778
|
+
if (!options.relay?.callDevice)
|
|
1779
|
+
fail(503, "Device relay unavailable");
|
|
1780
|
+
const result = await hubReconcileIntegration(store, req.params.id, req.params.conversationId, actor, req.params.integrationId, {
|
|
1781
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
1782
|
+
});
|
|
1783
|
+
res.json({ integration: result });
|
|
1784
|
+
});
|
|
1785
|
+
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/resume", async (req, res) => {
|
|
1786
|
+
const owner = account(req);
|
|
1787
|
+
if (agents.has(req))
|
|
1788
|
+
fail(403, "Publication resume requires a human account owner");
|
|
1789
|
+
const input = req.body;
|
|
1790
|
+
if (!input ||
|
|
1791
|
+
[input.intentId, input.intentDigest, input.candidateSha].some((value) => typeof value !== "string" || !value))
|
|
1792
|
+
fail(400, "Exact publication intent and candidate required");
|
|
1793
|
+
if (!options.relay?.callDevice)
|
|
1794
|
+
fail(503, "Device relay unavailable");
|
|
1795
|
+
const result = await hubResumeIntegration(store, req.params.id, req.params.conversationId, { accountId: owner.id }, req.params.integrationId, { intentId: input.intentId, intentDigest: input.intentDigest, candidateSha: input.candidateSha }, {
|
|
1796
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
1797
|
+
});
|
|
1798
|
+
res.json({ integration: result });
|
|
1799
|
+
});
|
|
1035
1800
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", async (req, res) => {
|
|
1036
1801
|
const owner = account(req);
|
|
1037
|
-
const actor = { accountId: owner.id };
|
|
1802
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1038
1803
|
if (!options.relay?.callDevice)
|
|
1039
1804
|
fail(503, "Device relay unavailable");
|
|
1040
1805
|
const driver = {
|
|
@@ -1050,23 +1815,32 @@ export async function createDeviceHub(options) {
|
|
|
1050
1815
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1051
1816
|
if (!conversation || !room)
|
|
1052
1817
|
fail(404, "Conversation missing");
|
|
1818
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1053
1819
|
const source = ownBot(req, draft);
|
|
1054
1820
|
if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
|
|
1055
1821
|
fail(403, "Bot may stop only its own conversation");
|
|
1056
1822
|
conversation.closed = true;
|
|
1057
|
-
|
|
1823
|
+
conversation.closedReason = "stopped";
|
|
1824
|
+
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id &&
|
|
1825
|
+
(taskPending(t) || (!t.outcomeFingerprint && t.recoveryUntil !== undefined)));
|
|
1826
|
+
const notices = [];
|
|
1058
1827
|
for (const task of tasks) {
|
|
1059
1828
|
task.cancelRequested = true;
|
|
1060
|
-
if (task.status === "queued"
|
|
1829
|
+
if ((task.status === "queued" || task.status === "waiting") &&
|
|
1830
|
+
!hasTaskLease(task) &&
|
|
1831
|
+
!deliveredTasks.has(task.id)) {
|
|
1061
1832
|
task.stopConfirmed = true;
|
|
1062
|
-
task
|
|
1063
|
-
|
|
1064
|
-
|
|
1833
|
+
const notice = recordTaskOutcome(draft, task, { status: "interrupted", report: "Conversation stopped before delivery." }, settlementContext());
|
|
1834
|
+
if (notice)
|
|
1835
|
+
notices.push(notice);
|
|
1065
1836
|
}
|
|
1066
1837
|
}
|
|
1067
|
-
|
|
1838
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
1839
|
+
settlement.settledWakes.unshift(...notices);
|
|
1840
|
+
return { tasks, settlement };
|
|
1068
1841
|
});
|
|
1069
|
-
|
|
1842
|
+
await publishSettlementEffects(pending.settlement);
|
|
1843
|
+
for (const task of pending.tasks) {
|
|
1070
1844
|
if (task.stopConfirmed)
|
|
1071
1845
|
continue;
|
|
1072
1846
|
const confirmed = await options.relay
|
|
@@ -1074,21 +1848,50 @@ export async function createDeviceHub(options) {
|
|
|
1074
1848
|
.catch(() => ({ stopped: false }));
|
|
1075
1849
|
if (!confirmed?.stopped)
|
|
1076
1850
|
continue;
|
|
1077
|
-
await store.transact((draft) => {
|
|
1851
|
+
const settlement = await store.transact((draft) => {
|
|
1078
1852
|
const current = draft.tasks.find((t) => t.id === task.id && t.attemptId === task.attemptId);
|
|
1079
1853
|
if (!current)
|
|
1080
1854
|
return;
|
|
1081
1855
|
current.stopConfirmed = true;
|
|
1082
|
-
current
|
|
1083
|
-
|
|
1084
|
-
|
|
1856
|
+
const notice = recordTaskOutcome(draft, current, { status: "interrupted", report: "Conversation stopped." }, settlementContext());
|
|
1857
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
1858
|
+
if (notice)
|
|
1859
|
+
result.settledWakes.unshift(notice);
|
|
1860
|
+
return result;
|
|
1085
1861
|
});
|
|
1862
|
+
if (settlement)
|
|
1863
|
+
await publishSettlementEffects(settlement);
|
|
1864
|
+
await releaseLocksAndWake(String(req.params.id), task.id);
|
|
1086
1865
|
}
|
|
1087
1866
|
const remaining = store
|
|
1088
1867
|
.snapshot()
|
|
1089
1868
|
.tasks.filter((t) => t.conversationId === req.params.conversationId && taskPending(t));
|
|
1090
1869
|
res.json({ stopped: remaining.length === 0, pending: remaining.length });
|
|
1091
1870
|
});
|
|
1871
|
+
app.post("/api/rooms/:id/conversations/:conversationId/delete", async (req, res) => {
|
|
1872
|
+
const owner = account(req);
|
|
1873
|
+
if (agents.has(req))
|
|
1874
|
+
fail(403, "Conversation deletion requires a user session");
|
|
1875
|
+
const result = await store.transact((draft) => {
|
|
1876
|
+
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1877
|
+
const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1878
|
+
if (!room || !conversation)
|
|
1879
|
+
fail(404, "Conversation missing");
|
|
1880
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1881
|
+
if (draft.tasks.some((t) => t.conversationId === conversation.id && taskPending(t)))
|
|
1882
|
+
throw Object.assign(new Error("Stop the conversation before deleting it"), {
|
|
1883
|
+
status: 409,
|
|
1884
|
+
code: "ACTIVE_TASKS",
|
|
1885
|
+
});
|
|
1886
|
+
// Delivery/review records are the audit trail; deleting them is a separate, explicit decision.
|
|
1887
|
+
if (conversationHasAuditRecords(draft, conversation.id))
|
|
1888
|
+
fail(409, "Conversation has delivery history; audit records are retained");
|
|
1889
|
+
dropConversationRecords(draft, conversation.id);
|
|
1890
|
+
return { deleted: true };
|
|
1891
|
+
});
|
|
1892
|
+
groupEvents.invalidate(String(req.params.id));
|
|
1893
|
+
res.json(result);
|
|
1894
|
+
});
|
|
1092
1895
|
app.post("/api/rooms/:id/conversations/:conversationId/attention", async (req, res) => {
|
|
1093
1896
|
const owner = account(req);
|
|
1094
1897
|
const question = text(req.body?.question, 2000);
|
|
@@ -1181,10 +1984,24 @@ export async function createDeviceHub(options) {
|
|
|
1181
1984
|
const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
|
|
1182
1985
|
if (!conversation)
|
|
1183
1986
|
fail(404, "Conversation missing");
|
|
1184
|
-
const
|
|
1987
|
+
const evidenceKind = req.query.evidenceKind ?? "report";
|
|
1988
|
+
if (!["report", "artifact", "acceptance"].includes(evidenceKind))
|
|
1989
|
+
fail(400, "Invalid evidenceKind");
|
|
1990
|
+
const allowedQueries = [
|
|
1991
|
+
"sourceBotId",
|
|
1992
|
+
"taskId",
|
|
1993
|
+
"deliveryId",
|
|
1994
|
+
"offset",
|
|
1995
|
+
"limit",
|
|
1996
|
+
"expectedDigest",
|
|
1997
|
+
"digest",
|
|
1998
|
+
"evidenceKind",
|
|
1999
|
+
];
|
|
1185
2000
|
for (const q of Object.keys(req.query)) {
|
|
1186
2001
|
if (!allowedQueries.includes(q))
|
|
1187
2002
|
fail(400, `Unknown query parameter: ${q}`);
|
|
2003
|
+
if (typeof req.query[q] !== "string")
|
|
2004
|
+
fail(400, `Invalid query parameter: ${q}`);
|
|
1188
2005
|
}
|
|
1189
2006
|
let offset = 0;
|
|
1190
2007
|
if (req.query.offset !== undefined) {
|
|
@@ -1195,7 +2012,7 @@ export async function createDeviceHub(options) {
|
|
|
1195
2012
|
let limit = 8192;
|
|
1196
2013
|
if (req.query.limit !== undefined) {
|
|
1197
2014
|
limit = Number(req.query.limit);
|
|
1198
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 65536)
|
|
2015
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > (evidenceKind !== "report" ? 24 * 1024 : 65536))
|
|
1199
2016
|
fail(400, "Invalid limit");
|
|
1200
2017
|
}
|
|
1201
2018
|
const expectedDigest = typeof req.query.expectedDigest === "string"
|
|
@@ -1203,12 +2020,97 @@ export async function createDeviceHub(options) {
|
|
|
1203
2020
|
: typeof req.query.digest === "string"
|
|
1204
2021
|
? req.query.digest
|
|
1205
2022
|
: undefined;
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
2023
|
+
if (req.query.expectedDigest !== undefined &&
|
|
2024
|
+
req.query.digest !== undefined &&
|
|
2025
|
+
req.query.expectedDigest !== req.query.digest)
|
|
2026
|
+
fail(409, "Conflicting evidence digest selectors");
|
|
2027
|
+
const deliveryId = req.query.deliveryId === undefined ? undefined : text(req.query.deliveryId, 128).trim();
|
|
2028
|
+
if (deliveryId === "")
|
|
2029
|
+
fail(400, "Invalid deliveryId");
|
|
1209
2030
|
const targetDelivery = deliveryId
|
|
1210
|
-
? state.deliveries.find((d) => d.id === deliveryId &&
|
|
2031
|
+
? state.deliveries.find((d) => d.id === deliveryId &&
|
|
2032
|
+
d.conversationId === conversation.id &&
|
|
2033
|
+
d.roomId === room.id &&
|
|
2034
|
+
d.accountId === owner.id)
|
|
1211
2035
|
: undefined;
|
|
2036
|
+
if (deliveryId && !targetDelivery)
|
|
2037
|
+
fail(404, "Delivery missing");
|
|
2038
|
+
const boundArtifactTaskId = evidenceKind !== "report" ? targetDelivery?.artifactRef?.artifactTaskId : undefined;
|
|
2039
|
+
if (evidenceKind !== "report" && targetDelivery && !boundArtifactTaskId)
|
|
2040
|
+
fail(409, "Delivery has no artifact subject");
|
|
2041
|
+
if (boundArtifactTaskId && req.query.taskId !== undefined && req.query.taskId !== boundArtifactTaskId)
|
|
2042
|
+
fail(409, "Task conflicts with delivery artifact subject");
|
|
2043
|
+
const taskId = boundArtifactTaskId ?? (typeof req.query.taskId === "string" ? req.query.taskId : conversation.latestTaskId);
|
|
2044
|
+
const targetTask = state.tasks.find((t) => t.id === taskId && t.conversationId === conversation.id && t.roomId === room.id && t.accountId === owner.id);
|
|
2045
|
+
if (evidenceKind !== "report" &&
|
|
2046
|
+
targetDelivery?.artifactRef &&
|
|
2047
|
+
(!targetTask ||
|
|
2048
|
+
!artifactRefsMatch(targetDelivery.artifactRef, deriveArtifactSubject(state, targetTask, { allowSuperseded: true }))))
|
|
2049
|
+
fail(409, "Delivery artifact subject changed");
|
|
2050
|
+
if (evidenceKind === "acceptance") {
|
|
2051
|
+
if (!targetTask?.contract)
|
|
2052
|
+
fail(404, "Task acceptance contract missing");
|
|
2053
|
+
const sealed = validateWorkContract(targetTask.contract);
|
|
2054
|
+
if (!sealed.valid)
|
|
2055
|
+
fail(409, "Invalid sealed acceptance contract");
|
|
2056
|
+
const contract = sealed.contract;
|
|
2057
|
+
if (expectedDigest !== undefined && expectedDigest !== contract.digest)
|
|
2058
|
+
fail(409, "Acceptance contract version digest mismatch");
|
|
2059
|
+
const bytes = Buffer.from(canonicalizeJson(contract.acceptanceCriteria ?? []), "utf8");
|
|
2060
|
+
if (offset > bytes.length)
|
|
2061
|
+
fail(400, "Invalid offset");
|
|
2062
|
+
const end = Math.min(offset + limit, bytes.length);
|
|
2063
|
+
res.json({
|
|
2064
|
+
conversationId: conversation.id,
|
|
2065
|
+
taskId,
|
|
2066
|
+
...(deliveryId ? { deliveryId } : {}),
|
|
2067
|
+
acceptance: {
|
|
2068
|
+
contractId: contract.id,
|
|
2069
|
+
contractRevision: contract.revision,
|
|
2070
|
+
contractDigest: contract.digest,
|
|
2071
|
+
criteriaDigest: createHash("sha256").update(bytes).digest("hex"),
|
|
2072
|
+
criteriaCount: (contract.acceptanceCriteria ?? []).length,
|
|
2073
|
+
},
|
|
2074
|
+
content: {
|
|
2075
|
+
encoding: "base64",
|
|
2076
|
+
data: bytes.subarray(offset, end).toString("base64"),
|
|
2077
|
+
offset,
|
|
2078
|
+
limit,
|
|
2079
|
+
totalBytes: bytes.length,
|
|
2080
|
+
nextOffset: end < bytes.length ? end : null,
|
|
2081
|
+
truncated: offset > 0 || end < bytes.length,
|
|
2082
|
+
},
|
|
2083
|
+
});
|
|
2084
|
+
return;
|
|
2085
|
+
}
|
|
2086
|
+
if (evidenceKind === "artifact") {
|
|
2087
|
+
if (!targetTask?.artifact)
|
|
2088
|
+
fail(404, "Task artifact missing");
|
|
2089
|
+
if (expectedDigest !== undefined && expectedDigest !== targetTask.artifact.digest)
|
|
2090
|
+
fail(409, "Artifact version digest mismatch");
|
|
2091
|
+
const { patchBase64, ...artifact } = targetTask.artifact;
|
|
2092
|
+
if (typeof patchBase64 !== "string")
|
|
2093
|
+
fail(404, "Artifact patch missing");
|
|
2094
|
+
const patch = Buffer.from(patchBase64, "base64");
|
|
2095
|
+
if (offset > patch.length)
|
|
2096
|
+
fail(400, "Invalid offset");
|
|
2097
|
+
const end = Math.min(offset + limit, patch.length);
|
|
2098
|
+
res.json({
|
|
2099
|
+
conversationId: conversation.id,
|
|
2100
|
+
taskId,
|
|
2101
|
+
artifact,
|
|
2102
|
+
content: {
|
|
2103
|
+
encoding: "base64",
|
|
2104
|
+
data: patch.subarray(offset, end).toString("base64"),
|
|
2105
|
+
offset,
|
|
2106
|
+
limit,
|
|
2107
|
+
totalBytes: patch.length,
|
|
2108
|
+
nextOffset: end < patch.length ? end : null,
|
|
2109
|
+
truncated: offset > 0 || end < patch.length,
|
|
2110
|
+
},
|
|
2111
|
+
});
|
|
2112
|
+
return;
|
|
2113
|
+
}
|
|
1212
2114
|
let evidence;
|
|
1213
2115
|
if (targetTask?.attemptId) {
|
|
1214
2116
|
const reportResult = taskReportStore.getReport(targetTask.id, targetTask.attemptId, owner.id, room.id, {
|
|
@@ -1357,6 +2259,7 @@ export async function createDeviceHub(options) {
|
|
|
1357
2259
|
.map((c) => ({
|
|
1358
2260
|
...c,
|
|
1359
2261
|
status: conversationStatus(state, c),
|
|
2262
|
+
stale: conversationStale(state, c),
|
|
1360
2263
|
...deliverySummary(state, c.id, !req.params.conversationId),
|
|
1361
2264
|
}));
|
|
1362
2265
|
if (!req.params.conversationId)
|
|
@@ -1374,6 +2277,7 @@ export async function createDeviceHub(options) {
|
|
|
1374
2277
|
});
|
|
1375
2278
|
app.post([
|
|
1376
2279
|
"/api/rooms/:id/messages",
|
|
2280
|
+
"/api/rooms/:id/tasks",
|
|
1377
2281
|
"/api/rooms/:id/conversations",
|
|
1378
2282
|
"/api/rooms/:id/conversations/:conversationId/messages",
|
|
1379
2283
|
], async (req, res) => {
|
|
@@ -1382,6 +2286,7 @@ export async function createDeviceHub(options) {
|
|
|
1382
2286
|
const conversationApi = req.path.includes("/conversations");
|
|
1383
2287
|
const conversationId = req.params.conversationId;
|
|
1384
2288
|
const kind = req.body?.kind ?? "message";
|
|
2289
|
+
const settings = currentSettings();
|
|
1385
2290
|
if (!["message", "request", "reply"].includes(kind))
|
|
1386
2291
|
fail(400, "Invalid message kind");
|
|
1387
2292
|
const requestId = req.body?.requestId === undefined
|
|
@@ -1397,7 +2302,48 @@ export async function createDeviceHub(options) {
|
|
|
1397
2302
|
const attentionId = req.body?.attentionId === undefined ? undefined : text(req.body.attentionId, 128);
|
|
1398
2303
|
const key = req.body?.idempotencyKey === undefined ? randomUUID() : text(req.body.idempotencyKey, 128);
|
|
1399
2304
|
const planOnly = req.body?.planOnly === true;
|
|
1400
|
-
const
|
|
2305
|
+
const replyToMessageId = req.body?.replyToMessageId === undefined ? undefined : text(req.body.replyToMessageId, 128);
|
|
2306
|
+
const dependsOnTaskId = req.body?.dependsOnTaskId === undefined ? undefined : text(req.body.dependsOnTaskId, 128);
|
|
2307
|
+
let resourceLocks;
|
|
2308
|
+
try {
|
|
2309
|
+
if (req.body?.resourceLocks !== undefined) {
|
|
2310
|
+
resourceLocks = validateResourceLocks(req.body.resourceLocks);
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
catch (err) {
|
|
2314
|
+
fail(400, err?.message ?? "Invalid resourceLocks");
|
|
2315
|
+
}
|
|
2316
|
+
if (req.body?.contract !== undefined &&
|
|
2317
|
+
(!req.body.contract || typeof req.body.contract !== "object" || Array.isArray(req.body.contract)))
|
|
2318
|
+
fail(400, "Contract input must be a non-null object");
|
|
2319
|
+
const rawExecutionMode = req.body?.executionMode;
|
|
2320
|
+
const contractExecutionMode = req.body?.contract?.executionMode;
|
|
2321
|
+
if (contractExecutionMode !== undefined && contractExecutionMode !== "chat" && contractExecutionMode !== "code")
|
|
2322
|
+
fail(400, "Invalid contract executionMode: must be 'chat' or 'code'");
|
|
2323
|
+
if (rawExecutionMode !== undefined &&
|
|
2324
|
+
contractExecutionMode !== undefined &&
|
|
2325
|
+
rawExecutionMode !== contractExecutionMode) {
|
|
2326
|
+
fail(400, "executionMode conflicts with contract.executionMode.");
|
|
2327
|
+
}
|
|
2328
|
+
const executionMode = rawExecutionMode ?? contractExecutionMode ?? "chat";
|
|
2329
|
+
if (rawExecutionMode !== undefined && rawExecutionMode !== "chat" && rawExecutionMode !== "code") {
|
|
2330
|
+
fail(400, "Invalid executionMode: must be 'chat' or 'code'");
|
|
2331
|
+
}
|
|
2332
|
+
let contract;
|
|
2333
|
+
if (req.body?.contract !== undefined || executionMode === "code") {
|
|
2334
|
+
try {
|
|
2335
|
+
const stableFallbackId = `contract-${createHash("sha256").update(`${owner.id}:${req.params.id}:${key}`).digest("hex").slice(0, 16)}`;
|
|
2336
|
+
contract = createWorkContract({
|
|
2337
|
+
id: req.body?.contract?.id ?? stableFallbackId,
|
|
2338
|
+
...(req.body?.contract ?? {}),
|
|
2339
|
+
executionMode,
|
|
2340
|
+
}, content);
|
|
2341
|
+
}
|
|
2342
|
+
catch (err) {
|
|
2343
|
+
fail(400, err?.message ?? "Invalid work contract");
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
const fingerprintFields = {
|
|
1401
2347
|
content,
|
|
1402
2348
|
attentionId,
|
|
1403
2349
|
targets,
|
|
@@ -1407,10 +2353,22 @@ export async function createDeviceHub(options) {
|
|
|
1407
2353
|
transfer,
|
|
1408
2354
|
parentTaskId,
|
|
1409
2355
|
planOnly,
|
|
2356
|
+
replyToMessageId,
|
|
2357
|
+
resourceLocks,
|
|
2358
|
+
executionMode,
|
|
2359
|
+
contractDigest: contract?.digest,
|
|
2360
|
+
contractId: contract?.id,
|
|
2361
|
+
contractRevision: contract?.revision,
|
|
1410
2362
|
sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
|
|
1411
2363
|
sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
|
|
1412
2364
|
senderType: agents.has(req) ? "bot" : "human",
|
|
1413
|
-
}
|
|
2365
|
+
};
|
|
2366
|
+
const fingerprint = hashSecret(JSON.stringify(fingerprintFields));
|
|
2367
|
+
// v45 chat receipts predate the optional execution contract fields.
|
|
2368
|
+
const legacyFingerprint = executionMode === "chat" && !contract
|
|
2369
|
+
? hashSecret(JSON.stringify({ ...fingerprintFields, executionMode: undefined }))
|
|
2370
|
+
: undefined;
|
|
2371
|
+
const matchesFingerprint = (stored) => stored === fingerprint || (legacyFingerprint !== undefined && stored === legacyFingerprint);
|
|
1414
2372
|
const result = await store.transact((draft) => {
|
|
1415
2373
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1416
2374
|
if (!room)
|
|
@@ -1432,6 +2390,17 @@ export async function createDeviceHub(options) {
|
|
|
1432
2390
|
}
|
|
1433
2391
|
if (source && !room.botIds.includes(source.id))
|
|
1434
2392
|
fail(403, "Source Bot is not a room member");
|
|
2393
|
+
if (replyToMessageId && !draft.messages.some((m) => m.id === replyToMessageId && m.roomId === room.id))
|
|
2394
|
+
fail(400, "Reply target message is not in this room");
|
|
2395
|
+
if (dependsOnTaskId && !draft.tasks.some((m) => m.id === dependsOnTaskId && m.roomId === room.id))
|
|
2396
|
+
fail(400, "Dependency target task is not in this room");
|
|
2397
|
+
const depTask = dependsOnTaskId ? draft.tasks.find((t) => t.id === dependsOnTaskId) : undefined;
|
|
2398
|
+
const dependencyActive = Boolean(depTask);
|
|
2399
|
+
// The Hub owns dispatch semantics: a human message that only names Bots in its text must not
|
|
2400
|
+
// silently fall back to the primary Bot just because a client did not pre-resolve the mentions.
|
|
2401
|
+
const canParseMentions = (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
|
|
2402
|
+
if (canParseMentions)
|
|
2403
|
+
targets.push(...groupMentionTargets(content, room, draft.bots, settings.botMentionBudgetPerTurn));
|
|
1435
2404
|
if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
|
|
1436
2405
|
fail(400, "Invalid target Bot");
|
|
1437
2406
|
if (source &&
|
|
@@ -1448,8 +2417,16 @@ export async function createDeviceHub(options) {
|
|
|
1448
2417
|
m.idempotencyKey === key &&
|
|
1449
2418
|
draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
|
|
1450
2419
|
if (prior) {
|
|
1451
|
-
if (prior.fingerprint
|
|
2420
|
+
if (!matchesFingerprint(prior.fingerprint))
|
|
1452
2421
|
fail(409, "Idempotency key reused");
|
|
2422
|
+
const priorTask = draft.tasks.find((t) => t.id === prior.taskId);
|
|
2423
|
+
if (priorTask) {
|
|
2424
|
+
if (priorTask.contract?.digest !== contract?.digest ||
|
|
2425
|
+
priorTask.contract?.revision !== contract?.revision ||
|
|
2426
|
+
(priorTask.executionMode ?? "chat") !== executionMode) {
|
|
2427
|
+
fail(409, "Idempotency key reused with different contract");
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
1453
2430
|
return {
|
|
1454
2431
|
message: draft.messages.find((m) => m.taskIds.includes(prior.taskId)),
|
|
1455
2432
|
tasks: draft.tasks.filter((t) => t.id === prior.taskId),
|
|
@@ -1459,14 +2436,38 @@ export async function createDeviceHub(options) {
|
|
|
1459
2436
|
}
|
|
1460
2437
|
const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
|
|
1461
2438
|
if (receipt) {
|
|
1462
|
-
if (receipt.fingerprint
|
|
2439
|
+
if (!matchesFingerprint(receipt.fingerprint))
|
|
1463
2440
|
fail(409, "Idempotency key reused");
|
|
2441
|
+
const priorReceiptTask = draft.tasks.find((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id));
|
|
2442
|
+
if (priorReceiptTask) {
|
|
2443
|
+
if (priorReceiptTask.contract?.digest !== contract?.digest ||
|
|
2444
|
+
priorReceiptTask.contract?.revision !== contract?.revision ||
|
|
2445
|
+
(priorReceiptTask.executionMode ?? "chat") !== executionMode) {
|
|
2446
|
+
fail(409, "Idempotency key reused with different contract");
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
1464
2449
|
return {
|
|
1465
2450
|
message: draft.messages.find((m) => m.id === receipt.messageId),
|
|
1466
2451
|
tasks: draft.tasks.filter((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id)),
|
|
1467
2452
|
duplicate: true,
|
|
1468
2453
|
};
|
|
1469
2454
|
}
|
|
2455
|
+
if (contract) {
|
|
2456
|
+
assertNoApplyingIntegration(draft, owner.id, room.id, undefined, contract.id);
|
|
2457
|
+
const existingTasks = draft.tasks.filter((t) => t.roomId === room.id && t.accountId === owner.id && t.contract?.id === contract.id);
|
|
2458
|
+
if (existingTasks.some((t) => t.contract.revision === contract.revision && t.contract.digest !== contract.digest))
|
|
2459
|
+
fail(409, "Contract id and revision already bind different content");
|
|
2460
|
+
// Queued leases and recovery represent live work. Replace only settled versions.
|
|
2461
|
+
if (existingTasks.some((t) => t.contract.revision < contract.revision && (!isTerminal(t.status) || isRecoveringTask(t, Date.now()))))
|
|
2462
|
+
fail(409, "Cannot advance contract revision while an older revision is active");
|
|
2463
|
+
if (depTask?.contract?.id === contract.id && depTask.contract.revision !== contract.revision)
|
|
2464
|
+
fail(409, "A contract revision cannot inherit acceptance from a different revision");
|
|
2465
|
+
for (const existing of existingTasks) {
|
|
2466
|
+
if (existing.contract && existing.contract.revision > contract.revision) {
|
|
2467
|
+
fail(409, `Contract '${contract.id}' already has a newer revision ${existing.contract.revision} (cannot submit older revision ${contract.revision})`);
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
}
|
|
1470
2471
|
// Resolve implicit human targets after replay detection so retries remain stable across configuration changes.
|
|
1471
2472
|
if (!source && !conversationApi && !targets.length && room.primaryBotId) {
|
|
1472
2473
|
if (!room.botIds.includes(room.primaryBotId) || !validBot(draft, room.primaryBotId, owner.id))
|
|
@@ -1529,59 +2530,123 @@ export async function createDeviceHub(options) {
|
|
|
1529
2530
|
const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
|
|
1530
2531
|
if (planOnly && targets.some((id) => !validBot(draft, id, owner.id)?.tools?.includes("plan_update")))
|
|
1531
2532
|
fail(409, "Planning requires plan_update authorization in each Bot tool allowlist");
|
|
1532
|
-
if (targets.length && depth >
|
|
2533
|
+
if (targets.length && depth > settings.maxDispatchDepth)
|
|
1533
2534
|
fail(409, "Dispatch depth exhausted");
|
|
1534
|
-
if (targets.length && (root?.dispatchCount ?? 0) + targets.length >
|
|
2535
|
+
if (targets.length && (root?.dispatchCount ?? 0) + targets.length > settings.maxDispatchBudget)
|
|
1535
2536
|
fail(409, "Dispatch budget exhausted");
|
|
1536
2537
|
if (root && targets.length)
|
|
1537
2538
|
root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
|
|
1538
|
-
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
|
|
2539
|
+
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
|
|
2540
|
+
getHistoryLimit())
|
|
1539
2541
|
fail(409, "Too many active tasks");
|
|
1540
|
-
if (!conversation &&
|
|
1541
|
-
|
|
2542
|
+
if (!conversation &&
|
|
2543
|
+
draft.conversations.filter((c) => c.roomId === room.id && !c.closed).length + targets.length >
|
|
2544
|
+
getHistoryLimit())
|
|
2545
|
+
fail(409, "Too many open conversations; stop or delete conversations to free capacity");
|
|
1542
2546
|
const now = Date.now();
|
|
1543
2547
|
const rootId = root?.id ?? randomUUID();
|
|
1544
|
-
const
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
2548
|
+
const isPipeline = targets.length > 1 && (req.body?.pipeline === true || content.includes("->"));
|
|
2549
|
+
const tasks = targets.map((botId, index) => {
|
|
2550
|
+
const targetBot = validBot(draft, botId, owner.id);
|
|
2551
|
+
let attenuatedTools;
|
|
2552
|
+
if (source) {
|
|
2553
|
+
const rawSourceTools = source.tools ?? [];
|
|
2554
|
+
const sourceTools = parent?.attenuatedTools
|
|
2555
|
+
? rawSourceTools.filter((t) => !parent.attenuatedTools.includes(t))
|
|
2556
|
+
: rawSourceTools;
|
|
2557
|
+
const attenuated = computeAttenuatedTools(sourceTools, targetBot.tools ?? []);
|
|
2558
|
+
if (attenuated.length > 0) {
|
|
2559
|
+
attenuatedTools = attenuated;
|
|
2560
|
+
}
|
|
2561
|
+
}
|
|
2562
|
+
const isWaitingInPipeline = isPipeline && index > 0;
|
|
2563
|
+
return {
|
|
2564
|
+
id: !root && index === 0 ? rootId : randomUUID(),
|
|
2565
|
+
rootTaskId: rootId,
|
|
2566
|
+
dispatchDepth: depth,
|
|
2567
|
+
...(!root && index === 0 ? { dispatchCount: targets.length } : {}),
|
|
2568
|
+
attemptId: randomUUID(),
|
|
2569
|
+
roomId: room.id,
|
|
2570
|
+
accountId: owner.id,
|
|
2571
|
+
botId,
|
|
2572
|
+
deviceId: targetBot.deviceId,
|
|
2573
|
+
botRevision: targetBot.revision,
|
|
2574
|
+
...(source ? { sourceBotId: source.id } : {}),
|
|
2575
|
+
text: content,
|
|
2576
|
+
status: isWaitingInPipeline
|
|
2577
|
+
? "waiting"
|
|
2578
|
+
: dependencyActive
|
|
2579
|
+
? "waiting"
|
|
2580
|
+
: "queued",
|
|
2581
|
+
...(isWaitingInPipeline
|
|
2582
|
+
? {
|
|
2583
|
+
blockReason: "dependency",
|
|
2584
|
+
blockReasonDetail: "",
|
|
2585
|
+
}
|
|
2586
|
+
: dependencyActive
|
|
2587
|
+
? {
|
|
2588
|
+
blockReason: "dependency_waiting",
|
|
2589
|
+
blockReasonDetail: `Waiting for dependency task ${dependsOnTaskId}`,
|
|
2590
|
+
dependsOnTaskId,
|
|
2591
|
+
}
|
|
2592
|
+
: dependsOnTaskId
|
|
2593
|
+
? { dependsOnTaskId }
|
|
2594
|
+
: {}),
|
|
2595
|
+
createdAt: now,
|
|
2596
|
+
updatedAt: now,
|
|
2597
|
+
...(resourceLocks && resourceLocks.length ? { resourceLocks } : {}),
|
|
2598
|
+
...(planOnly ? { planOnly: true, plan: { state: "draft", steps: [] } } : {}),
|
|
2599
|
+
...(transfer ? { handoff: transfer } : {}),
|
|
2600
|
+
...(parentTaskId ? { parentTaskId } : {}),
|
|
2601
|
+
...(attenuatedTools ? { attenuatedTools } : {}),
|
|
2602
|
+
executionMode,
|
|
2603
|
+
...(contract ? { contract } : {}),
|
|
2604
|
+
};
|
|
2605
|
+
});
|
|
2606
|
+
if (isPipeline) {
|
|
2607
|
+
for (let i = 1; i < tasks.length; i++) {
|
|
2608
|
+
const prev = tasks[i - 1];
|
|
2609
|
+
tasks[i].dependsOnTaskId = prev.id;
|
|
2610
|
+
tasks[i].blockReason = "dependency";
|
|
2611
|
+
tasks[i].blockReasonDetail = `Waiting for prior pipeline task ${prev.id} (@${prev.botId})`;
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
1564
2614
|
for (const task of tasks) {
|
|
1565
2615
|
task.kind = kind;
|
|
1566
2616
|
task.sourceConversationId = parent?.conversationId;
|
|
1567
2617
|
task.requestId = requestId;
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
2618
|
+
const targetConv = conversation && conversation.botId === task.botId
|
|
2619
|
+
? conversation
|
|
2620
|
+
: !source && !conversationApi && req.body?.newConversation !== true
|
|
2621
|
+
? draft.conversations
|
|
2622
|
+
.filter((entry) => entry.roomId === room.id &&
|
|
2623
|
+
entry.accountId === owner.id &&
|
|
2624
|
+
entry.botId === task.botId &&
|
|
2625
|
+
!entry.closed &&
|
|
2626
|
+
entry.botRevision === task.botRevision &&
|
|
2627
|
+
entry.deviceId === task.deviceId)
|
|
2628
|
+
.sort((a, b) => b.updatedAt - a.updatedAt)[0]
|
|
2629
|
+
: undefined;
|
|
2630
|
+
if (targetConv) {
|
|
2631
|
+
task.conversationId = targetConv.id;
|
|
2632
|
+
task.resume = task.executionMode !== "code";
|
|
2633
|
+
advanceConversationTask(draft, targetConv, task);
|
|
2634
|
+
targetConv.rootTaskId = task.rootTaskId;
|
|
2635
|
+
targetConv.updatedAt = now;
|
|
2636
|
+
targetConv.dispatchDepth = depth;
|
|
1575
2637
|
}
|
|
1576
2638
|
else
|
|
1577
2639
|
establishConversation(draft, task);
|
|
1578
2640
|
recordConversationTurn(draft, task, key, fingerprint);
|
|
1579
2641
|
}
|
|
2642
|
+
const messageText = isPipeline
|
|
2643
|
+
? `${content}\n\n⛓️ **[流水线编排 / Pipeline Execution]**: ${targets.map((id) => `@${id}`).join(" ➔ ")}`
|
|
2644
|
+
: content;
|
|
1580
2645
|
const message = {
|
|
1581
2646
|
id: randomUUID(),
|
|
1582
2647
|
roomId: room.id,
|
|
1583
2648
|
accountId: owner.id,
|
|
1584
|
-
text:
|
|
2649
|
+
text: messageText,
|
|
1585
2650
|
sender: source
|
|
1586
2651
|
? { type: "bot", id: source.id, name: source.name, sourceDeviceId: source.deviceId }
|
|
1587
2652
|
: {
|
|
@@ -1593,31 +2658,53 @@ export async function createDeviceHub(options) {
|
|
|
1593
2658
|
createdAt: now,
|
|
1594
2659
|
taskIds: tasks.map((t) => t.id),
|
|
1595
2660
|
targetBotIds: targets,
|
|
2661
|
+
...(replyToMessageId ? { replyToMessageId } : {}),
|
|
1596
2662
|
...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
|
|
1597
2663
|
...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
|
|
1598
2664
|
};
|
|
1599
2665
|
// Freeze shared context before any recipient starts. Parallel answers cannot leak into siblings.
|
|
1600
|
-
const context = tasks.length
|
|
2666
|
+
const context = tasks.length
|
|
2667
|
+
? groupTaskContext(room, draft.bots, draft.messages, settings.groupContextBytes)
|
|
2668
|
+
: undefined;
|
|
1601
2669
|
draft.tasks.push(...tasks);
|
|
1602
2670
|
draft.messages.push(message);
|
|
1603
|
-
draft.receipts.push({
|
|
1604
|
-
|
|
2671
|
+
draft.receipts.push({
|
|
2672
|
+
accountId: owner.id,
|
|
2673
|
+
roomId: room.id,
|
|
2674
|
+
key,
|
|
2675
|
+
fingerprint,
|
|
2676
|
+
messageId: message.id,
|
|
2677
|
+
createdAt: message.createdAt,
|
|
2678
|
+
});
|
|
2679
|
+
const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -getHistoryLimit());
|
|
1605
2680
|
const removed = new Set(oldMessages.map((m) => m.id));
|
|
2681
|
+
// Retention evicts messages, never the replay guard: a retry must not re-dispatch evicted work.
|
|
1606
2682
|
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
1607
|
-
draft
|
|
2683
|
+
trimRoomReceipts(draft, room.id);
|
|
1608
2684
|
const oldTasks = new Set(draft.tasks
|
|
1609
2685
|
.filter((t) => t.roomId === room.id &&
|
|
1610
2686
|
isTerminal(t.status) &&
|
|
2687
|
+
!taskHasImmutableEvidence(t) &&
|
|
1611
2688
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1612
|
-
.slice(0, -
|
|
2689
|
+
.slice(0, -getHistoryLimit())
|
|
1613
2690
|
.map((t) => t.id));
|
|
1614
2691
|
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
1615
2692
|
trimConversationHistory(draft, room.id);
|
|
1616
|
-
|
|
2693
|
+
trimClosedConversations(draft, room.id);
|
|
2694
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
2695
|
+
return { message, tasks, duplicate: false, context, settlement };
|
|
1617
2696
|
});
|
|
1618
|
-
if (!result.duplicate)
|
|
1619
|
-
|
|
1620
|
-
await
|
|
2697
|
+
if (!result.duplicate) {
|
|
2698
|
+
if (result.settlement)
|
|
2699
|
+
await publishSettlementEffects(result.settlement);
|
|
2700
|
+
for (const task of result.tasks) {
|
|
2701
|
+
if (task.status === "queued")
|
|
2702
|
+
await deliverTask(task, result.context);
|
|
2703
|
+
}
|
|
2704
|
+
if (result.message) {
|
|
2705
|
+
dispatchGroupWebhook(store, req.params.id, "message", result.message);
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
1621
2708
|
const state = store.snapshot();
|
|
1622
2709
|
res.json({
|
|
1623
2710
|
...(conversationApi
|
|
@@ -1630,6 +2717,28 @@ export async function createDeviceHub(options) {
|
|
|
1630
2717
|
tasks: result.tasks.map((task) => publicTask(state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task)),
|
|
1631
2718
|
});
|
|
1632
2719
|
});
|
|
2720
|
+
app.post("/api/devices/:id/remark", async (req, res) => {
|
|
2721
|
+
const owner = account(req);
|
|
2722
|
+
const id = String(req.params.id);
|
|
2723
|
+
const rawRemark = req.body?.remark;
|
|
2724
|
+
if (rawRemark !== null && rawRemark !== undefined && typeof rawRemark !== "string") {
|
|
2725
|
+
fail(400, "Invalid remark");
|
|
2726
|
+
}
|
|
2727
|
+
const remark = typeof rawRemark === "string" ? rawRemark.trim().slice(0, 80) : "";
|
|
2728
|
+
const updated = await store.transact((draft) => {
|
|
2729
|
+
const target = draft.devices.find((d) => d.id === id && d.accountId === owner.id);
|
|
2730
|
+
if (!target)
|
|
2731
|
+
fail(404, "Device missing");
|
|
2732
|
+
if (remark) {
|
|
2733
|
+
target.remark = remark;
|
|
2734
|
+
}
|
|
2735
|
+
else {
|
|
2736
|
+
delete target.remark;
|
|
2737
|
+
}
|
|
2738
|
+
return target;
|
|
2739
|
+
});
|
|
2740
|
+
res.json({ device: visibleDevice(publicDevice(updated)) });
|
|
2741
|
+
});
|
|
1633
2742
|
for (const action of ["alias", "portal"])
|
|
1634
2743
|
app.post(`/api/devices/:id/${action}`, async (req, res) => {
|
|
1635
2744
|
const owner = account(req);
|
|
@@ -1723,21 +2832,163 @@ export async function createDeviceHub(options) {
|
|
|
1723
2832
|
});
|
|
1724
2833
|
// Accepted queued tasks remain in flight until a terminal event, including asynchronous relay delivery.
|
|
1725
2834
|
const deliveredTasks = new Set();
|
|
2835
|
+
async function releaseLocksAndWake(roomId, taskId) {
|
|
2836
|
+
const promoted = lockManager.releaseLocks(roomId, taskId);
|
|
2837
|
+
if (promoted.length > 0) {
|
|
2838
|
+
await handlePromotedTasks(roomId, promoted);
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
async function handlePromotedTasks(roomId, promotedTaskIds) {
|
|
2842
|
+
for (const taskId of promotedTaskIds) {
|
|
2843
|
+
const state = store.snapshot();
|
|
2844
|
+
const task = state.tasks.find((t) => t.id === taskId);
|
|
2845
|
+
if (!task) {
|
|
2846
|
+
lockManager.releaseLocks(roomId, taskId);
|
|
2847
|
+
continue;
|
|
2848
|
+
}
|
|
2849
|
+
if (task.cancelRequested || state.conversations.find((c) => c.id === task.conversationId)?.closed) {
|
|
2850
|
+
const nextPromoted = lockManager.releaseLocks(roomId, taskId);
|
|
2851
|
+
if (nextPromoted.length > 0) {
|
|
2852
|
+
await handlePromotedTasks(roomId, nextPromoted);
|
|
2853
|
+
}
|
|
2854
|
+
continue;
|
|
2855
|
+
}
|
|
2856
|
+
await store.transact((draft) => {
|
|
2857
|
+
const current = draft.tasks.find((t) => t.id === taskId);
|
|
2858
|
+
if (current && current.status === "waiting" && current.blockReason === "resource_locked") {
|
|
2859
|
+
current.status = "queued";
|
|
2860
|
+
delete current.blockReason;
|
|
2861
|
+
delete current.blockReasonDetail;
|
|
2862
|
+
current.updatedAt = Date.now();
|
|
2863
|
+
}
|
|
2864
|
+
});
|
|
2865
|
+
const room = state.rooms.find((r) => r.id === roomId);
|
|
2866
|
+
const context = room
|
|
2867
|
+
? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes)
|
|
2868
|
+
: undefined;
|
|
2869
|
+
const updatedTask = store.snapshot().tasks.find((t) => t.id === taskId);
|
|
2870
|
+
if (updatedTask) {
|
|
2871
|
+
await deliverTask(updatedTask, context);
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
1726
2875
|
async function drainConversation(conversationId) {
|
|
1727
2876
|
if (!conversationId)
|
|
1728
2877
|
return;
|
|
1729
2878
|
const state = store.snapshot();
|
|
1730
|
-
const next =
|
|
2879
|
+
const next = nextReadyConversationTask(state, conversationId);
|
|
1731
2880
|
if (!next || deliveredTasks.has(next.id))
|
|
1732
2881
|
return;
|
|
1733
2882
|
const room = state.rooms.find((entry) => entry.id === next.roomId);
|
|
1734
|
-
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages) : undefined);
|
|
2883
|
+
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
2884
|
+
}
|
|
2885
|
+
function isSupersededContractTask(state, task) {
|
|
2886
|
+
return (!!task.contract &&
|
|
2887
|
+
state.tasks.some((other) => other.accountId === task.accountId &&
|
|
2888
|
+
other.roomId === task.roomId &&
|
|
2889
|
+
other.contract?.id === task.contract.id &&
|
|
2890
|
+
other.contract.revision > task.contract.revision));
|
|
2891
|
+
}
|
|
2892
|
+
function settlementContext() {
|
|
2893
|
+
return { settings: currentSettings(), getHistoryLimit };
|
|
2894
|
+
}
|
|
2895
|
+
function nextReadyConversationTask(state, conversationId) {
|
|
2896
|
+
const conversation = state.conversations.find((entry) => entry.id === conversationId);
|
|
2897
|
+
if (!conversation || conversation.closed)
|
|
2898
|
+
return;
|
|
2899
|
+
const pending = state.tasks.filter((entry) => entry.conversationId === conversationId &&
|
|
2900
|
+
(taskPending(entry) || (!entry.outcomeFingerprint && entry.recoveryUntil !== undefined)));
|
|
2901
|
+
if (pending.some((entry) => entry.status === "running" ||
|
|
2902
|
+
entry.cancelRequested ||
|
|
2903
|
+
hasTaskLease(entry) ||
|
|
2904
|
+
entry.recoveryUntil !== undefined))
|
|
2905
|
+
return;
|
|
2906
|
+
return pending[0]?.status === "queued" ? pending[0] : undefined;
|
|
2907
|
+
}
|
|
2908
|
+
async function publishSettlementEffects(result, dispatch = true) {
|
|
2909
|
+
for (const item of result.settledWakes) {
|
|
2910
|
+
const state = store.snapshot();
|
|
2911
|
+
const task = state.tasks.find((entry) => entry.id === item.taskId);
|
|
2912
|
+
if (!task)
|
|
2913
|
+
continue;
|
|
2914
|
+
deliveredTasks.delete(task.id);
|
|
2915
|
+
await releaseLocksAndWake(task.roomId, task.id);
|
|
2916
|
+
void taskJournalManager
|
|
2917
|
+
.append(task.id, {
|
|
2918
|
+
botId: task.botId,
|
|
2919
|
+
attemptId: task.attemptId,
|
|
2920
|
+
type: "status",
|
|
2921
|
+
phase: task.status,
|
|
2922
|
+
summary: `Task ${task.status}`,
|
|
2923
|
+
output: task.report,
|
|
2924
|
+
}, { roomId: task.roomId, accountId: task.accountId })
|
|
2925
|
+
.catch((cause) => console.warn(`[TaskJournal] Journal append failed for task ${task.id}:`, cause));
|
|
2926
|
+
dispatchGroupWebhook(store, task.roomId, task.status === "completed" ? "task_completed" : "task_failed", {
|
|
2927
|
+
taskId: task.id,
|
|
2928
|
+
botId: task.botId,
|
|
2929
|
+
status: task.status,
|
|
2930
|
+
report: task.report,
|
|
2931
|
+
text: task.text,
|
|
2932
|
+
});
|
|
2933
|
+
const message = state.messages.find((entry) => entry.taskIds.includes(task.id) && entry.sender.id === task.botId);
|
|
2934
|
+
if (message)
|
|
2935
|
+
dispatchGroupWebhook(store, task.roomId, "message", message);
|
|
2936
|
+
if (dispatch) {
|
|
2937
|
+
if (item.wake)
|
|
2938
|
+
await deliverTask(item.wake, item.context);
|
|
2939
|
+
await drainConversation(task.conversationId);
|
|
2940
|
+
}
|
|
2941
|
+
}
|
|
2942
|
+
if (!dispatch)
|
|
2943
|
+
return;
|
|
2944
|
+
for (const taskId of result.readyTaskIds) {
|
|
2945
|
+
const state = store.snapshot();
|
|
2946
|
+
const task = state.tasks.find((entry) => entry.id === taskId);
|
|
2947
|
+
const room = state.rooms.find((entry) => entry.id === task?.roomId);
|
|
2948
|
+
if (task)
|
|
2949
|
+
await deliverTask(task, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
2950
|
+
}
|
|
1735
2951
|
}
|
|
1736
2952
|
async function deliverTask(task, context) {
|
|
1737
|
-
|
|
2953
|
+
const state = store.snapshot();
|
|
2954
|
+
const current = state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
2955
|
+
if (!current ||
|
|
2956
|
+
current.status !== "queued" ||
|
|
2957
|
+
hasTaskLease(current) ||
|
|
2958
|
+
current.recoveryUntil !== undefined ||
|
|
2959
|
+
current.cancelRequested ||
|
|
2960
|
+
current.stopConfirmed ||
|
|
2961
|
+
deliveredTasks.has(task.id))
|
|
1738
2962
|
return;
|
|
1739
|
-
|
|
2963
|
+
task = current;
|
|
2964
|
+
if (task.dependsOnTaskId) {
|
|
2965
|
+
const pred = state.tasks.find((entry) => entry.id === task.dependsOnTaskId && entry.roomId === task.roomId && entry.accountId === task.accountId);
|
|
2966
|
+
if (!pred || pred.status !== "completed" || pred.cancelRequested || pred.stopConfirmed)
|
|
2967
|
+
return;
|
|
2968
|
+
}
|
|
2969
|
+
if (task.conversationId && nextReadyConversationTask(state, task.conversationId)?.id !== task.id)
|
|
1740
2970
|
return;
|
|
2971
|
+
if (task.resourceLocks && task.resourceLocks.length > 0) {
|
|
2972
|
+
const acquired = lockManager.acquireLocks({
|
|
2973
|
+
roomId: task.roomId,
|
|
2974
|
+
taskId: task.id,
|
|
2975
|
+
botId: task.botId,
|
|
2976
|
+
deviceId: task.deviceId,
|
|
2977
|
+
resourceLocks: task.resourceLocks,
|
|
2978
|
+
});
|
|
2979
|
+
if (!acquired.success) {
|
|
2980
|
+
await store.transact((draft) => {
|
|
2981
|
+
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
2982
|
+
if (current && !isTerminal(current.status)) {
|
|
2983
|
+
current.status = "waiting";
|
|
2984
|
+
current.blockReason = "resource_locked";
|
|
2985
|
+
current.blockReasonDetail = `Waiting for locks: ${acquired.conflictingLocks.join(", ")}`;
|
|
2986
|
+
current.updatedAt = Date.now();
|
|
2987
|
+
}
|
|
2988
|
+
});
|
|
2989
|
+
return;
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
1741
2992
|
deliveredTasks.add(task.id);
|
|
1742
2993
|
const deliver = options.onTask ?? options.relay?.onTask;
|
|
1743
2994
|
try {
|
|
@@ -1755,6 +3006,21 @@ export async function createDeviceHub(options) {
|
|
|
1755
3006
|
current.lastHeartbeatAt = Date.now();
|
|
1756
3007
|
task.leaseToken = current.leaseToken;
|
|
1757
3008
|
task.leaseGeneration = current.leaseGeneration;
|
|
3009
|
+
if (current.contract && !current.contextManifest) {
|
|
3010
|
+
const activeTaskState = draft.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
|
|
3011
|
+
current.contextManifest = createContextManifest({
|
|
3012
|
+
contract: current.contract,
|
|
3013
|
+
executionPolicy: { deviceId: current.deviceId, botId: current.botId, botRevision: current.botRevision },
|
|
3014
|
+
context: context ?? null,
|
|
3015
|
+
taskState: activeTaskState ?? null,
|
|
3016
|
+
inputs: contractInputReferences(current.contract),
|
|
3017
|
+
policyRef: "server/device-center/group-context.ts#groupTaskContext",
|
|
3018
|
+
truncationBudget: currentSettings().groupContextBytes,
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
3021
|
+
if (current.contextManifest) {
|
|
3022
|
+
task.contextManifest = current.contextManifest;
|
|
3023
|
+
}
|
|
1758
3024
|
}
|
|
1759
3025
|
const conversation = draft.conversations.find((entry) => entry.id === task.conversationId);
|
|
1760
3026
|
if (conversation && !conversation.closed) {
|
|
@@ -1767,68 +3033,41 @@ export async function createDeviceHub(options) {
|
|
|
1767
3033
|
committed.conversations.find((entry) => entry.id === task.conversationId)?.closed)
|
|
1768
3034
|
throw new Error("Conversation stopped before delivery");
|
|
1769
3035
|
const taskState = committed.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
3036
|
+
const wire = {
|
|
3037
|
+
...task,
|
|
3038
|
+
// Runtime consumes sealed snapshots directly. Legacy copies would count
|
|
3039
|
+
// their serialized size twice and can exceed the relay frame ceiling.
|
|
3040
|
+
...(task.contextManifest ? {} : { context, taskState }),
|
|
3041
|
+
executionMode: task.executionMode ?? task.contract?.executionMode ?? "chat",
|
|
3042
|
+
};
|
|
3043
|
+
if (Buffer.byteLength(JSON.stringify({ type: "task", task: wire })) > RELAY_LIMITS.frame)
|
|
3044
|
+
throw new HttpError(413, `Task payload exceeds relay frame size of ${RELAY_LIMITS.frame} bytes`);
|
|
3045
|
+
if (!deliver || (await deliver(task.deviceId, wire)) === false)
|
|
1778
3046
|
throw new Error("Delivery rejected");
|
|
1779
3047
|
}
|
|
1780
|
-
catch {
|
|
3048
|
+
catch (error) {
|
|
1781
3049
|
const failure = await store.transact((draft) => {
|
|
1782
3050
|
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
1783
3051
|
if (!current || isTerminal(current.status) || current.cancelRequested)
|
|
1784
3052
|
return;
|
|
1785
|
-
const
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
text: report,
|
|
1796
|
-
sourceBotId: current.botId,
|
|
1797
|
-
requestId: current.requestId,
|
|
1798
|
-
createdAt: current.updatedAt,
|
|
1799
|
-
});
|
|
1800
|
-
const room = draft.rooms.find((r) => r.id === current.roomId);
|
|
1801
|
-
const context = room ? groupTaskContext(room, draft.bots, draft.messages) : undefined;
|
|
1802
|
-
const wake = queueParentResult(draft, current);
|
|
1803
|
-
draft.messages.push({
|
|
1804
|
-
id: randomUUID(),
|
|
1805
|
-
roomId: current.roomId,
|
|
1806
|
-
accountId: current.accountId,
|
|
1807
|
-
text: report,
|
|
1808
|
-
sender: {
|
|
1809
|
-
type: "bot",
|
|
1810
|
-
id: current.botId,
|
|
1811
|
-
name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
|
|
1812
|
-
sourceDeviceId: current.deviceId,
|
|
1813
|
-
},
|
|
1814
|
-
createdAt: current.updatedAt,
|
|
1815
|
-
taskIds: [current.id],
|
|
1816
|
-
});
|
|
1817
|
-
const remove = new Set(draft.messages
|
|
1818
|
-
.filter((message) => message.roomId === current.roomId)
|
|
1819
|
-
.slice(0, -HISTORY)
|
|
1820
|
-
.map((message) => message.id));
|
|
1821
|
-
draft.messages = draft.messages.filter((message) => !remove.has(message.id));
|
|
1822
|
-
draft.receipts = draft.receipts.filter((receipt) => !remove.has(receipt.messageId));
|
|
1823
|
-
trimConversationHistory(draft, current.roomId);
|
|
1824
|
-
return { wake, context };
|
|
3053
|
+
const notice = recordTaskOutcome(draft, current, {
|
|
3054
|
+
status: "failed",
|
|
3055
|
+
report: error instanceof HttpError && error.status === 413
|
|
3056
|
+
? error.message
|
|
3057
|
+
: "Task delivery failed; submit a new request to retry.",
|
|
3058
|
+
}, settlementContext());
|
|
3059
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
3060
|
+
if (notice)
|
|
3061
|
+
result.settledWakes.unshift(notice);
|
|
3062
|
+
return result;
|
|
1825
3063
|
});
|
|
1826
|
-
if (failure
|
|
1827
|
-
await
|
|
3064
|
+
if (failure)
|
|
3065
|
+
await publishSettlementEffects(failure);
|
|
1828
3066
|
}
|
|
1829
3067
|
finally {
|
|
1830
3068
|
if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
|
|
1831
3069
|
deliveredTasks.delete(task.id);
|
|
3070
|
+
await releaseLocksAndWake(task.roomId, task.id);
|
|
1832
3071
|
await drainConversation(task.conversationId);
|
|
1833
3072
|
}
|
|
1834
3073
|
}
|
|
@@ -1840,15 +3079,10 @@ export async function createDeviceHub(options) {
|
|
|
1840
3079
|
typeof event.botId !== "string" ||
|
|
1841
3080
|
!["running", "completed", "failed", "interrupted"].includes(event.status))
|
|
1842
3081
|
fail(400, "Invalid task event");
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
? "Task execution was interrupted without a report."
|
|
1848
|
-
: undefined
|
|
1849
|
-
: text(event.report);
|
|
1850
|
-
if (event.status === "completed" && !report)
|
|
1851
|
-
fail(400, "Completed task requires agent report");
|
|
3082
|
+
if ((event.report !== undefined &&
|
|
3083
|
+
(typeof event.report !== "string" || Buffer.byteLength(event.report) > 64 * 1024)) ||
|
|
3084
|
+
(event.error !== undefined && (typeof event.error !== "string" || event.error.length > 4096)))
|
|
3085
|
+
fail(400, "Invalid task outcome");
|
|
1852
3086
|
let reportMetadata;
|
|
1853
3087
|
try {
|
|
1854
3088
|
if (event.reportMetadata !== undefined)
|
|
@@ -1858,164 +3092,136 @@ export async function createDeviceHub(options) {
|
|
|
1858
3092
|
fail(400, "Invalid report metadata");
|
|
1859
3093
|
}
|
|
1860
3094
|
const result = await store.transact((draft) => {
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
3095
|
+
if (event.status !== "running") {
|
|
3096
|
+
const device = draft.devices.find((entry) => entry.id === deviceId);
|
|
3097
|
+
const targetTask = draft.tasks.find((entry) => entry.id === event.taskId &&
|
|
3098
|
+
entry.deviceId === deviceId &&
|
|
3099
|
+
entry.botId === event.botId &&
|
|
3100
|
+
entry.accountId === device?.accountId);
|
|
3101
|
+
// Settle identity and durable terminal conflicts first, so an obsolete
|
|
3102
|
+
// artifact can receive a bound permanent rejection rather than retry forever.
|
|
3103
|
+
const settled = settleTaskTerminalOutcome(draft, deviceId, { ...event, type: "task_event", reportMetadata }, settlementContext());
|
|
3104
|
+
if (!settled.accepted)
|
|
3105
|
+
throw Object.assign(new HttpError(settled.statusCode ?? 409, settled.reason ?? "Outcome rejected"), {
|
|
3106
|
+
permanent: settled.permanent,
|
|
3107
|
+
reasonCode: settled.reasonCode,
|
|
3108
|
+
});
|
|
3109
|
+
if (targetTask) {
|
|
3110
|
+
const validation = validateCodeArtifactOutcome({
|
|
3111
|
+
task: targetTask,
|
|
3112
|
+
artifact: event.artifact,
|
|
3113
|
+
executionCompleted: event.executionCompleted,
|
|
3114
|
+
artifactProduced: event.artifactProduced,
|
|
3115
|
+
});
|
|
3116
|
+
if (!validation.valid)
|
|
3117
|
+
fail(400, `Invalid code task outcome: ${validation.reason}`);
|
|
3118
|
+
if (!settled.duplicate && validation.artifact)
|
|
3119
|
+
targetTask.artifact = validation.artifact;
|
|
3120
|
+
}
|
|
3121
|
+
return settled;
|
|
3122
|
+
}
|
|
3123
|
+
const device = draft.devices.find((entry) => entry.id === deviceId);
|
|
3124
|
+
const task = draft.tasks.find((entry) => entry.id === event.taskId &&
|
|
3125
|
+
entry.deviceId === deviceId &&
|
|
3126
|
+
entry.botId === event.botId &&
|
|
3127
|
+
entry.accountId === device?.accountId);
|
|
3128
|
+
const bot = draft.bots.find((entry) => entry.id === event.botId && entry.deviceId === deviceId && entry.accountId === device?.accountId);
|
|
3129
|
+
if (!task ||
|
|
3130
|
+
!device ||
|
|
3131
|
+
!bot ||
|
|
3132
|
+
!draft.rooms.some((room) => room.id === task.roomId && room.botIds.includes(bot.id)))
|
|
1869
3133
|
fail(404, "Task missing");
|
|
1870
|
-
if (
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
}
|
|
1884
|
-
if (task.status === event.status) {
|
|
1885
|
-
if (task.report && report && task.report !== report)
|
|
1886
|
-
fail(409, "Conflicting duplicate event");
|
|
1887
|
-
return { task };
|
|
1888
|
-
}
|
|
1889
|
-
// Allow safe outbox replay or recovery adoption if task was marked interrupted during restart/disconnect
|
|
1890
|
-
const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
|
|
1891
|
-
const canAdoptInterrupted = (inRecovery || task.status === "interrupted") && (event.status === "completed" || event.status === "failed");
|
|
1892
|
-
if (!canAdoptInterrupted) {
|
|
1893
|
-
if (isTerminal(task.status) ||
|
|
1894
|
-
(task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
|
|
1895
|
-
(task.status === "running" && !isTerminal(event.status)))
|
|
1896
|
-
fail(409, "Invalid task transition");
|
|
3134
|
+
if (task.attemptId !== event.attemptId ||
|
|
3135
|
+
task.leaseToken !== event.leaseToken ||
|
|
3136
|
+
task.leaseGeneration !== event.leaseGeneration)
|
|
3137
|
+
fail(409, "Attempt or lease mismatch");
|
|
3138
|
+
if (isSupersededContractTask(draft, task))
|
|
3139
|
+
fail(409, "Contract revision superseded");
|
|
3140
|
+
if (!bot.enabled || bot.revision !== task.botRevision || task.cancelRequested || task.stopConfirmed)
|
|
3141
|
+
fail(409, "Task unavailable");
|
|
3142
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3143
|
+
fail(409, "Recovery window expired");
|
|
3144
|
+
if (task.status === "running") {
|
|
3145
|
+
delete task.recoveryUntil;
|
|
3146
|
+
return { task, duplicate: true };
|
|
1897
3147
|
}
|
|
3148
|
+
if (task.status !== "queued" && !isRecoveringTask(task, Date.now()))
|
|
3149
|
+
fail(409, "Invalid task transition");
|
|
1898
3150
|
delete task.recoveryUntil;
|
|
1899
|
-
task.status =
|
|
3151
|
+
task.status = "running";
|
|
1900
3152
|
task.updatedAt = Date.now();
|
|
1901
|
-
|
|
1902
|
-
task.report = report;
|
|
1903
|
-
if (report) {
|
|
1904
|
-
draft.messages.push({
|
|
1905
|
-
id: randomUUID(),
|
|
1906
|
-
roomId: task.roomId,
|
|
1907
|
-
accountId: task.accountId,
|
|
1908
|
-
text: report,
|
|
1909
|
-
sender: { type: "bot", id: bot.id, name: bot.name, sourceDeviceId: deviceId },
|
|
1910
|
-
createdAt: Date.now(),
|
|
1911
|
-
taskIds: [task.id],
|
|
1912
|
-
conversationId: task.conversationId,
|
|
1913
|
-
});
|
|
1914
|
-
if (task.conversationId)
|
|
1915
|
-
draft.conversationMessages.push({
|
|
1916
|
-
id: randomUUID(),
|
|
1917
|
-
conversationId: task.conversationId,
|
|
1918
|
-
taskId: task.id,
|
|
1919
|
-
kind: "result",
|
|
1920
|
-
text: report,
|
|
1921
|
-
sourceBotId: bot.id,
|
|
1922
|
-
requestId: task.requestId,
|
|
1923
|
-
createdAt: Date.now(),
|
|
1924
|
-
});
|
|
1925
|
-
const remove = new Set(draft.messages
|
|
1926
|
-
.filter((m) => m.roomId === task.roomId)
|
|
1927
|
-
.slice(0, -HISTORY)
|
|
1928
|
-
.map((m) => m.id));
|
|
1929
|
-
draft.messages = draft.messages.filter((m) => !remove.has(m.id));
|
|
1930
|
-
draft.receipts = draft.receipts.filter((r) => !remove.has(r.messageId));
|
|
1931
|
-
}
|
|
1932
|
-
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);
|
|
1935
|
-
trimConversationHistory(draft, task.roomId);
|
|
1936
|
-
return { task, wake, context };
|
|
3153
|
+
return { task, duplicate: false };
|
|
1937
3154
|
});
|
|
1938
|
-
if (result
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
type: "status",
|
|
1944
|
-
phase: event.status,
|
|
1945
|
-
summary: `Task ${event.status}${report ? ": " + report.slice(0, 100) : ""}`,
|
|
1946
|
-
output: report,
|
|
1947
|
-
}, { roomId: result.task.roomId, accountId: result.task.accountId })
|
|
1948
|
-
.catch((cause) => {
|
|
1949
|
-
console.warn(`[TaskJournal] Journal append failed for task ${result.task.id}:`, cause);
|
|
3155
|
+
if (!result.duplicate && "settledWakes" in result)
|
|
3156
|
+
await publishSettlementEffects({
|
|
3157
|
+
settledWakes: result.settledWakes ?? [],
|
|
3158
|
+
readyTaskIds: result.readyTaskIds ?? [],
|
|
3159
|
+
cascadedFailedTaskIds: result.cascadedFailedTaskIds ?? [],
|
|
1950
3160
|
});
|
|
3161
|
+
if (!result.duplicate && event.status === "running") {
|
|
3162
|
+
const task = result.task;
|
|
3163
|
+
void taskJournalManager
|
|
3164
|
+
.append(task.id, { botId: task.botId, attemptId: task.attemptId, type: "status", phase: "running", summary: "Task running" }, { roomId: task.roomId, accountId: task.accountId })
|
|
3165
|
+
.catch((cause) => console.warn(`[TaskJournal] Journal append failed for task ${task.id}:`, cause));
|
|
1951
3166
|
}
|
|
1952
|
-
if (isTerminal(result.task.status))
|
|
1953
|
-
deliveredTasks.delete(result.task.id);
|
|
1954
|
-
if (result.wake)
|
|
1955
|
-
await deliverTask(result.wake, result.context);
|
|
1956
|
-
await drainConversation(result.task.conversationId);
|
|
1957
3167
|
return result.task;
|
|
1958
3168
|
}
|
|
1959
|
-
//
|
|
1960
|
-
const
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
3169
|
+
// Recover unissued work; outstanding leases must first claim within the recovery window.
|
|
3170
|
+
const recovery = await store.transact((draft) => rescanReadyTasksOnRecovery(draft, Date.now(), 60_000, settlementContext()));
|
|
3171
|
+
await publishSettlementEffects(recovery, false);
|
|
3172
|
+
async function resumeQueuedTasks(deviceId) {
|
|
3173
|
+
for (const task of store.snapshot().tasks) {
|
|
3174
|
+
if ((deviceId && task.deviceId !== deviceId) ||
|
|
3175
|
+
task.status !== "queued" ||
|
|
3176
|
+
hasTaskLease(task) ||
|
|
3177
|
+
task.recoveryUntil !== undefined)
|
|
3178
|
+
continue;
|
|
3179
|
+
const state = store.snapshot();
|
|
3180
|
+
const room = state.rooms.find((entry) => entry.id === task.roomId);
|
|
3181
|
+
await deliverTask(task, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
3182
|
+
}
|
|
1970
3183
|
}
|
|
1971
|
-
|
|
1972
|
-
|
|
3184
|
+
async function reconcilePendingPublications(deviceId) {
|
|
3185
|
+
if (!options.relay?.callDevice)
|
|
3186
|
+
return [];
|
|
3187
|
+
try {
|
|
3188
|
+
return await reconcilePendingIntegrations(store, {
|
|
3189
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
3190
|
+
}, { limit: 16, deviceId });
|
|
3191
|
+
}
|
|
3192
|
+
catch (cause) {
|
|
3193
|
+
console.warn("[HubRecovery] Publication query failed", cause);
|
|
3194
|
+
return [];
|
|
3195
|
+
}
|
|
1973
3196
|
}
|
|
3197
|
+
void reconcilePendingPublications();
|
|
1974
3198
|
let sweepInflight = false;
|
|
1975
3199
|
const recoverySweepTimer = setInterval(() => {
|
|
3200
|
+
void reconcilePendingPublications();
|
|
1976
3201
|
if (sweepInflight)
|
|
1977
3202
|
return;
|
|
1978
|
-
const
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
(
|
|
1982
|
-
|
|
3203
|
+
const now = Date.now();
|
|
3204
|
+
if (!store
|
|
3205
|
+
.snapshot()
|
|
3206
|
+
.tasks.some((task) => !task.outcomeFingerprint &&
|
|
3207
|
+
((task.recoveryUntil !== undefined && now > task.recoveryUntil) ||
|
|
3208
|
+
((task.status === "running" || (task.status === "queued" && hasTaskLease(task))) &&
|
|
3209
|
+
task.lastHeartbeatAt !== undefined &&
|
|
3210
|
+
now - task.lastHeartbeatAt > 30 * 60_000))))
|
|
1983
3211
|
return;
|
|
1984
3212
|
sweepInflight = true;
|
|
1985
3213
|
void (async () => {
|
|
1986
3214
|
try {
|
|
1987
|
-
const
|
|
1988
|
-
await
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
delete task.recoveryUntil;
|
|
1994
|
-
if (task.status === "running") {
|
|
1995
|
-
task.status = "interrupted";
|
|
1996
|
-
task.updatedAt = sweepNow;
|
|
1997
|
-
const report = windowExpired
|
|
1998
|
-
? "Hub restarted; recovery window expired without reconnect claim."
|
|
1999
|
-
: "Task lease expired due to prolonged inactivity.";
|
|
2000
|
-
task.report = report;
|
|
2001
|
-
const room = draft.rooms.find((r) => r.id === task.roomId);
|
|
2002
|
-
const context = room ? groupTaskContext(room, draft.bots, draft.messages) : undefined;
|
|
2003
|
-
const wake = queueParentResult(draft, task);
|
|
2004
|
-
trimConversationHistory(draft, task.roomId);
|
|
2005
|
-
settledWakes.push({ wake, context, conversationId: task.conversationId, taskId: task.id });
|
|
2006
|
-
}
|
|
2007
|
-
}
|
|
2008
|
-
}
|
|
2009
|
-
});
|
|
2010
|
-
for (const item of settledWakes) {
|
|
2011
|
-
deliveredTasks.delete(item.taskId);
|
|
2012
|
-
if (item.wake)
|
|
2013
|
-
await deliverTask(item.wake, item.context);
|
|
2014
|
-
await drainConversation(item.conversationId);
|
|
3215
|
+
const settled = await store.transact((draft) => sweepExpiredRecoveryLeases(draft, now, settlementContext()));
|
|
3216
|
+
await publishSettlementEffects(settled);
|
|
3217
|
+
for (const taskId of lockManager.cleanupExpiredLocks()) {
|
|
3218
|
+
const task = store.snapshot().tasks.find((entry) => entry.id === taskId);
|
|
3219
|
+
if (task)
|
|
3220
|
+
await handlePromotedTasks(task.roomId, [taskId]);
|
|
2015
3221
|
}
|
|
2016
3222
|
}
|
|
2017
|
-
catch {
|
|
2018
|
-
console.warn("[HubRecovery] Sweep transaction failed");
|
|
3223
|
+
catch (cause) {
|
|
3224
|
+
console.warn("[HubRecovery] Sweep transaction failed", cause);
|
|
2019
3225
|
}
|
|
2020
3226
|
finally {
|
|
2021
3227
|
sweepInflight = false;
|
|
@@ -2047,12 +3253,17 @@ export async function createDeviceHub(options) {
|
|
|
2047
3253
|
if (!task || !device) {
|
|
2048
3254
|
return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task not found" };
|
|
2049
3255
|
}
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
3256
|
+
if (isSupersededContractTask(draft, task))
|
|
3257
|
+
return {
|
|
3258
|
+
taskId: claim.taskId,
|
|
3259
|
+
attemptId: claim.attemptId,
|
|
3260
|
+
accepted: false,
|
|
3261
|
+
reason: "Contract revision superseded",
|
|
3262
|
+
};
|
|
3263
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3264
|
+
return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Recovery window expired" };
|
|
3265
|
+
const inRecovery = isRecoveringTask(task, Date.now());
|
|
3266
|
+
if (task.outcomeFingerprint || (isTerminal(task.status) && !inRecovery)) {
|
|
2056
3267
|
return {
|
|
2057
3268
|
taskId: claim.taskId,
|
|
2058
3269
|
attemptId: claim.attemptId,
|
|
@@ -2092,7 +3303,7 @@ export async function createDeviceHub(options) {
|
|
|
2092
3303
|
reason: "Lease generation mismatch",
|
|
2093
3304
|
};
|
|
2094
3305
|
}
|
|
2095
|
-
if (task.status !== "running" && !
|
|
3306
|
+
if (task.status !== "running" && !(task.status === "queued" && hasTaskLease(task)) && !inRecovery) {
|
|
2096
3307
|
return {
|
|
2097
3308
|
taskId: claim.taskId,
|
|
2098
3309
|
attemptId: claim.attemptId,
|
|
@@ -2131,9 +3342,18 @@ export async function createDeviceHub(options) {
|
|
|
2131
3342
|
if (!task || !device || task.status !== "running") {
|
|
2132
3343
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task not running" };
|
|
2133
3344
|
}
|
|
3345
|
+
if (isSupersededContractTask(draft, task))
|
|
3346
|
+
return {
|
|
3347
|
+
taskId: renew.taskId,
|
|
3348
|
+
attemptId: renew.attemptId,
|
|
3349
|
+
accepted: false,
|
|
3350
|
+
reason: "Contract revision superseded",
|
|
3351
|
+
};
|
|
2134
3352
|
if (task.cancelRequested || task.stopConfirmed) {
|
|
2135
3353
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task stop requested" };
|
|
2136
3354
|
}
|
|
3355
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3356
|
+
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Recovery window expired" };
|
|
2137
3357
|
if (task.leaseToken !== renew.leaseToken) {
|
|
2138
3358
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Lease token mismatch" };
|
|
2139
3359
|
}
|
|
@@ -2257,8 +3477,10 @@ export async function createDeviceHub(options) {
|
|
|
2257
3477
|
const recoveryGraceMs = 60_000;
|
|
2258
3478
|
await store.transact((draft) => {
|
|
2259
3479
|
const task = draft.tasks.find((t) => t.id === taskId && t.deviceId === deviceId && t.attemptId === attemptId);
|
|
2260
|
-
if (task &&
|
|
2261
|
-
task.
|
|
3480
|
+
if (task &&
|
|
3481
|
+
!task.outcomeFingerprint &&
|
|
3482
|
+
(task.status === "running" || (task.status === "queued" && hasTaskLease(task)))) {
|
|
3483
|
+
task.recoveryUntil ??= now + recoveryGraceMs;
|
|
2262
3484
|
task.updatedAt = now;
|
|
2263
3485
|
}
|
|
2264
3486
|
});
|
|
@@ -2270,6 +3492,8 @@ export async function createDeviceHub(options) {
|
|
|
2270
3492
|
claimTask,
|
|
2271
3493
|
renewTaskLease,
|
|
2272
3494
|
onTaskDisconnect,
|
|
3495
|
+
resumeQueuedTasks,
|
|
3496
|
+
reconcilePendingPublications,
|
|
2273
3497
|
getAccount,
|
|
2274
3498
|
getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req) ?? undefined,
|
|
2275
3499
|
authenticateAgent,
|
|
@@ -2280,9 +3504,11 @@ export async function createDeviceHub(options) {
|
|
|
2280
3504
|
acceptTaskPlanReady,
|
|
2281
3505
|
setRelay(relay) {
|
|
2282
3506
|
options.relay = relay;
|
|
3507
|
+
void reconcilePendingPublications();
|
|
2283
3508
|
},
|
|
2284
3509
|
async close() {
|
|
2285
3510
|
clearInterval(recoverySweepTimer);
|
|
3511
|
+
lockManager.close();
|
|
2286
3512
|
await groupEvents.close();
|
|
2287
3513
|
await taskJournalManager.close();
|
|
2288
3514
|
pairs.clear();
|