@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
|
@@ -6,7 +6,9 @@ import * as lark from '@larksuiteoapi/node-sdk';
|
|
|
6
6
|
import * as fs from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import { createLogger } from '../../core/log.js';
|
|
9
|
+
import { STORE_DIR, CONFIG_DIR } from '../../core/paths.js';
|
|
9
10
|
import { FeishuOutputStream } from './feishu-output-stream.js';
|
|
11
|
+
import { ProjectConduitsStore } from './project-conduits.js';
|
|
10
12
|
const log = createLogger('feishu');
|
|
11
13
|
export class FeishuAdapter {
|
|
12
14
|
name = 'feishu';
|
|
@@ -15,22 +17,28 @@ export class FeishuAdapter {
|
|
|
15
17
|
messageEdit: false, // Feishu has no message_changed event
|
|
16
18
|
modals: false, // No native modal; openModal() degrades to card form
|
|
17
19
|
reactions: true, // im.v1.messageReaction.create
|
|
18
|
-
ephemeral: false, // Feishu has no ephemeral messages
|
|
19
20
|
fileUpload: true, // im.v1.file.create + message
|
|
20
21
|
richFormatting: true, // Message cards with markdown
|
|
21
22
|
maxMessageLength: 4000, // Card 30KB limit, ~4000 chars safe
|
|
22
23
|
maxThreadDepth: 1, // UI shows 1 level
|
|
23
24
|
};
|
|
24
25
|
client;
|
|
25
|
-
|
|
26
|
+
// Lazily created in start(): the lark WSClient holds an open libuv handle the
|
|
27
|
+
// moment it is constructed, which keeps the process alive even before start().
|
|
28
|
+
// Unit tests instantiate the adapter without start()ing it, so building it
|
|
29
|
+
// eagerly here would hang the test runner's event loop on exit.
|
|
30
|
+
wsClient = null;
|
|
31
|
+
domain;
|
|
26
32
|
eventDispatcher;
|
|
27
33
|
config;
|
|
28
34
|
messageHandler = null;
|
|
29
35
|
actionHandlers = new Map();
|
|
30
36
|
modalHandlers = new Map();
|
|
37
|
+
_adminAutoDetected = false;
|
|
31
38
|
constructor(config) {
|
|
32
39
|
this.config = config;
|
|
33
40
|
const domain = config.domain === 'lark' ? lark.Domain.Lark : lark.Domain.Feishu;
|
|
41
|
+
this.domain = domain;
|
|
34
42
|
this.client = new lark.Client({
|
|
35
43
|
appId: config.appId,
|
|
36
44
|
appSecret: config.appSecret,
|
|
@@ -57,21 +65,51 @@ export class FeishuAdapter {
|
|
|
57
65
|
return await this.handleCardAction(data);
|
|
58
66
|
},
|
|
59
67
|
});
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
68
|
+
}
|
|
69
|
+
// --- Conduit prefixing ---
|
|
70
|
+
// The `feishu:` prefix is this adapter's canonical external form for conduits.
|
|
71
|
+
// Outbound conduits (MessageRef.conduit, getProjectConduits values, incoming
|
|
72
|
+
// file conduits, triggerId) carry the prefix; inbound conduits (Destination,
|
|
73
|
+
// bindProjectConduit hint, triggerId) are unwrapped before calling the Feishu
|
|
74
|
+
// SDK or reading/writing the bare chat_id registry. This lets multiple platform
|
|
75
|
+
// adapters coexist behind CompositeAdapter.
|
|
76
|
+
static PREFIX = 'feishu:';
|
|
77
|
+
/** Add the `feishu:` prefix (idempotent; passes through empty strings). */
|
|
78
|
+
_wrap(bare) {
|
|
79
|
+
if (!bare)
|
|
80
|
+
return bare;
|
|
81
|
+
return bare.startsWith(FeishuAdapter.PREFIX) ? bare : FeishuAdapter.PREFIX + bare;
|
|
82
|
+
}
|
|
83
|
+
/** Strip the `feishu:` prefix (tolerates already-bare values for back-compat). */
|
|
84
|
+
_unwrap(prefixed) {
|
|
85
|
+
if (!prefixed)
|
|
86
|
+
return prefixed;
|
|
87
|
+
return prefixed.startsWith(FeishuAdapter.PREFIX)
|
|
88
|
+
? prefixed.slice(FeishuAdapter.PREFIX.length)
|
|
89
|
+
: prefixed;
|
|
90
|
+
}
|
|
91
|
+
/** True if this conduit belongs to the Feishu adapter. */
|
|
92
|
+
ownsConduit(conduit) {
|
|
93
|
+
return conduit.startsWith(FeishuAdapter.PREFIX);
|
|
66
94
|
}
|
|
67
95
|
// --- Lifecycle ---
|
|
68
96
|
async start() {
|
|
97
|
+
// Construct the WSClient here (not in the constructor): it opens a libuv
|
|
98
|
+
// handle on creation, so deferring it until start() keeps adapter
|
|
99
|
+
// instantiation side-effect-free (see wsClient field comment).
|
|
100
|
+
this.wsClient = new lark.WSClient({
|
|
101
|
+
appId: this.config.appId,
|
|
102
|
+
appSecret: this.config.appSecret,
|
|
103
|
+
domain: this.domain,
|
|
104
|
+
loggerLevel: lark.LoggerLevel.info,
|
|
105
|
+
});
|
|
69
106
|
await this.wsClient.start({
|
|
70
107
|
eventDispatcher: this.eventDispatcher,
|
|
71
108
|
});
|
|
72
109
|
}
|
|
73
110
|
async stop() {
|
|
74
|
-
this.wsClient
|
|
111
|
+
this.wsClient?.close();
|
|
112
|
+
this.wsClient = null;
|
|
75
113
|
}
|
|
76
114
|
// --- Event registration ---
|
|
77
115
|
onMessage(handler) {
|
|
@@ -90,12 +128,12 @@ export class FeishuAdapter {
|
|
|
90
128
|
async postMessage(destination, content, opts) {
|
|
91
129
|
const resolved = await this.resolveDestination(destination);
|
|
92
130
|
if (!resolved.channel) {
|
|
93
|
-
return {
|
|
131
|
+
return { conduit: '', messageId: '' };
|
|
94
132
|
}
|
|
95
133
|
const threadId = opts?.threadId;
|
|
96
134
|
// If replying in a thread, use the reply API
|
|
97
135
|
if (threadId) {
|
|
98
|
-
return this.replyInThread(threadId, content);
|
|
136
|
+
return this.replyInThread(threadId, content, resolved.channel);
|
|
99
137
|
}
|
|
100
138
|
const { msgType, msgContent } = this.buildMessagePayload(content);
|
|
101
139
|
const res = await this.client.im.v1.message.create({
|
|
@@ -107,7 +145,7 @@ export class FeishuAdapter {
|
|
|
107
145
|
},
|
|
108
146
|
});
|
|
109
147
|
const messageId = res?.data?.message_id || '';
|
|
110
|
-
return {
|
|
148
|
+
return { conduit: this._wrap(resolved.channel), messageId };
|
|
111
149
|
}
|
|
112
150
|
async updateMessage(ref, content) {
|
|
113
151
|
// Feishu only supports updating interactive (card) messages via PATCH.
|
|
@@ -126,34 +164,53 @@ export class FeishuAdapter {
|
|
|
126
164
|
async postInteractive(destination, content, opts) {
|
|
127
165
|
const resolved = await this.resolveDestination(destination);
|
|
128
166
|
if (!resolved.channel) {
|
|
129
|
-
return {
|
|
167
|
+
return { conduit: '', messageId: '' };
|
|
130
168
|
}
|
|
131
169
|
const elements = content.richBlocks
|
|
132
170
|
? this.richBlocksToFeishuElements(content.richBlocks)
|
|
133
171
|
: [];
|
|
134
|
-
// Add action buttons
|
|
135
|
-
elements.push(
|
|
136
|
-
tag: 'action',
|
|
137
|
-
actions: content.actions.map(a => this.actionElementToFeishu(a)),
|
|
138
|
-
});
|
|
172
|
+
// Add action buttons (schema 2.0: column_set, not the removed `action` tag).
|
|
173
|
+
elements.push(this.buttonsToColumnSet(content.actions));
|
|
139
174
|
const cardJson = {
|
|
140
175
|
schema: '2.0',
|
|
141
176
|
header: {
|
|
142
177
|
title: { tag: 'plain_text', content: content.text },
|
|
143
178
|
},
|
|
144
179
|
body: { elements },
|
|
180
|
+
// Shared card: lets server-side PATCH updates (e.g. "Plan approved") persist
|
|
181
|
+
// for all viewers after a button click. Without this Feishu treats the card as
|
|
182
|
+
// independent and rolls the UI back to its original state after the callback.
|
|
183
|
+
config: {
|
|
184
|
+
update_multi: true,
|
|
185
|
+
},
|
|
145
186
|
};
|
|
146
187
|
const threadId = opts?.threadId;
|
|
147
188
|
if (threadId) {
|
|
148
|
-
const
|
|
189
|
+
const cardContent = JSON.stringify(cardJson);
|
|
190
|
+
// reply_in_thread:true collects the card into a real Feishu 话题 thread (matching
|
|
191
|
+
// postMessage/replyInThread). Without it Feishu posts an inline quoted reply in the
|
|
192
|
+
// main timeline, so the card never lands inside the topic. Some chats reject thread
|
|
193
|
+
// replies (230071/230072) — fall back to a plain reply so the card is never lost.
|
|
194
|
+
const reply = (replyInThread) => this.client.im.v1.message.reply({
|
|
149
195
|
path: { message_id: threadId },
|
|
150
|
-
data: {
|
|
151
|
-
msg_type: 'interactive',
|
|
152
|
-
content: JSON.stringify(cardJson),
|
|
153
|
-
},
|
|
196
|
+
data: { msg_type: 'interactive', content: cardContent, reply_in_thread: replyInThread },
|
|
154
197
|
});
|
|
198
|
+
let res;
|
|
199
|
+
try {
|
|
200
|
+
res = await reply(true);
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
const code = e?.response?.data?.code;
|
|
204
|
+
if (code === 230071 || code === 230072) {
|
|
205
|
+
log.warn(`Feishu chat rejects thread replies (code ${code}); falling back to plain reply`);
|
|
206
|
+
res = await reply(false);
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
throw e;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
155
212
|
const messageId = res?.data?.message_id || '';
|
|
156
|
-
return {
|
|
213
|
+
return { conduit: this._wrap(resolved.channel), messageId, threadId };
|
|
157
214
|
}
|
|
158
215
|
const res = await this.client.im.v1.message.create({
|
|
159
216
|
params: { receive_id_type: 'chat_id' },
|
|
@@ -164,12 +221,12 @@ export class FeishuAdapter {
|
|
|
164
221
|
},
|
|
165
222
|
});
|
|
166
223
|
const messageId = res?.data?.message_id || '';
|
|
167
|
-
return {
|
|
224
|
+
return { conduit: this._wrap(resolved.channel), messageId };
|
|
168
225
|
}
|
|
169
226
|
async openModal(triggerId, modal) {
|
|
170
227
|
// Feishu has no native modal. Degrade to posting a card with an embedded
|
|
171
|
-
// form container to the channel. triggerId format: "chatId:messageId"
|
|
172
|
-
const [channel] = triggerId.split(':');
|
|
228
|
+
// form container to the channel. triggerId format: "feishu:chatId:messageId"
|
|
229
|
+
const [channel] = this._unwrap(triggerId).split(':');
|
|
173
230
|
if (!channel)
|
|
174
231
|
return;
|
|
175
232
|
const cardJson = this.modalToFeishuCard(modal);
|
|
@@ -182,25 +239,31 @@ export class FeishuAdapter {
|
|
|
182
239
|
},
|
|
183
240
|
});
|
|
184
241
|
}
|
|
185
|
-
// ---
|
|
186
|
-
async
|
|
242
|
+
// --- Queue backpressure ---
|
|
243
|
+
async _addHourglassReaction(ref) {
|
|
187
244
|
try {
|
|
188
245
|
await this.client.im.v1.messageReaction.create({
|
|
189
246
|
path: { message_id: ref.messageId },
|
|
190
|
-
|
|
247
|
+
// Feishu has no 'hourglass' emoji_type (err 231001 "reaction type is
|
|
248
|
+
// invalid"). 'OnIt' (处理中) is a valid type and the right semantic fit
|
|
249
|
+
// for a "queued / working on it" indicator.
|
|
250
|
+
data: { reaction_type: { emoji_type: 'OnIt' } },
|
|
191
251
|
});
|
|
192
252
|
}
|
|
193
253
|
catch {
|
|
194
254
|
// Best-effort: emoji name may not map to Feishu's emoji set
|
|
195
255
|
}
|
|
196
256
|
}
|
|
257
|
+
async markQueued(ref) {
|
|
258
|
+
await this._addHourglassReaction(ref);
|
|
259
|
+
}
|
|
197
260
|
// --- Files ---
|
|
198
261
|
async uploadFile(destination, filePath, opts) {
|
|
199
262
|
const destResolved = await this.resolveDestination(destination);
|
|
200
263
|
if (!destResolved.channel) {
|
|
201
264
|
return;
|
|
202
265
|
}
|
|
203
|
-
const { resolved: fileResolved
|
|
266
|
+
const { resolved: fileResolved } = this.resolveFilePath(filePath);
|
|
204
267
|
const fileName = opts?.filename || path.basename(fileResolved);
|
|
205
268
|
// Upload file to get file_key
|
|
206
269
|
const uploadRes = await this.client.im.v1.file.create({
|
|
@@ -234,11 +297,26 @@ export class FeishuAdapter {
|
|
|
234
297
|
}
|
|
235
298
|
}
|
|
236
299
|
async downloadFile(fileRef, destDir) {
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
300
|
+
const raw = fileRef.raw || {};
|
|
301
|
+
const messageId = raw.message_id;
|
|
302
|
+
const type = raw.resourceType === 'image' ? 'image' : 'file';
|
|
240
303
|
const ext = path.extname(fileRef.name) || '';
|
|
241
304
|
const localPath = path.join(destDir, `${fileRef.id}${ext}`);
|
|
305
|
+
// Message attachments must be fetched via messageResource.get (requires the
|
|
306
|
+
// owning message_id + a resource type). im.v1.file.get only works for files
|
|
307
|
+
// we uploaded ourselves, so it's a last-resort fallback when message_id is
|
|
308
|
+
// somehow missing.
|
|
309
|
+
let resp;
|
|
310
|
+
if (messageId) {
|
|
311
|
+
resp = await this.client.im.v1.messageResource.get({
|
|
312
|
+
path: { message_id: messageId, file_key: fileRef.id },
|
|
313
|
+
params: { type },
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
else {
|
|
317
|
+
log.warn(`downloadFile: no message_id on fileRef "${fileRef.id}"; falling back to file.get`);
|
|
318
|
+
resp = await this.client.im.v1.file.get({ path: { file_key: fileRef.id } });
|
|
319
|
+
}
|
|
242
320
|
await resp.writeFile(localPath);
|
|
243
321
|
return { localPath, mimetype: fileRef.mimetype, name: fileRef.name };
|
|
244
322
|
}
|
|
@@ -247,27 +325,35 @@ export class FeishuAdapter {
|
|
|
247
325
|
// Feishu has no public permalink API.
|
|
248
326
|
return null;
|
|
249
327
|
}
|
|
250
|
-
async postEphemeral(_channel, _userId, _text) {
|
|
251
|
-
// Feishu does not support ephemeral messages — no-op.
|
|
252
|
-
}
|
|
253
328
|
// --- Output stream ---
|
|
254
329
|
openOutputStream(destination, opts) {
|
|
255
330
|
return new FeishuOutputStream(this, destination, opts);
|
|
256
331
|
}
|
|
257
332
|
// --- Project conduit mapping (file-backed, separate file from Slack) ---
|
|
258
|
-
|
|
333
|
+
_conduitsStore = null;
|
|
334
|
+
_getConduitsStore() {
|
|
335
|
+
if (!this._conduitsStore) {
|
|
336
|
+
this._conduitsStore = new ProjectConduitsStore(path.join(STORE_DIR, 'feishu-channel-registry.json'));
|
|
337
|
+
}
|
|
338
|
+
return this._conduitsStore;
|
|
339
|
+
}
|
|
259
340
|
async bindProjectConduit(projectId, conduitHint) {
|
|
260
|
-
|
|
341
|
+
// Registry stores bare chat_ids; strip the prefix before persisting.
|
|
342
|
+
await this._getConduitsStore().set(projectId, this._unwrap(conduitHint));
|
|
261
343
|
}
|
|
262
344
|
async unbindProjectConduit(projectId) {
|
|
263
|
-
|
|
345
|
+
await this._getConduitsStore().remove(projectId);
|
|
264
346
|
}
|
|
265
347
|
async getProjectConduits() {
|
|
266
|
-
|
|
348
|
+
// Registry stores bare chat_ids; expose prefixed conduits externally.
|
|
349
|
+
const all = await this._getConduitsStore().getAll();
|
|
350
|
+
return Object.fromEntries(Object.entries(all).map(([project, ch]) => [project, this._wrap(ch)]));
|
|
267
351
|
}
|
|
268
352
|
async resolveInboundProject(conduit) {
|
|
269
|
-
|
|
270
|
-
|
|
353
|
+
const bare = this._unwrap(conduit);
|
|
354
|
+
const conduits = await this._getConduitsStore().getAll();
|
|
355
|
+
for (const [project, ch] of Object.entries(conduits)) {
|
|
356
|
+
if (ch === bare)
|
|
271
357
|
return project;
|
|
272
358
|
}
|
|
273
359
|
return null;
|
|
@@ -280,11 +366,24 @@ export class FeishuAdapter {
|
|
|
280
366
|
async resolveDestination(dest) {
|
|
281
367
|
switch (dest.type) {
|
|
282
368
|
case 'interactive-reply':
|
|
283
|
-
return { channel: dest.conduit, kind: 'interactive-reply' };
|
|
284
|
-
case 'project-report':
|
|
285
|
-
//
|
|
286
|
-
//
|
|
287
|
-
|
|
369
|
+
return { channel: this._unwrap(dest.conduit), kind: 'interactive-reply' };
|
|
370
|
+
case 'project-report': {
|
|
371
|
+
// Read bare chat_ids directly from the store (getProjectConduits wraps
|
|
372
|
+
// for external callers; the SDK needs the bare chat_id).
|
|
373
|
+
const channel = await this._getConduitsStore().get(dest.projectId);
|
|
374
|
+
if (channel) {
|
|
375
|
+
return { channel, kind: 'project-report' };
|
|
376
|
+
}
|
|
377
|
+
// Unbound project: fall back to this platform's admin DM so the report
|
|
378
|
+
// still surfaces here instead of being silently dropped. Each platform
|
|
379
|
+
// falls back independently (a project bound on another platform but not
|
|
380
|
+
// this one still reaches this platform's DM).
|
|
381
|
+
if (this.config.adminChannel) {
|
|
382
|
+
return { channel: this.config.adminChannel, kind: 'project-report-dm' };
|
|
383
|
+
}
|
|
384
|
+
log.warn(`No conduit or admin channel for project "${dest.projectId}"; dropping project-report`);
|
|
385
|
+
return { channel: null, kind: 'project-report-noop' };
|
|
386
|
+
}
|
|
288
387
|
case 'system-notice':
|
|
289
388
|
if (!this.config.adminChannel) {
|
|
290
389
|
log.warn('No admin channel configured; dropping system-notice');
|
|
@@ -298,6 +397,34 @@ export class FeishuAdapter {
|
|
|
298
397
|
// =========================================================================
|
|
299
398
|
// Internal: Inbound event handlers
|
|
300
399
|
// =========================================================================
|
|
400
|
+
/**
|
|
401
|
+
* Upsert FEISHU_ADMIN_CHANNEL=<chatId> into <CONFIG_DIR>/.env so the detected
|
|
402
|
+
* admin DM survives restarts. Mirrors SlackAdapter._persistAdminChannel.
|
|
403
|
+
*/
|
|
404
|
+
async _persistAdminChannel(chatId) {
|
|
405
|
+
const envPath = path.join(CONFIG_DIR, '.env');
|
|
406
|
+
let content = '';
|
|
407
|
+
try {
|
|
408
|
+
content = await fs.promises.readFile(envPath, 'utf-8');
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
// File doesn't exist yet — will be created.
|
|
412
|
+
}
|
|
413
|
+
const lines = content.split('\n');
|
|
414
|
+
let found = false;
|
|
415
|
+
for (let i = 0; i < lines.length; i++) {
|
|
416
|
+
if (lines[i].startsWith('FEISHU_ADMIN_CHANNEL=')) {
|
|
417
|
+
lines[i] = `FEISHU_ADMIN_CHANNEL=${chatId}`;
|
|
418
|
+
found = true;
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (!found)
|
|
423
|
+
lines.push(`FEISHU_ADMIN_CHANNEL=${chatId}`);
|
|
424
|
+
await fs.promises.mkdir(CONFIG_DIR, { recursive: true });
|
|
425
|
+
await fs.promises.writeFile(envPath, lines.join('\n'), 'utf-8');
|
|
426
|
+
log.info(`FEISHU_ADMIN_CHANNEL=${chatId} written to ${envPath}`);
|
|
427
|
+
}
|
|
301
428
|
async handleIncomingMessage(data) {
|
|
302
429
|
if (!this.messageHandler)
|
|
303
430
|
return;
|
|
@@ -305,49 +432,105 @@ export class FeishuAdapter {
|
|
|
305
432
|
const sender = data.sender || {};
|
|
306
433
|
const senderId = sender.sender_id?.open_id || sender.sender_id?.user_id || '';
|
|
307
434
|
const isBot = sender.sender_type === 'app';
|
|
308
|
-
// Parse message content (JSON string)
|
|
309
|
-
let text = '';
|
|
310
|
-
try {
|
|
311
|
-
const parsed = JSON.parse(message.content || '{}');
|
|
312
|
-
text = parsed.text || '';
|
|
313
|
-
}
|
|
314
|
-
catch {
|
|
315
|
-
text = message.content || '';
|
|
316
|
-
}
|
|
317
435
|
const chatId = message.chat_id || '';
|
|
318
436
|
const messageId = message.message_id || '';
|
|
319
437
|
const rootId = message.root_id || undefined;
|
|
320
438
|
const parentId = message.parent_id || undefined;
|
|
439
|
+
const messageType = message.message_type || '';
|
|
440
|
+
const chatType = message.chat_type || ''; // 'p2p' (DM) | 'group'
|
|
441
|
+
// Auto-detect the admin channel from a DM when FEISHU_ADMIN_CHANNEL is not
|
|
442
|
+
// configured. Mirrors the Slack adapter: the first p2p (DM) message from a
|
|
443
|
+
// non-bot user is registered as the admin channel, persisted to .env, and set
|
|
444
|
+
// on process.env. Feishu deliberately does NOT fall back to CORTEX_ADMIN_CHANNEL
|
|
445
|
+
// (that is a Slack channel id).
|
|
446
|
+
if (!this.config.adminChannel && !this._adminAutoDetected && chatType === 'p2p' && !isBot && chatId) {
|
|
447
|
+
this._adminAutoDetected = true;
|
|
448
|
+
this.config.adminChannel = chatId;
|
|
449
|
+
process.env.FEISHU_ADMIN_CHANNEL = chatId;
|
|
450
|
+
log.info(`Admin channel auto-detected from DM: ${chatId}`);
|
|
451
|
+
// Persist to .env and notify (fire-and-forget, non-blocking).
|
|
452
|
+
this._persistAdminChannel(chatId).catch(e => log.warn(`Failed to persist FEISHU_ADMIN_CHANNEL to .env: ${e.message}`));
|
|
453
|
+
this.postMessage({ type: 'system-notice' }, {
|
|
454
|
+
text: `👋 This DM has been auto-registered as the Cortex admin channel. \`FEISHU_ADMIN_CHANNEL=${chatId}\` has been written to \`.env\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
|
|
455
|
+
}).catch(e => log.warn(`Failed to send admin auto-detect notification: ${e.message}`));
|
|
456
|
+
}
|
|
457
|
+
// Parse message content (JSON string). For file/image/media/audio messages,
|
|
458
|
+
// the resource key (file_key/image_key) lives inside this JSON — NOT on the
|
|
459
|
+
// message object itself.
|
|
460
|
+
let parsed = {};
|
|
461
|
+
try {
|
|
462
|
+
parsed = JSON.parse(message.content || '{}');
|
|
463
|
+
}
|
|
464
|
+
catch {
|
|
465
|
+
parsed = {};
|
|
466
|
+
}
|
|
467
|
+
const text = typeof parsed.text === 'string'
|
|
468
|
+
? parsed.text
|
|
469
|
+
: (typeof message.content === 'string' && !message.content.startsWith('{') ? message.content : '');
|
|
321
470
|
const ref = {
|
|
322
|
-
|
|
471
|
+
conduit: this._wrap(chatId),
|
|
323
472
|
messageId,
|
|
324
473
|
threadId: rootId || parentId || undefined,
|
|
325
474
|
};
|
|
326
|
-
// Extract file references
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
: undefined;
|
|
475
|
+
// Extract file references from the parsed content. The id (file_key/image_key)
|
|
476
|
+
// plus message_id + resourceType are needed by downloadFile (messageResource.get).
|
|
477
|
+
const files = this.extractInboundFiles(messageType, parsed, messageId, chatId);
|
|
330
478
|
// TODO: Parse Feishu forwarded/merged messages (merge_forward msg type) into
|
|
331
479
|
// IncomingAttachment[]. Feishu's format differs from Slack's msg.attachments.
|
|
480
|
+
const kind = files ? 'file_share' : 'user';
|
|
332
481
|
const incoming = {
|
|
333
482
|
ref,
|
|
334
483
|
text,
|
|
335
484
|
senderId,
|
|
336
485
|
isBot,
|
|
337
486
|
files,
|
|
338
|
-
|
|
487
|
+
kind,
|
|
339
488
|
raw: data,
|
|
340
489
|
};
|
|
341
490
|
const adapter = this;
|
|
342
491
|
await this.messageHandler({
|
|
343
492
|
message: incoming,
|
|
344
493
|
async reply(content, replyOpts) {
|
|
345
|
-
return adapter.postMessage({ type: 'interactive-reply', conduit: ref.
|
|
494
|
+
return adapter.postMessage({ type: 'interactive-reply', conduit: ref.conduit, sessionId: '' }, content, {
|
|
346
495
|
threadId: replyOpts?.threadId || ref.threadId,
|
|
347
496
|
});
|
|
348
497
|
},
|
|
349
498
|
});
|
|
350
499
|
}
|
|
500
|
+
/**
|
|
501
|
+
* Build PlatformFileRef[] from a parsed Feishu message content payload.
|
|
502
|
+
* Feishu stores the resource key inside `content` (not on the message object):
|
|
503
|
+
* - file / media (video): { file_key, file_name? }
|
|
504
|
+
* - image: { image_key }
|
|
505
|
+
* - audio: { file_key }
|
|
506
|
+
* message_id + resourceType are stashed in `raw` so downloadFile() can call
|
|
507
|
+
* im.v1.messageResource.get (which requires both message_id and a type param).
|
|
508
|
+
*/
|
|
509
|
+
extractInboundFiles(messageType, parsed, messageId, chatId) {
|
|
510
|
+
const mk = (id, name, mimetype, resourceType) => [
|
|
511
|
+
{ id, name, mimetype, url: '', conduit: this._wrap(chatId), raw: { message_id: messageId, resourceType } },
|
|
512
|
+
];
|
|
513
|
+
switch (messageType) {
|
|
514
|
+
case 'file':
|
|
515
|
+
if (!parsed.file_key)
|
|
516
|
+
return undefined;
|
|
517
|
+
return mk(parsed.file_key, parsed.file_name || parsed.file_key, '', 'file');
|
|
518
|
+
case 'media':
|
|
519
|
+
if (!parsed.file_key)
|
|
520
|
+
return undefined;
|
|
521
|
+
return mk(parsed.file_key, parsed.file_name || `${parsed.file_key}.mp4`, 'video/mp4', 'file');
|
|
522
|
+
case 'audio':
|
|
523
|
+
if (!parsed.file_key)
|
|
524
|
+
return undefined;
|
|
525
|
+
return mk(parsed.file_key, `${parsed.file_key}.opus`, 'audio/opus', 'file');
|
|
526
|
+
case 'image':
|
|
527
|
+
if (!parsed.image_key)
|
|
528
|
+
return undefined;
|
|
529
|
+
return mk(parsed.image_key, `${parsed.image_key}.png`, 'image/png', 'image');
|
|
530
|
+
default:
|
|
531
|
+
return undefined;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
351
534
|
async handleCardAction(data) {
|
|
352
535
|
const event = data.event || data;
|
|
353
536
|
const action = event.action || {};
|
|
@@ -364,15 +547,13 @@ export class FeishuAdapter {
|
|
|
364
547
|
const handler = this.modalHandlers.get(formName);
|
|
365
548
|
if (handler) {
|
|
366
549
|
const normalizedValues = this.normalizeFormValues(action.form_value);
|
|
367
|
-
let ackCalled = false;
|
|
368
550
|
await handler({
|
|
369
551
|
callbackId: formName,
|
|
370
552
|
privateMetadata: JSON.stringify(action.value || {}),
|
|
371
553
|
values: normalizedValues,
|
|
372
554
|
userId,
|
|
373
555
|
async ack(_response) {
|
|
374
|
-
|
|
375
|
-
// Feishu ack is implicit via response — nothing to do
|
|
556
|
+
// Feishu ack is implicit via the callback return value — nothing to do.
|
|
376
557
|
},
|
|
377
558
|
});
|
|
378
559
|
// Return toast or updated card if needed
|
|
@@ -389,10 +570,10 @@ export class FeishuAdapter {
|
|
|
389
570
|
await handler({
|
|
390
571
|
actionId,
|
|
391
572
|
value: typeof actionValue === 'string' ? actionValue : JSON.stringify(actionValue),
|
|
392
|
-
triggerId: `${chatId}:${messageId}
|
|
393
|
-
messageRef: messageId ? {
|
|
573
|
+
triggerId: this._wrap(`${chatId}:${messageId}`),
|
|
574
|
+
messageRef: messageId ? { conduit: this._wrap(chatId), messageId } : undefined,
|
|
394
575
|
userId,
|
|
395
|
-
channelId: chatId,
|
|
576
|
+
channelId: this._wrap(chatId),
|
|
396
577
|
});
|
|
397
578
|
return { toast: { type: 'success', content: 'OK' } };
|
|
398
579
|
}
|
|
@@ -402,11 +583,11 @@ export class FeishuAdapter {
|
|
|
402
583
|
// Internal: Outbound converters
|
|
403
584
|
// =========================================================================
|
|
404
585
|
buildMessagePayload(content) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
return { msgType: '
|
|
586
|
+
// Always send an interactive card. For text-only content buildCardJson emits a
|
|
587
|
+
// `markdown` element, so agent markdown (bold, lists, code blocks, tables,
|
|
588
|
+
// links) renders in Feishu instead of showing as raw text. Plain `msg_type:text`
|
|
589
|
+
// does not render markdown at all.
|
|
590
|
+
return { msgType: 'interactive', msgContent: JSON.stringify(this.buildCardJson(content)) };
|
|
410
591
|
}
|
|
411
592
|
buildCardJson(content) {
|
|
412
593
|
const elements = content.richBlocks
|
|
@@ -415,19 +596,40 @@ export class FeishuAdapter {
|
|
|
415
596
|
return {
|
|
416
597
|
schema: '2.0',
|
|
417
598
|
body: { elements },
|
|
599
|
+
// Keep cards shareable/updatable so post-interaction PATCH updates persist
|
|
600
|
+
// instead of being rolled back by the Feishu client.
|
|
601
|
+
config: {
|
|
602
|
+
update_multi: true,
|
|
603
|
+
},
|
|
418
604
|
};
|
|
419
605
|
}
|
|
420
|
-
async replyInThread(threadMessageId, content) {
|
|
606
|
+
async replyInThread(threadMessageId, content, conduit) {
|
|
421
607
|
const { msgType, msgContent } = this.buildMessagePayload(content);
|
|
422
|
-
|
|
608
|
+
// reply_in_thread:true collects replies into a real Feishu 话题 thread (Slack-
|
|
609
|
+
// style: first message in channel, the rest under it) instead of inline quoted
|
|
610
|
+
// replies in the main timeline. Some chats reject thread replies (err 230071 /
|
|
611
|
+
// 230072 — group disallows / aggregated message); fall back to a plain reply so
|
|
612
|
+
// output is never lost.
|
|
613
|
+
const reply = (replyInThread) => this.client.im.v1.message.reply({
|
|
423
614
|
path: { message_id: threadMessageId },
|
|
424
|
-
data: {
|
|
425
|
-
msg_type: msgType,
|
|
426
|
-
content: msgContent,
|
|
427
|
-
},
|
|
615
|
+
data: { msg_type: msgType, content: msgContent, reply_in_thread: replyInThread },
|
|
428
616
|
});
|
|
617
|
+
let res;
|
|
618
|
+
try {
|
|
619
|
+
res = await reply(true);
|
|
620
|
+
}
|
|
621
|
+
catch (e) {
|
|
622
|
+
const code = e?.response?.data?.code;
|
|
623
|
+
if (code === 230071 || code === 230072) {
|
|
624
|
+
log.warn(`Feishu chat rejects thread replies (code ${code}); falling back to plain reply`);
|
|
625
|
+
res = await reply(false);
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
throw e;
|
|
629
|
+
}
|
|
630
|
+
}
|
|
429
631
|
const messageId = res?.data?.message_id || '';
|
|
430
|
-
return {
|
|
632
|
+
return { conduit: this._wrap(conduit), messageId, threadId: threadMessageId };
|
|
431
633
|
}
|
|
432
634
|
/** Convert RichBlock[] to Feishu card schema 2.0 elements. */
|
|
433
635
|
richBlocksToFeishuElements(blocks) {
|
|
@@ -444,30 +646,54 @@ export class FeishuAdapter {
|
|
|
444
646
|
},
|
|
445
647
|
};
|
|
446
648
|
case 'context':
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
};
|
|
649
|
+
// Feishu card schema 2.0 removed the `note` tag (err 200861
|
|
650
|
+
// "unsupported tag note"). Render context text as a markdown element.
|
|
651
|
+
return { tag: 'markdown', content: block.text };
|
|
451
652
|
case 'divider':
|
|
452
653
|
return { tag: 'hr' };
|
|
453
654
|
case 'actions':
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
actions: block.elements.map(e => this.actionElementToFeishu(e)),
|
|
457
|
-
};
|
|
655
|
+
// Schema 2.0: no `action` container — render buttons via column_set.
|
|
656
|
+
return this.buttonsToColumnSet(block.elements);
|
|
458
657
|
default:
|
|
459
658
|
return { tag: 'markdown', content: block.text || '' };
|
|
460
659
|
}
|
|
461
660
|
});
|
|
462
661
|
}
|
|
463
|
-
/**
|
|
662
|
+
/**
|
|
663
|
+
* Convert a ButtonElement to a Feishu card **schema 2.0** button.
|
|
664
|
+
*
|
|
665
|
+
* Card 2.0 buttons carry their interaction in a `behaviors` callback (the old
|
|
666
|
+
* top-level `value` field is form-only in 2.0). `name` is preserved so
|
|
667
|
+
* handleCardAction's `action.name` lookup keeps working; the callback `value`
|
|
668
|
+
* delivers `{ actionId, value }`, which arrives as `event.action.value`.
|
|
669
|
+
*/
|
|
464
670
|
actionElementToFeishu(el) {
|
|
465
671
|
return {
|
|
466
672
|
tag: 'button',
|
|
467
673
|
text: { tag: 'plain_text', content: el.text },
|
|
468
674
|
type: el.style === 'danger' ? 'danger' : el.style === 'primary' ? 'primary' : 'default',
|
|
469
675
|
name: el.actionId,
|
|
470
|
-
value: { actionId: el.actionId, value: el.value },
|
|
676
|
+
behaviors: [{ type: 'callback', value: { actionId: el.actionId, value: el.value } }],
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Lay buttons out as a wrapping `column_set` (one auto-width column per button).
|
|
681
|
+
* Feishu card schema 2.0 removed the `action` container tag (error 200861:
|
|
682
|
+
* "unsupported tag action"), so buttons must be direct body elements.
|
|
683
|
+
* `flex_mode: 'flow'` + per-column `width: 'auto'` makes the buttons size to
|
|
684
|
+
* their text and wrap onto multiple rows — without `flow` many buttons get
|
|
685
|
+
* crushed into one unreadable row.
|
|
686
|
+
*/
|
|
687
|
+
buttonsToColumnSet(elements) {
|
|
688
|
+
return {
|
|
689
|
+
tag: 'column_set',
|
|
690
|
+
flex_mode: 'flow',
|
|
691
|
+
horizontal_spacing: '8px',
|
|
692
|
+
columns: elements.map(e => ({
|
|
693
|
+
tag: 'column',
|
|
694
|
+
width: 'auto',
|
|
695
|
+
elements: [this.actionElementToFeishu(e)],
|
|
696
|
+
})),
|
|
471
697
|
};
|
|
472
698
|
}
|
|
473
699
|
/**
|
|
@@ -488,7 +714,7 @@ export class FeishuAdapter {
|
|
|
488
714
|
case 'select':
|
|
489
715
|
formElements.push({
|
|
490
716
|
tag: 'select_static',
|
|
491
|
-
name: `${field.blockId}::${field.actionId}`,
|
|
717
|
+
name: `${field.blockId}::${field.actionId}::select`,
|
|
492
718
|
placeholder: field.placeholder
|
|
493
719
|
? { tag: 'plain_text', content: field.placeholder }
|
|
494
720
|
: undefined,
|
|
@@ -501,7 +727,7 @@ export class FeishuAdapter {
|
|
|
501
727
|
case 'multi_select':
|
|
502
728
|
formElements.push({
|
|
503
729
|
tag: 'multi_select_static',
|
|
504
|
-
name: `${field.blockId}::${field.actionId}`,
|
|
730
|
+
name: `${field.blockId}::${field.actionId}::multi`,
|
|
505
731
|
placeholder: field.placeholder
|
|
506
732
|
? { tag: 'plain_text', content: field.placeholder }
|
|
507
733
|
: undefined,
|
|
@@ -514,7 +740,7 @@ export class FeishuAdapter {
|
|
|
514
740
|
case 'text_input':
|
|
515
741
|
formElements.push({
|
|
516
742
|
tag: 'input',
|
|
517
|
-
name: `${field.blockId}::${field.actionId}`,
|
|
743
|
+
name: `${field.blockId}::${field.actionId}::text`,
|
|
518
744
|
placeholder: field.placeholder
|
|
519
745
|
? { tag: 'plain_text', content: field.placeholder }
|
|
520
746
|
: undefined,
|
|
@@ -522,13 +748,36 @@ export class FeishuAdapter {
|
|
|
522
748
|
break;
|
|
523
749
|
}
|
|
524
750
|
}
|
|
525
|
-
// Add submit button inside form
|
|
751
|
+
// Add submit button inside form.
|
|
752
|
+
// The button's `name` is what arrives as `event.action.name` in the
|
|
753
|
+
// card.action.trigger callback — handleCardAction uses it to look up the
|
|
754
|
+
// modal handler, which is registered under modal.callbackId. So the button
|
|
755
|
+
// name MUST equal callbackId (not a literal "submit"), otherwise the
|
|
756
|
+
// submission is silently dropped.
|
|
757
|
+
//
|
|
758
|
+
// The button's `value` arrives as `event.action.value` and becomes
|
|
759
|
+
// privateMetadata in handleCardAction. It MUST carry modal.privateMetadata
|
|
760
|
+
// (e.g. { groupId } for AskUserQuestion) — without it the modal handler has
|
|
761
|
+
// no context to resolve the submission. NOTE: `behaviors` and
|
|
762
|
+
// `action_type:'form_submit'` are mutually exclusive in Feishu card 2.0
|
|
763
|
+
// (adding behaviors makes Feishu no longer recognise the submit button), so
|
|
764
|
+
// the metadata must travel via the top-level `value` field, not a callback.
|
|
765
|
+
let submitValue;
|
|
766
|
+
if (modal.privateMetadata) {
|
|
767
|
+
try {
|
|
768
|
+
submitValue = JSON.parse(modal.privateMetadata);
|
|
769
|
+
}
|
|
770
|
+
catch {
|
|
771
|
+
submitValue = undefined;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
526
774
|
formElements.push({
|
|
527
775
|
tag: 'button',
|
|
528
776
|
text: { tag: 'plain_text', content: modal.submitLabel || 'Submit' },
|
|
529
777
|
type: 'primary',
|
|
530
|
-
name:
|
|
778
|
+
name: modal.callbackId,
|
|
531
779
|
action_type: 'form_submit',
|
|
780
|
+
...(submitValue ? { value: submitValue } : {}),
|
|
532
781
|
});
|
|
533
782
|
return {
|
|
534
783
|
schema: '2.0',
|
|
@@ -538,7 +787,11 @@ export class FeishuAdapter {
|
|
|
538
787
|
body: {
|
|
539
788
|
elements: [{
|
|
540
789
|
tag: 'form',
|
|
541
|
-
name
|
|
790
|
+
// Feishu requires every `name` in a card to be unique. The submit button
|
|
791
|
+
// already uses modal.callbackId (it must — that arrives as
|
|
792
|
+
// event.action.name), so the form container needs a distinct name or
|
|
793
|
+
// Feishu rejects the card (err 11310: "name duplicate").
|
|
794
|
+
name: `${modal.callbackId}__form`,
|
|
542
795
|
elements: formElements,
|
|
543
796
|
}],
|
|
544
797
|
},
|
|
@@ -549,37 +802,38 @@ export class FeishuAdapter {
|
|
|
549
802
|
}
|
|
550
803
|
/**
|
|
551
804
|
* Normalize Feishu form_value into the platform-agnostic ModalFieldValue format.
|
|
552
|
-
* Feishu form_value is a flat dict { field_name: value }
|
|
805
|
+
* Feishu form_value is a flat dict { field_name: value } where field_name follows
|
|
806
|
+
* our convention "{blockId}::{actionId}::{kind}" (kind ∈ select | multi | text).
|
|
807
|
+
* The kind segment is what lets us map a single-select (a bare string) to
|
|
808
|
+
* `selectedOption` rather than `value` — the downstream consumer
|
|
809
|
+
* (interaction-handlers.ts) reads `selectedOption.value` for single-select.
|
|
553
810
|
* We reconstruct the two-level { blockId: { actionId: ModalFieldValue } } structure.
|
|
554
811
|
*/
|
|
555
812
|
normalizeFormValues(formValue) {
|
|
556
813
|
const normalized = {};
|
|
557
814
|
for (const [fieldName, rawValue] of Object.entries(formValue)) {
|
|
558
|
-
|
|
559
|
-
const
|
|
560
|
-
const
|
|
561
|
-
const
|
|
815
|
+
const parts = fieldName.split('::');
|
|
816
|
+
const blockId = parts[0] ?? fieldName;
|
|
817
|
+
const actionId = parts[1] ?? fieldName;
|
|
818
|
+
const kind = parts[2]; // select | multi | text | undefined
|
|
562
819
|
if (!normalized[blockId])
|
|
563
820
|
normalized[blockId] = {};
|
|
564
|
-
if (Array.isArray(rawValue)) {
|
|
821
|
+
if (kind === 'multi' || Array.isArray(rawValue)) {
|
|
565
822
|
// Multi-select: array of selected values
|
|
823
|
+
const arr = Array.isArray(rawValue) ? rawValue : [rawValue];
|
|
566
824
|
normalized[blockId][actionId] = {
|
|
567
|
-
selectedOptions:
|
|
825
|
+
selectedOptions: arr.map(v => ({ value: String(v) })),
|
|
568
826
|
};
|
|
569
827
|
}
|
|
570
|
-
else if (
|
|
571
|
-
//
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
else if (rawValue && typeof rawValue === 'object') {
|
|
577
|
-
// Selected option object
|
|
578
|
-
normalized[blockId][actionId] = {
|
|
579
|
-
selectedOption: { value: String(rawValue.value || rawValue) },
|
|
580
|
-
};
|
|
828
|
+
else if (kind === 'select') {
|
|
829
|
+
// Single-select: Feishu sends the option value as a bare string
|
|
830
|
+
const value = rawValue && typeof rawValue === 'object'
|
|
831
|
+
? String(rawValue.value ?? '')
|
|
832
|
+
: String(rawValue ?? '');
|
|
833
|
+
normalized[blockId][actionId] = { selectedOption: { value } };
|
|
581
834
|
}
|
|
582
835
|
else {
|
|
836
|
+
// Text input (or unknown): plain string value
|
|
583
837
|
normalized[blockId][actionId] = { value: String(rawValue ?? '') };
|
|
584
838
|
}
|
|
585
839
|
}
|