pi-web-ui 0.116.0 → 0.118.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 +83 -3
- package/README.md +69 -138
- package/README.zh-CN.md +70 -179
- package/README.zh-TW.md +3 -1
- package/bin/device-hub-cli.mjs +163 -36
- package/bin/frp-manager.mjs +4 -80
- package/bin/hub-upgrade.mjs +561 -0
- package/bin/pi-device-hub.mjs +0 -1
- package/bin/pi-web-ui.mjs +184 -504
- package/deploy/nginx-subpath.conf +0 -33
- package/deploy/pi-web-ui.service +0 -20
- package/dist/server/agent-formatters.js +4 -38
- package/dist/server/agent-service-daemon.js +203 -371
- package/dist/server/agent-service.js +1281 -3030
- package/dist/server/approval-audit.js +2 -23
- package/dist/server/approval-default-rules.js +0 -6
- package/dist/server/approval-rules.js +7 -105
- package/dist/server/ask-user-question-tool.js +1 -12
- package/dist/server/atomic-file.js +33 -5
- package/dist/server/attachment-store.js +0 -36
- package/dist/server/attachments.js +3 -112
- package/dist/server/auth-cookie.js +0 -21
- package/dist/server/bash-tool.js +1 -32
- package/dist/server/bg-servers.js +0 -96
- package/dist/server/browser-page-tool.js +11 -62
- package/dist/server/builtin-modules.js +7 -0
- package/dist/server/canvas/canvas-agent-tool.js +58 -47
- package/dist/server/canvas/canvas-cards.js +0 -14
- package/dist/server/canvas/canvas-dispatch.js +7 -4
- package/dist/server/canvas/canvas-orchestrator.js +167 -181
- package/dist/server/canvas/canvas-runtime-messages.js +30 -0
- package/dist/server/canvas/canvas-scheduled-task.js +0 -3
- package/dist/server/canvas/canvas-scheduler.js +5 -7
- package/dist/server/canvas/canvas-store.js +24 -35
- package/dist/server/canvas/canvas-validation.js +17 -14
- package/dist/server/canvas/canvas-workspace.js +42 -114
- package/dist/server/canvas/pstack-skills-data.js +0 -5
- package/dist/server/claim-files-tool.js +1 -15
- package/dist/server/claim-store.js +5 -49
- package/dist/server/client-id-utils.js +0 -16
- package/dist/server/client-state.js +36 -214
- package/dist/server/communicate-tool.js +0 -3
- package/dist/server/compact-context-tool.js +0 -30
- package/dist/server/compacted-history.js +0 -35
- package/dist/server/compaction-instructions.js +0 -13
- package/dist/server/compaction-markers.js +38 -92
- package/dist/server/compaction-state.js +0 -21
- package/dist/server/composer-drafts.js +0 -34
- package/dist/server/context-budget-runner.js +0 -11
- package/dist/server/context-budget.js +1 -70
- package/dist/server/context-evidence.js +0 -14
- package/dist/server/context-usage.js +0 -12
- package/dist/server/control-socket.js +4 -48
- package/dist/server/conversation-communication.js +0 -10
- package/dist/server/conversation-identity.js +0 -1
- package/dist/server/conversation-read-tool.js +0 -58
- package/dist/server/conversation-tool-names.js +0 -1
- package/dist/server/conversation-tool.js +0 -1
- package/dist/server/conversation-touches.js +4 -75
- package/dist/server/dangling-tools.js +142 -68
- package/dist/server/delegate-mode.js +0 -36
- package/dist/server/delegate-task.js +2 -28
- package/dist/server/device-center/approval-summary.js +0 -1
- package/dist/server/device-center/bot-catalog.js +0 -3
- package/dist/server/device-center/bot-execution.js +48 -9
- package/dist/server/device-center/bot-presets.js +0 -1
- package/dist/server/device-center/bots.js +0 -1
- package/dist/server/device-center/collab-service.js +27 -11
- package/dist/server/device-center/collab-tool.js +393 -27
- package/dist/server/device-center/connector.js +128 -48
- package/dist/server/device-center/delivery-authority.js +95 -0
- package/dist/server/device-center/delivery-subject.js +29 -0
- package/dist/server/device-center/desktop-linux.js +3 -15
- package/dist/server/device-center/desktop-native.js +1 -10
- package/dist/server/device-center/desktop-page.js +2 -3
- package/dist/server/device-center/desktop-setup.js +1 -3
- package/dist/server/device-center/desktop.js +1 -7
- package/dist/server/device-center/device-integration.js +452 -208
- package/dist/server/device-center/device-lan-access.js +403 -0
- package/dist/server/device-center/device-lan.js +484 -0
- package/dist/server/device-center/device-portals.js +0 -3
- package/dist/server/device-center/execution-failure.js +0 -2
- package/dist/server/device-center/execution-guides.js +15 -6
- package/dist/server/device-center/execution-instructions.js +0 -1
- package/dist/server/device-center/execution-settings.js +0 -1
- package/dist/server/device-center/execution-system-prompt.js +0 -3
- package/dist/server/device-center/execution-workspace.js +1 -4
- package/dist/server/device-center/executor.js +46 -31
- package/dist/server/device-center/file-sync-paths.js +0 -5
- package/dist/server/device-center/file-sync.js +0 -10
- package/dist/server/device-center/group-context-delta.js +0 -8
- package/dist/server/device-center/group-context-message.js +0 -14
- package/dist/server/device-center/group-context.js +0 -19
- package/dist/server/device-center/group-events.js +0 -2
- package/dist/server/device-center/group-plan-guard.js +1 -35
- package/dist/server/device-center/group-router-runtime.js +182 -0
- package/dist/server/device-center/group-router-worker.js +178 -0
- package/dist/server/device-center/group-router.js +359 -0
- package/dist/server/device-center/hub-auth.js +24 -2
- package/dist/server/device-center/hub-conversations.js +13 -15
- package/dist/server/device-center/hub-deliveries.js +119 -15
- package/dist/server/device-center/hub-integration.js +647 -334
- package/dist/server/device-center/hub-locks.js +1 -5
- package/dist/server/device-center/hub-mobile.js +147 -0
- package/dist/server/device-center/hub-orchestration.js +400 -0
- package/dist/server/device-center/hub-page.js +28 -9
- package/dist/server/device-center/hub-setup.js +23 -7
- package/dist/server/device-center/hub-transaction-log.js +175 -0
- package/dist/server/device-center/hub-upgrade.js +162 -0
- package/dist/server/device-center/hub-webhooks.js +1 -3
- package/dist/server/device-center/hub.js +946 -404
- package/dist/server/device-center/human-interaction.js +1 -4
- package/dist/server/device-center/integration-errors.js +0 -2
- package/dist/server/device-center/integration-verification.js +111 -0
- package/dist/server/device-center/local-hub.js +6 -4
- package/dist/server/device-center/local-publication.js +416 -0
- package/dist/server/device-center/local-verification-job.js +95 -0
- package/dist/server/device-center/local-verification.js +273 -0
- package/dist/server/device-center/local.js +341 -18
- package/dist/server/device-center/main.js +18 -2
- package/dist/server/device-center/mobile-notification-forwarder.js +292 -0
- package/dist/server/device-center/native-desktop/macos.js +0 -1
- package/dist/server/device-center/native-desktop/windows.js +0 -1
- package/dist/server/device-center/partition-log.js +52 -46
- package/dist/server/device-center/path-portal.js +42 -12
- package/dist/server/device-center/publication-journal.js +305 -0
- package/dist/server/device-center/publish-intent.js +374 -0
- package/dist/server/device-center/relay.js +217 -52
- package/dist/server/device-center/report-upload.js +0 -1
- package/dist/server/device-center/runtime.js +419 -52
- package/dist/server/device-center/store.js +223 -65
- package/dist/server/device-center/task-context-budget.js +0 -3
- package/dist/server/device-center/task-error.js +0 -1
- package/dist/server/device-center/task-journal.js +6 -23
- package/dist/server/device-center/task-outcome.js +68 -0
- package/dist/server/device-center/task-plan.js +0 -1
- package/dist/server/device-center/task-progress.js +0 -16
- package/dist/server/device-center/task-recovery.js +569 -227
- package/dist/server/device-center/task-report-outbox.js +0 -4
- package/dist/server/device-center/task-report.js +2 -10
- package/dist/server/device-center/task-scheduler.js +1 -35
- package/dist/server/device-center/task-settlement.js +335 -0
- package/dist/server/device-center/task-state.js +0 -12
- package/dist/server/device-center/task-workspace.js +393 -0
- package/dist/server/device-center/transfer-stream.js +5 -45
- package/dist/server/device-center/transfers.js +2 -10
- package/dist/server/device-center/verification-limits.js +9 -0
- package/dist/server/device-center/work-contract.js +923 -0
- package/dist/server/device-center/work-items.js +317 -0
- package/dist/server/device-center/workspaces.js +0 -1
- package/dist/server/dispatch-domain-handlers.js +202 -29
- package/dist/server/dispatch-plugin-handlers.js +2 -19
- package/dist/server/dsh/dsh-agent-service.js +78 -601
- package/dist/server/dsh/dsh-client.js +7 -111
- package/dist/server/dsh/dsh-market-service.js +4 -25
- package/dist/server/dsh/dsh-serialize.js +0 -49
- package/dist/server/dsh/dsh-sessions.js +0 -37
- package/dist/server/dsh/dsh-usage.js +0 -37
- package/dist/server/dsh/preset-clones.js +1 -65
- package/dist/server/dsh/runtime/custom-prompt.mjs +0 -14
- package/dist/server/dsh/runtime/goal-rpc.mjs +7 -176
- package/dist/server/dsh/runtime/launcher.mjs +2 -53
- package/dist/server/dsh/runtime/override.patch.yml +0 -29
- package/dist/server/dsh/runtime/runtime-root.mjs +0 -54
- package/dist/server/durable/durable-agent-service.js +5 -23
- package/dist/server/durable/durable-driver.js +12 -73
- package/dist/server/durable/durable-event-projector.js +1 -50
- package/dist/server/durable/durable-loader.js +0 -12
- package/dist/server/durable/durable-models.js +11 -80
- package/dist/server/durable/durable-storage.js +1 -17
- package/dist/server/durable/durable-tools.js +2 -20
- package/dist/server/durable/index.js +0 -3
- package/dist/server/edit-soft-tool.js +2 -81
- package/dist/server/engine-capabilities.js +0 -13
- package/dist/server/engine-catalog.js +74 -0
- package/dist/server/engine-cli.js +89 -0
- package/dist/server/engine-probe.js +35 -217
- package/dist/server/ensure-bash.js +2 -28
- package/dist/server/eval-tool.js +1 -50
- package/dist/server/evidence-tool-hooks.js +0 -2
- package/dist/server/file-archives.js +0 -10
- package/dist/server/file-save.js +1 -12
- package/dist/server/file-transfer-routes.js +0 -11
- package/dist/server/files-service.js +18 -271
- package/dist/server/global-loader.js +9 -89
- package/dist/server/goal-evidence.js +1 -35
- package/dist/server/goal-review-gate.js +0 -58
- package/dist/server/goal-service.js +19 -422
- package/dist/server/hashline-engine.js +8 -112
- package/dist/server/host-guard.js +0 -24
- package/dist/server/host-metrics.js +0 -6
- package/dist/server/http-proxy.js +1 -7
- package/dist/server/i18n.js +5 -72
- package/dist/server/icon-svg.js +0 -15
- package/dist/server/index.js +199 -677
- package/dist/server/json-utils.js +0 -12
- package/dist/server/launch-origin.js +0 -44
- package/dist/server/left-panel-running.js +0 -9
- package/dist/server/load-timing.js +1 -4
- package/dist/server/load-tools-tool.js +0 -20
- package/dist/server/locales.js +1 -46
- package/dist/server/lsp-tool.js +13 -126
- package/dist/server/managed.js +0 -48
- package/dist/server/marker-service.js +1 -22
- package/dist/server/markers/builtins/action.js +0 -19
- package/dist/server/markers/builtins/notify.js +1 -9
- package/dist/server/markers/builtins/rename.js +0 -13
- package/dist/server/markers/index.js +0 -3
- package/dist/server/markers/marker.js +0 -13
- package/dist/server/markers/registry.js +0 -3
- package/dist/server/markers/store.js +1 -12
- package/dist/server/market-service.js +7 -43
- package/dist/server/mcp-agent-tool.js +0 -10
- package/dist/server/mcp-bridge.js +6 -138
- package/dist/server/mcp-hot-reload.js +0 -25
- package/dist/server/mcp-manager.js +2 -44
- package/dist/server/mcp-oauth-login.js +0 -2
- package/dist/server/mcp-oauth-ui.js +1 -4
- package/dist/server/mcp-oauth.js +5 -79
- package/dist/server/mcp-project-runtime.js +0 -4
- package/dist/server/message-deletion.js +0 -2
- package/dist/server/message-entry-resolver.js +0 -8
- package/dist/server/message-window.js +0 -71
- package/dist/server/mobile-notification-events.js +16 -0
- package/dist/server/mobile-origin.js +79 -0
- package/dist/server/mobile-push.js +523 -0
- package/dist/server/model-admin.js +19 -358
- package/dist/server/model-enrich.js +0 -19
- package/dist/server/model-resolver.js +2 -61
- package/dist/server/native-cli-discovery.js +115 -0
- package/dist/server/native-cli-model.js +71 -0
- package/dist/server/native-cli-references.js +214 -0
- package/dist/server/native-cli-remote-cleanup.js +58 -0
- package/dist/server/native-cli-remote-files.js +282 -0
- package/dist/server/native-cli-routes.js +68 -0
- package/dist/server/native-cli-runtime.js +1 -0
- package/dist/server/native-cli-session-hooks.js +170 -0
- package/dist/server/native-cli-session.js +585 -0
- package/dist/server/native-cli-state.js +82 -0
- package/dist/server/native-cli.js +210 -0
- package/dist/server/net-guard.js +9 -71
- package/dist/server/office-parse.js +0 -50
- package/dist/server/orphan-manager.js +0 -18
- package/dist/server/patch-bash-process.js +0 -4
- package/dist/server/patch-executable-lookup.js +0 -77
- package/dist/server/patch-node-pty.js +6 -45
- package/dist/server/patch-remote-catalog.js +4 -34
- package/dist/server/patch-tool.js +0 -15
- package/dist/server/payload-limits.js +0 -5
- package/dist/server/pending-question.js +0 -5
- package/dist/server/permission-preset.js +4 -33
- package/dist/server/persona-chain.js +0 -26
- package/dist/server/pkg-info.js +1 -17
- package/dist/server/plan-manager.js +2 -49
- package/dist/server/plan-mode.js +0 -97
- package/dist/server/plan-update-tool.js +1 -15
- package/dist/server/plugin-api-catalog.js +6 -4
- package/dist/server/plugin-assets.js +1 -35
- package/dist/server/plugin-bundled.js +68 -0
- package/dist/server/plugin-catalog-sync.js +0 -37
- package/dist/server/plugin-catalog.js +13 -67
- package/dist/server/plugin-chat-attachments.js +0 -1
- package/dist/server/plugin-conversation-view.js +0 -20
- package/dist/server/plugin-dom.js +1 -23
- package/dist/server/plugin-facilities.js +4 -115
- package/dist/server/plugin-grants.js +2 -90
- package/dist/server/plugin-install-spec.js +0 -43
- package/dist/server/plugin-installer.js +34 -75
- package/dist/server/plugin-llm.js +4 -38
- package/dist/server/plugin-manifest-validate.js +0 -31
- package/dist/server/plugin-permissions.js +1 -24
- package/dist/server/plugin-project.js +7 -129
- package/dist/server/plugin-removal.js +1 -8
- package/dist/server/plugin-schedule.js +1 -38
- package/dist/server/plugin-secrets.js +3 -16
- package/dist/server/plugin-tool-guard.js +1 -28
- package/dist/server/plugin-ui-slots.js +0 -4
- package/dist/server/plugin-updater.js +15 -90
- package/dist/server/plugins.js +71 -619
- package/dist/server/present-files-tool.js +0 -57
- package/dist/server/preset-fields.js +24 -61
- package/dist/server/preset-plugin-dependencies.js +0 -2
- package/dist/server/preset-share.js +4 -172
- package/dist/server/process-utils.js +4 -80
- package/dist/server/prompt-assembler.js +2 -30
- package/dist/server/prompt-base-store.js +0 -47
- package/dist/server/prompt-composer.js +21 -98
- package/dist/server/prompt-templates.js +0 -2
- package/dist/server/protocol-version.js +1 -11
- package/dist/server/protocol.js +0 -5
- package/dist/server/queue-modes.js +0 -3
- package/dist/server/queue-utils.js +0 -40
- package/dist/server/quick-ask-context.js +384 -0
- package/dist/server/quick-ask-settings.js +61 -0
- package/dist/server/quick-ask.js +260 -0
- package/dist/server/read-tool.js +0 -65
- package/dist/server/reasoning-registry.js +1 -29
- package/dist/server/remote-cli-persistence.js +373 -0
- package/dist/server/remote-native-cli.js +78 -0
- package/dist/server/remote-ssh-service.js +481 -190
- package/dist/server/request-context.js +0 -9
- package/dist/server/resolve-global-sdk.js +55 -31
- package/dist/server/sandbox-data.js +0 -1
- package/dist/server/sandbox-engines.js +0 -1
- package/dist/server/sandbox-runtime-gate.js +0 -3
- package/dist/server/sandbox-service.js +0 -41
- package/dist/server/sandbox-tool.js +0 -20
- package/dist/server/schedule-agent-tool.js +2 -31
- package/dist/server/scheduler-tasks.js +32 -56
- package/dist/server/scm-commitmsg.js +0 -53
- package/dist/server/scm.js +3 -48
- package/dist/server/sdk-builtin-extensions.js +2 -29
- package/dist/server/sdk-origin.js +0 -45
- package/dist/server/serialize.js +2 -92
- package/dist/server/server-config.js +0 -11
- package/dist/server/session-branch.js +1 -87
- package/dist/server/session-list-scan.js +215 -0
- package/dist/server/session-open.js +69 -0
- package/dist/server/session-parser.js +4 -54
- package/dist/server/session-scan.js +81 -45
- package/dist/server/session-search.js +0 -56
- package/dist/server/settings-service.js +19 -126
- package/dist/server/setup-config.js +0 -2
- package/dist/server/setup-page.js +0 -9
- package/dist/server/skill-content-filler.js +0 -17
- package/dist/server/skill-discovery.js +5 -92
- package/dist/server/skill-maintenance.js +1 -28
- package/dist/server/skill-tool.js +0 -30
- package/dist/server/slash-commands.js +5 -50
- package/dist/server/soft-cap.js +3 -40
- package/dist/server/startup-banner.js +0 -8
- package/dist/server/subagent-handoff.js +0 -11
- package/dist/server/subagent-helpers.js +2 -17
- package/dist/server/subagent-notify.js +0 -19
- package/dist/server/subagent-security-gate.js +0 -50
- package/dist/server/subagent-task.js +0 -9
- package/dist/server/subagent-templates-hant.js +0 -10
- package/dist/server/subagent-templates.js +3 -103
- package/dist/server/subagents.js +1 -87
- package/dist/server/system-screenshot-windows.js +259 -0
- package/dist/server/system-screenshot.js +77 -0
- package/dist/server/tabs.js +3 -48
- package/dist/server/terminals.js +559 -586
- package/dist/server/text-quote.js +0 -12
- package/dist/server/text-sniff.js +2 -52
- package/dist/server/themes.js +2 -41
- package/dist/server/tool-approval.js +0 -47
- package/dist/server/tool-guards.js +0 -90
- package/dist/server/tool-host-factories.js +1 -16
- package/dist/server/tool-info.js +0 -13
- package/dist/server/tool-manager.js +1 -229
- package/dist/server/tool-overrides.js +1 -46
- package/dist/server/tool-prompt-overrides.js +1 -30
- package/dist/server/tool-prompts.js +0 -14
- package/dist/server/tool-signature.js +0 -25
- package/dist/server/transcript-prepare.js +55 -0
- package/dist/server/tts-routes.js +58 -0
- package/dist/server/tts-service.js +106 -0
- package/dist/server/tts-system.js +160 -0
- package/dist/server/turn-timing.js +0 -1
- package/dist/server/unauthorized-page.js +0 -8
- package/dist/server/universal/driver-base.js +2 -31
- package/dist/server/universal/drivers/claude-code.js +98 -194
- package/dist/server/universal/drivers/codex.js +12 -35
- package/dist/server/universal/drivers/mock-driver.js +1 -11
- package/dist/server/universal/index.js +0 -3
- package/dist/server/universal/session-store.js +4 -21
- package/dist/server/universal/universal-attachments.js +2 -36
- package/dist/server/universal/universal-service.js +5 -24
- package/dist/server/universal/universal-session.js +30 -148
- package/dist/server/universal/universal-types.js +0 -3
- package/dist/server/update-check.js +6 -182
- package/dist/server/uploads.js +4 -43
- package/dist/server/virtual-tui.js +2 -27
- package/dist/server/vision-bridge.js +0 -27
- package/dist/server/wait-subscription-scan.js +13 -115
- package/dist/server/webui-context.js +2 -87
- package/dist/server/workspace-handle.js +373 -0
- package/dist/server/workspace-snapshot.js +7 -113
- package/dist/server/worktree-service.js +2 -53
- package/dist/server/worktree-tool.js +0 -11
- package/dist/server/ws-client-id.js +0 -18
- package/dist/server/ws-pending-queue.js +0 -7
- package/dist/server/ws-unknown-types.js +0 -17
- package/docs/README.md +24 -17
- package/docs/architecture-plugins.md +55 -6
- package/docs/device-center.md +57 -23
- package/docs/device-desktop.md +3 -3
- package/docs/group-orchestration.md +142 -0
- package/docs/hub-upgrade-release-testing.md +46 -0
- package/extensions/webui.ts +3 -74
- package/package.json +9 -6
- package/plugin-sdk/README.md +22 -8
- package/plugin-sdk/client-utils.mjs +0 -7
- package/plugin-sdk/client.d.ts +26 -0
- package/plugin-sdk/client.mjs +52 -0
- package/plugin-sdk/import-check.mjs +4 -51
- package/plugin-sdk/index.d.ts +128 -117
- package/plugin-sdk/index.mjs +2 -687
- package/plugin-sdk/package.json +15 -4
- package/plugin-sdk/ssh-host-trust.mjs +0 -12
- package/plugin-sdk/testing.d.ts +9 -0
- package/plugin-sdk/testing.mjs +511 -0
- package/plugins/catalog.json +52 -4
- package/plugins/superagent/README.md +110 -0
- package/plugins/superagent/client/entry.mjs +21 -0
- package/plugins/superagent/index.mjs +8 -0
- package/plugins/superagent/main.mjs +218 -0
- package/plugins/superagent/manifest.json +15 -0
- package/plugins/superagent/server.mjs +572 -0
- package/plugins/superagent/style.css +167 -0
- package/themes/aetheris.css +1 -31
- package/themes/ayu-light.css +0 -1
- package/themes/bases/flow-base.css +2 -83
- package/themes/bases/obsidian-base.css +2 -37
- package/themes/bases/statusbar-flat-base.css +0 -1
- package/themes/bases/zhujian-base.css +0 -63
- package/themes/bases/zhupi-base.css +0 -64
- package/themes/catppuccin-latte.css +0 -1
- package/themes/catppuccin.css +0 -1
- package/themes/claude-code-dark.css +0 -1
- package/themes/codex.css +0 -1
- package/themes/dark-teal.css +22 -54
- package/themes/everforest-light.css +0 -1
- package/themes/flow-cristallo.css +160 -0
- package/themes/flow-ink.css +160 -0
- package/themes/flow-light.css +1 -10
- package/themes/flow-obsidian.css +160 -0
- package/themes/flow-zurich.css +160 -0
- package/themes/flow.css +1 -9
- package/themes/geist.css +0 -1
- package/themes/gruvbox-light.css +0 -1
- package/themes/kanagawa-lotus.css +0 -1
- package/themes/md-preview.css +1 -2
- package/themes/mist.css +0 -1
- package/themes/nord.css +0 -1
- package/themes/one-dark.css +0 -1
- package/themes/paper.css +0 -1
- package/themes/rose-pine-dawn.css +0 -1
- package/themes/sakura.css +0 -1
- package/themes/solarized-light.css +0 -1
- package/themes/tokyo-night.css +0 -1
- package/themes/translucent.css +4 -35
- package/themes/transparent.css +4 -41
- package/themes/vs-code-dark.css +0 -1
- package/themes/wallpaper-flow.css +3 -17
- package/themes/wallpaper-obsidian.css +1 -4
- package/themes/white.css +0 -1
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-D-x7kA63.js} +1 -1
- package/web/dist/assets/CanvasStudio-CAWcs9tm.js +1579 -0
- package/web/dist/assets/DeviceCenter-Dc0whRcu.js +3 -0
- package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +1 -0
- package/web/dist/assets/DeviceGroups-C_fZMNeK.js +1 -0
- package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CTgVLUbp.js} +1 -1
- package/web/dist/assets/FilePreview-C6W0PvaK.js +2 -0
- package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +1 -0
- package/web/dist/assets/GroupConversation-C81YjF2C.js +61 -0
- package/web/dist/assets/GroupWorkItems-BIvZtr10.js +1 -0
- package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-Da6qc566.js} +1 -1
- package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +2 -0
- package/web/dist/assets/NativeCliPanel-CU1rZmyu.js +5 -0
- package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-DZKY5Wiw.js} +1 -1
- package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +1 -0
- package/web/dist/assets/SCMPanel-CuEgzAlO.js +2 -0
- package/web/dist/assets/SettingsModal-Cdu5h29p.js +33 -0
- package/web/dist/assets/TermXterm-Bt5WKAxP.js +3 -0
- package/web/dist/assets/TerminalPanel-BCIBV8se.js +1 -0
- package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +1 -0
- package/web/dist/assets/app-globals-CZjFtI4F.js +129 -0
- package/web/dist/assets/canvas-client-WkhM55mR.js +1 -0
- package/web/dist/assets/composer-bridge-CImnjDHq.js +1 -0
- package/web/dist/assets/desktop-B8NZ3KW-.js +1 -0
- package/web/dist/assets/index-CQc3VrWa.css +1 -0
- package/web/dist/assets/index-D_AGu4Zv.js +404 -0
- package/web/dist/assets/plugin-host-uqZGpvCs.js +1 -0
- package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Cdf-cTUe.js} +1 -1
- package/web/dist/assets/theme-DGL7hLUs.js +1 -0
- package/web/dist/index.html +12 -11
- package/web/dist/sw.js +15 -61
- package/web/public/sw.js +14 -60
- 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/BgTasksModal-C0i3O1FT.js +0 -1
- package/web/dist/assets/CanvasStudio-B8thymBN.js +0 -1579
- package/web/dist/assets/CanvasStudio-zSxyIx1R.js +0 -1579
- package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
- package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
- package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +0 -1
- 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/GlobalSearchModal-BWgU8yPd.js +0 -1
- package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +0 -1
- 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/ProviderOAuthControls-BGSBIKD7.js +0 -1
- 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/TerminalPanel-0CYvD72B.js +0 -3
- package/web/dist/assets/TerminalPanel-DDavKvFr.js +0 -3
- package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +0 -1
- package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +0 -1
- package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
- package/web/dist/assets/canvas-client-CUnXlQYX.js +0 -1
- package/web/dist/assets/desktop-aAKpvKJV.js +0 -1
- 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
- package/web/dist/assets/plugin-host-BRWib9DF.js +0 -1
- package/web/dist/assets/theme-D2l_mLNo.js +0 -1
|
@@ -5,22 +5,32 @@ 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";
|
|
29
|
+
import { createHubMobileApp, acceptMobileNotification } from "./hub-mobile.js";
|
|
30
|
+
import { createMobilePushService } from "../mobile-push.js";
|
|
31
|
+
import { HubUpgradeError } from "./hub-upgrade.js";
|
|
32
|
+
import { installHubOrchestration } from "./hub-orchestration.js";
|
|
33
|
+
import { queueRouterJob, nextRouterAction } from "./group-router.js";
|
|
24
34
|
class HttpError extends Error {
|
|
25
35
|
status;
|
|
26
36
|
constructor(status, message) {
|
|
@@ -85,7 +95,7 @@ export async function createDeviceHub(options) {
|
|
|
85
95
|
domain.hostname.endsWith(`.${origin.hostname}`))
|
|
86
96
|
throw new Error("Device domain must be independent of hub domain");
|
|
87
97
|
}
|
|
88
|
-
const store = await DeviceHubStore.open(options.dataDir);
|
|
98
|
+
const store = await DeviceHubStore.open(options.dataDir, { retainUnleasedQueued: true });
|
|
89
99
|
const taskJournalManager = createTaskJournalManager(options.dataDir);
|
|
90
100
|
const taskReportStore = createTaskReportStore(options.dataDir, "hub");
|
|
91
101
|
const groupEvents = createGroupEvents(store, taskJournalManager);
|
|
@@ -116,6 +126,21 @@ export async function createDeviceHub(options) {
|
|
|
116
126
|
};
|
|
117
127
|
const app = express();
|
|
118
128
|
app.disable("x-powered-by");
|
|
129
|
+
const loginLimit = new HubRateLimiter(10, 60000);
|
|
130
|
+
const mobilePush = createMobilePushService({ dataDir: options.dataDir });
|
|
131
|
+
const mobileApp = createHubMobileApp({
|
|
132
|
+
store,
|
|
133
|
+
publicUrl: options.publicUrl,
|
|
134
|
+
loginLimit,
|
|
135
|
+
mobilePush,
|
|
136
|
+
isOnline: (id) => options.isOnline?.(id) ?? false,
|
|
137
|
+
createCapability: (request) => options.relay?.createNativeCapability?.(request) ?? Promise.resolve(null),
|
|
138
|
+
});
|
|
139
|
+
app.use((req, res, next) => {
|
|
140
|
+
if (/^\/api\/(?:mobile-hub|mobile-push)(?:\/|$)/.test(req.path))
|
|
141
|
+
return mobileApp(req, res, next);
|
|
142
|
+
next();
|
|
143
|
+
});
|
|
119
144
|
app.use((req, _res, next) => {
|
|
120
145
|
if (!req.path.startsWith("/api/device-user/"))
|
|
121
146
|
return next();
|
|
@@ -131,8 +156,15 @@ export async function createDeviceHub(options) {
|
|
|
131
156
|
if (req.method === "POST" && !agentWrites.allow("user:" + device.id))
|
|
132
157
|
fail(429, "Too many user writes");
|
|
133
158
|
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);
|
|
159
|
+
const conversationRoute = /^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:messages|stop|deliveries|reviews|task-state|evidence|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel|reconcile|resume))?)?))?)?$/.test(suffix);
|
|
135
160
|
const taskRoute = /^\/rooms\/[^/]+\/tasks\/[^/]+(?:\/(?:journal|report))?$/.test(suffix);
|
|
161
|
+
const orchestrationRoute = /^\/(?:router-models|work-items(?:\/[^/]+)?|work-item-deliveries\/(?:claim|[^/]+\/(?:complete|fail))|rooms\/[^/]+\/(?:work-items(?:\/[^/]+)?|router\/jobs\/[^/]+\/retry))$/.test(suffix);
|
|
162
|
+
if ((orchestrationRoute && ["GET", "POST", "PATCH"].includes(req.method)) ||
|
|
163
|
+
(req.method === "POST" && /^\/rooms\/[^/]+$/.test(suffix))) {
|
|
164
|
+
users.set(req, { device, account: { id: owner.id, username: owner.username } });
|
|
165
|
+
req.url = req.url.replace("/api/device-user/", "/api/");
|
|
166
|
+
return next();
|
|
167
|
+
}
|
|
136
168
|
const webhookRoute = /^\/rooms\/[^/]+\/(?:webhooks(?:\/[^/]+(?:\/(?:delete|regenerate-token|test))?)?|hub-relay)$/.test(suffix);
|
|
137
169
|
if (!((req.method === "GET" &&
|
|
138
170
|
(conversationRoute ||
|
|
@@ -140,13 +172,14 @@ export async function createDeviceHub(options) {
|
|
|
140
172
|
webhookRoute ||
|
|
141
173
|
/^\/rooms\/[^/]+\/(?:events|interactions|transfers|locks|blackboard)$/.test(suffix) ||
|
|
142
174
|
/^\/rooms\/[^/]+\/transfers\/[^/]+\/preview$/.test(suffix) ||
|
|
143
|
-
["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
175
|
+
["/devices", "/bots", "/rooms", "/system/upgrade"].includes(suffix) ||
|
|
144
176
|
/^\/rooms\/[^/]+$/.test(suffix))) ||
|
|
145
177
|
(["POST", "PUT"].includes(req.method) &&
|
|
146
178
|
(suffix === "/rooms" ||
|
|
179
|
+
suffix === "/system/upgrade" ||
|
|
147
180
|
conversationRoute ||
|
|
148
181
|
webhookRoute ||
|
|
149
|
-
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard)$/.test(suffix) ||
|
|
182
|
+
/^\/rooms\/[^/]+\/(messages|rename|members|clear|delete|interactions|canvas|blackboard(?:\/sections\/[^/]+)?)$/.test(suffix) ||
|
|
150
183
|
/^\/rooms\/[^/]+\/tasks\/[^/]+\/approve-plan$/.test(suffix) ||
|
|
151
184
|
/^\/rooms\/[^/]+\/transfers(?:\/start|\/[^/]+(?:\/(?:apply|abort|resume))?)?$/.test(suffix) ||
|
|
152
185
|
/^\/devices\/[^/]+\/(open|remark)$/.test(suffix)))))
|
|
@@ -166,17 +199,24 @@ export async function createDeviceHub(options) {
|
|
|
166
199
|
fail(429, "Too many device writes");
|
|
167
200
|
agents.set(req, agent);
|
|
168
201
|
const suffix = req.path.slice("/api/agent".length);
|
|
202
|
+
if ((req.method === "GET" && suffix === "/router/jobs/next") ||
|
|
203
|
+
(req.method === "POST" && /^\/router\/jobs\/[^/]+\/(?:complete|renew|fail)$/.test(suffix))) {
|
|
204
|
+
req.url = req.url.replace("/api/agent/", "/api/");
|
|
205
|
+
return next();
|
|
206
|
+
}
|
|
169
207
|
if ((req.method === "GET" &&
|
|
170
208
|
(["/devices", "/bots", "/rooms"].includes(suffix) ||
|
|
171
|
-
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard))?$/.test(suffix) ||
|
|
209
|
+
/^\/rooms\/[^/]+(?:\/(?:history|locks|blackboard(?:\/sections\/[^/]+)?))?$/.test(suffix) ||
|
|
172
210
|
/^\/rooms\/[^/]+\/conversations(?:\/[^/]+(?:\/(?:task-state|evidence))?)?$/.test(suffix))) ||
|
|
173
211
|
(req.method === "POST" &&
|
|
174
212
|
(suffix === "/rooms" ||
|
|
175
213
|
/^\/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
|
|
214
|
+
/^\/rooms\/[^/]+\/(?:messages|blackboard|conversations(?:\/[^/]+\/(?:messages|stop|deliveries|reviews|attention|task-state|integrations(?:\/[^/]+(?:\/(?:verify|apply|cancel|reconcile|resume))?)?))?)$/.test(suffix))) ||
|
|
215
|
+
(req.method === "PUT" && /^\/rooms\/[^/]+\/blackboard(?:\/sections\/[^/]+)?$/.test(suffix)))
|
|
178
216
|
req.url = req.url.replace("/api/agent/", "/api/");
|
|
179
|
-
else if (!((suffix === "/transfers" && req.method === "POST") ||
|
|
217
|
+
else if (!((suffix === "/transfers" && req.method === "POST") ||
|
|
218
|
+
(suffix === "/bots" && req.method === "PUT") ||
|
|
219
|
+
(suffix === "/mobile-notifications" && req.method === "POST")))
|
|
180
220
|
fail(404, "Agent route missing");
|
|
181
221
|
next();
|
|
182
222
|
});
|
|
@@ -192,24 +232,38 @@ export async function createDeviceHub(options) {
|
|
|
192
232
|
next();
|
|
193
233
|
});
|
|
194
234
|
const json = express.json({ limit: "32kb", strict: true });
|
|
235
|
+
const contractJson = express.json({ limit: MAX_CONTRACT_REQUEST_BYTES, strict: true });
|
|
195
236
|
const blackboardJson = express.json({ limit: "512kb", strict: true });
|
|
196
237
|
const reportJson = express.json({ limit: TASK_REPORT_UPLOAD_JSON_BYTES, strict: true });
|
|
197
238
|
const reportWrites = new HubRateLimiter(4096, 60000);
|
|
198
239
|
app.use((req, res, next) => {
|
|
199
240
|
if (agents.has(req) && req.path === "/api/agent/transfers")
|
|
200
241
|
return next();
|
|
242
|
+
if (req.method === "POST" &&
|
|
243
|
+
(req.path === "/api/work-items/ingest" || /^\/api\/router\/jobs\/[^/]+\/complete$/.test(req.path)))
|
|
244
|
+
return contractJson(req, res, next);
|
|
245
|
+
if (req.method === "POST" &&
|
|
246
|
+
/^\/api\/rooms\/[^/]+\/(?:messages|tasks|conversations(?:\/[^/]+\/messages)?)$/.test(req.path))
|
|
247
|
+
return contractJson(req, res, next);
|
|
201
248
|
if (agents.has(req) && req.method === "POST" && /^\/api\/rooms\/[^/]+\/tasks\/[^/]+\/report$/.test(req.path)) {
|
|
202
249
|
if (!reportWrites.allow(agents.get(req).device.id))
|
|
203
250
|
return res.status(429).json({ error: "Too many report chunks" });
|
|
204
251
|
return reportJson(req, res, next);
|
|
205
252
|
}
|
|
206
253
|
if ((req.method === "PUT" || req.method === "POST") &&
|
|
207
|
-
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard
|
|
254
|
+
/^\/api\/(?:agent\/)?rooms\/[^/]+\/blackboard(?:\/sections\/[^/]+)?$/.test(req.path)) {
|
|
208
255
|
return blackboardJson(req, res, next);
|
|
209
256
|
}
|
|
210
257
|
json(req, res, next);
|
|
211
258
|
});
|
|
212
|
-
|
|
259
|
+
app.post("/api/agent/mobile-notifications", async (req, res) => {
|
|
260
|
+
const agent = agents.get(req);
|
|
261
|
+
if (store.getDeviceOwner(agent.device.id) !== agent.account.id)
|
|
262
|
+
fail(401, "Device revoked");
|
|
263
|
+
const device = store.getDevice(agent.device.id);
|
|
264
|
+
await acceptMobileNotification(req.body, device, mobilePush);
|
|
265
|
+
res.json({ ok: true });
|
|
266
|
+
});
|
|
213
267
|
const pairLimit = new HubRateLimiter(20, 60000);
|
|
214
268
|
const pairs = new Map();
|
|
215
269
|
const sweepPairs = () => {
|
|
@@ -235,8 +289,12 @@ export async function createDeviceHub(options) {
|
|
|
235
289
|
(options.deviceDomain ? `${origin.protocol}//${device.id}.${options.deviceDomain}` : null),
|
|
236
290
|
alias: options.portals?.getAlias(device.id) ?? null,
|
|
237
291
|
});
|
|
292
|
+
const publicAccount = (current) => ({
|
|
293
|
+
...current,
|
|
294
|
+
canUpgradeHub: store.snapshot().accounts[0]?.id === current.id,
|
|
295
|
+
});
|
|
238
296
|
for (const route of ["/api/me", "/api/auth/me"])
|
|
239
|
-
app.get(route, (req, res) => res.json({ account: account(req) }));
|
|
297
|
+
app.get(route, (req, res) => res.json({ account: publicAccount(account(req)) }));
|
|
240
298
|
app.post("/api/auth/register", async (req, res) => {
|
|
241
299
|
if (!loginLimit.allow(ip(req)))
|
|
242
300
|
fail(429, "Too many attempts");
|
|
@@ -262,7 +320,7 @@ export async function createDeviceHub(options) {
|
|
|
262
320
|
return { id: entry.id, username };
|
|
263
321
|
});
|
|
264
322
|
res.setHeader("Set-Cookie", auth.cookie(sessionToken));
|
|
265
|
-
res.status(201).json({ account: created });
|
|
323
|
+
res.status(201).json({ account: publicAccount(created) });
|
|
266
324
|
});
|
|
267
325
|
app.post("/api/auth/login", async (req, res) => {
|
|
268
326
|
if (!loginLimit.allow(ip(req)))
|
|
@@ -270,7 +328,6 @@ export async function createDeviceHub(options) {
|
|
|
270
328
|
const username = text(req.body?.username, 64).trim().toLowerCase();
|
|
271
329
|
const password = text(req.body?.["pass" + "word"], 1024);
|
|
272
330
|
const entry = store.snapshot().accounts.find((item) => item.username === username);
|
|
273
|
-
// Run the same KDF for missing accounts, avoiding a cheap username oracle.
|
|
274
331
|
if (!(await verifyPassword(password, entry?.passwordHash ?? `scrypt:${"0".repeat(32)}:${"0".repeat(128)}`)) ||
|
|
275
332
|
!entry)
|
|
276
333
|
fail(401, "Invalid credentials");
|
|
@@ -282,7 +339,7 @@ export async function createDeviceHub(options) {
|
|
|
282
339
|
draft.sessions.push({ accountId: entry.id, hash: hashSecret(sessionToken), expiresAt: Date.now() + SESSION_TTL });
|
|
283
340
|
});
|
|
284
341
|
res.setHeader("Set-Cookie", auth.cookie(sessionToken));
|
|
285
|
-
res.json({ account: { id: entry.id, username: entry.username } });
|
|
342
|
+
res.json({ account: publicAccount({ id: entry.id, username: entry.username }) });
|
|
286
343
|
});
|
|
287
344
|
app.post("/api/auth/logout", async (req, res) => {
|
|
288
345
|
const value = auth.getToken(req);
|
|
@@ -292,6 +349,40 @@ export async function createDeviceHub(options) {
|
|
|
292
349
|
res.setHeader("Set-Cookie", auth.cookie("", true));
|
|
293
350
|
res.json({ ok: true });
|
|
294
351
|
});
|
|
352
|
+
const upgradeOwner = (req) => {
|
|
353
|
+
const current = account(req);
|
|
354
|
+
if (store.snapshot().accounts[0]?.id !== current.id)
|
|
355
|
+
fail(403, "Only the Hub owner can upgrade the service");
|
|
356
|
+
return current;
|
|
357
|
+
};
|
|
358
|
+
app.post("/api/system/upgrade", async (req, res) => {
|
|
359
|
+
const current = upgradeOwner(req);
|
|
360
|
+
if (!options.upgradeManager)
|
|
361
|
+
fail(409, "Hub updates require an installed standalone service");
|
|
362
|
+
try {
|
|
363
|
+
const job = await options.upgradeManager.start(current.id);
|
|
364
|
+
res.setHeader("Cache-Control", "no-store");
|
|
365
|
+
res.status(202).json({ ok: true, job });
|
|
366
|
+
}
|
|
367
|
+
catch (error) {
|
|
368
|
+
if (error instanceof HubUpgradeError)
|
|
369
|
+
return res.status(error.status).json({ error: error.message });
|
|
370
|
+
throw error;
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
app.get("/api/system/upgrade", async (req, res) => {
|
|
374
|
+
upgradeOwner(req);
|
|
375
|
+
if (!options.upgradeManager)
|
|
376
|
+
fail(409, "Hub updates require an installed standalone service");
|
|
377
|
+
const id = typeof req.query.id === "string" ? req.query.id : undefined;
|
|
378
|
+
if (id && !/^[a-f0-9-]{36}$/.test(id))
|
|
379
|
+
fail(400, "Invalid upgrade job ID");
|
|
380
|
+
const job = await options.upgradeManager.status(id);
|
|
381
|
+
res.setHeader("Cache-Control", "no-store");
|
|
382
|
+
if (!job)
|
|
383
|
+
return res.status(404).json({ error: "Hub upgrade job not found" });
|
|
384
|
+
res.json({ ok: true, job });
|
|
385
|
+
});
|
|
295
386
|
app.post("/api/pair/start", (req, res) => {
|
|
296
387
|
if (!pairLimit.allow(ip(req)))
|
|
297
388
|
fail(429, "Too many attempts");
|
|
@@ -360,7 +451,12 @@ export async function createDeviceHub(options) {
|
|
|
360
451
|
fail(404, "Device revoked");
|
|
361
452
|
}
|
|
362
453
|
pairs.delete(key);
|
|
363
|
-
res.json({
|
|
454
|
+
res.json({
|
|
455
|
+
deviceId: pair.deviceId,
|
|
456
|
+
accountId: pair.accountId,
|
|
457
|
+
credential: pair.credential,
|
|
458
|
+
uiCredential: pair.uiCredential,
|
|
459
|
+
});
|
|
364
460
|
});
|
|
365
461
|
app.get("/api/info", (_req, res) => {
|
|
366
462
|
res.json({
|
|
@@ -377,7 +473,7 @@ export async function createDeviceHub(options) {
|
|
|
377
473
|
app.post("/api/devices/:id/revoke", async (req, res) => {
|
|
378
474
|
const owner = account(req);
|
|
379
475
|
const id = String(req.params.id);
|
|
380
|
-
await store.transact((draft) => {
|
|
476
|
+
const settlement = await store.transact((draft) => {
|
|
381
477
|
if (!draft.devices.some((device) => device.id === id && device.accountId === owner.id))
|
|
382
478
|
fail(404, "Device missing");
|
|
383
479
|
draft.devices = draft.devices.filter((device) => device.id !== id);
|
|
@@ -388,20 +484,26 @@ export async function createDeviceHub(options) {
|
|
|
388
484
|
if (room.primaryBotId && removedBots.has(room.primaryBotId))
|
|
389
485
|
delete room.primaryBotId;
|
|
390
486
|
}
|
|
391
|
-
// A revoked device can no longer continue its conversations: close them now so the next turn
|
|
392
|
-
// reports a reason instead of a late 409 against a Bot that no longer exists.
|
|
393
487
|
for (const conversation of draft.conversations)
|
|
394
488
|
if (!conversation.closed && removedBots.has(conversation.botId)) {
|
|
395
489
|
conversation.closed = true;
|
|
396
490
|
conversation.closedReason = "device_revoked";
|
|
397
491
|
conversation.updatedAt = Date.now();
|
|
398
492
|
}
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
493
|
+
const notices = [];
|
|
494
|
+
for (const task of [...draft.tasks]) {
|
|
495
|
+
if (task.deviceId !== id || (isTerminal(task.status) && !task.recoveryUntil))
|
|
496
|
+
continue;
|
|
497
|
+
task.cancelRequested = true;
|
|
498
|
+
const notice = recordTaskOutcome(draft, task, { status: "interrupted", report: "Device revoked; task interrupted." }, settlementContext());
|
|
499
|
+
if (notice)
|
|
500
|
+
notices.push(notice);
|
|
501
|
+
}
|
|
502
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
503
|
+
result.settledWakes.unshift(...notices);
|
|
504
|
+
return result;
|
|
404
505
|
});
|
|
506
|
+
await publishSettlementEffects(settlement);
|
|
405
507
|
for (const [key, pair] of pairs)
|
|
406
508
|
if (pair.deviceId === id)
|
|
407
509
|
pairs.delete(key);
|
|
@@ -469,6 +571,20 @@ export async function createDeviceHub(options) {
|
|
|
469
571
|
const bots = await store.transact((draft) => {
|
|
470
572
|
if (!draft.devices.some((d) => d.id === device.id && d.accountId === owner.id))
|
|
471
573
|
fail(401, "Device revoked");
|
|
574
|
+
const changedBotIds = new Set(draft.bots
|
|
575
|
+
.filter((bot) => {
|
|
576
|
+
if (bot.accountId !== owner.id || bot.deviceId !== device.id)
|
|
577
|
+
return false;
|
|
578
|
+
const next = incoming.find((row) => row.id === bot.id);
|
|
579
|
+
return (!next ||
|
|
580
|
+
next.revision !== bot.revision ||
|
|
581
|
+
next.enabled !== bot.enabled ||
|
|
582
|
+
(next.tools !== undefined && JSON.stringify(next.tools) !== JSON.stringify(bot.tools)));
|
|
583
|
+
})
|
|
584
|
+
.map((bot) => bot.id));
|
|
585
|
+
for (const room of draft.rooms)
|
|
586
|
+
if (room.accountId === owner.id && room.botIds.some((id) => changedBotIds.has(id)))
|
|
587
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
472
588
|
if (draft.tasks.some((task) => task.deviceId === device.id &&
|
|
473
589
|
!isTerminal(task.status) &&
|
|
474
590
|
!incoming.some((bot) => bot.id === task.botId && bot.enabled && bot.revision === task.botRevision)))
|
|
@@ -506,7 +622,7 @@ export async function createDeviceHub(options) {
|
|
|
506
622
|
}
|
|
507
623
|
return draft.bots.filter((b) => b.deviceId === device.id);
|
|
508
624
|
});
|
|
509
|
-
res.json({ bots });
|
|
625
|
+
res.json({ bots, accountId: owner.id });
|
|
510
626
|
});
|
|
511
627
|
app.get("/api/rooms", (req, res) => res.json({
|
|
512
628
|
rooms: store
|
|
@@ -765,6 +881,7 @@ export async function createDeviceHub(options) {
|
|
|
765
881
|
updatedBy,
|
|
766
882
|
...(title?.trim() ? { title: title.trim() } : {}),
|
|
767
883
|
content,
|
|
884
|
+
...(req.body?.sections && typeof req.body.sections === "object" ? { sections: req.body.sections } : {}),
|
|
768
885
|
};
|
|
769
886
|
room.blackboard = nextBlackboard;
|
|
770
887
|
return nextBlackboard;
|
|
@@ -774,7 +891,117 @@ export async function createDeviceHub(options) {
|
|
|
774
891
|
};
|
|
775
892
|
app.put("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
776
893
|
app.post("/api/rooms/:id/blackboard", handleBlackboardUpdate);
|
|
777
|
-
|
|
894
|
+
const handleBlackboardSectionUpdate = async (req, res) => {
|
|
895
|
+
const owner = account(req);
|
|
896
|
+
const roomId = String(req.params.id);
|
|
897
|
+
const rawSectionId = String(req.params.sectionId || "").trim();
|
|
898
|
+
if (!rawSectionId || rawSectionId.length > 100 || /[\x00-\x1F\x7F]/.test(rawSectionId)) {
|
|
899
|
+
fail(400, "Invalid sectionId");
|
|
900
|
+
}
|
|
901
|
+
const sectionId = rawSectionId;
|
|
902
|
+
const { content, expectedVersion, title } = req.body ?? {};
|
|
903
|
+
const settings = currentSettings();
|
|
904
|
+
if (typeof content !== "string" || !content.trim())
|
|
905
|
+
fail(400, "Content must be a nonempty string");
|
|
906
|
+
if (Buffer.byteLength(content, "utf8") > settings.blackboardMaxBytes)
|
|
907
|
+
fail(400, `Content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
908
|
+
if (/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(content))
|
|
909
|
+
fail(400, "Content must not contain control characters");
|
|
910
|
+
if (expectedVersion !== undefined) {
|
|
911
|
+
if (typeof expectedVersion !== "number" || !Number.isSafeInteger(expectedVersion) || expectedVersion < 0) {
|
|
912
|
+
fail(400, "expectedVersion must be a non-negative safe integer");
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
if (title !== undefined) {
|
|
916
|
+
if (typeof title !== "string" || title.length > 200 || /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/.test(title)) {
|
|
917
|
+
fail(400, "Invalid title");
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
let updatedBy;
|
|
921
|
+
const stateBefore = store.snapshot();
|
|
922
|
+
if (agents.has(req)) {
|
|
923
|
+
const agent = agents.get(req);
|
|
924
|
+
const sourceBotId = (req.body?.sourceBotId ?? req.query?.sourceBotId);
|
|
925
|
+
if (!sourceBotId)
|
|
926
|
+
fail(403, "Source Bot required");
|
|
927
|
+
const source = stateBefore.bots.find((b) => b.id === sourceBotId && b.deviceId === agent.device.id && b.accountId === agent.account.id && b.enabled);
|
|
928
|
+
if (!source)
|
|
929
|
+
fail(403, "Source Bot access denied");
|
|
930
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
931
|
+
if (!preRoom)
|
|
932
|
+
fail(404, "Room missing");
|
|
933
|
+
if (!preRoom.botIds.includes(source.id))
|
|
934
|
+
fail(403, "Source Bot is not a room member");
|
|
935
|
+
updatedBy = { type: "bot", id: source.id, name: source.name };
|
|
936
|
+
}
|
|
937
|
+
else {
|
|
938
|
+
const preRoom = stateBefore.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
939
|
+
if (!preRoom)
|
|
940
|
+
fail(404, "Room missing");
|
|
941
|
+
updatedBy = { type: "human", id: owner.id, name: owner.username };
|
|
942
|
+
}
|
|
943
|
+
const updatedBlackboard = await store.transact((draft) => {
|
|
944
|
+
const room = draft.rooms.find((r) => r.id === roomId && r.accountId === owner.id);
|
|
945
|
+
if (!room)
|
|
946
|
+
fail(404, "Room missing");
|
|
947
|
+
if (agents.has(req) && !room.botIds.includes(updatedBy.id))
|
|
948
|
+
fail(403, "Source Bot is not a room member");
|
|
949
|
+
const current = room.blackboard;
|
|
950
|
+
if (expectedVersion !== undefined) {
|
|
951
|
+
if (current) {
|
|
952
|
+
if (current.version !== expectedVersion)
|
|
953
|
+
fail(409, "Version conflict");
|
|
954
|
+
}
|
|
955
|
+
else {
|
|
956
|
+
if (expectedVersion !== 0)
|
|
957
|
+
fail(409, "Version conflict");
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
const sections = current?.sections
|
|
961
|
+
? { ...current.sections }
|
|
962
|
+
: {};
|
|
963
|
+
if (Object.keys(sections).length === 0 && current?.content?.trim()) {
|
|
964
|
+
sections["main"] = {
|
|
965
|
+
id: "main",
|
|
966
|
+
title: current.title || "Main",
|
|
967
|
+
content: current.content,
|
|
968
|
+
updatedAt: current.updatedAt,
|
|
969
|
+
updatedBy: current.updatedBy,
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
const prevSection = sections[sectionId];
|
|
973
|
+
const sectionTitle = title?.trim() || prevSection?.title || sectionId;
|
|
974
|
+
const sectionUpdatedAt = Date.now();
|
|
975
|
+
sections[sectionId] = {
|
|
976
|
+
id: sectionId,
|
|
977
|
+
title: sectionTitle,
|
|
978
|
+
content,
|
|
979
|
+
updatedAt: sectionUpdatedAt,
|
|
980
|
+
updatedBy,
|
|
981
|
+
};
|
|
982
|
+
const compiledContent = Object.values(sections)
|
|
983
|
+
.map((sec) => `## ${sec.title}\n\n${sec.content}`)
|
|
984
|
+
.join("\n\n");
|
|
985
|
+
if (Buffer.byteLength(compiledContent, "utf8") > settings.blackboardMaxBytes) {
|
|
986
|
+
fail(400, `Aggregated blackboard content exceeds ${settings.blackboardMaxBytes} bytes limit`);
|
|
987
|
+
}
|
|
988
|
+
const nextVersion = current ? current.version + 1 : 1;
|
|
989
|
+
const nextBlackboard = {
|
|
990
|
+
version: nextVersion,
|
|
991
|
+
updatedAt: sectionUpdatedAt,
|
|
992
|
+
updatedBy,
|
|
993
|
+
...(current?.title ? { title: current.title } : {}),
|
|
994
|
+
content: compiledContent,
|
|
995
|
+
sections,
|
|
996
|
+
};
|
|
997
|
+
room.blackboard = nextBlackboard;
|
|
998
|
+
return nextBlackboard;
|
|
999
|
+
});
|
|
1000
|
+
groupEvents.invalidate(roomId);
|
|
1001
|
+
res.json({ ok: true, blackboard: updatedBlackboard });
|
|
1002
|
+
};
|
|
1003
|
+
app.put("/api/rooms/:id/blackboard/sections/:sectionId", handleBlackboardSectionUpdate);
|
|
1004
|
+
app.post("/api/rooms/:id/blackboard/sections/:sectionId", handleBlackboardSectionUpdate);
|
|
778
1005
|
app.get("/api/rooms/:id/webhooks", (req, res) => {
|
|
779
1006
|
const owner = account(req);
|
|
780
1007
|
if (agents.has(req))
|
|
@@ -1009,7 +1236,7 @@ export async function createDeviceHub(options) {
|
|
|
1009
1236
|
if (settings.allowBotMentions) {
|
|
1010
1237
|
targets.push(...groupMentionTargets(content, activeRoom, draft.bots, settings.botMentionBudgetPerTurn));
|
|
1011
1238
|
}
|
|
1012
|
-
if (!targets.length && activeRoom.primaryBotId) {
|
|
1239
|
+
if (!targets.length && !activeRoom.router?.enabled && activeRoom.primaryBotId) {
|
|
1013
1240
|
if (activeRoom.botIds.includes(activeRoom.primaryBotId) &&
|
|
1014
1241
|
validBot(draft, activeRoom.primaryBotId, activeRoom.accountId)) {
|
|
1015
1242
|
targets.push(activeRoom.primaryBotId);
|
|
@@ -1086,6 +1313,14 @@ export async function createDeviceHub(options) {
|
|
|
1086
1313
|
: undefined;
|
|
1087
1314
|
draft.tasks.push(...tasks);
|
|
1088
1315
|
draft.messages.push(message);
|
|
1316
|
+
if (allowTrigger && !targets.length)
|
|
1317
|
+
queueRouterJob(draft, {
|
|
1318
|
+
accountId: activeRoom.accountId,
|
|
1319
|
+
roomId: activeRoom.id,
|
|
1320
|
+
eventKey: `webhook:${message.id}`,
|
|
1321
|
+
trigger: { type: "webhook_message", messageId: message.id },
|
|
1322
|
+
text: content,
|
|
1323
|
+
}, now);
|
|
1089
1324
|
draft.receipts.push({
|
|
1090
1325
|
accountId: activeRoom.accountId,
|
|
1091
1326
|
roomId: activeRoom.id,
|
|
@@ -1101,6 +1336,8 @@ export async function createDeviceHub(options) {
|
|
|
1101
1336
|
const oldTasks = new Set(draft.tasks
|
|
1102
1337
|
.filter((t) => t.roomId === activeRoom.id &&
|
|
1103
1338
|
isTerminal(t.status) &&
|
|
1339
|
+
!taskHasImmutableEvidence(t) &&
|
|
1340
|
+
!draft.workItems.some((w) => w.taskIds.includes(t.id)) &&
|
|
1104
1341
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
1105
1342
|
.slice(0, -getHistoryLimit())
|
|
1106
1343
|
.map((t) => t.id));
|
|
@@ -1121,7 +1358,6 @@ export async function createDeviceHub(options) {
|
|
|
1121
1358
|
tasks: result.tasks.map(publicTask),
|
|
1122
1359
|
});
|
|
1123
1360
|
});
|
|
1124
|
-
// === Task Details, Journal, and Reports ===
|
|
1125
1361
|
app.get("/api/rooms/:id/tasks/:taskId", (req, res) => {
|
|
1126
1362
|
const acc = account(req);
|
|
1127
1363
|
const state = store.snapshot();
|
|
@@ -1137,9 +1373,9 @@ export async function createDeviceHub(options) {
|
|
|
1137
1373
|
const interactions = state.interactions
|
|
1138
1374
|
? state.interactions.filter((i) => i.taskId === task.id)
|
|
1139
1375
|
: [];
|
|
1140
|
-
const deliveries = state.deliveries
|
|
1141
|
-
|
|
1142
|
-
|
|
1376
|
+
const deliveries = state.deliveries.filter((d) => d.accountId === acc.id &&
|
|
1377
|
+
d.roomId === room.id &&
|
|
1378
|
+
(d.taskId === task.id || d.artifactRef?.artifactTaskId === task.id));
|
|
1143
1379
|
res.json({
|
|
1144
1380
|
task: {
|
|
1145
1381
|
id: task.id,
|
|
@@ -1158,6 +1394,12 @@ export async function createDeviceHub(options) {
|
|
|
1158
1394
|
conversationId: task.conversationId,
|
|
1159
1395
|
report: task.report,
|
|
1160
1396
|
...(task.attenuatedTools ? { attenuatedTools: task.attenuatedTools } : {}),
|
|
1397
|
+
...(task.executionMode ? { executionMode: task.executionMode } : {}),
|
|
1398
|
+
...(task.contract ? { contract: task.contract } : {}),
|
|
1399
|
+
...(task.contextManifest ? { contextManifest: task.contextManifest } : {}),
|
|
1400
|
+
...(task.artifact ? { artifact: task.artifact } : {}),
|
|
1401
|
+
...(task.executionCompleted !== undefined ? { executionCompleted: task.executionCompleted } : {}),
|
|
1402
|
+
...(task.artifactProduced !== undefined ? { artifactProduced: task.artifactProduced } : {}),
|
|
1161
1403
|
},
|
|
1162
1404
|
reportMeta,
|
|
1163
1405
|
interactionCount: interactions.length,
|
|
@@ -1172,9 +1414,11 @@ export async function createDeviceHub(options) {
|
|
|
1172
1414
|
deliveries: deliveries.map((d) => ({
|
|
1173
1415
|
id: d.id,
|
|
1174
1416
|
commit: d.commit,
|
|
1417
|
+
artifactRef: d.artifactRef,
|
|
1175
1418
|
branch: d.branch,
|
|
1176
1419
|
summary: d.summary,
|
|
1177
|
-
|
|
1420
|
+
reportedCheckCount: d.checks.length,
|
|
1421
|
+
passed: d.checks.length > 0 && d.checks.every((c) => c.status === "passed"),
|
|
1178
1422
|
})),
|
|
1179
1423
|
});
|
|
1180
1424
|
});
|
|
@@ -1313,11 +1557,14 @@ export async function createDeviceHub(options) {
|
|
|
1313
1557
|
taskIds: [task.id],
|
|
1314
1558
|
});
|
|
1315
1559
|
});
|
|
1316
|
-
|
|
1317
|
-
if (
|
|
1318
|
-
|
|
1560
|
+
let steered = false;
|
|
1561
|
+
if (options.relay?.steerTask) {
|
|
1562
|
+
const relayResult = await options.relay
|
|
1563
|
+
.steerTask(task.deviceId, task.id, task.attemptId, instruction)
|
|
1564
|
+
.catch(() => ({ steered: false }));
|
|
1565
|
+
steered = relayResult.steered;
|
|
1319
1566
|
}
|
|
1320
|
-
res.json({ success: true, taskId: task.id, steered
|
|
1567
|
+
res.json({ success: true, taskId: task.id, steered });
|
|
1321
1568
|
});
|
|
1322
1569
|
app.get("/api/rooms/:id/tasks/:taskId/journal", async (req, res) => {
|
|
1323
1570
|
const acc = account(req);
|
|
@@ -1332,9 +1579,6 @@ export async function createDeviceHub(options) {
|
|
|
1332
1579
|
const limit = typeof req.query.limit === "string" ? parseInt(req.query.limit, 10) : undefined;
|
|
1333
1580
|
const direction = req.query.direction === "backward" ? "backward" : "forward";
|
|
1334
1581
|
const page = await taskJournalManager.getPage(task.id, acc.id, room.id, { cursor, limit, direction });
|
|
1335
|
-
// The task exists but never wrote a journal segment (queued, failed before the first progress
|
|
1336
|
-
// event, or created before the journal existed). An empty audit trail is a valid state, not a
|
|
1337
|
-
// missing resource: 404 here made every such task render as a broken panel in the UI.
|
|
1338
1582
|
if (!page)
|
|
1339
1583
|
return res.json({
|
|
1340
1584
|
taskId: task.id,
|
|
@@ -1463,6 +1707,8 @@ export async function createDeviceHub(options) {
|
|
|
1463
1707
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1464
1708
|
if (!room)
|
|
1465
1709
|
fail(404, "Room missing");
|
|
1710
|
+
if (operation !== "rename")
|
|
1711
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1466
1712
|
if (operation === "rename")
|
|
1467
1713
|
room.name = text(req.body?.name, 128);
|
|
1468
1714
|
if (operation === "members") {
|
|
@@ -1492,8 +1738,23 @@ export async function createDeviceHub(options) {
|
|
|
1492
1738
|
status: 409,
|
|
1493
1739
|
code: "ACTIVE_TASKS",
|
|
1494
1740
|
});
|
|
1495
|
-
if (operation === "delete")
|
|
1741
|
+
if (operation === "delete") {
|
|
1496
1742
|
draft.rooms = draft.rooms.filter((r) => r.id !== room.id);
|
|
1743
|
+
draft.workItems = draft.workItems.filter((w) => w.roomId !== room.id);
|
|
1744
|
+
draft.workItemEvents = draft.workItemEvents.filter((w) => w.roomId !== room.id);
|
|
1745
|
+
draft.workItemOutbox = draft.workItemOutbox.filter((w) => w.roomId !== room.id);
|
|
1746
|
+
draft.routerJobs = draft.routerJobs.filter((j) => j.roomId !== room.id);
|
|
1747
|
+
}
|
|
1748
|
+
else {
|
|
1749
|
+
room.routerRevision = (room.routerRevision ?? 0) + 1;
|
|
1750
|
+
for (const job of draft.routerJobs.filter((j) => j.roomId === room.id && (j.status === "queued" || j.status === "running"))) {
|
|
1751
|
+
job.status = "failed";
|
|
1752
|
+
job.error = "Group history cleared";
|
|
1753
|
+
job.updatedAt = Date.now();
|
|
1754
|
+
delete job.leaseToken;
|
|
1755
|
+
delete job.leaseExpiresAt;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1497
1758
|
draft.messages = draft.messages.filter((m) => m.roomId !== room.id);
|
|
1498
1759
|
draft.tasks = draft.tasks.filter((t) => t.roomId !== room.id);
|
|
1499
1760
|
draft.receipts = draft.receipts.filter((r) => r.roomId !== room.id);
|
|
@@ -1532,11 +1793,14 @@ export async function createDeviceHub(options) {
|
|
|
1532
1793
|
const conversation = snapshot.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1533
1794
|
if (!conversation)
|
|
1534
1795
|
fail(404, "Conversation missing");
|
|
1535
|
-
res.json({
|
|
1796
|
+
res.json({
|
|
1797
|
+
integrations: listIntegrations(snapshot, req.params.conversationId),
|
|
1798
|
+
canResumePublication: !agents.has(req) && conversation.accountId === owner.id,
|
|
1799
|
+
});
|
|
1536
1800
|
});
|
|
1537
1801
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations", async (req, res) => {
|
|
1538
1802
|
const owner = account(req);
|
|
1539
|
-
const actor = { accountId: owner.id };
|
|
1803
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1540
1804
|
if (!options.relay?.callDevice)
|
|
1541
1805
|
fail(503, "Device relay unavailable");
|
|
1542
1806
|
const driver = {
|
|
@@ -1547,7 +1811,7 @@ export async function createDeviceHub(options) {
|
|
|
1547
1811
|
});
|
|
1548
1812
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/verify", async (req, res) => {
|
|
1549
1813
|
const owner = account(req);
|
|
1550
|
-
const actor = { accountId: owner.id };
|
|
1814
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1551
1815
|
if (!options.relay?.callDevice)
|
|
1552
1816
|
fail(503, "Device relay unavailable");
|
|
1553
1817
|
const driver = {
|
|
@@ -1558,7 +1822,7 @@ export async function createDeviceHub(options) {
|
|
|
1558
1822
|
});
|
|
1559
1823
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/apply", async (req, res) => {
|
|
1560
1824
|
const owner = account(req);
|
|
1561
|
-
const actor = { accountId: owner.id };
|
|
1825
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1562
1826
|
if (!options.relay?.callDevice)
|
|
1563
1827
|
fail(503, "Device relay unavailable");
|
|
1564
1828
|
const driver = {
|
|
@@ -1567,9 +1831,42 @@ export async function createDeviceHub(options) {
|
|
|
1567
1831
|
const result = await hubConfirmIntegration(store, req.params.id, req.params.conversationId, req.params.integrationId, actor, req.body ?? {}, driver);
|
|
1568
1832
|
res.json({ integration: result });
|
|
1569
1833
|
});
|
|
1834
|
+
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/reconcile", async (req, res) => {
|
|
1835
|
+
const owner = account(req);
|
|
1836
|
+
const agent = agents.get(req);
|
|
1837
|
+
const actor = {
|
|
1838
|
+
accountId: owner.id,
|
|
1839
|
+
...(agent
|
|
1840
|
+
? { originalBot: { id: req.body?.sourceBotId, accountId: agent.account.id, deviceId: agent.device.id } }
|
|
1841
|
+
: {}),
|
|
1842
|
+
};
|
|
1843
|
+
if (agent && (typeof actor.originalBot?.id !== "string" || !actor.originalBot.id))
|
|
1844
|
+
fail(403, "Source Bot access denied");
|
|
1845
|
+
if (!options.relay?.callDevice)
|
|
1846
|
+
fail(503, "Device relay unavailable");
|
|
1847
|
+
const result = await hubReconcileIntegration(store, req.params.id, req.params.conversationId, actor, req.params.integrationId, {
|
|
1848
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
1849
|
+
});
|
|
1850
|
+
res.json({ integration: result });
|
|
1851
|
+
});
|
|
1852
|
+
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/resume", async (req, res) => {
|
|
1853
|
+
const owner = account(req);
|
|
1854
|
+
if (agents.has(req))
|
|
1855
|
+
fail(403, "Publication resume requires a human account owner");
|
|
1856
|
+
const input = req.body;
|
|
1857
|
+
if (!input ||
|
|
1858
|
+
[input.intentId, input.intentDigest, input.candidateSha].some((value) => typeof value !== "string" || !value))
|
|
1859
|
+
fail(400, "Exact publication intent and candidate required");
|
|
1860
|
+
if (!options.relay?.callDevice)
|
|
1861
|
+
fail(503, "Device relay unavailable");
|
|
1862
|
+
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 }, {
|
|
1863
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
1864
|
+
});
|
|
1865
|
+
res.json({ integration: result });
|
|
1866
|
+
});
|
|
1570
1867
|
app.post("/api/rooms/:id/conversations/:conversationId/integrations/:integrationId/cancel", async (req, res) => {
|
|
1571
1868
|
const owner = account(req);
|
|
1572
|
-
const actor = { accountId: owner.id };
|
|
1869
|
+
const actor = { accountId: owner.id, bot: ownBot(req, store.snapshot()) };
|
|
1573
1870
|
if (!options.relay?.callDevice)
|
|
1574
1871
|
fail(503, "Device relay unavailable");
|
|
1575
1872
|
const driver = {
|
|
@@ -1585,42 +1882,52 @@ export async function createDeviceHub(options) {
|
|
|
1585
1882
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1586
1883
|
if (!conversation || !room)
|
|
1587
1884
|
fail(404, "Conversation missing");
|
|
1885
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1588
1886
|
const source = ownBot(req, draft);
|
|
1589
1887
|
if (source && (!room.botIds.includes(source.id) || conversation.botId !== source.id))
|
|
1590
1888
|
fail(403, "Bot may stop only its own conversation");
|
|
1591
1889
|
conversation.closed = true;
|
|
1592
1890
|
conversation.closedReason = "stopped";
|
|
1593
|
-
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id &&
|
|
1891
|
+
const tasks = draft.tasks.filter((t) => t.conversationId === conversation.id &&
|
|
1892
|
+
(taskPending(t) || (!t.outcomeFingerprint && t.recoveryUntil !== undefined)));
|
|
1893
|
+
const notices = [];
|
|
1594
1894
|
for (const task of tasks) {
|
|
1595
1895
|
task.cancelRequested = true;
|
|
1596
|
-
if ((task.status === "queued" || task.status === "waiting") &&
|
|
1896
|
+
if ((task.status === "queued" || task.status === "waiting") &&
|
|
1897
|
+
!hasTaskLease(task) &&
|
|
1898
|
+
!deliveredTasks.has(task.id)) {
|
|
1597
1899
|
task.stopConfirmed = true;
|
|
1598
|
-
task
|
|
1599
|
-
|
|
1600
|
-
|
|
1900
|
+
const notice = recordTaskOutcome(draft, task, { status: "interrupted", report: "Conversation stopped before delivery." }, settlementContext());
|
|
1901
|
+
if (notice)
|
|
1902
|
+
notices.push(notice);
|
|
1601
1903
|
}
|
|
1602
1904
|
}
|
|
1603
|
-
|
|
1905
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
1906
|
+
settlement.settledWakes.unshift(...notices);
|
|
1907
|
+
return { tasks, settlement };
|
|
1604
1908
|
});
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1909
|
+
await publishSettlementEffects(pending.settlement);
|
|
1910
|
+
for (const task of pending.tasks) {
|
|
1911
|
+
if (task.stopConfirmed)
|
|
1608
1912
|
continue;
|
|
1609
|
-
}
|
|
1610
1913
|
const confirmed = await options.relay
|
|
1611
1914
|
?.cancelTask?.(task.deviceId, task.id, task.attemptId)
|
|
1612
1915
|
.catch(() => ({ stopped: false }));
|
|
1613
1916
|
if (!confirmed?.stopped)
|
|
1614
1917
|
continue;
|
|
1615
|
-
await store.transact((draft) => {
|
|
1918
|
+
const settlement = await store.transact((draft) => {
|
|
1616
1919
|
const current = draft.tasks.find((t) => t.id === task.id && t.attemptId === task.attemptId);
|
|
1617
1920
|
if (!current)
|
|
1618
1921
|
return;
|
|
1619
1922
|
current.stopConfirmed = true;
|
|
1620
|
-
current
|
|
1621
|
-
|
|
1622
|
-
|
|
1923
|
+
const notice = recordTaskOutcome(draft, current, { status: "interrupted", report: "Conversation stopped." }, settlementContext());
|
|
1924
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
1925
|
+
if (notice)
|
|
1926
|
+
result.settledWakes.unshift(notice);
|
|
1927
|
+
return result;
|
|
1623
1928
|
});
|
|
1929
|
+
if (settlement)
|
|
1930
|
+
await publishSettlementEffects(settlement);
|
|
1624
1931
|
await releaseLocksAndWake(String(req.params.id), task.id);
|
|
1625
1932
|
}
|
|
1626
1933
|
const remaining = store
|
|
@@ -1637,12 +1944,12 @@ export async function createDeviceHub(options) {
|
|
|
1637
1944
|
const conversation = draft.conversations.find((c) => c.id === req.params.conversationId && c.roomId === req.params.id && c.accountId === owner.id);
|
|
1638
1945
|
if (!room || !conversation)
|
|
1639
1946
|
fail(404, "Conversation missing");
|
|
1947
|
+
assertNoApplyingIntegration(draft, owner.id, room.id);
|
|
1640
1948
|
if (draft.tasks.some((t) => t.conversationId === conversation.id && taskPending(t)))
|
|
1641
1949
|
throw Object.assign(new Error("Stop the conversation before deleting it"), {
|
|
1642
1950
|
status: 409,
|
|
1643
1951
|
code: "ACTIVE_TASKS",
|
|
1644
1952
|
});
|
|
1645
|
-
// Delivery/review records are the audit trail; deleting them is a separate, explicit decision.
|
|
1646
1953
|
if (conversationHasAuditRecords(draft, conversation.id))
|
|
1647
1954
|
fail(409, "Conversation has delivery history; audit records are retained");
|
|
1648
1955
|
dropConversationRecords(draft, conversation.id);
|
|
@@ -1743,10 +2050,24 @@ export async function createDeviceHub(options) {
|
|
|
1743
2050
|
const conversation = state.conversations.find((entry) => entry.id === req.params.conversationId && entry.roomId === room.id && entry.accountId === owner.id);
|
|
1744
2051
|
if (!conversation)
|
|
1745
2052
|
fail(404, "Conversation missing");
|
|
1746
|
-
const
|
|
2053
|
+
const evidenceKind = req.query.evidenceKind ?? "report";
|
|
2054
|
+
if (!["report", "artifact", "acceptance"].includes(evidenceKind))
|
|
2055
|
+
fail(400, "Invalid evidenceKind");
|
|
2056
|
+
const allowedQueries = [
|
|
2057
|
+
"sourceBotId",
|
|
2058
|
+
"taskId",
|
|
2059
|
+
"deliveryId",
|
|
2060
|
+
"offset",
|
|
2061
|
+
"limit",
|
|
2062
|
+
"expectedDigest",
|
|
2063
|
+
"digest",
|
|
2064
|
+
"evidenceKind",
|
|
2065
|
+
];
|
|
1747
2066
|
for (const q of Object.keys(req.query)) {
|
|
1748
2067
|
if (!allowedQueries.includes(q))
|
|
1749
2068
|
fail(400, `Unknown query parameter: ${q}`);
|
|
2069
|
+
if (typeof req.query[q] !== "string")
|
|
2070
|
+
fail(400, `Invalid query parameter: ${q}`);
|
|
1750
2071
|
}
|
|
1751
2072
|
let offset = 0;
|
|
1752
2073
|
if (req.query.offset !== undefined) {
|
|
@@ -1757,7 +2078,7 @@ export async function createDeviceHub(options) {
|
|
|
1757
2078
|
let limit = 8192;
|
|
1758
2079
|
if (req.query.limit !== undefined) {
|
|
1759
2080
|
limit = Number(req.query.limit);
|
|
1760
|
-
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 65536)
|
|
2081
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > (evidenceKind !== "report" ? 24 * 1024 : 65536))
|
|
1761
2082
|
fail(400, "Invalid limit");
|
|
1762
2083
|
}
|
|
1763
2084
|
const expectedDigest = typeof req.query.expectedDigest === "string"
|
|
@@ -1765,12 +2086,97 @@ export async function createDeviceHub(options) {
|
|
|
1765
2086
|
: typeof req.query.digest === "string"
|
|
1766
2087
|
? req.query.digest
|
|
1767
2088
|
: undefined;
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
2089
|
+
if (req.query.expectedDigest !== undefined &&
|
|
2090
|
+
req.query.digest !== undefined &&
|
|
2091
|
+
req.query.expectedDigest !== req.query.digest)
|
|
2092
|
+
fail(409, "Conflicting evidence digest selectors");
|
|
2093
|
+
const deliveryId = req.query.deliveryId === undefined ? undefined : text(req.query.deliveryId, 128).trim();
|
|
2094
|
+
if (deliveryId === "")
|
|
2095
|
+
fail(400, "Invalid deliveryId");
|
|
1771
2096
|
const targetDelivery = deliveryId
|
|
1772
|
-
? state.deliveries.find((d) => d.id === deliveryId &&
|
|
2097
|
+
? state.deliveries.find((d) => d.id === deliveryId &&
|
|
2098
|
+
d.conversationId === conversation.id &&
|
|
2099
|
+
d.roomId === room.id &&
|
|
2100
|
+
d.accountId === owner.id)
|
|
1773
2101
|
: undefined;
|
|
2102
|
+
if (deliveryId && !targetDelivery)
|
|
2103
|
+
fail(404, "Delivery missing");
|
|
2104
|
+
const boundArtifactTaskId = evidenceKind !== "report" ? targetDelivery?.artifactRef?.artifactTaskId : undefined;
|
|
2105
|
+
if (evidenceKind !== "report" && targetDelivery && !boundArtifactTaskId)
|
|
2106
|
+
fail(409, "Delivery has no artifact subject");
|
|
2107
|
+
if (boundArtifactTaskId && req.query.taskId !== undefined && req.query.taskId !== boundArtifactTaskId)
|
|
2108
|
+
fail(409, "Task conflicts with delivery artifact subject");
|
|
2109
|
+
const taskId = boundArtifactTaskId ?? (typeof req.query.taskId === "string" ? req.query.taskId : conversation.latestTaskId);
|
|
2110
|
+
const targetTask = state.tasks.find((t) => t.id === taskId && t.conversationId === conversation.id && t.roomId === room.id && t.accountId === owner.id);
|
|
2111
|
+
if (evidenceKind !== "report" &&
|
|
2112
|
+
targetDelivery?.artifactRef &&
|
|
2113
|
+
(!targetTask ||
|
|
2114
|
+
!artifactRefsMatch(targetDelivery.artifactRef, deriveArtifactSubject(state, targetTask, { allowSuperseded: true }))))
|
|
2115
|
+
fail(409, "Delivery artifact subject changed");
|
|
2116
|
+
if (evidenceKind === "acceptance") {
|
|
2117
|
+
if (!targetTask?.contract)
|
|
2118
|
+
fail(404, "Task acceptance contract missing");
|
|
2119
|
+
const sealed = validateWorkContract(targetTask.contract);
|
|
2120
|
+
if (!sealed.valid)
|
|
2121
|
+
fail(409, "Invalid sealed acceptance contract");
|
|
2122
|
+
const contract = sealed.contract;
|
|
2123
|
+
if (expectedDigest !== undefined && expectedDigest !== contract.digest)
|
|
2124
|
+
fail(409, "Acceptance contract version digest mismatch");
|
|
2125
|
+
const bytes = Buffer.from(canonicalizeJson(contract.acceptanceCriteria ?? []), "utf8");
|
|
2126
|
+
if (offset > bytes.length)
|
|
2127
|
+
fail(400, "Invalid offset");
|
|
2128
|
+
const end = Math.min(offset + limit, bytes.length);
|
|
2129
|
+
res.json({
|
|
2130
|
+
conversationId: conversation.id,
|
|
2131
|
+
taskId,
|
|
2132
|
+
...(deliveryId ? { deliveryId } : {}),
|
|
2133
|
+
acceptance: {
|
|
2134
|
+
contractId: contract.id,
|
|
2135
|
+
contractRevision: contract.revision,
|
|
2136
|
+
contractDigest: contract.digest,
|
|
2137
|
+
criteriaDigest: createHash("sha256").update(bytes).digest("hex"),
|
|
2138
|
+
criteriaCount: (contract.acceptanceCriteria ?? []).length,
|
|
2139
|
+
},
|
|
2140
|
+
content: {
|
|
2141
|
+
encoding: "base64",
|
|
2142
|
+
data: bytes.subarray(offset, end).toString("base64"),
|
|
2143
|
+
offset,
|
|
2144
|
+
limit,
|
|
2145
|
+
totalBytes: bytes.length,
|
|
2146
|
+
nextOffset: end < bytes.length ? end : null,
|
|
2147
|
+
truncated: offset > 0 || end < bytes.length,
|
|
2148
|
+
},
|
|
2149
|
+
});
|
|
2150
|
+
return;
|
|
2151
|
+
}
|
|
2152
|
+
if (evidenceKind === "artifact") {
|
|
2153
|
+
if (!targetTask?.artifact)
|
|
2154
|
+
fail(404, "Task artifact missing");
|
|
2155
|
+
if (expectedDigest !== undefined && expectedDigest !== targetTask.artifact.digest)
|
|
2156
|
+
fail(409, "Artifact version digest mismatch");
|
|
2157
|
+
const { patchBase64, ...artifact } = targetTask.artifact;
|
|
2158
|
+
if (typeof patchBase64 !== "string")
|
|
2159
|
+
fail(404, "Artifact patch missing");
|
|
2160
|
+
const patch = Buffer.from(patchBase64, "base64");
|
|
2161
|
+
if (offset > patch.length)
|
|
2162
|
+
fail(400, "Invalid offset");
|
|
2163
|
+
const end = Math.min(offset + limit, patch.length);
|
|
2164
|
+
res.json({
|
|
2165
|
+
conversationId: conversation.id,
|
|
2166
|
+
taskId,
|
|
2167
|
+
artifact,
|
|
2168
|
+
content: {
|
|
2169
|
+
encoding: "base64",
|
|
2170
|
+
data: patch.subarray(offset, end).toString("base64"),
|
|
2171
|
+
offset,
|
|
2172
|
+
limit,
|
|
2173
|
+
totalBytes: patch.length,
|
|
2174
|
+
nextOffset: end < patch.length ? end : null,
|
|
2175
|
+
truncated: offset > 0 || end < patch.length,
|
|
2176
|
+
},
|
|
2177
|
+
});
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
1774
2180
|
let evidence;
|
|
1775
2181
|
if (targetTask?.attemptId) {
|
|
1776
2182
|
const reportResult = taskReportStore.getReport(targetTask.id, targetTask.attemptId, owner.id, room.id, {
|
|
@@ -1935,12 +2341,10 @@ export async function createDeviceHub(options) {
|
|
|
1935
2341
|
...deliveryHistory(state, conversation.id),
|
|
1936
2342
|
});
|
|
1937
2343
|
});
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
"/api/rooms/:id/conversations",
|
|
1941
|
-
"/api/rooms/:id/conversations/:conversationId/messages",
|
|
1942
|
-
], async (req, res) => {
|
|
2344
|
+
const routerSources = new WeakMap();
|
|
2345
|
+
const postRoomMessage = async (req, res) => {
|
|
1943
2346
|
const owner = account(req);
|
|
2347
|
+
const routerSource = routerSources.get(req);
|
|
1944
2348
|
const content = text(req.body?.text);
|
|
1945
2349
|
const conversationApi = req.path.includes("/conversations");
|
|
1946
2350
|
const conversationId = req.params.conversationId;
|
|
@@ -1972,7 +2376,37 @@ export async function createDeviceHub(options) {
|
|
|
1972
2376
|
catch (err) {
|
|
1973
2377
|
fail(400, err?.message ?? "Invalid resourceLocks");
|
|
1974
2378
|
}
|
|
1975
|
-
|
|
2379
|
+
if (req.body?.contract !== undefined &&
|
|
2380
|
+
(!req.body.contract || typeof req.body.contract !== "object" || Array.isArray(req.body.contract)))
|
|
2381
|
+
fail(400, "Contract input must be a non-null object");
|
|
2382
|
+
const rawExecutionMode = req.body?.executionMode;
|
|
2383
|
+
const contractExecutionMode = req.body?.contract?.executionMode;
|
|
2384
|
+
if (contractExecutionMode !== undefined && contractExecutionMode !== "chat" && contractExecutionMode !== "code")
|
|
2385
|
+
fail(400, "Invalid contract executionMode: must be 'chat' or 'code'");
|
|
2386
|
+
if (rawExecutionMode !== undefined &&
|
|
2387
|
+
contractExecutionMode !== undefined &&
|
|
2388
|
+
rawExecutionMode !== contractExecutionMode) {
|
|
2389
|
+
fail(400, "executionMode conflicts with contract.executionMode.");
|
|
2390
|
+
}
|
|
2391
|
+
const executionMode = rawExecutionMode ?? contractExecutionMode ?? "chat";
|
|
2392
|
+
if (rawExecutionMode !== undefined && rawExecutionMode !== "chat" && rawExecutionMode !== "code") {
|
|
2393
|
+
fail(400, "Invalid executionMode: must be 'chat' or 'code'");
|
|
2394
|
+
}
|
|
2395
|
+
let contract;
|
|
2396
|
+
if (req.body?.contract !== undefined || executionMode === "code") {
|
|
2397
|
+
try {
|
|
2398
|
+
const stableFallbackId = `contract-${createHash("sha256").update(`${owner.id}:${req.params.id}:${key}`).digest("hex").slice(0, 16)}`;
|
|
2399
|
+
contract = createWorkContract({
|
|
2400
|
+
id: req.body?.contract?.id ?? stableFallbackId,
|
|
2401
|
+
...(req.body?.contract ?? {}),
|
|
2402
|
+
executionMode,
|
|
2403
|
+
}, content);
|
|
2404
|
+
}
|
|
2405
|
+
catch (err) {
|
|
2406
|
+
fail(400, err?.message ?? "Invalid work contract");
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
const fingerprintFields = {
|
|
1976
2410
|
content,
|
|
1977
2411
|
attentionId,
|
|
1978
2412
|
targets,
|
|
@@ -1984,14 +2418,30 @@ export async function createDeviceHub(options) {
|
|
|
1984
2418
|
planOnly,
|
|
1985
2419
|
replyToMessageId,
|
|
1986
2420
|
resourceLocks,
|
|
2421
|
+
executionMode,
|
|
2422
|
+
contractDigest: contract?.digest,
|
|
2423
|
+
contractId: contract?.id,
|
|
2424
|
+
contractRevision: contract?.revision,
|
|
1987
2425
|
sourceDeviceId: (agents.get(req) ?? users.get(req))?.device.id,
|
|
1988
2426
|
sourceBotId: agents.has(req) ? req.body?.sourceBotId : undefined,
|
|
1989
|
-
senderType: agents.has(req) ? "bot" : "human",
|
|
1990
|
-
}
|
|
2427
|
+
senderType: routerSource ? "router" : agents.has(req) ? "bot" : "human",
|
|
2428
|
+
};
|
|
2429
|
+
const fingerprint = hashSecret(JSON.stringify(fingerprintFields));
|
|
2430
|
+
const legacyFingerprint = executionMode === "chat" && !contract
|
|
2431
|
+
? hashSecret(JSON.stringify({ ...fingerprintFields, executionMode: undefined }))
|
|
2432
|
+
: undefined;
|
|
2433
|
+
const matchesFingerprint = (stored) => stored === fingerprint || (legacyFingerprint !== undefined && stored === legacyFingerprint);
|
|
1991
2434
|
const result = await store.transact((draft) => {
|
|
1992
2435
|
const room = draft.rooms.find((r) => r.id === req.params.id && r.accountId === owner.id);
|
|
1993
2436
|
if (!room)
|
|
1994
2437
|
fail(404, "Room missing");
|
|
2438
|
+
if (routerSource)
|
|
2439
|
+
nextRouterAction(draft, {
|
|
2440
|
+
accountId: owner.id,
|
|
2441
|
+
jobId: routerSource.id,
|
|
2442
|
+
deviceId: routerSource.deviceId,
|
|
2443
|
+
leaseToken: routerSource.leaseToken,
|
|
2444
|
+
}, Date.now());
|
|
1995
2445
|
const source = ownBot(req, draft);
|
|
1996
2446
|
const userSource = users.get(req)?.device;
|
|
1997
2447
|
let conversation = conversationId
|
|
@@ -2014,10 +2464,8 @@ export async function createDeviceHub(options) {
|
|
|
2014
2464
|
if (dependsOnTaskId && !draft.tasks.some((m) => m.id === dependsOnTaskId && m.roomId === room.id))
|
|
2015
2465
|
fail(400, "Dependency target task is not in this room");
|
|
2016
2466
|
const depTask = dependsOnTaskId ? draft.tasks.find((t) => t.id === dependsOnTaskId) : undefined;
|
|
2017
|
-
const dependencyActive = Boolean(depTask
|
|
2018
|
-
|
|
2019
|
-
// silently fall back to the primary Bot just because a client did not pre-resolve the mentions.
|
|
2020
|
-
const canParseMentions = (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
|
|
2467
|
+
const dependencyActive = Boolean(depTask);
|
|
2468
|
+
const canParseMentions = !routerSource && (!source || settings.allowBotMentions) && !conversationApi && !conversation && !targets.length;
|
|
2021
2469
|
if (canParseMentions)
|
|
2022
2470
|
targets.push(...groupMentionTargets(content, room, draft.bots, settings.botMentionBudgetPerTurn));
|
|
2023
2471
|
if (targets.some((id) => !room.botIds.includes(id) || !validBot(draft, id, owner.id)))
|
|
@@ -2036,8 +2484,16 @@ export async function createDeviceHub(options) {
|
|
|
2036
2484
|
m.idempotencyKey === key &&
|
|
2037
2485
|
draft.conversations.some((c) => c.id === m.conversationId && c.roomId === room.id && c.accountId === owner.id));
|
|
2038
2486
|
if (prior) {
|
|
2039
|
-
if (prior.fingerprint
|
|
2487
|
+
if (!matchesFingerprint(prior.fingerprint))
|
|
2040
2488
|
fail(409, "Idempotency key reused");
|
|
2489
|
+
const priorTask = draft.tasks.find((t) => t.id === prior.taskId);
|
|
2490
|
+
if (priorTask) {
|
|
2491
|
+
if (priorTask.contract?.digest !== contract?.digest ||
|
|
2492
|
+
priorTask.contract?.revision !== contract?.revision ||
|
|
2493
|
+
(priorTask.executionMode ?? "chat") !== executionMode) {
|
|
2494
|
+
fail(409, "Idempotency key reused with different contract");
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2041
2497
|
return {
|
|
2042
2498
|
message: draft.messages.find((m) => m.taskIds.includes(prior.taskId)),
|
|
2043
2499
|
tasks: draft.tasks.filter((t) => t.id === prior.taskId),
|
|
@@ -2047,16 +2503,43 @@ export async function createDeviceHub(options) {
|
|
|
2047
2503
|
}
|
|
2048
2504
|
const receipt = draft.receipts.find((r) => r.roomId === room.id && r.accountId === owner.id && r.key === key);
|
|
2049
2505
|
if (receipt) {
|
|
2050
|
-
if (receipt.fingerprint
|
|
2506
|
+
if (!matchesFingerprint(receipt.fingerprint))
|
|
2051
2507
|
fail(409, "Idempotency key reused");
|
|
2508
|
+
const priorReceiptTask = draft.tasks.find((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id));
|
|
2509
|
+
if (priorReceiptTask) {
|
|
2510
|
+
if (priorReceiptTask.contract?.digest !== contract?.digest ||
|
|
2511
|
+
priorReceiptTask.contract?.revision !== contract?.revision ||
|
|
2512
|
+
(priorReceiptTask.executionMode ?? "chat") !== executionMode) {
|
|
2513
|
+
fail(409, "Idempotency key reused with different contract");
|
|
2514
|
+
}
|
|
2515
|
+
}
|
|
2052
2516
|
return {
|
|
2053
2517
|
message: draft.messages.find((m) => m.id === receipt.messageId),
|
|
2054
2518
|
tasks: draft.tasks.filter((t) => draft.messages.find((m) => m.id === receipt.messageId)?.taskIds.includes(t.id)),
|
|
2055
2519
|
duplicate: true,
|
|
2056
2520
|
};
|
|
2057
2521
|
}
|
|
2058
|
-
|
|
2059
|
-
|
|
2522
|
+
if (contract) {
|
|
2523
|
+
assertNoApplyingIntegration(draft, owner.id, room.id, undefined, contract.id);
|
|
2524
|
+
const existingTasks = draft.tasks.filter((t) => t.roomId === room.id && t.accountId === owner.id && t.contract?.id === contract.id);
|
|
2525
|
+
if (existingTasks.some((t) => t.contract.revision === contract.revision && t.contract.digest !== contract.digest))
|
|
2526
|
+
fail(409, "Contract id and revision already bind different content");
|
|
2527
|
+
if (existingTasks.some((t) => t.contract.revision < contract.revision && (!isTerminal(t.status) || isRecoveringTask(t, Date.now()))))
|
|
2528
|
+
fail(409, "Cannot advance contract revision while an older revision is active");
|
|
2529
|
+
if (depTask?.contract?.id === contract.id && depTask.contract.revision !== contract.revision)
|
|
2530
|
+
fail(409, "A contract revision cannot inherit acceptance from a different revision");
|
|
2531
|
+
for (const existing of existingTasks) {
|
|
2532
|
+
if (existing.contract && existing.contract.revision > contract.revision) {
|
|
2533
|
+
fail(409, `Contract '${contract.id}' already has a newer revision ${existing.contract.revision} (cannot submit older revision ${contract.revision})`);
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
if (!source &&
|
|
2538
|
+
!routerSource &&
|
|
2539
|
+
!conversationApi &&
|
|
2540
|
+
!targets.length &&
|
|
2541
|
+
!room.router?.enabled &&
|
|
2542
|
+
room.primaryBotId) {
|
|
2060
2543
|
if (!room.botIds.includes(room.primaryBotId) || !validBot(draft, room.primaryBotId, owner.id))
|
|
2061
2544
|
fail(400, "Primary Bot is unavailable");
|
|
2062
2545
|
targets.push(room.primaryBotId);
|
|
@@ -2110,11 +2593,18 @@ export async function createDeviceHub(options) {
|
|
|
2110
2593
|
const parent = parentTaskId ? draft.tasks.find((t) => t.id === parentTaskId) : undefined;
|
|
2111
2594
|
if (source && targets.length && (!parent || parent.botId !== source.id))
|
|
2112
2595
|
fail(400, "Device dispatch requires its own running or terminal parent task");
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2596
|
+
const priorRouterTaskId = routerSource
|
|
2597
|
+
? draft.messages.find((m) => m.routerJobId === routerSource.id && m.taskIds?.length)?.taskIds?.[0]
|
|
2598
|
+
: undefined;
|
|
2599
|
+
const priorRouterTask = priorRouterTaskId ? draft.tasks.find((t) => t.id === priorRouterTaskId) : undefined;
|
|
2600
|
+
const root = parent
|
|
2601
|
+
? draft.tasks.find((t) => t.id === (parent.rootTaskId ?? parent.id))
|
|
2602
|
+
: priorRouterTask
|
|
2603
|
+
? draft.tasks.find((t) => t.id === (priorRouterTask.rootTaskId ?? priorRouterTask.id))
|
|
2604
|
+
: undefined;
|
|
2605
|
+
if ((parent || priorRouterTaskId) && targets.length && !root)
|
|
2116
2606
|
fail(409, "Dispatch root expired");
|
|
2117
|
-
const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : 0;
|
|
2607
|
+
const depth = parent ? (parent.dispatchDepth ?? 0) + 1 : (priorRouterTask?.dispatchDepth ?? 0);
|
|
2118
2608
|
if (planOnly && targets.some((id) => !validBot(draft, id, owner.id)?.tools?.includes("plan_update")))
|
|
2119
2609
|
fail(409, "Planning requires plan_update authorization in each Bot tool allowlist");
|
|
2120
2610
|
if (targets.length && depth > settings.maxDispatchDepth)
|
|
@@ -2123,15 +2613,14 @@ export async function createDeviceHub(options) {
|
|
|
2123
2613
|
fail(409, "Dispatch budget exhausted");
|
|
2124
2614
|
if (root && targets.length)
|
|
2125
2615
|
root.dispatchCount = (root.dispatchCount ?? 0) + targets.length;
|
|
2126
|
-
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length >
|
|
2127
|
-
getHistoryLimit())
|
|
2616
|
+
if (draft.tasks.filter((t) => t.roomId === room.id && taskPending(t)).length + targets.length > getHistoryLimit())
|
|
2128
2617
|
fail(409, "Too many active tasks");
|
|
2129
2618
|
if (!conversation &&
|
|
2130
|
-
draft.conversations.filter((c) => c.roomId === room.id && !c.closed).length + targets.length >
|
|
2131
|
-
getHistoryLimit())
|
|
2619
|
+
draft.conversations.filter((c) => c.roomId === room.id && !c.closed).length + targets.length > getHistoryLimit())
|
|
2132
2620
|
fail(409, "Too many open conversations; stop or delete conversations to free capacity");
|
|
2133
2621
|
const now = Date.now();
|
|
2134
2622
|
const rootId = root?.id ?? randomUUID();
|
|
2623
|
+
const isPipeline = targets.length > 1 && (req.body?.pipeline === true || content.includes("->"));
|
|
2135
2624
|
const tasks = targets.map((botId, index) => {
|
|
2136
2625
|
const targetBot = validBot(draft, botId, owner.id);
|
|
2137
2626
|
let attenuatedTools;
|
|
@@ -2145,6 +2634,7 @@ export async function createDeviceHub(options) {
|
|
|
2145
2634
|
attenuatedTools = attenuated;
|
|
2146
2635
|
}
|
|
2147
2636
|
}
|
|
2637
|
+
const isWaitingInPipeline = isPipeline && index > 0;
|
|
2148
2638
|
return {
|
|
2149
2639
|
id: !root && index === 0 ? rootId : randomUUID(),
|
|
2150
2640
|
rootTaskId: rootId,
|
|
@@ -2158,16 +2648,25 @@ export async function createDeviceHub(options) {
|
|
|
2158
2648
|
botRevision: targetBot.revision,
|
|
2159
2649
|
...(source ? { sourceBotId: source.id } : {}),
|
|
2160
2650
|
text: content,
|
|
2161
|
-
status:
|
|
2162
|
-
|
|
2651
|
+
status: isWaitingInPipeline
|
|
2652
|
+
? "waiting"
|
|
2653
|
+
: dependencyActive
|
|
2654
|
+
? "waiting"
|
|
2655
|
+
: "queued",
|
|
2656
|
+
...(isWaitingInPipeline
|
|
2163
2657
|
? {
|
|
2164
|
-
blockReason: "
|
|
2165
|
-
blockReasonDetail:
|
|
2166
|
-
dependsOnTaskId,
|
|
2658
|
+
blockReason: "dependency",
|
|
2659
|
+
blockReasonDetail: "",
|
|
2167
2660
|
}
|
|
2168
|
-
:
|
|
2169
|
-
? {
|
|
2170
|
-
|
|
2661
|
+
: dependencyActive
|
|
2662
|
+
? {
|
|
2663
|
+
blockReason: "dependency_waiting",
|
|
2664
|
+
blockReasonDetail: `Waiting for dependency task ${dependsOnTaskId}`,
|
|
2665
|
+
dependsOnTaskId,
|
|
2666
|
+
}
|
|
2667
|
+
: dependsOnTaskId
|
|
2668
|
+
? { dependsOnTaskId }
|
|
2669
|
+
: {}),
|
|
2171
2670
|
createdAt: now,
|
|
2172
2671
|
updatedAt: now,
|
|
2173
2672
|
...(resourceLocks && resourceLocks.length ? { resourceLocks } : {}),
|
|
@@ -2175,8 +2674,18 @@ export async function createDeviceHub(options) {
|
|
|
2175
2674
|
...(transfer ? { handoff: transfer } : {}),
|
|
2176
2675
|
...(parentTaskId ? { parentTaskId } : {}),
|
|
2177
2676
|
...(attenuatedTools ? { attenuatedTools } : {}),
|
|
2677
|
+
executionMode,
|
|
2678
|
+
...(contract ? { contract } : {}),
|
|
2178
2679
|
};
|
|
2179
2680
|
});
|
|
2681
|
+
if (isPipeline) {
|
|
2682
|
+
for (let i = 1; i < tasks.length; i++) {
|
|
2683
|
+
const prev = tasks[i - 1];
|
|
2684
|
+
tasks[i].dependsOnTaskId = prev.id;
|
|
2685
|
+
tasks[i].blockReason = "dependency";
|
|
2686
|
+
tasks[i].blockReasonDetail = `Waiting for prior pipeline task ${prev.id} (@${prev.botId})`;
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2180
2689
|
for (const task of tasks) {
|
|
2181
2690
|
task.kind = kind;
|
|
2182
2691
|
task.sourceConversationId = parent?.conversationId;
|
|
@@ -2195,7 +2704,7 @@ export async function createDeviceHub(options) {
|
|
|
2195
2704
|
: undefined;
|
|
2196
2705
|
if (targetConv) {
|
|
2197
2706
|
task.conversationId = targetConv.id;
|
|
2198
|
-
task.resume =
|
|
2707
|
+
task.resume = task.executionMode !== "code";
|
|
2199
2708
|
advanceConversationTask(draft, targetConv, task);
|
|
2200
2709
|
targetConv.rootTaskId = task.rootTaskId;
|
|
2201
2710
|
targetConv.updatedAt = now;
|
|
@@ -2205,19 +2714,25 @@ export async function createDeviceHub(options) {
|
|
|
2205
2714
|
establishConversation(draft, task);
|
|
2206
2715
|
recordConversationTurn(draft, task, key, fingerprint);
|
|
2207
2716
|
}
|
|
2717
|
+
const messageText = isPipeline
|
|
2718
|
+
? `${content}\n\n⛓️ **[流水线编排 / Pipeline Execution]**: ${targets.map((id) => `@${id}`).join(" ➔ ")}`
|
|
2719
|
+
: content;
|
|
2208
2720
|
const message = {
|
|
2209
2721
|
id: randomUUID(),
|
|
2210
2722
|
roomId: room.id,
|
|
2211
2723
|
accountId: owner.id,
|
|
2212
|
-
text:
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
: {
|
|
2216
|
-
|
|
2217
|
-
id:
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2724
|
+
text: messageText,
|
|
2725
|
+
...(routerSource ? { routerJobId: routerSource.id } : {}),
|
|
2726
|
+
sender: routerSource
|
|
2727
|
+
? { type: "router", id: `router:${room.id}`, name: "群组 AI", sourceDeviceId: routerSource.deviceId }
|
|
2728
|
+
: source
|
|
2729
|
+
? { type: "bot", id: source.id, name: source.name, sourceDeviceId: source.deviceId }
|
|
2730
|
+
: {
|
|
2731
|
+
type: "human",
|
|
2732
|
+
id: owner.id,
|
|
2733
|
+
name: userSource ? `${owner.username} · ${userSource.name}` : owner.username,
|
|
2734
|
+
...(userSource ? { sourceDeviceId: userSource.id } : {}),
|
|
2735
|
+
},
|
|
2221
2736
|
createdAt: now,
|
|
2222
2737
|
taskIds: tasks.map((t) => t.id),
|
|
2223
2738
|
targetBotIds: targets,
|
|
@@ -2225,12 +2740,19 @@ export async function createDeviceHub(options) {
|
|
|
2225
2740
|
...(tasks.length === 1 ? { conversationId: tasks[0].conversationId } : {}),
|
|
2226
2741
|
...(tasks.length ? { conversationIds: tasks.map((task) => task.conversationId) } : {}),
|
|
2227
2742
|
};
|
|
2228
|
-
// Freeze shared context before any recipient starts. Parallel answers cannot leak into siblings.
|
|
2229
2743
|
const context = tasks.length
|
|
2230
2744
|
? groupTaskContext(room, draft.bots, draft.messages, settings.groupContextBytes)
|
|
2231
2745
|
: undefined;
|
|
2232
2746
|
draft.tasks.push(...tasks);
|
|
2233
2747
|
draft.messages.push(message);
|
|
2748
|
+
if (!source && !routerSource && !targets.length)
|
|
2749
|
+
queueRouterJob(draft, {
|
|
2750
|
+
accountId: owner.id,
|
|
2751
|
+
roomId: room.id,
|
|
2752
|
+
eventKey: `message:${message.id}`,
|
|
2753
|
+
trigger: { type: "human_message", messageId: message.id },
|
|
2754
|
+
text: content,
|
|
2755
|
+
}, now);
|
|
2234
2756
|
draft.receipts.push({
|
|
2235
2757
|
accountId: owner.id,
|
|
2236
2758
|
roomId: room.id,
|
|
@@ -2241,23 +2763,27 @@ export async function createDeviceHub(options) {
|
|
|
2241
2763
|
});
|
|
2242
2764
|
const oldMessages = draft.messages.filter((m) => m.roomId === room.id).slice(0, -getHistoryLimit());
|
|
2243
2765
|
const removed = new Set(oldMessages.map((m) => m.id));
|
|
2244
|
-
// Retention evicts messages, never the replay guard: a retry must not re-dispatch evicted work.
|
|
2245
2766
|
draft.messages = draft.messages.filter((m) => !removed.has(m.id));
|
|
2246
2767
|
trimRoomReceipts(draft, room.id);
|
|
2247
2768
|
const oldTasks = new Set(draft.tasks
|
|
2248
2769
|
.filter((t) => t.roomId === room.id &&
|
|
2249
2770
|
isTerminal(t.status) &&
|
|
2771
|
+
!taskHasImmutableEvidence(t) &&
|
|
2772
|
+
!draft.workItems.some((w) => w.taskIds.includes(t.id)) &&
|
|
2250
2773
|
!draft.conversations.some((c) => c.rootTaskId === t.id || c.id === t.conversationId))
|
|
2251
2774
|
.slice(0, -getHistoryLimit())
|
|
2252
2775
|
.map((t) => t.id));
|
|
2253
2776
|
draft.tasks = draft.tasks.filter((t) => !oldTasks.has(t.id));
|
|
2254
2777
|
trimConversationHistory(draft, room.id);
|
|
2255
2778
|
trimClosedConversations(draft, room.id);
|
|
2256
|
-
|
|
2779
|
+
const settlement = settleTaskDependencies(draft, settlementContext());
|
|
2780
|
+
return { message, tasks, duplicate: false, context, settlement };
|
|
2257
2781
|
});
|
|
2258
2782
|
if (!result.duplicate) {
|
|
2783
|
+
if (result.settlement)
|
|
2784
|
+
await publishSettlementEffects(result.settlement);
|
|
2259
2785
|
for (const task of result.tasks) {
|
|
2260
|
-
if (task.status
|
|
2786
|
+
if (task.status === "queued")
|
|
2261
2787
|
await deliverTask(task, result.context);
|
|
2262
2788
|
}
|
|
2263
2789
|
if (result.message) {
|
|
@@ -2275,6 +2801,52 @@ export async function createDeviceHub(options) {
|
|
|
2275
2801
|
message: result.message,
|
|
2276
2802
|
tasks: result.tasks.map((task) => publicTask(state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId) ?? task)),
|
|
2277
2803
|
});
|
|
2804
|
+
};
|
|
2805
|
+
app.post([
|
|
2806
|
+
"/api/rooms/:id/messages",
|
|
2807
|
+
"/api/rooms/:id/tasks",
|
|
2808
|
+
"/api/rooms/:id/conversations",
|
|
2809
|
+
"/api/rooms/:id/conversations/:conversationId/messages",
|
|
2810
|
+
], postRoomMessage);
|
|
2811
|
+
installHubOrchestration({
|
|
2812
|
+
app,
|
|
2813
|
+
store,
|
|
2814
|
+
actor(req) {
|
|
2815
|
+
const owner = account(req);
|
|
2816
|
+
return { accountId: owner.id, deviceId: (agents.get(req) ?? users.get(req))?.device.id, human: !agents.has(req) };
|
|
2817
|
+
},
|
|
2818
|
+
async getModels(_req, deviceId) {
|
|
2819
|
+
if (!options.relay?.callDevice)
|
|
2820
|
+
fail(503, "Device relay unavailable");
|
|
2821
|
+
const result = await options.relay.callDevice(deviceId, "group_router_models", {});
|
|
2822
|
+
return { deviceId, models: Array.isArray(result) ? result : (result?.models ?? []) };
|
|
2823
|
+
},
|
|
2824
|
+
async sendMessage(job, action, key) {
|
|
2825
|
+
const state = store.snapshot(), owner = state.accounts.find((a) => a.id === job.accountId), device = state.devices.find((d) => d.id === job.deviceId && d.accountId === job.accountId);
|
|
2826
|
+
if (!owner || !device)
|
|
2827
|
+
fail(403, "Router device revoked");
|
|
2828
|
+
const parentId = action.type === "dispatch" && job.trigger.type === "task_result" ? job.trigger.taskId : undefined;
|
|
2829
|
+
const request = {
|
|
2830
|
+
params: { id: job.roomId },
|
|
2831
|
+
path: `/api/rooms/${job.roomId}/messages`,
|
|
2832
|
+
body: {
|
|
2833
|
+
text: action.text,
|
|
2834
|
+
targetBotIds: action.type === "dispatch" ? [action.botId] : [],
|
|
2835
|
+
idempotencyKey: key,
|
|
2836
|
+
...(parentId ? { parentTaskId: parentId } : {}),
|
|
2837
|
+
...(action.type === "dispatch" ? { executionMode: action.executionMode, contract: action.contract } : {}),
|
|
2838
|
+
},
|
|
2839
|
+
};
|
|
2840
|
+
users.set(request, { device, account: { id: owner.id, username: owner.username } });
|
|
2841
|
+
routerSources.set(request, job);
|
|
2842
|
+
let response;
|
|
2843
|
+
await postRoomMessage(request, {
|
|
2844
|
+
json: (value) => {
|
|
2845
|
+
response = value;
|
|
2846
|
+
},
|
|
2847
|
+
});
|
|
2848
|
+
return response;
|
|
2849
|
+
},
|
|
2278
2850
|
});
|
|
2279
2851
|
app.post("/api/devices/:id/remark", async (req, res) => {
|
|
2280
2852
|
const owner = account(req);
|
|
@@ -2374,9 +2946,8 @@ export async function createDeviceHub(options) {
|
|
|
2374
2946
|
req.headers.origin = origin.origin;
|
|
2375
2947
|
if (!options.relay?.handleOpen)
|
|
2376
2948
|
fail(503, "Relay unavailable");
|
|
2377
|
-
await options.relay.handleOpen(req, res, String(req.params.id));
|
|
2949
|
+
await options.relay.handleOpen(req, res, String(req.params.id), false, users.has(req) && req.body?.preferLan === true);
|
|
2378
2950
|
});
|
|
2379
|
-
// No catch-all: the runner mounts the UI after creation.
|
|
2380
2951
|
app.use((error, _req, res, _next) => {
|
|
2381
2952
|
res.status(error.status ?? 500).json({
|
|
2382
2953
|
error: error.status && error.status < 500 ? error.message : "Storage or internal error",
|
|
@@ -2389,7 +2960,6 @@ export async function createDeviceHub(options) {
|
|
|
2389
2960
|
return;
|
|
2390
2961
|
app(req, res);
|
|
2391
2962
|
});
|
|
2392
|
-
// Accepted queued tasks remain in flight until a terminal event, including asynchronous relay delivery.
|
|
2393
2963
|
const deliveredTasks = new Set();
|
|
2394
2964
|
async function releaseLocksAndWake(roomId, taskId) {
|
|
2395
2965
|
const promoted = lockManager.releaseLocks(roomId, taskId);
|
|
@@ -2414,7 +2984,7 @@ export async function createDeviceHub(options) {
|
|
|
2414
2984
|
}
|
|
2415
2985
|
await store.transact((draft) => {
|
|
2416
2986
|
const current = draft.tasks.find((t) => t.id === taskId);
|
|
2417
|
-
if (current && current.status === "waiting") {
|
|
2987
|
+
if (current && current.status === "waiting" && current.blockReason === "resource_locked") {
|
|
2418
2988
|
current.status = "queued";
|
|
2419
2989
|
delete current.blockReason;
|
|
2420
2990
|
delete current.blockReasonDetail;
|
|
@@ -2435,47 +3005,97 @@ export async function createDeviceHub(options) {
|
|
|
2435
3005
|
if (!conversationId)
|
|
2436
3006
|
return;
|
|
2437
3007
|
const state = store.snapshot();
|
|
2438
|
-
const next =
|
|
3008
|
+
const next = nextReadyConversationTask(state, conversationId);
|
|
2439
3009
|
if (!next || deliveredTasks.has(next.id))
|
|
2440
3010
|
return;
|
|
2441
3011
|
const room = state.rooms.find((entry) => entry.id === next.roomId);
|
|
2442
3012
|
await deliverTask(next, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
2443
3013
|
}
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
3014
|
+
function isSupersededContractTask(state, task) {
|
|
3015
|
+
return (!!task.contract &&
|
|
3016
|
+
state.tasks.some((other) => other.accountId === task.accountId &&
|
|
3017
|
+
other.roomId === task.roomId &&
|
|
3018
|
+
other.contract?.id === task.contract.id &&
|
|
3019
|
+
other.contract.revision > task.contract.revision));
|
|
3020
|
+
}
|
|
3021
|
+
function settlementContext() {
|
|
3022
|
+
return { settings: currentSettings(), getHistoryLimit };
|
|
3023
|
+
}
|
|
3024
|
+
function nextReadyConversationTask(state, conversationId) {
|
|
3025
|
+
const conversation = state.conversations.find((entry) => entry.id === conversationId);
|
|
3026
|
+
if (!conversation || conversation.closed)
|
|
3027
|
+
return;
|
|
3028
|
+
const pending = state.tasks.filter((entry) => entry.conversationId === conversationId &&
|
|
3029
|
+
(taskPending(entry) || (!entry.outcomeFingerprint && entry.recoveryUntil !== undefined)));
|
|
3030
|
+
if (pending.some((entry) => entry.status === "running" ||
|
|
3031
|
+
entry.cancelRequested ||
|
|
3032
|
+
hasTaskLease(entry) ||
|
|
3033
|
+
entry.recoveryUntil !== undefined))
|
|
3034
|
+
return;
|
|
3035
|
+
return pending[0]?.status === "queued" ? pending[0] : undefined;
|
|
3036
|
+
}
|
|
3037
|
+
async function publishSettlementEffects(result, dispatch = true) {
|
|
3038
|
+
for (const item of result.settledWakes) {
|
|
2462
3039
|
const state = store.snapshot();
|
|
2463
|
-
const
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
3040
|
+
const task = state.tasks.find((entry) => entry.id === item.taskId);
|
|
3041
|
+
if (!task)
|
|
3042
|
+
continue;
|
|
3043
|
+
deliveredTasks.delete(task.id);
|
|
3044
|
+
await releaseLocksAndWake(task.roomId, task.id);
|
|
3045
|
+
void taskJournalManager
|
|
3046
|
+
.append(task.id, {
|
|
3047
|
+
botId: task.botId,
|
|
3048
|
+
attemptId: task.attemptId,
|
|
3049
|
+
type: "status",
|
|
3050
|
+
phase: task.status,
|
|
3051
|
+
summary: `Task ${task.status}`,
|
|
3052
|
+
output: task.report,
|
|
3053
|
+
}, { roomId: task.roomId, accountId: task.accountId })
|
|
3054
|
+
.catch((cause) => console.warn(`[TaskJournal] Journal append failed for task ${task.id}:`, cause));
|
|
3055
|
+
dispatchGroupWebhook(store, task.roomId, task.status === "completed" ? "task_completed" : "task_failed", {
|
|
3056
|
+
taskId: task.id,
|
|
3057
|
+
botId: task.botId,
|
|
3058
|
+
status: task.status,
|
|
3059
|
+
report: task.report,
|
|
3060
|
+
text: task.text,
|
|
3061
|
+
});
|
|
3062
|
+
const message = state.messages.find((entry) => entry.taskIds.includes(task.id) && entry.sender.id === task.botId);
|
|
3063
|
+
if (message)
|
|
3064
|
+
dispatchGroupWebhook(store, task.roomId, "message", message);
|
|
3065
|
+
if (dispatch) {
|
|
3066
|
+
if (item.wake)
|
|
3067
|
+
await deliverTask(item.wake, item.context);
|
|
3068
|
+
await drainConversation(task.conversationId);
|
|
2472
3069
|
}
|
|
2473
3070
|
}
|
|
3071
|
+
if (!dispatch)
|
|
3072
|
+
return;
|
|
3073
|
+
for (const taskId of result.readyTaskIds) {
|
|
3074
|
+
const state = store.snapshot();
|
|
3075
|
+
const task = state.tasks.find((entry) => entry.id === taskId);
|
|
3076
|
+
const room = state.rooms.find((entry) => entry.id === task?.roomId);
|
|
3077
|
+
if (task)
|
|
3078
|
+
await deliverTask(task, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
3079
|
+
}
|
|
2474
3080
|
}
|
|
2475
3081
|
async function deliverTask(task, context) {
|
|
2476
|
-
|
|
3082
|
+
const state = store.snapshot();
|
|
3083
|
+
const current = state.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
3084
|
+
if (!current ||
|
|
3085
|
+
current.status !== "queued" ||
|
|
3086
|
+
hasTaskLease(current) ||
|
|
3087
|
+
current.recoveryUntil !== undefined ||
|
|
3088
|
+
current.cancelRequested ||
|
|
3089
|
+
current.stopConfirmed ||
|
|
3090
|
+
deliveredTasks.has(task.id))
|
|
2477
3091
|
return;
|
|
2478
|
-
|
|
3092
|
+
task = current;
|
|
3093
|
+
if (task.dependsOnTaskId) {
|
|
3094
|
+
const pred = state.tasks.find((entry) => entry.id === task.dependsOnTaskId && entry.roomId === task.roomId && entry.accountId === task.accountId);
|
|
3095
|
+
if (!pred || pred.status !== "completed" || pred.cancelRequested || pred.stopConfirmed)
|
|
3096
|
+
return;
|
|
3097
|
+
}
|
|
3098
|
+
if (task.conversationId && nextReadyConversationTask(state, task.conversationId)?.id !== task.id)
|
|
2479
3099
|
return;
|
|
2480
3100
|
if (task.resourceLocks && task.resourceLocks.length > 0) {
|
|
2481
3101
|
const acquired = lockManager.acquireLocks({
|
|
@@ -2515,6 +3135,21 @@ export async function createDeviceHub(options) {
|
|
|
2515
3135
|
current.lastHeartbeatAt = Date.now();
|
|
2516
3136
|
task.leaseToken = current.leaseToken;
|
|
2517
3137
|
task.leaseGeneration = current.leaseGeneration;
|
|
3138
|
+
if (current.contract && !current.contextManifest) {
|
|
3139
|
+
const activeTaskState = draft.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
|
|
3140
|
+
current.contextManifest = createContextManifest({
|
|
3141
|
+
contract: current.contract,
|
|
3142
|
+
executionPolicy: { deviceId: current.deviceId, botId: current.botId, botRevision: current.botRevision },
|
|
3143
|
+
context: context ?? null,
|
|
3144
|
+
taskState: activeTaskState ?? null,
|
|
3145
|
+
inputs: contractInputReferences(current.contract),
|
|
3146
|
+
policyRef: "server/device-center/group-context.ts#groupTaskContext",
|
|
3147
|
+
truncationBudget: currentSettings().groupContextBytes,
|
|
3148
|
+
});
|
|
3149
|
+
}
|
|
3150
|
+
if (current.contextManifest) {
|
|
3151
|
+
task.contextManifest = current.contextManifest;
|
|
3152
|
+
}
|
|
2518
3153
|
}
|
|
2519
3154
|
const conversation = draft.conversations.find((entry) => entry.id === task.conversationId);
|
|
2520
3155
|
if (conversation && !conversation.closed) {
|
|
@@ -2527,66 +3162,34 @@ export async function createDeviceHub(options) {
|
|
|
2527
3162
|
committed.conversations.find((entry) => entry.id === task.conversationId)?.closed)
|
|
2528
3163
|
throw new Error("Conversation stopped before delivery");
|
|
2529
3164
|
const taskState = committed.conversations.find((entry) => entry.id === task.conversationId)?.taskState;
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
3165
|
+
const wire = {
|
|
3166
|
+
...task,
|
|
3167
|
+
...(task.contextManifest ? {} : { context, taskState }),
|
|
3168
|
+
executionMode: task.executionMode ?? task.contract?.executionMode ?? "chat",
|
|
3169
|
+
};
|
|
3170
|
+
if (Buffer.byteLength(JSON.stringify({ type: "task", task: wire })) > RELAY_LIMITS.frame)
|
|
3171
|
+
throw new HttpError(413, `Task payload exceeds relay frame size of ${RELAY_LIMITS.frame} bytes`);
|
|
3172
|
+
if (!deliver || (await deliver(task.deviceId, wire)) === false)
|
|
2538
3173
|
throw new Error("Delivery rejected");
|
|
2539
3174
|
}
|
|
2540
|
-
catch {
|
|
3175
|
+
catch (error) {
|
|
2541
3176
|
const failure = await store.transact((draft) => {
|
|
2542
3177
|
const current = draft.tasks.find((entry) => entry.id === task.id && entry.attemptId === task.attemptId);
|
|
2543
3178
|
if (!current || isTerminal(current.status) || current.cancelRequested)
|
|
2544
3179
|
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 };
|
|
3180
|
+
const notice = recordTaskOutcome(draft, current, {
|
|
3181
|
+
status: "failed",
|
|
3182
|
+
report: error instanceof HttpError && error.status === 413
|
|
3183
|
+
? error.message
|
|
3184
|
+
: "Task delivery failed; submit a new request to retry.",
|
|
3185
|
+
}, settlementContext());
|
|
3186
|
+
const result = settleTaskDependencies(draft, settlementContext());
|
|
3187
|
+
if (notice)
|
|
3188
|
+
result.settledWakes.unshift(notice);
|
|
3189
|
+
return result;
|
|
2587
3190
|
});
|
|
2588
|
-
if (failure
|
|
2589
|
-
await
|
|
3191
|
+
if (failure)
|
|
3192
|
+
await publishSettlementEffects(failure);
|
|
2590
3193
|
}
|
|
2591
3194
|
finally {
|
|
2592
3195
|
if (isTerminal(store.snapshot().tasks.find((entry) => entry.id === task.id)?.status ?? "interrupted")) {
|
|
@@ -2603,15 +3206,10 @@ export async function createDeviceHub(options) {
|
|
|
2603
3206
|
typeof event.botId !== "string" ||
|
|
2604
3207
|
!["running", "completed", "failed", "interrupted"].includes(event.status))
|
|
2605
3208
|
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");
|
|
3209
|
+
if ((event.report !== undefined &&
|
|
3210
|
+
(typeof event.report !== "string" || Buffer.byteLength(event.report) > 64 * 1024)) ||
|
|
3211
|
+
(event.error !== undefined && (typeof event.error !== "string" || event.error.length > 4096)))
|
|
3212
|
+
fail(400, "Invalid task outcome");
|
|
2615
3213
|
let reportMetadata;
|
|
2616
3214
|
try {
|
|
2617
3215
|
if (event.reportMetadata !== undefined)
|
|
@@ -2621,208 +3219,133 @@ export async function createDeviceHub(options) {
|
|
|
2621
3219
|
fail(400, "Invalid report metadata");
|
|
2622
3220
|
}
|
|
2623
3221
|
const result = await store.transact((draft) => {
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
3222
|
+
if (event.status !== "running") {
|
|
3223
|
+
const device = draft.devices.find((entry) => entry.id === deviceId);
|
|
3224
|
+
const targetTask = draft.tasks.find((entry) => entry.id === event.taskId &&
|
|
3225
|
+
entry.deviceId === deviceId &&
|
|
3226
|
+
entry.botId === event.botId &&
|
|
3227
|
+
entry.accountId === device?.accountId);
|
|
3228
|
+
const settled = settleTaskTerminalOutcome(draft, deviceId, { ...event, type: "task_event", reportMetadata }, settlementContext());
|
|
3229
|
+
if (!settled.accepted)
|
|
3230
|
+
throw Object.assign(new HttpError(settled.statusCode ?? 409, settled.reason ?? "Outcome rejected"), {
|
|
3231
|
+
permanent: settled.permanent,
|
|
3232
|
+
reasonCode: settled.reasonCode,
|
|
3233
|
+
});
|
|
3234
|
+
if (targetTask) {
|
|
3235
|
+
const validation = validateCodeArtifactOutcome({
|
|
3236
|
+
task: targetTask,
|
|
3237
|
+
artifact: event.artifact,
|
|
3238
|
+
executionCompleted: event.executionCompleted,
|
|
3239
|
+
artifactProduced: event.artifactProduced,
|
|
3240
|
+
});
|
|
3241
|
+
if (!validation.valid)
|
|
3242
|
+
fail(400, `Invalid code task outcome: ${validation.reason}`);
|
|
3243
|
+
if (!settled.duplicate && validation.artifact)
|
|
3244
|
+
targetTask.artifact = validation.artifact;
|
|
3245
|
+
}
|
|
3246
|
+
return settled;
|
|
3247
|
+
}
|
|
3248
|
+
const device = draft.devices.find((entry) => entry.id === deviceId);
|
|
3249
|
+
const task = draft.tasks.find((entry) => entry.id === event.taskId &&
|
|
3250
|
+
entry.deviceId === deviceId &&
|
|
3251
|
+
entry.botId === event.botId &&
|
|
3252
|
+
entry.accountId === device?.accountId);
|
|
3253
|
+
const bot = draft.bots.find((entry) => entry.id === event.botId && entry.deviceId === deviceId && entry.accountId === device?.accountId);
|
|
3254
|
+
if (!task ||
|
|
3255
|
+
!device ||
|
|
3256
|
+
!bot ||
|
|
3257
|
+
!draft.rooms.some((room) => room.id === task.roomId && room.botIds.includes(bot.id)))
|
|
2632
3258
|
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
|
-
}
|
|
3259
|
+
if (task.attemptId !== event.attemptId ||
|
|
3260
|
+
task.leaseToken !== event.leaseToken ||
|
|
3261
|
+
task.leaseGeneration !== event.leaseGeneration)
|
|
3262
|
+
fail(409, "Attempt or lease mismatch");
|
|
3263
|
+
if (isSupersededContractTask(draft, task))
|
|
3264
|
+
fail(409, "Contract revision superseded");
|
|
3265
|
+
if (!bot.enabled || bot.revision !== task.botRevision || task.cancelRequested || task.stopConfirmed)
|
|
3266
|
+
fail(409, "Task unavailable");
|
|
3267
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3268
|
+
fail(409, "Recovery window expired");
|
|
3269
|
+
if (task.status === "running") {
|
|
3270
|
+
delete task.recoveryUntil;
|
|
3271
|
+
return { task, duplicate: true };
|
|
3272
|
+
}
|
|
3273
|
+
if (task.status !== "queued" && !isRecoveringTask(task, Date.now()))
|
|
3274
|
+
fail(409, "Invalid task transition");
|
|
2661
3275
|
delete task.recoveryUntil;
|
|
2662
|
-
task.status =
|
|
3276
|
+
task.status = "running";
|
|
2663
3277
|
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 };
|
|
3278
|
+
return { task, duplicate: false };
|
|
2700
3279
|
});
|
|
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);
|
|
3280
|
+
if (!result.duplicate && "settledWakes" in result)
|
|
3281
|
+
await publishSettlementEffects({
|
|
3282
|
+
settledWakes: result.settledWakes ?? [],
|
|
3283
|
+
readyTaskIds: result.readyTaskIds ?? [],
|
|
3284
|
+
cascadedFailedTaskIds: result.cascadedFailedTaskIds ?? [],
|
|
2713
3285
|
});
|
|
3286
|
+
if (!result.duplicate && event.status === "running") {
|
|
3287
|
+
const task = result.task;
|
|
3288
|
+
void taskJournalManager
|
|
3289
|
+
.append(task.id, { botId: task.botId, attemptId: task.attemptId, type: "status", phase: "running", summary: "Task running" }, { roomId: task.roomId, accountId: task.accountId })
|
|
3290
|
+
.catch((cause) => console.warn(`[TaskJournal] Journal append failed for task ${task.id}:`, cause));
|
|
2714
3291
|
}
|
|
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
3292
|
return result.task;
|
|
2749
3293
|
}
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
3294
|
+
const recovery = await store.transact((draft) => rescanReadyTasksOnRecovery(draft, Date.now(), 60_000, settlementContext()));
|
|
3295
|
+
await publishSettlementEffects(recovery, false);
|
|
3296
|
+
async function resumeQueuedTasks(deviceId) {
|
|
3297
|
+
for (const task of store.snapshot().tasks) {
|
|
3298
|
+
if ((deviceId && task.deviceId !== deviceId) ||
|
|
3299
|
+
task.status !== "queued" ||
|
|
3300
|
+
hasTaskLease(task) ||
|
|
3301
|
+
task.recoveryUntil !== undefined)
|
|
3302
|
+
continue;
|
|
3303
|
+
const state = store.snapshot();
|
|
3304
|
+
const room = state.rooms.find((entry) => entry.id === task.roomId);
|
|
3305
|
+
await deliverTask(task, room ? groupTaskContext(room, state.bots, state.messages, currentSettings().groupContextBytes) : undefined);
|
|
3306
|
+
}
|
|
2761
3307
|
}
|
|
2762
|
-
|
|
2763
|
-
|
|
3308
|
+
async function reconcilePendingPublications(deviceId) {
|
|
3309
|
+
if (!options.relay?.callDevice)
|
|
3310
|
+
return [];
|
|
3311
|
+
try {
|
|
3312
|
+
return await reconcilePendingIntegrations(store, {
|
|
3313
|
+
callDeviceCommand: (id, action, payload, opts) => options.relay.callDevice(id, action, payload, opts),
|
|
3314
|
+
}, { limit: 16, deviceId });
|
|
3315
|
+
}
|
|
3316
|
+
catch (cause) {
|
|
3317
|
+
console.warn("[HubRecovery] Publication query failed", cause);
|
|
3318
|
+
return [];
|
|
3319
|
+
}
|
|
2764
3320
|
}
|
|
3321
|
+
void reconcilePendingPublications();
|
|
2765
3322
|
let sweepInflight = false;
|
|
2766
3323
|
const recoverySweepTimer = setInterval(() => {
|
|
3324
|
+
void reconcilePendingPublications();
|
|
2767
3325
|
if (sweepInflight)
|
|
2768
3326
|
return;
|
|
2769
|
-
const
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
(
|
|
2773
|
-
|
|
3327
|
+
const now = Date.now();
|
|
3328
|
+
if (!store
|
|
3329
|
+
.snapshot()
|
|
3330
|
+
.tasks.some((task) => !task.outcomeFingerprint &&
|
|
3331
|
+
((task.recoveryUntil !== undefined && now > task.recoveryUntil) ||
|
|
3332
|
+
((task.status === "running" || (task.status === "queued" && hasTaskLease(task))) &&
|
|
3333
|
+
task.lastHeartbeatAt !== undefined &&
|
|
3334
|
+
now - task.lastHeartbeatAt > 30 * 60_000))))
|
|
2774
3335
|
return;
|
|
2775
3336
|
sweepInflight = true;
|
|
2776
3337
|
void (async () => {
|
|
2777
3338
|
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
|
-
}
|
|
3339
|
+
const settled = await store.transact((draft) => sweepExpiredRecoveryLeases(draft, now, settlementContext()));
|
|
3340
|
+
await publishSettlementEffects(settled);
|
|
3341
|
+
for (const taskId of lockManager.cleanupExpiredLocks()) {
|
|
3342
|
+
const task = store.snapshot().tasks.find((entry) => entry.id === taskId);
|
|
3343
|
+
if (task)
|
|
3344
|
+
await handlePromotedTasks(task.roomId, [taskId]);
|
|
2822
3345
|
}
|
|
2823
3346
|
}
|
|
2824
|
-
catch {
|
|
2825
|
-
console.warn("[HubRecovery] Sweep transaction failed");
|
|
3347
|
+
catch (cause) {
|
|
3348
|
+
console.warn("[HubRecovery] Sweep transaction failed", cause);
|
|
2826
3349
|
}
|
|
2827
3350
|
finally {
|
|
2828
3351
|
sweepInflight = false;
|
|
@@ -2854,12 +3377,17 @@ export async function createDeviceHub(options) {
|
|
|
2854
3377
|
if (!task || !device) {
|
|
2855
3378
|
return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Task not found" };
|
|
2856
3379
|
}
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
3380
|
+
if (isSupersededContractTask(draft, task))
|
|
3381
|
+
return {
|
|
3382
|
+
taskId: claim.taskId,
|
|
3383
|
+
attemptId: claim.attemptId,
|
|
3384
|
+
accepted: false,
|
|
3385
|
+
reason: "Contract revision superseded",
|
|
3386
|
+
};
|
|
3387
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3388
|
+
return { taskId: claim.taskId, attemptId: claim.attemptId, accepted: false, reason: "Recovery window expired" };
|
|
3389
|
+
const inRecovery = isRecoveringTask(task, Date.now());
|
|
3390
|
+
if (task.outcomeFingerprint || (isTerminal(task.status) && !inRecovery)) {
|
|
2863
3391
|
return {
|
|
2864
3392
|
taskId: claim.taskId,
|
|
2865
3393
|
attemptId: claim.attemptId,
|
|
@@ -2899,7 +3427,7 @@ export async function createDeviceHub(options) {
|
|
|
2899
3427
|
reason: "Lease generation mismatch",
|
|
2900
3428
|
};
|
|
2901
3429
|
}
|
|
2902
|
-
if (task.status !== "running" && !
|
|
3430
|
+
if (task.status !== "running" && !(task.status === "queued" && hasTaskLease(task)) && !inRecovery) {
|
|
2903
3431
|
return {
|
|
2904
3432
|
taskId: claim.taskId,
|
|
2905
3433
|
attemptId: claim.attemptId,
|
|
@@ -2938,9 +3466,18 @@ export async function createDeviceHub(options) {
|
|
|
2938
3466
|
if (!task || !device || task.status !== "running") {
|
|
2939
3467
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task not running" };
|
|
2940
3468
|
}
|
|
3469
|
+
if (isSupersededContractTask(draft, task))
|
|
3470
|
+
return {
|
|
3471
|
+
taskId: renew.taskId,
|
|
3472
|
+
attemptId: renew.attemptId,
|
|
3473
|
+
accepted: false,
|
|
3474
|
+
reason: "Contract revision superseded",
|
|
3475
|
+
};
|
|
2941
3476
|
if (task.cancelRequested || task.stopConfirmed) {
|
|
2942
3477
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Task stop requested" };
|
|
2943
3478
|
}
|
|
3479
|
+
if (task.recoveryUntil !== undefined && Date.now() > task.recoveryUntil)
|
|
3480
|
+
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Recovery window expired" };
|
|
2944
3481
|
if (task.leaseToken !== renew.leaseToken) {
|
|
2945
3482
|
return { taskId: renew.taskId, attemptId: renew.attemptId, accepted: false, reason: "Lease token mismatch" };
|
|
2946
3483
|
}
|
|
@@ -2993,7 +3530,6 @@ export async function createDeviceHub(options) {
|
|
|
2993
3530
|
const room = state.rooms.find((r) => r.id === task.roomId && r.accountId === task.accountId);
|
|
2994
3531
|
if (!room)
|
|
2995
3532
|
return;
|
|
2996
|
-
// Deduplicate and enforce monotonic sequence if provided
|
|
2997
3533
|
if (typeof frame.sequence === "number" && Number.isSafeInteger(frame.sequence)) {
|
|
2998
3534
|
const seqKey = `${task.id}:${task.attemptId}`;
|
|
2999
3535
|
const prevSeq = toolLifecycleSeqs.get(seqKey);
|
|
@@ -3064,8 +3600,10 @@ export async function createDeviceHub(options) {
|
|
|
3064
3600
|
const recoveryGraceMs = 60_000;
|
|
3065
3601
|
await store.transact((draft) => {
|
|
3066
3602
|
const task = draft.tasks.find((t) => t.id === taskId && t.deviceId === deviceId && t.attemptId === attemptId);
|
|
3067
|
-
if (task &&
|
|
3068
|
-
task.
|
|
3603
|
+
if (task &&
|
|
3604
|
+
!task.outcomeFingerprint &&
|
|
3605
|
+
(task.status === "running" || (task.status === "queued" && hasTaskLease(task)))) {
|
|
3606
|
+
task.recoveryUntil ??= now + recoveryGraceMs;
|
|
3069
3607
|
task.updatedAt = now;
|
|
3070
3608
|
}
|
|
3071
3609
|
});
|
|
@@ -3077,6 +3615,8 @@ export async function createDeviceHub(options) {
|
|
|
3077
3615
|
claimTask,
|
|
3078
3616
|
renewTaskLease,
|
|
3079
3617
|
onTaskDisconnect,
|
|
3618
|
+
resumeQueuedTasks,
|
|
3619
|
+
reconcilePendingPublications,
|
|
3080
3620
|
getAccount,
|
|
3081
3621
|
getRelayAccount: (req) => users.get(req)?.account ?? getAccount(req) ?? undefined,
|
|
3082
3622
|
authenticateAgent,
|
|
@@ -3087,8 +3627,10 @@ export async function createDeviceHub(options) {
|
|
|
3087
3627
|
acceptTaskPlanReady,
|
|
3088
3628
|
setRelay(relay) {
|
|
3089
3629
|
options.relay = relay;
|
|
3630
|
+
void reconcilePendingPublications();
|
|
3090
3631
|
},
|
|
3091
3632
|
async close() {
|
|
3633
|
+
await mobilePush.dispose();
|
|
3092
3634
|
clearInterval(recoverySweepTimer);
|
|
3093
3635
|
lockManager.close();
|
|
3094
3636
|
await groupEvents.close();
|