@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,313 @@
|
|
|
1
|
+
// input: mode.json, profiles.json, env, gateway
|
|
2
|
+
// output: loadMode/switchMode/setActiveBackend/setActiveProfile + all config helpers
|
|
3
|
+
// pos: domain/agents — mode/profile/backend/agent switching and adapter dispatch [S11]
|
|
4
|
+
import { readFileSync, writeFileSync } from 'fs';
|
|
5
|
+
import { parse as parseDotenv } from 'dotenv';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import * as http from 'http';
|
|
8
|
+
import { STORE_DIR, CONFIG_DIR } from '../../core/utils.js';
|
|
9
|
+
import { getProfileModel, resolveProfileConfig } from './profile-manager.js';
|
|
10
|
+
import { GATEWAY_URL, isGatewayHealthy } from '../costs/gateway-manager.js';
|
|
11
|
+
import { createLogger } from '../../core/log.js';
|
|
12
|
+
const log = createLogger('config');
|
|
13
|
+
const MODE_FILE = path.join(STORE_DIR, 'mode.json');
|
|
14
|
+
const ENV_FILE = path.join(CONFIG_DIR, '.env');
|
|
15
|
+
const DEFAULT_CLAUDE_MODE = 'plan';
|
|
16
|
+
const DEFAULT_CLAUDE_MODEL = 'opus';
|
|
17
|
+
// Gateway proxy URL for Claude Code's ANTHROPIC_BASE_URL (DR-0001)
|
|
18
|
+
const GATEWAY_ANTHROPIC_URL = `${GATEWAY_URL}/anthropic`;
|
|
19
|
+
// Per-request mode URL: encodes mode in URL path so gateway resolves endpoints per-request
|
|
20
|
+
// instead of relying on global POST /mode state (eliminates race conditions)
|
|
21
|
+
export function gatewayModeUrl(mode, metadata) {
|
|
22
|
+
if (metadata && Object.keys(metadata).length > 0) {
|
|
23
|
+
const metaStr = Object.entries(metadata)
|
|
24
|
+
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
|
|
25
|
+
.join(",");
|
|
26
|
+
return `${GATEWAY_URL}/m/${mode}/${metaStr}/anthropic`;
|
|
27
|
+
}
|
|
28
|
+
return `${GATEWAY_URL}/m/${mode}/anthropic`;
|
|
29
|
+
}
|
|
30
|
+
function normalizeEnvValue(value) {
|
|
31
|
+
if (typeof value !== 'string')
|
|
32
|
+
return undefined;
|
|
33
|
+
const trimmed = value.trim();
|
|
34
|
+
if (!trimmed || trimmed === 'undefined' || trimmed === 'null')
|
|
35
|
+
return undefined;
|
|
36
|
+
return trimmed;
|
|
37
|
+
}
|
|
38
|
+
function readApiEnvFromDotenvFile() {
|
|
39
|
+
try {
|
|
40
|
+
const parsed = parseDotenv(readFileSync(ENV_FILE, 'utf8'));
|
|
41
|
+
return {
|
|
42
|
+
ANTHROPIC_API_KEY: normalizeEnvValue(parsed.ANTHROPIC_API_KEY),
|
|
43
|
+
ANTHROPIC_BASE_URL: normalizeEnvValue(parsed.ANTHROPIC_BASE_URL),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return {
|
|
48
|
+
ANTHROPIC_API_KEY: undefined,
|
|
49
|
+
ANTHROPIC_BASE_URL: undefined,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function captureApiEnvSnapshot() {
|
|
54
|
+
const fileEnv = readApiEnvFromDotenvFile();
|
|
55
|
+
return {
|
|
56
|
+
ANTHROPIC_API_KEY: normalizeEnvValue(process.env.ANTHROPIC_API_KEY) || fileEnv.ANTHROPIC_API_KEY,
|
|
57
|
+
ANTHROPIC_BASE_URL: normalizeEnvValue(process.env.ANTHROPIC_BASE_URL) || fileEnv.ANTHROPIC_BASE_URL,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
let savedApiEnv = captureApiEnvSnapshot();
|
|
61
|
+
function getSavedApiEnv() {
|
|
62
|
+
const liveEnv = captureApiEnvSnapshot();
|
|
63
|
+
if (liveEnv.ANTHROPIC_API_KEY)
|
|
64
|
+
savedApiEnv.ANTHROPIC_API_KEY = liveEnv.ANTHROPIC_API_KEY;
|
|
65
|
+
if (liveEnv.ANTHROPIC_BASE_URL)
|
|
66
|
+
savedApiEnv.ANTHROPIC_BASE_URL = liveEnv.ANTHROPIC_BASE_URL;
|
|
67
|
+
return savedApiEnv;
|
|
68
|
+
}
|
|
69
|
+
function applySavedApiEnv() {
|
|
70
|
+
const apiEnv = getSavedApiEnv();
|
|
71
|
+
if (apiEnv.ANTHROPIC_API_KEY)
|
|
72
|
+
process.env.ANTHROPIC_API_KEY = apiEnv.ANTHROPIC_API_KEY;
|
|
73
|
+
else
|
|
74
|
+
delete process.env.ANTHROPIC_API_KEY;
|
|
75
|
+
if (apiEnv.ANTHROPIC_BASE_URL)
|
|
76
|
+
process.env.ANTHROPIC_BASE_URL = apiEnv.ANTHROPIC_BASE_URL;
|
|
77
|
+
else
|
|
78
|
+
delete process.env.ANTHROPIC_BASE_URL;
|
|
79
|
+
}
|
|
80
|
+
function normalizeClaudeMode(mode) {
|
|
81
|
+
return mode === 'plan' ? 'plan' : 'api';
|
|
82
|
+
}
|
|
83
|
+
function loadModeFile() {
|
|
84
|
+
try {
|
|
85
|
+
return JSON.parse(readFileSync(MODE_FILE, 'utf8'));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return {};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
export function loadMode() {
|
|
92
|
+
const modeState = loadModeFile();
|
|
93
|
+
if (modeState.claudeMode)
|
|
94
|
+
return normalizeClaudeMode(modeState.claudeMode);
|
|
95
|
+
if (modeState.backend === 'claude' && modeState.mode)
|
|
96
|
+
return normalizeClaudeMode(modeState.mode);
|
|
97
|
+
return DEFAULT_CLAUDE_MODE;
|
|
98
|
+
}
|
|
99
|
+
export function loadBackend() {
|
|
100
|
+
return loadModeFile().backend || 'claude';
|
|
101
|
+
}
|
|
102
|
+
function loadClaudeModel() {
|
|
103
|
+
const modeState = loadModeFile();
|
|
104
|
+
return modeState.claudeModel || DEFAULT_CLAUDE_MODEL;
|
|
105
|
+
}
|
|
106
|
+
function loadActiveProfile() {
|
|
107
|
+
return loadModeFile().activeProfile || null;
|
|
108
|
+
}
|
|
109
|
+
function loadChannelProfiles() {
|
|
110
|
+
return loadModeFile().channelProfiles || {};
|
|
111
|
+
}
|
|
112
|
+
function loadDefaultAgent() {
|
|
113
|
+
return loadModeFile().defaultAgent || null;
|
|
114
|
+
}
|
|
115
|
+
let claudeMode = loadMode();
|
|
116
|
+
let activeBackend = loadBackend();
|
|
117
|
+
let claudeModel = loadClaudeModel();
|
|
118
|
+
let activeProfile = loadActiveProfile();
|
|
119
|
+
let channelProfiles = loadChannelProfiles();
|
|
120
|
+
let defaultAgent = loadDefaultAgent();
|
|
121
|
+
process.env.CORTEX_CLAUDE_MODEL = claudeModel;
|
|
122
|
+
function saveModeFile(mode, backend, model = claudeModel, profile = activeProfile, agent = defaultAgent) {
|
|
123
|
+
const n = normalizeClaudeMode(mode);
|
|
124
|
+
const data = { mode: n, claudeMode: n, backend, claudeModel: model };
|
|
125
|
+
if (profile)
|
|
126
|
+
data.activeProfile = profile;
|
|
127
|
+
if (agent)
|
|
128
|
+
data.defaultAgent = agent;
|
|
129
|
+
if (Object.keys(channelProfiles).length > 0)
|
|
130
|
+
data.channelProfiles = channelProfiles;
|
|
131
|
+
writeFileSync(MODE_FILE, JSON.stringify(data));
|
|
132
|
+
}
|
|
133
|
+
export function saveMode(mode) {
|
|
134
|
+
saveModeFile(mode, activeBackend);
|
|
135
|
+
}
|
|
136
|
+
export function getClaudeMode() { return claudeMode; }
|
|
137
|
+
export function getActiveBackend() { return activeBackend; }
|
|
138
|
+
export function getClaudeModel() { return claudeModel; }
|
|
139
|
+
export function setActiveBackend(backend) {
|
|
140
|
+
activeBackend = backend;
|
|
141
|
+
saveModeFile(claudeMode, activeBackend, claudeModel);
|
|
142
|
+
}
|
|
143
|
+
export function setClaudeModel(model) {
|
|
144
|
+
claudeModel = model;
|
|
145
|
+
process.env.CORTEX_CLAUDE_MODEL = claudeModel;
|
|
146
|
+
saveModeFile(claudeMode, activeBackend, claudeModel);
|
|
147
|
+
}
|
|
148
|
+
export function getActiveProfile(channel) {
|
|
149
|
+
if (channel && channelProfiles[channel])
|
|
150
|
+
return channelProfiles[channel];
|
|
151
|
+
// '__active__' is the init default — resolve to profiles.json defaultProfile if still unset
|
|
152
|
+
if (activeProfile === '__active__') {
|
|
153
|
+
try {
|
|
154
|
+
const data = JSON.parse(readFileSync(path.join(CONFIG_DIR, 'profiles.json'), 'utf8'));
|
|
155
|
+
return data.defaultProfile || null;
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return activeProfile;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Resolve the effective backend for a channel. Channel profile overrides global activeBackend
|
|
165
|
+
* — without this, conversations on channels using a non-default profile (e.g. profile `execute`
|
|
166
|
+
* with `backend: pi`) end up storing the wrong backend in the conversation ledger and routing
|
|
167
|
+
* rollback / session lookup to the wrong adapter.
|
|
168
|
+
*
|
|
169
|
+
* Falls back to global activeBackend when the channel has no profile or the profile lookup
|
|
170
|
+
* fails (e.g. profile was renamed/removed since channelProfiles was last persisted).
|
|
171
|
+
*/
|
|
172
|
+
export function resolveBackendForChannel(channel) {
|
|
173
|
+
const profileName = getActiveProfile(channel);
|
|
174
|
+
if (profileName) {
|
|
175
|
+
try {
|
|
176
|
+
const cfg = resolveProfileConfig(profileName);
|
|
177
|
+
if (cfg.backend)
|
|
178
|
+
return cfg.backend;
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
// Profile referenced by channelProfiles no longer exists — fall through to global
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return activeBackend;
|
|
185
|
+
}
|
|
186
|
+
export function setActiveProfile(profileName, channel) {
|
|
187
|
+
if (channel) {
|
|
188
|
+
if (profileName) {
|
|
189
|
+
channelProfiles[channel] = profileName;
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
delete channelProfiles[channel];
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
activeProfile = profileName;
|
|
197
|
+
}
|
|
198
|
+
saveModeFile(claudeMode, activeBackend, claudeModel, activeProfile);
|
|
199
|
+
}
|
|
200
|
+
export function clearChannelProfile(channel) {
|
|
201
|
+
delete channelProfiles[channel];
|
|
202
|
+
saveModeFile(claudeMode, activeBackend, claudeModel, activeProfile);
|
|
203
|
+
}
|
|
204
|
+
export function getChannelProfiles() {
|
|
205
|
+
return { ...channelProfiles };
|
|
206
|
+
}
|
|
207
|
+
export function getDefaultAgent() { return defaultAgent; }
|
|
208
|
+
export function setDefaultAgent(name) {
|
|
209
|
+
defaultAgent = name;
|
|
210
|
+
saveModeFile(claudeMode, activeBackend, claudeModel, activeProfile, defaultAgent);
|
|
211
|
+
}
|
|
212
|
+
export function switchMode() {
|
|
213
|
+
const oldMode = claudeMode;
|
|
214
|
+
claudeMode = claudeMode === 'plan' ? 'api' : 'plan';
|
|
215
|
+
configureEnvForMode(claudeMode);
|
|
216
|
+
saveModeFile(claudeMode, activeBackend, claudeModel);
|
|
217
|
+
return { oldMode, newMode: claudeMode };
|
|
218
|
+
}
|
|
219
|
+
export function isApiRateLimitError(errorMessage) {
|
|
220
|
+
if (!errorMessage)
|
|
221
|
+
return false;
|
|
222
|
+
const msg = errorMessage.toLowerCase();
|
|
223
|
+
return msg.includes('rate limit') || msg.includes('rate_limit') ||
|
|
224
|
+
msg.includes('overloaded') || msg.includes('529') ||
|
|
225
|
+
msg.includes('too many requests') || msg.includes('quota');
|
|
226
|
+
}
|
|
227
|
+
export function isRetryableResult(result) {
|
|
228
|
+
return result?.rateLimited === true;
|
|
229
|
+
}
|
|
230
|
+
export function isRetryableError(error) {
|
|
231
|
+
return isApiRateLimitError(error?.message);
|
|
232
|
+
}
|
|
233
|
+
export function configureEnvForMode(mode, metadata) {
|
|
234
|
+
if (isGatewayHealthy()) {
|
|
235
|
+
const url = gatewayModeUrl(mode, metadata);
|
|
236
|
+
process.env.ANTHROPIC_BASE_URL = url;
|
|
237
|
+
delete process.env.ANTHROPIC_API_KEY;
|
|
238
|
+
return url;
|
|
239
|
+
}
|
|
240
|
+
// Gateway unhealthy — fallback to direct connection
|
|
241
|
+
log.info(`Gateway unhealthy — using direct Anthropic connection (mode=${mode})`);
|
|
242
|
+
if (mode === 'plan') {
|
|
243
|
+
// Plan mode direct: delete everything, let Claude Code use OAuth
|
|
244
|
+
delete process.env.ANTHROPIC_API_KEY;
|
|
245
|
+
delete process.env.ANTHROPIC_BASE_URL;
|
|
246
|
+
return undefined;
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
// API mode direct: restore saved API key and base URL
|
|
250
|
+
applySavedApiEnv();
|
|
251
|
+
const saved = getSavedApiEnv();
|
|
252
|
+
if (saved.ANTHROPIC_BASE_URL) {
|
|
253
|
+
process.env.ANTHROPIC_BASE_URL = saved.ANTHROPIC_BASE_URL;
|
|
254
|
+
return saved.ANTHROPIC_BASE_URL;
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
delete process.env.ANTHROPIC_BASE_URL;
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
export function setGatewayMode(mode) {
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
const payload = JSON.stringify({ mode });
|
|
265
|
+
const modeUrl = `${GATEWAY_URL}/mode`;
|
|
266
|
+
const parsed = new URL(modeUrl);
|
|
267
|
+
const req = http.request({
|
|
268
|
+
hostname: parsed.hostname,
|
|
269
|
+
port: parsed.port,
|
|
270
|
+
path: parsed.pathname,
|
|
271
|
+
method: 'POST',
|
|
272
|
+
headers: {
|
|
273
|
+
'Content-Type': 'application/json',
|
|
274
|
+
'Content-Length': Buffer.byteLength(payload),
|
|
275
|
+
},
|
|
276
|
+
timeout: 3000,
|
|
277
|
+
}, (res) => {
|
|
278
|
+
let data = '';
|
|
279
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
280
|
+
res.on('end', () => {
|
|
281
|
+
if (res.statusCode === 200) {
|
|
282
|
+
resolve(data);
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
reject(new Error(`Gateway /mode returned ${res.statusCode}: ${data}`));
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
req.on('error', reject);
|
|
290
|
+
req.on('timeout', () => { req.destroy(); reject(new Error('Gateway /mode timeout')); });
|
|
291
|
+
req.write(payload);
|
|
292
|
+
req.end();
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
export function resolveAgentModel({ profileName = null, modelOverride = null } = {}) {
|
|
296
|
+
if (modelOverride)
|
|
297
|
+
return modelOverride;
|
|
298
|
+
if (profileName)
|
|
299
|
+
return getProfileModel(profileName);
|
|
300
|
+
return claudeModel;
|
|
301
|
+
}
|
|
302
|
+
export function detectBillingMode() {
|
|
303
|
+
try {
|
|
304
|
+
const modeState = loadModeFile();
|
|
305
|
+
if (modeState.claudeMode === 'plan' || modeState.mode === 'plan')
|
|
306
|
+
return 'plan';
|
|
307
|
+
}
|
|
308
|
+
catch { }
|
|
309
|
+
return 'api';
|
|
310
|
+
}
|
|
311
|
+
// Apply persisted mode on startup — route through gateway if healthy, else direct
|
|
312
|
+
configureEnvForMode(claudeMode);
|
|
313
|
+
export { GATEWAY_ANTHROPIC_URL, saveModeFile, loadModeFile, };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { AgentAdapter, AgentSpawnConfig } from '../../agent-adapter/index.js';
|
|
2
|
+
import type { AgentHandle, AgentResult } from '../../core/types/agent-types.js';
|
|
3
|
+
export interface AgentConfig {
|
|
4
|
+
model: string;
|
|
5
|
+
backend: string;
|
|
6
|
+
mode: string | null;
|
|
7
|
+
extraEnv?: Record<string, string>;
|
|
8
|
+
extraOption?: Record<string, string>;
|
|
9
|
+
/** DR-0012: Claude adapter mode (print/tui). Only meaningful for backend='claude'. */
|
|
10
|
+
claudeBackend?: 'print' | 'tui';
|
|
11
|
+
}
|
|
12
|
+
export interface RunAgentOptions {
|
|
13
|
+
profileName?: string | null;
|
|
14
|
+
sessionId?: string | null;
|
|
15
|
+
sessionKey?: string | null;
|
|
16
|
+
channel?: string;
|
|
17
|
+
files?: unknown[];
|
|
18
|
+
callbackSource?: string | null;
|
|
19
|
+
scheduleTaskId?: string | null;
|
|
20
|
+
isUserInitiated?: boolean;
|
|
21
|
+
project?: string;
|
|
22
|
+
trigger?: string;
|
|
23
|
+
/** Cortex execution context surfaced to the MCP server child as CORTEX_THREAD_ID/PROFILE/PROJECT/SESSION_NAME env vars.
|
|
24
|
+
* Read by the cortex_context / cortex_schedule_* MCP tools so LLMs can self-discover their thread and target schedules
|
|
25
|
+
* at the current thread / session without guessing IDs. */
|
|
26
|
+
threadId?: string | null;
|
|
27
|
+
sessionName?: string | null;
|
|
28
|
+
/** Cortex execution record id, surfaced as CORTEX_EXECUTION_ID to subprocess env. */
|
|
29
|
+
executionId?: string | null;
|
|
30
|
+
/** When true, load only core MCP server (remote_* tools). Used by template thread sessions.
|
|
31
|
+
* Default (undefined/false) loads full MCP config with cortex-ext tools. */
|
|
32
|
+
useCoreMcp?: boolean;
|
|
33
|
+
onProgress?: ((progress: any) => void) | null;
|
|
34
|
+
onAssistantMessage?: ((msg: string) => void) | null;
|
|
35
|
+
onToolUse?: ((name: string, input: any) => void) | null;
|
|
36
|
+
onFallback?: (current: AgentConfig, next: AgentConfig, result: AgentResult | null, error?: Error) => Promise<void>;
|
|
37
|
+
[key: string]: any;
|
|
38
|
+
}
|
|
39
|
+
declare function buildSpawnConfig(options: RunAgentOptions, config: AgentConfig, anthropicBaseUrl: string | undefined): AgentSpawnConfig;
|
|
40
|
+
export declare function runWithAdapter(adapter: AgentAdapter, message: string, options: RunAgentOptions, config: AgentConfig, anthropicBaseUrl: string | undefined): AgentHandle;
|
|
41
|
+
export declare function runAgentOnce(message: string, options: RunAgentOptions, config: AgentConfig): AgentHandle;
|
|
42
|
+
export declare function runAgent(message: string, options?: RunAgentOptions): AgentHandle;
|
|
43
|
+
/** Returns true when every mode in the profile's fallback chain is currently rate-limited.
|
|
44
|
+
* Enables job runners to skip claiming/running when all paths are blocked. */
|
|
45
|
+
export declare function allConfigsRateLimited(profileName: string | null): boolean;
|
|
46
|
+
export declare const _test: {
|
|
47
|
+
runWithAdapter: typeof runWithAdapter;
|
|
48
|
+
buildSpawnConfig: typeof buildSpawnConfig;
|
|
49
|
+
};
|
|
50
|
+
export { closeSession, closeSessionsByPrefix, closeAllSessions, _test as claudeTest, } from '../../agent-adapter/claude/adapter.js';
|
|
51
|
+
export { shutdownCodex, buildMcpBlock } from '../../agent-adapter/codex/adapter.js';
|
|
52
|
+
export { getCurrentPlanFilePath } from '../../agent-adapter/claude/event-parser.js';
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// input: config, agent-adapter, profile-manager, agent-types
|
|
2
|
+
// output: runAgent / runAgentOnce / runWithAdapter + fallback chain + bridge helper re-exports
|
|
3
|
+
// pos: domain/agents — sole agent execution path [S11]
|
|
4
|
+
import { getAdapter } from '../../agent-adapter/index.js';
|
|
5
|
+
import { resolveProfileConfig } from './profile-manager.js';
|
|
6
|
+
import { recordCost } from '../costs/cost-tracker.js';
|
|
7
|
+
import { configureEnvForMode, isRetryableResult, isRetryableError } from './config.js';
|
|
8
|
+
import { isModeRateLimited, isThrottled } from '../costs/rate-limit-throttle.js';
|
|
9
|
+
import { createLogger } from '../../core/log.js';
|
|
10
|
+
import { loadCortexRules } from '../memory/rules-loader.js';
|
|
11
|
+
const log = createLogger('facade');
|
|
12
|
+
// --- Adapter execution ---
|
|
13
|
+
function buildSpawnConfig(options, config, anthropicBaseUrl) {
|
|
14
|
+
// Pack the Cortex execution context only if at least one field is set, so adapters can
|
|
15
|
+
// skip writing CORTEX_* env vars / route-context fields when there's nothing to report.
|
|
16
|
+
const ctx = {
|
|
17
|
+
threadId: options.threadId ?? null,
|
|
18
|
+
profile: options.profileName ?? null,
|
|
19
|
+
project: options.project ?? null,
|
|
20
|
+
sessionName: options.sessionName ?? null,
|
|
21
|
+
executionId: options.executionId ?? null,
|
|
22
|
+
useCoreMcp: options.useCoreMcp ?? undefined,
|
|
23
|
+
};
|
|
24
|
+
const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp);
|
|
25
|
+
// Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
|
|
26
|
+
// Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
|
|
27
|
+
const rules = loadCortexRules();
|
|
28
|
+
const appendSystemPrompt = rules.global.length > 0
|
|
29
|
+
? rules.global.map(r => r.body).join('\n\n---\n\n')
|
|
30
|
+
: undefined;
|
|
31
|
+
return {
|
|
32
|
+
sessionId: options.sessionId ?? null,
|
|
33
|
+
sessionKey: options.sessionKey || options.channel || 'default',
|
|
34
|
+
resume: !!options.sessionId,
|
|
35
|
+
model: config.model,
|
|
36
|
+
systemPrompt: typeof options.systemPrompt === 'string' ? options.systemPrompt : undefined,
|
|
37
|
+
outputStyle: typeof options.outputStyle === 'string' ? options.outputStyle : undefined,
|
|
38
|
+
pluginDirs: Array.isArray(options.pluginDirs) ? options.pluginDirs : undefined,
|
|
39
|
+
env: config.extraEnv && Object.keys(config.extraEnv).length > 0 ? config.extraEnv : undefined,
|
|
40
|
+
extraOption: config.extraOption && Object.keys(config.extraOption).length > 0 ? config.extraOption : undefined,
|
|
41
|
+
claudeBackend: config.claudeBackend,
|
|
42
|
+
channel: options.channel,
|
|
43
|
+
claudeAgent: options.claudeAgent ?? undefined,
|
|
44
|
+
callbackSource: options.callbackSource ?? undefined,
|
|
45
|
+
scheduleTaskId: options.scheduleTaskId ?? undefined,
|
|
46
|
+
isUserInitiated: !!options.isUserInitiated,
|
|
47
|
+
rawTools: typeof options.tools === 'string' ? options.tools : undefined,
|
|
48
|
+
anthropicBaseUrl,
|
|
49
|
+
cortexContext: hasContext ? ctx : undefined,
|
|
50
|
+
appendSystemPrompt,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function runWithAdapter(adapter, message, options, config, anthropicBaseUrl) {
|
|
54
|
+
const spawnConfig = buildSpawnConfig(options, config, anthropicBaseUrl);
|
|
55
|
+
const proc = adapter.spawn(spawnConfig);
|
|
56
|
+
const attachments = (options.files || []).map((f) => ({
|
|
57
|
+
mimeType: f.mimetype ?? f.mimeType,
|
|
58
|
+
path: f.localPath ?? f.path,
|
|
59
|
+
}));
|
|
60
|
+
const turnPromise = proc.send({ text: message, attachments });
|
|
61
|
+
// Drive legacy callbacks from the normalized event stream
|
|
62
|
+
const eventLoop = (async () => {
|
|
63
|
+
try {
|
|
64
|
+
for await (const event of proc.events) {
|
|
65
|
+
switch (event.type) {
|
|
66
|
+
case 'assistant_text':
|
|
67
|
+
options.onAssistantMessage?.(event.text);
|
|
68
|
+
break;
|
|
69
|
+
case 'tool_use':
|
|
70
|
+
options.onToolUse?.(event.name, event.input);
|
|
71
|
+
break;
|
|
72
|
+
case 'turn_progress':
|
|
73
|
+
options.onProgress?.({
|
|
74
|
+
num_turns: event.numTurns,
|
|
75
|
+
total_cost_usd: null,
|
|
76
|
+
duration_ms: null,
|
|
77
|
+
});
|
|
78
|
+
break;
|
|
79
|
+
case 'turn_complete':
|
|
80
|
+
options.onProgress?.({
|
|
81
|
+
num_turns: event.numTurns,
|
|
82
|
+
total_cost_usd: event.totalCostUsd,
|
|
83
|
+
duration_ms: null,
|
|
84
|
+
});
|
|
85
|
+
return;
|
|
86
|
+
case 'cost_record':
|
|
87
|
+
// All three backends emit cost_record via their event parser/adapter.
|
|
88
|
+
// This is the single recording point for all LLM costs.
|
|
89
|
+
recordCost({
|
|
90
|
+
project: options.project || 'general',
|
|
91
|
+
trigger: options.trigger || 'unknown',
|
|
92
|
+
cost_usd: event.cost_usd,
|
|
93
|
+
backend: adapter.backend,
|
|
94
|
+
mode: config.mode || 'api',
|
|
95
|
+
source: 'estimate',
|
|
96
|
+
input_tokens: event.tokens_in,
|
|
97
|
+
output_tokens: event.tokens_out,
|
|
98
|
+
provider: event.provider || undefined,
|
|
99
|
+
model: event.model || undefined,
|
|
100
|
+
}).catch(err => log.warn('recordCost failed:', err?.message ?? err));
|
|
101
|
+
break;
|
|
102
|
+
case 'plan_written':
|
|
103
|
+
options.onPlanWritten?.({ path: event.path, content: event.content, toolUseId: event.toolUseId });
|
|
104
|
+
break;
|
|
105
|
+
case 'ask_user_question':
|
|
106
|
+
options.onAskUserQuestion?.({ toolUseId: event.toolUseId, questions: event.questions });
|
|
107
|
+
break;
|
|
108
|
+
default:
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
log.warn('runWithAdapter event loop error:', e?.message ?? e);
|
|
115
|
+
}
|
|
116
|
+
})();
|
|
117
|
+
const promise = (async () => {
|
|
118
|
+
try {
|
|
119
|
+
const [result] = await Promise.all([turnPromise, eventLoop]);
|
|
120
|
+
return result;
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
await eventLoop.catch(() => { });
|
|
124
|
+
throw err;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
await proc.close().catch(() => { });
|
|
128
|
+
}
|
|
129
|
+
})();
|
|
130
|
+
return {
|
|
131
|
+
promise,
|
|
132
|
+
kill: () => proc.kill(),
|
|
133
|
+
get sessionId() { return proc.sessionId; },
|
|
134
|
+
agentProcess: proc,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
export function runAgentOnce(message, options, config) {
|
|
138
|
+
const effectiveMode = config.mode || 'api';
|
|
139
|
+
const metadata = {};
|
|
140
|
+
if (options.project)
|
|
141
|
+
metadata.project = options.project;
|
|
142
|
+
if (options.trigger)
|
|
143
|
+
metadata.trigger = options.trigger;
|
|
144
|
+
const anthropicBaseUrl = configureEnvForMode(effectiveMode, Object.keys(metadata).length > 0 ? metadata : undefined);
|
|
145
|
+
const adapter = getAdapter(config.backend);
|
|
146
|
+
return runWithAdapter(adapter, message, options, config, anthropicBaseUrl);
|
|
147
|
+
}
|
|
148
|
+
export function runAgent(message, options = {}) {
|
|
149
|
+
const profileConfig = resolveProfileConfig(options.profileName);
|
|
150
|
+
const configs = [
|
|
151
|
+
{ model: profileConfig.model, backend: profileConfig.backend, mode: profileConfig.mode, extraEnv: profileConfig.extraEnv, extraOption: profileConfig.extraOption, claudeBackend: profileConfig.claudeBackend },
|
|
152
|
+
...(profileConfig.fallback || []),
|
|
153
|
+
];
|
|
154
|
+
// Single config — no fallback wrapper needed
|
|
155
|
+
if (configs.length <= 1) {
|
|
156
|
+
const effectiveMode = configs[0].mode || 'api';
|
|
157
|
+
if (isModeRateLimited(effectiveMode) && !options.isUserInitiated) {
|
|
158
|
+
return {
|
|
159
|
+
promise: Promise.resolve({
|
|
160
|
+
sessionId: null,
|
|
161
|
+
total_cost_usd: null,
|
|
162
|
+
num_turns: null,
|
|
163
|
+
rateLimited: true,
|
|
164
|
+
rateLimitMessage: `Mode ${effectiveMode} is rate-limited`,
|
|
165
|
+
planFilePath: null,
|
|
166
|
+
enteredPlanMode: false,
|
|
167
|
+
exitedPlanMode: false,
|
|
168
|
+
finalOutput: null,
|
|
169
|
+
}),
|
|
170
|
+
kill: () => false,
|
|
171
|
+
sessionId: null,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
return runAgentOnce(message, options, configs[0]);
|
|
175
|
+
}
|
|
176
|
+
// Multiple configs — wrap with fallback chain
|
|
177
|
+
let currentHandle = null;
|
|
178
|
+
let killed = false;
|
|
179
|
+
const promise = (async () => {
|
|
180
|
+
for (let i = 0; i < configs.length; i++) {
|
|
181
|
+
const config = configs[i];
|
|
182
|
+
const isLast = i === configs.length - 1;
|
|
183
|
+
const attemptOptions = i === 0 ? options : { ...options, sessionId: null };
|
|
184
|
+
// Pre-flight: skip modes already known rate-limited without spawning CLI
|
|
185
|
+
const effectiveMode = config.mode || 'api';
|
|
186
|
+
if (isModeRateLimited(effectiveMode) && !options.isUserInitiated) {
|
|
187
|
+
if (isLast) {
|
|
188
|
+
return {
|
|
189
|
+
sessionId: null,
|
|
190
|
+
total_cost_usd: null,
|
|
191
|
+
num_turns: null,
|
|
192
|
+
rateLimited: true,
|
|
193
|
+
rateLimitMessage: `Mode ${effectiveMode} is rate-limited`,
|
|
194
|
+
planFilePath: null,
|
|
195
|
+
enteredPlanMode: false,
|
|
196
|
+
exitedPlanMode: false,
|
|
197
|
+
finalOutput: null,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
log.info(`${config.model}/${effectiveMode} rate-limited, skipping to fallback[${i}]`);
|
|
201
|
+
if (options.onFallback)
|
|
202
|
+
await options.onFallback(config, configs[i + 1], null);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
currentHandle = runAgentOnce(message, attemptOptions, config);
|
|
206
|
+
try {
|
|
207
|
+
const result = await currentHandle.promise;
|
|
208
|
+
if (!isRetryableResult(result) || isLast) {
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
211
|
+
const modeLabel = config.mode || 'api';
|
|
212
|
+
log.info(`${config.model}/${modeLabel} rate limited, trying fallback[${i}]`);
|
|
213
|
+
if (options.onFallback) {
|
|
214
|
+
await options.onFallback(config, configs[i + 1], result);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
if (killed)
|
|
219
|
+
throw error;
|
|
220
|
+
if (!isRetryableError(error) || isLast)
|
|
221
|
+
throw error;
|
|
222
|
+
const modeLabel = config.mode || 'api';
|
|
223
|
+
log.info(`${config.model}/${modeLabel} retryable error, trying fallback[${i}]`);
|
|
224
|
+
if (options.onFallback) {
|
|
225
|
+
await options.onFallback(config, configs[i + 1], null, error);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
throw new Error('All fallback configs exhausted without result');
|
|
230
|
+
})();
|
|
231
|
+
return {
|
|
232
|
+
promise,
|
|
233
|
+
kill() {
|
|
234
|
+
killed = true;
|
|
235
|
+
return currentHandle?.kill() ?? false;
|
|
236
|
+
},
|
|
237
|
+
get sessionId() { return currentHandle?.sessionId ?? null; },
|
|
238
|
+
get agentProcess() { return currentHandle?.agentProcess; },
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/** Returns true when every mode in the profile's fallback chain is currently rate-limited.
|
|
242
|
+
* Enables job runners to skip claiming/running when all paths are blocked. */
|
|
243
|
+
export function allConfigsRateLimited(profileName) {
|
|
244
|
+
if (!isThrottled())
|
|
245
|
+
return false;
|
|
246
|
+
try {
|
|
247
|
+
const config = resolveProfileConfig(profileName);
|
|
248
|
+
const primaryMode = config.mode || 'api';
|
|
249
|
+
const allModes = [primaryMode, ...config.fallback.map(f => f.mode || primaryMode)];
|
|
250
|
+
return allModes.every(m => isModeRateLimited(m));
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
return false;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
// Exposed for tests/run-with-adapter.test.ts; not intended as a public API.
|
|
257
|
+
export const _test = {
|
|
258
|
+
runWithAdapter,
|
|
259
|
+
buildSpawnConfig,
|
|
260
|
+
};
|
|
261
|
+
// --- Bridge helper re-exports (replacing claude-bridge.ts / codex-bridge.ts) ---
|
|
262
|
+
export { closeSession, closeSessionsByPrefix, closeAllSessions, _test as claudeTest, } from '../../agent-adapter/claude/adapter.js';
|
|
263
|
+
export { shutdownCodex, buildMcpBlock } from '../../agent-adapter/codex/adapter.js';
|
|
264
|
+
export { getCurrentPlanFilePath } from '../../agent-adapter/claude/event-parser.js';
|