@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,630 @@
|
|
|
1
|
+
// input: @slack/bolt, @slack/web-api, ../adapter.js, ../types.js
|
|
2
|
+
// output: SlackAdapter + SlackAdapterConfig
|
|
3
|
+
// pos: Slack platform PlatformAdapter implementation
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { App } from '@slack/bolt';
|
|
6
|
+
import { TokenBucketRateLimiter } from '../utils/rate-limiter.js';
|
|
7
|
+
import { createLogger } from '../../core/log.js';
|
|
8
|
+
import * as fs from 'fs';
|
|
9
|
+
import * as path from 'path';
|
|
10
|
+
import { writeFile, readFile, mkdir } from 'fs/promises';
|
|
11
|
+
import { CONFIG_DIR } from '../../core/utils.js';
|
|
12
|
+
const log = createLogger('slack');
|
|
13
|
+
const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
|
|
14
|
+
const IMAGE_MAGIC = {
|
|
15
|
+
'\x89PNG': 'image/png',
|
|
16
|
+
'\xFF\xD8\xFF': 'image/jpeg',
|
|
17
|
+
'GIF8': 'image/gif',
|
|
18
|
+
'RIFF': 'image/webp',
|
|
19
|
+
};
|
|
20
|
+
function sleep(ms) {
|
|
21
|
+
if (ms <= 0)
|
|
22
|
+
return Promise.resolve();
|
|
23
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
24
|
+
}
|
|
25
|
+
/** Maximum entries in the pendingEdits coalescing map (LRU eviction). */
|
|
26
|
+
const PENDING_EDITS_MAX = 200;
|
|
27
|
+
export class SlackAdapter {
|
|
28
|
+
name = 'slack';
|
|
29
|
+
capabilities = {
|
|
30
|
+
threads: true,
|
|
31
|
+
messageEdit: true,
|
|
32
|
+
modals: true,
|
|
33
|
+
reactions: true,
|
|
34
|
+
ephemeral: true,
|
|
35
|
+
fileUpload: true,
|
|
36
|
+
richFormatting: true,
|
|
37
|
+
maxMessageLength: 3000,
|
|
38
|
+
maxThreadDepth: 1,
|
|
39
|
+
};
|
|
40
|
+
app;
|
|
41
|
+
client;
|
|
42
|
+
config;
|
|
43
|
+
editHandler = null;
|
|
44
|
+
_adminAutoDetected = false;
|
|
45
|
+
/**
|
|
46
|
+
* Per-message pending edit buffer for chat.update coalescing.
|
|
47
|
+
* When multiple callers race to update the same message, only the latest
|
|
48
|
+
* content is preserved — intermediate edits are discarded. The async flush
|
|
49
|
+
* loop acquires a rate-limit token, then sends whatever the latest content
|
|
50
|
+
* is at that point.
|
|
51
|
+
*
|
|
52
|
+
* Key = `${channel}:${ts}`, value = latest content + shared promise.
|
|
53
|
+
* Bounded at PENDING_EDITS_MAX entries with LRU-style eviction.
|
|
54
|
+
*/
|
|
55
|
+
pendingEdits = new Map();
|
|
56
|
+
/** Token-bucket rate limiter shared across all Slack API methods. */
|
|
57
|
+
rateLimiter;
|
|
58
|
+
constructor(config) {
|
|
59
|
+
this.config = config;
|
|
60
|
+
this.app = new App({
|
|
61
|
+
token: config.botToken,
|
|
62
|
+
signingSecret: config.signingSecret,
|
|
63
|
+
socketMode: true,
|
|
64
|
+
appToken: config.appToken,
|
|
65
|
+
});
|
|
66
|
+
this.client = this.app.client;
|
|
67
|
+
// Rate limiter defaults: conservative (40-60% of Slack Tier 3 limits).
|
|
68
|
+
// Override via CORTEX_SLACK_RL_* env vars.
|
|
69
|
+
this.rateLimiter = new TokenBucketRateLimiter({
|
|
70
|
+
globalCapacity: this._envNum('CORTEX_SLACK_RL_GLOBAL_CAPACITY', 20),
|
|
71
|
+
globalRefillPerSec: this._envNum('CORTEX_SLACK_RL_GLOBAL_REFILL_PER_SEC', 1),
|
|
72
|
+
perChannelCapacity: this._envNum('CORTEX_SLACK_RL_CHANNEL_CAPACITY', 1),
|
|
73
|
+
perChannelRefillPerSec: this._envNum('CORTEX_SLACK_RL_CHANNEL_REFILL_PER_SEC', 1),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
_envNum(key, def) {
|
|
77
|
+
const v = process.env[key];
|
|
78
|
+
return v ? Number(v) : def;
|
|
79
|
+
}
|
|
80
|
+
// --- Lifecycle ---
|
|
81
|
+
async start() {
|
|
82
|
+
await this.app.start();
|
|
83
|
+
}
|
|
84
|
+
async stop() {
|
|
85
|
+
await this.app.stop();
|
|
86
|
+
}
|
|
87
|
+
// --- Event registration ---
|
|
88
|
+
onMessage(handler) {
|
|
89
|
+
this.app.event('message', async ({ event, client }) => {
|
|
90
|
+
const msg = event;
|
|
91
|
+
// Route message_changed to onMessageEdit handler
|
|
92
|
+
if (msg.subtype === 'message_changed' && this.editHandler) {
|
|
93
|
+
const editedMsg = msg.message;
|
|
94
|
+
const previousMsg = msg.previous_message;
|
|
95
|
+
if (editedMsg && previousMsg) {
|
|
96
|
+
if (editedMsg.bot_id || editedMsg.subtype === 'bot_message')
|
|
97
|
+
return;
|
|
98
|
+
if (editedMsg.text === previousMsg.text)
|
|
99
|
+
return;
|
|
100
|
+
await this.editHandler({
|
|
101
|
+
originalRef: { channel: msg.channel, messageId: editedMsg.ts },
|
|
102
|
+
newText: editedMsg.text || '',
|
|
103
|
+
raw: msg,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
// Auto-detect admin channel from DM when CORTEX_ADMIN_CHANNEL is not configured.
|
|
109
|
+
// The first DM (channel starting with "D") from a non-bot user is registered
|
|
110
|
+
// as the admin channel, persisted to .env, and set on process.env.
|
|
111
|
+
if (!this.config.adminChannel && !this._adminAutoDetected && msg.channel?.startsWith('D') && !msg.bot_id) {
|
|
112
|
+
this._adminAutoDetected = true;
|
|
113
|
+
this.config.adminChannel = msg.channel;
|
|
114
|
+
process.env.CORTEX_ADMIN_CHANNEL = msg.channel;
|
|
115
|
+
log.info(`Admin channel auto-detected from DM: ${msg.channel}`);
|
|
116
|
+
// Persist to .env and notify (fire-and-forget, non-blocking)
|
|
117
|
+
this._persistAdminChannel(msg.channel).catch(e => log.warn(`Failed to persist CORTEX_ADMIN_CHANNEL to .env: ${e.message}`));
|
|
118
|
+
this.postMessage(msg.channel, {
|
|
119
|
+
text: `:wave: This DM channel has been auto-registered as the Cortex admin channel. \`CORTEX_ADMIN_CHANNEL=${msg.channel}\` has been written to \`.env\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
|
|
120
|
+
}).catch(e => log.warn(`Failed to send admin auto-detect notification: ${e.message}`));
|
|
121
|
+
}
|
|
122
|
+
const ref = {
|
|
123
|
+
channel: msg.channel,
|
|
124
|
+
messageId: msg.ts,
|
|
125
|
+
threadId: msg.thread_ts || undefined,
|
|
126
|
+
};
|
|
127
|
+
const files = msg.files?.map((f) => ({
|
|
128
|
+
id: f.id,
|
|
129
|
+
name: f.name,
|
|
130
|
+
mimetype: f.mimetype,
|
|
131
|
+
url: f.url_private,
|
|
132
|
+
raw: f,
|
|
133
|
+
}));
|
|
134
|
+
const attachments = msg.attachments?.map((att) => ({
|
|
135
|
+
authorName: att.author_name,
|
|
136
|
+
text: att.text || att.fallback,
|
|
137
|
+
url: att.from_url,
|
|
138
|
+
isForwarded: !!(att.is_msg_unfurl || att.author_name || att.from_url),
|
|
139
|
+
}));
|
|
140
|
+
const incoming = {
|
|
141
|
+
ref,
|
|
142
|
+
text: msg.text || '',
|
|
143
|
+
senderId: msg.user || msg.bot_id || '',
|
|
144
|
+
isBot: !!msg.bot_id,
|
|
145
|
+
files,
|
|
146
|
+
attachments,
|
|
147
|
+
subtype: msg.subtype,
|
|
148
|
+
raw: msg,
|
|
149
|
+
};
|
|
150
|
+
const adapter = this;
|
|
151
|
+
await handler({
|
|
152
|
+
message: incoming,
|
|
153
|
+
async reply(content, opts) {
|
|
154
|
+
return adapter.postMessage(ref.channel, content, {
|
|
155
|
+
threadId: opts?.threadId || ref.threadId,
|
|
156
|
+
});
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
onMessageEdit(handler) {
|
|
162
|
+
this.editHandler = handler;
|
|
163
|
+
}
|
|
164
|
+
onAction(actionId, handler) {
|
|
165
|
+
this.app.action(actionId, async ({ ack, body, action }) => {
|
|
166
|
+
await ack();
|
|
167
|
+
await handler({
|
|
168
|
+
actionId,
|
|
169
|
+
value: action.value,
|
|
170
|
+
triggerId: body.trigger_id,
|
|
171
|
+
messageRef: body.message?.ts ? {
|
|
172
|
+
channel: body.channel?.id || '',
|
|
173
|
+
messageId: body.message.ts,
|
|
174
|
+
} : undefined,
|
|
175
|
+
userId: body.user?.id || '',
|
|
176
|
+
channelId: body.channel?.id || '',
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
onModalSubmit(callbackId, handler) {
|
|
181
|
+
this.app.view(callbackId, async ({ ack, body, view }) => {
|
|
182
|
+
let ackCalled = false;
|
|
183
|
+
await handler({
|
|
184
|
+
callbackId,
|
|
185
|
+
privateMetadata: view.private_metadata || '',
|
|
186
|
+
values: this.normalizeModalValues(view.state?.values || {}),
|
|
187
|
+
userId: body.user?.id || '',
|
|
188
|
+
async ack(response) {
|
|
189
|
+
if (ackCalled)
|
|
190
|
+
return;
|
|
191
|
+
ackCalled = true;
|
|
192
|
+
if (response?.errors) {
|
|
193
|
+
await ack({ response_action: 'errors', errors: response.errors });
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
await ack();
|
|
197
|
+
}
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
if (!ackCalled)
|
|
201
|
+
await ack();
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
// --- Outbound messaging ---
|
|
205
|
+
/**
|
|
206
|
+
* Wrap a Slack API call with rate-limiting + 429 response handling.
|
|
207
|
+
* 1. Acquires a token from the rate limiter (blocks if needed)
|
|
208
|
+
* 2. Calls the API
|
|
209
|
+
* 3. On 429: reports backpressure to the rate limiter, re-throws
|
|
210
|
+
*/
|
|
211
|
+
async rateLimitedCall(method, channel, fn) {
|
|
212
|
+
await this.rateLimiter.acquire(method, channel);
|
|
213
|
+
try {
|
|
214
|
+
return await fn();
|
|
215
|
+
}
|
|
216
|
+
catch (e) {
|
|
217
|
+
const retryAfterSec = Number(e?.retryAfter ?? e?.headers?.['retry-after']);
|
|
218
|
+
if (Number.isFinite(retryAfterSec) && retryAfterSec > 0) {
|
|
219
|
+
this.rateLimiter.reportThrottled(method, channel, retryAfterSec);
|
|
220
|
+
}
|
|
221
|
+
throw e;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async postMessage(channel, content, opts) {
|
|
225
|
+
const blocks = content.richBlocks ? this.richBlocksToSlack(content.richBlocks) : undefined;
|
|
226
|
+
const payload = {
|
|
227
|
+
channel,
|
|
228
|
+
text: content.text,
|
|
229
|
+
...(blocks && { blocks }),
|
|
230
|
+
...(opts?.threadId && { thread_ts: opts.threadId }),
|
|
231
|
+
};
|
|
232
|
+
const result = await this.rateLimitedCall('chat.postMessage', channel, () => this.client.chat.postMessage(payload));
|
|
233
|
+
return {
|
|
234
|
+
channel,
|
|
235
|
+
messageId: result.ts,
|
|
236
|
+
threadId: opts?.threadId,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Update a message with per-message coalescing.
|
|
241
|
+
*
|
|
242
|
+
* If another update is already in-flight for the same message (pending a rate
|
|
243
|
+
* limiter token), this call replaces the buffered content and returns the
|
|
244
|
+
* shared promise — the intermediate edit is discarded. Once the rate limiter
|
|
245
|
+
* grants a token, the latest content is sent via chat.update.
|
|
246
|
+
*
|
|
247
|
+
* This eliminates wasted API calls when multiple callers (VirtualMessage
|
|
248
|
+
* streaming, status helpers, lifecycle) concurrently update the same message
|
|
249
|
+
* while rate-limited.
|
|
250
|
+
*
|
|
251
|
+
* Internal retry loop: on 429, re-queues the entry and loops back to acquire
|
|
252
|
+
* instead of recursing, which avoids coalescing confusion.
|
|
253
|
+
*/
|
|
254
|
+
async updateMessage(ref, content) {
|
|
255
|
+
const key = `${ref.channel}:${ref.messageId}`;
|
|
256
|
+
const existing = this.pendingEdits.get(key);
|
|
257
|
+
if (existing) {
|
|
258
|
+
// ── Coalesce ──
|
|
259
|
+
// This message already has a pending flush. Discard the old content,
|
|
260
|
+
// keep only the latest. Return the shared promise so all callers
|
|
261
|
+
// unblock at the same time when the flush completes.
|
|
262
|
+
existing.content = content;
|
|
263
|
+
return existing.promise;
|
|
264
|
+
}
|
|
265
|
+
// ── First call for this message ──
|
|
266
|
+
let resolve;
|
|
267
|
+
const promise = new Promise(r => { resolve = r; });
|
|
268
|
+
this.pendingEdits.set(key, { content, promise, resolve });
|
|
269
|
+
// LRU eviction: keep the map bounded
|
|
270
|
+
this._evictStalePending();
|
|
271
|
+
// Retry loop: re-acquire token on 429 and send the latest content.
|
|
272
|
+
// The entry stays in the map during the API call so concurrent callers
|
|
273
|
+
// continue to coalesce into it. Reference equality on `content` detects
|
|
274
|
+
// whether new content arrived during the send.
|
|
275
|
+
while (this.pendingEdits.has(key)) {
|
|
276
|
+
try {
|
|
277
|
+
await this.rateLimiter.acquire('chat.update', ref.channel);
|
|
278
|
+
const entry = this.pendingEdits.get(key);
|
|
279
|
+
if (!entry) {
|
|
280
|
+
resolve();
|
|
281
|
+
return;
|
|
282
|
+
} // cleaned up (deleteMessage / eviction)
|
|
283
|
+
const snapshot = entry.content;
|
|
284
|
+
const blocks = snapshot.richBlocks ? this.richBlocksToSlack(snapshot.richBlocks) : undefined;
|
|
285
|
+
await this.client.chat.update({
|
|
286
|
+
channel: ref.channel,
|
|
287
|
+
ts: ref.messageId,
|
|
288
|
+
text: snapshot.text,
|
|
289
|
+
...(blocks && { blocks }),
|
|
290
|
+
});
|
|
291
|
+
// Check if content was coalesced during the API call.
|
|
292
|
+
const current = this.pendingEdits.get(key);
|
|
293
|
+
if (current && current.content !== snapshot) {
|
|
294
|
+
continue; // new content arrived — loop to send it
|
|
295
|
+
}
|
|
296
|
+
this.pendingEdits.delete(key);
|
|
297
|
+
resolve();
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
catch (e) {
|
|
301
|
+
const retryAfterSec = Number(e?.retryAfter ?? e?.headers?.['retry-after']);
|
|
302
|
+
if (Number.isFinite(retryAfterSec) && retryAfterSec > 0) {
|
|
303
|
+
this.rateLimiter.reportThrottled('chat.update', ref.channel, retryAfterSec);
|
|
304
|
+
// Entry stays in the map with latest coalesced content — just loop.
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
// Non-429 error: resolve to avoid hanging callers, but re-throw so the
|
|
308
|
+
// caller (e.g. VirtualMessage) can fall back to posting a new message.
|
|
309
|
+
this.pendingEdits.delete(key);
|
|
310
|
+
resolve();
|
|
311
|
+
throw e;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Evict the oldest entry if the pendingEdits map exceeds PENDING_EDITS_MAX.
|
|
317
|
+
* Resolves the evicted promise so any waiting callers don't hang.
|
|
318
|
+
*/
|
|
319
|
+
_evictStalePending() {
|
|
320
|
+
if (this.pendingEdits.size <= PENDING_EDITS_MAX)
|
|
321
|
+
return;
|
|
322
|
+
const oldest = this.pendingEdits.keys().next().value;
|
|
323
|
+
if (oldest !== undefined) {
|
|
324
|
+
const entry = this.pendingEdits.get(oldest);
|
|
325
|
+
this.pendingEdits.delete(oldest);
|
|
326
|
+
entry?.resolve();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
async deleteMessage(ref) {
|
|
330
|
+
// Clean up any pending edit for this message so coalescing doesn't
|
|
331
|
+
// try to update a deleted message.
|
|
332
|
+
const key = `${ref.channel}:${ref.messageId}`;
|
|
333
|
+
const pending = this.pendingEdits.get(key);
|
|
334
|
+
if (pending) {
|
|
335
|
+
this.pendingEdits.delete(key);
|
|
336
|
+
pending.resolve();
|
|
337
|
+
}
|
|
338
|
+
await this.rateLimitedCall('chat.delete', ref.channel, () => this.client.chat.delete({
|
|
339
|
+
channel: ref.channel,
|
|
340
|
+
ts: ref.messageId,
|
|
341
|
+
}));
|
|
342
|
+
}
|
|
343
|
+
// --- Interactive messages ---
|
|
344
|
+
async postInteractive(channel, content, opts) {
|
|
345
|
+
const blocks = [
|
|
346
|
+
...(content.richBlocks ? this.richBlocksToSlack(content.richBlocks) : []),
|
|
347
|
+
{
|
|
348
|
+
type: 'actions',
|
|
349
|
+
elements: content.actions.map(a => this.actionElementToSlack(a)),
|
|
350
|
+
},
|
|
351
|
+
];
|
|
352
|
+
const result = await this.rateLimitedCall('chat.postMessage', channel, () => this.client.chat.postMessage({
|
|
353
|
+
channel,
|
|
354
|
+
text: content.text,
|
|
355
|
+
blocks,
|
|
356
|
+
...(opts?.threadId && { thread_ts: opts.threadId }),
|
|
357
|
+
}));
|
|
358
|
+
return {
|
|
359
|
+
channel,
|
|
360
|
+
messageId: result.ts,
|
|
361
|
+
threadId: opts?.threadId,
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
// --- Modals ---
|
|
365
|
+
async openModal(triggerId, modal) {
|
|
366
|
+
await this.rateLimitedCall('views.open', undefined, () => this.client.views.open({
|
|
367
|
+
trigger_id: triggerId,
|
|
368
|
+
view: this.modalToSlack(modal),
|
|
369
|
+
}));
|
|
370
|
+
}
|
|
371
|
+
// --- Reactions ---
|
|
372
|
+
async addReaction(ref, emoji) {
|
|
373
|
+
await this.rateLimitedCall('reactions.add', ref.channel, () => this.client.reactions.add({
|
|
374
|
+
channel: ref.channel,
|
|
375
|
+
name: emoji,
|
|
376
|
+
timestamp: ref.messageId,
|
|
377
|
+
}));
|
|
378
|
+
}
|
|
379
|
+
// --- Files ---
|
|
380
|
+
async uploadFile(channel, filePath, opts) {
|
|
381
|
+
const { resolved, size } = this.resolveFilePath(filePath);
|
|
382
|
+
const body = fs.readFileSync(resolved);
|
|
383
|
+
const uploadName = opts?.filename || path.basename(resolved);
|
|
384
|
+
const uploadInit = await this.rateLimitedCall('files.getUploadURLExternal', channel, () => this.client.files.getUploadURLExternal({
|
|
385
|
+
filename: uploadName,
|
|
386
|
+
length: size,
|
|
387
|
+
}));
|
|
388
|
+
if (!uploadInit?.upload_url || !uploadInit?.file_id) {
|
|
389
|
+
throw new Error('Slack upload initialization failed');
|
|
390
|
+
}
|
|
391
|
+
const uploadRes = await fetch(uploadInit.upload_url, {
|
|
392
|
+
method: 'POST',
|
|
393
|
+
headers: { 'Content-Type': 'application/octet-stream' },
|
|
394
|
+
body,
|
|
395
|
+
});
|
|
396
|
+
if (!uploadRes.ok) {
|
|
397
|
+
throw new Error(`Slack file upload failed (${uploadRes.status})`);
|
|
398
|
+
}
|
|
399
|
+
await this.rateLimitedCall('files.completeUploadExternal', channel, () => this.client.files.completeUploadExternal({
|
|
400
|
+
files: [{ id: uploadInit.file_id, title: uploadName }],
|
|
401
|
+
channel_id: channel,
|
|
402
|
+
}));
|
|
403
|
+
}
|
|
404
|
+
async downloadFile(fileRef, destDir) {
|
|
405
|
+
const authHeader = { Authorization: `Bearer ${this.config.botToken}` };
|
|
406
|
+
let res = await fetch(fileRef.url, {
|
|
407
|
+
headers: authHeader,
|
|
408
|
+
redirect: 'manual',
|
|
409
|
+
});
|
|
410
|
+
while (res.status >= 300 && res.status < 400) {
|
|
411
|
+
const location = res.headers.get('location');
|
|
412
|
+
if (!location)
|
|
413
|
+
break;
|
|
414
|
+
res = await fetch(location, {
|
|
415
|
+
headers: authHeader,
|
|
416
|
+
redirect: 'manual',
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
if (!res.ok)
|
|
420
|
+
throw new Error(`Failed to download file: ${res.status}`);
|
|
421
|
+
const contentType = res.headers.get('content-type') || '';
|
|
422
|
+
if (contentType.includes('text/html') && !fileRef.mimetype?.includes('text/html')) {
|
|
423
|
+
throw new Error('Slack returned HTML instead of file — check bot token has files:read scope');
|
|
424
|
+
}
|
|
425
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
426
|
+
if (IMAGE_MIMES.has(fileRef.mimetype)) {
|
|
427
|
+
const header = buf.subarray(0, 4).toString('binary');
|
|
428
|
+
const isImage = Object.keys(IMAGE_MAGIC).some(magic => header.startsWith(magic));
|
|
429
|
+
if (!isImage) {
|
|
430
|
+
throw new Error(`Downloaded content is not a valid image (got ${contentType || 'unknown type'})`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const ext = path.extname(fileRef.name) || '';
|
|
434
|
+
const localPath = path.join(destDir, `${fileRef.id}${ext}`);
|
|
435
|
+
await writeFile(localPath, buf);
|
|
436
|
+
return { localPath, mimetype: fileRef.mimetype, name: fileRef.name };
|
|
437
|
+
}
|
|
438
|
+
// --- Misc ---
|
|
439
|
+
async getPermalink(ref) {
|
|
440
|
+
try {
|
|
441
|
+
const result = await this.client.chat.getPermalink({
|
|
442
|
+
channel: ref.channel,
|
|
443
|
+
message_ts: ref.messageId,
|
|
444
|
+
});
|
|
445
|
+
return result?.permalink || null;
|
|
446
|
+
}
|
|
447
|
+
catch {
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
async postEphemeral(channel, userId, text) {
|
|
452
|
+
await this.rateLimitedCall('chat.postEphemeral', channel, () => this.client.chat.postEphemeral({ channel, user: userId, text }));
|
|
453
|
+
}
|
|
454
|
+
getAdminChannel() {
|
|
455
|
+
return this.config.adminChannel || null;
|
|
456
|
+
}
|
|
457
|
+
/** Write CORTEX_ADMIN_CHANNEL to the .env file for persistence across restarts. */
|
|
458
|
+
async _persistAdminChannel(channel) {
|
|
459
|
+
const envPath = path.join(CONFIG_DIR, '.env');
|
|
460
|
+
let content = '';
|
|
461
|
+
try {
|
|
462
|
+
content = await readFile(envPath, 'utf-8');
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
// File doesn't exist yet, will be created
|
|
466
|
+
}
|
|
467
|
+
const lines = content.split('\n');
|
|
468
|
+
let found = false;
|
|
469
|
+
for (let i = 0; i < lines.length; i++) {
|
|
470
|
+
if (lines[i].startsWith('CORTEX_ADMIN_CHANNEL=')) {
|
|
471
|
+
lines[i] = `CORTEX_ADMIN_CHANNEL=${channel}`;
|
|
472
|
+
found = true;
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (!found) {
|
|
477
|
+
lines.push(`CORTEX_ADMIN_CHANNEL=${channel}`);
|
|
478
|
+
}
|
|
479
|
+
await mkdir(CONFIG_DIR, { recursive: true });
|
|
480
|
+
await writeFile(envPath, lines.join('\n'), 'utf-8');
|
|
481
|
+
log.info(`CORTEX_ADMIN_CHANNEL=${channel} written to ${envPath}`);
|
|
482
|
+
}
|
|
483
|
+
/** Expose the rate limiter for sharing with MCP tools and testing. */
|
|
484
|
+
getRateLimiter() {
|
|
485
|
+
return this.rateLimiter;
|
|
486
|
+
}
|
|
487
|
+
getRawClient() {
|
|
488
|
+
return this.client;
|
|
489
|
+
}
|
|
490
|
+
// --- Slack-specific converters ---
|
|
491
|
+
normalizeModalValues(rawValues) {
|
|
492
|
+
const normalized = {};
|
|
493
|
+
for (const [blockId, actions] of Object.entries(rawValues)) {
|
|
494
|
+
normalized[blockId] = {};
|
|
495
|
+
for (const [actionId, rawValue] of Object.entries(actions)) {
|
|
496
|
+
normalized[blockId][actionId] = {
|
|
497
|
+
selectedOption: rawValue.selected_option
|
|
498
|
+
? { value: rawValue.selected_option.value }
|
|
499
|
+
: undefined,
|
|
500
|
+
selectedOptions: rawValue.selected_options?.map((o) => ({ value: o.value })),
|
|
501
|
+
value: rawValue.value,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
return normalized;
|
|
506
|
+
}
|
|
507
|
+
richBlocksToSlack(blocks) {
|
|
508
|
+
return blocks.map(block => {
|
|
509
|
+
switch (block.type) {
|
|
510
|
+
case 'markdown':
|
|
511
|
+
return { type: 'markdown', text: block.text };
|
|
512
|
+
case 'section':
|
|
513
|
+
return {
|
|
514
|
+
type: 'section',
|
|
515
|
+
text: { type: block.format === 'plain' ? 'plain_text' : 'mrkdwn', text: block.text },
|
|
516
|
+
};
|
|
517
|
+
case 'context':
|
|
518
|
+
return {
|
|
519
|
+
type: 'context',
|
|
520
|
+
elements: [{ type: 'mrkdwn', text: block.text }],
|
|
521
|
+
};
|
|
522
|
+
case 'divider':
|
|
523
|
+
return { type: 'divider' };
|
|
524
|
+
case 'actions':
|
|
525
|
+
return {
|
|
526
|
+
type: 'actions',
|
|
527
|
+
elements: block.elements.map(e => this.actionElementToSlack(e)),
|
|
528
|
+
};
|
|
529
|
+
default:
|
|
530
|
+
return { type: 'section', text: { type: 'mrkdwn', text: block.text || '' } };
|
|
531
|
+
}
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
actionElementToSlack(el) {
|
|
535
|
+
return {
|
|
536
|
+
type: 'button',
|
|
537
|
+
text: { type: 'plain_text', text: el.text },
|
|
538
|
+
action_id: el.actionId,
|
|
539
|
+
...(el.value && { value: el.value }),
|
|
540
|
+
...(el.style && { style: el.style }),
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
modalToSlack(modal) {
|
|
544
|
+
const blocks = [];
|
|
545
|
+
for (const field of modal.fields) {
|
|
546
|
+
switch (field.type) {
|
|
547
|
+
case 'section':
|
|
548
|
+
blocks.push({
|
|
549
|
+
type: 'section',
|
|
550
|
+
text: { type: 'mrkdwn', text: field.text },
|
|
551
|
+
});
|
|
552
|
+
break;
|
|
553
|
+
case 'select':
|
|
554
|
+
blocks.push({
|
|
555
|
+
type: 'input',
|
|
556
|
+
block_id: field.blockId,
|
|
557
|
+
optional: field.optional ?? false,
|
|
558
|
+
label: { type: 'plain_text', text: field.label },
|
|
559
|
+
element: {
|
|
560
|
+
type: 'static_select',
|
|
561
|
+
action_id: field.actionId,
|
|
562
|
+
placeholder: field.placeholder
|
|
563
|
+
? { type: 'plain_text', text: field.placeholder }
|
|
564
|
+
: undefined,
|
|
565
|
+
options: field.options.map(o => ({
|
|
566
|
+
text: { type: 'plain_text', text: o.label },
|
|
567
|
+
value: o.value,
|
|
568
|
+
})),
|
|
569
|
+
},
|
|
570
|
+
});
|
|
571
|
+
break;
|
|
572
|
+
case 'multi_select':
|
|
573
|
+
blocks.push({
|
|
574
|
+
type: 'input',
|
|
575
|
+
block_id: field.blockId,
|
|
576
|
+
optional: field.optional ?? false,
|
|
577
|
+
label: { type: 'plain_text', text: field.label },
|
|
578
|
+
element: {
|
|
579
|
+
type: 'multi_static_select',
|
|
580
|
+
action_id: field.actionId,
|
|
581
|
+
placeholder: field.placeholder
|
|
582
|
+
? { type: 'plain_text', text: field.placeholder }
|
|
583
|
+
: undefined,
|
|
584
|
+
options: field.options.map(o => ({
|
|
585
|
+
text: { type: 'plain_text', text: o.label },
|
|
586
|
+
value: o.value,
|
|
587
|
+
})),
|
|
588
|
+
},
|
|
589
|
+
});
|
|
590
|
+
break;
|
|
591
|
+
case 'text_input':
|
|
592
|
+
blocks.push({
|
|
593
|
+
type: 'input',
|
|
594
|
+
block_id: field.blockId,
|
|
595
|
+
optional: field.optional ?? false,
|
|
596
|
+
label: { type: 'plain_text', text: field.label },
|
|
597
|
+
element: {
|
|
598
|
+
type: 'plain_text_input',
|
|
599
|
+
action_id: field.actionId,
|
|
600
|
+
multiline: field.multiline ?? false,
|
|
601
|
+
...(field.placeholder && {
|
|
602
|
+
placeholder: { type: 'plain_text', text: field.placeholder },
|
|
603
|
+
}),
|
|
604
|
+
},
|
|
605
|
+
});
|
|
606
|
+
break;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return {
|
|
610
|
+
type: 'modal',
|
|
611
|
+
callback_id: modal.callbackId,
|
|
612
|
+
private_metadata: modal.privateMetadata || '',
|
|
613
|
+
title: { type: 'plain_text', text: modal.title },
|
|
614
|
+
submit: { type: 'plain_text', text: modal.submitLabel || 'Submit' },
|
|
615
|
+
close: { type: 'plain_text', text: modal.closeLabel || 'Cancel' },
|
|
616
|
+
blocks,
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
resolveFilePath(filePath) {
|
|
620
|
+
const resolved = path.isAbsolute(filePath)
|
|
621
|
+
? filePath
|
|
622
|
+
: path.resolve(process.cwd(), filePath);
|
|
623
|
+
if (!fs.existsSync(resolved))
|
|
624
|
+
throw new Error(`File not found: ${resolved}`);
|
|
625
|
+
const stat = fs.statSync(resolved);
|
|
626
|
+
if (!stat.isFile())
|
|
627
|
+
throw new Error(`Not a file: ${resolved}`);
|
|
628
|
+
return { resolved, size: stat.size };
|
|
629
|
+
}
|
|
630
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type { PlatformAdapter } from './adapter.js';
|
|
2
|
+
export type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, ModalField, ModalSelectField, ModalMultiSelectField, ModalTextInputField, ModalSectionField, SelectOption, ModalFieldValue, PlatformCapabilities, PlatformFileRef, DownloadedFile, IncomingMessage, IncomingAttachment, PostMessageOpts, FileUploadOpts, RichBlock, ActionElement, ButtonElement, } from './types.js';
|
|
3
|
+
export { VirtualMessage } from './virtual-message.js';
|
|
4
|
+
export { ToolTrace, createToolTrace, isToolTraceEnabled } from './tool-trace.js';
|
|
5
|
+
export { buildQuestionGroupBlocks, buildQuestionModalDefinition, buildPlanApprovalContent, buildPlanFeedbackModal, } from './interactive-builder.js';
|
|
6
|
+
export type { QuestionOption, QuestionRecord, QuestionGroup } from './interactive-builder.js';
|
|
7
|
+
export { createAdapter, createAdapterFromEnv } from './adapters/index.js';
|
|
8
|
+
export type { PlatformType, AdapterConfig } from './adapters/index.js';
|
|
9
|
+
export { SlackAdapter } from './adapters/slack.js';
|
|
10
|
+
export type { SlackAdapterConfig } from './adapters/slack.js';
|
|
11
|
+
export { FeishuAdapter } from './adapters/feishu.js';
|
|
12
|
+
export type { FeishuAdapterConfig } from './adapters/feishu.js';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// input: adapter + types + virtual-message + adapters/*
|
|
2
|
+
// output: Re-export full family of PlatformAdapter public APIs
|
|
3
|
+
// pos: Public API export of the Platform abstraction
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
export { VirtualMessage } from './virtual-message.js';
|
|
6
|
+
export { ToolTrace, createToolTrace, isToolTraceEnabled } from './tool-trace.js';
|
|
7
|
+
export { buildQuestionGroupBlocks, buildQuestionModalDefinition, buildPlanApprovalContent, buildPlanFeedbackModal, } from './interactive-builder.js';
|
|
8
|
+
export { createAdapter, createAdapterFromEnv } from './adapters/index.js';
|
|
9
|
+
export { SlackAdapter } from './adapters/slack.js';
|
|
10
|
+
export { FeishuAdapter } from './adapters/feishu.js';
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { RichBlock, ModalDefinition, ActionElement } from './types.js';
|
|
2
|
+
export interface QuestionOption {
|
|
3
|
+
label: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface QuestionRecord {
|
|
7
|
+
pendingId: string;
|
|
8
|
+
header: string;
|
|
9
|
+
question: string;
|
|
10
|
+
options: QuestionOption[];
|
|
11
|
+
multiSelect: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface QuestionGroup {
|
|
14
|
+
groupId: string;
|
|
15
|
+
questions: QuestionRecord[];
|
|
16
|
+
answers: Map<string, {
|
|
17
|
+
header: string;
|
|
18
|
+
value: string | string[];
|
|
19
|
+
}>;
|
|
20
|
+
}
|
|
21
|
+
export declare function buildQuestionGroupBlocks(group: QuestionGroup): RichBlock[];
|
|
22
|
+
export declare function buildQuestionModalDefinition(group: QuestionGroup): ModalDefinition;
|
|
23
|
+
export declare function buildPlanApprovalContent(requestId: string): {
|
|
24
|
+
richBlocks: RichBlock[];
|
|
25
|
+
actions: ActionElement[];
|
|
26
|
+
};
|
|
27
|
+
export declare function buildPlanFeedbackModal(requestId: string): ModalDefinition;
|