@cortex-agent/server 2026.5.25 → 2026.6.15
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/defaults/config/thread-templates.json +28 -1
- package/defaults/hooks/cortex-md-injector.mjs +47 -31
- package/defaults/hooks/post-task-hook.mjs +6 -0
- package/defaults/hooks/task-status-check.mjs +8 -0
- package/defaults/mcp-config-slack.json +11 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
- package/defaults/prompts/directives/manager.md +67 -0
- package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
- package/dist/agent-adapter/claude/adapter-tui.js +91 -12
- package/dist/agent-adapter/claude/adapter.js +11 -0
- package/dist/agent-adapter/claude/defaults.d.ts +30 -0
- package/dist/agent-adapter/claude/defaults.js +30 -0
- package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
- package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
- package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
- package/dist/agent-adapter/claude/spawn-args.js +49 -7
- package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
- package/dist/agent-adapter/claude/tmux-control.js +54 -8
- package/dist/agent-adapter/codex/adapter.js +1 -1
- package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
- package/dist/agent-adapter/pi/adapter.js +46 -19
- package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
- package/dist/agent-adapter/pi/agent-dir.js +53 -2
- package/dist/agent-adapter/pi/event-parser.js +13 -1
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
- package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
- package/dist/agent-adapter/pi/tool-shims.js +167 -140
- package/dist/agent-adapter/types.d.ts +7 -2
- package/dist/core/atomic-write.js +21 -0
- package/dist/core/config-generator.d.ts +10 -0
- package/dist/core/config-generator.js +28 -0
- package/dist/core/gateway-generator.d.ts +77 -7
- package/dist/core/gateway-generator.js +323 -30
- package/dist/core/i18n.d.ts +19 -0
- package/dist/core/i18n.js +46 -0
- package/dist/core/icons.d.ts +68 -0
- package/dist/core/icons.js +67 -0
- package/dist/core/locales/en.d.ts +438 -0
- package/dist/core/locales/en.js +24 -0
- package/dist/core/locales/slices/commands.d.ts +214 -0
- package/dist/core/locales/slices/commands.js +462 -0
- package/dist/core/locales/slices/init.d.ts +121 -0
- package/dist/core/locales/slices/init.js +380 -0
- package/dist/core/locales/slices/interactions.d.ts +47 -0
- package/dist/core/locales/slices/interactions.js +102 -0
- package/dist/core/locales/slices/lang.d.ts +8 -0
- package/dist/core/locales/slices/lang.js +18 -0
- package/dist/core/locales/slices/scheduling.d.ts +36 -0
- package/dist/core/locales/slices/scheduling.js +74 -0
- package/dist/core/locales/slices/startup.d.ts +6 -0
- package/dist/core/locales/slices/startup.js +14 -0
- package/dist/core/locales/slices/status.d.ts +20 -0
- package/dist/core/locales/slices/status.js +48 -0
- package/dist/core/locales/zh.d.ts +5 -0
- package/dist/core/locales/zh.js +23 -0
- package/dist/core/profile-generator.d.ts +6 -0
- package/dist/core/profile-generator.js +35 -7
- package/dist/core/running-executions.d.ts +51 -41
- package/dist/core/running-executions.js +120 -73
- package/dist/core/singleton-lock.d.ts +23 -0
- package/dist/core/singleton-lock.js +53 -0
- package/dist/core/status-format.js +4 -2
- package/dist/core/task-parser.d.ts +3 -0
- package/dist/core/task-parser.js +3 -1
- package/dist/core/types/thread-types.d.ts +54 -8
- package/dist/core/utils.d.ts +9 -1
- package/dist/core/utils.js +9 -1
- package/dist/domain/agents/config.d.ts +2 -1
- package/dist/domain/agents/config.js +25 -6
- package/dist/domain/agents/facade.d.ts +18 -0
- package/dist/domain/agents/facade.js +26 -3
- package/dist/domain/agents/profile-manager.d.ts +11 -0
- package/dist/domain/agents/profile-manager.js +21 -2
- package/dist/domain/costs/codex-usage-monitor.js +2 -1
- package/dist/domain/costs/rate-limit-throttle.js +14 -2
- package/dist/domain/executions/registry.d.ts +24 -0
- package/dist/domain/executions/registry.js +38 -0
- package/dist/domain/mcp/core-server.js +15 -3
- package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
- package/dist/domain/mcp/feishu/bitable.js +168 -0
- package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
- package/dist/domain/mcp/feishu/block-types.js +127 -0
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
- package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
- package/dist/domain/mcp/feishu/client.d.ts +46 -0
- package/dist/domain/mcp/feishu/client.js +87 -0
- package/dist/domain/mcp/feishu/docx.d.ts +3 -0
- package/dist/domain/mcp/feishu/docx.js +163 -0
- package/dist/domain/mcp/feishu/drive.d.ts +23 -0
- package/dist/domain/mcp/feishu/drive.js +66 -0
- package/dist/domain/mcp/feishu/file.d.ts +14 -0
- package/dist/domain/mcp/feishu/file.js +107 -0
- package/dist/domain/mcp/feishu/index.d.ts +6 -0
- package/dist/domain/mcp/feishu/index.js +61 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
- package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
- package/dist/domain/mcp/feishu/sheets.js +119 -0
- package/dist/domain/mcp/feishu/types.d.ts +26 -0
- package/dist/domain/mcp/feishu/types.js +38 -0
- package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
- package/dist/domain/mcp/feishu/user-auth.js +286 -0
- package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
- package/dist/domain/mcp/feishu/wiki.js +77 -0
- package/dist/domain/mcp/feishu-server.d.ts +2 -0
- package/dist/domain/mcp/feishu-server.js +33 -0
- package/dist/domain/mcp/server.d.ts +0 -1
- package/dist/domain/mcp/server.js +6 -25
- package/dist/domain/mcp/slack-server.d.ts +3 -0
- package/dist/domain/mcp/slack-server.js +46 -0
- package/dist/domain/mcp/tools/context.js +1 -1
- package/dist/domain/mcp/tools/schedule.d.ts +1 -1
- package/dist/domain/mcp/tools/schedule.js +6 -20
- package/dist/domain/mcp/tools/slack.js +20 -7
- package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
- package/dist/domain/mcp/tools/thread-ops.js +121 -0
- package/dist/domain/mcp/tools/time.d.ts +2 -0
- package/dist/domain/mcp/tools/time.js +66 -0
- package/dist/domain/mcp/tools/tui-ask.js +1 -1
- package/dist/domain/mcp/tools/tui-plan.js +2 -2
- package/dist/domain/mcp/tui-server.js +1 -0
- package/dist/domain/monitor/disk-monitor.js +2 -1
- package/dist/domain/monitor/gpu-monitor.js +2 -1
- package/dist/domain/remote/client-hot-reload.js +3 -2
- package/dist/domain/remote/client-manager.js +8 -6
- package/dist/domain/scheduling/job-registry.d.ts +4 -0
- package/dist/domain/scheduling/job-registry.js +1 -0
- package/dist/domain/scheduling/jobs/_shared.js +2 -1
- package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
- package/dist/domain/scheduling/jobs/sync-public.js +4 -3
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
- package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
- package/dist/domain/scheduling/jobs/task-archive.js +3 -2
- package/dist/domain/scheduling/jobs/task-dispatch.js +126 -20
- package/dist/domain/scheduling/schedule-command.js +45 -43
- package/dist/domain/scheduling/scheduler.d.ts +1 -1
- package/dist/domain/scheduling/scheduler.js +2 -1
- package/dist/domain/sessions/session-hooks.d.ts +2 -2
- package/dist/domain/sessions/session-hooks.js +19 -18
- package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
- package/dist/domain/sessions/session-lifecycle.js +44 -0
- package/dist/domain/system/github-release.d.ts +18 -0
- package/dist/domain/system/github-release.js +106 -0
- package/dist/domain/system/install-cli.d.ts +7 -0
- package/dist/domain/system/install-cli.js +106 -0
- package/dist/domain/system/preferences.d.ts +12 -0
- package/dist/domain/system/preferences.js +36 -0
- package/dist/domain/system/server-update-check.js +2 -2
- package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
- package/dist/domain/tasks/dispatch-utils.js +53 -4
- package/dist/domain/tasks/dispatcher.d.ts +11 -2
- package/dist/domain/tasks/dispatcher.js +63 -7
- package/dist/domain/tasks/lint.js +28 -0
- package/dist/domain/tasks/mutator.d.ts +16 -3
- package/dist/domain/tasks/mutator.js +41 -12
- package/dist/domain/tasks/pending-tracker.js +6 -5
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +37 -6
- package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
- package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
- package/dist/domain/tasks/system/task-mutations.js +166 -8
- package/dist/domain/threads/contract.d.ts +17 -0
- package/dist/domain/threads/contract.js +59 -0
- package/dist/domain/threads/hook-runner.js +7 -6
- package/dist/domain/threads/index.d.ts +2 -0
- package/dist/domain/threads/index.js +3 -1
- package/dist/domain/threads/prompt-builder.d.ts +21 -1
- package/dist/domain/threads/prompt-builder.js +60 -4
- package/dist/domain/threads/runner.d.ts +6 -5
- package/dist/domain/threads/runner.js +128 -79
- package/dist/domain/threads/state-machine.d.ts +23 -21
- package/dist/domain/threads/state-machine.js +113 -54
- package/dist/domain/threads/template-loader.js +3 -2
- package/dist/domain/threads/tree.d.ts +45 -0
- package/dist/domain/threads/tree.js +171 -0
- package/dist/domain/tui-session/index.d.ts +2 -0
- package/dist/domain/tui-session/index.js +3 -0
- package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
- package/dist/domain/tui-session/tui-session-service.js +103 -0
- package/dist/domain/tui-session/types.d.ts +67 -0
- package/dist/domain/tui-session/types.js +4 -0
- package/dist/domain/ui-service/index.d.ts +5 -0
- package/dist/domain/ui-service/index.js +3 -0
- package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
- package/dist/domain/ui-service/mutate/executions.js +15 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
- package/dist/domain/ui-service/mutate/schedules.js +39 -0
- package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
- package/dist/domain/ui-service/mutate/tasks.js +59 -0
- package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
- package/dist/domain/ui-service/mutate/threads.js +21 -0
- package/dist/domain/ui-service/query/cost.d.ts +3 -0
- package/dist/domain/ui-service/query/cost.js +6 -0
- package/dist/domain/ui-service/query/executions.d.ts +2 -0
- package/dist/domain/ui-service/query/executions.js +35 -0
- package/dist/domain/ui-service/query/projects.d.ts +2 -0
- package/dist/domain/ui-service/query/projects.js +30 -0
- package/dist/domain/ui-service/query/schedules.d.ts +2 -0
- package/dist/domain/ui-service/query/schedules.js +23 -0
- package/dist/domain/ui-service/query/sessions.d.ts +2 -0
- package/dist/domain/ui-service/query/sessions.js +35 -0
- package/dist/domain/ui-service/query/tasks.d.ts +2 -0
- package/dist/domain/ui-service/query/tasks.js +30 -0
- package/dist/domain/ui-service/query/threads.d.ts +2 -0
- package/dist/domain/ui-service/query/threads.js +27 -0
- package/dist/domain/ui-service/subscribe.d.ts +5 -0
- package/dist/domain/ui-service/subscribe.js +118 -0
- package/dist/domain/ui-service/types.d.ts +237 -0
- package/dist/domain/ui-service/types.js +5 -0
- package/dist/domain/ui-service/ui-service.d.ts +2 -0
- package/dist/domain/ui-service/ui-service.js +83 -0
- package/dist/entry/app.js +130 -8
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +122 -12
- package/dist/entry/daemon.js +12 -30
- package/dist/entry/feishu-login.d.ts +28 -0
- package/dist/entry/feishu-login.js +218 -0
- package/dist/entry/init.d.ts +29 -5
- package/dist/entry/init.js +323 -233
- package/dist/entry/startup-notify.js +6 -3
- package/dist/events/event-types.d.ts +14 -0
- package/dist/hooks/cortex-md-injector.mjs +47 -31
- package/dist/hooks/post-task-hook.mjs +6 -0
- package/dist/hooks/task-status-check.mjs +8 -0
- package/dist/orchestration/agent-runner.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +55 -55
- package/dist/orchestration/conduit-queue.d.ts +18 -0
- package/dist/orchestration/conduit-queue.js +32 -0
- package/dist/orchestration/conversation-runner.d.ts +48 -0
- package/dist/orchestration/conversation-runner.js +109 -0
- package/dist/orchestration/dispatch-reconciler.js +8 -1
- package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
- package/dist/orchestration/interactions/ask-user-question.js +3 -3
- package/dist/orchestration/interactions/interaction-handlers.js +55 -23
- package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
- package/dist/orchestration/interactions/plan-handler.js +4 -3
- package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
- package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
- package/dist/orchestration/interactions/update-prompt.js +155 -0
- package/dist/orchestration/lifecycle.d.ts +4 -4
- package/dist/orchestration/lifecycle.js +25 -22
- package/dist/orchestration/orchestrator.d.ts +1 -1
- package/dist/orchestration/routing/commands/cancel.js +45 -52
- package/dist/orchestration/routing/commands/channel.js +41 -27
- package/dist/orchestration/routing/commands/cost.js +11 -2
- package/dist/orchestration/routing/commands/device.js +12 -9
- package/dist/orchestration/routing/commands/dispatch.js +11 -10
- package/dist/orchestration/routing/commands/index.d.ts +1 -1
- package/dist/orchestration/routing/commands/index.js +15 -10
- package/dist/orchestration/routing/commands/lang.d.ts +3 -0
- package/dist/orchestration/routing/commands/lang.js +31 -0
- package/dist/orchestration/routing/commands/mode.js +32 -30
- package/dist/orchestration/routing/commands/nvtop.js +15 -13
- package/dist/orchestration/routing/commands/orient.js +2 -1
- package/dist/orchestration/routing/commands/schedule.js +23 -22
- package/dist/orchestration/routing/commands/sendfile.js +9 -7
- package/dist/orchestration/routing/commands/session.d.ts +1 -1
- package/dist/orchestration/routing/commands/session.js +24 -39
- package/dist/orchestration/routing/commands/status.js +78 -71
- package/dist/orchestration/routing/commands/tail.js +7 -5
- package/dist/orchestration/routing/commands/task.js +25 -23
- package/dist/orchestration/routing/commands/thread-handlers.js +55 -44
- package/dist/orchestration/routing/edit-handler.js +8 -7
- package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
- package/dist/orchestration/routing/message-router.d.ts +1 -1
- package/dist/orchestration/routing/message-router.js +9 -9
- package/dist/orchestration/routing/webhook.js +233 -2
- package/dist/orchestration/status-helpers.d.ts +5 -1
- package/dist/orchestration/status-helpers.js +13 -11
- package/dist/orchestration/thread-callback.d.ts +67 -0
- package/dist/orchestration/thread-callback.js +465 -0
- package/dist/orchestration/thread-executor.d.ts +22 -1
- package/dist/orchestration/thread-executor.js +85 -36
- package/dist/platform/adapter.d.ts +6 -2
- package/dist/platform/adapters/composite-adapter.d.ts +89 -0
- package/dist/platform/adapters/composite-adapter.js +318 -0
- package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
- package/dist/platform/adapters/feishu-output-stream.js +274 -36
- package/dist/platform/adapters/feishu.d.ts +50 -5
- package/dist/platform/adapters/feishu.js +370 -116
- package/dist/platform/adapters/index.d.ts +24 -3
- package/dist/platform/adapters/index.js +89 -11
- package/dist/platform/adapters/project-conduits.d.ts +9 -0
- package/dist/platform/adapters/project-conduits.js +42 -0
- package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
- package/dist/platform/adapters/slack-project-conduits.js +6 -40
- package/dist/platform/adapters/slack.d.ts +9 -2
- package/dist/platform/adapters/slack.js +83 -39
- package/dist/platform/adapters/tui/index.d.ts +9 -0
- package/dist/platform/adapters/tui/index.js +10 -0
- package/dist/platform/adapters/tui/ports.d.ts +20 -0
- package/dist/platform/adapters/tui/ports.js +4 -0
- package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
- package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
- package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
- package/dist/platform/adapters/tui/tui-connection.js +53 -0
- package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
- package/dist/platform/adapters/tui/tui-gateway.js +919 -0
- package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
- package/dist/platform/adapters/tui/tui-notifications.js +60 -0
- package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
- package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
- package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
- package/dist/platform/adapters/tui/tui-transcript.js +56 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +2 -1
- package/dist/platform/interactive-builder.js +21 -19
- package/dist/platform/output-stream.d.ts +5 -0
- package/dist/platform/testing.d.ts +7 -11
- package/dist/platform/testing.js +18 -15
- package/dist/platform/tool-trace.js +15 -5
- package/dist/platform/tui/protocol.d.ts +355 -0
- package/dist/platform/tui/protocol.js +199 -0
- package/dist/platform/types.d.ts +12 -3
- package/dist/store/execution-repo.d.ts +6 -1
- package/dist/store/execution-repo.js +13 -3
- package/dist/store/hook-sync.d.ts +18 -0
- package/dist/store/hook-sync.js +92 -0
- package/dist/store/outbound-queue.js +2 -2
- package/dist/store/profile-repo.js +3 -2
- package/dist/store/schedule-repo.d.ts +1 -8
- package/dist/store/session-registry-repo.d.ts +9 -1
- package/dist/store/session-registry-repo.js +19 -3
- package/dist/store/session-repo.d.ts +14 -0
- package/dist/store/session-repo.js +23 -0
- package/dist/store/thread-repo.d.ts +3 -0
- package/dist/store/thread-repo.js +49 -2
- package/dist/store/version-migrations.d.ts +7 -0
- package/dist/store/version-migrations.js +183 -0
- package/dist/tui/App.d.ts +27 -0
- package/dist/tui/App.js +219 -0
- package/dist/tui/components/AskUserModal.d.ts +11 -0
- package/dist/tui/components/AskUserModal.js +364 -0
- package/dist/tui/components/ConfirmModal.d.ts +12 -0
- package/dist/tui/components/ConfirmModal.js +31 -0
- package/dist/tui/components/Dashboard.d.ts +23 -0
- package/dist/tui/components/Dashboard.js +80 -0
- package/dist/tui/components/DashboardCostTab.d.ts +7 -0
- package/dist/tui/components/DashboardCostTab.js +16 -0
- package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
- package/dist/tui/components/DashboardExecutionsTab.js +94 -0
- package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
- package/dist/tui/components/DashboardSchedulesTab.js +124 -0
- package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
- package/dist/tui/components/DashboardTasksTab.js +200 -0
- package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
- package/dist/tui/components/DashboardThreadsTab.js +81 -0
- package/dist/tui/components/Header.d.ts +11 -0
- package/dist/tui/components/Header.js +5 -0
- package/dist/tui/components/InputBox.d.ts +10 -0
- package/dist/tui/components/InputBox.js +19 -0
- package/dist/tui/components/MessageRow.d.ts +7 -0
- package/dist/tui/components/MessageRow.js +10 -0
- package/dist/tui/components/Notifications.d.ts +19 -0
- package/dist/tui/components/Notifications.js +72 -0
- package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
- package/dist/tui/components/PlanFeedbackModal.js +161 -0
- package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
- package/dist/tui/components/ProjectSwitcher.js +43 -0
- package/dist/tui/components/SessionPicker.d.ts +14 -0
- package/dist/tui/components/SessionPicker.js +34 -0
- package/dist/tui/components/SidePanel.d.ts +19 -0
- package/dist/tui/components/SidePanel.js +8 -0
- package/dist/tui/components/StatusLine.d.ts +10 -0
- package/dist/tui/components/StatusLine.js +29 -0
- package/dist/tui/components/Transcript.d.ts +13 -0
- package/dist/tui/components/Transcript.js +56 -0
- package/dist/tui/hooks/useDashboardData.d.ts +32 -0
- package/dist/tui/hooks/useDashboardData.js +104 -0
- package/dist/tui/hooks/useKeybindings.d.ts +19 -0
- package/dist/tui/hooks/useKeybindings.js +87 -0
- package/dist/tui/hooks/useMutate.d.ts +22 -0
- package/dist/tui/hooks/useMutate.js +56 -0
- package/dist/tui/hooks/useNotifications.d.ts +28 -0
- package/dist/tui/hooks/useNotifications.js +70 -0
- package/dist/tui/hooks/useTranscript.d.ts +39 -0
- package/dist/tui/hooks/useTranscript.js +265 -0
- package/dist/tui/hooks/useWsClient.d.ts +29 -0
- package/dist/tui/hooks/useWsClient.js +69 -0
- package/dist/tui/index.d.ts +2 -0
- package/dist/tui/index.js +210 -0
- package/dist/tui/logic.d.ts +16 -0
- package/dist/tui/logic.js +49 -0
- package/dist/tui/render/markdown.d.ts +10 -0
- package/dist/tui/render/markdown.js +38 -0
- package/dist/tui/render/rich-blocks.d.ts +11 -0
- package/dist/tui/render/rich-blocks.js +24 -0
- package/dist/tui/ws-client.d.ts +44 -0
- package/dist/tui/ws-client.js +157 -0
- package/package.json +11 -3
- package/dist/orchestration/channel-queue.d.ts +0 -18
- package/dist/orchestration/channel-queue.js +0 -32
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
// pos: Status message and execution helper functions collection
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { createLogger } from '../core/log.js';
|
|
6
|
+
import { Icons } from '../core/icons.js';
|
|
7
|
+
import { t } from '../core/i18n.js';
|
|
6
8
|
import * as executionRegistry from '../domain/executions/registry.js';
|
|
7
9
|
import { runAgent } from '../domain/agents/index.js';
|
|
8
10
|
import { shouldAutoRunCompound, combineFinalOutputs } from '../domain/threads/auto-thread.js';
|
|
@@ -18,8 +20,8 @@ export function resolveExecutionProject({ execution, fallbackMessage }) {
|
|
|
18
20
|
export function buildExecutionStatusReport() {
|
|
19
21
|
const running = executionRegistry.getRunningExecutions();
|
|
20
22
|
if (running.length === 0)
|
|
21
|
-
return '
|
|
22
|
-
const lines = [
|
|
23
|
+
return t('status.noRunningExecutions');
|
|
24
|
+
const lines = [t('status.runningExecutions', { count: running.length })];
|
|
23
25
|
for (const record of running) {
|
|
24
26
|
const location = record.kind === 'dispatch'
|
|
25
27
|
? `${record.dispatch?.machine || '?'}:${record.dispatch?.taskId || record.id}`
|
|
@@ -55,7 +57,7 @@ export function makeFallbackNotifier(channel, statusMsg, adapter) {
|
|
|
55
57
|
if (statusMsg) {
|
|
56
58
|
try {
|
|
57
59
|
await adapter.updateMessage(statusMsg, {
|
|
58
|
-
text:
|
|
60
|
+
text: `${Icons.warning} ${fromLabel} rate limited, falling back to *${toLabel}*...`,
|
|
59
61
|
});
|
|
60
62
|
}
|
|
61
63
|
catch { }
|
|
@@ -85,8 +87,8 @@ export async function runAutoCompoundForScheduledTask({ baseResult, channel, pro
|
|
|
85
87
|
};
|
|
86
88
|
}
|
|
87
89
|
/** Build a streaming callback that aggregates assistant messages via OutputStream. */
|
|
88
|
-
export function makeStreamingMessageCallback(adapter, destination,
|
|
89
|
-
const stream = adapter.openOutputStream(destination, { threadId:
|
|
90
|
+
export function makeStreamingMessageCallback(adapter, destination, threadAnchorId = null, onMessagePosted = null, durable) {
|
|
91
|
+
const stream = adapter.openOutputStream(destination, { threadId: threadAnchorId, onMessagePosted, durable: durable ?? null });
|
|
90
92
|
const callback = (text) => stream.emitText(text);
|
|
91
93
|
callback.stream = stream;
|
|
92
94
|
return callback;
|
|
@@ -107,21 +109,21 @@ export function extractForwardedContent(message) {
|
|
|
107
109
|
}
|
|
108
110
|
return parts.length > 0 ? parts.join('\n\n') : null;
|
|
109
111
|
}
|
|
110
|
-
function buildActionElements({ channel, sessionName, isDm, includeCancel, threadId }) {
|
|
112
|
+
function buildActionElements({ channel, sessionName, isDm, includeCancel, threadId, executionId }) {
|
|
111
113
|
const elements = [];
|
|
112
114
|
if (includeCancel) {
|
|
113
115
|
elements.push({
|
|
114
116
|
type: 'button',
|
|
115
|
-
text: '
|
|
117
|
+
text: t('btn.cancel'),
|
|
116
118
|
actionId: 'status_cancel',
|
|
117
|
-
value: JSON.stringify({ channel, threadId: threadId ?? null }),
|
|
119
|
+
value: JSON.stringify({ channel, threadId: threadId ?? null, executionId: executionId ?? null }),
|
|
118
120
|
style: 'danger',
|
|
119
121
|
});
|
|
120
122
|
}
|
|
121
123
|
if (sessionName) {
|
|
122
124
|
elements.push({
|
|
123
125
|
type: 'button',
|
|
124
|
-
text: '
|
|
126
|
+
text: t('btn.resume'),
|
|
125
127
|
actionId: 'status_resume',
|
|
126
128
|
value: sessionName,
|
|
127
129
|
});
|
|
@@ -129,7 +131,7 @@ function buildActionElements({ channel, sessionName, isDm, includeCancel, thread
|
|
|
129
131
|
if (isDm) {
|
|
130
132
|
elements.push({
|
|
131
133
|
type: 'button',
|
|
132
|
-
text: '
|
|
134
|
+
text: t('btn.new'),
|
|
133
135
|
actionId: 'status_new',
|
|
134
136
|
value: channel,
|
|
135
137
|
});
|
|
@@ -156,7 +158,7 @@ function buildStatusBlocksImpl(text, template, opts) {
|
|
|
156
158
|
}
|
|
157
159
|
const statusStates = new Map();
|
|
158
160
|
function statusKey(ref) {
|
|
159
|
-
return `${ref.
|
|
161
|
+
return `${ref.conduit}:${ref.messageId}`;
|
|
160
162
|
}
|
|
161
163
|
function getOrCreateStatusState(ref) {
|
|
162
164
|
const key = statusKey(ref);
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { type Task } from '../core/task-parser.js';
|
|
2
|
+
import type { ThreadRecord } from '../core/types/thread-types.js';
|
|
3
|
+
import type { PlatformAdapter } from '../platform/index.js';
|
|
4
|
+
/** Test hook: clear in-memory dedup state to simulate a server restart. */
|
|
5
|
+
export declare function _testResetCallbackState(): void;
|
|
6
|
+
/** Child-result notice delivered into a suspended parent's pendingMessages. Echoes the
|
|
7
|
+
* delegation contract and demands acceptance verification before the result is trusted
|
|
8
|
+
* (DR-0014 L1 纠偏: verify the deliverable, never the child's self-report). */
|
|
9
|
+
export declare function buildChildResultNotice(child: ThreadRecord): string;
|
|
10
|
+
/** Refresh the status message persisted at suspension (metadata.statusMsgRef): a resumed
|
|
11
|
+
* thread's terminal summary, or the new suspension count if it suspended again. Without
|
|
12
|
+
* this, the dispatch/webhook status message reads "suspended — waiting on children"
|
|
13
|
+
* forever after the thread has finished (2026-06-11 verification finding). */
|
|
14
|
+
export declare function sealSuspendedStatusMsg(threadId: string, adapter?: PlatformAdapter | null): Promise<void>;
|
|
15
|
+
export type ResumeFn = (parentThreadId: string) => void;
|
|
16
|
+
/** Deliver a terminal child's result to its thread parent: remove the child from waitingOn,
|
|
17
|
+
* queue the result notice into pendingMessages (persistent idempotency via
|
|
18
|
+
* deliveredChildResults), and resume the parent when nothing is left to wait on.
|
|
19
|
+
* Orphan children (parent purged or already terminal) degrade to a project-report notice. */
|
|
20
|
+
export declare function notifyThreadParent(childId: string, deps?: {
|
|
21
|
+
resume?: ResumeFn;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
/** Child-task result notice delivered into a suspended manager's pendingMessages.
|
|
24
|
+
* completed → acceptance instructions (verify the deliverable, never the report);
|
|
25
|
+
* blocked → escalation instructions (the child cannot finish on its own). */
|
|
26
|
+
export declare function buildTaskResultNotice(task: Task, kind: 'completed' | 'blocked'): string;
|
|
27
|
+
/** Event-bridge entry: a task completed or got blocked — wake every manager thread waiting
|
|
28
|
+
* on it. For 'completed', the task's real status is verified on disk first: the dispatch
|
|
29
|
+
* cycle publishes task.completed loosely (thread ended ≠ task done), so the disk state is
|
|
30
|
+
* the source of truth. A rejected bogus event keeps the manager waiting; the genuine
|
|
31
|
+
* completion publishes again later. */
|
|
32
|
+
export declare function notifyTaskParentThreads(taskId: string, kind: 'completed' | 'blocked', deps?: {
|
|
33
|
+
resume?: ResumeFn;
|
|
34
|
+
}): Promise<void>;
|
|
35
|
+
/** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
|
|
36
|
+
* already-blocked children, drop missing ones, keep open ones. Closes the race window
|
|
37
|
+
* where a child task turns terminal between the suspension snapshot and the waiting
|
|
38
|
+
* persist (its event fired before anyone was listening). Also the recovery path for task
|
|
39
|
+
* children — unlike thread children, open tasks survive restarts and stay awaited. */
|
|
40
|
+
export declare function reconcileWaitingTasks(threadId: string, deps?: {
|
|
41
|
+
resume?: ResumeFn;
|
|
42
|
+
}): Promise<void>;
|
|
43
|
+
/** Register the EventBus subscribers that wake suspended manager threads on child-task
|
|
44
|
+
* terminal events (DR-0014 §8). Call once at startup, before recoverWaitingThreads. */
|
|
45
|
+
export declare function registerTaskTreeSubscribers(bus: {
|
|
46
|
+
subscribe: (type: any, fn: (e: any) => void) => unknown;
|
|
47
|
+
}): void;
|
|
48
|
+
/** Startup recovery: re-deliver results that completed while the server was down.
|
|
49
|
+
* Idempotent — safe to call repeatedly. Thread children still marked waiting whose records
|
|
50
|
+
* are gone are treated as failed (the restart already failed all in-flight running threads,
|
|
51
|
+
* so every surviving child THREAD record is terminal by the time this runs). Task children
|
|
52
|
+
* are reconciled against disk — open ones stay awaited. Returns the number
|
|
53
|
+
* of suspended parents processed. */
|
|
54
|
+
export declare function recoverWaitingThreads(deps?: {
|
|
55
|
+
resume?: ResumeFn;
|
|
56
|
+
}): Promise<number>;
|
|
57
|
+
/**
|
|
58
|
+
* Fire the completion callback for an MCP-spawned thread once it is terminal.
|
|
59
|
+
* - Non-terminal statuses (e.g. a parent that suspended via [WAIT_CHILDREN] and returned
|
|
60
|
+
* from runThread in 'waiting') are ignored — suspension is not completion.
|
|
61
|
+
* - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
|
|
62
|
+
* its channel via agentRunner.route.
|
|
63
|
+
* - Thread-agent parent (parentThreadId set): deliver into the parent thread's
|
|
64
|
+
* pendingMessages and resume it when its waitingOn empties (notifyThreadParent).
|
|
65
|
+
* Threads not spawned via thread_start (no parentSessionId) are ignored.
|
|
66
|
+
*/
|
|
67
|
+
export declare function fireThreadCallback(threadId: string): Promise<void>;
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
// input: terminal thread record (threadStore), interactive runner, outbound queue, live adapter
|
|
2
|
+
// output: fireThreadCallback / notifyThreadParent / recoverWaitingThreads / buildChildResultNotice
|
|
3
|
+
// pos: completion callback for MCP thread_start; closes the loop when a spawned thread finishes.
|
|
4
|
+
// DR-0014: thread-parent children deliver results into the parent's pendingMessages and
|
|
5
|
+
// resume the suspended parent when its last awaited child turns terminal.
|
|
6
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
|
+
import { threadStore } from '../store/thread-repo.js';
|
|
8
|
+
import { agentRunner } from './agent-runner.js';
|
|
9
|
+
import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
|
|
10
|
+
import { ctx as jobCtx } from '../domain/scheduling/job-registry.js';
|
|
11
|
+
import { resumeThread, buildThreadSummary } from '../domain/threads/runner.js';
|
|
12
|
+
import { isTerminalStatus } from '../domain/threads/tree.js';
|
|
13
|
+
import { runThreadDetached } from './thread-executor.js';
|
|
14
|
+
import { createLogger } from '../core/log.js';
|
|
15
|
+
import { scanAllTasks } from '../core/task-parser.js';
|
|
16
|
+
const log = createLogger('thread-callback');
|
|
17
|
+
// Single-fire guard for the interactive-parent wake path (in-memory; resets on restart —
|
|
18
|
+
// acceptable there because waking a chat session twice is merely noisy). The thread-parent
|
|
19
|
+
// path does NOT use this set: its idempotency is persistent, via metadata.deliveredChildResults.
|
|
20
|
+
const fired = new Set();
|
|
21
|
+
// Parents with a resume already in flight (guards the gap between scheduling the detached
|
|
22
|
+
// resume and resumeThread flipping status to 'running').
|
|
23
|
+
const resuming = new Set();
|
|
24
|
+
/** Test hook: clear in-memory dedup state to simulate a server restart. */
|
|
25
|
+
export function _testResetCallbackState() {
|
|
26
|
+
fired.clear();
|
|
27
|
+
resuming.clear();
|
|
28
|
+
}
|
|
29
|
+
/** Compose a short, agent-actionable completion notice from the final thread record. */
|
|
30
|
+
function buildNotice(threadId) {
|
|
31
|
+
const t = threadStore.get(threadId);
|
|
32
|
+
const cost = `$${(t.totalCostUsd || 0).toFixed(4)}`;
|
|
33
|
+
const last = t.steps.length ? t.steps[t.steps.length - 1].output : null;
|
|
34
|
+
const tail = t.abortReason || t.error || last || '(无输出)';
|
|
35
|
+
const summary = tail.length > 200 ? tail.slice(0, 200) + '…' : tail;
|
|
36
|
+
const label = t.templateName || t.activeAgent || 'thread';
|
|
37
|
+
return `[后台线程完成] 你启动的线程 ${threadId} (${label}) 状态=${t.status} | ${cost}\n摘要: ${summary}\n调用 thread_result("${threadId}") 查看完整产出。`;
|
|
38
|
+
}
|
|
39
|
+
/** Child-result notice delivered into a suspended parent's pendingMessages. Echoes the
|
|
40
|
+
* delegation contract and demands acceptance verification before the result is trusted
|
|
41
|
+
* (DR-0014 L1 纠偏: verify the deliverable, never the child's self-report). */
|
|
42
|
+
export function buildChildResultNotice(child) {
|
|
43
|
+
const cost = `$${(child.totalCostUsd || 0).toFixed(4)}`;
|
|
44
|
+
const label = child.templateName || child.activeAgent || 'thread';
|
|
45
|
+
const contract = child.metadata?.contract;
|
|
46
|
+
const parent = child.metadata?.parentThreadId ? threadStore.get(child.metadata.parentThreadId) : null;
|
|
47
|
+
const childCount = parent?.metadata?.childThreadIds?.length ?? 0;
|
|
48
|
+
const maxChildren = parseInt(process.env.CORTEX_THREAD_MAX_CHILDREN || '8', 10) || 8;
|
|
49
|
+
const lines = [
|
|
50
|
+
`[子线程完成] ${child.id} (${label}) 状态=${child.status} | ${cost}`,
|
|
51
|
+
];
|
|
52
|
+
if (child.abortReason)
|
|
53
|
+
lines.push(`子线程升级/中止原因: ${child.abortReason}`);
|
|
54
|
+
if (child.error)
|
|
55
|
+
lines.push(`子线程错误: ${child.error}`);
|
|
56
|
+
if (contract) {
|
|
57
|
+
lines.push(`契约: ${contract.goal}`);
|
|
58
|
+
if (contract.doneWhen)
|
|
59
|
+
lines.push(`Done when: ${contract.doneWhen}`);
|
|
60
|
+
if (contract.deliverablePath)
|
|
61
|
+
lines.push(`Deliverable: ${contract.deliverablePath}`);
|
|
62
|
+
}
|
|
63
|
+
lines.push(`完整产出: thread_result("${child.id}")${child.artifactPath ? `;artifact: ${child.artifactPath}` : ''}`);
|
|
64
|
+
lines.push('');
|
|
65
|
+
lines.push('验收要求(必须执行,不得凭子线程的汇报文本直接采信):');
|
|
66
|
+
lines.push('1. 读取 deliverable 实物,逐条核对 done_when;涉及代码的跑测试验证。');
|
|
67
|
+
lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
|
|
68
|
+
lines.push('3. 未达标 → 写出 expected/actual 差异与失败假设,用修订后的契约重新 thread_start' +
|
|
69
|
+
`(你已使用 ${childCount}/${maxChildren} 个子线程额度;额度耗尽时 thread_start 会被拒绝)。`);
|
|
70
|
+
lines.push('4. 无法判断或方向性问题 → 在 artifact 写 [ABORT: <诊断>] 升级到你的上层。');
|
|
71
|
+
return lines.join('\n');
|
|
72
|
+
}
|
|
73
|
+
/** Durable degraded-path notice to the project-report channel. */
|
|
74
|
+
async function postProjectNotice(t, text) {
|
|
75
|
+
const adapter = jobCtx.adapter;
|
|
76
|
+
if (!adapter) {
|
|
77
|
+
log.error(`no adapter; cannot post notice for ${t.id}`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const dest = { type: 'project-report', projectId: t.projectId, trigger: 'mcp-thread', sessionId: '' };
|
|
81
|
+
const queue = getOutboundQueue();
|
|
82
|
+
if (queue) {
|
|
83
|
+
await durablePost(queue, adapter, dest, { text });
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
await adapter.postMessage(dest, { text });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
|
|
90
|
+
* persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
|
|
91
|
+
* from metadata.taskId/taskProject (the reason dispatch threads must store them). */
|
|
92
|
+
function buildResumeOptions(parent) {
|
|
93
|
+
const adapter = jobCtx.adapter;
|
|
94
|
+
if (!adapter)
|
|
95
|
+
return null;
|
|
96
|
+
const m = parent.metadata;
|
|
97
|
+
const dest = m?.resumeDest === 'interactive-reply'
|
|
98
|
+
? { type: 'interactive-reply', conduit: parent.channel, sessionId: '' }
|
|
99
|
+
: { type: 'project-report', projectId: parent.projectId, trigger: m?.trigger || 'mcp-thread', sessionId: '' };
|
|
100
|
+
const extraHooks = (m?.trigger === 'task-dispatch' && m?.taskId)
|
|
101
|
+
? { onEnd: { command: 'node hooks/task-status-check.mjs', args: [m.taskProject || parent.projectId, m.taskId], timeout: 10000 } }
|
|
102
|
+
: undefined;
|
|
103
|
+
return {
|
|
104
|
+
adapter,
|
|
105
|
+
channel: parent.channel,
|
|
106
|
+
destination: dest,
|
|
107
|
+
threadAnchorId: parent.platformThreadId ?? null,
|
|
108
|
+
statusMsg: null,
|
|
109
|
+
startTime: Date.now(),
|
|
110
|
+
onProgress: null,
|
|
111
|
+
onToolUse: null,
|
|
112
|
+
extraHooks,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/** Refresh the status message persisted at suspension (metadata.statusMsgRef): a resumed
|
|
116
|
+
* thread's terminal summary, or the new suspension count if it suspended again. Without
|
|
117
|
+
* this, the dispatch/webhook status message reads "suspended — waiting on children"
|
|
118
|
+
* forever after the thread has finished (2026-06-11 verification finding). */
|
|
119
|
+
export async function sealSuspendedStatusMsg(threadId, adapter) {
|
|
120
|
+
const t = threadStore.get(threadId);
|
|
121
|
+
const ref = t?.metadata?.statusMsgRef;
|
|
122
|
+
if (!t || !ref)
|
|
123
|
+
return;
|
|
124
|
+
const a = adapter ?? jobCtx.adapter;
|
|
125
|
+
if (!a)
|
|
126
|
+
return;
|
|
127
|
+
const totalNumTurns = t.steps.reduce((acc, st) => acc + (st.numTurns || 0), 0);
|
|
128
|
+
const text = buildThreadSummary({ thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null });
|
|
129
|
+
await a.updateMessage(ref, { text }).catch((e) => log.warn(`seal status msg ${threadId}: ${e.message}`));
|
|
130
|
+
}
|
|
131
|
+
const defaultResume = (parentId) => {
|
|
132
|
+
const parent = threadStore.get(parentId);
|
|
133
|
+
if (!parent) {
|
|
134
|
+
resuming.delete(parentId);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
const opts = buildResumeOptions(parent);
|
|
138
|
+
if (!opts) {
|
|
139
|
+
resuming.delete(parentId);
|
|
140
|
+
log.error(`cannot resume suspended parent ${parentId}: no adapter`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
log.info(`resuming suspended parent ${parentId} (all awaited children terminal)`);
|
|
144
|
+
runThreadDetached(parentId, opts, {
|
|
145
|
+
run: (tid, o) => resumeThread(tid, o),
|
|
146
|
+
onSettled: async (tid) => {
|
|
147
|
+
resuming.delete(tid);
|
|
148
|
+
// Refresh the suspension-era status message (terminal summary or new wait count).
|
|
149
|
+
await sealSuspendedStatusMsg(tid).catch(() => { });
|
|
150
|
+
// Cascade: when the resumed parent itself terminates (or suspends again and later
|
|
151
|
+
// terminates), its own parent gets notified through the same callback chain.
|
|
152
|
+
await fireThreadCallback(tid).catch((e) => log.error(`cascade callback ${tid}: ${e.message}`));
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
/** Resume `parentId` if (and only if) it is suspended with nothing left to wait on —
|
|
157
|
+
* both thread children (waitingOn) and task children (waitingOnTasks, DR-0014 §8). */
|
|
158
|
+
function maybeResumeParent(parentId, resume) {
|
|
159
|
+
if (resuming.has(parentId))
|
|
160
|
+
return;
|
|
161
|
+
const parent = threadStore.get(parentId);
|
|
162
|
+
if (!parent || parent.status !== 'waiting')
|
|
163
|
+
return;
|
|
164
|
+
if (parent.metadata?.waitingOn?.length)
|
|
165
|
+
return;
|
|
166
|
+
if (parent.metadata?.waitingOnTasks?.length)
|
|
167
|
+
return;
|
|
168
|
+
resuming.add(parentId);
|
|
169
|
+
(resume ?? defaultResume)(parentId);
|
|
170
|
+
}
|
|
171
|
+
/** Deliver a terminal child's result to its thread parent: remove the child from waitingOn,
|
|
172
|
+
* queue the result notice into pendingMessages (persistent idempotency via
|
|
173
|
+
* deliveredChildResults), and resume the parent when nothing is left to wait on.
|
|
174
|
+
* Orphan children (parent purged or already terminal) degrade to a project-report notice. */
|
|
175
|
+
export async function notifyThreadParent(childId, deps = {}) {
|
|
176
|
+
const child = threadStore.get(childId);
|
|
177
|
+
if (!child)
|
|
178
|
+
return;
|
|
179
|
+
const parentId = child.metadata?.parentThreadId;
|
|
180
|
+
if (!parentId)
|
|
181
|
+
return;
|
|
182
|
+
const parent = threadStore.get(parentId);
|
|
183
|
+
if (!parent || isTerminalStatus(parent.status)) {
|
|
184
|
+
log.info(`orphan child ${childId}: parent ${parentId} ${parent ? parent.status : 'purged'} — degrading to project notice`);
|
|
185
|
+
await postProjectNotice(child, buildNotice(childId));
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
let delivered = false;
|
|
189
|
+
await threadStore.mutate(parentId, (t) => {
|
|
190
|
+
const m = (t.metadata ??= {});
|
|
191
|
+
const waiting = m.waitingOn ?? [];
|
|
192
|
+
const idx = waiting.indexOf(childId);
|
|
193
|
+
if (idx >= 0) {
|
|
194
|
+
waiting.splice(idx, 1);
|
|
195
|
+
m.waitingOn = waiting;
|
|
196
|
+
}
|
|
197
|
+
const alreadyDelivered = (m.deliveredChildResults ?? []).includes(childId);
|
|
198
|
+
if (alreadyDelivered)
|
|
199
|
+
return;
|
|
200
|
+
delivered = true;
|
|
201
|
+
(m.deliveredChildResults ??= []).push(childId);
|
|
202
|
+
if (!Array.isArray(m.pendingMessages))
|
|
203
|
+
m.pendingMessages = [];
|
|
204
|
+
if (m.pendingMessages.length >= 10)
|
|
205
|
+
m.pendingMessages.shift();
|
|
206
|
+
m.pendingMessages.push(buildChildResultNotice(child));
|
|
207
|
+
});
|
|
208
|
+
// Failure visibility (tree noise reduction trades per-node completion spam for this):
|
|
209
|
+
// failed/aborted children additionally surface on the project-report channel.
|
|
210
|
+
if (delivered && (child.status === 'failed' || child.status === 'aborted')) {
|
|
211
|
+
await postProjectNotice(child, buildNotice(childId)).catch(() => { });
|
|
212
|
+
}
|
|
213
|
+
if (delivered)
|
|
214
|
+
maybeResumeParent(parentId, deps.resume);
|
|
215
|
+
}
|
|
216
|
+
// --- Task-children bridge (DR-0014 §8: resident manager waits on child TASKS) ---
|
|
217
|
+
/** Child-task result notice delivered into a suspended manager's pendingMessages.
|
|
218
|
+
* completed → acceptance instructions (verify the deliverable, never the report);
|
|
219
|
+
* blocked → escalation instructions (the child cannot finish on its own). */
|
|
220
|
+
export function buildTaskResultNotice(task, kind) {
|
|
221
|
+
const lines = [];
|
|
222
|
+
if (kind === 'completed') {
|
|
223
|
+
lines.push(`[子任务完成] #${task.id} ${task.text}`);
|
|
224
|
+
if (task.done_when)
|
|
225
|
+
lines.push(`Done when: ${task.done_when}`);
|
|
226
|
+
if (task.completed_note)
|
|
227
|
+
lines.push(`完成备注: ${task.completed_note}`);
|
|
228
|
+
lines.push('');
|
|
229
|
+
lines.push('验收要求(必须执行,不得凭完成备注直接采信):');
|
|
230
|
+
lines.push('1. 读取实际产出(代码/文档/实验记录),逐条核对 done_when;涉及代码的跑测试验证。');
|
|
231
|
+
lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
|
|
232
|
+
lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再 [WAIT_CHILDREN]。`);
|
|
233
|
+
lines.push('4. 方向性问题 → 在 artifact 写 [ABORT: <诊断>] 升级。');
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
lines.push(`[子任务被阻塞 — 升级信号] #${task.id} ${task.text}`);
|
|
237
|
+
lines.push(`阻塞原因: ${task.blocked_by || '(未记录)'}`);
|
|
238
|
+
lines.push('');
|
|
239
|
+
lines.push('这是子任务的升级:它无法自行完成。你必须处理:');
|
|
240
|
+
lines.push('1. 诊断原因(读它的产出/日志;too-big 类原因 = 你当初的分解需要修订)。');
|
|
241
|
+
lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再 [WAIT_CHILDREN]。');
|
|
242
|
+
lines.push('3. 超出你的职权或方向性问题 → 在 artifact 写 [ABORT: <诊断>] 向上升级。');
|
|
243
|
+
}
|
|
244
|
+
return lines.join('\n');
|
|
245
|
+
}
|
|
246
|
+
/** Disk-fresh read of one task (zero-dependency core parser — consistent with the
|
|
247
|
+
* suspension snapshot, immune to taskStore cache staleness). */
|
|
248
|
+
function readTaskFromDisk(project, taskId) {
|
|
249
|
+
try {
|
|
250
|
+
return scanAllTasks(project).find((t) => t.id === taskId) ?? null;
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
/** Deliver one child-task result to one waiting manager thread. Returns true if delivered.
|
|
257
|
+
* Idempotency rides the same persistent deliveredChildResults array as thread children
|
|
258
|
+
* (4-hex task ids cannot collide with thr_ thread ids). */
|
|
259
|
+
async function deliverTaskResult(parentThreadId, task, kind, deps) {
|
|
260
|
+
let delivered = false;
|
|
261
|
+
await threadStore.mutate(parentThreadId, (t) => {
|
|
262
|
+
const m = (t.metadata ??= {});
|
|
263
|
+
const waiting = m.waitingOnTasks ?? [];
|
|
264
|
+
const idx = waiting.indexOf(task.id);
|
|
265
|
+
if (idx >= 0) {
|
|
266
|
+
waiting.splice(idx, 1);
|
|
267
|
+
m.waitingOnTasks = waiting;
|
|
268
|
+
}
|
|
269
|
+
if ((m.deliveredChildResults ?? []).includes(task.id))
|
|
270
|
+
return;
|
|
271
|
+
delivered = true;
|
|
272
|
+
(m.deliveredChildResults ??= []).push(task.id);
|
|
273
|
+
if (!Array.isArray(m.pendingMessages))
|
|
274
|
+
m.pendingMessages = [];
|
|
275
|
+
if (m.pendingMessages.length >= 10)
|
|
276
|
+
m.pendingMessages.shift();
|
|
277
|
+
m.pendingMessages.push(buildTaskResultNotice(task, kind));
|
|
278
|
+
});
|
|
279
|
+
if (delivered)
|
|
280
|
+
maybeResumeParent(parentThreadId, deps.resume);
|
|
281
|
+
return delivered;
|
|
282
|
+
}
|
|
283
|
+
/** Event-bridge entry: a task completed or got blocked — wake every manager thread waiting
|
|
284
|
+
* on it. For 'completed', the task's real status is verified on disk first: the dispatch
|
|
285
|
+
* cycle publishes task.completed loosely (thread ended ≠ task done), so the disk state is
|
|
286
|
+
* the source of truth. A rejected bogus event keeps the manager waiting; the genuine
|
|
287
|
+
* completion publishes again later. */
|
|
288
|
+
export async function notifyTaskParentThreads(taskId, kind, deps = {}) {
|
|
289
|
+
for (const parent of threadStore.getAll()) {
|
|
290
|
+
if (parent.status !== 'waiting')
|
|
291
|
+
continue;
|
|
292
|
+
if (!parent.metadata?.waitingOnTasks?.includes(taskId))
|
|
293
|
+
continue;
|
|
294
|
+
const project = parent.metadata?.taskProject || parent.projectId;
|
|
295
|
+
const task = readTaskFromDisk(project, taskId);
|
|
296
|
+
if (!task) {
|
|
297
|
+
log.warn(`task ${taskId} not found on disk for waiting manager ${parent.id} — leaving to reconcile/recovery`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (kind === 'completed' && task.status !== 'done') {
|
|
301
|
+
log.info(`ignoring loose task.completed for ${taskId} (disk status=${task.status})`);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (kind === 'blocked' && !task.blocked_by) {
|
|
305
|
+
log.info(`ignoring stale task.blocked for ${taskId} (no blocked_by on disk)`);
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
await deliverTaskResult(parent.id, task, kind, deps);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
|
|
312
|
+
* already-blocked children, drop missing ones, keep open ones. Closes the race window
|
|
313
|
+
* where a child task turns terminal between the suspension snapshot and the waiting
|
|
314
|
+
* persist (its event fired before anyone was listening). Also the recovery path for task
|
|
315
|
+
* children — unlike thread children, open tasks survive restarts and stay awaited. */
|
|
316
|
+
export async function reconcileWaitingTasks(threadId, deps = {}) {
|
|
317
|
+
const thread = threadStore.get(threadId);
|
|
318
|
+
if (!thread || thread.status !== 'waiting')
|
|
319
|
+
return;
|
|
320
|
+
const ids = [...(thread.metadata?.waitingOnTasks ?? [])];
|
|
321
|
+
if (!ids.length) {
|
|
322
|
+
maybeResumeParent(threadId, deps.resume);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const project = thread.metadata?.taskProject || thread.projectId;
|
|
326
|
+
for (const taskId of ids) {
|
|
327
|
+
const task = readTaskFromDisk(project, taskId);
|
|
328
|
+
if (!task) {
|
|
329
|
+
await threadStore.mutate(threadId, (t) => {
|
|
330
|
+
const m = t.metadata;
|
|
331
|
+
m.waitingOnTasks = (m.waitingOnTasks ?? []).filter((id) => id !== taskId);
|
|
332
|
+
if (!Array.isArray(m.pendingMessages))
|
|
333
|
+
m.pendingMessages = [];
|
|
334
|
+
m.pendingMessages.push(`[子任务丢失] #${taskId} 已不在 TASKS.yaml(可能被归档或删除),按失败处理。`);
|
|
335
|
+
});
|
|
336
|
+
log.warn(`reconcile: dropped missing task ${taskId} from waiting thread ${threadId}`);
|
|
337
|
+
}
|
|
338
|
+
else if (task.status === 'done') {
|
|
339
|
+
await deliverTaskResult(threadId, task, 'completed', deps);
|
|
340
|
+
}
|
|
341
|
+
else if (task.blocked_by) {
|
|
342
|
+
await deliverTaskResult(threadId, task, 'blocked', deps);
|
|
343
|
+
}
|
|
344
|
+
// open/pending and unblocked → keep waiting (tasks survive restarts).
|
|
345
|
+
}
|
|
346
|
+
maybeResumeParent(threadId, deps.resume);
|
|
347
|
+
}
|
|
348
|
+
/** Register the EventBus subscribers that wake suspended manager threads on child-task
|
|
349
|
+
* terminal events (DR-0014 §8). Call once at startup, before recoverWaitingThreads. */
|
|
350
|
+
export function registerTaskTreeSubscribers(bus) {
|
|
351
|
+
bus.subscribe('task.completed', (e) => {
|
|
352
|
+
void notifyTaskParentThreads(e.taskId, 'completed').catch((err) => log.error(`task.completed bridge: ${err.message}`));
|
|
353
|
+
});
|
|
354
|
+
bus.subscribe('task.blocked', (e) => {
|
|
355
|
+
void notifyTaskParentThreads(e.taskId, 'blocked').catch((err) => log.error(`task.blocked bridge: ${err.message}`));
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
/** Startup recovery: re-deliver results that completed while the server was down.
|
|
359
|
+
* Idempotent — safe to call repeatedly. Thread children still marked waiting whose records
|
|
360
|
+
* are gone are treated as failed (the restart already failed all in-flight running threads,
|
|
361
|
+
* so every surviving child THREAD record is terminal by the time this runs). Task children
|
|
362
|
+
* are reconciled against disk — open ones stay awaited. Returns the number
|
|
363
|
+
* of suspended parents processed. */
|
|
364
|
+
export async function recoverWaitingThreads(deps = {}) {
|
|
365
|
+
let recovered = 0;
|
|
366
|
+
for (const parent of threadStore.getAll()) {
|
|
367
|
+
if (parent.status !== 'waiting')
|
|
368
|
+
continue;
|
|
369
|
+
const m = parent.metadata;
|
|
370
|
+
if (!m?.waitingOn?.length && !m?.childThreadIds?.length && !m?.waitingOnTasks?.length)
|
|
371
|
+
continue; // legacy waiting — not ours
|
|
372
|
+
recovered++;
|
|
373
|
+
for (const childId of [...(m.waitingOn ?? [])]) {
|
|
374
|
+
const child = threadStore.get(childId);
|
|
375
|
+
if (!child) {
|
|
376
|
+
await threadStore.mutate(parent.id, (t) => {
|
|
377
|
+
const meta = t.metadata;
|
|
378
|
+
meta.waitingOn = (meta.waitingOn ?? []).filter((id) => id !== childId);
|
|
379
|
+
if (!Array.isArray(meta.pendingMessages))
|
|
380
|
+
meta.pendingMessages = [];
|
|
381
|
+
meta.pendingMessages.push(`[子线程丢失] ${childId} 的记录已不存在(可能被清理),按失败处理。`);
|
|
382
|
+
});
|
|
383
|
+
log.warn(`recover: dropped missing child ${childId} from waiting parent ${parent.id}`);
|
|
384
|
+
}
|
|
385
|
+
else if (isTerminalStatus(child.status)) {
|
|
386
|
+
await notifyThreadParent(childId, deps);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
// Task children: reconcile against disk (already-done/blocked delivered, missing
|
|
390
|
+
// dropped, open kept — tasks survive restarts). Ends with its own resume check, which
|
|
391
|
+
// also covers the crash-after-last-delivery-before-resume window and the
|
|
392
|
+
// missing-child branch above (neither resumes by itself).
|
|
393
|
+
await reconcileWaitingTasks(parent.id, deps);
|
|
394
|
+
}
|
|
395
|
+
if (recovered > 0)
|
|
396
|
+
log.info(`recovered ${recovered} suspended parent thread(s)`);
|
|
397
|
+
return recovered;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Fire the completion callback for an MCP-spawned thread once it is terminal.
|
|
401
|
+
* - Non-terminal statuses (e.g. a parent that suspended via [WAIT_CHILDREN] and returned
|
|
402
|
+
* from runThread in 'waiting') are ignored — suspension is not completion.
|
|
403
|
+
* - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
|
|
404
|
+
* its channel via agentRunner.route.
|
|
405
|
+
* - Thread-agent parent (parentThreadId set): deliver into the parent thread's
|
|
406
|
+
* pendingMessages and resume it when its waitingOn empties (notifyThreadParent).
|
|
407
|
+
* Threads not spawned via thread_start (no parentSessionId) are ignored.
|
|
408
|
+
*/
|
|
409
|
+
export async function fireThreadCallback(threadId) {
|
|
410
|
+
const t = threadStore.get(threadId);
|
|
411
|
+
if (!t)
|
|
412
|
+
return;
|
|
413
|
+
if (!isTerminalStatus(t.status)) {
|
|
414
|
+
// Suspension is not completion — but it IS the moment to close the task-side race
|
|
415
|
+
// window: a child task that turned terminal between the suspension snapshot and the
|
|
416
|
+
// waiting persist fired its event before anyone was listening. Sweep disk state now.
|
|
417
|
+
// (All detached run paths — webhook start, resume — settle through this callback.)
|
|
418
|
+
if (t.status === 'waiting' && t.metadata?.waitingOnTasks?.length) {
|
|
419
|
+
await reconcileWaitingTasks(threadId).catch((e) => log.error(`reconcile ${threadId}: ${e.message}`));
|
|
420
|
+
}
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
const m = t.metadata;
|
|
424
|
+
if (!m?.parentSessionId)
|
|
425
|
+
return; // not agent-spawned → nobody to notify
|
|
426
|
+
// Thread-agent parent → persistent-idempotent delivery into the parent thread.
|
|
427
|
+
if (m.parentThreadId) {
|
|
428
|
+
await notifyThreadParent(threadId);
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
// Interactive parent → wake its session (single-fire, in-memory guard).
|
|
432
|
+
if (fired.has(threadId))
|
|
433
|
+
return;
|
|
434
|
+
fired.add(threadId);
|
|
435
|
+
const notice = buildNotice(threadId);
|
|
436
|
+
const adapter = jobCtx.adapter;
|
|
437
|
+
if (m.parentChannel) {
|
|
438
|
+
if (!adapter) {
|
|
439
|
+
log.error(`no adapter; cannot wake parent for ${threadId}`);
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const channel = m.parentChannel;
|
|
443
|
+
const message = {
|
|
444
|
+
ref: { conduit: channel, messageId: `cb_${threadId}_${Date.now()}` },
|
|
445
|
+
text: notice,
|
|
446
|
+
senderId: 'cortex-thread-callback',
|
|
447
|
+
isBot: false,
|
|
448
|
+
kind: 'user',
|
|
449
|
+
raw: { source: 'thread-callback', threadId },
|
|
450
|
+
};
|
|
451
|
+
log.info(`waking parent session on ${channel} for thread ${threadId}`);
|
|
452
|
+
await agentRunner.route({
|
|
453
|
+
message,
|
|
454
|
+
channel,
|
|
455
|
+
adapter,
|
|
456
|
+
threadAnchorId: null,
|
|
457
|
+
hasFiles: false,
|
|
458
|
+
userMessage: notice,
|
|
459
|
+
agentMessage: notice,
|
|
460
|
+
});
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
// No channel → durable notice to the project-report channel.
|
|
464
|
+
await postProjectNotice(t, notice);
|
|
465
|
+
}
|
|
@@ -1,12 +1,33 @@
|
|
|
1
1
|
import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
|
|
2
|
+
import type { RunThreadOptions } from '../core/types/thread-types.js';
|
|
2
3
|
type Enqueuer = (channel: string, fn: () => Promise<void>) => boolean;
|
|
3
4
|
type Tracker = (delta: number) => void;
|
|
4
5
|
type Executor = (ctx: ThreadExecCtx) => Promise<void>;
|
|
6
|
+
/** Run a thread fire-and-forget while holding the daemon busy gate for the ENTIRE pipeline.
|
|
7
|
+
* The Slack `!thread` path (ThreadExecutor.route), the scheduled-task path, and the task-dispatch
|
|
8
|
+
* path all bracket runThread with trackPendingTask(±1). The MCP `thread_start` webhook path did
|
|
9
|
+
* not — so a background thread was invisible to the busy/idle gate, and a deploy/restart deferred
|
|
10
|
+
* during the orchestrating session's turn would fire on the next idle and SIGTERM app.ts
|
|
11
|
+
* mid-thread, stamping it "Interrupted by server restart". This helper closes that gap.
|
|
12
|
+
*
|
|
13
|
+
* track(+1) is synchronous so the daemon observes `busy` before it can act on any idle. The gate
|
|
14
|
+
* is held across BOTH the run AND the onSettled callback: onSettled (the MCP completion callback)
|
|
15
|
+
* may wake the parent agent for a full LLM turn, and `track(-1)` synchronously emits IPC `idle`.
|
|
16
|
+
* If we released the gate before awaiting onSettled, a deferred restart would fire mid-callback and
|
|
17
|
+
* SIGTERM app.ts, dropping the proactive completion notification. So we await onSettled first, then
|
|
18
|
+
* release. track(-1) lives in an inner `finally` so the gate never leaks. The thread runs detached:
|
|
19
|
+
* errors are logged (the caller already returned the threadId to the MCP client, which polls
|
|
20
|
+
* thread_status). `deps` is injectable for unit tests. */
|
|
21
|
+
export declare function runThreadDetached(threadId: string, runOpts: RunThreadOptions, deps?: {
|
|
22
|
+
run?: (id: string, opts: RunThreadOptions) => Promise<unknown>;
|
|
23
|
+
track?: Tracker;
|
|
24
|
+
onSettled?: (threadId: string) => void | Promise<void>;
|
|
25
|
+
}): void;
|
|
5
26
|
export interface ThreadExecCtx {
|
|
6
27
|
message: IncomingMessage;
|
|
7
28
|
channel: string;
|
|
8
29
|
adapter: PlatformAdapter;
|
|
9
|
-
|
|
30
|
+
threadAnchorId: string | null;
|
|
10
31
|
hasFiles: boolean;
|
|
11
32
|
agentMessage: string;
|
|
12
33
|
threadAddMatch: RegExpMatchArray | null;
|