@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,18 @@
|
|
|
1
|
+
interface DeviceResult {
|
|
2
|
+
device: string;
|
|
3
|
+
updated: boolean;
|
|
4
|
+
restarted: boolean;
|
|
5
|
+
oldVersion?: string;
|
|
6
|
+
newVersion?: string;
|
|
7
|
+
error?: string;
|
|
8
|
+
}
|
|
9
|
+
interface ClientUpdateResult {
|
|
10
|
+
oldVersion: string | null;
|
|
11
|
+
newVersion: string;
|
|
12
|
+
devices: DeviceResult[];
|
|
13
|
+
duration: number;
|
|
14
|
+
}
|
|
15
|
+
declare function checkAndUpdateClients(): Promise<ClientUpdateResult | null>;
|
|
16
|
+
declare function formatUpdateSlackMessage(result: ClientUpdateResult): string;
|
|
17
|
+
export { checkAndUpdateClients, formatUpdateSlackMessage };
|
|
18
|
+
export type { ClientUpdateResult, DeviceResult };
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Client hot-reload via npm update — replaces the old SCP-based approach.
|
|
2
|
+
// On startup, checks all registered remote devices for outdated cortex-client
|
|
3
|
+
// and runs `npm update -g cortex-client` + restart when needed.
|
|
4
|
+
import * as fs from 'fs';
|
|
5
|
+
import * as path from 'path';
|
|
6
|
+
import { execSync } from 'child_process';
|
|
7
|
+
import { getMachineRegistry } from '../tasks/dispatch-utils.js';
|
|
8
|
+
import { sshExec, clientPids } from './client-manager.js';
|
|
9
|
+
import { STORE_DIR } from '../../core/utils.js';
|
|
10
|
+
import { createLogger } from '../../core/log.js';
|
|
11
|
+
const log = createLogger('client-hot-reload');
|
|
12
|
+
const VERSION_FILE = path.join(STORE_DIR, 'client-version.json');
|
|
13
|
+
// --- Version helpers ---
|
|
14
|
+
function getLocalClientVersion() {
|
|
15
|
+
try {
|
|
16
|
+
const result = execSync('npm ls -g cortex-client --json 2>/dev/null || true', { encoding: 'utf8', timeout: 10000 });
|
|
17
|
+
try {
|
|
18
|
+
const parsed = JSON.parse(result);
|
|
19
|
+
return parsed?.dependencies?.['cortex-client']?.version || null;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function loadStoredVersion() {
|
|
30
|
+
try {
|
|
31
|
+
return JSON.parse(fs.readFileSync(VERSION_FILE, 'utf8'));
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function saveVersion(ver) {
|
|
38
|
+
fs.mkdirSync(STORE_DIR, { recursive: true });
|
|
39
|
+
fs.writeFileSync(VERSION_FILE, JSON.stringify({ version: ver, updatedAt: new Date().toISOString() }, null, 2));
|
|
40
|
+
}
|
|
41
|
+
// --- Per-device operations ---
|
|
42
|
+
async function killClientOnDevice(device, reg) {
|
|
43
|
+
const pid = clientPids.get(device);
|
|
44
|
+
if (!pid)
|
|
45
|
+
return false;
|
|
46
|
+
try {
|
|
47
|
+
if (!reg.ssh) {
|
|
48
|
+
try {
|
|
49
|
+
process.kill(pid, 'SIGTERM');
|
|
50
|
+
}
|
|
51
|
+
catch { }
|
|
52
|
+
}
|
|
53
|
+
else if (reg.win) {
|
|
54
|
+
await sshExec(reg.ssh, `taskkill /pid ${pid} /f /t 2>nul || echo ok`, 10000);
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
await sshExec(reg.ssh, `kill ${pid} 2>/dev/null || true`, 10000);
|
|
58
|
+
}
|
|
59
|
+
clientPids.delete(device);
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async function updateClientOnDevice(device, reg) {
|
|
67
|
+
const res = { device, updated: false, restarted: false };
|
|
68
|
+
try {
|
|
69
|
+
if (!reg.ssh) {
|
|
70
|
+
// Local device: npm update + restart handled externally
|
|
71
|
+
res.error = 'Local client update not yet supported (use npm update -g cortex-client manually)';
|
|
72
|
+
return res;
|
|
73
|
+
}
|
|
74
|
+
// Kill existing client
|
|
75
|
+
await killClientOnDevice(device, reg);
|
|
76
|
+
// npm update
|
|
77
|
+
const updateCmd = 'npm update -g cortex-client 2>&1';
|
|
78
|
+
const updateOutput = await sshExec(reg.ssh, updateCmd, 60000);
|
|
79
|
+
res.updated = true;
|
|
80
|
+
log.info(` ${device}: npm update output: ${updateOutput.slice(0, 200)}`);
|
|
81
|
+
// Restart (config file is managed by LLM, not rewritten here)
|
|
82
|
+
if (reg.win) {
|
|
83
|
+
const wmiArg = 'cortex-client';
|
|
84
|
+
await sshExec(reg.ssh, `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${wmiArg}').ProcessId"`, 30000);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
await sshExec(reg.ssh, `nohup cortex-client > /dev/null 2>&1 & echo $!`, 30000);
|
|
88
|
+
}
|
|
89
|
+
res.restarted = true;
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
res.error = err.message;
|
|
93
|
+
log.warn(` ${device}: update failed — ${res.error}`);
|
|
94
|
+
}
|
|
95
|
+
return res;
|
|
96
|
+
}
|
|
97
|
+
// --- Main check-and-update ---
|
|
98
|
+
async function checkAndUpdateClients() {
|
|
99
|
+
const localVersion = getLocalClientVersion();
|
|
100
|
+
const stored = loadStoredVersion();
|
|
101
|
+
// First run: save version, skip update
|
|
102
|
+
if (!stored) {
|
|
103
|
+
const ver = localVersion || 'unknown';
|
|
104
|
+
log.info(`First run — saving client version ${ver}, skipping update`);
|
|
105
|
+
saveVersion(ver);
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
// No local version info (cortex-client not installed locally)
|
|
109
|
+
if (!localVersion) {
|
|
110
|
+
log.info('cortex-client not found in local npm — skipping hot-reload');
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
// No change
|
|
114
|
+
if (stored.version === localVersion) {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
log.info(`cortex-client updated: ${stored.version} → ${localVersion}`);
|
|
118
|
+
const start = Date.now();
|
|
119
|
+
const registry = getMachineRegistry();
|
|
120
|
+
const devices = await Promise.all(Object.entries(registry).map(async ([device, reg]) => {
|
|
121
|
+
return updateClientOnDevice(device, reg);
|
|
122
|
+
}));
|
|
123
|
+
const duration = Date.now() - start;
|
|
124
|
+
saveVersion(localVersion);
|
|
125
|
+
for (const d of devices) {
|
|
126
|
+
const status = d.updated && d.restarted ? 'OK' : (d.error ? 'FAIL' : 'SKIP');
|
|
127
|
+
log.info(` ${d.device}: ${status}${d.error ? ` (${d.error})` : ''}`);
|
|
128
|
+
}
|
|
129
|
+
return { oldVersion: stored.version, newVersion: localVersion, devices, duration };
|
|
130
|
+
}
|
|
131
|
+
// --- Slack message formatting ---
|
|
132
|
+
function formatUpdateSlackMessage(result) {
|
|
133
|
+
const lines = [
|
|
134
|
+
`:arrows_counterclockwise: *Client hot-reload* \`${result.oldVersion}\` → \`${result.newVersion}\` (${(result.duration / 1000).toFixed(1)}s)`,
|
|
135
|
+
];
|
|
136
|
+
for (const d of result.devices) {
|
|
137
|
+
const icon = d.updated && d.restarted ? ':white_check_mark:' : ':x:';
|
|
138
|
+
lines.push(` ${d.device}: ${icon}${d.error ? ` _${d.error}_` : ''}`);
|
|
139
|
+
}
|
|
140
|
+
return lines.join('\n');
|
|
141
|
+
}
|
|
142
|
+
export { checkAndUpdateClients, formatUpdateSlackMessage };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type MachineEntry, type MachineRegistry } from '../tasks/dispatch-utils.js';
|
|
2
|
+
interface CommandParams {
|
|
3
|
+
action: string;
|
|
4
|
+
params: Record<string, any>;
|
|
5
|
+
timeout?: number;
|
|
6
|
+
}
|
|
7
|
+
declare function startClientManager(port: number): void;
|
|
8
|
+
declare function stopClientManager(): void;
|
|
9
|
+
declare function getOnlineDevices(): Array<{
|
|
10
|
+
device: string;
|
|
11
|
+
platform: string;
|
|
12
|
+
connectedAt: Date;
|
|
13
|
+
lastHeartbeat: Date;
|
|
14
|
+
capabilities: string[];
|
|
15
|
+
}>;
|
|
16
|
+
declare function isDeviceOnline(device: string): boolean;
|
|
17
|
+
declare function sendCommand(device: string, command: CommandParams): Promise<any>;
|
|
18
|
+
declare function getPid(device: string): number | undefined;
|
|
19
|
+
declare function setPid(device: string, pid: number): void;
|
|
20
|
+
declare function deletePid(device: string): void;
|
|
21
|
+
declare const clientPids: {
|
|
22
|
+
get: typeof getPid;
|
|
23
|
+
set: typeof setPid;
|
|
24
|
+
delete: typeof deletePid;
|
|
25
|
+
};
|
|
26
|
+
declare function sshExec(host: string, command: string, timeout?: number): Promise<string>;
|
|
27
|
+
type SshExec = (host: string, command: string, timeout?: number) => Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* Build the shell command run over SSH to spawn cortex-client on a remote device.
|
|
30
|
+
*
|
|
31
|
+
* Windows note: WMI `Win32_Process.Create` does NOT perform PATH lookup, and
|
|
32
|
+
* `cortex-client` installed by npm on Windows is a `.cmd` shim
|
|
33
|
+
* (e.g. `C:\Users\<u>\AppData\Roaming\npm\cortex-client.cmd`). Passing the bare
|
|
34
|
+
* name returns ReturnValue=9 (Path Not Found) with an empty ProcessId, which
|
|
35
|
+
* over SSH serializes to "" and the parent caller logs
|
|
36
|
+
* `Failed to parse PID for <device>: ""`. Wrapping with `cmd.exe /c` makes cmd
|
|
37
|
+
* do the PATH lookup and run the .cmd shim correctly.
|
|
38
|
+
*
|
|
39
|
+
* Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
|
|
40
|
+
* returns the child PID on stdout.
|
|
41
|
+
*/
|
|
42
|
+
declare function buildRemoteSpawnCommand(reg: MachineEntry): string;
|
|
43
|
+
declare function startRemoteClient(device: string): Promise<void>;
|
|
44
|
+
/** Start clients on all registered devices */
|
|
45
|
+
declare function startAllRemoteClients(): Promise<void>;
|
|
46
|
+
declare function _setSshExecForTesting(fn: SshExec): void;
|
|
47
|
+
declare function _setMachineRegistryProviderForTesting(fn: () => MachineRegistry): void;
|
|
48
|
+
declare function _getRestartTimerCount(): number;
|
|
49
|
+
declare function _testReset(): void;
|
|
50
|
+
export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, startRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, clientPids, sshExec, _setSshExecForTesting, _setMachineRegistryProviderForTesting, _getRestartTimerCount, _testReset, };
|
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
// input: WebSocket connections from cortex-client instances
|
|
2
|
+
// output: start/stop/getOnlineDevices/sendCommand/isDeviceOnline/buildRemoteSpawnCommand
|
|
3
|
+
// pos: cortex-client WebSocket connection registration, command routing, and
|
|
4
|
+
// SSH-based remote client lifecycle (spawn / retry / PID tracking)
|
|
5
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
6
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
7
|
+
import * as crypto from 'crypto';
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { execFile, spawn } from 'child_process';
|
|
11
|
+
import { getMachineRegistry } from '../tasks/dispatch-utils.js';
|
|
12
|
+
import { STORE_DIR } from '../../core/utils.js';
|
|
13
|
+
import { createLogger } from '../../core/log.js';
|
|
14
|
+
import { readTasks, findTask } from '../tasks/system/task-lifecycle-edit.js';
|
|
15
|
+
import { completeTask } from '../tasks/system/task-completion.js';
|
|
16
|
+
import { blockTask } from '../tasks/system/task-state.js';
|
|
17
|
+
const log = createLogger('client-manager');
|
|
18
|
+
// --- State ---
|
|
19
|
+
const devices = new Map();
|
|
20
|
+
const pendingCommands = new Map();
|
|
21
|
+
let wss = null;
|
|
22
|
+
let heartbeatCheckInterval = null;
|
|
23
|
+
const HEARTBEAT_TIMEOUT_MS = 15_000; // 3 missed 5s heartbeats
|
|
24
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 120_000; // 2 min for bash
|
|
25
|
+
const FILE_COMMAND_TIMEOUT_MS = 30_000; // 30s for file operations
|
|
26
|
+
// --- Server lifecycle ---
|
|
27
|
+
function startClientManager(port) {
|
|
28
|
+
if (wss) {
|
|
29
|
+
log.warn('Already running');
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
wss = new WebSocketServer({ port });
|
|
33
|
+
log.info(`WebSocket server started on port ${port}`);
|
|
34
|
+
wss.on('connection', (ws) => {
|
|
35
|
+
let deviceName = null;
|
|
36
|
+
ws.on('message', (raw) => {
|
|
37
|
+
let msg;
|
|
38
|
+
try {
|
|
39
|
+
msg = JSON.parse(raw.toString());
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (msg.type === 'hello') {
|
|
45
|
+
deviceName = msg.device;
|
|
46
|
+
if (!deviceName) {
|
|
47
|
+
ws.close(4001, 'Missing device name');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
// If a device with the same name is already connected, reject the new connection
|
|
51
|
+
const existing = devices.get(deviceName);
|
|
52
|
+
if (existing && existing.ws !== ws) {
|
|
53
|
+
log.info(`Device ${deviceName} already connected, rejecting new connection`);
|
|
54
|
+
ws.close(4002, 'Device already connected');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
devices.set(deviceName, {
|
|
58
|
+
device: deviceName,
|
|
59
|
+
platform: msg.platform || 'unknown',
|
|
60
|
+
capabilities: msg.capabilities || [],
|
|
61
|
+
connectedAt: new Date(),
|
|
62
|
+
lastHeartbeat: new Date(),
|
|
63
|
+
ws,
|
|
64
|
+
});
|
|
65
|
+
log.info(`Device connected: ${deviceName} (${msg.platform || 'unknown'})`);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (msg.type === 'heartbeat' && deviceName) {
|
|
69
|
+
const info = devices.get(deviceName);
|
|
70
|
+
if (info) {
|
|
71
|
+
info.lastHeartbeat = new Date();
|
|
72
|
+
}
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (msg.type === 'result' && msg.commandId) {
|
|
76
|
+
const pending = pendingCommands.get(msg.commandId);
|
|
77
|
+
if (pending) {
|
|
78
|
+
pendingCommands.delete(msg.commandId);
|
|
79
|
+
clearTimeout(pending.timer);
|
|
80
|
+
if (msg.success) {
|
|
81
|
+
pending.resolve(msg.data);
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
pending.reject(new Error(msg.error || 'Command failed'));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (msg.type === 'task-callback') {
|
|
90
|
+
handleTaskCallback(ws, msg);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
ws.on('close', () => {
|
|
95
|
+
if (deviceName) {
|
|
96
|
+
const current = devices.get(deviceName);
|
|
97
|
+
if (current && current.ws === ws) {
|
|
98
|
+
log.info(`Device disconnected: ${deviceName}`);
|
|
99
|
+
devices.delete(deviceName);
|
|
100
|
+
// Reject all pending commands for this device
|
|
101
|
+
for (const [id, pending] of pendingCommands) {
|
|
102
|
+
if (pending.device === deviceName) {
|
|
103
|
+
clearTimeout(pending.timer);
|
|
104
|
+
pending.reject(new Error(`Device "${deviceName}" disconnected`));
|
|
105
|
+
pendingCommands.delete(id);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Auto-restart remote client
|
|
109
|
+
scheduleRestart(deviceName);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
ws.on('error', (err) => {
|
|
114
|
+
log.error(`WebSocket error for ${deviceName || 'unknown'}: ${err.message}`);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
// Periodic heartbeat check — mark stale devices as offline
|
|
118
|
+
heartbeatCheckInterval = setInterval(() => {
|
|
119
|
+
const now = Date.now();
|
|
120
|
+
const toEvict = [];
|
|
121
|
+
for (const [name, info] of devices) {
|
|
122
|
+
if (now - info.lastHeartbeat.getTime() > HEARTBEAT_TIMEOUT_MS) {
|
|
123
|
+
toEvict.push({ name, info });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const { name, info } of toEvict) {
|
|
127
|
+
// Guard: only evict if entry hasn't been replaced by a reconnect
|
|
128
|
+
const current = devices.get(name);
|
|
129
|
+
if (current && current.ws === info.ws) {
|
|
130
|
+
log.info(`Device ${name} heartbeat timeout, marking offline`);
|
|
131
|
+
try {
|
|
132
|
+
info.ws.close(4003, 'Heartbeat timeout');
|
|
133
|
+
}
|
|
134
|
+
catch { }
|
|
135
|
+
devices.delete(name);
|
|
136
|
+
// Reject pending commands for this device
|
|
137
|
+
for (const [id, pending] of pendingCommands) {
|
|
138
|
+
if (pending.device === name) {
|
|
139
|
+
clearTimeout(pending.timer);
|
|
140
|
+
pending.reject(new Error(`Device "${name}" heartbeat timeout`));
|
|
141
|
+
pendingCommands.delete(id);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Auto-restart remote client after heartbeat timeout
|
|
145
|
+
scheduleRestart(name);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}, 5000);
|
|
149
|
+
wss.on('error', (err) => {
|
|
150
|
+
log.error(`Server error: ${err.message}`);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
function stopClientManager() {
|
|
154
|
+
if (heartbeatCheckInterval) {
|
|
155
|
+
clearInterval(heartbeatCheckInterval);
|
|
156
|
+
heartbeatCheckInterval = null;
|
|
157
|
+
}
|
|
158
|
+
// Reject all pending commands
|
|
159
|
+
for (const [id, pending] of pendingCommands) {
|
|
160
|
+
clearTimeout(pending.timer);
|
|
161
|
+
pending.reject(new Error('Client manager shutting down'));
|
|
162
|
+
pendingCommands.delete(id);
|
|
163
|
+
}
|
|
164
|
+
// Close all connections
|
|
165
|
+
for (const [, info] of devices) {
|
|
166
|
+
try {
|
|
167
|
+
info.ws.close(1001, 'Server shutting down');
|
|
168
|
+
}
|
|
169
|
+
catch { }
|
|
170
|
+
}
|
|
171
|
+
devices.clear();
|
|
172
|
+
if (wss) {
|
|
173
|
+
wss.close();
|
|
174
|
+
wss = null;
|
|
175
|
+
log.info('WebSocket server stopped');
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
// --- Device queries ---
|
|
179
|
+
function getOnlineDevices() {
|
|
180
|
+
const result = [];
|
|
181
|
+
for (const [, info] of devices) {
|
|
182
|
+
result.push({
|
|
183
|
+
device: info.device,
|
|
184
|
+
platform: info.platform,
|
|
185
|
+
connectedAt: info.connectedAt,
|
|
186
|
+
lastHeartbeat: info.lastHeartbeat,
|
|
187
|
+
capabilities: info.capabilities,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
function isDeviceOnline(device) {
|
|
193
|
+
return devices.has(device);
|
|
194
|
+
}
|
|
195
|
+
// --- Command routing ---
|
|
196
|
+
function sendCommand(device, command) {
|
|
197
|
+
const info = devices.get(device);
|
|
198
|
+
if (!info) {
|
|
199
|
+
return Promise.reject(new Error(`Device "${device}" is not online`));
|
|
200
|
+
}
|
|
201
|
+
if (info.ws.readyState !== WebSocket.OPEN) {
|
|
202
|
+
devices.delete(device);
|
|
203
|
+
return Promise.reject(new Error(`Device "${device}" WebSocket is not open`));
|
|
204
|
+
}
|
|
205
|
+
const commandId = crypto.randomBytes(8).toString('hex');
|
|
206
|
+
const timeoutMs = command.timeout || (command.action === 'bash' ? DEFAULT_COMMAND_TIMEOUT_MS : FILE_COMMAND_TIMEOUT_MS);
|
|
207
|
+
return new Promise((resolve, reject) => {
|
|
208
|
+
const timer = setTimeout(() => {
|
|
209
|
+
pendingCommands.delete(commandId);
|
|
210
|
+
reject(new Error(`Command to "${device}" timed out after ${timeoutMs / 1000}s`));
|
|
211
|
+
}, timeoutMs);
|
|
212
|
+
pendingCommands.set(commandId, { resolve, reject, timer, device });
|
|
213
|
+
try {
|
|
214
|
+
info.ws.send(JSON.stringify({
|
|
215
|
+
type: 'command',
|
|
216
|
+
commandId,
|
|
217
|
+
action: command.action,
|
|
218
|
+
params: command.params,
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
pendingCommands.delete(commandId);
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
reject(new Error(`Failed to send command to "${device}": ${err.message}`));
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
// --- Remote client lifecycle (SSH nohup start, PID tracking, auto-restart) ---
|
|
229
|
+
const PID_FILE = path.join(STORE_DIR, 'client-pids.json');
|
|
230
|
+
const restartTimers = new Map();
|
|
231
|
+
const RESTART_DELAY_MS = 60_000; // retry every 60s until device reconnects
|
|
232
|
+
function loadPids() {
|
|
233
|
+
try {
|
|
234
|
+
return JSON.parse(fs.readFileSync(PID_FILE, 'utf8'));
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return {};
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function savePids(pids) {
|
|
241
|
+
fs.mkdirSync(STORE_DIR, { recursive: true });
|
|
242
|
+
fs.writeFileSync(PID_FILE, JSON.stringify(pids, null, 2));
|
|
243
|
+
}
|
|
244
|
+
function getPid(device) { return loadPids()[device]; }
|
|
245
|
+
function setPid(device, pid) { const p = loadPids(); p[device] = pid; savePids(p); }
|
|
246
|
+
function deletePid(device) { const p = loadPids(); delete p[device]; savePids(p); }
|
|
247
|
+
// Keep in-memory alias for export compatibility
|
|
248
|
+
const clientPids = { get: getPid, set: setPid, delete: deletePid };
|
|
249
|
+
function sshExec(host, command, timeout = 15000) {
|
|
250
|
+
return new Promise((resolve, reject) => {
|
|
251
|
+
execFile('ssh', ['-o', 'ConnectTimeout=5', '-o', 'StrictHostKeyChecking=no', host, command], { timeout }, (err, stdout, stderr) => {
|
|
252
|
+
if (err)
|
|
253
|
+
reject(new Error(`SSH error: ${err.message}\n${stderr}`));
|
|
254
|
+
else
|
|
255
|
+
resolve(stdout.trim());
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
let _sshExecImpl = sshExec;
|
|
260
|
+
let _getRegistryImpl = getMachineRegistry;
|
|
261
|
+
/**
|
|
262
|
+
* Build the shell command run over SSH to spawn cortex-client on a remote device.
|
|
263
|
+
*
|
|
264
|
+
* Windows note: WMI `Win32_Process.Create` does NOT perform PATH lookup, and
|
|
265
|
+
* `cortex-client` installed by npm on Windows is a `.cmd` shim
|
|
266
|
+
* (e.g. `C:\Users\<u>\AppData\Roaming\npm\cortex-client.cmd`). Passing the bare
|
|
267
|
+
* name returns ReturnValue=9 (Path Not Found) with an empty ProcessId, which
|
|
268
|
+
* over SSH serializes to "" and the parent caller logs
|
|
269
|
+
* `Failed to parse PID for <device>: ""`. Wrapping with `cmd.exe /c` makes cmd
|
|
270
|
+
* do the PATH lookup and run the .cmd shim correctly.
|
|
271
|
+
*
|
|
272
|
+
* Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
|
|
273
|
+
* returns the child PID on stdout.
|
|
274
|
+
*/
|
|
275
|
+
function buildRemoteSpawnCommand(reg) {
|
|
276
|
+
if (reg.win) {
|
|
277
|
+
return `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList 'cmd.exe /c cortex-client').ProcessId"`;
|
|
278
|
+
}
|
|
279
|
+
return `nohup cortex-client > /dev/null 2>&1 & echo $!`;
|
|
280
|
+
}
|
|
281
|
+
async function isRemotePidAlive(device) {
|
|
282
|
+
const reg = _getRegistryImpl()[device];
|
|
283
|
+
if (!reg?.ssh)
|
|
284
|
+
return false;
|
|
285
|
+
const pid = clientPids.get(device);
|
|
286
|
+
if (!pid)
|
|
287
|
+
return false;
|
|
288
|
+
try {
|
|
289
|
+
const cmd = reg.win
|
|
290
|
+
? `tasklist /fi "pid eq ${pid}" /fo csv /nh`
|
|
291
|
+
: `kill -0 ${pid} 2>/dev/null && echo alive || echo dead`;
|
|
292
|
+
const result = await _sshExecImpl(reg.ssh, cmd);
|
|
293
|
+
return reg.win ? result.includes(`"${pid}"`) : result.includes('alive');
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function startRemoteClient(device) {
|
|
300
|
+
const reg = _getRegistryImpl()[device];
|
|
301
|
+
if (!reg)
|
|
302
|
+
return;
|
|
303
|
+
// Check if already online via WebSocket
|
|
304
|
+
if (devices.has(device))
|
|
305
|
+
return;
|
|
306
|
+
// Check if existing PID still alive
|
|
307
|
+
if (reg.ssh && await isRemotePidAlive(device)) {
|
|
308
|
+
log.info(`Client on ${device} already running (PID ${clientPids.get(device)}), waiting for reconnect...`);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
// Local device (no SSH): spawn cortex-client (config managed by LLM)
|
|
312
|
+
if (!reg.ssh) {
|
|
313
|
+
try {
|
|
314
|
+
const child = spawn('cortex-client', [], {
|
|
315
|
+
detached: true,
|
|
316
|
+
stdio: 'ignore',
|
|
317
|
+
});
|
|
318
|
+
child.on('error', (err) => {
|
|
319
|
+
const e = err;
|
|
320
|
+
if (e.code === 'ENOENT') {
|
|
321
|
+
log.warn(`cortex-client binary not found on PATH — skipping local client spawn on ${device} (install with: npm i -g cortex-client)`);
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
log.error(`Local client spawn error on ${device}: ${e.message}`);
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
child.unref();
|
|
328
|
+
if (child.pid) {
|
|
329
|
+
clientPids.set(device, child.pid);
|
|
330
|
+
log.info(`Started local client on ${device} (PID ${child.pid})`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
catch (err) {
|
|
334
|
+
log.error(`Failed to start local client on ${device}: ${err.message}`);
|
|
335
|
+
}
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
// Remote device: launch cortex-client (config managed by LLM, written once at bootstrap).
|
|
339
|
+
// On ANY failure path (SSH error, empty/unparseable PID), we MUST schedule a retry —
|
|
340
|
+
// otherwise a single startup failure leaves the device offline until the next server
|
|
341
|
+
// restart, because scheduleRestart() is otherwise only triggered by disconnect or
|
|
342
|
+
// heartbeat-timeout of an already-connected device.
|
|
343
|
+
try {
|
|
344
|
+
const pidStr = await _sshExecImpl(reg.ssh, buildRemoteSpawnCommand(reg), 30000);
|
|
345
|
+
const pid = parseInt(pidStr);
|
|
346
|
+
if (!isNaN(pid) && pid > 0) {
|
|
347
|
+
clientPids.set(device, pid);
|
|
348
|
+
log.info(`Started client on ${device} (PID ${pid})`);
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
log.warn(`Failed to parse PID for ${device}: "${pidStr}" — scheduling retry`);
|
|
352
|
+
scheduleRestart(device);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
catch (err) {
|
|
356
|
+
log.error(`Failed to start client on ${device}: ${err.message} — scheduling retry`);
|
|
357
|
+
scheduleRestart(device);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function scheduleRestart(device) {
|
|
361
|
+
const reg = _getRegistryImpl()[device];
|
|
362
|
+
if (!reg || restartTimers.has(device))
|
|
363
|
+
return;
|
|
364
|
+
const timer = setTimeout(async () => {
|
|
365
|
+
restartTimers.delete(device);
|
|
366
|
+
if (devices.has(device))
|
|
367
|
+
return; // already reconnected
|
|
368
|
+
log.info(`Auto-restarting client on ${device}...`);
|
|
369
|
+
try {
|
|
370
|
+
await startRemoteClient(device);
|
|
371
|
+
}
|
|
372
|
+
catch (err) {
|
|
373
|
+
log.error(`Restart failed for ${device}: ${err.message}`);
|
|
374
|
+
}
|
|
375
|
+
// If still offline, schedule another attempt
|
|
376
|
+
if (!devices.has(device)) {
|
|
377
|
+
scheduleRestart(device);
|
|
378
|
+
}
|
|
379
|
+
}, RESTART_DELAY_MS);
|
|
380
|
+
restartTimers.set(device, timer);
|
|
381
|
+
}
|
|
382
|
+
/** Start clients on all registered devices */
|
|
383
|
+
async function startAllRemoteClients() {
|
|
384
|
+
for (const [device] of Object.entries(_getRegistryImpl())) {
|
|
385
|
+
try {
|
|
386
|
+
await startRemoteClient(device);
|
|
387
|
+
}
|
|
388
|
+
catch (err) {
|
|
389
|
+
log.error(`Failed to start ${device}: ${err.message}`);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
// --- Test hooks ---
|
|
394
|
+
// Tests override sshExec / registry to exercise spawn-failure and retry-scheduling
|
|
395
|
+
// paths without actually invoking the `ssh` binary. _testReset() must clear timers
|
|
396
|
+
// before module state leaks between tests.
|
|
397
|
+
function _setSshExecForTesting(fn) { _sshExecImpl = fn; }
|
|
398
|
+
function _setMachineRegistryProviderForTesting(fn) { _getRegistryImpl = fn; }
|
|
399
|
+
function _getRestartTimerCount() { return restartTimers.size; }
|
|
400
|
+
function _testReset() {
|
|
401
|
+
for (const [, timer] of restartTimers)
|
|
402
|
+
clearTimeout(timer);
|
|
403
|
+
restartTimers.clear();
|
|
404
|
+
_sshExecImpl = sshExec;
|
|
405
|
+
_getRegistryImpl = getMachineRegistry;
|
|
406
|
+
}
|
|
407
|
+
// --- Task callback handler (DR-0011 §4.4) ---
|
|
408
|
+
function sendAck(ws, callbackId, ok, message) {
|
|
409
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
410
|
+
ws.send(JSON.stringify({ type: 'task-callback-ack', callbackId, ok, message }));
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
function handleTaskCallback(ws, msg) {
|
|
414
|
+
const { taskProject, taskId, termination, exitCode, durationHuman, remoteResultPath, remoteLogPath, device, callbackId, logTail } = msg;
|
|
415
|
+
// No task linkage: ack-true immediately (client doesn't need to retry)
|
|
416
|
+
if (!taskProject || !taskId) {
|
|
417
|
+
sendAck(ws, callbackId, true, 'no task linkage');
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
// Read task state from TASKS.yaml for idempotency check
|
|
421
|
+
const tasks = readTasks(taskProject);
|
|
422
|
+
const found = findTask(tasks, null, taskId);
|
|
423
|
+
if ('error' in found) {
|
|
424
|
+
log.info(`Ghost callback: task ${taskId} not found in ${taskProject}`);
|
|
425
|
+
sendAck(ws, callbackId, true, 'ghost callback');
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const task = found.task;
|
|
429
|
+
if (task.status === 'done') {
|
|
430
|
+
sendAck(ws, callbackId, true, 'already done, idempotent');
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const isSuccess = termination === 'completed' && exitCode === 0;
|
|
434
|
+
const remoteRef = remoteResultPath || remoteLogPath || 'unknown';
|
|
435
|
+
const note = isSuccess
|
|
436
|
+
? `cortex-run on ${device} completed in ${durationHuman || '?'}, exit 0. Remote: ${remoteRef}`
|
|
437
|
+
: `cortex-run on ${device} ${termination || '?'} after ${durationHuman || '?'}, exit ${exitCode ?? '?'}. Remote: ${remoteRef}\n--- log tail ---\n${logTail || '(no log tail)'}`;
|
|
438
|
+
let result;
|
|
439
|
+
if (isSuccess) {
|
|
440
|
+
result = completeTask(null, taskProject, note, taskId, true, 'remote-run');
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
result = blockTask(null, taskProject, note, taskId);
|
|
444
|
+
}
|
|
445
|
+
const ackMessage = result.verify_warning
|
|
446
|
+
? `${result.message} (${result.verify_warning})`
|
|
447
|
+
: result.message;
|
|
448
|
+
sendAck(ws, callbackId, result.success, ackMessage);
|
|
449
|
+
}
|
|
450
|
+
export { startClientManager, stopClientManager, getOnlineDevices, isDeviceOnline, sendCommand, startRemoteClient, startAllRemoteClients, buildRemoteSpawnCommand, clientPids, sshExec,
|
|
451
|
+
// Test-only hooks (prefixed with _ by convention).
|
|
452
|
+
_setSshExecForTesting, _setMachineRegistryProviderForTesting, _getRestartTimerCount, _testReset, };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|