@cortex-agent/server 2026.5.25 → 2026.6.11
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 +301 -29
- package/dist/core/icons.d.ts +68 -0
- package/dist/core/icons.js +67 -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/status-format.js +3 -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/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 +120 -10
- package/dist/domain/scheduling/schedule-command.js +16 -15
- 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/install-cli.d.ts +7 -0
- package/dist/domain/system/install-cli.js +106 -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.js +26 -0
- 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 +15 -1
- package/dist/domain/threads/prompt-builder.js +41 -2
- 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 +94 -5
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +122 -12
- package/dist/entry/feishu-login.d.ts +28 -0
- package/dist/entry/feishu-login.js +218 -0
- package/dist/entry/init.d.ts +25 -2
- package/dist/entry/init.js +211 -64
- 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 +48 -17
- 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.d.ts +6 -0
- package/dist/orchestration/interactions/update-prompt.js +100 -0
- package/dist/orchestration/lifecycle.d.ts +4 -4
- package/dist/orchestration/lifecycle.js +24 -22
- package/dist/orchestration/orchestrator.d.ts +1 -1
- package/dist/orchestration/routing/commands/cancel.js +39 -47
- package/dist/orchestration/routing/commands/channel.js +24 -11
- package/dist/orchestration/routing/commands/cost.js +2 -1
- package/dist/orchestration/routing/commands/device.js +3 -2
- package/dist/orchestration/routing/commands/dispatch.js +6 -5
- package/dist/orchestration/routing/commands/index.d.ts +1 -1
- package/dist/orchestration/routing/commands/index.js +11 -10
- package/dist/orchestration/routing/commands/mode.js +19 -18
- package/dist/orchestration/routing/commands/nvtop.js +10 -9
- package/dist/orchestration/routing/commands/sendfile.js +7 -6
- package/dist/orchestration/routing/commands/session.d.ts +1 -1
- package/dist/orchestration/routing/commands/session.js +17 -33
- package/dist/orchestration/routing/commands/tail.js +4 -3
- package/dist/orchestration/routing/commands/task.js +4 -3
- package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
- 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 +7 -6
- 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 +3 -2
- 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.js +95 -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
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// input: domain/threads, mode-manager, hook-runner, handles
|
|
2
|
-
// output: runThread / continueThread / buildThreadSummary
|
|
2
|
+
// output: runThread / continueThread / resumeThread / buildThreadSummary
|
|
3
3
|
// pos: runtime execution engine for the Thread system
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { threadStore } from '../../store/thread-repo.js';
|
|
6
|
-
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, detectAbortMarker,
|
|
6
|
+
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, detectAbortMarker, detectWaitMarker, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
|
|
7
7
|
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
8
|
+
import { Icons } from '../../core/icons.js';
|
|
8
9
|
import { closeSessionsByPrefix } from '../agents/index.js';
|
|
9
10
|
import * as executionRegistry from '../executions/registry.js';
|
|
10
11
|
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
@@ -22,13 +23,13 @@ function initThreadContext(threadId, opts) {
|
|
|
22
23
|
const thread = threadStore.get(threadId);
|
|
23
24
|
if (!thread)
|
|
24
25
|
throw new Error(`Thread not found: ${threadId}`);
|
|
25
|
-
const isDefault = isDefaultThread(threadId);
|
|
26
26
|
const template = thread.templateName ? (getTemplate(thread.templateName) || null) : null;
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
|
|
31
|
-
|
|
27
|
+
// Aggregate agent output into an OutputStream. The caller supplies the Destination
|
|
28
|
+
// (interactive-reply or project-report).
|
|
29
|
+
// Pass the full statusMsg as anchorRef so CompositeAdapter can resolve a per-platform
|
|
30
|
+
// thread anchor for each sub-stream (a Slack ts must not be used as a Feishu message_id).
|
|
31
|
+
const stream = opts.adapter.openOutputStream(opts.destination, { threadId: opts.threadAnchorId, anchorRef: opts.statusMsg });
|
|
32
|
+
return { thread, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0 };
|
|
32
33
|
}
|
|
33
34
|
/** Resolve next step, post boundary notifications, update the status message.
|
|
34
35
|
* Returns null if the loop should break (cancelled, no next step). */
|
|
@@ -51,12 +52,12 @@ async function resolveAndNotifyStep(threadId, ctx, opts) {
|
|
|
51
52
|
if (ctx.stream && multiAgent && !isFirstStep) {
|
|
52
53
|
const prevStep = threadRecord.steps[threadRecord.steps.length - 1];
|
|
53
54
|
const prevLabel = prevStep ? formatAgentStageLabel(prevStep.agentSlotId, prevStep.stage) : '?';
|
|
54
|
-
ctx.stream.emitText(
|
|
55
|
+
ctx.stream.emitText(`${Icons.arrowRight} Step ${threadRecord.currentStepIndex + 1}: *${label}* starting (prev: ${prevLabel})`);
|
|
55
56
|
}
|
|
56
57
|
// Update status message (multi-agent thread format; skip if caller provides onProgress)
|
|
57
58
|
if (ctx.stream && multiAgent && !opts.onProgress) {
|
|
58
59
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
59
|
-
const statusText =
|
|
60
|
+
const statusText = `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`;
|
|
60
61
|
try {
|
|
61
62
|
if (opts.statusMsg) {
|
|
62
63
|
await opts.adapter.updateMessage(opts.statusMsg, { text: statusText });
|
|
@@ -73,20 +74,10 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
73
74
|
const slot = threadStore.get(threadId).agents[agentSlotId];
|
|
74
75
|
// Build prompt for this step — pass the stage so stage-aware agents send their stage-specific
|
|
75
76
|
// prompt (and, in incremental mode on session resume, skip directive + preamble + auto previousOutput).
|
|
76
|
-
const prompt = buildStepPrompt(threadId, agentConfig, stage
|
|
77
|
-
// Determine session configuration
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (ctx.isDefault) {
|
|
81
|
-
// Default template: use existing channel session (backward compatible)
|
|
82
|
-
sessionId = opts.existingSessionId;
|
|
83
|
-
sessionKey = null; // falls back to channel key in claude-bridge
|
|
84
|
-
}
|
|
85
|
-
else {
|
|
86
|
-
// Multi-agent: use thread-specific session key
|
|
87
|
-
sessionKey = getSessionKey(threadId, agentSlotId);
|
|
88
|
-
sessionId = slot.persistSession ? slot.sessionId : null;
|
|
89
|
-
}
|
|
77
|
+
const prompt = buildStepPrompt(threadId, agentConfig, stage);
|
|
78
|
+
// Determine session configuration — thread steps use a thread-scoped session key.
|
|
79
|
+
const sessionKey = getSessionKey(threadId, agentSlotId);
|
|
80
|
+
const sessionId = slot.persistSession ? slot.sessionId : null;
|
|
90
81
|
// Resolve profile: agents with a hardcoded profile always use their own declaration.
|
|
91
82
|
// metadata.profileOverride only applies to __active__ agents (default/main/scheduler-main),
|
|
92
83
|
// letting scheduler/dispatch inject a concrete profile without overriding research-pipeline agents.
|
|
@@ -97,7 +88,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
97
88
|
const executionKind = ctx.meta?.trigger === 'task-dispatch' ? 'dispatch'
|
|
98
89
|
: ctx.meta?.trigger === 'scheduled' ? 'scheduled'
|
|
99
90
|
: 'local';
|
|
100
|
-
const executionTrigger = ctx.meta?.trigger ||
|
|
91
|
+
const executionTrigger = ctx.meta?.trigger || 'thread-step';
|
|
101
92
|
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
102
93
|
const execution = executionRegistry.startLocalExecution({
|
|
103
94
|
kind: executionKind,
|
|
@@ -107,7 +98,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
107
98
|
backend: getActiveBackend(),
|
|
108
99
|
billingMode: getClaudeMode(),
|
|
109
100
|
sessionId,
|
|
110
|
-
label:
|
|
101
|
+
label: `[${label}] ${prompt.substring(0, 40)}`,
|
|
111
102
|
scheduleTaskId: ctx.meta?.scheduleTaskId || null,
|
|
112
103
|
threadId,
|
|
113
104
|
agentSlotId,
|
|
@@ -115,7 +106,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
115
106
|
return {
|
|
116
107
|
agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
|
|
117
108
|
prompt, sessionId, sessionKey,
|
|
118
|
-
sessionName:
|
|
109
|
+
sessionName: await sessionStore.generateSessionName(),
|
|
119
110
|
profileName, execution,
|
|
120
111
|
stepStartTime: new Date().toISOString(),
|
|
121
112
|
};
|
|
@@ -128,18 +119,14 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
128
119
|
const slot = threadRecord.agents[agentSlotId];
|
|
129
120
|
const stream = ctx.stream;
|
|
130
121
|
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
131
|
-
//
|
|
132
|
-
// - default: pass through from opts (app.ts OutputStream)
|
|
133
|
-
// - non-default: aggregate into thread-runner's stream; prefix only for multi-agent
|
|
122
|
+
// Aggregate assistant output into the thread-runner's OutputStream; prefix only for multi-agent.
|
|
134
123
|
const slotPrefix = multiAgent ? `*[${label}]*` : null;
|
|
135
|
-
const baseAssistantMessage = stream
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
// Tool trace (env-gated): caller-supplied onToolUse takes precedence (default-thread path —
|
|
139
|
-
// agent-runner owns the stream). Otherwise build one bound to the runner's own stream.
|
|
124
|
+
const baseAssistantMessage = (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); };
|
|
125
|
+
// Tool trace (env-gated): caller-supplied onToolUse takes precedence. Otherwise build one bound
|
|
126
|
+
// to the runner's own stream.
|
|
140
127
|
const callerOnToolUse = opts.onToolUse ?? null;
|
|
141
128
|
const toolTrace = callerOnToolUse ? null : createToolTrace(stream, { slotPrefix });
|
|
142
|
-
const onAssistantMessage = toolTrace
|
|
129
|
+
const onAssistantMessage = toolTrace
|
|
143
130
|
? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
|
|
144
131
|
: baseAssistantMessage;
|
|
145
132
|
const onToolUse = callerOnToolUse
|
|
@@ -147,12 +134,12 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
147
134
|
// onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
|
|
148
135
|
// fallback to thread-specific status format for multi-agent pipelines
|
|
149
136
|
const onProgress = opts.onProgress
|
|
150
|
-
|| (
|
|
137
|
+
|| (multiAgent
|
|
151
138
|
? (progress) => {
|
|
152
139
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
153
140
|
if (opts.statusMsg) {
|
|
154
141
|
opts.adapter.updateMessage(opts.statusMsg, {
|
|
155
|
-
text:
|
|
142
|
+
text: `${Icons.processing} Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* (${progress?.num_turns || '?'} turns) | ${Icons.stopwatch} ${formatDurationCompact(elapsed)}`,
|
|
156
143
|
}).catch(() => { });
|
|
157
144
|
}
|
|
158
145
|
}
|
|
@@ -177,15 +164,16 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
|
|
|
177
164
|
project: threadStore.get(threadId)?.projectId,
|
|
178
165
|
trigger: meta?.trigger || undefined,
|
|
179
166
|
threadId,
|
|
180
|
-
|
|
167
|
+
threadDepth: meta?.depth ?? 0,
|
|
168
|
+
useCoreMcp: true,
|
|
181
169
|
sessionName: stepCtx.sessionName,
|
|
182
170
|
claudeAgent: agentConfig.claudeAgent || null,
|
|
183
171
|
systemPrompt: agentConfig.systemPrompt ? resolveSystemVars(agentConfig.systemPrompt) : null,
|
|
184
172
|
outputStyle: agentConfig.outputStyle || null,
|
|
185
173
|
tools: agentConfig.tools || null,
|
|
186
174
|
pluginDirs: agentConfig.pluginDirs || null,
|
|
187
|
-
onFallback:
|
|
188
|
-
isUserInitiated:
|
|
175
|
+
onFallback: null,
|
|
176
|
+
isUserInitiated: false,
|
|
189
177
|
onAssistantMessage: callbacks.onAssistantMessage,
|
|
190
178
|
onProgress: callbacks.onProgress,
|
|
191
179
|
onToolUse: callbacks.onToolUse,
|
|
@@ -193,31 +181,34 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
|
|
|
193
181
|
onAskUserQuestion: opts.onAskUserQuestion ?? null,
|
|
194
182
|
});
|
|
195
183
|
// Track handle for cancellation
|
|
196
|
-
runningExecutions.register(
|
|
184
|
+
runningExecutions.register({
|
|
197
185
|
threadId,
|
|
198
186
|
channel: opts.channel,
|
|
199
187
|
agentSlotId: stepCtx.agentSlotId,
|
|
200
188
|
executionId: stepCtx.execution.id,
|
|
189
|
+
kind: stepCtx.execution.kind,
|
|
201
190
|
kill: () => handle.kill(),
|
|
202
191
|
backend: getActiveBackend(),
|
|
203
192
|
agentProcess: handle.agentProcess,
|
|
204
193
|
sessionId: handle.sessionId,
|
|
205
194
|
});
|
|
206
195
|
try {
|
|
196
|
+
// On success the registry entry stays live until recordStepOutcome tears it down
|
|
197
|
+
// (so the agent.completed event fires there). On error we tear down here.
|
|
207
198
|
return await handle.promise;
|
|
208
199
|
}
|
|
209
200
|
catch (agentError) {
|
|
210
|
-
// Finalize execution as failed
|
|
201
|
+
// Finalize execution as failed (persistent record + registry + agent.failed event)
|
|
202
|
+
// so it doesn't stay stuck in 'running' and the dashboards see a balanced lifecycle.
|
|
211
203
|
const failDurationS = (Date.now() - new Date(stepStartTime).getTime()) / 1000;
|
|
212
|
-
executionRegistry.
|
|
204
|
+
executionRegistry.teardownExecution({
|
|
205
|
+
executionId: execution.id,
|
|
206
|
+
status: 'failed',
|
|
213
207
|
durationS: failDurationS,
|
|
214
|
-
error: agentError?.message || 'Agent process error',
|
|
208
|
+
error: { message: agentError?.message || 'Agent process error' },
|
|
215
209
|
});
|
|
216
210
|
throw agentError;
|
|
217
211
|
}
|
|
218
|
-
finally {
|
|
219
|
-
runningExecutions.remove(opts.channel);
|
|
220
|
-
}
|
|
221
212
|
}
|
|
222
213
|
/** Record step result, register session, finalize execution; update aggregate counters. */
|
|
223
214
|
async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
@@ -252,28 +243,22 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
|
252
243
|
projectId: currentThread.projectId,
|
|
253
244
|
});
|
|
254
245
|
}
|
|
255
|
-
// Finalize execution
|
|
246
|
+
// Finalize execution: persistent record + registry teardown + balanced agent.* event.
|
|
256
247
|
if (result?.rateLimited) {
|
|
257
|
-
executionRegistry.
|
|
258
|
-
durationS: stepDurationS,
|
|
259
|
-
error: 'Rate limited',
|
|
248
|
+
executionRegistry.teardownExecution({
|
|
249
|
+
executionId: execution.id, status: 'failed', durationS: stepDurationS,
|
|
250
|
+
error: { message: 'Rate limited' },
|
|
260
251
|
});
|
|
261
252
|
}
|
|
262
253
|
else {
|
|
263
|
-
executionRegistry.
|
|
264
|
-
|
|
265
|
-
numTurns: result?.num_turns,
|
|
266
|
-
durationS: stepDurationS,
|
|
267
|
-
finalOutput: result?.finalOutput || null,
|
|
254
|
+
executionRegistry.teardownExecution({
|
|
255
|
+
executionId: execution.id, status: 'completed', durationS: stepDurationS, result,
|
|
268
256
|
});
|
|
269
257
|
}
|
|
270
258
|
}
|
|
271
259
|
/** Decide whether the loop continues; run onTransition hook when transitioning.
|
|
272
260
|
* Returns false to break the loop. */
|
|
273
261
|
async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
|
|
274
|
-
// For default template, we only run one step
|
|
275
|
-
if (ctx.isDefault)
|
|
276
|
-
return false;
|
|
277
262
|
// Ad-hoc threads: run one agent per invocation, then stop
|
|
278
263
|
if (isAdHocThread(threadId))
|
|
279
264
|
return false;
|
|
@@ -308,20 +293,18 @@ async function finalizeThread(threadId, ctx) {
|
|
|
308
293
|
finalOutput,
|
|
309
294
|
totalCostUsd: finalThread.totalCostUsd,
|
|
310
295
|
totalNumTurns: ctx.totalNumTurns,
|
|
311
|
-
isDefault: ctx.isDefault,
|
|
312
296
|
lastAgentResult: ctx.lastAgentResult,
|
|
313
297
|
executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
|
|
314
298
|
};
|
|
315
299
|
}
|
|
316
300
|
async function runThread(threadId, opts) {
|
|
317
301
|
const ctx = initThreadContext(threadId, opts);
|
|
302
|
+
let enteredWaiting = false;
|
|
318
303
|
try {
|
|
319
304
|
// --- onStart hook (before first step) ---
|
|
320
305
|
// Template hook first, then per-call extraHooks (see note at onTransition).
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
await executeLifecycleHook(threadId, 'start', opts.extraHooks?.onStart, opts);
|
|
324
|
-
}
|
|
306
|
+
await executeLifecycleHook(threadId, 'start', ctx.template?.hooks?.onStart, opts);
|
|
307
|
+
await executeLifecycleHook(threadId, 'start', opts.extraHooks?.onStart, opts);
|
|
325
308
|
while (true) {
|
|
326
309
|
const stepInfo = await resolveAndNotifyStep(threadId, ctx, opts);
|
|
327
310
|
if (!stepInfo)
|
|
@@ -338,16 +321,47 @@ async function runThread(threadId, opts) {
|
|
|
338
321
|
if (ctx.stream) {
|
|
339
322
|
const reasonStr = abortCheck.reason ? `: ${abortCheck.reason}` : '';
|
|
340
323
|
const abortLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
|
|
341
|
-
ctx.stream.emitText(
|
|
324
|
+
ctx.stream.emitText(`${Icons.stopped} Thread aborted by *${abortLabel}*${reasonStr}`);
|
|
342
325
|
}
|
|
343
326
|
break;
|
|
344
327
|
}
|
|
328
|
+
// Parent suspension (DR-0014): [WAIT_CHILDREN] marker in last step output / artifact.
|
|
329
|
+
// Checked after abort, before transitions. Three outcomes:
|
|
330
|
+
// - live awaited children remain → thread enters 'waiting' (resumed by thread-callback
|
|
331
|
+
// when the last child turns terminal); skip onEnd — it fires once, at true termination.
|
|
332
|
+
// - all awaited children already terminal (callback won the race) and their results sit
|
|
333
|
+
// in pendingMessages → re-enter the loop immediately so the same agent processes them.
|
|
334
|
+
// - marker but nothing to wait on or process → fall through to normal transitions.
|
|
335
|
+
if (detectWaitMarker(threadId)) {
|
|
336
|
+
if (await tryEnterWaiting(threadId)) {
|
|
337
|
+
enteredWaiting = true;
|
|
338
|
+
const n = threadStore.get(threadId)?.metadata?.waitingOn?.length ?? 0;
|
|
339
|
+
if (ctx.stream)
|
|
340
|
+
ctx.stream.emitText(`${Icons.processing} Thread suspended — waiting on ${n} child thread(s)`);
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
const t = threadStore.get(threadId);
|
|
344
|
+
if (t?.metadata?.pendingMessages?.length) {
|
|
345
|
+
// Ad-hoc parents bypass transition evaluation, so the contract budget breaker
|
|
346
|
+
// must gate the re-entry loop here (template threads get it in checkTemplateLimits).
|
|
347
|
+
if (t && checkContractBudget(t)) {
|
|
348
|
+
if (ctx.stream)
|
|
349
|
+
ctx.stream.emitText(`${Icons.warning} Contract budget exhausted — not re-entering wait loop`);
|
|
350
|
+
}
|
|
351
|
+
else {
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
345
356
|
if (!await evaluateAndTransition(threadId, stepCtx, ctx, opts))
|
|
346
357
|
break;
|
|
347
358
|
}
|
|
348
359
|
// --- onEnd hook (after main loop) ---
|
|
349
360
|
// Template hook first, then per-call extraHooks (see note at onTransition).
|
|
350
|
-
|
|
361
|
+
// Skipped on suspension: onEnd semantics are "thread truly finished" (e.g. the dispatch
|
|
362
|
+
// task-status-check hook must not nag while children are still working). The re-entry
|
|
363
|
+
// path re-runs runThread, so onEnd still fires exactly once at final termination.
|
|
364
|
+
if (!enteredWaiting) {
|
|
351
365
|
const threadForEnd = threadStore.get(threadId);
|
|
352
366
|
const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
|
|
353
367
|
await executeLifecycleHook(threadId, 'end', ctx.template?.hooks?.onEnd, opts, lastStep?.agentSlotId);
|
|
@@ -367,8 +381,25 @@ async function runThread(threadId, opts) {
|
|
|
367
381
|
throw error;
|
|
368
382
|
}
|
|
369
383
|
finally {
|
|
370
|
-
|
|
371
|
-
//
|
|
384
|
+
// Defensive: the per-step path finalizes each execution on success (recordStepOutcome) and on
|
|
385
|
+
// error (executeAndAwaitAgent). If the loop threw AFTER an agent result but BEFORE the step was
|
|
386
|
+
// finalized, the step's execution can still be registered and its persistent record still
|
|
387
|
+
// 'running' — finalize it as failed across both ledgers so it neither leaks a 'running' record
|
|
388
|
+
// nor poisons a dispatch slot. Scope to THIS thread's entries so a concurrent run on the same
|
|
389
|
+
// channel is never touched.
|
|
390
|
+
for (const e of runningExecutions.getByChannel(opts.channel)) {
|
|
391
|
+
if (e.threadId !== threadId)
|
|
392
|
+
continue;
|
|
393
|
+
if (e.executionId) {
|
|
394
|
+
executionRegistry.teardownExecution({ executionId: e.executionId, status: 'failed', durationS: 0, error: { message: 'thread ended before step finalized' } });
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
runningExecutions.remove(e.registryKey);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// Cleanup thread-specific sessions. Intentionally also runs on suspension (DR-0014):
|
|
401
|
+
// a waiting parent holds no live session — the artifact is its durable memory, and
|
|
402
|
+
// persistSession slots keep their sessionId so re-entry resumes via --resume.
|
|
372
403
|
closeSessionsByPrefix(`thr:${threadId}:`);
|
|
373
404
|
}
|
|
374
405
|
return finalizeThread(threadId, ctx);
|
|
@@ -388,6 +419,22 @@ async function continueThread(threadId, userMessage, opts) {
|
|
|
388
419
|
});
|
|
389
420
|
return runThread(threadId, opts);
|
|
390
421
|
}
|
|
422
|
+
// --- Resume a suspended parent thread (DR-0014) ---
|
|
423
|
+
/** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
|
|
424
|
+
* the userMessage is NOT overwritten — the original contract stays in {{input}}; the child
|
|
425
|
+
* results arrive through metadata.pendingMessages (injected by the prompt builder). */
|
|
426
|
+
async function resumeThread(threadId, opts) {
|
|
427
|
+
const thread = threadStore.get(threadId);
|
|
428
|
+
if (!thread)
|
|
429
|
+
throw new Error(`Thread not found: ${threadId}`);
|
|
430
|
+
if (thread.status !== 'waiting') {
|
|
431
|
+
throw new Error(`Thread ${threadId} is ${thread.status}, cannot resume`);
|
|
432
|
+
}
|
|
433
|
+
await threadStore.mutate(threadId, (t) => {
|
|
434
|
+
t.status = 'running';
|
|
435
|
+
});
|
|
436
|
+
return runThread(threadId, opts);
|
|
437
|
+
}
|
|
391
438
|
// --- Thread summary for Slack ---
|
|
392
439
|
function buildThreadSummary(result) {
|
|
393
440
|
const { thread, totalCostUsd, totalNumTurns } = result;
|
|
@@ -395,13 +442,15 @@ function buildThreadSummary(result) {
|
|
|
395
442
|
const elapsed = thread.endedAt && thread.createdAt
|
|
396
443
|
? (new Date(thread.endedAt).getTime() - new Date(thread.createdAt).getTime()) / 1000
|
|
397
444
|
: 0;
|
|
398
|
-
const statusEmoji = thread.status === 'completed' ?
|
|
399
|
-
: thread.status === 'cancelled' ?
|
|
400
|
-
: thread.status === 'aborted' ?
|
|
401
|
-
: '
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
445
|
+
const statusEmoji = thread.status === 'completed' ? Icons.ok
|
|
446
|
+
: thread.status === 'cancelled' ? Icons.blocked
|
|
447
|
+
: thread.status === 'aborted' ? Icons.stopped
|
|
448
|
+
: thread.status === 'waiting' ? Icons.processing
|
|
449
|
+
: Icons.error;
|
|
450
|
+
const headline = thread.status === 'waiting'
|
|
451
|
+
? `${statusEmoji} Thread suspended — waiting on ${(thread.metadata?.waitingOn?.length ?? 0) + (thread.metadata?.waitingOnTasks?.length ?? 0)} child(ren) | ${steps.length} steps | $${totalCostUsd.toFixed(4)}`
|
|
452
|
+
: `${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`;
|
|
453
|
+
const lines = [headline];
|
|
405
454
|
if (steps.length > 1) {
|
|
406
455
|
for (const step of steps) {
|
|
407
456
|
const costStr = step.costUsd != null ? `$${step.costUsd.toFixed(4)}` : '?';
|
|
@@ -425,12 +474,12 @@ function buildThreadSummary(result) {
|
|
|
425
474
|
// Proxy functions to support existing callers that import cancelActiveThread / getActiveHandle from runner.ts.
|
|
426
475
|
// These delegate to the unified RunningExecutions singleton.
|
|
427
476
|
function cancelActiveThread(channel) {
|
|
428
|
-
return runningExecutions.
|
|
477
|
+
return runningExecutions.killByChannel(channel) > 0;
|
|
429
478
|
}
|
|
430
479
|
function getActiveHandle(channel) {
|
|
431
|
-
return runningExecutions.
|
|
480
|
+
return runningExecutions.getByChannel(channel)[0] ?? null;
|
|
432
481
|
}
|
|
433
|
-
export { runThread, continueThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
|
|
482
|
+
export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
|
|
434
483
|
// Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
|
|
435
484
|
// Not part of the public API; callers outside the test harness should continue to use runThread().
|
|
436
485
|
initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
|
|
@@ -8,27 +8,6 @@ export declare function createThread(channel: string, options: {
|
|
|
8
8
|
projectId?: string;
|
|
9
9
|
metadata?: import('../../core/types/thread-types.js').ThreadMetadata | null;
|
|
10
10
|
}): ThreadRecord;
|
|
11
|
-
/** Create a lightweight completed thread record (no filesystem workspace).
|
|
12
|
-
* Used to track single-agent path executions so !thread add can chain off them. */
|
|
13
|
-
export declare function createAutoThreadRecord(channel: string, options: {
|
|
14
|
-
agentName: string;
|
|
15
|
-
userMessage: string;
|
|
16
|
-
userMessageTs: string;
|
|
17
|
-
platformThreadId?: string | null;
|
|
18
|
-
projectId?: string;
|
|
19
|
-
}): ThreadRecord;
|
|
20
|
-
/** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
|
|
21
|
-
* Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
|
|
22
|
-
* returns true and the thread runner uses default-path semantics.
|
|
23
|
-
* Unlike createAutoThreadRecord (post-hoc, templateName=null, no workspace), this sets
|
|
24
|
-
* templateName='default' and creates a workspace so it is detected as a default thread. */
|
|
25
|
-
export declare function createDefaultThread(channel: string, options: {
|
|
26
|
-
agentName: string;
|
|
27
|
-
userMessage: string;
|
|
28
|
-
userMessageTs: string;
|
|
29
|
-
platformThreadId?: string | null;
|
|
30
|
-
projectId?: string;
|
|
31
|
-
}): ThreadRecord;
|
|
32
11
|
export declare function addAgentToThread(threadId: string, agentName: string, userMessage?: string | null): Promise<ThreadRecord>;
|
|
33
12
|
interface NextStepInfo {
|
|
34
13
|
agentSlotId: AgentSlotId;
|
|
@@ -57,6 +36,29 @@ export declare function detectAbortMarker(threadId: string): {
|
|
|
57
36
|
aborted: boolean;
|
|
58
37
|
reason: string | null;
|
|
59
38
|
};
|
|
39
|
+
/** Detect `[WAIT_CHILDREN]` in the last step's output or in the artifact. The marker alone
|
|
40
|
+
* does not suspend the thread — tryEnterWaiting() additionally requires live children. */
|
|
41
|
+
export declare function detectWaitMarker(threadId: string): boolean;
|
|
42
|
+
/** Try to suspend the thread until its waited-on children finish. Inside a single mutate
|
|
43
|
+
* (serialized with the callback side via the store mutex), filter waitingOn down to
|
|
44
|
+
* children that still exist and are non-terminal; additionally (DR-0014 §8) snapshot live
|
|
45
|
+
* child TASKS (parent === metadata.taskId) into waitingOnTasks. If either list is
|
|
46
|
+
* non-empty, set status='waiting'. Returns true iff the thread entered waiting.
|
|
47
|
+
* Either interleaving with the completion callback converges: callback-first → nothing
|
|
48
|
+
* left to wait on (results already in pendingMessages); runner-first → callback sees
|
|
49
|
+
* waiting and resumes when both lists empty. The task-side race (a child completing
|
|
50
|
+
* between the snapshot and the waiting persist, its event missed) is closed by
|
|
51
|
+
* reconcileWaitingTasks right after suspension. */
|
|
52
|
+
export declare function tryEnterWaiting(threadId: string): Promise<boolean>;
|
|
53
|
+
export interface SplitDetection {
|
|
54
|
+
split: boolean;
|
|
55
|
+
subtasks: any[] | null;
|
|
56
|
+
error: string | null;
|
|
57
|
+
}
|
|
58
|
+
/** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
|
|
59
|
+
* ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
|
|
60
|
+
* (not swallowed) so the dispatch path can report them instead of silently dropping. */
|
|
61
|
+
export declare function detectSplitMarker(threadId: string): SplitDetection;
|
|
60
62
|
/** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
|
|
61
63
|
export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
|
|
62
64
|
export declare function completeThread(threadId: string): Promise<boolean>;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Thread lifecycle state machine.
|
|
2
2
|
// input: thread-store, template-loader, prompt-builder, utils, artifact-io
|
|
3
|
-
// output: createThread /
|
|
3
|
+
// output: createThread / addAgentToThread /
|
|
4
4
|
// resolveNextStep / evaluateTransitions / recordStepResult / completeThread /
|
|
5
|
-
// failThread / cancelThread / abortThread / detectAbortMarker
|
|
5
|
+
// failThread / cancelThread / abortThread / detectAbortMarker /
|
|
6
|
+
// detectWaitMarker / tryEnterWaiting / detectSplitMarker (DR-0014)
|
|
6
7
|
import { mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
7
8
|
import * as path from 'path';
|
|
8
9
|
import { WORKSPACE_DIR } from '../../core/utils.js';
|
|
@@ -13,6 +14,8 @@ import { getTemplate, getAgent } from './template-loader.js';
|
|
|
13
14
|
import { resolveAgentSlotConfigByName, resolveTemplateAgents, resolveActiveAgentName } from './prompt-builder.js';
|
|
14
15
|
import { resolveStageName, parseTarget } from './utils.js';
|
|
15
16
|
import { readArtifact } from './artifact-io.js';
|
|
17
|
+
import { checkContractBudget } from './contract.js';
|
|
18
|
+
import { scanAllTasks } from '../../core/task-parser.js';
|
|
16
19
|
// --- Agent slot helpers ---
|
|
17
20
|
function newAgentSlot(config) {
|
|
18
21
|
return {
|
|
@@ -101,58 +104,6 @@ export function createThread(channel, options) {
|
|
|
101
104
|
log.info(`Created thread ${id} (${mode}, workspace=${workspacePath})`);
|
|
102
105
|
return thread;
|
|
103
106
|
}
|
|
104
|
-
/** Create a lightweight completed thread record (no filesystem workspace).
|
|
105
|
-
* Used to track single-agent path executions so !thread add can chain off them. */
|
|
106
|
-
export function createAutoThreadRecord(channel, options) {
|
|
107
|
-
const agentConfig = resolveAgentSlotConfigByName(options.agentName);
|
|
108
|
-
if (!agentConfig)
|
|
109
|
-
throw new Error(`Unknown agent: ${options.agentName}`);
|
|
110
|
-
const id = threadStore.generateId();
|
|
111
|
-
const thread = makeThreadRecord({
|
|
112
|
-
id, channel,
|
|
113
|
-
projectId: options.projectId,
|
|
114
|
-
templateName: null,
|
|
115
|
-
platformThreadId: options.platformThreadId || null,
|
|
116
|
-
userMessage: options.userMessage,
|
|
117
|
-
userMessageTs: options.userMessageTs,
|
|
118
|
-
workspacePath: '', artifactPath: '',
|
|
119
|
-
agents: { [agentConfig.slotId]: newAgentSlot(agentConfig) },
|
|
120
|
-
activeAgent: agentConfig.slotId,
|
|
121
|
-
activeStage: resolveStageName(agentConfig, null),
|
|
122
|
-
metadata: null,
|
|
123
|
-
});
|
|
124
|
-
threadStore.set(thread);
|
|
125
|
-
log.info(`Created auto thread record ${id} (agent=${options.agentName})`);
|
|
126
|
-
return thread;
|
|
127
|
-
}
|
|
128
|
-
/** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
|
|
129
|
-
* Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
|
|
130
|
-
* returns true and the thread runner uses default-path semantics.
|
|
131
|
-
* Unlike createAutoThreadRecord (post-hoc, templateName=null, no workspace), this sets
|
|
132
|
-
* templateName='default' and creates a workspace so it is detected as a default thread. */
|
|
133
|
-
export function createDefaultThread(channel, options) {
|
|
134
|
-
const agentConfig = resolveAgentSlotConfigByName(options.agentName);
|
|
135
|
-
if (!agentConfig)
|
|
136
|
-
throw new Error(`Unknown agent: ${options.agentName}`);
|
|
137
|
-
const id = threadStore.generateId();
|
|
138
|
-
const { workspacePath, artifactPath } = createWorkspace(id);
|
|
139
|
-
const thread = makeThreadRecord({
|
|
140
|
-
id, channel,
|
|
141
|
-
projectId: options.projectId,
|
|
142
|
-
templateName: 'default',
|
|
143
|
-
platformThreadId: options.platformThreadId || null,
|
|
144
|
-
userMessage: options.userMessage,
|
|
145
|
-
userMessageTs: options.userMessageTs,
|
|
146
|
-
workspacePath, artifactPath,
|
|
147
|
-
agents: { [agentConfig.slotId]: newAgentSlot(agentConfig) },
|
|
148
|
-
activeAgent: agentConfig.slotId,
|
|
149
|
-
activeStage: resolveStageName(agentConfig, null),
|
|
150
|
-
metadata: null,
|
|
151
|
-
});
|
|
152
|
-
threadStore.set(thread);
|
|
153
|
-
log.info(`Created default thread ${id} (agent=${options.agentName})`);
|
|
154
|
-
return thread;
|
|
155
|
-
}
|
|
156
107
|
// --- Add agent to existing thread ---
|
|
157
108
|
/** Lazy workspace creation for auto-records that started without a filesystem workspace. */
|
|
158
109
|
function ensureThreadWorkspace(thread) {
|
|
@@ -272,6 +223,11 @@ function checkTemplateLimits(thread, template) {
|
|
|
272
223
|
if (template.maxTotalCostUsd != null && thread.totalCostUsd >= template.maxTotalCostUsd) {
|
|
273
224
|
return { shouldTransition: false, reason: 'cost_limit' };
|
|
274
225
|
}
|
|
226
|
+
// DR-0014: per-thread delegation-contract budget (second gate after the spawn-time
|
|
227
|
+
// tree guards — catches a single thread burning through its allowance step by step).
|
|
228
|
+
if (checkContractBudget(thread)) {
|
|
229
|
+
return { shouldTransition: false, reason: 'cost_limit' };
|
|
230
|
+
}
|
|
275
231
|
return null;
|
|
276
232
|
}
|
|
277
233
|
function applyTransition(thread, rule, result) {
|
|
@@ -402,6 +358,109 @@ export function detectAbortMarker(threadId) {
|
|
|
402
358
|
const raw = m[1] != null ? m[1].trim() : '';
|
|
403
359
|
return { aborted: true, reason: raw.length > 0 ? raw : null };
|
|
404
360
|
}
|
|
361
|
+
// --- Wait-on-children + split markers (DR-0014) ---
|
|
362
|
+
const WAIT_MARKER_RE = /\[WAIT_CHILDREN\]/;
|
|
363
|
+
/** Detect `[WAIT_CHILDREN]` in the last step's output or in the artifact. The marker alone
|
|
364
|
+
* does not suspend the thread — tryEnterWaiting() additionally requires live children. */
|
|
365
|
+
export function detectWaitMarker(threadId) {
|
|
366
|
+
const thread = threadStore.get(threadId);
|
|
367
|
+
if (!thread)
|
|
368
|
+
return false;
|
|
369
|
+
const lastStep = thread.steps[thread.steps.length - 1];
|
|
370
|
+
if (lastStep?.output && WAIT_MARKER_RE.test(lastStep.output))
|
|
371
|
+
return true;
|
|
372
|
+
const content = readArtifact(threadId);
|
|
373
|
+
return !!content && WAIT_MARKER_RE.test(content);
|
|
374
|
+
}
|
|
375
|
+
function isTerminal(status) {
|
|
376
|
+
return status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'aborted';
|
|
377
|
+
}
|
|
378
|
+
/** Live (open, unblocked) child tasks of the given task, read straight from TASKS.yaml via
|
|
379
|
+
* the zero-dependency core parser — no domain/tasks import (avoids a layer cycle).
|
|
380
|
+
* Wait set = UNION of parent-linked children and the task's own unmet depends_on: any
|
|
381
|
+
* not-done dependency at manager runtime was added by the manager itself (pre-existing
|
|
382
|
+
* deps were cleared before dispatch by the actionability filter), so suspension stays
|
|
383
|
+
* correct even when the manager created children without the parent field (bulk-add +
|
|
384
|
+
* edit --add-depends-on instead of decompose --keep-parent — 2026-06-11 incident
|
|
385
|
+
* thr_6faa13a1: [WAIT_CHILDREN] emitted, suspension found no children, thread completed). */
|
|
386
|
+
function liveChildTaskIds(taskId, taskProject) {
|
|
387
|
+
try {
|
|
388
|
+
const tasks = scanAllTasks(taskProject);
|
|
389
|
+
const own = tasks.find((t) => t.id === taskId);
|
|
390
|
+
const depIds = new Set(own?.depends_on ?? []);
|
|
391
|
+
return tasks
|
|
392
|
+
.filter((t) => t.id && t.id !== taskId
|
|
393
|
+
&& (t.parent === taskId || depIds.has(t.id))
|
|
394
|
+
&& t.status !== 'done' && !t.blocked_by)
|
|
395
|
+
.map((t) => t.id);
|
|
396
|
+
}
|
|
397
|
+
catch {
|
|
398
|
+
return [];
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/** Try to suspend the thread until its waited-on children finish. Inside a single mutate
|
|
402
|
+
* (serialized with the callback side via the store mutex), filter waitingOn down to
|
|
403
|
+
* children that still exist and are non-terminal; additionally (DR-0014 §8) snapshot live
|
|
404
|
+
* child TASKS (parent === metadata.taskId) into waitingOnTasks. If either list is
|
|
405
|
+
* non-empty, set status='waiting'. Returns true iff the thread entered waiting.
|
|
406
|
+
* Either interleaving with the completion callback converges: callback-first → nothing
|
|
407
|
+
* left to wait on (results already in pendingMessages); runner-first → callback sees
|
|
408
|
+
* waiting and resumes when both lists empty. The task-side race (a child completing
|
|
409
|
+
* between the snapshot and the waiting persist, its event missed) is closed by
|
|
410
|
+
* reconcileWaitingTasks right after suspension. */
|
|
411
|
+
export async function tryEnterWaiting(threadId) {
|
|
412
|
+
const thread = threadStore.get(threadId);
|
|
413
|
+
if (!thread)
|
|
414
|
+
return false;
|
|
415
|
+
const hasThreadChildren = !!thread.metadata?.waitingOn?.length;
|
|
416
|
+
const taskId = thread.metadata?.taskId;
|
|
417
|
+
const taskProject = thread.metadata?.taskProject;
|
|
418
|
+
if (!hasThreadChildren && !(taskId && taskProject))
|
|
419
|
+
return false;
|
|
420
|
+
const taskChildren = taskId && taskProject ? liveChildTaskIds(taskId, taskProject) : [];
|
|
421
|
+
let entered = false;
|
|
422
|
+
await threadStore.mutate(threadId, (t) => {
|
|
423
|
+
const m = (t.metadata ??= {});
|
|
424
|
+
const live = (m.waitingOn || []).filter((id) => {
|
|
425
|
+
const child = threadStore.get(id);
|
|
426
|
+
return !!child && !isTerminal(child.status);
|
|
427
|
+
});
|
|
428
|
+
m.waitingOn = live;
|
|
429
|
+
m.waitingOnTasks = taskChildren;
|
|
430
|
+
if (live.length > 0 || taskChildren.length > 0) {
|
|
431
|
+
t.status = 'waiting';
|
|
432
|
+
entered = true;
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
if (entered) {
|
|
436
|
+
const m = threadStore.get(threadId).metadata;
|
|
437
|
+
log.info(`Thread ${threadId} suspended, waiting on ${m.waitingOn.length} thread children + ${m.waitingOnTasks.length} task children`);
|
|
438
|
+
}
|
|
439
|
+
return entered;
|
|
440
|
+
}
|
|
441
|
+
const SPLIT_MARKER_RE = /\[SPLIT\]/;
|
|
442
|
+
const SPLIT_JSON_FENCE_RE = /\[SPLIT\][\s\S]*?```json\s*\n([\s\S]*?)\n\s*```/;
|
|
443
|
+
/** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
|
|
444
|
+
* ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
|
|
445
|
+
* (not swallowed) so the dispatch path can report them instead of silently dropping. */
|
|
446
|
+
export function detectSplitMarker(threadId) {
|
|
447
|
+
const content = readArtifact(threadId) || '';
|
|
448
|
+
if (!SPLIT_MARKER_RE.test(content))
|
|
449
|
+
return { split: false, subtasks: null, error: null };
|
|
450
|
+
const fence = SPLIT_JSON_FENCE_RE.exec(content);
|
|
451
|
+
if (!fence)
|
|
452
|
+
return { split: true, subtasks: null, error: '[SPLIT] marker present but no ```json fenced block follows' };
|
|
453
|
+
try {
|
|
454
|
+
const parsed = JSON.parse(fence[1]);
|
|
455
|
+
if (!parsed || !Array.isArray(parsed.subtasks) || parsed.subtasks.length === 0) {
|
|
456
|
+
return { split: true, subtasks: null, error: '[SPLIT] JSON must be an object with a non-empty "subtasks" array' };
|
|
457
|
+
}
|
|
458
|
+
return { split: true, subtasks: parsed.subtasks, error: null };
|
|
459
|
+
}
|
|
460
|
+
catch (e) {
|
|
461
|
+
return { split: true, subtasks: null, error: `[SPLIT] JSON parse failed: ${e?.message || e}` };
|
|
462
|
+
}
|
|
463
|
+
}
|
|
405
464
|
/** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
|
|
406
465
|
export async function abortThread(threadId, reason) {
|
|
407
466
|
const thread = threadStore.get(threadId);
|