pi-web-ui 0.116.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 +38 -4
- package/bin/device-hub-cli.mjs +26 -3
- package/bin/pi-web-ui.mjs +138 -70
- package/dist/server/agent-service-daemon.js +52 -6
- package/dist/server/agent-service.js +495 -141
- package/dist/server/canvas/canvas-workspace.js +18 -86
- package/dist/server/client-state.js +35 -6
- package/dist/server/compaction-markers.js +43 -24
- package/dist/server/dangling-tools.js +172 -16
- package/dist/server/device-center/bot-execution.js +48 -1
- package/dist/server/device-center/collab-service.js +26 -8
- package/dist/server/device-center/collab-tool.js +394 -18
- 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 +15 -5
- package/dist/server/device-center/executor.js +47 -5
- package/dist/server/device-center/hub-conversations.js +14 -4
- 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-page.js +5 -4
- 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.js +772 -354
- package/dist/server/device-center/integration-verification.js +113 -0
- package/dist/server/device-center/local-hub.js +6 -2
- 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 +107 -12
- package/dist/server/device-center/main.js +4 -1
- package/dist/server/device-center/partition-log.js +62 -25
- 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 +426 -42
- package/dist/server/device-center/store.js +225 -47
- 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-settlement.js +353 -0
- package/dist/server/device-center/task-workspace.js +443 -0
- 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 +15 -0
- package/dist/server/dsh/dsh-agent-service.js +9 -2
- package/dist/server/index.js +26 -1
- package/dist/server/patch-node-pty.js +3 -2
- package/dist/server/patch-remote-catalog.js +3 -2
- package/dist/server/preset-fields.js +17 -1
- package/dist/server/preset-share.js +1 -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/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/transcript-prepare.js +73 -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 +18 -5
- package/docs/device-center.md +30 -22
- package/package.json +3 -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-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
- package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
- package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
- package/web/dist/assets/{CanvasStudio-zSxyIx1R.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-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
- package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
- package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
- package/web/dist/assets/{Dropdown-C4LIhshN.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-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
- package/web/dist/assets/{GlobalSearchModal-F7fNimKk.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-c6d0TJoh.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-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
- package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.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-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
- package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
- package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
- package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
- package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
- package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
- package/web/dist/assets/{desktop-aAKpvKJV.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-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
- package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
- package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
- package/web/dist/index.html +11 -11
- package/web/dist/sw.js +1 -1
- package/dist/gh-comment-781.md +0 -5
- package/dist/server/device-center/local-page.js +0 -17
- package/dist/server/device-center/smoke-preview.js +0 -3
- package/dist/server/durable/durable-capabilities.js +0 -11
- package/dist/server/markers/builtins/services.js +0 -123
- package/dist/server/markers/builtins/todo.js +0 -189
- package/dist/server/markers-list-tool.js +0 -34
- package/dist/server/orchestrator.js +0 -109
- package/dist/server/patch-turn-end-boundary.js +0 -77
- package/dist/server/system-prompt-soul.js +0 -41
- package/dist/server/univer-service.js +0 -448
- package/dist/server/universal/drivers/dsh-driver.js +0 -379
- package/dist/test-artifact.md +0 -9
- package/dist/test-preview-modal.md +0 -11
- package/dist/test-report.html +0 -20
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
- package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
- package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
- package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
- package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
- package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
- package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
- package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
- package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
- package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
- package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
- package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
- package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
- package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
- package/web/dist/assets/index-C6DwztqE.css +0 -1
- package/web/dist/assets/index-CuN802Sj.js +0 -93
- package/web/dist/assets/index-EH5Fw9fa.js +0 -93
|
@@ -5,22 +5,27 @@ import { createGroupEvents } from "./group-events.js";
|
|
|
5
5
|
import { createTaskJournalManager } from "./task-journal.js";
|
|
6
6
|
import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
|
|
7
7
|
import { TASK_REPORT_UPLOAD_JSON_BYTES } from "../payload-limits.js";
|
|
8
|
-
import { parseReportMetadata, mergeTaskReportMetadata
|
|
8
|
+
import { parseReportMetadata, mergeTaskReportMetadata } from "./report-metadata.js";
|
|
9
9
|
import { buildDeterministicTaskSummary, queryTaskReportChunk } from "./task-state.js";
|
|
10
10
|
import { addDelivery, addReview, deliveryHistory, deliverySummary } from "./hub-deliveries.js";
|
|
11
|
-
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";
|
|
12
14
|
import { createServer } from "node:http";
|
|
13
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
14
|
-
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";
|
|
15
17
|
import { atomicApproveGroupPlan } from "./group-plan-guard.js";
|
|
16
18
|
import { computeAttenuatedTools } from "./bot-execution.js";
|
|
17
19
|
import { validateTaskPlan } from "./task-plan.js";
|
|
18
20
|
import { ALLOWED_WEBHOOK_EVENTS, createWebhookToken, dispatchGroupWebhook, isIncomingWebhookRequest, secureCompareTokens, testOutgoingWebhook, validateWebhookInput, } from "./hub-webhooks.js";
|
|
19
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";
|
|
20
23
|
import { createHubLockManager, validateResourceLocks } from "./hub-locks.js";
|
|
21
24
|
import { createAccountAuth, hashPassword, verifyPassword, SESSION_TTL, HubRateLimiter } from "./hub-auth.js";
|
|
22
|
-
import { establishConversation, advanceConversationTask,
|
|
25
|
+
import { establishConversation, advanceConversationTask, recordConversationTurn, conversationStatus, conversationPage, trimConversationHistory, conversationStale, conversationHasAuditRecords, dropConversationRecords, trimClosedConversations, trimRoomReceipts, } from "./hub-conversations.js";
|
|
23
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";
|
|
24
29
|
class HttpError extends Error {
|
|
25
30
|
status;
|
|
26
31
|
constructor(status, message) {
|
|
@@ -85,7 +90,7 @@ export async function createDeviceHub(options) {
|
|
|
85
90
|
domain.hostname.endsWith(`.${origin.hostname}`))
|
|
86
91
|
throw new Error("Device domain must be independent of hub domain");
|
|
87
92
|
}
|
|
88
|
-
const store = await DeviceHubStore.open(options.dataDir);
|
|
93
|
+
const store = await DeviceHubStore.open(options.dataDir, { retainUnleasedQueued: true });
|
|
89
94
|
const taskJournalManager = createTaskJournalManager(options.dataDir);
|
|
90
95
|
const taskReportStore = createTaskReportStore(options.dataDir, "hub");
|
|
91
96
|
const groupEvents = createGroupEvents(store, taskJournalManager);
|
|
@@ -131,7 +136,7 @@ export async function createDeviceHub(options) {
|
|
|
131
136
|
if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
|
|
132
137
|
fail(429, "Too many user writes");
|
|
133
138
|
const suffix = req.path.slice("/api/device-user".length);
|
|
134
|
-
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);
|
|
135
140
|
const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
|
|
136
141
|
const webhookRoute = /^\/rooms\/[^/]+\/(?:webhooks(?:\/[^/]+(?:\/(?:delete|regenerate-token|test))?)?|hub-relay)$/.test(suffix);
|
|
137
142
|
if (!((req.method === "GET" &&
|
|
@@ -146,7 +151,7 @@ export async function createDeviceHub(options) {
|
|
|
146
151
|
(suffix === "/rooms" ||
|
|
147
152
|
conversationRoute ||
|
|
148
153
|
webhookRoute ||
|
|
149
|
-
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard)$/.test(suffix) ||
|
|
154
|
+
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard(?:\/sections\/[^/]+)?)$/.test(suffix) ||
|
|
150
155
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
|
|
151
156
|
/^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
|
|
152
157
|
/^\/devices\/[^/]+\/(open|remark)$/.test(suffix)))))
|
|
@@ -168,13 +173,13 @@ export async function createDeviceHub(options) {
|
|
|
168
173
|
const suffix = req.path.slice("/api/agent".length);
|
|
169
174
|
if ((req.method === "GET" &&
|
|
170
175
|
(["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
171
|
-
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard))?$/.test(suffix) ||
|
|
176
|
+
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard(?:\/sections\/[^/]+)?))?$/.test(suffix) ||
|
|
172
177
|
/^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
|
|
173
178
|
(req.method === "POST" &&
|
|
174
179
|
(suffix === "/rooms" ||
|
|
175
180
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(suffix) ||
|
|
176
|
-
/^\/rooms\/[^/]+\/(?:messages|blackboard|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel))?)?))?)$/.test(suffix))) ||
|
|
177
|
-
(req.method === "PUT" && /^\/rooms\/[^/]+\/blackboard
|
|
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)))
|
|
178
183
|
req.url = req.url.replace("/api/agent/", "/api/");
|
|
179
184
|
else if (!((suffix === "/transfers" && req.method === "POST") || (suffix === "/bots" && req.method === "PUT")))
|
|
180
185
|
fail(404, "Agent route missing");
|
|
@@ -192,19 +197,23 @@ export async function createDeviceHub(options) {
|
|
|
192
197
|
next();
|
|
193
198
|
});
|
|
194
199
|
const json = express.json({ limit: "32kb", strict: true });
|
|
200
|
+
const contractJson = express.json({ limit: MAX_CONTRACT_REQUEST_BYTES, strict: true });
|
|
195
201
|
const blackboardJson = express.json({ limit: "512kb", strict: true });
|
|
196
202
|
const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
|
|
197
203
|
const reportWrites = new HubRateLimiter(4096, 60000);
|
|
198
204
|
app.use((req, res, next) => {
|
|
199
205
|
if (agents.has(req) && req.path === "/api/agent/transfers")
|
|
200
206
|
return next();
|
|
207
|
+
if (req.method === "POST" &&
|
|
208
|
+
/^\/api\/rooms\/[^/]+\/(?:messages|tasks|conversations(?:\/[^/]+\/messages)?)$/.test(req.path))
|
|
209
|
+
return contractJson(req, res, next);
|
|
201
210
|
if (agents.has(req) && req.method === "POST" && /^\/api\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path)) {
|
|
202
211
|
if (!reportWrites.allow(agents.get(req).device.id))
|
|
203
212
|
return res.status(429).json({ error: "Too many report chunks" });
|
|
204
213
|
return reportJson(req, res, next);
|
|
205
214
|
}
|
|
206
215
|
if ((req.method === "PUT" || req.method === "POST") &&
|
|
207
|
-
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard
|
|
216
|
+
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard(?:\/sections\/[^/]+)?$/.test(req.path)) {
|
|
208
217
|
return blackboardJson(req, res, next);
|
|
209
218
|
}
|
|
210
219
|
json(req, res, next);
|
|
@@ -292,6 +301,37 @@ export async function createDeviceHub(options) {
|
|
|
292
301
|
res.setHeader("Set-Cookie", auth.cookie("", true));
|
|
293
302
|
res.json({ ok: true });
|
|
294
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
|
+
});
|
|
295
335
|
app.post("/api/pair/start", (req, res) => {
|
|
296
336
|
if (!pairLimit.allow(ip(req)))
|
|
297
337
|
fail(429, "Too many attempts");
|
|
@@ -360,7 +400,12 @@ export async function createDeviceHub(options) {
|
|
|
360
400
|
fail(404, "Device revoked");
|
|
361
401
|
}
|
|
362
402
|
pairs.delete(key);
|
|
363
|
-
res.json({
|
|
403
|
+
res.json({
|
|
404
|
+
deviceId: pair.deviceId,
|
|
405
|
+
accountId: pair.accountId,
|
|
406
|
+
credential: pair.credential,
|
|
407
|
+
uiCredential: pair.uiCredential,
|
|
408
|
+
});
|
|
364
409
|
});
|
|
365
410
|
app.get("/api/info", (_req, res) => {
|
|
366
411
|
res.json({
|
|
@@ -377,7 +422,7 @@ export async function createDeviceHub(options) {
|
|
|
377
422
|
app.post("/api/devices/:id/revoke", async (req, res) => {
|
|
378
423
|
const owner = account(req);
|
|
379
424
|
const id = String(req.params.id);
|
|
380
|
-
await store.transact((draft) => {
|
|
425
|
+
const settlement = await store.transact((draft) => {
|
|
381
426
|
if (!draft.devices.some((device) => device.id === id && device.accountId === owner.id))
|
|
382
427
|
fail(404, "Device missing");
|
|
383
428
|
draft.devices = draft.devices.filter((device) => device.id !== id);
|
|
@@ -396,12 +441,20 @@ export async function createDeviceHub(options) {
|
|
|
396
441
|
conversation.closedReason = "device_revoked";
|
|
397
442
|
conversation.updatedAt = Date.now();
|
|
398
443
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
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;
|
|
404
456
|
});
|
|
457
|
+
await publishSettlementEffects(settlement);
|
|
405
458
|
for (const [key, pair] of pairs)
|
|
406
459
|
if (pair.deviceId === id)
|
|
407
460
|
pairs.delete(key);
|
|
@@ -469,6 +522,20 @@ export async function createDeviceHub(options) {
|
|
|
469
522
|
const bots = await store.transact((draft) => {
|
|
470
523
|
if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
|
|
471
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);
|
|
472
539
|
if (draft.tasks.some((task) => task.deviceId === device.id &&
|
|
473
540
|
!isTerminal(task.status) &&
|
|
474
541
|
!incoming.some((bot) => bot.id === task.botId && bot.enabled && bot.revision === task.botRevision)))
|
|
@@ -506,7 +573,7 @@ export async function createDeviceHub(options) {
|
|
|
506
573
|
}
|
|
507
574
|
return draft.bots.filter((b) => b.deviceId === device.id);
|
|
508
575
|
});
|
|
509
|
-
res.json({ bots });
|
|
576
|
+
res.json({ bots, accountId: owner.id });
|
|
510
577
|
});
|
|
511
578
|
app.get("/api/rooms", (req, res) => res.json({
|
|
512
579
|
rooms: store
|
|
@@ -765,6 +832,7 @@ export async function createDeviceHub(options) {
|
|
|
765
832
|
updatedBy,
|
|
766
833
|
...(title?.trim() ? { title: title.trim() } : {}),
|
|
767
834
|
content,
|
|
835
|
+
...(req.body?.sections && typeof req.body.sections === "object" ? { sections: req.body.sections } : {}),
|
|
768
836
|
};
|
|
769
837
|
room.blackboard = nextBlackboard;
|
|
770
838
|
return nextBlackboard;
|
|
@@ -774,6 +842,117 @@ export async function createDeviceHub(options) {
|
|
|
774
842
|
};
|
|
775
843
|
app.put("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
776
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);
|
|
777
956
|
// === Group Webhooks ===
|
|
778
957
|
app.get("/api/rooms/:id/webhooks", (req, res) => {
|
|
779
958
|
const owner = account(req);
|
|
@@ -1101,6 +1280,7 @@ export async function createDeviceHub(options) {
|
|
|
1101
1280
|
const oldTasks = new Set(draft.tasks
|
|
1102
1281
|
.filter((t) => t.roomId === activeRoom.id &&
|
|
1103
1282
|
isTerminal(t.status) &&
|
|
1283
|
+
!taskHasImmutableEvidence(t) &&
|
|
1104
1284
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1105
1285
|
.slice(0, -getHistoryLimit())
|
|
1106
1286
|
.map((t) => t.id));
|
|
@@ -1137,9 +1317,9 @@ export async function createDeviceHub(options) {
|
|
|
1137
1317
|
const interactions = state.interactions
|
|
1138
1318
|
? state.interactions.filter((i) => i.taskId === task.id)
|
|
1139
1319
|
: [];
|
|
1140
|
-
const deliveries = state.deliveries
|
|
1141
|
-
|
|
1142
|
-
|
|
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));
|
|
1143
1323
|
res.json({
|
|
1144
1324
|
task: {
|
|
1145
1325
|
id: task.id,
|
|
@@ -1158,6 +1338,12 @@ export async function createDeviceHub(options) {
|
|
|
1158
1338
|
conversationId: task.conversationId,
|
|
1159
1339
|
report: task.report,
|
|
1160
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 } : {}),
|
|
1161
1347
|
},
|
|
1162
1348
|
reportMeta,
|
|
1163
1349
|
interactionCount: interactions.length,
|
|
@@ -1172,9 +1358,11 @@ export async function createDeviceHub(options) {
|
|
|
1172
1358
|
deliveries: deliveries.map((d) => ({
|
|
1173
1359
|
id: d.id,
|
|
1174
1360
|
commit: d.commit,
|
|
1361
|
+
artifactRef: d.artifactRef,
|
|
1175
1362
|
branch: d.branch,
|
|
1176
1363
|
summary: d.summary,
|
|
1177
|
-
|
|
1364
|
+
reportedCheckCount: d.checks.length,
|
|
1365
|
+
passed: d.checks.length > 0 && d.checks.every((c) => c.status === "passed"),
|
|
1178
1366
|
})),
|
|
1179
1367
|
});
|
|
1180
1368
|
});
|
|
@@ -1313,11 +1501,14 @@ export async function createDeviceHub(options) {
|
|
|
1313
1501
|
taskIds: [task.id],
|
|
1314
1502
|
});
|
|
1315
1503
|
});
|
|
1316
|
-
|
|
1317
|
-
if (
|
|
1318
|
-
|
|
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;
|
|
1319
1510
|
}
|
|
1320
|
-
res.json({ success: true, taskId: task.id, steered
|
|
1511
|
+
res.json({ success: true, taskId: task.id, steered });
|
|
1321
1512
|
});
|
|
1322
1513
|
app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
|
|
1323
1514
|
const acc = account(req);
|
|
@@ -1463,6 +1654,8 @@ export async function createDeviceHub(options) {
|
|
|
1463
1654
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1464
1655
|
if (!room)
|
|
1465
1656
|
fail(404, "Room missing");
|
|
1657
|
+
if (operation !== "rename")
|
|
1658
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1466
1659
|
if (operation === "rename")
|
|
1467
1660
|
room.name = text(req.body?.name, 128);
|
|
1468
1661
|
if (operation === "members") {
|
|
@@ -1532,11 +1725,14 @@ export async function createDeviceHub(options) {
|
|
|
1532
1725
|
const conversation = snapshot.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1533
1726
|
if (!conversation)
|
|
1534
1727
|
fail(404, "Conversation missing");
|
|
1535
|
-
res.json({
|
|
1728
|
+
res.json({
|
|
1729
|
+
integrations: listIntegrations(snapshot, req.params.conversationId),
|
|
1730
|
+
canResumePublication: !agents.has(req) && conversation.accountId === owner.id,
|
|
1731
|
+
});
|
|
1536
1732
|
});
|
|
1537
1733
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations", async (req, res) => {
|
|
1538
1734
|
const owner = account(req);
|
|
1539
|
-
const actor = { accountId: owner.id };
|
|
1735
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1540
1736
|
if (!options.relay?.callDevice)
|
|
1541
1737
|
fail(503, "Device relay unavailable");
|
|
1542
1738
|
const driver = {
|
|
@@ -1547,7 +1743,7 @@ export async function createDeviceHub(options) {
|
|
|
1547
1743
|
});
|
|
1548
1744
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", async (req, res) => {
|
|
1549
1745
|
const owner = account(req);
|
|
1550
|
-
const actor = { accountId: owner.id };
|
|
1746
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1551
1747
|
if (!options.relay?.callDevice)
|
|
1552
1748
|
fail(503, "Device relay unavailable");
|
|
1553
1749
|
const driver = {
|
|
@@ -1558,7 +1754,7 @@ export async function createDeviceHub(options) {
|
|
|
1558
1754
|
});
|
|
1559
1755
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", async (req, res) => {
|
|
1560
1756
|
const owner = account(req);
|
|
1561
|
-
const actor = { accountId: owner.id };
|
|
1757
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1562
1758
|
if (!options.relay?.callDevice)
|
|
1563
1759
|
fail(503, "Device relay unavailable");
|
|
1564
1760
|
const driver = {
|
|
@@ -1567,9 +1763,43 @@ export async function createDeviceHub(options) {
|
|
|
1567
1763
|
const result = await hubConfirmIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
|
|
1568
1764
|
res.json({ integration: result });
|
|
1569
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
|
+
});
|
|
1570
1800
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", async (req, res) => {
|
|
1571
1801
|
const owner = account(req);
|
|
1572
|
-
const actor = { accountId: owner.id };
|
|
1802
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1573
1803
|
if (!options.relay?.callDevice)
|
|
1574
1804
|
fail(503, "Device relay unavailable");
|
|
1575
1805
|
const driver = {
|
|
@@ -1585,42 +1815,52 @@ export async function createDeviceHub(options) {
|
|
|
1585
1815
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1586
1816
|
if (!conversation || !room)
|
|
1587
1817
|
fail(404, "Conversation missing");
|
|
1818
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1588
1819
|
const source = ownBot(req, draft);
|
|
1589
1820
|
if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
|
|
1590
1821
|
fail(403, "Bot may stop only its own conversation");
|
|
1591
1822
|
conversation.closed = true;
|
|
1592
1823
|
conversation.closedReason = "stopped";
|
|
1593
|
-
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id &&
|
|
1824
|
+
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id &&
|
|
1825
|
+
(taskPending(t) || (!t.outcomeFingerprint && t.recoveryUntil !== undefined)));
|
|
1826
|
+
const notices = [];
|
|
1594
1827
|
for (const task of tasks) {
|
|
1595
1828
|
task.cancelRequested = true;
|
|
1596
|
-
if ((task.status === "queued" || task.status === "waiting") &&
|
|
1829
|
+
if ((task.status === "queued" || task.status === "waiting") &&
|
|
1830
|
+
!hasTaskLease(task) &&
|
|
1831
|
+
!deliveredTasks.has(task.id)) {
|
|
1597
1832
|
task.stopConfirmed = true;
|
|
1598
|
-
task
|
|
1599
|
-
|
|
1600
|
-
|
|
1833
|
+
const notice = recordTaskOutcome(draft, task, { status: "interrupted", report: "Conversation stopped before delivery." }, settlementContext());
|
|
1834
|
+
if (notice)
|
|
1835
|
+
notices.push(notice);
|
|
1601
1836
|
}
|
|
1602
1837
|
}
|
|
1603
|
-
|
|
1838
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
1839
|
+
settlement.settledWakes.unshift(...notices);
|
|
1840
|
+
return { tasks, settlement };
|
|
1604
1841
|
});
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1842
|
+
await publishSettlementEffects(pending.settlement);
|
|
1843
|
+
for (const task of pending.tasks) {
|
|
1844
|
+
if (task.stopConfirmed)
|
|
1608
1845
|
continue;
|
|
1609
|
-
}
|
|
1610
1846
|
const confirmed = await options.relay
|
|
1611
1847
|
?.cancelTask?.(task.deviceId, task.id, task.attemptId)
|
|
1612
1848
|
.catch(() => ({ stopped: false }));
|
|
1613
1849
|
if (!confirmed?.stopped)
|
|
1614
1850
|
continue;
|
|
1615
|
-
await store.transact((draft) => {
|
|
1851
|
+
const settlement = await store.transact((draft) => {
|
|
1616
1852
|
const current = draft.tasks.find((t) => t.id === task.id && t.attemptId === task.attemptId);
|
|
1617
1853
|
if (!current)
|
|
1618
1854
|
return;
|
|
1619
1855
|
current.stopConfirmed = true;
|
|
1620
|
-
current
|
|
1621
|
-
|
|
1622
|
-
|
|
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;
|
|
1623
1861
|
});
|
|
1862
|
+
if (settlement)
|
|
1863
|
+
await publishSettlementEffects(settlement);
|
|
1624
1864
|
await releaseLocksAndWake(String(req.params.id), task.id);
|
|
1625
1865
|
}
|
|
1626
1866
|
const remaining = store
|
|
@@ -1637,6 +1877,7 @@ export async function createDeviceHub(options) {
|
|
|
1637
1877
|
const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1638
1878
|
if (!room || !conversation)
|
|
1639
1879
|
fail(404, "Conversation missing");
|
|
1880
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1640
1881
|
if (draft.tasks.some((t) => t.conversationId === conversation.id && taskPending(t)))
|
|
1641
1882
|
throw Object.assign(new Error("Stop the conversation before deleting it"), {
|
|
1642
1883
|
status: 409,
|
|
@@ -1743,10 +1984,24 @@ export async function createDeviceHub(options) {
|
|
|
1743
1984
|
const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
|
|
1744
1985
|
if (!conversation)
|
|
1745
1986
|
fail(404, "Conversation missing");
|
|
1746
|
-
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
|
+
];
|
|
1747
2000
|
for (const q of Object.keys(req.query)) {
|
|
1748
2001
|
if (!allowedQueries.includes(q))
|
|
1749
2002
|
fail(400, `Unknown query parameter: ${q}`);
|
|
2003
|
+
if (typeof req.query[q] !== "string")
|
|
2004
|
+
fail(400, `Invalid query parameter: ${q}`);
|
|
1750
2005
|
}
|
|
1751
2006
|
let offset = 0;
|
|
1752
2007
|
if (req.query.offset !== undefined) {
|
|
@@ -1757,7 +2012,7 @@ export async function createDeviceHub(options) {
|
|
|
1757
2012
|
let limit = 8192;
|
|
1758
2013
|
if (req.query.limit !== undefined) {
|
|
1759
2014
|
limit = Number(req.query.limit);
|
|
1760
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 65536)
|
|
2015
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > (evidenceKind !== "report" ? 24 * 1024 : 65536))
|
|
1761
2016
|
fail(400, "Invalid limit");
|
|
1762
2017
|
}
|
|
1763
2018
|
const expectedDigest = typeof req.query.expectedDigest === "string"
|
|
@@ -1765,12 +2020,97 @@ export async function createDeviceHub(options) {
|
|
|
1765
2020
|
: typeof req.query.digest === "string"
|
|
1766
2021
|
? req.query.digest
|
|
1767
2022
|
: undefined;
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
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");
|
|
1771
2030
|
const targetDelivery = deliveryId
|
|
1772
|
-
? 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)
|
|
1773
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
|
+
}
|
|
1774
2114
|
let evidence;
|
|
1775
2115
|
if (targetTask?.attemptId) {
|
|
1776
2116
|
const reportResult = taskReportStore.getReport(targetTask.id, targetTask.attemptId, owner.id, room.id, {
|
|
@@ -1937,6 +2277,7 @@ export async function createDeviceHub(options) {
|
|
|
1937
2277
|
});
|
|
1938
2278
|
app.post([
|
|
1939
2279
|
"/api/rooms/:id/messages",
|
|
2280
|
+
"/api/rooms/:id/tasks",
|
|
1940
2281
|
"/api/rooms/:id/conversations",
|
|
1941
2282
|
"/api/rooms/:id/conversations/:conversationId/messages",
|
|
1942
2283
|
], async (req, res) => {
|
|
@@ -1972,7 +2313,37 @@ export async function createDeviceHub(options) {
|
|
|
1972
2313
|
catch (err) {
|
|
1973
2314
|
fail(400, err?.message ?? "Invalid resourceLocks");
|
|
1974
2315
|
}
|
|
1975
|
-
|
|
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 = {
|
|
1976
2347
|
content,
|
|
1977
2348
|
attentionId,
|
|
1978
2349
|
targets,
|
|
@@ -1984,10 +2355,20 @@ export async function createDeviceHub(options) {
|
|
|
1984
2355
|
planOnly,
|
|
1985
2356
|
replyToMessageId,
|
|
1986
2357
|
resourceLocks,
|
|
2358
|
+
executionMode,
|
|
2359
|
+
contractDigest: contract?.digest,
|
|
2360
|
+
contractId: contract?.id,
|
|
2361
|
+
contractRevision: contract?.revision,
|
|
1987
2362
|
sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
|
|
1988
2363
|
sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
|
|
1989
2364
|
senderType: agents.has(req) ? "bot" : "human",
|
|
1990
|
-
}
|
|
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);
|
|
1991
2372
|
const result = await store.transact((draft) => {
|
|
1992
2373
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1993
2374
|
if (!room)
|
|
@@ -2014,7 +2395,7 @@ export async function createDeviceHub(options) {
|
|
|
2014
2395
|
if (dependsOnTaskId && !draft.tasks.some((m) => m.id === dependsOnTaskId && m.roomId === room.id))
|
|
2015
2396
|
fail(400, "Dependency target task is not in this room");
|
|
2016
2397
|
const depTask = dependsOnTaskId ? draft.tasks.find((t) => t.id === dependsOnTaskId) : undefined;
|
|
2017
|
-
const dependencyActive = Boolean(depTask
|
|
2398
|
+
const dependencyActive = Boolean(depTask);
|
|
2018
2399
|
// The Hub owns dispatch semantics: a human message that only names Bots in its text must not
|
|
2019
2400
|
// silently fall back to the primary Bot just because a client did not pre-resolve the mentions.
|
|
2020
2401
|
const canParseMentions = (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
|
|
@@ -2036,8 +2417,16 @@ export async function createDeviceHub(options) {
|
|
|
2036
2417
|
m.idempotencyKey === key &&
|
|
2037
2418
|
draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
|
|
2038
2419
|
if (prior) {
|
|
2039
|
-
if (prior.fingerprint
|
|
2420
|
+
if (!matchesFingerprint(prior.fingerprint))
|
|
2040
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
|
+
}
|
|
2041
2430
|
return {
|
|
2042
2431
|
message: draft.messages.find((m) => m.taskIds.includes(prior.taskId)),
|
|
2043
2432
|
tasks: draft.tasks.filter((t) => t.id === prior.taskId),
|
|
@@ -2047,14 +2436,38 @@ export async function createDeviceHub(options) {
|
|
|
2047
2436
|
}
|
|
2048
2437
|
const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
|
|
2049
2438
|
if (receipt) {
|
|
2050
|
-
if (receipt.fingerprint
|
|
2439
|
+
if (!matchesFingerprint(receipt.fingerprint))
|
|
2051
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
|
+
}
|
|
2052
2449
|
return {
|
|
2053
2450
|
message: draft.messages.find((m) => m.id === receipt.messageId),
|
|
2054
2451
|
tasks: draft.tasks.filter((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id)),
|
|
2055
2452
|
duplicate: true,
|
|
2056
2453
|
};
|
|
2057
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
|
+
}
|
|
2058
2471
|
// Resolve implicit human targets after replay detection so retries remain stable across configuration changes.
|
|
2059
2472
|
if (!source && !conversationApi && !targets.length && room.primaryBotId) {
|
|
2060
2473
|
if (!room.botIds.includes(room.primaryBotId) || !validBot(draft, room.primaryBotId, owner.id))
|
|
@@ -2132,6 +2545,7 @@ export async function createDeviceHub(options) {
|
|
|
2132
2545
|
fail(409, "Too many open conversations; stop or delete conversations to free capacity");
|
|
2133
2546
|
const now = Date.now();
|
|
2134
2547
|
const rootId = root?.id ?? randomUUID();
|
|
2548
|
+
const isPipeline = targets.length > 1 && (req.body?.pipeline === true || content.includes("->"));
|
|
2135
2549
|
const tasks = targets.map((botId, index) => {
|
|
2136
2550
|
const targetBot = validBot(draft, botId, owner.id);
|
|
2137
2551
|
let attenuatedTools;
|
|
@@ -2145,6 +2559,7 @@ export async function createDeviceHub(options) {
|
|
|
2145
2559
|
attenuatedTools = attenuated;
|
|
2146
2560
|
}
|
|
2147
2561
|
}
|
|
2562
|
+
const isWaitingInPipeline = isPipeline && index > 0;
|
|
2148
2563
|
return {
|
|
2149
2564
|
id: !root && index === 0 ? rootId : randomUUID(),
|
|
2150
2565
|
rootTaskId: rootId,
|
|
@@ -2158,16 +2573,25 @@ export async function createDeviceHub(options) {
|
|
|
2158
2573
|
botRevision: targetBot.revision,
|
|
2159
2574
|
...(source ? { sourceBotId: source.id } : {}),
|
|
2160
2575
|
text: content,
|
|
2161
|
-
status:
|
|
2162
|
-
|
|
2576
|
+
status: isWaitingInPipeline
|
|
2577
|
+
? "waiting"
|
|
2578
|
+
: dependencyActive
|
|
2579
|
+
? "waiting"
|
|
2580
|
+
: "queued",
|
|
2581
|
+
...(isWaitingInPipeline
|
|
2163
2582
|
? {
|
|
2164
|
-
blockReason: "
|
|
2165
|
-
blockReasonDetail:
|
|
2166
|
-
dependsOnTaskId,
|
|
2583
|
+
blockReason: "dependency",
|
|
2584
|
+
blockReasonDetail: "",
|
|
2167
2585
|
}
|
|
2168
|
-
:
|
|
2169
|
-
? {
|
|
2170
|
-
|
|
2586
|
+
: dependencyActive
|
|
2587
|
+
? {
|
|
2588
|
+
blockReason: "dependency_waiting",
|
|
2589
|
+
blockReasonDetail: `Waiting for dependency task ${dependsOnTaskId}`,
|
|
2590
|
+
dependsOnTaskId,
|
|
2591
|
+
}
|
|
2592
|
+
: dependsOnTaskId
|
|
2593
|
+
? { dependsOnTaskId }
|
|
2594
|
+
: {}),
|
|
2171
2595
|
createdAt: now,
|
|
2172
2596
|
updatedAt: now,
|
|
2173
2597
|
...(resourceLocks && resourceLocks.length ? { resourceLocks } : {}),
|
|
@@ -2175,8 +2599,18 @@ export async function createDeviceHub(options) {
|
|
|
2175
2599
|
...(transfer ? { handoff: transfer } : {}),
|
|
2176
2600
|
...(parentTaskId ? { parentTaskId } : {}),
|
|
2177
2601
|
...(attenuatedTools ? { attenuatedTools } : {}),
|
|
2602
|
+
executionMode,
|
|
2603
|
+
...(contract ? { contract } : {}),
|
|
2178
2604
|
};
|
|
2179
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
|
+
}
|
|
2180
2614
|
for (const task of tasks) {
|
|
2181
2615
|
task.kind = kind;
|
|
2182
2616
|
task.sourceConversationId = parent?.conversationId;
|
|
@@ -2195,7 +2629,7 @@ export async function createDeviceHub(options) {
|
|
|
2195
2629
|
: undefined;
|
|
2196
2630
|
if (targetConv) {
|
|
2197
2631
|
task.conversationId = targetConv.id;
|
|
2198
|
-
task.resume =
|
|
2632
|
+
task.resume = task.executionMode !== "code";
|
|
2199
2633
|
advanceConversationTask(draft, targetConv, task);
|
|
2200
2634
|
targetConv.rootTaskId = task.rootTaskId;
|
|
2201
2635
|
targetConv.updatedAt = now;
|
|
@@ -2205,11 +2639,14 @@ export async function createDeviceHub(options) {
|
|
|
2205
2639
|
establishConversation(draft, task);
|
|
2206
2640
|
recordConversationTurn(draft, task, key, fingerprint);
|
|
2207
2641
|
}
|
|
2642
|
+
const messageText = isPipeline
|
|
2643
|
+
? `${content}\n\n⛓️ **[流水线编排 / Pipeline Execution]**: ${targets.map((id) => `@${id}`).join(" ➔ ")}`
|
|
2644
|
+
: content;
|
|
2208
2645
|
const message = {
|
|
2209
2646
|
id: randomUUID(),
|
|
2210
2647
|
roomId: room.id,
|
|
2211
2648
|
accountId: owner.id,
|
|
2212
|
-
text:
|
|
2649
|
+
text: messageText,
|
|
2213
2650
|
sender: source
|
|
2214
2651
|
? { type: "bot", id: source.id, name: source.name, sourceDeviceId: source.deviceId }
|
|
2215
2652
|
: {
|
|
@@ -2247,17 +2684,21 @@ export async function createDeviceHub(options) {
|
|
|
2247
2684
|
const oldTasks = new Set(draft.tasks
|
|
2248
2685
|
.filter((t) => t.roomId === room.id &&
|
|
2249
2686
|
isTerminal(t.status) &&
|
|
2687
|
+
!taskHasImmutableEvidence(t) &&
|
|
2250
2688
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
2251
2689
|
.slice(0, -getHistoryLimit())
|
|
2252
2690
|
.map((t) => t.id));
|
|
2253
2691
|
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
2254
2692
|
trimConversationHistory(draft, room.id);
|
|
2255
2693
|
trimClosedConversations(draft, room.id);
|
|
2256
|
-
|
|
2694
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
2695
|
+
return { message, tasks, duplicate: false, context, settlement };
|
|
2257
2696
|
});
|
|
2258
2697
|
if (!result.duplicate) {
|
|
2698
|
+
if (result.settlement)
|
|
2699
|
+
await publishSettlementEffects(result.settlement);
|
|
2259
2700
|
for (const task of result.tasks) {
|
|
2260
|
-
if (task.status
|
|
2701
|
+
if (task.status === "queued")
|
|
2261
2702
|
await deliverTask(task, result.context);
|
|
2262
2703
|
}
|
|
2263
2704
|
if (result.message) {
|
|
@@ -2414,7 +2855,7 @@ export async function createDeviceHub(options) {
|
|
|
2414
2855
|
}
|
|
2415
2856
|
await store.transact((draft) => {
|
|
2416
2857
|
const current = draft.tasks.find((t) => t.id === taskId);
|
|
2417
|
-
if (current && current.status === "waiting") {
|
|
2858
|
+
if (current && current.status === "waiting" && current.blockReason === "resource_locked") {
|
|
2418
2859
|
current.status = "queued";
|
|
2419
2860
|
delete current.blockReason;
|
|
2420
2861
|
delete current.blockReasonDetail;
|
|
@@ -2435,47 +2876,97 @@ export async function createDeviceHub(options) {
|
|
|
2435
2876
|
if (!conversationId)
|
|
2436
2877
|
return;
|
|
2437
2878
|
const state = store.snapshot();
|
|
2438
|
-
const next =
|
|
2879
|
+
const next = nextReadyConversationTask(state, conversationId);
|
|
2439
2880
|
if (!next || deliveredTasks.has(next.id))
|
|
2440
2881
|
return;
|
|
2441
2882
|
const room = state.rooms.find((entry) => entry.id === next.roomId);
|
|
2442
2883
|
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
2443
2884
|
}
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
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) {
|
|
2462
2910
|
const state = store.snapshot();
|
|
2463
|
-
const
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
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);
|
|
2472
2940
|
}
|
|
2473
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
|
+
}
|
|
2474
2951
|
}
|
|
2475
2952
|
async function deliverTask(task, context) {
|
|
2476
|
-
|
|
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))
|
|
2477
2962
|
return;
|
|
2478
|
-
|
|
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)
|
|
2479
2970
|
return;
|
|
2480
2971
|
if (task.resourceLocks && task.resourceLocks.length > 0) {
|
|
2481
2972
|
const acquired = lockManager.acquireLocks({
|
|
@@ -2515,6 +3006,21 @@ export async function createDeviceHub(options) {
|
|
|
2515
3006
|
current.lastHeartbeatAt = Date.now();
|
|
2516
3007
|
task.leaseToken = current.leaseToken;
|
|
2517
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
|
+
}
|
|
2518
3024
|
}
|
|
2519
3025
|
const conversation = draft.conversations.find((entry) => entry.id === task.conversationId);
|
|
2520
3026
|
if (conversation && !conversation.closed) {
|
|
@@ -2527,66 +3033,36 @@ export async function createDeviceHub(options) {
|
|
|
2527
3033
|
committed.conversations.find((entry) => entry.id === task.conversationId)?.closed)
|
|
2528
3034
|
throw new Error("Conversation stopped before delivery");
|
|
2529
3035
|
const taskState = committed.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
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)
|
|
2538
3046
|
throw new Error("Delivery rejected");
|
|
2539
3047
|
}
|
|
2540
|
-
catch {
|
|
3048
|
+
catch (error) {
|
|
2541
3049
|
const failure = await store.transact((draft) => {
|
|
2542
3050
|
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
2543
3051
|
if (!current || isTerminal(current.status) || current.cancelRequested)
|
|
2544
3052
|
return;
|
|
2545
|
-
const
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
text: report,
|
|
2556
|
-
sourceBotId: current.botId,
|
|
2557
|
-
requestId: current.requestId,
|
|
2558
|
-
createdAt: current.updatedAt,
|
|
2559
|
-
});
|
|
2560
|
-
const room = draft.rooms.find((r) => r.id === current.roomId);
|
|
2561
|
-
const context = room
|
|
2562
|
-
? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
|
|
2563
|
-
: undefined;
|
|
2564
|
-
const wake = queueParentResult(draft, current, currentSettings());
|
|
2565
|
-
draft.messages.push({
|
|
2566
|
-
id: randomUUID(),
|
|
2567
|
-
roomId: current.roomId,
|
|
2568
|
-
accountId: current.accountId,
|
|
2569
|
-
text: report,
|
|
2570
|
-
sender: {
|
|
2571
|
-
type: "bot",
|
|
2572
|
-
id: current.botId,
|
|
2573
|
-
name: draft.bots.find((bot) => bot.id === current.botId)?.name ?? current.botId,
|
|
2574
|
-
sourceDeviceId: current.deviceId,
|
|
2575
|
-
},
|
|
2576
|
-
createdAt: current.updatedAt,
|
|
2577
|
-
taskIds: [current.id],
|
|
2578
|
-
});
|
|
2579
|
-
const remove = new Set(draft.messages
|
|
2580
|
-
.filter((message) => message.roomId === current.roomId)
|
|
2581
|
-
.slice(0, -getHistoryLimit())
|
|
2582
|
-
.map((message) => message.id));
|
|
2583
|
-
draft.messages = draft.messages.filter((message) => !remove.has(message.id));
|
|
2584
|
-
trimRoomReceipts(draft, current.roomId);
|
|
2585
|
-
trimConversationHistory(draft, current.roomId);
|
|
2586
|
-
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;
|
|
2587
3063
|
});
|
|
2588
|
-
if (failure
|
|
2589
|
-
await
|
|
3064
|
+
if (failure)
|
|
3065
|
+
await publishSettlementEffects(failure);
|
|
2590
3066
|
}
|
|
2591
3067
|
finally {
|
|
2592
3068
|
if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
|
|
@@ -2603,15 +3079,10 @@ export async function createDeviceHub(options) {
|
|
|
2603
3079
|
typeof event.botId !== "string" ||
|
|
2604
3080
|
!["running", "completed", "failed", "interrupted"].includes(event.status))
|
|
2605
3081
|
fail(400, "Invalid task event");
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
? "Task execution was interrupted without a report."
|
|
2611
|
-
: undefined
|
|
2612
|
-
: text(event.report);
|
|
2613
|
-
if (event.status === "completed" && !report)
|
|
2614
|
-
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");
|
|
2615
3086
|
let reportMetadata;
|
|
2616
3087
|
try {
|
|
2617
3088
|
if (event.reportMetadata !== undefined)
|
|
@@ -2621,208 +3092,136 @@ export async function createDeviceHub(options) {
|
|
|
2621
3092
|
fail(400, "Invalid report metadata");
|
|
2622
3093
|
}
|
|
2623
3094
|
const result = await store.transact((draft) => {
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
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)))
|
|
2632
3133
|
fail(404, "Task missing");
|
|
2633
|
-
if (
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
}
|
|
2647
|
-
if (task.status
|
|
2648
|
-
|
|
2649
|
-
fail(409, "Conflicting duplicate event");
|
|
2650
|
-
return { task };
|
|
2651
|
-
}
|
|
2652
|
-
// Allow safe outbox replay or recovery adoption if task was marked interrupted during restart/disconnect
|
|
2653
|
-
const inRecovery = typeof task.recoveryUntil === "number" && Date.now() <= task.recoveryUntil;
|
|
2654
|
-
const canAdoptInterrupted = (inRecovery || task.status === "interrupted") && (event.status === "completed" || event.status === "failed");
|
|
2655
|
-
if (!canAdoptInterrupted) {
|
|
2656
|
-
if (isTerminal(task.status) ||
|
|
2657
|
-
(task.status === "queued" && event.status !== "running" && event.status !== "interrupted") ||
|
|
2658
|
-
(task.status === "running" && !isTerminal(event.status)))
|
|
2659
|
-
fail(409, "Invalid task transition");
|
|
2660
|
-
}
|
|
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 };
|
|
3147
|
+
}
|
|
3148
|
+
if (task.status !== "queued" && !isRecoveringTask(task, Date.now()))
|
|
3149
|
+
fail(409, "Invalid task transition");
|
|
2661
3150
|
delete task.recoveryUntil;
|
|
2662
|
-
task.status =
|
|
3151
|
+
task.status = "running";
|
|
2663
3152
|
task.updatedAt = Date.now();
|
|
2664
|
-
|
|
2665
|
-
task.report = report;
|
|
2666
|
-
if (report) {
|
|
2667
|
-
draft.messages.push({
|
|
2668
|
-
id: randomUUID(),
|
|
2669
|
-
roomId: task.roomId,
|
|
2670
|
-
accountId: task.accountId,
|
|
2671
|
-
text: report,
|
|
2672
|
-
sender: { type: "bot", id: bot.id, name: bot.name, sourceDeviceId: deviceId },
|
|
2673
|
-
createdAt: Date.now(),
|
|
2674
|
-
taskIds: [task.id],
|
|
2675
|
-
conversationId: task.conversationId,
|
|
2676
|
-
});
|
|
2677
|
-
if (task.conversationId)
|
|
2678
|
-
draft.conversationMessages.push({
|
|
2679
|
-
id: randomUUID(),
|
|
2680
|
-
conversationId: task.conversationId,
|
|
2681
|
-
taskId: task.id,
|
|
2682
|
-
kind: "result",
|
|
2683
|
-
text: report,
|
|
2684
|
-
sourceBotId: bot.id,
|
|
2685
|
-
requestId: task.requestId,
|
|
2686
|
-
createdAt: Date.now(),
|
|
2687
|
-
});
|
|
2688
|
-
const remove = new Set(draft.messages
|
|
2689
|
-
.filter((m) => m.roomId === task.roomId)
|
|
2690
|
-
.slice(0, -getHistoryLimit())
|
|
2691
|
-
.map((m) => m.id));
|
|
2692
|
-
draft.messages = draft.messages.filter((m) => !remove.has(m.id));
|
|
2693
|
-
trimRoomReceipts(draft, task.roomId);
|
|
2694
|
-
}
|
|
2695
|
-
const room = draft.rooms.find((r) => r.id === task.roomId);
|
|
2696
|
-
const context = groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes);
|
|
2697
|
-
const wake = queueParentResult(draft, task, currentSettings());
|
|
2698
|
-
trimConversationHistory(draft, task.roomId);
|
|
2699
|
-
return { task, wake, context };
|
|
3153
|
+
return { task, duplicate: false };
|
|
2700
3154
|
});
|
|
2701
|
-
if (result
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
type: "status",
|
|
2707
|
-
phase: event.status,
|
|
2708
|
-
summary: `Task ${event.status}${report ? ": " + report.slice(0, 100) : ""}`,
|
|
2709
|
-
output: report,
|
|
2710
|
-
}, { roomId: result.task.roomId, accountId: result.task.accountId })
|
|
2711
|
-
.catch((cause) => {
|
|
2712
|
-
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 ?? [],
|
|
2713
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));
|
|
2714
3166
|
}
|
|
2715
|
-
if (isTerminal(result.task.status)) {
|
|
2716
|
-
deliveredTasks.delete(result.task.id);
|
|
2717
|
-
await releaseLocksAndWake(result.task.roomId, result.task.id);
|
|
2718
|
-
if (result.task.status === "completed") {
|
|
2719
|
-
await wakeDependentTasks(result.task.roomId, result.task.id, report);
|
|
2720
|
-
dispatchGroupWebhook(store, result.task.roomId, "task_completed", {
|
|
2721
|
-
taskId: result.task.id,
|
|
2722
|
-
botId: result.task.botId,
|
|
2723
|
-
status: "completed",
|
|
2724
|
-
report: result.task.report,
|
|
2725
|
-
text: result.task.text,
|
|
2726
|
-
});
|
|
2727
|
-
}
|
|
2728
|
-
else if (result.task.status === "failed") {
|
|
2729
|
-
dispatchGroupWebhook(store, result.task.roomId, "task_failed", {
|
|
2730
|
-
taskId: result.task.id,
|
|
2731
|
-
botId: result.task.botId,
|
|
2732
|
-
status: "failed",
|
|
2733
|
-
report: result.task.report,
|
|
2734
|
-
text: result.task.text,
|
|
2735
|
-
});
|
|
2736
|
-
}
|
|
2737
|
-
if (report) {
|
|
2738
|
-
const state = store.snapshot();
|
|
2739
|
-
const msg = state.messages.find((m) => m.taskIds.includes(result.task.id) && m.sender.id === result.task.botId);
|
|
2740
|
-
if (msg) {
|
|
2741
|
-
dispatchGroupWebhook(store, result.task.roomId, "message", msg);
|
|
2742
|
-
}
|
|
2743
|
-
}
|
|
2744
|
-
}
|
|
2745
|
-
if (result.wake)
|
|
2746
|
-
await deliverTask(result.wake, result.context);
|
|
2747
|
-
await drainConversation(result.task.conversationId);
|
|
2748
3167
|
return result.task;
|
|
2749
3168
|
}
|
|
2750
|
-
//
|
|
2751
|
-
const
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
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
|
+
}
|
|
2761
3183
|
}
|
|
2762
|
-
|
|
2763
|
-
|
|
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
|
+
}
|
|
2764
3196
|
}
|
|
3197
|
+
void reconcilePendingPublications();
|
|
2765
3198
|
let sweepInflight = false;
|
|
2766
3199
|
const recoverySweepTimer = setInterval(() => {
|
|
3200
|
+
void reconcilePendingPublications();
|
|
2767
3201
|
if (sweepInflight)
|
|
2768
3202
|
return;
|
|
2769
|
-
const
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
(
|
|
2773
|
-
|
|
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))))
|
|
2774
3211
|
return;
|
|
2775
3212
|
sweepInflight = true;
|
|
2776
3213
|
void (async () => {
|
|
2777
3214
|
try {
|
|
2778
|
-
const
|
|
2779
|
-
await
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
delete task.recoveryUntil;
|
|
2785
|
-
if (task.status === "running") {
|
|
2786
|
-
task.status = "interrupted";
|
|
2787
|
-
task.updatedAt = sweepNow;
|
|
2788
|
-
const report = windowExpired
|
|
2789
|
-
? "Hub restarted; recovery window expired without reconnect claim."
|
|
2790
|
-
: "Task lease expired due to prolonged inactivity.";
|
|
2791
|
-
task.report = report;
|
|
2792
|
-
const room = draft.rooms.find((r) => r.id === task.roomId);
|
|
2793
|
-
const context = room
|
|
2794
|
-
? groupTaskContext(room, draft.bots, draft.messages, currentSettings().groupContextBytes)
|
|
2795
|
-
: undefined;
|
|
2796
|
-
const wake = queueParentResult(draft, task, currentSettings());
|
|
2797
|
-
trimConversationHistory(draft, task.roomId);
|
|
2798
|
-
settledWakes.push({
|
|
2799
|
-
wake,
|
|
2800
|
-
context,
|
|
2801
|
-
conversationId: task.conversationId,
|
|
2802
|
-
taskId: task.id,
|
|
2803
|
-
roomId: task.roomId,
|
|
2804
|
-
});
|
|
2805
|
-
}
|
|
2806
|
-
}
|
|
2807
|
-
}
|
|
2808
|
-
});
|
|
2809
|
-
for (const item of settledWakes) {
|
|
2810
|
-
deliveredTasks.delete(item.taskId);
|
|
2811
|
-
await releaseLocksAndWake(item.roomId, item.taskId);
|
|
2812
|
-
if (item.wake)
|
|
2813
|
-
await deliverTask(item.wake, item.context);
|
|
2814
|
-
await drainConversation(item.conversationId);
|
|
2815
|
-
}
|
|
2816
|
-
const expiredPromoted = lockManager.cleanupExpiredLocks();
|
|
2817
|
-
for (const pTaskId of expiredPromoted) {
|
|
2818
|
-
const pTask = store.snapshot().tasks.find((t) => t.id === pTaskId);
|
|
2819
|
-
if (pTask) {
|
|
2820
|
-
await handlePromotedTasks(pTask.roomId, [pTaskId]);
|
|
2821
|
-
}
|
|
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]);
|
|
2822
3221
|
}
|
|
2823
3222
|
}
|
|
2824
|
-
catch {
|
|
2825
|
-
console.warn("[HubRecovery] Sweep transaction failed");
|
|
3223
|
+
catch (cause) {
|
|
3224
|
+
console.warn("[HubRecovery] Sweep transaction failed", cause);
|
|
2826
3225
|
}
|
|
2827
3226
|
finally {
|
|
2828
3227
|
sweepInflight = false;
|
|
@@ -2854,12 +3253,17 @@ export async function createDeviceHub(options) {
|
|
|
2854
3253
|
if (!task || !device) {
|
|
2855
3254
|
return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task not found" };
|
|
2856
3255
|
}
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
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)) {
|
|
2863
3267
|
return {
|
|
2864
3268
|
taskId: claim.taskId,
|
|
2865
3269
|
attemptId: claim.attemptId,
|
|
@@ -2899,7 +3303,7 @@ export async function createDeviceHub(options) {
|
|
|
2899
3303
|
reason: "Lease generation mismatch",
|
|
2900
3304
|
};
|
|
2901
3305
|
}
|
|
2902
|
-
if (task.status !== "running" && !
|
|
3306
|
+
if (task.status !== "running" && !(task.status === "queued" && hasTaskLease(task)) && !inRecovery) {
|
|
2903
3307
|
return {
|
|
2904
3308
|
taskId: claim.taskId,
|
|
2905
3309
|
attemptId: claim.attemptId,
|
|
@@ -2938,9 +3342,18 @@ export async function createDeviceHub(options) {
|
|
|
2938
3342
|
if (!task || !device || task.status !== "running") {
|
|
2939
3343
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task not running" };
|
|
2940
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
|
+
};
|
|
2941
3352
|
if (task.cancelRequested || task.stopConfirmed) {
|
|
2942
3353
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task stop requested" };
|
|
2943
3354
|
}
|
|
3355
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3356
|
+
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Recovery window expired" };
|
|
2944
3357
|
if (task.leaseToken !== renew.leaseToken) {
|
|
2945
3358
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Lease token mismatch" };
|
|
2946
3359
|
}
|
|
@@ -3064,8 +3477,10 @@ export async function createDeviceHub(options) {
|
|
|
3064
3477
|
const recoveryGraceMs = 60_000;
|
|
3065
3478
|
await store.transact((draft) => {
|
|
3066
3479
|
const task = draft.tasks.find((t) => t.id === taskId && t.deviceId === deviceId && t.attemptId === attemptId);
|
|
3067
|
-
if (task &&
|
|
3068
|
-
task.
|
|
3480
|
+
if (task &&
|
|
3481
|
+
!task.outcomeFingerprint &&
|
|
3482
|
+
(task.status === "running" || (task.status === "queued" && hasTaskLease(task)))) {
|
|
3483
|
+
task.recoveryUntil ??= now + recoveryGraceMs;
|
|
3069
3484
|
task.updatedAt = now;
|
|
3070
3485
|
}
|
|
3071
3486
|
});
|
|
@@ -3077,6 +3492,8 @@ export async function createDeviceHub(options) {
|
|
|
3077
3492
|
claimTask,
|
|
3078
3493
|
renewTaskLease,
|
|
3079
3494
|
onTaskDisconnect,
|
|
3495
|
+
resumeQueuedTasks,
|
|
3496
|
+
reconcilePendingPublications,
|
|
3080
3497
|
getAccount,
|
|
3081
3498
|
getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req) ?? undefined,
|
|
3082
3499
|
authenticateAgent,
|
|
@@ -3087,6 +3504,7 @@ export async function createDeviceHub(options) {
|
|
|
3087
3504
|
acceptTaskPlanReady,
|
|
3088
3505
|
setRelay(relay) {
|
|
3089
3506
|
options.relay = relay;
|
|
3507
|
+
void reconcilePendingPublications();
|
|
3090
3508
|
},
|
|
3091
3509
|
async close() {
|
|
3092
3510
|
clearInterval(recoverySweepTimer);
|