@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,771 @@
|
|
|
1
|
+
// input: user message + session context, AgentSpawnConfig
|
|
2
|
+
// output: runClaude / closeSession / ClaudeAdapter
|
|
3
|
+
// pos: Claude CLI session pool and AgentAdapter implementation
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
import { createWriteStream } from 'fs';
|
|
7
|
+
import { createInterface } from 'readline';
|
|
8
|
+
import * as path from 'path';
|
|
9
|
+
import * as crypto from 'crypto';
|
|
10
|
+
import { DATA_DIR, readableTimestamp } from '../../core/utils.js';
|
|
11
|
+
import { createLogger } from '../../core/log.js';
|
|
12
|
+
import { handleRateLimitEvent } from '../../domain/costs/rate-limit-throttle.js';
|
|
13
|
+
import { fromCanonical } from '../normalize/tool-names.js';
|
|
14
|
+
import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
|
|
15
|
+
import { createEventStream } from '../normalize/event-stream.js';
|
|
16
|
+
import { CancelledError, CORE_MCP_CONFIG, IDLE_SESSION_TIMEOUT, LOGS_DIR, MAX_TIMEOUT, TURN_IDLE_TIMEOUT, } from './defaults.js';
|
|
17
|
+
import { buildClaudeEnv, buildSpawnArgs } from './spawn-args.js';
|
|
18
|
+
import { ClaudeTuiSession, defaultTailFactory } from './adapter-tui.js';
|
|
19
|
+
import { TmuxControl } from './tmux-control.js';
|
|
20
|
+
import { TUI_TMUX_NAME_PREFIX } from './defaults.js';
|
|
21
|
+
import { buildPrompt, clearActivePlanFile, extractAskUserQuestions, extractResult, formatEvent, getCurrentPlanFilePath, isPlanFilePath, mergeSubstantialOutput, setActivePlanFile, } from './event-parser.js';
|
|
22
|
+
const log = createLogger('claude-bridge');
|
|
23
|
+
/** Single source of truth for ClaudeSession fields → ClaudeSpawnOptions CLI args translation.
|
|
24
|
+
* Used by both ClaudeSession.toSpawnOptions() (production) and _test.computeSpawnArgs (lock-in test). */
|
|
25
|
+
function deriveClaudeSpawnOptions(fields) {
|
|
26
|
+
return {
|
|
27
|
+
tools: fields.tools,
|
|
28
|
+
systemPrompt: fields.systemPrompt,
|
|
29
|
+
appendSystemPrompt: fields.appendSystemPrompt,
|
|
30
|
+
model: fields.model,
|
|
31
|
+
claudeAgent: fields.claudeAgent,
|
|
32
|
+
pluginDirs: fields.pluginDirs,
|
|
33
|
+
outputStyle: fields.outputStyle,
|
|
34
|
+
extraOption: fields.extraOption,
|
|
35
|
+
needsResume: fields.needsResume,
|
|
36
|
+
sessionId: fields.sessionId,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
class ClaudeSession {
|
|
40
|
+
proc = null;
|
|
41
|
+
rl = null;
|
|
42
|
+
sessionId;
|
|
43
|
+
channel;
|
|
44
|
+
sessionKey;
|
|
45
|
+
/** Model name requested via --model CLI arg (used as fallback for cost_record). */
|
|
46
|
+
modelName;
|
|
47
|
+
isUserInitiated;
|
|
48
|
+
callbackSource;
|
|
49
|
+
scheduleTaskId;
|
|
50
|
+
claudeAgent;
|
|
51
|
+
systemPrompt;
|
|
52
|
+
appendSystemPrompt;
|
|
53
|
+
outputStyle;
|
|
54
|
+
tools;
|
|
55
|
+
pluginDirs;
|
|
56
|
+
anthropicBaseUrl;
|
|
57
|
+
extraEnv;
|
|
58
|
+
extraOption;
|
|
59
|
+
context;
|
|
60
|
+
currentTurn = null;
|
|
61
|
+
alive = false;
|
|
62
|
+
needsResume;
|
|
63
|
+
idleTimer = null;
|
|
64
|
+
turnIdleTimer = null;
|
|
65
|
+
maxTimer = null;
|
|
66
|
+
stderr = '';
|
|
67
|
+
cumulativeCostUsd = 0;
|
|
68
|
+
/** Captured from result event's modelUsage key for cost_record. */
|
|
69
|
+
lastModelName = null;
|
|
70
|
+
/** Captured from result event's usage for cost_record (per-turn, non-cumulative). */
|
|
71
|
+
lastTokenUsage = null;
|
|
72
|
+
constructor(channel, sessionId, options) {
|
|
73
|
+
this.channel = channel;
|
|
74
|
+
this.sessionId = sessionId;
|
|
75
|
+
this.sessionKey = options.sessionKey || channel;
|
|
76
|
+
this.needsResume = options.needsResume;
|
|
77
|
+
this.modelName = options.model || null;
|
|
78
|
+
this.isUserInitiated = options.isUserInitiated || false;
|
|
79
|
+
this.callbackSource = options.callbackSource || null;
|
|
80
|
+
this.scheduleTaskId = options.scheduleTaskId || null;
|
|
81
|
+
this.claudeAgent = options.claudeAgent || null;
|
|
82
|
+
this.systemPrompt = options.systemPrompt || null;
|
|
83
|
+
this.appendSystemPrompt = options.appendSystemPrompt ?? null;
|
|
84
|
+
this.outputStyle = options.outputStyle || null;
|
|
85
|
+
this.tools = options.tools || null;
|
|
86
|
+
this.pluginDirs = options.pluginDirs || null;
|
|
87
|
+
this.anthropicBaseUrl = options.anthropicBaseUrl;
|
|
88
|
+
this.extraEnv = options.extraEnv;
|
|
89
|
+
this.extraOption = options.extraOption;
|
|
90
|
+
this.context = options.context;
|
|
91
|
+
this.spawnProcess();
|
|
92
|
+
}
|
|
93
|
+
toSpawnOptions() {
|
|
94
|
+
return deriveClaudeSpawnOptions({
|
|
95
|
+
tools: this.tools,
|
|
96
|
+
systemPrompt: this.systemPrompt,
|
|
97
|
+
appendSystemPrompt: this.appendSystemPrompt,
|
|
98
|
+
model: this.modelName,
|
|
99
|
+
claudeAgent: this.claudeAgent,
|
|
100
|
+
pluginDirs: this.pluginDirs,
|
|
101
|
+
outputStyle: this.outputStyle,
|
|
102
|
+
extraOption: this.extraOption,
|
|
103
|
+
needsResume: this.needsResume,
|
|
104
|
+
sessionId: this.sessionId,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
handleProcessClose(code) {
|
|
108
|
+
log.info(`Process closed: ${this.sessionId.substring(0, 8)} code=${code}`);
|
|
109
|
+
this.alive = false;
|
|
110
|
+
clearActivePlanFile(this.sessionId);
|
|
111
|
+
if (this.currentTurn) {
|
|
112
|
+
const turn = this.currentTurn;
|
|
113
|
+
this.currentTurn = null;
|
|
114
|
+
this.closeTurnLogs(turn);
|
|
115
|
+
if (this.turnIdleTimer)
|
|
116
|
+
clearTimeout(this.turnIdleTimer);
|
|
117
|
+
if (turn.killed) {
|
|
118
|
+
turn.reject(new CancelledError());
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
const result = extractResult(turn.resultData, this.sessionId, false, code || 1, this.stderr, turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
|
|
122
|
+
if (result.resolved)
|
|
123
|
+
turn.resolve(result.value);
|
|
124
|
+
else
|
|
125
|
+
turn.reject(result.error);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
sessions.delete(this.sessionKey);
|
|
129
|
+
}
|
|
130
|
+
spawnProcess() {
|
|
131
|
+
const env = buildClaudeEnv(this.channel, this.sessionId, this.callbackSource, this.scheduleTaskId, this.anthropicBaseUrl, this.extraEnv, this.context);
|
|
132
|
+
const spawnOptions = this.toSpawnOptions();
|
|
133
|
+
// Template thread sessions load only the core MCP server (remote_* tools).
|
|
134
|
+
// Default / direct sessions load both core and ext servers.
|
|
135
|
+
if (this.context?.useCoreMcp) {
|
|
136
|
+
spawnOptions.mcpConfigPath = CORE_MCP_CONFIG;
|
|
137
|
+
}
|
|
138
|
+
const args = buildSpawnArgs(spawnOptions);
|
|
139
|
+
log.info(`Spawning persistent process: ${this.sessionId.substring(0, 8)} ${this.needsResume ? '(resume)' : '(new)'}`);
|
|
140
|
+
this.proc = spawn('claude', args, { cwd: DATA_DIR, env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
141
|
+
this.stderr = '';
|
|
142
|
+
this.rl = createInterface({ input: this.proc.stdout, crlfDelay: Infinity });
|
|
143
|
+
this.rl.on('line', (line) => this.handleLine(line));
|
|
144
|
+
this.proc.stderr.on('data', (d) => { this.stderr += d.toString(); });
|
|
145
|
+
this.proc.on('close', (code) => this.handleProcessClose(code));
|
|
146
|
+
this.alive = true;
|
|
147
|
+
this.resetIdleTimer();
|
|
148
|
+
this.maxTimer = setTimeout(() => {
|
|
149
|
+
log.info(`Session ${this.sessionId.substring(0, 8)} hit max timeout, killing`);
|
|
150
|
+
this.kill();
|
|
151
|
+
}, MAX_TIMEOUT);
|
|
152
|
+
}
|
|
153
|
+
createTurnStreams(userMessage) {
|
|
154
|
+
const ts = readableTimestamp();
|
|
155
|
+
const rawStream = createWriteStream(path.join(LOGS_DIR, `claude-output-${ts}.jsonl`), { flags: 'a' });
|
|
156
|
+
const txtStream = createWriteStream(path.join(LOGS_DIR, `claude-output-${ts}.txt`), { flags: 'a' });
|
|
157
|
+
txtStream.write(`=== Cortex session started at ${new Date().toISOString()} ===\n=== channel=${this.channel}, session=${this.sessionId} ===\n\n`);
|
|
158
|
+
txtStream.write(`[user-input] ${userMessage}\n\n`);
|
|
159
|
+
return { rawStream, txtStream };
|
|
160
|
+
}
|
|
161
|
+
registerTurn(resolve, reject, streams, options) {
|
|
162
|
+
clearActivePlanFile(this.sessionId);
|
|
163
|
+
this.currentTurn = {
|
|
164
|
+
resolve, reject,
|
|
165
|
+
resultData: null,
|
|
166
|
+
planFilePath: null,
|
|
167
|
+
enteredPlanMode: false,
|
|
168
|
+
exitedPlanMode: false,
|
|
169
|
+
askUserQuestions: [],
|
|
170
|
+
finalOutput: null,
|
|
171
|
+
longestOutput: null,
|
|
172
|
+
turnCount: 0,
|
|
173
|
+
onProgress: options.onProgress || null,
|
|
174
|
+
onAssistantMessage: options.onAssistantMessage || null,
|
|
175
|
+
onToolUse: options.onToolUse || null,
|
|
176
|
+
rawStream: streams.rawStream,
|
|
177
|
+
txtStream: streams.txtStream,
|
|
178
|
+
killed: false,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
writeTurnStdin(prompt) {
|
|
182
|
+
const stdinMsg = JSON.stringify({
|
|
183
|
+
type: 'user',
|
|
184
|
+
message: { role: 'user', content: prompt },
|
|
185
|
+
session_id: this.sessionId,
|
|
186
|
+
}) + '\n';
|
|
187
|
+
try {
|
|
188
|
+
this.proc.stdin.write(stdinMsg);
|
|
189
|
+
}
|
|
190
|
+
catch (e) {
|
|
191
|
+
this.alive = false;
|
|
192
|
+
if (this.currentTurn) {
|
|
193
|
+
const turn = this.currentTurn;
|
|
194
|
+
this.currentTurn = null;
|
|
195
|
+
this.closeTurnLogs(turn);
|
|
196
|
+
turn.reject(new Error(`Failed to write to claude stdin: ${e.message}`));
|
|
197
|
+
}
|
|
198
|
+
sessions.delete(this.sessionKey);
|
|
199
|
+
throw new Error(`Claude process stdin write failed: ${e.message}`);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
startTurnIdleTimer() {
|
|
203
|
+
this.turnIdleTimer = setTimeout(() => {
|
|
204
|
+
log.info(`Session ${this.sessionId.substring(0, 8)} turn idle for 60min, killing`);
|
|
205
|
+
this.kill();
|
|
206
|
+
}, TURN_IDLE_TIMEOUT);
|
|
207
|
+
}
|
|
208
|
+
async sendMessage(userMessage, options) {
|
|
209
|
+
if (!this.alive) {
|
|
210
|
+
this.needsResume = true;
|
|
211
|
+
this.spawnProcess();
|
|
212
|
+
}
|
|
213
|
+
this.resetIdleTimer();
|
|
214
|
+
const prompt = buildPrompt(userMessage, options.files || []);
|
|
215
|
+
const streams = this.createTurnStreams(userMessage);
|
|
216
|
+
const turnPromise = new Promise((resolve, reject) => {
|
|
217
|
+
this.registerTurn(resolve, reject, streams, options);
|
|
218
|
+
});
|
|
219
|
+
this.writeTurnStdin(prompt);
|
|
220
|
+
this.startTurnIdleTimer();
|
|
221
|
+
const result = await turnPromise;
|
|
222
|
+
if (this.turnIdleTimer)
|
|
223
|
+
clearTimeout(this.turnIdleTimer);
|
|
224
|
+
this.turnIdleTimer = null;
|
|
225
|
+
this.resetIdleTimer();
|
|
226
|
+
return result;
|
|
227
|
+
}
|
|
228
|
+
bumpTurnIdleTimer() {
|
|
229
|
+
if (!this.turnIdleTimer)
|
|
230
|
+
return;
|
|
231
|
+
clearTimeout(this.turnIdleTimer);
|
|
232
|
+
this.startTurnIdleTimer();
|
|
233
|
+
}
|
|
234
|
+
handleResultEvent(turn, data) {
|
|
235
|
+
// Reset per-turn capture fields so we never leak stale data from a previous turn
|
|
236
|
+
this.lastTokenUsage = null;
|
|
237
|
+
this.lastModelName = null;
|
|
238
|
+
const cumulativeCost = data.total_cost_usd ?? 0;
|
|
239
|
+
const turnCost = cumulativeCost - this.cumulativeCostUsd;
|
|
240
|
+
this.cumulativeCostUsd = cumulativeCost;
|
|
241
|
+
turn.resultData = { ...data, total_cost_usd: turnCost > 0 ? turnCost : 0 };
|
|
242
|
+
// Capture token data from the result event for cost_record (per-turn, non-cumulative)
|
|
243
|
+
if (data.usage) {
|
|
244
|
+
this.lastTokenUsage = {
|
|
245
|
+
input: data.usage.input_tokens ?? 0,
|
|
246
|
+
output: data.usage.output_tokens ?? 0,
|
|
247
|
+
cacheCreation: data.usage.cache_creation_input_tokens ?? 0,
|
|
248
|
+
cacheRead: data.usage.cache_read_input_tokens ?? 0,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
// modelUsage keys contain the actual model name(s) used
|
|
252
|
+
if (data.modelUsage) {
|
|
253
|
+
const keys = Object.keys(data.modelUsage);
|
|
254
|
+
if (keys.length > 0)
|
|
255
|
+
this.lastModelName = keys[0];
|
|
256
|
+
}
|
|
257
|
+
const result = extractResult(turn.resultData, this.sessionId, false, 0, '', turn.planFilePath, turn.enteredPlanMode, turn.exitedPlanMode, turn.askUserQuestions, turn.finalOutput, turn.longestOutput);
|
|
258
|
+
this.currentTurn = null;
|
|
259
|
+
if (this.turnIdleTimer)
|
|
260
|
+
clearTimeout(this.turnIdleTimer);
|
|
261
|
+
this.turnIdleTimer = null;
|
|
262
|
+
const formatted = formatEvent(data);
|
|
263
|
+
if (formatted)
|
|
264
|
+
turn.txtStream.write(formatted + '\n');
|
|
265
|
+
turn.txtStream.write(`\n=== Turn finished at ${new Date().toISOString()} ===\n`);
|
|
266
|
+
turn.rawStream.end();
|
|
267
|
+
turn.txtStream.end();
|
|
268
|
+
if (result.resolved)
|
|
269
|
+
turn.resolve(result.value);
|
|
270
|
+
else
|
|
271
|
+
turn.reject(result.error);
|
|
272
|
+
}
|
|
273
|
+
handleAssistantEvent(turn, data) {
|
|
274
|
+
turn.turnCount += 1;
|
|
275
|
+
for (const block of (data.message?.content || [])) {
|
|
276
|
+
if (block.type === 'tool_use') {
|
|
277
|
+
if (block.name === 'Write' && isPlanFilePath(block.input?.file_path)) {
|
|
278
|
+
turn.planFilePath = block.input.file_path;
|
|
279
|
+
setActivePlanFile(this.sessionId, block.input.file_path);
|
|
280
|
+
}
|
|
281
|
+
if (block.name === 'EnterPlanMode') {
|
|
282
|
+
turn.enteredPlanMode = true;
|
|
283
|
+
}
|
|
284
|
+
if (block.name === 'ExitPlanMode') {
|
|
285
|
+
turn.exitedPlanMode = true;
|
|
286
|
+
}
|
|
287
|
+
if (typeof turn.onToolUse === 'function') {
|
|
288
|
+
try {
|
|
289
|
+
turn.onToolUse(block.name || '?', block.input || {});
|
|
290
|
+
}
|
|
291
|
+
catch (e) {
|
|
292
|
+
log.warn('onToolUse threw:', e.message);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (block.type === 'text' && block.text) {
|
|
297
|
+
turn.finalOutput = block.text;
|
|
298
|
+
if (block.text.length > (turn.longestOutput?.length || 0))
|
|
299
|
+
turn.longestOutput = block.text;
|
|
300
|
+
if (typeof turn.onAssistantMessage === 'function')
|
|
301
|
+
turn.onAssistantMessage(block.text);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (typeof turn.onProgress === 'function') {
|
|
305
|
+
turn.onProgress({ num_turns: turn.turnCount, total_cost_usd: null, duration_ms: null });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
handleLine(line) {
|
|
309
|
+
if (!line)
|
|
310
|
+
return;
|
|
311
|
+
this.resetIdleTimer();
|
|
312
|
+
this.bumpTurnIdleTimer();
|
|
313
|
+
if (this.currentTurn?.rawStream)
|
|
314
|
+
this.currentTurn.rawStream.write(line + '\n');
|
|
315
|
+
try {
|
|
316
|
+
const data = JSON.parse(line);
|
|
317
|
+
if (data.type === 'rate_limit_event' && data.rate_limit_info) {
|
|
318
|
+
const mode = this.anthropicBaseUrl?.match(/\/m\/([^/]+)\//)?.[1] || undefined;
|
|
319
|
+
handleRateLimitEvent(data.rate_limit_info, mode).catch(e => log.error('handleRateLimitEvent error:', e));
|
|
320
|
+
}
|
|
321
|
+
if (data.type === 'result' && this.currentTurn) {
|
|
322
|
+
this.handleResultEvent(this.currentTurn, data);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (data.type === 'assistant' && this.currentTurn)
|
|
326
|
+
this.handleAssistantEvent(this.currentTurn, data);
|
|
327
|
+
const formatted = formatEvent(data);
|
|
328
|
+
if (formatted && this.currentTurn?.txtStream)
|
|
329
|
+
this.currentTurn.txtStream.write(formatted + '\n');
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
if (this.currentTurn?.txtStream)
|
|
333
|
+
this.currentTurn.txtStream.write(`[raw] ${line}\n`);
|
|
334
|
+
}
|
|
335
|
+
log.info('stream:', line.substring(0, 200));
|
|
336
|
+
}
|
|
337
|
+
closeTurnLogs(turn) {
|
|
338
|
+
try {
|
|
339
|
+
turn.txtStream.write(`\n=== Turn ended at ${new Date().toISOString()} ===\n`);
|
|
340
|
+
turn.rawStream.end();
|
|
341
|
+
turn.txtStream.end();
|
|
342
|
+
}
|
|
343
|
+
catch { }
|
|
344
|
+
}
|
|
345
|
+
resetIdleTimer() {
|
|
346
|
+
if (this.idleTimer)
|
|
347
|
+
clearTimeout(this.idleTimer);
|
|
348
|
+
this.idleTimer = setTimeout(() => {
|
|
349
|
+
log.info(`Session ${this.sessionId.substring(0, 8)} idle for 65min, closing`);
|
|
350
|
+
this.close();
|
|
351
|
+
}, IDLE_SESSION_TIMEOUT);
|
|
352
|
+
}
|
|
353
|
+
close() {
|
|
354
|
+
if (this.idleTimer)
|
|
355
|
+
clearTimeout(this.idleTimer);
|
|
356
|
+
if (this.maxTimer)
|
|
357
|
+
clearTimeout(this.maxTimer);
|
|
358
|
+
if (this.turnIdleTimer)
|
|
359
|
+
clearTimeout(this.turnIdleTimer);
|
|
360
|
+
if (!this.proc || !this.alive) {
|
|
361
|
+
sessions.delete(this.sessionKey);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
this.alive = false;
|
|
365
|
+
sessions.delete(this.sessionKey);
|
|
366
|
+
try {
|
|
367
|
+
this.proc.stdin.end();
|
|
368
|
+
}
|
|
369
|
+
catch { }
|
|
370
|
+
const graceTimer = setTimeout(() => {
|
|
371
|
+
if (this.proc && this.proc.exitCode === null) {
|
|
372
|
+
try {
|
|
373
|
+
this.proc.kill('SIGTERM');
|
|
374
|
+
}
|
|
375
|
+
catch { }
|
|
376
|
+
setTimeout(() => {
|
|
377
|
+
if (this.proc && this.proc.exitCode === null) {
|
|
378
|
+
try {
|
|
379
|
+
this.proc.kill('SIGKILL');
|
|
380
|
+
}
|
|
381
|
+
catch { }
|
|
382
|
+
}
|
|
383
|
+
}, 10_000);
|
|
384
|
+
}
|
|
385
|
+
}, 30_000);
|
|
386
|
+
this.proc.on('close', () => clearTimeout(graceTimer));
|
|
387
|
+
}
|
|
388
|
+
kill() {
|
|
389
|
+
if (this.idleTimer)
|
|
390
|
+
clearTimeout(this.idleTimer);
|
|
391
|
+
if (this.maxTimer)
|
|
392
|
+
clearTimeout(this.maxTimer);
|
|
393
|
+
if (this.turnIdleTimer)
|
|
394
|
+
clearTimeout(this.turnIdleTimer);
|
|
395
|
+
if (!this.proc || this.proc.exitCode !== null)
|
|
396
|
+
return false;
|
|
397
|
+
this.alive = false;
|
|
398
|
+
sessions.delete(this.sessionKey);
|
|
399
|
+
if (this.currentTurn) {
|
|
400
|
+
this.currentTurn.killed = true;
|
|
401
|
+
}
|
|
402
|
+
try {
|
|
403
|
+
this.proc.kill('SIGTERM');
|
|
404
|
+
return true;
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
isAlive() {
|
|
411
|
+
return this.alive;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
// --- Session pool ---
|
|
415
|
+
const sessions = new Map();
|
|
416
|
+
function getOrCreateSession(channel, sessionId, options) {
|
|
417
|
+
const key = options.sessionKey || channel;
|
|
418
|
+
let session = sessions.get(key);
|
|
419
|
+
if (!session || !session.isAlive() || (options.needsResume && session.sessionId !== sessionId)) {
|
|
420
|
+
if (session)
|
|
421
|
+
session.close();
|
|
422
|
+
session = new ClaudeSession(channel, sessionId, { ...options, sessionKey: key });
|
|
423
|
+
sessions.set(key, session);
|
|
424
|
+
}
|
|
425
|
+
return session;
|
|
426
|
+
}
|
|
427
|
+
export function closeSession(channel, sessionKey) {
|
|
428
|
+
const key = sessionKey || channel;
|
|
429
|
+
const session = sessions.get(key);
|
|
430
|
+
if (session)
|
|
431
|
+
session.close();
|
|
432
|
+
}
|
|
433
|
+
/** Close all sessions whose key starts with the given prefix (used by Thread cleanup). */
|
|
434
|
+
export function closeSessionsByPrefix(prefix) {
|
|
435
|
+
for (const [key, session] of sessions) {
|
|
436
|
+
if (key.startsWith(prefix))
|
|
437
|
+
session.close();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
export function closeAllSessions() {
|
|
441
|
+
for (const [, session] of sessions)
|
|
442
|
+
session.close();
|
|
443
|
+
sessions.clear();
|
|
444
|
+
}
|
|
445
|
+
export function runClaude(userMessage, opts) {
|
|
446
|
+
const effectiveSessionId = opts.sessionId || crypto.randomUUID();
|
|
447
|
+
const session = getOrCreateSession(opts.channel, effectiveSessionId, { ...opts, needsResume: !!opts.sessionId });
|
|
448
|
+
const promise = session.sendMessage(userMessage, {
|
|
449
|
+
files: opts.files || [],
|
|
450
|
+
callbackSource: opts.callbackSource ?? null,
|
|
451
|
+
scheduleTaskId: opts.scheduleTaskId ?? null,
|
|
452
|
+
isUserInitiated: opts.isUserInitiated ?? false,
|
|
453
|
+
onProgress: opts.onProgress ?? null,
|
|
454
|
+
onAssistantMessage: opts.onAssistantMessage ?? null,
|
|
455
|
+
onToolUse: opts.onToolUse ?? null,
|
|
456
|
+
});
|
|
457
|
+
return { promise, kill() { return session.kill(); }, sessionId: effectiveSessionId };
|
|
458
|
+
}
|
|
459
|
+
// --- DR-0012: TUI-mode session pool + dispatch helpers ---
|
|
460
|
+
/** Module-scoped TUI session pool, keyed by sessionKey (parallel to `sessions` for print mode). */
|
|
461
|
+
const tuiSessions = new Map();
|
|
462
|
+
/** Shared TmuxControl singleton — stateless, safe to reuse across all TUI sessions. */
|
|
463
|
+
const sharedTmux = new TmuxControl();
|
|
464
|
+
/** Pure dispatch: select claude adapter mode from an AgentSpawnConfig.
|
|
465
|
+
* Defaults to 'print' for missing or unrecognized values (conservative — never silently
|
|
466
|
+
* flips a session into the experimental TUI path). */
|
|
467
|
+
export function selectClaudeMode(config) {
|
|
468
|
+
return config.claudeBackend === 'tui' ? 'tui' : 'print';
|
|
469
|
+
}
|
|
470
|
+
function getOrCreateTuiSession(config, sessionIdEffective) {
|
|
471
|
+
const key = config.sessionKey;
|
|
472
|
+
let session = tuiSessions.get(key);
|
|
473
|
+
// If existing session has a different sessionId (e.g. user passed --new), close and recreate.
|
|
474
|
+
if (session && session.sessionId !== sessionIdEffective) {
|
|
475
|
+
session.kill();
|
|
476
|
+
session = undefined;
|
|
477
|
+
}
|
|
478
|
+
if (!session) {
|
|
479
|
+
const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
|
|
480
|
+
const cwd = config.cwd || DATA_DIR;
|
|
481
|
+
const opts = sessionOptionsFromSpawnConfig({ ...config, sessionId: sessionIdEffective });
|
|
482
|
+
const sessionConfig = {
|
|
483
|
+
channel,
|
|
484
|
+
sessionId: sessionIdEffective,
|
|
485
|
+
sessionKey: key,
|
|
486
|
+
cwd,
|
|
487
|
+
needsResume: config.resume,
|
|
488
|
+
tools: opts.tools,
|
|
489
|
+
systemPrompt: opts.systemPrompt,
|
|
490
|
+
appendSystemPrompt: opts.appendSystemPrompt,
|
|
491
|
+
model: opts.model,
|
|
492
|
+
claudeAgent: opts.claudeAgent,
|
|
493
|
+
pluginDirs: opts.pluginDirs,
|
|
494
|
+
outputStyle: opts.outputStyle,
|
|
495
|
+
extraOption: opts.extraOption ?? null,
|
|
496
|
+
callbackSource: opts.callbackSource,
|
|
497
|
+
scheduleTaskId: opts.scheduleTaskId,
|
|
498
|
+
anthropicBaseUrl: opts.anthropicBaseUrl,
|
|
499
|
+
extraEnv: opts.extraEnv,
|
|
500
|
+
context: opts.context,
|
|
501
|
+
deps: { tmux: sharedTmux, tailFactory: defaultTailFactory },
|
|
502
|
+
};
|
|
503
|
+
session = new ClaudeTuiSession(sessionConfig);
|
|
504
|
+
tuiSessions.set(key, session);
|
|
505
|
+
}
|
|
506
|
+
return session;
|
|
507
|
+
}
|
|
508
|
+
// --- ClaudeAdapter — DR-0008 §3.2 generic AgentAdapter entry point ---
|
|
509
|
+
//
|
|
510
|
+
// task f7cf scope:
|
|
511
|
+
// - spawn() returns a real AgentProcess that drives one turn through the pooled ClaudeSession
|
|
512
|
+
// via event-emitting callbacks (onAssistantMessage / onToolUse), then derives
|
|
513
|
+
// ask_user_question / plan_written / rate_limit events from the resolved AgentResult
|
|
514
|
+
// before pushing turn_complete and returning the AgentResult from send().
|
|
515
|
+
// - AgentSpawnConfig.hooks (NormalizedHookSpec[]) is still NOT consumed; buildHooksSettings
|
|
516
|
+
// uses the native tools string per DR-0008 §3.5 (Phase 3 work).
|
|
517
|
+
// - AgentSpawnConfig.mcpServers is still NOT consumed; --mcp-config still references
|
|
518
|
+
// agent-server/mcp-config.json per DR-0008 §3.6 (Phase 3 work).
|
|
519
|
+
// - Claude-specific passthrough fields (channel / claudeAgent / callbackSource / scheduleTaskId /
|
|
520
|
+
// isUserInitiated / rawTools / anthropicBaseUrl) are read directly from AgentSpawnConfig;
|
|
521
|
+
// they're Phase-3 cleanup targets (see types.ts).
|
|
522
|
+
function canonicalToolsToNative(tools) {
|
|
523
|
+
if (!tools || tools.length === 0)
|
|
524
|
+
return null;
|
|
525
|
+
const native = tools
|
|
526
|
+
.map(t => fromCanonical('claude', t))
|
|
527
|
+
.filter((n) => typeof n === 'string');
|
|
528
|
+
return native.length ? native.join(',') : null;
|
|
529
|
+
}
|
|
530
|
+
function sessionOptionsFromSpawnConfig(config) {
|
|
531
|
+
const sessionIdEffective = config.sessionId || crypto.randomUUID();
|
|
532
|
+
// rawTools (if set) overrides canonical→native translation so legacy callers that already pass Claude-native
|
|
533
|
+
// "Bash,Read,..." strings via mode-manager do not need to be refactored in this task.
|
|
534
|
+
const tools = config.rawTools ?? canonicalToolsToNative(config.tools);
|
|
535
|
+
return {
|
|
536
|
+
sessionIdEffective,
|
|
537
|
+
needsResume: config.resume,
|
|
538
|
+
model: config.model ?? null,
|
|
539
|
+
sessionKey: config.sessionKey,
|
|
540
|
+
systemPrompt: config.systemPrompt ?? null,
|
|
541
|
+
appendSystemPrompt: config.appendSystemPrompt ?? null,
|
|
542
|
+
outputStyle: config.outputStyle ?? null,
|
|
543
|
+
tools,
|
|
544
|
+
pluginDirs: config.pluginDirs ?? null,
|
|
545
|
+
isUserInitiated: !!config.isUserInitiated,
|
|
546
|
+
callbackSource: config.callbackSource ?? null,
|
|
547
|
+
scheduleTaskId: config.scheduleTaskId ?? null,
|
|
548
|
+
claudeAgent: config.claudeAgent ?? null,
|
|
549
|
+
anthropicBaseUrl: config.anthropicBaseUrl,
|
|
550
|
+
extraEnv: config.env,
|
|
551
|
+
extraOption: config.extraOption,
|
|
552
|
+
context: config.cortexContext,
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
/** Test hook: mirror of ClaudeSession.toSpawnOptions() for the AgentSpawnConfig entry point.
|
|
556
|
+
* Must stay in sync with ClaudeSession constructor + toSpawnOptions — both paths derive
|
|
557
|
+
* ClaudeSpawnOptions through deriveClaudeSpawnOptions(), so any field added to that helper
|
|
558
|
+
* is covered here without divergence. */
|
|
559
|
+
function computeSpawnArgsForConfig(config) {
|
|
560
|
+
const opts = sessionOptionsFromSpawnConfig(config);
|
|
561
|
+
const spawnOptions = deriveClaudeSpawnOptions({
|
|
562
|
+
tools: opts.tools ?? null,
|
|
563
|
+
systemPrompt: opts.systemPrompt ?? null,
|
|
564
|
+
appendSystemPrompt: opts.appendSystemPrompt ?? null,
|
|
565
|
+
model: opts.model ?? null,
|
|
566
|
+
claudeAgent: opts.claudeAgent ?? null,
|
|
567
|
+
pluginDirs: opts.pluginDirs ?? null,
|
|
568
|
+
outputStyle: opts.outputStyle ?? null,
|
|
569
|
+
extraOption: opts.extraOption,
|
|
570
|
+
needsResume: opts.needsResume,
|
|
571
|
+
sessionId: opts.sessionIdEffective,
|
|
572
|
+
});
|
|
573
|
+
return buildSpawnArgs(spawnOptions);
|
|
574
|
+
}
|
|
575
|
+
export class ClaudeAdapter {
|
|
576
|
+
backend = 'claude';
|
|
577
|
+
capabilities = CAPABILITIES_BY_BACKEND.claude;
|
|
578
|
+
spawn(config) {
|
|
579
|
+
// DR-0012: route to TUI implementation when profile selects it.
|
|
580
|
+
if (selectClaudeMode(config) === 'tui')
|
|
581
|
+
return this.spawnTui(config);
|
|
582
|
+
const { sessionIdEffective, ...sessionOptions } = sessionOptionsFromSpawnConfig(config);
|
|
583
|
+
const channel = config.channel ?? config.env?.SLACK_CHANNEL ?? config.sessionKey;
|
|
584
|
+
const session = getOrCreateSession(channel, sessionIdEffective, sessionOptions);
|
|
585
|
+
const stream = createEventStream();
|
|
586
|
+
let started = false;
|
|
587
|
+
return {
|
|
588
|
+
sessionKey: config.sessionKey,
|
|
589
|
+
get sessionId() { return session.sessionId; },
|
|
590
|
+
async send(message) {
|
|
591
|
+
if (!started) {
|
|
592
|
+
stream.push({ type: 'session_started', sessionId: session.sessionId });
|
|
593
|
+
started = true;
|
|
594
|
+
}
|
|
595
|
+
const files = (message.attachments || []).map((a) => ({
|
|
596
|
+
mimetype: a.mimeType, localPath: a.path, name: path.basename(a.path),
|
|
597
|
+
}));
|
|
598
|
+
try {
|
|
599
|
+
const result = await session.sendMessage(message.text, {
|
|
600
|
+
files,
|
|
601
|
+
onAssistantMessage: (text) => stream.push({ type: 'assistant_text', text }),
|
|
602
|
+
onToolUse: (name, input) => stream.push({ type: 'tool_use', toolUseId: '', name, input }),
|
|
603
|
+
onProgress: (p) => {
|
|
604
|
+
stream.push({ type: 'turn_progress', numTurns: p?.num_turns ?? 0 });
|
|
605
|
+
},
|
|
606
|
+
});
|
|
607
|
+
// Derived events, in order, before the terminating turn_complete.
|
|
608
|
+
for (const q of (result.askUserQuestions || [])) {
|
|
609
|
+
stream.push({
|
|
610
|
+
type: 'ask_user_question',
|
|
611
|
+
toolUseId: q.toolUseId ?? '',
|
|
612
|
+
questions: q.questions,
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
if (result.planFilePath) {
|
|
616
|
+
stream.push({
|
|
617
|
+
type: 'plan_written',
|
|
618
|
+
toolUseId: '',
|
|
619
|
+
path: result.planFilePath,
|
|
620
|
+
content: '',
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
if (result.rateLimited) {
|
|
624
|
+
stream.push({ type: 'rate_limit', raw: { message: result.rateLimitMessage } });
|
|
625
|
+
}
|
|
626
|
+
// Emit cost_record from Claude CLI result data (tokens from usage, model from modelUsage)
|
|
627
|
+
if (result.total_cost_usd != null || session.lastTokenUsage) {
|
|
628
|
+
const tu = session.lastTokenUsage;
|
|
629
|
+
stream.push({
|
|
630
|
+
type: 'cost_record',
|
|
631
|
+
provider: 'anthropic',
|
|
632
|
+
model: session.lastModelName || session.modelName || 'unknown',
|
|
633
|
+
tokens_in: tu?.input ?? 0,
|
|
634
|
+
tokens_out: tu?.output ?? 0,
|
|
635
|
+
cost_usd: result.total_cost_usd ?? null,
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
stream.push({
|
|
639
|
+
type: 'turn_complete',
|
|
640
|
+
numTurns: result.num_turns ?? 0,
|
|
641
|
+
totalCostUsd: result.total_cost_usd ?? null,
|
|
642
|
+
});
|
|
643
|
+
return result;
|
|
644
|
+
}
|
|
645
|
+
catch (err) {
|
|
646
|
+
if (!err?.cancelled) {
|
|
647
|
+
stream.push({ type: 'error', message: String(err?.message ?? err), fatal: true });
|
|
648
|
+
}
|
|
649
|
+
stream.close(); // unblock any for-await consumer
|
|
650
|
+
throw err;
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
events: stream.iterable,
|
|
654
|
+
// Intentionally does NOT call session.close(): sessions are pooled per sessionKey and
|
|
655
|
+
// reused across runAgentOnce turns. Pool-level cleanup goes through ClaudeAdapter.close(key)
|
|
656
|
+
// or the legacy closeSession / closeSessionsByPrefix exports.
|
|
657
|
+
async close() { stream.close(); },
|
|
658
|
+
kill() { return session.kill(); },
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* DR-0012 TUI-mode dispatch. Returns an AgentProcess whose send() pushes ALL NormalizedEvents
|
|
663
|
+
* (including derived ones — ask_user_question, plan_*, cost_record, turn_complete) via
|
|
664
|
+
* ClaudeTuiSession's onEvent stream, then resolves with the TuiAgentResult cast to AgentResult.
|
|
665
|
+
*
|
|
666
|
+
* Sessions are pooled in `tuiSessions` by sessionKey; multi-turn reuses the same tmux session.
|
|
667
|
+
* kill() forwards to ClaudeTuiSession.kill() which tears down the tmux session.
|
|
668
|
+
*/
|
|
669
|
+
spawnTui(config) {
|
|
670
|
+
const sessionIdEffective = config.sessionId || crypto.randomUUID();
|
|
671
|
+
const session = getOrCreateTuiSession(config, sessionIdEffective);
|
|
672
|
+
const stream = createEventStream();
|
|
673
|
+
let started = false;
|
|
674
|
+
return {
|
|
675
|
+
sessionKey: config.sessionKey,
|
|
676
|
+
get sessionId() { return session.sessionId; },
|
|
677
|
+
async send(message) {
|
|
678
|
+
if (!started) {
|
|
679
|
+
stream.push({ type: 'session_started', sessionId: session.sessionId });
|
|
680
|
+
started = true;
|
|
681
|
+
}
|
|
682
|
+
const files = (message.attachments || []).map((a) => ({
|
|
683
|
+
mimetype: a.mimeType, localPath: a.path, name: path.basename(a.path),
|
|
684
|
+
}));
|
|
685
|
+
try {
|
|
686
|
+
const tuiResult = await session.sendMessage(message.text, {
|
|
687
|
+
files,
|
|
688
|
+
onEvent: (ev) => stream.push(ev),
|
|
689
|
+
});
|
|
690
|
+
// TuiAgentResult shape lines up with AgentResult — only structural cast needed.
|
|
691
|
+
return tuiResult;
|
|
692
|
+
}
|
|
693
|
+
catch (err) {
|
|
694
|
+
if (!err?.cancelled) {
|
|
695
|
+
stream.push({ type: 'error', message: String(err?.message ?? err), fatal: true });
|
|
696
|
+
}
|
|
697
|
+
stream.close();
|
|
698
|
+
throw err;
|
|
699
|
+
}
|
|
700
|
+
},
|
|
701
|
+
events: stream.iterable,
|
|
702
|
+
async close() { stream.close(); },
|
|
703
|
+
kill() { return session.kill(); },
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
async close(sessionKey) {
|
|
707
|
+
closeSession(sessionKey, sessionKey);
|
|
708
|
+
// Also clean up any TUI session under this key (DR-0012).
|
|
709
|
+
const tui = tuiSessions.get(sessionKey);
|
|
710
|
+
if (tui) {
|
|
711
|
+
tui.close();
|
|
712
|
+
tuiSessions.delete(sessionKey);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
kill(sessionKey) {
|
|
716
|
+
const session = sessions.get(sessionKey);
|
|
717
|
+
if (session)
|
|
718
|
+
return session.kill();
|
|
719
|
+
const tui = tuiSessions.get(sessionKey);
|
|
720
|
+
if (tui) {
|
|
721
|
+
const killed = tui.kill();
|
|
722
|
+
tuiSessions.delete(sessionKey);
|
|
723
|
+
return killed;
|
|
724
|
+
}
|
|
725
|
+
return false;
|
|
726
|
+
}
|
|
727
|
+
listSessions() {
|
|
728
|
+
return [...sessions.keys(), ...tuiSessions.keys()];
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* DR-0012 §3.6 startup hook — sweep orphan tmux sessions matching the cortex-claude- prefix.
|
|
733
|
+
*
|
|
734
|
+
* Rationale: tmux sessions are independent of agent-server's process lifetime, but the in-memory
|
|
735
|
+
* `tuiSessions` Map is not. After an agent-server restart we have no record of channel/sessionKey
|
|
736
|
+
* → tmux mapping (it was never persisted), so we cannot re-adopt existing tmux sessions into the
|
|
737
|
+
* pool. The honest choice is to kill them at startup; otherwise they accumulate forever and a
|
|
738
|
+
* later session reusing the same sessionId would conflict with `tmux new-session -s <name>`
|
|
739
|
+
* (which fails on duplicate). Logs the killed names so operators can investigate if needed.
|
|
740
|
+
*
|
|
741
|
+
* Full re-adoption (preserving an in-flight TUI session across restart) requires persisting
|
|
742
|
+
* sessionKey + cwd + needsResume metadata to disk — deferred as a follow-up.
|
|
743
|
+
*
|
|
744
|
+
* Override `exec` in tests so we don't touch the real tmux server.
|
|
745
|
+
*/
|
|
746
|
+
export function recoverTuiOrphans(exec) {
|
|
747
|
+
const tmux = exec ? new TmuxControl(exec) : sharedTmux;
|
|
748
|
+
const found = tmux.listSessions(TUI_TMUX_NAME_PREFIX);
|
|
749
|
+
if (found.length === 0)
|
|
750
|
+
return { found: [], killed: [] };
|
|
751
|
+
const killed = [];
|
|
752
|
+
for (const name of found) {
|
|
753
|
+
try {
|
|
754
|
+
tmux.killSession(name);
|
|
755
|
+
killed.push(name);
|
|
756
|
+
}
|
|
757
|
+
catch (e) {
|
|
758
|
+
log.warn(`recoverTuiOrphans: failed to kill ${name}: ${e.message}`);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
log.info(`recoverTuiOrphans: swept ${killed.length}/${found.length} orphan tmux sessions (prefix=${TUI_TMUX_NAME_PREFIX})`);
|
|
762
|
+
return { found, killed };
|
|
763
|
+
}
|
|
764
|
+
export const _test = {
|
|
765
|
+
extractAskUserQuestions,
|
|
766
|
+
mergeSubstantialOutput,
|
|
767
|
+
computeSpawnArgs: computeSpawnArgsForConfig,
|
|
768
|
+
};
|
|
769
|
+
// Re-exported for webhook consumer (parity with pre-refactor claude-bridge.ts:286 export)
|
|
770
|
+
export { getCurrentPlanFilePath };
|
|
771
|
+
export { CancelledError };
|