@cortex-agent/server 2026.5.25-1 → 2026.6.11
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/config/thread-templates.json +28 -1
- package/defaults/hooks/cortex-md-injector.mjs +47 -31
- package/defaults/hooks/post-task-hook.mjs +6 -0
- package/defaults/hooks/task-status-check.mjs +8 -0
- package/defaults/mcp-config-slack.json +11 -0
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +18 -0
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +5 -6
- package/defaults/prompts/directives/manager.md +67 -0
- package/dist/agent-adapter/claude/adapter-tui.d.ts +35 -3
- package/dist/agent-adapter/claude/adapter-tui.js +91 -12
- package/dist/agent-adapter/claude/adapter.js +11 -0
- package/dist/agent-adapter/claude/defaults.d.ts +30 -0
- package/dist/agent-adapter/claude/defaults.js +30 -0
- package/dist/agent-adapter/claude/jsonl-tail.d.ts +2 -2
- package/dist/agent-adapter/claude/jsonl-tail.js +25 -20
- package/dist/agent-adapter/claude/spawn-args.d.ts +11 -0
- package/dist/agent-adapter/claude/spawn-args.js +49 -7
- package/dist/agent-adapter/claude/tmux-control.d.ts +20 -0
- package/dist/agent-adapter/claude/tmux-control.js +54 -8
- package/dist/agent-adapter/codex/adapter.js +1 -1
- package/dist/agent-adapter/normalize/event-types.d.ts +1 -0
- package/dist/agent-adapter/pi/adapter.js +46 -19
- package/dist/agent-adapter/pi/agent-dir.d.ts +21 -0
- package/dist/agent-adapter/pi/agent-dir.js +53 -2
- package/dist/agent-adapter/pi/event-parser.js +13 -1
- package/dist/agent-adapter/pi/mcp-bridge.d.ts +12 -0
- package/dist/agent-adapter/pi/mcp-bridge.js +47 -9
- package/dist/agent-adapter/pi/tool-shims.d.ts +14 -0
- package/dist/agent-adapter/pi/tool-shims.js +167 -140
- package/dist/agent-adapter/types.d.ts +7 -2
- package/dist/core/atomic-write.js +21 -0
- package/dist/core/config-generator.d.ts +10 -0
- package/dist/core/config-generator.js +28 -0
- package/dist/core/gateway-generator.d.ts +77 -7
- package/dist/core/gateway-generator.js +301 -29
- package/dist/core/icons.d.ts +68 -0
- package/dist/core/icons.js +67 -0
- package/dist/core/profile-generator.d.ts +6 -0
- package/dist/core/profile-generator.js +35 -7
- package/dist/core/running-executions.d.ts +51 -41
- package/dist/core/running-executions.js +120 -73
- package/dist/core/status-format.js +3 -2
- package/dist/core/task-parser.d.ts +3 -0
- package/dist/core/task-parser.js +3 -1
- package/dist/core/types/thread-types.d.ts +54 -8
- package/dist/domain/agents/facade.d.ts +18 -0
- package/dist/domain/agents/facade.js +26 -3
- package/dist/domain/agents/profile-manager.d.ts +11 -0
- package/dist/domain/agents/profile-manager.js +21 -2
- package/dist/domain/costs/codex-usage-monitor.js +2 -1
- package/dist/domain/costs/rate-limit-throttle.js +14 -2
- package/dist/domain/executions/registry.d.ts +24 -0
- package/dist/domain/executions/registry.js +38 -0
- package/dist/domain/mcp/core-server.js +15 -3
- package/dist/domain/mcp/feishu/bitable.d.ts +3 -0
- package/dist/domain/mcp/feishu/bitable.js +168 -0
- package/dist/domain/mcp/feishu/block-types.d.ts +44 -0
- package/dist/domain/mcp/feishu/block-types.js +127 -0
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +19 -0
- package/dist/domain/mcp/feishu/blocks-to-text.js +43 -0
- package/dist/domain/mcp/feishu/client.d.ts +46 -0
- package/dist/domain/mcp/feishu/client.js +87 -0
- package/dist/domain/mcp/feishu/docx.d.ts +3 -0
- package/dist/domain/mcp/feishu/docx.js +163 -0
- package/dist/domain/mcp/feishu/drive.d.ts +23 -0
- package/dist/domain/mcp/feishu/drive.js +66 -0
- package/dist/domain/mcp/feishu/file.d.ts +14 -0
- package/dist/domain/mcp/feishu/file.js +107 -0
- package/dist/domain/mcp/feishu/index.d.ts +6 -0
- package/dist/domain/mcp/feishu/index.js +61 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +40 -0
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +191 -0
- package/dist/domain/mcp/feishu/sheets.d.ts +3 -0
- package/dist/domain/mcp/feishu/sheets.js +119 -0
- package/dist/domain/mcp/feishu/types.d.ts +26 -0
- package/dist/domain/mcp/feishu/types.js +38 -0
- package/dist/domain/mcp/feishu/user-auth.d.ts +140 -0
- package/dist/domain/mcp/feishu/user-auth.js +286 -0
- package/dist/domain/mcp/feishu/wiki.d.ts +3 -0
- package/dist/domain/mcp/feishu/wiki.js +77 -0
- package/dist/domain/mcp/feishu-server.d.ts +2 -0
- package/dist/domain/mcp/feishu-server.js +33 -0
- package/dist/domain/mcp/server.d.ts +0 -1
- package/dist/domain/mcp/server.js +6 -25
- package/dist/domain/mcp/slack-server.d.ts +3 -0
- package/dist/domain/mcp/slack-server.js +46 -0
- package/dist/domain/mcp/tools/context.js +1 -1
- package/dist/domain/mcp/tools/schedule.d.ts +1 -1
- package/dist/domain/mcp/tools/schedule.js +6 -20
- package/dist/domain/mcp/tools/slack.js +20 -7
- package/dist/domain/mcp/tools/thread-ops.d.ts +2 -0
- package/dist/domain/mcp/tools/thread-ops.js +121 -0
- package/dist/domain/mcp/tools/time.d.ts +2 -0
- package/dist/domain/mcp/tools/time.js +66 -0
- package/dist/domain/mcp/tools/tui-ask.js +1 -1
- package/dist/domain/mcp/tools/tui-plan.js +2 -2
- package/dist/domain/mcp/tui-server.js +1 -0
- package/dist/domain/monitor/disk-monitor.js +2 -1
- package/dist/domain/monitor/gpu-monitor.js +2 -1
- package/dist/domain/remote/client-hot-reload.js +3 -2
- package/dist/domain/remote/client-manager.js +8 -6
- package/dist/domain/scheduling/job-registry.d.ts +4 -0
- package/dist/domain/scheduling/job-registry.js +1 -0
- package/dist/domain/scheduling/jobs/_shared.js +2 -1
- package/dist/domain/scheduling/jobs/memory-index-regen.js +3 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +9 -23
- package/dist/domain/scheduling/jobs/sync-public.js +4 -3
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +1 -8
- package/dist/domain/scheduling/jobs/target-dispatch.js +0 -7
- package/dist/domain/scheduling/jobs/task-archive.js +3 -2
- package/dist/domain/scheduling/jobs/task-dispatch.js +120 -10
- package/dist/domain/scheduling/schedule-command.js +16 -15
- package/dist/domain/scheduling/scheduler.d.ts +1 -1
- package/dist/domain/scheduling/scheduler.js +2 -1
- package/dist/domain/sessions/session-hooks.d.ts +2 -2
- package/dist/domain/sessions/session-hooks.js +19 -18
- package/dist/domain/sessions/session-lifecycle.d.ts +38 -0
- package/dist/domain/sessions/session-lifecycle.js +44 -0
- package/dist/domain/system/install-cli.d.ts +7 -0
- package/dist/domain/system/install-cli.js +106 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +58 -1
- package/dist/domain/tasks/dispatch-utils.js +53 -4
- package/dist/domain/tasks/dispatcher.js +26 -0
- package/dist/domain/tasks/lint.js +28 -0
- package/dist/domain/tasks/mutator.d.ts +16 -3
- package/dist/domain/tasks/mutator.js +41 -12
- package/dist/domain/tasks/pending-tracker.js +6 -5
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +37 -6
- package/dist/domain/tasks/system/task-lifecycle-edit.js +6 -1
- package/dist/domain/tasks/system/task-mutations.d.ts +41 -3
- package/dist/domain/tasks/system/task-mutations.js +166 -8
- package/dist/domain/threads/contract.d.ts +17 -0
- package/dist/domain/threads/contract.js +59 -0
- package/dist/domain/threads/hook-runner.js +7 -6
- package/dist/domain/threads/index.d.ts +2 -0
- package/dist/domain/threads/index.js +3 -1
- package/dist/domain/threads/prompt-builder.d.ts +15 -1
- package/dist/domain/threads/prompt-builder.js +41 -2
- package/dist/domain/threads/runner.d.ts +6 -5
- package/dist/domain/threads/runner.js +128 -79
- package/dist/domain/threads/state-machine.d.ts +23 -21
- package/dist/domain/threads/state-machine.js +113 -54
- package/dist/domain/threads/template-loader.js +3 -2
- package/dist/domain/threads/tree.d.ts +45 -0
- package/dist/domain/threads/tree.js +171 -0
- package/dist/domain/tui-session/index.d.ts +2 -0
- package/dist/domain/tui-session/index.js +3 -0
- package/dist/domain/tui-session/tui-session-service.d.ts +2 -0
- package/dist/domain/tui-session/tui-session-service.js +103 -0
- package/dist/domain/tui-session/types.d.ts +67 -0
- package/dist/domain/tui-session/types.js +4 -0
- package/dist/domain/ui-service/index.d.ts +5 -0
- package/dist/domain/ui-service/index.js +3 -0
- package/dist/domain/ui-service/mutate/executions.d.ts +4 -0
- package/dist/domain/ui-service/mutate/executions.js +15 -0
- package/dist/domain/ui-service/mutate/schedules.d.ts +10 -0
- package/dist/domain/ui-service/mutate/schedules.js +39 -0
- package/dist/domain/ui-service/mutate/tasks.d.ts +23 -0
- package/dist/domain/ui-service/mutate/tasks.js +59 -0
- package/dist/domain/ui-service/mutate/threads.d.ts +4 -0
- package/dist/domain/ui-service/mutate/threads.js +21 -0
- package/dist/domain/ui-service/query/cost.d.ts +3 -0
- package/dist/domain/ui-service/query/cost.js +6 -0
- package/dist/domain/ui-service/query/executions.d.ts +2 -0
- package/dist/domain/ui-service/query/executions.js +35 -0
- package/dist/domain/ui-service/query/projects.d.ts +2 -0
- package/dist/domain/ui-service/query/projects.js +30 -0
- package/dist/domain/ui-service/query/schedules.d.ts +2 -0
- package/dist/domain/ui-service/query/schedules.js +23 -0
- package/dist/domain/ui-service/query/sessions.d.ts +2 -0
- package/dist/domain/ui-service/query/sessions.js +35 -0
- package/dist/domain/ui-service/query/tasks.d.ts +2 -0
- package/dist/domain/ui-service/query/tasks.js +30 -0
- package/dist/domain/ui-service/query/threads.d.ts +2 -0
- package/dist/domain/ui-service/query/threads.js +27 -0
- package/dist/domain/ui-service/subscribe.d.ts +5 -0
- package/dist/domain/ui-service/subscribe.js +118 -0
- package/dist/domain/ui-service/types.d.ts +237 -0
- package/dist/domain/ui-service/types.js +5 -0
- package/dist/domain/ui-service/ui-service.d.ts +2 -0
- package/dist/domain/ui-service/ui-service.js +83 -0
- package/dist/entry/app.js +94 -5
- package/dist/entry/cli.d.ts +12 -0
- package/dist/entry/cli.js +122 -12
- package/dist/entry/feishu-login.d.ts +28 -0
- package/dist/entry/feishu-login.js +218 -0
- package/dist/entry/init.d.ts +25 -2
- package/dist/entry/init.js +211 -64
- package/dist/events/event-types.d.ts +14 -0
- package/dist/hooks/cortex-md-injector.mjs +47 -31
- package/dist/hooks/post-task-hook.mjs +6 -0
- package/dist/hooks/task-status-check.mjs +8 -0
- package/dist/orchestration/agent-runner.d.ts +2 -1
- package/dist/orchestration/agent-runner.js +55 -55
- package/dist/orchestration/conduit-queue.d.ts +18 -0
- package/dist/orchestration/conduit-queue.js +32 -0
- package/dist/orchestration/conversation-runner.d.ts +48 -0
- package/dist/orchestration/conversation-runner.js +109 -0
- package/dist/orchestration/dispatch-reconciler.js +8 -1
- package/dist/orchestration/interactions/ask-user-question.d.ts +1 -1
- package/dist/orchestration/interactions/ask-user-question.js +3 -3
- package/dist/orchestration/interactions/interaction-handlers.js +48 -17
- package/dist/orchestration/interactions/plan-handler.d.ts +2 -2
- package/dist/orchestration/interactions/plan-handler.js +4 -3
- package/dist/orchestration/interactions/update-prompt.d.ts +6 -0
- package/dist/orchestration/interactions/update-prompt.js +100 -0
- package/dist/orchestration/lifecycle.d.ts +4 -4
- package/dist/orchestration/lifecycle.js +24 -22
- package/dist/orchestration/orchestrator.d.ts +1 -1
- package/dist/orchestration/routing/commands/cancel.js +39 -47
- package/dist/orchestration/routing/commands/channel.js +24 -11
- package/dist/orchestration/routing/commands/cost.js +2 -1
- package/dist/orchestration/routing/commands/device.js +3 -2
- package/dist/orchestration/routing/commands/dispatch.js +6 -5
- package/dist/orchestration/routing/commands/index.d.ts +1 -1
- package/dist/orchestration/routing/commands/index.js +11 -10
- package/dist/orchestration/routing/commands/mode.js +19 -18
- package/dist/orchestration/routing/commands/nvtop.js +10 -9
- package/dist/orchestration/routing/commands/sendfile.js +7 -6
- package/dist/orchestration/routing/commands/session.d.ts +1 -1
- package/dist/orchestration/routing/commands/session.js +17 -33
- package/dist/orchestration/routing/commands/tail.js +4 -3
- package/dist/orchestration/routing/commands/task.js +4 -3
- package/dist/orchestration/routing/commands/thread-handlers.js +16 -6
- package/dist/orchestration/routing/edit-handler.js +8 -7
- package/dist/orchestration/routing/hook-bridge-subscribers.js +17 -1
- package/dist/orchestration/routing/message-router.d.ts +1 -1
- package/dist/orchestration/routing/message-router.js +9 -9
- package/dist/orchestration/routing/webhook.js +233 -2
- package/dist/orchestration/status-helpers.d.ts +5 -1
- package/dist/orchestration/status-helpers.js +7 -6
- package/dist/orchestration/thread-callback.d.ts +67 -0
- package/dist/orchestration/thread-callback.js +465 -0
- package/dist/orchestration/thread-executor.d.ts +22 -1
- package/dist/orchestration/thread-executor.js +85 -36
- package/dist/platform/adapter.d.ts +6 -2
- package/dist/platform/adapters/composite-adapter.d.ts +89 -0
- package/dist/platform/adapters/composite-adapter.js +318 -0
- package/dist/platform/adapters/feishu-output-stream.d.ts +26 -4
- package/dist/platform/adapters/feishu-output-stream.js +274 -36
- package/dist/platform/adapters/feishu.d.ts +50 -5
- package/dist/platform/adapters/feishu.js +370 -116
- package/dist/platform/adapters/index.d.ts +24 -3
- package/dist/platform/adapters/index.js +89 -11
- package/dist/platform/adapters/project-conduits.d.ts +9 -0
- package/dist/platform/adapters/project-conduits.js +42 -0
- package/dist/platform/adapters/slack-project-conduits.d.ts +1 -9
- package/dist/platform/adapters/slack-project-conduits.js +6 -40
- package/dist/platform/adapters/slack.d.ts +9 -2
- package/dist/platform/adapters/slack.js +83 -39
- package/dist/platform/adapters/tui/index.d.ts +9 -0
- package/dist/platform/adapters/tui/index.js +10 -0
- package/dist/platform/adapters/tui/ports.d.ts +20 -0
- package/dist/platform/adapters/tui/ports.js +4 -0
- package/dist/platform/adapters/tui/tui-conduit-state.d.ts +10 -0
- package/dist/platform/adapters/tui/tui-conduit-state.js +17 -0
- package/dist/platform/adapters/tui/tui-connection.d.ts +30 -0
- package/dist/platform/adapters/tui/tui-connection.js +53 -0
- package/dist/platform/adapters/tui/tui-gateway.d.ts +120 -0
- package/dist/platform/adapters/tui/tui-gateway.js +919 -0
- package/dist/platform/adapters/tui/tui-notifications.d.ts +12 -0
- package/dist/platform/adapters/tui/tui-notifications.js +60 -0
- package/dist/platform/adapters/tui/tui-output-stream.d.ts +36 -0
- package/dist/platform/adapters/tui/tui-output-stream.js +99 -0
- package/dist/platform/adapters/tui/tui-transcript.d.ts +8 -0
- package/dist/platform/adapters/tui/tui-transcript.js +56 -0
- package/dist/platform/index.d.ts +1 -0
- package/dist/platform/index.js +2 -1
- package/dist/platform/interactive-builder.js +3 -2
- package/dist/platform/output-stream.d.ts +5 -0
- package/dist/platform/testing.d.ts +7 -11
- package/dist/platform/testing.js +18 -15
- package/dist/platform/tool-trace.js +15 -5
- package/dist/platform/tui/protocol.d.ts +355 -0
- package/dist/platform/tui/protocol.js +199 -0
- package/dist/platform/types.d.ts +12 -3
- package/dist/store/execution-repo.d.ts +6 -1
- package/dist/store/execution-repo.js +13 -3
- package/dist/store/hook-sync.d.ts +18 -0
- package/dist/store/hook-sync.js +92 -0
- package/dist/store/outbound-queue.js +2 -2
- package/dist/store/profile-repo.js +3 -2
- package/dist/store/schedule-repo.d.ts +1 -8
- package/dist/store/session-registry-repo.d.ts +9 -1
- package/dist/store/session-registry-repo.js +19 -3
- package/dist/store/session-repo.d.ts +14 -0
- package/dist/store/session-repo.js +23 -0
- package/dist/store/thread-repo.d.ts +3 -0
- package/dist/store/thread-repo.js +49 -2
- package/dist/store/version-migrations.js +95 -0
- package/dist/tui/App.d.ts +27 -0
- package/dist/tui/App.js +219 -0
- package/dist/tui/components/AskUserModal.d.ts +11 -0
- package/dist/tui/components/AskUserModal.js +364 -0
- package/dist/tui/components/ConfirmModal.d.ts +12 -0
- package/dist/tui/components/ConfirmModal.js +31 -0
- package/dist/tui/components/Dashboard.d.ts +23 -0
- package/dist/tui/components/Dashboard.js +80 -0
- package/dist/tui/components/DashboardCostTab.d.ts +7 -0
- package/dist/tui/components/DashboardCostTab.js +16 -0
- package/dist/tui/components/DashboardExecutionsTab.d.ts +11 -0
- package/dist/tui/components/DashboardExecutionsTab.js +94 -0
- package/dist/tui/components/DashboardSchedulesTab.d.ts +11 -0
- package/dist/tui/components/DashboardSchedulesTab.js +124 -0
- package/dist/tui/components/DashboardTasksTab.d.ts +12 -0
- package/dist/tui/components/DashboardTasksTab.js +200 -0
- package/dist/tui/components/DashboardThreadsTab.d.ts +11 -0
- package/dist/tui/components/DashboardThreadsTab.js +81 -0
- package/dist/tui/components/Header.d.ts +11 -0
- package/dist/tui/components/Header.js +5 -0
- package/dist/tui/components/InputBox.d.ts +10 -0
- package/dist/tui/components/InputBox.js +19 -0
- package/dist/tui/components/MessageRow.d.ts +7 -0
- package/dist/tui/components/MessageRow.js +10 -0
- package/dist/tui/components/Notifications.d.ts +19 -0
- package/dist/tui/components/Notifications.js +72 -0
- package/dist/tui/components/PlanFeedbackModal.d.ts +11 -0
- package/dist/tui/components/PlanFeedbackModal.js +161 -0
- package/dist/tui/components/ProjectSwitcher.d.ts +18 -0
- package/dist/tui/components/ProjectSwitcher.js +43 -0
- package/dist/tui/components/SessionPicker.d.ts +14 -0
- package/dist/tui/components/SessionPicker.js +34 -0
- package/dist/tui/components/SidePanel.d.ts +19 -0
- package/dist/tui/components/SidePanel.js +8 -0
- package/dist/tui/components/StatusLine.d.ts +10 -0
- package/dist/tui/components/StatusLine.js +29 -0
- package/dist/tui/components/Transcript.d.ts +13 -0
- package/dist/tui/components/Transcript.js +56 -0
- package/dist/tui/hooks/useDashboardData.d.ts +32 -0
- package/dist/tui/hooks/useDashboardData.js +104 -0
- package/dist/tui/hooks/useKeybindings.d.ts +19 -0
- package/dist/tui/hooks/useKeybindings.js +87 -0
- package/dist/tui/hooks/useMutate.d.ts +22 -0
- package/dist/tui/hooks/useMutate.js +56 -0
- package/dist/tui/hooks/useNotifications.d.ts +28 -0
- package/dist/tui/hooks/useNotifications.js +70 -0
- package/dist/tui/hooks/useTranscript.d.ts +39 -0
- package/dist/tui/hooks/useTranscript.js +265 -0
- package/dist/tui/hooks/useWsClient.d.ts +29 -0
- package/dist/tui/hooks/useWsClient.js +69 -0
- package/dist/tui/index.d.ts +2 -0
- package/dist/tui/index.js +210 -0
- package/dist/tui/logic.d.ts +16 -0
- package/dist/tui/logic.js +49 -0
- package/dist/tui/render/markdown.d.ts +10 -0
- package/dist/tui/render/markdown.js +38 -0
- package/dist/tui/render/rich-blocks.d.ts +11 -0
- package/dist/tui/render/rich-blocks.js +24 -0
- package/dist/tui/ws-client.d.ts +44 -0
- package/dist/tui/ws-client.js +157 -0
- package/package.json +11 -3
- package/dist/orchestration/channel-queue.d.ts +0 -18
- package/dist/orchestration/channel-queue.js +0 -32
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { createLogger } from '../../../core/log.js';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { Icons } from '../../../core/icons.js';
|
|
3
|
+
import { closeSession, getActiveBackend, getActiveProfile } from '../../../domain/agents/index.js';
|
|
4
4
|
import { fireAndForgetPreCloseHook } from '../../../domain/sessions/session-hooks.js';
|
|
5
5
|
import { sessionStore } from '../../../store/session-registry-repo.js';
|
|
6
6
|
import { conversationLedger } from '../../../store/conversation-ledger-repo.js';
|
|
7
|
-
import
|
|
7
|
+
import { attachExistingSession, resetChannelSession } from '../../../domain/sessions/session-lifecycle.js';
|
|
8
8
|
import { planApprovals } from '../../interactions/plan-approvals.js';
|
|
9
9
|
const log = createLogger('session');
|
|
10
10
|
function formatTimeAgo(ms) {
|
|
@@ -21,12 +21,12 @@ function formatTimeAgo(ms) {
|
|
|
21
21
|
return `${days}d ago`;
|
|
22
22
|
}
|
|
23
23
|
/** Resolve the Slack thread timestamp for the session:
|
|
24
|
-
* 1. Command-level
|
|
24
|
+
* 1. Command-level threadAnchorId (user typed !new in-thread)
|
|
25
25
|
* 2. Conversation ledger's last status message ts (session's thread parent)
|
|
26
26
|
* 3. null (no thread context available) */
|
|
27
|
-
async function resolveSessionThreadTs(channel,
|
|
28
|
-
if (
|
|
29
|
-
return
|
|
27
|
+
async function resolveSessionThreadTs(channel, threadAnchorId) {
|
|
28
|
+
if (threadAnchorId)
|
|
29
|
+
return threadAnchorId;
|
|
30
30
|
const conv = await conversationLedger.getConversation(channel);
|
|
31
31
|
if (conv?.turns.length) {
|
|
32
32
|
// Walk backwards to find the last turn with a statusMessageTs
|
|
@@ -37,25 +37,15 @@ async function resolveSessionThreadTs(channel, threadTs) {
|
|
|
37
37
|
}
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
40
|
-
export async function handleNewCmd(channel, adapter, opts = {},
|
|
40
|
+
export async function handleNewCmd(channel, adapter, opts = {}, threadAnchorId) {
|
|
41
41
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
42
42
|
if (!opts.skipHook) {
|
|
43
|
-
const resolvedThreadTs = await resolveSessionThreadTs(channel,
|
|
43
|
+
const resolvedThreadTs = await resolveSessionThreadTs(channel, threadAnchorId);
|
|
44
44
|
void fireAndForgetPreCloseHook(channel, adapter, resolvedThreadTs);
|
|
45
45
|
}
|
|
46
46
|
closeSession(channel);
|
|
47
|
-
const conv = await conversationLedger.getConversation(channel);
|
|
48
47
|
const profileName = getActiveProfile(channel) || 'default';
|
|
49
|
-
|
|
50
|
-
sessionBackup.cleanupAllBackups(conv.sessionId);
|
|
51
|
-
await conversationLedger.clearConversation(channel);
|
|
52
|
-
}
|
|
53
|
-
// Clear sessions for ALL backends, not just the current one — otherwise switching
|
|
54
|
-
// profiles after !newq can resurrect a stale session from the previous backend
|
|
55
|
-
// (e.g. !newq on PI backend leaves claude:C<channel> intact; switching to Claude
|
|
56
|
-
// backend then tries to --resume a session whose claude-side file is gone).
|
|
57
|
-
const ALL_BACKENDS = ['claude', 'pi', 'codex'];
|
|
58
|
-
await Promise.all(ALL_BACKENDS.map(b => deleteSessionAsync(channel, b).catch(() => { })));
|
|
48
|
+
await resetChannelSession(channel);
|
|
59
49
|
const cleared = planApprovals.clearByChannel(channel);
|
|
60
50
|
if (cleared > 0)
|
|
61
51
|
log.info('Cleared pending plan for channel:', channel);
|
|
@@ -74,19 +64,16 @@ export function createResumeHandler(router) {
|
|
|
74
64
|
if (!record) {
|
|
75
65
|
if (ctx.messageRef) {
|
|
76
66
|
await adapter.updateMessage(ctx.messageRef, {
|
|
77
|
-
text:
|
|
67
|
+
text: `${Icons.error} Session \`${name}\` not found.`,
|
|
78
68
|
}).catch(() => { });
|
|
79
69
|
}
|
|
80
70
|
return;
|
|
81
71
|
}
|
|
82
|
-
|
|
83
|
-
setActiveProfile(record.profileName, ctx.channelId);
|
|
84
|
-
await setSessionAsync(ctx.channelId, record.sessionId, record.backend);
|
|
85
|
-
await conversationLedger.switchSession(ctx.channelId, { sessionId: record.sessionId, sessionName: name, backend: record.backend, profileName: record.profileName });
|
|
72
|
+
await attachExistingSession(ctx.channelId, { sessionId: record.sessionId, sessionName: name, backend: record.backend, profileName: record.profileName });
|
|
86
73
|
const profileNote = record.profileName ? ` (profile: ${record.profileName})` : '';
|
|
87
74
|
if (ctx.messageRef) {
|
|
88
75
|
await adapter.updateMessage(ctx.messageRef, {
|
|
89
|
-
text:
|
|
76
|
+
text: `${Icons.refresh} Switched to session \`${name}\`${profileNote}`,
|
|
90
77
|
}).catch(() => { });
|
|
91
78
|
}
|
|
92
79
|
};
|
|
@@ -104,15 +91,12 @@ export function createResumeHandler(router) {
|
|
|
104
91
|
const name = args[0];
|
|
105
92
|
const record = await sessionStore.lookupSession(name);
|
|
106
93
|
if (!record) {
|
|
107
|
-
await adapter.postMessage(dest, { text:
|
|
94
|
+
await adapter.postMessage(dest, { text: `${Icons.error} Session \`${name}\` not found. Run \`!resume\` to list sessions.` });
|
|
108
95
|
return;
|
|
109
96
|
}
|
|
110
|
-
|
|
111
|
-
setActiveProfile(record.profileName, channel);
|
|
112
|
-
await setSessionAsync(channel, record.sessionId, record.backend);
|
|
113
|
-
await conversationLedger.switchSession(channel, { sessionId: record.sessionId, sessionName: name, backend: record.backend, profileName: record.profileName });
|
|
97
|
+
await attachExistingSession(channel, { sessionId: record.sessionId, sessionName: name, backend: record.backend, profileName: record.profileName });
|
|
114
98
|
const profileNote = record.profileName ? ` (profile: ${record.profileName})` : '';
|
|
115
|
-
await adapter.postMessage(dest, { text:
|
|
99
|
+
await adapter.postMessage(dest, { text: `${Icons.refresh} Switched to session \`${name}\`${profileNote}` });
|
|
116
100
|
return;
|
|
117
101
|
}
|
|
118
102
|
const sessions = await sessionStore.listRecentSessions(10);
|
|
@@ -128,7 +112,7 @@ export function createResumeHandler(router) {
|
|
|
128
112
|
const activeTag = isActive ? ' *(active)*' : '';
|
|
129
113
|
const ago = formatTimeAgo(now - new Date(s.lastUsedAt).getTime());
|
|
130
114
|
const label = s.label ? ` — ${s.label}` : '';
|
|
131
|
-
const kind = s.kind === 'scheduled' ?
|
|
115
|
+
const kind = s.kind === 'scheduled' ? ` ${Icons.scheduled}` : '';
|
|
132
116
|
lines.push(`• \`${s.name}\`${activeTag}${kind}${label} — ${ago}`);
|
|
133
117
|
}
|
|
134
118
|
const text = lines.join('\n');
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { statSync, openSync, readSync, closeSync } from 'fs';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import { moduleDir } from '../../../core/utils.js';
|
|
4
|
+
import { Icons } from '../../../core/icons.js';
|
|
4
5
|
const DAEMON_LOG_PATH = path.join(moduleDir(import.meta.url), '..', '..', '..', '..', 'logs', 'daemon.log');
|
|
5
6
|
const activeTails = new Map();
|
|
6
7
|
async function stopTail(channel, adapter) {
|
|
@@ -12,7 +13,7 @@ async function stopTail(channel, adapter) {
|
|
|
12
13
|
}
|
|
13
14
|
clearInterval(active.interval);
|
|
14
15
|
activeTails.delete(channel);
|
|
15
|
-
await adapter.postMessage(dest, { text:
|
|
16
|
+
await adapter.postMessage(dest, { text: `${Icons.stopped} Tail stopped.` });
|
|
16
17
|
}
|
|
17
18
|
async function sendInitialTailPreview(channel, adapter) {
|
|
18
19
|
const previewDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
@@ -24,11 +25,11 @@ async function sendInitialTailPreview(channel, adapter) {
|
|
|
24
25
|
readSync(fd, buf, 0, previewBytes, stat.size - previewBytes);
|
|
25
26
|
closeSync(fd);
|
|
26
27
|
const lines = buf.toString('utf-8').split('\n').filter(Boolean).slice(-30);
|
|
27
|
-
await adapter.postMessage(previewDest, { text:
|
|
28
|
+
await adapter.postMessage(previewDest, { text: `${Icons.scroll} *Tailing daemon.log* (last ${lines.length} lines, refresh every 3s)\n\`\`\`\n${lines.join('\n')}\n\`\`\`\nUse \`!tail stop\` to stop.` });
|
|
28
29
|
return stat.size;
|
|
29
30
|
}
|
|
30
31
|
catch (err) {
|
|
31
|
-
await adapter.postMessage(previewDest, { text:
|
|
32
|
+
await adapter.postMessage(previewDest, { text: `${Icons.error} Cannot read daemon.log: ${err.message}` });
|
|
32
33
|
return null;
|
|
33
34
|
}
|
|
34
35
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Icons } from '../../../core/icons.js';
|
|
1
2
|
import { scanAllTasks, completedHashSet, isActionable } from '../../../domain/tasks/parser.js';
|
|
2
3
|
import { PROJECTS_DIR } from '../../../core/utils.js';
|
|
3
4
|
import * as path from 'path';
|
|
@@ -15,7 +16,7 @@ function formatTaskList(tasks, filter, project) {
|
|
|
15
16
|
const filterLabel = filter === 'all' ? '' : ` — ${filter}`;
|
|
16
17
|
const lines = [`*Tasks for \`${project}\`* (${filtered.length}/${tasks.length})${filterLabel}\n`];
|
|
17
18
|
for (const task of filtered) {
|
|
18
|
-
const status = task.status === 'done' ?
|
|
19
|
+
const status = task.status === 'done' ? Icons.ok : (task.blocked_by ? Icons.blocked : (task.claimed_by ? Icons.refresh : (task.paused ? Icons.paused : Icons.pending)));
|
|
19
20
|
const id = task.id ? `\`${task.id}\`` : '—';
|
|
20
21
|
const tags = [];
|
|
21
22
|
if (task.priority)
|
|
@@ -110,13 +111,13 @@ export function createTasksHandler(router) {
|
|
|
110
111
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
111
112
|
const args = trimmedMessage.split(/\s+/).slice(1);
|
|
112
113
|
if (args.length === 0) {
|
|
113
|
-
await adapter.postMessage(dest, { text:
|
|
114
|
+
await adapter.postMessage(dest, { text: `${Icons.error} Usage: \`!tasks <project>\`` });
|
|
114
115
|
return;
|
|
115
116
|
}
|
|
116
117
|
const project = args[0];
|
|
117
118
|
const projectDir = path.join(PROJECTS_DIR, project);
|
|
118
119
|
if (!existsSync(projectDir)) {
|
|
119
|
-
await adapter.postMessage(dest, { text:
|
|
120
|
+
await adapter.postMessage(dest, { text: `${Icons.error} Project not found: \`${project}\`` });
|
|
120
121
|
return;
|
|
121
122
|
}
|
|
122
123
|
const tasks = scanAllTasks(project);
|
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
// pos: !thread sub-command family handlers
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { createLogger } from '../../../core/log.js';
|
|
6
|
+
import { Icons } from '../../../core/icons.js';
|
|
6
7
|
import { threadStore } from '../../../store/thread-repo.js';
|
|
7
8
|
import { listTemplates, listAgents } from '../../../domain/threads/index.js';
|
|
8
9
|
import { runningExecutions } from '../../../core/running-executions.js';
|
|
9
|
-
import
|
|
10
|
+
import * as executionRegistry from '../../../domain/executions/registry.js';
|
|
11
|
+
import { conduitQueues } from '../../conduit-queue.js';
|
|
10
12
|
const log = createLogger('thread-handlers');
|
|
11
13
|
async function handleThreadStatus(channel, adapter) {
|
|
12
14
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
@@ -60,7 +62,7 @@ async function handleThreadAgents(channel, adapter) {
|
|
|
60
62
|
lines.push('');
|
|
61
63
|
lines.push(`*Active Thread* \`${active.id}\``);
|
|
62
64
|
for (const [slotId, slot] of Object.entries(active.agents)) {
|
|
63
|
-
const isActiveAgent = slotId === active.activeAgent ?
|
|
65
|
+
const isActiveAgent = slotId === active.activeAgent ? ` ${Icons.arrowLeft}` : '';
|
|
64
66
|
const sessionStr = slot.sessionName || 'no session';
|
|
65
67
|
lines.push(` • *${slotId}* (${slot.profile}) — ${slot.status} | ${sessionStr}${isActiveAgent}`);
|
|
66
68
|
}
|
|
@@ -69,11 +71,19 @@ async function handleThreadAgents(channel, adapter) {
|
|
|
69
71
|
}
|
|
70
72
|
async function handleThreadCancelAlias(channel, adapter) {
|
|
71
73
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
72
|
-
// Alias for !cancel —
|
|
73
|
-
|
|
74
|
+
// Alias for !cancel — tear down every live execution on the channel as 'cancelled'
|
|
75
|
+
// (record→cancelled, kill the handle, balanced event), matching the !cancel path.
|
|
76
|
+
const execs = runningExecutions.getByChannel(channel);
|
|
77
|
+
for (const e of execs) {
|
|
78
|
+
if (e.executionId)
|
|
79
|
+
executionRegistry.teardownExecution({ executionId: e.executionId, status: 'cancelled', durationS: 0 });
|
|
80
|
+
else
|
|
81
|
+
runningExecutions.killById(e.registryKey);
|
|
82
|
+
}
|
|
83
|
+
if (execs.length > 0) {
|
|
74
84
|
log.info('Cancel requested for channel:', channel);
|
|
75
|
-
|
|
76
|
-
await adapter.postMessage(dest, { text:
|
|
85
|
+
conduitQueues.delete(channel);
|
|
86
|
+
await adapter.postMessage(dest, { text: `${Icons.stopped} Cancelled. Session preserved — next message will resume.` });
|
|
77
87
|
}
|
|
78
88
|
else {
|
|
79
89
|
await adapter.postMessage(dest, { text: 'Nothing running to cancel.' });
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createLogger } from '../../core/log.js';
|
|
2
|
+
import { Icons } from '../../core/icons.js';
|
|
2
3
|
import { conversationLedger } from '../../store/conversation-ledger-repo.js';
|
|
3
4
|
import * as sessionBackup from '../../domain/sessions/session-backup.js';
|
|
4
5
|
import { deleteSessionAsync } from '../../domain/sessions/session.js';
|
|
5
6
|
import { resolveBackendForChannel } from '../../domain/agents/index.js';
|
|
6
|
-
import {
|
|
7
|
+
import { conduitQueues } from '../conduit-queue.js';
|
|
7
8
|
import { supersededEdits } from '../superseded-edits.js';
|
|
8
9
|
const log = createLogger('edit-handler');
|
|
9
10
|
const DEBOUNCE_MS = 500;
|
|
@@ -22,7 +23,7 @@ const pendingEdits = new Map();
|
|
|
22
23
|
function createEditHandler(deps) {
|
|
23
24
|
return async function handleMessageEdit(ctx, adapter) {
|
|
24
25
|
const { originalRef, newText } = ctx;
|
|
25
|
-
const channel = originalRef.
|
|
26
|
+
const channel = originalRef.conduit;
|
|
26
27
|
const originalTs = originalRef.messageId;
|
|
27
28
|
log.info('Message edited:', { channel, ts: originalTs, new: newText?.substring(0, 40) });
|
|
28
29
|
// Look up the original processing record
|
|
@@ -64,10 +65,10 @@ async function processEdit({ channel, adapter, originalTs, newText, turnIndex, c
|
|
|
64
65
|
// resolveBackendForChannel reads the channel's profile and falls back to global if absent.
|
|
65
66
|
const backend = resolveBackendForChannel(channel) || conversation.backend;
|
|
66
67
|
// Step 1: Cancel any active processing on this channel
|
|
67
|
-
if (activeAgents.
|
|
68
|
+
if (activeAgents.hasChannel(channel)) {
|
|
68
69
|
supersededEdits.mark(channel);
|
|
69
|
-
activeAgents.
|
|
70
|
-
|
|
70
|
+
activeAgents.supersedeByChannel(channel, 'edit');
|
|
71
|
+
conduitQueues.delete(channel);
|
|
71
72
|
log.info('Killed active process for edit retry');
|
|
72
73
|
}
|
|
73
74
|
// Step 2: Rollback — mark all turns from editedTurnIndex onward as superseded
|
|
@@ -146,13 +147,13 @@ async function cleanupSupersededMessages(supersededTurns, channel, adapter) {
|
|
|
146
147
|
const supersededStatusTimestamps = [];
|
|
147
148
|
for (const turn of supersededTurns) {
|
|
148
149
|
for (const ts of turn.responseMessageTimestamps) {
|
|
149
|
-
promises.push(adapter.deleteMessage({ channel, messageId: ts }).catch((e) => {
|
|
150
|
+
promises.push(adapter.deleteMessage({ conduit: channel, messageId: ts }).catch((e) => {
|
|
150
151
|
log.warn('Failed to delete message:', ts, e.message);
|
|
151
152
|
}));
|
|
152
153
|
}
|
|
153
154
|
if (turn.statusMessageTs) {
|
|
154
155
|
supersededStatusTimestamps.push(turn.statusMessageTs);
|
|
155
|
-
promises.push(adapter.updateMessage({ channel, messageId: turn.statusMessageTs }, { text:
|
|
156
|
+
promises.push(adapter.updateMessage({ conduit: channel, messageId: turn.statusMessageTs }, { text: `${Icons.superseded} Superseded by edit` }).catch(() => { }));
|
|
156
157
|
}
|
|
157
158
|
}
|
|
158
159
|
await Promise.allSettled(promises);
|
|
@@ -17,6 +17,19 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
|
|
|
17
17
|
try {
|
|
18
18
|
const group = askUserQuestion.createHookGroup(ev.requestId, ev.channel, ev.sessionId, ev.questions, ev.extensionUiId, ev.threadId ?? null);
|
|
19
19
|
askUserQuestion.registerHookResolver(ev.requestId, (data) => resolveHookRequest(ev.requestId, data));
|
|
20
|
+
// Inline-modal platforms (Feishu) render the question form as an inline card,
|
|
21
|
+
// so the intermediate "Answer" summary card + click is redundant — post the
|
|
22
|
+
// form directly. Slack requires a user click (trigger_id) to open a modal, so
|
|
23
|
+
// it keeps the summary card + Answer button below. The conduit prefix is the
|
|
24
|
+
// reliable per-channel signal under a multi-platform CompositeAdapter (merged
|
|
25
|
+
// capabilities can't distinguish channels).
|
|
26
|
+
if (ev.channel.startsWith('feishu:')) {
|
|
27
|
+
// Flush any pending streamed text so the form lands after it, in order.
|
|
28
|
+
const fstream = getStreamingCallback(ev.channel)?.stream;
|
|
29
|
+
await fstream?.flush?.().catch(() => { });
|
|
30
|
+
await adapter.openModal(ev.channel, askUserQuestion.buildQuestionModalDefinition(group));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
20
33
|
// streamingCb is fetched only to extract the stream reference — not invoked directly for AskUser
|
|
21
34
|
const streamingCb = getStreamingCallback(ev.channel);
|
|
22
35
|
const stream = streamingCb?.stream;
|
|
@@ -67,10 +80,13 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
|
|
|
67
80
|
});
|
|
68
81
|
}
|
|
69
82
|
else {
|
|
83
|
+
// Fallback path (stream already finalized after the turn): pass threadId
|
|
84
|
+
// explicitly so the approval card lands inside the conversation topic via
|
|
85
|
+
// message.reply instead of being posted as a standalone message.
|
|
70
86
|
await adapter.postInteractive(planDest, {
|
|
71
87
|
text: 'Plan approval',
|
|
72
88
|
...planApproval,
|
|
73
|
-
});
|
|
89
|
+
}, { threadId: ev.threadId ?? undefined });
|
|
74
90
|
}
|
|
75
91
|
}
|
|
76
92
|
catch (e) {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { PlatformAdapter, MessageEditContext } from '../../platform/index.js';
|
|
2
2
|
export interface MessageHandlerDeps {
|
|
3
|
-
dispatchCommand: (text: string | undefined, channel: string, adapter: PlatformAdapter,
|
|
3
|
+
dispatchCommand: (text: string | undefined, channel: string, adapter: PlatformAdapter, threadAnchorId?: string | null) => boolean;
|
|
4
4
|
handleMessageEdit: (ctx: MessageEditContext, adapter: PlatformAdapter) => void;
|
|
5
5
|
}
|
|
6
6
|
export declare function registerMessageHandler(adapter: PlatformAdapter, deps: MessageHandlerDeps): void;
|
|
@@ -13,11 +13,11 @@ export function registerMessageHandler(adapter, deps) {
|
|
|
13
13
|
});
|
|
14
14
|
adapter.onMessage(async (ctx) => {
|
|
15
15
|
const message = ctx.message;
|
|
16
|
-
log.info('Message event:', JSON.stringify({
|
|
16
|
+
log.info('Message event:', JSON.stringify({ kind: message.kind, isBot: message.isBot, text: message.text?.substring(0, 50), files: message.files?.length, threadId: message.ref.threadId }));
|
|
17
17
|
if (routeBotMessage(message)) { /* stripped BRANCH_CALLBACK prefix, continue */ }
|
|
18
18
|
else if (message.isBot)
|
|
19
19
|
return;
|
|
20
|
-
if (message.
|
|
20
|
+
if (message.kind === 'system')
|
|
21
21
|
return;
|
|
22
22
|
const hasFiles = (message.files?.length || 0) > 0;
|
|
23
23
|
const userMessage = message.text;
|
|
@@ -25,20 +25,20 @@ export function registerMessageHandler(adapter, deps) {
|
|
|
25
25
|
const forwardedContent = extractForwardedContent(message);
|
|
26
26
|
if (!userMessage && !hasFiles && !forwardedContent)
|
|
27
27
|
return;
|
|
28
|
-
const
|
|
29
|
-
if (shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, message.ref.
|
|
28
|
+
const threadAnchorId = message.ref.threadId || null;
|
|
29
|
+
if (shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, message.ref.conduit, adapter, threadAnchorId))
|
|
30
30
|
return;
|
|
31
|
-
const channel = message.ref.
|
|
31
|
+
const channel = message.ref.conduit;
|
|
32
32
|
let agentMessage = normalizeSkillCommandPrefix(userMessage || '');
|
|
33
33
|
if (forwardedContent) {
|
|
34
34
|
agentMessage = `[Forwarded message]\n${forwardedContent}\n[End forwarded message]\n\n${agentMessage || 'The user forwarded the above message to you.'}`;
|
|
35
35
|
}
|
|
36
36
|
const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/) ?? null;
|
|
37
37
|
const threadStartMatch = trimmedMessage?.match(/^!thread\s+(\S+)\s+([\s\S]+)/) ?? null;
|
|
38
|
-
const existingThread =
|
|
38
|
+
const existingThread = threadAnchorId ? threadStore.findByPlatformThread(channel, threadAnchorId) : null;
|
|
39
39
|
const isActiveThread = !!(existingThread && (existingThread.status === 'running' || existingThread.status === 'waiting'));
|
|
40
40
|
await orchestrator.handleMessage({
|
|
41
|
-
message, channel, adapter,
|
|
41
|
+
message, channel, adapter, threadAnchorId, hasFiles,
|
|
42
42
|
userMessage: userMessage || '', agentMessage,
|
|
43
43
|
threadAddMatch, threadStartMatch, existingThread, isActiveThread,
|
|
44
44
|
});
|
|
@@ -56,7 +56,7 @@ function routeBotMessage(message) {
|
|
|
56
56
|
return false;
|
|
57
57
|
}
|
|
58
58
|
// --- Command dispatch check ---
|
|
59
|
-
function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel, adapter,
|
|
59
|
+
function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel, adapter, threadAnchorId) {
|
|
60
60
|
const threadAddMatch = trimmedMessage?.match(/^!thread\s+add\s+(\S+)(?:\s+([\s\S]+))?$/);
|
|
61
61
|
const isThreadExecCmd = (() => {
|
|
62
62
|
if (threadAddMatch)
|
|
@@ -66,5 +66,5 @@ function shouldSkipForCommandDispatch(trimmedMessage, dispatchCommand, channel,
|
|
|
66
66
|
return false;
|
|
67
67
|
return getTemplate(m[1]) != null || getAgent(m[1]) != null;
|
|
68
68
|
})();
|
|
69
|
-
return !isThreadExecCmd && dispatchCommand(trimmedMessage, channel, adapter,
|
|
69
|
+
return !isThreadExecCmd && dispatchCommand(trimmedMessage, channel, adapter, threadAnchorId);
|
|
70
70
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// input: GitHub push, task-op, remote cmd, hook HTTP events
|
|
1
|
+
// input: GitHub push, task-op, thread-op, remote cmd, hook HTTP events
|
|
2
2
|
// output: startWebhookServer
|
|
3
|
-
// pos: GitHub/task-op/hook webhook HTTP entry point
|
|
3
|
+
// pos: GitHub/task-op/thread-op/hook webhook HTTP entry point
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { createLogger } from '../../core/log.js';
|
|
6
6
|
import * as http from 'http';
|
|
@@ -10,6 +10,14 @@ import { taskMutator } from '../../domain/tasks/mutator.js';
|
|
|
10
10
|
import { sendCommand, isDeviceOnline, getOnlineDevices } from '../../domain/remote/client-manager.js';
|
|
11
11
|
import { registerAskQuestion, registerPlanApproval } from './hook-bridge.js';
|
|
12
12
|
import { getCurrentPlanFilePath } from '../../domain/agents/index.js';
|
|
13
|
+
import { ctx as jobCtx } from '../../domain/scheduling/job-registry.js';
|
|
14
|
+
import { createThread, cancelThread, readArtifact, listTemplates, listAgents, checkSpawnGuards, getRootThreadId, registerChildSpawn, buildThreadTree, getTreeThreads, buildContractPrompt, buildMissionChain } from '../../domain/threads/index.js';
|
|
15
|
+
import { runThreadDetached } from '../thread-executor.js';
|
|
16
|
+
import { buildThreadSummary } from '../../domain/threads/runner.js';
|
|
17
|
+
import { Icons } from '../../core/icons.js';
|
|
18
|
+
import { buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from '../status-helpers.js';
|
|
19
|
+
import { threadStore } from '../../store/thread-repo.js';
|
|
20
|
+
import { fireThreadCallback } from '../thread-callback.js';
|
|
13
21
|
const log = createLogger('webhook');
|
|
14
22
|
const PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
|
|
15
23
|
// Read at call time, not import time — dotenv.config() in app.ts runs AFTER ESM imports
|
|
@@ -133,6 +141,229 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
|
|
|
133
141
|
});
|
|
134
142
|
return;
|
|
135
143
|
}
|
|
144
|
+
// --- Thread operation (from MCP sidecar → thread system) ---
|
|
145
|
+
// Local-only, no secret (same trust model as /webhook/remote-command). thread_start is
|
|
146
|
+
// fire-and-forget: createThread + runThread().catch() without await, returning the threadId.
|
|
147
|
+
if (req.method === 'POST' && req.url === '/webhook/thread-op') {
|
|
148
|
+
readJsonBody(req, async (error, _body, data) => {
|
|
149
|
+
if (error) {
|
|
150
|
+
res.writeHead(400);
|
|
151
|
+
res.end('Bad JSON');
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const reply = (obj) => {
|
|
155
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
156
|
+
res.end(JSON.stringify(obj));
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
const action = data.action;
|
|
160
|
+
if (action === 'start') {
|
|
161
|
+
const { template, agent, message } = data;
|
|
162
|
+
if ((template && agent) || (!template && !agent)) {
|
|
163
|
+
return reply({ success: false, error: 'provide exactly one of template or agent' });
|
|
164
|
+
}
|
|
165
|
+
if (!message)
|
|
166
|
+
return reply({ success: false, error: 'message required' });
|
|
167
|
+
const maxDepth = parseInt(process.env.CORTEX_THREAD_MAX_DEPTH || '5', 10) || 5;
|
|
168
|
+
const curDepth = Number(data.depth) || 0;
|
|
169
|
+
if (curDepth >= maxDepth) {
|
|
170
|
+
return reply({ success: false, error: `max thread depth (${maxDepth}) reached — cannot spawn nested thread at depth ${curDepth}` });
|
|
171
|
+
}
|
|
172
|
+
if (!jobCtx.adapter) {
|
|
173
|
+
return reply({ success: false, error: 'no platform adapter available (daemon not fully initialized)' });
|
|
174
|
+
}
|
|
175
|
+
// Tree resource guards (DR-0014): width / node count / budget. A rejection is a
|
|
176
|
+
// signal to escalate or re-plan — the error text says so to the calling agent.
|
|
177
|
+
const parentThread = data.parentThreadId ? threadStore.get(String(data.parentThreadId)) : null;
|
|
178
|
+
const guard = checkSpawnGuards(parentThread);
|
|
179
|
+
if (guard.ok === false) {
|
|
180
|
+
return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate via [ABORT: <diagnosis>].` });
|
|
181
|
+
}
|
|
182
|
+
const projectId = data.projectId || 'general';
|
|
183
|
+
// The originating conduit (the starter agent's SLACK_CHANNEL, forwarded by thread-ops.ts).
|
|
184
|
+
// When present we route output back to that channel with a live status message, mirroring
|
|
185
|
+
// the Slack `!thread` path (thread-executor handleThreadStart). When absent (non-Slack /
|
|
186
|
+
// channel-less context) we fall back to project-report routing (project conduit → admin DM).
|
|
187
|
+
const haveChannel = typeof data.channel === 'string' && data.channel.length > 0;
|
|
188
|
+
const channel = data.channel || projectId;
|
|
189
|
+
// Structured delegation contract (DR-0014): optional thread_start params compose
|
|
190
|
+
// into a contract prompt; the ancestor goal chain rides along to prevent drift.
|
|
191
|
+
const contract = (data.goal || data.done_when || data.context_files || data.deliverable_path || data.budget_usd != null)
|
|
192
|
+
? {
|
|
193
|
+
goal: String(data.goal || message).slice(0, 500),
|
|
194
|
+
doneWhen: data.done_when ? String(data.done_when) : null,
|
|
195
|
+
contextFiles: Array.isArray(data.context_files) ? data.context_files.map(String) : undefined,
|
|
196
|
+
deliverablePath: data.deliverable_path ? String(data.deliverable_path) : null,
|
|
197
|
+
budgetUsd: data.budget_usd != null ? Number(data.budget_usd) : null,
|
|
198
|
+
}
|
|
199
|
+
: null;
|
|
200
|
+
const missionChain = buildMissionChain(parentThread);
|
|
201
|
+
const thread = createThread(channel, {
|
|
202
|
+
templateName: template || null,
|
|
203
|
+
agentName: agent || null,
|
|
204
|
+
userMessage: buildContractPrompt({ message, contract, missionChain }),
|
|
205
|
+
userMessageTs: `mcp_${Date.now()}`,
|
|
206
|
+
projectId,
|
|
207
|
+
metadata: {
|
|
208
|
+
trigger: 'mcp-thread',
|
|
209
|
+
depth: curDepth + 1,
|
|
210
|
+
parentSessionId: data.parentSessionId || null,
|
|
211
|
+
parentThreadId: data.parentThreadId || null,
|
|
212
|
+
parentChannel: data.parentChannel || null,
|
|
213
|
+
parentProfile: data.parentProfile || null,
|
|
214
|
+
rootThreadId: parentThread ? getRootThreadId(parentThread) : null,
|
|
215
|
+
resumeDest: haveChannel ? 'interactive-reply' : 'project-report',
|
|
216
|
+
contract,
|
|
217
|
+
missionChain,
|
|
218
|
+
},
|
|
219
|
+
});
|
|
220
|
+
// Register the child on its thread parent: childThreadIds always (width counter),
|
|
221
|
+
// waitingOn when the parent intends to suspend on it (wait defaults to true for
|
|
222
|
+
// thread parents — the [WAIT_CHILDREN] protocol).
|
|
223
|
+
if (parentThread) {
|
|
224
|
+
await registerChildSpawn(parentThread.id, thread.id, data.wait !== false);
|
|
225
|
+
}
|
|
226
|
+
let dest;
|
|
227
|
+
let statusMsg = null;
|
|
228
|
+
if (haveChannel) {
|
|
229
|
+
dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
230
|
+
const label = template || agent;
|
|
231
|
+
const startText = `${Icons.processing} Starting thread (${template ? label : `agent:${label}`})...`;
|
|
232
|
+
try {
|
|
233
|
+
statusMsg = await jobCtx.adapter.postMessage(dest, { text: startText });
|
|
234
|
+
const blocksTemplate = { channel, sessionName: null, isDm: false, threadId: thread.id };
|
|
235
|
+
await jobCtx.adapter.updateMessage(statusMsg, {
|
|
236
|
+
text: startText,
|
|
237
|
+
richBlocks: buildStatusActionBlocks(startText, blocksTemplate),
|
|
238
|
+
}).catch(() => { });
|
|
239
|
+
initStatusBlocks(statusMsg, blocksTemplate);
|
|
240
|
+
}
|
|
241
|
+
catch (e) {
|
|
242
|
+
log.warn(`thread-op start: status message post failed: ${e.message}`);
|
|
243
|
+
statusMsg = null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
dest = { type: 'project-report', projectId, trigger: 'mcp-thread', sessionId: '' };
|
|
248
|
+
}
|
|
249
|
+
const runOpts = {
|
|
250
|
+
adapter: jobCtx.adapter,
|
|
251
|
+
channel,
|
|
252
|
+
destination: dest,
|
|
253
|
+
threadAnchorId: statusMsg ? statusMsg.messageId : null,
|
|
254
|
+
statusMsg,
|
|
255
|
+
startTime: Date.now(),
|
|
256
|
+
onProgress: null,
|
|
257
|
+
onToolUse: null,
|
|
258
|
+
};
|
|
259
|
+
// Hold the daemon busy gate for the WHOLE pipeline so a deferred rebuild/restart can't
|
|
260
|
+
// SIGTERM app.ts mid-thread and stamp it "Interrupted by server restart". (Bare runThread
|
|
261
|
+
// here was invisible to the busy/idle gate — see runThreadDetached.)
|
|
262
|
+
runThreadDetached(thread.id, runOpts, {
|
|
263
|
+
onSettled: (id) => {
|
|
264
|
+
// Seal the live status message with a summary (interactive path only).
|
|
265
|
+
// A suspended parent ([WAIT_CHILDREN] → status 'waiting') is NOT sealed:
|
|
266
|
+
// it will resume; the message just reflects the suspension.
|
|
267
|
+
if (statusMsg) {
|
|
268
|
+
const t = threadStore.get(id);
|
|
269
|
+
if (t && t.status === 'waiting') {
|
|
270
|
+
const n = (t.metadata?.waitingOn?.length ?? 0) + (t.metadata?.waitingOnTasks?.length ?? 0);
|
|
271
|
+
// Persist the ref so the post-resume settle can refresh this message.
|
|
272
|
+
void threadStore.mutate(t.id, (r) => { (r.metadata ??= {}).statusMsgRef = statusMsg; }).catch(() => { });
|
|
273
|
+
void jobCtx.adapter.updateMessage(statusMsg, {
|
|
274
|
+
text: `${Icons.processing} Thread suspended — waiting on ${n} child(ren)`,
|
|
275
|
+
}).catch(() => { });
|
|
276
|
+
}
|
|
277
|
+
else if (t) {
|
|
278
|
+
const totalNumTurns = t.steps.reduce((s, st) => s + (st.numTurns || 0), 0);
|
|
279
|
+
const summaryText = buildThreadSummary({ thread: t, totalCostUsd: t.totalCostUsd, totalNumTurns, finalOutput: null, lastAgentResult: null, executionId: null });
|
|
280
|
+
void jobCtx.adapter.updateMessage(statusMsg, {
|
|
281
|
+
text: summaryText,
|
|
282
|
+
richBlocks: buildSealedStatusActionBlocks(summaryText, { channel, sessionName: null, isDm: false, threadId: t.id }),
|
|
283
|
+
}).catch(() => { });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
// Return the promise so runThreadDetached holds the busy gate across this callback —
|
|
287
|
+
// it wakes the parent agent for a full turn, and a deferred restart firing mid-wake
|
|
288
|
+
// would drop the notification. The .catch keeps the returned promise non-rejecting.
|
|
289
|
+
return fireThreadCallback(id).catch((e) => log.error(`thread-callback ${id}: ${e.message}`));
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
log.info(`thread-op start ${thread.id} (${template || agent}, depth ${curDepth + 1})`);
|
|
293
|
+
return reply({ success: true, data: { threadId: thread.id, status: 'running' } });
|
|
294
|
+
}
|
|
295
|
+
if (action === 'status') {
|
|
296
|
+
const t = threadStore.get(data.threadId);
|
|
297
|
+
if (!t)
|
|
298
|
+
return reply({ success: false, error: 'thread not found' });
|
|
299
|
+
return reply({ success: true, data: {
|
|
300
|
+
threadId: t.id, status: t.status, activeAgent: t.activeAgent, stepCount: t.steps.length,
|
|
301
|
+
totalCostUsd: t.totalCostUsd, abortReason: t.abortReason, artifactPath: t.artifactPath,
|
|
302
|
+
createdAt: t.createdAt, updatedAt: t.updatedAt, endedAt: t.endedAt, error: t.error,
|
|
303
|
+
} });
|
|
304
|
+
}
|
|
305
|
+
if (action === 'result') {
|
|
306
|
+
const t = threadStore.get(data.threadId);
|
|
307
|
+
if (!t)
|
|
308
|
+
return reply({ success: false, error: 'thread not found' });
|
|
309
|
+
const terminal = ['completed', 'failed', 'cancelled', 'aborted'].includes(t.status);
|
|
310
|
+
const artifact = readArtifact(t.id);
|
|
311
|
+
const finalOutput = t.steps.length ? t.steps[t.steps.length - 1].output : null;
|
|
312
|
+
return reply({ success: true, data: {
|
|
313
|
+
threadId: t.id, status: t.status, terminal,
|
|
314
|
+
...(terminal ? {} : { note: 'thread still running — result is partial' }),
|
|
315
|
+
artifact, finalOutput,
|
|
316
|
+
} });
|
|
317
|
+
}
|
|
318
|
+
if (action === 'list') {
|
|
319
|
+
return reply({ success: true, data: {
|
|
320
|
+
templates: listTemplates().map((t) => ({ name: t.name, description: t.description })),
|
|
321
|
+
agents: listAgents().map((a) => ({ name: a.name, description: a.description })),
|
|
322
|
+
} });
|
|
323
|
+
}
|
|
324
|
+
if (action === 'list-threads') {
|
|
325
|
+
const scope = data.scope || 'mine';
|
|
326
|
+
let threads = threadStore.getAll();
|
|
327
|
+
if (scope === 'project') {
|
|
328
|
+
const pid = data.projectId || 'general';
|
|
329
|
+
threads = threads.filter((t) => t.projectId === pid);
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
// 'mine': threads spawned from the caller's session
|
|
333
|
+
const sid = data.parentSessionId || null;
|
|
334
|
+
threads = sid ? threads.filter((t) => t.metadata?.parentSessionId === sid) : [];
|
|
335
|
+
}
|
|
336
|
+
// Tree view (DR-0014): expand the matched threads to their full trees and
|
|
337
|
+
// return nested nodes with per-root rollups (nodeCount/cost/byStatus/maxDepth).
|
|
338
|
+
if (data.view === 'tree') {
|
|
339
|
+
const rootIds = new Set(threads.map((t) => getRootThreadId(t)));
|
|
340
|
+
const treeThreads = [...rootIds].flatMap((rid) => getTreeThreads(rid));
|
|
341
|
+
const trees = buildThreadTree(treeThreads);
|
|
342
|
+
return reply({ success: true, data: { scope, view: 'tree', count: trees.length, trees } });
|
|
343
|
+
}
|
|
344
|
+
threads = threads.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
|
|
345
|
+
const limit = Number(data.limit) || 50;
|
|
346
|
+
const out = threads.slice(0, limit).map((t) => ({
|
|
347
|
+
threadId: t.id, status: t.status, templateName: t.templateName, activeAgent: t.activeAgent,
|
|
348
|
+
stepCount: t.steps.length, totalCostUsd: t.totalCostUsd,
|
|
349
|
+
createdAt: t.createdAt, updatedAt: t.updatedAt,
|
|
350
|
+
trigger: t.metadata?.trigger ?? null, depth: t.metadata?.depth ?? null,
|
|
351
|
+
}));
|
|
352
|
+
return reply({ success: true, data: { scope, count: out.length, threads: out } });
|
|
353
|
+
}
|
|
354
|
+
if (action === 'cancel') {
|
|
355
|
+
const cancelled = await cancelThread(data.threadId);
|
|
356
|
+
return reply({ success: true, data: { cancelled } });
|
|
357
|
+
}
|
|
358
|
+
return reply({ success: false, error: `unknown action: ${action}` });
|
|
359
|
+
}
|
|
360
|
+
catch (e) {
|
|
361
|
+
log.error(`thread-op error: ${e.message}`);
|
|
362
|
+
reply({ success: false, error: e.message });
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
136
367
|
// --- PreToolUse hook: AskUserQuestion ---
|
|
137
368
|
if (req.method === 'POST' && req.url === '/hook/ask-user-question') {
|
|
138
369
|
readJsonBody(req, async (error, _body, data) => {
|