@kodelyth/feishu 2026.5.42 → 2026.6.1

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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
@@ -1,618 +0,0 @@
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 KlawConfig,
14
- type SecretInput,
15
- } from "klaw/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: KlawConfig): 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: KlawConfig,
93
- accountId: string,
94
- patch: Record<string, unknown>,
95
- ): KlawConfig {
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: KlawConfig;
125
- accountId?: string;
126
- prompter: Parameters<NonNullable<ChannelSetupDmPolicy["promptAllowFrom"]>>[0]["prompter"];
127
- }): Promise<KlawConfig> {
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: KlawConfig,
236
- accountId: string,
237
- openId: string | undefined,
238
- groupPolicy: "allowlist" | "open" | "disabled",
239
- ): KlawConfig {
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: KlawConfig;
340
- prompter: WizardPrompter;
341
- options: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["options"];
342
- }): Promise<{ cfg: KlawConfig }> {
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: KlawConfig;
450
- prompter: WizardPrompter;
451
- options: Parameters<NonNullable<ChannelSetupWizard["finalize"]>>[0]["options"];
452
- }): Promise<{ cfg: KlawConfig } | 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: KlawConfig;
513
- prompter: WizardPrompter;
514
- }): Promise<KlawConfig> {
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
- };