@nextclaw/channel-plugin-feishu 0.2.13 → 0.2.15

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.
Files changed (120) hide show
  1. package/README.md +3 -1
  2. package/index.ts +65 -0
  3. package/openclaw.plugin.json +3 -7
  4. package/package.json +32 -9
  5. package/skills/feishu-doc/SKILL.md +211 -0
  6. package/skills/feishu-doc/references/block-types.md +103 -0
  7. package/skills/feishu-drive/SKILL.md +97 -0
  8. package/skills/feishu-perm/SKILL.md +119 -0
  9. package/skills/feishu-wiki/SKILL.md +111 -0
  10. package/src/accounts.test.ts +371 -0
  11. package/src/accounts.ts +244 -0
  12. package/src/async.ts +62 -0
  13. package/src/bitable.ts +725 -0
  14. package/src/bot.card-action.test.ts +63 -0
  15. package/src/bot.checkBotMentioned.test.ts +193 -0
  16. package/src/bot.stripBotMention.test.ts +134 -0
  17. package/src/bot.test.ts +2107 -0
  18. package/src/bot.ts +1556 -0
  19. package/src/card-action.ts +79 -0
  20. package/src/channel.test.ts +48 -0
  21. package/src/channel.ts +369 -0
  22. package/src/chat-schema.ts +24 -0
  23. package/src/chat.test.ts +89 -0
  24. package/src/chat.ts +130 -0
  25. package/src/client.test.ts +324 -0
  26. package/src/client.ts +196 -0
  27. package/src/config-schema.test.ts +247 -0
  28. package/src/config-schema.ts +306 -0
  29. package/src/dedup.ts +203 -0
  30. package/src/directory.test.ts +40 -0
  31. package/src/directory.ts +156 -0
  32. package/src/doc-schema.ts +182 -0
  33. package/src/docx-batch-insert.test.ts +90 -0
  34. package/src/docx-batch-insert.ts +187 -0
  35. package/src/docx-color-text.ts +149 -0
  36. package/src/docx-table-ops.ts +298 -0
  37. package/src/docx.account-selection.test.ts +70 -0
  38. package/src/docx.test.ts +445 -0
  39. package/src/docx.ts +1460 -0
  40. package/src/drive-schema.ts +46 -0
  41. package/src/drive.ts +228 -0
  42. package/src/dynamic-agent.ts +131 -0
  43. package/src/external-keys.test.ts +20 -0
  44. package/src/external-keys.ts +19 -0
  45. package/src/feishu-command-handler.ts +59 -0
  46. package/src/media.test.ts +523 -0
  47. package/src/media.ts +484 -0
  48. package/src/mention.ts +133 -0
  49. package/src/monitor.account.ts +562 -0
  50. package/src/monitor.reaction.test.ts +653 -0
  51. package/src/monitor.startup.test.ts +190 -0
  52. package/src/monitor.startup.ts +64 -0
  53. package/src/monitor.state.defaults.test.ts +46 -0
  54. package/src/monitor.state.ts +155 -0
  55. package/src/monitor.test-mocks.ts +45 -0
  56. package/src/monitor.transport.ts +264 -0
  57. package/src/monitor.ts +95 -0
  58. package/src/monitor.webhook-e2e.test.ts +214 -0
  59. package/src/monitor.webhook-security.test.ts +142 -0
  60. package/src/monitor.webhook.test-helpers.ts +98 -0
  61. package/src/nextclaw-sdk/account-id.ts +31 -0
  62. package/src/nextclaw-sdk/compat.ts +8 -0
  63. package/src/nextclaw-sdk/core-channel.ts +296 -0
  64. package/src/nextclaw-sdk/core-pairing.ts +224 -0
  65. package/src/nextclaw-sdk/core.ts +26 -0
  66. package/src/nextclaw-sdk/dedupe.ts +246 -0
  67. package/src/nextclaw-sdk/feishu.ts +77 -0
  68. package/src/nextclaw-sdk/history.ts +127 -0
  69. package/src/nextclaw-sdk/network-body.ts +245 -0
  70. package/src/nextclaw-sdk/network-fetch.ts +129 -0
  71. package/src/nextclaw-sdk/network-webhook.ts +182 -0
  72. package/src/nextclaw-sdk/network.ts +13 -0
  73. package/src/nextclaw-sdk/runtime-store.ts +26 -0
  74. package/src/nextclaw-sdk/secrets-config.ts +109 -0
  75. package/src/nextclaw-sdk/secrets-core.ts +170 -0
  76. package/src/nextclaw-sdk/secrets-prompt.ts +305 -0
  77. package/src/nextclaw-sdk/secrets.ts +18 -0
  78. package/src/nextclaw-sdk/types.ts +300 -0
  79. package/src/onboarding.status.test.ts +25 -0
  80. package/src/onboarding.test.ts +143 -0
  81. package/src/onboarding.ts +489 -0
  82. package/src/outbound.test.ts +356 -0
  83. package/src/outbound.ts +176 -0
  84. package/src/perm-schema.ts +52 -0
  85. package/src/perm.ts +176 -0
  86. package/src/policy.test.ts +154 -0
  87. package/src/policy.ts +123 -0
  88. package/src/post.test.ts +105 -0
  89. package/src/post.ts +274 -0
  90. package/src/probe.test.ts +270 -0
  91. package/src/probe.ts +156 -0
  92. package/src/reactions.ts +153 -0
  93. package/src/reply-dispatcher.test.ts +513 -0
  94. package/src/reply-dispatcher.ts +397 -0
  95. package/src/runtime.ts +6 -0
  96. package/src/secret-input.ts +13 -0
  97. package/src/send-message.ts +71 -0
  98. package/src/send-result.ts +29 -0
  99. package/src/send-target.test.ts +74 -0
  100. package/src/send-target.ts +29 -0
  101. package/src/send.reply-fallback.test.ts +189 -0
  102. package/src/send.test.ts +168 -0
  103. package/src/send.ts +481 -0
  104. package/src/streaming-card.test.ts +54 -0
  105. package/src/streaming-card.ts +374 -0
  106. package/src/targets.test.ts +70 -0
  107. package/src/targets.ts +107 -0
  108. package/src/tool-account-routing.test.ts +129 -0
  109. package/src/tool-account.ts +70 -0
  110. package/src/tool-factory-test-harness.ts +76 -0
  111. package/src/tool-result.test.ts +32 -0
  112. package/src/tool-result.ts +14 -0
  113. package/src/tools-config.test.ts +21 -0
  114. package/src/tools-config.ts +22 -0
  115. package/src/types.ts +103 -0
  116. package/src/typing.test.ts +144 -0
  117. package/src/typing.ts +210 -0
  118. package/src/wiki-schema.ts +55 -0
  119. package/src/wiki.ts +233 -0
  120. package/index.js +0 -27
@@ -0,0 +1,247 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { FeishuConfigSchema, FeishuGroupSchema } from "./config-schema.js";
3
+
4
+ function expectSchemaIssue(
5
+ result: ReturnType<typeof FeishuConfigSchema.safeParse>,
6
+ issuePath: string,
7
+ ) {
8
+ expect(result.success).toBe(false);
9
+ if (!result.success) {
10
+ expect(result.error.issues.some((issue) => issue.path.join(".") === issuePath)).toBe(true);
11
+ }
12
+ }
13
+
14
+ describe("FeishuConfigSchema webhook validation", () => {
15
+ it("applies top-level defaults", () => {
16
+ const result = FeishuConfigSchema.parse({});
17
+ expect(result.domain).toBe("feishu");
18
+ expect(result.connectionMode).toBe("websocket");
19
+ expect(result.webhookPath).toBe("/feishu/events");
20
+ expect(result.dmPolicy).toBe("pairing");
21
+ expect(result.groupPolicy).toBe("allowlist");
22
+ expect(result.requireMention).toBe(true);
23
+ });
24
+
25
+ it("does not force top-level policy defaults into account config", () => {
26
+ const result = FeishuConfigSchema.parse({
27
+ accounts: {
28
+ main: {},
29
+ },
30
+ });
31
+
32
+ expect(result.accounts?.main?.dmPolicy).toBeUndefined();
33
+ expect(result.accounts?.main?.groupPolicy).toBeUndefined();
34
+ expect(result.accounts?.main?.requireMention).toBeUndefined();
35
+ });
36
+
37
+ it("normalizes legacy groupPolicy allowall to open", () => {
38
+ const result = FeishuConfigSchema.parse({
39
+ groupPolicy: "allowall",
40
+ });
41
+
42
+ expect(result.groupPolicy).toBe("open");
43
+ });
44
+
45
+ it("rejects top-level webhook mode without verificationToken", () => {
46
+ const result = FeishuConfigSchema.safeParse({
47
+ connectionMode: "webhook",
48
+ appId: "cli_top",
49
+ appSecret: "secret_top", // pragma: allowlist secret
50
+ });
51
+
52
+ expectSchemaIssue(result, "verificationToken");
53
+ });
54
+
55
+ it("rejects top-level webhook mode without encryptKey", () => {
56
+ const result = FeishuConfigSchema.safeParse({
57
+ connectionMode: "webhook",
58
+ verificationToken: "token_top",
59
+ appId: "cli_top",
60
+ appSecret: "secret_top", // pragma: allowlist secret
61
+ });
62
+
63
+ expectSchemaIssue(result, "encryptKey");
64
+ });
65
+
66
+ it("accepts top-level webhook mode with verificationToken and encryptKey", () => {
67
+ const result = FeishuConfigSchema.safeParse({
68
+ connectionMode: "webhook",
69
+ verificationToken: "token_top",
70
+ encryptKey: "encrypt_top",
71
+ appId: "cli_top",
72
+ appSecret: "secret_top", // pragma: allowlist secret
73
+ });
74
+
75
+ expect(result.success).toBe(true);
76
+ });
77
+
78
+ it("rejects account webhook mode without verificationToken", () => {
79
+ const result = FeishuConfigSchema.safeParse({
80
+ accounts: {
81
+ main: {
82
+ connectionMode: "webhook",
83
+ appId: "cli_main",
84
+ appSecret: "secret_main", // pragma: allowlist secret
85
+ },
86
+ },
87
+ });
88
+
89
+ expectSchemaIssue(result, "accounts.main.verificationToken");
90
+ });
91
+
92
+ it("rejects account webhook mode without encryptKey", () => {
93
+ const result = FeishuConfigSchema.safeParse({
94
+ accounts: {
95
+ main: {
96
+ connectionMode: "webhook",
97
+ verificationToken: "token_main",
98
+ appId: "cli_main",
99
+ appSecret: "secret_main", // pragma: allowlist secret
100
+ },
101
+ },
102
+ });
103
+
104
+ expectSchemaIssue(result, "accounts.main.encryptKey");
105
+ });
106
+
107
+ it("accepts account webhook mode inheriting top-level verificationToken and encryptKey", () => {
108
+ const result = FeishuConfigSchema.safeParse({
109
+ verificationToken: "token_top",
110
+ encryptKey: "encrypt_top",
111
+ accounts: {
112
+ main: {
113
+ connectionMode: "webhook",
114
+ appId: "cli_main",
115
+ appSecret: "secret_main", // pragma: allowlist secret
116
+ },
117
+ },
118
+ });
119
+
120
+ expect(result.success).toBe(true);
121
+ });
122
+
123
+ it("accepts SecretRef verificationToken in webhook mode", () => {
124
+ const result = FeishuConfigSchema.safeParse({
125
+ connectionMode: "webhook",
126
+ verificationToken: {
127
+ source: "env",
128
+ provider: "default",
129
+ id: "FEISHU_VERIFICATION_TOKEN",
130
+ },
131
+ encryptKey: "encrypt_top",
132
+ appId: "cli_top",
133
+ appSecret: {
134
+ source: "env",
135
+ provider: "default",
136
+ id: "FEISHU_APP_SECRET",
137
+ },
138
+ });
139
+
140
+ expect(result.success).toBe(true);
141
+ });
142
+
143
+ it("accepts SecretRef encryptKey in webhook mode", () => {
144
+ const result = FeishuConfigSchema.safeParse({
145
+ connectionMode: "webhook",
146
+ verificationToken: {
147
+ source: "env",
148
+ provider: "default",
149
+ id: "FEISHU_VERIFICATION_TOKEN",
150
+ },
151
+ encryptKey: {
152
+ source: "env",
153
+ provider: "default",
154
+ id: "FEISHU_ENCRYPT_KEY",
155
+ },
156
+ appId: "cli_top",
157
+ appSecret: {
158
+ source: "env",
159
+ provider: "default",
160
+ id: "FEISHU_APP_SECRET",
161
+ },
162
+ });
163
+
164
+ expect(result.success).toBe(true);
165
+ });
166
+ });
167
+
168
+ describe("FeishuConfigSchema replyInThread", () => {
169
+ it("accepts replyInThread at top level", () => {
170
+ const result = FeishuConfigSchema.parse({ replyInThread: "enabled" });
171
+ expect(result.replyInThread).toBe("enabled");
172
+ });
173
+
174
+ it("defaults replyInThread to undefined when not set", () => {
175
+ const result = FeishuConfigSchema.parse({});
176
+ expect(result.replyInThread).toBeUndefined();
177
+ });
178
+
179
+ it("rejects invalid replyInThread value", () => {
180
+ const result = FeishuConfigSchema.safeParse({ replyInThread: "always" });
181
+ expect(result.success).toBe(false);
182
+ });
183
+
184
+ it("accepts replyInThread in group config", () => {
185
+ const result = FeishuGroupSchema.parse({ replyInThread: "enabled" });
186
+ expect(result.replyInThread).toBe("enabled");
187
+ });
188
+
189
+ it("accepts replyInThread in account config", () => {
190
+ const result = FeishuConfigSchema.parse({
191
+ accounts: {
192
+ main: { replyInThread: "enabled" },
193
+ },
194
+ });
195
+ expect(result.accounts?.main?.replyInThread).toBe("enabled");
196
+ });
197
+ });
198
+
199
+ describe("FeishuConfigSchema optimization flags", () => {
200
+ it("defaults top-level typingIndicator and resolveSenderNames to true", () => {
201
+ const result = FeishuConfigSchema.parse({});
202
+ expect(result.typingIndicator).toBe(true);
203
+ expect(result.resolveSenderNames).toBe(true);
204
+ });
205
+
206
+ it("accepts account-level optimization flags", () => {
207
+ const result = FeishuConfigSchema.parse({
208
+ accounts: {
209
+ main: {
210
+ typingIndicator: false,
211
+ resolveSenderNames: false,
212
+ },
213
+ },
214
+ });
215
+ expect(result.accounts?.main?.typingIndicator).toBe(false);
216
+ expect(result.accounts?.main?.resolveSenderNames).toBe(false);
217
+ });
218
+ });
219
+
220
+ describe("FeishuConfigSchema defaultAccount", () => {
221
+ it("accepts defaultAccount when it matches an account key", () => {
222
+ const result = FeishuConfigSchema.safeParse({
223
+ defaultAccount: "router-d",
224
+ accounts: {
225
+ "router-d": { appId: "cli_router", appSecret: "secret_router" }, // pragma: allowlist secret
226
+ },
227
+ });
228
+
229
+ expect(result.success).toBe(true);
230
+ });
231
+
232
+ it("rejects defaultAccount when it does not match an account key", () => {
233
+ const result = FeishuConfigSchema.safeParse({
234
+ defaultAccount: "router-d",
235
+ accounts: {
236
+ backup: { appId: "cli_backup", appSecret: "secret_backup" }, // pragma: allowlist secret
237
+ },
238
+ });
239
+
240
+ expect(result.success).toBe(false);
241
+ if (!result.success) {
242
+ expect(result.error.issues.some((issue) => issue.path.join(".") === "defaultAccount")).toBe(
243
+ true,
244
+ );
245
+ }
246
+ });
247
+ });
@@ -0,0 +1,306 @@
1
+ import { normalizeAccountId } from "./nextclaw-sdk/account-id.js";
2
+ import { z } from "zod";
3
+ export { z };
4
+ import { buildSecretInputSchema, hasConfiguredSecretInput } from "./secret-input.js";
5
+
6
+ const DmPolicySchema = z.enum(["open", "pairing", "allowlist"]);
7
+ const GroupPolicySchema = z.union([
8
+ z.enum(["open", "allowlist", "disabled"]),
9
+ z.literal("allowall").transform(() => "open" as const),
10
+ ]);
11
+ const FeishuDomainSchema = z.union([
12
+ z.enum(["feishu", "lark"]),
13
+ z.string().url().startsWith("https://"),
14
+ ]);
15
+ const FeishuConnectionModeSchema = z.enum(["websocket", "webhook"]);
16
+
17
+ const ToolPolicySchema = z
18
+ .object({
19
+ allow: z.array(z.string()).optional(),
20
+ deny: z.array(z.string()).optional(),
21
+ })
22
+ .strict()
23
+ .optional();
24
+
25
+ const DmConfigSchema = z
26
+ .object({
27
+ enabled: z.boolean().optional(),
28
+ systemPrompt: z.string().optional(),
29
+ })
30
+ .strict()
31
+ .optional();
32
+
33
+ const MarkdownConfigSchema = z
34
+ .object({
35
+ mode: z.enum(["native", "escape", "strip"]).optional(),
36
+ tableMode: z.enum(["native", "ascii", "simple"]).optional(),
37
+ })
38
+ .strict()
39
+ .optional();
40
+
41
+ // Message render mode: auto (default) = detect markdown, raw = plain text, card = always card
42
+ const RenderModeSchema = z.enum(["auto", "raw", "card"]).optional();
43
+
44
+ // Streaming card mode: when enabled, card replies use Feishu's Card Kit streaming API
45
+ // for incremental text display with a "Thinking..." placeholder
46
+ const StreamingModeSchema = z.boolean().optional();
47
+
48
+ const BlockStreamingCoalesceSchema = z
49
+ .object({
50
+ enabled: z.boolean().optional(),
51
+ minDelayMs: z.number().int().positive().optional(),
52
+ maxDelayMs: z.number().int().positive().optional(),
53
+ })
54
+ .strict()
55
+ .optional();
56
+
57
+ const ChannelHeartbeatVisibilitySchema = z
58
+ .object({
59
+ visibility: z.enum(["visible", "hidden"]).optional(),
60
+ intervalMs: z.number().int().positive().optional(),
61
+ })
62
+ .strict()
63
+ .optional();
64
+
65
+ /**
66
+ * Dynamic agent creation configuration.
67
+ * When enabled, a new agent is created for each unique DM user.
68
+ */
69
+ const DynamicAgentCreationSchema = z
70
+ .object({
71
+ enabled: z.boolean().optional(),
72
+ workspaceTemplate: z.string().optional(),
73
+ agentDirTemplate: z.string().optional(),
74
+ maxAgents: z.number().int().positive().optional(),
75
+ })
76
+ .strict()
77
+ .optional();
78
+
79
+ /**
80
+ * Feishu tools configuration.
81
+ * Controls which tool categories are enabled.
82
+ *
83
+ * Dependencies:
84
+ * - wiki requires doc (wiki content is edited via doc tools)
85
+ * - perm can work independently but is typically used with drive
86
+ */
87
+ const FeishuToolsConfigSchema = z
88
+ .object({
89
+ doc: z.boolean().optional(), // Document operations (default: true)
90
+ chat: z.boolean().optional(), // Chat info + member query operations (default: true)
91
+ wiki: z.boolean().optional(), // Knowledge base operations (default: true, requires doc)
92
+ drive: z.boolean().optional(), // Cloud storage operations (default: true)
93
+ perm: z.boolean().optional(), // Permission management (default: false, sensitive)
94
+ scopes: z.boolean().optional(), // App scopes diagnostic (default: true)
95
+ })
96
+ .strict()
97
+ .optional();
98
+
99
+ /**
100
+ * Group session scope for routing Feishu group messages.
101
+ * - "group" (default): one session per group chat
102
+ * - "group_sender": one session per (group + sender)
103
+ * - "group_topic": one session per group topic thread (falls back to group if no topic)
104
+ * - "group_topic_sender": one session per (group + topic thread + sender),
105
+ * falls back to (group + sender) if no topic
106
+ */
107
+ const GroupSessionScopeSchema = z
108
+ .enum(["group", "group_sender", "group_topic", "group_topic_sender"])
109
+ .optional();
110
+
111
+ /**
112
+ * @deprecated Use groupSessionScope instead.
113
+ *
114
+ * Topic session isolation mode for group chats.
115
+ * - "disabled" (default): All messages in a group share one session
116
+ * - "enabled": Messages in different topics get separate sessions
117
+ *
118
+ * Topic routing uses `root_id` when present to keep session continuity and
119
+ * falls back to `thread_id` when `root_id` is unavailable.
120
+ */
121
+ const TopicSessionModeSchema = z.enum(["disabled", "enabled"]).optional();
122
+ const ReactionNotificationModeSchema = z.enum(["off", "own", "all"]).optional();
123
+
124
+ /**
125
+ * Reply-in-thread mode for group chats.
126
+ * - "disabled" (default): Bot replies are normal inline replies
127
+ * - "enabled": Bot replies create or continue a Feishu topic thread
128
+ *
129
+ * When enabled, the Feishu reply API is called with `reply_in_thread: true`,
130
+ * causing the reply to appear as a topic (话题) under the original message.
131
+ */
132
+ const ReplyInThreadSchema = z.enum(["disabled", "enabled"]).optional();
133
+
134
+ export const FeishuGroupSchema = z
135
+ .object({
136
+ requireMention: z.boolean().optional(),
137
+ tools: ToolPolicySchema,
138
+ skills: z.array(z.string()).optional(),
139
+ enabled: z.boolean().optional(),
140
+ allowFrom: z.array(z.union([z.string(), z.number()])).optional(),
141
+ systemPrompt: z.string().optional(),
142
+ groupSessionScope: GroupSessionScopeSchema,
143
+ topicSessionMode: TopicSessionModeSchema,
144
+ replyInThread: ReplyInThreadSchema,
145
+ })
146
+ .strict();
147
+
148
+ const FeishuSharedConfigShape = {
149
+ webhookHost: z.string().optional(),
150
+ webhookPort: z.number().int().positive().optional(),
151
+ capabilities: z.array(z.string()).optional(),
152
+ markdown: MarkdownConfigSchema,
153
+ configWrites: z.boolean().optional(),
154
+ dmPolicy: DmPolicySchema.optional(),
155
+ allowFrom: z.array(z.union([z.string(), z.number()])).optional(),
156
+ groupPolicy: GroupPolicySchema.optional(),
157
+ groupAllowFrom: z.array(z.union([z.string(), z.number()])).optional(),
158
+ groupSenderAllowFrom: z.array(z.union([z.string(), z.number()])).optional(),
159
+ requireMention: z.boolean().optional(),
160
+ groups: z.record(z.string(), FeishuGroupSchema.optional()).optional(),
161
+ historyLimit: z.number().int().min(0).optional(),
162
+ dmHistoryLimit: z.number().int().min(0).optional(),
163
+ dms: z.record(z.string(), DmConfigSchema).optional(),
164
+ textChunkLimit: z.number().int().positive().optional(),
165
+ chunkMode: z.enum(["length", "newline"]).optional(),
166
+ blockStreamingCoalesce: BlockStreamingCoalesceSchema,
167
+ mediaMaxMb: z.number().positive().optional(),
168
+ httpTimeoutMs: z.number().int().positive().max(300_000).optional(),
169
+ heartbeat: ChannelHeartbeatVisibilitySchema,
170
+ renderMode: RenderModeSchema,
171
+ streaming: StreamingModeSchema,
172
+ tools: FeishuToolsConfigSchema,
173
+ replyInThread: ReplyInThreadSchema,
174
+ reactionNotifications: ReactionNotificationModeSchema,
175
+ typingIndicator: z.boolean().optional(),
176
+ resolveSenderNames: z.boolean().optional(),
177
+ };
178
+
179
+ /**
180
+ * Per-account configuration.
181
+ * All fields are optional - missing fields inherit from top-level config.
182
+ */
183
+ export const FeishuAccountConfigSchema = z
184
+ .object({
185
+ enabled: z.boolean().optional(),
186
+ name: z.string().optional(), // Display name for this account
187
+ appId: z.string().optional(),
188
+ appSecret: buildSecretInputSchema().optional(),
189
+ encryptKey: buildSecretInputSchema().optional(),
190
+ verificationToken: buildSecretInputSchema().optional(),
191
+ domain: FeishuDomainSchema.optional(),
192
+ connectionMode: FeishuConnectionModeSchema.optional(),
193
+ webhookPath: z.string().optional(),
194
+ ...FeishuSharedConfigShape,
195
+ groupSessionScope: GroupSessionScopeSchema,
196
+ topicSessionMode: TopicSessionModeSchema,
197
+ })
198
+ .strict();
199
+
200
+ export const FeishuConfigSchema = z
201
+ .object({
202
+ enabled: z.boolean().optional(),
203
+ defaultAccount: z.string().optional(),
204
+ // Top-level credentials (backward compatible for single-account mode)
205
+ appId: z.string().optional(),
206
+ appSecret: buildSecretInputSchema().optional(),
207
+ encryptKey: buildSecretInputSchema().optional(),
208
+ verificationToken: buildSecretInputSchema().optional(),
209
+ domain: FeishuDomainSchema.optional().default("feishu"),
210
+ connectionMode: FeishuConnectionModeSchema.optional().default("websocket"),
211
+ webhookPath: z.string().optional().default("/feishu/events"),
212
+ ...FeishuSharedConfigShape,
213
+ dmPolicy: DmPolicySchema.optional().default("pairing"),
214
+ reactionNotifications: ReactionNotificationModeSchema.optional().default("own"),
215
+ groupPolicy: GroupPolicySchema.optional().default("allowlist"),
216
+ requireMention: z.boolean().optional().default(true),
217
+ groupSessionScope: GroupSessionScopeSchema,
218
+ topicSessionMode: TopicSessionModeSchema,
219
+ // Dynamic agent creation for DM users
220
+ dynamicAgentCreation: DynamicAgentCreationSchema,
221
+ // Optimization flags
222
+ typingIndicator: z.boolean().optional().default(true),
223
+ resolveSenderNames: z.boolean().optional().default(true),
224
+ // Multi-account configuration
225
+ accounts: z.record(z.string(), FeishuAccountConfigSchema.optional()).optional(),
226
+ })
227
+ .strict()
228
+ .superRefine((value, ctx) => {
229
+ const defaultAccount = value.defaultAccount?.trim();
230
+ if (defaultAccount && value.accounts && Object.keys(value.accounts).length > 0) {
231
+ const normalizedDefaultAccount = normalizeAccountId(defaultAccount);
232
+ if (!Object.prototype.hasOwnProperty.call(value.accounts, normalizedDefaultAccount)) {
233
+ ctx.addIssue({
234
+ code: z.ZodIssueCode.custom,
235
+ path: ["defaultAccount"],
236
+ message: `channels.feishu.defaultAccount="${defaultAccount}" does not match a configured account key`,
237
+ });
238
+ }
239
+ }
240
+
241
+ const defaultConnectionMode = value.connectionMode ?? "websocket";
242
+ const defaultVerificationTokenConfigured = hasConfiguredSecretInput(value.verificationToken);
243
+ const defaultEncryptKeyConfigured = hasConfiguredSecretInput(value.encryptKey);
244
+ if (defaultConnectionMode === "webhook") {
245
+ if (!defaultVerificationTokenConfigured) {
246
+ ctx.addIssue({
247
+ code: z.ZodIssueCode.custom,
248
+ path: ["verificationToken"],
249
+ message:
250
+ 'channels.feishu.connectionMode="webhook" requires channels.feishu.verificationToken',
251
+ });
252
+ }
253
+ if (!defaultEncryptKeyConfigured) {
254
+ ctx.addIssue({
255
+ code: z.ZodIssueCode.custom,
256
+ path: ["encryptKey"],
257
+ message: 'channels.feishu.connectionMode="webhook" requires channels.feishu.encryptKey',
258
+ });
259
+ }
260
+ }
261
+
262
+ for (const [accountId, account] of Object.entries(value.accounts ?? {})) {
263
+ if (!account) {
264
+ continue;
265
+ }
266
+ const accountConnectionMode = account.connectionMode ?? defaultConnectionMode;
267
+ if (accountConnectionMode !== "webhook") {
268
+ continue;
269
+ }
270
+ const accountVerificationTokenConfigured =
271
+ hasConfiguredSecretInput(account.verificationToken) || defaultVerificationTokenConfigured;
272
+ const accountEncryptKeyConfigured =
273
+ hasConfiguredSecretInput(account.encryptKey) || defaultEncryptKeyConfigured;
274
+ if (!accountVerificationTokenConfigured) {
275
+ ctx.addIssue({
276
+ code: z.ZodIssueCode.custom,
277
+ path: ["accounts", accountId, "verificationToken"],
278
+ message:
279
+ `channels.feishu.accounts.${accountId}.connectionMode="webhook" requires ` +
280
+ "a verificationToken (account-level or top-level)",
281
+ });
282
+ }
283
+ if (!accountEncryptKeyConfigured) {
284
+ ctx.addIssue({
285
+ code: z.ZodIssueCode.custom,
286
+ path: ["accounts", accountId, "encryptKey"],
287
+ message:
288
+ `channels.feishu.accounts.${accountId}.connectionMode="webhook" requires ` +
289
+ "an encryptKey (account-level or top-level)",
290
+ });
291
+ }
292
+ }
293
+
294
+ if (value.dmPolicy === "open") {
295
+ const allowFrom = value.allowFrom ?? [];
296
+ const hasWildcard = allowFrom.some((entry) => String(entry).trim() === "*");
297
+ if (!hasWildcard) {
298
+ ctx.addIssue({
299
+ code: z.ZodIssueCode.custom,
300
+ path: ["allowFrom"],
301
+ message:
302
+ 'channels.feishu.dmPolicy="open" requires channels.feishu.allowFrom to include "*"',
303
+ });
304
+ }
305
+ }
306
+ });