@openclaw/feishu 2026.2.24 → 2026.3.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 (64) hide show
  1. package/index.ts +2 -0
  2. package/package.json +2 -1
  3. package/skills/feishu-doc/SKILL.md +109 -3
  4. package/src/accounts.test.ts +90 -0
  5. package/src/accounts.ts +11 -2
  6. package/src/async.ts +62 -0
  7. package/src/bitable.ts +189 -215
  8. package/src/bot.card-action.test.ts +63 -0
  9. package/src/bot.checkBotMentioned.test.ts +55 -0
  10. package/src/bot.test.ts +863 -9
  11. package/src/bot.ts +414 -200
  12. package/src/card-action.ts +79 -0
  13. package/src/channel.ts +6 -0
  14. package/src/chat-schema.ts +24 -0
  15. package/src/chat.test.ts +89 -0
  16. package/src/chat.ts +130 -0
  17. package/src/client.test.ts +107 -0
  18. package/src/client.ts +13 -0
  19. package/src/config-schema.test.ts +82 -1
  20. package/src/config-schema.ts +54 -3
  21. package/src/doc-schema.ts +141 -0
  22. package/src/docx-batch-insert.ts +190 -0
  23. package/src/docx-color-text.ts +149 -0
  24. package/src/docx-table-ops.ts +298 -0
  25. package/src/docx.account-selection.test.ts +76 -0
  26. package/src/docx.test.ts +470 -0
  27. package/src/docx.ts +996 -72
  28. package/src/drive.ts +38 -33
  29. package/src/media.test.ts +123 -6
  30. package/src/media.ts +31 -10
  31. package/src/monitor.account.ts +286 -0
  32. package/src/monitor.reaction.test.ts +235 -0
  33. package/src/monitor.startup.test.ts +187 -0
  34. package/src/monitor.startup.ts +51 -0
  35. package/src/monitor.state.ts +76 -0
  36. package/src/monitor.transport.ts +163 -0
  37. package/src/monitor.ts +44 -346
  38. package/src/monitor.webhook-security.test.ts +27 -1
  39. package/src/outbound.test.ts +181 -0
  40. package/src/outbound.ts +94 -7
  41. package/src/perm.ts +37 -30
  42. package/src/policy.test.ts +56 -1
  43. package/src/policy.ts +5 -1
  44. package/src/post.test.ts +105 -0
  45. package/src/post.ts +274 -0
  46. package/src/probe.test.ts +253 -0
  47. package/src/probe.ts +99 -7
  48. package/src/reply-dispatcher.test.ts +259 -0
  49. package/src/reply-dispatcher.ts +139 -45
  50. package/src/send.reply-fallback.test.ts +105 -0
  51. package/src/send.test.ts +168 -0
  52. package/src/send.ts +143 -18
  53. package/src/streaming-card.ts +131 -43
  54. package/src/targets.test.ts +26 -1
  55. package/src/targets.ts +11 -6
  56. package/src/tool-account-routing.test.ts +129 -0
  57. package/src/tool-account.ts +70 -0
  58. package/src/tool-factory-test-harness.ts +76 -0
  59. package/src/tools-config.test.ts +21 -0
  60. package/src/tools-config.ts +2 -1
  61. package/src/types.ts +1 -0
  62. package/src/typing.test.ts +144 -0
  63. package/src/typing.ts +140 -10
  64. package/src/wiki.ts +55 -50
@@ -0,0 +1,129 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ import { beforeEach, describe, expect, test, vi } from "vitest";
3
+ import { registerFeishuBitableTools } from "./bitable.js";
4
+ import { registerFeishuDriveTools } from "./drive.js";
5
+ import { registerFeishuPermTools } from "./perm.js";
6
+ import { createToolFactoryHarness } from "./tool-factory-test-harness.js";
7
+ import { registerFeishuWikiTools } from "./wiki.js";
8
+
9
+ const createFeishuClientMock = vi.fn((account: { appId?: string } | undefined) => ({
10
+ __appId: account?.appId,
11
+ }));
12
+
13
+ vi.mock("./client.js", () => ({
14
+ createFeishuClient: (account: { appId?: string } | undefined) => createFeishuClientMock(account),
15
+ }));
16
+
17
+ function createConfig(params: {
18
+ toolsA?: {
19
+ wiki?: boolean;
20
+ drive?: boolean;
21
+ perm?: boolean;
22
+ };
23
+ toolsB?: {
24
+ wiki?: boolean;
25
+ drive?: boolean;
26
+ perm?: boolean;
27
+ };
28
+ defaultAccount?: string;
29
+ }): OpenClawPluginApi["config"] {
30
+ return {
31
+ channels: {
32
+ feishu: {
33
+ enabled: true,
34
+ defaultAccount: params.defaultAccount,
35
+ accounts: {
36
+ a: {
37
+ appId: "app-a",
38
+ appSecret: "sec-a",
39
+ tools: params.toolsA,
40
+ },
41
+ b: {
42
+ appId: "app-b",
43
+ appSecret: "sec-b",
44
+ tools: params.toolsB,
45
+ },
46
+ },
47
+ },
48
+ },
49
+ } as OpenClawPluginApi["config"];
50
+ }
51
+
52
+ describe("feishu tool account routing", () => {
53
+ beforeEach(() => {
54
+ vi.clearAllMocks();
55
+ });
56
+
57
+ test("wiki tool registers when first account disables it and routes to agentAccountId", async () => {
58
+ const { api, resolveTool } = createToolFactoryHarness(
59
+ createConfig({
60
+ toolsA: { wiki: false },
61
+ toolsB: { wiki: true },
62
+ }),
63
+ );
64
+ registerFeishuWikiTools(api);
65
+
66
+ const tool = resolveTool("feishu_wiki", { agentAccountId: "b" });
67
+ await tool.execute("call", { action: "search" });
68
+
69
+ expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-b");
70
+ });
71
+
72
+ test("wiki tool prefers configured defaultAccount over inherited default account context", async () => {
73
+ const { api, resolveTool } = createToolFactoryHarness(
74
+ createConfig({
75
+ defaultAccount: "b",
76
+ toolsA: { wiki: true },
77
+ toolsB: { wiki: true },
78
+ }),
79
+ );
80
+ registerFeishuWikiTools(api);
81
+
82
+ const tool = resolveTool("feishu_wiki", { agentAccountId: "a" });
83
+ await tool.execute("call", { action: "search" });
84
+
85
+ expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-b");
86
+ });
87
+
88
+ test("drive tool registers when first account disables it and routes to agentAccountId", async () => {
89
+ const { api, resolveTool } = createToolFactoryHarness(
90
+ createConfig({
91
+ toolsA: { drive: false },
92
+ toolsB: { drive: true },
93
+ }),
94
+ );
95
+ registerFeishuDriveTools(api);
96
+
97
+ const tool = resolveTool("feishu_drive", { agentAccountId: "b" });
98
+ await tool.execute("call", { action: "unknown_action" });
99
+
100
+ expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-b");
101
+ });
102
+
103
+ test("perm tool registers when only second account enables it and routes to agentAccountId", async () => {
104
+ const { api, resolveTool } = createToolFactoryHarness(
105
+ createConfig({
106
+ toolsA: { perm: false },
107
+ toolsB: { perm: true },
108
+ }),
109
+ );
110
+ registerFeishuPermTools(api);
111
+
112
+ const tool = resolveTool("feishu_perm", { agentAccountId: "b" });
113
+ await tool.execute("call", { action: "unknown_action" });
114
+
115
+ expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-b");
116
+ });
117
+
118
+ test("bitable tool routes to agentAccountId and allows explicit accountId override", async () => {
119
+ const { api, resolveTool } = createToolFactoryHarness(createConfig({}));
120
+ registerFeishuBitableTools(api);
121
+
122
+ const tool = resolveTool("feishu_bitable_get_meta", { agentAccountId: "b" });
123
+ await tool.execute("call-ctx", { url: "invalid-url" });
124
+ await tool.execute("call-override", { url: "invalid-url", accountId: "a" });
125
+
126
+ expect(createFeishuClientMock.mock.calls[0]?.[0]?.appId).toBe("app-b");
127
+ expect(createFeishuClientMock.mock.calls[1]?.[0]?.appId).toBe("app-a");
128
+ });
129
+ });
@@ -0,0 +1,70 @@
1
+ import type * as Lark from "@larksuiteoapi/node-sdk";
2
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
3
+ import { resolveFeishuAccount } from "./accounts.js";
4
+ import { createFeishuClient } from "./client.js";
5
+ import { resolveToolsConfig } from "./tools-config.js";
6
+ import type { FeishuToolsConfig, ResolvedFeishuAccount } from "./types.js";
7
+
8
+ type AccountAwareParams = { accountId?: string };
9
+
10
+ function normalizeOptionalAccountId(value: string | undefined): string | undefined {
11
+ const trimmed = value?.trim();
12
+ return trimmed ? trimmed : undefined;
13
+ }
14
+
15
+ function readConfiguredDefaultAccountId(config: OpenClawPluginApi["config"]): string | undefined {
16
+ const value = (config?.channels?.feishu as { defaultAccount?: unknown } | undefined)
17
+ ?.defaultAccount;
18
+ if (typeof value !== "string") {
19
+ return undefined;
20
+ }
21
+ return normalizeOptionalAccountId(value);
22
+ }
23
+
24
+ export function resolveFeishuToolAccount(params: {
25
+ api: Pick<OpenClawPluginApi, "config">;
26
+ executeParams?: AccountAwareParams;
27
+ defaultAccountId?: string;
28
+ }): ResolvedFeishuAccount {
29
+ if (!params.api.config) {
30
+ throw new Error("Feishu config unavailable");
31
+ }
32
+ return resolveFeishuAccount({
33
+ cfg: params.api.config,
34
+ accountId:
35
+ normalizeOptionalAccountId(params.executeParams?.accountId) ??
36
+ readConfiguredDefaultAccountId(params.api.config) ??
37
+ normalizeOptionalAccountId(params.defaultAccountId),
38
+ });
39
+ }
40
+
41
+ export function createFeishuToolClient(params: {
42
+ api: Pick<OpenClawPluginApi, "config">;
43
+ executeParams?: AccountAwareParams;
44
+ defaultAccountId?: string;
45
+ }): Lark.Client {
46
+ return createFeishuClient(resolveFeishuToolAccount(params));
47
+ }
48
+
49
+ export function resolveAnyEnabledFeishuToolsConfig(
50
+ accounts: ResolvedFeishuAccount[],
51
+ ): Required<FeishuToolsConfig> {
52
+ const merged: Required<FeishuToolsConfig> = {
53
+ doc: false,
54
+ chat: false,
55
+ wiki: false,
56
+ drive: false,
57
+ perm: false,
58
+ scopes: false,
59
+ };
60
+ for (const account of accounts) {
61
+ const cfg = resolveToolsConfig(account.config.tools);
62
+ merged.doc = merged.doc || cfg.doc;
63
+ merged.chat = merged.chat || cfg.chat;
64
+ merged.wiki = merged.wiki || cfg.wiki;
65
+ merged.drive = merged.drive || cfg.drive;
66
+ merged.perm = merged.perm || cfg.perm;
67
+ merged.scopes = merged.scopes || cfg.scopes;
68
+ }
69
+ return merged;
70
+ }
@@ -0,0 +1,76 @@
1
+ import type { AnyAgentTool, OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+
3
+ type ToolContextLike = {
4
+ agentAccountId?: string;
5
+ };
6
+
7
+ type ToolFactoryLike = (ctx: ToolContextLike) => AnyAgentTool | AnyAgentTool[] | null | undefined;
8
+
9
+ export type ToolLike = {
10
+ name: string;
11
+ execute: (toolCallId: string, params: unknown) => Promise<unknown> | unknown;
12
+ };
13
+
14
+ type RegisteredTool = {
15
+ tool: AnyAgentTool | ToolFactoryLike;
16
+ opts?: { name?: string };
17
+ };
18
+
19
+ function toToolList(value: AnyAgentTool | AnyAgentTool[] | null | undefined): AnyAgentTool[] {
20
+ if (!value) return [];
21
+ return Array.isArray(value) ? value : [value];
22
+ }
23
+
24
+ function asToolLike(tool: AnyAgentTool, fallbackName?: string): ToolLike {
25
+ const candidate = tool as Partial<ToolLike>;
26
+ const name = candidate.name ?? fallbackName;
27
+ const execute = candidate.execute;
28
+ if (!name || typeof execute !== "function") {
29
+ throw new Error(`Resolved tool is missing required fields (name=${String(name)})`);
30
+ }
31
+ return {
32
+ name,
33
+ execute: (toolCallId, params) => execute(toolCallId, params),
34
+ };
35
+ }
36
+
37
+ export function createToolFactoryHarness(cfg: OpenClawPluginApi["config"]) {
38
+ const registered: RegisteredTool[] = [];
39
+
40
+ const api: Pick<OpenClawPluginApi, "config" | "logger" | "registerTool"> = {
41
+ config: cfg,
42
+ logger: {
43
+ info: () => {},
44
+ warn: () => {},
45
+ error: () => {},
46
+ debug: () => {},
47
+ },
48
+ registerTool: (tool, opts) => {
49
+ registered.push({ tool, opts });
50
+ },
51
+ };
52
+
53
+ const resolveTool = (name: string, ctx: ToolContextLike = {}): ToolLike => {
54
+ for (const entry of registered) {
55
+ if (entry.opts?.name === name && typeof entry.tool !== "function") {
56
+ return asToolLike(entry.tool, name);
57
+ }
58
+
59
+ if (typeof entry.tool === "function") {
60
+ const builtTools = toToolList(entry.tool(ctx));
61
+ const hit = builtTools.find((tool) => (tool as { name?: string }).name === name);
62
+ if (hit) {
63
+ return asToolLike(hit, name);
64
+ }
65
+ } else if ((entry.tool as { name?: string }).name === name) {
66
+ return asToolLike(entry.tool, name);
67
+ }
68
+ }
69
+ throw new Error(`Tool not registered: ${name}`);
70
+ };
71
+
72
+ return {
73
+ api: api as OpenClawPluginApi,
74
+ resolveTool,
75
+ };
76
+ }
@@ -0,0 +1,21 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { FeishuConfigSchema } from "./config-schema.js";
3
+ import { resolveToolsConfig } from "./tools-config.js";
4
+
5
+ describe("feishu tools config", () => {
6
+ it("enables chat tool by default", () => {
7
+ const resolved = resolveToolsConfig(undefined);
8
+ expect(resolved.chat).toBe(true);
9
+ });
10
+
11
+ it("accepts tools.chat in config schema", () => {
12
+ const parsed = FeishuConfigSchema.parse({
13
+ enabled: true,
14
+ tools: {
15
+ chat: false,
16
+ },
17
+ });
18
+
19
+ expect(parsed.tools?.chat).toBe(false);
20
+ });
21
+ });
@@ -2,11 +2,12 @@ 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, chat, wiki, drive, scopes: enabled by default
6
6
  * - perm: disabled by default (sensitive operation)
7
7
  */
8
8
  export const DEFAULT_TOOLS_CONFIG: Required<FeishuToolsConfig> = {
9
9
  doc: true,
10
+ chat: true,
10
11
  wiki: true,
11
12
  drive: true,
12
13
  perm: false,
package/src/types.ts CHANGED
@@ -67,6 +67,7 @@ export type FeishuMediaInfo = {
67
67
 
68
68
  export type FeishuToolsConfig = {
69
69
  doc?: boolean;
70
+ chat?: boolean;
70
71
  wiki?: boolean;
71
72
  drive?: boolean;
72
73
  perm?: boolean;
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { isFeishuBackoffError, getBackoffCodeFromResponse, FeishuBackoffError } from "./typing.js";
3
+
4
+ describe("isFeishuBackoffError", () => {
5
+ it("returns true for HTTP 429 (AxiosError shape)", () => {
6
+ const err = { response: { status: 429, data: {} } };
7
+ expect(isFeishuBackoffError(err)).toBe(true);
8
+ });
9
+
10
+ it("returns true for Feishu quota exceeded code 99991403", () => {
11
+ const err = { response: { status: 200, data: { code: 99991403 } } };
12
+ expect(isFeishuBackoffError(err)).toBe(true);
13
+ });
14
+
15
+ it("returns true for Feishu rate limit code 99991400", () => {
16
+ const err = { response: { status: 200, data: { code: 99991400 } } };
17
+ expect(isFeishuBackoffError(err)).toBe(true);
18
+ });
19
+
20
+ it("returns true for SDK error with code 429", () => {
21
+ const err = { code: 429, message: "too many requests" };
22
+ expect(isFeishuBackoffError(err)).toBe(true);
23
+ });
24
+
25
+ it("returns true for SDK error with top-level code 99991403", () => {
26
+ const err = { code: 99991403, message: "quota exceeded" };
27
+ expect(isFeishuBackoffError(err)).toBe(true);
28
+ });
29
+
30
+ it("returns false for other HTTP errors (e.g. 500)", () => {
31
+ const err = { response: { status: 500, data: {} } };
32
+ expect(isFeishuBackoffError(err)).toBe(false);
33
+ });
34
+
35
+ it("returns false for non-rate-limit Feishu codes", () => {
36
+ const err = { response: { status: 200, data: { code: 99991401 } } };
37
+ expect(isFeishuBackoffError(err)).toBe(false);
38
+ });
39
+
40
+ it("returns false for generic Error", () => {
41
+ expect(isFeishuBackoffError(new Error("network timeout"))).toBe(false);
42
+ });
43
+
44
+ it("returns false for null", () => {
45
+ expect(isFeishuBackoffError(null)).toBe(false);
46
+ });
47
+
48
+ it("returns false for undefined", () => {
49
+ expect(isFeishuBackoffError(undefined)).toBe(false);
50
+ });
51
+
52
+ it("returns false for string", () => {
53
+ expect(isFeishuBackoffError("429")).toBe(false);
54
+ });
55
+
56
+ it("returns true for 429 even without data", () => {
57
+ const err = { response: { status: 429 } };
58
+ expect(isFeishuBackoffError(err)).toBe(true);
59
+ });
60
+ });
61
+
62
+ describe("getBackoffCodeFromResponse", () => {
63
+ it("returns backoff code for response with quota exceeded code", () => {
64
+ const response = { code: 99991403, msg: "quota exceeded", data: null };
65
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
66
+ });
67
+
68
+ it("returns backoff code for response with rate limit code", () => {
69
+ const response = { code: 99991400, msg: "rate limit", data: null };
70
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
71
+ });
72
+
73
+ it("returns backoff code for response with code 429", () => {
74
+ const response = { code: 429, msg: "too many requests", data: null };
75
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
76
+ });
77
+
78
+ it("returns undefined for successful response (code 0)", () => {
79
+ const response = { code: 0, msg: "success", data: { reaction_id: "r1" } };
80
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
81
+ });
82
+
83
+ it("returns undefined for other error codes", () => {
84
+ const response = { code: 99991401, msg: "other error", data: null };
85
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
86
+ });
87
+
88
+ it("returns undefined for null", () => {
89
+ expect(getBackoffCodeFromResponse(null)).toBeUndefined();
90
+ });
91
+
92
+ it("returns undefined for undefined", () => {
93
+ expect(getBackoffCodeFromResponse(undefined)).toBeUndefined();
94
+ });
95
+
96
+ it("returns undefined for response without code field", () => {
97
+ const response = { data: { reaction_id: "r1" } };
98
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
99
+ });
100
+ });
101
+
102
+ describe("FeishuBackoffError", () => {
103
+ it("is detected by isFeishuBackoffError via .code property", () => {
104
+ const err = new FeishuBackoffError(99991403);
105
+ expect(isFeishuBackoffError(err)).toBe(true);
106
+ });
107
+
108
+ it("is detected for rate limit code 99991400", () => {
109
+ const err = new FeishuBackoffError(99991400);
110
+ expect(isFeishuBackoffError(err)).toBe(true);
111
+ });
112
+
113
+ it("has correct name and message", () => {
114
+ const err = new FeishuBackoffError(99991403);
115
+ expect(err.name).toBe("FeishuBackoffError");
116
+ expect(err.message).toBe("Feishu API backoff: code 99991403");
117
+ expect(err.code).toBe(99991403);
118
+ });
119
+
120
+ it("is an instance of Error", () => {
121
+ const err = new FeishuBackoffError(99991403);
122
+ expect(err instanceof Error).toBe(true);
123
+ });
124
+
125
+ it("survives catch-and-rethrow pattern", () => {
126
+ // Simulates the exact pattern in addTypingIndicator/removeTypingIndicator:
127
+ // thrown inside try, caught by catch, isFeishuBackoffError must match
128
+ let caught: unknown;
129
+ try {
130
+ try {
131
+ throw new FeishuBackoffError(99991403);
132
+ } catch (err) {
133
+ if (isFeishuBackoffError(err)) {
134
+ throw err; // re-thrown — this is the fix
135
+ }
136
+ // would be silently swallowed with plain Error
137
+ caught = "swallowed";
138
+ }
139
+ } catch (err) {
140
+ caught = err;
141
+ }
142
+ expect(caught).toBeInstanceOf(FeishuBackoffError);
143
+ });
144
+ });
package/src/typing.ts CHANGED
@@ -1,26 +1,112 @@
1
- import type { ClawdbotConfig } from "openclaw/plugin-sdk";
1
+ import type { ClawdbotConfig, RuntimeEnv } from "openclaw/plugin-sdk";
2
2
  import { resolveFeishuAccount } from "./accounts.js";
3
3
  import { createFeishuClient } from "./client.js";
4
+ import { getFeishuRuntime } from "./runtime.js";
4
5
 
5
6
  // Feishu emoji types for typing indicator
6
7
  // See: https://open.feishu.cn/document/server-docs/im-v1/message-reaction/emojis-introduce
7
8
  // Full list: https://github.com/go-lark/lark/blob/main/emoji.go
8
9
  const TYPING_EMOJI = "Typing"; // Typing indicator emoji
9
10
 
11
+ /**
12
+ * Feishu API error codes that indicate the caller should back off.
13
+ * These must propagate to the typing circuit breaker so the keepalive loop
14
+ * can trip and stop retrying.
15
+ *
16
+ * - 99991400: Rate limit (too many requests per second)
17
+ * - 99991403: Monthly API call quota exceeded
18
+ * - 429: Standard HTTP 429 returned as a Feishu SDK error code
19
+ *
20
+ * @see https://open.feishu.cn/document/server-docs/api-call-guide/generic-error-code
21
+ */
22
+ const FEISHU_BACKOFF_CODES = new Set([99991400, 99991403, 429]);
23
+
24
+ /**
25
+ * Custom error class for Feishu backoff conditions detected from non-throwing
26
+ * SDK responses. Carries a numeric `.code` so that `isFeishuBackoffError()`
27
+ * recognises it when the error is caught downstream.
28
+ */
29
+ export class FeishuBackoffError extends Error {
30
+ code: number;
31
+ constructor(code: number) {
32
+ super(`Feishu API backoff: code ${code}`);
33
+ this.name = "FeishuBackoffError";
34
+ this.code = code;
35
+ }
36
+ }
37
+
10
38
  export type TypingIndicatorState = {
11
39
  messageId: string;
12
40
  reactionId: string | null;
13
41
  };
14
42
 
15
43
  /**
16
- * Add a typing indicator (reaction) to a message
44
+ * Check whether an error represents a rate-limit or quota-exceeded condition
45
+ * from the Feishu API that should stop the typing keepalive loop.
46
+ *
47
+ * Handles two shapes:
48
+ * 1. AxiosError with `response.status` and `response.data.code`
49
+ * 2. Feishu SDK error with a top-level `code` property
50
+ */
51
+ export function isFeishuBackoffError(err: unknown): boolean {
52
+ if (typeof err !== "object" || err === null) {
53
+ return false;
54
+ }
55
+
56
+ // AxiosError shape: err.response.status / err.response.data.code
57
+ const response = (err as { response?: { status?: number; data?: { code?: number } } }).response;
58
+ if (response) {
59
+ if (response.status === 429) {
60
+ return true;
61
+ }
62
+ if (typeof response.data?.code === "number" && FEISHU_BACKOFF_CODES.has(response.data.code)) {
63
+ return true;
64
+ }
65
+ }
66
+
67
+ // Feishu SDK error shape: err.code
68
+ const code = (err as { code?: number }).code;
69
+ if (typeof code === "number" && FEISHU_BACKOFF_CODES.has(code)) {
70
+ return true;
71
+ }
72
+
73
+ return false;
74
+ }
75
+
76
+ /**
77
+ * Check whether a Feishu SDK response object contains a backoff error code.
78
+ *
79
+ * The Feishu SDK sometimes returns a normal response (no throw) with an
80
+ * API-level error code in the response body. This must be detected so the
81
+ * circuit breaker can trip. See codex review on #28157.
82
+ */
83
+ export function getBackoffCodeFromResponse(response: unknown): number | undefined {
84
+ if (typeof response !== "object" || response === null) {
85
+ return undefined;
86
+ }
87
+ const code = (response as { code?: number }).code;
88
+ if (typeof code === "number" && FEISHU_BACKOFF_CODES.has(code)) {
89
+ return code;
90
+ }
91
+ return undefined;
92
+ }
93
+
94
+ /**
95
+ * Add a typing indicator (reaction) to a message.
96
+ *
97
+ * Rate-limit and quota errors are re-thrown so the circuit breaker in
98
+ * `createTypingCallbacks` (typing-start-guard) can trip and stop the
99
+ * keepalive loop. See #28062.
100
+ *
101
+ * Also checks for backoff codes in non-throwing SDK responses (#28157).
17
102
  */
18
103
  export async function addTypingIndicator(params: {
19
104
  cfg: ClawdbotConfig;
20
105
  messageId: string;
21
106
  accountId?: string;
107
+ runtime?: RuntimeEnv;
22
108
  }): Promise<TypingIndicatorState> {
23
- const { cfg, messageId, accountId } = params;
109
+ const { cfg, messageId, accountId, runtime } = params;
24
110
  const account = resolveFeishuAccount({ cfg, accountId });
25
111
  if (!account.configured) {
26
112
  return { messageId, reactionId: null };
@@ -36,25 +122,48 @@ export async function addTypingIndicator(params: {
36
122
  },
37
123
  });
38
124
 
125
+ // Feishu SDK may return a normal response with an API-level error code
126
+ // instead of throwing. Detect backoff codes and throw to trip the breaker.
127
+ const backoffCode = getBackoffCodeFromResponse(response);
128
+ if (backoffCode !== undefined) {
129
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
130
+ runtime?.log?.(
131
+ `[feishu] typing indicator response contains backoff code ${backoffCode}, stopping keepalive`,
132
+ );
133
+ }
134
+ throw new FeishuBackoffError(backoffCode);
135
+ }
136
+
39
137
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK response type
40
138
  const reactionId = (response as any)?.data?.reaction_id ?? null;
41
139
  return { messageId, reactionId };
42
140
  } catch (err) {
43
- // Silently fail - typing indicator is not critical
44
- console.log(`[feishu] failed to add typing indicator: ${err}`);
141
+ if (isFeishuBackoffError(err)) {
142
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
143
+ runtime?.log?.("[feishu] typing indicator hit rate-limit/quota, stopping keepalive");
144
+ }
145
+ throw err;
146
+ }
147
+ // Silently fail for other non-critical errors (e.g. message deleted, permission issues)
148
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
149
+ runtime?.log?.(`[feishu] failed to add typing indicator: ${String(err)}`);
150
+ }
45
151
  return { messageId, reactionId: null };
46
152
  }
47
153
  }
48
154
 
49
155
  /**
50
- * Remove a typing indicator (reaction) from a message
156
+ * Remove a typing indicator (reaction) from a message.
157
+ *
158
+ * Rate-limit and quota errors are re-thrown for the same reason as above.
51
159
  */
52
160
  export async function removeTypingIndicator(params: {
53
161
  cfg: ClawdbotConfig;
54
162
  state: TypingIndicatorState;
55
163
  accountId?: string;
164
+ runtime?: RuntimeEnv;
56
165
  }): Promise<void> {
57
- const { cfg, state, accountId } = params;
166
+ const { cfg, state, accountId, runtime } = params;
58
167
  if (!state.reactionId) {
59
168
  return;
60
169
  }
@@ -67,14 +176,35 @@ export async function removeTypingIndicator(params: {
67
176
  const client = createFeishuClient(account);
68
177
 
69
178
  try {
70
- await client.im.messageReaction.delete({
179
+ const result = await client.im.messageReaction.delete({
71
180
  path: {
72
181
  message_id: state.messageId,
73
182
  reaction_id: state.reactionId,
74
183
  },
75
184
  });
185
+
186
+ // Check for backoff codes in non-throwing SDK responses
187
+ const backoffCode = getBackoffCodeFromResponse(result);
188
+ if (backoffCode !== undefined) {
189
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
190
+ runtime?.log?.(
191
+ `[feishu] typing indicator removal response contains backoff code ${backoffCode}, stopping keepalive`,
192
+ );
193
+ }
194
+ throw new FeishuBackoffError(backoffCode);
195
+ }
76
196
  } catch (err) {
77
- // Silently fail - cleanup is not critical
78
- console.log(`[feishu] failed to remove typing indicator: ${err}`);
197
+ if (isFeishuBackoffError(err)) {
198
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
199
+ runtime?.log?.(
200
+ "[feishu] typing indicator removal hit rate-limit/quota, stopping keepalive",
201
+ );
202
+ }
203
+ throw err;
204
+ }
205
+ // Silently fail for other non-critical errors
206
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
207
+ runtime?.log?.(`[feishu] failed to remove typing indicator: ${String(err)}`);
208
+ }
79
209
  }
80
210
  }