@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,464 @@
|
|
|
1
|
+
// input: PlatformAdapter, MessageRef/RichBlock/ActionElement
|
|
2
|
+
// output: VirtualMessage class + append/flush/postStandalone/mutableTail
|
|
3
|
+
// pos: Platform-independent continuous message aggregator
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { createLogger } from '../core/log.js';
|
|
6
|
+
const log = createLogger('virtual-message');
|
|
7
|
+
const SEPARATOR = '\n';
|
|
8
|
+
const TAIL_SEPARATOR = '\n';
|
|
9
|
+
const DEFAULT_MAX_CHUNK = 3000;
|
|
10
|
+
const MAX_HORIZONTAL_RULES = 3;
|
|
11
|
+
// Retry delays for transient adapter failures (Slack rate-limits typically last
|
|
12
|
+
// 1–5s). Total wall time across all retries: ~6.3s, comfortably under the
|
|
13
|
+
// caller-side timeouts but long enough to ride out a typical rate-limit.
|
|
14
|
+
const DEFAULT_RETRY_DELAYS_MS = [200, 600, 1500, 4000];
|
|
15
|
+
let retryDelaysMs = DEFAULT_RETRY_DELAYS_MS;
|
|
16
|
+
function sleep(ms) {
|
|
17
|
+
if (ms <= 0)
|
|
18
|
+
return Promise.resolve();
|
|
19
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
20
|
+
}
|
|
21
|
+
async function withRetries(fn, label) {
|
|
22
|
+
let lastError;
|
|
23
|
+
const delays = retryDelaysMs;
|
|
24
|
+
for (let attempt = 0; attempt <= delays.length; attempt++) {
|
|
25
|
+
try {
|
|
26
|
+
return await fn();
|
|
27
|
+
}
|
|
28
|
+
catch (e) {
|
|
29
|
+
lastError = e;
|
|
30
|
+
if (attempt < delays.length) {
|
|
31
|
+
const delay = delays[attempt];
|
|
32
|
+
log.warn(`${label} attempt ${attempt + 1} failed (${e.message}); retrying in ${delay}ms`);
|
|
33
|
+
await sleep(delay);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
throw lastError;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Test-only: override retry delays to skip real wall-clock waits.
|
|
41
|
+
* Pass [] for no retries, [0,0,0,0] to keep 4-attempt retry semantics with no wait.
|
|
42
|
+
* Production code must never call this.
|
|
43
|
+
*/
|
|
44
|
+
export function _testSetRetryDelays(delays) {
|
|
45
|
+
retryDelaysMs = delays;
|
|
46
|
+
}
|
|
47
|
+
/** Test-only: restore production retry delays. */
|
|
48
|
+
export function _testResetRetryDelays() {
|
|
49
|
+
retryDelaysMs = DEFAULT_RETRY_DELAYS_MS;
|
|
50
|
+
}
|
|
51
|
+
function countHorizontalRules(text) {
|
|
52
|
+
return text.split('\n').filter(line => /^-{3,}\s*$/.test(line.trim())).length;
|
|
53
|
+
}
|
|
54
|
+
function countTables(text) {
|
|
55
|
+
const lines = text.split('\n');
|
|
56
|
+
let count = 0;
|
|
57
|
+
let inTable = false;
|
|
58
|
+
for (const line of lines) {
|
|
59
|
+
const isTableLine = /^\s*\|/.test(line);
|
|
60
|
+
if (isTableLine && !inTable) {
|
|
61
|
+
count++;
|
|
62
|
+
inTable = true;
|
|
63
|
+
}
|
|
64
|
+
else if (!isTableLine) {
|
|
65
|
+
inTable = false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return count;
|
|
69
|
+
}
|
|
70
|
+
function needsSplit(text, maxChunk) {
|
|
71
|
+
return countTables(text) > 1
|
|
72
|
+
|| text.length > maxChunk
|
|
73
|
+
|| countHorizontalRules(text) >= MAX_HORIZONTAL_RULES;
|
|
74
|
+
}
|
|
75
|
+
function chunkText(text, maxChunk) {
|
|
76
|
+
if (text.length <= maxChunk)
|
|
77
|
+
return [text];
|
|
78
|
+
const chunks = [];
|
|
79
|
+
let remaining = text;
|
|
80
|
+
while (remaining.length > maxChunk) {
|
|
81
|
+
let splitAt = remaining.lastIndexOf('\n', maxChunk);
|
|
82
|
+
if (splitAt <= 0)
|
|
83
|
+
splitAt = maxChunk;
|
|
84
|
+
chunks.push(remaining.substring(0, splitAt));
|
|
85
|
+
remaining = remaining.substring(splitAt).replace(/^\n/, '');
|
|
86
|
+
}
|
|
87
|
+
if (remaining)
|
|
88
|
+
chunks.push(remaining);
|
|
89
|
+
return chunks;
|
|
90
|
+
}
|
|
91
|
+
export class VirtualMessage {
|
|
92
|
+
adapter;
|
|
93
|
+
channel;
|
|
94
|
+
threadId;
|
|
95
|
+
onMessagePosted;
|
|
96
|
+
maxChunk;
|
|
97
|
+
durable;
|
|
98
|
+
parentRef = null;
|
|
99
|
+
currentRef = null;
|
|
100
|
+
currentContent = '';
|
|
101
|
+
// Unsealed tail text on the current Slack message. Slack displays
|
|
102
|
+
// `currentContent + SEPARATOR + mutableTail`. Empty string means no tail open.
|
|
103
|
+
// appendMutableTail opens/rotates; editMutableTail replaces; any append() or
|
|
104
|
+
// postStandalone() auto-seals by folding mutableTail into currentContent.
|
|
105
|
+
mutableTail = '';
|
|
106
|
+
allRefs = [];
|
|
107
|
+
queue = Promise.resolve();
|
|
108
|
+
// Last error from a queued operation. flush() throws and clears this so
|
|
109
|
+
// callers can detect that some messages did not reach the platform.
|
|
110
|
+
lastError = null;
|
|
111
|
+
constructor(adapter, channel, opts) {
|
|
112
|
+
this.adapter = adapter;
|
|
113
|
+
this.channel = channel;
|
|
114
|
+
this.threadId = opts?.threadId ?? null;
|
|
115
|
+
this.onMessagePosted = opts?.onMessagePosted ?? null;
|
|
116
|
+
this.durable = opts?.durable ?? null;
|
|
117
|
+
this.maxChunk = adapter.capabilities.maxMessageLength || DEFAULT_MAX_CHUNK;
|
|
118
|
+
}
|
|
119
|
+
append(text) {
|
|
120
|
+
if (!text?.trim())
|
|
121
|
+
return;
|
|
122
|
+
this.queue = this.queue.then(() => this._processAppend(text)).catch(e => {
|
|
123
|
+
// Record the failure so flush() can surface it; swallow here so subsequent
|
|
124
|
+
// appends still get a chance to run instead of a poisoned queue.
|
|
125
|
+
log.error(`Queue error in channel ${this.channel} (text len=${text.length}):`, e.message);
|
|
126
|
+
this.lastError = e instanceof Error ? e : new Error(String(e));
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/** Append `text` as a new mutable tail on the current Slack message.
|
|
130
|
+
* Seals any existing mutable tail into `currentContent` first, then writes
|
|
131
|
+
* the new tail via updateMessage (or postMessage if no message yet).
|
|
132
|
+
* Use this for "start a new tool group" or any ephemeral trailing line. */
|
|
133
|
+
appendMutableTail(text) {
|
|
134
|
+
if (!text?.trim())
|
|
135
|
+
return;
|
|
136
|
+
this.queue = this.queue.then(() => this._processAppendMutableTail(text)).catch(e => {
|
|
137
|
+
log.error(`Queue error in appendMutableTail (channel ${this.channel}, len=${text.length}):`, e.message);
|
|
138
|
+
this.lastError = e instanceof Error ? e : new Error(String(e));
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
/** Replace the current mutable tail with `text`. No-op if no tail is open
|
|
142
|
+
* (use appendMutableTail to open one). Use this for "update same tool group". */
|
|
143
|
+
editMutableTail(text) {
|
|
144
|
+
if (!text?.trim())
|
|
145
|
+
return;
|
|
146
|
+
this.queue = this.queue.then(() => this._processEditMutableTail(text)).catch(e => {
|
|
147
|
+
log.error(`Queue error in editMutableTail (channel ${this.channel}, len=${text.length}):`, e.message);
|
|
148
|
+
this.lastError = e instanceof Error ? e : new Error(String(e));
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
postStandalone(text, opts) {
|
|
152
|
+
const richBlocks = opts?.richBlocks;
|
|
153
|
+
const actions = opts?.actions;
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
this.queue = this.queue.then(async () => {
|
|
156
|
+
this.currentRef = null;
|
|
157
|
+
this.currentContent = '';
|
|
158
|
+
this.mutableTail = '';
|
|
159
|
+
const effectiveThreadId = this.threadId || this.parentRef?.messageId || undefined;
|
|
160
|
+
let walId = null;
|
|
161
|
+
try {
|
|
162
|
+
walId = this.durable
|
|
163
|
+
? await this.durable.beforePost(this.channel, text, { threadId: effectiveThreadId, richBlocks })
|
|
164
|
+
: null;
|
|
165
|
+
const ref = await withRetries(async () => {
|
|
166
|
+
return actions && actions.length > 0
|
|
167
|
+
? await this.adapter.postInteractive(this.channel, {
|
|
168
|
+
text,
|
|
169
|
+
richBlocks,
|
|
170
|
+
actions,
|
|
171
|
+
}, { threadId: effectiveThreadId })
|
|
172
|
+
: await this.adapter.postMessage(this.channel, {
|
|
173
|
+
text,
|
|
174
|
+
richBlocks,
|
|
175
|
+
}, { threadId: effectiveThreadId });
|
|
176
|
+
}, 'postStandalone');
|
|
177
|
+
if (walId && this.durable) {
|
|
178
|
+
await this.durable.afterSent(walId, ref.messageId).catch(e => {
|
|
179
|
+
log.warn(`afterSent failed for walId=${walId}:`, e.message);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
if (!this.parentRef && !this.threadId)
|
|
183
|
+
this.parentRef = ref;
|
|
184
|
+
this.allRefs.push(ref);
|
|
185
|
+
if (this.onMessagePosted)
|
|
186
|
+
this.onMessagePosted(ref);
|
|
187
|
+
resolve(ref);
|
|
188
|
+
}
|
|
189
|
+
catch (e) {
|
|
190
|
+
if (walId && this.durable?.onSendFailed) {
|
|
191
|
+
this.durable.onSendFailed(walId);
|
|
192
|
+
}
|
|
193
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
194
|
+
log.error(`Standalone post failed after retries in channel ${this.channel}:`, err.message);
|
|
195
|
+
this.lastError = err;
|
|
196
|
+
reject(err);
|
|
197
|
+
throw err; // also propagate so flush() sees it
|
|
198
|
+
}
|
|
199
|
+
}).catch(e => {
|
|
200
|
+
// Upstream queue error; surface it to the caller too.
|
|
201
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
202
|
+
this.lastError = err;
|
|
203
|
+
reject(err);
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
async flush() {
|
|
208
|
+
await this.queue.catch(() => { });
|
|
209
|
+
if (this.lastError) {
|
|
210
|
+
const err = this.lastError;
|
|
211
|
+
this.lastError = null;
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
static async postOnce(adapter, channel, text, opts) {
|
|
216
|
+
const vm = new VirtualMessage(adapter, channel, opts);
|
|
217
|
+
vm.append(text);
|
|
218
|
+
await vm.flush();
|
|
219
|
+
return vm.getParentRef();
|
|
220
|
+
}
|
|
221
|
+
getRefs() {
|
|
222
|
+
return [...this.allRefs];
|
|
223
|
+
}
|
|
224
|
+
getParentRef() {
|
|
225
|
+
return this.parentRef;
|
|
226
|
+
}
|
|
227
|
+
/** Compatibility: return parentRef's messageId (maps to Slack's ts). */
|
|
228
|
+
getParentTs() {
|
|
229
|
+
return this.parentRef?.messageId ?? null;
|
|
230
|
+
}
|
|
231
|
+
async _processAppend(text) {
|
|
232
|
+
// Seal any open mutable tail into committed content first — plain append()
|
|
233
|
+
// is a hard break for tools/trace. After this, mutableTail is empty and
|
|
234
|
+
// currentContent includes what Slack already displays as the sealed prefix.
|
|
235
|
+
this._sealMutableTailNow();
|
|
236
|
+
if (this.currentRef === null) {
|
|
237
|
+
await this._postNew(text);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const combined = this.currentContent + SEPARATOR + text;
|
|
241
|
+
if (needsSplit(combined, this.maxChunk)) {
|
|
242
|
+
await this._postNew(text);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
// Only commit currentContent AFTER the update succeeds. If we mutate
|
|
246
|
+
// currentContent before the await and the update fails, the next append
|
|
247
|
+
// that triggers needsSplit would call _postNew(text) with only the new
|
|
248
|
+
// text — silently dropping `text` from anywhere in Slack.
|
|
249
|
+
const updateResult = await this._updateCurrent(combined);
|
|
250
|
+
if (updateResult.delivered) {
|
|
251
|
+
this.currentContent = combined;
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
// Update permanently failed (after retries). Don't lose `text` — fall
|
|
255
|
+
// back to posting it as a new message so it remains visible to the user.
|
|
256
|
+
// If THIS also fails, _postNew throws and the queue catch records lastError.
|
|
257
|
+
log.error(`Update permanently failed in channel ${this.channel}; falling back to new post`);
|
|
258
|
+
await this._postNew(text);
|
|
259
|
+
// After fallback post succeeds, mark the stale update's WAL entry as
|
|
260
|
+
// delivered so the drain loop doesn't retry it against the old message
|
|
261
|
+
// (which would duplicate content already shown in the new message).
|
|
262
|
+
if (updateResult.walId) {
|
|
263
|
+
await this.durable?.afterSent(updateResult.walId).catch(() => { });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/** Combined display = currentContent [+ SEP + mutableTail]. */
|
|
268
|
+
_renderWithTail(tail) {
|
|
269
|
+
if (!this.currentContent)
|
|
270
|
+
return tail;
|
|
271
|
+
if (!tail)
|
|
272
|
+
return this.currentContent;
|
|
273
|
+
return this.currentContent + TAIL_SEPARATOR + tail;
|
|
274
|
+
}
|
|
275
|
+
/** Synchronously move mutableTail into currentContent. Slack state is
|
|
276
|
+
* already up-to-date with the tail displayed; this is pure bookkeeping. */
|
|
277
|
+
_sealMutableTailNow() {
|
|
278
|
+
if (!this.mutableTail)
|
|
279
|
+
return;
|
|
280
|
+
this.currentContent = this.currentContent
|
|
281
|
+
? this.currentContent + TAIL_SEPARATOR + this.mutableTail
|
|
282
|
+
: this.mutableTail;
|
|
283
|
+
this.mutableTail = '';
|
|
284
|
+
}
|
|
285
|
+
async _processAppendMutableTail(text) {
|
|
286
|
+
// Seal any existing tail first, then open a fresh one containing `text`.
|
|
287
|
+
this._sealMutableTailNow();
|
|
288
|
+
const combined = this._renderWithTail(text);
|
|
289
|
+
if (this.currentRef === null) {
|
|
290
|
+
await this._postNew(combined);
|
|
291
|
+
// _postNew leaves currentContent = combined (the whole blob). We want
|
|
292
|
+
// committed='' tail=text since the whole freshly-posted blob is, in
|
|
293
|
+
// fact, just the tail (currentContent was empty).
|
|
294
|
+
this.currentContent = '';
|
|
295
|
+
this.mutableTail = text;
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (needsSplit(combined, this.maxChunk)) {
|
|
299
|
+
// Too long — commit everything that was already on screen, start a fresh
|
|
300
|
+
// message whose content is just the new tail.
|
|
301
|
+
await this._postNew(text);
|
|
302
|
+
this.currentContent = '';
|
|
303
|
+
this.mutableTail = text;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const updateResult = await this._updateCurrent(combined);
|
|
307
|
+
if (updateResult.delivered) {
|
|
308
|
+
this.mutableTail = text;
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
log.error(`Update failed in appendMutableTail (channel ${this.channel}); falling back to new post`);
|
|
312
|
+
await this._postNew(text);
|
|
313
|
+
this.currentContent = '';
|
|
314
|
+
this.mutableTail = text;
|
|
315
|
+
if (updateResult.walId) {
|
|
316
|
+
await this.durable?.afterSent(updateResult.walId).catch(() => { });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async _processEditMutableTail(text) {
|
|
321
|
+
if (!this.mutableTail)
|
|
322
|
+
return; // nothing to edit; caller must appendMutableTail first
|
|
323
|
+
const combined = this._renderWithTail(text);
|
|
324
|
+
if (this.currentRef === null) {
|
|
325
|
+
// Shouldn't happen if a tail is open (tail implies a message exists),
|
|
326
|
+
// but handle defensively: fall back to opening a fresh one.
|
|
327
|
+
await this._postNew(combined);
|
|
328
|
+
this.currentContent = '';
|
|
329
|
+
this.mutableTail = text;
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (needsSplit(combined, this.maxChunk)) {
|
|
333
|
+
// Overflow during same-group update — commit the old tail into content,
|
|
334
|
+
// then open a fresh message carrying the new (larger) tail text.
|
|
335
|
+
this._sealMutableTailNow();
|
|
336
|
+
await this._postNew(text);
|
|
337
|
+
this.currentContent = '';
|
|
338
|
+
this.mutableTail = text;
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
const updateResult = await this._updateCurrent(combined);
|
|
342
|
+
if (updateResult.delivered) {
|
|
343
|
+
this.mutableTail = text;
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
log.error(`Update failed in editMutableTail (channel ${this.channel}); falling back to new post`);
|
|
347
|
+
this._sealMutableTailNow();
|
|
348
|
+
await this._postNew(text);
|
|
349
|
+
this.currentContent = '';
|
|
350
|
+
this.mutableTail = text;
|
|
351
|
+
if (updateResult.walId) {
|
|
352
|
+
await this.durable?.afterSent(updateResult.walId).catch(() => { });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
async _postNew(text) {
|
|
357
|
+
const chunks = chunkText(text, this.maxChunk);
|
|
358
|
+
let lastChunkSentIndex = -1;
|
|
359
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
360
|
+
const chunk = chunks[i];
|
|
361
|
+
// After chunk[0] succeeds, parentRef is set, so subsequent chunks go to
|
|
362
|
+
// the thread automatically. If chunk[0] fails permanently, we abort the
|
|
363
|
+
// remaining chunks — they would otherwise be posted as orphan top-level
|
|
364
|
+
// messages without context.
|
|
365
|
+
let effectiveThreadId;
|
|
366
|
+
if (this.threadId) {
|
|
367
|
+
effectiveThreadId = this.threadId;
|
|
368
|
+
}
|
|
369
|
+
else if (this.parentRef === null && i === 0) {
|
|
370
|
+
effectiveThreadId = undefined;
|
|
371
|
+
}
|
|
372
|
+
else if (this.parentRef === null) {
|
|
373
|
+
// chunk[0] failed and we have no parent — don't orphan subsequent chunks.
|
|
374
|
+
throw new Error(`[virtual-message] aborting chunk ${i} — chunk 0 failed to post and would orphan subsequent chunks`);
|
|
375
|
+
}
|
|
376
|
+
else {
|
|
377
|
+
effectiveThreadId = this.parentRef.messageId;
|
|
378
|
+
}
|
|
379
|
+
const ref = await this._postOne(chunk, effectiveThreadId);
|
|
380
|
+
if (this.parentRef === null && !this.threadId) {
|
|
381
|
+
this.parentRef = ref;
|
|
382
|
+
}
|
|
383
|
+
this.allRefs.push(ref);
|
|
384
|
+
if (this.onMessagePosted)
|
|
385
|
+
this.onMessagePosted(ref);
|
|
386
|
+
lastChunkSentIndex = i;
|
|
387
|
+
}
|
|
388
|
+
if (lastChunkSentIndex >= 0) {
|
|
389
|
+
this.currentRef = this.allRefs[this.allRefs.length - 1];
|
|
390
|
+
this.currentContent = chunks[lastChunkSentIndex];
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Post a single chunk with rich-text + plain-text fallback wrapped in
|
|
395
|
+
* exponential-backoff retries. Throws on permanent failure (after retries).
|
|
396
|
+
* When durable hooks are configured, persists intent to WAL before sending.
|
|
397
|
+
*/
|
|
398
|
+
async _postOne(chunk, threadId) {
|
|
399
|
+
const richBlocks = [{ type: 'markdown', text: chunk }];
|
|
400
|
+
const richContent = { text: chunk, richBlocks };
|
|
401
|
+
const walId = this.durable
|
|
402
|
+
? await this.durable.beforePost(this.channel, chunk, { threadId, richBlocks })
|
|
403
|
+
: null;
|
|
404
|
+
try {
|
|
405
|
+
const ref = await withRetries(async () => {
|
|
406
|
+
try {
|
|
407
|
+
return await this.adapter.postMessage(this.channel, richContent, { threadId });
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return await this.adapter.postMessage(this.channel, { text: chunk }, { threadId });
|
|
411
|
+
}
|
|
412
|
+
}, `postMessage(channel=${this.channel}, len=${chunk.length})`);
|
|
413
|
+
if (walId && this.durable) {
|
|
414
|
+
await this.durable.afterSent(walId, ref.messageId).catch(e => {
|
|
415
|
+
log.warn(`afterSent failed for walId=${walId}:`, e.message);
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
return ref;
|
|
419
|
+
}
|
|
420
|
+
catch (e) {
|
|
421
|
+
// Inline send failed permanently — release the WAL claim so the drain
|
|
422
|
+
// loop can retry delivery later.
|
|
423
|
+
if (walId && this.durable?.onSendFailed) {
|
|
424
|
+
this.durable.onSendFailed(walId);
|
|
425
|
+
}
|
|
426
|
+
throw e;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
async _updateCurrent(content) {
|
|
430
|
+
if (!this.currentRef)
|
|
431
|
+
return { delivered: true };
|
|
432
|
+
const ref = this.currentRef;
|
|
433
|
+
const richBlocks = [{ type: 'markdown', text: content }];
|
|
434
|
+
const richContent = { text: content, richBlocks };
|
|
435
|
+
const walId = this.durable
|
|
436
|
+
? await this.durable.beforeUpdate(this.channel, ref.messageId, content, { richBlocks })
|
|
437
|
+
: null;
|
|
438
|
+
try {
|
|
439
|
+
await withRetries(async () => {
|
|
440
|
+
try {
|
|
441
|
+
await this.adapter.updateMessage(ref, richContent);
|
|
442
|
+
}
|
|
443
|
+
catch {
|
|
444
|
+
await this.adapter.updateMessage(ref, { text: content });
|
|
445
|
+
}
|
|
446
|
+
}, `updateMessage(channel=${this.channel}, len=${content.length})`);
|
|
447
|
+
if (walId && this.durable) {
|
|
448
|
+
await this.durable.afterSent(walId).catch(e => {
|
|
449
|
+
log.warn(`afterSent failed for walId=${walId}:`, e.message);
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return { delivered: true };
|
|
453
|
+
}
|
|
454
|
+
catch (e) {
|
|
455
|
+
// Don't release the WAL claim yet — let the caller decide whether to
|
|
456
|
+
// mark as delivered (after fallback _postNew succeeds) or release
|
|
457
|
+
// (after fallback _postNew also fails, so drain loop can retry).
|
|
458
|
+
// When no durable hooks are configured, return delivered:false without
|
|
459
|
+
// a walId — the caller still needs to fall back to _postNew but
|
|
460
|
+
// doesn't need to clean up any WAL entry.
|
|
461
|
+
return { delivered: false, ...(walId ? { walId } : {}) };
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Write `data` to `filePath` atomically via a sibling tmp file + fs.rename.
|
|
3
|
+
* The original file is never in a partially-written state: either the rename
|
|
4
|
+
* succeeds (new content visible) or it does not (original intact, tmp left on disk).
|
|
5
|
+
*/
|
|
6
|
+
export declare function atomicWrite(filePath: string, data: string): Promise<void>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// input: filePath, data string
|
|
2
|
+
// output: atomic file write (tmp → rename)
|
|
3
|
+
// pos: write primitive used by JsonRepository; guarantees original is never partially overwritten
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import fs from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
/**
|
|
8
|
+
* Write `data` to `filePath` atomically via a sibling tmp file + fs.rename.
|
|
9
|
+
* The original file is never in a partially-written state: either the rename
|
|
10
|
+
* succeeds (new content visible) or it does not (original intact, tmp left on disk).
|
|
11
|
+
*/
|
|
12
|
+
export async function atomicWrite(filePath, data) {
|
|
13
|
+
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
14
|
+
const rnd = Math.random().toString(36).slice(2, 8);
|
|
15
|
+
const tmp = `${filePath}.tmp.${process.pid}.${Date.now()}.${rnd}`;
|
|
16
|
+
await fs.writeFile(tmp, data, 'utf8');
|
|
17
|
+
await fs.rename(tmp, filePath);
|
|
18
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export declare const CHANNEL_REGISTRY_FILE: string;
|
|
2
|
+
/** Shape of channel-registry.json: `{"projectName": "channelId", ...}` */
|
|
3
|
+
export type ChannelRegistryData = Record<string, string>;
|
|
4
|
+
interface ChannelRepoOptions {
|
|
5
|
+
filePath?: string;
|
|
6
|
+
projectsDir?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare class ChannelRepo {
|
|
9
|
+
private readonly _repo;
|
|
10
|
+
private readonly _projectsDir;
|
|
11
|
+
constructor(opts?: ChannelRepoOptions);
|
|
12
|
+
getProjectChannel(project: string): Promise<string | null>;
|
|
13
|
+
setProjectChannel(project: string, channelId: string): Promise<void>;
|
|
14
|
+
removeProjectChannel(project: string): Promise<void>;
|
|
15
|
+
getAllRegistrations(): Promise<Record<string, string>>;
|
|
16
|
+
listProjects(): Promise<string[]>;
|
|
17
|
+
/** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
|
|
18
|
+
flush(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare const channelRepo: ChannelRepo;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// input: channel-registry.json + context/projects/ directory
|
|
2
|
+
// output: ChannelRepo (async getProjectChannel / setProjectChannel / removeProjectChannel / getAllRegistrations / listProjects)
|
|
3
|
+
// pos: Project-Channel mapping persistence layer. Based on JsonRepository abstraction, AsyncMutex serializes reads/writes of channel-registry.json.
|
|
4
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import * as fsSync from 'fs';
|
|
6
|
+
import * as path from 'path';
|
|
7
|
+
import { JsonRepository } from './json-repository.js';
|
|
8
|
+
import { STORE_DIR, PROJECTS_DIR } from '../core/paths.js';
|
|
9
|
+
export const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
|
|
10
|
+
export class ChannelRepo {
|
|
11
|
+
_repo;
|
|
12
|
+
_projectsDir;
|
|
13
|
+
constructor(opts = {}) {
|
|
14
|
+
this._repo = new JsonRepository({
|
|
15
|
+
filePath: opts.filePath ?? CHANNEL_REGISTRY_FILE,
|
|
16
|
+
defaultValue: () => ({}),
|
|
17
|
+
migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
|
|
18
|
+
});
|
|
19
|
+
this._projectsDir = opts.projectsDir ?? PROJECTS_DIR;
|
|
20
|
+
}
|
|
21
|
+
async getProjectChannel(project) {
|
|
22
|
+
const data = await this._repo.read();
|
|
23
|
+
return data[project] ?? null;
|
|
24
|
+
}
|
|
25
|
+
async setProjectChannel(project, channelId) {
|
|
26
|
+
await this._repo.mutate((data) => {
|
|
27
|
+
data[project] = channelId;
|
|
28
|
+
return { next: data, result: undefined };
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async removeProjectChannel(project) {
|
|
32
|
+
await this._repo.mutate((data) => {
|
|
33
|
+
delete data[project];
|
|
34
|
+
return { next: data, result: undefined };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async getAllRegistrations() {
|
|
38
|
+
return { ...(await this._repo.read()) };
|
|
39
|
+
}
|
|
40
|
+
async listProjects() {
|
|
41
|
+
try {
|
|
42
|
+
return fsSync.readdirSync(this._projectsDir).filter((name) => {
|
|
43
|
+
return fsSync.statSync(path.join(this._projectsDir, name)).isDirectory() && !name.startsWith('.');
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
|
|
51
|
+
flush() {
|
|
52
|
+
return this._repo.flush();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export const channelRepo = new ChannelRepo();
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
export type TurnStatus = 'processing' | 'completed' | 'superseded';
|
|
2
|
+
export interface LedgerTurn {
|
|
3
|
+
turnIndex: number;
|
|
4
|
+
userMessageTs: string;
|
|
5
|
+
userMessageText: string;
|
|
6
|
+
statusMessageTs: string | null;
|
|
7
|
+
responseMessageTimestamps: string[];
|
|
8
|
+
executionId: string | null;
|
|
9
|
+
backupPath: string | null;
|
|
10
|
+
status: TurnStatus;
|
|
11
|
+
createdAt: string;
|
|
12
|
+
updatedAt: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ChannelConversation {
|
|
15
|
+
sessionId: string | null;
|
|
16
|
+
sessionName: string | null;
|
|
17
|
+
backend: string;
|
|
18
|
+
/** Profile name used when the conversation was created or switched — needed
|
|
19
|
+
* by !new / pre-close hooks to resume the session with the same profile. */
|
|
20
|
+
profileName: string | null;
|
|
21
|
+
turns: LedgerTurn[];
|
|
22
|
+
updatedAt: string;
|
|
23
|
+
}
|
|
24
|
+
export type LedgerData = Record<string, ChannelConversation>;
|
|
25
|
+
export declare class ConversationLedgerRepo {
|
|
26
|
+
private repo;
|
|
27
|
+
getConversation(channel: string): Promise<ChannelConversation | null>;
|
|
28
|
+
findTurn(channel: string, userMessageTs: string): Promise<{
|
|
29
|
+
conversation: ChannelConversation;
|
|
30
|
+
turn: LedgerTurn;
|
|
31
|
+
turnIndex: number;
|
|
32
|
+
} | null>;
|
|
33
|
+
initConversation(channel: string, opts: {
|
|
34
|
+
sessionId: string | null;
|
|
35
|
+
sessionName: string | null;
|
|
36
|
+
backend: string;
|
|
37
|
+
profileName?: string | null;
|
|
38
|
+
}): Promise<ChannelConversation>;
|
|
39
|
+
updateSessionId(channel: string, sessionId: string): Promise<void>;
|
|
40
|
+
beginTurn(channel: string, opts: {
|
|
41
|
+
userMessageTs: string;
|
|
42
|
+
userMessageText: string;
|
|
43
|
+
statusMessageTs?: string | null;
|
|
44
|
+
backupPath?: string | null;
|
|
45
|
+
}): Promise<LedgerTurn>;
|
|
46
|
+
addResponseTs(channel: string, userMessageTs: string, responseTs: string): Promise<void>;
|
|
47
|
+
completeTurn(channel: string, userMessageTs: string, opts?: {
|
|
48
|
+
executionId?: string | null;
|
|
49
|
+
}): Promise<void>;
|
|
50
|
+
rollbackTo(channel: string, turnIndex: number): Promise<{
|
|
51
|
+
supersededTurns: LedgerTurn[];
|
|
52
|
+
conversation: ChannelConversation;
|
|
53
|
+
} | null>;
|
|
54
|
+
truncateTurns(channel: string, fromIndex: number): Promise<void>;
|
|
55
|
+
clearConversation(channel: string): Promise<void>;
|
|
56
|
+
switchSession(channel: string, opts: {
|
|
57
|
+
sessionId: string;
|
|
58
|
+
sessionName: string | null;
|
|
59
|
+
backend: string;
|
|
60
|
+
profileName?: string | null;
|
|
61
|
+
}): Promise<void>;
|
|
62
|
+
/**
|
|
63
|
+
* Atomic init-if-missing + beginTurn. Captures the turn index under mutex
|
|
64
|
+
* so callers can safely pass it to sessionBackup.createBackup.
|
|
65
|
+
* Returns { turn, turnIndex } for the caller.
|
|
66
|
+
*/
|
|
67
|
+
initAndBeginTurn(channel: string, opts: {
|
|
68
|
+
sessionId: string | null;
|
|
69
|
+
sessionName: string | null;
|
|
70
|
+
backend: string;
|
|
71
|
+
profileName?: string | null;
|
|
72
|
+
userMessageTs: string;
|
|
73
|
+
userMessageText: string;
|
|
74
|
+
statusMessageTs: string;
|
|
75
|
+
}): Promise<{
|
|
76
|
+
turn: LedgerTurn;
|
|
77
|
+
turnIndex: number;
|
|
78
|
+
}>;
|
|
79
|
+
/** Set the backup path on the turn identified by userMessageTs. */
|
|
80
|
+
setBackupPath(channel: string, userMessageTs: string, backupPath: string | null): Promise<void>;
|
|
81
|
+
/** Drop the in-memory cache so the next read() fetches from disk. For testing. */
|
|
82
|
+
invalidate(): void;
|
|
83
|
+
/** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
|
|
84
|
+
flush(): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
export declare const conversationLedger: ConversationLedgerRepo;
|