@tothemax/tasking 0.0.0-stage → 0.6.16
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.
- package/LICENSE +21 -0
- package/README.md +121 -2
- package/README.zh-CN.md +122 -0
- package/assets/skills/install-glab/SKILL.md +70 -0
- package/assets/skills/land/SKILL.md +63 -0
- package/assets/skills/land/land_watch.py +312 -0
- package/assets/skills/openspec-archive-change/SKILL.md +114 -0
- package/assets/skills/opsx-grill-with-docs/SKILL.md +193 -0
- package/assets/skills/opsx-implement/SKILL.md +258 -0
- package/assets/skills/opsx-propose-with-tdd/SKILL.md +271 -0
- package/assets/workflows/WORKFLOW.code-mr.en.md.example +345 -0
- package/assets/workflows/WORKFLOW.code-mr.md.example +339 -0
- package/assets/workflows/WORKFLOW.feishu-direct.en.md.example +267 -0
- package/assets/workflows/WORKFLOW.feishu-direct.md.example +258 -0
- package/assets/workflows/WORKFLOW.grill-openspec.en.md.example +362 -0
- package/assets/workflows/WORKFLOW.grill-openspec.md.example +356 -0
- package/assets/workflows/WORKFLOW.minimal.en.md.example +296 -0
- package/assets/workflows/WORKFLOW.minimal.md.example +289 -0
- package/dist/adapters/feishu/events.d.ts +55 -0
- package/dist/adapters/feishu/events.d.ts.map +1 -0
- package/dist/adapters/feishu/events.js +184 -0
- package/dist/adapters/feishu/events.js.map +1 -0
- package/dist/adapters/feishu/index.d.ts +2 -0
- package/dist/adapters/feishu/index.d.ts.map +1 -0
- package/dist/adapters/feishu/index.js +2 -0
- package/dist/adapters/feishu/index.js.map +1 -0
- package/dist/adapters/feishu/probe.d.ts +31 -0
- package/dist/adapters/feishu/probe.d.ts.map +1 -0
- package/dist/adapters/feishu/probe.js +179 -0
- package/dist/adapters/feishu/probe.js.map +1 -0
- package/dist/adapters/feishu/source.d.ts +124 -0
- package/dist/adapters/feishu/source.d.ts.map +1 -0
- package/dist/adapters/feishu/source.js +715 -0
- package/dist/adapters/feishu/source.js.map +1 -0
- package/dist/adapters/jira/index.d.ts +2 -0
- package/dist/adapters/jira/index.d.ts.map +1 -0
- package/dist/adapters/jira/index.js +2 -0
- package/dist/adapters/jira/index.js.map +1 -0
- package/dist/adapters/jira/tracker.d.ts +63 -0
- package/dist/adapters/jira/tracker.d.ts.map +1 -0
- package/dist/adapters/jira/tracker.js +402 -0
- package/dist/adapters/jira/tracker.js.map +1 -0
- package/dist/bridge/binding-store.d.ts +93 -0
- package/dist/bridge/binding-store.d.ts.map +1 -0
- package/dist/bridge/binding-store.js +365 -0
- package/dist/bridge/binding-store.js.map +1 -0
- package/dist/bridge/commands.d.ts +45 -0
- package/dist/bridge/commands.d.ts.map +1 -0
- package/dist/bridge/commands.js +197 -0
- package/dist/bridge/commands.js.map +1 -0
- package/dist/bridge/comment-bridge.d.ts +116 -0
- package/dist/bridge/comment-bridge.d.ts.map +1 -0
- package/dist/bridge/comment-bridge.js +1473 -0
- package/dist/bridge/comment-bridge.js.map +1 -0
- package/dist/cli/daemon-info.d.ts +17 -0
- package/dist/cli/daemon-info.d.ts.map +1 -0
- package/dist/cli/daemon-info.js +64 -0
- package/dist/cli/daemon-info.js.map +1 -0
- package/dist/cli/daemon.d.ts +27 -0
- package/dist/cli/daemon.d.ts.map +1 -0
- package/dist/cli/daemon.js +77 -0
- package/dist/cli/daemon.js.map +1 -0
- package/dist/cli/doctor.d.ts +7 -0
- package/dist/cli/doctor.d.ts.map +1 -0
- package/dist/cli/doctor.js +156 -0
- package/dist/cli/doctor.js.map +1 -0
- package/dist/cli/event-channel.d.ts +16 -0
- package/dist/cli/event-channel.d.ts.map +1 -0
- package/dist/cli/event-channel.js +51 -0
- package/dist/cli/event-channel.js.map +1 -0
- package/dist/cli/help.d.ts +3 -0
- package/dist/cli/help.d.ts.map +1 -0
- package/dist/cli/help.js +155 -0
- package/dist/cli/help.js.map +1 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +774 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli/init.d.ts +64 -0
- package/dist/cli/init.d.ts.map +1 -0
- package/dist/cli/init.js +1296 -0
- package/dist/cli/init.js.map +1 -0
- package/dist/cli/instance-lock.d.ts +13 -0
- package/dist/cli/instance-lock.d.ts.map +1 -0
- package/dist/cli/instance-lock.js +53 -0
- package/dist/cli/instance-lock.js.map +1 -0
- package/dist/cli/prompts.d.ts +13 -0
- package/dist/cli/prompts.d.ts.map +1 -0
- package/dist/cli/prompts.js +26 -0
- package/dist/cli/prompts.js.map +1 -0
- package/dist/cli/style.d.ts +26 -0
- package/dist/cli/style.d.ts.map +1 -0
- package/dist/cli/style.js +58 -0
- package/dist/cli/style.js.map +1 -0
- package/dist/cli/tui-helpers.d.ts +5 -0
- package/dist/cli/tui-helpers.d.ts.map +1 -0
- package/dist/cli/tui-helpers.js +124 -0
- package/dist/cli/tui-helpers.js.map +1 -0
- package/dist/cli/workflow-path.d.ts +12 -0
- package/dist/cli/workflow-path.d.ts.map +1 -0
- package/dist/cli/workflow-path.js +37 -0
- package/dist/cli/workflow-path.js.map +1 -0
- package/dist/config/config-types.d.ts +180 -0
- package/dist/config/config-types.d.ts.map +1 -0
- package/dist/config/config-types.js +71 -0
- package/dist/config/config-types.js.map +1 -0
- package/dist/config/dotenv.d.ts +2 -0
- package/dist/config/dotenv.d.ts.map +1 -0
- package/dist/config/dotenv.js +10 -0
- package/dist/config/dotenv.js.map +1 -0
- package/dist/config/index.d.ts +6 -0
- package/dist/config/index.d.ts.map +1 -0
- package/dist/config/index.js +6 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/loader.d.ts +5 -0
- package/dist/config/loader.d.ts.map +1 -0
- package/dist/config/loader.js +304 -0
- package/dist/config/loader.js.map +1 -0
- package/dist/config/manager.d.ts +31 -0
- package/dist/config/manager.d.ts.map +1 -0
- package/dist/config/manager.js +110 -0
- package/dist/config/manager.js.map +1 -0
- package/dist/config/resolver.d.ts +6 -0
- package/dist/config/resolver.d.ts.map +1 -0
- package/dist/config/resolver.js +267 -0
- package/dist/config/resolver.js.map +1 -0
- package/dist/config/validator.d.ts +9 -0
- package/dist/config/validator.d.ts.map +1 -0
- package/dist/config/validator.js +70 -0
- package/dist/config/validator.js.map +1 -0
- package/dist/direct/card.d.ts +49 -0
- package/dist/direct/card.d.ts.map +1 -0
- package/dist/direct/card.js +274 -0
- package/dist/direct/card.js.map +1 -0
- package/dist/direct/command.d.ts +12 -0
- package/dist/direct/command.d.ts.map +1 -0
- package/dist/direct/command.js +23 -0
- package/dist/direct/command.js.map +1 -0
- package/dist/direct/manager.d.ts +159 -0
- package/dist/direct/manager.d.ts.map +1 -0
- package/dist/direct/manager.js +1862 -0
- package/dist/direct/manager.js.map +1 -0
- package/dist/mcp/inject.d.ts +5 -0
- package/dist/mcp/inject.d.ts.map +1 -0
- package/dist/mcp/inject.js +51 -0
- package/dist/mcp/inject.js.map +1 -0
- package/dist/mcp/jira-server.d.ts +29 -0
- package/dist/mcp/jira-server.d.ts.map +1 -0
- package/dist/mcp/jira-server.js +288 -0
- package/dist/mcp/jira-server.js.map +1 -0
- package/dist/observability/activity-store.d.ts +29 -0
- package/dist/observability/activity-store.d.ts.map +1 -0
- package/dist/observability/activity-store.js +32 -0
- package/dist/observability/activity-store.js.map +1 -0
- package/dist/observability/config-view.d.ts +19 -0
- package/dist/observability/config-view.d.ts.map +1 -0
- package/dist/observability/config-view.js +61 -0
- package/dist/observability/config-view.js.map +1 -0
- package/dist/observability/http-dashboard.d.ts +36 -0
- package/dist/observability/http-dashboard.d.ts.map +1 -0
- package/dist/observability/http-dashboard.js +297 -0
- package/dist/observability/http-dashboard.js.map +1 -0
- package/dist/observability/log-buffer.d.ts +21 -0
- package/dist/observability/log-buffer.d.ts.map +1 -0
- package/dist/observability/log-buffer.js +69 -0
- package/dist/observability/log-buffer.js.map +1 -0
- package/dist/observability/logger.d.ts +37 -0
- package/dist/observability/logger.d.ts.map +1 -0
- package/dist/observability/logger.js +114 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/snapshot.d.ts +11 -0
- package/dist/observability/snapshot.d.ts.map +1 -0
- package/dist/observability/snapshot.js +59 -0
- package/dist/observability/snapshot.js.map +1 -0
- package/dist/observability/terminal-dashboard.d.ts +155 -0
- package/dist/observability/terminal-dashboard.d.ts.map +1 -0
- package/dist/observability/terminal-dashboard.js +1598 -0
- package/dist/observability/terminal-dashboard.js.map +1 -0
- package/dist/observability/wrap.d.ts +4 -0
- package/dist/observability/wrap.d.ts.map +1 -0
- package/dist/observability/wrap.js +80 -0
- package/dist/observability/wrap.js.map +1 -0
- package/dist/scheduler/index.d.ts +2 -0
- package/dist/scheduler/index.d.ts.map +1 -0
- package/dist/scheduler/index.js +2 -0
- package/dist/scheduler/index.js.map +1 -0
- package/dist/scheduler/scheduler.d.ts +52 -0
- package/dist/scheduler/scheduler.d.ts.map +1 -0
- package/dist/scheduler/scheduler.js +535 -0
- package/dist/scheduler/scheduler.js.map +1 -0
- package/dist/shared/agent-resolver.d.ts +11 -0
- package/dist/shared/agent-resolver.d.ts.map +1 -0
- package/dist/shared/agent-resolver.js +20 -0
- package/dist/shared/agent-resolver.js.map +1 -0
- package/dist/shared/errors.d.ts +14 -0
- package/dist/shared/errors.d.ts.map +1 -0
- package/dist/shared/errors.js +24 -0
- package/dist/shared/errors.js.map +1 -0
- package/dist/shared/index.d.ts +4 -0
- package/dist/shared/index.d.ts.map +1 -0
- package/dist/shared/index.js +4 -0
- package/dist/shared/index.js.map +1 -0
- package/dist/shared/info-card.d.ts +24 -0
- package/dist/shared/info-card.d.ts.map +1 -0
- package/dist/shared/info-card.js +46 -0
- package/dist/shared/info-card.js.map +1 -0
- package/dist/shared/types.d.ts +148 -0
- package/dist/shared/types.d.ts.map +1 -0
- package/dist/shared/types.js +15 -0
- package/dist/shared/types.js.map +1 -0
- package/dist/translate/card.d.ts +2 -0
- package/dist/translate/card.d.ts.map +1 -0
- package/dist/translate/card.js +17 -0
- package/dist/translate/card.js.map +1 -0
- package/dist/translate/dict.d.ts +7 -0
- package/dist/translate/dict.d.ts.map +1 -0
- package/dist/translate/dict.js +895 -0
- package/dist/translate/dict.js.map +1 -0
- package/dist/translate/locale.d.ts +8 -0
- package/dist/translate/locale.d.ts.map +1 -0
- package/dist/translate/locale.js +75 -0
- package/dist/translate/locale.js.map +1 -0
- package/dist/translate/normalize.d.ts +4 -0
- package/dist/translate/normalize.d.ts.map +1 -0
- package/dist/translate/normalize.js +38 -0
- package/dist/translate/normalize.js.map +1 -0
- package/dist/translate/output.d.ts +3 -0
- package/dist/translate/output.d.ts.map +1 -0
- package/dist/translate/output.js +16 -0
- package/dist/translate/output.js.map +1 -0
- package/dist/worker/prompt.d.ts +11 -0
- package/dist/worker/prompt.d.ts.map +1 -0
- package/dist/worker/prompt.js +153 -0
- package/dist/worker/prompt.js.map +1 -0
- package/dist/worker/runner.d.ts +101 -0
- package/dist/worker/runner.d.ts.map +1 -0
- package/dist/worker/runner.js +448 -0
- package/dist/worker/runner.js.map +1 -0
- package/dist/workspace/index.d.ts +2 -0
- package/dist/workspace/index.d.ts.map +1 -0
- package/dist/workspace/index.js +2 -0
- package/dist/workspace/index.js.map +1 -0
- package/dist/workspace/manager.d.ts +37 -0
- package/dist/workspace/manager.d.ts.map +1 -0
- package/dist/workspace/manager.js +157 -0
- package/dist/workspace/manager.js.map +1 -0
- package/package.json +70 -4
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
import { TaskingError, toTaskingError } from "../../shared/errors.js";
|
|
2
|
+
import { translateCard } from "../../translate/card.js";
|
|
3
|
+
import { translate } from "../../translate/locale.js";
|
|
4
|
+
import { diagnoseFeishuError, feishuBodyCode } from "./probe.js";
|
|
5
|
+
import { crossRegionHint, feishuApiBase } from "./probe.js";
|
|
6
|
+
const DEFAULT_TIMEOUT_MS = 15000;
|
|
7
|
+
const TOKEN_TIMEOUT_MS = 10000;
|
|
8
|
+
export function toSecondsStr(raw) {
|
|
9
|
+
if (typeof raw !== "string" || raw === "")
|
|
10
|
+
return "";
|
|
11
|
+
const n = Number(raw);
|
|
12
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
13
|
+
return "";
|
|
14
|
+
if (n > 1e12)
|
|
15
|
+
return String(Math.floor(n / 1000));
|
|
16
|
+
return raw;
|
|
17
|
+
}
|
|
18
|
+
function parsePolledMessage(raw) {
|
|
19
|
+
const body = raw.body ?? {};
|
|
20
|
+
const content = typeof body.content === "string" ? body.content : "";
|
|
21
|
+
const sender = raw.sender ?? {};
|
|
22
|
+
const senderId = sender.sender_id ?? {};
|
|
23
|
+
const msgType = typeof raw.msg_type === "string" ? raw.msg_type : "";
|
|
24
|
+
const restId = typeof sender.id === "string" ? sender.id : null;
|
|
25
|
+
const restIdType = typeof sender.id_type === "string" ? sender.id_type : null;
|
|
26
|
+
const webhookOpenId = typeof senderId.open_id === "string" ? senderId.open_id : null;
|
|
27
|
+
return {
|
|
28
|
+
message_id: String(raw.message_id ?? ""),
|
|
29
|
+
root_id: typeof raw.root_id === "string" && raw.root_id !== "" ? raw.root_id : null,
|
|
30
|
+
parent_id: typeof raw.parent_id === "string" && raw.parent_id !== "" ? raw.parent_id : null,
|
|
31
|
+
msg_type: msgType,
|
|
32
|
+
text: parseMessageText(msgType, content),
|
|
33
|
+
sender_open_id: webhookOpenId ?? (restId !== null && restIdType === "open_id" ? restId : null),
|
|
34
|
+
sender_name: typeof sender.sender_name === "string" ? sender.sender_name : null,
|
|
35
|
+
sender_type: typeof sender.sender_type === "string" ? sender.sender_type : null,
|
|
36
|
+
create_time: toSecondsStr(raw.create_time),
|
|
37
|
+
chat_id: typeof raw.chat_id === "string" ? raw.chat_id : "",
|
|
38
|
+
attachments: parseMessageAttachments(msgType, content),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export function parseMessageText(msgType, content) {
|
|
42
|
+
return msgType === "post" ? flattenPostContent(content) : parseTextContent(content);
|
|
43
|
+
}
|
|
44
|
+
export class FeishuSource {
|
|
45
|
+
static COOLDOWN_BASE_MS = 60000;
|
|
46
|
+
static COOLDOWN_CAP_MS = 600000;
|
|
47
|
+
config;
|
|
48
|
+
apiBase;
|
|
49
|
+
logger;
|
|
50
|
+
fetchImpl;
|
|
51
|
+
defaultTimeoutMs;
|
|
52
|
+
tokenTimeoutMs;
|
|
53
|
+
tenantAccessToken = null;
|
|
54
|
+
tokenExpiresAt = 0;
|
|
55
|
+
cooldownUntil = 0;
|
|
56
|
+
cooldownMs = 0;
|
|
57
|
+
shownHints = new Set();
|
|
58
|
+
constructor(config, logger, fetchImpl, timeouts) {
|
|
59
|
+
this.config = config;
|
|
60
|
+
this.apiBase = feishuApiBase(config.edition);
|
|
61
|
+
this.logger = logger;
|
|
62
|
+
this.fetchImpl = fetchImpl ?? fetch;
|
|
63
|
+
this.defaultTimeoutMs = timeouts?.defaultMs ?? DEFAULT_TIMEOUT_MS;
|
|
64
|
+
this.tokenTimeoutMs = timeouts?.tokenMs ?? TOKEN_TIMEOUT_MS;
|
|
65
|
+
}
|
|
66
|
+
async fetchWithTimeout(url, init, timeoutMs) {
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
69
|
+
try {
|
|
70
|
+
return await this.fetchImpl(url, { ...init, signal: controller.signal });
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
assertNotCooling() {
|
|
77
|
+
if (Date.now() < this.cooldownUntil) {
|
|
78
|
+
throw new TaskingError("feishu_cooldown", `feishu cooling down for ${Math.ceil((this.cooldownUntil - Date.now()) / 1000)}s after 429`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
enterCooldown() {
|
|
82
|
+
this.cooldownMs =
|
|
83
|
+
this.cooldownMs === 0
|
|
84
|
+
? FeishuSource.COOLDOWN_BASE_MS
|
|
85
|
+
: Math.min(this.cooldownMs * 2, FeishuSource.COOLDOWN_CAP_MS);
|
|
86
|
+
this.cooldownUntil = Date.now() + this.cooldownMs;
|
|
87
|
+
this.logger.warn("feishu 429 received; entering cooldown", { cooldown_ms: this.cooldownMs });
|
|
88
|
+
}
|
|
89
|
+
resetCooldown() {
|
|
90
|
+
this.cooldownUntil = 0;
|
|
91
|
+
this.cooldownMs = 0;
|
|
92
|
+
}
|
|
93
|
+
warnTokenEditionHintOnce() {
|
|
94
|
+
if (this.shownHints.has("token-edition"))
|
|
95
|
+
return;
|
|
96
|
+
this.shownHints.add("token-edition");
|
|
97
|
+
this.logger.warn(`feishu tenant token auth failed: ${crossRegionHint(this.config.edition)}`);
|
|
98
|
+
}
|
|
99
|
+
diagnosticSuffix(label, status, body) {
|
|
100
|
+
const key = `${label}:${status}`;
|
|
101
|
+
if (this.shownHints.has(key))
|
|
102
|
+
return "";
|
|
103
|
+
const hint = diagnoseFeishuError(status, body, this.config.app_id || null, this.config.edition);
|
|
104
|
+
if (hint === null)
|
|
105
|
+
return "";
|
|
106
|
+
this.shownHints.add(key);
|
|
107
|
+
return ` | ${hint}`;
|
|
108
|
+
}
|
|
109
|
+
async reply(chatId, text) {
|
|
110
|
+
await this.postMessage(chatId, text);
|
|
111
|
+
}
|
|
112
|
+
async postMessage(chatId, text) {
|
|
113
|
+
this.assertNotCooling();
|
|
114
|
+
const token = await this.getTenantAccessToken();
|
|
115
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages?receive_id_type=chat_id`;
|
|
116
|
+
try {
|
|
117
|
+
const res = await this.fetchWithTimeout(url, {
|
|
118
|
+
method: "POST",
|
|
119
|
+
headers: {
|
|
120
|
+
Authorization: `Bearer ${token}`,
|
|
121
|
+
"Content-Type": "application/json",
|
|
122
|
+
},
|
|
123
|
+
body: JSON.stringify({
|
|
124
|
+
receive_id: chatId,
|
|
125
|
+
msg_type: "text",
|
|
126
|
+
content: JSON.stringify({ text: translate(text) }),
|
|
127
|
+
}),
|
|
128
|
+
}, this.defaultTimeoutMs);
|
|
129
|
+
if (!res.ok) {
|
|
130
|
+
if (res.status === 429)
|
|
131
|
+
this.enterCooldown();
|
|
132
|
+
const body = await res.text().catch(() => "");
|
|
133
|
+
const suffix = this.diagnosticSuffix("postMessage", res.status, body);
|
|
134
|
+
throw new TaskingError("feishu_api_status", `feishu postMessage failed: ${res.status}${suffix}`, {
|
|
135
|
+
status: res.status,
|
|
136
|
+
body: body.slice(0, 500),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
this.resetCooldown();
|
|
140
|
+
const data = (await res.json());
|
|
141
|
+
return data.data?.message_id ?? "";
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
if (e instanceof TaskingError)
|
|
145
|
+
throw e;
|
|
146
|
+
throw new TaskingError("feishu_api_request", `feishu postMessage request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async replyInThread(rootId, text) {
|
|
150
|
+
return this.replyToMessage(rootId, text, true);
|
|
151
|
+
}
|
|
152
|
+
async replyFlat(rootId, text) {
|
|
153
|
+
await this.replyToMessage(rootId, text, false);
|
|
154
|
+
}
|
|
155
|
+
async replyCardInThread(rootId, card) {
|
|
156
|
+
return this.replyPayload(rootId, "interactive", JSON.stringify(translateCard(card)), true);
|
|
157
|
+
}
|
|
158
|
+
async replyCardFlat(rootId, card) {
|
|
159
|
+
return this.replyPayload(rootId, "interactive", JSON.stringify(translateCard(card)), false);
|
|
160
|
+
}
|
|
161
|
+
async updateCard(messageId, card) {
|
|
162
|
+
this.assertNotCooling();
|
|
163
|
+
const token = await this.getTenantAccessToken();
|
|
164
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}`;
|
|
165
|
+
try {
|
|
166
|
+
const res = await this.fetchWithTimeout(url, {
|
|
167
|
+
method: "PATCH",
|
|
168
|
+
headers: {
|
|
169
|
+
Authorization: `Bearer ${token}`,
|
|
170
|
+
"Content-Type": "application/json",
|
|
171
|
+
},
|
|
172
|
+
body: JSON.stringify({ content: JSON.stringify(translateCard(card)) }),
|
|
173
|
+
}, this.defaultTimeoutMs);
|
|
174
|
+
if (!res.ok) {
|
|
175
|
+
if (res.status === 429)
|
|
176
|
+
this.enterCooldown();
|
|
177
|
+
const body = await res.text().catch(() => "");
|
|
178
|
+
const suffix = this.diagnosticSuffix("updateCard", res.status, body);
|
|
179
|
+
throw new TaskingError("feishu_api_status", `feishu updateCard failed: ${res.status}${suffix}`, {
|
|
180
|
+
status: res.status,
|
|
181
|
+
body: body.slice(0, 500),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
this.resetCooldown();
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
if (e instanceof TaskingError)
|
|
188
|
+
throw e;
|
|
189
|
+
throw new TaskingError("feishu_api_request", `feishu updateCard request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async deleteMessage(messageId) {
|
|
193
|
+
this.assertNotCooling();
|
|
194
|
+
const token = await this.getTenantAccessToken();
|
|
195
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}`;
|
|
196
|
+
try {
|
|
197
|
+
const res = await this.fetchWithTimeout(url, { method: "DELETE", headers: { Authorization: `Bearer ${token}` } }, this.defaultTimeoutMs);
|
|
198
|
+
if (!res.ok) {
|
|
199
|
+
if (res.status === 429)
|
|
200
|
+
this.enterCooldown();
|
|
201
|
+
const body = await res.text().catch(() => "");
|
|
202
|
+
const suffix = this.diagnosticSuffix("deleteMessage", res.status, body);
|
|
203
|
+
throw new TaskingError("feishu_api_status", `feishu deleteMessage failed: ${res.status}${suffix}`, {
|
|
204
|
+
status: res.status,
|
|
205
|
+
body: body.slice(0, 500),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
this.resetCooldown();
|
|
209
|
+
}
|
|
210
|
+
catch (e) {
|
|
211
|
+
if (e instanceof TaskingError)
|
|
212
|
+
throw e;
|
|
213
|
+
throw new TaskingError("feishu_api_request", `feishu deleteMessage request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async uploadFile(content, fileName) {
|
|
217
|
+
this.assertNotCooling();
|
|
218
|
+
const token = await this.getTenantAccessToken();
|
|
219
|
+
const url = `${this.apiBase}/open-apis/im/v1/files`;
|
|
220
|
+
const form = new FormData();
|
|
221
|
+
form.append("file_type", "stream");
|
|
222
|
+
form.append("file_name", fileName);
|
|
223
|
+
form.append("file", new Blob([content]), fileName);
|
|
224
|
+
try {
|
|
225
|
+
const res = await this.fetchWithTimeout(url, {
|
|
226
|
+
method: "POST",
|
|
227
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
228
|
+
body: form,
|
|
229
|
+
}, this.defaultTimeoutMs);
|
|
230
|
+
if (!res.ok) {
|
|
231
|
+
if (res.status === 429)
|
|
232
|
+
this.enterCooldown();
|
|
233
|
+
const body = await res.text().catch(() => "");
|
|
234
|
+
const suffix = this.diagnosticSuffix("uploadFile", res.status, body);
|
|
235
|
+
throw new TaskingError("feishu_api_status", `feishu uploadFile failed: ${res.status}${suffix}`, {
|
|
236
|
+
status: res.status,
|
|
237
|
+
body: body.slice(0, 500),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
this.resetCooldown();
|
|
241
|
+
const data = (await res.json());
|
|
242
|
+
return data.data?.file_key ?? "";
|
|
243
|
+
}
|
|
244
|
+
catch (e) {
|
|
245
|
+
if (e instanceof TaskingError)
|
|
246
|
+
throw e;
|
|
247
|
+
throw new TaskingError("feishu_api_request", `feishu uploadFile request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async sendFileMessage(rootId, fileKey) {
|
|
251
|
+
return this.replyPayload(rootId, "file", JSON.stringify({ file_key: fileKey }), true);
|
|
252
|
+
}
|
|
253
|
+
async replyToMessage(rootId, text, asThread) {
|
|
254
|
+
return this.replyPayload(rootId, "text", JSON.stringify({ text: translate(text) }), asThread);
|
|
255
|
+
}
|
|
256
|
+
async replyPayload(rootId, msgType, content, asThread) {
|
|
257
|
+
this.assertNotCooling();
|
|
258
|
+
const token = await this.getTenantAccessToken();
|
|
259
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages/${encodeURIComponent(rootId)}/reply`;
|
|
260
|
+
const body = {
|
|
261
|
+
msg_type: msgType,
|
|
262
|
+
content,
|
|
263
|
+
};
|
|
264
|
+
if (asThread)
|
|
265
|
+
body.reply_in_thread = true;
|
|
266
|
+
try {
|
|
267
|
+
const res = await this.fetchWithTimeout(url, {
|
|
268
|
+
method: "POST",
|
|
269
|
+
headers: {
|
|
270
|
+
Authorization: `Bearer ${token}`,
|
|
271
|
+
"Content-Type": "application/json",
|
|
272
|
+
},
|
|
273
|
+
body: JSON.stringify(body),
|
|
274
|
+
}, this.defaultTimeoutMs);
|
|
275
|
+
if (!res.ok) {
|
|
276
|
+
if (res.status === 429)
|
|
277
|
+
this.enterCooldown();
|
|
278
|
+
const resBody = await res.text().catch(() => "");
|
|
279
|
+
const suffix = this.diagnosticSuffix(asThread ? "replyInThread" : "replyFlat", res.status, resBody);
|
|
280
|
+
throw new TaskingError("feishu_api_status", `feishu reply${asThread ? "InThread" : "Flat"} failed: ${res.status}${suffix}`, { status: res.status, body: resBody.slice(0, 500) });
|
|
281
|
+
}
|
|
282
|
+
this.resetCooldown();
|
|
283
|
+
const data = (await res.json());
|
|
284
|
+
const msgId = data.data?.message_id ?? "";
|
|
285
|
+
const root = data.data?.root_id ?? null;
|
|
286
|
+
const threadId = data.data?.thread_id ?? null;
|
|
287
|
+
return { message_id: msgId, root_id: root, thread_id: threadId };
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
if (e instanceof TaskingError)
|
|
291
|
+
throw e;
|
|
292
|
+
throw new TaskingError("feishu_api_request", `feishu reply${asThread ? "InThread" : "Flat"} request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
async downloadMessageResource(messageId, fileKey, kind) {
|
|
296
|
+
this.assertNotCooling();
|
|
297
|
+
const token = await this.getTenantAccessToken();
|
|
298
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}/resources/${encodeURIComponent(fileKey)}?type=${kind}`;
|
|
299
|
+
try {
|
|
300
|
+
const res = await this.fetchWithTimeout(url, { method: "GET", headers: { Authorization: `Bearer ${token}` } }, this.defaultTimeoutMs);
|
|
301
|
+
if (!res.ok) {
|
|
302
|
+
if (res.status === 429)
|
|
303
|
+
this.enterCooldown();
|
|
304
|
+
const body = await res.text().catch(() => "");
|
|
305
|
+
const suffix = this.diagnosticSuffix("downloadMessageResource", res.status, body);
|
|
306
|
+
throw new TaskingError("feishu_api_status", `feishu downloadMessageResource failed: ${res.status}${suffix}`, { status: res.status, body: body.slice(0, 500) });
|
|
307
|
+
}
|
|
308
|
+
this.resetCooldown();
|
|
309
|
+
return {
|
|
310
|
+
data: new Uint8Array(await res.arrayBuffer()),
|
|
311
|
+
contentType: res.headers.get("content-type"),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
if (e instanceof TaskingError)
|
|
316
|
+
throw e;
|
|
317
|
+
throw new TaskingError("feishu_api_request", `feishu downloadMessageResource request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async listChatMembers(chatId) {
|
|
321
|
+
this.assertNotCooling();
|
|
322
|
+
const token = await this.getTenantAccessToken();
|
|
323
|
+
const members = [];
|
|
324
|
+
let pageToken = "";
|
|
325
|
+
for (let page = 0; page < 10; page++) {
|
|
326
|
+
const params = new URLSearchParams({ member_id_type: "open_id", page_size: "100" });
|
|
327
|
+
if (pageToken !== "")
|
|
328
|
+
params.set("page_token", pageToken);
|
|
329
|
+
const url = `${this.apiBase}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members?${params.toString()}`;
|
|
330
|
+
try {
|
|
331
|
+
const res = await this.fetchWithTimeout(url, { method: "GET", headers: { Authorization: `Bearer ${token}` } }, this.defaultTimeoutMs);
|
|
332
|
+
if (!res.ok) {
|
|
333
|
+
if (res.status === 429)
|
|
334
|
+
this.enterCooldown();
|
|
335
|
+
const body = await res.text().catch(() => "");
|
|
336
|
+
const suffix = this.diagnosticSuffix("listChatMembers", res.status, body);
|
|
337
|
+
throw new TaskingError("feishu_api_status", `feishu listChatMembers failed: ${res.status}${suffix}`, { status: res.status, body: body.slice(0, 500) });
|
|
338
|
+
}
|
|
339
|
+
this.resetCooldown();
|
|
340
|
+
const data = (await res.json());
|
|
341
|
+
for (const item of data.data?.items ?? []) {
|
|
342
|
+
if (typeof item.member_id === "string" && item.member_id !== "") {
|
|
343
|
+
members.push({
|
|
344
|
+
open_id: item.member_id,
|
|
345
|
+
name: typeof item.name === "string" ? item.name : "",
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (data.data?.has_more !== true || typeof data.data.page_token !== "string")
|
|
350
|
+
break;
|
|
351
|
+
pageToken = data.data.page_token;
|
|
352
|
+
if (pageToken === "")
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
catch (e) {
|
|
356
|
+
if (e instanceof TaskingError)
|
|
357
|
+
throw e;
|
|
358
|
+
throw new TaskingError("feishu_api_request", `feishu listChatMembers request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return members;
|
|
362
|
+
}
|
|
363
|
+
async listMessages(chatId, sinceTime) {
|
|
364
|
+
this.assertNotCooling();
|
|
365
|
+
const token = await this.getTenantAccessToken();
|
|
366
|
+
const nowSec = String(Math.floor(Date.now() / 1000));
|
|
367
|
+
const startTime = this.resolveStartTime(sinceTime);
|
|
368
|
+
const params = new URLSearchParams({
|
|
369
|
+
container_id: chatId,
|
|
370
|
+
container_id_type: "chat",
|
|
371
|
+
end_time: nowSec,
|
|
372
|
+
page_size: "50",
|
|
373
|
+
});
|
|
374
|
+
if (startTime !== null)
|
|
375
|
+
params.set("start_time", startTime);
|
|
376
|
+
return this.listPages(token, params, "listMessages");
|
|
377
|
+
}
|
|
378
|
+
async listThreadReplies(threadId, since) {
|
|
379
|
+
this.assertNotCooling();
|
|
380
|
+
const token = await this.getTenantAccessToken();
|
|
381
|
+
const nowSec = String(Math.floor(Date.now() / 1000));
|
|
382
|
+
const startTime = this.resolveStartTime(since);
|
|
383
|
+
const params = new URLSearchParams({
|
|
384
|
+
container_id: threadId,
|
|
385
|
+
container_id_type: "thread",
|
|
386
|
+
end_time: nowSec,
|
|
387
|
+
page_size: "50",
|
|
388
|
+
});
|
|
389
|
+
if (startTime !== null)
|
|
390
|
+
params.set("start_time", startTime);
|
|
391
|
+
return this.listPages(token, params, "listThreadReplies");
|
|
392
|
+
}
|
|
393
|
+
async listPages(token, params, label, singlePage = false) {
|
|
394
|
+
const all = [];
|
|
395
|
+
let pageToken = null;
|
|
396
|
+
try {
|
|
397
|
+
do {
|
|
398
|
+
if (pageToken !== null)
|
|
399
|
+
params.set("page_token", pageToken);
|
|
400
|
+
const url = `${this.apiBase}/open-apis/im/v1/messages?${params.toString()}`;
|
|
401
|
+
const res = await this.fetchWithTimeout(url, {
|
|
402
|
+
method: "GET",
|
|
403
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
404
|
+
}, this.defaultTimeoutMs);
|
|
405
|
+
if (!res.ok) {
|
|
406
|
+
if (res.status === 429)
|
|
407
|
+
this.enterCooldown();
|
|
408
|
+
const body = await res.text().catch(() => "");
|
|
409
|
+
const suffix = this.diagnosticSuffix(label, res.status, body);
|
|
410
|
+
throw new TaskingError("feishu_api_status", `feishu ${label} failed: ${res.status} ${body.slice(0, 200)}${suffix}`, { status: res.status, body: body.slice(0, 500) });
|
|
411
|
+
}
|
|
412
|
+
this.resetCooldown();
|
|
413
|
+
const data = (await res.json());
|
|
414
|
+
const items = Array.isArray(data.data?.items) ? data.data.items : [];
|
|
415
|
+
for (const item of items)
|
|
416
|
+
all.push(parsePolledMessage(item));
|
|
417
|
+
const hasMore = data.data?.has_more === true;
|
|
418
|
+
const nextToken = typeof data.data?.page_token === "string" ? data.data.page_token : null;
|
|
419
|
+
pageToken =
|
|
420
|
+
!singlePage && hasMore && nextToken !== null && nextToken !== "" ? nextToken : null;
|
|
421
|
+
} while (pageToken !== null);
|
|
422
|
+
return all;
|
|
423
|
+
}
|
|
424
|
+
catch (e) {
|
|
425
|
+
if (e instanceof TaskingError)
|
|
426
|
+
throw e;
|
|
427
|
+
throw new TaskingError("feishu_api_request", `feishu ${label} request failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
resolveStartTime(since) {
|
|
431
|
+
const sinceSec = since ? toSecondsStr(since) : "";
|
|
432
|
+
return sinceSec !== "" ? sinceSec : null;
|
|
433
|
+
}
|
|
434
|
+
async getTenantAccessToken() {
|
|
435
|
+
if (this.tenantAccessToken && Date.now() < this.tokenExpiresAt) {
|
|
436
|
+
return this.tenantAccessToken;
|
|
437
|
+
}
|
|
438
|
+
if (!this.config.app_id || !this.config.app_secret) {
|
|
439
|
+
throw new TaskingError("feishu_missing_credentials", "feishu app_id/app_secret required");
|
|
440
|
+
}
|
|
441
|
+
const url = `${this.apiBase}/open-apis/auth/v3/tenant_access_token/internal`;
|
|
442
|
+
try {
|
|
443
|
+
const res = await this.fetchWithTimeout(url, {
|
|
444
|
+
method: "POST",
|
|
445
|
+
headers: { "Content-Type": "application/json" },
|
|
446
|
+
body: JSON.stringify({
|
|
447
|
+
app_id: this.config.app_id,
|
|
448
|
+
app_secret: this.config.app_secret,
|
|
449
|
+
}),
|
|
450
|
+
}, this.tokenTimeoutMs);
|
|
451
|
+
if (!res.ok) {
|
|
452
|
+
if (res.status === 429)
|
|
453
|
+
this.enterCooldown();
|
|
454
|
+
this.warnTokenEditionHintOnce();
|
|
455
|
+
throw new TaskingError("feishu_api_status", `feishu token failed: ${res.status}`);
|
|
456
|
+
}
|
|
457
|
+
const data = (await res.json());
|
|
458
|
+
this.resetCooldown();
|
|
459
|
+
this.tenantAccessToken = data.tenant_access_token ?? null;
|
|
460
|
+
this.tokenExpiresAt = Date.now() + (data.expire ?? 7200) * 1000 - 60000;
|
|
461
|
+
if (!this.tenantAccessToken) {
|
|
462
|
+
this.warnTokenEditionHintOnce();
|
|
463
|
+
throw new TaskingError("feishu_api_status", "feishu token response missing access token");
|
|
464
|
+
}
|
|
465
|
+
return this.tenantAccessToken;
|
|
466
|
+
}
|
|
467
|
+
catch (e) {
|
|
468
|
+
if (e instanceof TaskingError)
|
|
469
|
+
throw e;
|
|
470
|
+
throw toTaskingError(e);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
export function parseTextContent(content) {
|
|
475
|
+
try {
|
|
476
|
+
const parsed = JSON.parse(content);
|
|
477
|
+
return parsed.text ?? content;
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
return content;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
export function parseMessageAttachments(msgType, content) {
|
|
484
|
+
let parsed = {};
|
|
485
|
+
try {
|
|
486
|
+
parsed = JSON.parse(content);
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
return [];
|
|
490
|
+
}
|
|
491
|
+
if (msgType === "image") {
|
|
492
|
+
const key = typeof parsed.image_key === "string" ? parsed.image_key : "";
|
|
493
|
+
return key === "" ? [] : [{ kind: "image", key, name: "image.png" }];
|
|
494
|
+
}
|
|
495
|
+
if (msgType === "file" || msgType === "media" || msgType === "audio") {
|
|
496
|
+
const key = typeof parsed.file_key === "string" ? parsed.file_key : "";
|
|
497
|
+
if (key === "")
|
|
498
|
+
return [];
|
|
499
|
+
const name = typeof parsed.file_name === "string" && parsed.file_name !== ""
|
|
500
|
+
? parsed.file_name
|
|
501
|
+
: "attachment";
|
|
502
|
+
return [{ kind: "file", key, name }];
|
|
503
|
+
}
|
|
504
|
+
if (msgType !== "post")
|
|
505
|
+
return [];
|
|
506
|
+
const attachments = [];
|
|
507
|
+
let index = 0;
|
|
508
|
+
const lines = Array.isArray(parsed.content) ? parsed.content : [];
|
|
509
|
+
for (const line of lines) {
|
|
510
|
+
if (!Array.isArray(line))
|
|
511
|
+
continue;
|
|
512
|
+
for (const block of line) {
|
|
513
|
+
if (typeof block !== "object" || block === null)
|
|
514
|
+
continue;
|
|
515
|
+
const b = block;
|
|
516
|
+
const tag = typeof b.tag === "string" ? b.tag : "";
|
|
517
|
+
if (tag !== "img")
|
|
518
|
+
continue;
|
|
519
|
+
const key = typeof b.image_key === "string" ? b.image_key : "";
|
|
520
|
+
if (key === "")
|
|
521
|
+
continue;
|
|
522
|
+
index++;
|
|
523
|
+
attachments.push({ kind: "image", key, name: `image-${index}.png` });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return attachments;
|
|
527
|
+
}
|
|
528
|
+
export function isReadableText(msgType) {
|
|
529
|
+
return msgType === "text" || msgType === "post";
|
|
530
|
+
}
|
|
531
|
+
export function flattenPostContent(content) {
|
|
532
|
+
try {
|
|
533
|
+
const parsed = JSON.parse(content);
|
|
534
|
+
if (!Array.isArray(parsed.content))
|
|
535
|
+
return "";
|
|
536
|
+
const lines = [];
|
|
537
|
+
for (const line of parsed.content) {
|
|
538
|
+
if (!Array.isArray(line))
|
|
539
|
+
continue;
|
|
540
|
+
const parts = [];
|
|
541
|
+
for (const block of line) {
|
|
542
|
+
if (typeof block !== "object" || block === null)
|
|
543
|
+
continue;
|
|
544
|
+
const b = block;
|
|
545
|
+
const tag = typeof b.tag === "string" ? b.tag : "";
|
|
546
|
+
const text = typeof b.text === "string" ? b.text : "";
|
|
547
|
+
switch (tag) {
|
|
548
|
+
case "text":
|
|
549
|
+
case "a":
|
|
550
|
+
case "plain_text":
|
|
551
|
+
case "md":
|
|
552
|
+
case "emoji":
|
|
553
|
+
parts.push(text);
|
|
554
|
+
break;
|
|
555
|
+
case "at":
|
|
556
|
+
parts.push(typeof b.user_name === "string" && b.user_name !== "" ? `@${b.user_name}` : "@user");
|
|
557
|
+
break;
|
|
558
|
+
case "img":
|
|
559
|
+
parts.push("[图片]");
|
|
560
|
+
break;
|
|
561
|
+
default:
|
|
562
|
+
break;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
lines.push(parts.join(""));
|
|
566
|
+
}
|
|
567
|
+
const title = typeof parsed.title === "string" && parsed.title.trim() !== "" ? parsed.title.trim() : "";
|
|
568
|
+
const body = lines.filter((l) => l.trim() !== "").join("\n");
|
|
569
|
+
return [title, body].filter((s) => s !== "").join("\n");
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
return "";
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
export function validateFeishuConfig(config) {
|
|
576
|
+
const errors = [];
|
|
577
|
+
if (config.enabled) {
|
|
578
|
+
if (!config.app_id) {
|
|
579
|
+
errors.push(new TaskingError("feishu_missing_credentials", "feishu.app_id is required when enabled"));
|
|
580
|
+
}
|
|
581
|
+
if (!config.app_secret) {
|
|
582
|
+
errors.push(new TaskingError("feishu_missing_credentials", "feishu.app_secret is required when enabled"));
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return errors;
|
|
586
|
+
}
|
|
587
|
+
const TOKEN_CODE_HINTS = {
|
|
588
|
+
10003: "App Secret 不正确",
|
|
589
|
+
10014: "App ID 不正确或应用不存在",
|
|
590
|
+
};
|
|
591
|
+
export async function fetchTenantTokenFor(appId, appSecret, fetchImpl, edition = "feishu") {
|
|
592
|
+
const f = fetchImpl ?? fetch;
|
|
593
|
+
try {
|
|
594
|
+
const res = await f(`${feishuApiBase(edition)}/open-apis/auth/v3/tenant_access_token/internal`, {
|
|
595
|
+
method: "POST",
|
|
596
|
+
headers: { "Content-Type": "application/json" },
|
|
597
|
+
body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
|
|
598
|
+
});
|
|
599
|
+
if (!res.ok)
|
|
600
|
+
return { ok: false, reason: `服务不可用(HTTP ${res.status})` };
|
|
601
|
+
const data = (await res.json());
|
|
602
|
+
if (data.code !== 0 || typeof data.tenant_access_token !== "string") {
|
|
603
|
+
const hint = data.code !== undefined ? TOKEN_CODE_HINTS[data.code] : undefined;
|
|
604
|
+
return { ok: false, reason: hint ?? data.msg ?? "凭据错误或应用未发布版本" };
|
|
605
|
+
}
|
|
606
|
+
return { ok: true, token: data.tenant_access_token };
|
|
607
|
+
}
|
|
608
|
+
catch (e) {
|
|
609
|
+
return { ok: false, reason: `网络不可达(${e instanceof Error ? e.message : String(e)})` };
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
export async function lookupFeishuUserId(token, emailOrMobile, fetchImpl, edition = "feishu") {
|
|
613
|
+
const f = fetchImpl ?? fetch;
|
|
614
|
+
const isEmail = emailOrMobile.includes("@");
|
|
615
|
+
const body = isEmail ? { emails: [emailOrMobile] } : { mobiles: [emailOrMobile] };
|
|
616
|
+
try {
|
|
617
|
+
const res = await f(`${feishuApiBase(edition)}/open-apis/contact/v3/users/batch_get_id?user_id_type=open_id`, {
|
|
618
|
+
method: "POST",
|
|
619
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
|
620
|
+
body: JSON.stringify(body),
|
|
621
|
+
});
|
|
622
|
+
if (!res.ok) {
|
|
623
|
+
const text = await res.text().catch(() => "");
|
|
624
|
+
const permission = res.status === 403 || feishuBodyCode(text) === 230027;
|
|
625
|
+
return {
|
|
626
|
+
ok: false,
|
|
627
|
+
reason: permission ? "permission" : "other",
|
|
628
|
+
detail: `HTTP ${res.status} ${text.slice(0, 120)}`,
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const data = (await res.json());
|
|
632
|
+
const openId = data.data?.user_list?.[0]?.user_id;
|
|
633
|
+
if (typeof openId === "string" && openId !== "") {
|
|
634
|
+
return { ok: true, open_id: openId };
|
|
635
|
+
}
|
|
636
|
+
return { ok: false, reason: "not_found", detail: "未找到对应用户" };
|
|
637
|
+
}
|
|
638
|
+
catch (e) {
|
|
639
|
+
return { ok: false, reason: "other", detail: e instanceof Error ? e.message : String(e) };
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
export async function dismissBotChat(token, chatId, fetchImpl, edition = "feishu") {
|
|
643
|
+
const f = fetchImpl ?? fetch;
|
|
644
|
+
try {
|
|
645
|
+
const res = await f(`${feishuApiBase(edition)}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}`, {
|
|
646
|
+
method: "DELETE",
|
|
647
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
648
|
+
});
|
|
649
|
+
return res.ok;
|
|
650
|
+
}
|
|
651
|
+
catch {
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
export async function createBotChat(token, name, fetchImpl, userIds = [], edition = "feishu") {
|
|
656
|
+
const f = fetchImpl ?? fetch;
|
|
657
|
+
try {
|
|
658
|
+
const res = await f(`${feishuApiBase(edition)}/open-apis/im/v1/chats`, {
|
|
659
|
+
method: "POST",
|
|
660
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
|
661
|
+
body: JSON.stringify({
|
|
662
|
+
name,
|
|
663
|
+
description: "tasking intake",
|
|
664
|
+
chat_mode: "group",
|
|
665
|
+
user_id_list: userIds,
|
|
666
|
+
}),
|
|
667
|
+
});
|
|
668
|
+
if (!res.ok) {
|
|
669
|
+
const body = await res.text().catch(() => "");
|
|
670
|
+
const permission = res.status === 403 || feishuBodyCode(body) === 99991672;
|
|
671
|
+
return {
|
|
672
|
+
ok: false,
|
|
673
|
+
reason: permission ? "permission" : "other",
|
|
674
|
+
detail: `HTTP ${res.status} ${body.slice(0, 120)}`,
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
const data = (await res.json());
|
|
678
|
+
const chatId = typeof data.data?.chat_id === "string" ? data.data.chat_id : "";
|
|
679
|
+
if (chatId === "")
|
|
680
|
+
return { ok: false, reason: "other", detail: "响应缺少 chat_id" };
|
|
681
|
+
return { ok: true, chat_id: chatId };
|
|
682
|
+
}
|
|
683
|
+
catch (e) {
|
|
684
|
+
return { ok: false, reason: "other", detail: e instanceof Error ? e.message : String(e) };
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
export async function listBotChats(token, fetchImpl, edition = "feishu") {
|
|
688
|
+
const f = fetchImpl ?? fetch;
|
|
689
|
+
const chats = [];
|
|
690
|
+
let pageToken = "";
|
|
691
|
+
try {
|
|
692
|
+
for (let page = 0; page < 5; page++) {
|
|
693
|
+
const url = `${feishuApiBase(edition)}/open-apis/im/v1/chats?page_size=100${pageToken === "" ? "" : `&page_token=${encodeURIComponent(pageToken)}`}`;
|
|
694
|
+
const res = await f(url, { headers: { Authorization: `Bearer ${token}` } });
|
|
695
|
+
if (!res.ok)
|
|
696
|
+
return null;
|
|
697
|
+
const data = (await res.json());
|
|
698
|
+
for (const item of data.data?.items ?? []) {
|
|
699
|
+
if (typeof item.chat_id === "string" && typeof item.name === "string" && item.name !== "") {
|
|
700
|
+
chats.push({ chat_id: item.chat_id, name: item.name });
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
if (data.data?.has_more !== true)
|
|
704
|
+
break;
|
|
705
|
+
pageToken = typeof data.data?.page_token === "string" ? data.data.page_token : "";
|
|
706
|
+
if (pageToken === "")
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
return chats;
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
return null;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
//# sourceMappingURL=source.js.map
|