@chenkai114/dsh-superagent-dingtalk 0.0.0-stage → 0.0.2
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 +103 -2
- package/cordis.patch.yml +197 -0
- package/lib/client.js +6883 -0
- package/lib/deployment-DWOTbxsX.js +483 -0
- package/lib/dingtalk-watch.d.ts +221 -0
- package/lib/dingtalk-watch.js +1164 -0
- package/lib/feishu-CQ3D3dWE.js +1325 -0
- package/lib/feishu-watch.d.ts +125 -0
- package/lib/feishu-watch.js +2 -0
- package/lib/github-pull-D87HmHAP.js +596 -0
- package/lib/github-watch.d.ts +2 -0
- package/lib/github-watch.js +833 -0
- package/lib/index.d.ts +369 -0
- package/lib/index.js +10631 -0
- package/lib/intake-Ba9xBNyb.d.ts +734 -0
- package/lib/kind-BlPO15JX.d.ts +959 -0
- package/lib/poll-BWa7O9Kk.js +395 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +147 -4
- package/prompts/admission.md +68 -0
- package/prompts/cli.md +17 -0
- package/prompts/dispatch.md +59 -0
- package/prompts/handoff-orchestrator.md +4 -0
- package/prompts/handoff-worker.md +7 -0
- package/prompts/handoff.md +6 -0
- package/prompts/orchestrator.md +16 -0
- package/prompts/replies.md +35 -0
- package/prompts/shared.md +7 -0
- package/prompts/subscriptions.md +13 -0
- package/prompts/team/communication.md +97 -0
- package/prompts/team/delivery.md +28 -0
- package/prompts/team/scope.md +22 -0
- package/prompts/work.md +49 -0
- package/prompts/worker.md +10 -0
- package/skills/dsh-superagent-feishu/SKILL.md +12 -0
- package/skills/dsh-superagent-github/SKILL.md +14 -0
|
@@ -0,0 +1,1164 @@
|
|
|
1
|
+
import { _ as key, c as sourceContext, d as validItems, o as KV, r as pause } from "./poll-BWa7O9Kk.js";
|
|
2
|
+
import { createHmac } from "node:crypto";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
|
|
5
|
+
//#region src/sources/dingtalk-trigger.ts
|
|
6
|
+
/** Normalizes DingTalk messages from the Stream callback and the dws history read into domain Triggers. */
|
|
7
|
+
const SOURCE = "dingtalk";
|
|
8
|
+
/** Constructs a DingTalk reply channel address; `messageId` is the message a reply quotes, when one is known. */
|
|
9
|
+
const dingtalkChannel = (conversationId, messageId, extra = {}) => ({
|
|
10
|
+
source: SOURCE,
|
|
11
|
+
thread: `${SOURCE}:${conversationId}`,
|
|
12
|
+
address: {
|
|
13
|
+
conversationId,
|
|
14
|
+
...messageId ? { messageId } : {},
|
|
15
|
+
...extra
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
/** One conversation is one Thread: a group's messages and a direct conversation's messages each reply in place. */
|
|
19
|
+
const dingtalkThreadId = (conversationId) => `${SOURCE}:${conversationId}`;
|
|
20
|
+
/** Deterministic Trigger ID for a DingTalk message, so every read path for it produces the same ID and the Engine deduplicates. */
|
|
21
|
+
const dingtalkTriggerId = (messageId) => key(SOURCE, messageId);
|
|
22
|
+
/**
|
|
23
|
+
* Parses a DingTalk timestamp into ISO-8601. The Stream callback sends epoch milliseconds, while `dws chat message list`
|
|
24
|
+
* prints Shanghai wall-clock time without an offset; an unqualified value is read as UTC+08:00.
|
|
25
|
+
* @param value Epoch milliseconds, or `YYYY-MM-DD HH:mm:ss`.
|
|
26
|
+
* @returns The instant as an ISO-8601 string.
|
|
27
|
+
* @throws when the value is neither form.
|
|
28
|
+
*/
|
|
29
|
+
function dingtalkTime(value) {
|
|
30
|
+
if (typeof value === "number" || /^\d{11,}$/.test(String(value))) return new Date(Number(value)).toISOString();
|
|
31
|
+
const text = String(value).trim().replace(" ", "T");
|
|
32
|
+
const time = Date.parse(/[+-]\d{2}:?\d{2}$|Z$/.test(text) ? text : `${text}+08:00`);
|
|
33
|
+
if (!Number.isFinite(time)) throw new Error(`Unreadable DingTalk message time: ${String(value)}`);
|
|
34
|
+
return new Date(time).toISOString();
|
|
35
|
+
}
|
|
36
|
+
/** A message read by `dws chat message list`; `sendType` distinguishes a person from a robot. */
|
|
37
|
+
const DwsMessageSchema = z.looseObject({
|
|
38
|
+
messageId: z.string(),
|
|
39
|
+
openConversationId: z.string().nullish(),
|
|
40
|
+
conversationId: z.string().nullish(),
|
|
41
|
+
createTime: z.string(),
|
|
42
|
+
sender: z.string().default(""),
|
|
43
|
+
senderId: z.string().default(""),
|
|
44
|
+
senderOpenDingTalkId: z.string().nullish(),
|
|
45
|
+
sendType: z.string().default("user"),
|
|
46
|
+
/**
|
|
47
|
+
* Set to `DWS` (and to other tool names later) on a message an AI tool sent through the operator's own account. Such a
|
|
48
|
+
* message is a person's account speaking, not a person: it must never become a request, or the agent would answer itself.
|
|
49
|
+
*/
|
|
50
|
+
messageAiSendFlag: z.string().nullish(),
|
|
51
|
+
text: z.string().default("")
|
|
52
|
+
});
|
|
53
|
+
/**
|
|
54
|
+
* A message as the Stream callback delivers it. A message that addresses the robot arrives as `richText`, whose text is a
|
|
55
|
+
* JSON `content` string, not as `text`; a plain text message carries `text.content` instead.
|
|
56
|
+
*/
|
|
57
|
+
const StreamMessageSchema = z.looseObject({
|
|
58
|
+
msgId: z.string(),
|
|
59
|
+
conversationId: z.string(),
|
|
60
|
+
conversationType: z.string().default("2"),
|
|
61
|
+
conversationTitle: z.string().optional(),
|
|
62
|
+
chatbotUserId: z.string().optional(),
|
|
63
|
+
robotCode: z.string().optional(),
|
|
64
|
+
senderId: z.string().default(""),
|
|
65
|
+
senderNick: z.string().default(""),
|
|
66
|
+
senderStaffId: z.string().optional(),
|
|
67
|
+
createAt: z.number(),
|
|
68
|
+
msgtype: z.string().default("text"),
|
|
69
|
+
text: z.looseObject({ content: z.string().default("") }).optional(),
|
|
70
|
+
/** The rich-text body of a message that addresses the robot; the platform sends it as an object, not JSON text. */
|
|
71
|
+
content: z.union([z.string(), z.looseObject({ richText: z.array(z.looseObject({ text: z.string().optional() })).optional() })]).optional(),
|
|
72
|
+
/** Whether the robot is among the addressed members; the platform sets it for every group message it delivers. */
|
|
73
|
+
isInAtList: z.boolean().optional(),
|
|
74
|
+
sessionWebhook: z.string().optional(),
|
|
75
|
+
sessionWebhookExpiredTime: z.number().optional(),
|
|
76
|
+
atUsers: z.array(z.looseObject({
|
|
77
|
+
dingtalkId: z.string().optional(),
|
|
78
|
+
staffId: z.string().optional()
|
|
79
|
+
})).default([])
|
|
80
|
+
});
|
|
81
|
+
/**
|
|
82
|
+
* Flattens a Stream message body to plain text. A rich-text body is a JSON `content` whose `richText` array carries text
|
|
83
|
+
* runs in order, so a mention and the request that follows it read as one sentence.
|
|
84
|
+
* @param message The message as the Stream callback delivered it.
|
|
85
|
+
* @returns The text, or an empty string when the body carries none this Source can read.
|
|
86
|
+
*/
|
|
87
|
+
function streamText(message) {
|
|
88
|
+
const content = message.content;
|
|
89
|
+
if (content !== void 0) {
|
|
90
|
+
const runs = (typeof content === "string" ? parseRichText(content) : content)?.richText;
|
|
91
|
+
if (Array.isArray(runs)) return runs.map((run) => typeof run?.text === "string" ? run.text : "").join("");
|
|
92
|
+
}
|
|
93
|
+
return message.text?.content ?? "";
|
|
94
|
+
}
|
|
95
|
+
/** Reads a rich-text body the platform sent as a JSON string; anything else reads as no runs. */
|
|
96
|
+
function parseRichText(value) {
|
|
97
|
+
try {
|
|
98
|
+
const parsed = JSON.parse(value);
|
|
99
|
+
return parsed !== null && typeof parsed === "object" ? parsed : void 0;
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Builds a Trigger for a normalized DingTalk message.
|
|
106
|
+
* @param input The message as either transport normalized it.
|
|
107
|
+
* @returns The Trigger, or `undefined` when the text is empty and the message can carry no request.
|
|
108
|
+
*/
|
|
109
|
+
function dingtalkTrigger(input) {
|
|
110
|
+
const text = input.text;
|
|
111
|
+
if (!text.trim()) return void 0;
|
|
112
|
+
const thread = dingtalkThreadId(input.conversationId);
|
|
113
|
+
return {
|
|
114
|
+
id: dingtalkTriggerId(input.messageId),
|
|
115
|
+
source: SOURCE,
|
|
116
|
+
threads: [{
|
|
117
|
+
source: SOURCE,
|
|
118
|
+
id: thread
|
|
119
|
+
}],
|
|
120
|
+
actor: {
|
|
121
|
+
source: SOURCE,
|
|
122
|
+
id: input.senderId
|
|
123
|
+
},
|
|
124
|
+
human: input.human,
|
|
125
|
+
...input.direct ? { addressed: "direct" } : input.mentioned ? { addressed: "mention" } : {},
|
|
126
|
+
at: dingtalkTime(input.at),
|
|
127
|
+
text,
|
|
128
|
+
channel: dingtalkChannel(input.conversationId, input.messageId),
|
|
129
|
+
meta: {
|
|
130
|
+
conversationId: input.conversationId,
|
|
131
|
+
messageId: input.messageId,
|
|
132
|
+
senderName: input.senderName ?? "",
|
|
133
|
+
actorIds: [input.senderId, ...input.senderAliases ?? []].filter((id, index, all) => id && all.indexOf(id) === index),
|
|
134
|
+
sendType: input.human ? "user" : "robot",
|
|
135
|
+
direct: input.direct,
|
|
136
|
+
mentioned: input.mentioned,
|
|
137
|
+
...input.sessionWebhook ? { sessionWebhook: input.sessionWebhook } : {},
|
|
138
|
+
...input.sessionWebhookExpiredTime ? { sessionWebhookExpiredTime: input.sessionWebhookExpiredTime } : {},
|
|
139
|
+
...input.robotCode ? { robotCode: input.robotCode } : {},
|
|
140
|
+
...input.conversationTitle ? { conversationTitle: input.conversationTitle } : {},
|
|
141
|
+
...input.quoteMessageId ? { quoteMessageId: input.quoteMessageId } : {}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
//#endregion
|
|
146
|
+
//#region src/sources/dingtalk-dws.ts
|
|
147
|
+
/** Reads DingTalk conversations through the official `dws` CLI acting as the operator, and sends as a group bot. */
|
|
148
|
+
/** `dws chat message list` prints the page and its completeness; `messages` is what this Source reads. */
|
|
149
|
+
const PageSchema = z.looseObject({
|
|
150
|
+
messages: z.array(z.unknown()).default([]),
|
|
151
|
+
hasMore: z.boolean().default(false)
|
|
152
|
+
});
|
|
153
|
+
/** Formats an instant as the `YYYY-MM-DD HH:mm:ss` in UTC+08:00 that `dws --time` accepts. */
|
|
154
|
+
function dwsTime(instant) {
|
|
155
|
+
const at = new Date(instant);
|
|
156
|
+
if (!Number.isFinite(at.getTime())) throw new Error(`Unreadable cursor time: ${instant}`);
|
|
157
|
+
return new Date(at.getTime() + 288e5).toISOString().slice(0, 19).replace("T", " ");
|
|
158
|
+
}
|
|
159
|
+
/** The message fields this Source reads; `sendType` is what separates a person from a robot. */
|
|
160
|
+
const FIELDS = "messageId,createTime,sender,senderId,senderOpenDingTalkId,sendType,text";
|
|
161
|
+
/**
|
|
162
|
+
* One page of a conversation's messages newer than `since`, oldest first.
|
|
163
|
+
* @param commands The deployment's command runner.
|
|
164
|
+
* @param cli The `dws` command name or absolute path.
|
|
165
|
+
* @param conversationId The conversation's `openConversationId`.
|
|
166
|
+
* @param since Exclusive lower bound; the caller advances it to the newest message it ingested.
|
|
167
|
+
* @param limit Messages per page.
|
|
168
|
+
* @returns The readable messages and whether the conversation has more beyond this page.
|
|
169
|
+
*/
|
|
170
|
+
async function readDwsPage(commands, cli, conversationId, since, limit, direction = "newer") {
|
|
171
|
+
const args = [
|
|
172
|
+
"chat",
|
|
173
|
+
"message",
|
|
174
|
+
"list",
|
|
175
|
+
"--conversation-id",
|
|
176
|
+
conversationId,
|
|
177
|
+
"--direction",
|
|
178
|
+
direction,
|
|
179
|
+
"--limit",
|
|
180
|
+
String(limit),
|
|
181
|
+
"--fields",
|
|
182
|
+
FIELDS,
|
|
183
|
+
"-f",
|
|
184
|
+
"json"
|
|
185
|
+
];
|
|
186
|
+
if (since) args.push("--time", dwsTime(since));
|
|
187
|
+
const page = PageSchema.parse(JSON.parse(await commands.run(cli, args)));
|
|
188
|
+
return {
|
|
189
|
+
messages: validItems(DwsMessageSchema, page.messages),
|
|
190
|
+
hasMore: page.hasMore
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Sends a message as a group bot through the DingTalk OpenAPI, so the message is signed by the bot rather than the operator.
|
|
195
|
+
* @param commands The deployment's command runner.
|
|
196
|
+
* @param cli The `dws` command name or absolute path.
|
|
197
|
+
* @param robotCode The robot that posts, named on the Settings card.
|
|
198
|
+
* @param conversationId The target conversation.
|
|
199
|
+
* @param title The message title the client shows above the body.
|
|
200
|
+
* @param text The Markdown body.
|
|
201
|
+
* @throws CliError when the CLI refuses, such as a robot the group does not contain.
|
|
202
|
+
*/
|
|
203
|
+
async function sendDwsBot(commands, cli, robotCode, conversationId, title, text) {
|
|
204
|
+
await commands.run(cli, [
|
|
205
|
+
"chat",
|
|
206
|
+
"message",
|
|
207
|
+
"send-by-bot",
|
|
208
|
+
"--robot-code",
|
|
209
|
+
robotCode,
|
|
210
|
+
"--conversation-id",
|
|
211
|
+
conversationId,
|
|
212
|
+
"--title",
|
|
213
|
+
title.slice(0, 64),
|
|
214
|
+
"--text",
|
|
215
|
+
text
|
|
216
|
+
]);
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/sources/dingtalk-config.ts
|
|
220
|
+
/** DingTalk Source configuration: which conversations are listened to, and which transports read and write them. */
|
|
221
|
+
/** One conversation the Source listens to; `all` also reads messages that do not address the robot. */
|
|
222
|
+
const DingtalkGroupSchema = z.object({
|
|
223
|
+
conversationId: z.string().trim().min(1),
|
|
224
|
+
name: z.string().trim().max(60).optional(),
|
|
225
|
+
listen: z.enum(["mentions", "all"]).default("mentions")
|
|
226
|
+
}).strict();
|
|
227
|
+
/** A custom group robot: it posts to its own conversation and needs no application credentials. */
|
|
228
|
+
const DingtalkBotSchema = z.object({
|
|
229
|
+
name: z.string().trim().min(1).max(40),
|
|
230
|
+
conversationId: z.string().trim().min(1),
|
|
231
|
+
token: z.string().trim().min(1),
|
|
232
|
+
secret: z.string().trim().min(1).optional()
|
|
233
|
+
}).strict();
|
|
234
|
+
/**
|
|
235
|
+
* The Source configuration. Fields are flat because the Settings form edits top-level keys only; the accessors below
|
|
236
|
+
* group them for the code that uses them.
|
|
237
|
+
*/
|
|
238
|
+
const DingtalkConfigSchema = z.object({
|
|
239
|
+
groups: z.array(DingtalkGroupSchema).refine((groups) => new Set(groups.map((group) => group.conversationId)).size === groups.length, "Duplicate conversation IDs").default([]),
|
|
240
|
+
bots: z.array(DingtalkBotSchema).refine((bots) => new Set(bots.map((bot) => bot.conversationId)).size === bots.length, "Duplicate conversation IDs").default([]),
|
|
241
|
+
/** The application robot whose Stream connection receives messages addressed to it. */
|
|
242
|
+
streamClientId: z.string().trim().default(""),
|
|
243
|
+
streamClientSecret: z.string().trim().default(""),
|
|
244
|
+
/** The robot that posts through the OpenAPI; an application robot uses its AppKey. */
|
|
245
|
+
streamRobotCode: z.string().trim().default(""),
|
|
246
|
+
/** The operator's `dws` CLI, which reads a conversation as the operator. */
|
|
247
|
+
dwsEnabled: z.boolean().default(true),
|
|
248
|
+
dwsCli: z.string().trim().min(1).default("dws"),
|
|
249
|
+
dwsPollSeconds: z.number().int().min(10).max(3600).default(60),
|
|
250
|
+
dwsPageSize: z.number().int().min(1).max(100).default(50),
|
|
251
|
+
/** Robot display names whose `@name` in a message counts as addressing the agent; only a history read needs them. */
|
|
252
|
+
mentionNames: z.array(z.object({ name: z.string().trim().min(1).max(40) }).strict()).refine((entries) => new Set(entries.map((entry) => entry.name)).size === entries.length, "Duplicate robot names").default([]),
|
|
253
|
+
otherChats: z.boolean().default(false),
|
|
254
|
+
directMessages: z.boolean().default(true),
|
|
255
|
+
readPageSize: z.number().int().min(1).max(50).default(20),
|
|
256
|
+
failuresBeforeError: z.number().int().min(1).max(20).default(3)
|
|
257
|
+
}).strict();
|
|
258
|
+
/** The Stream robot credentials, or `undefined` when either half is unset. */
|
|
259
|
+
const streamOf = (config) => config.streamClientId && config.streamClientSecret ? {
|
|
260
|
+
clientId: config.streamClientId,
|
|
261
|
+
clientSecret: config.streamClientSecret,
|
|
262
|
+
...config.streamRobotCode ? { robotCode: config.streamRobotCode } : {}
|
|
263
|
+
} : void 0;
|
|
264
|
+
/** The `dws` settings the readers, the poll loop and the channel share. */
|
|
265
|
+
const dwsOf = (config) => ({
|
|
266
|
+
enabled: config.dwsEnabled,
|
|
267
|
+
cli: config.dwsCli,
|
|
268
|
+
pollSeconds: config.dwsPollSeconds,
|
|
269
|
+
pageSize: config.dwsPageSize
|
|
270
|
+
});
|
|
271
|
+
//#endregion
|
|
272
|
+
//#region src/sources/dingtalk-channel.ts
|
|
273
|
+
/** DingTalk outbound channel: replies in the conversation a message came from, signed by a bot rather than the operator. */
|
|
274
|
+
/** DingTalk rejects a markdown body beyond about 5,000 bytes; the renderer keeps each message well inside that. */
|
|
275
|
+
const MAX_TEXT = 3800;
|
|
276
|
+
/** The heading and body one message renders as: the heading names the purpose, so a reader knows what to do. */
|
|
277
|
+
function render(message) {
|
|
278
|
+
const body = message.text.trim();
|
|
279
|
+
const cut = body.length > MAX_TEXT ? `${body.slice(0, MAX_TEXT)}\n\n…(内容过长已截断,完整内容见面板)` : body;
|
|
280
|
+
switch (message.purpose) {
|
|
281
|
+
case "attention": return {
|
|
282
|
+
title: "需要你决定",
|
|
283
|
+
text: `### 🙋 需要你决定\n\n${cut}\n\n---\n\n直接回复这条消息告诉我你的决定,例如回复序号或补充要求。`
|
|
284
|
+
};
|
|
285
|
+
case "result": return {
|
|
286
|
+
title: "工单结果",
|
|
287
|
+
text: `### ✅ 工单结果\n\n${cut}`
|
|
288
|
+
};
|
|
289
|
+
case "answer": return {
|
|
290
|
+
title: "回答",
|
|
291
|
+
text: `### 💬 回答\n\n${cut}`
|
|
292
|
+
};
|
|
293
|
+
default: return {
|
|
294
|
+
title: "已收到",
|
|
295
|
+
text: `### 👀 已收到\n\n${cut}`
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** The signature a robot that requires one needs, as DingTalk documents it: HMAC-SHA256 over `<timestamp>\n<secret>`. */
|
|
300
|
+
function signed(bot, timestamp) {
|
|
301
|
+
if (!bot.secret) return `timestamp=${timestamp}`;
|
|
302
|
+
const digest = createHmac("sha256", bot.secret).update(`${timestamp}\n${bot.secret}`).digest("base64");
|
|
303
|
+
return `timestamp=${timestamp}&sign=${encodeURIComponent(digest)}`;
|
|
304
|
+
}
|
|
305
|
+
/** Posts a markdown message through a custom group robot, which needs no application credentials. */
|
|
306
|
+
async function sendWebhook(bot, title, text) {
|
|
307
|
+
const timestamp = Date.now();
|
|
308
|
+
const response = await fetch(`https://oapi.dingtalk.com/robot/send?access_token=${encodeURIComponent(bot.token)}&${signed(bot, timestamp)}`, {
|
|
309
|
+
method: "POST",
|
|
310
|
+
headers: { "content-type": "application/json" },
|
|
311
|
+
body: JSON.stringify({
|
|
312
|
+
msgtype: "markdown",
|
|
313
|
+
markdown: {
|
|
314
|
+
title,
|
|
315
|
+
text
|
|
316
|
+
}
|
|
317
|
+
})
|
|
318
|
+
});
|
|
319
|
+
const body = await response.json().catch(() => ({}));
|
|
320
|
+
if (body.errcode !== 0) {
|
|
321
|
+
const gone = body.errcode === 300001 || body.errcode === 31e4;
|
|
322
|
+
const error = /* @__PURE__ */ new Error(`DingTalk robot ${bot.name} refused the message: ${body.errmsg ?? "unknown error"} (${body.errcode ?? response.status})`);
|
|
323
|
+
if (gone) throw Object.assign(error, { gone: true });
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Delivers one message, preferring the reply address the triggering message carried, then a group robot for that
|
|
329
|
+
* conversation, then the application robot through `dws`. Every path signs the message as a bot, never as the operator.
|
|
330
|
+
* @param host The Source context.
|
|
331
|
+
* @param message The queued message.
|
|
332
|
+
* @returns `'gone'` when the conversation can never receive it, so the Outbox stops retrying.
|
|
333
|
+
*/
|
|
334
|
+
async function sendDingtalk(host, message) {
|
|
335
|
+
const config = host.config(SOURCE);
|
|
336
|
+
const conversationId = message.channel.address.conversationId;
|
|
337
|
+
if (!conversationId) throw new Error("Missing DingTalk reply target");
|
|
338
|
+
const { title, text } = render(message);
|
|
339
|
+
const webhook = message.channel.address.sessionWebhook;
|
|
340
|
+
const expiresAt = Number(message.channel.address.sessionWebhookExpiresAt ?? 0);
|
|
341
|
+
if (webhook && (!expiresAt || expiresAt > Date.now())) {
|
|
342
|
+
if ((await fetch(webhook, {
|
|
343
|
+
method: "POST",
|
|
344
|
+
headers: { "content-type": "application/json" },
|
|
345
|
+
body: JSON.stringify({
|
|
346
|
+
msgtype: "markdown",
|
|
347
|
+
markdown: {
|
|
348
|
+
title,
|
|
349
|
+
text
|
|
350
|
+
}
|
|
351
|
+
})
|
|
352
|
+
})).ok) return "sent";
|
|
353
|
+
}
|
|
354
|
+
const bot = config?.bots.find((item) => item.conversationId === conversationId);
|
|
355
|
+
if (bot) {
|
|
356
|
+
try {
|
|
357
|
+
await sendWebhook(bot, title, text);
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (error.gone) return "gone";
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
return "sent";
|
|
363
|
+
}
|
|
364
|
+
const dws = config ? dwsOf(config) : void 0;
|
|
365
|
+
const robotCode = config ? streamOf(config)?.robotCode ?? config.streamClientId : void 0;
|
|
366
|
+
if (dws?.enabled && robotCode) {
|
|
367
|
+
await sendDwsBot(host.commands, dws.cli, robotCode, conversationId, title, text);
|
|
368
|
+
return "sent";
|
|
369
|
+
}
|
|
370
|
+
throw new Error(`No DingTalk sender covers conversation ${conversationId}: set a group robot for it, or enable dws with an application robot code`);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Names the conversation a message went to. DingTalk has no stable web address for a conversation, so the link is empty
|
|
374
|
+
* unless the deployment knows one.
|
|
375
|
+
* @param address The channel address.
|
|
376
|
+
* @param links Deployment links.
|
|
377
|
+
* @returns The label the panel shows.
|
|
378
|
+
*/
|
|
379
|
+
function dingtalkLink(address, links) {
|
|
380
|
+
const name = address.conversationName ?? address.conversationId ?? "";
|
|
381
|
+
return {
|
|
382
|
+
url: links.dingtalk?.[address.conversationId ?? ""] ?? "",
|
|
383
|
+
label: {
|
|
384
|
+
zh: `钉钉群 ${name}`,
|
|
385
|
+
en: `DingTalk chat ${name}`
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
//#endregion
|
|
390
|
+
//#region src/sources/dingtalk-stream.ts
|
|
391
|
+
/** Receives DingTalk robot messages over the official Stream long connection. */
|
|
392
|
+
/**
|
|
393
|
+
* Holds one Stream connection and turns its callbacks into domain messages.
|
|
394
|
+
* A connection the platform refuses means the application robot is not published or its receiving mode is not Stream;
|
|
395
|
+
* the failure is reported once, because a person must change it in the DingTalk developer console.
|
|
396
|
+
*/
|
|
397
|
+
var DingtalkStream = class {
|
|
398
|
+
config;
|
|
399
|
+
handlers;
|
|
400
|
+
client;
|
|
401
|
+
stopped = false;
|
|
402
|
+
constructor(config, handlers) {
|
|
403
|
+
this.config = config;
|
|
404
|
+
this.handlers = handlers;
|
|
405
|
+
}
|
|
406
|
+
/** The robot code this connection receives for. */
|
|
407
|
+
get robotCode() {
|
|
408
|
+
return this.config.robotCode ?? this.config.clientId;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Opens the connection and registers the robot message topic.
|
|
412
|
+
* @throws when the credentials are rejected, so the Source reports the failure instead of waiting silently.
|
|
413
|
+
*/
|
|
414
|
+
async start() {
|
|
415
|
+
const client = new DWClient({
|
|
416
|
+
clientId: this.config.clientId,
|
|
417
|
+
clientSecret: this.config.clientSecret,
|
|
418
|
+
keepAlive: true
|
|
419
|
+
});
|
|
420
|
+
this.client = client;
|
|
421
|
+
client.registerCallbackListener(TOPIC_ROBOT, (frame) => {
|
|
422
|
+
this.handleRobot(frame.data);
|
|
423
|
+
return { status: "SUCCESS" };
|
|
424
|
+
});
|
|
425
|
+
client.on("connect", () => this.handlers.report("ready", `Stream connected as ${this.robotCode}`));
|
|
426
|
+
client.on("disconnect", () => {
|
|
427
|
+
if (!this.stopped) this.handlers.report("starting", "Stream disconnected; reconnecting");
|
|
428
|
+
});
|
|
429
|
+
client.on("error", (error) => this.handlers.report("error", `Stream failed: ${error?.message ?? "unknown error"}`));
|
|
430
|
+
await client.connect();
|
|
431
|
+
}
|
|
432
|
+
/** Closes the connection; a later `start` opens a new one. */
|
|
433
|
+
stop() {
|
|
434
|
+
this.stopped = true;
|
|
435
|
+
try {
|
|
436
|
+
this.client?.disconnect();
|
|
437
|
+
} catch {}
|
|
438
|
+
this.client = void 0;
|
|
439
|
+
}
|
|
440
|
+
handleRobot(data) {
|
|
441
|
+
let parsed;
|
|
442
|
+
try {
|
|
443
|
+
parsed = StreamMessageSchema.safeParse(JSON.parse(data));
|
|
444
|
+
} catch {
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
if (!parsed.success) return;
|
|
448
|
+
const message = parsed.data;
|
|
449
|
+
const direct = message.conversationType === "1";
|
|
450
|
+
if (message.chatbotUserId && message.senderId === message.chatbotUserId) return;
|
|
451
|
+
const input = {
|
|
452
|
+
messageId: message.msgId,
|
|
453
|
+
conversationId: message.conversationId,
|
|
454
|
+
at: message.createAt,
|
|
455
|
+
text: streamText(message),
|
|
456
|
+
senderId: message.senderId,
|
|
457
|
+
senderAliases: [message.senderStaffId, message.senderId].filter((id) => !!id),
|
|
458
|
+
senderName: message.senderNick,
|
|
459
|
+
human: true,
|
|
460
|
+
direct,
|
|
461
|
+
mentioned: !direct && (message.isInAtList ?? true),
|
|
462
|
+
robotCode: message.robotCode ?? this.robotCode,
|
|
463
|
+
conversationTitle: message.conversationTitle
|
|
464
|
+
};
|
|
465
|
+
this.handlers.message(input, input.robotCode ?? this.robotCode).catch((error) => this.handlers.report("error", `Stream message handling failed: ${String(error)}`));
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
//#endregion
|
|
469
|
+
//#region src/sources/dingtalk-loops.ts
|
|
470
|
+
/** DingTalk reception: the Stream long connection for messages addressed to the robot, and `dws` polling for everything a person wrote. */
|
|
471
|
+
/** The health entry every part of this Source reports under. */
|
|
472
|
+
const HEALTH = "dingtalk";
|
|
473
|
+
/**
|
|
474
|
+
* Whether `text` addresses one of the configured robot names. A history read has no structural mention field, so this is
|
|
475
|
+
* the only addressing signal it has; the admission table still decides whether an unaddressed message may become work.
|
|
476
|
+
* @param text The message body.
|
|
477
|
+
* @param names The robot display names to look for.
|
|
478
|
+
* @returns True when the text names one of them with an `@`.
|
|
479
|
+
*/
|
|
480
|
+
function addressedTo(text, names) {
|
|
481
|
+
return names.some((name) => name.length > 0 && text.includes(`@${name}`));
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Whether a message read from history may become a request. A message a tool sent through the operator's account is the
|
|
485
|
+
* agent's own output, and reading it as input would make the agent answer itself.
|
|
486
|
+
* @param message The message as the history read reported it.
|
|
487
|
+
* @returns False for a message the platform marks as sent by an AI tool.
|
|
488
|
+
*/
|
|
489
|
+
const ingestible = (message) => !message.messageAiSendFlag;
|
|
490
|
+
/**
|
|
491
|
+
* Steps a cursor back a few seconds before reading, because DingTalk indexes a message a moment after accepting it: a
|
|
492
|
+
* message indexed late would otherwise carry a time older than the cursor and never be read. The deterministic Trigger ID
|
|
493
|
+
* keeps the overlap from creating a second request.
|
|
494
|
+
* @param cursor The newest instant already ingested.
|
|
495
|
+
* @returns The instant to read from.
|
|
496
|
+
*/
|
|
497
|
+
const readFrom = (cursor) => {
|
|
498
|
+
const at = Date.parse(cursor);
|
|
499
|
+
return Number.isFinite(at) ? (/* @__PURE__ */ new Date(at - 5e3)).toISOString() : cursor;
|
|
500
|
+
};
|
|
501
|
+
/** Normalizes a Shanghai wall-clock timestamp so it can be compared with an ISO cursor. */
|
|
502
|
+
function storableTime(value) {
|
|
503
|
+
const time = Date.parse(/[+-]\d{2}:?\d{2}$|Z$/.test(value) ? value : `${value.replace(" ", "T")}+08:00`);
|
|
504
|
+
return Number.isFinite(time) ? new Date(time).toISOString() : "";
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Reads every configured group's messages newer than the stored cursor and ingests them.
|
|
508
|
+
* A conversation advances its cursor only after its messages are ingested, so a failed run re-reads the same page and the
|
|
509
|
+
* deterministic Trigger ID keeps that from creating a second request.
|
|
510
|
+
* @param host The Source context.
|
|
511
|
+
* @param config The current configuration.
|
|
512
|
+
* @param tally Cleared on success and incremented on failure, so one interrupted read is not reported.
|
|
513
|
+
*/
|
|
514
|
+
async function pollGroups(host, config, tally) {
|
|
515
|
+
const dws = dwsOf(config);
|
|
516
|
+
if (!dws.enabled) return;
|
|
517
|
+
for (const group of config.groups) {
|
|
518
|
+
const key = KV.dingtalk.cursor(group.conversationId);
|
|
519
|
+
const stored = host.state.get(key);
|
|
520
|
+
if (stored === void 0) {
|
|
521
|
+
host.state.set(key, (/* @__PURE__ */ new Date()).toISOString());
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
const page = await readDwsPage(host.commands, dws.cli, group.conversationId, readFrom(stored), dws.pageSize);
|
|
525
|
+
let newest = stored;
|
|
526
|
+
for (const message of page.messages) {
|
|
527
|
+
if (!ingestible(message)) continue;
|
|
528
|
+
const trigger = dingtalkTrigger({
|
|
529
|
+
messageId: message.messageId,
|
|
530
|
+
conversationId: message.openConversationId ?? message.conversationId ?? group.conversationId,
|
|
531
|
+
at: message.createTime,
|
|
532
|
+
text: message.text,
|
|
533
|
+
senderId: message.senderOpenDingTalkId ?? message.senderId,
|
|
534
|
+
senderAliases: [message.senderId, message.senderOpenDingTalkId].filter((id) => !!id),
|
|
535
|
+
senderName: message.sender,
|
|
536
|
+
human: message.sendType === "user",
|
|
537
|
+
direct: false,
|
|
538
|
+
mentioned: addressedTo(message.text, config.mentionNames.map((entry) => entry.name))
|
|
539
|
+
});
|
|
540
|
+
if (trigger) await host.receive(trigger);
|
|
541
|
+
const instant = storableTime(message.createTime);
|
|
542
|
+
if (instant > newest) newest = instant;
|
|
543
|
+
}
|
|
544
|
+
if (newest !== stored) host.state.set(key, newest);
|
|
545
|
+
}
|
|
546
|
+
tally.failures = 0;
|
|
547
|
+
}
|
|
548
|
+
/** Runs one poll, reporting a failure without stopping the loop. */
|
|
549
|
+
async function pollSafely(host, config, tally) {
|
|
550
|
+
try {
|
|
551
|
+
await pollGroups(host, config, tally);
|
|
552
|
+
tally.last = void 0;
|
|
553
|
+
host.report(HEALTH, {
|
|
554
|
+
state: "ready",
|
|
555
|
+
detail: dwsOf(config).enabled ? "Reading configured groups" : "Stream only"
|
|
556
|
+
});
|
|
557
|
+
} catch (error) {
|
|
558
|
+
tally.failures += 1;
|
|
559
|
+
tally.last = error instanceof Error ? error.message : String(error);
|
|
560
|
+
if (tally.failures >= config.failuresBeforeError) host.report(HEALTH, {
|
|
561
|
+
state: "error",
|
|
562
|
+
detail: `${tally.failures} consecutive failed reads; last: ${tally.last}`
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
/** Whether a message belongs to a conversation this Source listens to. */
|
|
567
|
+
const listensTo = (config, conversationId, direct) => direct ? config.directMessages : config.groups.some((group) => group.conversationId === conversationId) || config.otherChats;
|
|
568
|
+
/** Opens the Stream connection and keeps it for as long as the Source runs. */
|
|
569
|
+
async function runStream(host, signal) {
|
|
570
|
+
const config = host.config("dingtalk");
|
|
571
|
+
const stream = config ? streamOf(config) : void 0;
|
|
572
|
+
if (!config || !stream) {
|
|
573
|
+
host.report(HEALTH, {
|
|
574
|
+
state: "ready",
|
|
575
|
+
detail: "Stream robot not configured; reading through dws only"
|
|
576
|
+
});
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const client = new DingtalkStream(stream, {
|
|
580
|
+
async message(input, robotCode) {
|
|
581
|
+
const current = host.config("dingtalk");
|
|
582
|
+
if (!current || !listensTo(current, input.conversationId, input.direct)) return;
|
|
583
|
+
const trigger = dingtalkTrigger({
|
|
584
|
+
...input,
|
|
585
|
+
robotCode
|
|
586
|
+
});
|
|
587
|
+
if (trigger) await host.receive(trigger);
|
|
588
|
+
},
|
|
589
|
+
report(state, detail) {
|
|
590
|
+
host.report(HEALTH, {
|
|
591
|
+
state,
|
|
592
|
+
detail
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
});
|
|
596
|
+
try {
|
|
597
|
+
await client.start();
|
|
598
|
+
} catch (error) {
|
|
599
|
+
host.report(HEALTH, {
|
|
600
|
+
state: "error",
|
|
601
|
+
detail: `Stream failed to start: ${error instanceof Error ? error.message : String(error)}`
|
|
602
|
+
});
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
await new Promise((resolve) => {
|
|
606
|
+
signal.addEventListener("abort", () => {
|
|
607
|
+
resolve();
|
|
608
|
+
}, { once: true });
|
|
609
|
+
});
|
|
610
|
+
client.stop();
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Runs every configured transport until `signal` aborts: the Stream connection, and the `dws` poll loop.
|
|
614
|
+
* @param host The Source context.
|
|
615
|
+
* @param signal Aborts the run, closing the connection.
|
|
616
|
+
*/
|
|
617
|
+
async function runDingtalk(host, signal) {
|
|
618
|
+
if (!host.config("dingtalk")) {
|
|
619
|
+
host.report(HEALTH, {
|
|
620
|
+
state: "ready",
|
|
621
|
+
detail: "DingTalk Source is off"
|
|
622
|
+
});
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
const tally = { failures: 0 };
|
|
626
|
+
const polling = (async () => {
|
|
627
|
+
while (!signal.aborted) {
|
|
628
|
+
const current = host.config("dingtalk");
|
|
629
|
+
if (current) await pollSafely(host, current, tally);
|
|
630
|
+
await pause((current ? dwsOf(current).pollSeconds : 60) * 1e3, signal);
|
|
631
|
+
}
|
|
632
|
+
})();
|
|
633
|
+
await Promise.all([polling, runStream(host, signal)]);
|
|
634
|
+
}
|
|
635
|
+
//#endregion
|
|
636
|
+
//#region src/sources/dingtalk-read.ts
|
|
637
|
+
/** A message as the context reader reports it: `bot` marks a robot, which can never authorize work on its own. */
|
|
638
|
+
const toContext = (message) => ({
|
|
639
|
+
id: message.messageId,
|
|
640
|
+
from: message.sender || message.senderId,
|
|
641
|
+
at: dingtalkTime(message.createTime),
|
|
642
|
+
text: message.text,
|
|
643
|
+
...message.sendType === "robot" ? { bot: true } : {}
|
|
644
|
+
});
|
|
645
|
+
/**
|
|
646
|
+
* Reads one page of the conversation a Trigger came from.
|
|
647
|
+
* @param commands The deployment's command runner.
|
|
648
|
+
* @param trigger The Trigger whose conversation is read.
|
|
649
|
+
* @param part `thread` reads the conversation; `root` and `parent` fall back to it, because DingTalk has no topic roots.
|
|
650
|
+
* @param cursor An ISO instant to read older messages before; the first page when omitted.
|
|
651
|
+
* @param config The reader's configuration.
|
|
652
|
+
* @returns The page, oldest first, and the cursor for the next older page.
|
|
653
|
+
* @throws when `dws` is not enabled, because then no reader can see the conversation.
|
|
654
|
+
*/
|
|
655
|
+
async function readDingtalkThread(commands, trigger, part, cursor, config) {
|
|
656
|
+
if (!config.dwsEnabled) return {
|
|
657
|
+
messages: [],
|
|
658
|
+
body: { reason: "dws is disabled, so no conversation history can be read" }
|
|
659
|
+
};
|
|
660
|
+
const conversationId = String(trigger.meta.conversationId ?? trigger.channel?.address.conversationId ?? "");
|
|
661
|
+
if (!conversationId) return {
|
|
662
|
+
messages: [],
|
|
663
|
+
body: { reason: "the Trigger names no conversation" }
|
|
664
|
+
};
|
|
665
|
+
const size = config.readPageSize ?? 20;
|
|
666
|
+
const page = await readDwsPage(commands, config.dwsCli ?? "dws", conversationId, cursor, size, "older");
|
|
667
|
+
const messages = page.messages.map(toContext).sort((a, b) => a.at.localeCompare(b.at));
|
|
668
|
+
const oldest = page.messages.reduce((last, message) => {
|
|
669
|
+
const at = dingtalkTime(message.createTime);
|
|
670
|
+
return last === void 0 || at < last ? at : last;
|
|
671
|
+
}, void 0);
|
|
672
|
+
return {
|
|
673
|
+
messages,
|
|
674
|
+
...page.hasMore && oldest ? { next: oldest } : {},
|
|
675
|
+
body: {
|
|
676
|
+
conversationId,
|
|
677
|
+
part
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
/** The Thread context a Source kind exposes to assessments. */
|
|
682
|
+
const dingtalkThreadContext = {
|
|
683
|
+
messageId: (trigger) => trigger.channel?.address.messageId ?? String(trigger.meta.messageId ?? ""),
|
|
684
|
+
read: readDingtalkThread
|
|
685
|
+
};
|
|
686
|
+
//#endregion
|
|
687
|
+
//#region src/sources/dingtalk.ts
|
|
688
|
+
const SOURCE$1 = "dingtalk";
|
|
689
|
+
/**
|
|
690
|
+
* DingTalk Source: reads a conversation through the operator's `dws` CLI, receives messages addressed to an application
|
|
691
|
+
* robot over the Stream long connection, and replies as a bot so its words are never attributed to the operator.
|
|
692
|
+
*/
|
|
693
|
+
const dingtalkKind = {
|
|
694
|
+
kind: SOURCE$1,
|
|
695
|
+
title: {
|
|
696
|
+
zh: "钉钉",
|
|
697
|
+
en: "DingTalk"
|
|
698
|
+
},
|
|
699
|
+
description: {
|
|
700
|
+
zh: "读取配置的群和私聊:用 dws 以你本人身份读取全量消息,用 Stream 机器人接收 @ 它的消息;回复一律以机器人身份发出。",
|
|
701
|
+
en: "Reads the configured groups and direct messages: dws reads them as the operator, and a Stream robot receives the messages that address it; every reply is posted as a bot."
|
|
702
|
+
},
|
|
703
|
+
schema: DingtalkConfigSchema,
|
|
704
|
+
fields: [
|
|
705
|
+
{
|
|
706
|
+
key: "groups",
|
|
707
|
+
type: "rows",
|
|
708
|
+
label: {
|
|
709
|
+
zh: "接收的群",
|
|
710
|
+
en: "Groups"
|
|
711
|
+
},
|
|
712
|
+
hint: {
|
|
713
|
+
zh: "点 dws 读取的群与 Stream 接收的群取交集以外的部分由“其他群”和“接收私聊”决定。选“全部消息”时,群里没 @ 机器人的消息也会读到,由策略的接收表决定是否成为候选。",
|
|
714
|
+
en: "The groups read by dws and received by Stream. \"All\" also reads messages that do not address the robot; the Policy admission table decides whether they become candidates."
|
|
715
|
+
},
|
|
716
|
+
columns: [
|
|
717
|
+
{
|
|
718
|
+
key: "conversationId",
|
|
719
|
+
type: "text",
|
|
720
|
+
label: {
|
|
721
|
+
zh: "群 openConversationId",
|
|
722
|
+
en: "Group openConversationId"
|
|
723
|
+
},
|
|
724
|
+
pattern: "[^\\s]+"
|
|
725
|
+
},
|
|
726
|
+
{
|
|
727
|
+
key: "name",
|
|
728
|
+
type: "text",
|
|
729
|
+
label: {
|
|
730
|
+
zh: "群名",
|
|
731
|
+
en: "Name"
|
|
732
|
+
},
|
|
733
|
+
optional: true
|
|
734
|
+
},
|
|
735
|
+
{
|
|
736
|
+
key: "listen",
|
|
737
|
+
type: "select",
|
|
738
|
+
label: {
|
|
739
|
+
zh: "接收",
|
|
740
|
+
en: "Receive"
|
|
741
|
+
},
|
|
742
|
+
options: [{
|
|
743
|
+
value: "mentions",
|
|
744
|
+
label: {
|
|
745
|
+
zh: "仅 @",
|
|
746
|
+
en: "@ only"
|
|
747
|
+
}
|
|
748
|
+
}, {
|
|
749
|
+
value: "all",
|
|
750
|
+
label: {
|
|
751
|
+
zh: "全部消息",
|
|
752
|
+
en: "All"
|
|
753
|
+
}
|
|
754
|
+
}]
|
|
755
|
+
}
|
|
756
|
+
]
|
|
757
|
+
},
|
|
758
|
+
{
|
|
759
|
+
key: "otherChats",
|
|
760
|
+
type: "switch",
|
|
761
|
+
label: {
|
|
762
|
+
zh: "接收其他群里 @ 机器人的消息",
|
|
763
|
+
en: "Receive mentions in other groups"
|
|
764
|
+
}
|
|
765
|
+
},
|
|
766
|
+
{
|
|
767
|
+
key: "directMessages",
|
|
768
|
+
type: "switch",
|
|
769
|
+
label: {
|
|
770
|
+
zh: "接收私聊",
|
|
771
|
+
en: "Direct messages"
|
|
772
|
+
}
|
|
773
|
+
},
|
|
774
|
+
{
|
|
775
|
+
key: "dwsEnabled",
|
|
776
|
+
type: "switch",
|
|
777
|
+
label: {
|
|
778
|
+
zh: "用 dws 读取消息",
|
|
779
|
+
en: "Read messages through dws"
|
|
780
|
+
},
|
|
781
|
+
hint: {
|
|
782
|
+
zh: "以你本人身份读取群消息,能看到没有 @ 机器人的消息和历史。关闭后只能靠 Stream 接收 @ 机器人的消息。",
|
|
783
|
+
en: "Reads a group as the operator, including messages that do not address the robot and their history. When off, only messages that address the robot through Stream are received."
|
|
784
|
+
}
|
|
785
|
+
},
|
|
786
|
+
{
|
|
787
|
+
key: "dwsCli",
|
|
788
|
+
type: "text",
|
|
789
|
+
label: {
|
|
790
|
+
zh: "dws 命令",
|
|
791
|
+
en: "dws command"
|
|
792
|
+
},
|
|
793
|
+
hint: {
|
|
794
|
+
zh: "命令名或绝对路径。执行器以 dws 调用它读取消息;智能体不得以它发送消息,发送只走机器人身份。",
|
|
795
|
+
en: "A command name or absolute path. Executors call it as dws to read; agents must never send with it, because sending is bot-signed only."
|
|
796
|
+
}
|
|
797
|
+
},
|
|
798
|
+
{
|
|
799
|
+
key: "mentionNames",
|
|
800
|
+
type: "rows",
|
|
801
|
+
label: {
|
|
802
|
+
zh: "机器人显示名",
|
|
803
|
+
en: "Robot display names"
|
|
804
|
+
},
|
|
805
|
+
hint: {
|
|
806
|
+
zh: "dws 读到的消息没有结构化的 @ 信息,只能按文本里的“@名字”判断有没有 @ 机器人。填机器人在群里的显示名。",
|
|
807
|
+
en: "A message read by dws carries no structured mention, so \"@name\" in the text is the only signal; enter the robot's display name in the group."
|
|
808
|
+
},
|
|
809
|
+
columns: [{
|
|
810
|
+
key: "name",
|
|
811
|
+
type: "text",
|
|
812
|
+
label: {
|
|
813
|
+
zh: "名字",
|
|
814
|
+
en: "Name"
|
|
815
|
+
},
|
|
816
|
+
pattern: ".{1,40}"
|
|
817
|
+
}]
|
|
818
|
+
},
|
|
819
|
+
{
|
|
820
|
+
key: "streamClientId",
|
|
821
|
+
type: "text",
|
|
822
|
+
label: {
|
|
823
|
+
zh: "Stream 机器人 ClientID(AppKey)",
|
|
824
|
+
en: "Stream robot ClientID (AppKey)"
|
|
825
|
+
},
|
|
826
|
+
hint: {
|
|
827
|
+
zh: "企业内部应用的 AppKey。应用需添加机器人能力、消息接收模式选 Stream,并发布版本。留空则不接收 Stream 消息。",
|
|
828
|
+
en: "The AppKey of the internal application. The application needs the robot capability, Stream as its receiving mode, and a published version. Leave empty to receive nothing over Stream."
|
|
829
|
+
}
|
|
830
|
+
},
|
|
831
|
+
{
|
|
832
|
+
key: "streamClientSecret",
|
|
833
|
+
type: "text",
|
|
834
|
+
label: {
|
|
835
|
+
zh: "Stream 机器人 Client*",
|
|
836
|
+
en: "Stream robot Client*"
|
|
837
|
+
}
|
|
838
|
+
},
|
|
839
|
+
{
|
|
840
|
+
key: "streamRobotCode",
|
|
841
|
+
type: "text",
|
|
842
|
+
label: {
|
|
843
|
+
zh: "发送用 robotCode",
|
|
844
|
+
en: "robotCode for sending"
|
|
845
|
+
},
|
|
846
|
+
hint: {
|
|
847
|
+
zh: "没有配置群机器人时,用它经 dws 以机器人身份发送。留空则用 AppKey。",
|
|
848
|
+
en: "Used through dws to post as a bot when no group robot covers a conversation. Defaults to the AppKey."
|
|
849
|
+
}
|
|
850
|
+
},
|
|
851
|
+
{
|
|
852
|
+
key: "bots",
|
|
853
|
+
type: "rows",
|
|
854
|
+
label: {
|
|
855
|
+
zh: "群机器人(webhook)",
|
|
856
|
+
en: "Group robots (webhook)"
|
|
857
|
+
},
|
|
858
|
+
hint: {
|
|
859
|
+
zh: "每个群一个自定义机器人,只管发不管收;有加签时填 *。它的回复署名是机器人,不会冒充你。",
|
|
860
|
+
en: "One custom robot per group; it only posts and receives nothing. Fill the * when the robot signs its requests. Its messages are signed by the robot and never impersonate the operator."
|
|
861
|
+
},
|
|
862
|
+
columns: [
|
|
863
|
+
{
|
|
864
|
+
key: "name",
|
|
865
|
+
type: "text",
|
|
866
|
+
label: {
|
|
867
|
+
zh: "名字",
|
|
868
|
+
en: "Name"
|
|
869
|
+
},
|
|
870
|
+
pattern: ".{1,40}"
|
|
871
|
+
},
|
|
872
|
+
{
|
|
873
|
+
key: "conversationId",
|
|
874
|
+
type: "text",
|
|
875
|
+
label: {
|
|
876
|
+
zh: "群 openConversationId",
|
|
877
|
+
en: "Group openConversationId"
|
|
878
|
+
},
|
|
879
|
+
pattern: "[^\\s]+"
|
|
880
|
+
},
|
|
881
|
+
{
|
|
882
|
+
key: "token",
|
|
883
|
+
type: "text",
|
|
884
|
+
label: {
|
|
885
|
+
zh: "access_token",
|
|
886
|
+
en: "access_token"
|
|
887
|
+
},
|
|
888
|
+
pattern: "[^\\s]+"
|
|
889
|
+
},
|
|
890
|
+
{
|
|
891
|
+
key: "secret",
|
|
892
|
+
type: "text",
|
|
893
|
+
label: {
|
|
894
|
+
zh: "*(可选)",
|
|
895
|
+
en: "* (optional)"
|
|
896
|
+
},
|
|
897
|
+
optional: true
|
|
898
|
+
}
|
|
899
|
+
]
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
key: "dwsPollSeconds",
|
|
903
|
+
type: "number",
|
|
904
|
+
advanced: true,
|
|
905
|
+
min: 10,
|
|
906
|
+
max: 3600,
|
|
907
|
+
label: {
|
|
908
|
+
zh: "轮询间隔 / 秒",
|
|
909
|
+
en: "Polling interval / seconds"
|
|
910
|
+
}
|
|
911
|
+
},
|
|
912
|
+
{
|
|
913
|
+
key: "dwsPageSize",
|
|
914
|
+
type: "number",
|
|
915
|
+
advanced: true,
|
|
916
|
+
min: 1,
|
|
917
|
+
max: 100,
|
|
918
|
+
label: {
|
|
919
|
+
zh: "每次读取条数",
|
|
920
|
+
en: "Messages per read"
|
|
921
|
+
}
|
|
922
|
+
},
|
|
923
|
+
{
|
|
924
|
+
key: "readPageSize",
|
|
925
|
+
type: "number",
|
|
926
|
+
advanced: true,
|
|
927
|
+
min: 1,
|
|
928
|
+
max: 50,
|
|
929
|
+
label: {
|
|
930
|
+
zh: "线程上下文每页条数",
|
|
931
|
+
en: "Thread context page size"
|
|
932
|
+
}
|
|
933
|
+
},
|
|
934
|
+
{
|
|
935
|
+
key: "failuresBeforeError",
|
|
936
|
+
type: "number",
|
|
937
|
+
advanced: true,
|
|
938
|
+
min: 1,
|
|
939
|
+
max: 20,
|
|
940
|
+
label: {
|
|
941
|
+
zh: "连续失败几次后报告异常",
|
|
942
|
+
en: "Failed reads before reporting an error"
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
],
|
|
946
|
+
health: ["dingtalk"],
|
|
947
|
+
scope({ meta }, config) {
|
|
948
|
+
if (meta.direct === true) return config.directMessages ? {
|
|
949
|
+
listened: true,
|
|
950
|
+
observed: false,
|
|
951
|
+
row: "direct"
|
|
952
|
+
} : {
|
|
953
|
+
listened: false,
|
|
954
|
+
reason: "direct_messages_not_allowed"
|
|
955
|
+
};
|
|
956
|
+
const group = config.groups.find((item) => item.conversationId === meta.conversationId);
|
|
957
|
+
if (group) return {
|
|
958
|
+
listened: true,
|
|
959
|
+
observed: group.listen === "all",
|
|
960
|
+
row: group.conversationId
|
|
961
|
+
};
|
|
962
|
+
return config.otherChats ? {
|
|
963
|
+
listened: true,
|
|
964
|
+
observed: false,
|
|
965
|
+
row: "other"
|
|
966
|
+
} : {
|
|
967
|
+
listened: false,
|
|
968
|
+
reason: "chat_not_allowed"
|
|
969
|
+
};
|
|
970
|
+
},
|
|
971
|
+
channel: {
|
|
972
|
+
allowed: (address, config) => dingtalkKind.scope({ meta: {
|
|
973
|
+
conversationId: address.conversationId ?? "",
|
|
974
|
+
direct: address.direct === "true"
|
|
975
|
+
} }, config).listened,
|
|
976
|
+
send: sendDingtalk,
|
|
977
|
+
link: dingtalkLink
|
|
978
|
+
},
|
|
979
|
+
threadContext: dingtalkThreadContext,
|
|
980
|
+
find: (query) => ({
|
|
981
|
+
threads: [],
|
|
982
|
+
terms: [...new Set(query.match(/cid\/[A-Za-z0-9+/=]+/g) ?? [])]
|
|
983
|
+
}),
|
|
984
|
+
policy: {
|
|
985
|
+
unnamed: {
|
|
986
|
+
person: {
|
|
987
|
+
zh: "钉钉用户",
|
|
988
|
+
en: "DingTalk user"
|
|
989
|
+
},
|
|
990
|
+
bot: {
|
|
991
|
+
zh: "钉钉机器人",
|
|
992
|
+
en: "DingTalk bot"
|
|
993
|
+
}
|
|
994
|
+
},
|
|
995
|
+
schema: z.object({
|
|
996
|
+
allowed: z.array(z.object({
|
|
997
|
+
id: z.string().trim().min(1),
|
|
998
|
+
name: z.string().trim().max(100).optional()
|
|
999
|
+
}).strict()).refine((users) => new Set(users.map((user) => user.id)).size === users.length, "Duplicate ids").default([]),
|
|
1000
|
+
bots: z.array(z.object({
|
|
1001
|
+
id: z.string().trim().min(1),
|
|
1002
|
+
name: z.string().trim().max(100).optional()
|
|
1003
|
+
}).strict()).refine((bots) => new Set(bots.map((bot) => bot.id)).size === bots.length, "Duplicate ids").optional()
|
|
1004
|
+
}).strict(),
|
|
1005
|
+
fields: [{
|
|
1006
|
+
key: "allowed",
|
|
1007
|
+
type: "rows",
|
|
1008
|
+
label: {
|
|
1009
|
+
zh: "能发起工作的钉钉用户",
|
|
1010
|
+
en: "DingTalk users who may originate work"
|
|
1011
|
+
},
|
|
1012
|
+
hint: {
|
|
1013
|
+
zh: "填成员的 staffId 或 openDingTalkId。名单为空时任何请求都不会成为工单。",
|
|
1014
|
+
en: "Fill a member's staffId or openDingTalkId. While the list is empty no request can become a Ticket."
|
|
1015
|
+
},
|
|
1016
|
+
columns: [{
|
|
1017
|
+
key: "id",
|
|
1018
|
+
type: "text",
|
|
1019
|
+
label: {
|
|
1020
|
+
zh: "staffId / openDingTalkId",
|
|
1021
|
+
en: "staffId / openDingTalkId"
|
|
1022
|
+
},
|
|
1023
|
+
pattern: "[^\\s]+"
|
|
1024
|
+
}, {
|
|
1025
|
+
key: "name",
|
|
1026
|
+
type: "text",
|
|
1027
|
+
label: {
|
|
1028
|
+
zh: "名字",
|
|
1029
|
+
en: "Name"
|
|
1030
|
+
},
|
|
1031
|
+
optional: true
|
|
1032
|
+
}]
|
|
1033
|
+
}, {
|
|
1034
|
+
key: "bots",
|
|
1035
|
+
type: "rows",
|
|
1036
|
+
label: {
|
|
1037
|
+
zh: "消息可以成为候选的机器人",
|
|
1038
|
+
en: "Bots whose messages may become candidates"
|
|
1039
|
+
},
|
|
1040
|
+
hint: {
|
|
1041
|
+
zh: "名单里的机器人发的消息成为推断的候选,交给评估;它们不能发起明确的请求,也不能停止工单。",
|
|
1042
|
+
en: "Messages of a bot on this list become inferred candidates for an assessment; they never make an explicit request or stop a ticket."
|
|
1043
|
+
},
|
|
1044
|
+
columns: [{
|
|
1045
|
+
key: "id",
|
|
1046
|
+
type: "text",
|
|
1047
|
+
label: {
|
|
1048
|
+
zh: "openDingTalkId",
|
|
1049
|
+
en: "openDingTalkId"
|
|
1050
|
+
},
|
|
1051
|
+
pattern: "[^\\s]+"
|
|
1052
|
+
}, {
|
|
1053
|
+
key: "name",
|
|
1054
|
+
type: "text",
|
|
1055
|
+
label: {
|
|
1056
|
+
zh: "名字",
|
|
1057
|
+
en: "Name"
|
|
1058
|
+
},
|
|
1059
|
+
optional: true
|
|
1060
|
+
}]
|
|
1061
|
+
}],
|
|
1062
|
+
explicit: {
|
|
1063
|
+
zh: "名单内的人 @ 机器人或私聊机器人,总是明确的请求。",
|
|
1064
|
+
en: "Someone on the list who mentions the robot or messages it directly always makes an explicit request."
|
|
1065
|
+
},
|
|
1066
|
+
rows(stored) {
|
|
1067
|
+
const config = DingtalkConfigSchema.parse(stored);
|
|
1068
|
+
const mentions = {
|
|
1069
|
+
zh: "仅 @",
|
|
1070
|
+
en: "@ only"
|
|
1071
|
+
};
|
|
1072
|
+
return [
|
|
1073
|
+
...config.groups.map((group) => ({
|
|
1074
|
+
id: group.conversationId,
|
|
1075
|
+
label: group.name || group.conversationId,
|
|
1076
|
+
note: group.listen === "all" ? {
|
|
1077
|
+
zh: "全部消息",
|
|
1078
|
+
en: "All"
|
|
1079
|
+
} : mentions,
|
|
1080
|
+
cells: {
|
|
1081
|
+
listedUnaddressed: group.listen === "all",
|
|
1082
|
+
unlistedAddressed: true,
|
|
1083
|
+
unlistedUnaddressed: group.listen === "all"
|
|
1084
|
+
}
|
|
1085
|
+
})),
|
|
1086
|
+
{
|
|
1087
|
+
id: "other",
|
|
1088
|
+
label: {
|
|
1089
|
+
zh: "其他群",
|
|
1090
|
+
en: "Other groups"
|
|
1091
|
+
},
|
|
1092
|
+
note: config.otherChats ? mentions : {
|
|
1093
|
+
zh: "不接收",
|
|
1094
|
+
en: "Not received"
|
|
1095
|
+
},
|
|
1096
|
+
cells: {
|
|
1097
|
+
listedUnaddressed: false,
|
|
1098
|
+
unaddressedAddressed: false,
|
|
1099
|
+
unlistedAddressed: config.otherChats,
|
|
1100
|
+
unlistedUnaddressed: false
|
|
1101
|
+
}
|
|
1102
|
+
},
|
|
1103
|
+
{
|
|
1104
|
+
id: "direct",
|
|
1105
|
+
label: {
|
|
1106
|
+
zh: "私聊",
|
|
1107
|
+
en: "Direct messages"
|
|
1108
|
+
},
|
|
1109
|
+
note: config.directMessages ? {
|
|
1110
|
+
zh: "接收",
|
|
1111
|
+
en: "Received"
|
|
1112
|
+
} : {
|
|
1113
|
+
zh: "不接收",
|
|
1114
|
+
en: "Not received"
|
|
1115
|
+
},
|
|
1116
|
+
cells: {
|
|
1117
|
+
listedUnaddressed: false,
|
|
1118
|
+
unlistedAddressed: config.directMessages,
|
|
1119
|
+
unlistedUnaddressed: false
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
];
|
|
1123
|
+
}
|
|
1124
|
+
},
|
|
1125
|
+
environment: {
|
|
1126
|
+
variables: [{
|
|
1127
|
+
key: "DSH_SUPERAGENT_DINGTALK_CHAT",
|
|
1128
|
+
description: {
|
|
1129
|
+
zh: "接下工单的钉钉会话 openConversationId;工单不是从钉钉来的时为空",
|
|
1130
|
+
en: "openConversationId of the DingTalk conversation that started the ticket; empty when the ticket did not start on DingTalk"
|
|
1131
|
+
}
|
|
1132
|
+
}, {
|
|
1133
|
+
key: "DSH_SUPERAGENT_DINGTALK_ROBOT",
|
|
1134
|
+
description: {
|
|
1135
|
+
zh: "接收这条消息的机器人;回复一律以机器人身份发出,不得以你本人名义发言",
|
|
1136
|
+
en: "The robot that received the message. Every reply is posted as a bot and must never speak as the operator"
|
|
1137
|
+
}
|
|
1138
|
+
}],
|
|
1139
|
+
values: ({ trigger }) => ({
|
|
1140
|
+
DSH_SUPERAGENT_DINGTALK_CHAT: trigger?.source === SOURCE$1 ? String(trigger.meta.conversationId ?? "") : "",
|
|
1141
|
+
DSH_SUPERAGENT_DINGTALK_ROBOT: trigger?.source === SOURCE$1 ? String(trigger.meta.robotCode ?? "") : ""
|
|
1142
|
+
})
|
|
1143
|
+
},
|
|
1144
|
+
facts: (deployment) => deployment ? {} : {}
|
|
1145
|
+
};
|
|
1146
|
+
const name = "dsh-superagent-dingtalk";
|
|
1147
|
+
const inject = ["orchestrator"];
|
|
1148
|
+
/**
|
|
1149
|
+
* Registers the DingTalk Source kind and runs its transports.
|
|
1150
|
+
* @param ctx The Cordis context the bundle mounts in.
|
|
1151
|
+
*/
|
|
1152
|
+
function apply(ctx) {
|
|
1153
|
+
ctx.effect(() => ctx.orchestrator.sources.register(dingtalkKind), "dingtalk: source kind");
|
|
1154
|
+
ctx.effect(() => {
|
|
1155
|
+
const controller = new AbortController();
|
|
1156
|
+
const running = runDingtalk(sourceContext(ctx.orchestrator, dingtalkKind), controller.signal);
|
|
1157
|
+
return async () => {
|
|
1158
|
+
controller.abort();
|
|
1159
|
+
await running;
|
|
1160
|
+
};
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
//#endregion
|
|
1164
|
+
export { DingtalkConfigSchema, DingtalkStream, SOURCE, StreamMessageSchema, addressedTo, apply, dingtalkChannel, dingtalkKind, dingtalkThreadId, dingtalkTime, dingtalkTrigger, dingtalkTriggerId, dwsOf, inject, name, runDingtalk, streamOf, streamText };
|