@gakr-gakr/feishu 0.1.0

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