@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,1299 @@
|
|
|
1
|
+
// input: @clack/prompts, fs, path, os, yaml, @core/config-generator
|
|
2
|
+
// output: runInit — interactive CORTEX_HOME initialization
|
|
3
|
+
// pos: cortex init subcommand — backend selection & install, gateway usage opt-in,
|
|
4
|
+
// creates directory structure, generates .env, copies default configs,
|
|
5
|
+
// auto-generates mcp-config.json and mode.json
|
|
6
|
+
//
|
|
7
|
+
// INSTALL_ROOT is computed from import.meta.url (agent-server dir, 2 levels up from dist/entry/).
|
|
8
|
+
// DATA_DIR is resolved via the --home arg, $CORTEX_HOME env, or ~/.cortex/ default.
|
|
9
|
+
// Run with: node dist/entry/cli.js init [--home <path>] [--force]
|
|
10
|
+
import { mkdirSync, writeFileSync, copyFileSync, existsSync, readFileSync, readdirSync } from 'fs';
|
|
11
|
+
import { execSync } from 'child_process';
|
|
12
|
+
import * as path from 'path';
|
|
13
|
+
import * as os from 'os';
|
|
14
|
+
import { fileURLToPath } from 'url';
|
|
15
|
+
import { createInterface } from 'readline/promises';
|
|
16
|
+
import { stdin as processStdin } from 'process';
|
|
17
|
+
import * as clack from '@clack/prompts';
|
|
18
|
+
import * as yaml from 'yaml';
|
|
19
|
+
import { buildFullConfig, buildCoreConfig, buildTuiConfig } from '../core/config-generator.js';
|
|
20
|
+
import { discoverEndpoints, generateGatewayYaml, writeGatewayYaml } from '../core/gateway-generator.js';
|
|
21
|
+
import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
|
|
22
|
+
import { createLogger } from '../core/log.js';
|
|
23
|
+
import { INSTALL_ROOT, DEFAULTS_DIR } from '../core/utils.js';
|
|
24
|
+
// ─── Path computation (DATA_DIR resolved locally to support --home override) ──
|
|
25
|
+
const log = createLogger('init');
|
|
26
|
+
// MODULE_DIR kept for any consumers that still derive paths locally; the canonical roots
|
|
27
|
+
// (INSTALL_ROOT, DEFAULTS_DIR) come from @core/paths via @core/utils.
|
|
28
|
+
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
/** Resolve DATA_DIR from --home arg, $CORTEX_HOME env, or ~/.cortex/ default. */
|
|
30
|
+
export function getResolvedPaths(homeDir) {
|
|
31
|
+
const dataDir = homeDir
|
|
32
|
+
? path.resolve(homeDir)
|
|
33
|
+
: process.env.CORTEX_HOME
|
|
34
|
+
? path.resolve(process.env.CORTEX_HOME)
|
|
35
|
+
: path.join(os.homedir(), '.cortex');
|
|
36
|
+
const contextDir = path.join(dataDir, 'context');
|
|
37
|
+
return {
|
|
38
|
+
DATA_DIR: dataDir,
|
|
39
|
+
CONFIG_DIR: path.join(dataDir, 'config'),
|
|
40
|
+
STORE_DIR: path.join(dataDir, 'data'),
|
|
41
|
+
CONTEXT_DIR: contextDir,
|
|
42
|
+
PROJECTS_DIR: process.env.CORTEX_PROJECTS_DIR
|
|
43
|
+
? path.resolve(process.env.CORTEX_PROJECTS_DIR)
|
|
44
|
+
: path.join(contextDir, 'projects'),
|
|
45
|
+
WORKSPACE_DIR: path.join(dataDir, 'tmp'),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Parse "mode:model" stdin string into a ModelChoice. Returns undefined for empty/invalid. */
|
|
49
|
+
function parseChoiceLine(raw) {
|
|
50
|
+
if (!raw)
|
|
51
|
+
return undefined;
|
|
52
|
+
const trimmed = raw.trim();
|
|
53
|
+
if (!trimmed)
|
|
54
|
+
return undefined;
|
|
55
|
+
const colonIdx = trimmed.indexOf(':');
|
|
56
|
+
if (colonIdx <= 0 || colonIdx === trimmed.length - 1)
|
|
57
|
+
return undefined;
|
|
58
|
+
return {
|
|
59
|
+
mode: trimmed.substring(0, colonIdx).trim(),
|
|
60
|
+
model: trimmed.substring(colonIdx + 1).trim(),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
// ─── Dot env generation ──────────────────────────────────────────
|
|
64
|
+
/** Generate .env content — includes CORTEX_MACHINE, CORTEX_PLATFORM, and platform-specific tokens. */
|
|
65
|
+
export function generateDotEnvContent(answers) {
|
|
66
|
+
const lines = [
|
|
67
|
+
'# Cortex Configuration',
|
|
68
|
+
'# Generated by `cortex init`',
|
|
69
|
+
'',
|
|
70
|
+
`CORTEX_MACHINE=${answers.machineName}`,
|
|
71
|
+
];
|
|
72
|
+
if (answers.platform && answers.platform !== 'none') {
|
|
73
|
+
lines.push(`CORTEX_PLATFORM=${answers.platform}`);
|
|
74
|
+
lines.push('');
|
|
75
|
+
if (answers.platform === 'slack' && answers.slackConfig) {
|
|
76
|
+
lines.push('# Slack configuration');
|
|
77
|
+
lines.push(`SLACK_BOT_TOKEN=${answers.slackConfig.botToken}`);
|
|
78
|
+
lines.push(`SLACK_SIGNING_SECRET=${answers.slackConfig.signingSecret}`);
|
|
79
|
+
lines.push(`SLACK_APP_TOKEN=${answers.slackConfig.appToken}`);
|
|
80
|
+
if (answers.slackConfig.adminChannel) {
|
|
81
|
+
lines.push(`CORTEX_ADMIN_CHANNEL=${answers.slackConfig.adminChannel}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
else if (answers.platform === 'feishu' && answers.feishuConfig) {
|
|
85
|
+
lines.push('# Feishu configuration');
|
|
86
|
+
lines.push(`FEISHU_APP_ID=${answers.feishuConfig.appId}`);
|
|
87
|
+
lines.push(`FEISHU_APP_SECRET=${answers.feishuConfig.appSecret}`);
|
|
88
|
+
if (answers.feishuConfig.encryptKey) {
|
|
89
|
+
lines.push(`FEISHU_ENCRYPT_KEY=${answers.feishuConfig.encryptKey}`);
|
|
90
|
+
}
|
|
91
|
+
if (answers.feishuConfig.verificationToken) {
|
|
92
|
+
lines.push(`FEISHU_VERIFICATION_TOKEN=${answers.feishuConfig.verificationToken}`);
|
|
93
|
+
}
|
|
94
|
+
if (answers.feishuConfig.domain) {
|
|
95
|
+
lines.push(`FEISHU_DOMAIN=${answers.feishuConfig.domain}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
lines.push('');
|
|
100
|
+
return lines.join('\n');
|
|
101
|
+
}
|
|
102
|
+
// ─── Configuration generation ────────────────────────────────────
|
|
103
|
+
/** Generate default mode.json content (compact JSON, single line). */
|
|
104
|
+
export function generateDefaultModeJson(primaryBackend = 'claude') {
|
|
105
|
+
return JSON.stringify({
|
|
106
|
+
mode: 'plan',
|
|
107
|
+
backend: primaryBackend,
|
|
108
|
+
claudeModel: 'opus',
|
|
109
|
+
activeProfile: '__active__',
|
|
110
|
+
defaultAgent: 'direct',
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Format resolved paths and initialization status for `cortex config` output. */
|
|
114
|
+
export function formatConfigOutput(paths, status) {
|
|
115
|
+
const lines = [
|
|
116
|
+
'Cortex configuration:',
|
|
117
|
+
` INSTALL_ROOT: ${paths.INSTALL_ROOT}`,
|
|
118
|
+
` DATA_DIR: ${paths.DATA_DIR}`,
|
|
119
|
+
` CONFIG_DIR: ${paths.CONFIG_DIR}`,
|
|
120
|
+
` STORE_DIR: ${paths.STORE_DIR}`,
|
|
121
|
+
` CONTEXT_DIR: ${paths.CONTEXT_DIR}`,
|
|
122
|
+
` PROJECTS_DIR: ${paths.PROJECTS_DIR}`,
|
|
123
|
+
` WORKSPACE_DIR: ${paths.WORKSPACE_DIR}`,
|
|
124
|
+
'',
|
|
125
|
+
'Status:',
|
|
126
|
+
` DATA_DIR: ${status.dataDirExists ? 'initialized' : 'not initialized'}`,
|
|
127
|
+
` .env: ${status.dotEnvExists ? 'found' : 'missing'}`,
|
|
128
|
+
` mcp-config.json: ${status.mcpConfigExists ? 'found' : 'missing'}`,
|
|
129
|
+
` mode.json: ${status.modeJsonExists ? 'found' : 'missing'}`,
|
|
130
|
+
];
|
|
131
|
+
return lines.join('\n');
|
|
132
|
+
}
|
|
133
|
+
// ─── Backend detection & installation ────────────────────────────
|
|
134
|
+
const BACKEND_INFO = {
|
|
135
|
+
claude: {
|
|
136
|
+
bin: 'claude',
|
|
137
|
+
npmPackage: '@anthropic-ai/claude-code',
|
|
138
|
+
label: 'Claude Code',
|
|
139
|
+
loginHint: 'Run `claude login` to authenticate.',
|
|
140
|
+
},
|
|
141
|
+
pi: {
|
|
142
|
+
bin: 'pi',
|
|
143
|
+
npmPackage: '@mariozechner/pi-coding-agent',
|
|
144
|
+
label: 'PI',
|
|
145
|
+
loginHint: 'Configure your provider in PI settings.',
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
// ─── Slack App Manifest ──────────────────────────────────────────
|
|
149
|
+
/** Slack App Manifest for Cortex bot. Users paste this when creating a Slack App via "From a manifest". */
|
|
150
|
+
export const SLACK_APP_MANIFEST = JSON.stringify({
|
|
151
|
+
display_information: {
|
|
152
|
+
name: 'Cortex',
|
|
153
|
+
description: 'Autonomous research agent',
|
|
154
|
+
background_color: '#2c2d30',
|
|
155
|
+
},
|
|
156
|
+
features: {
|
|
157
|
+
bot_user: {
|
|
158
|
+
display_name: 'Cortex',
|
|
159
|
+
always_online: true,
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
oauth_config: {
|
|
163
|
+
scopes: {
|
|
164
|
+
bot: [
|
|
165
|
+
'chat:write',
|
|
166
|
+
'im:history',
|
|
167
|
+
'im:write',
|
|
168
|
+
'reactions:read',
|
|
169
|
+
'reactions:write',
|
|
170
|
+
'users:read',
|
|
171
|
+
'commands',
|
|
172
|
+
'app_mentions:read',
|
|
173
|
+
'channels:history',
|
|
174
|
+
'channels:read',
|
|
175
|
+
'groups:history',
|
|
176
|
+
'files:read',
|
|
177
|
+
'files:write',
|
|
178
|
+
'emoji:read',
|
|
179
|
+
'pins:read',
|
|
180
|
+
'pins:write',
|
|
181
|
+
],
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
settings: {
|
|
185
|
+
event_subscriptions: {
|
|
186
|
+
bot_events: [
|
|
187
|
+
'message.im',
|
|
188
|
+
'message.channels',
|
|
189
|
+
'message.groups',
|
|
190
|
+
'app_mention',
|
|
191
|
+
],
|
|
192
|
+
},
|
|
193
|
+
interactivity: {
|
|
194
|
+
is_enabled: false,
|
|
195
|
+
},
|
|
196
|
+
org_deploy_enabled: false,
|
|
197
|
+
socket_mode_enabled: true,
|
|
198
|
+
token_rotation_enabled: false,
|
|
199
|
+
},
|
|
200
|
+
}, null, 2);
|
|
201
|
+
// ─── Clipboard utilities ─────────────────────────────────────────
|
|
202
|
+
/**
|
|
203
|
+
* Copy text to system clipboard.
|
|
204
|
+
* Tries OSC 52 escape sequence first (works in modern terminals without external tools,
|
|
205
|
+
* same approach Claude Code uses), then falls back to platform-specific CLI tools.
|
|
206
|
+
* Returns true on success.
|
|
207
|
+
*/
|
|
208
|
+
function copyToClipboard(text) {
|
|
209
|
+
// 1. OSC 52 escape sequence — no external tool needed, works in VS Code, iTerm2,
|
|
210
|
+
// Windows Terminal, Kitty, WezTerm, foot, and most modern terminal emulators.
|
|
211
|
+
if (process.stdout.isTTY) {
|
|
212
|
+
const b64 = Buffer.from(text, 'utf-8').toString('base64');
|
|
213
|
+
// BEL-terminated variant (wider terminal support than ST)
|
|
214
|
+
process.stdout.write(`\x1b]52;c;${b64}\x07`);
|
|
215
|
+
// Assume success — terminals silently ignore OSC 52 if unsupported/disabled
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
// 2. Platform-specific external clipboard tools (fallback for non-TTY)
|
|
219
|
+
const commands = process.platform === 'darwin'
|
|
220
|
+
? [['pbcopy', []]]
|
|
221
|
+
: process.platform === 'win32'
|
|
222
|
+
? [['clip', []]]
|
|
223
|
+
: [
|
|
224
|
+
['xclip', ['-selection', 'clipboard']],
|
|
225
|
+
['wl-copy', []],
|
|
226
|
+
['xsel', ['--clipboard', '--input']],
|
|
227
|
+
];
|
|
228
|
+
for (const [bin, args] of commands) {
|
|
229
|
+
try {
|
|
230
|
+
const cmd = [bin, ...args].join(' ');
|
|
231
|
+
execSync(cmd, { input: text, stdio: 'pipe', timeout: 3000 });
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
/** Prompt user to press 'c' to copy manifest to clipboard. Single-key, no Enter needed. */
|
|
241
|
+
async function promptCopyManifestToClipboard(manifest) {
|
|
242
|
+
if (!process.stdin.isTTY)
|
|
243
|
+
return; // Non-interactive mode, skip
|
|
244
|
+
process.stdout.write('\nPress "c" to copy manifest to clipboard (any other key to skip)...');
|
|
245
|
+
return new Promise((resolve) => {
|
|
246
|
+
const wasRaw = process.stdin.isRaw ?? false;
|
|
247
|
+
try {
|
|
248
|
+
process.stdin.setRawMode(true);
|
|
249
|
+
process.stdin.resume();
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
process.stdout.write('\r\x1b[K');
|
|
253
|
+
resolve();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const onData = (key) => {
|
|
257
|
+
const ch = key.toString();
|
|
258
|
+
// Erase the typed character from screen
|
|
259
|
+
process.stdout.write('\b \b');
|
|
260
|
+
// Restore stdin to previous state
|
|
261
|
+
try {
|
|
262
|
+
process.stdin.setRawMode(wasRaw);
|
|
263
|
+
process.stdin.pause();
|
|
264
|
+
}
|
|
265
|
+
catch { /* best effort */ }
|
|
266
|
+
process.stdin.removeListener('data', onData);
|
|
267
|
+
// Clear the prompt line
|
|
268
|
+
process.stdout.write('\r\x1b[K');
|
|
269
|
+
if (ch.toLowerCase() === 'c') {
|
|
270
|
+
const ok = copyToClipboard(manifest);
|
|
271
|
+
if (ok) {
|
|
272
|
+
clack.log.success('Manifest copied to clipboard!');
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
clack.log.warn('Could not copy. If running in a terminal, ensure OSC 52 is enabled.');
|
|
276
|
+
clack.log.info('The manifest text is shown above — please copy it manually.');
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
resolve();
|
|
280
|
+
};
|
|
281
|
+
process.stdin.on('data', onData);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
/** Parse existing Slack configuration from a .env file. Returns null if no Slack config found. */
|
|
285
|
+
function parseExistingEnvSlackConfig(envPath) {
|
|
286
|
+
if (!existsSync(envPath))
|
|
287
|
+
return null;
|
|
288
|
+
try {
|
|
289
|
+
const content = readFileSync(envPath, 'utf-8');
|
|
290
|
+
const result = {};
|
|
291
|
+
for (const line of content.split('\n')) {
|
|
292
|
+
const trimmed = line.trim();
|
|
293
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
294
|
+
continue;
|
|
295
|
+
const eqIdx = trimmed.indexOf('=');
|
|
296
|
+
if (eqIdx === -1)
|
|
297
|
+
continue;
|
|
298
|
+
const key = trimmed.substring(0, eqIdx).trim();
|
|
299
|
+
const value = trimmed.substring(eqIdx + 1).trim();
|
|
300
|
+
if (key === 'SLACK_SIGNING_SECRET')
|
|
301
|
+
result.signingSecret = value;
|
|
302
|
+
else if (key === 'SLACK_APP_TOKEN')
|
|
303
|
+
result.appToken = value;
|
|
304
|
+
else if (key === 'SLACK_BOT_TOKEN')
|
|
305
|
+
result.botToken = value;
|
|
306
|
+
else if (key === 'CORTEX_ADMIN_CHANNEL')
|
|
307
|
+
result.adminChannel = value;
|
|
308
|
+
}
|
|
309
|
+
if (!result.signingSecret && !result.appToken && !result.botToken)
|
|
310
|
+
return null;
|
|
311
|
+
return result;
|
|
312
|
+
}
|
|
313
|
+
catch {
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
/** Check whether a backend binary is on PATH. */
|
|
318
|
+
export function isBackendInstalled(backend) {
|
|
319
|
+
const cmd = process.platform === 'win32' ? 'where' : 'which';
|
|
320
|
+
const { bin } = BACKEND_INFO[backend];
|
|
321
|
+
try {
|
|
322
|
+
execSync(`${cmd} ${bin}`, { stdio: 'pipe' });
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return false;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/** Return the npm install command for a backend. */
|
|
330
|
+
export function getInstallCommand(backend) {
|
|
331
|
+
return `npm install -g ${BACKEND_INFO[backend].npmPackage}`;
|
|
332
|
+
}
|
|
333
|
+
/** Detect GPU count via nvidia-smi. Returns 0 if nvidia-smi is unavailable or no GPUs found. */
|
|
334
|
+
function detectGpuCount() {
|
|
335
|
+
try {
|
|
336
|
+
const result = execSync('nvidia-smi --query-gpu=count --format=csv,noheader', {
|
|
337
|
+
stdio: 'pipe',
|
|
338
|
+
encoding: 'utf-8',
|
|
339
|
+
timeout: 5000,
|
|
340
|
+
});
|
|
341
|
+
const count = parseInt(result.trim(), 10);
|
|
342
|
+
return Number.isFinite(count) ? count : 0;
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
return 0;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** Check and install selected backends. Returns list of backends that were installed. */
|
|
349
|
+
async function checkAndInstallBackends(backends) {
|
|
350
|
+
for (const backend of backends) {
|
|
351
|
+
const info = BACKEND_INFO[backend];
|
|
352
|
+
const installed = isBackendInstalled(backend);
|
|
353
|
+
if (installed) {
|
|
354
|
+
clack.log.success(`${info.label} is already installed.`);
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
const s = clack.spinner();
|
|
358
|
+
s.start(`Installing ${info.label}...`);
|
|
359
|
+
try {
|
|
360
|
+
execSync(getInstallCommand(backend), { stdio: 'pipe', timeout: 120_000 });
|
|
361
|
+
s.stop(`${info.label} installed successfully.`);
|
|
362
|
+
}
|
|
363
|
+
catch (err) {
|
|
364
|
+
s.stop(`Failed to install ${info.label}.`);
|
|
365
|
+
clack.log.error(`Installation failed. Install manually: ${getInstallCommand(backend)}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
clack.log.info(info.loginHint);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
// ─── Gateway usage config ────────────────────────────────────────
|
|
372
|
+
/** Path to aistatus config file. */
|
|
373
|
+
export function getAistatusConfigPath() {
|
|
374
|
+
return path.join(os.homedir(), '.aistatus', 'config.yaml');
|
|
375
|
+
}
|
|
376
|
+
/** Generate gateway usage config YAML string. */
|
|
377
|
+
export function generateGatewayUsageYaml(config) {
|
|
378
|
+
const doc = { uploadEnabled: config.enabled };
|
|
379
|
+
if (config.enabled) {
|
|
380
|
+
doc.name = config.name || '';
|
|
381
|
+
doc.org = config.org || '';
|
|
382
|
+
doc.email = config.email || '';
|
|
383
|
+
}
|
|
384
|
+
return yaml.stringify(doc);
|
|
385
|
+
}
|
|
386
|
+
/** Write gateway usage config to ~/.aistatus/config.yaml, or <configDir>/config.yaml if configDir is given. */
|
|
387
|
+
function writeGatewayUsageConfig(config, configDir) {
|
|
388
|
+
const configPath = configDir
|
|
389
|
+
? path.join(configDir, 'config.yaml')
|
|
390
|
+
: getAistatusConfigPath();
|
|
391
|
+
const configDirPath = path.dirname(configPath);
|
|
392
|
+
mkdirSync(configDirPath, { recursive: true });
|
|
393
|
+
// Preserve existing fields (e.g. gateway.yaml keys) if config.yaml already exists
|
|
394
|
+
let existing = {};
|
|
395
|
+
if (existsSync(configPath)) {
|
|
396
|
+
try {
|
|
397
|
+
existing = yaml.parse(readFileSync(configPath, 'utf-8')) || {};
|
|
398
|
+
}
|
|
399
|
+
catch { /* ignore parse errors, overwrite */ }
|
|
400
|
+
}
|
|
401
|
+
const merged = {
|
|
402
|
+
...existing,
|
|
403
|
+
name: config.enabled ? (config.name || '') : (existing.name ?? ''),
|
|
404
|
+
org: config.enabled ? (config.org || '') : (existing.org ?? ''),
|
|
405
|
+
email: config.enabled ? (config.email || '') : (existing.email ?? ''),
|
|
406
|
+
uploadEnabled: config.enabled,
|
|
407
|
+
};
|
|
408
|
+
writeFileSync(configPath, yaml.stringify(merged));
|
|
409
|
+
}
|
|
410
|
+
// ─── Service registration ────────────────────────────────────────
|
|
411
|
+
/** Generate systemd unit file content for Linux. */
|
|
412
|
+
export function generateSystemdUnit(user, cortexBin, dataDir) {
|
|
413
|
+
return [
|
|
414
|
+
'[Unit]',
|
|
415
|
+
'Description=Cortex Agent Server',
|
|
416
|
+
'After=network.target',
|
|
417
|
+
'',
|
|
418
|
+
'[Service]',
|
|
419
|
+
'Type=simple',
|
|
420
|
+
`User=${user}`,
|
|
421
|
+
`ExecStart=${cortexBin} daemon`,
|
|
422
|
+
`Environment=CORTEX_HOME=${dataDir}`,
|
|
423
|
+
'Restart=on-failure',
|
|
424
|
+
'RestartSec=5',
|
|
425
|
+
'',
|
|
426
|
+
'[Install]',
|
|
427
|
+
'WantedBy=multi-user.target',
|
|
428
|
+
'',
|
|
429
|
+
].join('\n');
|
|
430
|
+
}
|
|
431
|
+
/** Generate launchd plist content for macOS. */
|
|
432
|
+
export function generateLaunchdPlist(user, cortexBin, dataDir) {
|
|
433
|
+
return [
|
|
434
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
435
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
436
|
+
'<plist version="1.0">',
|
|
437
|
+
'<dict>',
|
|
438
|
+
' <key>Label</key>',
|
|
439
|
+
' <string>cc.cortex.agent-server</string>',
|
|
440
|
+
' <key>ProgramArguments</key>',
|
|
441
|
+
' <array>',
|
|
442
|
+
` <string>${cortexBin}</string>`,
|
|
443
|
+
' <string>daemon</string>',
|
|
444
|
+
' </array>',
|
|
445
|
+
' <key>EnvironmentVariables</key>',
|
|
446
|
+
' <dict>',
|
|
447
|
+
' <key>CORTEX_HOME</key>',
|
|
448
|
+
` <string>${dataDir}</string>`,
|
|
449
|
+
' </dict>',
|
|
450
|
+
' <key>RunAtLoad</key>',
|
|
451
|
+
' <true/>',
|
|
452
|
+
' <key>KeepAlive</key>',
|
|
453
|
+
' <true/>',
|
|
454
|
+
' <key>StandardOutPath</key>',
|
|
455
|
+
` <string>${dataDir}/logs/cortex-stdout.log</string>`,
|
|
456
|
+
' <key>StandardErrorPath</key>',
|
|
457
|
+
` <string>${dataDir}/logs/cortex-stderr.log</string>`,
|
|
458
|
+
'</dict>',
|
|
459
|
+
'</plist>',
|
|
460
|
+
'',
|
|
461
|
+
].join('\n');
|
|
462
|
+
}
|
|
463
|
+
/** Resolve the cortex binary path (used in service files). */
|
|
464
|
+
function resolveCortexBin() {
|
|
465
|
+
const cmd = process.platform === 'win32' ? 'where' : 'which';
|
|
466
|
+
try {
|
|
467
|
+
return execSync(`${cmd} cortex`, { stdio: 'pipe', encoding: 'utf-8' }).trim();
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
// Fallback: node + cli.js
|
|
471
|
+
return `${process.execPath} ${path.join(INSTALL_ROOT, 'dist', 'entry', 'cli.js')}`;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/** Check if we have sudo/root access (Linux/macOS only). */
|
|
475
|
+
function hasSudo() {
|
|
476
|
+
if (process.platform === 'win32')
|
|
477
|
+
return false;
|
|
478
|
+
try {
|
|
479
|
+
execSync('sudo -n true', { stdio: 'pipe' });
|
|
480
|
+
return true;
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
return false;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
/** Install the service file. Returns true if installed by us, false if manual action needed. */
|
|
487
|
+
function installService(dataDir) {
|
|
488
|
+
const user = os.userInfo().username;
|
|
489
|
+
const cortexBin = resolveCortexBin();
|
|
490
|
+
const platform = process.platform;
|
|
491
|
+
if (platform === 'darwin') {
|
|
492
|
+
const plistName = 'cc.cortex.agent-server.plist';
|
|
493
|
+
const plistContent = generateLaunchdPlist(user, cortexBin, dataDir);
|
|
494
|
+
const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', plistName);
|
|
495
|
+
writeFileSync(plistPath, plistContent);
|
|
496
|
+
clack.log.success(`launchd plist written to ${plistPath}`);
|
|
497
|
+
clack.log.info('To start now: launchctl load ' + plistPath);
|
|
498
|
+
}
|
|
499
|
+
else if (platform === 'linux') {
|
|
500
|
+
const unitContent = generateSystemdUnit(user, cortexBin, dataDir);
|
|
501
|
+
const unitName = 'cortex.service';
|
|
502
|
+
const systemPath = `/etc/systemd/system/${unitName}`;
|
|
503
|
+
const userUnitDir = path.join(os.homedir(), '.config', 'systemd', 'user');
|
|
504
|
+
// Try user-level systemd first (no sudo needed)
|
|
505
|
+
try {
|
|
506
|
+
mkdirSync(userUnitDir, { recursive: true });
|
|
507
|
+
const userUnitPath = path.join(userUnitDir, unitName);
|
|
508
|
+
writeFileSync(userUnitPath, unitContent);
|
|
509
|
+
clack.log.success(`systemd unit written to ${userUnitPath}`);
|
|
510
|
+
clack.log.info('To enable: sudo systemctl --user enable --now cortex');
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
// Fall through to system-level
|
|
515
|
+
}
|
|
516
|
+
// System-level: needs sudo
|
|
517
|
+
if (hasSudo()) {
|
|
518
|
+
try {
|
|
519
|
+
const tmpPath = path.join(os.tmpdir(), unitName);
|
|
520
|
+
writeFileSync(tmpPath, unitContent);
|
|
521
|
+
execSync(`sudo cp ${tmpPath} ${systemPath} && sudo systemctl daemon-reload`, { stdio: 'pipe' });
|
|
522
|
+
clack.log.success(`systemd unit installed to ${systemPath}`);
|
|
523
|
+
clack.log.info('To enable: sudo systemctl enable --now cortex');
|
|
524
|
+
}
|
|
525
|
+
catch (err) {
|
|
526
|
+
clack.log.warn(`Failed to install system service: ${err.message}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
else {
|
|
530
|
+
// No sudo — write to config dir and show instructions
|
|
531
|
+
const localPath = path.join(dataDir, 'config', unitName);
|
|
532
|
+
writeFileSync(localPath, unitContent);
|
|
533
|
+
clack.log.warn('No sudo access. Service file saved locally.');
|
|
534
|
+
clack.log.info(`To install manually:\n sudo cp ${localPath} ${systemPath}\n sudo systemctl daemon-reload\n sudo systemctl enable --now cortex`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
else {
|
|
538
|
+
clack.log.warn(`Service registration is not supported on ${platform}. Start Cortex manually with \`cortex daemon\`.`);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
// ─── Interactive prompts (TTY) ───────────────────────────────────
|
|
542
|
+
function handleCancel(value) {
|
|
543
|
+
if (clack.isCancel(value)) {
|
|
544
|
+
clack.cancel('Init cancelled.');
|
|
545
|
+
process.exit(0);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async function collectSlackConfig(prefill) {
|
|
549
|
+
clack.note(SLACK_APP_MANIFEST, 'Slack App Manifest — copy and paste when creating the app');
|
|
550
|
+
clack.note([
|
|
551
|
+
'To set up Slack, you need a Slack App:',
|
|
552
|
+
'',
|
|
553
|
+
'1. Go to https://api.slack.com/apps',
|
|
554
|
+
'2. Click "Create New App" → "From a manifest"',
|
|
555
|
+
'3. Select your workspace, then paste the manifest (shown above)',
|
|
556
|
+
'4. Go to "Basic Information" → copy the Signing Secret',
|
|
557
|
+
'5. Under Basic Information, generate an App-Level Token',
|
|
558
|
+
' (scope: connections:write, name it "cortex-socket")',
|
|
559
|
+
'6. Go to "OAuth & Permissions" → Install to Workspace',
|
|
560
|
+
' Copy the *Bot User OAuth Token* after installing',
|
|
561
|
+
'7. Go to "App Home" → Show Tabs → enable *Messages Tab*',
|
|
562
|
+
' and check "Allow users to send messages from the messages tab"',
|
|
563
|
+
' (required for DM support)',
|
|
564
|
+
'',
|
|
565
|
+
'The manifest includes socket_mode_enabled, so Socket Mode',
|
|
566
|
+
'is automatically enabled when you import it.',
|
|
567
|
+
'',
|
|
568
|
+
'Required Bot Token Scopes (included in manifest):',
|
|
569
|
+
' chat:write, im:history, im:write, reactions:read, reactions:write,',
|
|
570
|
+
' users:read, commands, app_mentions:read,',
|
|
571
|
+
' channels:history, channels:read, groups:history,',
|
|
572
|
+
' files:read, files:write, emoji:read, pins:read, pins:write',
|
|
573
|
+
].join('\n'), 'Slack App Setup Guide');
|
|
574
|
+
await promptCopyManifestToClipboard(SLACK_APP_MANIFEST);
|
|
575
|
+
const hasPrefill = prefill && (prefill.signingSecret || prefill.appToken || prefill.botToken);
|
|
576
|
+
if (hasPrefill) {
|
|
577
|
+
clack.log.info('Found existing Slack configuration — values are pre-filled. Press Enter to keep them, or type to replace.');
|
|
578
|
+
}
|
|
579
|
+
const signingSecret = await clack.password({
|
|
580
|
+
message: 'Step 1/4: SLACK_SIGNING_SECRET (from Basic Information):',
|
|
581
|
+
initialValue: prefill?.signingSecret,
|
|
582
|
+
validate(value) {
|
|
583
|
+
if (!value)
|
|
584
|
+
return 'Signing secret is required.';
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
handleCancel(signingSecret);
|
|
588
|
+
const appToken = await clack.password({
|
|
589
|
+
message: 'Step 2/4: SLACK_APP_TOKEN (App-Level Token, starts with xapp-):',
|
|
590
|
+
initialValue: prefill?.appToken,
|
|
591
|
+
validate(value) {
|
|
592
|
+
if (!value)
|
|
593
|
+
return 'App token is required.';
|
|
594
|
+
if (!value.startsWith('xapp-'))
|
|
595
|
+
return 'Token should start with xapp-';
|
|
596
|
+
},
|
|
597
|
+
});
|
|
598
|
+
handleCancel(appToken);
|
|
599
|
+
const botToken = await clack.password({
|
|
600
|
+
message: 'Step 3/4: SLACK_BOT_TOKEN (Bot User OAuth Token, starts with xoxb-):',
|
|
601
|
+
initialValue: prefill?.botToken,
|
|
602
|
+
validate(value) {
|
|
603
|
+
if (!value)
|
|
604
|
+
return 'Bot token is required.';
|
|
605
|
+
if (!value.startsWith('xoxb-'))
|
|
606
|
+
return 'Token should start with xoxb-';
|
|
607
|
+
},
|
|
608
|
+
});
|
|
609
|
+
handleCancel(botToken);
|
|
610
|
+
const adminChannelRaw = await clack.text({
|
|
611
|
+
message: 'Step 4/4: CORTEX_ADMIN_CHANNEL (optional — Slack channel ID for admin notifications):',
|
|
612
|
+
placeholder: 'e.g. C0123456789 or D0123456789 (leave blank to configure later)',
|
|
613
|
+
initialValue: prefill?.adminChannel,
|
|
614
|
+
});
|
|
615
|
+
handleCancel(adminChannelRaw);
|
|
616
|
+
return {
|
|
617
|
+
botToken: botToken,
|
|
618
|
+
signingSecret: signingSecret,
|
|
619
|
+
appToken: appToken,
|
|
620
|
+
adminChannel: adminChannelRaw.trim() || undefined,
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
async function collectFeishuConfig() {
|
|
624
|
+
clack.note([
|
|
625
|
+
'To set up Feishu (飞书), create a Feishu app:',
|
|
626
|
+
'',
|
|
627
|
+
'1. Go to https://open.feishu.cn/app',
|
|
628
|
+
'2. Create a new app with bot capability enabled',
|
|
629
|
+
'3. Get App ID and App Secret from "Credentials & Basic Info"',
|
|
630
|
+
'4. Enable bot events and subscribe to: im.message.receive_v1',
|
|
631
|
+
'5. Publish the app and get it approved by your admin',
|
|
632
|
+
].join('\n'), 'Feishu App Setup Guide');
|
|
633
|
+
const appId = await clack.text({
|
|
634
|
+
message: 'FEISHU_APP_ID:',
|
|
635
|
+
validate(value) {
|
|
636
|
+
if (!value)
|
|
637
|
+
return 'App ID is required.';
|
|
638
|
+
},
|
|
639
|
+
});
|
|
640
|
+
handleCancel(appId);
|
|
641
|
+
const appSecret = await clack.password({
|
|
642
|
+
message: 'FEISHU_APP_SECRET:',
|
|
643
|
+
validate(value) {
|
|
644
|
+
if (!value)
|
|
645
|
+
return 'App secret is required.';
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
handleCancel(appSecret);
|
|
649
|
+
const encryptKeyRaw = await clack.text({
|
|
650
|
+
message: 'FEISHU_ENCRYPT_KEY (optional):',
|
|
651
|
+
placeholder: 'leave blank to skip',
|
|
652
|
+
});
|
|
653
|
+
handleCancel(encryptKeyRaw);
|
|
654
|
+
const verificationTokenRaw = await clack.text({
|
|
655
|
+
message: 'FEISHU_VERIFICATION_TOKEN (optional):',
|
|
656
|
+
placeholder: 'leave blank to skip',
|
|
657
|
+
});
|
|
658
|
+
handleCancel(verificationTokenRaw);
|
|
659
|
+
const domainRaw = await clack.text({
|
|
660
|
+
message: 'FEISHU_DOMAIN (optional, "feishu" or "lark"):',
|
|
661
|
+
placeholder: 'feishu (leave blank to use default)',
|
|
662
|
+
});
|
|
663
|
+
handleCancel(domainRaw);
|
|
664
|
+
const domainVal = domainRaw.trim().toLowerCase();
|
|
665
|
+
const domain = (domainVal === 'feishu' || domainVal === 'lark')
|
|
666
|
+
? domainVal
|
|
667
|
+
: undefined;
|
|
668
|
+
return {
|
|
669
|
+
appId: appId,
|
|
670
|
+
appSecret: appSecret,
|
|
671
|
+
encryptKey: encryptKeyRaw.trim() || undefined,
|
|
672
|
+
verificationToken: verificationTokenRaw.trim() || undefined,
|
|
673
|
+
domain,
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
async function collectAnswersInteractive(paths) {
|
|
677
|
+
clack.intro('Cortex Setup');
|
|
678
|
+
// Step 1: Backend selection
|
|
679
|
+
clack.note('Both Claude Code and PI support API key access to any model.', 'Backend info');
|
|
680
|
+
const backends = await clack.multiselect({
|
|
681
|
+
message: 'Which backends would you like to use?',
|
|
682
|
+
options: [
|
|
683
|
+
{ value: 'claude', label: 'Claude Code', hint: 'recommended, for Claude subscription' },
|
|
684
|
+
{ value: 'pi', label: 'PI', hint: 'for other subscription' },
|
|
685
|
+
],
|
|
686
|
+
required: true,
|
|
687
|
+
});
|
|
688
|
+
handleCancel(backends);
|
|
689
|
+
// Step 2: Platform selection
|
|
690
|
+
const platform = await clack.select({
|
|
691
|
+
message: 'Which interaction platform would you like to use?',
|
|
692
|
+
options: [
|
|
693
|
+
{ value: 'slack', label: 'Slack', hint: 'recommended' },
|
|
694
|
+
{ value: 'none', label: 'Skip — configure later manually' },
|
|
695
|
+
],
|
|
696
|
+
});
|
|
697
|
+
handleCancel(platform);
|
|
698
|
+
// Step 2b: Platform-specific token input
|
|
699
|
+
let slackConfig;
|
|
700
|
+
let feishuConfig;
|
|
701
|
+
if (platform === 'slack') {
|
|
702
|
+
const envPath = path.join(paths.CONFIG_DIR, '.env');
|
|
703
|
+
const existingSlackConfig = parseExistingEnvSlackConfig(envPath);
|
|
704
|
+
slackConfig = await collectSlackConfig(existingSlackConfig ?? undefined);
|
|
705
|
+
}
|
|
706
|
+
else if (platform === 'feishu') {
|
|
707
|
+
feishuConfig = await collectFeishuConfig();
|
|
708
|
+
}
|
|
709
|
+
// Step 3: Machine identity
|
|
710
|
+
const hostname = os.hostname();
|
|
711
|
+
const machineName = await clack.text({
|
|
712
|
+
message: 'Machine name for this device:',
|
|
713
|
+
placeholder: hostname,
|
|
714
|
+
defaultValue: hostname,
|
|
715
|
+
validate(value) {
|
|
716
|
+
if (!value)
|
|
717
|
+
return 'Machine name is required.';
|
|
718
|
+
},
|
|
719
|
+
});
|
|
720
|
+
handleCancel(machineName);
|
|
721
|
+
// GPU detection
|
|
722
|
+
const gpuCount = detectGpuCount();
|
|
723
|
+
if (gpuCount > 0) {
|
|
724
|
+
clack.log.success(`Detected ${gpuCount} NVIDIA GPU(s)`);
|
|
725
|
+
}
|
|
726
|
+
else {
|
|
727
|
+
clack.log.info('No NVIDIA GPU detected (gpuCount=0)');
|
|
728
|
+
}
|
|
729
|
+
// Step 4: Gateway usage
|
|
730
|
+
clack.note([
|
|
731
|
+
'Cortex includes an open-source local gateway that proxies all',
|
|
732
|
+
'LLM calls, providing multi-key rotation, automatic failover,',
|
|
733
|
+
'and per-request cost tracking.',
|
|
734
|
+
'',
|
|
735
|
+
'You can optionally share anonymous token usage with aistatus.cc,',
|
|
736
|
+
'an AI model status monitoring site. Your token usage will appear',
|
|
737
|
+
'on the public leaderboard (name + org + token counts). Email is',
|
|
738
|
+
'used only as an identity key and is never displayed.',
|
|
739
|
+
'',
|
|
740
|
+
'Learn more: https://aistatus.cc',
|
|
741
|
+
].join('\n'), 'Gateway & aistatus');
|
|
742
|
+
const enableGateway = await clack.confirm({
|
|
743
|
+
message: 'Enable token usage reporting to aistatus?',
|
|
744
|
+
initialValue: true,
|
|
745
|
+
});
|
|
746
|
+
handleCancel(enableGateway);
|
|
747
|
+
let gatewayUsage = { enabled: false };
|
|
748
|
+
if (enableGateway) {
|
|
749
|
+
const name = await clack.text({ message: 'Name:', placeholder: 'your name' });
|
|
750
|
+
handleCancel(name);
|
|
751
|
+
const org = await clack.text({ message: 'Organization:', placeholder: 'your organization' });
|
|
752
|
+
handleCancel(org);
|
|
753
|
+
const email = await clack.text({
|
|
754
|
+
message: 'Email (identity only, not displayed):',
|
|
755
|
+
placeholder: 'you@example.com',
|
|
756
|
+
});
|
|
757
|
+
handleCancel(email);
|
|
758
|
+
gatewayUsage = { enabled: true, name: name, org: org, email: email };
|
|
759
|
+
}
|
|
760
|
+
// Step 5: Service registration
|
|
761
|
+
const wantService = await clack.confirm({
|
|
762
|
+
message: 'Register Cortex as a system service (auto-start on boot)?',
|
|
763
|
+
initialValue: true,
|
|
764
|
+
});
|
|
765
|
+
handleCancel(wantService);
|
|
766
|
+
return {
|
|
767
|
+
backends: backends,
|
|
768
|
+
machineName: machineName,
|
|
769
|
+
gpuCount,
|
|
770
|
+
platform: platform,
|
|
771
|
+
slackConfig,
|
|
772
|
+
feishuConfig,
|
|
773
|
+
gatewayUsage,
|
|
774
|
+
installService: wantService,
|
|
775
|
+
};
|
|
776
|
+
}
|
|
777
|
+
// ─── Non-interactive prompts (piped stdin) ───────────────────────
|
|
778
|
+
async function collectAnswersNonInteractive() {
|
|
779
|
+
const lines = [];
|
|
780
|
+
const rl = createInterface({ input: processStdin });
|
|
781
|
+
for await (const line of rl) {
|
|
782
|
+
lines.push(line);
|
|
783
|
+
}
|
|
784
|
+
// Line format:
|
|
785
|
+
// backends, platform, gatewayEnabled, name, org, email, installService
|
|
786
|
+
// [+ platform-specific tokens: signingSecret, appToken, botToken, adminChannel (slack)]
|
|
787
|
+
const [backendsRaw, platformRaw, gatewayEnabledRaw, name, org, email, installServiceRaw] = lines;
|
|
788
|
+
const backends = (backendsRaw || 'claude')
|
|
789
|
+
.split(',')
|
|
790
|
+
.map(s => s.trim())
|
|
791
|
+
.filter((s) => s === 'claude' || s === 'pi');
|
|
792
|
+
const platform = (platformRaw && ['slack', 'feishu'].includes(platformRaw))
|
|
793
|
+
? platformRaw
|
|
794
|
+
: 'none';
|
|
795
|
+
const gatewayEnabled = gatewayEnabledRaw?.toLowerCase() === 'y';
|
|
796
|
+
log.info('Cortex Initialization (non-interactive)');
|
|
797
|
+
// Parse platform-specific tokens from remaining lines (starting at index 7).
|
|
798
|
+
// After platform tokens, optional planChoice and executeChoice lines (format "mode:model";
|
|
799
|
+
// empty string → auto-infer). Index varies by platform:
|
|
800
|
+
// none → planChoice at 7, executeChoice at 8
|
|
801
|
+
// slack → planChoice at 11, executeChoice at 12
|
|
802
|
+
// feishu → planChoice at 12, executeChoice at 13
|
|
803
|
+
let slackConfig;
|
|
804
|
+
let feishuConfig;
|
|
805
|
+
let profileChoiceStart = 7;
|
|
806
|
+
if (platform === 'slack' && lines.length >= 11) {
|
|
807
|
+
slackConfig = {
|
|
808
|
+
signingSecret: lines[7] || '',
|
|
809
|
+
appToken: lines[8] || '',
|
|
810
|
+
botToken: lines[9] || '',
|
|
811
|
+
adminChannel: lines[10]?.trim() || undefined,
|
|
812
|
+
};
|
|
813
|
+
profileChoiceStart = 11;
|
|
814
|
+
}
|
|
815
|
+
else if (platform === 'feishu' && lines.length >= 12) {
|
|
816
|
+
const domainVal = (lines[11] || '').trim().toLowerCase();
|
|
817
|
+
feishuConfig = {
|
|
818
|
+
appId: lines[7] || '',
|
|
819
|
+
appSecret: lines[8] || '',
|
|
820
|
+
encryptKey: lines[9]?.trim() || undefined,
|
|
821
|
+
verificationToken: lines[10]?.trim() || undefined,
|
|
822
|
+
domain: (domainVal === 'feishu' || domainVal === 'lark')
|
|
823
|
+
? domainVal
|
|
824
|
+
: undefined,
|
|
825
|
+
};
|
|
826
|
+
profileChoiceStart = 12;
|
|
827
|
+
}
|
|
828
|
+
const planChoice = parseChoiceLine(lines[profileChoiceStart]);
|
|
829
|
+
const executeChoice = parseChoiceLine(lines[profileChoiceStart + 1]);
|
|
830
|
+
return {
|
|
831
|
+
backends: backends.length > 0 ? backends : ['claude'],
|
|
832
|
+
machineName: os.hostname(),
|
|
833
|
+
gpuCount: detectGpuCount(),
|
|
834
|
+
platform,
|
|
835
|
+
slackConfig,
|
|
836
|
+
feishuConfig,
|
|
837
|
+
gatewayUsage: gatewayEnabled
|
|
838
|
+
? { enabled: true, name: name || '', org: org || '', email: email || '' }
|
|
839
|
+
: { enabled: false },
|
|
840
|
+
installService: installServiceRaw?.toLowerCase() === 'y',
|
|
841
|
+
planChoice,
|
|
842
|
+
executeChoice,
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
// ─── Directory creation ─────────────────────────────────────────
|
|
846
|
+
function createDirectories(paths) {
|
|
847
|
+
const dirs = [
|
|
848
|
+
paths.DATA_DIR,
|
|
849
|
+
paths.CONFIG_DIR,
|
|
850
|
+
paths.STORE_DIR,
|
|
851
|
+
path.join(paths.DATA_DIR, 'logs', 'sessions'),
|
|
852
|
+
path.join(paths.WORKSPACE_DIR, 'threads'),
|
|
853
|
+
paths.PROJECTS_DIR,
|
|
854
|
+
// Dense Context structure
|
|
855
|
+
path.join(paths.CONTEXT_DIR, 'user'),
|
|
856
|
+
path.join(paths.CONTEXT_DIR, 'decisions'),
|
|
857
|
+
path.join(paths.CONTEXT_DIR, 'scans'),
|
|
858
|
+
path.join(paths.CONTEXT_DIR, 'ideas'),
|
|
859
|
+
path.join(paths.CONTEXT_DIR, 'retrospectives'),
|
|
860
|
+
// Claude Code config
|
|
861
|
+
path.join(paths.DATA_DIR, '.claude', 'hooks'),
|
|
862
|
+
path.join(paths.DATA_DIR, '.claude', 'rules'),
|
|
863
|
+
// Runtime directories
|
|
864
|
+
path.join(paths.DATA_DIR, 'plugins'),
|
|
865
|
+
path.join(paths.DATA_DIR, 'prompts', 'directives'),
|
|
866
|
+
path.join(paths.DATA_DIR, 'prompts', 'systemPrompts'),
|
|
867
|
+
path.join(paths.DATA_DIR, 'prompts', 'promptTemplates'),
|
|
868
|
+
path.join(paths.DATA_DIR, 'hooks'),
|
|
869
|
+
path.join(paths.DATA_DIR, 'plan'),
|
|
870
|
+
path.join(paths.DATA_DIR, 'logs', 'sessions-pi'),
|
|
871
|
+
];
|
|
872
|
+
for (const dir of dirs) {
|
|
873
|
+
mkdirSync(dir, { recursive: true });
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
// ─── Git detection & installation ────────────────────────────────
|
|
877
|
+
/** Check whether git is available on PATH. */
|
|
878
|
+
export function isGitInstalled() {
|
|
879
|
+
const cmd = process.platform === 'win32' ? 'where' : 'which';
|
|
880
|
+
try {
|
|
881
|
+
execSync(`${cmd} git`, { stdio: 'pipe' });
|
|
882
|
+
return true;
|
|
883
|
+
}
|
|
884
|
+
catch {
|
|
885
|
+
return false;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Detect the system package manager on Linux and return its install command prefix.
|
|
890
|
+
* Returns null if no known package manager is found.
|
|
891
|
+
*/
|
|
892
|
+
function detectLinuxPkgInstall() {
|
|
893
|
+
const candidates = [
|
|
894
|
+
{ bin: '/usr/bin/apt-get', install: 'apt-get install -y' },
|
|
895
|
+
{ bin: '/usr/bin/dnf', install: 'dnf install -y' },
|
|
896
|
+
{ bin: '/usr/bin/yum', install: 'yum install -y' },
|
|
897
|
+
{ bin: '/usr/bin/pacman', install: 'pacman -S --noconfirm' },
|
|
898
|
+
{ bin: '/usr/bin/zypper', install: 'zypper install -y' },
|
|
899
|
+
{ bin: '/sbin/apk', install: 'apk add' },
|
|
900
|
+
];
|
|
901
|
+
for (const c of candidates) {
|
|
902
|
+
if (existsSync(c.bin))
|
|
903
|
+
return c.install;
|
|
904
|
+
}
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
/** Return a human-readable install instruction for git on the current platform. */
|
|
908
|
+
export function getGitInstallHint() {
|
|
909
|
+
switch (process.platform) {
|
|
910
|
+
case 'linux': {
|
|
911
|
+
const pkg = detectLinuxPkgInstall();
|
|
912
|
+
if (pkg)
|
|
913
|
+
return `sudo ${pkg} git`;
|
|
914
|
+
return 'Install git via your package manager or download from https://git-scm.com/downloads/linux';
|
|
915
|
+
}
|
|
916
|
+
case 'darwin':
|
|
917
|
+
return 'xcode-select --install (or brew install git if you use Homebrew)';
|
|
918
|
+
case 'win32':
|
|
919
|
+
return 'winget install --id Git.Git -e --source winget';
|
|
920
|
+
default:
|
|
921
|
+
return 'Download from https://git-scm.com/downloads';
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Ensure git is available on PATH. If missing, attempt automatic installation.
|
|
926
|
+
* Returns true if git is now available, false otherwise.
|
|
927
|
+
*/
|
|
928
|
+
export function ensureGitInstalled() {
|
|
929
|
+
if (isGitInstalled())
|
|
930
|
+
return true;
|
|
931
|
+
clack.log.warn('Git is required but was not found on your system.');
|
|
932
|
+
// Build the auto-install command for the current platform
|
|
933
|
+
let installCmd = null;
|
|
934
|
+
if (process.platform === 'linux') {
|
|
935
|
+
const pkg = detectLinuxPkgInstall();
|
|
936
|
+
if (pkg)
|
|
937
|
+
installCmd = `sudo ${pkg} git`;
|
|
938
|
+
}
|
|
939
|
+
else if (process.platform === 'darwin') {
|
|
940
|
+
// Prefer brew in headless contexts; xcode-select --install opens a GUI dialog
|
|
941
|
+
try {
|
|
942
|
+
execSync('which brew', { stdio: 'pipe' });
|
|
943
|
+
installCmd = 'brew install git';
|
|
944
|
+
}
|
|
945
|
+
catch {
|
|
946
|
+
installCmd = 'xcode-select --install';
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
else if (process.platform === 'win32') {
|
|
950
|
+
installCmd = 'winget install --id Git.Git -e --source winget --silent';
|
|
951
|
+
}
|
|
952
|
+
if (installCmd) {
|
|
953
|
+
const s = clack.spinner();
|
|
954
|
+
s.start('Attempting automatic git installation...');
|
|
955
|
+
try {
|
|
956
|
+
execSync(installCmd, { stdio: 'pipe', timeout: 120_000 });
|
|
957
|
+
s.stop('Git installed successfully.');
|
|
958
|
+
// Verify the install actually put git on PATH
|
|
959
|
+
if (isGitInstalled())
|
|
960
|
+
return true;
|
|
961
|
+
clack.log.warn('Git was installed but is not on PATH. You may need to restart your shell.');
|
|
962
|
+
}
|
|
963
|
+
catch (err) {
|
|
964
|
+
s.stop('Automatic installation failed.');
|
|
965
|
+
clack.log.warn(err.message);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
const hint = getGitInstallHint();
|
|
969
|
+
clack.log.info(`Please install git manually: ${hint}`);
|
|
970
|
+
return false;
|
|
971
|
+
}
|
|
972
|
+
// ─── Git repo initialization ────────────────────────────────────
|
|
973
|
+
function ensureGitRepo(dataDir) {
|
|
974
|
+
if (existsSync(path.join(dataDir, '.git')))
|
|
975
|
+
return;
|
|
976
|
+
try {
|
|
977
|
+
execSync('git init', { cwd: dataDir, stdio: 'pipe' });
|
|
978
|
+
}
|
|
979
|
+
catch (err) {
|
|
980
|
+
clack.log.warn(`git init failed: ${err.message}`);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
// ─── Safe copy helpers ──────────────────────────────────────────
|
|
984
|
+
export function safeCopy(src, dst, force, _label) {
|
|
985
|
+
if (!existsSync(src))
|
|
986
|
+
return false;
|
|
987
|
+
if (existsSync(dst) && !force)
|
|
988
|
+
return false;
|
|
989
|
+
const dstDir = path.dirname(dst);
|
|
990
|
+
if (!existsSync(dstDir))
|
|
991
|
+
mkdirSync(dstDir, { recursive: true });
|
|
992
|
+
copyFileSync(src, dst);
|
|
993
|
+
return true;
|
|
994
|
+
}
|
|
995
|
+
/**
|
|
996
|
+
* Recursively seed a directory tree from defaults/ into DATA_DIR. Per-file behavior matches
|
|
997
|
+
* safeCopy(): existing files are preserved unless force=true. New files in defaults/ that the
|
|
998
|
+
* user hasn't created are always added (so package upgrades automatically deliver new
|
|
999
|
+
* directives/skills without overwriting user edits).
|
|
1000
|
+
*/
|
|
1001
|
+
function safeCopyDir(srcDir, dstDir, force) {
|
|
1002
|
+
if (!existsSync(srcDir))
|
|
1003
|
+
return;
|
|
1004
|
+
mkdirSync(dstDir, { recursive: true });
|
|
1005
|
+
for (const entry of readdirSync(srcDir, { withFileTypes: true })) {
|
|
1006
|
+
const srcPath = path.join(srcDir, entry.name);
|
|
1007
|
+
const dstPath = path.join(dstDir, entry.name);
|
|
1008
|
+
if (entry.isDirectory()) {
|
|
1009
|
+
safeCopyDir(srcPath, dstPath, force);
|
|
1010
|
+
}
|
|
1011
|
+
else if (entry.isFile()) {
|
|
1012
|
+
if (existsSync(dstPath) && !force)
|
|
1013
|
+
continue;
|
|
1014
|
+
copyFileSync(srcPath, dstPath);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
// ─── Config copy & generation ──────────────────────────────────
|
|
1019
|
+
function copyDefaults(paths, force) {
|
|
1020
|
+
// Scaffold files — never overwrite (user-customized content)
|
|
1021
|
+
safeCopy(path.join(DEFAULTS_DIR, 'CORTEX.md'), path.join(paths.DATA_DIR, 'CORTEX.md'), false, 'CORTEX.md');
|
|
1022
|
+
safeCopy(path.join(DEFAULTS_DIR, 'gitignore'), path.join(paths.DATA_DIR, '.gitignore'), false, '.gitignore');
|
|
1023
|
+
safeCopy(path.join(DEFAULTS_DIR, '.claude', 'settings.json'), path.join(paths.DATA_DIR, '.claude', 'settings.json'), false, '.claude/settings.json');
|
|
1024
|
+
// Context scaffold files — never overwrite
|
|
1025
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'CORTEX.md'), false, 'context/CORTEX.md');
|
|
1026
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'projects', 'CORTEX.md'), path.join(paths.PROJECTS_DIR, 'CORTEX.md'), false, 'context/projects/CORTEX.md');
|
|
1027
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'scans', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'scans', 'CORTEX.md'), false, 'context/scans/CORTEX.md');
|
|
1028
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'ideas', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'ideas', 'CORTEX.md'), false, 'context/ideas/CORTEX.md');
|
|
1029
|
+
safeCopy(path.join(DEFAULTS_DIR, 'context', 'user', 'CORTEX.md'), path.join(paths.CONTEXT_DIR, 'user', 'CORTEX.md'), false, 'context/user/CORTEX.md');
|
|
1030
|
+
// Config defaults — overwrite only with --force
|
|
1031
|
+
safeCopy(path.join(DEFAULTS_DIR, 'config', 'budget.json'), path.join(paths.CONFIG_DIR, 'budget.json'), force, 'budget.json');
|
|
1032
|
+
safeCopy(path.join(DEFAULTS_DIR, 'config', 'thread-templates.json'), path.join(paths.CONFIG_DIR, 'thread-templates.json'), force, 'thread-templates.json');
|
|
1033
|
+
safeCopy(path.join(DEFAULTS_DIR, 'config', 'session-hooks.json'), path.join(paths.CONFIG_DIR, 'session-hooks.json'), force, 'session-hooks.json');
|
|
1034
|
+
// Seed asset trees — per-file safeCopy semantics: new files always added, existing files
|
|
1035
|
+
// preserved unless force=true. These directories are referenced at runtime; without them
|
|
1036
|
+
// thread-manager / skill-scanner / rules-loader can't find their inputs.
|
|
1037
|
+
safeCopyDir(path.join(DEFAULTS_DIR, 'prompts'), path.join(paths.DATA_DIR, 'prompts'), force);
|
|
1038
|
+
safeCopyDir(path.join(DEFAULTS_DIR, 'rules'), path.join(paths.DATA_DIR, 'rules'), force);
|
|
1039
|
+
safeCopyDir(path.join(DEFAULTS_DIR, 'plugins'), path.join(paths.DATA_DIR, 'plugins'), force);
|
|
1040
|
+
safeCopyDir(path.join(DEFAULTS_DIR, 'context', 'decisions'), path.join(paths.CONTEXT_DIR, 'decisions'), force);
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Deploy hook scripts from defaults/hooks/ to DATA_DIR/hooks/.
|
|
1044
|
+
* All hooks are standalone .mjs files referenced via HOOKS_DIR.
|
|
1045
|
+
*/
|
|
1046
|
+
function deployHooks(paths, force) {
|
|
1047
|
+
const hooksDir = path.join(paths.DATA_DIR, 'hooks');
|
|
1048
|
+
const srcDir = path.join(DEFAULTS_DIR, 'hooks');
|
|
1049
|
+
if (!existsSync(srcDir))
|
|
1050
|
+
return;
|
|
1051
|
+
mkdirSync(hooksDir, { recursive: true });
|
|
1052
|
+
const files = readdirSync(srcDir);
|
|
1053
|
+
for (const file of files) {
|
|
1054
|
+
if (!file.endsWith('.mjs'))
|
|
1055
|
+
continue;
|
|
1056
|
+
const src = path.join(srcDir, file);
|
|
1057
|
+
const dst = path.join(hooksDir, file);
|
|
1058
|
+
safeCopy(src, dst, force, `hooks/${file}`);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
function generateConfigs(paths, answers, force) {
|
|
1062
|
+
// MCP configs — always regenerate (machine-specific, in .gitignore)
|
|
1063
|
+
writeFileSync(path.join(paths.CONFIG_DIR, 'mcp-config.json'), JSON.stringify(buildFullConfig(INSTALL_ROOT), null, 2));
|
|
1064
|
+
writeFileSync(path.join(paths.CONFIG_DIR, 'mcp-config-core.json'), JSON.stringify(buildCoreConfig(INSTALL_ROOT), null, 2));
|
|
1065
|
+
writeFileSync(path.join(paths.CONFIG_DIR, 'mcp-config-tui.json'), JSON.stringify(buildTuiConfig(INSTALL_ROOT), null, 2));
|
|
1066
|
+
// mode.json — skip if exists (user may have customized)
|
|
1067
|
+
const modeJsonPath = path.join(paths.STORE_DIR, 'mode.json');
|
|
1068
|
+
if (!existsSync(modeJsonPath) || force) {
|
|
1069
|
+
const primaryBackend = answers.backends[0] || 'claude';
|
|
1070
|
+
writeFileSync(modeJsonPath, generateDefaultModeJson(primaryBackend));
|
|
1071
|
+
}
|
|
1072
|
+
// machines.json — runtime machine registry, server won't start without it
|
|
1073
|
+
const machinesJsonPath = path.join(paths.CONFIG_DIR, 'machines.json');
|
|
1074
|
+
if (!existsSync(machinesJsonPath) || force) {
|
|
1075
|
+
const entry = {
|
|
1076
|
+
cortexPath: paths.DATA_DIR,
|
|
1077
|
+
gpuCount: answers.gpuCount,
|
|
1078
|
+
};
|
|
1079
|
+
const machines = { [answers.machineName]: entry };
|
|
1080
|
+
writeFileSync(machinesJsonPath, JSON.stringify(machines, null, 2) + '\n');
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
/**
|
|
1084
|
+
* Seed schedules.json from defaults/data/schedules.json into STORE_DIR.
|
|
1085
|
+
* Replaces __ADMIN_CHANNEL__ placeholder with the configured admin channel,
|
|
1086
|
+
* and stamps createdAt with the current timestamp. Never overwrites existing file.
|
|
1087
|
+
*/
|
|
1088
|
+
function seedSchedules(paths, answers, force) {
|
|
1089
|
+
const dstPath = path.join(paths.STORE_DIR, 'schedules.json');
|
|
1090
|
+
if (existsSync(dstPath) && !force)
|
|
1091
|
+
return;
|
|
1092
|
+
const srcPath = path.join(DEFAULTS_DIR, 'data', 'schedules.json');
|
|
1093
|
+
if (!existsSync(srcPath))
|
|
1094
|
+
return;
|
|
1095
|
+
const adminChannel = answers.slackConfig?.adminChannel || '';
|
|
1096
|
+
const now = Date.now();
|
|
1097
|
+
let content = readFileSync(srcPath, 'utf-8');
|
|
1098
|
+
content = content.replace(/__ADMIN_CHANNEL__/g, adminChannel);
|
|
1099
|
+
// Stamp createdAt on all seed tasks
|
|
1100
|
+
const data = JSON.parse(content);
|
|
1101
|
+
for (const task of data.tasks) {
|
|
1102
|
+
if (task.createdAt === 0)
|
|
1103
|
+
task.createdAt = now;
|
|
1104
|
+
}
|
|
1105
|
+
mkdirSync(path.dirname(dstPath), { recursive: true });
|
|
1106
|
+
writeFileSync(dstPath, JSON.stringify(data, null, 2) + '\n');
|
|
1107
|
+
}
|
|
1108
|
+
function writeDotEnv(paths, answers, force) {
|
|
1109
|
+
const envPath = path.join(paths.CONFIG_DIR, '.env');
|
|
1110
|
+
if (existsSync(envPath) && !force)
|
|
1111
|
+
return;
|
|
1112
|
+
const content = generateDotEnvContent(answers);
|
|
1113
|
+
writeFileSync(envPath, content);
|
|
1114
|
+
}
|
|
1115
|
+
// ─── Gateway & profile auto-setup ──────────────────────────────
|
|
1116
|
+
/** Detect whether a profiles.json at <configDir>/profiles.json already has `plan` or `execute`. */
|
|
1117
|
+
function detectExistingPlanOrExecute(configDir) {
|
|
1118
|
+
const profilesPath = path.join(configDir, 'profiles.json');
|
|
1119
|
+
if (!existsSync(profilesPath))
|
|
1120
|
+
return false;
|
|
1121
|
+
try {
|
|
1122
|
+
const data = JSON.parse(readFileSync(profilesPath, 'utf-8'));
|
|
1123
|
+
return !!(data?.profiles?.plan || data?.profiles?.execute);
|
|
1124
|
+
}
|
|
1125
|
+
catch {
|
|
1126
|
+
return false;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Interactively pick plan / execute (mode, model) from discovered endpoints.
|
|
1131
|
+
* Pre-selects auto-inferred defaults. Returns undefined for either choice if the user
|
|
1132
|
+
* declined to overwrite an existing profile.
|
|
1133
|
+
*/
|
|
1134
|
+
async function pickPlanExecuteInteractive(endpoints, configDir) {
|
|
1135
|
+
// If existing profiles.json has plan/execute, ask before overwriting
|
|
1136
|
+
if (detectExistingPlanOrExecute(configDir)) {
|
|
1137
|
+
const confirm = await clack.confirm({
|
|
1138
|
+
message: 'Existing `plan` or `execute` profile detected. Overwrite with a new selection?',
|
|
1139
|
+
initialValue: false,
|
|
1140
|
+
});
|
|
1141
|
+
handleCancel(confirm);
|
|
1142
|
+
if (!confirm) {
|
|
1143
|
+
return { overwrite: false };
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
const choices = listChoices(endpoints);
|
|
1147
|
+
if (choices.length === 0)
|
|
1148
|
+
return { overwrite: true };
|
|
1149
|
+
const autoDefaults = generateProfiles(endpoints).profiles;
|
|
1150
|
+
const planDefault = autoDefaults.plan
|
|
1151
|
+
? `${autoDefaults.plan.mode}:${autoDefaults.plan.model}`
|
|
1152
|
+
: `${choices[0].mode}:${choices[0].model}`;
|
|
1153
|
+
const executeDefault = autoDefaults.execute
|
|
1154
|
+
? `${autoDefaults.execute.mode}:${autoDefaults.execute.model}`
|
|
1155
|
+
: planDefault;
|
|
1156
|
+
const options = choices.map(c => ({
|
|
1157
|
+
value: `${c.mode}:${c.model}`,
|
|
1158
|
+
label: `${c.mode} / ${c.model}`,
|
|
1159
|
+
}));
|
|
1160
|
+
const planSel = await clack.select({
|
|
1161
|
+
message: 'Pick model for the `plan` profile (used by executor agents — planner, doc-writer, coder, etc.):',
|
|
1162
|
+
options,
|
|
1163
|
+
initialValue: planDefault,
|
|
1164
|
+
});
|
|
1165
|
+
handleCancel(planSel);
|
|
1166
|
+
const execSel = await clack.select({
|
|
1167
|
+
message: 'Pick model for the `execute` profile (used by reviewer agents — reviewer, doc-reviewer, coder-reviewer, etc.):',
|
|
1168
|
+
options,
|
|
1169
|
+
initialValue: executeDefault,
|
|
1170
|
+
});
|
|
1171
|
+
handleCancel(execSel);
|
|
1172
|
+
const [planMode, planModel] = planSel.split(':');
|
|
1173
|
+
const [execMode, execModel] = execSel.split(':');
|
|
1174
|
+
return {
|
|
1175
|
+
planChoice: { mode: planMode, model: planModel },
|
|
1176
|
+
executeChoice: { mode: execMode, model: execModel },
|
|
1177
|
+
overwrite: true,
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
async function runGatewaySetup(backends, paths, gatewayConfigDir, answers) {
|
|
1181
|
+
// Discover endpoints from Claude/PI local configs
|
|
1182
|
+
const endpoints = discoverEndpoints();
|
|
1183
|
+
if (endpoints.length === 0) {
|
|
1184
|
+
clack.log.warn('No backends discovered. Make sure you have logged into Claude Code and/or PI first.');
|
|
1185
|
+
clack.log.info('You can re-run detection later with: cortex setup-gateway');
|
|
1186
|
+
return;
|
|
1187
|
+
}
|
|
1188
|
+
// Show discovered summary
|
|
1189
|
+
const summary = endpoints.map(ep => ` ${ep.mode}/${ep.endpoint}: ${ep.models.slice(0, 3).join(', ')}${ep.models.length > 3 ? ', ...' : ''} (${ep.keys.length > 0 ? 'with key' : 'passthrough'})`).join('\n');
|
|
1190
|
+
clack.log.success(`Discovered ${endpoints.length} endpoint modes:\n${summary}`);
|
|
1191
|
+
// Generate gateway.yaml — scoped to gatewayConfigDir when provided (test/alt env),
|
|
1192
|
+
// otherwise defaults to ~/.aistatus/gateway.yaml (production).
|
|
1193
|
+
const yamlContent = generateGatewayYaml(endpoints);
|
|
1194
|
+
const gatewayPath = writeGatewayYaml(yamlContent, gatewayConfigDir);
|
|
1195
|
+
clack.log.success(`Gateway config written to ${gatewayPath}`);
|
|
1196
|
+
// Resolve plan/execute choices + overwrite intent.
|
|
1197
|
+
let planChoice = answers?.planChoice;
|
|
1198
|
+
let executeChoice = answers?.executeChoice;
|
|
1199
|
+
let overwrite;
|
|
1200
|
+
if (processStdin.isTTY) {
|
|
1201
|
+
// Interactive: prompt for selection (with overwrite confirmation if needed)
|
|
1202
|
+
const picked = await pickPlanExecuteInteractive(endpoints, paths.CONFIG_DIR);
|
|
1203
|
+
planChoice = picked.planChoice ?? planChoice;
|
|
1204
|
+
executeChoice = picked.executeChoice ?? executeChoice;
|
|
1205
|
+
overwrite = picked.overwrite;
|
|
1206
|
+
}
|
|
1207
|
+
else {
|
|
1208
|
+
// Non-interactive: stdin already provided choices (or empty → auto-infer).
|
|
1209
|
+
// Always overwrite — scripted (re)install assumes the operator knows the intent.
|
|
1210
|
+
overwrite = true;
|
|
1211
|
+
}
|
|
1212
|
+
// Generate profiles.json
|
|
1213
|
+
const profilesPath = writeProfilesJson(endpoints, {
|
|
1214
|
+
outputDir: paths.CONFIG_DIR,
|
|
1215
|
+
planChoice,
|
|
1216
|
+
executeChoice,
|
|
1217
|
+
overwrite,
|
|
1218
|
+
});
|
|
1219
|
+
clack.log.success(`Profiles written to ${profilesPath}`);
|
|
1220
|
+
// Show profile summary (reflects what was actually generated, not what was merged)
|
|
1221
|
+
const profiles = generateProfiles(endpoints, { planChoice, executeChoice });
|
|
1222
|
+
const profileNames = Object.keys(profiles.profiles).join(', ');
|
|
1223
|
+
clack.log.info(`Generated profiles: ${profileNames} (default: ${profiles.defaultProfile})`);
|
|
1224
|
+
}
|
|
1225
|
+
export async function runInit(options = {}) {
|
|
1226
|
+
const paths = getResolvedPaths(options.homeDir);
|
|
1227
|
+
const force = options.force ?? false;
|
|
1228
|
+
// 1. Collect user choices
|
|
1229
|
+
const answers = processStdin.isTTY
|
|
1230
|
+
? await collectAnswersInteractive(paths)
|
|
1231
|
+
: await collectAnswersNonInteractive();
|
|
1232
|
+
// 2. Check & install backends
|
|
1233
|
+
await checkAndInstallBackends(answers.backends);
|
|
1234
|
+
// 3. Ensure git + directory structure
|
|
1235
|
+
ensureGitInstalled();
|
|
1236
|
+
createDirectories(paths);
|
|
1237
|
+
ensureGitRepo(paths.DATA_DIR);
|
|
1238
|
+
// 4. Write configs
|
|
1239
|
+
writeDotEnv(paths, answers, force);
|
|
1240
|
+
copyDefaults(paths, force);
|
|
1241
|
+
deployHooks(paths, force);
|
|
1242
|
+
generateConfigs(paths, answers, force);
|
|
1243
|
+
seedSchedules(paths, answers, force);
|
|
1244
|
+
// 5. Gateway usage
|
|
1245
|
+
writeGatewayUsageConfig(answers.gatewayUsage, paths.CONFIG_DIR);
|
|
1246
|
+
// 6. Service registration
|
|
1247
|
+
if (answers.installService) {
|
|
1248
|
+
installService(paths.DATA_DIR);
|
|
1249
|
+
}
|
|
1250
|
+
// 7. Gateway & profile auto-setup (detect from Claude/PI local configs)
|
|
1251
|
+
if (processStdin.isTTY) {
|
|
1252
|
+
clack.note([
|
|
1253
|
+
'Cortex can auto-detect your Claude Code and PI configurations',
|
|
1254
|
+
'to generate gateway.yaml and profiles.json automatically.',
|
|
1255
|
+
'',
|
|
1256
|
+
'Make sure you have logged into:',
|
|
1257
|
+
' • Claude Code: claude login',
|
|
1258
|
+
' • PI: pi login (if using PI)',
|
|
1259
|
+
].join('\n'), 'Gateway & Profile Setup');
|
|
1260
|
+
const ready = await clack.confirm({
|
|
1261
|
+
message: 'Have you logged into Claude Code and/or PI? Ready to auto-detect?',
|
|
1262
|
+
initialValue: true,
|
|
1263
|
+
});
|
|
1264
|
+
if (!clack.isCancel(ready) && ready) {
|
|
1265
|
+
await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
|
|
1266
|
+
}
|
|
1267
|
+
else {
|
|
1268
|
+
clack.log.info('Skipped. Run `cortex setup-gateway` later to auto-configure.');
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
else {
|
|
1272
|
+
// Non-interactive: auto-detect silently, passing stdin-supplied choices
|
|
1273
|
+
try {
|
|
1274
|
+
await runGatewaySetup(answers.backends, paths, options.gatewayConfigDir, answers);
|
|
1275
|
+
}
|
|
1276
|
+
catch (e) {
|
|
1277
|
+
log.warn(`Gateway setup failed (non-interactive): ${e.message}`);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
// 8. Patch mode.json activeProfile to match profiles.json defaultProfile
|
|
1281
|
+
try {
|
|
1282
|
+
const profilesJsonPath = path.join(paths.CONFIG_DIR, 'profiles.json');
|
|
1283
|
+
const modeJsonPath = path.join(paths.STORE_DIR, 'mode.json');
|
|
1284
|
+
if (existsSync(profilesJsonPath) && existsSync(modeJsonPath)) {
|
|
1285
|
+
const profilesData = JSON.parse(readFileSync(profilesJsonPath, 'utf8'));
|
|
1286
|
+
const modeData = JSON.parse(readFileSync(modeJsonPath, 'utf8'));
|
|
1287
|
+
if (modeData.activeProfile === '__active__' && profilesData.defaultProfile) {
|
|
1288
|
+
modeData.activeProfile = profilesData.defaultProfile;
|
|
1289
|
+
writeFileSync(modeJsonPath, JSON.stringify(modeData));
|
|
1290
|
+
log.info(`mode.json activeProfile set to "${profilesData.defaultProfile}"`);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
catch (e) {
|
|
1295
|
+
log.warn(`Failed to update activeProfile in mode.json: ${e.message}`);
|
|
1296
|
+
}
|
|
1297
|
+
// 9. Done
|
|
1298
|
+
clack.outro(`Cortex initialized at ${paths.DATA_DIR}. Run \`cortex start\` to launch.`);
|
|
1299
|
+
}
|