@actagent/feishu 2026.6.2

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 (207) hide show
  1. package/README.md +11 -0
  2. package/actagent.plugin.json +224 -0
  3. package/api.ts +33 -0
  4. package/channel-entry.ts +21 -0
  5. package/channel-plugin-api.ts +2 -0
  6. package/contract-api.ts +17 -0
  7. package/index.ts +83 -0
  8. package/legacy-state-migrations-api.ts +2 -0
  9. package/npm-shrinkwrap.json +539 -0
  10. package/package.json +64 -0
  11. package/runtime-api.ts +58 -0
  12. package/runtime-setter-api.ts +3 -0
  13. package/secret-contract-api.ts +6 -0
  14. package/security-contract-api.ts +2 -0
  15. package/session-key-api.ts +2 -0
  16. package/setup-api.ts +4 -0
  17. package/setup-entry.test.ts +33 -0
  18. package/setup-entry.ts +25 -0
  19. package/skills/feishu-doc/SKILL.md +211 -0
  20. package/skills/feishu-doc/references/block-types.md +103 -0
  21. package/skills/feishu-drive/SKILL.md +97 -0
  22. package/skills/feishu-perm/SKILL.md +119 -0
  23. package/skills/feishu-wiki/SKILL.md +113 -0
  24. package/src/accounts.test.ts +481 -0
  25. package/src/accounts.ts +380 -0
  26. package/src/agent-config.ts +22 -0
  27. package/src/app-registration.test.ts +62 -0
  28. package/src/app-registration.ts +355 -0
  29. package/src/approval-auth.test.ts +25 -0
  30. package/src/approval-auth.ts +26 -0
  31. package/src/async.test.ts +68 -0
  32. package/src/async.ts +109 -0
  33. package/src/audio-preflight.runtime.ts +10 -0
  34. package/src/bitable.test.ts +174 -0
  35. package/src/bitable.ts +781 -0
  36. package/src/bot-content.ts +488 -0
  37. package/src/bot-group-name.test.ts +148 -0
  38. package/src/bot-runtime-api.ts +13 -0
  39. package/src/bot-sender-name.test.ts +68 -0
  40. package/src/bot-sender-name.ts +137 -0
  41. package/src/bot.broadcast.test.ts +643 -0
  42. package/src/bot.card-action.test.ts +647 -0
  43. package/src/bot.checkBotMentioned.test.ts +266 -0
  44. package/src/bot.helpers.test.ts +136 -0
  45. package/src/bot.stripBotMention.test.ts +127 -0
  46. package/src/bot.test.ts +3817 -0
  47. package/src/bot.ts +1788 -0
  48. package/src/card-action.ts +515 -0
  49. package/src/card-interaction.test.ts +132 -0
  50. package/src/card-interaction.ts +160 -0
  51. package/src/card-test-helpers.ts +55 -0
  52. package/src/card-ux-approval.ts +66 -0
  53. package/src/card-ux-launcher.test.ts +126 -0
  54. package/src/card-ux-launcher.ts +136 -0
  55. package/src/card-ux-shared.ts +34 -0
  56. package/src/channel-runtime-api.ts +17 -0
  57. package/src/channel.runtime.ts +48 -0
  58. package/src/channel.test.ts +1337 -0
  59. package/src/channel.ts +1401 -0
  60. package/src/chat-schema.ts +30 -0
  61. package/src/chat.test.ts +295 -0
  62. package/src/chat.ts +198 -0
  63. package/src/client-timeout.ts +44 -0
  64. package/src/client.test.ts +463 -0
  65. package/src/client.ts +263 -0
  66. package/src/comment-dispatcher-runtime-api.ts +7 -0
  67. package/src/comment-dispatcher.test.ts +186 -0
  68. package/src/comment-dispatcher.ts +108 -0
  69. package/src/comment-handler-runtime-api.ts +4 -0
  70. package/src/comment-handler.test.ts +588 -0
  71. package/src/comment-handler.ts +304 -0
  72. package/src/comment-reaction.test.ts +139 -0
  73. package/src/comment-reaction.ts +260 -0
  74. package/src/comment-shared.test.ts +184 -0
  75. package/src/comment-shared.ts +405 -0
  76. package/src/comment-target.ts +45 -0
  77. package/src/config-schema.test.ts +327 -0
  78. package/src/config-schema.ts +338 -0
  79. package/src/conversation-id.test.ts +19 -0
  80. package/src/conversation-id.ts +199 -0
  81. package/src/dedup-migrations.test.ts +90 -0
  82. package/src/dedup-migrations.ts +103 -0
  83. package/src/dedup.test.ts +95 -0
  84. package/src/dedup.ts +304 -0
  85. package/src/dedupe-key.ts +68 -0
  86. package/src/directory.static.ts +62 -0
  87. package/src/directory.test.ts +142 -0
  88. package/src/directory.ts +125 -0
  89. package/src/doc-schema.ts +183 -0
  90. package/src/doctor.test.ts +382 -0
  91. package/src/doctor.ts +876 -0
  92. package/src/docx-batch-insert.test.ts +117 -0
  93. package/src/docx-batch-insert.ts +223 -0
  94. package/src/docx-color-text.ts +154 -0
  95. package/src/docx-table-ops.test.ts +54 -0
  96. package/src/docx-table-ops.ts +316 -0
  97. package/src/docx-types.ts +39 -0
  98. package/src/docx.account-selection.test.ts +96 -0
  99. package/src/docx.test.ts +706 -0
  100. package/src/docx.ts +1598 -0
  101. package/src/drive-schema.ts +93 -0
  102. package/src/drive.test.ts +1240 -0
  103. package/src/drive.ts +830 -0
  104. package/src/dynamic-agent.test.ts +156 -0
  105. package/src/dynamic-agent.ts +144 -0
  106. package/src/event-types.ts +46 -0
  107. package/src/external-keys.test.ts +21 -0
  108. package/src/external-keys.ts +20 -0
  109. package/src/lifecycle.test-support.ts +223 -0
  110. package/src/media.test.ts +956 -0
  111. package/src/media.ts +1106 -0
  112. package/src/mention-target.types.ts +6 -0
  113. package/src/mention.ts +115 -0
  114. package/src/message-action-contract.ts +14 -0
  115. package/src/monitor-state-runtime-api.ts +8 -0
  116. package/src/monitor-transport-runtime-api.ts +11 -0
  117. package/src/monitor.account.ts +501 -0
  118. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +215 -0
  119. package/src/monitor.bot-identity.ts +87 -0
  120. package/src/monitor.bot-menu-handler.ts +164 -0
  121. package/src/monitor.bot-menu.lifecycle.test-support.ts +221 -0
  122. package/src/monitor.bot-menu.test.ts +200 -0
  123. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +265 -0
  124. package/src/monitor.card-action.lifecycle.test-support.ts +418 -0
  125. package/src/monitor.cleanup.test.ts +384 -0
  126. package/src/monitor.comment-notice-handler.ts +106 -0
  127. package/src/monitor.comment.test.ts +968 -0
  128. package/src/monitor.comment.ts +1386 -0
  129. package/src/monitor.lifecycle.test.ts +5 -0
  130. package/src/monitor.message-handler.ts +346 -0
  131. package/src/monitor.reaction.test.ts +770 -0
  132. package/src/monitor.startup.test.ts +232 -0
  133. package/src/monitor.startup.ts +76 -0
  134. package/src/monitor.state.defaults.test.ts +47 -0
  135. package/src/monitor.state.ts +171 -0
  136. package/src/monitor.synthetic-error.ts +19 -0
  137. package/src/monitor.test-mocks.ts +47 -0
  138. package/src/monitor.transport.ts +451 -0
  139. package/src/monitor.ts +104 -0
  140. package/src/monitor.webhook-e2e.test.ts +284 -0
  141. package/src/monitor.webhook-security.test.ts +394 -0
  142. package/src/monitor.webhook.test-helpers.ts +138 -0
  143. package/src/outbound-runtime-api.ts +2 -0
  144. package/src/outbound.test.ts +1255 -0
  145. package/src/outbound.ts +742 -0
  146. package/src/perm-schema.ts +53 -0
  147. package/src/perm.ts +171 -0
  148. package/src/pins.ts +109 -0
  149. package/src/policy.test.ts +224 -0
  150. package/src/policy.ts +322 -0
  151. package/src/post.test.ts +106 -0
  152. package/src/post.ts +276 -0
  153. package/src/presentation-card.ts +204 -0
  154. package/src/probe.test.ts +310 -0
  155. package/src/probe.ts +181 -0
  156. package/src/processing-claims.ts +60 -0
  157. package/src/qr-terminal.ts +2 -0
  158. package/src/reactions.ts +124 -0
  159. package/src/reasoning-preview.test.ts +114 -0
  160. package/src/reasoning-preview.ts +29 -0
  161. package/src/reply-dispatcher-runtime-api.ts +8 -0
  162. package/src/reply-dispatcher.test.ts +2009 -0
  163. package/src/reply-dispatcher.ts +865 -0
  164. package/src/runtime.ts +10 -0
  165. package/src/secret-contract.ts +146 -0
  166. package/src/secret-input.ts +2 -0
  167. package/src/security-audit-shared.ts +70 -0
  168. package/src/security-audit.test.ts +60 -0
  169. package/src/security-audit.ts +2 -0
  170. package/src/send-result.ts +81 -0
  171. package/src/send-target.test.ts +87 -0
  172. package/src/send-target.ts +36 -0
  173. package/src/send.reply-fallback.test.ts +418 -0
  174. package/src/send.test.ts +661 -0
  175. package/src/send.ts +860 -0
  176. package/src/sequential-key.test.ts +73 -0
  177. package/src/sequential-key.ts +29 -0
  178. package/src/sequential-queue.test.ts +184 -0
  179. package/src/sequential-queue.ts +90 -0
  180. package/src/session-conversation.ts +42 -0
  181. package/src/session-route.ts +49 -0
  182. package/src/setup-core.ts +52 -0
  183. package/src/setup-surface.test.ts +485 -0
  184. package/src/setup-surface.ts +620 -0
  185. package/src/streaming-card.test.ts +549 -0
  186. package/src/streaming-card.ts +611 -0
  187. package/src/subagent-hooks.test.ts +632 -0
  188. package/src/subagent-hooks.ts +414 -0
  189. package/src/targets.ts +98 -0
  190. package/src/test-support/lifecycle-test-support.ts +459 -0
  191. package/src/thread-bindings.test.ts +181 -0
  192. package/src/thread-bindings.ts +332 -0
  193. package/src/tool-account-routing.test.ts +419 -0
  194. package/src/tool-account.test.ts +45 -0
  195. package/src/tool-account.ts +98 -0
  196. package/src/tool-factory-test-harness.ts +83 -0
  197. package/src/tool-result.test.ts +33 -0
  198. package/src/tool-result.ts +17 -0
  199. package/src/tools-config.test.ts +52 -0
  200. package/src/tools-config.ts +29 -0
  201. package/src/types.ts +111 -0
  202. package/src/typing.test.ts +145 -0
  203. package/src/typing.ts +215 -0
  204. package/src/wiki-schema.ts +70 -0
  205. package/src/wiki.ts +271 -0
  206. package/subagent-hooks-api.ts +22 -0
  207. package/tsconfig.json +16 -0
@@ -0,0 +1,620 @@
1
+ // Feishu plugin module implements setup surface behavior.
2
+ import {
3
+ DEFAULT_ACCOUNT_ID,
4
+ formatDocsLink,
5
+ hasConfiguredSecretInput,
6
+ mergeAllowFromEntries,
7
+ patchTopLevelChannelConfigSection,
8
+ promptSingleChannelSecretInput,
9
+ splitSetupEntries,
10
+ createSetupTranslator,
11
+ type ChannelSetupDmPolicy,
12
+ type ChannelSetupWizard,
13
+ type DmPolicy,
14
+ type ACTAgentConfig,
15
+ type SecretInput,
16
+ } from "actagent/plugin-sdk/setup";
17
+ import { normalizeOptionalString as normalizeString } from "actagent/plugin-sdk/string-coerce-runtime";
18
+ import { resolveDefaultFeishuAccountId, resolveFeishuAccount } from "./accounts.js";
19
+ import type { AppRegistrationResult } from "./app-registration.js";
20
+ import type { FeishuConfig, FeishuDomain } from "./types.js";
21
+
22
+ const t = createSetupTranslator();
23
+
24
+ const channel = "feishu" as const;
25
+ const SCAN_TO_CREATE_TP = "ob_cli_app";
26
+ const FEISHU_SETUP_FLOW_KEY = "_flow";
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Helpers
30
+ // ---------------------------------------------------------------------------
31
+
32
+ function isFeishuConfigured(cfg: ACTAgentConfig): boolean {
33
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
34
+
35
+ const isAppIdConfigured = (value: unknown): boolean => {
36
+ const asString = normalizeString(value);
37
+ if (asString) {
38
+ return true;
39
+ }
40
+ if (!value || typeof value !== "object") {
41
+ return false;
42
+ }
43
+ const rec = value as Record<string, unknown>;
44
+ const source = normalizeString(rec.source)?.toLowerCase();
45
+ const id = normalizeString(rec.id);
46
+ if (source === "env" && id) {
47
+ return Boolean(normalizeString(process.env[id]));
48
+ }
49
+ return hasConfiguredSecretInput(value);
50
+ };
51
+
52
+ const topLevelConfigured =
53
+ isAppIdConfigured(feishuCfg?.appId) && hasConfiguredSecretInput(feishuCfg?.appSecret);
54
+
55
+ const accountConfigured = Object.values(feishuCfg?.accounts ?? {}).some((account) => {
56
+ if (!account || typeof account !== "object") {
57
+ return false;
58
+ }
59
+ const hasOwnAppId = Object.hasOwn(account, "appId");
60
+ const hasOwnAppSecret = Object.hasOwn(account, "appSecret");
61
+ const accountAppIdConfigured = hasOwnAppId
62
+ ? isAppIdConfigured((account as Record<string, unknown>).appId)
63
+ : isAppIdConfigured(feishuCfg?.appId);
64
+ const accountSecretConfigured = hasOwnAppSecret
65
+ ? hasConfiguredSecretInput((account as Record<string, unknown>).appSecret)
66
+ : hasConfiguredSecretInput(feishuCfg?.appSecret);
67
+ return accountAppIdConfigured && accountSecretConfigured;
68
+ });
69
+
70
+ return topLevelConfigured || accountConfigured;
71
+ }
72
+
73
+ function formatFeishuStatusLine(status: "configured-unverified" | "needs-credentials"): string {
74
+ if (status === "needs-credentials") {
75
+ return `Feishu: ${t("wizard.channels.statusNeedsAppCredentials")}`;
76
+ }
77
+ return `Feishu: ${t("wizard.channels.statusConfiguredConnectionNotVerified")}`;
78
+ }
79
+
80
+ /**
81
+ * Patch feishu config at the correct location based on accountId.
82
+ * - DEFAULT_ACCOUNT_ID → writes to top-level channels.feishu
83
+ * - named account → writes to channels.feishu.accounts[accountId]
84
+ */
85
+ function patchFeishuConfig(
86
+ cfg: ACTAgentConfig,
87
+ accountId: string,
88
+ patch: Record<string, unknown>,
89
+ ): ACTAgentConfig {
90
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
91
+ if (accountId === DEFAULT_ACCOUNT_ID) {
92
+ return patchTopLevelChannelConfigSection({
93
+ cfg,
94
+ channel,
95
+ enabled: true,
96
+ patch,
97
+ });
98
+ }
99
+ const nextAccountPatch = {
100
+ ...(feishuCfg?.accounts?.[accountId] as Record<string, unknown> | undefined),
101
+ enabled: true,
102
+ ...patch,
103
+ };
104
+ return patchTopLevelChannelConfigSection({
105
+ cfg,
106
+ channel,
107
+ enabled: true,
108
+ patch: {
109
+ accounts: {
110
+ ...feishuCfg?.accounts,
111
+ [accountId]: nextAccountPatch,
112
+ },
113
+ },
114
+ });
115
+ }
116
+
117
+ async function promptFeishuAllowFrom(params: {
118
+ cfg: ACTAgentConfig;
119
+ accountId?: string;
120
+ prompter: Parameters<NonNullable<ChannelSetupDmPolicy["promptAllowFrom"]>>[0]["prompter"];
121
+ }): Promise<ACTAgentConfig> {
122
+ const feishuCfg = params.cfg.channels?.feishu as FeishuConfig | undefined;
123
+ const resolvedAccountId = params.accountId ?? resolveDefaultFeishuAccountId(params.cfg);
124
+ const account =
125
+ resolvedAccountId !== DEFAULT_ACCOUNT_ID
126
+ ? (feishuCfg?.accounts?.[resolvedAccountId] as Record<string, unknown> | undefined)
127
+ : undefined;
128
+ const existingAllowFrom = (account?.allowFrom ?? feishuCfg?.allowFrom ?? []) as Array<
129
+ string | number
130
+ >;
131
+ await params.prompter.note(
132
+ [
133
+ t("wizard.feishu.allowlistIntro"),
134
+ t("wizard.feishu.allowlistFindUser"),
135
+ t("wizard.feishu.examples"),
136
+ "- ou_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
137
+ "- on_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
138
+ ].join("\n"),
139
+ t("wizard.feishu.allowlistTitle"),
140
+ );
141
+ const entry = await params.prompter.text({
142
+ message: t("wizard.feishu.allowFromPrompt"),
143
+ placeholder: "ou_xxxxx, ou_yyyyy",
144
+ initialValue:
145
+ existingAllowFrom.length > 0 ? existingAllowFrom.map(String).join(", ") : undefined,
146
+ });
147
+ const mergedAllowFrom = mergeAllowFromEntries(existingAllowFrom, splitSetupEntries(entry));
148
+ return patchFeishuConfig(params.cfg, resolvedAccountId, { allowFrom: mergedAllowFrom });
149
+ }
150
+
151
+ async function noteFeishuCredentialHelp(
152
+ prompter: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["prompter"],
153
+ ): Promise<void> {
154
+ await prompter.note(
155
+ [
156
+ t("wizard.feishu.credentialsStepOpenPlatform"),
157
+ t("wizard.feishu.credentialsStepCreateApp"),
158
+ t("wizard.feishu.credentialsStepGetCredentials"),
159
+ t("wizard.feishu.credentialsStepPermissions"),
160
+ t("wizard.feishu.credentialsStepPublish"),
161
+ t("wizard.feishu.credentialsEnvTip"),
162
+ t("wizard.channels.docs", { link: formatDocsLink("/channels/feishu", "feishu") }),
163
+ ].join("\n"),
164
+ t("wizard.feishu.credentialsTitle"),
165
+ );
166
+ }
167
+
168
+ async function promptFeishuAppId(params: {
169
+ prompter: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["prompter"];
170
+ initialValue?: string;
171
+ }): Promise<string> {
172
+ return (
173
+ await params.prompter.text({
174
+ message: t("wizard.feishu.appIdPrompt"),
175
+ initialValue: params.initialValue,
176
+ validate: (value) => (value?.trim() ? undefined : t("common.required")),
177
+ })
178
+ ).trim();
179
+ }
180
+
181
+ const feishuDmPolicy: ChannelSetupDmPolicy = {
182
+ label: "Feishu",
183
+ channel,
184
+ policyKey: "channels.feishu.dmPolicy",
185
+ allowFromKey: "channels.feishu.allowFrom",
186
+ resolveConfigKeys: (_cfg, accountId) => {
187
+ const resolvedAccountId = accountId ?? resolveDefaultFeishuAccountId(_cfg);
188
+ return resolvedAccountId !== DEFAULT_ACCOUNT_ID
189
+ ? {
190
+ policyKey: `channels.feishu.accounts.${resolvedAccountId}.dmPolicy`,
191
+ allowFromKey: `channels.feishu.accounts.${resolvedAccountId}.allowFrom`,
192
+ }
193
+ : {
194
+ policyKey: "channels.feishu.dmPolicy",
195
+ allowFromKey: "channels.feishu.allowFrom",
196
+ };
197
+ },
198
+ getCurrent: (cfg, accountId) => {
199
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
200
+ const resolvedAccountId = accountId ?? resolveDefaultFeishuAccountId(cfg);
201
+ if (resolvedAccountId !== DEFAULT_ACCOUNT_ID) {
202
+ const account = feishuCfg?.accounts?.[resolvedAccountId] as
203
+ | Record<string, unknown>
204
+ | undefined;
205
+ if (account?.dmPolicy) {
206
+ return account.dmPolicy as DmPolicy;
207
+ }
208
+ }
209
+ return (feishuCfg?.dmPolicy as DmPolicy | undefined) ?? "pairing";
210
+ },
211
+ setPolicy: (cfg, policy, accountId) => {
212
+ const resolvedAccountId = accountId ?? resolveDefaultFeishuAccountId(cfg);
213
+ return patchFeishuConfig(cfg, resolvedAccountId, {
214
+ dmPolicy: policy,
215
+ ...(policy === "open" ? { allowFrom: mergeAllowFromEntries([], ["*"]) } : {}),
216
+ });
217
+ },
218
+ promptAllowFrom: promptFeishuAllowFrom,
219
+ };
220
+
221
+ type WizardPrompter = Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["prompter"];
222
+ type FeishuSetupMethod = "manual" | "scan";
223
+
224
+ // ---------------------------------------------------------------------------
225
+ // Security policy helpers
226
+ // ---------------------------------------------------------------------------
227
+
228
+ function applyNewAppSecurityPolicy(
229
+ cfg: ACTAgentConfig,
230
+ accountId: string,
231
+ openId: string | undefined,
232
+ groupPolicy: "allowlist" | "open" | "disabled",
233
+ ): ACTAgentConfig {
234
+ let next = cfg;
235
+
236
+ if (openId) {
237
+ // dmPolicy=allowlist, allowFrom=[openId]
238
+ next = patchFeishuConfig(next, accountId, { dmPolicy: "allowlist", allowFrom: [openId] });
239
+ }
240
+
241
+ // Apply group policy.
242
+ const groupPatch: Record<string, unknown> = { groupPolicy };
243
+ if (groupPolicy === "open") {
244
+ groupPatch.requireMention = true;
245
+ }
246
+ next = patchFeishuConfig(next, accountId, groupPatch);
247
+
248
+ return next;
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Scan-to-create flow
253
+ // ---------------------------------------------------------------------------
254
+
255
+ let appRegistrationModulePromise: Promise<typeof import("./app-registration.js")> | null = null;
256
+
257
+ const loadAppRegistrationModule = async () => {
258
+ appRegistrationModulePromise ??= import("./app-registration.js");
259
+ return await appRegistrationModulePromise;
260
+ };
261
+
262
+ async function promptFeishuDomain(params: {
263
+ prompter: WizardPrompter;
264
+ initialValue?: FeishuDomain;
265
+ }): Promise<FeishuDomain> {
266
+ return (await params.prompter.select({
267
+ message: t("wizard.feishu.domainPrompt"),
268
+ options: [
269
+ { value: "feishu", label: t("wizard.feishu.domainFeishu") },
270
+ { value: "lark", label: t("wizard.feishu.domainLark") },
271
+ ],
272
+ initialValue: params.initialValue ?? "feishu",
273
+ })) as FeishuDomain;
274
+ }
275
+
276
+ async function promptFeishuSetupMethod(prompter: WizardPrompter): Promise<FeishuSetupMethod> {
277
+ return (await prompter.select({
278
+ message: t("wizard.feishu.setupMethodPrompt"),
279
+ options: [
280
+ { value: "manual", label: t("wizard.feishu.setupMethodManual") },
281
+ { value: "scan", label: t("wizard.feishu.setupMethodScan") },
282
+ ],
283
+ initialValue: "manual",
284
+ })) as FeishuSetupMethod;
285
+ }
286
+
287
+ async function runScanToCreate(
288
+ prompter: WizardPrompter,
289
+ domain: FeishuDomain,
290
+ ): Promise<AppRegistrationResult | null> {
291
+ const { beginAppRegistration, initAppRegistration, pollAppRegistration, printQrCode } =
292
+ await loadAppRegistrationModule();
293
+ try {
294
+ await initAppRegistration(domain);
295
+ } catch {
296
+ await prompter.note(t("wizard.feishu.scanUnavailable"), t("wizard.feishu.setupTitle"));
297
+ return null;
298
+ }
299
+
300
+ const begin = await beginAppRegistration(domain);
301
+
302
+ await prompter.note(t("wizard.feishu.scanQr"), t("wizard.feishu.scanTitle"));
303
+ await printQrCode(begin.qrUrl);
304
+
305
+ const progress = prompter.progress(t("wizard.feishu.fetchingConfig"));
306
+
307
+ const outcome = await pollAppRegistration({
308
+ deviceCode: begin.deviceCode,
309
+ interval: begin.interval,
310
+ expireIn: begin.expireIn,
311
+ initialDomain: domain,
312
+ tp: SCAN_TO_CREATE_TP,
313
+ });
314
+
315
+ switch (outcome.status) {
316
+ case "success":
317
+ progress.stop(t("wizard.feishu.scanCompleted"));
318
+ return outcome.result;
319
+ case "access_denied":
320
+ progress.stop(t("wizard.feishu.scanDenied"));
321
+ return null;
322
+ case "expired":
323
+ progress.stop(t("wizard.feishu.scanExpired"));
324
+ return null;
325
+ case "timeout":
326
+ progress.stop(t("wizard.feishu.scanTimedOut"));
327
+ return null;
328
+ case "error":
329
+ progress.stop(t("wizard.feishu.scanError", { error: outcome.message }));
330
+ return null;
331
+ }
332
+ return null;
333
+ }
334
+
335
+ // ---------------------------------------------------------------------------
336
+ // New app configuration flow
337
+ // ---------------------------------------------------------------------------
338
+
339
+ async function runNewAppFlow(params: {
340
+ cfg: ACTAgentConfig;
341
+ prompter: WizardPrompter;
342
+ options: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["options"];
343
+ }): Promise<{ cfg: ACTAgentConfig }> {
344
+ const { prompter, options } = params;
345
+ let next = params.cfg;
346
+
347
+ // Resolve target account: defaultAccount > first account key > top-level.
348
+ const targetAccountId = resolveDefaultFeishuAccountId(next);
349
+
350
+ // ----- QR scan flow -----
351
+ let appId: string | null;
352
+ let appSecret: SecretInput | null = null;
353
+ let appSecretProbeValue: string | null = null;
354
+ let scanDomain: FeishuDomain | undefined;
355
+ let scanOpenId: string | undefined;
356
+ const feishuCfg = next.channels?.feishu as FeishuConfig | undefined;
357
+ const currentDomain = feishuCfg?.domain ?? "feishu";
358
+ const setupMethod = await promptFeishuSetupMethod(prompter);
359
+ const selectedDomain = await promptFeishuDomain({
360
+ prompter,
361
+ initialValue: currentDomain,
362
+ });
363
+ scanDomain = selectedDomain;
364
+
365
+ const scanResult =
366
+ setupMethod === "scan" ? await runScanToCreate(prompter, selectedDomain) : null;
367
+ if (scanResult) {
368
+ appId = scanResult.appId;
369
+ appSecret = scanResult.appSecret;
370
+ scanDomain = scanResult.domain;
371
+ scanOpenId = scanResult.openId;
372
+ } else {
373
+ // Fallback to manual input: collect domain, appId, appSecret.
374
+ await noteFeishuCredentialHelp(prompter);
375
+
376
+ appId = await promptFeishuAppId({
377
+ prompter,
378
+ initialValue: normalizeString(process.env.FEISHU_APP_ID),
379
+ });
380
+
381
+ const appSecretResult = await promptSingleChannelSecretInput({
382
+ cfg: next,
383
+ prompter,
384
+ providerHint: "feishu",
385
+ credentialLabel: "App Secret",
386
+ secretInputMode: options?.secretInputMode,
387
+ accountConfigured: false,
388
+ canUseEnv: false,
389
+ hasConfigToken: false,
390
+ envPrompt: "",
391
+ keepPrompt: t("wizard.feishu.appSecretKeep"),
392
+ inputPrompt: t("wizard.feishu.appSecretPrompt"),
393
+ preferredEnvVar: "FEISHU_APP_SECRET",
394
+ });
395
+ if (appSecretResult.action === "set") {
396
+ appSecret = appSecretResult.value;
397
+ appSecretProbeValue = appSecretResult.resolvedValue;
398
+ }
399
+
400
+ // Fetch openId via API for manual flow.
401
+ if (appId && appSecretProbeValue) {
402
+ const { getAppOwnerOpenId } = await loadAppRegistrationModule();
403
+ scanOpenId = await getAppOwnerOpenId({
404
+ appId,
405
+ appSecret: appSecretProbeValue,
406
+ domain: selectedDomain,
407
+ });
408
+ }
409
+ }
410
+
411
+ // ----- Group chat policy -----
412
+ const groupPolicy = (await prompter.select({
413
+ message: t("wizard.feishu.groupPolicyPrompt"),
414
+ options: [
415
+ { value: "allowlist", label: t("wizard.feishu.groupPolicyAllowlist") },
416
+ { value: "open", label: t("wizard.feishu.groupPolicyOpen") },
417
+ { value: "disabled", label: t("wizard.feishu.groupPolicyDisabled") },
418
+ ],
419
+ initialValue: "allowlist",
420
+ })) as "allowlist" | "open" | "disabled";
421
+
422
+ // ----- Apply credentials & security policy -----
423
+ const configProgress = prompter.progress(t("wizard.feishu.configuring"));
424
+ await new Promise((resolve) => {
425
+ setTimeout(resolve, 50);
426
+ });
427
+
428
+ if (appId && appSecret) {
429
+ next = patchFeishuConfig(next, targetAccountId, {
430
+ appId,
431
+ appSecret,
432
+ connectionMode: "websocket",
433
+ ...(scanDomain ? { domain: scanDomain } : {}),
434
+ });
435
+ } else if (scanDomain) {
436
+ next = patchFeishuConfig(next, targetAccountId, { domain: scanDomain });
437
+ }
438
+
439
+ next = applyNewAppSecurityPolicy(next, targetAccountId, scanOpenId, groupPolicy);
440
+
441
+ configProgress.stop(t("wizard.feishu.botConfigured"));
442
+
443
+ return { cfg: next };
444
+ }
445
+
446
+ // ---------------------------------------------------------------------------
447
+ // Edit configuration flow
448
+ // ---------------------------------------------------------------------------
449
+
450
+ async function runEditFlow(params: {
451
+ cfg: ACTAgentConfig;
452
+ prompter: WizardPrompter;
453
+ options: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["options"];
454
+ }): Promise<{ cfg: ACTAgentConfig } | null> {
455
+ const { prompter, options } = params;
456
+ const next = params.cfg;
457
+ const feishuCfg = next.channels?.feishu as FeishuConfig | undefined;
458
+
459
+ // Check existing appId (top-level or first configured account).
460
+ // Supports both plain string and SecretRef (env-backed) appId values.
461
+ const resolveAppIdLabel = (value: unknown): string | undefined => {
462
+ const asString = normalizeString(value);
463
+ if (asString) {
464
+ return asString;
465
+ }
466
+ if (value && typeof value === "object") {
467
+ const rec = value as Record<string, unknown>;
468
+ if (normalizeString(rec.source) && normalizeString(rec.id)) {
469
+ const envValue = normalizeString(process.env[rec.id as string]);
470
+ return envValue ?? `env:${String(rec.id)}`;
471
+ }
472
+ if (hasConfiguredSecretInput(value)) {
473
+ return "(configured)";
474
+ }
475
+ }
476
+ return undefined;
477
+ };
478
+ const existingAppId =
479
+ resolveAppIdLabel(feishuCfg?.appId) ??
480
+ Object.values(feishuCfg?.accounts ?? {}).reduce<string | undefined>((found, account) => {
481
+ if (found) {
482
+ return found;
483
+ }
484
+ if (account && typeof account === "object") {
485
+ return resolveAppIdLabel((account as Record<string, unknown>).appId);
486
+ }
487
+ return undefined;
488
+ }, undefined);
489
+ if (existingAppId) {
490
+ const useExisting = await prompter.confirm({
491
+ message: t("wizard.feishu.existingBotPrompt", { appId: existingAppId }),
492
+ initialValue: true,
493
+ });
494
+
495
+ if (!useExisting) {
496
+ // User wants a new bot — run new app flow.
497
+ return runNewAppFlow({ cfg: next, prompter, options });
498
+ }
499
+ } else {
500
+ // No existing appId — run new app flow.
501
+ return runNewAppFlow({ cfg: next, prompter, options });
502
+ }
503
+
504
+ await prompter.note(t("wizard.feishu.botConfigured"), "");
505
+
506
+ return { cfg: next };
507
+ }
508
+
509
+ // ---------------------------------------------------------------------------
510
+ // Standalone login entry point (for `channels login --channel feishu`)
511
+ // ---------------------------------------------------------------------------
512
+
513
+ export async function runFeishuLogin(params: {
514
+ cfg: ACTAgentConfig;
515
+ prompter: WizardPrompter;
516
+ }): Promise<ACTAgentConfig> {
517
+ const { cfg, prompter } = params;
518
+ const options = {};
519
+ const alreadyConfigured = isFeishuConfigured(cfg);
520
+
521
+ if (alreadyConfigured) {
522
+ const result = await runEditFlow({ cfg, prompter, options });
523
+ if (result === null) {
524
+ return cfg;
525
+ }
526
+ return result.cfg;
527
+ }
528
+
529
+ const result = await runNewAppFlow({ cfg, prompter, options });
530
+ return result.cfg;
531
+ }
532
+
533
+ // ---------------------------------------------------------------------------
534
+ // Exported wizard
535
+ // ---------------------------------------------------------------------------
536
+
537
+ export const feishuSetupWizard: ChannelSetupWizard = {
538
+ channel,
539
+ resolveAccountIdForConfigure: ({ accountOverride, defaultAccountId, cfg }) =>
540
+ (typeof accountOverride === "string" && accountOverride.trim()
541
+ ? accountOverride.trim()
542
+ : undefined) ??
543
+ resolveDefaultFeishuAccountId(cfg) ??
544
+ defaultAccountId,
545
+ resolveShouldPromptAccountIds: () => false,
546
+ status: {
547
+ configuredLabel: t("wizard.channels.statusConfigured"),
548
+ unconfiguredLabel: t("wizard.channels.statusNeedsAppCredentials"),
549
+ configuredHint: t("wizard.channels.statusConfigured"),
550
+ unconfiguredHint: t("wizard.channels.statusNeedsAppCreds"),
551
+ configuredScore: 2,
552
+ unconfiguredScore: 0,
553
+ resolveConfigured: ({ cfg }) => isFeishuConfigured(cfg),
554
+ resolveStatusLines: async ({ cfg, accountId, configured }) => {
555
+ const account = resolveFeishuAccount({ cfg, accountId });
556
+ let probeResult = null;
557
+ if (configured && account.configured) {
558
+ try {
559
+ const { probeFeishu } = await import("./probe.js");
560
+ probeResult = await probeFeishu(account);
561
+ } catch {}
562
+ }
563
+ if (!configured) {
564
+ return [formatFeishuStatusLine("needs-credentials")];
565
+ }
566
+ if (probeResult?.ok) {
567
+ return [
568
+ `Feishu: ${t("wizard.channels.statusConnectedAs", {
569
+ name: probeResult.botName ?? probeResult.botOpenId ?? "bot",
570
+ })}`,
571
+ ];
572
+ }
573
+ return [formatFeishuStatusLine("configured-unverified")];
574
+ },
575
+ },
576
+
577
+ // -------------------------------------------------------------------------
578
+ // prepare: determine flow based on existing configuration
579
+ // -------------------------------------------------------------------------
580
+ prepare: async ({ cfg, credentialValues }) => {
581
+ const alreadyConfigured = isFeishuConfigured(cfg);
582
+
583
+ if (alreadyConfigured) {
584
+ return {
585
+ credentialValues: { ...credentialValues, [FEISHU_SETUP_FLOW_KEY]: "edit" },
586
+ };
587
+ }
588
+
589
+ return {
590
+ credentialValues: { ...credentialValues, [FEISHU_SETUP_FLOW_KEY]: "new" },
591
+ };
592
+ },
593
+
594
+ credentials: [],
595
+
596
+ // -------------------------------------------------------------------------
597
+ // finalize: run the appropriate flow
598
+ // -------------------------------------------------------------------------
599
+ finalize: async ({ cfg, prompter, options, credentialValues }) => {
600
+ const flow = credentialValues[FEISHU_SETUP_FLOW_KEY] ?? "new";
601
+
602
+ if (flow === "edit") {
603
+ const result = await runEditFlow({ cfg, prompter, options });
604
+ if (result === null) {
605
+ return { cfg };
606
+ }
607
+ return result;
608
+ }
609
+
610
+ return runNewAppFlow({ cfg, prompter, options });
611
+ },
612
+
613
+ dmPolicy: feishuDmPolicy,
614
+ disable: (cfg) =>
615
+ patchTopLevelChannelConfigSection({
616
+ cfg,
617
+ channel,
618
+ patch: { enabled: false },
619
+ }),
620
+ };