@agent-dock/cli 0.3.26-alpha.20261127.1 → 0.3.26
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/dist/cli.js +2299 -215
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
- package/public/assets/{ImageLightbox-grJCsR4t.js → ImageLightbox-YDlbaRH6.js} +1 -1
- package/public/assets/PromptEditor-BTyntjMc.js +17 -0
- package/public/assets/index-B-OYCYdp.css +1 -0
- package/public/assets/main-DT9E5c9a.js +1384 -0
- package/public/assets/main-ZPee2kLL.css +32 -0
- package/public/assets/{sourcesRouter-qDCVf0Tw.js → sourcesRouter-BHsOmuuI.js} +1 -1
- package/public/index.html +4 -4
- package/public/sources-router.html +3 -3
- package/public/assets/PromptEditor-bg0qzPOr.js +0 -22
- package/public/assets/index-DvciGSwD.css +0 -1
- package/public/assets/main-D1J9EIXz.js +0 -1375
- package/public/assets/main-D8qGdbGV.css +0 -32
- /package/public/assets/{index-RtJf6Gxv.js → index-DuwbW0Zw.js} +0 -0
package/dist/cli.js
CHANGED
|
@@ -2694,6 +2694,7 @@ var init_service = __esm({
|
|
|
2694
2694
|
const chatId = String(item.chat_id ?? "").trim();
|
|
2695
2695
|
if (!chatId.startsWith("oc_")) return [];
|
|
2696
2696
|
const description = String(item.description ?? "").trim() || void 0;
|
|
2697
|
+
const avatar = String(item.avatar ?? "").trim() || void 0;
|
|
2697
2698
|
const ownerId = String(item.owner_id ?? "").trim() || void 0;
|
|
2698
2699
|
const chatMode = String(item.chat_mode ?? "").trim() || void 0;
|
|
2699
2700
|
const chatStatus = String(item.chat_status ?? "").trim() || void 0;
|
|
@@ -2701,6 +2702,7 @@ var init_service = __esm({
|
|
|
2701
2702
|
chatId,
|
|
2702
2703
|
name: String(item.name ?? "").trim() || chatId,
|
|
2703
2704
|
...description ? { description } : {},
|
|
2705
|
+
...avatar ? { avatar } : {},
|
|
2704
2706
|
...ownerId ? { ownerId } : {},
|
|
2705
2707
|
external: item.external === true,
|
|
2706
2708
|
...chatMode ? { chatMode } : {},
|
|
@@ -2809,6 +2811,8 @@ var init_service = __esm({
|
|
|
2809
2811
|
}));
|
|
2810
2812
|
const updateTime = String(item?.update_time ?? "").trim() || void 0;
|
|
2811
2813
|
const threadId = String(item?.thread_id ?? "").trim() || void 0;
|
|
2814
|
+
const rootId = String(item?.root_id ?? "").trim() || void 0;
|
|
2815
|
+
const parentId = String(item?.parent_id ?? "").trim() || void 0;
|
|
2812
2816
|
const itemChatId = String(item?.chat_id ?? "").trim() || void 0;
|
|
2813
2817
|
const upperMessageId = String(item?.upper_message_id ?? "").trim() || void 0;
|
|
2814
2818
|
return {
|
|
@@ -2823,6 +2827,8 @@ var init_service = __esm({
|
|
|
2823
2827
|
...itemChatId ? { chatId: itemChatId } : {},
|
|
2824
2828
|
...updateTime ? { updateTime } : {},
|
|
2825
2829
|
...threadId ? { threadId } : {},
|
|
2830
|
+
...rootId ? { rootId } : {},
|
|
2831
|
+
...parentId ? { parentId } : {},
|
|
2826
2832
|
...upperMessageId ? { upperMessageId } : {}
|
|
2827
2833
|
};
|
|
2828
2834
|
}
|
|
@@ -4554,6 +4560,1081 @@ var init_side_chat_config = __esm({
|
|
|
4554
4560
|
}
|
|
4555
4561
|
});
|
|
4556
4562
|
|
|
4563
|
+
// src/lark/regex-triggers.ts
|
|
4564
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
4565
|
+
import vm from "node:vm";
|
|
4566
|
+
import safeRegex2 from "safe-regex2";
|
|
4567
|
+
function detectRiskyRegexStructure(pattern) {
|
|
4568
|
+
let depth = 0;
|
|
4569
|
+
let maxDepth = 0;
|
|
4570
|
+
let inClass = false;
|
|
4571
|
+
let escaped = false;
|
|
4572
|
+
for (let i = 0; i < pattern.length; i++) {
|
|
4573
|
+
const ch = pattern[i];
|
|
4574
|
+
if (escaped) {
|
|
4575
|
+
escaped = false;
|
|
4576
|
+
continue;
|
|
4577
|
+
}
|
|
4578
|
+
if (ch === "\\") {
|
|
4579
|
+
escaped = true;
|
|
4580
|
+
continue;
|
|
4581
|
+
}
|
|
4582
|
+
if (ch === "[" && !inClass) {
|
|
4583
|
+
inClass = true;
|
|
4584
|
+
continue;
|
|
4585
|
+
}
|
|
4586
|
+
if (ch === "]" && inClass) {
|
|
4587
|
+
inClass = false;
|
|
4588
|
+
continue;
|
|
4589
|
+
}
|
|
4590
|
+
if (inClass) continue;
|
|
4591
|
+
if (ch === "(") {
|
|
4592
|
+
depth++;
|
|
4593
|
+
if (depth > maxDepth) maxDepth = depth;
|
|
4594
|
+
} else if (ch === ")") {
|
|
4595
|
+
depth = Math.max(0, depth - 1);
|
|
4596
|
+
}
|
|
4597
|
+
}
|
|
4598
|
+
if (maxDepth > 12) {
|
|
4599
|
+
return "\u6B63\u5219\u8868\u8FBE\u5F0F\u5206\u7EC4\u5D4C\u5957\u8FC7\u6DF1\uFF08\u6700\u591A 12 \u5C42\uFF09\uFF0C\u8BF7\u7B80\u5316\u8868\u8FBE\u5F0F";
|
|
4600
|
+
}
|
|
4601
|
+
if (/\\[1-9]\s*(?:[*+?]|{\d+,)/.test(pattern)) {
|
|
4602
|
+
return "\u6B63\u5219\u8868\u8FBE\u5F0F\u5305\u542B\u5E26\u91CF\u8BCD\u7684\u53CD\u5411\u5F15\u7528\uFF0C\u53EF\u80FD\u9020\u6210\u707E\u96BE\u6027\u56DE\u6EAF\uFF0C\u8BF7\u6539\u5199";
|
|
4603
|
+
}
|
|
4604
|
+
if (/\(\?[=!<][^)]*(?:[*+]|{\d+,})[^)]*\)\s*(?:[*+?]|{\d+,})/.test(pattern)) {
|
|
4605
|
+
return "\u6B63\u5219\u8868\u8FBE\u5F0F\u5305\u542B\u590D\u6742\u91CF\u5316\u7684\u65AD\u8A00\u7ED3\u6784\uFF0C\u53EF\u80FD\u5F15\u53D1\u56DE\u6EAF\u98CE\u9669\uFF0C\u8BF7\u7B80\u5316";
|
|
4606
|
+
}
|
|
4607
|
+
return void 0;
|
|
4608
|
+
}
|
|
4609
|
+
function validateLarkTriggerRegex(pattern, rawFlags = LARK_REGEX_DEFAULT_FLAGS) {
|
|
4610
|
+
const source2 = typeof pattern === "string" ? pattern : "";
|
|
4611
|
+
const flagsInput = typeof rawFlags === "string" ? rawFlags.trim() : LARK_REGEX_DEFAULT_FLAGS;
|
|
4612
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4613
|
+
const invalidChars = [];
|
|
4614
|
+
for (const ch of flagsInput) {
|
|
4615
|
+
if (ch === "g") continue;
|
|
4616
|
+
if (allowedRegexFlags.has(ch)) seen.add(ch);
|
|
4617
|
+
else invalidChars.push(ch);
|
|
4618
|
+
}
|
|
4619
|
+
const normalizedFlags = flagOrder.filter((flag) => seen.has(flag)).join("");
|
|
4620
|
+
if (invalidChars.length > 0) {
|
|
4621
|
+
return {
|
|
4622
|
+
valid: false,
|
|
4623
|
+
normalizedFlags,
|
|
4624
|
+
error: `\u4E0D\u652F\u6301\u7684\u6B63\u5219\u6807\u5FD7\u4F4D\uFF1A${[...new Set(invalidChars)].join("\u3001")}\uFF08\u4EC5\u652F\u6301 i\u3001m\u3001s\u3001u\uFF09`
|
|
4625
|
+
};
|
|
4626
|
+
}
|
|
4627
|
+
if (!source2.trim()) {
|
|
4628
|
+
return { valid: false, normalizedFlags, error: "\u8BF7\u8F93\u5165\u6B63\u5219\u8868\u8FBE\u5F0F" };
|
|
4629
|
+
}
|
|
4630
|
+
if (source2.length > LARK_REGEX_MAX_PATTERN_LENGTH) {
|
|
4631
|
+
return { valid: false, normalizedFlags, error: `\u6B63\u5219\u8868\u8FBE\u5F0F\u8FC7\u957F\uFF08\u6700\u591A ${LARK_REGEX_MAX_PATTERN_LENGTH} \u4E2A\u5B57\u7B26\uFF09` };
|
|
4632
|
+
}
|
|
4633
|
+
try {
|
|
4634
|
+
new RegExp(source2, normalizedFlags);
|
|
4635
|
+
} catch (error) {
|
|
4636
|
+
return {
|
|
4637
|
+
valid: false,
|
|
4638
|
+
normalizedFlags,
|
|
4639
|
+
error: `\u6B63\u5219\u8868\u8FBE\u5F0F\u8BED\u6CD5\u9519\u8BEF\uFF1A${error instanceof Error ? error.message : String(error)}`
|
|
4640
|
+
};
|
|
4641
|
+
}
|
|
4642
|
+
const structureIssue = detectRiskyRegexStructure(source2);
|
|
4643
|
+
if (structureIssue) {
|
|
4644
|
+
return { valid: false, normalizedFlags, error: structureIssue };
|
|
4645
|
+
}
|
|
4646
|
+
if (!safeRegex2(source2)) {
|
|
4647
|
+
return {
|
|
4648
|
+
valid: false,
|
|
4649
|
+
normalizedFlags,
|
|
4650
|
+
error: "\u6B63\u5219\u8868\u8FBE\u5F0F\u53EF\u80FD\u9020\u6210\u707E\u96BE\u6027\u56DE\u6EAF\uFF08ReDoS\uFF09\uFF0C\u8BF7\u907F\u514D\u5D4C\u5957\u91CF\u8BCD\u6216\u91CD\u53E0\u5206\u652F"
|
|
4651
|
+
};
|
|
4652
|
+
}
|
|
4653
|
+
return { valid: true, normalizedFlags };
|
|
4654
|
+
}
|
|
4655
|
+
function matchLarkTriggerMessages(pattern, flags, messages, options = {}) {
|
|
4656
|
+
const validation = validateLarkTriggerRegex(pattern, flags);
|
|
4657
|
+
if (!validation.valid) {
|
|
4658
|
+
return {
|
|
4659
|
+
valid: false,
|
|
4660
|
+
error: validation.error,
|
|
4661
|
+
normalizedFlags: validation.normalizedFlags,
|
|
4662
|
+
totalCount: messages.length,
|
|
4663
|
+
matchedCount: 0,
|
|
4664
|
+
results: []
|
|
4665
|
+
};
|
|
4666
|
+
}
|
|
4667
|
+
const ignoreBots = options.ignoreBotMessages === true;
|
|
4668
|
+
const maxMatches = Math.min(LARK_REGEX_MAX_MATCHES_PER_MESSAGE, Math.max(1, options.maxMatchesPerMessage ?? LARK_REGEX_MAX_MATCHES_PER_MESSAGE));
|
|
4669
|
+
const timeoutMs = Math.min(500, Math.max(20, options.timeoutMs ?? 150));
|
|
4670
|
+
const scanFlags = validation.normalizedFlags.includes("g") ? validation.normalizedFlags : `${validation.normalizedFlags}g`;
|
|
4671
|
+
const skippedFlags = messages.map((item) => ignoreBots && (item.senderType === "app" || item.senderType === "bot"));
|
|
4672
|
+
const texts = messages.map((item, index) => skippedFlags[index] ? null : String(item.text ?? ""));
|
|
4673
|
+
try {
|
|
4674
|
+
const context = vm.createContext({
|
|
4675
|
+
__pattern: pattern,
|
|
4676
|
+
__flags: scanFlags,
|
|
4677
|
+
__texts: texts,
|
|
4678
|
+
__maxTextLen: LARK_REGEX_MAX_TEXT_LENGTH,
|
|
4679
|
+
__maxMatches: maxMatches
|
|
4680
|
+
});
|
|
4681
|
+
const rawResults = VM_BATCH_MATCH_SCRIPT.runInContext(context, { timeout: timeoutMs });
|
|
4682
|
+
let matchedCount = 0;
|
|
4683
|
+
const results = messages.map((item, index) => {
|
|
4684
|
+
if (skippedFlags[index]) {
|
|
4685
|
+
return { messageId: item.messageId, matched: false, skippedBot: true, matches: [] };
|
|
4686
|
+
}
|
|
4687
|
+
const entry = rawResults[index] ?? { matched: false, matches: [] };
|
|
4688
|
+
if (entry.matched) matchedCount += 1;
|
|
4689
|
+
return {
|
|
4690
|
+
messageId: item.messageId,
|
|
4691
|
+
matched: entry.matched,
|
|
4692
|
+
matches: entry.matches
|
|
4693
|
+
};
|
|
4694
|
+
});
|
|
4695
|
+
return {
|
|
4696
|
+
valid: true,
|
|
4697
|
+
normalizedFlags: validation.normalizedFlags,
|
|
4698
|
+
totalCount: messages.length,
|
|
4699
|
+
matchedCount,
|
|
4700
|
+
results
|
|
4701
|
+
};
|
|
4702
|
+
} catch (error) {
|
|
4703
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4704
|
+
const isTimeout = /timed out/i.test(message);
|
|
4705
|
+
return {
|
|
4706
|
+
valid: false,
|
|
4707
|
+
error: isTimeout ? "\u6B63\u5219\u5339\u914D\u8D85\u65F6\uFF0C\u53EF\u80FD\u5B58\u5728\u56DE\u6EAF\u6027\u80FD\u98CE\u9669\uFF0C\u8BF7\u7B80\u5316\u6B63\u5219\u8868\u8FBE\u5F0F" : `\u6B63\u5219\u6267\u884C\u5931\u8D25\uFF1A${message}`,
|
|
4708
|
+
normalizedFlags: validation.normalizedFlags,
|
|
4709
|
+
totalCount: messages.length,
|
|
4710
|
+
matchedCount: 0,
|
|
4711
|
+
results: []
|
|
4712
|
+
};
|
|
4713
|
+
}
|
|
4714
|
+
}
|
|
4715
|
+
function matchLarkTriggerText(pattern, flags, text3, options = {}) {
|
|
4716
|
+
const preview = matchLarkTriggerMessages(
|
|
4717
|
+
pattern,
|
|
4718
|
+
flags,
|
|
4719
|
+
[{ messageId: "_single", text: text3 }],
|
|
4720
|
+
{ timeoutMs: options.timeoutMs ?? 50 }
|
|
4721
|
+
);
|
|
4722
|
+
if (!preview.valid) {
|
|
4723
|
+
return { valid: false, matched: false, matches: [], matchedText: "", error: preview.error };
|
|
4724
|
+
}
|
|
4725
|
+
const first = preview.results[0];
|
|
4726
|
+
const matches = first?.matches ?? [];
|
|
4727
|
+
const matchedText = matches.map((span) => span.text).filter(Boolean).slice(0, 5).join(" | ");
|
|
4728
|
+
return {
|
|
4729
|
+
valid: true,
|
|
4730
|
+
matched: Boolean(first?.matched),
|
|
4731
|
+
matches,
|
|
4732
|
+
matchedText
|
|
4733
|
+
};
|
|
4734
|
+
}
|
|
4735
|
+
function formatLarkMessageTime(rawTime) {
|
|
4736
|
+
const trimmed = String(rawTime ?? "").trim();
|
|
4737
|
+
if (!trimmed) return (/* @__PURE__ */ new Date()).toLocaleString("zh-CN", { hour12: false });
|
|
4738
|
+
if (/^\d{10,13}$/.test(trimmed)) {
|
|
4739
|
+
const ms = trimmed.length === 10 ? Number(trimmed) * 1e3 : Number(trimmed);
|
|
4740
|
+
const date = new Date(ms);
|
|
4741
|
+
if (!Number.isNaN(date.getTime())) {
|
|
4742
|
+
return date.toLocaleString("zh-CN", { hour12: false });
|
|
4743
|
+
}
|
|
4744
|
+
}
|
|
4745
|
+
const parsed = new Date(trimmed);
|
|
4746
|
+
if (!Number.isNaN(parsed.getTime())) {
|
|
4747
|
+
return parsed.toLocaleString("zh-CN", { hour12: false });
|
|
4748
|
+
}
|
|
4749
|
+
return trimmed;
|
|
4750
|
+
}
|
|
4751
|
+
function larkCreateTimeToIso(rawTime) {
|
|
4752
|
+
const trimmed = String(rawTime ?? "").trim();
|
|
4753
|
+
if (/^\d{10,13}$/.test(trimmed)) {
|
|
4754
|
+
const ms = trimmed.length === 10 ? Number(trimmed) * 1e3 : Number(trimmed);
|
|
4755
|
+
const date = new Date(ms);
|
|
4756
|
+
if (!Number.isNaN(date.getTime())) return date.toISOString();
|
|
4757
|
+
}
|
|
4758
|
+
if (trimmed) {
|
|
4759
|
+
const parsed = new Date(trimmed);
|
|
4760
|
+
if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
|
|
4761
|
+
}
|
|
4762
|
+
return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
4763
|
+
}
|
|
4764
|
+
function buildRegexTriggerPrompt(input) {
|
|
4765
|
+
const chatName = input.chatName?.trim() || input.chatId;
|
|
4766
|
+
const botName = input.botName?.trim() || input.botId;
|
|
4767
|
+
const ruleName = input.ruleName?.trim() || "\u4E34\u65F6\u6B63\u5219\u8865\u507F";
|
|
4768
|
+
const senderName = input.senderName?.trim() || input.senderId?.trim() || "\u7FA4\u6210\u5458";
|
|
4769
|
+
const messageTime2 = formatLarkMessageTime(input.messageTime);
|
|
4770
|
+
const messageText = input.messageText.trim() || "\uFF08\u7A7A\u6D88\u606F\uFF09";
|
|
4771
|
+
const matchedText = input.matchedText?.trim() || "\uFF08\u6B63\u5219\u547D\u4E2D\uFF09";
|
|
4772
|
+
const flags = input.flags ?? LARK_REGEX_DEFAULT_FLAGS;
|
|
4773
|
+
const vars = {
|
|
4774
|
+
chatName,
|
|
4775
|
+
chatId: input.chatId,
|
|
4776
|
+
botName,
|
|
4777
|
+
ruleName,
|
|
4778
|
+
pattern: input.pattern,
|
|
4779
|
+
senderName,
|
|
4780
|
+
messageTime: messageTime2,
|
|
4781
|
+
messageText,
|
|
4782
|
+
matchedText
|
|
4783
|
+
};
|
|
4784
|
+
const template = (input.promptTemplate ?? "").trim();
|
|
4785
|
+
const renderedTemplate = template ? template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (full, key) => Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : full) : "";
|
|
4786
|
+
const triggerLabel2 = input.triggerType === "backfill" ? "\u5386\u53F2\u6D88\u606F\u8865\u507F\u89E6\u53D1" : "\u5B9E\u65F6\u7FA4\u804A\u76D1\u542C\u81EA\u52A8\u89E6\u53D1";
|
|
4787
|
+
const replyModeLabel = input.replyMode === "thread" ? "\u8BDD\u9898\u5185\u5524\u8D77\uFF08reply_in_thread \u56DE\u590D\u539F\u6D88\u606F\uFF09" : "\u4E3B\u7EBF\u7A0B\u5524\u8D77\uFF08\u5728\u7FA4\u804A\u4E3B\u7EBF\u7A0B\u56DE\u590D\u5E76\u5B9A\u4F4D\u539F\u6D88\u606F\uFF09";
|
|
4788
|
+
const senderDetail = input.senderId && input.senderId !== senderName ? `${senderName}\uFF08${input.senderId}\uFF09` : senderName;
|
|
4789
|
+
const baseContextBlock = [
|
|
4790
|
+
"[\u7FA4\u804A\u6B63\u5219\u81EA\u52A8\u5524\u8D77 \xB7 \u57FA\u7840\u4E0A\u4E0B\u6587]",
|
|
4791
|
+
`- \u89E6\u53D1\u65B9\u5F0F\uFF1A${triggerLabel2}`,
|
|
4792
|
+
`- \u6240\u5728\u7FA4\u804A\uFF1A${chatName}\uFF08chat_id: ${input.chatId}\uFF09`,
|
|
4793
|
+
`- \u6240\u5C5E\u673A\u5668\u4EBA\uFF1A${botName}\uFF08app_id: ${input.botId}\uFF09`,
|
|
4794
|
+
`- \u547D\u4E2D\u89C4\u5219\uFF1A${ruleName}\uFF08/${input.pattern}/${flags}\uFF09`,
|
|
4795
|
+
`- \u5524\u8D77\u6A21\u5F0F\uFF1A${replyModeLabel}`,
|
|
4796
|
+
`- \u6D88\u606F\u53D1\u9001\u4EBA\uFF1A${senderDetail}`,
|
|
4797
|
+
`- \u6D88\u606F\u65F6\u95F4\uFF1A${messageTime2}`,
|
|
4798
|
+
`- \u6D88\u606F ID\uFF1A${input.messageId}`,
|
|
4799
|
+
`- \u6B63\u5219\u547D\u4E2D\u7247\u6BB5\uFF1A${matchedText}`,
|
|
4800
|
+
"- \u539F\u59CB\u7FA4\u804A\u6D88\u606F\uFF1A",
|
|
4801
|
+
messageText
|
|
4802
|
+
].join("\n");
|
|
4803
|
+
return renderedTemplate ? `${renderedTemplate}
|
|
4804
|
+
|
|
4805
|
+
${baseContextBlock}` : baseContextBlock;
|
|
4806
|
+
}
|
|
4807
|
+
function normalizeRule(raw) {
|
|
4808
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
4809
|
+
const item = raw;
|
|
4810
|
+
const id = String(item.id ?? "").trim();
|
|
4811
|
+
const botId = String(item.botId ?? "").trim();
|
|
4812
|
+
const chatId = String(item.chatId ?? "").trim();
|
|
4813
|
+
const pattern = String(item.pattern ?? "");
|
|
4814
|
+
if (!id || !botId || !chatId.startsWith("oc_") || !pattern.trim()) return void 0;
|
|
4815
|
+
const replyMode = item.replyMode === "main" ? "main" : "thread";
|
|
4816
|
+
const flags = typeof item.flags === "string" ? item.flags : LARK_REGEX_DEFAULT_FLAGS;
|
|
4817
|
+
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
4818
|
+
return {
|
|
4819
|
+
id,
|
|
4820
|
+
name: String(item.name ?? "").trim() || "\u672A\u547D\u540D\u6B63\u5219\u89C4\u5219",
|
|
4821
|
+
enabled: item.enabled !== false,
|
|
4822
|
+
botId,
|
|
4823
|
+
chatId,
|
|
4824
|
+
chatName: String(item.chatName ?? "").trim() || chatId,
|
|
4825
|
+
pattern,
|
|
4826
|
+
flags,
|
|
4827
|
+
replyMode,
|
|
4828
|
+
promptTemplate: String(item.promptTemplate ?? ""),
|
|
4829
|
+
...item.presetId ? { presetId: String(item.presetId).trim() } : {},
|
|
4830
|
+
ignoreBotMessages: item.ignoreBotMessages !== false,
|
|
4831
|
+
createdAt: String(item.createdAt ?? now2),
|
|
4832
|
+
updatedAt: String(item.updatedAt ?? now2)
|
|
4833
|
+
};
|
|
4834
|
+
}
|
|
4835
|
+
function normalizeHit(raw) {
|
|
4836
|
+
if (!raw || typeof raw !== "object") return void 0;
|
|
4837
|
+
const item = raw;
|
|
4838
|
+
const ruleId = String(item.ruleId ?? "").trim();
|
|
4839
|
+
const botId = String(item.botId ?? "").trim();
|
|
4840
|
+
const chatId = String(item.chatId ?? "").trim();
|
|
4841
|
+
const messageId = String(item.messageId ?? "").trim();
|
|
4842
|
+
if (!ruleId || !botId || !chatId || !messageId) return void 0;
|
|
4843
|
+
return {
|
|
4844
|
+
id: String(item.id ?? `${ruleId}:${messageId}`),
|
|
4845
|
+
ruleId,
|
|
4846
|
+
botId,
|
|
4847
|
+
chatId,
|
|
4848
|
+
messageId,
|
|
4849
|
+
...item.sessionId ? { sessionId: String(item.sessionId) } : {},
|
|
4850
|
+
...item.cardMessageId ? { cardMessageId: String(item.cardMessageId) } : {},
|
|
4851
|
+
matchedText: String(item.matchedText ?? ""),
|
|
4852
|
+
...item.senderName ? { senderName: String(item.senderName) } : {},
|
|
4853
|
+
...item.messagePreview ? { messagePreview: String(item.messagePreview) } : {},
|
|
4854
|
+
triggerType: item.triggerType === "backfill" ? "backfill" : "realtime",
|
|
4855
|
+
status: item.status === "failed" ? "failed" : "triggered",
|
|
4856
|
+
...item.error ? { error: String(item.error) } : {},
|
|
4857
|
+
triggeredAt: String(item.triggeredAt ?? (/* @__PURE__ */ new Date()).toISOString())
|
|
4858
|
+
};
|
|
4859
|
+
}
|
|
4860
|
+
async function readRulesState(repository) {
|
|
4861
|
+
const raw = await repository?.get(larkRegexTriggersConfigKey);
|
|
4862
|
+
if (!raw) return { raw, rules: [] };
|
|
4863
|
+
try {
|
|
4864
|
+
const parsed = JSON.parse(raw);
|
|
4865
|
+
if (!Array.isArray(parsed)) return { raw, rules: [] };
|
|
4866
|
+
return {
|
|
4867
|
+
raw,
|
|
4868
|
+
rules: parsed.map(normalizeRule).filter((item) => Boolean(item))
|
|
4869
|
+
};
|
|
4870
|
+
} catch {
|
|
4871
|
+
return { raw, rules: [] };
|
|
4872
|
+
}
|
|
4873
|
+
}
|
|
4874
|
+
async function writeRulesState(repository, raw, rules) {
|
|
4875
|
+
const serialized = JSON.stringify(rules);
|
|
4876
|
+
if (repository.compareAndSet) return repository.compareAndSet(larkRegexTriggersConfigKey, raw, serialized);
|
|
4877
|
+
await repository.set(larkRegexTriggersConfigKey, serialized);
|
|
4878
|
+
return true;
|
|
4879
|
+
}
|
|
4880
|
+
async function readHitsState(repository) {
|
|
4881
|
+
const raw = await repository?.get(larkRegexTriggerHitsConfigKey);
|
|
4882
|
+
if (!raw) return { raw, hits: [] };
|
|
4883
|
+
try {
|
|
4884
|
+
const parsed = JSON.parse(raw);
|
|
4885
|
+
if (!Array.isArray(parsed)) return { raw, hits: [] };
|
|
4886
|
+
return {
|
|
4887
|
+
raw,
|
|
4888
|
+
hits: parsed.map(normalizeHit).filter((item) => Boolean(item))
|
|
4889
|
+
};
|
|
4890
|
+
} catch {
|
|
4891
|
+
return { raw, hits: [] };
|
|
4892
|
+
}
|
|
4893
|
+
}
|
|
4894
|
+
async function writeHitsState(repository, raw, hits) {
|
|
4895
|
+
const bounded = hits.length > LARK_REGEX_MAX_HITS_LEDGER ? hits.slice(-LARK_REGEX_MAX_HITS_LEDGER) : hits;
|
|
4896
|
+
const serialized = JSON.stringify(bounded);
|
|
4897
|
+
if (repository.compareAndSet) return repository.compareAndSet(larkRegexTriggerHitsConfigKey, raw, serialized);
|
|
4898
|
+
await repository.set(larkRegexTriggerHitsConfigKey, serialized);
|
|
4899
|
+
return true;
|
|
4900
|
+
}
|
|
4901
|
+
async function readLarkRegexTriggerRules(repository) {
|
|
4902
|
+
return (await readRulesState(repository)).rules;
|
|
4903
|
+
}
|
|
4904
|
+
async function readLarkRegexTriggerHits(repository) {
|
|
4905
|
+
return (await readHitsState(repository)).hits;
|
|
4906
|
+
}
|
|
4907
|
+
async function listLarkRegexTriggerRulesWithStats(repository) {
|
|
4908
|
+
const [rules, hits] = await Promise.all([readLarkRegexTriggerRules(repository), readLarkRegexTriggerHits(repository)]);
|
|
4909
|
+
const stats = /* @__PURE__ */ new Map();
|
|
4910
|
+
for (const hit of hits) {
|
|
4911
|
+
if (hit.status !== "triggered") continue;
|
|
4912
|
+
const current = stats.get(hit.ruleId) ?? { count: 0 };
|
|
4913
|
+
current.count += 1;
|
|
4914
|
+
if (!current.lastTriggeredAt || hit.triggeredAt > current.lastTriggeredAt) {
|
|
4915
|
+
current.lastTriggeredAt = hit.triggeredAt;
|
|
4916
|
+
}
|
|
4917
|
+
stats.set(hit.ruleId, current);
|
|
4918
|
+
}
|
|
4919
|
+
return rules.map((rule) => {
|
|
4920
|
+
const stat7 = stats.get(rule.id);
|
|
4921
|
+
return {
|
|
4922
|
+
...rule,
|
|
4923
|
+
hitCount: stat7?.count ?? 0,
|
|
4924
|
+
...stat7?.lastTriggeredAt ? { lastTriggeredAt: stat7.lastTriggeredAt } : {}
|
|
4925
|
+
};
|
|
4926
|
+
});
|
|
4927
|
+
}
|
|
4928
|
+
async function createLarkRegexTriggerRule(repository, bots, input) {
|
|
4929
|
+
if (!repository) throw new LarkServiceError("LARK_CONFIG_STORAGE_UNAVAILABLE", "\u6301\u4E45\u5316\u5B58\u50A8\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u4FDD\u5B58\u6B63\u5219\u89C4\u5219", 503);
|
|
4930
|
+
const botId = String(input.botId ?? "").trim();
|
|
4931
|
+
if (!botId) throw new LarkServiceError("INVALID_REGEX_RULE", "\u8BF7\u9009\u62E9\u98DE\u4E66\u673A\u5668\u4EBA", 400);
|
|
4932
|
+
if (!bots.some((bot) => bot.appId === botId)) {
|
|
4933
|
+
throw new LarkServiceError("LARK_BOT_NOT_FOUND", `\u672A\u627E\u5230\u98DE\u4E66\u673A\u5668\u4EBA\uFF1A${botId}`, 404);
|
|
4934
|
+
}
|
|
4935
|
+
const chatId = String(input.chatId ?? "").trim();
|
|
4936
|
+
if (!chatId.startsWith("oc_")) {
|
|
4937
|
+
throw new LarkServiceError("INVALID_CHAT_ID", "\u8BF7\u9009\u62E9\u6709\u6548\u7684\u98DE\u4E66\u7FA4\u804A\uFF08chatId \u987B\u4EE5 oc_ \u5F00\u5934\uFF09", 400);
|
|
4938
|
+
}
|
|
4939
|
+
const replyMode = input.replyMode === "main" ? "main" : input.replyMode === "thread" || input.replyMode === void 0 ? "thread" : (() => {
|
|
4940
|
+
throw new LarkServiceError("INVALID_REPLY_MODE", "\u5524\u8D77\u6A21\u5F0F\u4EC5\u652F\u6301 thread\uFF08\u8BDD\u9898\uFF09\u6216 main\uFF08\u4E3B\u7EBF\u7A0B\uFF09", 400);
|
|
4941
|
+
})();
|
|
4942
|
+
const pattern = String(input.pattern ?? "");
|
|
4943
|
+
const validation = validateLarkTriggerRegex(pattern, input.flags ?? LARK_REGEX_DEFAULT_FLAGS);
|
|
4944
|
+
if (!validation.valid) {
|
|
4945
|
+
throw new LarkServiceError("INVALID_REGEX_PATTERN", validation.error, 400);
|
|
4946
|
+
}
|
|
4947
|
+
const chatName = String(input.chatName ?? "").trim() || chatId;
|
|
4948
|
+
const name = String(input.name ?? "").trim() || `${chatName} \u6B63\u5219\u5524\u8D77`;
|
|
4949
|
+
const now2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
4950
|
+
const rule = {
|
|
4951
|
+
id: `lrt_${randomUUID5().slice(0, 12)}`,
|
|
4952
|
+
name,
|
|
4953
|
+
enabled: input.enabled !== false,
|
|
4954
|
+
botId,
|
|
4955
|
+
chatId,
|
|
4956
|
+
chatName,
|
|
4957
|
+
pattern,
|
|
4958
|
+
flags: validation.normalizedFlags,
|
|
4959
|
+
replyMode,
|
|
4960
|
+
promptTemplate: String(input.promptTemplate ?? ""),
|
|
4961
|
+
...input.presetId ? { presetId: String(input.presetId).trim() } : {},
|
|
4962
|
+
ignoreBotMessages: input.ignoreBotMessages !== false,
|
|
4963
|
+
createdAt: now2,
|
|
4964
|
+
updatedAt: now2
|
|
4965
|
+
};
|
|
4966
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4967
|
+
const { raw, rules } = await readRulesState(repository);
|
|
4968
|
+
if (await writeRulesState(repository, raw, [...rules, rule])) return rule;
|
|
4969
|
+
}
|
|
4970
|
+
throw new LarkServiceError("LARK_CONFIG_CONFLICT", "\u89C4\u5219\u6B63\u5728\u88AB\u5E76\u53D1\u66F4\u65B0\uFF0C\u8BF7\u91CD\u8BD5", 409);
|
|
4971
|
+
}
|
|
4972
|
+
async function updateLarkRegexTriggerRule(repository, bots, id, patch) {
|
|
4973
|
+
if (!repository) throw new LarkServiceError("LARK_CONFIG_STORAGE_UNAVAILABLE", "\u6301\u4E45\u5316\u5B58\u50A8\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u66F4\u65B0\u6B63\u5219\u89C4\u5219", 503);
|
|
4974
|
+
const targetId = id.trim();
|
|
4975
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
4976
|
+
const { raw, rules } = await readRulesState(repository);
|
|
4977
|
+
const index = rules.findIndex((item) => item.id === targetId);
|
|
4978
|
+
if (index < 0) throw new LarkServiceError("REGEX_RULE_NOT_FOUND", `\u672A\u627E\u5230\u6B63\u5219\u76D1\u542C\u89C4\u5219\uFF1A${targetId}`, 404);
|
|
4979
|
+
const current = rules[index];
|
|
4980
|
+
const botId = patch.botId === void 0 ? current.botId : String(patch.botId).trim();
|
|
4981
|
+
if (!botId || !bots.some((bot) => bot.appId === botId)) {
|
|
4982
|
+
throw new LarkServiceError("LARK_BOT_NOT_FOUND", `\u672A\u627E\u5230\u98DE\u4E66\u673A\u5668\u4EBA\uFF1A${botId || "(\u7A7A)"}`, 404);
|
|
4983
|
+
}
|
|
4984
|
+
const chatId = patch.chatId === void 0 ? current.chatId : String(patch.chatId).trim();
|
|
4985
|
+
if (!chatId.startsWith("oc_")) {
|
|
4986
|
+
throw new LarkServiceError("INVALID_CHAT_ID", "\u8BF7\u9009\u62E9\u6709\u6548\u7684\u98DE\u4E66\u7FA4\u804A\uFF08chatId \u987B\u4EE5 oc_ \u5F00\u5934\uFF09", 400);
|
|
4987
|
+
}
|
|
4988
|
+
let replyMode = current.replyMode;
|
|
4989
|
+
if (patch.replyMode !== void 0) {
|
|
4990
|
+
if (patch.replyMode !== "thread" && patch.replyMode !== "main") {
|
|
4991
|
+
throw new LarkServiceError("INVALID_REPLY_MODE", "\u5524\u8D77\u6A21\u5F0F\u4EC5\u652F\u6301 thread\uFF08\u8BDD\u9898\uFF09\u6216 main\uFF08\u4E3B\u7EBF\u7A0B\uFF09", 400);
|
|
4992
|
+
}
|
|
4993
|
+
replyMode = patch.replyMode;
|
|
4994
|
+
}
|
|
4995
|
+
const pattern = patch.pattern === void 0 ? current.pattern : String(patch.pattern);
|
|
4996
|
+
const rawFlags = patch.flags === void 0 ? current.flags : String(patch.flags);
|
|
4997
|
+
const validation = validateLarkTriggerRegex(pattern, rawFlags);
|
|
4998
|
+
if (!validation.valid) {
|
|
4999
|
+
throw new LarkServiceError("INVALID_REGEX_PATTERN", validation.error, 400);
|
|
5000
|
+
}
|
|
5001
|
+
const presetId = patch.presetId === void 0 ? current.presetId : patch.presetId ? String(patch.presetId).trim() : void 0;
|
|
5002
|
+
const updated = {
|
|
5003
|
+
...current,
|
|
5004
|
+
name: patch.name === void 0 ? current.name : String(patch.name).trim() || current.name,
|
|
5005
|
+
enabled: patch.enabled === void 0 ? current.enabled : Boolean(patch.enabled),
|
|
5006
|
+
botId,
|
|
5007
|
+
chatId,
|
|
5008
|
+
chatName: patch.chatName === void 0 ? current.chatName : String(patch.chatName).trim() || chatId,
|
|
5009
|
+
pattern,
|
|
5010
|
+
flags: validation.normalizedFlags,
|
|
5011
|
+
replyMode,
|
|
5012
|
+
promptTemplate: patch.promptTemplate === void 0 ? current.promptTemplate : String(patch.promptTemplate),
|
|
5013
|
+
...presetId ? { presetId } : {},
|
|
5014
|
+
ignoreBotMessages: patch.ignoreBotMessages === void 0 ? current.ignoreBotMessages : Boolean(patch.ignoreBotMessages),
|
|
5015
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
5016
|
+
};
|
|
5017
|
+
if (!presetId) delete updated.presetId;
|
|
5018
|
+
const next = [...rules];
|
|
5019
|
+
next[index] = updated;
|
|
5020
|
+
if (await writeRulesState(repository, raw, next)) return updated;
|
|
5021
|
+
}
|
|
5022
|
+
throw new LarkServiceError("LARK_CONFIG_CONFLICT", "\u89C4\u5219\u6B63\u5728\u88AB\u5E76\u53D1\u66F4\u65B0\uFF0C\u8BF7\u91CD\u8BD5", 409);
|
|
5023
|
+
}
|
|
5024
|
+
async function deleteLarkRegexTriggerRule(repository, id) {
|
|
5025
|
+
if (!repository) throw new LarkServiceError("LARK_CONFIG_STORAGE_UNAVAILABLE", "\u6301\u4E45\u5316\u5B58\u50A8\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5220\u9664\u6B63\u5219\u89C4\u5219", 503);
|
|
5026
|
+
const targetId = id.trim();
|
|
5027
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
5028
|
+
const { raw, rules } = await readRulesState(repository);
|
|
5029
|
+
const next = rules.filter((item) => item.id !== targetId);
|
|
5030
|
+
if (next.length === rules.length) throw new LarkServiceError("REGEX_RULE_NOT_FOUND", `\u672A\u627E\u5230\u6B63\u5219\u76D1\u542C\u89C4\u5219\uFF1A${targetId}`, 404);
|
|
5031
|
+
if (await writeRulesState(repository, raw, next)) return { deleted: true, id: targetId };
|
|
5032
|
+
}
|
|
5033
|
+
throw new LarkServiceError("LARK_CONFIG_CONFLICT", "\u89C4\u5219\u6B63\u5728\u88AB\u5E76\u53D1\u66F4\u65B0\uFF0C\u8BF7\u91CD\u8BD5", 409);
|
|
5034
|
+
}
|
|
5035
|
+
async function findLarkRegexTriggerHit(repository, query) {
|
|
5036
|
+
const hits = await readLarkRegexTriggerHits(repository);
|
|
5037
|
+
for (let i = hits.length - 1; i >= 0; i--) {
|
|
5038
|
+
const item = hits[i];
|
|
5039
|
+
if (item.status !== "triggered") continue;
|
|
5040
|
+
if (item.messageId !== query.messageId) continue;
|
|
5041
|
+
if (query.ruleId && item.ruleId === query.ruleId) return item;
|
|
5042
|
+
if (!query.ruleId && query.botId && query.chatId && item.botId === query.botId && item.chatId === query.chatId) return item;
|
|
5043
|
+
}
|
|
5044
|
+
return void 0;
|
|
5045
|
+
}
|
|
5046
|
+
async function recordLarkRegexTriggerHit(repository, input) {
|
|
5047
|
+
const hit = {
|
|
5048
|
+
...input,
|
|
5049
|
+
id: `${input.ruleId}:${input.messageId}`,
|
|
5050
|
+
triggeredAt: input.triggeredAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
5051
|
+
};
|
|
5052
|
+
if (!repository) return hit;
|
|
5053
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
5054
|
+
const { raw, hits } = await readHitsState(repository);
|
|
5055
|
+
const filtered = hits.filter((item) => !(item.ruleId === hit.ruleId && item.messageId === hit.messageId));
|
|
5056
|
+
if (await writeHitsState(repository, raw, [...filtered, hit])) return hit;
|
|
5057
|
+
}
|
|
5058
|
+
return hit;
|
|
5059
|
+
}
|
|
5060
|
+
async function findMatchingRealtimeRegexTrigger(repository, input) {
|
|
5061
|
+
if (!repository || input.isSelfBot) return void 0;
|
|
5062
|
+
const rules = await readLarkRegexTriggerRules(repository);
|
|
5063
|
+
const candidates = rules.filter((rule) => rule.enabled && rule.botId === input.botId && rule.chatId === input.chatId);
|
|
5064
|
+
if (!candidates.length) return void 0;
|
|
5065
|
+
const isBotSender = input.senderType === "app" || input.senderType === "bot";
|
|
5066
|
+
const hits = await readLarkRegexTriggerHits(repository);
|
|
5067
|
+
const triggeredKeys = new Set(
|
|
5068
|
+
hits.filter((hit) => hit.status === "triggered" && hit.messageId === input.messageId).map((hit) => hit.ruleId)
|
|
5069
|
+
);
|
|
5070
|
+
for (const rule of candidates) {
|
|
5071
|
+
if (rule.ignoreBotMessages && isBotSender) continue;
|
|
5072
|
+
if (triggeredKeys.has(rule.id)) continue;
|
|
5073
|
+
const match = matchLarkTriggerText(rule.pattern, rule.flags, input.messageText, { timeoutMs: 50 });
|
|
5074
|
+
if (match.valid && match.matched) {
|
|
5075
|
+
return {
|
|
5076
|
+
rule,
|
|
5077
|
+
matchedText: match.matchedText,
|
|
5078
|
+
matches: match.matches
|
|
5079
|
+
};
|
|
5080
|
+
}
|
|
5081
|
+
}
|
|
5082
|
+
return void 0;
|
|
5083
|
+
}
|
|
5084
|
+
function formatLarkOpenApiError(error, scopeHint) {
|
|
5085
|
+
if (error instanceof LarkServiceError) {
|
|
5086
|
+
const upstreamCode = Number(error.details?.upstreamCode);
|
|
5087
|
+
const consoleUrl = typeof error.details?.consoleUrl === "string" ? error.details.consoleUrl : void 0;
|
|
5088
|
+
const violations = Array.isArray(error.details?.permissionViolations) ? error.details?.permissionViolations : [];
|
|
5089
|
+
const isPermission = upstreamCode === 99991672 || upstreamCode === 99991668 || upstreamCode === 230027 || violations.length > 0 || /permission|scope|privilege|权限/i.test(error.message);
|
|
5090
|
+
if (isPermission) {
|
|
5091
|
+
const requiredPerm = scopeHint === "chats" ? "im:chat:read\uFF08\u8BFB\u53D6\u673A\u5668\u4EBA\u6240\u5728\u7FA4\u804A\u5217\u8868\uFF09" : scopeHint === "messages" ? "im:message:readonly\u3001im:message.group_msg\uFF08\u8BFB\u53D6\u7FA4\u804A\u5386\u53F2\u6D88\u606F\uFF09" : "im:message:send_as_bot\uFF08\u4EE5\u673A\u5668\u4EBA\u8EAB\u4EFD\u56DE\u590D\u7FA4\u6D88\u606F\uFF09";
|
|
5092
|
+
const detail = consoleUrl ? `\uFF0C\u8BF7\u524D\u5F80\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u5F00\u901A\u6743\u9650\uFF1A${consoleUrl}` : "\uFF0C\u8BF7\u524D\u5F80\u98DE\u4E66\u5F00\u653E\u5E73\u53F0\u5F00\u901A\u6743\u9650\u540E\u91CD\u8BD5";
|
|
5093
|
+
return new LarkServiceError(
|
|
5094
|
+
"LARK_PERMISSION_DENIED",
|
|
5095
|
+
`\u98DE\u4E66\u6743\u9650\u4E0D\u8DB3\uFF1A\u7F3A\u5C11 ${requiredPerm}${detail}`,
|
|
5096
|
+
403,
|
|
5097
|
+
{ ...consoleUrl ? { consoleUrl } : {}, ...Number.isFinite(upstreamCode) ? { upstreamCode } : {} }
|
|
5098
|
+
);
|
|
5099
|
+
}
|
|
5100
|
+
const safeMessage = error.message.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer [REDACTED]").replace(/t-[A-Za-z0-9._-]{8,}/g, "[REDACTED_TOKEN]");
|
|
5101
|
+
return new LarkServiceError(error.code, safeMessage, error.statusCode);
|
|
5102
|
+
}
|
|
5103
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
5104
|
+
const safe = raw.replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer [REDACTED]").replace(/t-[A-Za-z0-9._-]{8,}/g, "[REDACTED_TOKEN]");
|
|
5105
|
+
return new LarkServiceError("LARK_OPENAPI_ERROR", safe, 502);
|
|
5106
|
+
}
|
|
5107
|
+
function renderMessageMentions(text3, mentions) {
|
|
5108
|
+
let rendered = text3;
|
|
5109
|
+
for (const mention of mentions) {
|
|
5110
|
+
const key = mention.key?.trim();
|
|
5111
|
+
const name = mention.name?.trim();
|
|
5112
|
+
if (!key) continue;
|
|
5113
|
+
rendered = rendered.split(key).join(name ? `@${name}` : "@\u6210\u5458");
|
|
5114
|
+
}
|
|
5115
|
+
return rendered;
|
|
5116
|
+
}
|
|
5117
|
+
async function fetchLarkChatMessagesForPreview(service, input) {
|
|
5118
|
+
const chatId = input.chatId.trim();
|
|
5119
|
+
if (!chatId.startsWith("oc_")) {
|
|
5120
|
+
throw new LarkServiceError("INVALID_CHAT_ID", "chatId \u5FC5\u987B\u4EE5 oc_ \u5F00\u5934", 400);
|
|
5121
|
+
}
|
|
5122
|
+
const limit = Math.min(100, Math.max(1, Math.floor(input.limit ?? 50)));
|
|
5123
|
+
const rawMessages = [];
|
|
5124
|
+
let pageToken = input.pageToken;
|
|
5125
|
+
let hasMore = false;
|
|
5126
|
+
try {
|
|
5127
|
+
const maxPages = limit > 50 ? 2 : 1;
|
|
5128
|
+
for (let page = 0; page < maxPages && rawMessages.length < limit; page++) {
|
|
5129
|
+
const remaining = limit - rawMessages.length;
|
|
5130
|
+
const batch = await service.listChatMessages({
|
|
5131
|
+
chatId,
|
|
5132
|
+
order: "desc",
|
|
5133
|
+
pageSize: Math.min(50, remaining),
|
|
5134
|
+
...pageToken ? { pageToken } : {}
|
|
5135
|
+
});
|
|
5136
|
+
rawMessages.push(...batch.items);
|
|
5137
|
+
hasMore = batch.hasMore;
|
|
5138
|
+
pageToken = batch.hasMore ? batch.pageToken : void 0;
|
|
5139
|
+
if (!pageToken) break;
|
|
5140
|
+
}
|
|
5141
|
+
} catch (error) {
|
|
5142
|
+
throw formatLarkOpenApiError(error, "messages");
|
|
5143
|
+
}
|
|
5144
|
+
const unresolvedOpenIds = [...new Set(
|
|
5145
|
+
rawMessages.filter((item) => !item.sender.name && item.sender.id?.startsWith("ou_") && item.sender.type !== "app" && item.sender.type !== "bot").map((item) => item.sender.id)
|
|
5146
|
+
)].slice(0, 25);
|
|
5147
|
+
const resolvedNames = /* @__PURE__ */ new Map();
|
|
5148
|
+
if (unresolvedOpenIds.length && typeof service.getUserName === "function") {
|
|
5149
|
+
await Promise.all(unresolvedOpenIds.map(async (openId) => {
|
|
5150
|
+
try {
|
|
5151
|
+
const name = await service.getUserName(openId);
|
|
5152
|
+
if (name) resolvedNames.set(openId, name);
|
|
5153
|
+
} catch {
|
|
5154
|
+
}
|
|
5155
|
+
}));
|
|
5156
|
+
}
|
|
5157
|
+
const parsedItems = await Promise.all(rawMessages.map(async (item) => {
|
|
5158
|
+
const parsed = await parseLarkMessageContent(item.messageType, item.rawContent, {
|
|
5159
|
+
messageId: item.messageId
|
|
5160
|
+
}).catch(() => ({ text: item.rawContent || "", resources: [] }));
|
|
5161
|
+
const text3 = renderMessageMentions(parsed.text, item.mentions).trim();
|
|
5162
|
+
const senderType = item.sender.type || "unknown";
|
|
5163
|
+
const fallbackName = senderType === "app" || senderType === "bot" ? item.sender.id || "\u98DE\u4E66\u673A\u5668\u4EBA" : item.sender.id || "\u7FA4\u6210\u5458";
|
|
5164
|
+
const senderName = item.sender.name?.trim() || (item.sender.id ? resolvedNames.get(item.sender.id) : void 0) || fallbackName;
|
|
5165
|
+
const createdAt = larkCreateTimeToIso(item.createTime);
|
|
5166
|
+
return {
|
|
5167
|
+
messageId: item.messageId,
|
|
5168
|
+
chatId: item.chatId || chatId,
|
|
5169
|
+
...item.threadId ? { threadId: item.threadId } : {},
|
|
5170
|
+
...item.rootId ? { rootId: item.rootId } : {},
|
|
5171
|
+
...item.parentId ? { parentId: item.parentId } : {},
|
|
5172
|
+
...item.sender.id ? { senderId: item.sender.id } : {},
|
|
5173
|
+
senderName,
|
|
5174
|
+
senderType,
|
|
5175
|
+
text: item.deleted ? "\uFF08\u8BE5\u6D88\u606F\u5DF2\u64A4\u56DE\uFF09" : text3,
|
|
5176
|
+
msgType: item.messageType,
|
|
5177
|
+
createTime: item.createTime,
|
|
5178
|
+
createdAt,
|
|
5179
|
+
...item.deleted ? { deleted: true } : {},
|
|
5180
|
+
...item.mentions.length ? { mentions: item.mentions.map((m) => ({ ...m.key ? { key: m.key } : {}, ...m.name ? { name: m.name } : {}, ...m.id ? { id: m.id } : {} })) } : {}
|
|
5181
|
+
};
|
|
5182
|
+
}));
|
|
5183
|
+
parsedItems.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.messageId.localeCompare(b.messageId));
|
|
5184
|
+
const hits = await readLarkRegexTriggerHits(input.repository);
|
|
5185
|
+
const hitsByMessageId = {};
|
|
5186
|
+
for (const hit of hits) {
|
|
5187
|
+
if (hit.botId !== input.botId || hit.chatId !== chatId) continue;
|
|
5188
|
+
if (input.ruleId && hit.ruleId !== input.ruleId) continue;
|
|
5189
|
+
const list = hitsByMessageId[hit.messageId] ?? [];
|
|
5190
|
+
list.push(hit);
|
|
5191
|
+
hitsByMessageId[hit.messageId] = list;
|
|
5192
|
+
}
|
|
5193
|
+
return {
|
|
5194
|
+
botId: input.botId,
|
|
5195
|
+
chatId,
|
|
5196
|
+
items: parsedItems,
|
|
5197
|
+
hasMore,
|
|
5198
|
+
...pageToken ? { pageToken } : {},
|
|
5199
|
+
hitsByMessageId
|
|
5200
|
+
};
|
|
5201
|
+
}
|
|
5202
|
+
function registerLarkRegexTriggerRoutes(app, deps) {
|
|
5203
|
+
const handleError = (handler) => async (request, reply) => {
|
|
5204
|
+
try {
|
|
5205
|
+
return await handler(request, reply);
|
|
5206
|
+
} catch (error) {
|
|
5207
|
+
if (error instanceof LarkServiceError) {
|
|
5208
|
+
return reply.code(error.statusCode).send({
|
|
5209
|
+
error: {
|
|
5210
|
+
code: error.code,
|
|
5211
|
+
message: error.message,
|
|
5212
|
+
...error.details?.consoleUrl ? { consoleUrl: error.details.consoleUrl } : {}
|
|
5213
|
+
}
|
|
5214
|
+
});
|
|
5215
|
+
}
|
|
5216
|
+
throw error;
|
|
5217
|
+
}
|
|
5218
|
+
};
|
|
5219
|
+
app.get("/api/lark/bots/:appId/chats/:chatId/messages", handleError(async (request) => {
|
|
5220
|
+
const appId = request.params.appId.trim();
|
|
5221
|
+
const chatId = request.params.chatId.trim();
|
|
5222
|
+
const limit = request.query.limit ? Number(request.query.limit) : 50;
|
|
5223
|
+
const service = await deps.resolveService(appId);
|
|
5224
|
+
return fetchLarkChatMessagesForPreview(service, {
|
|
5225
|
+
botId: appId,
|
|
5226
|
+
chatId,
|
|
5227
|
+
limit: Number.isFinite(limit) ? limit : 50,
|
|
5228
|
+
...request.query.pageToken ? { pageToken: request.query.pageToken } : {},
|
|
5229
|
+
repository: deps.config,
|
|
5230
|
+
...request.query.ruleId ? { ruleId: request.query.ruleId.trim() } : {}
|
|
5231
|
+
});
|
|
5232
|
+
}));
|
|
5233
|
+
app.get("/api/lark/regex-triggers", handleError(async () => ({
|
|
5234
|
+
rules: await listLarkRegexTriggerRulesWithStats(deps.config),
|
|
5235
|
+
templates: LARK_REGEX_PROMPT_TEMPLATES,
|
|
5236
|
+
variables: LARK_REGEX_TEMPLATE_VARIABLES
|
|
5237
|
+
})));
|
|
5238
|
+
app.post("/api/lark/regex-triggers", handleError(async (request, reply) => {
|
|
5239
|
+
const bots = await readLarkConfigs(deps.config);
|
|
5240
|
+
const rule = await createLarkRegexTriggerRule(deps.config, bots, request.body ?? {});
|
|
5241
|
+
return reply.code(201).send({ rule: { ...rule, hitCount: 0 } });
|
|
5242
|
+
}));
|
|
5243
|
+
app.patch("/api/lark/regex-triggers/:id", handleError(async (request) => {
|
|
5244
|
+
const bots = await readLarkConfigs(deps.config);
|
|
5245
|
+
const rule = await updateLarkRegexTriggerRule(deps.config, bots, request.params.id, request.body ?? {});
|
|
5246
|
+
const allWithStats = await listLarkRegexTriggerRulesWithStats(deps.config);
|
|
5247
|
+
const enriched = allWithStats.find((item) => item.id === rule.id) ?? { ...rule, hitCount: 0 };
|
|
5248
|
+
return { rule: enriched };
|
|
5249
|
+
}));
|
|
5250
|
+
app.delete("/api/lark/regex-triggers/:id", handleError(async (request) => deleteLarkRegexTriggerRule(deps.config, request.params.id)));
|
|
5251
|
+
app.get("/api/lark/regex-triggers/hits", handleError(async (request) => {
|
|
5252
|
+
const hits = await readLarkRegexTriggerHits(deps.config);
|
|
5253
|
+
const limit = Math.min(200, Math.max(1, Number(request.query.limit ?? 100) || 100));
|
|
5254
|
+
const filtered = hits.filter((item) => (!request.query.botId || item.botId === request.query.botId) && (!request.query.chatId || item.chatId === request.query.chatId) && (!request.query.ruleId || item.ruleId === request.query.ruleId)).reverse().slice(0, limit);
|
|
5255
|
+
return { hits: filtered };
|
|
5256
|
+
}));
|
|
5257
|
+
app.get("/api/lark/regex-triggers/:id/hits", handleError(async (request) => {
|
|
5258
|
+
const hits = await readLarkRegexTriggerHits(deps.config);
|
|
5259
|
+
const limit = Math.min(200, Math.max(1, Number(request.query.limit ?? 100) || 100));
|
|
5260
|
+
return {
|
|
5261
|
+
hits: hits.filter((item) => item.ruleId === request.params.id).reverse().slice(0, limit)
|
|
5262
|
+
};
|
|
5263
|
+
}));
|
|
5264
|
+
app.post("/api/lark/regex-triggers/preview", handleError(async (request) => {
|
|
5265
|
+
const body = request.body ?? {};
|
|
5266
|
+
const pattern = String(body.pattern ?? "");
|
|
5267
|
+
const flags = typeof body.flags === "string" ? body.flags : LARK_REGEX_DEFAULT_FLAGS;
|
|
5268
|
+
const ignoreBotMessages = body.ignoreBotMessages === true;
|
|
5269
|
+
let messages = Array.isArray(body.messages) ? body.messages : void 0;
|
|
5270
|
+
let fetchedMessages;
|
|
5271
|
+
if (!messages) {
|
|
5272
|
+
const botId = String(body.botId ?? "").trim();
|
|
5273
|
+
const chatId = String(body.chatId ?? "").trim();
|
|
5274
|
+
if (!botId || !chatId) {
|
|
5275
|
+
throw new LarkServiceError("INVALID_PREVIEW_REQUEST", "\u8BF7\u63D0\u4F9B messages \u5217\u8868\uFF0C\u6216\u540C\u65F6\u63D0\u4F9B botId \u4E0E chatId", 400);
|
|
5276
|
+
}
|
|
5277
|
+
const service = await deps.resolveService(botId);
|
|
5278
|
+
const fetched = await fetchLarkChatMessagesForPreview(service, {
|
|
5279
|
+
botId,
|
|
5280
|
+
chatId,
|
|
5281
|
+
limit: body.limit ?? 50,
|
|
5282
|
+
repository: deps.config
|
|
5283
|
+
});
|
|
5284
|
+
fetchedMessages = fetched.items;
|
|
5285
|
+
messages = fetched.items.map((item) => ({
|
|
5286
|
+
messageId: item.messageId,
|
|
5287
|
+
text: item.text,
|
|
5288
|
+
senderType: item.senderType
|
|
5289
|
+
}));
|
|
5290
|
+
}
|
|
5291
|
+
const preview = matchLarkTriggerMessages(pattern, flags, messages, { ignoreBotMessages });
|
|
5292
|
+
return {
|
|
5293
|
+
...preview,
|
|
5294
|
+
...fetchedMessages ? { messages: fetchedMessages } : {}
|
|
5295
|
+
};
|
|
5296
|
+
}));
|
|
5297
|
+
app.post("/api/lark/regex-triggers/backfill", handleError(async (request) => {
|
|
5298
|
+
const body = request.body ?? {};
|
|
5299
|
+
const botId = String(body.botId ?? "").trim();
|
|
5300
|
+
const chatId = String(body.chatId ?? "").trim();
|
|
5301
|
+
if (!botId) throw new LarkServiceError("INVALID_BACKFILL_REQUEST", "botId \u5FC5\u586B", 400);
|
|
5302
|
+
if (!chatId.startsWith("oc_")) throw new LarkServiceError("INVALID_CHAT_ID", "chatId \u5FC5\u987B\u4EE5 oc_ \u5F00\u5934", 400);
|
|
5303
|
+
const botConfig = await readLarkConfig(deps.config, botId);
|
|
5304
|
+
if (!botConfig) throw new LarkServiceError("LARK_BOT_NOT_FOUND", `\u672A\u627E\u5230\u98DE\u4E66\u673A\u5668\u4EBA\uFF1A${botId}`, 404);
|
|
5305
|
+
if (!botConfig.defaultAgentId) {
|
|
5306
|
+
throw new LarkServiceError("LARK_BOT_INCOMPLETE", "\u8BE5\u673A\u5668\u4EBA\u5C1A\u672A\u914D\u7F6E\u9ED8\u8BA4 Agent\uFF0C\u8BF7\u5148\u5728\u300C\u98DE\u4E66\u8BBE\u7F6E\u300D\u4E2D\u5B8C\u6210 Agent \u914D\u7F6E\u540E\u518D\u53D1\u8D77\u8F6E\u6B21", 409);
|
|
5307
|
+
}
|
|
5308
|
+
const replyMode = body.replyMode === "main" ? "main" : "thread";
|
|
5309
|
+
const pattern = String(body.pattern ?? "");
|
|
5310
|
+
const validation = validateLarkTriggerRegex(pattern, body.flags ?? LARK_REGEX_DEFAULT_FLAGS);
|
|
5311
|
+
if (!validation.valid) {
|
|
5312
|
+
throw new LarkServiceError("INVALID_REGEX_PATTERN", validation.error, 400);
|
|
5313
|
+
}
|
|
5314
|
+
const messages = Array.isArray(body.messages) ? body.messages : [];
|
|
5315
|
+
if (!messages.length) {
|
|
5316
|
+
throw new LarkServiceError("INVALID_BACKFILL_REQUEST", "\u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u6761\u8981\u8865\u507F\u7684\u5386\u53F2\u6D88\u606F", 400);
|
|
5317
|
+
}
|
|
5318
|
+
if (messages.length > LARK_REGEX_MAX_BACKFILL_BATCH) {
|
|
5319
|
+
throw new LarkServiceError("BACKFILL_BATCH_TOO_LARGE", `\u5355\u6B21\u6700\u591A\u6279\u91CF\u8865\u507F ${LARK_REGEX_MAX_BACKFILL_BATCH} \u6761\u6D88\u606F`, 400);
|
|
5320
|
+
}
|
|
5321
|
+
const savedRule = body.ruleId ? (await readLarkRegexTriggerRules(deps.config)).find((item) => item.id === body.ruleId) : void 0;
|
|
5322
|
+
const effectiveRuleId = savedRule?.id ?? body.ruleId?.trim() ?? `adhoc:${botId}:${chatId}`;
|
|
5323
|
+
const effectiveRuleName = body.ruleName?.trim() || savedRule?.name || "\u5386\u53F2\u8865\u507F\u89E6\u53D1";
|
|
5324
|
+
const effectiveChatName = body.chatName?.trim() || savedRule?.chatName || chatId;
|
|
5325
|
+
const effectivePromptTemplate = body.promptTemplate !== void 0 ? String(body.promptTemplate) : savedRule?.promptTemplate ?? "";
|
|
5326
|
+
const force = body.force === true;
|
|
5327
|
+
const results = [];
|
|
5328
|
+
let triggeredCount = 0;
|
|
5329
|
+
let skippedCount = 0;
|
|
5330
|
+
let failedCount = 0;
|
|
5331
|
+
for (const message of messages) {
|
|
5332
|
+
const messageId = String(message?.messageId ?? "").trim();
|
|
5333
|
+
if (!messageId) {
|
|
5334
|
+
failedCount += 1;
|
|
5335
|
+
results.push({ messageId: "", status: "failed", reason: "\u7F3A\u5C11\u6709\u6548\u7684 messageId" });
|
|
5336
|
+
continue;
|
|
5337
|
+
}
|
|
5338
|
+
if (!force) {
|
|
5339
|
+
const existing = await findLarkRegexTriggerHit(deps.config, {
|
|
5340
|
+
ruleId: savedRule?.id || body.ruleId?.trim() || void 0,
|
|
5341
|
+
botId,
|
|
5342
|
+
chatId,
|
|
5343
|
+
messageId
|
|
5344
|
+
});
|
|
5345
|
+
if (existing) {
|
|
5346
|
+
skippedCount += 1;
|
|
5347
|
+
results.push({
|
|
5348
|
+
messageId,
|
|
5349
|
+
status: "skipped",
|
|
5350
|
+
alreadyTriggered: true,
|
|
5351
|
+
...existing.sessionId ? { sessionId: existing.sessionId } : {},
|
|
5352
|
+
...existing.cardMessageId ? { cardMessageId: existing.cardMessageId } : {},
|
|
5353
|
+
matchedText: existing.matchedText,
|
|
5354
|
+
reason: "\u8BE5\u6D88\u606F\u5DF2\u89E6\u53D1\u8FC7\u5524\u8D77\uFF0C\u5DF2\u8DF3\u8FC7\u91CD\u590D\u6267\u884C"
|
|
5355
|
+
});
|
|
5356
|
+
continue;
|
|
5357
|
+
}
|
|
5358
|
+
}
|
|
5359
|
+
const text3 = String(message.text ?? "");
|
|
5360
|
+
const match = matchLarkTriggerText(pattern, validation.normalizedFlags, text3);
|
|
5361
|
+
if (!match.valid) {
|
|
5362
|
+
failedCount += 1;
|
|
5363
|
+
results.push({ messageId, status: "failed", reason: match.error || "\u6B63\u5219\u5339\u914D\u5931\u8D25" });
|
|
5364
|
+
continue;
|
|
5365
|
+
}
|
|
5366
|
+
if (!match.matched && !force) {
|
|
5367
|
+
skippedCount += 1;
|
|
5368
|
+
results.push({ messageId, status: "skipped", reason: "\u8BE5\u6D88\u606F\u672A\u547D\u4E2D\u5F53\u524D\u6B63\u5219\u8868\u8FBE\u5F0F" });
|
|
5369
|
+
continue;
|
|
5370
|
+
}
|
|
5371
|
+
const matchedText = match.matchedText || text3.slice(0, 80);
|
|
5372
|
+
try {
|
|
5373
|
+
const dispatched = await deps.dispatchBackfillTurn({
|
|
5374
|
+
botConfig,
|
|
5375
|
+
rule: {
|
|
5376
|
+
id: effectiveRuleId,
|
|
5377
|
+
name: effectiveRuleName,
|
|
5378
|
+
chatId,
|
|
5379
|
+
chatName: effectiveChatName,
|
|
5380
|
+
pattern,
|
|
5381
|
+
flags: validation.normalizedFlags,
|
|
5382
|
+
replyMode,
|
|
5383
|
+
promptTemplate: effectivePromptTemplate
|
|
5384
|
+
},
|
|
5385
|
+
message: {
|
|
5386
|
+
...message,
|
|
5387
|
+
messageId,
|
|
5388
|
+
text: text3
|
|
5389
|
+
},
|
|
5390
|
+
matchedText,
|
|
5391
|
+
triggerType: "backfill"
|
|
5392
|
+
});
|
|
5393
|
+
await recordLarkRegexTriggerHit(deps.config, {
|
|
5394
|
+
ruleId: effectiveRuleId,
|
|
5395
|
+
botId,
|
|
5396
|
+
chatId,
|
|
5397
|
+
messageId,
|
|
5398
|
+
...dispatched.sessionId ? { sessionId: dispatched.sessionId } : {},
|
|
5399
|
+
...dispatched.cardMessageId ? { cardMessageId: dispatched.cardMessageId } : {},
|
|
5400
|
+
matchedText,
|
|
5401
|
+
...message.senderName ? { senderName: message.senderName } : {},
|
|
5402
|
+
messagePreview: text3.slice(0, 120),
|
|
5403
|
+
triggerType: "backfill",
|
|
5404
|
+
status: "triggered"
|
|
5405
|
+
});
|
|
5406
|
+
triggeredCount += 1;
|
|
5407
|
+
results.push({
|
|
5408
|
+
messageId,
|
|
5409
|
+
status: "triggered",
|
|
5410
|
+
...dispatched.sessionId ? { sessionId: dispatched.sessionId } : {},
|
|
5411
|
+
...dispatched.cardMessageId ? { cardMessageId: dispatched.cardMessageId } : {},
|
|
5412
|
+
matchedText
|
|
5413
|
+
});
|
|
5414
|
+
} catch (error) {
|
|
5415
|
+
const formatted = formatLarkOpenApiError(error, "reply");
|
|
5416
|
+
await recordLarkRegexTriggerHit(deps.config, {
|
|
5417
|
+
ruleId: effectiveRuleId,
|
|
5418
|
+
botId,
|
|
5419
|
+
chatId,
|
|
5420
|
+
messageId,
|
|
5421
|
+
matchedText,
|
|
5422
|
+
...message.senderName ? { senderName: message.senderName } : {},
|
|
5423
|
+
messagePreview: text3.slice(0, 120),
|
|
5424
|
+
triggerType: "backfill",
|
|
5425
|
+
status: "failed",
|
|
5426
|
+
error: formatted.message
|
|
5427
|
+
});
|
|
5428
|
+
failedCount += 1;
|
|
5429
|
+
results.push({
|
|
5430
|
+
messageId,
|
|
5431
|
+
status: "failed",
|
|
5432
|
+
matchedText,
|
|
5433
|
+
reason: formatted.message
|
|
5434
|
+
});
|
|
5435
|
+
}
|
|
5436
|
+
}
|
|
5437
|
+
return {
|
|
5438
|
+
ruleId: effectiveRuleId,
|
|
5439
|
+
botId,
|
|
5440
|
+
chatId,
|
|
5441
|
+
replyMode,
|
|
5442
|
+
triggeredCount,
|
|
5443
|
+
skippedCount,
|
|
5444
|
+
failedCount,
|
|
5445
|
+
results
|
|
5446
|
+
};
|
|
5447
|
+
}));
|
|
5448
|
+
}
|
|
5449
|
+
var larkRegexTriggersConfigKey, larkRegexTriggerHitsConfigKey, LARK_REGEX_MAX_PATTERN_LENGTH, LARK_REGEX_MAX_TEXT_LENGTH, LARK_REGEX_MAX_MATCHES_PER_MESSAGE, LARK_REGEX_MAX_HITS_LEDGER, LARK_REGEX_MAX_BACKFILL_BATCH, LARK_REGEX_DEFAULT_FLAGS, allowedRegexFlags, flagOrder, LARK_REGEX_TEMPLATE_VARIABLES, LARK_REGEX_PROMPT_TEMPLATES, VM_BATCH_MATCH_SCRIPT, LarkBotChatCache;
|
|
5450
|
+
var init_regex_triggers = __esm({
|
|
5451
|
+
"src/lark/regex-triggers.ts"() {
|
|
5452
|
+
"use strict";
|
|
5453
|
+
init_config();
|
|
5454
|
+
init_message_content();
|
|
5455
|
+
init_service();
|
|
5456
|
+
larkRegexTriggersConfigKey = "lark.regex_triggers.rules";
|
|
5457
|
+
larkRegexTriggerHitsConfigKey = "lark.regex_triggers.hits";
|
|
5458
|
+
LARK_REGEX_MAX_PATTERN_LENGTH = 1024;
|
|
5459
|
+
LARK_REGEX_MAX_TEXT_LENGTH = 8e3;
|
|
5460
|
+
LARK_REGEX_MAX_MATCHES_PER_MESSAGE = 50;
|
|
5461
|
+
LARK_REGEX_MAX_HITS_LEDGER = 2e3;
|
|
5462
|
+
LARK_REGEX_MAX_BACKFILL_BATCH = 20;
|
|
5463
|
+
LARK_REGEX_DEFAULT_FLAGS = "i";
|
|
5464
|
+
allowedRegexFlags = /* @__PURE__ */ new Set(["i", "m", "s", "u"]);
|
|
5465
|
+
flagOrder = ["i", "m", "s", "u"];
|
|
5466
|
+
LARK_REGEX_TEMPLATE_VARIABLES = [
|
|
5467
|
+
{ key: "chatName", token: "{{chatName}}", label: "\u7FA4\u804A\u540D\u79F0", description: "\u89E6\u53D1\u6D88\u606F\u6240\u5728\u98DE\u4E66\u7FA4\u7684\u540D\u79F0" },
|
|
5468
|
+
{ key: "chatId", token: "{{chatId}}", label: "\u7FA4\u804A ID", description: "\u98DE\u4E66\u7FA4\u804A oc_ \u5F00\u5934\u7684\u552F\u4E00\u6807\u8BC6" },
|
|
5469
|
+
{ key: "botName", token: "{{botName}}", label: "\u673A\u5668\u4EBA\u540D\u79F0", description: "\u5F53\u524D\u8D1F\u8D23\u54CD\u5E94\u7684\u98DE\u4E66\u673A\u5668\u4EBA\u540D\u79F0" },
|
|
5470
|
+
{ key: "ruleName", token: "{{ruleName}}", label: "\u89C4\u5219\u540D\u79F0", description: "\u547D\u4E2D\u7684\u6B63\u5219\u76D1\u542C\u89C4\u5219\u540D\u79F0" },
|
|
5471
|
+
{ key: "pattern", token: "{{pattern}}", label: "\u6B63\u5219\u8868\u8FBE\u5F0F", description: "\u547D\u4E2D\u8BE5\u6D88\u606F\u7684\u6B63\u5219\u8868\u8FBE\u5F0F\u6587\u672C" },
|
|
5472
|
+
{ key: "senderName", token: "{{senderName}}", label: "\u53D1\u9001\u4EBA", description: "\u53D1\u9001\u8BE5\u6761\u7FA4\u804A\u6D88\u606F\u7684\u6210\u5458\u59D3\u540D" },
|
|
5473
|
+
{ key: "messageTime", token: "{{messageTime}}", label: "\u6D88\u606F\u65F6\u95F4", description: "\u8BE5\u6761\u6D88\u606F\u5728\u7FA4\u5185\u53D1\u51FA\u7684\u65F6\u95F4" },
|
|
5474
|
+
{ key: "messageText", token: "{{messageText}}", label: "\u539F\u59CB\u6D88\u606F", description: "\u89E3\u6790\u540E\u7684\u7FA4\u804A\u6D88\u606F\u5B8C\u6574\u6B63\u6587" },
|
|
5475
|
+
{ key: "matchedText", token: "{{matchedText}}", label: "\u547D\u4E2D\u7247\u6BB5", description: "\u6B63\u5219\u8868\u8FBE\u5F0F\u5B9E\u9645\u547D\u4E2D\u7684\u5B50\u4E32\u5185\u5BB9" }
|
|
5476
|
+
];
|
|
5477
|
+
LARK_REGEX_PROMPT_TEMPLATES = [
|
|
5478
|
+
{
|
|
5479
|
+
id: "incident-triage",
|
|
5480
|
+
name: "\u544A\u8B66 / \u6545\u969C\u81EA\u52A8\u6392\u67E5",
|
|
5481
|
+
badge: "\u544A\u8B66\u8FD0\u7EF4",
|
|
5482
|
+
description: "\u81EA\u52A8\u8BC6\u522B P0/P1 \u544A\u8B66\u30015xx \u6216\u7EBF\u4E0A\u5F02\u5E38\uFF0C\u5FEB\u901F\u8F93\u51FA\u5F71\u54CD\u5224\u65AD\u3001\u6839\u56E0\u5047\u8BBE\u4E0E\u6B62\u8840\u5EFA\u8BAE",
|
|
5483
|
+
suggestedPattern: "(?:P[01]|\u544A\u8B66|\u62A5\u8B66|\u7EBF\u4E0A\u5F02\u5E38|\u62A5\u9519|50[0234]|timeout|OOM|panic)",
|
|
5484
|
+
suggestedFlags: "i",
|
|
5485
|
+
suggestedReplyMode: "thread",
|
|
5486
|
+
promptTemplate: [
|
|
5487
|
+
"\u4F60\u6B63\u5728\u54CD\u5E94\u98DE\u4E66\u7FA4\u300C{{chatName}}\u300D\u4E2D\u7684\u4E00\u6761\u544A\u8B66/\u6545\u969C\u6D88\u606F\uFF08\u547D\u4E2D\u7247\u6BB5\uFF1A{{matchedText}}\uFF09\uFF0C\u8BF7\u6309\u4EE5\u4E0B\u987A\u5E8F\u5FEB\u901F\u5904\u7406\uFF1A",
|
|
5488
|
+
"1. \u5148\u7528 1-2 \u53E5\u8BDD\u63D0\u70BC\u6545\u969C\u73B0\u8C61\u3001\u53D7\u5F71\u54CD\u6A21\u5757\u4E0E\u7D27\u6025\u7A0B\u5EA6\u3002",
|
|
5489
|
+
"2. \u7ED3\u5408\u5F53\u524D\u5DE5\u4F5C\u533A\u4EE3\u7801\u6216\u65E5\u5FD7\u7EBF\u7D22\uFF0C\u5217\u51FA\u6700\u53EF\u80FD\u7684 2-3 \u4E2A\u6839\u56E0\u5047\u8BBE\u53CA\u6392\u67E5\u547D\u4EE4\u3002",
|
|
5490
|
+
"3. \u7ED9\u51FA\u7ACB\u5373\u53EF\u6267\u884C\u7684\u6B62\u8840/\u964D\u7EA7/\u56DE\u6EDA\u5EFA\u8BAE\uFF0C\u7ED3\u8BBA\u5148\u884C\u3001\u907F\u514D\u5197\u957F\u5BD2\u6684\u3002"
|
|
5491
|
+
].join("\n")
|
|
5492
|
+
},
|
|
5493
|
+
{
|
|
5494
|
+
id: "ticket-breakdown",
|
|
5495
|
+
name: "\u9700\u6C42 / \u5DE5\u5355\u62C6\u89E3\u54CD\u5E94",
|
|
5496
|
+
badge: "\u4EA7\u7814\u534F\u4F5C",
|
|
5497
|
+
description: "\u547D\u4E2D\u9700\u6C42\u3001\u5DE5\u5355\u6216\u7F3A\u9677\u63D0\u62A5\u65F6\uFF0C\u81EA\u52A8\u62C6\u89E3\u4E0A\u4E0B\u6587\u3001\u9A8C\u6536\u6807\u51C6\u4E0E\u5F85\u6F84\u6E05\u95EE\u9898",
|
|
5498
|
+
suggestedPattern: "(?:\u9700\u6C42|\u5DE5\u5355|BUG|\u7F3A\u9677|ISSUE-\\d+|\u5E2E\u5FD9\u6392\u67E5|\u9EBB\u70E6\u770B\u4E0B)",
|
|
5499
|
+
suggestedFlags: "i",
|
|
5500
|
+
suggestedReplyMode: "thread",
|
|
5501
|
+
promptTemplate: [
|
|
5502
|
+
"\u7FA4\u6210\u5458 {{senderName}} \u5728\u300C{{chatName}}\u300D\u63D0\u4EA4\u4E86\u4E00\u6761\u9700\u6C42/\u5DE5\u5355\u76F8\u5173\u6D88\u606F\uFF0C\u8BF7\u534F\u52A9\u5FEB\u901F\u54CD\u5E94\uFF1A",
|
|
5503
|
+
"1. \u6982\u62EC\u6838\u5FC3\u8BC9\u6C42\u3001\u76EE\u6807\u5BF9\u8C61\u4E0E\u5DF2\u77E5\u7EA6\u675F\u3002",
|
|
5504
|
+
"2. \u62C6\u89E3\u53EF\u6267\u884C\u5B50\u4EFB\u52A1\u4E0E\u9A8C\u6536\u8981\u70B9\uFF1B\u82E5\u5173\u952E\u4FE1\u606F\u7F3A\u5931\uFF0C\u5217\u51FA\u6700\u591A 3 \u4E2A\u6700\u9700\u8981\u8865\u5145\u786E\u8BA4\u7684\u95EE\u9898\u3002",
|
|
5505
|
+
"3. \u8F93\u51FA\u7B80\u6D01\u6E05\u6670\u7684 Markdown \u8981\u70B9\uFF0C\u65B9\u4FBF\u56E2\u961F\u76F4\u63A5\u5728\u8BDD\u9898\u5185\u63A5\u529B\u63A8\u8FDB\u3002"
|
|
5506
|
+
].join("\n")
|
|
5507
|
+
},
|
|
5508
|
+
{
|
|
5509
|
+
id: "group-qa",
|
|
5510
|
+
name: "\u7FA4\u804A\u5173\u952E\u8BCD\u7B54\u7591",
|
|
5511
|
+
badge: "\u77E5\u8BC6\u7B54\u7591",
|
|
5512
|
+
description: "\u547D\u4E2D\u5E38\u89C1\u6280\u672F\u6216\u4E1A\u52A1\u63D0\u95EE\u5173\u952E\u8BCD\u65F6\uFF0C\u7ED3\u5408\u5DE5\u4F5C\u533A\u6587\u6863\u4E0E\u6E90\u7801\u7ED9\u51FA\u53EF\u9A8C\u8BC1\u56DE\u7B54",
|
|
5513
|
+
suggestedPattern: "(?:\u600E\u4E48\u914D\u7F6E|\u5982\u4F55\u63A5\u5165|\u6587\u6863\u5728\u54EA|\u62A5\u9519\u600E\u4E48\u89E3\u51B3|\u600E\u4E48\u7528|\u6709\u6CA1\u6709\u4EBA\u77E5\u9053)",
|
|
5514
|
+
suggestedFlags: "i",
|
|
5515
|
+
suggestedReplyMode: "thread",
|
|
5516
|
+
promptTemplate: [
|
|
5517
|
+
"\u8BF7\u7ED3\u5408\u5F53\u524D\u5DE5\u4F5C\u533A\u4EE3\u7801\u548C\u6587\u6863\uFF0C\u51C6\u786E\u56DE\u7B54\u7FA4\u804A\u300C{{chatName}}\u300D\u4E2D {{senderName}} \u7684\u63D0\u95EE\uFF1A",
|
|
5518
|
+
"- \u4F18\u5148\u7ED9\u51FA\u76F4\u63A5\u7ED3\u8BBA\u4E0E\u53EF\u590D\u73B0\u7684\u64CD\u4F5C\u6B65\u9AA4\uFF08\u9644\u5173\u952E\u6587\u4EF6\u8DEF\u5F84\u6216\u547D\u4EE4\uFF09\u3002",
|
|
5519
|
+
"- \u5982\u4E0A\u4E0B\u6587\u4E0D\u8DB3\u4EE5\u786E\u8BA4\u7B54\u6848\uFF0C\u8BF7\u660E\u786E\u8BF4\u660E\u4E0D\u786E\u5B9A\u4E4B\u5904\uFF0C\u5207\u52FF\u7F16\u9020\u63A5\u53E3\u3001\u53C2\u6570\u6216\u5185\u90E8\u6D41\u7A0B\u3002"
|
|
5520
|
+
].join("\n")
|
|
5521
|
+
},
|
|
5522
|
+
{
|
|
5523
|
+
id: "monitor-digest",
|
|
5524
|
+
name: "\u76D1\u63A7\u6458\u8981\u8BB0\u5F55",
|
|
5525
|
+
badge: "\u5DE1\u68C0\u6458\u8981",
|
|
5526
|
+
description: "\u547D\u4E2D\u53D1\u5E03\u5B8C\u6210\u3001\u5DE1\u68C0\u62A5\u544A\u6216\u6307\u6807\u64AD\u62A5\u65F6\uFF0C\u63D0\u53D6\u5173\u952E\u6307\u6807\u4E0E\u9700\u8DDF\u8FDB\u98CE\u9669\u9879",
|
|
5527
|
+
suggestedPattern: "(?:\u53D1\u5E03\u5B8C\u6210|\u4E0A\u7EBF\u901A\u77E5|\u5DE1\u68C0\u62A5\u544A|\u65E5\u62A5|\u5468\u62A5|\u6307\u6807\u6CE2\u52A8|SLA)",
|
|
5528
|
+
suggestedFlags: "i",
|
|
5529
|
+
suggestedReplyMode: "main",
|
|
5530
|
+
promptTemplate: [
|
|
5531
|
+
"\u8BF7\u5BF9\u300C{{chatName}}\u300D\u5728 {{messageTime}} \u6536\u5230\u7684\u64AD\u62A5/\u76D1\u63A7\u6D88\u606F\u751F\u6210\u7ED3\u6784\u5316\u6458\u8981\uFF1A",
|
|
5532
|
+
"- \u6838\u5FC3\u4E8B\u4EF6\u4E0E\u53D8\u66F4\u8303\u56F4",
|
|
5533
|
+
"- \u5173\u952E\u6307\u6807\u6216\u6838\u5FC3\u7ED3\u8BBA\uFF08\u7528\u7CBE\u70BC\u8981\u70B9\u6216\u8868\u683C\u5217\u51FA\uFF09",
|
|
5534
|
+
"- \u9700\u8981\u4EBA\u5DE5\u8DDF\u8FDB\u7684\u98CE\u9669/\u5F02\u5E38\u9879\uFF08\u65E0\u5219\u6CE8\u660E\u300C\u6682\u65E0\u660E\u663E\u98CE\u9669\u300D\uFF09"
|
|
5535
|
+
].join("\n")
|
|
5536
|
+
},
|
|
5537
|
+
{
|
|
5538
|
+
id: "concise-direct",
|
|
5539
|
+
name: "\u7B80\u6D01\u76F4\u8FBE",
|
|
5540
|
+
badge: "\u901A\u7528\u8F7B\u6A21\u677F",
|
|
5541
|
+
description: "\u4FDD\u6301\u6781\u7B80\u6307\u4EE4\uFF0C\u5B8C\u5168\u7531\u81EA\u52A8\u9644\u5E26\u7684\u7FA4\u804A\u4E0E\u6D88\u606F\u57FA\u7840\u4E0A\u4E0B\u6587\u9A71\u52A8",
|
|
5542
|
+
suggestedPattern: "(?:\u7D27\u6025|\u8BF7\u5904\u7406|\u8DDF\u8FDB\u4E00\u4E0B)",
|
|
5543
|
+
suggestedFlags: "i",
|
|
5544
|
+
suggestedReplyMode: "thread",
|
|
5545
|
+
promptTemplate: "\u8BF7\u67E5\u770B\u7FA4\u804A\u300C{{chatName}}\u300D\u4E2D {{senderName}} \u53D1\u51FA\u7684\u547D\u4E2D\u6D88\u606F\uFF0C\u7ED3\u5408\u57FA\u7840\u4E0A\u4E0B\u6587\u76F4\u63A5\u7ED9\u51FA\u7B80\u6D01\u3001\u51C6\u786E\u7684\u5904\u7406\u7ED3\u8BBA\u3002"
|
|
5546
|
+
}
|
|
5547
|
+
];
|
|
5548
|
+
VM_BATCH_MATCH_SCRIPT = new vm.Script(`
|
|
5549
|
+
(() => {
|
|
5550
|
+
const re = new RegExp(__pattern, __flags);
|
|
5551
|
+
const out = [];
|
|
5552
|
+
for (let i = 0; i < __texts.length; i++) {
|
|
5553
|
+
const raw = __texts[i];
|
|
5554
|
+
if (raw === null) {
|
|
5555
|
+
out.push({ matched: false, matches: [] });
|
|
5556
|
+
continue;
|
|
5557
|
+
}
|
|
5558
|
+
const text = raw.length > __maxTextLen ? raw.slice(0, __maxTextLen) : raw;
|
|
5559
|
+
re.lastIndex = 0;
|
|
5560
|
+
const spans = [];
|
|
5561
|
+
let matched = false;
|
|
5562
|
+
let guard = 0;
|
|
5563
|
+
while (guard < __maxMatches) {
|
|
5564
|
+
const m = re.exec(text);
|
|
5565
|
+
if (!m) break;
|
|
5566
|
+
matched = true;
|
|
5567
|
+
const value = m[0];
|
|
5568
|
+
const start = m.index;
|
|
5569
|
+
const end = start + value.length;
|
|
5570
|
+
if (value.length > 0) {
|
|
5571
|
+
spans.push({ start, end, text: value });
|
|
5572
|
+
}
|
|
5573
|
+
if (value.length === 0) {
|
|
5574
|
+
if (re.lastIndex >= text.length) break;
|
|
5575
|
+
re.lastIndex += 1;
|
|
5576
|
+
}
|
|
5577
|
+
guard += 1;
|
|
5578
|
+
}
|
|
5579
|
+
out.push({ matched, matches: spans });
|
|
5580
|
+
}
|
|
5581
|
+
return out;
|
|
5582
|
+
})();
|
|
5583
|
+
`);
|
|
5584
|
+
LarkBotChatCache = class {
|
|
5585
|
+
constructor(ttlMs = 2e4) {
|
|
5586
|
+
this.ttlMs = ttlMs;
|
|
5587
|
+
}
|
|
5588
|
+
ttlMs;
|
|
5589
|
+
cache = /* @__PURE__ */ new Map();
|
|
5590
|
+
invalidate(appId) {
|
|
5591
|
+
if (!appId) {
|
|
5592
|
+
this.cache.clear();
|
|
5593
|
+
return;
|
|
5594
|
+
}
|
|
5595
|
+
for (const key of this.cache.keys()) {
|
|
5596
|
+
if (key.startsWith(`${appId}:`)) this.cache.delete(key);
|
|
5597
|
+
}
|
|
5598
|
+
}
|
|
5599
|
+
async list(appId, service, options = {}) {
|
|
5600
|
+
const cacheKey = `${appId}:${options.all ? "all" : "page"}:${options.pageToken ?? ""}`;
|
|
5601
|
+
if (!options.refresh) {
|
|
5602
|
+
const cached5 = this.cache.get(cacheKey);
|
|
5603
|
+
if (cached5 && cached5.expiresAt > Date.now()) return cached5.value;
|
|
5604
|
+
}
|
|
5605
|
+
try {
|
|
5606
|
+
let result;
|
|
5607
|
+
if (options.all && !options.pageToken) {
|
|
5608
|
+
const items = [];
|
|
5609
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5610
|
+
let pageToken;
|
|
5611
|
+
let hasMore = false;
|
|
5612
|
+
for (let page = 0; page < 5; page++) {
|
|
5613
|
+
const batch = await service.listChats(pageToken);
|
|
5614
|
+
for (const chat of batch.items) {
|
|
5615
|
+
if (seen.has(chat.chatId)) continue;
|
|
5616
|
+
seen.add(chat.chatId);
|
|
5617
|
+
items.push(chat);
|
|
5618
|
+
}
|
|
5619
|
+
hasMore = batch.hasMore;
|
|
5620
|
+
pageToken = batch.hasMore ? batch.pageToken : void 0;
|
|
5621
|
+
if (!pageToken) break;
|
|
5622
|
+
}
|
|
5623
|
+
result = { items, hasMore, ...pageToken ? { pageToken } : {} };
|
|
5624
|
+
} else {
|
|
5625
|
+
result = await service.listChats(options.pageToken);
|
|
5626
|
+
}
|
|
5627
|
+
if (this.cache.size >= 100) this.cache.delete(this.cache.keys().next().value);
|
|
5628
|
+
this.cache.set(cacheKey, { value: result, expiresAt: Date.now() + this.ttlMs });
|
|
5629
|
+
return result;
|
|
5630
|
+
} catch (error) {
|
|
5631
|
+
throw formatLarkOpenApiError(error, "chats");
|
|
5632
|
+
}
|
|
5633
|
+
}
|
|
5634
|
+
};
|
|
5635
|
+
}
|
|
5636
|
+
});
|
|
5637
|
+
|
|
4557
5638
|
// src/lark/listener.ts
|
|
4558
5639
|
var listener_exports = {};
|
|
4559
5640
|
__export(listener_exports, {
|
|
@@ -4709,15 +5790,20 @@ async function materializeLarkResources(messageId, prompt, resources, service) {
|
|
|
4709
5790
|
${notes.join("\n")}`.trim();
|
|
4710
5791
|
}
|
|
4711
5792
|
async function sendTaskCard(service, event, input, log) {
|
|
4712
|
-
|
|
5793
|
+
const { forceMainThread, ...cardInput } = input;
|
|
5794
|
+
if (forceMainThread && event.threadId?.trim()) {
|
|
5795
|
+
return await service.send({ chatId: event.chatId, ...cardInput });
|
|
5796
|
+
}
|
|
5797
|
+
if ((event.chatType === "group" || cardInput.replyInThread) && typeof service.reply === "function") {
|
|
4713
5798
|
try {
|
|
4714
|
-
|
|
5799
|
+
const replyContext = forceMainThread ? { messageId: event.messageId } : larkReplyContext(event);
|
|
5800
|
+
return await service.reply({ ...replyContext, ...cardInput });
|
|
4715
5801
|
} catch (error) {
|
|
4716
5802
|
log?.warn({ error, messageId: event.messageId, chatId: event.chatId }, "\u56DE\u590D\u5361\u7247\u5931\u8D25\uFF0C\u56DE\u9000\u4E3A\u7FA4\u5185\u53D1\u9001");
|
|
4717
|
-
return await service.send({ chatId: event.chatId, ...
|
|
5803
|
+
return await service.send({ chatId: event.chatId, ...cardInput });
|
|
4718
5804
|
}
|
|
4719
5805
|
}
|
|
4720
|
-
return await service.send({ chatId: event.chatId, ...
|
|
5806
|
+
return await service.send({ chatId: event.chatId, ...cardInput });
|
|
4721
5807
|
}
|
|
4722
5808
|
async function sendPersistedTaskCard(service, persisted, input, log) {
|
|
4723
5809
|
const replyMessageId = persisted.reply_message_id?.trim() || (persisted.root_message_id?.trim().startsWith("om_") ? persisted.root_message_id.trim() : void 0);
|
|
@@ -4730,11 +5816,16 @@ async function sendPersistedTaskCard(service, persisted, input, log) {
|
|
|
4730
5816
|
}
|
|
4731
5817
|
return await service.send({ chatId: persisted.chat_id, ...input });
|
|
4732
5818
|
}
|
|
4733
|
-
async function sendQuietFinalReply(service, event, text3, log, forceReplyInThread) {
|
|
5819
|
+
async function sendQuietFinalReply(service, event, text3, log, forceReplyInThread, forceMainThread) {
|
|
4734
5820
|
const content = text3.trim() || "\uFF08Agent \u672A\u8FD4\u56DE\u6700\u7EC8\u8F93\u51FA\uFF09";
|
|
5821
|
+
if (forceMainThread && event.threadId?.trim()) {
|
|
5822
|
+
await service.sendText({ chatId: event.chatId, text: content });
|
|
5823
|
+
return;
|
|
5824
|
+
}
|
|
4735
5825
|
if ((event.chatType === "group" || forceReplyInThread) && typeof service.replyText === "function") {
|
|
4736
5826
|
try {
|
|
4737
|
-
|
|
5827
|
+
const replyInThread = forceMainThread ? false : Boolean(forceReplyInThread || event.threadId?.trim());
|
|
5828
|
+
await service.replyText({ messageId: event.messageId, text: content, ...replyInThread ? { replyInThread: true } : {} });
|
|
4738
5829
|
return;
|
|
4739
5830
|
} catch (error) {
|
|
4740
5831
|
log?.warn({ error, messageId: event.messageId, chatId: event.chatId }, "\u9759\u9ED8\u56DE\u590D\u5931\u8D25\uFF0C\u56DE\u9000\u4E3A\u7FA4\u5185\u53D1\u9001");
|
|
@@ -4746,7 +5837,7 @@ async function deliverTaskFailure(service, event, config, input, log) {
|
|
|
4746
5837
|
if (config.quietReply) {
|
|
4747
5838
|
const markdown = typeof input.markdown === "string" ? input.markdown : "";
|
|
4748
5839
|
const text3 = markdown.replace(/<[^>]+>/g, "").replace(/\*\*/g, "").replace(/`/g, "").replace(/\n{3,}/g, "\n\n").trim() || "\uFF08AgentDock \u5904\u7406\u5931\u8D25\uFF09";
|
|
4749
|
-
await sendQuietFinalReply(service, event, text3, log, input.replyInThread);
|
|
5840
|
+
await sendQuietFinalReply(service, event, text3, log, input.replyInThread, input.forceMainThread);
|
|
4750
5841
|
return { messageId: "" };
|
|
4751
5842
|
}
|
|
4752
5843
|
return await sendTaskCard(service, event, input, log);
|
|
@@ -4874,6 +5965,7 @@ var init_listener = __esm({
|
|
|
4874
5965
|
init_agent_tools();
|
|
4875
5966
|
init_handover_binding();
|
|
4876
5967
|
init_side_chat_config();
|
|
5968
|
+
init_regex_triggers();
|
|
4877
5969
|
init_src2();
|
|
4878
5970
|
init_handover_binding();
|
|
4879
5971
|
acknowledgementEmojis = ["OK", "THUMBSUP", "FINGERHEART", "APPLAUSE", "JIAYI"];
|
|
@@ -5723,18 +6815,20 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
5723
6815
|
}
|
|
5724
6816
|
async saveCardTask(task, state = task.state) {
|
|
5725
6817
|
if (!this.cardMappings || !task.sessionId || !task.cardMessageId || !task.startedAt) return;
|
|
6818
|
+
const cardTaskName = task.regexTrigger ? `[${task.regexTrigger.ruleName}] ${task.regexTrigger.messagePreview}`.slice(0, 80) : task.prompt.slice(0, 80);
|
|
6819
|
+
const forceMainFromThread = task.regexTrigger?.replyMode === "main" && Boolean(task.event.threadId?.trim());
|
|
5726
6820
|
const extra = {
|
|
5727
6821
|
app_id: task.config.appId,
|
|
5728
6822
|
chat_id: task.event.chatId,
|
|
5729
6823
|
card_message_id: task.cardMessageId,
|
|
5730
6824
|
...task.runtimeTaskId ? { runtime_task_id: task.runtimeTaskId } : {},
|
|
5731
|
-
task_name:
|
|
6825
|
+
task_name: cardTaskName,
|
|
5732
6826
|
prompt: task.prompt,
|
|
5733
6827
|
state,
|
|
5734
6828
|
...task.lastSuccessfulElements?.length ? { last_successful_elements: task.lastSuccessfulElements } : {},
|
|
5735
|
-
|
|
6829
|
+
...!forceMainFromThread && (task.event.chatType === "group" || task.forceReplyInThread) ? {
|
|
5736
6830
|
reply_message_id: task.event.messageId,
|
|
5737
|
-
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.forceReplyInThread || task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
6831
|
+
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.regexTrigger ? { reply_in_thread: task.regexTrigger.replyMode === "thread" } : task.forceReplyInThread || task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
5738
6832
|
} : {},
|
|
5739
6833
|
started_at: task.startedAt
|
|
5740
6834
|
};
|
|
@@ -6047,6 +7141,34 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
6047
7141
|
const existingSideThread = await this.lookupSideChatThread(config.appId, event);
|
|
6048
7142
|
const inSideChatFollowUp = Boolean(existingSideThread) && (event.chatType === "p2p" || mentionsBot || event.mentions.length === 0);
|
|
6049
7143
|
let shouldWake = event.chatType === "p2p" || event.chatType === "group" && mentionsBot || inSideChatFollowUp;
|
|
7144
|
+
let matchedRegex;
|
|
7145
|
+
let regexParsedText = "";
|
|
7146
|
+
if (!shouldWake && !this.stopped && !this.handledMessages.has(event.messageId) && event.chatType === "group" && this.configRepository) {
|
|
7147
|
+
const isSelfBot = Boolean(this.botOpenId && event.senderOpenId === this.botOpenId);
|
|
7148
|
+
if (!isSelfBot) {
|
|
7149
|
+
try {
|
|
7150
|
+
const quickParsed = await parseLarkMessageContent(event.messageType, event.content, { messageId: event.messageId });
|
|
7151
|
+
regexParsedText = renderPromptMentions(quickParsed.text, event.mentions, (mention) => this.isSelfMention(config, mention)).trim();
|
|
7152
|
+
matchedRegex = await findMatchingRealtimeRegexTrigger(this.configRepository, {
|
|
7153
|
+
botId: config.appId,
|
|
7154
|
+
chatId: event.chatId,
|
|
7155
|
+
messageId: event.messageId,
|
|
7156
|
+
messageText: regexParsedText,
|
|
7157
|
+
...event.senderType ? { senderType: event.senderType } : {},
|
|
7158
|
+
isSelfBot
|
|
7159
|
+
});
|
|
7160
|
+
if (matchedRegex) {
|
|
7161
|
+
shouldWake = true;
|
|
7162
|
+
this.log.info(
|
|
7163
|
+
{ messageId: event.messageId, chatId: event.chatId, appId: config.appId, ruleId: matchedRegex.rule.id, ruleName: matchedRegex.rule.name, replyMode: matchedRegex.rule.replyMode },
|
|
7164
|
+
"\u98DE\u4E66\u7FA4\u6D88\u606F\u547D\u4E2D\u6B63\u5219\u89C4\u5219\uFF0C\u81EA\u52A8\u5524\u8D77\u673A\u5668\u4EBA"
|
|
7165
|
+
);
|
|
7166
|
+
}
|
|
7167
|
+
} catch (error) {
|
|
7168
|
+
this.log.warn({ error, messageId: event.messageId, chatId: event.chatId, appId: config.appId }, "\u68C0\u6D4B\u98DE\u4E66\u7FA4\u804A\u6B63\u5219\u76D1\u542C\u89C4\u5219\u5931\u8D25");
|
|
7169
|
+
}
|
|
7170
|
+
}
|
|
7171
|
+
}
|
|
6050
7172
|
if (!shouldWake && !this.stopped && !this.handledMessages.has(event.messageId) && event.chatType === "group" && event.mentions.length === 0 && (!event.senderType || event.senderType === "user")) {
|
|
6051
7173
|
if (await this.isSoloUserGroup(config, event.chatId)) {
|
|
6052
7174
|
shouldWake = true;
|
|
@@ -6063,7 +7185,7 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
6063
7185
|
const mainScopeId = larkGroupScopeId(event, config.groupSessionScope);
|
|
6064
7186
|
const mainGroupKey = larkGroupKey(event, config.groupSessionScope);
|
|
6065
7187
|
let matchedNewSideChat = false;
|
|
6066
|
-
if (!existingSideThread && sideChatConfig.btwEnabled) {
|
|
7188
|
+
if (!matchedRegex && !existingSideThread && sideChatConfig.btwEnabled) {
|
|
6067
7189
|
try {
|
|
6068
7190
|
const quickParsed = await parseLarkMessageContent(event.messageType, event.content, { messageId: event.messageId });
|
|
6069
7191
|
const quickText = renderPromptMentions(quickParsed.text, event.mentions, (mention) => this.isSelfMention(config, mention)).trim();
|
|
@@ -6072,15 +7194,16 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
6072
7194
|
}
|
|
6073
7195
|
}
|
|
6074
7196
|
const triggerRootId = event.rootId?.trim() || event.messageId;
|
|
6075
|
-
const isSideChat = Boolean(existingSideThread) || matchedNewSideChat;
|
|
6076
|
-
const
|
|
7197
|
+
const isSideChat = !matchedRegex && (Boolean(existingSideThread) || matchedNewSideChat);
|
|
7198
|
+
const regexGroupKey = matchedRegex ? matchedRegex.rule.replyMode === "thread" ? `${event.chatId}:${event.threadId?.trim() ? `thread:${event.threadId.trim()}` : `regex-thread:${event.messageId}`}` : mainGroupKey : void 0;
|
|
7199
|
+
const groupKey = isSideChat ? `side-chat:${event.chatId}:${existingSideThread ? existingSideThread.key : triggerRootId}` : regexGroupKey ?? mainGroupKey;
|
|
6077
7200
|
const group = this.groups.get(groupKey) ?? { tail: Promise.resolve() };
|
|
6078
7201
|
if (existingSideThread) {
|
|
6079
7202
|
group.boundSessionId = existingSideThread.sessionId;
|
|
6080
7203
|
if (event.threadId?.trim()) {
|
|
6081
7204
|
void this.saveSideChatThread(config.appId, [existingSideThread.key, event.threadId.trim()], existingSideThread.sessionId);
|
|
6082
7205
|
}
|
|
6083
|
-
} else if (!isSideChat && !group.boundSessionId && this.cardMappings) {
|
|
7206
|
+
} else if (!isSideChat && !matchedRegex && !group.boundSessionId && this.cardMappings) {
|
|
6084
7207
|
try {
|
|
6085
7208
|
const mapping = await this.cardMappings.get(larkHandoverChannel(config.appId), event.chatId);
|
|
6086
7209
|
if (mapping?.sessionId) group.boundSessionId = mapping.sessionId;
|
|
@@ -6098,7 +7221,22 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
6098
7221
|
state: "queued",
|
|
6099
7222
|
events: [],
|
|
6100
7223
|
turn: 0,
|
|
6101
|
-
...isSideChat ? { forceReplyInThread: true } : {},
|
|
7224
|
+
...isSideChat || matchedRegex?.rule.replyMode === "thread" ? { forceReplyInThread: true } : {},
|
|
7225
|
+
...matchedRegex ? {
|
|
7226
|
+
regexTrigger: {
|
|
7227
|
+
ruleId: matchedRegex.rule.id,
|
|
7228
|
+
ruleName: matchedRegex.rule.name,
|
|
7229
|
+
chatName: matchedRegex.rule.chatName,
|
|
7230
|
+
pattern: matchedRegex.rule.pattern,
|
|
7231
|
+
flags: matchedRegex.rule.flags,
|
|
7232
|
+
replyMode: matchedRegex.rule.replyMode,
|
|
7233
|
+
promptTemplate: matchedRegex.rule.promptTemplate,
|
|
7234
|
+
matchedText: matchedRegex.matchedText,
|
|
7235
|
+
messagePreview: regexParsedText.slice(0, 120),
|
|
7236
|
+
triggerType: "realtime",
|
|
7237
|
+
allowBotSender: !matchedRegex.rule.ignoreBotMessages
|
|
7238
|
+
}
|
|
7239
|
+
} : {},
|
|
6102
7240
|
...matchedNewSideChat ? {
|
|
6103
7241
|
sideChat: {
|
|
6104
7242
|
parentGroupKey: mainGroupKey,
|
|
@@ -6118,14 +7256,136 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
6118
7256
|
appId: config.appId,
|
|
6119
7257
|
...stripSideChatTriggerPrefix ? { stripSideChatTriggerPrefix } : {}
|
|
6120
7258
|
});
|
|
6121
|
-
task.
|
|
7259
|
+
if (task.regexTrigger) {
|
|
7260
|
+
let senderName = task.regexTrigger.senderName;
|
|
7261
|
+
if (!senderName && event.senderOpenId && event.senderType !== "app" && event.senderType !== "bot") {
|
|
7262
|
+
senderName = await this.service.getUserName(event.senderOpenId).catch(() => void 0);
|
|
7263
|
+
if (senderName) task.regexTrigger.senderName = senderName;
|
|
7264
|
+
}
|
|
7265
|
+
const chatName = task.regexTrigger.chatName && task.regexTrigger.chatName !== event.chatId ? task.regexTrigger.chatName : await this.resolveCurrentChatName(config, event) || event.chatId;
|
|
7266
|
+
task.regexTrigger.chatName = chatName;
|
|
7267
|
+
const messageText = parsed.prompt || regexParsedText;
|
|
7268
|
+
task.regexTrigger.messagePreview = messageText.slice(0, 120);
|
|
7269
|
+
task.prompt = buildRegexTriggerPrompt({
|
|
7270
|
+
promptTemplate: task.regexTrigger.promptTemplate,
|
|
7271
|
+
chatName,
|
|
7272
|
+
chatId: event.chatId,
|
|
7273
|
+
botName: config.name ?? config.appId,
|
|
7274
|
+
botId: config.appId,
|
|
7275
|
+
ruleName: task.regexTrigger.ruleName,
|
|
7276
|
+
pattern: task.regexTrigger.pattern,
|
|
7277
|
+
flags: task.regexTrigger.flags,
|
|
7278
|
+
replyMode: task.regexTrigger.replyMode,
|
|
7279
|
+
...senderName ? { senderName } : {},
|
|
7280
|
+
...event.senderOpenId ? { senderId: event.senderOpenId } : {},
|
|
7281
|
+
messageId: event.messageId,
|
|
7282
|
+
...event.createTime ? { messageTime: event.createTime } : {},
|
|
7283
|
+
messageText,
|
|
7284
|
+
matchedText: task.regexTrigger.matchedText,
|
|
7285
|
+
triggerType: "realtime"
|
|
7286
|
+
});
|
|
7287
|
+
} else {
|
|
7288
|
+
task.prompt = parsed.prompt;
|
|
7289
|
+
}
|
|
6122
7290
|
task.resources = parsed.resources;
|
|
6123
7291
|
await this.runTurn(task);
|
|
7292
|
+
if (task.regexTrigger) {
|
|
7293
|
+
await recordLarkRegexTriggerHit(this.configRepository, {
|
|
7294
|
+
ruleId: task.regexTrigger.ruleId,
|
|
7295
|
+
botId: config.appId,
|
|
7296
|
+
chatId: event.chatId,
|
|
7297
|
+
messageId: event.messageId,
|
|
7298
|
+
...task.sessionId ? { sessionId: task.sessionId } : {},
|
|
7299
|
+
...task.cardMessageId ? { cardMessageId: task.cardMessageId } : {},
|
|
7300
|
+
matchedText: task.regexTrigger.matchedText,
|
|
7301
|
+
...task.regexTrigger.senderName ? { senderName: task.regexTrigger.senderName } : {},
|
|
7302
|
+
messagePreview: task.regexTrigger.messagePreview,
|
|
7303
|
+
triggerType: "realtime",
|
|
7304
|
+
status: task.state === "failed" ? "failed" : "triggered",
|
|
7305
|
+
...task.failureReason ? { error: task.failureReason } : {}
|
|
7306
|
+
});
|
|
7307
|
+
}
|
|
6124
7308
|
}).catch((error) => {
|
|
6125
7309
|
this.log.error({ error, chatId: event.chatId, messageId: event.messageId }, "\u5904\u7406\u98DE\u4E66\u5524\u9192\u6D88\u606F\u5931\u8D25");
|
|
6126
7310
|
});
|
|
6127
7311
|
this.groups.set(groupKey, group);
|
|
6128
7312
|
}
|
|
7313
|
+
/**
|
|
7314
|
+
* 历史命中消息补偿入口:100% 复用当前机器人的飞书设置(Agent/模型/工作区/预注入 Prompt/群协作工具/门禁/卡片流式推送),
|
|
7315
|
+
* 按规则的 replyMode(话题内或主线程)发起一轮 Agent,并在派发成功后立即返回 sessionId 与 cardMessageId。
|
|
7316
|
+
*/
|
|
7317
|
+
async triggerRegexMatch(input) {
|
|
7318
|
+
const { event, config, rule } = input;
|
|
7319
|
+
const triggerType = input.triggerType ?? "backfill";
|
|
7320
|
+
const mainGroupKey = larkGroupKey(event, config.groupSessionScope);
|
|
7321
|
+
const groupKey = rule.replyMode === "thread" ? `${event.chatId}:${event.threadId?.trim() ? `thread:${event.threadId.trim()}` : `regex-thread:${event.messageId}`}` : mainGroupKey;
|
|
7322
|
+
const group = this.groups.get(groupKey) ?? { tail: Promise.resolve() };
|
|
7323
|
+
this.groups.set(groupKey, group);
|
|
7324
|
+
const chatName = rule.chatName?.trim() || event.chatId;
|
|
7325
|
+
const prompt = buildRegexTriggerPrompt({
|
|
7326
|
+
promptTemplate: rule.promptTemplate,
|
|
7327
|
+
chatName,
|
|
7328
|
+
chatId: event.chatId,
|
|
7329
|
+
botName: config.name ?? config.appId,
|
|
7330
|
+
botId: config.appId,
|
|
7331
|
+
ruleName: rule.name,
|
|
7332
|
+
pattern: rule.pattern,
|
|
7333
|
+
flags: rule.flags,
|
|
7334
|
+
replyMode: rule.replyMode,
|
|
7335
|
+
...input.senderName ? { senderName: input.senderName } : {},
|
|
7336
|
+
...event.senderOpenId ? { senderId: event.senderOpenId } : {},
|
|
7337
|
+
messageId: event.messageId,
|
|
7338
|
+
...event.createTime ? { messageTime: event.createTime } : {},
|
|
7339
|
+
messageText: input.messageText,
|
|
7340
|
+
matchedText: input.matchedText,
|
|
7341
|
+
triggerType
|
|
7342
|
+
});
|
|
7343
|
+
const taskId = triggerType === "backfill" ? `${event.messageId}:bf:${Date.now().toString(36)}` : event.messageId;
|
|
7344
|
+
const task = {
|
|
7345
|
+
id: taskId,
|
|
7346
|
+
group,
|
|
7347
|
+
event,
|
|
7348
|
+
prompt,
|
|
7349
|
+
resources: [],
|
|
7350
|
+
config,
|
|
7351
|
+
state: "queued",
|
|
7352
|
+
events: [],
|
|
7353
|
+
turn: 0,
|
|
7354
|
+
...rule.replyMode === "thread" ? { forceReplyInThread: true } : {},
|
|
7355
|
+
regexTrigger: {
|
|
7356
|
+
ruleId: rule.id,
|
|
7357
|
+
ruleName: rule.name,
|
|
7358
|
+
chatName,
|
|
7359
|
+
pattern: rule.pattern,
|
|
7360
|
+
flags: rule.flags,
|
|
7361
|
+
replyMode: rule.replyMode,
|
|
7362
|
+
promptTemplate: rule.promptTemplate,
|
|
7363
|
+
matchedText: input.matchedText,
|
|
7364
|
+
messagePreview: input.messageText.slice(0, 120),
|
|
7365
|
+
...input.senderName ? { senderName: input.senderName } : {},
|
|
7366
|
+
triggerType,
|
|
7367
|
+
allowBotSender: true,
|
|
7368
|
+
backfillByAdmin: triggerType === "backfill"
|
|
7369
|
+
}
|
|
7370
|
+
};
|
|
7371
|
+
this.tasks.set(task.id, task);
|
|
7372
|
+
if (this.tasks.size > 5e3) this.tasks.delete(this.tasks.keys().next().value);
|
|
7373
|
+
this.handledMessages.add(event.messageId);
|
|
7374
|
+
if (this.handledMessages.size > 5e3) this.handledMessages.delete(this.handledMessages.values().next().value);
|
|
7375
|
+
const runPromise = group.tail.then(() => this.runTurn(task));
|
|
7376
|
+
group.tail = runPromise.catch((error) => {
|
|
7377
|
+
this.log.error({ error, chatId: event.chatId, messageId: event.messageId, ruleId: rule.id }, "\u98DE\u4E66\u5386\u53F2\u8865\u507F\u8F6E\u6B21\u6267\u884C\u5931\u8D25");
|
|
7378
|
+
});
|
|
7379
|
+
await runPromise;
|
|
7380
|
+
if (task.state === "failed" && (!task.sessionId || task.failureReason)) {
|
|
7381
|
+
throw new LarkServiceError("LARK_BACKFILL_FAILED", task.failureReason || "\u53D1\u8D77\u5386\u53F2\u8865\u507F\u8F6E\u6B21\u5931\u8D25", 502);
|
|
7382
|
+
}
|
|
7383
|
+
return {
|
|
7384
|
+
taskId: task.id,
|
|
7385
|
+
...task.sessionId ? { sessionId: task.sessionId } : {},
|
|
7386
|
+
...task.cardMessageId ? { cardMessageId: task.cardMessageId } : {}
|
|
7387
|
+
};
|
|
7388
|
+
}
|
|
6129
7389
|
/**
|
|
6130
7390
|
* 卡片操作人的访问权限校验,与 runTurn 中「谁可以使用 Agent」的配置保持一致:
|
|
6131
7391
|
* - 未配置白名单时所有人均可操作
|
|
@@ -6353,8 +7613,10 @@ ${lines.join("\n")}`;
|
|
|
6353
7613
|
if (!task.prompt.trim()) {
|
|
6354
7614
|
task.prompt = task.sideChat ? "\u7528\u6237\u5F00\u542F\u4E86\u4FA7\u8FB9\u5BF9\u8BDD\uFF0C\u4F46\u672A\u8F93\u5165\u5177\u4F53\u95EE\u9898\u3002\u8BF7\u7B80\u77ED\u8BF4\u660E\u4FA7\u8FB9\u5BF9\u8BDD\u5DF2\u5C31\u7EEA\uFF0C\u7528\u6237\u53EF\u5728\u672C\u8BDD\u9898\u4E2D\u7EE7\u7EED\u63D0\u95EE\u3002" : await this.buildEmptyMessageFallback(event, config);
|
|
6355
7615
|
}
|
|
6356
|
-
const
|
|
7616
|
+
const forceMainThread = task.regexTrigger?.replyMode === "main";
|
|
7617
|
+
const replyDeliveryOpt = task.forceReplyInThread ? { replyInThread: true } : forceMainThread ? { replyInThread: false, forceMainThread: true } : {};
|
|
6357
7618
|
const prompt = task.prompt;
|
|
7619
|
+
const cardTaskName = task.regexTrigger ? `[${task.regexTrigger.ruleName}] ${task.regexTrigger.messagePreview}`.slice(0, 80) : prompt.slice(0, 80);
|
|
6358
7620
|
const firstAttempt = !task.cardMessageId;
|
|
6359
7621
|
const emojiType = acknowledgementEmojis[Math.floor(this.random() * acknowledgementEmojis.length)] ?? acknowledgementEmojis[0];
|
|
6360
7622
|
let reactionId;
|
|
@@ -6365,21 +7627,26 @@ ${lines.join("\n")}`;
|
|
|
6365
7627
|
this.log.warn({ error, messageId: event.messageId }, "\u53D1\u9001\u98DE\u4E66\u786E\u8BA4\u8868\u60C5\u5931\u8D25\uFF0C\u7EE7\u7EED\u6267\u884C\u4EFB\u52A1");
|
|
6366
7628
|
}
|
|
6367
7629
|
}
|
|
6368
|
-
|
|
6369
|
-
|
|
6370
|
-
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
6374
|
-
|
|
6375
|
-
|
|
7630
|
+
const backfillByAdmin = task.regexTrigger?.backfillByAdmin === true;
|
|
7631
|
+
const allowRegexBotSender = task.regexTrigger?.allowBotSender === true;
|
|
7632
|
+
if (!backfillByAdmin) {
|
|
7633
|
+
try {
|
|
7634
|
+
config = await resolveLarkAccessConfig(config, this.service, event.senderType === "app" || event.senderType === "bot" ? "bot" : "user", this.configRepository);
|
|
7635
|
+
task.config = config;
|
|
7636
|
+
} catch (error) {
|
|
7637
|
+
task.state = "failed";
|
|
7638
|
+
task.retryable = false;
|
|
7639
|
+
task.startedAt = Date.now();
|
|
7640
|
+
task.failureReason = error instanceof Error ? error.message : String(error);
|
|
7641
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", retryable: false, taskId: task.id, taskName: "\u767D\u540D\u5355\u8EAB\u4EFD\u89E3\u6790\u5931\u8D25", markdown: `**\u6682\u65F6\u65E0\u6CD5\u9A8C\u8BC1\u767D\u540D\u5355\u8EAB\u4EFD\u3002**
|
|
6376
7642
|
|
|
6377
7643
|
${error instanceof Error ? error.message : String(error)}
|
|
6378
7644
|
|
|
6379
|
-
\u8BF7\u786E\u8BA4\u673A\u5668\u4EBA\u4E0E\u540D\u5355\u4E2D\u7684\u6210\u5458\u5728\u540C\u4E00\u7FA4\u4E2D\uFF0C\u4E14\u5177\u5907\u8BFB\u53D6\u7FA4\u6210\u5458\u6743\u9650\uFF1B\u4FEE\u6B63\u540E\u91CD\u65B0\u53D1\u9001\u6D88\u606F\u3002`, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} }, this.log);
|
|
6380
|
-
|
|
6381
|
-
|
|
6382
|
-
|
|
7645
|
+
\u8BF7\u786E\u8BA4\u673A\u5668\u4EBA\u4E0E\u540D\u5355\u4E2D\u7684\u6210\u5458\u5728\u540C\u4E00\u7FA4\u4E2D\uFF0C\u4E14\u5177\u5907\u8BFB\u53D6\u7FA4\u6210\u5458\u6743\u9650\uFF1B\u4FEE\u6B63\u540E\u91CD\u65B0\u53D1\u9001\u6D88\u606F\u3002`, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
7646
|
+
if (card.messageId) task.cardMessageId = card.messageId;
|
|
7647
|
+
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
7648
|
+
return;
|
|
7649
|
+
}
|
|
6383
7650
|
}
|
|
6384
7651
|
let actorEmails = [];
|
|
6385
7652
|
const allowedUsers = config.allowedUsers ?? [];
|
|
@@ -6391,33 +7658,37 @@ ${error instanceof Error ? error.message : String(error)}
|
|
|
6391
7658
|
const highRiskPattern = config.highRiskPattern || defaultHighRiskPattern;
|
|
6392
7659
|
const gateEnabled = config.gateEnabled === true;
|
|
6393
7660
|
const botSender = event.senderType === "app" || event.senderType === "bot";
|
|
6394
|
-
if (
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
|
|
6398
|
-
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
7661
|
+
if (!backfillByAdmin) {
|
|
7662
|
+
if (botSender) {
|
|
7663
|
+
try {
|
|
7664
|
+
if (!allowRegexBotSender && config.groupToolsEnabled && event.senderOpenId) await this.peerBotAuthorized?.(event.chatId, event.senderOpenId);
|
|
7665
|
+
} catch (error) {
|
|
7666
|
+
task.state = "failed";
|
|
7667
|
+
task.retryable = false;
|
|
7668
|
+
task.startedAt = Date.now();
|
|
7669
|
+
task.failureReason = error instanceof Error ? error.message : String(error);
|
|
7670
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", retryable: false, taskId: task.id, taskName: "Agent \u534F\u4F5C\u8EAB\u4EFD\u6821\u9A8C\u5931\u8D25", markdown: `**\u65E0\u6CD5\u9A8C\u8BC1\u53D1\u8D77\u4EA4\u63A5\u7684 Agent\u3002**
|
|
6402
7671
|
|
|
6403
|
-
${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} }, this.log);
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
|
|
6408
|
-
|
|
6409
|
-
|
|
6410
|
-
|
|
6411
|
-
|
|
6412
|
-
|
|
6413
|
-
|
|
6414
|
-
|
|
6415
|
-
|
|
6416
|
-
|
|
6417
|
-
|
|
6418
|
-
|
|
6419
|
-
|
|
6420
|
-
|
|
7672
|
+
${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
7673
|
+
if (card.messageId) task.cardMessageId = card.messageId;
|
|
7674
|
+
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
7675
|
+
return;
|
|
7676
|
+
}
|
|
7677
|
+
} else if (!allowedUsers.length && allowedEmails.length || gateEnabled && !highRiskAllowedUsers.length && highRiskAllowedEmails.length) {
|
|
7678
|
+
try {
|
|
7679
|
+
if (!event.senderOpenId) throw new Error("\u6D88\u606F\u4E8B\u4EF6\u672A\u5305\u542B\u53D1\u9001\u4EBA open_id");
|
|
7680
|
+
actorEmails = await this.service.getUserEmails(event.senderOpenId);
|
|
7681
|
+
if (!actorEmails.length) throw new LarkServiceError("LARK_SENDER_EMAIL_EMPTY", "\u98DE\u4E66\u6CA1\u6709\u8FD4\u56DE\u5F53\u524D\u53D1\u9001\u4EBA\u7684\u90AE\u7BB1\u5B57\u6BB5", 409);
|
|
7682
|
+
} catch (error) {
|
|
7683
|
+
task.state = "failed";
|
|
7684
|
+
task.retryable = false;
|
|
7685
|
+
task.startedAt = Date.now();
|
|
7686
|
+
task.failureReason = error instanceof Error ? error.message : String(error);
|
|
7687
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", retryable: false, taskId: task.id, taskName: "\u8EAB\u4EFD\u89E3\u6790\u6743\u9650\u7F3A\u5931", markdown: larkIdentityPermissionHelp(error, config.appId), ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
7688
|
+
if (card.messageId) task.cardMessageId = card.messageId;
|
|
7689
|
+
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
7690
|
+
return;
|
|
7691
|
+
}
|
|
6421
7692
|
}
|
|
6422
7693
|
}
|
|
6423
7694
|
const senderOpenId = event.senderOpenId ?? "";
|
|
@@ -6425,12 +7696,13 @@ ${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl
|
|
|
6425
7696
|
const allowedBot = allowedBots.find((bot) => bot.openId === senderOpenId);
|
|
6426
7697
|
const highRiskAllowedUser = highRiskAllowedUsers.find((user) => user.openId === senderOpenId);
|
|
6427
7698
|
const accessRestricted = allowedUsers.length > 0 || allowedEmails.length > 0 || Boolean(config.allowedUserNames?.length);
|
|
6428
|
-
const allowed = botSender ? !accessRestricted || peerBotsAllowed || Boolean(allowedBot) : !accessRestricted || (allowedUsers.length ? Boolean(allowedUser) : actorEmails.some((email) => allowedEmails.includes(email)));
|
|
7699
|
+
const allowed = backfillByAdmin ? true : botSender ? allowRegexBotSender || !accessRestricted || peerBotsAllowed || Boolean(allowedBot) : !accessRestricted || (allowedUsers.length ? Boolean(allowedUser) : actorEmails.some((email) => allowedEmails.includes(email)));
|
|
6429
7700
|
if (!allowed) {
|
|
6430
7701
|
task.state = "failed";
|
|
6431
7702
|
task.retryable = false;
|
|
6432
7703
|
task.startedAt = Date.now();
|
|
6433
|
-
|
|
7704
|
+
task.failureReason = "\u5F53\u524D\u8D26\u53F7\u4E0D\u5728\u673A\u5668\u4EBA\u767D\u540D\u5355\u4E2D";
|
|
7705
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", retryable: false, taskId: task.id, taskName: "\u8BBF\u95EE\u88AB\u62D2\u7EDD", markdown: "**\u5F53\u524D\u8D26\u53F7\u4E0D\u5728\u673A\u5668\u4EBA\u767D\u540D\u5355\u4E2D\u3002**\n\n\u5982\u9700\u4F7F\u7528\uFF0C\u8BF7\u8054\u7CFB\u673A\u5668\u4EBA\u7BA1\u7406\u5458\u6DFB\u52A0\u4F60\u3002", ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
6434
7706
|
if (card.messageId) task.cardMessageId = card.messageId;
|
|
6435
7707
|
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
6436
7708
|
return;
|
|
@@ -6444,16 +7716,18 @@ ${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl
|
|
|
6444
7716
|
...actorEmail ? { actorEmail } : {},
|
|
6445
7717
|
reason: "\u5F53\u524D\u98DE\u4E66\u53D1\u9001\u4EBA\u4E0D\u5728\u9AD8\u5371\u64CD\u4F5C\u5141\u8BB8\u540D\u5355\u4E2D"
|
|
6446
7718
|
};
|
|
7719
|
+
const regexScopeId = task.regexTrigger?.replyMode === "thread" ? event.threadId?.trim() ? `thread:${event.threadId.trim()}` : `regex-thread:${event.messageId}` : void 0;
|
|
6447
7720
|
let session;
|
|
6448
7721
|
try {
|
|
6449
|
-
session = task.sideChat ? await this.sideChatSessionFor(task) : await this.sessionFor(group, config, event.chatId, event.chatType, larkGroupScopeId(event, config.groupSessionScope));
|
|
7722
|
+
session = task.sideChat ? await this.sideChatSessionFor(task) : await this.sessionFor(group, config, event.chatId, event.chatType, regexScopeId ?? larkGroupScopeId(event, config.groupSessionScope));
|
|
6450
7723
|
} catch (error) {
|
|
6451
7724
|
task.state = "failed";
|
|
6452
7725
|
task.startedAt = Date.now();
|
|
7726
|
+
task.failureReason = error instanceof Error ? error.message : String(error);
|
|
6453
7727
|
const markdown = `**Agent \u542F\u52A8\u5931\u8D25**
|
|
6454
7728
|
|
|
6455
|
-
${
|
|
6456
|
-
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", taskId: task.id, taskName:
|
|
7729
|
+
${task.failureReason}`;
|
|
7730
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", taskId: task.id, taskName: cardTaskName, markdown, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
6457
7731
|
if (card.messageId) task.cardMessageId = card.messageId;
|
|
6458
7732
|
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
6459
7733
|
return;
|
|
@@ -6468,9 +7742,9 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6468
7742
|
} else {
|
|
6469
7743
|
const initialElements = boundLarkCardElements(renderLarkCardElements([], config));
|
|
6470
7744
|
if (task.cardMessageId) {
|
|
6471
|
-
await this.service.update({ messageId: task.cardMessageId, state: "running", taskId: task.id, taskName:
|
|
7745
|
+
await this.service.update({ messageId: task.cardMessageId, state: "running", taskId: task.id, taskName: cardTaskName, markdown: "\u6B63\u5728\u601D\u8003\u4E2D\u2026", sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} });
|
|
6472
7746
|
} else {
|
|
6473
|
-
const card = await sendTaskCard(this.service, event, { state: "running", taskId: task.id, taskName:
|
|
7747
|
+
const card = await sendTaskCard(this.service, event, { state: "running", taskId: task.id, taskName: cardTaskName, markdown: "\u6B63\u5728\u601D\u8003\u4E2D\u2026", sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyDeliveryOpt }, this.log);
|
|
6474
7748
|
task.cardMessageId = card.messageId;
|
|
6475
7749
|
}
|
|
6476
7750
|
task.lastSuccessfulElements = initialElements;
|
|
@@ -6549,13 +7823,14 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6549
7823
|
const replacement = await sendTaskCard(this.service, event, {
|
|
6550
7824
|
state: pending.input.state,
|
|
6551
7825
|
taskId: task.id,
|
|
6552
|
-
taskName:
|
|
7826
|
+
taskName: cardTaskName,
|
|
6553
7827
|
elapsedSeconds: pending.input.elapsedSeconds,
|
|
6554
7828
|
sessionId: task.sessionId,
|
|
6555
7829
|
...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {},
|
|
6556
7830
|
elements: replacementElements,
|
|
6557
7831
|
...replacementActions ? { actions: replacementActions } : {},
|
|
6558
|
-
idempotencyKey: `comp_${pending.input.messageId}_${pending.input.state}`.slice(0, 50)
|
|
7832
|
+
idempotencyKey: `comp_${pending.input.messageId}_${pending.input.state}`.slice(0, 50),
|
|
7833
|
+
...replyDeliveryOpt
|
|
6559
7834
|
}, this.log);
|
|
6560
7835
|
task.cardMessageId = replacement.messageId;
|
|
6561
7836
|
task.lastSuccessfulElements = replacementElements;
|
|
@@ -6569,13 +7844,14 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6569
7844
|
const minimal = await sendTaskCard(this.service, event, {
|
|
6570
7845
|
state: pending.input.state,
|
|
6571
7846
|
taskId: task.id,
|
|
6572
|
-
taskName:
|
|
7847
|
+
taskName: cardTaskName,
|
|
6573
7848
|
elapsedSeconds: pending.input.elapsedSeconds,
|
|
6574
7849
|
sessionId: task.sessionId,
|
|
6575
7850
|
...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {},
|
|
6576
7851
|
elements: patchedElements,
|
|
6577
7852
|
...minimalActions ? { actions: minimalActions } : {},
|
|
6578
|
-
idempotencyKey: `comp_safe_${pending.input.messageId}_${pending.input.state}`.slice(0, 50)
|
|
7853
|
+
idempotencyKey: `comp_safe_${pending.input.messageId}_${pending.input.state}`.slice(0, 50),
|
|
7854
|
+
...replyDeliveryOpt
|
|
6579
7855
|
}, this.log);
|
|
6580
7856
|
task.cardMessageId = minimal.messageId;
|
|
6581
7857
|
task.lastSuccessfulElements = patchedElements;
|
|
@@ -6612,7 +7888,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6612
7888
|
messageId: task.cardMessageId,
|
|
6613
7889
|
state,
|
|
6614
7890
|
taskId: task.id,
|
|
6615
|
-
taskName:
|
|
7891
|
+
taskName: cardTaskName,
|
|
6616
7892
|
elapsedSeconds: (Date.now() - task.startedAt) / 1e3,
|
|
6617
7893
|
sessionId: task.sessionId,
|
|
6618
7894
|
...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {},
|
|
@@ -6634,7 +7910,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6634
7910
|
let lastQuietError;
|
|
6635
7911
|
for (let attempt = 1; attempt <= maxQuietReplyAttempts; attempt++) {
|
|
6636
7912
|
try {
|
|
6637
|
-
await sendQuietFinalReply(this.service, event, reply, this.log, task.forceReplyInThread);
|
|
7913
|
+
await sendQuietFinalReply(this.service, event, reply, this.log, task.forceReplyInThread, forceMainThread);
|
|
6638
7914
|
lastQuietError = void 0;
|
|
6639
7915
|
break;
|
|
6640
7916
|
} catch (error) {
|
|
@@ -6651,7 +7927,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6651
7927
|
}
|
|
6652
7928
|
return;
|
|
6653
7929
|
}
|
|
6654
|
-
const defaultReplyInThread = Boolean(task.forceReplyInThread || event.threadId?.trim());
|
|
7930
|
+
const defaultReplyInThread = task.regexTrigger ? task.regexTrigger.replyMode === "thread" : Boolean(task.forceReplyInThread || event.threadId?.trim());
|
|
6655
7931
|
const agentReplyInThread = agentReplyMode === "thread";
|
|
6656
7932
|
if (agentReplyMode && agentReplyInThread !== defaultReplyInThread) {
|
|
6657
7933
|
task.replyMode = agentReplyMode;
|
|
@@ -6663,7 +7939,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6663
7939
|
messageId: task.cardMessageId,
|
|
6664
7940
|
state,
|
|
6665
7941
|
taskId: task.id,
|
|
6666
|
-
taskName:
|
|
7942
|
+
taskName: cardTaskName,
|
|
6667
7943
|
elapsedSeconds: (Date.now() - task.startedAt) / 1e3,
|
|
6668
7944
|
sessionId: task.sessionId,
|
|
6669
7945
|
...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {},
|
|
@@ -6675,7 +7951,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
6675
7951
|
const replacement = await sendTaskCard(this.service, event, {
|
|
6676
7952
|
state,
|
|
6677
7953
|
taskId: task.id,
|
|
6678
|
-
taskName:
|
|
7954
|
+
taskName: cardTaskName,
|
|
6679
7955
|
elapsedSeconds: (Date.now() - task.startedAt) / 1e3,
|
|
6680
7956
|
sessionId: task.sessionId,
|
|
6681
7957
|
...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {},
|
|
@@ -6817,14 +8093,16 @@ ${prompt}` : prompt;
|
|
|
6817
8093
|
buffered = [];
|
|
6818
8094
|
if (runtimeTask.status === "queued" && (runtimeTask.queuedAhead ?? 0) > 0 && task.state === "queued") {
|
|
6819
8095
|
if (config.quietReply) {
|
|
6820
|
-
await sendQuietFinalReply(this.service, event, `\u5DF2\u6536\u5230\u8BF7\u6C42\uFF0C\u524D\u9762\u8FD8\u6709 ${runtimeTask.queuedAhead} \u4E2A\u4EFB\u52A1\uFF0C\u5B8C\u6210\u540E\u6211\u4F1A\u628A\u7ED3\u679C\u53D1\u5230\u8FD9\u91CC\u3002`, this.log, task.forceReplyInThread);
|
|
8096
|
+
await sendQuietFinalReply(this.service, event, `\u5DF2\u6536\u5230\u8BF7\u6C42\uFF0C\u524D\u9762\u8FD8\u6709 ${runtimeTask.queuedAhead} \u4E2A\u4EFB\u52A1\uFF0C\u5B8C\u6210\u540E\u6211\u4F1A\u628A\u7ED3\u679C\u53D1\u5230\u8FD9\u91CC\u3002`, this.log, task.forceReplyInThread, forceMainThread);
|
|
6821
8097
|
} else {
|
|
6822
|
-
await this.service.update({ messageId: task.cardMessageId, state: "queued", taskId: task.id, taskName:
|
|
8098
|
+
await this.service.update({ messageId: task.cardMessageId, state: "queued", taskId: task.id, taskName: cardTaskName, markdown: `\u6B63\u5728\u6392\u961F\uFF0C\u524D\u9762\u8FD8\u6709 ${runtimeTask.queuedAhead} \u4E2A\u4EFB\u52A1\u2026`, sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} });
|
|
6823
8099
|
}
|
|
6824
8100
|
await this.saveCardTask(task, "queued");
|
|
6825
8101
|
}
|
|
6826
8102
|
} catch (error) {
|
|
6827
|
-
|
|
8103
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
8104
|
+
task.failureReason = message;
|
|
8105
|
+
task.events.push({ id: `lark-error-${event.messageId}`, sessionId: session.id, sequence: Number.MAX_SAFE_INTEGER, type: "error", timestamp: (/* @__PURE__ */ new Date()).toISOString(), data: { message } });
|
|
6828
8106
|
task.state = "failed";
|
|
6829
8107
|
await finalizeCard("failed", false);
|
|
6830
8108
|
cleanup();
|
|
@@ -7035,6 +8313,9 @@ ${prompt}` : prompt;
|
|
|
7035
8313
|
throw new LarkServiceError("LARK_LISTENER_START_FAILED", `Failed to start Lark listener: ${error instanceof Error ? error.message : String(error)}`, 502);
|
|
7036
8314
|
}
|
|
7037
8315
|
}
|
|
8316
|
+
coordinatorFor() {
|
|
8317
|
+
return this.coordinator;
|
|
8318
|
+
}
|
|
7038
8319
|
stop() {
|
|
7039
8320
|
this.client?.close();
|
|
7040
8321
|
this.coordinator?.stop();
|
|
@@ -7067,6 +8348,9 @@ ${prompt}` : prompt;
|
|
|
7067
8348
|
get activeAppIds() {
|
|
7068
8349
|
return [...this.listeners.keys()];
|
|
7069
8350
|
}
|
|
8351
|
+
coordinatorFor(appId) {
|
|
8352
|
+
return this.listeners.get(appId)?.coordinatorFor?.();
|
|
8353
|
+
}
|
|
7070
8354
|
async sync(configs2) {
|
|
7071
8355
|
const enabled = new Map(configs2.filter((config) => config.listening).map((config) => [config.appId, config]));
|
|
7072
8356
|
this.configs.clear();
|
|
@@ -18832,6 +20116,7 @@ var AcpxAdapter = class {
|
|
|
18832
20116
|
reportedTitle;
|
|
18833
20117
|
riskPolicy;
|
|
18834
20118
|
permissionMode;
|
|
20119
|
+
cachedConfigOptions;
|
|
18835
20120
|
sessionInput() {
|
|
18836
20121
|
return { sessionKey: this.sessionKey, agent: this.agent.id, mode: "persistent", cwd: this.agent.cwd, ...this.options.resumeSessionId ? { resumeSessionId: this.options.resumeSessionId } : {}, sessionOptions: buildAcpxSessionOptions(this.agent) };
|
|
18837
20122
|
}
|
|
@@ -18860,17 +20145,60 @@ var AcpxAdapter = class {
|
|
|
18860
20145
|
record.acpx = { ...record.acpx, reset_on_next_ensure: true };
|
|
18861
20146
|
await this.sessionStore.save(record);
|
|
18862
20147
|
}
|
|
20148
|
+
async syncDesiredOptionsBeforeEnsure() {
|
|
20149
|
+
const record = await this.sessionStore.load(this.sessionKey);
|
|
20150
|
+
if (!record) return false;
|
|
20151
|
+
const acpxState = { ...record.acpx ?? {} };
|
|
20152
|
+
let changed = false;
|
|
20153
|
+
if (this.agent.model && acpxState.session_options?.model !== this.agent.model) {
|
|
20154
|
+
const nextSessionOptions = { ...acpxState.session_options ?? {}, model: this.agent.model };
|
|
20155
|
+
if (isCodexAgent(this.agent)) {
|
|
20156
|
+
nextSessionOptions.env = { ...nextSessionOptions.env ?? {}, agentdock_codex_model: this.agent.model };
|
|
20157
|
+
}
|
|
20158
|
+
acpxState.session_options = nextSessionOptions;
|
|
20159
|
+
changed = true;
|
|
20160
|
+
}
|
|
20161
|
+
const storedOptions = Array.isArray(acpxState.config_options) ? acpxState.config_options : [];
|
|
20162
|
+
if (storedOptions.length) this.cachedConfigOptions = storedOptions;
|
|
20163
|
+
let syncedReasoning = false;
|
|
20164
|
+
if (this.agent.reasoningEffort && storedOptions.length) {
|
|
20165
|
+
const reasoning = storedOptions.find((option) => option.category === "thought_level" || option.id === "reasoning_effort" || option.id === "effort");
|
|
20166
|
+
if (reasoning && typeof reasoning.id === "string") {
|
|
20167
|
+
const currentDesired = acpxState.desired_config_options?.[reasoning.id];
|
|
20168
|
+
if (currentDesired !== this.agent.reasoningEffort) {
|
|
20169
|
+
acpxState.desired_config_options = { ...acpxState.desired_config_options ?? {}, [reasoning.id]: this.agent.reasoningEffort };
|
|
20170
|
+
changed = true;
|
|
20171
|
+
}
|
|
20172
|
+
syncedReasoning = true;
|
|
20173
|
+
}
|
|
20174
|
+
}
|
|
20175
|
+
if (changed) {
|
|
20176
|
+
record.acpx = acpxState;
|
|
20177
|
+
await this.sessionStore.save(record);
|
|
20178
|
+
}
|
|
20179
|
+
return syncedReasoning;
|
|
20180
|
+
}
|
|
20181
|
+
async loadConfigOptions(force = false) {
|
|
20182
|
+
if (!force && this.cachedConfigOptions?.length) return this.cachedConfigOptions;
|
|
20183
|
+
if (!this.handle) return [];
|
|
20184
|
+
const status = await this.runtime.getStatus?.({ handle: this.handle });
|
|
20185
|
+
const options = Array.isArray(status?.details?.configOptions) ? status.details.configOptions : [];
|
|
20186
|
+
if (options.length) this.cachedConfigOptions = options;
|
|
20187
|
+
return options;
|
|
20188
|
+
}
|
|
20189
|
+
getConfigOptions() {
|
|
20190
|
+
return this.cachedConfigOptions;
|
|
20191
|
+
}
|
|
18863
20192
|
/**
|
|
18864
20193
|
* 启动阶段应用配置里的思考深度。与模型同理:一个过期/不被当前模型支持的
|
|
18865
20194
|
* reasoningEffort 不应让整个 Session 起不来(用户会被锁死在改不了配置的状态),
|
|
18866
20195
|
* 因此这里降级为提示并继续,用 Agent 默认深度。
|
|
18867
20196
|
* 注意:运行时通过 setReasoningEffort 显式切换仍会抛错——那是用户的即时操作,需要明确反馈。
|
|
18868
20197
|
*/
|
|
18869
|
-
async applyReasoningEffort() {
|
|
20198
|
+
async applyReasoningEffort(skipWhenSyncedOnDormantRecord = false) {
|
|
18870
20199
|
if (!this.handle || !this.agent.reasoningEffort) return;
|
|
18871
20200
|
const requested = this.agent.reasoningEffort;
|
|
18872
|
-
const
|
|
18873
|
-
const options = Array.isArray(status?.details?.configOptions) ? status.details.configOptions : [];
|
|
20201
|
+
const options = await this.loadConfigOptions(true);
|
|
18874
20202
|
const reasoning = options.find((option) => option.category === "thought_level" || option.id === "reasoning_effort" || option.id === "effort");
|
|
18875
20203
|
const unsupported = !reasoning || typeof reasoning.id !== "string" ? `Agent ${this.agent.id} \u4E0D\u652F\u6301\u914D\u7F6E\u601D\u8003\u6DF1\u5EA6` : Array.isArray(reasoning.options) && !reasoning.options.some((option) => option?.value === requested) ? `\u6A21\u578B ${this.agent.model ?? "(\u9ED8\u8BA4)"} \u4E0D\u652F\u6301\u601D\u8003\u6DF1\u5EA6 ${requested}` : void 0;
|
|
18876
20204
|
if (unsupported) {
|
|
@@ -18881,7 +20209,11 @@ var AcpxAdapter = class {
|
|
|
18881
20209
|
});
|
|
18882
20210
|
return;
|
|
18883
20211
|
}
|
|
18884
|
-
|
|
20212
|
+
if (reasoning.currentValue === requested || skipWhenSyncedOnDormantRecord) return;
|
|
20213
|
+
const response = await this.runtime.setConfigOption?.({ handle: this.handle, key: reasoning.id, value: requested });
|
|
20214
|
+
if (response && Array.isArray(response.configOptions)) {
|
|
20215
|
+
this.cachedConfigOptions = response.configOptions;
|
|
20216
|
+
}
|
|
18885
20217
|
}
|
|
18886
20218
|
isUnadvertisedModelError(error) {
|
|
18887
20219
|
for (let current = error, depth = 0; current && depth < 5; depth++) {
|
|
@@ -18905,6 +20237,7 @@ var AcpxAdapter = class {
|
|
|
18905
20237
|
}
|
|
18906
20238
|
async start() {
|
|
18907
20239
|
await this.resetWhenScopedEnvironmentChanged();
|
|
20240
|
+
const syncedDormantReasoning = await this.syncDesiredOptionsBeforeEnsure();
|
|
18908
20241
|
try {
|
|
18909
20242
|
this.handle = await this.runtime.ensureSession(this.sessionInput());
|
|
18910
20243
|
} catch (error) {
|
|
@@ -18920,11 +20253,14 @@ var AcpxAdapter = class {
|
|
|
18920
20253
|
}
|
|
18921
20254
|
try {
|
|
18922
20255
|
await this.applyCodexPermissionMode();
|
|
18923
|
-
await this.applyReasoningEffort();
|
|
20256
|
+
await this.applyReasoningEffort(syncedDormantReasoning);
|
|
18924
20257
|
} catch (error) {
|
|
18925
20258
|
await this.stop().catch(() => void 0);
|
|
18926
20259
|
throw error;
|
|
18927
20260
|
}
|
|
20261
|
+
if (!this.cachedConfigOptions?.length) {
|
|
20262
|
+
await this.loadConfigOptions(true).catch(() => void 0);
|
|
20263
|
+
}
|
|
18928
20264
|
await this.reportAgentTitle();
|
|
18929
20265
|
}
|
|
18930
20266
|
/**
|
|
@@ -19091,6 +20427,7 @@ var AcpxAdapter = class {
|
|
|
19091
20427
|
}
|
|
19092
20428
|
const handle = this.handle;
|
|
19093
20429
|
this.handle = void 0;
|
|
20430
|
+
this.cachedConfigOptions = void 0;
|
|
19094
20431
|
if (handle) await this.runtime.close({ handle, reason: "AgentDock stop" });
|
|
19095
20432
|
if (options.discardSession) await this.resetPersistentState();
|
|
19096
20433
|
}
|
|
@@ -19104,22 +20441,37 @@ var AcpxAdapter = class {
|
|
|
19104
20441
|
}
|
|
19105
20442
|
async setModel(model) {
|
|
19106
20443
|
if (!this.handle) await this.start();
|
|
19107
|
-
|
|
19108
|
-
|
|
19109
|
-
|
|
20444
|
+
let options = await this.loadConfigOptions(false);
|
|
20445
|
+
let modelOption = options.find((option) => option.id === "model" || option.category === "model");
|
|
20446
|
+
if (!modelOption || typeof modelOption.id !== "string") {
|
|
20447
|
+
options = await this.loadConfigOptions(true);
|
|
20448
|
+
modelOption = options.find((option) => option.id === "model" || option.category === "model");
|
|
20449
|
+
}
|
|
19110
20450
|
if (!modelOption || typeof modelOption.id !== "string") throw new Error(`Agent ${this.agent.id} does not support runtime model switching`);
|
|
19111
|
-
await this.runtime.setConfigOption?.({ handle: this.handle, key: modelOption.id, value: model });
|
|
20451
|
+
const response = await this.runtime.setConfigOption?.({ handle: this.handle, key: modelOption.id, value: model });
|
|
20452
|
+
if (response && Array.isArray(response.configOptions)) {
|
|
20453
|
+
this.cachedConfigOptions = response.configOptions;
|
|
20454
|
+
} else {
|
|
20455
|
+
this.cachedConfigOptions = void 0;
|
|
20456
|
+
}
|
|
19112
20457
|
this.agent.model = model;
|
|
19113
20458
|
}
|
|
19114
20459
|
async setReasoningEffort(reasoningEffort) {
|
|
19115
20460
|
if (!this.handle) await this.start();
|
|
19116
|
-
|
|
19117
|
-
|
|
19118
|
-
|
|
20461
|
+
let options = await this.loadConfigOptions(false);
|
|
20462
|
+
let reasoning = options.find((option) => option.category === "thought_level" || option.id === "reasoning_effort" || option.id === "effort");
|
|
20463
|
+
let allowed = reasoning && Array.isArray(reasoning.options) ? reasoning.options.some((option) => option?.value === reasoningEffort) : true;
|
|
20464
|
+
if (!reasoning || typeof reasoning.id !== "string" || !allowed) {
|
|
20465
|
+
options = await this.loadConfigOptions(true);
|
|
20466
|
+
reasoning = options.find((option) => option.category === "thought_level" || option.id === "reasoning_effort" || option.id === "effort");
|
|
20467
|
+
allowed = reasoning && Array.isArray(reasoning.options) ? reasoning.options.some((option) => option?.value === reasoningEffort) : true;
|
|
20468
|
+
}
|
|
19119
20469
|
if (!reasoning || typeof reasoning.id !== "string") throw new Error(`Agent ${this.agent.id} does not support runtime reasoning effort switching`);
|
|
19120
|
-
const allowed = Array.isArray(reasoning.options) ? reasoning.options.some((option) => option?.value === reasoningEffort) : true;
|
|
19121
20470
|
if (!allowed) throw new Error(`Reasoning effort ${reasoningEffort} is not supported by model ${this.agent.model ?? "(default)"}`);
|
|
19122
|
-
await this.runtime.setConfigOption?.({ handle: this.handle, key: reasoning.id, value: reasoningEffort });
|
|
20471
|
+
const response = await this.runtime.setConfigOption?.({ handle: this.handle, key: reasoning.id, value: reasoningEffort });
|
|
20472
|
+
if (response && Array.isArray(response.configOptions)) {
|
|
20473
|
+
this.cachedConfigOptions = response.configOptions;
|
|
20474
|
+
}
|
|
19123
20475
|
this.agent.reasoningEffort = reasoningEffort;
|
|
19124
20476
|
}
|
|
19125
20477
|
setRiskPolicy(policy) {
|
|
@@ -19426,6 +20778,11 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
19426
20778
|
factory;
|
|
19427
20779
|
streamCoalescer;
|
|
19428
20780
|
persistChains = /* @__PURE__ */ new Map();
|
|
20781
|
+
// 按会话串行化模型 / 思考深度配置变更,并配合单调版本号实现 last-write-wins,
|
|
20782
|
+
// 防止用户连续快切时慢请求后到把新值覆盖回旧值。
|
|
20783
|
+
configLocks = /* @__PURE__ */ new Map();
|
|
20784
|
+
modelVersions = /* @__PURE__ */ new Map();
|
|
20785
|
+
reasoningVersions = /* @__PURE__ */ new Map();
|
|
19429
20786
|
lastActivity = /* @__PURE__ */ new Map();
|
|
19430
20787
|
cleanupTimer;
|
|
19431
20788
|
cleanupRun;
|
|
@@ -20634,22 +21991,49 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
20634
21991
|
const { session, driver } = await this.active(id);
|
|
20635
21992
|
await this.applyRiskPolicy(session, driver, policy);
|
|
20636
21993
|
}
|
|
21994
|
+
async withConfigLock(id, task) {
|
|
21995
|
+
const previous = this.configLocks.get(id) ?? Promise.resolve();
|
|
21996
|
+
const next = previous.catch(() => void 0).then(task);
|
|
21997
|
+
const tail2 = next.then(() => void 0, () => void 0);
|
|
21998
|
+
this.configLocks.set(id, tail2);
|
|
21999
|
+
try {
|
|
22000
|
+
return await next;
|
|
22001
|
+
} finally {
|
|
22002
|
+
if (this.configLocks.get(id) === tail2) this.configLocks.delete(id);
|
|
22003
|
+
}
|
|
22004
|
+
}
|
|
22005
|
+
getSessionConfigOptions(id) {
|
|
22006
|
+
return this.drivers.get(id)?.getConfigOptions?.();
|
|
22007
|
+
}
|
|
20637
22008
|
async setModel(id, model) {
|
|
20638
22009
|
const normalized2 = model.trim();
|
|
20639
22010
|
if (!normalized2) throw new RuntimeError("INVALID_MODEL", "Model must not be empty", 400);
|
|
20640
|
-
const
|
|
20641
|
-
|
|
20642
|
-
|
|
20643
|
-
|
|
20644
|
-
|
|
20645
|
-
|
|
20646
|
-
|
|
20647
|
-
|
|
20648
|
-
|
|
20649
|
-
|
|
20650
|
-
|
|
20651
|
-
|
|
20652
|
-
|
|
22011
|
+
const version = (this.modelVersions.get(id) ?? 0) + 1;
|
|
22012
|
+
this.modelVersions.set(id, version);
|
|
22013
|
+
return this.withConfigLock(id, async () => {
|
|
22014
|
+
const { session, driver } = await this.active(id);
|
|
22015
|
+
if (this.modelVersions.get(id) !== version) return session;
|
|
22016
|
+
if (session.model === normalized2) return session;
|
|
22017
|
+
if (!driver) {
|
|
22018
|
+
const agent = await this.repos.agents.get(session.agentId);
|
|
22019
|
+
if (!agent) throw new RuntimeError("AGENT_NOT_FOUND", `Unknown agent: ${session.agentId}`, 404);
|
|
22020
|
+
} else {
|
|
22021
|
+
if (!driver.setModel) throw new RuntimeError("MODEL_SWITCH_UNSUPPORTED", `Agent ${session.agentId} does not support runtime model switching`, 422);
|
|
22022
|
+
try {
|
|
22023
|
+
await driver.setModel(normalized2);
|
|
22024
|
+
} catch (error) {
|
|
22025
|
+
if (this.modelVersions.get(id) !== version) return await this.repos.sessions.get(id) ?? session;
|
|
22026
|
+
throw new RuntimeError("MODEL_SWITCH_FAILED", error instanceof Error ? error.message : String(error), 422);
|
|
22027
|
+
}
|
|
22028
|
+
if (this.modelVersions.get(id) !== version) return await this.repos.sessions.get(id) ?? session;
|
|
22029
|
+
}
|
|
22030
|
+
const latest = await this.repos.sessions.get(id) ?? session;
|
|
22031
|
+
latest.model = normalized2;
|
|
22032
|
+
latest.updatedAt = now();
|
|
22033
|
+
await this.repos.sessions.save(latest);
|
|
22034
|
+
await this.emit(id, "status", { state: latest.state, model: normalized2 });
|
|
22035
|
+
return latest;
|
|
22036
|
+
});
|
|
20653
22037
|
}
|
|
20654
22038
|
/**
|
|
20655
22039
|
* Agent 推来的会话名。**不覆盖用户手改的名字**:`customTitle` 一旦存在就锁定,
|
|
@@ -20684,19 +22068,32 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
20684
22068
|
async setReasoningEffort(id, reasoningEffort) {
|
|
20685
22069
|
const normalized2 = reasoningEffort.trim();
|
|
20686
22070
|
if (!normalized2) throw new RuntimeError("INVALID_REASONING_EFFORT", "Reasoning effort must not be empty", 400);
|
|
20687
|
-
const
|
|
20688
|
-
|
|
20689
|
-
|
|
20690
|
-
|
|
20691
|
-
|
|
20692
|
-
|
|
20693
|
-
|
|
20694
|
-
|
|
20695
|
-
|
|
20696
|
-
|
|
20697
|
-
|
|
20698
|
-
|
|
20699
|
-
|
|
22071
|
+
const version = (this.reasoningVersions.get(id) ?? 0) + 1;
|
|
22072
|
+
this.reasoningVersions.set(id, version);
|
|
22073
|
+
return this.withConfigLock(id, async () => {
|
|
22074
|
+
const { session, driver } = await this.active(id);
|
|
22075
|
+
if (this.reasoningVersions.get(id) !== version) return session;
|
|
22076
|
+
if (session.reasoningEffort === normalized2) return session;
|
|
22077
|
+
if (!driver) {
|
|
22078
|
+
const agent = await this.repos.agents.get(session.agentId);
|
|
22079
|
+
if (!agent) throw new RuntimeError("AGENT_NOT_FOUND", `Unknown agent: ${session.agentId}`, 404);
|
|
22080
|
+
} else {
|
|
22081
|
+
if (!driver.setReasoningEffort) throw new RuntimeError("REASONING_SWITCH_UNSUPPORTED", `Agent ${session.agentId} does not support runtime reasoning effort switching`, 422);
|
|
22082
|
+
try {
|
|
22083
|
+
await driver.setReasoningEffort(normalized2);
|
|
22084
|
+
} catch (error) {
|
|
22085
|
+
if (this.reasoningVersions.get(id) !== version) return await this.repos.sessions.get(id) ?? session;
|
|
22086
|
+
throw new RuntimeError("REASONING_SWITCH_FAILED", error instanceof Error ? error.message : String(error), 422);
|
|
22087
|
+
}
|
|
22088
|
+
if (this.reasoningVersions.get(id) !== version) return await this.repos.sessions.get(id) ?? session;
|
|
22089
|
+
}
|
|
22090
|
+
const latest = await this.repos.sessions.get(id) ?? session;
|
|
22091
|
+
latest.reasoningEffort = normalized2;
|
|
22092
|
+
latest.updatedAt = now();
|
|
22093
|
+
await this.repos.sessions.save(latest);
|
|
22094
|
+
await this.emit(id, "status", { state: latest.state, reasoningEffort: normalized2 });
|
|
22095
|
+
return latest;
|
|
22096
|
+
});
|
|
20700
22097
|
}
|
|
20701
22098
|
waitForTurn(id) {
|
|
20702
22099
|
if (!this.activeTurns.has(id)) return Promise.resolve();
|
|
@@ -20829,6 +22226,9 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
20829
22226
|
releaseSessionMemory(sessionId) {
|
|
20830
22227
|
this.streamCoalescer.discard(sessionId);
|
|
20831
22228
|
this.persistChains.delete(sessionId);
|
|
22229
|
+
this.configLocks.delete(sessionId);
|
|
22230
|
+
this.modelVersions.delete(sessionId);
|
|
22231
|
+
this.reasoningVersions.delete(sessionId);
|
|
20832
22232
|
this.drivers.delete(sessionId);
|
|
20833
22233
|
this.sequences.delete(sessionId);
|
|
20834
22234
|
this.lastActivity.delete(sessionId);
|
|
@@ -21321,6 +22721,7 @@ init_message_content();
|
|
|
21321
22721
|
init_access_config();
|
|
21322
22722
|
init_config();
|
|
21323
22723
|
init_listener();
|
|
22724
|
+
init_regex_triggers();
|
|
21324
22725
|
|
|
21325
22726
|
// src/lark/security-hooks.ts
|
|
21326
22727
|
init_service();
|
|
@@ -21928,7 +23329,24 @@ async function registerLarkRoutes(app, options = {}) {
|
|
|
21928
23329
|
}, "AI \u66FF\u8EAB\u5DF2\u542F\u7528\u8868\u60C5\u89E6\u53D1\uFF0C\u4F46\u98DE\u4E66\u673A\u5668\u4EBA reaction \u4E8B\u4EF6\u901A\u9053\u672A\u5C31\u7EEA");
|
|
21929
23330
|
}
|
|
21930
23331
|
}
|
|
21931
|
-
|
|
23332
|
+
const chatCache = new LarkBotChatCache(2e4);
|
|
23333
|
+
const fallbackCoordinators = /* @__PURE__ */ new Map();
|
|
23334
|
+
const clearFallbackCoordinator = (appId) => {
|
|
23335
|
+
if (!appId) {
|
|
23336
|
+
for (const coordinator of fallbackCoordinators.values()) coordinator.stop();
|
|
23337
|
+
fallbackCoordinators.clear();
|
|
23338
|
+
return;
|
|
23339
|
+
}
|
|
23340
|
+
const existing = fallbackCoordinators.get(appId);
|
|
23341
|
+
if (existing) {
|
|
23342
|
+
existing.stop();
|
|
23343
|
+
fallbackCoordinators.delete(appId);
|
|
23344
|
+
}
|
|
23345
|
+
};
|
|
23346
|
+
app.addHook("onClose", async () => {
|
|
23347
|
+
clearFallbackCoordinator();
|
|
23348
|
+
listener.stop();
|
|
23349
|
+
});
|
|
21932
23350
|
const larkErrors = (handler) => async (request, reply) => {
|
|
21933
23351
|
try {
|
|
21934
23352
|
return await handler(request);
|
|
@@ -22181,12 +23599,75 @@ data: ${JSON.stringify(data)}
|
|
|
22181
23599
|
});
|
|
22182
23600
|
app.get("/api/lark/bots/:appId/chats", async (request, reply) => {
|
|
22183
23601
|
try {
|
|
22184
|
-
|
|
23602
|
+
const botService = await resolveService(void 0, request.params.appId);
|
|
23603
|
+
const all = request.query.all === "1" || request.query.all === "true";
|
|
23604
|
+
const refresh = request.query.refresh === "1" || request.query.refresh === "true";
|
|
23605
|
+
return await chatCache.list(request.params.appId, botService, {
|
|
23606
|
+
...request.query.pageToken ? { pageToken: request.query.pageToken } : {},
|
|
23607
|
+
all,
|
|
23608
|
+
refresh
|
|
23609
|
+
});
|
|
22185
23610
|
} catch (error) {
|
|
22186
|
-
if (error instanceof LarkServiceError) return reply.code(error.statusCode).send({ error: { code: error.code, message: error.message } });
|
|
23611
|
+
if (error instanceof LarkServiceError) return reply.code(error.statusCode).send({ error: { code: error.code, message: error.message, ...error.details?.consoleUrl ? { consoleUrl: error.details.consoleUrl } : {} } });
|
|
22187
23612
|
throw error;
|
|
22188
23613
|
}
|
|
22189
23614
|
});
|
|
23615
|
+
registerLarkRegexTriggerRoutes(app, {
|
|
23616
|
+
config: options.config,
|
|
23617
|
+
chatCache,
|
|
23618
|
+
resolveService: (appId) => resolveService(void 0, appId),
|
|
23619
|
+
dispatchBackfillTurn: async (input) => {
|
|
23620
|
+
if (!options.runtime) {
|
|
23621
|
+
throw new LarkServiceError("LARK_RUNTIME_UNAVAILABLE", "Agent runtime \u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u53D1\u8D77\u8F6E\u6B21", 503);
|
|
23622
|
+
}
|
|
23623
|
+
const { botConfig, rule, message, matchedText, triggerType } = input;
|
|
23624
|
+
let coordinator = listener.coordinatorFor?.(botConfig.appId);
|
|
23625
|
+
if (!coordinator) {
|
|
23626
|
+
coordinator = fallbackCoordinators.get(botConfig.appId);
|
|
23627
|
+
if (!coordinator) {
|
|
23628
|
+
const botService = await resolveService(void 0, botConfig.appId);
|
|
23629
|
+
coordinator = new LarkMessageCoordinator(
|
|
23630
|
+
options.runtime,
|
|
23631
|
+
botService,
|
|
23632
|
+
app.log,
|
|
23633
|
+
Math.random,
|
|
23634
|
+
void 0,
|
|
23635
|
+
(chatId, senderOpenId) => options.agentTools?.isConfiguredPeer(botConfig.appId, chatId, senderOpenId) ?? Promise.resolve(false),
|
|
23636
|
+
options.cardMappings,
|
|
23637
|
+
options.config
|
|
23638
|
+
);
|
|
23639
|
+
fallbackCoordinators.set(botConfig.appId, coordinator);
|
|
23640
|
+
}
|
|
23641
|
+
}
|
|
23642
|
+
const event = {
|
|
23643
|
+
messageId: message.messageId,
|
|
23644
|
+
chatId: rule.chatId,
|
|
23645
|
+
chatType: "group",
|
|
23646
|
+
...message.createTime ? { createTime: message.createTime } : message.createdAt ? { createTime: message.createdAt } : {},
|
|
23647
|
+
...message.rootId ? { rootId: message.rootId } : {},
|
|
23648
|
+
...message.parentId ? { parentId: message.parentId } : {},
|
|
23649
|
+
...message.threadId ? { threadId: message.threadId } : {},
|
|
23650
|
+
messageType: message.msgType || "text",
|
|
23651
|
+
content: JSON.stringify({ text: message.text }),
|
|
23652
|
+
...message.senderId ? { senderOpenId: message.senderId } : {},
|
|
23653
|
+
...message.senderType ? { senderType: message.senderType } : {},
|
|
23654
|
+
mentions: []
|
|
23655
|
+
};
|
|
23656
|
+
const result = await coordinator.triggerRegexMatch({
|
|
23657
|
+
event,
|
|
23658
|
+
config: botConfig,
|
|
23659
|
+
rule,
|
|
23660
|
+
matchedText,
|
|
23661
|
+
messageText: message.text,
|
|
23662
|
+
...message.senderName ? { senderName: message.senderName } : {},
|
|
23663
|
+
triggerType
|
|
23664
|
+
});
|
|
23665
|
+
return {
|
|
23666
|
+
...result.sessionId ? { sessionId: result.sessionId } : {},
|
|
23667
|
+
...result.cardMessageId ? { cardMessageId: result.cardMessageId } : {}
|
|
23668
|
+
};
|
|
23669
|
+
}
|
|
23670
|
+
});
|
|
22190
23671
|
app.get("/api/lark/bots/:appId/chats/:chatId/members", async (request, reply) => {
|
|
22191
23672
|
try {
|
|
22192
23673
|
return await (await resolveService(void 0, request.params.appId)).listChatMembers({
|
|
@@ -22265,6 +23746,8 @@ data: ${JSON.stringify(data)}
|
|
|
22265
23746
|
if (!hook.supported || !hook.installed || !hook.writable) throw new LarkServiceError("HARD_GATE_NOT_READY", hook.reason ?? "Install the selected Agent hook before enabling the hard gate", 409);
|
|
22266
23747
|
}
|
|
22267
23748
|
const saved = await saveLarkConfig(options.config, options.agents, listeningDisabled ? { ...input, listening: void 0 } : input);
|
|
23749
|
+
chatCache.invalidate(input.originalAppId || input.appId);
|
|
23750
|
+
clearFallbackCoordinator(input.originalAppId || input.appId);
|
|
22268
23751
|
if (!listeningDisabled) await syncListeners(saved);
|
|
22269
23752
|
if (!options.service) service = void 0;
|
|
22270
23753
|
return publicLarkConfigs(saved, { activeAppIds: listener.activeAppIds, listeningDisabled });
|
|
@@ -22276,6 +23759,8 @@ data: ${JSON.stringify(data)}
|
|
|
22276
23759
|
app.delete("/api/lark/config/:appId", async (request, reply) => {
|
|
22277
23760
|
try {
|
|
22278
23761
|
const saved = await deleteLarkConfig(options.config, request.params.appId);
|
|
23762
|
+
chatCache.invalidate(request.params.appId);
|
|
23763
|
+
clearFallbackCoordinator(request.params.appId);
|
|
22279
23764
|
if (!listeningDisabled) await syncListeners(saved);
|
|
22280
23765
|
if (!options.service) service = void 0;
|
|
22281
23766
|
return publicLarkConfigs(saved, { activeAppIds: listener.activeAppIds, listeningDisabled });
|
|
@@ -23321,34 +24806,89 @@ function agentModelsCacheKey(agent, model) {
|
|
|
23321
24806
|
timeout: agent.timeout
|
|
23322
24807
|
})).digest("hex");
|
|
23323
24808
|
}
|
|
24809
|
+
function modelsFromConfigOptions(configOptions, extraModels) {
|
|
24810
|
+
const modelOption = configOptions.find((option) => option.id === "model" || option.category === "model");
|
|
24811
|
+
const reasoningOption = configOptions.find((option) => option.category === "thought_level" || option.id === "reasoning_effort" || option.id === "effort");
|
|
24812
|
+
const names = /* @__PURE__ */ new Map();
|
|
24813
|
+
for (const option of Array.isArray(modelOption?.options) ? modelOption.options : []) {
|
|
24814
|
+
if (typeof option?.value === "string" && !names.has(option.value)) {
|
|
24815
|
+
names.set(option.value, typeof option.name === "string" ? option.name : option.value);
|
|
24816
|
+
}
|
|
24817
|
+
}
|
|
24818
|
+
const reasoningEfforts = (Array.isArray(reasoningOption?.options) ? reasoningOption.options : []).flatMap((option) => typeof option?.value === "string" ? [{ id: option.value, name: typeof option.name === "string" ? option.name : option.value }] : []);
|
|
24819
|
+
const currentModelId = typeof modelOption?.currentValue === "string" ? modelOption.currentValue : void 0;
|
|
24820
|
+
const ids = [...names.keys()];
|
|
24821
|
+
if (!ids.length && !currentModelId && !reasoningEfforts.length) return void 0;
|
|
24822
|
+
const models = ids.map((id) => ({ id, name: names.get(id) ?? id }));
|
|
24823
|
+
if (extraModels?.length) {
|
|
24824
|
+
const seen = new Set(models.map((item) => item.id));
|
|
24825
|
+
for (const id of extraModels) {
|
|
24826
|
+
if (id && !seen.has(id)) {
|
|
24827
|
+
seen.add(id);
|
|
24828
|
+
models.push({ id, name: id });
|
|
24829
|
+
}
|
|
24830
|
+
}
|
|
24831
|
+
}
|
|
24832
|
+
return {
|
|
24833
|
+
models,
|
|
24834
|
+
...currentModelId ? { defaultModel: currentModelId } : {},
|
|
24835
|
+
reasoningEfforts,
|
|
24836
|
+
...typeof reasoningOption?.currentValue === "string" ? { defaultReasoningEffort: reasoningOption.currentValue } : {},
|
|
24837
|
+
source: "acp"
|
|
24838
|
+
};
|
|
24839
|
+
}
|
|
24840
|
+
function seedAgentModelsCache(agent, model, configOptions) {
|
|
24841
|
+
if (!Array.isArray(configOptions) || !configOptions.length) return void 0;
|
|
24842
|
+
const parsed = modelsFromConfigOptions(configOptions, agent.extraModels);
|
|
24843
|
+
if (!parsed) return void 0;
|
|
24844
|
+
const expiresAt = Date.now() + 5 * 6e4;
|
|
24845
|
+
cache.set(agentModelsCacheKey(agent, model), { expiresAt, value: parsed });
|
|
24846
|
+
if (model) {
|
|
24847
|
+
const baseKey = agentModelsCacheKey(agent, void 0);
|
|
24848
|
+
if (!cache.has(baseKey)) cache.set(baseKey, { expiresAt, value: parsed });
|
|
24849
|
+
}
|
|
24850
|
+
return parsed;
|
|
24851
|
+
}
|
|
23324
24852
|
var cache = /* @__PURE__ */ new Map();
|
|
24853
|
+
var inFlight = /* @__PURE__ */ new Map();
|
|
23325
24854
|
async function discoverAgentModels(agent, model, forceRefresh = false) {
|
|
23326
24855
|
const cacheKey = agentModelsCacheKey(agent, model);
|
|
23327
24856
|
const cached5 = cache.get(cacheKey);
|
|
23328
24857
|
if (!forceRefresh && cached5 && cached5.expiresAt > Date.now()) return cached5.value;
|
|
23329
|
-
|
|
23330
|
-
|
|
23331
|
-
|
|
23332
|
-
|
|
23333
|
-
|
|
23334
|
-
warning
|
|
23335
|
-
}
|
|
23336
|
-
if (!value?.models.length) {
|
|
24858
|
+
const flightKey = forceRefresh ? `${cacheKey}:refresh` : cacheKey;
|
|
24859
|
+
const existing = inFlight.get(flightKey);
|
|
24860
|
+
if (existing) return existing;
|
|
24861
|
+
const pending = (async () => {
|
|
24862
|
+
let value;
|
|
24863
|
+
let warning;
|
|
23337
24864
|
try {
|
|
23338
|
-
|
|
23339
|
-
|
|
23340
|
-
|
|
24865
|
+
value = await discoverThroughAcp(agent, model);
|
|
24866
|
+
} catch (error) {
|
|
24867
|
+
warning = agentModelProbeWarning(error);
|
|
23341
24868
|
}
|
|
24869
|
+
if (!value?.models.length) {
|
|
24870
|
+
try {
|
|
24871
|
+
const models = await discoverThroughCli(agent.id);
|
|
24872
|
+
if (models.length) value = { models, ...agent.model ? { defaultModel: agent.model } : {}, reasoningEfforts: value?.reasoningEfforts ?? [], ...value?.defaultReasoningEffort ? { defaultReasoningEffort: value.defaultReasoningEffort } : {}, source: "cli" };
|
|
24873
|
+
} catch {
|
|
24874
|
+
}
|
|
24875
|
+
}
|
|
24876
|
+
value ??= { models: [], ...agent.model ? { defaultModel: agent.model } : {}, reasoningEfforts: [], source: "agent" };
|
|
24877
|
+
if (agent.extraModels?.length) {
|
|
24878
|
+
const seen = new Set(value.models.map((m) => m.id));
|
|
24879
|
+
const extras = agent.extraModels.filter((id) => id && !seen.has(id)).map((id) => ({ id, name: id }));
|
|
24880
|
+
if (extras.length) value = { ...value, models: [...value.models, ...extras] };
|
|
24881
|
+
}
|
|
24882
|
+
if (warning) value = { ...value, warning };
|
|
24883
|
+
cache.set(cacheKey, { expiresAt: Date.now() + (value.source === "acp" && !warning ? 5 * 6e4 : 15e3), value });
|
|
24884
|
+
return value;
|
|
24885
|
+
})();
|
|
24886
|
+
inFlight.set(flightKey, pending);
|
|
24887
|
+
try {
|
|
24888
|
+
return await pending;
|
|
24889
|
+
} finally {
|
|
24890
|
+
if (inFlight.get(flightKey) === pending) inFlight.delete(flightKey);
|
|
23342
24891
|
}
|
|
23343
|
-
value ??= { models: [], ...agent.model ? { defaultModel: agent.model } : {}, reasoningEfforts: [], source: "agent" };
|
|
23344
|
-
if (agent.extraModels?.length) {
|
|
23345
|
-
const seen = new Set(value.models.map((m) => m.id));
|
|
23346
|
-
const extras = agent.extraModels.filter((id) => id && !seen.has(id)).map((id) => ({ id, name: id }));
|
|
23347
|
-
if (extras.length) value = { ...value, models: [...value.models, ...extras] };
|
|
23348
|
-
}
|
|
23349
|
-
if (warning) value = { ...value, warning };
|
|
23350
|
-
cache.set(cacheKey, { expiresAt: Date.now() + (value.source === "acp" && !warning ? 5 * 6e4 : 15e3), value });
|
|
23351
|
-
return value;
|
|
23352
24892
|
}
|
|
23353
24893
|
|
|
23354
24894
|
// src/ssh/hosts.ts
|
|
@@ -23929,16 +25469,16 @@ function readFromCodex() {
|
|
|
23929
25469
|
});
|
|
23930
25470
|
}
|
|
23931
25471
|
var cached;
|
|
23932
|
-
var
|
|
25472
|
+
var inFlight2;
|
|
23933
25473
|
async function getCodexUsage(refresh = false) {
|
|
23934
25474
|
if (!refresh && cached && Date.now() - cached.checkedAt < 6e4) return cached;
|
|
23935
|
-
if (!
|
|
25475
|
+
if (!inFlight2) inFlight2 = readFromCodex().then((result) => {
|
|
23936
25476
|
cached = result;
|
|
23937
25477
|
return result;
|
|
23938
25478
|
}).finally(() => {
|
|
23939
|
-
|
|
25479
|
+
inFlight2 = void 0;
|
|
23940
25480
|
});
|
|
23941
|
-
return
|
|
25481
|
+
return inFlight2;
|
|
23942
25482
|
}
|
|
23943
25483
|
|
|
23944
25484
|
// src/claude-usage.ts
|
|
@@ -23988,16 +25528,16 @@ async function readClaudeUsage() {
|
|
|
23988
25528
|
return unavailableUsage("\u672A\u627E\u5230 Claude \u989D\u5EA6\u5FEB\u7167\u3002\u767B\u5F55 Claude Code \u5E76\u914D\u7F6E statusline \u540E\u53EF\u67E5\u770B\uFF1B\u5F53\u524D\u672A\u8BFB\u53D6\u5176 OAuth \u51ED\u8BC1\u3002");
|
|
23989
25529
|
}
|
|
23990
25530
|
var cached2;
|
|
23991
|
-
var
|
|
25531
|
+
var inFlight3;
|
|
23992
25532
|
async function getClaudeUsage(refresh = false) {
|
|
23993
25533
|
if (!refresh && cached2 && Date.now() - cached2.checkedAt < 6e4) return cached2;
|
|
23994
|
-
if (!
|
|
25534
|
+
if (!inFlight3) inFlight3 = readClaudeUsage().then((result) => {
|
|
23995
25535
|
cached2 = result;
|
|
23996
25536
|
return result;
|
|
23997
25537
|
}).finally(() => {
|
|
23998
|
-
|
|
25538
|
+
inFlight3 = void 0;
|
|
23999
25539
|
});
|
|
24000
|
-
return
|
|
25540
|
+
return inFlight3;
|
|
24001
25541
|
}
|
|
24002
25542
|
|
|
24003
25543
|
// src/cursor-usage.ts
|
|
@@ -24077,16 +25617,16 @@ async function readCursorUsage() {
|
|
|
24077
25617
|
}
|
|
24078
25618
|
}
|
|
24079
25619
|
var cached3;
|
|
24080
|
-
var
|
|
25620
|
+
var inFlight4;
|
|
24081
25621
|
async function getCursorUsage(refresh = false) {
|
|
24082
25622
|
if (!refresh && cached3 && Date.now() - cached3.checkedAt < 6e4) return cached3;
|
|
24083
|
-
if (!
|
|
25623
|
+
if (!inFlight4) inFlight4 = readCursorUsage().then((result) => {
|
|
24084
25624
|
cached3 = result;
|
|
24085
25625
|
return result;
|
|
24086
25626
|
}).finally(() => {
|
|
24087
|
-
|
|
25627
|
+
inFlight4 = void 0;
|
|
24088
25628
|
});
|
|
24089
|
-
return
|
|
25629
|
+
return inFlight4;
|
|
24090
25630
|
}
|
|
24091
25631
|
|
|
24092
25632
|
// src/antigravity-usage.ts
|
|
@@ -24290,16 +25830,16 @@ async function readAntigravityUsage(runner = spawnAntigravity) {
|
|
|
24290
25830
|
return unavailableUsage("\u627E\u4E0D\u5230 Antigravity CLI\uFF08agy\uFF09\uFF0C\u8BF7\u786E\u8BA4\u5B83\u5DF2\u5B89\u88C5\u5E76\u52A0\u5165 PATH\u3002", SOURCE);
|
|
24291
25831
|
}
|
|
24292
25832
|
var cached4;
|
|
24293
|
-
var
|
|
25833
|
+
var inFlight5;
|
|
24294
25834
|
async function getAntigravityUsage(refresh = false) {
|
|
24295
25835
|
if (!refresh && cached4 && Date.now() - cached4.checkedAt < 6e4) return cached4;
|
|
24296
|
-
if (!
|
|
25836
|
+
if (!inFlight5) inFlight5 = readAntigravityUsage().then((result) => {
|
|
24297
25837
|
cached4 = result;
|
|
24298
25838
|
return result;
|
|
24299
25839
|
}).finally(() => {
|
|
24300
|
-
|
|
25840
|
+
inFlight5 = void 0;
|
|
24301
25841
|
});
|
|
24302
|
-
return
|
|
25842
|
+
return inFlight5;
|
|
24303
25843
|
}
|
|
24304
25844
|
|
|
24305
25845
|
// src/magpie-usage.ts
|
|
@@ -25298,7 +26838,7 @@ function createUsageBackfiller(target, options = {}) {
|
|
|
25298
26838
|
const scannedMtime = /* @__PURE__ */ new Map();
|
|
25299
26839
|
const minIntervalMs = Math.max(0, options.minIntervalMs ?? 6e4);
|
|
25300
26840
|
let lastSyncedAt = 0;
|
|
25301
|
-
let
|
|
26841
|
+
let inFlight6;
|
|
25302
26842
|
async function runOnce() {
|
|
25303
26843
|
const sessions2 = await target.listSessions();
|
|
25304
26844
|
let inserted = 0;
|
|
@@ -25371,13 +26911,13 @@ function createUsageBackfiller(target, options = {}) {
|
|
|
25371
26911
|
async sync(force = false) {
|
|
25372
26912
|
const nowMs = Date.now();
|
|
25373
26913
|
if (!force && lastSyncedAt > 0 && nowMs - lastSyncedAt < minIntervalMs) return 0;
|
|
25374
|
-
if (!
|
|
25375
|
-
|
|
26914
|
+
if (!inFlight6) {
|
|
26915
|
+
inFlight6 = runOnce().finally(() => {
|
|
25376
26916
|
lastSyncedAt = Date.now();
|
|
25377
|
-
|
|
26917
|
+
inFlight6 = void 0;
|
|
25378
26918
|
});
|
|
25379
26919
|
}
|
|
25380
|
-
return
|
|
26920
|
+
return inFlight6;
|
|
25381
26921
|
}
|
|
25382
26922
|
};
|
|
25383
26923
|
}
|
|
@@ -27426,6 +28966,528 @@ var LlmClient = class {
|
|
|
27426
28966
|
}
|
|
27427
28967
|
};
|
|
27428
28968
|
|
|
28969
|
+
// src/llm/assist.ts
|
|
28970
|
+
init_src2();
|
|
28971
|
+
import { z as z8 } from "zod";
|
|
28972
|
+
var llmAssistModes = [
|
|
28973
|
+
"prompt_write",
|
|
28974
|
+
"prompt_optimize",
|
|
28975
|
+
"message_polish",
|
|
28976
|
+
"title_generate",
|
|
28977
|
+
"regex_generate",
|
|
28978
|
+
"description_polish"
|
|
28979
|
+
];
|
|
28980
|
+
var llmAssistActions = [
|
|
28981
|
+
"write",
|
|
28982
|
+
"optimize",
|
|
28983
|
+
"concise",
|
|
28984
|
+
"structure",
|
|
28985
|
+
"generate"
|
|
28986
|
+
];
|
|
28987
|
+
var recentMessageSchema = z8.object({
|
|
28988
|
+
role: z8.string().max(40).optional(),
|
|
28989
|
+
text: z8.string().max(2e3)
|
|
28990
|
+
});
|
|
28991
|
+
var llmAssistContextSchema = z8.object({
|
|
28992
|
+
/** 字段/输入框名称,例如「会话 System Prompt」「定时任务指令」 */
|
|
28993
|
+
field: z8.string().max(120).optional(),
|
|
28994
|
+
/** 输入框用途说明 */
|
|
28995
|
+
purpose: z8.string().max(1e3).optional(),
|
|
28996
|
+
/** 可用模板变量列表,如 ['项目', '验证命令'] */
|
|
28997
|
+
variables: z8.array(z8.string().max(80)).max(40).optional(),
|
|
28998
|
+
/** 工作目录 */
|
|
28999
|
+
cwd: z8.string().max(500).optional(),
|
|
29000
|
+
/** Agent 名称 */
|
|
29001
|
+
agentName: z8.string().max(120).optional(),
|
|
29002
|
+
/** 模型名称 */
|
|
29003
|
+
model: z8.string().max(160).optional(),
|
|
29004
|
+
/** 当前会话/任务标题 */
|
|
29005
|
+
sessionTitle: z8.string().max(200).optional(),
|
|
29006
|
+
/** 会话最近消息摘要(按时间正序) */
|
|
29007
|
+
recentMessages: z8.array(recentMessageSchema).max(20).optional(),
|
|
29008
|
+
/** 飞书机器人或第三方配置上下文 */
|
|
29009
|
+
botContext: z8.string().max(2e3).optional(),
|
|
29010
|
+
/** 群聊名称 */
|
|
29011
|
+
groupName: z8.string().max(200).optional(),
|
|
29012
|
+
/** 正向示例消息(供正则生成参考) */
|
|
29013
|
+
sampleMessages: z8.array(z8.string().max(1e3)).max(20).optional(),
|
|
29014
|
+
/** 反向示例消息(供正则生成防误伤) */
|
|
29015
|
+
negativeSamples: z8.array(z8.string().max(1e3)).max(20).optional(),
|
|
29016
|
+
/** 看板/列/卡片相关上下文 */
|
|
29017
|
+
boardName: z8.string().max(160).optional(),
|
|
29018
|
+
columnName: z8.string().max(160).optional(),
|
|
29019
|
+
cards: z8.array(z8.string().max(300)).max(20).optional(),
|
|
29020
|
+
/** 定时任务触发时间/投递目标摘要 */
|
|
29021
|
+
scheduleSummary: z8.string().max(400).optional(),
|
|
29022
|
+
/** 期望最大字符数提示 */
|
|
29023
|
+
maxChars: z8.number().int().min(4).max(2e4).optional(),
|
|
29024
|
+
/** 补充说明 */
|
|
29025
|
+
extra: z8.string().max(2e3).optional()
|
|
29026
|
+
}).passthrough();
|
|
29027
|
+
var llmAssistInputSchema = z8.object({
|
|
29028
|
+
mode: z8.enum(llmAssistModes),
|
|
29029
|
+
text: z8.string().max(4e4).optional().default(""),
|
|
29030
|
+
instruction: z8.string().max(4e3).optional(),
|
|
29031
|
+
action: z8.enum(llmAssistActions).optional(),
|
|
29032
|
+
context: llmAssistContextSchema.optional(),
|
|
29033
|
+
timeoutMs: z8.number().int().min(1e3).max(12e4).optional()
|
|
29034
|
+
});
|
|
29035
|
+
var STRICT_TEXT_OUTPUT_RULES = [
|
|
29036
|
+
"\u3010\u8F93\u51FA\u7981\u4EE4\uFF08\u5FC5\u987B\u4E25\u683C\u9075\u5B88\uFF09\u3011",
|
|
29037
|
+
"1. \u53EA\u8F93\u51FA\u6700\u7EC8\u53EF\u76F4\u63A5\u56DE\u586B\u5230\u8F93\u5165\u6846\u7684\u5E72\u51C0\u6B63\u6587\u6587\u672C\u3002",
|
|
29038
|
+
"2. \u4E25\u7981\u6DFB\u52A0\u4EFB\u4F55\u5F00\u573A\u767D\u3001\u793C\u8C8C\u8BED\u6216\u7ED3\u8BED\uFF08\u5982\u201C\u597D\u7684\u201D\u201C\u4EE5\u4E0B\u662F\u4E3A\u60A8\u4F18\u5316\u7684\u5185\u5BB9\uFF1A\u201D\u201C\u5E0C\u671B\u5BF9\u4F60\u6709\u5E2E\u52A9\u201D\uFF09\u3002",
|
|
29039
|
+
"3. \u4E25\u7981\u5728\u6574\u6BB5\u8F93\u51FA\u5916\u5C42\u5305\u88F9 Markdown \u4EE3\u7801\u56F4\u680F\uFF08```\uFF09\u6216\u591A\u4F59\u5F15\u53F7\u3002",
|
|
29040
|
+
"4. \u4E25\u7981\u7F16\u9020\u4E0A\u4E0B\u6587\u672A\u63D0\u4F9B\u7684\u6743\u9650\u3001\u5BC6\u94A5\u3001\u63A5\u53E3\u5730\u5740\u3001\u771F\u5B9E\u4EBA\u540D\u6216\u8DEF\u5F84\uFF0C\u4E5F\u4E0D\u8981\u8BD5\u56FE\u8986\u76D6\u7CFB\u7EDF\u5B89\u5168\u8FB9\u754C\u3002"
|
|
29041
|
+
].join("\n");
|
|
29042
|
+
var MAX_DRAFT_CHARS = 6e3;
|
|
29043
|
+
var MAX_SINGLE_MESSAGE_CHARS = 360;
|
|
29044
|
+
function clipAssistDraft(input, limit = MAX_DRAFT_CHARS) {
|
|
29045
|
+
const text3 = input.trim();
|
|
29046
|
+
if (text3.length <= limit) return text3;
|
|
29047
|
+
const head = Math.floor(limit * 0.7);
|
|
29048
|
+
const tail2 = limit - head;
|
|
29049
|
+
return `${text3.slice(0, head)}
|
|
29050
|
+
|
|
29051
|
+
\u2026\uFF08\u4E2D\u95F4\u7701\u7565 ${text3.length - head - tail2} \u5B57\uFF09\u2026
|
|
29052
|
+
|
|
29053
|
+
${text3.slice(-tail2)}`;
|
|
29054
|
+
}
|
|
29055
|
+
function extractMustacheVariables(text3) {
|
|
29056
|
+
const seen = /* @__PURE__ */ new Set();
|
|
29057
|
+
const result = [];
|
|
29058
|
+
for (const match of text3.matchAll(/\{\{\s*([^{}\n]+?)\s*\}\}/g)) {
|
|
29059
|
+
const key = match[1]?.trim();
|
|
29060
|
+
if (!key || seen.has(key)) continue;
|
|
29061
|
+
seen.add(key);
|
|
29062
|
+
result.push(key);
|
|
29063
|
+
}
|
|
29064
|
+
return result;
|
|
29065
|
+
}
|
|
29066
|
+
function formatAssistContext(context, draftText = "") {
|
|
29067
|
+
if (!context) {
|
|
29068
|
+
const inferredVars = extractMustacheVariables(draftText);
|
|
29069
|
+
return inferredVars.length ? `- \u68C0\u6D4B\u5230\u7684\u6A21\u677F\u53D8\u91CF\uFF08\u5FC5\u987B\u539F\u6837\u4FDD\u7559\uFF09\uFF1A${inferredVars.map((v) => `{{${v}}}`).join("\u3001")}` : "";
|
|
29070
|
+
}
|
|
29071
|
+
const lines = [];
|
|
29072
|
+
if (context.field?.trim()) lines.push(`- \u8F93\u5165\u6846 / \u5B57\u6BB5\uFF1A${context.field.trim()}`);
|
|
29073
|
+
if (context.purpose?.trim()) lines.push(`- \u4F7F\u7528\u573A\u666F\uFF1A${context.purpose.trim()}`);
|
|
29074
|
+
if (context.agentName?.trim()) lines.push(`- Agent\uFF1A${context.agentName.trim()}`);
|
|
29075
|
+
if (context.model?.trim()) lines.push(`- \u6A21\u578B\uFF1A${context.model.trim()}`);
|
|
29076
|
+
if (context.cwd?.trim()) lines.push(`- \u5DE5\u4F5C\u76EE\u5F55\uFF1A${context.cwd.trim()}`);
|
|
29077
|
+
if (context.sessionTitle?.trim()) lines.push(`- \u5F53\u524D\u6807\u9898 / \u4E3B\u9898\uFF1A${context.sessionTitle.trim()}`);
|
|
29078
|
+
if (context.scheduleSummary?.trim()) lines.push(`- \u5B9A\u65F6\u89C4\u5219\u4E0E\u76EE\u6807\uFF1A${context.scheduleSummary.trim()}`);
|
|
29079
|
+
if (context.boardName?.trim()) lines.push(`- \u6240\u5C5E\u770B\u677F\uFF1A${context.boardName.trim()}`);
|
|
29080
|
+
if (context.columnName?.trim()) lines.push(`- \u6240\u5C5E\u5217\uFF1A${context.columnName.trim()}`);
|
|
29081
|
+
if (context.groupName?.trim()) lines.push(`- \u98DE\u4E66\u7FA4\u804A\uFF1A${context.groupName.trim()}`);
|
|
29082
|
+
const mergedVars = [.../* @__PURE__ */ new Set([
|
|
29083
|
+
...(context.variables ?? []).map((v) => v.trim()).filter(Boolean),
|
|
29084
|
+
...extractMustacheVariables(draftText)
|
|
29085
|
+
])];
|
|
29086
|
+
if (mergedVars.length) {
|
|
29087
|
+
lines.push(`- \u6A21\u677F\u53D8\u91CF\u5360\u4F4D\u7B26\uFF08\u5FC5\u987B\u539F\u6837\u4FDD\u7559\u82B1\u62EC\u53F7\u4E0E\u53D8\u91CF\u540D\uFF09\uFF1A${mergedVars.map((v) => `{{${v}}}`).join("\u3001")}`);
|
|
29088
|
+
}
|
|
29089
|
+
if (context.cards?.length) {
|
|
29090
|
+
lines.push(`- \u5173\u8054\u5361\u7247\uFF1A
|
|
29091
|
+
${context.cards.slice(0, 12).map((card) => ` * ${card.trim()}`).join("\n")}`);
|
|
29092
|
+
}
|
|
29093
|
+
if (context.botContext?.trim()) {
|
|
29094
|
+
lines.push(`- \u673A\u5668\u4EBA\u914D\u7F6E\u4E0A\u4E0B\u6587\uFF1A
|
|
29095
|
+
${context.botContext.trim().split("\n").map((line) => ` ${line}`).join("\n")}`);
|
|
29096
|
+
}
|
|
29097
|
+
if (context.sampleMessages?.length) {
|
|
29098
|
+
lines.push(`- \u671F\u671B\u547D\u4E2D\u7684\u793A\u4F8B\u6D88\u606F\uFF1A
|
|
29099
|
+
${context.sampleMessages.slice(0, 12).map((msg, i) => ` ${i + 1}. ${msg.trim().slice(0, 300)}`).join("\n")}`);
|
|
29100
|
+
}
|
|
29101
|
+
if (context.negativeSamples?.length) {
|
|
29102
|
+
lines.push(`- \u4E0D\u5E94\u547D\u4E2D\u7684\u53CD\u5411\u793A\u4F8B\uFF1A
|
|
29103
|
+
${context.negativeSamples.slice(0, 12).map((msg, i) => ` ${i + 1}. ${msg.trim().slice(0, 300)}`).join("\n")}`);
|
|
29104
|
+
}
|
|
29105
|
+
if (context.recentMessages?.length) {
|
|
29106
|
+
const rendered = context.recentMessages.filter((item) => item.text.trim()).slice(-12).map((item) => {
|
|
29107
|
+
const role = item.role?.trim() || "\u6D88\u606F";
|
|
29108
|
+
const snippet = item.text.replace(/\s+/g, " ").trim().slice(0, MAX_SINGLE_MESSAGE_CHARS);
|
|
29109
|
+
return ` - [${role}] ${snippet}`;
|
|
29110
|
+
});
|
|
29111
|
+
if (rendered.length) lines.push(`- \u6700\u8FD1\u5BF9\u8BDD\u6458\u8981\uFF1A
|
|
29112
|
+
${rendered.join("\n")}`);
|
|
29113
|
+
}
|
|
29114
|
+
if (context.maxChars) lines.push(`- \u5EFA\u8BAE\u957F\u5EA6\u4E0A\u9650\uFF1A\u4E0D\u8D85\u8FC7 ${context.maxChars} \u5B57`);
|
|
29115
|
+
if (context.extra?.trim()) lines.push(`- \u8865\u5145\u4FE1\u606F\uFF1A${context.extra.trim()}`);
|
|
29116
|
+
const knownKeys = /* @__PURE__ */ new Set([
|
|
29117
|
+
"field",
|
|
29118
|
+
"purpose",
|
|
29119
|
+
"variables",
|
|
29120
|
+
"cwd",
|
|
29121
|
+
"agentName",
|
|
29122
|
+
"model",
|
|
29123
|
+
"sessionTitle",
|
|
29124
|
+
"recentMessages",
|
|
29125
|
+
"botContext",
|
|
29126
|
+
"groupName",
|
|
29127
|
+
"sampleMessages",
|
|
29128
|
+
"negativeSamples",
|
|
29129
|
+
"boardName",
|
|
29130
|
+
"columnName",
|
|
29131
|
+
"cards",
|
|
29132
|
+
"scheduleSummary",
|
|
29133
|
+
"maxChars",
|
|
29134
|
+
"extra"
|
|
29135
|
+
]);
|
|
29136
|
+
for (const [key, value] of Object.entries(context)) {
|
|
29137
|
+
if (knownKeys.has(key) || value === void 0 || value === null || value === "") continue;
|
|
29138
|
+
const text3 = typeof value === "string" ? value.trim() : JSON.stringify(value);
|
|
29139
|
+
if (text3 && text3 !== "{}" && text3 !== "[]") {
|
|
29140
|
+
lines.push(`- ${key}\uFF1A${text3.slice(0, 400)}`);
|
|
29141
|
+
}
|
|
29142
|
+
}
|
|
29143
|
+
return lines.join("\n");
|
|
29144
|
+
}
|
|
29145
|
+
function actionDirective(mode, action) {
|
|
29146
|
+
if (!action) return "";
|
|
29147
|
+
switch (action) {
|
|
29148
|
+
case "concise":
|
|
29149
|
+
return "\u5904\u7406\u504F\u597D\uFF1A\u6781\u7B80\u63D0\u70BC\u2014\u2014\u5728\u4E0D\u4E22\u5931\u6838\u5FC3\u610F\u56FE\u3001\u5173\u952E\u53C2\u6570\u3001\u8DEF\u5F84\u3001\u547D\u4EE4\u4E0E {{\u53D8\u91CF}} \u7684\u524D\u63D0\u4E0B\uFF0C\u5927\u5E45\u538B\u7F29\u5197\u4F59\u8BCD\u53E5\uFF0C\u77ED\u5C0F\u5E72\u7EC3\u3002";
|
|
29150
|
+
case "structure":
|
|
29151
|
+
return mode === "description_polish" ? "\u5904\u7406\u504F\u597D\uFF1A\u7ED3\u6784\u5316\u5206\u70B9\u2014\u2014\u6309\u8981\u70B9\u5206\u6761\u6574\u7406\uFF0C\u91CD\u70B9\u6E05\u6670\u3001\u4FBF\u4E8E\u4E00\u773C\u626B\u8BFB\u3002" : "\u5904\u7406\u504F\u597D\uFF1A\u7ED3\u6784\u5316\u5C55\u5F00\u2014\u2014\u7528\u6E05\u6670\u7684\u5C42\u6B21\u6216\u5206\u70B9\uFF08\u76EE\u6807 / \u7EA6\u675F\u4E0E\u8303\u56F4 / \u6267\u884C\u8981\u70B9 / \u9884\u671F\u8F93\u51FA\uFF09\u91CD\u65B0\u7EC4\u7EC7\uFF0C\u6761\u7406\u5206\u660E\u4E14\u4E0D\u5197\u957F\u3002";
|
|
29152
|
+
case "write":
|
|
29153
|
+
return "\u5904\u7406\u504F\u597D\uFF1A\u6839\u636E\u573A\u666F\u4E0A\u4E0B\u6587\u548C\u7528\u6237\u610F\u56FE\u4ECE\u96F6\u8D77\u8349\u4E00\u4EFD\u5B8C\u6574\u3001\u9AD8\u8D28\u91CF\u3001\u53EF\u76F4\u63A5\u4F7F\u7528\u7684\u7248\u672C\u3002";
|
|
29154
|
+
case "optimize":
|
|
29155
|
+
return "\u5904\u7406\u504F\u597D\uFF1A\u4FDD\u7559\u539F\u6838\u5FC3\u610F\u56FE\u4E0E\u4E8B\u5B9E\u7EC6\u8282\uFF0C\u8BA9\u8868\u8FBE\u66F4\u6E05\u6670\u3001\u7CBE\u51C6\u3001\u65E0\u6B67\u4E49\uFF0C\u53BB\u6389\u53E3\u8BED\u5316\u5570\u55E6\u3002";
|
|
29156
|
+
case "generate":
|
|
29157
|
+
return "\u5904\u7406\u504F\u597D\uFF1A\u76F4\u63A5\u6839\u636E\u63D0\u4F9B\u7684\u4E0A\u4E0B\u6587\u4FE1\u606F\u7CBE\u51C6\u751F\u6210\u6700\u7EC8\u7ED3\u679C\u3002";
|
|
29158
|
+
}
|
|
29159
|
+
}
|
|
29160
|
+
function buildLlmAssistPrompt(input) {
|
|
29161
|
+
const mode = input.mode;
|
|
29162
|
+
const draft = clipAssistDraft(input.text ?? "");
|
|
29163
|
+
const instruction = input.instruction?.trim() ?? "";
|
|
29164
|
+
const contextBlock = formatAssistContext(input.context, draft);
|
|
29165
|
+
const actionNote = actionDirective(mode, input.action);
|
|
29166
|
+
const vars = [.../* @__PURE__ */ new Set([
|
|
29167
|
+
...(input.context?.variables ?? []).map((v) => v.trim()).filter(Boolean),
|
|
29168
|
+
...extractMustacheVariables(draft)
|
|
29169
|
+
])];
|
|
29170
|
+
const varRule = vars.length ? `\u3010\u53D8\u91CF\u4FDD\u62A4\u94C1\u5F8B\u3011\u4E0B\u5217\u6A21\u677F\u5360\u4F4D\u7B26\u5FC5\u987B\u539F\u6837\u4FDD\u7559\uFF08\u7CBE\u786E\u5B57\u7B26\u4E0E\u53CC\u82B1\u62EC\u53F7\u4E0D\u53EF\u6539\u52A8\uFF09\uFF1A${vars.map((v) => `{{${v}}}`).join("\u3001")}\u3002` : "\u82E5\u6587\u672C\u4E2D\u5B58\u5728 {{\u53D8\u91CF\u540D}} \u5360\u4F4D\u7B26\uFF0C\u5FC5\u987B\u539F\u6837\u4FDD\u7559\u5176\u7CBE\u786E\u540D\u79F0\u4E0E\u82B1\u62EC\u53F7\u683C\u5F0F\uFF0C\u4E0D\u5F97\u5220\u9664\u6216\u7FFB\u8BD1\u3002";
|
|
29171
|
+
let systemPrompt;
|
|
29172
|
+
let temperature = 0.35;
|
|
29173
|
+
let maxTokens;
|
|
29174
|
+
switch (mode) {
|
|
29175
|
+
case "prompt_write": {
|
|
29176
|
+
systemPrompt = [
|
|
29177
|
+
"\u4F60\u662F AgentDock \u7684\u8D44\u6DF1 AI Prompt \u5DE5\u7A0B\u5E08\uFF0C\u4E13\u7CBE\u4E3A\u7F16\u7A0B Agent\uFF08Claude Code / Codex \u7B49\uFF09\u3001\u7CFB\u7EDF\u63D0\u793A\u8BCD\uFF08System Prompt\uFF09\u3001\u98DE\u4E66\u673A\u5668\u4EBA\u9884\u6CE8\u5165\u6307\u4EE4\u3001\u63D0\u793A\u8BCD\u6A21\u677F\u53CA\u5B9A\u65F6\u81EA\u52A8\u5316\u4EFB\u52A1\u7F16\u5199\u9AD8\u8D28\u91CF\u3001\u53EF\u76F4\u63A5\u843D\u5730\u7684\u63D0\u793A\u8BCD\u3002",
|
|
29178
|
+
"",
|
|
29179
|
+
"\u3010\u64B0\u5199\u89C4\u8303\u3011",
|
|
29180
|
+
"- \u7D27\u6263\u8F93\u5165\u6846\u7528\u9014\u3001\u6CE8\u5165\u4E0A\u4E0B\u6587\u4E0E\u7528\u6237\u9700\u6C42\uFF1B\u76EE\u6807\u660E\u786E\u3001\u8FB9\u754C\u6E05\u6670\u3001\u5177\u5907\u53EF\u6267\u884C\u6027\u3002",
|
|
29181
|
+
"- \u4F7F\u7528\u7B80\u6D01\u81EA\u7136\u7684\u4E2D\u6587\uFF08\u9664\u975E\u7528\u6237\u660E\u786E\u8981\u6C42\u82F1\u6587\u6216\u539F\u6587\u4E3A\u82F1\u6587\uFF09\uFF0C\u4F18\u5148\u91C7\u7528\u77ED\u6BB5\u843D\u6216\u6E05\u6670\u5206\u70B9\uFF0C\u907F\u514D\u7A7A\u8BDD\u4E0E\u5B98\u50DA\u5957\u8BDD\u3002",
|
|
29182
|
+
`- ${varRule}`,
|
|
29183
|
+
"- \u82E5\u5B57\u6BB5\u4E3A\u98DE\u4E66\u673A\u5668\u4EBA\u9884\u6CE8\u5165 Prompt \u6216\u7CFB\u7EDF\u63D0\u793A\u8BCD\uFF0C\u63A7\u5236\u7BC7\u5E45\u7CBE\u70BC\uFF08\u9ED8\u8BA4 120\u2013260 \u5B57\uFF0C\u9664\u975E\u9700\u6C42\u660E\u786E\u8981\u6C42\u8BE6\u5C3D\u89C4\u8303\uFF09\uFF0C\u65B9\u4FBF Agent \u6BCF\u8F6E\u7A33\u5B9A\u9075\u5FAA\u3002",
|
|
29184
|
+
"- \u82E5\u5B57\u6BB5\u4E3A\u5B9A\u65F6\u4EFB\u52A1\u6307\u4EE4\uFF0C\u786E\u4FDD\u5199\u6210 Agent \u5728\u65E0\u5386\u53F2\u5BF9\u8BDD\u80CC\u666F\u4E0B\u4E5F\u80FD\u72EC\u7ACB\u6267\u884C\u7684\u5B8C\u6574\u4EFB\u52A1\u8BF4\u660E\uFF08\u5305\u542B\u68C0\u67E5\u5BF9\u8C61\u3001\u6267\u884C\u52A8\u4F5C\u4E0E\u6C47\u62A5\u683C\u5F0F\uFF09\u3002",
|
|
29185
|
+
...actionNote ? ["", actionNote] : [],
|
|
29186
|
+
"",
|
|
29187
|
+
STRICT_TEXT_OUTPUT_RULES
|
|
29188
|
+
].join("\n");
|
|
29189
|
+
temperature = 0.4;
|
|
29190
|
+
break;
|
|
29191
|
+
}
|
|
29192
|
+
case "prompt_optimize": {
|
|
29193
|
+
systemPrompt = [
|
|
29194
|
+
"\u4F60\u662F AgentDock \u7684\u8D44\u6DF1 Prompt \u4F18\u5316\u4E13\u5BB6\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u5728\u5FE0\u5B9E\u4FDD\u7559\u7528\u6237\u6838\u5FC3\u610F\u56FE\u4E0E\u5168\u90E8\u6280\u672F\u7EA6\u675F\u7684\u524D\u63D0\u4E0B\uFF0C\u628A\u5DF2\u6709\u8349\u7A3F\u6DA6\u8272\u5F97\u66F4\u6E05\u6670\u3001\u903B\u8F91\u4E25\u5BC6\u3001\u8FB9\u754C\u660E\u786E\u3001\u6613\u4E8E Agent \u4E00\u6B21\u6267\u884C\u5230\u4F4D\u3002",
|
|
29195
|
+
"",
|
|
29196
|
+
"\u3010\u4F18\u5316\u89C4\u8303\u3011",
|
|
29197
|
+
"- \u4FEE\u6B63\u6B67\u4E49\u3001\u6D88\u9664\u91CD\u590D\u548C\u53E3\u8BED\u5316\u62D6\u6C93\uFF0C\u8865\u8DB3\u9690\u542B\u4F46\u4E0D\u6539\u53D8\u539F\u610F\u7684\u6267\u884C\u8854\u63A5\u3002",
|
|
29198
|
+
"- \u4E25\u683C\u4FDD\u7559\u539F\u6587\u4E2D\u7684\u6240\u6709\u6587\u4EF6\u8DEF\u5F84\u3001\u547D\u4EE4\u3001\u4E13\u6709\u540D\u8BCD\u3001\u6570\u5B57\u9608\u503C\u3001\u659C\u6760\u547D\u4EE4\u4E0E\u6761\u4EF6\u5224\u65AD\u3002",
|
|
29199
|
+
`- ${varRule}`,
|
|
29200
|
+
"- \u4FDD\u6301\u4E0E\u539F\u6587\u4E00\u81F4\u7684\u4E3B\u8981\u8BED\u8A00\uFF08\u4E2D\u6587\u8F93\u5165\u8F93\u51FA\u4E2D\u6587\uFF0C\u82F1\u6587\u8F93\u5165\u8F93\u51FA\u82F1\u6587\uFF09\u3002",
|
|
29201
|
+
"- \u4E0D\u8981\u8FC7\u5EA6\u81A8\u80C0\u7BC7\u5E45\uFF0C\u8FFD\u6C42\u9AD8\u4FE1\u606F\u5BC6\u5EA6\u4E0E\u53EF\u8BFB\u6027\u3002",
|
|
29202
|
+
...actionNote ? ["", actionNote] : [],
|
|
29203
|
+
"",
|
|
29204
|
+
STRICT_TEXT_OUTPUT_RULES
|
|
29205
|
+
].join("\n");
|
|
29206
|
+
temperature = 0.3;
|
|
29207
|
+
break;
|
|
29208
|
+
}
|
|
29209
|
+
case "message_polish": {
|
|
29210
|
+
systemPrompt = [
|
|
29211
|
+
"\u4F60\u662F AgentDock \u7684\u667A\u80FD\u8F93\u5165\u6DA6\u8272\u52A9\u624B\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u628A\u7528\u6237\u968F\u624B\u6253\u51FA\u7684\u53E3\u8BED\u5316\u60F3\u6CD5\u3001\u788E\u7247\u9700\u6C42\u6216\u804A\u5929\u6D88\u606F\uFF0C\u6DA6\u8272\u6210\u8868\u8FBE\u6E05\u6670\u3001\u91CD\u70B9\u7A81\u51FA\u3001\u65E0\u6B67\u4E49\u4E14\u81EA\u7136\u5F97\u4F53\u7684\u6D88\u606F\u6587\u672C\u3002",
|
|
29212
|
+
"",
|
|
29213
|
+
"\u3010\u6DA6\u8272\u89C4\u8303\u3011",
|
|
29214
|
+
"- \u51C6\u786E\u4F20\u8FBE\u7528\u6237\u7684\u771F\u5B9E\u610F\u56FE\uFF1A\u6539\u6389\u8BED\u75C5\u3001\u9519\u6F0F\u4E0E\u542B\u7CCA\u6307\u4EE3\uFF0C\u8BA9\u63A5\u6536\u65B9\uFF08AI Agent\u3001\u4E3B\u5C0F\u732B\u6216\u98DE\u4E66\u540C\u4E8B\uFF09\u4E00\u773C\u660E\u767D\u80CC\u666F\u4E0E\u8981\u505A\u4EC0\u4E48\u3002",
|
|
29215
|
+
"- \u4E25\u683C\u4FDD\u7559\u539F\u6709\u659C\u6760\u547D\u4EE4\u524D\u7F00\uFF08\u5982 /plan\u3001/goal\u3001/fast\u3001/btw\uFF09\u3001@\u63D0\u53CA\u3001\u6587\u4EF6\u8DEF\u5F84\u3001\u4EE3\u7801\u7247\u6BB5\u3001\u62A5\u9519\u4FE1\u606F\u3001URL \u4E0E\u6570\u5B57\u7EC6\u8282\u3002",
|
|
29216
|
+
"- \u4FDD\u6301\u514B\u5236\u81EA\u7136\uFF1A\u7B80\u77ED\u95EE\u9898\u6DA6\u8272\u6210\u5E72\u7EC3\u7684\u4E00\u4E24\u53E5\uFF0C\u590D\u6742\u9700\u6C42\u624D\u9002\u5EA6\u5206\u70B9\uFF1B\u7EDD\u4E0D\u8981\u628A\u4E00\u53E5\u65E5\u5E38\u6307\u4EE4\u5199\u6210\u957F\u7BC7\u5927\u8BBA\u6216\u5B98\u6837\u6587\u7AE0\u3002",
|
|
29217
|
+
"- \u82E5\u539F\u6587\u4E3A\u7A7A\u4E14\u7528\u6237\u63D0\u4F9B\u4E86\u7B80\u77ED\u610F\u56FE\uFF0C\u5219\u7ED3\u5408\u5F53\u524D\u4F1A\u8BDD/\u770B\u677F\u4E0A\u4E0B\u6587\u76F4\u63A5\u8D77\u8349\u4E00\u6761\u5373\u53EF\u53D1\u9001\u7684\u9AD8\u8D28\u91CF\u6D88\u606F\u3002",
|
|
29218
|
+
...actionNote ? ["", actionNote] : [],
|
|
29219
|
+
"",
|
|
29220
|
+
STRICT_TEXT_OUTPUT_RULES
|
|
29221
|
+
].join("\n");
|
|
29222
|
+
temperature = 0.35;
|
|
29223
|
+
break;
|
|
29224
|
+
}
|
|
29225
|
+
case "title_generate": {
|
|
29226
|
+
const maxChars = input.context?.maxChars ?? 22;
|
|
29227
|
+
systemPrompt = [
|
|
29228
|
+
"\u4F60\u662F AgentDock \u7684\u7CBE\u51C6\u6807\u9898\u547D\u540D\u52A9\u624B\u3002\u4F60\u7684\u4EFB\u52A1\u662F\u6839\u636E\u4F1A\u8BDD\u5185\u5BB9\u3001\u4EFB\u52A1\u6B63\u6587\u6216\u6A21\u677F\u4E0A\u4E0B\u6587\uFF0C\u63D0\u70BC\u51FA\u4E00\u4E2A\u7B80\u77ED\u3001\u5177\u4F53\u3001\u4E00\u773C\u5373\u53EF\u533A\u5206\u4E3B\u9898\u7684\u4E2D\u6587\u6807\u9898\u3002",
|
|
29229
|
+
"",
|
|
29230
|
+
"\u3010\u547D\u540D\u89C4\u8303\u3011",
|
|
29231
|
+
`- \u4F18\u5148\u4F7F\u7528\u7B80\u660E\u4E2D\u6587\u52A8\u5BBE\u6216\u504F\u6B63\u77ED\u8BED\uFF08API/SQLite/React/Lark/SSH \u7B49\u5E38\u89C1\u6280\u672F\u540D\u8BCD\u53EF\u4FDD\u7559\u82F1\u6587\uFF09\uFF0C\u957F\u5EA6\u63A7\u5236\u5728 6\u2013${Math.min(maxChars, 28)} \u4E2A\u5B57\u7B26\u5185\u3002`,
|
|
29232
|
+
"- \u7D27\u6263\u6838\u5FC3\u5BF9\u8C61\u4E0E\u5177\u4F53\u4E8B\u9879\uFF08\u4F8B\u5982\uFF1A\u300C\u5168\u7AD9\u63A5\u5165 LLM \u8F85\u52A9\u8F93\u5165\u300D\u300C\u6392\u67E5\u98DE\u4E66\u7FA4\u804A\u53BB\u91CD\u5F02\u5E38\u300D\u300C\u6BCF\u65E5\u65E9\u62A5\u5B9A\u65F6\u6C47\u603B\u300D\uFF09\u3002",
|
|
29233
|
+
"- \u7981\u6B62\u6CDB\u6CDB\u65E0\u4FE1\u606F\u91CF\u7684\u6807\u9898\uFF08\u5982\u201C\u95EE\u9898\u54A8\u8BE2\u201D\u201C\u4EE3\u7801\u4FEE\u6539\u201D\u201C\u65B0\u5EFA\u4EFB\u52A1\u201D\u201C\u4F1A\u8BDD\u8BB0\u5F55\u201D\uFF09\u3002",
|
|
29234
|
+
"- \u82E5\u539F\u6807\u9898\u5DF2\u5B58\u5728\u4E14\u7528\u6237\u8981\u6C42\u91CD\u751F\u6210\uFF0C\u5C3D\u91CF\u751F\u6210\u6BD4\u539F\u6807\u9898\u66F4\u8D34\u5207\u3001\u66F4\u805A\u7126\u7684\u8868\u8FBE\u3002",
|
|
29235
|
+
...actionNote ? ["", actionNote] : [],
|
|
29236
|
+
"",
|
|
29237
|
+
"\u3010\u8F93\u51FA\u7981\u4EE4\uFF08\u6781\u4E25\u683C\uFF09\u3011",
|
|
29238
|
+
"1. \u53EA\u8F93\u51FA\u552F\u4E00\u4E00\u884C\u7EAF\u6807\u9898\u6587\u672C\uFF0C\u4E0D\u8981\u6362\u884C\u3002",
|
|
29239
|
+
'2. \u4E25\u7981\u52A0\u5F15\u53F7\uFF08""/\u300C\u300D/\u300A\u300B\uFF09\u3001\u53E5\u53F7\u3001\u5E8F\u53F7\u3001Markdown \u6807\u9898\u7B26\uFF08#\uFF09\u6216\u201C\u6807\u9898\uFF1A\u201D\u524D\u7F00\u3002',
|
|
29240
|
+
"3. \u4E0D\u8981\u8F93\u51FA\u591A\u4E2A\u5019\u9009\uFF0C\u4E5F\u4E0D\u8981\u9644\u5E26\u4EFB\u4F55\u89E3\u91CA\u3002"
|
|
29241
|
+
].join("\n");
|
|
29242
|
+
temperature = 0.3;
|
|
29243
|
+
maxTokens = 96;
|
|
29244
|
+
break;
|
|
29245
|
+
}
|
|
29246
|
+
case "regex_generate": {
|
|
29247
|
+
systemPrompt = [
|
|
29248
|
+
"\u4F60\u662F\u7CBE\u901A ECMAScript\uFF08JavaScript\uFF09\u6B63\u5219\u8868\u8FBE\u5F0F\u4E0E ReDoS \u9632\u62A4\u7684\u4E13\u5BB6\u3002\u8BF7\u6839\u636E\u7528\u6237\u7684\u81EA\u7136\u8BED\u8A00\u5339\u914D\u610F\u56FE\u3001\u6B63/\u53CD\u793A\u4F8B\u6D88\u606F\u53CA\u573A\u666F\u4E0A\u4E0B\u6587\uFF0C\u751F\u6210\u7CBE\u51C6\u3001\u5B89\u5168\u3001\u53EF\u76F4\u63A5\u4F20\u7ED9 JavaScript `new RegExp(pattern, flags)` \u7684\u6B63\u5219\u8868\u8FBE\u5F0F\u3002",
|
|
29249
|
+
"",
|
|
29250
|
+
"\u3010\u6B63\u5219\u5DE5\u7A0B\u89C4\u8303\u3011",
|
|
29251
|
+
"- \u5FC5\u987B\u662F\u6807\u51C6 JavaScript RegExp \u8BED\u6CD5\uFF08\u4E0D\u8981\u4F7F\u7528 PCRE \u4E13\u6709\u8BED\u6CD5\u5982 (?i) \u5185\u8054\u4FEE\u9970\u7B26\u6216\u5360\u6709\u91CF\u8BCD *+\uFF09\u3002",
|
|
29252
|
+
"- \u4E25\u683C\u9632\u8303\u707E\u96BE\u6027\u56DE\u6EAF\uFF08ReDoS\uFF09\uFF1A\u7981\u6B62\u5D4C\u5957\u4E0D\u786E\u5B9A\u91CF\u8BCD\uFF08\u5982 (a+)+\u3001(.*x)+\uFF09\uFF0C\u4F18\u5148\u4F7F\u7528\u660E\u786E\u5B57\u7B26\u7C7B\u3001\u975E\u6355\u83B7\u5206\u7EC4 (?:...) \u4E0E\u8FB9\u754C\u7EA6\u675F\u3002",
|
|
29253
|
+
'- flags \u4EC5\u4ECE\u5408\u6CD5 JS \u6807\u5FD7\uFF08i / m / s / u\uFF09\u4E2D\u6309\u9700\u9009\u62E9\uFF08\u4F8B\u5982\u82F1\u6587\u5173\u952E\u8BCD\u5339\u914D\u901A\u5E38\u7528 "i"\uFF0C\u7EAF\u4E2D\u6587\u53EF\u4E3A\u7A7A\u4E32 ""\uFF09\uFF1B**\u4E0D\u8981\u6DFB\u52A0 g \u6807\u5FD7**\uFF08RegExp.prototype.test \u5E26 g \u5B58\u5728 lastIndex \u590D\u7528\u72B6\u6001\u9677\u9631\uFF09\u3002',
|
|
29254
|
+
"- \u82E5\u63D0\u4F9B\u4E86\u300C\u671F\u671B\u547D\u4E2D\u7684\u793A\u4F8B\u6D88\u606F\u300D\u4E0E\u300C\u4E0D\u5E94\u547D\u4E2D\u7684\u53CD\u5411\u793A\u4F8B\u300D\uFF0C\u52A1\u5FC5\u786E\u4FDD\u6B63\u4F8B\u5168\u90E8\u547D\u4E2D\u3001\u53CD\u4F8B\u5168\u90E8\u4E0D\u8BEF\u547D\u4E2D\u3002",
|
|
29255
|
+
"- \u82E5\u5DF2\u6709\u73B0\u6210\u6B63\u5219\u8349\u7A3F\u4E14\u7528\u6237\u8981\u6C42\u4F18\u5316\uFF0C\u4FDD\u7559\u5176\u6838\u5FC3\u9632\u62A4/\u5339\u914D\u610F\u56FE\u5E76\u4FEE\u8865\u6F0F\u6D1E\u6216\u8BEF\u62A5\u3002",
|
|
29256
|
+
"",
|
|
29257
|
+
"\u3010\u8F93\u51FA\u683C\u5F0F\uFF08\u6781\u4E25\u683C\uFF09\u3011",
|
|
29258
|
+
"\u5FC5\u987B\u4E14\u53EA\u80FD\u8F93\u51FA\u5355\u4E2A\u5408\u6CD5 JSON \u5BF9\u8C61\uFF0C\u4E0D\u8981\u5305\u542B Markdown \u4EE3\u7801\u56F4\u680F\u3001\u4E0D\u8981\u6709\u4EFB\u4F55\u524D\u540E\u89E3\u91CA\u6587\u5B57\uFF1A",
|
|
29259
|
+
'{"pattern":"<\u53EF\u76F4\u63A5\u4F20\u7ED9 new RegExp \u7684\u8F6C\u4E49\u540E\u6B63\u5219\u6E90\u7801>","flags":"<\u4F8B\u5982 i \u6216\u7A7A\u4E32>","explanation":"<20\u201360 \u5B57\u7B80\u6D01\u4E2D\u6587\uFF0C\u8BF4\u660E\u5339\u914D\u89C4\u5219\u4E0E\u8FB9\u754C>"}'
|
|
29260
|
+
].join("\n");
|
|
29261
|
+
temperature = 0.15;
|
|
29262
|
+
maxTokens = 512;
|
|
29263
|
+
break;
|
|
29264
|
+
}
|
|
29265
|
+
case "description_polish": {
|
|
29266
|
+
systemPrompt = [
|
|
29267
|
+
"\u4F60\u662F AgentDock \u7684\u534F\u4F5C\u6587\u6863\u4E0E\u4EA7\u54C1\u6587\u6848\u7F16\u8F91\u52A9\u624B\u3002\u4F60\u8D1F\u8D23\u4E3A\u63D0\u793A\u8BCD\u6A21\u677F\u8BF4\u660E\u3001\u4EFB\u52A1\u770B\u677F\u7B80\u4ECB\u3001\u770B\u677F\u5361\u7247\u5185\u5BB9/\u5907\u6CE8\u3001\u5C0F\u732B\u7763\u529E\u6279\u6CE8\u6216\u98DE\u4E66\u56DE\u590D\u7F72\u540D\u64B0\u5199\u6216\u6DA6\u8272\u7CBE\u70BC\u6E05\u6670\u3001\u76F4\u89C2\u6613\u8BFB\u7684\u6587\u6848\u3002",
|
|
29268
|
+
"",
|
|
29269
|
+
"\u3010\u6587\u6848\u89C4\u8303\u3011",
|
|
29270
|
+
"- \u8D34\u5408\u5B57\u6BB5\u5B9A\u4F4D\u4E0E\u957F\u5EA6\u8981\u6C42\uFF1A\u5355\u884C\u8BF4\u660E/\u7F72\u540D\u4FDD\u6301\u7B80\u77ED\u7CBE\u70BC\uFF08\u901A\u5E38 10\u201345 \u5B57\uFF09\uFF1B\u5361\u7247\u5907\u6CE8/\u8981\u70B9\u53EF\u5206\u70B9\u5217\u51FA\u91CD\u70B9\u4E0E\u9A8C\u6536\u9879\u3002",
|
|
29271
|
+
"- \u4FDD\u7559\u539F\u6587\u4E2D\u7684\u5173\u952E\u4E8B\u5B9E\u3001\u7F16\u53F7\u3001\u4EBA\u540D\u3001\u8DEF\u5F84\u4E0E\u4F18\u5148\u7EA7\u6807\u7B7E\uFF0C\u4E0D\u80E1\u4E71\u7F16\u9020\u672A\u63D0\u53CA\u7684\u8FDB\u5C55\u6216\u7ED3\u8BBA\u3002",
|
|
29272
|
+
"- \u8BED\u6C14\u514B\u5236\u3001\u4E13\u4E1A\u3001\u81EA\u7136\uFF0C\u53BB\u6389\u5570\u55E6\u94FA\u57AB\u3002",
|
|
29273
|
+
...actionNote ? ["", actionNote] : [],
|
|
29274
|
+
"",
|
|
29275
|
+
STRICT_TEXT_OUTPUT_RULES
|
|
29276
|
+
].join("\n");
|
|
29277
|
+
temperature = 0.35;
|
|
29278
|
+
break;
|
|
29279
|
+
}
|
|
29280
|
+
}
|
|
29281
|
+
const sections = [];
|
|
29282
|
+
if (contextBlock) {
|
|
29283
|
+
sections.push(`\u3010\u573A\u666F\u4E0A\u4E0B\u6587\u3011
|
|
29284
|
+
${contextBlock}`);
|
|
29285
|
+
}
|
|
29286
|
+
if (instruction) {
|
|
29287
|
+
sections.push(`\u3010\u7528\u6237\u9700\u6C42 / \u8865\u5145\u6307\u793A\u3011
|
|
29288
|
+
${instruction}`);
|
|
29289
|
+
}
|
|
29290
|
+
if (draft) {
|
|
29291
|
+
sections.push(`\u3010\u5F53\u524D\u8F93\u5165\u6846\u5185\u5BB9\u3011
|
|
29292
|
+
${draft}`);
|
|
29293
|
+
} else {
|
|
29294
|
+
sections.push("\u3010\u5F53\u524D\u8F93\u5165\u6846\u5185\u5BB9\u3011\n\uFF08\u7A7A\uFF09");
|
|
29295
|
+
}
|
|
29296
|
+
sections.push(
|
|
29297
|
+
mode === "regex_generate" ? "\u8BF7\u4E25\u683C\u6309\u7167 JSON \u683C\u5F0F\u8F93\u51FA\u6700\u7EC8\u6B63\u5219\u8868\u8FBE\u5F0F\u7ED3\u679C\u3002" : mode === "title_generate" ? "\u8BF7\u76F4\u63A5\u8F93\u51FA\u552F\u4E00\u4E00\u884C\u6700\u7CBE\u51C6\u7B80\u77ED\u7684\u6807\u9898\u3002" : "\u8BF7\u76F4\u63A5\u8F93\u51FA\u6700\u7EC8\u53EF\u76F4\u63A5\u56DE\u586B\u5230\u8F93\u5165\u6846\u7684\u5E72\u51C0\u6B63\u6587\u3002"
|
|
29298
|
+
);
|
|
29299
|
+
return {
|
|
29300
|
+
systemPrompt,
|
|
29301
|
+
prompt: sections.join("\n\n"),
|
|
29302
|
+
temperature,
|
|
29303
|
+
...maxTokens !== void 0 ? { maxTokens } : {}
|
|
29304
|
+
};
|
|
29305
|
+
}
|
|
29306
|
+
function sanitizePlainAssistText(raw) {
|
|
29307
|
+
let text3 = raw.replace(/\r\n/g, "\n").trim();
|
|
29308
|
+
if (!text3) return "";
|
|
29309
|
+
text3 = text3.replace(/^(?:好的|当然|没问题|明白了|以下是|这是|为您|已为您|优化后|润色后|生成结果)[^\n]{0,36}[::]\s*\n+/, "").trim();
|
|
29310
|
+
const fenced2 = text3.match(/^```[a-zA-Z0-9_-]*[ \t]*\n([\s\S]*?)\n```$/);
|
|
29311
|
+
if (fenced2 && !fenced2[1].includes("\n```")) {
|
|
29312
|
+
text3 = fenced2[1].trim();
|
|
29313
|
+
}
|
|
29314
|
+
return text3.trim();
|
|
29315
|
+
}
|
|
29316
|
+
function sanitizeTitleOutput(raw, maxChars = 60) {
|
|
29317
|
+
const cleaned = sanitizePlainAssistText(raw);
|
|
29318
|
+
const firstLine = cleaned.split("\n").map((line) => line.trim()).find(Boolean) ?? "";
|
|
29319
|
+
let title = firstLine.replace(/^#+\s*/, "").replace(/^(?:[-•*]|\d+[.)\]])\s+/, "").replace(/^(?:标题|会话标题|名称)[::]\s*/, "").trim();
|
|
29320
|
+
title = title.replace(/^\*\*([\s\S]+)\*\*$/, "$1").trim();
|
|
29321
|
+
const pairs = [
|
|
29322
|
+
['"', '"'],
|
|
29323
|
+
["'", "'"],
|
|
29324
|
+
["\u201C", "\u201D"],
|
|
29325
|
+
["\u300C", "\u300D"],
|
|
29326
|
+
["\u300E", "\u300F"],
|
|
29327
|
+
["\u300A", "\u300B"],
|
|
29328
|
+
["\u3010", "\u3011"]
|
|
29329
|
+
];
|
|
29330
|
+
for (const [open, close] of pairs) {
|
|
29331
|
+
if (title.startsWith(open) && title.endsWith(close) && title.length > open.length + close.length) {
|
|
29332
|
+
title = title.slice(open.length, -close.length).trim();
|
|
29333
|
+
}
|
|
29334
|
+
}
|
|
29335
|
+
title = title.replace(/[。!?!?.]+$/, "").replace(/\s+/g, " ").trim();
|
|
29336
|
+
if (title.length > maxChars) title = title.slice(0, maxChars).trim();
|
|
29337
|
+
return title;
|
|
29338
|
+
}
|
|
29339
|
+
var VALID_JS_REGEX_FLAGS = /* @__PURE__ */ new Set(["d", "g", "i", "m", "s", "u", "v", "y"]);
|
|
29340
|
+
function normalizeRegexFlags(raw) {
|
|
29341
|
+
if (!raw) return "";
|
|
29342
|
+
const seen = /* @__PURE__ */ new Set();
|
|
29343
|
+
let result = "";
|
|
29344
|
+
for (const ch of raw) {
|
|
29345
|
+
if (!VALID_JS_REGEX_FLAGS.has(ch) || seen.has(ch)) continue;
|
|
29346
|
+
seen.add(ch);
|
|
29347
|
+
result += ch;
|
|
29348
|
+
}
|
|
29349
|
+
return result;
|
|
29350
|
+
}
|
|
29351
|
+
function hasObviousCatastrophicQuantifier(pattern) {
|
|
29352
|
+
return /\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)[+*{]/.test(pattern);
|
|
29353
|
+
}
|
|
29354
|
+
function parseRegexAssistOutput(raw) {
|
|
29355
|
+
const cleaned = sanitizePlainAssistText(raw);
|
|
29356
|
+
if (!cleaned) {
|
|
29357
|
+
throw new RuntimeError("LLM_EMPTY_REPLY", "\u6A21\u578B\u6CA1\u6709\u8FD4\u56DE\u6709\u6548\u7684\u6B63\u5219\u8868\u8FBE\u5F0F\uFF0C\u8BF7\u91CD\u8BD5\u6216\u8865\u5145\u5339\u914D\u793A\u4F8B\u3002", 502);
|
|
29358
|
+
}
|
|
29359
|
+
let pattern = "";
|
|
29360
|
+
let flags = "";
|
|
29361
|
+
let explanation = "";
|
|
29362
|
+
const tryJson = (candidate) => {
|
|
29363
|
+
try {
|
|
29364
|
+
const parsed2 = JSON.parse(candidate);
|
|
29365
|
+
if (!parsed2 || typeof parsed2 !== "object") return false;
|
|
29366
|
+
if (typeof parsed2.pattern !== "string" || !parsed2.pattern.trim()) return false;
|
|
29367
|
+
pattern = parsed2.pattern.trim();
|
|
29368
|
+
flags = typeof parsed2.flags === "string" ? normalizeRegexFlags(parsed2.flags) : "";
|
|
29369
|
+
explanation = typeof parsed2.explanation === "string" ? parsed2.explanation.trim() : "";
|
|
29370
|
+
return true;
|
|
29371
|
+
} catch {
|
|
29372
|
+
return false;
|
|
29373
|
+
}
|
|
29374
|
+
};
|
|
29375
|
+
let parsed = tryJson(cleaned);
|
|
29376
|
+
if (!parsed) {
|
|
29377
|
+
const start = cleaned.indexOf("{");
|
|
29378
|
+
const end = cleaned.lastIndexOf("}");
|
|
29379
|
+
if (start >= 0 && end > start) {
|
|
29380
|
+
parsed = tryJson(cleaned.slice(start, end + 1));
|
|
29381
|
+
}
|
|
29382
|
+
}
|
|
29383
|
+
if (!parsed) {
|
|
29384
|
+
const firstLine = cleaned.split("\n").map((line) => line.trim()).find(Boolean) ?? "";
|
|
29385
|
+
const literal = firstLine.match(/^\/(.+)\/([a-z]*)$/i);
|
|
29386
|
+
if (literal) {
|
|
29387
|
+
pattern = literal[1].trim();
|
|
29388
|
+
flags = normalizeRegexFlags(literal[2]);
|
|
29389
|
+
} else {
|
|
29390
|
+
pattern = firstLine.replace(/^`+|`+$/g, "").trim();
|
|
29391
|
+
}
|
|
29392
|
+
}
|
|
29393
|
+
if (!flags && pattern.length > 2 && pattern.startsWith("/") && /\/[a-z]*$/i.test(pattern)) {
|
|
29394
|
+
const literal = pattern.match(/^\/(.+)\/([a-z]*)$/i);
|
|
29395
|
+
if (literal) {
|
|
29396
|
+
pattern = literal[1].trim();
|
|
29397
|
+
flags = normalizeRegexFlags(literal[2]);
|
|
29398
|
+
}
|
|
29399
|
+
}
|
|
29400
|
+
if (!pattern) {
|
|
29401
|
+
throw new RuntimeError("LLM_INVALID_REGEX", "\u6A21\u578B\u672A\u751F\u6210\u53EF\u7528\u7684\u6B63\u5219\u8868\u8FBE\u5F0F\u5185\u5BB9\uFF0C\u8BF7\u8865\u5145\u66F4\u660E\u786E\u7684\u5339\u914D\u89C4\u5219\u3002", 422);
|
|
29402
|
+
}
|
|
29403
|
+
if (hasObviousCatastrophicQuantifier(pattern)) {
|
|
29404
|
+
throw new RuntimeError("LLM_UNSAFE_REGEX", `\u751F\u6210\u7684\u6B63\u5219\u5B58\u5728\u56DE\u6EAF\u98CE\u9669\uFF08${pattern}\uFF09\uFF0C\u8BF7\u6362\u4E00\u79CD\u66F4\u5177\u4F53\u7684\u63CF\u8FF0\u91CD\u8BD5\u3002`, 422);
|
|
29405
|
+
}
|
|
29406
|
+
try {
|
|
29407
|
+
new RegExp(pattern, flags);
|
|
29408
|
+
} catch (error) {
|
|
29409
|
+
throw new RuntimeError(
|
|
29410
|
+
"LLM_INVALID_REGEX",
|
|
29411
|
+
`\u6A21\u578B\u751F\u6210\u7684\u6B63\u5219\u8BED\u6CD5\u4E0D\u5408\u6CD5\uFF08${error instanceof Error ? error.message : String(error)}\uFF09\uFF0C\u8BF7\u91CD\u8BD5\u3002`,
|
|
29412
|
+
422
|
|
29413
|
+
);
|
|
29414
|
+
}
|
|
29415
|
+
return {
|
|
29416
|
+
pattern,
|
|
29417
|
+
flags,
|
|
29418
|
+
explanation: explanation || "\u5DF2\u6839\u636E\u63CF\u8FF0\u751F\u6210\u53EF\u76F4\u63A5\u7528\u4E8E JavaScript RegExp \u7684\u5339\u914D\u89C4\u5219\u3002"
|
|
29419
|
+
};
|
|
29420
|
+
}
|
|
29421
|
+
function validateAssistContent(input) {
|
|
29422
|
+
const hasText = Boolean(input.text?.trim());
|
|
29423
|
+
const hasInstruction = Boolean(input.instruction?.trim());
|
|
29424
|
+
const ctx = input.context;
|
|
29425
|
+
const hasContext = Boolean(
|
|
29426
|
+
ctx && (ctx.purpose?.trim() || ctx.botContext?.trim() || ctx.sessionTitle?.trim() || ctx.scheduleSummary?.trim() || ctx.groupName?.trim() || ctx.boardName?.trim() || ctx.columnName?.trim() || ctx.extra?.trim() || ctx.recentMessages?.some((m) => m.text.trim()) || ctx.sampleMessages?.some((s) => s.trim()) || ctx.cards?.some((c) => c.trim()) || ctx.variables?.length)
|
|
29427
|
+
);
|
|
29428
|
+
if (input.mode === "prompt_optimize" && !hasText && !hasInstruction) {
|
|
29429
|
+
throw new RuntimeError("INVALID_ASSIST_INPUT", "\u8BF7\u5148\u8F93\u5165\u8981\u4F18\u5316\u7684 Prompt\uFF0C\u6216\u586B\u5199\u751F\u6210\u9700\u6C42\u3002", 400);
|
|
29430
|
+
}
|
|
29431
|
+
if (input.mode === "regex_generate" && !hasText && !hasInstruction && !ctx?.sampleMessages?.some((s) => s.trim())) {
|
|
29432
|
+
throw new RuntimeError("INVALID_ASSIST_INPUT", "\u8BF7\u63CF\u8FF0\u9700\u8981\u5339\u914D\u7684\u5185\u5BB9\u6216\u63D0\u4F9B\u793A\u4F8B\u6D88\u606F\u3002", 400);
|
|
29433
|
+
}
|
|
29434
|
+
if (!hasText && !hasInstruction && !hasContext) {
|
|
29435
|
+
throw new RuntimeError("INVALID_ASSIST_INPUT", "\u8BF7\u5148\u8F93\u5165\u6587\u672C\u3001\u9700\u6C42\u63CF\u8FF0\u6216\u63D0\u4F9B\u573A\u666F\u4E0A\u4E0B\u6587\u3002", 400);
|
|
29436
|
+
}
|
|
29437
|
+
}
|
|
29438
|
+
async function runLlmAssist(service, rawInput) {
|
|
29439
|
+
const parsed = llmAssistInputSchema.safeParse(rawInput);
|
|
29440
|
+
if (!parsed.success) {
|
|
29441
|
+
const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "body"} ${issue.message}`).join("\uFF1B");
|
|
29442
|
+
throw new RuntimeError("INVALID_ASSIST_INPUT", `AI \u8F85\u52A9\u53C2\u6570\u4E0D\u5408\u6CD5\uFF1A${detail}`, 400);
|
|
29443
|
+
}
|
|
29444
|
+
const input = parsed.data;
|
|
29445
|
+
validateAssistContent(input);
|
|
29446
|
+
const endpoint = await service.endpoint();
|
|
29447
|
+
if (!endpoint) {
|
|
29448
|
+
throw new RuntimeError(
|
|
29449
|
+
"LLM_NOT_CONFIGURED",
|
|
29450
|
+
"\u5C1A\u672A\u914D\u7F6E LLM \u6A21\u578B\u7AEF\u70B9\uFF1A\u8BF7\u524D\u5F80\u300C\u8BBE\u7F6E \u2192 Agent \u8BBE\u7F6E \u2192 \u6A21\u578B\u7AEF\u70B9\u300D\u5B8C\u6210\u914D\u7F6E\u540E\u518D\u4F7F\u7528 AI \u8F85\u52A9\u529F\u80FD\u3002",
|
|
29451
|
+
503
|
|
29452
|
+
);
|
|
29453
|
+
}
|
|
29454
|
+
const built = buildLlmAssistPrompt(input);
|
|
29455
|
+
const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 6e4, 1e3), 12e4);
|
|
29456
|
+
const run2 = await service.run({
|
|
29457
|
+
prompt: built.prompt,
|
|
29458
|
+
systemPrompt: built.systemPrompt,
|
|
29459
|
+
temperature: built.temperature,
|
|
29460
|
+
...built.maxTokens !== void 0 ? { maxTokens: built.maxTokens } : {},
|
|
29461
|
+
timeoutMs
|
|
29462
|
+
});
|
|
29463
|
+
if (input.mode === "regex_generate") {
|
|
29464
|
+
const regex = parseRegexAssistOutput(run2.text);
|
|
29465
|
+
return {
|
|
29466
|
+
mode: input.mode,
|
|
29467
|
+
text: regex.pattern,
|
|
29468
|
+
pattern: regex.pattern,
|
|
29469
|
+
flags: regex.flags,
|
|
29470
|
+
explanation: regex.explanation,
|
|
29471
|
+
model: run2.model,
|
|
29472
|
+
format: run2.format,
|
|
29473
|
+
baseUrl: run2.baseUrl,
|
|
29474
|
+
...run2.truncated ? { truncated: true } : {}
|
|
29475
|
+
};
|
|
29476
|
+
}
|
|
29477
|
+
const text3 = input.mode === "title_generate" ? sanitizeTitleOutput(run2.text, input.context?.maxChars ? Math.max(input.context.maxChars, 32) : 60) : sanitizePlainAssistText(run2.text);
|
|
29478
|
+
if (!text3) {
|
|
29479
|
+
throw new RuntimeError("LLM_EMPTY_REPLY", "\u6A21\u578B\u8FD4\u56DE\u4E86\u7A7A\u5185\u5BB9\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u8C03\u6574\u9700\u6C42\u63CF\u8FF0\u3002", 502);
|
|
29480
|
+
}
|
|
29481
|
+
return {
|
|
29482
|
+
mode: input.mode,
|
|
29483
|
+
text: text3,
|
|
29484
|
+
model: run2.model,
|
|
29485
|
+
format: run2.format,
|
|
29486
|
+
baseUrl: run2.baseUrl,
|
|
29487
|
+
...run2.truncated ? { truncated: true } : {}
|
|
29488
|
+
};
|
|
29489
|
+
}
|
|
29490
|
+
|
|
27429
29491
|
// src/llm/service.ts
|
|
27430
29492
|
var llmEndpointConfigKey = "platform.llm";
|
|
27431
29493
|
var llmAuthOptions = [
|
|
@@ -27500,7 +29562,14 @@ var LlmEndpointService = class {
|
|
|
27500
29562
|
const endpoint = await this.resolve();
|
|
27501
29563
|
const prompt = input.prompt?.trim();
|
|
27502
29564
|
if (!prompt) throw new RuntimeError("INVALID_PROMPT", "Prompt \u4E0D\u80FD\u4E3A\u7A7A", 400);
|
|
27503
|
-
const result = await this.client.complete(endpoint, {
|
|
29565
|
+
const result = await this.client.complete(endpoint, {
|
|
29566
|
+
prompt,
|
|
29567
|
+
...input.systemPrompt !== void 0 ? { systemPrompt: input.systemPrompt } : {},
|
|
29568
|
+
...input.maxTokens !== void 0 ? { maxTokens: input.maxTokens } : {},
|
|
29569
|
+
...input.temperature !== void 0 ? { temperature: input.temperature } : {},
|
|
29570
|
+
timeoutMs: input.timeoutMs,
|
|
29571
|
+
onDelta: input.onDelta
|
|
29572
|
+
});
|
|
27504
29573
|
return {
|
|
27505
29574
|
format: endpoint.format,
|
|
27506
29575
|
model: endpoint.model,
|
|
@@ -27529,6 +29598,7 @@ async function registerLlmRoutes(app, options) {
|
|
|
27529
29598
|
const testPrompt = options?.testPrompt ?? defaultLlmTestPrompt;
|
|
27530
29599
|
const detect = options?.detect ?? detectLlmEndpoints;
|
|
27531
29600
|
app.get("/api/llm", async () => service.state());
|
|
29601
|
+
app.post("/api/llm/assist", async (request) => runLlmAssist(service, request.body));
|
|
27532
29602
|
app.post("/api/llm/complete", async (request) => {
|
|
27533
29603
|
const prompt = request.body?.prompt?.trim();
|
|
27534
29604
|
if (!prompt) throw new RuntimeError("INVALID_PROMPT", "Prompt \u4E0D\u80FD\u4E3A\u7A7A", 400);
|
|
@@ -28411,10 +30481,24 @@ async function buildApp(runtime, options = {}) {
|
|
|
28411
30481
|
app.patch("/api/sessions/:id/title", async (request) => runtime.setSessionTitle(request.params.id, request.body?.title ?? null));
|
|
28412
30482
|
app.patch("/api/sessions/:id/config", async (request) => {
|
|
28413
30483
|
const model = request.body?.model?.trim();
|
|
28414
|
-
if (model) return runtime.setModel(request.params.id, model);
|
|
28415
30484
|
const reasoningEffort = request.body?.reasoningEffort?.trim();
|
|
28416
|
-
if (
|
|
28417
|
-
|
|
30485
|
+
if (!model && !reasoningEffort) {
|
|
30486
|
+
throw new RuntimeError("INVALID_SESSION_CONFIG", "Model or reasoning effort is required", 400);
|
|
30487
|
+
}
|
|
30488
|
+
let updated = model ? await runtime.setModel(request.params.id, model) : void 0;
|
|
30489
|
+
if (reasoningEffort) {
|
|
30490
|
+
updated = await runtime.setReasoningEffort(request.params.id, reasoningEffort);
|
|
30491
|
+
}
|
|
30492
|
+
if (updated && !updated.sshHost) {
|
|
30493
|
+
const configOptions = typeof runtime.getSessionConfigOptions === "function" ? runtime.getSessionConfigOptions(request.params.id) : void 0;
|
|
30494
|
+
if (configOptions?.length && typeof runtime.listAgents === "function") {
|
|
30495
|
+
const agents = await runtime.listAgents(true).catch(() => []);
|
|
30496
|
+
const agent = agents.find((item) => item.id === updated.agentId);
|
|
30497
|
+
const discoveredModels = agent ? seedAgentModelsCache(agent, updated.model, configOptions) : void 0;
|
|
30498
|
+
if (discoveredModels) return { ...updated, discoveredModels };
|
|
30499
|
+
}
|
|
30500
|
+
}
|
|
30501
|
+
return updated;
|
|
28418
30502
|
});
|
|
28419
30503
|
app.delete("/api/sessions/:id/queue/:taskId", async (request) => runtime.cancelQueued(request.params.id, request.params.taskId));
|
|
28420
30504
|
app.patch("/api/sessions/:id/queue/:taskId", async (request) => {
|
|
@@ -28749,7 +30833,7 @@ import { EventEmitter as EventEmitter2 } from "node:events";
|
|
|
28749
30833
|
|
|
28750
30834
|
// src/notifications/config.ts
|
|
28751
30835
|
init_src2();
|
|
28752
|
-
import { z as
|
|
30836
|
+
import { z as z9 } from "zod";
|
|
28753
30837
|
var notificationsConfigKey = "notifications.config";
|
|
28754
30838
|
var notificationRuleEventKinds = ["completed", "failed", "waiting_approval"];
|
|
28755
30839
|
var scheduledNotifyModes = ["all", "failed_only", "off"];
|
|
@@ -28784,55 +30868,55 @@ function isValidHttpUrl(raw) {
|
|
|
28784
30868
|
return false;
|
|
28785
30869
|
}
|
|
28786
30870
|
}
|
|
28787
|
-
var optionalTrimmed = (max = 500) =>
|
|
30871
|
+
var optionalTrimmed = (max = 500) => z9.preprocess(
|
|
28788
30872
|
(value) => {
|
|
28789
30873
|
if (typeof value !== "string") return value;
|
|
28790
30874
|
const trimmed = value.trim();
|
|
28791
30875
|
return trimmed ? trimmed : void 0;
|
|
28792
30876
|
},
|
|
28793
|
-
|
|
30877
|
+
z9.string().max(max).optional()
|
|
28794
30878
|
);
|
|
28795
|
-
var webhookHeaderEntrySchema =
|
|
28796
|
-
key:
|
|
28797
|
-
value:
|
|
30879
|
+
var webhookHeaderEntrySchema = z9.object({
|
|
30880
|
+
key: z9.string().trim().min(1).max(120),
|
|
30881
|
+
value: z9.string().max(2e3)
|
|
28798
30882
|
});
|
|
28799
|
-
var storedWebhookSchema =
|
|
28800
|
-
id:
|
|
28801
|
-
name:
|
|
28802
|
-
enabled:
|
|
28803
|
-
preset:
|
|
28804
|
-
url:
|
|
28805
|
-
headers:
|
|
30883
|
+
var storedWebhookSchema = z9.object({
|
|
30884
|
+
id: z9.string().trim().min(1).max(120),
|
|
30885
|
+
name: z9.string().trim().min(1).max(80),
|
|
30886
|
+
enabled: z9.boolean().default(true),
|
|
30887
|
+
preset: z9.enum(webhookPresets).default("generic"),
|
|
30888
|
+
url: z9.string().trim().min(1).max(2048).refine(isValidHttpUrl, "Webhook \u5730\u5740\u5FC5\u987B\u662F http:// \u6216 https://"),
|
|
30889
|
+
headers: z9.array(webhookHeaderEntrySchema).max(20).default([]),
|
|
28806
30890
|
secret: optionalTrimmed(512),
|
|
28807
|
-
timeoutSec:
|
|
28808
|
-
events:
|
|
30891
|
+
timeoutSec: z9.number().int().min(1).max(30).default(8),
|
|
30892
|
+
events: z9.array(z9.enum(notificationRuleEventKinds)).optional()
|
|
28809
30893
|
});
|
|
28810
|
-
var notificationServerConfigSchema =
|
|
28811
|
-
enabled:
|
|
28812
|
-
events:
|
|
28813
|
-
completed:
|
|
28814
|
-
failed:
|
|
28815
|
-
waitingApproval:
|
|
30894
|
+
var notificationServerConfigSchema = z9.object({
|
|
30895
|
+
enabled: z9.boolean().default(true),
|
|
30896
|
+
events: z9.object({
|
|
30897
|
+
completed: z9.boolean().default(true),
|
|
30898
|
+
failed: z9.boolean().default(true),
|
|
30899
|
+
waitingApproval: z9.boolean().default(true)
|
|
28816
30900
|
}).default({ completed: true, failed: true, waitingApproval: true }),
|
|
28817
|
-
antiSpam:
|
|
28818
|
-
minDurationSec:
|
|
28819
|
-
coalesceWindowMs:
|
|
28820
|
-
remoteOnlyWhenAway:
|
|
28821
|
-
awayAfterSec:
|
|
30901
|
+
antiSpam: z9.object({
|
|
30902
|
+
minDurationSec: z9.number().int().min(0).max(3600).default(10),
|
|
30903
|
+
coalesceWindowMs: z9.number().int().min(0).max(3e4).default(3e3),
|
|
30904
|
+
remoteOnlyWhenAway: z9.boolean().default(false),
|
|
30905
|
+
awayAfterSec: z9.number().int().min(5).max(3600).default(30)
|
|
28822
30906
|
}).default({ minDurationSec: 10, coalesceWindowMs: 3e3, remoteOnlyWhenAway: false, awayAfterSec: 30 }),
|
|
28823
|
-
scopes:
|
|
28824
|
-
normalSessions:
|
|
28825
|
-
assistantSubtasks:
|
|
28826
|
-
scheduledSessions:
|
|
30907
|
+
scopes: z9.object({
|
|
30908
|
+
normalSessions: z9.boolean().default(true),
|
|
30909
|
+
assistantSubtasks: z9.boolean().default(false),
|
|
30910
|
+
scheduledSessions: z9.enum(scheduledNotifyModes).default("failed_only")
|
|
28827
30911
|
}).default({ normalSessions: true, assistantSubtasks: false, scheduledSessions: "failed_only" }),
|
|
28828
|
-
lark:
|
|
28829
|
-
enabled:
|
|
30912
|
+
lark: z9.object({
|
|
30913
|
+
enabled: z9.boolean().default(false),
|
|
28830
30914
|
appId: optionalTrimmed(120),
|
|
28831
|
-
mode:
|
|
30915
|
+
mode: z9.enum(larkNotifyTargetModes).default("auto_handover_then_fallback"),
|
|
28832
30916
|
fallbackReceiveId: optionalTrimmed(160),
|
|
28833
|
-
fallbackReceiveIdType:
|
|
28834
|
-
skipOriginalLarkChat:
|
|
28835
|
-
includeSummary:
|
|
30917
|
+
fallbackReceiveIdType: z9.enum(["open_id", "chat_id"]).default("open_id"),
|
|
30918
|
+
skipOriginalLarkChat: z9.boolean().default(true),
|
|
30919
|
+
includeSummary: z9.boolean().default(true)
|
|
28836
30920
|
}).default({
|
|
28837
30921
|
enabled: false,
|
|
28838
30922
|
mode: "auto_handover_then_fallback",
|
|
@@ -28840,12 +30924,12 @@ var notificationServerConfigSchema = z8.object({
|
|
|
28840
30924
|
skipOriginalLarkChat: true,
|
|
28841
30925
|
includeSummary: true
|
|
28842
30926
|
}),
|
|
28843
|
-
webhooks:
|
|
28844
|
-
commandHook:
|
|
28845
|
-
enabled:
|
|
28846
|
-
command:
|
|
28847
|
-
timeoutSec:
|
|
28848
|
-
trustConfirmed:
|
|
30927
|
+
webhooks: z9.array(storedWebhookSchema).max(20).default([]),
|
|
30928
|
+
commandHook: z9.object({
|
|
30929
|
+
enabled: z9.boolean().default(false),
|
|
30930
|
+
command: z9.preprocess((value) => typeof value === "string" ? value.trim() : "", z9.string().max(1e3)).default(""),
|
|
30931
|
+
timeoutSec: z9.number().int().min(1).max(30).default(10),
|
|
30932
|
+
trustConfirmed: z9.boolean().default(false)
|
|
28849
30933
|
}).default({ enabled: false, command: "", timeoutSec: 10, trustConfirmed: false })
|
|
28850
30934
|
});
|
|
28851
30935
|
var DEFAULT_NOTIFICATION_CONFIG = notificationServerConfigSchema.parse({});
|
|
@@ -34895,7 +36979,7 @@ function resolveSessionVisualState(session) {
|
|
|
34895
36979
|
|
|
34896
36980
|
// src/lark-avatar/service.ts
|
|
34897
36981
|
init_src2();
|
|
34898
|
-
import { createHash as createHash8, randomUUID as
|
|
36982
|
+
import { createHash as createHash8, randomUUID as randomUUID7 } from "node:crypto";
|
|
34899
36983
|
|
|
34900
36984
|
// src/lark-avatar/store.ts
|
|
34901
36985
|
init_src();
|
|
@@ -35949,7 +38033,7 @@ var importCookieString = async (input) => {
|
|
|
35949
38033
|
import WebSocket from "ws";
|
|
35950
38034
|
|
|
35951
38035
|
// src/lark-avatar/protocol/ids.ts
|
|
35952
|
-
import { createHash as createHash7, randomBytes as randomBytes5, randomUUID as
|
|
38036
|
+
import { createHash as createHash7, randomBytes as randomBytes5, randomUUID as randomUUID6 } from "node:crypto";
|
|
35953
38037
|
var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
35954
38038
|
var REQUEST_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
35955
38039
|
var generateAccessKey = (input) => createHash7("md5").update(input, "utf8").digest("hex");
|
|
@@ -35963,7 +38047,7 @@ var randomFrom = (alphabet, length) => {
|
|
|
35963
38047
|
};
|
|
35964
38048
|
var generateRequestId = () => randomFrom(REQUEST_ALPHABET, 10);
|
|
35965
38049
|
var generateRequestCid = () => randomFrom(ALPHABET, 10);
|
|
35966
|
-
var generateLongRequestId = () =>
|
|
38050
|
+
var generateLongRequestId = () => randomUUID6();
|
|
35967
38051
|
|
|
35968
38052
|
// src/lark-avatar/protocol/proto.ts
|
|
35969
38053
|
import { readFileSync as readFileSync9 } from "node:fs";
|
|
@@ -37222,7 +39306,7 @@ var LarkAvatarService = class {
|
|
|
37222
39306
|
workspace: normalizeOptionalText(input.workspace ?? current?.config.workspace)
|
|
37223
39307
|
};
|
|
37224
39308
|
const state = {
|
|
37225
|
-
id: current?.id ?? `avatar_${
|
|
39309
|
+
id: current?.id ?? `avatar_${randomUUID7()}`,
|
|
37226
39310
|
config,
|
|
37227
39311
|
...!regionChanged && current?.account ? { account: current.account } : {},
|
|
37228
39312
|
state: regionChanged ? "disconnected" : current?.state ?? "disconnected",
|
|
@@ -37389,7 +39473,7 @@ var LarkAvatarService = class {
|
|
|
37389
39473
|
workspace: ""
|
|
37390
39474
|
};
|
|
37391
39475
|
this.store.saveState({
|
|
37392
|
-
id: current?.id ?? `avatar_${
|
|
39476
|
+
id: current?.id ?? `avatar_${randomUUID7()}`,
|
|
37393
39477
|
config,
|
|
37394
39478
|
account,
|
|
37395
39479
|
state: "connected",
|
|
@@ -37596,7 +39680,7 @@ var LarkAvatarService = class {
|
|
|
37596
39680
|
const replyTarget = this.replyTargetFor(message, chatType, state.config);
|
|
37597
39681
|
const threadKey = `lark:${message.chatId}${anchor ? `:${message.threadId || anchor}` : ""}`;
|
|
37598
39682
|
const item = {
|
|
37599
|
-
id: `item_${
|
|
39683
|
+
id: `item_${randomUUID7()}`,
|
|
37600
39684
|
threadKey,
|
|
37601
39685
|
messageId: message.messageId,
|
|
37602
39686
|
chatId: message.chatId,
|
|
@@ -38080,7 +40164,7 @@ ${signature}` : body;
|
|
|
38080
40164
|
for (const chunk of splitMessageText(text3)) {
|
|
38081
40165
|
const now2 = this.clock().toISOString();
|
|
38082
40166
|
const draft = {
|
|
38083
|
-
id: `draft_${
|
|
40167
|
+
id: `draft_${randomUUID7()}`,
|
|
38084
40168
|
itemId: input.item.id,
|
|
38085
40169
|
threadKey: input.item.threadKey,
|
|
38086
40170
|
target: input.item.chatId,
|
|
@@ -38089,7 +40173,7 @@ ${signature}` : body;
|
|
|
38089
40173
|
...input.replyTarget?.threadChat ? { replyThreadChat: true } : {},
|
|
38090
40174
|
body: chunk,
|
|
38091
40175
|
state: "pending",
|
|
38092
|
-
idempotencyKey: `agent:${input.item.messageId}:${
|
|
40176
|
+
idempotencyKey: `agent:${input.item.messageId}:${randomUUID7()}`,
|
|
38093
40177
|
attempts: 0,
|
|
38094
40178
|
createdAt: now2,
|
|
38095
40179
|
updatedAt: now2
|
|
@@ -38617,7 +40701,7 @@ ${signature}` : body;
|
|
|
38617
40701
|
const replyTarget = this.replyTargetFromItem(item);
|
|
38618
40702
|
const now2 = this.clock().toISOString();
|
|
38619
40703
|
const draft = existing ? { ...existing, body, state: "pending", lastError: void 0, updatedAt: now2 } : {
|
|
38620
|
-
id: `draft_${
|
|
40704
|
+
id: `draft_${randomUUID7()}`,
|
|
38621
40705
|
itemId: item.id,
|
|
38622
40706
|
threadKey: item.threadKey,
|
|
38623
40707
|
target: item.chatId,
|
|
@@ -38644,7 +40728,7 @@ ${signature}` : body;
|
|
|
38644
40728
|
const replyRootId = input.replyRootId ?? itemTarget.rootId ?? "";
|
|
38645
40729
|
const useItemTarget = input.replyRootId === void 0;
|
|
38646
40730
|
const draft = {
|
|
38647
|
-
id: `draft_${
|
|
40731
|
+
id: `draft_${randomUUID7()}`,
|
|
38648
40732
|
...item ? { itemId: item.id } : {},
|
|
38649
40733
|
...input.threadKey ?? item?.threadKey ? { threadKey: input.threadKey ?? item?.threadKey } : {},
|
|
38650
40734
|
target: input.target.trim(),
|
|
@@ -38653,7 +40737,7 @@ ${signature}` : body;
|
|
|
38653
40737
|
...useItemTarget && itemTarget.threadChat ? { replyThreadChat: true } : {},
|
|
38654
40738
|
body: input.body.trim(),
|
|
38655
40739
|
state: "pending",
|
|
38656
|
-
idempotencyKey: `manual:${
|
|
40740
|
+
idempotencyKey: `manual:${randomUUID7()}`,
|
|
38657
40741
|
attempts: 0,
|
|
38658
40742
|
createdAt: now2,
|
|
38659
40743
|
updatedAt: now2
|