@cortex-agent/server 2026.5.19-1
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/.claude/settings.json +13 -0
- package/defaults/CORTEX.md +15 -0
- package/defaults/config/budget.json +4 -0
- package/defaults/config/session-hooks.json +7 -0
- package/defaults/config/thread-templates.json +528 -0
- package/defaults/context/CORTEX.md +40 -0
- package/defaults/context/decisions/DR-0012.md +54 -0
- package/defaults/context/ideas/CORTEX.md +10 -0
- package/defaults/context/projects/CORTEX.md +25 -0
- package/defaults/context/scans/CORTEX.md +13 -0
- package/defaults/context/user/CORTEX.md +21 -0
- package/defaults/data/schedules.json +52 -0
- package/defaults/gitignore +44 -0
- package/defaults/hooks/ask-user-question-hook.mjs +66 -0
- package/defaults/hooks/cortex-md-injector.mjs +237 -0
- package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
- package/defaults/hooks/memory-ref-tracker.mjs +154 -0
- package/defaults/hooks/new-session-hook.mjs +83 -0
- package/defaults/hooks/post-task-hook.mjs +63 -0
- package/defaults/hooks/rules-loader.mjs +212 -0
- package/defaults/hooks/sensitive-file-edit.mjs +84 -0
- package/defaults/hooks/session-activity-tracker.mjs +254 -0
- package/defaults/hooks/task-status-check.mjs +218 -0
- package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
- package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
- package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
- package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
- package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
- package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
- package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
- package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
- package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
- package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
- package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
- package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
- package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
- package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
- package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
- package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
- package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
- package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
- package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
- package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
- package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
- package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
- package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
- package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
- package/defaults/prompts/directives/coder-reviewer.md +106 -0
- package/defaults/prompts/directives/coder.md +90 -0
- package/defaults/prompts/directives/director.md +97 -0
- package/defaults/prompts/directives/doc-reviewer.md +93 -0
- package/defaults/prompts/directives/doc-writer.md +85 -0
- package/defaults/prompts/directives/executor-reviewer.md +96 -0
- package/defaults/prompts/directives/executor.md +85 -0
- package/defaults/prompts/directives/milestone-executor.md +119 -0
- package/defaults/prompts/directives/milestone-reviewer.md +108 -0
- package/defaults/prompts/directives/plan-executor.md +121 -0
- package/defaults/prompts/directives/plan-reviewer.md +99 -0
- package/defaults/prompts/systemPrompts/coder.md +64 -0
- package/defaults/prompts/systemPrompts/direct.md +92 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
- package/defaults/prompts/systemPrompts/web.md +50 -0
- package/defaults/prompts/systemPrompts/worker.md +67 -0
- package/defaults/rules/correction-propagation.md +31 -0
- package/defaults/rules/decision-records.md +49 -0
- package/defaults/rules/experiment-format.md +165 -0
- package/defaults/rules/issues-md.md +37 -0
- package/defaults/rules/meta-conventions.md +45 -0
- package/defaults/rules/mission-md.md +47 -0
- package/defaults/rules/overview-md.md +41 -0
- package/defaults/rules/roadmap-md.md +55 -0
- package/defaults/rules/status-md.md +49 -0
- package/defaults/rules/task-system.md +53 -0
- package/dist/agent-adapter/capabilities.d.ts +12 -0
- package/dist/agent-adapter/capabilities.js +52 -0
- package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
- package/dist/agent-adapter/claude/adapter-tui.js +422 -0
- package/dist/agent-adapter/claude/adapter.d.ts +85 -0
- package/dist/agent-adapter/claude/adapter.js +771 -0
- package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
- package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
- package/dist/agent-adapter/claude/defaults.d.ts +30 -0
- package/dist/agent-adapter/claude/defaults.js +49 -0
- package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
- package/dist/agent-adapter/claude/event-parser.js +173 -0
- package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
- package/dist/agent-adapter/claude/hooks-builder.js +57 -0
- package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
- package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
- package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
- package/dist/agent-adapter/claude/spawn-args.js +83 -0
- package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
- package/dist/agent-adapter/claude/tmux-control.js +127 -0
- package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
- package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
- package/dist/agent-adapter/codex/adapter.d.ts +42 -0
- package/dist/agent-adapter/codex/adapter.js +916 -0
- package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
- package/dist/agent-adapter/codex/event-parser.js +41 -0
- package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
- package/dist/agent-adapter/codex/spawn-args.js +30 -0
- package/dist/agent-adapter/index.d.ts +8 -0
- package/dist/agent-adapter/index.js +33 -0
- package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
- package/dist/agent-adapter/normalize/event-stream.js +47 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
- package/dist/agent-adapter/normalize/event-types.js +5 -0
- package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
- package/dist/agent-adapter/normalize/hooks.js +5 -0
- package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
- package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
- package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
- package/dist/agent-adapter/normalize/tool-names.js +73 -0
- package/dist/agent-adapter/pi/adapter.d.ts +60 -0
- package/dist/agent-adapter/pi/adapter.js +626 -0
- package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
- package/dist/agent-adapter/pi/agent-dir.js +34 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
- package/dist/agent-adapter/pi/event-parser.js +313 -0
- package/dist/agent-adapter/pi/framing.d.ts +6 -0
- package/dist/agent-adapter/pi/framing.js +35 -0
- package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
- package/dist/agent-adapter/pi/hook-bridge.js +233 -0
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
- package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
- package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
- package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
- package/dist/agent-adapter/pi/spawn-args.js +54 -0
- package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
- package/dist/agent-adapter/pi/tool-shims.js +181 -0
- package/dist/agent-adapter/types.d.ts +94 -0
- package/dist/agent-adapter/types.js +5 -0
- package/dist/core/async-mutex.d.ts +6 -0
- package/dist/core/async-mutex.js +36 -0
- package/dist/core/cli-utils.d.ts +37 -0
- package/dist/core/cli-utils.js +69 -0
- package/dist/core/config-generator.d.ts +9 -0
- package/dist/core/config-generator.js +58 -0
- package/dist/core/gateway-generator.d.ts +46 -0
- package/dist/core/gateway-generator.js +336 -0
- package/dist/core/log.d.ts +7 -0
- package/dist/core/log.js +103 -0
- package/dist/core/paths.d.ts +32 -0
- package/dist/core/paths.js +49 -0
- package/dist/core/profile-generator.d.ts +65 -0
- package/dist/core/profile-generator.js +310 -0
- package/dist/core/running-executions.d.ts +88 -0
- package/dist/core/running-executions.js +186 -0
- package/dist/core/status-format.d.ts +18 -0
- package/dist/core/status-format.js +31 -0
- package/dist/core/task-parser.d.ts +69 -0
- package/dist/core/task-parser.js +423 -0
- package/dist/core/types/agent-types.d.ts +31 -0
- package/dist/core/types/agent-types.js +5 -0
- package/dist/core/types/thread-types.d.ts +261 -0
- package/dist/core/types/thread-types.js +5 -0
- package/dist/core/utils.d.ts +29 -0
- package/dist/core/utils.js +98 -0
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +12 -0
- package/dist/domain/agents/config.d.ts +58 -0
- package/dist/domain/agents/config.js +313 -0
- package/dist/domain/agents/facade.d.ts +52 -0
- package/dist/domain/agents/facade.js +264 -0
- package/dist/domain/agents/index.d.ts +2 -0
- package/dist/domain/agents/index.js +4 -0
- package/dist/domain/agents/profile-manager.d.ts +54 -0
- package/dist/domain/agents/profile-manager.js +161 -0
- package/dist/domain/costs/codex-event-format.d.ts +4 -0
- package/dist/domain/costs/codex-event-format.js +66 -0
- package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
- package/dist/domain/costs/codex-usage-monitor.js +72 -0
- package/dist/domain/costs/cost-tracker.d.ts +115 -0
- package/dist/domain/costs/cost-tracker.js +327 -0
- package/dist/domain/costs/gateway-manager.d.ts +6 -0
- package/dist/domain/costs/gateway-manager.js +228 -0
- package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
- package/dist/domain/costs/rate-limit-parser.js +87 -0
- package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
- package/dist/domain/costs/rate-limit-throttle.js +129 -0
- package/dist/domain/executions/registry.d.ts +20 -0
- package/dist/domain/executions/registry.js +124 -0
- package/dist/domain/mcp/core-server.d.ts +2 -0
- package/dist/domain/mcp/core-server.js +34 -0
- package/dist/domain/mcp/server.d.ts +3 -0
- package/dist/domain/mcp/server.js +78 -0
- package/dist/domain/mcp/tools/context.d.ts +23 -0
- package/dist/domain/mcp/tools/context.js +51 -0
- package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
- package/dist/domain/mcp/tools/cortex-md.js +36 -0
- package/dist/domain/mcp/tools/cost.d.ts +2 -0
- package/dist/domain/mcp/tools/cost.js +54 -0
- package/dist/domain/mcp/tools/executions.d.ts +2 -0
- package/dist/domain/mcp/tools/executions.js +94 -0
- package/dist/domain/mcp/tools/schedule.d.ts +23 -0
- package/dist/domain/mcp/tools/schedule.js +245 -0
- package/dist/domain/mcp/tools/slack.d.ts +21 -0
- package/dist/domain/mcp/tools/slack.js +124 -0
- package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
- package/dist/domain/mcp/tools/task-ops.js +509 -0
- package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
- package/dist/domain/mcp/tools/tui-ask.js +108 -0
- package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
- package/dist/domain/mcp/tools/tui-plan.js +118 -0
- package/dist/domain/mcp/tui-server.d.ts +2 -0
- package/dist/domain/mcp/tui-server.js +69 -0
- package/dist/domain/memory/consolidate.d.ts +55 -0
- package/dist/domain/memory/consolidate.js +471 -0
- package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
- package/dist/domain/memory/cortex-md-injector.js +123 -0
- package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
- package/dist/domain/memory/cortex-md-scanner.js +67 -0
- package/dist/domain/memory/index-regen.d.ts +19 -0
- package/dist/domain/memory/index-regen.js +398 -0
- package/dist/domain/memory/rules-loader.d.ts +27 -0
- package/dist/domain/memory/rules-loader.js +97 -0
- package/dist/domain/memory/skill-scanner.d.ts +5 -0
- package/dist/domain/memory/skill-scanner.js +132 -0
- package/dist/domain/memory/user-context.d.ts +5 -0
- package/dist/domain/memory/user-context.js +34 -0
- package/dist/domain/memory/watcher.d.ts +2 -0
- package/dist/domain/memory/watcher.js +81 -0
- package/dist/domain/monitor/disk-monitor.d.ts +20 -0
- package/dist/domain/monitor/disk-monitor.js +97 -0
- package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
- package/dist/domain/monitor/gpu-monitor.js +135 -0
- package/dist/domain/remote/client-bootstrap.d.ts +1 -0
- package/dist/domain/remote/client-bootstrap.js +139 -0
- package/dist/domain/remote/client-hot-reload.d.ts +18 -0
- package/dist/domain/remote/client-hot-reload.js +142 -0
- package/dist/domain/remote/client-manager.d.ts +50 -0
- package/dist/domain/remote/client-manager.js +452 -0
- package/dist/domain/remote/cortex-client.d.ts +1 -0
- package/dist/domain/remote/cortex-client.js +704 -0
- package/dist/domain/scheduling/job-registry.d.ts +31 -0
- package/dist/domain/scheduling/job-registry.js +34 -0
- package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
- package/dist/domain/scheduling/jobs/_shared.js +45 -0
- package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
- package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
- package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
- package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
- package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
- package/dist/domain/scheduling/jobs/task-archive.js +19 -0
- package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
- package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
- package/dist/domain/scheduling/runner.d.ts +13 -0
- package/dist/domain/scheduling/runner.js +24 -0
- package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
- package/dist/domain/scheduling/schedule-cli.js +268 -0
- package/dist/domain/scheduling/schedule-command.d.ts +4 -0
- package/dist/domain/scheduling/schedule-command.js +274 -0
- package/dist/domain/scheduling/scheduler.d.ts +86 -0
- package/dist/domain/scheduling/scheduler.js +544 -0
- package/dist/domain/sessions/session-backup.d.ts +49 -0
- package/dist/domain/sessions/session-backup.js +217 -0
- package/dist/domain/sessions/session-hooks.d.ts +103 -0
- package/dist/domain/sessions/session-hooks.js +311 -0
- package/dist/domain/sessions/session-registry.d.ts +21 -0
- package/dist/domain/sessions/session-registry.js +31 -0
- package/dist/domain/sessions/session.d.ts +3 -0
- package/dist/domain/sessions/session.js +14 -0
- package/dist/domain/tasks/archiver.d.ts +9 -0
- package/dist/domain/tasks/archiver.js +123 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
- package/dist/domain/tasks/dispatch-utils.js +143 -0
- package/dist/domain/tasks/dispatcher.d.ts +48 -0
- package/dist/domain/tasks/dispatcher.js +285 -0
- package/dist/domain/tasks/lint.d.ts +12 -0
- package/dist/domain/tasks/lint.js +102 -0
- package/dist/domain/tasks/mutator.d.ts +21 -0
- package/dist/domain/tasks/mutator.js +208 -0
- package/dist/domain/tasks/parser.d.ts +1 -0
- package/dist/domain/tasks/parser.js +6 -0
- package/dist/domain/tasks/pending-tracker.d.ts +67 -0
- package/dist/domain/tasks/pending-tracker.js +163 -0
- package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
- package/dist/domain/tasks/recommendation/extractor.js +563 -0
- package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
- package/dist/domain/tasks/recommendation/patterns.js +99 -0
- package/dist/domain/tasks/recommendation/types.d.ts +67 -0
- package/dist/domain/tasks/recommendation/types.js +5 -0
- package/dist/domain/tasks/store.d.ts +1 -0
- package/dist/domain/tasks/store.js +3 -0
- package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
- package/dist/domain/tasks/system/cortex-run.js +342 -0
- package/dist/domain/tasks/system/task-cli.d.ts +49 -0
- package/dist/domain/tasks/system/task-cli.js +664 -0
- package/dist/domain/tasks/system/task-completion.d.ts +22 -0
- package/dist/domain/tasks/system/task-completion.js +89 -0
- package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
- package/dist/domain/tasks/system/task-id-utils.js +84 -0
- package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
- package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
- package/dist/domain/tasks/system/task-lock.d.ts +25 -0
- package/dist/domain/tasks/system/task-lock.js +139 -0
- package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
- package/dist/domain/tasks/system/task-mutations.js +110 -0
- package/dist/domain/tasks/system/task-process.d.ts +37 -0
- package/dist/domain/tasks/system/task-process.js +119 -0
- package/dist/domain/tasks/system/task-state.d.ts +70 -0
- package/dist/domain/tasks/system/task-state.js +176 -0
- package/dist/domain/threads/artifact-io.d.ts +18 -0
- package/dist/domain/threads/artifact-io.js +182 -0
- package/dist/domain/threads/auto-thread.d.ts +3 -0
- package/dist/domain/threads/auto-thread.js +19 -0
- package/dist/domain/threads/hook-runner.d.ts +4 -0
- package/dist/domain/threads/hook-runner.js +250 -0
- package/dist/domain/threads/index.d.ts +5 -0
- package/dist/domain/threads/index.js +7 -0
- package/dist/domain/threads/prompt-builder.d.ts +25 -0
- package/dist/domain/threads/prompt-builder.js +176 -0
- package/dist/domain/threads/runner.d.ts +83 -0
- package/dist/domain/threads/runner.js +434 -0
- package/dist/domain/threads/state-machine.d.ts +61 -0
- package/dist/domain/threads/state-machine.js +440 -0
- package/dist/domain/threads/template-loader.d.ts +20 -0
- package/dist/domain/threads/template-loader.js +189 -0
- package/dist/domain/threads/template-resolver.d.ts +1 -0
- package/dist/domain/threads/template-resolver.js +95 -0
- package/dist/domain/threads/utils.d.ts +19 -0
- package/dist/domain/threads/utils.js +49 -0
- package/dist/entry/app.d.ts +1 -0
- package/dist/entry/app.js +234 -0
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +254 -0
- package/dist/entry/daemon.d.ts +11 -0
- package/dist/entry/daemon.js +521 -0
- package/dist/entry/init.d.ts +93 -0
- package/dist/entry/init.js +1299 -0
- package/dist/entry/startup-helpers.d.ts +2 -0
- package/dist/entry/startup-helpers.js +56 -0
- package/dist/entry/startup-notify.d.ts +10 -0
- package/dist/entry/startup-notify.js +20 -0
- package/dist/events/event-bus.d.ts +42 -0
- package/dist/events/event-bus.js +84 -0
- package/dist/events/event-logger.d.ts +12 -0
- package/dist/events/event-logger.js +135 -0
- package/dist/events/event-replay.d.ts +1 -0
- package/dist/events/event-replay.js +51 -0
- package/dist/events/event-types.d.ts +145 -0
- package/dist/events/event-types.js +5 -0
- package/dist/events/index.d.ts +5 -0
- package/dist/events/index.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +66 -0
- package/dist/hooks/cortex-md-injector.mjs +237 -0
- package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
- package/dist/hooks/memory-ref-tracker.mjs +154 -0
- package/dist/hooks/new-session-hook.mjs +83 -0
- package/dist/hooks/post-task-hook.mjs +63 -0
- package/dist/hooks/rules-loader.mjs +212 -0
- package/dist/hooks/sensitive-file-edit.mjs +84 -0
- package/dist/hooks/session-activity-tracker.mjs +254 -0
- package/dist/hooks/task-status-check.mjs +218 -0
- package/dist/hooks/tasks-yaml-guard.mjs +230 -0
- package/dist/orchestration/agent-runner.d.ts +72 -0
- package/dist/orchestration/agent-runner.js +289 -0
- package/dist/orchestration/busy-tracker.d.ts +12 -0
- package/dist/orchestration/busy-tracker.js +35 -0
- package/dist/orchestration/channel-queue.d.ts +18 -0
- package/dist/orchestration/channel-queue.js +32 -0
- package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
- package/dist/orchestration/dispatch-reconciler.js +16 -0
- package/dist/orchestration/durable-helpers.d.ts +4 -0
- package/dist/orchestration/durable-helpers.js +42 -0
- package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
- package/dist/orchestration/interactions/ask-user-question.js +182 -0
- package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
- package/dist/orchestration/interactions/command-action-router.js +91 -0
- package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
- package/dist/orchestration/interactions/interaction-handlers.js +279 -0
- package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
- package/dist/orchestration/interactions/plan-approvals.js +77 -0
- package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
- package/dist/orchestration/interactions/plan-handler.js +12 -0
- package/dist/orchestration/lifecycle.d.ts +50 -0
- package/dist/orchestration/lifecycle.js +308 -0
- package/dist/orchestration/orchestrator.d.ts +29 -0
- package/dist/orchestration/orchestrator.js +25 -0
- package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
- package/dist/orchestration/routing/commands/cancel.js +136 -0
- package/dist/orchestration/routing/commands/channel.d.ts +11 -0
- package/dist/orchestration/routing/commands/channel.js +219 -0
- package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
- package/dist/orchestration/routing/commands/command-context.js +4 -0
- package/dist/orchestration/routing/commands/cost.d.ts +3 -0
- package/dist/orchestration/routing/commands/cost.js +22 -0
- package/dist/orchestration/routing/commands/device.d.ts +6 -0
- package/dist/orchestration/routing/commands/device.js +83 -0
- package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
- package/dist/orchestration/routing/commands/dispatch.js +49 -0
- package/dist/orchestration/routing/commands/index.d.ts +15 -0
- package/dist/orchestration/routing/commands/index.js +130 -0
- package/dist/orchestration/routing/commands/mode.d.ts +13 -0
- package/dist/orchestration/routing/commands/mode.js +290 -0
- package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
- package/dist/orchestration/routing/commands/nvtop.js +103 -0
- package/dist/orchestration/routing/commands/orient.d.ts +2 -0
- package/dist/orchestration/routing/commands/orient.js +3 -0
- package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
- package/dist/orchestration/routing/commands/schedule.js +132 -0
- package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
- package/dist/orchestration/routing/commands/sendfile.js +92 -0
- package/dist/orchestration/routing/commands/session.d.ts +9 -0
- package/dist/orchestration/routing/commands/session.js +153 -0
- package/dist/orchestration/routing/commands/status.d.ts +7 -0
- package/dist/orchestration/routing/commands/status.js +180 -0
- package/dist/orchestration/routing/commands/tail.d.ts +2 -0
- package/dist/orchestration/routing/commands/tail.js +73 -0
- package/dist/orchestration/routing/commands/task.d.ts +6 -0
- package/dist/orchestration/routing/commands/task.js +142 -0
- package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
- package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
- package/dist/orchestration/routing/commands/thread.d.ts +2 -0
- package/dist/orchestration/routing/commands/thread.js +2 -0
- package/dist/orchestration/routing/edit-handler.d.ts +24 -0
- package/dist/orchestration/routing/edit-handler.js +161 -0
- package/dist/orchestration/routing/file-handler.d.ts +6 -0
- package/dist/orchestration/routing/file-handler.js +23 -0
- package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
- package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
- package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
- package/dist/orchestration/routing/hook-bridge.js +112 -0
- package/dist/orchestration/routing/message-router.d.ts +6 -0
- package/dist/orchestration/routing/message-router.js +70 -0
- package/dist/orchestration/routing/webhook.d.ts +10 -0
- package/dist/orchestration/routing/webhook.js +239 -0
- package/dist/orchestration/status-helpers.d.ts +66 -0
- package/dist/orchestration/status-helpers.js +222 -0
- package/dist/orchestration/superseded-edits.d.ts +22 -0
- package/dist/orchestration/superseded-edits.js +31 -0
- package/dist/orchestration/thread-executor.d.ts +31 -0
- package/dist/orchestration/thread-executor.js +234 -0
- package/dist/platform/adapter.d.ts +28 -0
- package/dist/platform/adapter.js +5 -0
- package/dist/platform/adapters/feishu.d.ts +66 -0
- package/dist/platform/adapters/feishu.js +558 -0
- package/dist/platform/adapters/index.d.ts +16 -0
- package/dist/platform/adapters/index.js +65 -0
- package/dist/platform/adapters/slack.d.ts +90 -0
- package/dist/platform/adapters/slack.js +630 -0
- package/dist/platform/index.d.ts +12 -0
- package/dist/platform/index.js +10 -0
- package/dist/platform/interactive-builder.d.ts +27 -0
- package/dist/platform/interactive-builder.js +120 -0
- package/dist/platform/testing.d.ts +100 -0
- package/dist/platform/testing.js +190 -0
- package/dist/platform/tool-trace.d.ts +33 -0
- package/dist/platform/tool-trace.js +165 -0
- package/dist/platform/types.d.ts +176 -0
- package/dist/platform/types.js +5 -0
- package/dist/platform/utils/rate-limiter.d.ts +92 -0
- package/dist/platform/utils/rate-limiter.js +213 -0
- package/dist/platform/virtual-message.d.ts +68 -0
- package/dist/platform/virtual-message.js +464 -0
- package/dist/store/atomic-write.d.ts +6 -0
- package/dist/store/atomic-write.js +18 -0
- package/dist/store/channel-repo.d.ts +21 -0
- package/dist/store/channel-repo.js +55 -0
- package/dist/store/conversation-ledger-repo.d.ts +86 -0
- package/dist/store/conversation-ledger-repo.js +220 -0
- package/dist/store/cost-repo.d.ts +57 -0
- package/dist/store/cost-repo.js +135 -0
- package/dist/store/execution-repo.d.ts +172 -0
- package/dist/store/execution-repo.js +343 -0
- package/dist/store/in-memory-repository.d.ts +14 -0
- package/dist/store/in-memory-repository.js +31 -0
- package/dist/store/json-repository.d.ts +51 -0
- package/dist/store/json-repository.js +118 -0
- package/dist/store/outbound-queue.d.ts +65 -0
- package/dist/store/outbound-queue.js +269 -0
- package/dist/store/profile-repo.d.ts +36 -0
- package/dist/store/profile-repo.js +144 -0
- package/dist/store/project-dir-repo.d.ts +22 -0
- package/dist/store/project-dir-repo.js +60 -0
- package/dist/store/schedule-repo.d.ts +92 -0
- package/dist/store/schedule-repo.js +88 -0
- package/dist/store/session-registry-repo.d.ts +38 -0
- package/dist/store/session-registry-repo.js +96 -0
- package/dist/store/session-repo.d.ts +14 -0
- package/dist/store/session-repo.js +56 -0
- package/dist/store/task-repo.d.ts +41 -0
- package/dist/store/task-repo.js +137 -0
- package/dist/store/thread-repo.d.ts +50 -0
- package/dist/store/thread-repo.js +190 -0
- package/package.json +58 -0
- package/scripts/postinstall-restart-trigger.mjs +39 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
// input: domain/threads, mode-manager, hook-runner, handles
|
|
2
|
+
// output: runThread / continueThread / buildThreadSummary
|
|
3
|
+
// pos: runtime execution engine for the Thread system
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { threadStore } from '../../store/thread-repo.js';
|
|
6
|
+
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, detectAbortMarker, isDefaultThread, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
|
|
7
|
+
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
8
|
+
import { closeSessionsByPrefix } from '../agents/index.js';
|
|
9
|
+
import * as executionRegistry from '../executions/registry.js';
|
|
10
|
+
import { sessionRegistryRepo } from '../../store/session-registry-repo.js';
|
|
11
|
+
import { formatDurationCompact } from '../../core/utils.js';
|
|
12
|
+
import { VirtualMessage } from '../../platform/index.js';
|
|
13
|
+
import { runningExecutions } from '../../core/running-executions.js';
|
|
14
|
+
import { executeLifecycleHook } from './hook-runner.js';
|
|
15
|
+
import { createToolTrace } from '../../platform/index.js';
|
|
16
|
+
/** Render `agent` or `agent:stage` for log/status display — matches the transition endpoint syntax
|
|
17
|
+
* used in thread-templates.json transitions. Falls back to bare agent name when stage is null. */
|
|
18
|
+
function formatAgentStageLabel(agentSlotId, stage) {
|
|
19
|
+
return stage ? `${agentSlotId}:${stage}` : agentSlotId;
|
|
20
|
+
}
|
|
21
|
+
/** Validate thread, load template/metadata, init the aggregating VirtualMessage. */
|
|
22
|
+
function initThreadContext(threadId, opts) {
|
|
23
|
+
const thread = threadStore.get(threadId);
|
|
24
|
+
if (!thread)
|
|
25
|
+
throw new Error(`Thread not found: ${threadId}`);
|
|
26
|
+
const isDefault = isDefaultThread(threadId);
|
|
27
|
+
const template = thread.templateName ? (getTemplate(thread.templateName) || null) : null;
|
|
28
|
+
// For all non-default threads, aggregate output into a VirtualMessage.
|
|
29
|
+
// Default template passes through opts.onAssistantMessage from app.ts (backward compat).
|
|
30
|
+
const vm = !isDefault ? new VirtualMessage(opts.adapter, opts.channel, { threadId: opts.threadTs }) : null;
|
|
31
|
+
return { thread, isDefault, template, meta: thread.metadata, vm, lastAgentResult: null, totalNumTurns: 0 };
|
|
32
|
+
}
|
|
33
|
+
/** Resolve next step, post boundary notifications, update the status message.
|
|
34
|
+
* Returns null if the loop should break (cancelled, no next step). */
|
|
35
|
+
async function resolveAndNotifyStep(threadId, ctx, opts) {
|
|
36
|
+
// Check if thread was cancelled externally
|
|
37
|
+
const current = threadStore.get(threadId);
|
|
38
|
+
if (!current || current.status === 'cancelled')
|
|
39
|
+
return null;
|
|
40
|
+
// Resolve the next step
|
|
41
|
+
const nextStep = resolveNextStep(threadId);
|
|
42
|
+
if (!nextStep) {
|
|
43
|
+
await completeThread(threadId);
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
const { agentSlotId, agentConfig, isFirstStep, stage } = nextStep;
|
|
47
|
+
const threadRecord = threadStore.get(threadId);
|
|
48
|
+
const multiAgent = Object.keys(threadRecord.agents).length > 1;
|
|
49
|
+
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
50
|
+
// Post step boundary notification for multi-agent threads via VirtualMessage
|
|
51
|
+
if (ctx.vm && multiAgent && !isFirstStep) {
|
|
52
|
+
const prevStep = threadRecord.steps[threadRecord.steps.length - 1];
|
|
53
|
+
const prevLabel = prevStep ? formatAgentStageLabel(prevStep.agentSlotId, prevStep.stage) : '?';
|
|
54
|
+
ctx.vm.append(`:arrow_right: Step ${threadRecord.currentStepIndex + 1}: *${label}* starting (prev: ${prevLabel})`);
|
|
55
|
+
}
|
|
56
|
+
// Update status message (multi-agent thread format; skip if caller provides onProgress)
|
|
57
|
+
if (ctx.vm && multiAgent && !opts.onProgress) {
|
|
58
|
+
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
59
|
+
const statusText = `:hourglass_flowing_sand: Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | :stopwatch: ${formatDurationCompact(elapsed)}`;
|
|
60
|
+
try {
|
|
61
|
+
if (opts.statusMsg) {
|
|
62
|
+
await opts.adapter.updateMessage(opts.statusMsg, { text: statusText });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
}
|
|
67
|
+
return { agentSlotId, agentConfig, isFirstStep, multiAgent, stage };
|
|
68
|
+
}
|
|
69
|
+
/** Build prompt, resolve session config, profile, register execution, generate session name + start time.
|
|
70
|
+
* Returns a fully-populated StepContext — no placeholder fields. */
|
|
71
|
+
async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
72
|
+
const { agentSlotId, agentConfig, isFirstStep, multiAgent, stage } = stepInfo;
|
|
73
|
+
const slot = threadStore.get(threadId).agents[agentSlotId];
|
|
74
|
+
// Build prompt for this step — pass the stage so stage-aware agents send their stage-specific
|
|
75
|
+
// prompt (and, in incremental mode on session resume, skip directive + preamble + auto previousOutput).
|
|
76
|
+
const prompt = buildStepPrompt(threadId, agentConfig, stage, opts.isUserInitiated);
|
|
77
|
+
// Determine session configuration
|
|
78
|
+
let sessionId = null;
|
|
79
|
+
let sessionKey = null;
|
|
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
|
+
}
|
|
90
|
+
// Resolve profile: agents with a hardcoded profile always use their own declaration.
|
|
91
|
+
// metadata.profileOverride only applies to __active__ agents (default/main/scheduler-main),
|
|
92
|
+
// letting scheduler/dispatch inject a concrete profile without overriding research-pipeline agents.
|
|
93
|
+
const profileName = agentConfig.profile === '__active__'
|
|
94
|
+
? (ctx.meta?.profileOverride || getActiveProfile(opts.channel))
|
|
95
|
+
: agentConfig.profile;
|
|
96
|
+
// Register execution
|
|
97
|
+
const executionKind = ctx.meta?.trigger === 'task-dispatch' ? 'dispatch'
|
|
98
|
+
: ctx.meta?.trigger === 'scheduled' ? 'scheduled'
|
|
99
|
+
: 'local';
|
|
100
|
+
const executionTrigger = ctx.meta?.trigger || (ctx.isDefault ? 'user' : 'thread-step');
|
|
101
|
+
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
102
|
+
const execution = executionRegistry.startLocalExecution({
|
|
103
|
+
kind: executionKind,
|
|
104
|
+
channel: opts.channel,
|
|
105
|
+
project: ctx.meta?.project || null,
|
|
106
|
+
trigger: executionTrigger,
|
|
107
|
+
backend: getActiveBackend(),
|
|
108
|
+
billingMode: getClaudeMode(),
|
|
109
|
+
sessionId,
|
|
110
|
+
label: ctx.isDefault ? prompt.substring(0, 60) : `[${label}] ${prompt.substring(0, 40)}`,
|
|
111
|
+
scheduleTaskId: ctx.meta?.scheduleTaskId || null,
|
|
112
|
+
threadId,
|
|
113
|
+
agentSlotId,
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
|
|
117
|
+
prompt, sessionId, sessionKey,
|
|
118
|
+
sessionName: (ctx.isDefault && opts.sessionName) ? opts.sessionName : await sessionRegistryRepo.generateSessionName(),
|
|
119
|
+
profileName, execution,
|
|
120
|
+
stepStartTime: new Date().toISOString(),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** Resolve onAssistantMessage/onProgress callbacks and mark slot as running.
|
|
124
|
+
* Returns the callbacks instead of mutating the StepContext. */
|
|
125
|
+
function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
126
|
+
const { agentSlotId, multiAgent, stage } = stepCtx;
|
|
127
|
+
const threadRecord = threadStore.get(threadId);
|
|
128
|
+
const slot = threadRecord.agents[agentSlotId];
|
|
129
|
+
const vm = ctx.vm;
|
|
130
|
+
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
131
|
+
// Determine callbacks:
|
|
132
|
+
// - default: pass through from opts (app.ts VirtualMessage)
|
|
133
|
+
// - non-default: aggregate into thread-runner's VM; prefix only for multi-agent
|
|
134
|
+
const slotPrefix = multiAgent ? `*[${label}]*` : null;
|
|
135
|
+
const baseAssistantMessage = vm
|
|
136
|
+
? (text) => { vm.append(slotPrefix ? `${slotPrefix} ${text}` : text); }
|
|
137
|
+
: opts.onAssistantMessage;
|
|
138
|
+
// Tool trace (env-gated): caller-supplied onToolUse takes precedence (default-thread path —
|
|
139
|
+
// agent-runner owns the VM). Otherwise build one bound to the runner's own VM.
|
|
140
|
+
const callerOnToolUse = opts.onToolUse ?? null;
|
|
141
|
+
const toolTrace = callerOnToolUse ? null : createToolTrace(vm, { slotPrefix });
|
|
142
|
+
const onAssistantMessage = toolTrace && baseAssistantMessage
|
|
143
|
+
? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
|
|
144
|
+
: baseAssistantMessage;
|
|
145
|
+
const onToolUse = callerOnToolUse
|
|
146
|
+
?? (toolTrace ? (name, input) => toolTrace.onToolUse(name, input) : null);
|
|
147
|
+
// onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
|
|
148
|
+
// fallback to thread-specific status format for multi-agent pipelines
|
|
149
|
+
const onProgress = opts.onProgress
|
|
150
|
+
|| (vm && multiAgent
|
|
151
|
+
? (progress) => {
|
|
152
|
+
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
153
|
+
if (opts.statusMsg) {
|
|
154
|
+
opts.adapter.updateMessage(opts.statusMsg, {
|
|
155
|
+
text: `:hourglass_flowing_sand: Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* (${progress?.num_turns || '?'} turns) | :stopwatch: ${formatDurationCompact(elapsed)}`,
|
|
156
|
+
}).catch(() => { });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
: null);
|
|
160
|
+
// Mark agent slot as running
|
|
161
|
+
slot.status = 'running';
|
|
162
|
+
threadStore.set(threadRecord);
|
|
163
|
+
return { onAssistantMessage, onProgress, onToolUse };
|
|
164
|
+
}
|
|
165
|
+
/** Run the agent, manage handle, await result; fail execution + rethrow on error.
|
|
166
|
+
* Returns the agent result. */
|
|
167
|
+
async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
|
|
168
|
+
const { agentConfig, isFirstStep, prompt, sessionId, sessionKey, profileName, execution, stepStartTime } = stepCtx;
|
|
169
|
+
const meta = ctx.meta;
|
|
170
|
+
const handle = runAgent(prompt, {
|
|
171
|
+
channel: opts.channel,
|
|
172
|
+
executionId: execution.id,
|
|
173
|
+
sessionId,
|
|
174
|
+
sessionKey,
|
|
175
|
+
files: isFirstStep ? (opts.files || []) : [],
|
|
176
|
+
profileName,
|
|
177
|
+
project: meta?.project || undefined,
|
|
178
|
+
trigger: meta?.trigger || undefined,
|
|
179
|
+
threadId,
|
|
180
|
+
useCoreMcp: !ctx.isDefault,
|
|
181
|
+
sessionName: stepCtx.sessionName,
|
|
182
|
+
claudeAgent: agentConfig.claudeAgent || null,
|
|
183
|
+
systemPrompt: agentConfig.systemPrompt ? resolveSystemVars(agentConfig.systemPrompt) : null,
|
|
184
|
+
outputStyle: agentConfig.outputStyle || null,
|
|
185
|
+
tools: agentConfig.tools || null,
|
|
186
|
+
pluginDirs: agentConfig.pluginDirs || null,
|
|
187
|
+
onFallback: ctx.isDefault ? opts.onFallback : null,
|
|
188
|
+
isUserInitiated: ctx.isDefault ? (opts.isUserInitiated || false) : false,
|
|
189
|
+
onAssistantMessage: callbacks.onAssistantMessage,
|
|
190
|
+
onProgress: callbacks.onProgress,
|
|
191
|
+
onToolUse: callbacks.onToolUse,
|
|
192
|
+
onPlanWritten: opts.onPlanWritten ?? null,
|
|
193
|
+
onAskUserQuestion: opts.onAskUserQuestion ?? null,
|
|
194
|
+
});
|
|
195
|
+
// Track handle for cancellation
|
|
196
|
+
runningExecutions.register(opts.channel, {
|
|
197
|
+
threadId,
|
|
198
|
+
channel: opts.channel,
|
|
199
|
+
agentSlotId: stepCtx.agentSlotId,
|
|
200
|
+
executionId: stepCtx.execution.id,
|
|
201
|
+
kill: () => handle.kill(),
|
|
202
|
+
backend: getActiveBackend(),
|
|
203
|
+
agentProcess: handle.agentProcess,
|
|
204
|
+
sessionId: handle.sessionId,
|
|
205
|
+
});
|
|
206
|
+
try {
|
|
207
|
+
return await handle.promise;
|
|
208
|
+
}
|
|
209
|
+
catch (agentError) {
|
|
210
|
+
// Finalize execution as failed so it doesn't stay stuck in 'running'
|
|
211
|
+
const failDurationS = (Date.now() - new Date(stepStartTime).getTime()) / 1000;
|
|
212
|
+
executionRegistry.failExecution(execution.id, {
|
|
213
|
+
durationS: failDurationS,
|
|
214
|
+
error: agentError?.message || 'Agent process error',
|
|
215
|
+
});
|
|
216
|
+
throw agentError;
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
runningExecutions.remove(opts.channel);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/** Record step result, register session, finalize execution; update aggregate counters. */
|
|
223
|
+
async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
224
|
+
const { agentSlotId, prompt, sessionName, execution, stepStartTime, stage } = stepCtx;
|
|
225
|
+
ctx.lastAgentResult = result;
|
|
226
|
+
// Record the step result
|
|
227
|
+
const stepEndTime = new Date().toISOString();
|
|
228
|
+
const stepDurationS = (new Date(stepEndTime).getTime() - new Date(stepStartTime).getTime()) / 1000;
|
|
229
|
+
await recordStepResult(threadId, agentSlotId, {
|
|
230
|
+
sessionId: result?.sessionId || null,
|
|
231
|
+
sessionName,
|
|
232
|
+
executionId: execution.id,
|
|
233
|
+
input: prompt,
|
|
234
|
+
startedAt: stepStartTime,
|
|
235
|
+
output: result?.finalOutput || null,
|
|
236
|
+
costUsd: result?.total_cost_usd || null,
|
|
237
|
+
numTurns: result?.num_turns || null,
|
|
238
|
+
durationS: stepDurationS,
|
|
239
|
+
stage,
|
|
240
|
+
});
|
|
241
|
+
ctx.totalNumTurns += result?.num_turns || 0;
|
|
242
|
+
// Register session
|
|
243
|
+
if (result?.sessionId && sessionName) {
|
|
244
|
+
await sessionRegistryRepo.registerSession(sessionName, {
|
|
245
|
+
sessionId: result.sessionId,
|
|
246
|
+
channel: opts.channel,
|
|
247
|
+
backend: getActiveBackend(),
|
|
248
|
+
kind: 'local',
|
|
249
|
+
label: `[${threadId}:${agentSlotId}]`,
|
|
250
|
+
profileName: getActiveProfile(opts.channel),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
// Finalize execution
|
|
254
|
+
if (result?.rateLimited) {
|
|
255
|
+
executionRegistry.failExecution(execution.id, {
|
|
256
|
+
durationS: stepDurationS,
|
|
257
|
+
error: 'Rate limited',
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
executionRegistry.completeExecution(execution.id, {
|
|
262
|
+
costUsd: result?.total_cost_usd,
|
|
263
|
+
numTurns: result?.num_turns,
|
|
264
|
+
durationS: stepDurationS,
|
|
265
|
+
finalOutput: result?.finalOutput || null,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** Decide whether the loop continues; run onTransition hook when transitioning.
|
|
270
|
+
* Returns false to break the loop. */
|
|
271
|
+
async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
|
|
272
|
+
// For default template, we only run one step
|
|
273
|
+
if (ctx.isDefault)
|
|
274
|
+
return false;
|
|
275
|
+
// Ad-hoc threads: run one agent per invocation, then stop
|
|
276
|
+
if (isAdHocThread(threadId))
|
|
277
|
+
return false;
|
|
278
|
+
// Evaluate transitions for template-based multi-agent
|
|
279
|
+
const transition = evaluateTransitions(threadId);
|
|
280
|
+
if (!transition.shouldTransition)
|
|
281
|
+
return false;
|
|
282
|
+
// transition.nextAgent / nextStage are already set on the thread by evaluateTransitions
|
|
283
|
+
// --- onTransition hook (between steps) ---
|
|
284
|
+
// Template hook first, then per-call extraHooks. executeLifecycleHook is a no-op for undefined
|
|
285
|
+
// config so the second call costs nothing when the caller didn't inject an extra hook.
|
|
286
|
+
const prevAgent = stepCtx.agentSlotId;
|
|
287
|
+
const fromLabel = formatAgentStageLabel(prevAgent, stepCtx.stage);
|
|
288
|
+
const toLabel = formatAgentStageLabel(transition.nextAgent, transition.nextStage ?? null);
|
|
289
|
+
const transitionLogSuffix = `(${fromLabel} → ${toLabel})`;
|
|
290
|
+
await executeLifecycleHook(threadId, 'transition', ctx.template?.hooks?.onTransition, opts, prevAgent, transitionLogSuffix);
|
|
291
|
+
await executeLifecycleHook(threadId, 'transition', opts.extraHooks?.onTransition, opts, prevAgent, transitionLogSuffix);
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
/** Read final artifact, flush VM, build the run result. */
|
|
295
|
+
async function finalizeThread(threadId, ctx) {
|
|
296
|
+
const finalThread = threadStore.get(threadId);
|
|
297
|
+
// Final output comes from the artifact file
|
|
298
|
+
const artifactContent = readArtifact(threadId);
|
|
299
|
+
const finalOutput = artifactContent || ctx.lastAgentResult?.finalOutput || null;
|
|
300
|
+
if (ctx.vm && finalOutput) {
|
|
301
|
+
ctx.vm.append(finalOutput);
|
|
302
|
+
await ctx.vm.flush();
|
|
303
|
+
}
|
|
304
|
+
return {
|
|
305
|
+
thread: finalThread,
|
|
306
|
+
finalOutput,
|
|
307
|
+
totalCostUsd: finalThread.totalCostUsd,
|
|
308
|
+
totalNumTurns: ctx.totalNumTurns,
|
|
309
|
+
isDefault: ctx.isDefault,
|
|
310
|
+
lastAgentResult: ctx.lastAgentResult,
|
|
311
|
+
executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
async function runThread(threadId, opts) {
|
|
315
|
+
const ctx = initThreadContext(threadId, opts);
|
|
316
|
+
try {
|
|
317
|
+
// --- onStart hook (before first step) ---
|
|
318
|
+
// Template hook first, then per-call extraHooks (see note at onTransition).
|
|
319
|
+
if (!ctx.isDefault) {
|
|
320
|
+
await executeLifecycleHook(threadId, 'start', ctx.template?.hooks?.onStart, opts);
|
|
321
|
+
await executeLifecycleHook(threadId, 'start', opts.extraHooks?.onStart, opts);
|
|
322
|
+
}
|
|
323
|
+
while (true) {
|
|
324
|
+
const stepInfo = await resolveAndNotifyStep(threadId, ctx, opts);
|
|
325
|
+
if (!stepInfo)
|
|
326
|
+
break;
|
|
327
|
+
const stepCtx = await buildStepConfig(threadId, stepInfo, ctx, opts);
|
|
328
|
+
const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
|
|
329
|
+
const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
|
|
330
|
+
await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
|
|
331
|
+
// Agent-initiated abort: [ABORT] / [ABORT: <reason>] marker in artifact.
|
|
332
|
+
// Global check, higher precedence than transitions. Loop exits → onEnd hook still fires.
|
|
333
|
+
const abortCheck = detectAbortMarker(threadId);
|
|
334
|
+
if (abortCheck.aborted) {
|
|
335
|
+
await abortThread(threadId, abortCheck.reason);
|
|
336
|
+
if (ctx.vm) {
|
|
337
|
+
const reasonStr = abortCheck.reason ? `: ${abortCheck.reason}` : '';
|
|
338
|
+
const abortLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
|
|
339
|
+
ctx.vm.append(`:octagonal_sign: Thread aborted by *${abortLabel}*${reasonStr}`);
|
|
340
|
+
}
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
if (!await evaluateAndTransition(threadId, stepCtx, ctx, opts))
|
|
344
|
+
break;
|
|
345
|
+
}
|
|
346
|
+
// --- onEnd hook (after main loop) ---
|
|
347
|
+
// Template hook first, then per-call extraHooks (see note at onTransition).
|
|
348
|
+
if (!ctx.isDefault) {
|
|
349
|
+
const threadForEnd = threadStore.get(threadId);
|
|
350
|
+
const lastStep = threadForEnd.steps[threadForEnd.steps.length - 1];
|
|
351
|
+
await executeLifecycleHook(threadId, 'end', ctx.template?.hooks?.onEnd, opts, lastStep?.agentSlotId);
|
|
352
|
+
await executeLifecycleHook(threadId, 'end', opts.extraHooks?.onEnd, opts, lastStep?.agentSlotId);
|
|
353
|
+
}
|
|
354
|
+
// Only complete if not already in a terminal state (e.g. cancelled during loop)
|
|
355
|
+
const threadBeforeComplete = threadStore.get(threadId);
|
|
356
|
+
if (threadBeforeComplete && threadBeforeComplete.status === 'running') {
|
|
357
|
+
await completeThread(threadId);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
const t = threadStore.get(threadId);
|
|
362
|
+
if (t && t.status === 'running') {
|
|
363
|
+
await failThread(threadId, error.message || 'Unknown error');
|
|
364
|
+
}
|
|
365
|
+
throw error;
|
|
366
|
+
}
|
|
367
|
+
finally {
|
|
368
|
+
runningExecutions.remove(opts.channel);
|
|
369
|
+
// Cleanup thread-specific sessions
|
|
370
|
+
closeSessionsByPrefix(`thr:${threadId}:`);
|
|
371
|
+
}
|
|
372
|
+
return finalizeThread(threadId, ctx);
|
|
373
|
+
}
|
|
374
|
+
// --- Continue an existing thread with new user input ---
|
|
375
|
+
async function continueThread(threadId, userMessage, opts) {
|
|
376
|
+
const thread = threadStore.get(threadId);
|
|
377
|
+
if (!thread)
|
|
378
|
+
throw new Error(`Thread not found: ${threadId}`);
|
|
379
|
+
if (thread.status !== 'running' && thread.status !== 'waiting') {
|
|
380
|
+
throw new Error(`Thread ${threadId} is ${thread.status}, cannot continue`);
|
|
381
|
+
}
|
|
382
|
+
// Update the thread's user message for the new input
|
|
383
|
+
await threadStore.mutate(threadId, (t) => {
|
|
384
|
+
t.userMessage = userMessage;
|
|
385
|
+
t.status = 'running';
|
|
386
|
+
});
|
|
387
|
+
return runThread(threadId, opts);
|
|
388
|
+
}
|
|
389
|
+
// --- Thread summary for Slack ---
|
|
390
|
+
function buildThreadSummary(result) {
|
|
391
|
+
const { thread, totalCostUsd, totalNumTurns } = result;
|
|
392
|
+
const steps = thread.steps;
|
|
393
|
+
const elapsed = thread.endedAt && thread.createdAt
|
|
394
|
+
? (new Date(thread.endedAt).getTime() - new Date(thread.createdAt).getTime()) / 1000
|
|
395
|
+
: 0;
|
|
396
|
+
const statusEmoji = thread.status === 'completed' ? ':white_check_mark:'
|
|
397
|
+
: thread.status === 'cancelled' ? ':no_entry_sign:'
|
|
398
|
+
: thread.status === 'aborted' ? ':octagonal_sign:'
|
|
399
|
+
: ':x:';
|
|
400
|
+
const lines = [
|
|
401
|
+
`${statusEmoji} Thread complete | ${steps.length} steps | $${totalCostUsd.toFixed(4)} | ${formatDurationCompact(elapsed)}`,
|
|
402
|
+
];
|
|
403
|
+
if (steps.length > 1) {
|
|
404
|
+
for (const step of steps) {
|
|
405
|
+
const costStr = step.costUsd != null ? `$${step.costUsd.toFixed(4)}` : '?';
|
|
406
|
+
const turnsStr = step.numTurns != null ? `${step.numTurns} turns` : '?';
|
|
407
|
+
const durStr = step.durationS != null ? formatDurationCompact(step.durationS) : '?';
|
|
408
|
+
const label = formatAgentStageLabel(step.agentSlotId, step.stage);
|
|
409
|
+
lines.push(` ${label}: ${turnsStr} · ${costStr} · ${durStr}`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (thread.abortReason) {
|
|
413
|
+
lines.push(`Aborted: ${thread.abortReason}`);
|
|
414
|
+
}
|
|
415
|
+
else if (thread.status === 'aborted') {
|
|
416
|
+
lines.push(`Aborted (no reason given)`);
|
|
417
|
+
}
|
|
418
|
+
if (thread.error) {
|
|
419
|
+
lines.push(`Error: ${thread.error}`);
|
|
420
|
+
}
|
|
421
|
+
return lines.join('\n');
|
|
422
|
+
}
|
|
423
|
+
// Proxy functions to support existing callers that import cancelActiveThread / getActiveHandle from runner.ts.
|
|
424
|
+
// These delegate to the unified RunningExecutions singleton.
|
|
425
|
+
function cancelActiveThread(channel) {
|
|
426
|
+
return runningExecutions.killByKey(channel);
|
|
427
|
+
}
|
|
428
|
+
function getActiveHandle(channel) {
|
|
429
|
+
return runningExecutions.getByKey(channel);
|
|
430
|
+
}
|
|
431
|
+
export { runThread, continueThread, buildThreadSummary, cancelActiveThread, getActiveHandle,
|
|
432
|
+
// Internal helpers — exported to support focused unit tests from agent-server/tests/thread-runner.test.ts.
|
|
433
|
+
// Not part of the public API; callers outside the test harness should continue to use runThread().
|
|
434
|
+
initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ThreadRecord, AgentSlotConfig, AgentSlotId, AgentStep, TransitionResult } from '../../core/types/thread-types.js';
|
|
2
|
+
export declare function createThread(channel: string, options: {
|
|
3
|
+
templateName?: string | null;
|
|
4
|
+
agentName?: string | null;
|
|
5
|
+
userMessage: string;
|
|
6
|
+
userMessageTs: string;
|
|
7
|
+
platformThreadId?: string | null;
|
|
8
|
+
metadata?: import('../../core/types/thread-types.js').ThreadMetadata | null;
|
|
9
|
+
}): ThreadRecord;
|
|
10
|
+
/** Create a lightweight completed thread record (no filesystem workspace).
|
|
11
|
+
* Used to track single-agent path executions so !thread add can chain off them. */
|
|
12
|
+
export declare function createAutoThreadRecord(channel: string, options: {
|
|
13
|
+
agentName: string;
|
|
14
|
+
userMessage: string;
|
|
15
|
+
userMessageTs: string;
|
|
16
|
+
platformThreadId?: string | null;
|
|
17
|
+
}): ThreadRecord;
|
|
18
|
+
/** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
|
|
19
|
+
* Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
|
|
20
|
+
* returns true and the thread runner uses default-path semantics.
|
|
21
|
+
* Unlike createAutoThreadRecord (post-hoc, templateName=null, no workspace), this sets
|
|
22
|
+
* templateName='default' and creates a workspace so it is detected as a default thread. */
|
|
23
|
+
export declare function createDefaultThread(channel: string, options: {
|
|
24
|
+
agentName: string;
|
|
25
|
+
userMessage: string;
|
|
26
|
+
userMessageTs: string;
|
|
27
|
+
platformThreadId?: string | null;
|
|
28
|
+
}): ThreadRecord;
|
|
29
|
+
export declare function addAgentToThread(threadId: string, agentName: string, userMessage?: string | null): Promise<ThreadRecord>;
|
|
30
|
+
interface NextStepInfo {
|
|
31
|
+
agentSlotId: AgentSlotId;
|
|
32
|
+
agentConfig: AgentSlotConfig;
|
|
33
|
+
isFirstStep: boolean;
|
|
34
|
+
stage: string | null;
|
|
35
|
+
}
|
|
36
|
+
export declare function resolveNextStep(threadId: string): NextStepInfo | null;
|
|
37
|
+
interface StepResultInput {
|
|
38
|
+
sessionId?: string | null;
|
|
39
|
+
sessionName?: string | null;
|
|
40
|
+
executionId?: string | null;
|
|
41
|
+
input?: string | null;
|
|
42
|
+
startedAt?: string | null;
|
|
43
|
+
output: string | null;
|
|
44
|
+
costUsd: number | null;
|
|
45
|
+
numTurns: number | null;
|
|
46
|
+
durationS: number | null;
|
|
47
|
+
stage?: string | null;
|
|
48
|
+
}
|
|
49
|
+
export declare function recordStepResult(threadId: string, agentSlotId: AgentSlotId, result: StepResultInput): Promise<AgentStep>;
|
|
50
|
+
export declare function evaluateTransitions(threadId: string): TransitionResult;
|
|
51
|
+
export declare function cancelThread(threadId: string): Promise<boolean>;
|
|
52
|
+
/** Detect `[ABORT]` or `[ABORT: <reason>]` marker in the thread's current artifact. */
|
|
53
|
+
export declare function detectAbortMarker(threadId: string): {
|
|
54
|
+
aborted: boolean;
|
|
55
|
+
reason: string | null;
|
|
56
|
+
};
|
|
57
|
+
/** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
|
|
58
|
+
export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
|
|
59
|
+
export declare function completeThread(threadId: string): Promise<boolean>;
|
|
60
|
+
export declare function failThread(threadId: string, error: string): Promise<boolean>;
|
|
61
|
+
export {};
|