@m1heng-clawd/feishu 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Minimal response shape shared by Feishu OpenAPI endpoints.
3
+ * Most endpoints return success when `code` is `0` (or omitted).
4
+ */
5
+ export type FeishuApiResponse = {
6
+ code?: number;
7
+ msg?: string;
8
+ log_id?: string;
9
+ logId?: string;
10
+ };
11
+
12
+ type FeishuErrorInfo = {
13
+ code?: number;
14
+ msg?: string;
15
+ logId?: string;
16
+ };
17
+
18
+ type RunFeishuApiCallOptions = {
19
+ /** Feishu error codes that should be treated as transient and retried. */
20
+ retryableCodes?: Iterable<number>;
21
+ /** Retry delays in milliseconds. Number of entries controls retry attempts. */
22
+ backoffMs?: number[];
23
+ };
24
+
25
+ /**
26
+ * Standard tool result payload:
27
+ * - `content` for model-visible text output
28
+ * - `details` for structured downstream access
29
+ */
30
+ export function json(data: unknown) {
31
+ return {
32
+ content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
33
+ details: data,
34
+ };
35
+ }
36
+
37
+ /** Convert any thrown value into the standard JSON error envelope. */
38
+ export function errorResult(err: unknown) {
39
+ return json({ error: err instanceof Error ? err.message : String(err) });
40
+ }
41
+
42
+ /** Small async sleep utility used by retry backoff. */
43
+ function sleep(ms: number) {
44
+ return new Promise((resolve) => setTimeout(resolve, ms));
45
+ }
46
+
47
+ /**
48
+ * Extract Feishu error fields (`code`, `msg`, `log_id`) from different throw shapes.
49
+ * Handles nested SDK error arrays and axios-style `response.data`.
50
+ */
51
+ function extractFeishuErrorInfo(err: unknown): FeishuErrorInfo | null {
52
+ if (!err) return null;
53
+
54
+ // Feishu SDK may throw nested array structures like:
55
+ // [axiosError, { code, msg, log_id, ... }]
56
+ if (Array.isArray(err)) {
57
+ for (let i = err.length - 1; i >= 0; i -= 1) {
58
+ const info = extractFeishuErrorInfo(err[i]);
59
+ if (info) return info;
60
+ }
61
+ return null;
62
+ }
63
+
64
+ if (typeof err !== "object") return null;
65
+
66
+ const obj = err as Record<string, unknown>;
67
+ const codeValue = obj.code;
68
+ const msgValue = obj.msg ?? obj.message;
69
+ const logIdValue = obj.log_id ?? obj.logId;
70
+
71
+ const hasCode = typeof codeValue === "number";
72
+ const hasMsg = typeof msgValue === "string";
73
+ const hasLogId = typeof logIdValue === "string";
74
+
75
+ if (hasCode || hasMsg || hasLogId) {
76
+ return {
77
+ code: hasCode ? codeValue : undefined,
78
+ msg: hasMsg ? (msgValue as string) : undefined,
79
+ logId: hasLogId ? (logIdValue as string) : undefined,
80
+ };
81
+ }
82
+
83
+ const responseData = (obj.response as { data?: unknown } | undefined)?.data;
84
+ if (responseData) return extractFeishuErrorInfo(responseData);
85
+
86
+ return null;
87
+ }
88
+
89
+ function assertFeishuOk<T extends FeishuApiResponse>(response: T, context: string): T {
90
+ if (response.code === undefined || response.code === 0) return response;
91
+
92
+ const message = response.msg || `code ${response.code}`;
93
+ const detail = response.log_id ?? response.logId;
94
+ const error = new Error(
95
+ detail
96
+ ? `${context} failed: ${message}, code=${response.code}, log_id=${detail}`
97
+ : `${context} failed: ${message}, code=${response.code}`,
98
+ ) as Error & { code?: number; log_id?: string; logId?: string };
99
+ error.code = response.code;
100
+ if (detail) {
101
+ error.log_id = detail;
102
+ error.logId = detail;
103
+ }
104
+ throw error;
105
+ }
106
+
107
+ /**
108
+ * Normalize unknown errors to a readable, context-aware Error message.
109
+ * Preserves Feishu `code/log_id` details when available.
110
+ */
111
+ function toError(err: unknown, context: string): Error {
112
+ if (err instanceof Error) {
113
+ const info = extractFeishuErrorInfo(err);
114
+ if (!info) return err;
115
+ const details = [
116
+ info.msg || `code ${info.code}`,
117
+ info.code !== undefined ? `code=${info.code}` : undefined,
118
+ info.logId ? `log_id=${info.logId}` : undefined,
119
+ ]
120
+ .filter(Boolean)
121
+ .join(", ");
122
+ return new Error(`${context} failed: ${details}`);
123
+ }
124
+
125
+ const info = extractFeishuErrorInfo(err);
126
+ if (info) {
127
+ const details = [
128
+ info.msg || `code ${info.code}`,
129
+ info.code !== undefined ? `code=${info.code}` : undefined,
130
+ info.logId ? `log_id=${info.logId}` : undefined,
131
+ ]
132
+ .filter(Boolean)
133
+ .join(", ");
134
+ return new Error(`${context} failed: ${details}`);
135
+ }
136
+
137
+ return new Error(`${context} failed: ${String(err)}`);
138
+ }
139
+
140
+ /**
141
+ * Execute a Feishu API call with shared success/error handling.
142
+ *
143
+ * Behavior:
144
+ * - Treats `code === 0` (or undefined) as success.
145
+ * - Converts non-zero responses and thrown values into normalized Errors.
146
+ * - Optionally retries only for configured transient error codes.
147
+ *
148
+ * Retry model:
149
+ * - Attempts = `backoffMs.length + 1`
150
+ * - Delay before each retry uses the corresponding `backoffMs` entry.
151
+ */
152
+ export async function runFeishuApiCall<T extends FeishuApiResponse>(
153
+ context: string,
154
+ fn: () => Promise<T>,
155
+ options?: RunFeishuApiCallOptions,
156
+ ): Promise<T> {
157
+ const retryableCodes = new Set(options?.retryableCodes ?? []);
158
+ const backoffMs = options?.backoffMs ?? [];
159
+ const maxAttempts = backoffMs.length + 1;
160
+ let attempt = 0;
161
+ let lastErr: unknown = null;
162
+
163
+ while (attempt < maxAttempts) {
164
+ try {
165
+ const response = await fn();
166
+ return assertFeishuOk(response, context);
167
+ } catch (err) {
168
+ lastErr = err;
169
+ const info = extractFeishuErrorInfo(err);
170
+ const retryable =
171
+ retryableCodes.size > 0 && info?.code !== undefined && retryableCodes.has(info.code);
172
+ const exhausted = attempt >= maxAttempts - 1;
173
+ if (!retryable || exhausted) {
174
+ throw toError(err, context);
175
+ }
176
+
177
+ const waitMs = backoffMs[Math.min(attempt, backoffMs.length - 1)];
178
+ await sleep(waitMs);
179
+ attempt += 1;
180
+ }
181
+ }
182
+
183
+ throw toError(lastErr, context);
184
+ }
@@ -0,0 +1,23 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ export type FeishuToolContext = {
4
+ channel: "feishu";
5
+ accountId: string;
6
+ sessionKey?: string;
7
+ };
8
+
9
+ const toolContextStorage = new AsyncLocalStorage<FeishuToolContext>();
10
+
11
+ export function runWithFeishuToolContext<T>(
12
+ context: FeishuToolContext,
13
+ fn: () => T,
14
+ ): T {
15
+ // Propagate the active Feishu account through async boundaries so tool execution
16
+ // can resolve the correct account without changing OpenClaw core APIs.
17
+ return toolContextStorage.run(context, fn);
18
+ }
19
+
20
+ export function getCurrentFeishuToolContext(): FeishuToolContext | undefined {
21
+ // Returns undefined when execution is outside a message-dispatch context.
22
+ return toolContextStorage.getStore();
23
+ }
@@ -0,0 +1,73 @@
1
+ import type * as Lark from "@larksuiteoapi/node-sdk";
2
+ import type { ClawdbotConfig, OpenClawPluginApi } from "openclaw/plugin-sdk";
3
+ import {
4
+ listEnabledFeishuAccounts,
5
+ resolveDefaultFeishuAccountId,
6
+ resolveFeishuAccount,
7
+ } from "../accounts.js";
8
+ import { createFeishuClient } from "../client.js";
9
+ import { resolveToolsConfig } from "../tools-config.js";
10
+ import { getCurrentFeishuToolContext } from "./tool-context.js";
11
+ import type { FeishuToolsConfig, ResolvedFeishuAccount } from "../types.js";
12
+
13
+ export type FeishuToolFlag = keyof Required<FeishuToolsConfig>;
14
+
15
+ export function hasFeishuToolEnabledForAnyAccount(
16
+ cfg: ClawdbotConfig,
17
+ requiredTool?: FeishuToolFlag,
18
+ ): boolean {
19
+ // Tool registration is global (one definition), so we only need to know whether
20
+ // at least one enabled account can use the tool.
21
+ const accounts = listEnabledFeishuAccounts(cfg);
22
+ if (accounts.length === 0) {
23
+ return false;
24
+ }
25
+ if (!requiredTool) {
26
+ return true;
27
+ }
28
+ return accounts.some((account) => resolveToolsConfig(account.config.tools)[requiredTool]);
29
+ }
30
+
31
+ export function resolveToolAccount(cfg: ClawdbotConfig): ResolvedFeishuAccount {
32
+ const context = getCurrentFeishuToolContext();
33
+ if (context?.channel === "feishu" && context.accountId) {
34
+ // Message-driven path: use the account from AsyncLocalStorage context.
35
+ return resolveFeishuAccount({ cfg, accountId: context.accountId });
36
+ }
37
+ // Non-session path (e.g. background/manual invocation): fall back to default account.
38
+ return resolveFeishuAccount({ cfg, accountId: resolveDefaultFeishuAccountId(cfg) });
39
+ }
40
+
41
+ export async function withFeishuToolClient<T>(params: {
42
+ api: OpenClawPluginApi;
43
+ toolName: string;
44
+ requiredTool?: FeishuToolFlag;
45
+ run: (args: { client: Lark.Client; account: ResolvedFeishuAccount }) => Promise<T>;
46
+ }): Promise<T> {
47
+ if (!params.api.config) {
48
+ throw new Error("Feishu config is not available");
49
+ }
50
+
51
+ // Resolve account at execution time (not registration time).
52
+ const account = resolveToolAccount(params.api.config);
53
+
54
+ if (!account.enabled) {
55
+ throw new Error(`Feishu account "${account.accountId}" is disabled`);
56
+ }
57
+ if (!account.configured) {
58
+ throw new Error(`Feishu account "${account.accountId}" is not configured`);
59
+ }
60
+
61
+ if (params.requiredTool) {
62
+ // Enforce per-account tool toggles, even though the tool is registered globally.
63
+ const toolsCfg = resolveToolsConfig(account.config.tools);
64
+ if (!toolsCfg[params.requiredTool]) {
65
+ throw new Error(
66
+ `Feishu tool "${params.toolName}" is disabled for account "${account.accountId}"`,
67
+ );
68
+ }
69
+ }
70
+
71
+ const client = createFeishuClient(account);
72
+ return params.run({ client, account });
73
+ }
@@ -2,7 +2,7 @@ import type { FeishuToolsConfig } from "./types.js";
2
2
 
3
3
  /**
4
4
  * Default tool configuration.
5
- * - doc, wiki, drive, scopes: enabled by default
5
+ * - doc, wiki, drive, scopes, task: enabled by default
6
6
  * - perm: disabled by default (sensitive operation)
7
7
  */
8
8
  export const DEFAULT_TOOLS_CONFIG: Required<FeishuToolsConfig> = {
@@ -11,6 +11,7 @@ export const DEFAULT_TOOLS_CONFIG: Required<FeishuToolsConfig> = {
11
11
  drive: true,
12
12
  perm: false,
13
13
  scopes: true,
14
+ task: true,
14
15
  };
15
16
 
16
17
  /**
package/src/types.ts CHANGED
@@ -67,6 +67,7 @@ export type FeishuToolsConfig = {
67
67
  drive?: boolean;
68
68
  perm?: boolean;
69
69
  scopes?: boolean;
70
+ task?: boolean;
70
71
  };
71
72
 
72
73
  export type DynamicAgentCreationConfig = {
package/src/wiki.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
- import { createFeishuClient } from "./client.js";
3
- import { listEnabledFeishuAccounts } from "./accounts.js";
4
2
  import type * as Lark from "@larksuiteoapi/node-sdk";
5
3
  import { FeishuWikiSchema, type FeishuWikiParams } from "./wiki-schema.js";
6
- import { resolveToolsConfig } from "./tools-config.js";
4
+ import { hasFeishuToolEnabledForAnyAccount, withFeishuToolClient } from "./tools-common/tool-exec.js";
7
5
 
8
6
  // ============ Helpers ============
9
7
 
@@ -155,21 +153,16 @@ export function registerFeishuWikiTools(api: OpenClawPluginApi) {
155
153
  return;
156
154
  }
157
155
 
158
- const accounts = listEnabledFeishuAccounts(api.config);
159
- if (accounts.length === 0) {
156
+ if (!hasFeishuToolEnabledForAnyAccount(api.config)) {
160
157
  api.logger.debug?.("feishu_wiki: No Feishu accounts configured, skipping wiki tools");
161
158
  return;
162
159
  }
163
160
 
164
- const firstAccount = accounts[0];
165
- const toolsCfg = resolveToolsConfig(firstAccount.config.tools);
166
- if (!toolsCfg.wiki) {
161
+ if (!hasFeishuToolEnabledForAnyAccount(api.config, "wiki")) {
167
162
  api.logger.debug?.("feishu_wiki: wiki tool disabled in config");
168
163
  return;
169
164
  }
170
165
 
171
- const getClient = () => createFeishuClient(firstAccount);
172
-
173
166
  api.registerTool(
174
167
  {
175
168
  name: "feishu_wiki",
@@ -180,38 +173,44 @@ export function registerFeishuWikiTools(api: OpenClawPluginApi) {
180
173
  async execute(_toolCallId, params) {
181
174
  const p = params as FeishuWikiParams;
182
175
  try {
183
- const client = getClient();
184
- switch (p.action) {
185
- case "spaces":
186
- return json(await listSpaces(client));
187
- case "nodes":
188
- return json(await listNodes(client, p.space_id, p.parent_node_token));
189
- case "get":
190
- return json(await getNode(client, p.token));
191
- case "search":
192
- return json({
193
- error:
194
- "Search is not available. Use feishu_wiki with action: 'nodes' to browse or action: 'get' to lookup by token.",
195
- });
196
- case "create":
197
- return json(
198
- await createNode(client, p.space_id, p.title, p.obj_type, p.parent_node_token),
199
- );
200
- case "move":
201
- return json(
202
- await moveNode(
203
- client,
204
- p.space_id,
205
- p.node_token,
206
- p.target_space_id,
207
- p.target_parent_token,
208
- ),
209
- );
210
- case "rename":
211
- return json(await renameNode(client, p.space_id, p.node_token, p.title));
212
- default:
213
- return json({ error: `Unknown action: ${(p as any).action}` });
214
- }
176
+ return await withFeishuToolClient({
177
+ api,
178
+ toolName: "feishu_wiki",
179
+ requiredTool: "wiki",
180
+ run: async ({ client }) => {
181
+ switch (p.action) {
182
+ case "spaces":
183
+ return json(await listSpaces(client));
184
+ case "nodes":
185
+ return json(await listNodes(client, p.space_id, p.parent_node_token));
186
+ case "get":
187
+ return json(await getNode(client, p.token));
188
+ case "search":
189
+ return json({
190
+ error:
191
+ "Search is not available. Use feishu_wiki with action: 'nodes' to browse or action: 'get' to lookup by token.",
192
+ });
193
+ case "create":
194
+ return json(
195
+ await createNode(client, p.space_id, p.title, p.obj_type, p.parent_node_token),
196
+ );
197
+ case "move":
198
+ return json(
199
+ await moveNode(
200
+ client,
201
+ p.space_id,
202
+ p.node_token,
203
+ p.target_space_id,
204
+ p.target_parent_token,
205
+ ),
206
+ );
207
+ case "rename":
208
+ return json(await renameNode(client, p.space_id, p.node_token, p.title));
209
+ default:
210
+ return json({ error: `Unknown action: ${(p as any).action}` });
211
+ }
212
+ },
213
+ });
215
214
  } catch (err) {
216
215
  return json({ error: err instanceof Error ? err.message : String(err) });
217
216
  }
@@ -220,5 +219,5 @@ export function registerFeishuWikiTools(api: OpenClawPluginApi) {
220
219
  { name: "feishu_wiki" },
221
220
  );
222
221
 
223
- api.logger.info?.(`feishu_wiki: Registered feishu_wiki tool`);
222
+ api.logger.debug?.("feishu_wiki: Registered feishu_wiki tool");
224
223
  }