@agent-dock/cli 0.3.15 → 0.3.17
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 +654 -146
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
- package/public/agent-icons/README.md +2 -2
- package/public/agent-icons/antigravity.svg +1 -0
- package/public/assets/{ImageLightbox-CG_aUrA5.js → ImageLightbox-B3SUoIsx.js} +1 -1
- package/public/assets/{PromptEditor-CTuIApSy.js → PromptEditor-runeE0Fs.js} +1 -1
- package/public/assets/index-Qk8aqJbd.css +1 -0
- package/public/assets/main-BO-GkKfl.js +1165 -0
- package/public/assets/{sourcesRouter-0GumH6sq.js → sourcesRouter-DJG5qPtX.js} +1 -1
- package/public/index.html +3 -3
- package/public/sources-router.html +3 -3
- package/public/assets/index-PoNA5i4C.css +0 -1
- package/public/assets/main-Bo2Nr4tl.js +0 -1150
- /package/public/assets/{index-BZYJ7lCZ.js → index-CB32HX8U.js} +0 -0
package/dist/cli.js
CHANGED
|
@@ -738,6 +738,14 @@ function pickFinalAssistantEntry(entries) {
|
|
|
738
738
|
const picked = folded[index];
|
|
739
739
|
return picked.origin ?? picked;
|
|
740
740
|
}
|
|
741
|
+
function isAgentAuthErrorText(text3, pattern) {
|
|
742
|
+
if (!pattern) return false;
|
|
743
|
+
try {
|
|
744
|
+
return new RegExp(pattern, "i").test(text3);
|
|
745
|
+
} catch {
|
|
746
|
+
return false;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
741
749
|
function stripAgentStreamErrorSuffix(text3) {
|
|
742
750
|
return agentStreamErrorSuffix.test(text3) ? text3.replace(agentStreamErrorSuffix, "").trimEnd() : text3;
|
|
743
751
|
}
|
|
@@ -781,7 +789,7 @@ function pickFinalAssistantText(entries) {
|
|
|
781
789
|
const text3 = index >= 0 ? folded[index]?.data?.text : void 0;
|
|
782
790
|
return typeof text3 === "string" ? text3 : "";
|
|
783
791
|
}
|
|
784
|
-
var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText;
|
|
792
|
+
var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText, antigravityAuthErrorPattern;
|
|
785
793
|
var init_turn_outcome = __esm({
|
|
786
794
|
"../../packages/shared/src/turn-outcome.ts"() {
|
|
787
795
|
"use strict";
|
|
@@ -797,6 +805,7 @@ var init_turn_outcome = __esm({
|
|
|
797
805
|
agentStreamErrorPrefix = /^\s*Error:\s*(?:RetriableError|T):/i;
|
|
798
806
|
agentStreamErrorSuffix = /(?:\r?\n){1,2}Error:\s*(?:RetriableError|T):[^\n]*\s*$/i;
|
|
799
807
|
isAgentStreamErrorText = (text3) => agentStreamErrorPrefix.test(text3);
|
|
808
|
+
antigravityAuthErrorPattern = "^\\s*(?:\u26A0\\s*)?UNAUTHENTICATED\\s*\\(code\\s+401\\)";
|
|
800
809
|
}
|
|
801
810
|
});
|
|
802
811
|
|
|
@@ -934,7 +943,11 @@ var init_src2 = __esm({
|
|
|
934
943
|
capabilities: z.object({ pause: z.boolean().default(false), resume: z.boolean().default(true) }).default({ pause: false, resume: true }),
|
|
935
944
|
builtin: z.boolean().default(false),
|
|
936
945
|
// 可选以保持既有 AgentConfig 字面量与行 JSON 兼容;读取方一律按 undefined === false 处理。
|
|
937
|
-
disabled: z.boolean().optional()
|
|
946
|
+
disabled: z.boolean().optional(),
|
|
947
|
+
/** 空闲驱动回收阈值(毫秒);未设置时回落到 runtime 全局默认值,0 表示不按空闲回收。 */
|
|
948
|
+
idleTimeoutMs: z.number().nonnegative().optional(),
|
|
949
|
+
/** 认证失效错误匹配正则;命中时驱逐旧驱动并重连重试一次,仍失败则判 failed。 */
|
|
950
|
+
authErrorPattern: z.string().optional()
|
|
938
951
|
});
|
|
939
952
|
RuntimeError = class extends Error {
|
|
940
953
|
constructor(code, message, statusCode = 400) {
|
|
@@ -1092,7 +1105,7 @@ function sessionTokenAllows(method, pathname, sessionId, search) {
|
|
|
1092
1105
|
if (pathname === `/api/sessions/${sessionId}` || pathname.startsWith(`/api/sessions/${sessionId}/`)) return true;
|
|
1093
1106
|
if (method !== "GET" && method !== "HEAD") return false;
|
|
1094
1107
|
if (pathname === "/api/schedules") return search?.get("sessionId") === sessionId;
|
|
1095
|
-
return pathname === "/api/sessions" || pathname.startsWith("/api/agents") || pathname === "/api/lark/config" || pathname === "/api/system/capabilities" || pathname === "/api/system/skills" || pathname === "/api/system/update" || pathname === "/api/llm";
|
|
1108
|
+
return pathname === "/api/sessions" || pathname.startsWith("/api/agents") || pathname === "/api/lark/config" || pathname === "/api/system/capabilities" || pathname === "/api/system/skills" || pathname === "/api/system/update" || pathname === "/api/llm" || pathname === "/api/side-chat/config";
|
|
1096
1109
|
}
|
|
1097
1110
|
var webAccessSecretConfigKey, webAccessCookieName, webAccessSessionCookieName, defaultSessionTokenTtlMs, defaultMasterTokenTtlMs, activeState;
|
|
1098
1111
|
var init_web_access = __esm({
|
|
@@ -3421,6 +3434,157 @@ var init_handover_binding = __esm({
|
|
|
3421
3434
|
}
|
|
3422
3435
|
});
|
|
3423
3436
|
|
|
3437
|
+
// src/side-chat-config.ts
|
|
3438
|
+
import { z as z4 } from "zod";
|
|
3439
|
+
function normalizeSideChatConfig(input) {
|
|
3440
|
+
const base = {
|
|
3441
|
+
targetMode: input.targetMode,
|
|
3442
|
+
openMode: input.openMode,
|
|
3443
|
+
btwEnabled: input.btwEnabled,
|
|
3444
|
+
triggerPrefix: input.triggerPrefix.trim() || defaultSideChatTriggerPrefix,
|
|
3445
|
+
btwSessionReuse: input.btwSessionReuse
|
|
3446
|
+
};
|
|
3447
|
+
if (input.targetMode === "custom_agent") {
|
|
3448
|
+
return {
|
|
3449
|
+
...base,
|
|
3450
|
+
...input.agentId ? { agentId: input.agentId } : {},
|
|
3451
|
+
...input.model ? { model: input.model } : {},
|
|
3452
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
3453
|
+
};
|
|
3454
|
+
}
|
|
3455
|
+
return base;
|
|
3456
|
+
}
|
|
3457
|
+
function matchSideChatTrigger(input, triggerPrefix = defaultSideChatTriggerPrefix) {
|
|
3458
|
+
const prefix = triggerPrefix.trim() || defaultSideChatTriggerPrefix;
|
|
3459
|
+
const trimmed = input.trim();
|
|
3460
|
+
if (!trimmed) return { matched: false };
|
|
3461
|
+
const needsBoundary = /[A-Za-z0-9_]$/.test(prefix);
|
|
3462
|
+
const pattern = needsBoundary ? new RegExp(`^${escapeRegExp(prefix)}(?:\\s+([\\s\\S]*))?$`, "i") : new RegExp(`^${escapeRegExp(prefix)}\\s*([\\s\\S]*)$`, "i");
|
|
3463
|
+
const match = pattern.exec(trimmed);
|
|
3464
|
+
if (!match) return { matched: false };
|
|
3465
|
+
return { matched: true, prompt: (match[1] ?? "").trim() };
|
|
3466
|
+
}
|
|
3467
|
+
function buildSideSessionSeed(mainSessionId) {
|
|
3468
|
+
return [
|
|
3469
|
+
`\u4F60\u662F\u4E00\u4E2A\u4FA7\u8FB9\u4F1A\u8BDD\uFF1A\u7531\u4E3B\u4F1A\u8BDD ${mainSessionId} \u6D3E\u751F\u7684\u72EC\u7ACB\u4F1A\u8BDD\uFF0C\u5386\u53F2\u548C\u4EFB\u52A1\u961F\u5217\u4E0D\u5171\u4EAB\u3002`,
|
|
3470
|
+
"\u7528\u6237\u901A\u5E38\u4F1A\u95EE\u4E3B\u4F1A\u8BDD\u5728\u505A\u4EC0\u4E48\uFF0C\u6216\u8981\u4F60\u63A5\u7740\u4E3B\u4F1A\u8BDD\u7684\u6D3B\u7EE7\u7EED\u505A\u3002",
|
|
3471
|
+
`\u4E0D\u8981\u5047\u8BBE\u81EA\u5DF1\u5DF2\u7ECF\u77E5\u9053\u4E3B\u4F1A\u8BDD\u7684\u5185\u5BB9\u2014\u2014\u9700\u8981\u65F6\u5148\u7528 \`agent-dock session show ${mainSessionId}\` \u8BFB\u53D6\u8F6C\u5F55\uFF0C\u518D\u56DE\u7B54\uFF1B\u53D1\u6D88\u606F\u3001\u6253\u65AD\u7B49\u7528\u6CD5\u89C1 \`agent-dock session -h\`\u3002`
|
|
3472
|
+
].join("\n");
|
|
3473
|
+
}
|
|
3474
|
+
async function readSideChatConfig(config) {
|
|
3475
|
+
if (!config) return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3476
|
+
const raw = await config.get(sideChatConfigKey);
|
|
3477
|
+
if (!raw?.trim()) return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3478
|
+
try {
|
|
3479
|
+
const parsed = sideChatConfigInputSchema.safeParse(JSON.parse(raw));
|
|
3480
|
+
return parsed.success ? normalizeSideChatConfig(parsed.data) : { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3481
|
+
} catch {
|
|
3482
|
+
return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3483
|
+
}
|
|
3484
|
+
}
|
|
3485
|
+
function registerSideChatConfigRoutes(app, service) {
|
|
3486
|
+
app.get("/api/side-chat/config", async () => service.state());
|
|
3487
|
+
app.put("/api/side-chat/config", async (request) => service.save(request.body));
|
|
3488
|
+
app.delete("/api/side-chat/config", async () => service.reset());
|
|
3489
|
+
}
|
|
3490
|
+
var sideChatConfigKey, sideChatTargetModes, sideChatOpenModes, btwSessionReuseModes, optionalTrimmedString, defaultSideChatTriggerPrefix, triggerPrefixSchema, sideChatConfigInputSchema, DEFAULT_SIDE_CHAT_CONFIG, escapeRegExp, SideChatConfigService;
|
|
3491
|
+
var init_side_chat_config = __esm({
|
|
3492
|
+
"src/side-chat-config.ts"() {
|
|
3493
|
+
"use strict";
|
|
3494
|
+
init_src2();
|
|
3495
|
+
sideChatConfigKey = "side_chat.config";
|
|
3496
|
+
sideChatTargetModes = ["follow_current", "custom_agent"];
|
|
3497
|
+
sideChatOpenModes = ["side_pane", "switch_session"];
|
|
3498
|
+
btwSessionReuseModes = ["new_session", "reuse_latest"];
|
|
3499
|
+
optionalTrimmedString = z4.preprocess(
|
|
3500
|
+
(value) => {
|
|
3501
|
+
if (typeof value !== "string") return value;
|
|
3502
|
+
const trimmed = value.trim();
|
|
3503
|
+
return trimmed ? trimmed : void 0;
|
|
3504
|
+
},
|
|
3505
|
+
z4.string().max(200).optional()
|
|
3506
|
+
);
|
|
3507
|
+
defaultSideChatTriggerPrefix = "/btw";
|
|
3508
|
+
triggerPrefixSchema = z4.preprocess(
|
|
3509
|
+
(value) => {
|
|
3510
|
+
if (value === void 0 || value === null) return defaultSideChatTriggerPrefix;
|
|
3511
|
+
if (typeof value !== "string") return value;
|
|
3512
|
+
const trimmed = value.trim();
|
|
3513
|
+
return trimmed || defaultSideChatTriggerPrefix;
|
|
3514
|
+
},
|
|
3515
|
+
z4.string().min(1).max(32)
|
|
3516
|
+
);
|
|
3517
|
+
sideChatConfigInputSchema = z4.object({
|
|
3518
|
+
targetMode: z4.enum(sideChatTargetModes).default("follow_current"),
|
|
3519
|
+
agentId: optionalTrimmedString,
|
|
3520
|
+
model: optionalTrimmedString,
|
|
3521
|
+
reasoningEffort: optionalTrimmedString,
|
|
3522
|
+
openMode: z4.enum(sideChatOpenModes).default("side_pane"),
|
|
3523
|
+
btwEnabled: z4.boolean().default(true),
|
|
3524
|
+
triggerPrefix: triggerPrefixSchema.default(defaultSideChatTriggerPrefix),
|
|
3525
|
+
btwSessionReuse: z4.enum(btwSessionReuseModes).default("new_session")
|
|
3526
|
+
});
|
|
3527
|
+
DEFAULT_SIDE_CHAT_CONFIG = {
|
|
3528
|
+
targetMode: "follow_current",
|
|
3529
|
+
openMode: "side_pane",
|
|
3530
|
+
btwEnabled: true,
|
|
3531
|
+
triggerPrefix: defaultSideChatTriggerPrefix,
|
|
3532
|
+
btwSessionReuse: "new_session"
|
|
3533
|
+
};
|
|
3534
|
+
escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3535
|
+
SideChatConfigService = class {
|
|
3536
|
+
constructor(options) {
|
|
3537
|
+
this.options = options;
|
|
3538
|
+
}
|
|
3539
|
+
options;
|
|
3540
|
+
/** 读配置;库里没有或损坏时安全回退默认配置,不让前端 500。 */
|
|
3541
|
+
async state() {
|
|
3542
|
+
const raw = await this.options.config.get(sideChatConfigKey);
|
|
3543
|
+
if (!raw?.trim()) return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3544
|
+
try {
|
|
3545
|
+
const parsed = sideChatConfigInputSchema.safeParse(JSON.parse(raw));
|
|
3546
|
+
if (!parsed.success) return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3547
|
+
return { configured: true, config: normalizeSideChatConfig(parsed.data) };
|
|
3548
|
+
} catch {
|
|
3549
|
+
return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3550
|
+
}
|
|
3551
|
+
}
|
|
3552
|
+
async get() {
|
|
3553
|
+
return (await this.state()).config;
|
|
3554
|
+
}
|
|
3555
|
+
async save(input) {
|
|
3556
|
+
const parsed = sideChatConfigInputSchema.safeParse(input);
|
|
3557
|
+
if (!parsed.success) {
|
|
3558
|
+
throw new RuntimeError(
|
|
3559
|
+
"INVALID_SIDE_CHAT_CONFIG",
|
|
3560
|
+
`\u4FA7\u8FB9\u5BF9\u8BDD\u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A${parsed.error.issues.map((issue) => `${issue.path.join(".") || "body"} ${issue.message}`).join("\uFF1B")}`,
|
|
3561
|
+
400
|
|
3562
|
+
);
|
|
3563
|
+
}
|
|
3564
|
+
const normalized2 = normalizeSideChatConfig(parsed.data);
|
|
3565
|
+
if (normalized2.targetMode === "custom_agent") {
|
|
3566
|
+
if (!normalized2.agentId) {
|
|
3567
|
+
throw new RuntimeError("SIDE_CHAT_AGENT_REQUIRED", "\u9009\u62E9\u300C\u6307\u5B9A\u72EC\u7ACB Agent\u300D\u65F6\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A Agent\u3002", 400);
|
|
3568
|
+
}
|
|
3569
|
+
if (this.options.listAgents) {
|
|
3570
|
+
const agents = await this.options.listAgents();
|
|
3571
|
+
const found = agents.find((agent) => agent.id === normalized2.agentId && !agent.disabled);
|
|
3572
|
+
if (!found) {
|
|
3573
|
+
throw new RuntimeError("SIDE_CHAT_AGENT_NOT_FOUND", `\u6307\u5B9A\u7684 Agent \u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528\uFF1A${normalized2.agentId}`, 400);
|
|
3574
|
+
}
|
|
3575
|
+
}
|
|
3576
|
+
}
|
|
3577
|
+
await this.options.config.set(sideChatConfigKey, JSON.stringify(normalized2));
|
|
3578
|
+
return { configured: true, config: normalized2 };
|
|
3579
|
+
}
|
|
3580
|
+
async reset() {
|
|
3581
|
+
await this.options.config.set(sideChatConfigKey, "");
|
|
3582
|
+
return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3583
|
+
}
|
|
3584
|
+
};
|
|
3585
|
+
}
|
|
3586
|
+
});
|
|
3587
|
+
|
|
3424
3588
|
// src/lark/listener.ts
|
|
3425
3589
|
var listener_exports = {};
|
|
3426
3590
|
__export(listener_exports, {
|
|
@@ -3433,6 +3597,7 @@ __export(listener_exports, {
|
|
|
3433
3597
|
isLarkMessageUnupdatable: () => isLarkMessageUnupdatable,
|
|
3434
3598
|
larkHandoverChannel: () => larkHandoverChannel,
|
|
3435
3599
|
larkRateLimitBackoffMs: () => larkRateLimitBackoffMs,
|
|
3600
|
+
larkSideChatThreadChannel: () => larkSideChatThreadChannel,
|
|
3436
3601
|
parseLarkReactionEvent: () => parseLarkReactionEvent,
|
|
3437
3602
|
patchRejectedCardDelta: () => patchRejectedCardDelta,
|
|
3438
3603
|
renderLarkCardElements: () => renderLarkCardElements,
|
|
@@ -3474,12 +3639,16 @@ function renderPromptMentions(text3, mentions, isSelfMention) {
|
|
|
3474
3639
|
return text3;
|
|
3475
3640
|
}
|
|
3476
3641
|
async function parsePrompt(event, selfMention, service, trace) {
|
|
3477
|
-
const { log, appId } = trace ?? {};
|
|
3642
|
+
const { log, appId, stripSideChatTriggerPrefix } = trace ?? {};
|
|
3478
3643
|
const parsed = await parseLarkMessageContent(event.messageType, event.content, {
|
|
3479
3644
|
messageId: event.messageId
|
|
3480
3645
|
});
|
|
3481
3646
|
let text3 = renderPromptMentions(parsed.text, event.mentions, selfMention);
|
|
3482
3647
|
text3 = text3.trim();
|
|
3648
|
+
if (stripSideChatTriggerPrefix) {
|
|
3649
|
+
const matched = matchSideChatTrigger(text3, stripSideChatTriggerPrefix);
|
|
3650
|
+
if (matched.matched) text3 = matched.prompt;
|
|
3651
|
+
}
|
|
3483
3652
|
const quotedResources = [];
|
|
3484
3653
|
const [senderName, parentIdBlock] = await Promise.all([
|
|
3485
3654
|
(async () => {
|
|
@@ -3571,7 +3740,7 @@ async function materializeLarkResources(messageId, prompt, resources, service) {
|
|
|
3571
3740
|
${notes.join("\n")}`.trim();
|
|
3572
3741
|
}
|
|
3573
3742
|
async function sendTaskCard(service, event, input, log) {
|
|
3574
|
-
if (event.chatType === "group" && typeof service.reply === "function") {
|
|
3743
|
+
if ((event.chatType === "group" || input.replyInThread) && typeof service.reply === "function") {
|
|
3575
3744
|
try {
|
|
3576
3745
|
return await service.reply({ ...larkReplyContext(event), ...input });
|
|
3577
3746
|
} catch (error) {
|
|
@@ -3592,11 +3761,11 @@ async function sendPersistedTaskCard(service, persisted, input, log) {
|
|
|
3592
3761
|
}
|
|
3593
3762
|
return await service.send({ chatId: persisted.chat_id, ...input });
|
|
3594
3763
|
}
|
|
3595
|
-
async function sendQuietFinalReply(service, event, text3, log) {
|
|
3764
|
+
async function sendQuietFinalReply(service, event, text3, log, forceReplyInThread) {
|
|
3596
3765
|
const content = text3.trim() || "\uFF08Agent \u672A\u8FD4\u56DE\u6700\u7EC8\u8F93\u51FA\uFF09";
|
|
3597
|
-
if (event.chatType === "group" && typeof service.replyText === "function") {
|
|
3766
|
+
if ((event.chatType === "group" || forceReplyInThread) && typeof service.replyText === "function") {
|
|
3598
3767
|
try {
|
|
3599
|
-
await service.replyText({ messageId: event.messageId, text: content, ...event.threadId?.trim() ? { replyInThread: true } : {} });
|
|
3768
|
+
await service.replyText({ messageId: event.messageId, text: content, ...forceReplyInThread || event.threadId?.trim() ? { replyInThread: true } : {} });
|
|
3600
3769
|
return;
|
|
3601
3770
|
} catch (error) {
|
|
3602
3771
|
log?.warn({ error, messageId: event.messageId, chatId: event.chatId }, "\u9759\u9ED8\u56DE\u590D\u5931\u8D25\uFF0C\u56DE\u9000\u4E3A\u7FA4\u5185\u53D1\u9001");
|
|
@@ -3608,7 +3777,7 @@ async function deliverTaskFailure(service, event, config, input, log) {
|
|
|
3608
3777
|
if (config.quietReply) {
|
|
3609
3778
|
const markdown = typeof input.markdown === "string" ? input.markdown : "";
|
|
3610
3779
|
const text3 = markdown.replace(/<[^>]+>/g, "").replace(/\*\*/g, "").replace(/`/g, "").replace(/\n{3,}/g, "\n\n").trim() || "\uFF08AgentDock \u5904\u7406\u5931\u8D25\uFF09";
|
|
3611
|
-
await sendQuietFinalReply(service, event, text3, log);
|
|
3780
|
+
await sendQuietFinalReply(service, event, text3, log, input.replyInThread);
|
|
3612
3781
|
return { messageId: "" };
|
|
3613
3782
|
}
|
|
3614
3783
|
return await sendTaskCard(service, event, input, log);
|
|
@@ -3724,7 +3893,7 @@ ${data.message ?? "Agent \u6267\u884C\u5931\u8D25"}`;
|
|
|
3724
3893
|
return "";
|
|
3725
3894
|
}).filter(Boolean).join("\n\n---\n\n");
|
|
3726
3895
|
}
|
|
3727
|
-
var acknowledgementEmojis, larkReconnectMaxAttempts, larkReconnectBaseIntervalMs, larkReconnectMaxIntervalMs, larkReconnectMultiplier, larkReconnectCooldownMs, larkCardChannel, terminalTaskStates, maxChatNamePages, chatNamesTimeoutMs, MAX_RECONCILE_ATTEMPTS, persistedCardTask, larkSessionConfigKey, larkGroupScopeId, larkGroupKey, larkReplyContext, larkSourceId, escapeRegExpLiteral, resourceExtensions, safeResourceName, resourceFailureGuidance, isLarkMessageRateLimit, larkRateLimitBackoffMs, isLarkCardContentRejected, isLarkMessageUnupdatable, rejectedDeltaElement, fenced, truncate, truncateInline, traceElapsed, escapeCardInline, firstValue, toolIcon, toolPresentation, hasUnresolvedToolCalls, toolPanel, traceGroups, groupDescription, groupPanel, findFinalMessageEntry, extractFinalText, LarkMessageCoordinator, LarkLongConnectionListener, LarkLongConnectionListenerPool;
|
|
3896
|
+
var acknowledgementEmojis, larkReconnectMaxAttempts, larkReconnectBaseIntervalMs, larkReconnectMaxIntervalMs, larkReconnectMultiplier, larkReconnectCooldownMs, larkCardChannel, larkSideChatThreadChannel, terminalTaskStates, maxChatNamePages, chatNamesTimeoutMs, MAX_RECONCILE_ATTEMPTS, persistedCardTask, larkSessionConfigKey, larkGroupScopeId, larkGroupKey, larkReplyContext, larkSourceId, escapeRegExpLiteral, resourceExtensions, safeResourceName, resourceFailureGuidance, isLarkMessageRateLimit, larkRateLimitBackoffMs, isLarkCardContentRejected, isLarkMessageUnupdatable, rejectedDeltaElement, fenced, truncate, truncateInline, traceElapsed, escapeCardInline, firstValue, toolIcon, toolPresentation, hasUnresolvedToolCalls, toolPanel, traceGroups, groupDescription, groupPanel, findFinalMessageEntry, extractFinalText, LarkMessageCoordinator, LarkLongConnectionListener, LarkLongConnectionListenerPool;
|
|
3728
3897
|
var init_listener = __esm({
|
|
3729
3898
|
"src/lark/listener.ts"() {
|
|
3730
3899
|
"use strict";
|
|
@@ -3735,6 +3904,7 @@ var init_listener = __esm({
|
|
|
3735
3904
|
init_service();
|
|
3736
3905
|
init_agent_tools();
|
|
3737
3906
|
init_handover_binding();
|
|
3907
|
+
init_side_chat_config();
|
|
3738
3908
|
init_src2();
|
|
3739
3909
|
init_handover_binding();
|
|
3740
3910
|
acknowledgementEmojis = ["OK", "THUMBSUP", "FINGERHEART", "APPLAUSE", "JIAYI"];
|
|
@@ -3744,6 +3914,7 @@ var init_listener = __esm({
|
|
|
3744
3914
|
larkReconnectMultiplier = 2;
|
|
3745
3915
|
larkReconnectCooldownMs = 6e4;
|
|
3746
3916
|
larkCardChannel = (appId) => `lark-card:${appId}`;
|
|
3917
|
+
larkSideChatThreadChannel = (appId) => `lark-side-chat:${appId}`;
|
|
3747
3918
|
terminalTaskStates = /* @__PURE__ */ new Set(["completed", "failed", "interrupted", "cancelled"]);
|
|
3748
3919
|
maxChatNamePages = 5;
|
|
3749
3920
|
chatNamesTimeoutMs = 2e3;
|
|
@@ -4100,6 +4271,8 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4100
4271
|
groups = /* @__PURE__ */ new Map();
|
|
4101
4272
|
tasks = /* @__PURE__ */ new Map();
|
|
4102
4273
|
handledMessages = /* @__PURE__ */ new Set();
|
|
4274
|
+
/** 飞书侧聊话题映射(`${appId}:${rootId|threadId}` -> sideChatSessionId),与 cardMappings 双写。 */
|
|
4275
|
+
sideChatThreads = /* @__PURE__ */ new Map();
|
|
4103
4276
|
reconcileTimer;
|
|
4104
4277
|
reconcileRun;
|
|
4105
4278
|
reconcileConfig;
|
|
@@ -4278,9 +4451,9 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4278
4451
|
prompt: task.prompt,
|
|
4279
4452
|
state,
|
|
4280
4453
|
...task.lastSuccessfulElements?.length ? { last_successful_elements: task.lastSuccessfulElements } : {},
|
|
4281
|
-
...task.event.chatType === "group" ? {
|
|
4454
|
+
...task.event.chatType === "group" || task.forceReplyInThread ? {
|
|
4282
4455
|
reply_message_id: task.event.messageId,
|
|
4283
|
-
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
4456
|
+
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.forceReplyInThread || task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
4284
4457
|
} : {},
|
|
4285
4458
|
started_at: task.startedAt
|
|
4286
4459
|
};
|
|
@@ -4479,18 +4652,148 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4479
4652
|
isSelfMention(config, mention) {
|
|
4480
4653
|
return this.botOpenId !== void 0 && mention.openId === this.botOpenId || mention.appId !== void 0 && mention.appId === config.appId || this.botOpenId === void 0 && mention.mentionedType === "bot";
|
|
4481
4654
|
}
|
|
4655
|
+
async lookupSideChatThread(appId, event) {
|
|
4656
|
+
const keys = [event.rootId?.trim(), event.threadId?.trim()].filter((value) => Boolean(value));
|
|
4657
|
+
for (const key of keys) {
|
|
4658
|
+
const mem = this.sideChatThreads.get(`${appId}:${key}`);
|
|
4659
|
+
if (mem) return { key, sessionId: mem };
|
|
4660
|
+
if (this.cardMappings) {
|
|
4661
|
+
try {
|
|
4662
|
+
const mapping = await this.cardMappings.get(larkSideChatThreadChannel(appId), key);
|
|
4663
|
+
if (mapping?.sessionId) {
|
|
4664
|
+
this.sideChatThreads.set(`${appId}:${key}`, mapping.sessionId);
|
|
4665
|
+
return { key, sessionId: mapping.sessionId };
|
|
4666
|
+
}
|
|
4667
|
+
} catch (error) {
|
|
4668
|
+
this.log.warn({ error, appId, key }, "\u8BFB\u53D6\u98DE\u4E66\u4FA7\u804A\u8BDD\u9898\u7ED1\u5B9A\u5931\u8D25");
|
|
4669
|
+
}
|
|
4670
|
+
}
|
|
4671
|
+
}
|
|
4672
|
+
return void 0;
|
|
4673
|
+
}
|
|
4674
|
+
async saveSideChatThread(appId, keys, sessionId) {
|
|
4675
|
+
const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter(Boolean))];
|
|
4676
|
+
for (const key of uniqueKeys) {
|
|
4677
|
+
this.sideChatThreads.set(`${appId}:${key}`, sessionId);
|
|
4678
|
+
if (this.sideChatThreads.size > 5e3) this.sideChatThreads.delete(this.sideChatThreads.keys().next().value);
|
|
4679
|
+
if (this.cardMappings) {
|
|
4680
|
+
try {
|
|
4681
|
+
await this.cardMappings.save({
|
|
4682
|
+
id: `${larkSideChatThreadChannel(appId)}:${key}`,
|
|
4683
|
+
channel: larkSideChatThreadChannel(appId),
|
|
4684
|
+
externalId: key,
|
|
4685
|
+
sessionId,
|
|
4686
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4687
|
+
});
|
|
4688
|
+
} catch (error) {
|
|
4689
|
+
this.log.warn({ error, appId, key, sessionId }, "\u6301\u4E45\u5316\u98DE\u4E66\u4FA7\u804A\u8BDD\u9898\u7ED1\u5B9A\u5931\u8D25");
|
|
4690
|
+
}
|
|
4691
|
+
}
|
|
4692
|
+
}
|
|
4693
|
+
}
|
|
4694
|
+
/** 查找当前聊天对应的主会话(用于侧边会话关联父会话上下文,不新建主会话)。 */
|
|
4695
|
+
async findParentSessionForSideChat(config, event, parentGroupKey, parentSourceId) {
|
|
4696
|
+
const parentGroup = this.groups.get(parentGroupKey);
|
|
4697
|
+
let candidateId = parentGroup?.boundSessionId ?? parentGroup?.sessionId;
|
|
4698
|
+
if (!candidateId && this.cardMappings) {
|
|
4699
|
+
try {
|
|
4700
|
+
const handover = await this.cardMappings.get(larkHandoverChannel(config.appId), event.chatId);
|
|
4701
|
+
if (handover?.sessionId) candidateId = handover.sessionId;
|
|
4702
|
+
} catch {
|
|
4703
|
+
}
|
|
4704
|
+
}
|
|
4705
|
+
if (candidateId) {
|
|
4706
|
+
const existing = await this.runtime.getSession(candidateId);
|
|
4707
|
+
if (existing && !existing.archivedAt) return existing;
|
|
4708
|
+
}
|
|
4709
|
+
if (this.runtime.listSessions) {
|
|
4710
|
+
const sessions2 = await this.runtime.listSessions();
|
|
4711
|
+
const matched = [...sessions2].reverse().find((item) => item.source === "lark" && item.sourceId === parentSourceId && !item.archivedAt);
|
|
4712
|
+
if (matched) return matched;
|
|
4713
|
+
}
|
|
4714
|
+
return void 0;
|
|
4715
|
+
}
|
|
4716
|
+
/**
|
|
4717
|
+
* 按 SideChatConfig 创建飞书侧边会话并绑定话题。
|
|
4718
|
+
* 复用与网页端完全一致的「侧边会话」模型(source: 'side-chat' + buildSideSessionSeed)。
|
|
4719
|
+
*/
|
|
4720
|
+
async sideChatSessionFor(task) {
|
|
4721
|
+
const { group, event, config, sideChat } = task;
|
|
4722
|
+
if (!sideChat) throw new Error("Missing sideChat context");
|
|
4723
|
+
if (group.boundSessionId) {
|
|
4724
|
+
const existing = await this.runtime.getSession(group.boundSessionId);
|
|
4725
|
+
if (existing && !existing.archivedAt && !["failed", "stopped"].includes(existing.state)) return existing;
|
|
4726
|
+
}
|
|
4727
|
+
const parentSession = await this.findParentSessionForSideChat(config, event, sideChat.parentGroupKey, sideChat.parentSourceId);
|
|
4728
|
+
const sideConfig = sideChat.config;
|
|
4729
|
+
let agentId;
|
|
4730
|
+
let model;
|
|
4731
|
+
let reasoningEffort;
|
|
4732
|
+
if (sideConfig.targetMode === "custom_agent" && sideConfig.agentId?.trim()) {
|
|
4733
|
+
const targetId = sideConfig.agentId.trim();
|
|
4734
|
+
const availableAgents = this.runtime.listAgents ? await this.runtime.listAgents() : void 0;
|
|
4735
|
+
const available = !availableAgents || availableAgents.some((agent) => agent.id === targetId && !agent.disabled);
|
|
4736
|
+
if (available) {
|
|
4737
|
+
agentId = targetId;
|
|
4738
|
+
model = sideConfig.model?.trim() || void 0;
|
|
4739
|
+
reasoningEffort = sideConfig.reasoningEffort?.trim() || void 0;
|
|
4740
|
+
}
|
|
4741
|
+
}
|
|
4742
|
+
if (!agentId) {
|
|
4743
|
+
agentId = parentSession?.agentId ?? config.defaultAgentId;
|
|
4744
|
+
model = parentSession ? parentSession.model : config.defaultModel;
|
|
4745
|
+
reasoningEffort = parentSession ? parentSession.reasoningEffort : config.defaultReasoningEffort;
|
|
4746
|
+
}
|
|
4747
|
+
if (!agentId) throw new Error("\u5C1A\u672A\u914D\u7F6E\u9ED8\u8BA4 Agent\uFF0C\u8BF7\u5148\u5728\u8BBE\u7F6E\u4E2D\u914D\u7F6E\u98DE\u4E66\u9ED8\u8BA4 Agent \u6216\u4FA7\u8FB9\u5BF9\u8BDD\u76EE\u6807 Agent");
|
|
4748
|
+
const cwd = parentSession?.cwd ?? config.workspace;
|
|
4749
|
+
const session = await this.runtime.start({
|
|
4750
|
+
agentId,
|
|
4751
|
+
...cwd ? { cwd } : {},
|
|
4752
|
+
...model ? { model } : {},
|
|
4753
|
+
...reasoningEffort ? { reasoningEffort } : {},
|
|
4754
|
+
...parentSession ? { systemPrompt: buildSideSessionSeed(parentSession.id) } : {},
|
|
4755
|
+
permissionMode: "full-trust",
|
|
4756
|
+
source: "side-chat",
|
|
4757
|
+
sourceId: parentSession ? parentSession.id : sideChat.parentSourceId
|
|
4758
|
+
});
|
|
4759
|
+
group.boundSessionId = session.id;
|
|
4760
|
+
group.sessionId = session.id;
|
|
4761
|
+
await this.saveSideChatThread(config.appId, [sideChat.triggerRootId, ...event.threadId ? [event.threadId] : []], session.id);
|
|
4762
|
+
return session;
|
|
4763
|
+
}
|
|
4482
4764
|
async handle(event, config) {
|
|
4483
4765
|
const mentionsBot = event.mentions.some((mention) => this.isSelfMention(config, mention));
|
|
4484
|
-
const
|
|
4766
|
+
const existingSideThread = await this.lookupSideChatThread(config.appId, event);
|
|
4767
|
+
const inSideChatFollowUp = Boolean(existingSideThread) && (event.chatType === "p2p" || mentionsBot || event.mentions.length === 0);
|
|
4768
|
+
const shouldWake = event.chatType === "p2p" || event.chatType === "group" && mentionsBot || inSideChatFollowUp;
|
|
4485
4769
|
if (event.chatType === "group" && !shouldWake && event.mentions.length) {
|
|
4486
4770
|
this.log.info({ messageId: event.messageId, chatId: event.chatId, appId: config.appId, botOpenId: this.botOpenId, mentions: event.mentions }, "\u98DE\u4E66\u6D88\u606F\u542B @ \u4F46\u672A\u547D\u4E2D\u672C\u673A\u5668\u4EBA\uFF0C\u8DF3\u8FC7");
|
|
4487
4771
|
}
|
|
4488
4772
|
if (this.stopped || !shouldWake || this.handledMessages.has(event.messageId)) return;
|
|
4489
4773
|
this.handledMessages.add(event.messageId);
|
|
4490
4774
|
if (this.handledMessages.size > 5e3) this.handledMessages.delete(this.handledMessages.values().next().value);
|
|
4491
|
-
const
|
|
4775
|
+
const sideChatConfig = await readSideChatConfig(this.configRepository);
|
|
4776
|
+
const mainScopeId = larkGroupScopeId(event, config.groupSessionScope);
|
|
4777
|
+
const mainGroupKey = larkGroupKey(event, config.groupSessionScope);
|
|
4778
|
+
let matchedNewSideChat = false;
|
|
4779
|
+
if (!existingSideThread && sideChatConfig.btwEnabled) {
|
|
4780
|
+
try {
|
|
4781
|
+
const quickParsed = await parseLarkMessageContent(event.messageType, event.content, { messageId: event.messageId });
|
|
4782
|
+
const quickText = renderPromptMentions(quickParsed.text, event.mentions, (mention) => this.isSelfMention(config, mention)).trim();
|
|
4783
|
+
matchedNewSideChat = matchSideChatTrigger(quickText, sideChatConfig.triggerPrefix).matched;
|
|
4784
|
+
} catch {
|
|
4785
|
+
}
|
|
4786
|
+
}
|
|
4787
|
+
const triggerRootId = event.rootId?.trim() || event.messageId;
|
|
4788
|
+
const isSideChat = Boolean(existingSideThread) || matchedNewSideChat;
|
|
4789
|
+
const groupKey = isSideChat ? `side-chat:${event.chatId}:${existingSideThread ? existingSideThread.key : triggerRootId}` : mainGroupKey;
|
|
4492
4790
|
const group = this.groups.get(groupKey) ?? { tail: Promise.resolve() };
|
|
4493
|
-
if (
|
|
4791
|
+
if (existingSideThread) {
|
|
4792
|
+
group.boundSessionId = existingSideThread.sessionId;
|
|
4793
|
+
if (event.threadId?.trim()) {
|
|
4794
|
+
void this.saveSideChatThread(config.appId, [existingSideThread.key, event.threadId.trim()], existingSideThread.sessionId);
|
|
4795
|
+
}
|
|
4796
|
+
} else if (!isSideChat && !group.boundSessionId && this.cardMappings) {
|
|
4494
4797
|
try {
|
|
4495
4798
|
const mapping = await this.cardMappings.get(larkHandoverChannel(config.appId), event.chatId);
|
|
4496
4799
|
if (mapping?.sessionId) group.boundSessionId = mapping.sessionId;
|
|
@@ -4498,12 +4801,36 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4498
4801
|
this.log.warn({ error, appId: config.appId, chatId: event.chatId }, "\u8BFB\u53D6\u6258\u7BA1\u7ED1\u5B9A\u5931\u8D25\uFF0C\u6309\u666E\u901A\u4F1A\u8BDD\u5904\u7406");
|
|
4499
4802
|
}
|
|
4500
4803
|
}
|
|
4501
|
-
const task = {
|
|
4804
|
+
const task = {
|
|
4805
|
+
id: event.messageId,
|
|
4806
|
+
group,
|
|
4807
|
+
event,
|
|
4808
|
+
prompt: "",
|
|
4809
|
+
resources: [],
|
|
4810
|
+
config,
|
|
4811
|
+
state: "queued",
|
|
4812
|
+
events: [],
|
|
4813
|
+
turn: 0,
|
|
4814
|
+
...isSideChat ? { forceReplyInThread: true } : {},
|
|
4815
|
+
...matchedNewSideChat ? {
|
|
4816
|
+
sideChat: {
|
|
4817
|
+
parentGroupKey: mainGroupKey,
|
|
4818
|
+
parentSourceId: larkSourceId(config, event.chatId, event.chatType, mainScopeId),
|
|
4819
|
+
triggerRootId,
|
|
4820
|
+
config: sideChatConfig
|
|
4821
|
+
}
|
|
4822
|
+
} : {}
|
|
4823
|
+
};
|
|
4502
4824
|
this.tasks.set(task.id, task);
|
|
4503
4825
|
if (this.tasks.size > 5e3) this.tasks.delete(this.tasks.keys().next().value);
|
|
4826
|
+
const stripSideChatTriggerPrefix = isSideChat && sideChatConfig.btwEnabled ? sideChatConfig.triggerPrefix : void 0;
|
|
4504
4827
|
group.tail = group.tail.then(async () => {
|
|
4505
4828
|
if (this.stopped) return;
|
|
4506
|
-
const parsed = await parsePrompt(event, (mention) => this.isSelfMention(config, mention), this.service, {
|
|
4829
|
+
const parsed = await parsePrompt(event, (mention) => this.isSelfMention(config, mention), this.service, {
|
|
4830
|
+
log: this.log,
|
|
4831
|
+
appId: config.appId,
|
|
4832
|
+
...stripSideChatTriggerPrefix ? { stripSideChatTriggerPrefix } : {}
|
|
4833
|
+
});
|
|
4507
4834
|
task.prompt = parsed.prompt;
|
|
4508
4835
|
task.resources = parsed.resources;
|
|
4509
4836
|
await this.runTurn(task);
|
|
@@ -4737,8 +5064,9 @@ ${lines.join("\n")}`;
|
|
|
4737
5064
|
task.resources = [];
|
|
4738
5065
|
}
|
|
4739
5066
|
if (!task.prompt.trim()) {
|
|
4740
|
-
task.prompt = await this.buildEmptyMessageFallback(event, config);
|
|
5067
|
+
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);
|
|
4741
5068
|
}
|
|
5069
|
+
const replyInThreadOpt = task.forceReplyInThread ? { replyInThread: true } : {};
|
|
4742
5070
|
const prompt = task.prompt;
|
|
4743
5071
|
const firstAttempt = !task.cardMessageId;
|
|
4744
5072
|
const emojiType = acknowledgementEmojis[Math.floor(this.random() * acknowledgementEmojis.length)] ?? acknowledgementEmojis[0];
|
|
@@ -4831,14 +5159,14 @@ ${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl
|
|
|
4831
5159
|
};
|
|
4832
5160
|
let session;
|
|
4833
5161
|
try {
|
|
4834
|
-
session = await this.sessionFor(group, config, event.chatId, event.chatType, larkGroupScopeId(event, config.groupSessionScope));
|
|
5162
|
+
session = task.sideChat ? await this.sideChatSessionFor(task) : await this.sessionFor(group, config, event.chatId, event.chatType, larkGroupScopeId(event, config.groupSessionScope));
|
|
4835
5163
|
} catch (error) {
|
|
4836
5164
|
task.state = "failed";
|
|
4837
5165
|
task.startedAt = Date.now();
|
|
4838
5166
|
const markdown = `**Agent \u542F\u52A8\u5931\u8D25**
|
|
4839
5167
|
|
|
4840
5168
|
${error instanceof Error ? error.message : String(error)}`;
|
|
4841
|
-
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", taskId: task.id, taskName: prompt.slice(0, 80), markdown, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} }, this.log);
|
|
5169
|
+
const card = await deliverTaskFailure(this.service, event, config, { state: "failed", taskId: task.id, taskName: prompt.slice(0, 80), markdown, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyInThreadOpt }, this.log);
|
|
4842
5170
|
if (card.messageId) task.cardMessageId = card.messageId;
|
|
4843
5171
|
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
4844
5172
|
return;
|
|
@@ -4855,7 +5183,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
4855
5183
|
if (task.cardMessageId) {
|
|
4856
5184
|
await this.service.update({ messageId: task.cardMessageId, state: "running", taskId: task.id, taskName: prompt.slice(0, 80), markdown: "\u6B63\u5728\u601D\u8003\u4E2D\u2026", sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} });
|
|
4857
5185
|
} else {
|
|
4858
|
-
const card = await sendTaskCard(this.service, event, { state: "running", taskId: task.id, taskName: prompt.slice(0, 80), markdown: "\u6B63\u5728\u601D\u8003\u4E2D\u2026", sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} }, this.log);
|
|
5186
|
+
const card = await sendTaskCard(this.service, event, { state: "running", taskId: task.id, taskName: prompt.slice(0, 80), markdown: "\u6B63\u5728\u601D\u8003\u4E2D\u2026", sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {}, ...replyInThreadOpt }, this.log);
|
|
4859
5187
|
task.cardMessageId = card.messageId;
|
|
4860
5188
|
}
|
|
4861
5189
|
task.lastSuccessfulElements = initialElements;
|
|
@@ -5019,7 +5347,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
5019
5347
|
let lastQuietError;
|
|
5020
5348
|
for (let attempt = 1; attempt <= maxQuietReplyAttempts; attempt++) {
|
|
5021
5349
|
try {
|
|
5022
|
-
await sendQuietFinalReply(this.service, event, reply, this.log);
|
|
5350
|
+
await sendQuietFinalReply(this.service, event, reply, this.log, task.forceReplyInThread);
|
|
5023
5351
|
lastQuietError = void 0;
|
|
5024
5352
|
break;
|
|
5025
5353
|
} catch (error) {
|
|
@@ -5036,7 +5364,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
5036
5364
|
}
|
|
5037
5365
|
return;
|
|
5038
5366
|
}
|
|
5039
|
-
const defaultReplyInThread = Boolean(event.threadId?.trim());
|
|
5367
|
+
const defaultReplyInThread = Boolean(task.forceReplyInThread || event.threadId?.trim());
|
|
5040
5368
|
const agentReplyInThread = agentReplyMode === "thread";
|
|
5041
5369
|
if (agentReplyMode && agentReplyInThread !== defaultReplyInThread) {
|
|
5042
5370
|
task.replyMode = agentReplyMode;
|
|
@@ -5202,7 +5530,7 @@ ${prompt}` : prompt;
|
|
|
5202
5530
|
buffered = [];
|
|
5203
5531
|
if (runtimeTask.status === "queued" && (runtimeTask.queuedAhead ?? 0) > 0 && task.state === "queued") {
|
|
5204
5532
|
if (config.quietReply) {
|
|
5205
|
-
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);
|
|
5533
|
+
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);
|
|
5206
5534
|
} else {
|
|
5207
5535
|
await this.service.update({ messageId: task.cardMessageId, state: "queued", taskId: task.id, taskName: prompt.slice(0, 80), markdown: `\u6B63\u5728\u6392\u961F\uFF0C\u524D\u9762\u8FD8\u6709 ${runtimeTask.queuedAhead} \u4E2A\u4EFB\u52A1\u2026`, sessionId: task.sessionId, ...config.webBaseUrl ? { webBaseUrl: config.webBaseUrl } : {} });
|
|
5208
5536
|
}
|
|
@@ -5707,14 +6035,14 @@ __export(session_cli_exports, {
|
|
|
5707
6035
|
sourceSessionId: () => sourceSessionId,
|
|
5708
6036
|
streamSessionShow: () => streamSessionShow
|
|
5709
6037
|
});
|
|
5710
|
-
import { existsSync as
|
|
5711
|
-
import { join as
|
|
6038
|
+
import { existsSync as existsSync10 } from "node:fs";
|
|
6039
|
+
import { join as join21, resolve as resolve12 } from "node:path";
|
|
5712
6040
|
function resolveDatabasePath(explicit, cwd = process.cwd()) {
|
|
5713
6041
|
if (explicit) return resolve12(cwd, explicit);
|
|
5714
6042
|
if (process.env.AGENTDOCK_DATABASE_URL) return resolve12(cwd, process.env.AGENTDOCK_DATABASE_URL);
|
|
5715
6043
|
const daemonDir = resolveDaemonDir(cwd);
|
|
5716
6044
|
const recorded = readDaemonStatus(daemonDir)?.database;
|
|
5717
|
-
return recorded ? resolve12(daemonDir, recorded) :
|
|
6045
|
+
return recorded ? resolve12(daemonDir, recorded) : join21(daemonDir, "..", "agentdock.db");
|
|
5718
6046
|
}
|
|
5719
6047
|
function sessionPeerIds(sessions2, sourceId2) {
|
|
5720
6048
|
const source2 = sessions2.find((session) => session.id === sourceId2);
|
|
@@ -5733,7 +6061,7 @@ function sourceSessionId(explicit) {
|
|
|
5733
6061
|
}
|
|
5734
6062
|
async function runSessionPeers(sessionId, options = {}) {
|
|
5735
6063
|
const filename = resolveDatabasePath(options.database);
|
|
5736
|
-
if (!
|
|
6064
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5737
6065
|
const repos = createRepositories(filename);
|
|
5738
6066
|
try {
|
|
5739
6067
|
const sourceId2 = sourceSessionId(sessionId);
|
|
@@ -5808,7 +6136,7 @@ async function runSessionCancel(targetId, taskId, options = {}) {
|
|
|
5808
6136
|
}
|
|
5809
6137
|
async function runSessionList(options = {}) {
|
|
5810
6138
|
const filename = resolveDatabasePath(options.database);
|
|
5811
|
-
if (!
|
|
6139
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5812
6140
|
const repos = createRepositories(filename);
|
|
5813
6141
|
try {
|
|
5814
6142
|
const sessions2 = await repos.sessions.list();
|
|
@@ -5820,7 +6148,7 @@ async function runSessionList(options = {}) {
|
|
|
5820
6148
|
}
|
|
5821
6149
|
async function withSessionView(sessionId, options, view) {
|
|
5822
6150
|
const filename = resolveDatabasePath(options.database);
|
|
5823
|
-
if (!
|
|
6151
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5824
6152
|
const repos = createRepositories(filename);
|
|
5825
6153
|
try {
|
|
5826
6154
|
const session = await repos.sessions.get(sessionId);
|
|
@@ -5963,7 +6291,7 @@ var AutostartService = class {
|
|
|
5963
6291
|
|
|
5964
6292
|
// src/cli.ts
|
|
5965
6293
|
init_src();
|
|
5966
|
-
import { existsSync as
|
|
6294
|
+
import { existsSync as existsSync13, readFileSync as readFileSync16 } from "node:fs";
|
|
5967
6295
|
import { spawn as spawn13 } from "node:child_process";
|
|
5968
6296
|
import { loadEnvFile } from "node:process";
|
|
5969
6297
|
import { fileURLToPath as fileURLToPath6 } from "node:url";
|
|
@@ -7175,12 +7503,12 @@ function resolveInstalledBuiltInAgentLaunch(agentCommand, options = {}) {
|
|
|
7175
7503
|
}
|
|
7176
7504
|
function resolveInstalledBuiltInAgentLaunchForSpec(spec, options) {
|
|
7177
7505
|
const readFileSync17 = options.readFileSync ?? fs.readFileSync;
|
|
7178
|
-
const
|
|
7506
|
+
const existsSync14 = options.existsSync ?? fs.existsSync;
|
|
7179
7507
|
const resolvePackageRoot = options.resolvePackageRoot ?? defaultResolvePackageRoot;
|
|
7180
7508
|
try {
|
|
7181
7509
|
const resolved = resolveInstalledBuiltInAgentPackage(spec, {
|
|
7182
7510
|
readFileSync: readFileSync17,
|
|
7183
|
-
existsSync:
|
|
7511
|
+
existsSync: existsSync14,
|
|
7184
7512
|
resolvePackageRoot
|
|
7185
7513
|
});
|
|
7186
7514
|
if (!resolved) return;
|
|
@@ -7213,12 +7541,12 @@ function resolveInstalledBuiltInAgentPackage(spec, options) {
|
|
|
7213
7541
|
function resolvePackageExecBuiltInAgentLaunch(agentCommand, options = {}) {
|
|
7214
7542
|
const spec = findBuiltInAgentPackage(agentCommand);
|
|
7215
7543
|
if (!spec) return;
|
|
7216
|
-
const
|
|
7544
|
+
const existsSync14 = options.existsSync ?? fs.existsSync;
|
|
7217
7545
|
const execPath = options.execPath ?? process.execPath;
|
|
7218
7546
|
const resolveNpmCliPath = options.resolveNpmCliPath ?? defaultResolveNpmCliPath;
|
|
7219
7547
|
try {
|
|
7220
7548
|
const npmCliPath = resolveNpmCliPath(execPath);
|
|
7221
|
-
if (!
|
|
7549
|
+
if (!existsSync14(npmCliPath)) return;
|
|
7222
7550
|
return {
|
|
7223
7551
|
source: "package-exec",
|
|
7224
7552
|
command: execPath,
|
|
@@ -17555,13 +17883,13 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
17555
17883
|
const range = await this.repos.events.turnRange(sessionId, taskId);
|
|
17556
17884
|
return range ? this.repos.events.listRange(sessionId, { after: range.startSequence, before: range.endSequence }) : [];
|
|
17557
17885
|
}
|
|
17558
|
-
async resolveTaskOutcome(session, task) {
|
|
17886
|
+
async resolveTaskOutcome(session, task, afterSequence = this.turnAnchors.get(task.id)) {
|
|
17559
17887
|
const stopReason = this.driverStopReasons.get(session.id);
|
|
17560
17888
|
if (this.interruptedTurns.has(session.id) || stopReason === "cancelled") return { status: "interrupted", stopReason };
|
|
17561
17889
|
if (_AgentDockRuntime.isTruncatedStopReason(stopReason)) {
|
|
17562
17890
|
return { status: "failed", stopReason, message: `\u8F93\u51FA\u56E0\u8FBE\u5230 token \u4E0A\u9650\u88AB\u622A\u65AD\uFF08stopReason: ${stopReason}\uFF09\uFF0C\u672A\u4EA7\u751F\u5B8C\u6574\u6700\u7EC8\u8F93\u51FA` };
|
|
17563
17891
|
}
|
|
17564
|
-
const turnEvents = await this.turnEventsFor(session.id, task.id,
|
|
17892
|
+
const turnEvents = await this.turnEventsFor(session.id, task.id, afterSequence);
|
|
17565
17893
|
const finalText = pickFinalAssistantText(turnEvents);
|
|
17566
17894
|
if (unresolvedToolCallsAfterAnswer(turnEvents).length) {
|
|
17567
17895
|
return { status: "failed", stopReason, message: "Agent \u5B58\u5728\u672A\u8FD4\u56DE\u7ED3\u679C\u7684\u5DE5\u5177\u8C03\u7528\uFF0C\u672C\u8F6E\u4EFB\u52A1\u672A\u6B63\u5E38\u7ED3\u675F", finalText };
|
|
@@ -17569,6 +17897,10 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
17569
17897
|
if (!finalText) {
|
|
17570
17898
|
return { status: "failed", stopReason, message: "Agent \u672A\u8FD4\u56DE\u6700\u7EC8\u8F93\u51FA", finalText };
|
|
17571
17899
|
}
|
|
17900
|
+
const agent = await this.repos.agents.get(session.agentId);
|
|
17901
|
+
if (agent?.authErrorPattern && isAgentAuthErrorText(finalText, agent.authErrorPattern)) {
|
|
17902
|
+
return { status: "failed", stopReason, message: `${agent.name} \u8BA4\u8BC1\u5DF2\u5931\u6548\uFF08401 UNAUTHENTICATED\uFF09\uFF0C\u8BF7\u91CD\u65B0\u8BA4\u8BC1\u540E\u91CD\u8BD5`, authError: true, finalText };
|
|
17903
|
+
}
|
|
17572
17904
|
return { status: "completed", stopReason, finalText };
|
|
17573
17905
|
}
|
|
17574
17906
|
onDriverEvent(session) {
|
|
@@ -18109,6 +18441,21 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18109
18441
|
await mkdir(directory, { recursive: true });
|
|
18110
18442
|
await writeFile(join7(directory, `${session.id}.json`), JSON.stringify(policy ?? { enabled: false }), { mode: 384 });
|
|
18111
18443
|
}
|
|
18444
|
+
async evictDriver(sessionId, driver) {
|
|
18445
|
+
try {
|
|
18446
|
+
await driver.stop();
|
|
18447
|
+
} catch {
|
|
18448
|
+
} finally {
|
|
18449
|
+
if (this.drivers.get(sessionId) === driver) this.drivers.delete(sessionId);
|
|
18450
|
+
}
|
|
18451
|
+
}
|
|
18452
|
+
async executeTurnAndResolve(id, session, task, driver, prompt, afterSequence) {
|
|
18453
|
+
this.driverStopReasons.delete(id);
|
|
18454
|
+
await driver.send(prompt);
|
|
18455
|
+
await this.flushDriverEvents(id);
|
|
18456
|
+
await this.flushStream(id);
|
|
18457
|
+
return this.resolveTaskOutcome(session, task, afterSequence);
|
|
18458
|
+
}
|
|
18112
18459
|
async runTask(id, task, agentPrompt = task.prompt, riskPolicy) {
|
|
18113
18460
|
const { session } = await this.active(id);
|
|
18114
18461
|
if (["stopped", "failed"].includes(session.state)) throw new RuntimeError("INVALID_STATE", `Cannot send while session is ${session.state}`, 409);
|
|
@@ -18139,11 +18486,14 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18139
18486
|
const resolvedAgentPrompt = await this.options.sessionPrompt?.(session, agentPrompt, task.origin ?? void 0) ?? agentPrompt;
|
|
18140
18487
|
task.sentPrompt = resolvedAgentPrompt;
|
|
18141
18488
|
await this.repos.tasks.save(task);
|
|
18142
|
-
this.
|
|
18143
|
-
|
|
18144
|
-
|
|
18145
|
-
|
|
18146
|
-
|
|
18489
|
+
let outcome = await this.executeTurnAndResolve(id, session, task, driver, resolvedAgentPrompt);
|
|
18490
|
+
if (outcome.status === "failed" && outcome.authError) {
|
|
18491
|
+
const retryAfterSequence = this.sequences.get(id);
|
|
18492
|
+
await this.evictDriver(id, driver);
|
|
18493
|
+
driver = await this.reconnect(session);
|
|
18494
|
+
if (riskPolicy) await this.applyRiskPolicy(session, driver, riskPolicy);
|
|
18495
|
+
outcome = await this.executeTurnAndResolve(id, session, task, driver, resolvedAgentPrompt, retryAfterSequence);
|
|
18496
|
+
}
|
|
18147
18497
|
task.finalText = outcome.finalText;
|
|
18148
18498
|
session.lastMessageAt = now();
|
|
18149
18499
|
if (outcome.status === "interrupted") {
|
|
@@ -18589,12 +18939,15 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18589
18939
|
for (const key of this.permissions.keys()) if (key.startsWith(`${sessionId}:`)) this.permissions.delete(key);
|
|
18590
18940
|
}
|
|
18591
18941
|
async cleanupIdleDriversOnce(at) {
|
|
18592
|
-
|
|
18593
|
-
|
|
18942
|
+
if (!this.drivers.size) return;
|
|
18943
|
+
const defaultTimeout = this.options.driverIdleTimeoutMs ?? 6 * 60 * 6e4;
|
|
18944
|
+
const agentsById = new Map((await this.repos.agents.list()).map((agent) => [agent.id, agent]));
|
|
18594
18945
|
for (const [sessionId, driver] of this.drivers) {
|
|
18595
|
-
if (this.activeTurns.has(sessionId)
|
|
18946
|
+
if (this.activeTurns.has(sessionId)) continue;
|
|
18596
18947
|
const session = await this.repos.sessions.get(sessionId);
|
|
18597
18948
|
if (!session || !["idle", "completed", "interrupted"].includes(session.state)) continue;
|
|
18949
|
+
const timeout = agentsById.get(session.agentId)?.idleTimeoutMs ?? defaultTimeout;
|
|
18950
|
+
if (timeout <= 0 || at - (this.lastActivity.get(sessionId) ?? at) < timeout) continue;
|
|
18598
18951
|
try {
|
|
18599
18952
|
await driver.stop();
|
|
18600
18953
|
} catch {
|
|
@@ -18682,7 +19035,7 @@ var agentDetails = {
|
|
|
18682
19035
|
qwen: { name: "Qwen Code", cli: "qwen" },
|
|
18683
19036
|
trae: { name: "Trae", cli: "traecli" },
|
|
18684
19037
|
zeroclaw: { name: "ZeroClaw", cli: "zeroclaw" },
|
|
18685
|
-
antigravity: { name: "Google Antigravity", cli: ["agy", "antigravity"], argvExecutable: true }
|
|
19038
|
+
antigravity: { name: "Google Antigravity", cli: ["agy", "antigravity"], argvExecutable: true, idleTimeoutMs: 15 * 6e4, authErrorPattern: antigravityAuthErrorPattern }
|
|
18686
19039
|
};
|
|
18687
19040
|
function cliVersion(command, prefixArgs = []) {
|
|
18688
19041
|
for (const args of [["--version"], ["-V"], ["version"]]) {
|
|
@@ -18714,7 +19067,9 @@ function discoverBuiltinAgents(entries = listAcpxBuiltinAgents(), dependencies =
|
|
|
18714
19067
|
timeout: 600,
|
|
18715
19068
|
capabilities: { pause: false, resume: true },
|
|
18716
19069
|
builtin: true,
|
|
18717
|
-
version: id === "antigravity" ? version(argv[0]) : id === "codex" ? version(argv[0], argv.slice(1)) : version(commands[0])
|
|
19070
|
+
version: id === "antigravity" ? version(argv[0]) : id === "codex" ? version(argv[0], argv.slice(1)) : version(commands[0]),
|
|
19071
|
+
...detail.idleTimeoutMs !== void 0 ? { idleTimeoutMs: detail.idleTimeoutMs } : {},
|
|
19072
|
+
...detail.authErrorPattern !== void 0 ? { authErrorPattern: detail.authErrorPattern } : {}
|
|
18718
19073
|
}];
|
|
18719
19074
|
});
|
|
18720
19075
|
}
|
|
@@ -19038,8 +19393,8 @@ import Fastify from "fastify";
|
|
|
19038
19393
|
import cors from "@fastify/cors";
|
|
19039
19394
|
import { readFile as readFile12, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
|
|
19040
19395
|
import { Readable as Readable3 } from "node:stream";
|
|
19041
|
-
import { extname as extname2, join as
|
|
19042
|
-
import { homedir as
|
|
19396
|
+
import { extname as extname2, join as join20, resolve as resolve10, sep as sep3 } from "node:path";
|
|
19397
|
+
import { homedir as homedir15 } from "node:os";
|
|
19043
19398
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
19044
19399
|
|
|
19045
19400
|
// src/lark/routes.ts
|
|
@@ -22278,11 +22633,11 @@ function isSourceIngressRequest(method, pathname) {
|
|
|
22278
22633
|
// src/sources-router/routes.ts
|
|
22279
22634
|
init_src2();
|
|
22280
22635
|
import { Readable as Readable2 } from "node:stream";
|
|
22281
|
-
import { z as
|
|
22636
|
+
import { z as z6 } from "zod";
|
|
22282
22637
|
|
|
22283
22638
|
// src/sources-router/ingress.ts
|
|
22284
22639
|
init_src2();
|
|
22285
|
-
import { z as
|
|
22640
|
+
import { z as z5 } from "zod";
|
|
22286
22641
|
|
|
22287
22642
|
// src/sources-router/types.ts
|
|
22288
22643
|
function publicSource(source2) {
|
|
@@ -22293,22 +22648,22 @@ function publicSource(source2) {
|
|
|
22293
22648
|
// src/sources-router/ingress.ts
|
|
22294
22649
|
var defaultBodyLimitBytes = 1024 * 1024;
|
|
22295
22650
|
var defaultSignatureToleranceMs = 5 * 6e4;
|
|
22296
|
-
var objectSchema =
|
|
22297
|
-
var actorSchema =
|
|
22298
|
-
var envelopeSchema =
|
|
22299
|
-
specVersion:
|
|
22300
|
-
sourceId:
|
|
22301
|
-
eventId:
|
|
22302
|
-
eventType:
|
|
22303
|
-
dedupeKey:
|
|
22304
|
-
occurredAt:
|
|
22651
|
+
var objectSchema = z5.object({ type: z5.string().min(1), id: z5.string().min(1), url: z5.string().optional(), title: z5.string().optional() });
|
|
22652
|
+
var actorSchema = z5.object({ id: z5.string().optional(), name: z5.string().optional(), isBot: z5.boolean().optional() }).optional();
|
|
22653
|
+
var envelopeSchema = z5.object({
|
|
22654
|
+
specVersion: z5.literal("agentdock.source.v1"),
|
|
22655
|
+
sourceId: z5.string().min(1),
|
|
22656
|
+
eventId: z5.string().min(1),
|
|
22657
|
+
eventType: z5.string().min(1),
|
|
22658
|
+
dedupeKey: z5.string().min(1),
|
|
22659
|
+
occurredAt: z5.string().datetime(),
|
|
22305
22660
|
object: objectSchema,
|
|
22306
22661
|
actor: actorSchema,
|
|
22307
|
-
correlationKey:
|
|
22308
|
-
payload:
|
|
22309
|
-
raw:
|
|
22310
|
-
causationId:
|
|
22311
|
-
traceId:
|
|
22662
|
+
correlationKey: z5.string().min(1).optional(),
|
|
22663
|
+
payload: z5.record(z5.string(), z5.unknown()).default({}),
|
|
22664
|
+
raw: z5.string().optional(),
|
|
22665
|
+
causationId: z5.string().nullable().optional(),
|
|
22666
|
+
traceId: z5.string().min(1)
|
|
22312
22667
|
}).strict();
|
|
22313
22668
|
var IngressError = class extends RuntimeError {
|
|
22314
22669
|
constructor(code, message, statusCode) {
|
|
@@ -22318,19 +22673,19 @@ var IngressError = class extends RuntimeError {
|
|
|
22318
22673
|
};
|
|
22319
22674
|
|
|
22320
22675
|
// src/sources-router/routes.ts
|
|
22321
|
-
var createSourceSchema =
|
|
22322
|
-
name:
|
|
22323
|
-
kind:
|
|
22324
|
-
enabled:
|
|
22325
|
-
config:
|
|
22326
|
-
secretRefs:
|
|
22327
|
-
secrets:
|
|
22676
|
+
var createSourceSchema = z6.object({
|
|
22677
|
+
name: z6.string().min(1),
|
|
22678
|
+
kind: z6.enum(["webhook", "poll", "stream", "worker"]).optional(),
|
|
22679
|
+
enabled: z6.boolean().optional(),
|
|
22680
|
+
config: z6.record(z6.string(), z6.unknown()).optional(),
|
|
22681
|
+
secretRefs: z6.array(z6.string()).optional(),
|
|
22682
|
+
secrets: z6.record(z6.string(), z6.string()).optional()
|
|
22328
22683
|
}).strict();
|
|
22329
|
-
var updateSourceSchema =
|
|
22330
|
-
name:
|
|
22331
|
-
config:
|
|
22332
|
-
secretRefs:
|
|
22333
|
-
secrets:
|
|
22684
|
+
var updateSourceSchema = z6.object({
|
|
22685
|
+
name: z6.string().min(1).optional(),
|
|
22686
|
+
config: z6.record(z6.string(), z6.unknown()).optional(),
|
|
22687
|
+
secretRefs: z6.array(z6.string()).optional(),
|
|
22688
|
+
secrets: z6.record(z6.string(), z6.string()).optional()
|
|
22334
22689
|
}).strict();
|
|
22335
22690
|
function asHeaders(request) {
|
|
22336
22691
|
return request.headers;
|
|
@@ -22746,11 +23101,12 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
|
|
|
22746
23101
|
init_src2();
|
|
22747
23102
|
import { realpathSync as realpathSync3 } from "node:fs";
|
|
22748
23103
|
import { readdir as readdir3, readFile as readFile10, stat as stat4 } from "node:fs/promises";
|
|
22749
|
-
import { isAbsolute as isAbsolute7, relative } from "node:path";
|
|
23104
|
+
import { basename as basename6, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
|
|
22750
23105
|
|
|
22751
23106
|
// src/fs-paths.ts
|
|
22752
|
-
import { realpathSync as realpathSync2 } from "node:fs";
|
|
22753
|
-
import {
|
|
23107
|
+
import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
|
|
23108
|
+
import { homedir as homedir12, tmpdir as tmpdir3 } from "node:os";
|
|
23109
|
+
import { basename as basename5, isAbsolute as isAbsolute6, join as join17, resolve as resolve9, sep } from "node:path";
|
|
22754
23110
|
function resolveInsideRoot(root4, userPath) {
|
|
22755
23111
|
const normalized2 = (userPath ?? "").trim();
|
|
22756
23112
|
if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
|
|
@@ -22778,6 +23134,95 @@ var WorkspacePathError = class extends Error {
|
|
|
22778
23134
|
this.name = "WorkspacePathError";
|
|
22779
23135
|
}
|
|
22780
23136
|
};
|
|
23137
|
+
var sensitiveExactNames = /* @__PURE__ */ new Set([
|
|
23138
|
+
".env",
|
|
23139
|
+
".npmrc",
|
|
23140
|
+
".netrc",
|
|
23141
|
+
".pypirc",
|
|
23142
|
+
".dockercfg",
|
|
23143
|
+
".htpasswd",
|
|
23144
|
+
"auth.json",
|
|
23145
|
+
"credentials.json",
|
|
23146
|
+
".credentials.json",
|
|
23147
|
+
"secrets.json",
|
|
23148
|
+
"token.json"
|
|
23149
|
+
]);
|
|
23150
|
+
var sensitiveExtensions = /* @__PURE__ */ new Set([
|
|
23151
|
+
".key",
|
|
23152
|
+
".pem",
|
|
23153
|
+
".p12",
|
|
23154
|
+
".pfx",
|
|
23155
|
+
".jks",
|
|
23156
|
+
".keystore"
|
|
23157
|
+
]);
|
|
23158
|
+
var sensitiveKeyPrefixPattern = /^id_(?:rsa|ed25519|ecdsa|dsa)(?:\..+)?$/i;
|
|
23159
|
+
function isSensitivePath(targetPath) {
|
|
23160
|
+
const normalized2 = targetPath.replace(/\\/g, "/");
|
|
23161
|
+
const segments = normalized2.split("/").filter(Boolean);
|
|
23162
|
+
if (!segments.length) return false;
|
|
23163
|
+
for (let i = 0; i < segments.length; i++) {
|
|
23164
|
+
const seg = segments[i].toLowerCase();
|
|
23165
|
+
if (seg === ".ssh" || seg === ".gnupg") return true;
|
|
23166
|
+
if (seg === ".aws" && segments[i + 1]?.toLowerCase() === "credentials") return true;
|
|
23167
|
+
if (seg === ".kube" && segments[i + 1]?.toLowerCase() === "config") return true;
|
|
23168
|
+
}
|
|
23169
|
+
const name = basename5(normalized2).toLowerCase();
|
|
23170
|
+
if (sensitiveExactNames.has(name)) return true;
|
|
23171
|
+
if (name.startsWith(".env.")) return true;
|
|
23172
|
+
if (sensitiveKeyPrefixPattern.test(name)) return true;
|
|
23173
|
+
if (name.startsWith("service-account") && name.endsWith(".json")) return true;
|
|
23174
|
+
const dot = name.lastIndexOf(".");
|
|
23175
|
+
if (dot >= 0 && sensitiveExtensions.has(name.slice(dot))) return true;
|
|
23176
|
+
return false;
|
|
23177
|
+
}
|
|
23178
|
+
function allowedReadRoots(options) {
|
|
23179
|
+
const home = options.homeDir ?? homedir12();
|
|
23180
|
+
const candidates = [options.cwd];
|
|
23181
|
+
if (options.role === "session") {
|
|
23182
|
+
if (options.sessionId) {
|
|
23183
|
+
candidates.push(join17(home, ".agentdock", "uploads", options.sessionId));
|
|
23184
|
+
}
|
|
23185
|
+
} else {
|
|
23186
|
+
candidates.push(
|
|
23187
|
+
join17(home, ".agentdock", "uploads"),
|
|
23188
|
+
join17(home, ".gemini"),
|
|
23189
|
+
"/tmp",
|
|
23190
|
+
"/private/tmp",
|
|
23191
|
+
options.tempDir ?? tmpdir3(),
|
|
23192
|
+
...options.extraMasterRoots ?? []
|
|
23193
|
+
);
|
|
23194
|
+
}
|
|
23195
|
+
const resolved = [];
|
|
23196
|
+
const seen = /* @__PURE__ */ new Set();
|
|
23197
|
+
for (const candidate of candidates) {
|
|
23198
|
+
if (!candidate || !existsSync8(candidate)) continue;
|
|
23199
|
+
try {
|
|
23200
|
+
const real = realpathSync2(candidate);
|
|
23201
|
+
if (!seen.has(real)) {
|
|
23202
|
+
seen.add(real);
|
|
23203
|
+
resolved.push(real);
|
|
23204
|
+
}
|
|
23205
|
+
} catch {
|
|
23206
|
+
}
|
|
23207
|
+
}
|
|
23208
|
+
return resolved;
|
|
23209
|
+
}
|
|
23210
|
+
function isRealPathWithinRoots(realTarget, realRoots) {
|
|
23211
|
+
return realRoots.some((root4) => realTarget === root4 || realTarget.startsWith(`${root4}${sep}`));
|
|
23212
|
+
}
|
|
23213
|
+
function isBinaryBuffer(buffer) {
|
|
23214
|
+
const len = Math.min(buffer.length, 8192);
|
|
23215
|
+
if (len === 0) return false;
|
|
23216
|
+
let suspicious = 0;
|
|
23217
|
+
for (let i = 0; i < len; i++) {
|
|
23218
|
+
const byte = buffer[i];
|
|
23219
|
+
if (byte === 0) return true;
|
|
23220
|
+
if (byte < 7 || byte > 14 && byte < 32 && byte !== 27) {
|
|
23221
|
+
suspicious++;
|
|
23222
|
+
}
|
|
23223
|
+
}
|
|
23224
|
+
return suspicious / len > 0.3;
|
|
23225
|
+
}
|
|
22781
23226
|
var textExtensions = /* @__PURE__ */ new Set([
|
|
22782
23227
|
".txt",
|
|
22783
23228
|
".md",
|
|
@@ -22790,7 +23235,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22790
23235
|
".ini",
|
|
22791
23236
|
".cfg",
|
|
22792
23237
|
".conf",
|
|
22793
|
-
".env",
|
|
22794
23238
|
".csv",
|
|
22795
23239
|
".tsv",
|
|
22796
23240
|
".js",
|
|
@@ -22826,7 +23270,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22826
23270
|
".scss",
|
|
22827
23271
|
".less",
|
|
22828
23272
|
".xml",
|
|
22829
|
-
".svg",
|
|
22830
23273
|
".vue",
|
|
22831
23274
|
".svelte",
|
|
22832
23275
|
".sql",
|
|
@@ -22839,7 +23282,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22839
23282
|
".editorconfig",
|
|
22840
23283
|
".eslintrc",
|
|
22841
23284
|
".prettierrc",
|
|
22842
|
-
".npmrc",
|
|
22843
23285
|
".lock",
|
|
22844
23286
|
".sum",
|
|
22845
23287
|
".mod",
|
|
@@ -22858,8 +23300,8 @@ function previewKindForName(name) {
|
|
|
22858
23300
|
const lower = name.toLowerCase();
|
|
22859
23301
|
const dot = lower.lastIndexOf(".");
|
|
22860
23302
|
const ext = dot >= 0 ? lower.slice(dot) : lower;
|
|
22861
|
-
if (textExtensions.has(ext)) return "text";
|
|
22862
23303
|
if (imageExtensions.has(ext)) return "image";
|
|
23304
|
+
if (textExtensions.has(ext)) return "text";
|
|
22863
23305
|
if (ext === ".pdf") return "pdf";
|
|
22864
23306
|
return "unsupported";
|
|
22865
23307
|
}
|
|
@@ -22880,15 +23322,23 @@ function imageMimeForName(name) {
|
|
|
22880
23322
|
|
|
22881
23323
|
// src/fs-routes.ts
|
|
22882
23324
|
function badPath(error) {
|
|
23325
|
+
if (error instanceof RuntimeError) throw error;
|
|
22883
23326
|
if (error instanceof WorkspacePathError) throw new RuntimeError("INVALID_PATH", error.message, 400);
|
|
22884
23327
|
if (error?.code === "ENOENT") throw new RuntimeError("PATH_NOT_FOUND", "\u8DEF\u5F84\u4E0D\u5B58\u5728", 404);
|
|
22885
23328
|
if (error?.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
|
|
22886
23329
|
throw error;
|
|
22887
23330
|
}
|
|
22888
|
-
|
|
23331
|
+
function contentDispositionAttachment(filename) {
|
|
23332
|
+
const safeAscii = filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
|
23333
|
+
return `attachment; filename="${safeAscii}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
|
|
23334
|
+
}
|
|
23335
|
+
async function registerFsRoutes(app, runtime, options = {}) {
|
|
22889
23336
|
app.get("/api/sessions/:id/fs/list", async (request) => {
|
|
22890
23337
|
const session = await runtime.getSession(request.params.id);
|
|
22891
23338
|
if (!session) throw new RuntimeError("SESSION_NOT_FOUND", "Session not found", 404);
|
|
23339
|
+
if (session.sshHost) {
|
|
23340
|
+
throw new RuntimeError("REMOTE_SESSION_UNSUPPORTED", `SSH \u8FDC\u7AEF\u4F1A\u8BDD\uFF08${session.sshHost}\uFF09\u6682\u4E0D\u652F\u6301\u672C\u673A\u6587\u4EF6\u6D4F\u89C8`, 400);
|
|
23341
|
+
}
|
|
22892
23342
|
const userPath = request.query.path ?? "";
|
|
22893
23343
|
let resolved;
|
|
22894
23344
|
try {
|
|
@@ -22900,9 +23350,7 @@ async function registerFsRoutes(app, runtime) {
|
|
|
22900
23350
|
try {
|
|
22901
23351
|
names = await readdir3(resolved.absolute);
|
|
22902
23352
|
} catch (error) {
|
|
22903
|
-
|
|
22904
|
-
if (error.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
|
|
22905
|
-
throw error;
|
|
23353
|
+
badPath(error);
|
|
22906
23354
|
}
|
|
22907
23355
|
const entries = [];
|
|
22908
23356
|
await Promise.all(names.map(async (name) => {
|
|
@@ -22919,43 +23367,96 @@ async function registerFsRoutes(app, runtime) {
|
|
|
22919
23367
|
app.get("/api/sessions/:id/fs/read", async (request, reply) => {
|
|
22920
23368
|
const session = await runtime.getSession(request.params.id);
|
|
22921
23369
|
if (!session) throw new RuntimeError("SESSION_NOT_FOUND", "Session not found", 404);
|
|
23370
|
+
if (session.sshHost) {
|
|
23371
|
+
throw new RuntimeError("REMOTE_SESSION_UNSUPPORTED", `SSH \u8FDC\u7AEF\u4F1A\u8BDD\uFF08${session.sshHost}\uFF09\u6682\u4E0D\u652F\u6301\u672C\u673A\u6587\u4EF6\u9884\u89C8`, 400);
|
|
23372
|
+
}
|
|
22922
23373
|
const userPath = request.query.path;
|
|
22923
23374
|
if (!userPath) throw new RuntimeError("INVALID_PATH", "\u7F3A\u5C11 path \u53C2\u6570", 400);
|
|
23375
|
+
if (isSensitivePath(userPath)) {
|
|
23376
|
+
throw new RuntimeError("SENSITIVE_FILE_BLOCKED", "\u7981\u6B62\u9884\u89C8\u6216\u4E0B\u8F7D\u654F\u611F\u6587\u4EF6", 403);
|
|
23377
|
+
}
|
|
23378
|
+
const claim = request.webClaim;
|
|
23379
|
+
const role = claim?.kind === "session" ? "session" : "master";
|
|
22924
23380
|
let resolved;
|
|
22925
23381
|
try {
|
|
22926
23382
|
if (isAbsolute7(userPath)) {
|
|
23383
|
+
const realTarget = realpathSync3(userPath);
|
|
23384
|
+
const roots = allowedReadRoots({
|
|
23385
|
+
role,
|
|
23386
|
+
cwd: session.cwd,
|
|
23387
|
+
sessionId: request.params.id,
|
|
23388
|
+
...options.homeDir ? { homeDir: options.homeDir } : {},
|
|
23389
|
+
...options.tempDir ? { tempDir: options.tempDir } : {},
|
|
23390
|
+
...options.extraMasterRoots ? { extraMasterRoots: options.extraMasterRoots } : {}
|
|
23391
|
+
});
|
|
23392
|
+
if (!isRealPathWithinRoots(realTarget, roots)) {
|
|
23393
|
+
throw new RuntimeError(
|
|
23394
|
+
"FORBIDDEN",
|
|
23395
|
+
role === "session" ? "\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5\u53EA\u80FD\u9884\u89C8\u8BE5\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u53CA\u4E0A\u4F20\u76EE\u5F55\u5185\u7684\u6587\u4EF6" : "\u8DEF\u5F84\u4E0D\u5728\u5141\u8BB8\u9884\u89C8\u7684\u76EE\u5F55\u8303\u56F4\u5185",
|
|
23396
|
+
403
|
|
23397
|
+
);
|
|
23398
|
+
}
|
|
23399
|
+
let rel = userPath;
|
|
22927
23400
|
try {
|
|
22928
|
-
|
|
23401
|
+
const realCwd = realpathSync3(session.cwd);
|
|
23402
|
+
if (realTarget === realCwd || realTarget.startsWith(`${realCwd}${sep2}`)) {
|
|
23403
|
+
rel = relative(realCwd, realTarget);
|
|
23404
|
+
}
|
|
22929
23405
|
} catch {
|
|
22930
|
-
const claim = request.webClaim;
|
|
22931
|
-
if (claim?.kind === "session") throw new RuntimeError("FORBIDDEN", "\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5\u53EA\u80FD\u9884\u89C8\u8BE5\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u5185\u7684\u6587\u4EF6", 403);
|
|
22932
|
-
resolved = { absolute: realpathSync3(userPath), relative: userPath };
|
|
22933
23406
|
}
|
|
23407
|
+
resolved = { absolute: realTarget, relative: rel };
|
|
22934
23408
|
} else {
|
|
22935
23409
|
resolved = resolveExistingInside(session.cwd, userPath);
|
|
22936
23410
|
}
|
|
22937
23411
|
} catch (error) {
|
|
22938
23412
|
badPath(error);
|
|
22939
23413
|
}
|
|
23414
|
+
if (isSensitivePath(resolved.absolute)) {
|
|
23415
|
+
throw new RuntimeError("SENSITIVE_FILE_BLOCKED", "\u7981\u6B62\u9884\u89C8\u6216\u4E0B\u8F7D\u654F\u611F\u6587\u4EF6", 403);
|
|
23416
|
+
}
|
|
22940
23417
|
let info;
|
|
22941
23418
|
try {
|
|
22942
23419
|
info = await stat4(resolved.absolute);
|
|
22943
23420
|
} catch (error) {
|
|
22944
|
-
|
|
22945
|
-
throw error;
|
|
23421
|
+
badPath(error);
|
|
22946
23422
|
}
|
|
22947
23423
|
if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
|
|
22948
|
-
const
|
|
22949
|
-
|
|
22950
|
-
const
|
|
22951
|
-
|
|
23424
|
+
const filename = basename6(resolved.absolute);
|
|
23425
|
+
const isSvg = filename.toLowerCase().endsWith(".svg");
|
|
23426
|
+
const wantDownload = request.query.download === "1" || request.query.download === "true";
|
|
23427
|
+
const wantText = request.query.format === "text";
|
|
23428
|
+
if (wantDownload) {
|
|
23429
|
+
if (info.size > maxDocumentPreviewBytes) {
|
|
23430
|
+
throw new RuntimeError("FILE_TOO_LARGE", `\u6587\u4EF6\u8D85\u8FC7 20MB \u4E0B\u8F7D\u4E0A\u9650\uFF08\u5B9E\u9645 ${info.size} \u5B57\u8282\uFF09\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u5904\u7406`, 415);
|
|
23431
|
+
}
|
|
23432
|
+
const buffer2 = await readFile10(resolved.absolute);
|
|
23433
|
+
reply.header("Content-Type", imageMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream"));
|
|
23434
|
+
reply.header("Content-Disposition", contentDispositionAttachment(filename));
|
|
23435
|
+
reply.header("X-Content-Type-Options", "nosniff");
|
|
23436
|
+
if (isSvg) reply.header("Content-Security-Policy", "sandbox");
|
|
23437
|
+
reply.header("Cache-Control", "private, no-store");
|
|
23438
|
+
return reply.send(buffer2);
|
|
23439
|
+
}
|
|
23440
|
+
const baseKind = previewKindForName(filename);
|
|
23441
|
+
const effectiveKind = wantText && (baseKind === "text" || isSvg) ? "text" : baseKind;
|
|
23442
|
+
if (effectiveKind === "unsupported") {
|
|
23443
|
+
throw new RuntimeError("UNSUPPORTED_PREVIEW", "\u4E0D\u652F\u6301\u9884\u89C8\u7684\u6587\u4EF6\u7C7B\u578B\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u67E5\u770B\u6216\u4E0B\u8F7D", 415);
|
|
23444
|
+
}
|
|
23445
|
+
const maxBytes = effectiveKind === "text" ? maxTextPreviewBytes : maxDocumentPreviewBytes;
|
|
23446
|
+
if (info.size > maxBytes) {
|
|
23447
|
+
throw new RuntimeError("FILE_TOO_LARGE", `\u6587\u4EF6\u8D85\u8FC7 ${effectiveKind === "text" ? "1MB" : "20MB"} \u9884\u89C8\u4E0A\u9650\uFF08\u5B9E\u9645 ${info.size} \u5B57\u8282\uFF09\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u67E5\u770B\u6216\u4E0B\u8F7D`, 415);
|
|
23448
|
+
}
|
|
22952
23449
|
const buffer = await readFile10(resolved.absolute);
|
|
22953
|
-
if (
|
|
22954
|
-
reply.header("Content-Type",
|
|
23450
|
+
if (effectiveKind === "image" || effectiveKind === "pdf") {
|
|
23451
|
+
reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
|
|
22955
23452
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
23453
|
+
if (isSvg) reply.header("Content-Security-Policy", "sandbox");
|
|
22956
23454
|
reply.header("Cache-Control", "private, max-age=60");
|
|
22957
23455
|
return reply.send(buffer);
|
|
22958
23456
|
}
|
|
23457
|
+
if (isBinaryBuffer(buffer)) {
|
|
23458
|
+
throw new RuntimeError("BINARY_FILE", "\u68C0\u6D4B\u5230\u4E8C\u8FDB\u5236\u6587\u4EF6\u5185\u5BB9\uFF0C\u6682\u4E0D\u652F\u6301\u6587\u672C\u9884\u89C8\uFF0C\u8BF7\u4E0B\u8F7D\u67E5\u770B", 415);
|
|
23459
|
+
}
|
|
22959
23460
|
return { cwd: session.cwd, path: resolved.relative, size: info.size, content: buffer.toString("utf8") };
|
|
22960
23461
|
});
|
|
22961
23462
|
}
|
|
@@ -23024,7 +23525,7 @@ async function readSseEvents(body, onEach) {
|
|
|
23024
23525
|
}
|
|
23025
23526
|
|
|
23026
23527
|
// src/llm/types.ts
|
|
23027
|
-
import { z as
|
|
23528
|
+
import { z as z7 } from "zod";
|
|
23028
23529
|
var llmFormats = ["openai-chat", "openai-responses", "anthropic-messages"];
|
|
23029
23530
|
var llmAuthTypes = ["api-key", "bearer"];
|
|
23030
23531
|
var llmErrorCodes = {
|
|
@@ -23041,20 +23542,20 @@ var llmErrorCodes = {
|
|
|
23041
23542
|
empty: "LLM_EMPTY_REPLY",
|
|
23042
23543
|
abandoned: "LLM_STREAM_ABANDONED"
|
|
23043
23544
|
};
|
|
23044
|
-
var baseUrlSchema =
|
|
23045
|
-
var apiKeySchema =
|
|
23046
|
-
var modelSchema =
|
|
23047
|
-
var llmEndpointInputSchema =
|
|
23048
|
-
format:
|
|
23545
|
+
var baseUrlSchema = z7.string().trim().min(1, "Base URL \u4E0D\u80FD\u4E3A\u7A7A");
|
|
23546
|
+
var apiKeySchema = z7.string();
|
|
23547
|
+
var modelSchema = z7.string().trim().min(1, "\u6A21\u578B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
23548
|
+
var llmEndpointInputSchema = z7.object({
|
|
23549
|
+
format: z7.enum(llmFormats),
|
|
23049
23550
|
baseUrl: baseUrlSchema,
|
|
23050
23551
|
apiKey: apiKeySchema.optional(),
|
|
23051
|
-
auth:
|
|
23552
|
+
auth: z7.enum(llmAuthTypes).optional(),
|
|
23052
23553
|
model: modelSchema,
|
|
23053
|
-
systemPrompt:
|
|
23054
|
-
maxTokens:
|
|
23554
|
+
systemPrompt: z7.string().optional(),
|
|
23555
|
+
maxTokens: z7.number().int().positive().optional(),
|
|
23055
23556
|
// 区间取三种格式的交集:Anthropic 只接受 0..1,照 0..2 校验会让用户在 anthropic 上撞 400。
|
|
23056
|
-
temperature:
|
|
23057
|
-
timeoutMs:
|
|
23557
|
+
temperature: z7.number().min(0).max(1).optional(),
|
|
23558
|
+
timeoutMs: z7.number().int().positive().optional()
|
|
23058
23559
|
});
|
|
23059
23560
|
function normalizeBaseUrl(input) {
|
|
23060
23561
|
const trimmed = input.trim();
|
|
@@ -23377,8 +23878,8 @@ var LlmClient = class {
|
|
|
23377
23878
|
|
|
23378
23879
|
// src/llm/detect.ts
|
|
23379
23880
|
import { readFile as readFile11 } from "node:fs/promises";
|
|
23380
|
-
import { homedir as
|
|
23381
|
-
import { join as
|
|
23881
|
+
import { homedir as homedir13 } from "node:os";
|
|
23882
|
+
import { join as join18 } from "node:path";
|
|
23382
23883
|
var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
23383
23884
|
async function readJson(path5) {
|
|
23384
23885
|
try {
|
|
@@ -23508,9 +24009,9 @@ function codexCandidate(configText, env) {
|
|
|
23508
24009
|
}
|
|
23509
24010
|
async function detectLlmEndpoints(options = {}) {
|
|
23510
24011
|
const env = options.env ?? process.env;
|
|
23511
|
-
const home = options.home ??
|
|
24012
|
+
const home = options.home ?? homedir13();
|
|
23512
24013
|
const candidates = [];
|
|
23513
|
-
const settings = await readJson(
|
|
24014
|
+
const settings = await readJson(join18(home, ".claude", "settings.json"));
|
|
23514
24015
|
const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
|
|
23515
24016
|
const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
|
|
23516
24017
|
if (fromSettings) candidates.push(fromSettings);
|
|
@@ -23518,7 +24019,7 @@ async function detectLlmEndpoints(options = {}) {
|
|
|
23518
24019
|
if (fromEnv) candidates.push(fromEnv);
|
|
23519
24020
|
const openai = openAiCandidate(env);
|
|
23520
24021
|
if (openai) candidates.push(openai);
|
|
23521
|
-
const codexConfig = await readText(
|
|
24022
|
+
const codexConfig = await readText(join18(home, ".codex", "config.toml"));
|
|
23522
24023
|
if (codexConfig) {
|
|
23523
24024
|
const codex = codexCandidate(codexConfig, env);
|
|
23524
24025
|
if (codex) candidates.push(codex);
|
|
@@ -23705,6 +24206,9 @@ data: ${JSON.stringify(data)}
|
|
|
23705
24206
|
});
|
|
23706
24207
|
}
|
|
23707
24208
|
|
|
24209
|
+
// src/app.ts
|
|
24210
|
+
init_side_chat_config();
|
|
24211
|
+
|
|
23708
24212
|
// src/json-compression.ts
|
|
23709
24213
|
import { promisify as promisify6 } from "node:util";
|
|
23710
24214
|
import { brotliCompress, constants as constants4, gzip } from "node:zlib";
|
|
@@ -23744,17 +24248,17 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
|
|
|
23744
24248
|
|
|
23745
24249
|
// src/web-password.ts
|
|
23746
24250
|
import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
23747
|
-
import { chmodSync as chmodSync2, existsSync as
|
|
23748
|
-
import { homedir as
|
|
23749
|
-
import { dirname as dirname11, join as
|
|
24251
|
+
import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
24252
|
+
import { homedir as homedir14 } from "node:os";
|
|
24253
|
+
import { dirname as dirname11, join as join19 } from "node:path";
|
|
23750
24254
|
var webPasswordFileName = "web-password";
|
|
23751
24255
|
var SCRYPT_N = 16384;
|
|
23752
24256
|
var SCRYPT_R = 8;
|
|
23753
24257
|
var SCRYPT_P = 1;
|
|
23754
24258
|
var KEY_LENGTH = 32;
|
|
23755
24259
|
var minWebPasswordLength = 6;
|
|
23756
|
-
function webPasswordPath(home =
|
|
23757
|
-
return
|
|
24260
|
+
function webPasswordPath(home = homedir14()) {
|
|
24261
|
+
return join19(home, ".agentdock", webPasswordFileName);
|
|
23758
24262
|
}
|
|
23759
24263
|
function hashWebPassword(password) {
|
|
23760
24264
|
const salt = randomBytes3(16);
|
|
@@ -23794,7 +24298,7 @@ function setWebPassword(password, path5 = webPasswordPath()) {
|
|
|
23794
24298
|
chmodSync2(path5, 384);
|
|
23795
24299
|
}
|
|
23796
24300
|
function clearWebPassword(path5 = webPasswordPath()) {
|
|
23797
|
-
if (!
|
|
24301
|
+
if (!existsSync9(path5)) return false;
|
|
23798
24302
|
rmSync3(path5, { force: true });
|
|
23799
24303
|
return true;
|
|
23800
24304
|
}
|
|
@@ -24259,6 +24763,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24259
24763
|
});
|
|
24260
24764
|
await registerFsRoutes(app, runtime);
|
|
24261
24765
|
await registerLlmRoutes(app, options.llm);
|
|
24766
|
+
if (options.sideChatConfig) registerSideChatConfigRoutes(app, options.sideChatConfig);
|
|
24262
24767
|
const mimeToExt = {
|
|
24263
24768
|
"image/png": ".png",
|
|
24264
24769
|
"image/jpeg": ".jpg",
|
|
@@ -24292,7 +24797,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24292
24797
|
"audio/flac": ".flac",
|
|
24293
24798
|
"application/octet-stream": ""
|
|
24294
24799
|
};
|
|
24295
|
-
const globalUploadRoot =
|
|
24800
|
+
const globalUploadRoot = join20(homedir15(), ".agentdock", "uploads");
|
|
24296
24801
|
const uploadTtlMs = 7 * 24 * 60 * 6e4;
|
|
24297
24802
|
const collectExpiredUploads = async (now2 = Date.now()) => {
|
|
24298
24803
|
let removedFiles = 0;
|
|
@@ -24303,7 +24808,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24303
24808
|
return { removedFiles };
|
|
24304
24809
|
}
|
|
24305
24810
|
for (const sessionDir of sessionDirs) {
|
|
24306
|
-
const directory =
|
|
24811
|
+
const directory = join20(globalUploadRoot, sessionDir);
|
|
24307
24812
|
let names;
|
|
24308
24813
|
try {
|
|
24309
24814
|
names = await readdir4(directory);
|
|
@@ -24311,7 +24816,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24311
24816
|
continue;
|
|
24312
24817
|
}
|
|
24313
24818
|
for (const name of names) {
|
|
24314
|
-
const filePath =
|
|
24819
|
+
const filePath = join20(directory, name);
|
|
24315
24820
|
try {
|
|
24316
24821
|
const info = await stat5(filePath);
|
|
24317
24822
|
if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
|
|
@@ -24357,10 +24862,10 @@ async function buildApp(runtime, options = {}) {
|
|
|
24357
24862
|
originalName = rawName;
|
|
24358
24863
|
}
|
|
24359
24864
|
const ext = extFromContentType(contentType, originalName);
|
|
24360
|
-
const uploadDir =
|
|
24865
|
+
const uploadDir = join20(globalUploadRoot, session.id);
|
|
24361
24866
|
await mkdir4(uploadDir, { recursive: true });
|
|
24362
24867
|
const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
|
|
24363
|
-
const filePath =
|
|
24868
|
+
const filePath = join20(uploadDir, filename);
|
|
24364
24869
|
await writeFile4(filePath, buffer);
|
|
24365
24870
|
return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
|
|
24366
24871
|
});
|
|
@@ -24371,13 +24876,14 @@ async function buildApp(runtime, options = {}) {
|
|
|
24371
24876
|
if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
|
|
24372
24877
|
throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
|
|
24373
24878
|
}
|
|
24374
|
-
const filePath =
|
|
24879
|
+
const filePath = join20(globalUploadRoot, session.id, filename);
|
|
24375
24880
|
const ext = extname2(filename).toLowerCase();
|
|
24376
24881
|
const data = await readFile12(filePath);
|
|
24377
24882
|
reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
|
|
24378
24883
|
reply.header("Cache-Control", "public, max-age=31536000, immutable");
|
|
24379
24884
|
reply.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
24380
24885
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
24886
|
+
if (ext === ".svg") reply.header("Content-Security-Policy", "sandbox");
|
|
24381
24887
|
return reply.send(data);
|
|
24382
24888
|
});
|
|
24383
24889
|
app.get("/api/sessions/:id/stream", async (request, reply) => {
|
|
@@ -24428,7 +24934,7 @@ data: ${JSON.stringify(event)}
|
|
|
24428
24934
|
} catch {
|
|
24429
24935
|
return reply.code(400).send({ error: { code: "INVALID_PATH", message: "Invalid URL path" } });
|
|
24430
24936
|
}
|
|
24431
|
-
if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${
|
|
24937
|
+
if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${sep3}`)) return reply.code(404).send();
|
|
24432
24938
|
let file = requestedFile;
|
|
24433
24939
|
let body;
|
|
24434
24940
|
try {
|
|
@@ -24456,6 +24962,7 @@ init_handover_binding();
|
|
|
24456
24962
|
init_agent_tools();
|
|
24457
24963
|
init_config();
|
|
24458
24964
|
init_service();
|
|
24965
|
+
init_side_chat_config();
|
|
24459
24966
|
|
|
24460
24967
|
// src/lark-avatar/service.ts
|
|
24461
24968
|
init_src2();
|
|
@@ -30974,12 +31481,12 @@ function withContext(percent2) {
|
|
|
30974
31481
|
// src/assistant/cwd.ts
|
|
30975
31482
|
init_src2();
|
|
30976
31483
|
import { accessSync as accessSync2, constants as constants5, statSync as statSync5 } from "node:fs";
|
|
30977
|
-
import { homedir as
|
|
31484
|
+
import { homedir as homedir16 } from "node:os";
|
|
30978
31485
|
import { isAbsolute as isAbsolute8, resolve as resolve11 } from "node:path";
|
|
30979
31486
|
function expandHomePath(value) {
|
|
30980
31487
|
const trimmed = value.trim();
|
|
30981
|
-
if (trimmed === "~") return
|
|
30982
|
-
if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve11(
|
|
31488
|
+
if (trimmed === "~") return homedir16();
|
|
31489
|
+
if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve11(homedir16(), trimmed.slice(2));
|
|
30983
31490
|
return trimmed;
|
|
30984
31491
|
}
|
|
30985
31492
|
function resolveCwdArgument(value, base = process.cwd()) {
|
|
@@ -32373,6 +32880,7 @@ async function startLocalServer(options = {}) {
|
|
|
32373
32880
|
}
|
|
32374
32881
|
const webRoot = options.webRoot ?? fileURLToPath5(new URL("../public", import.meta.url));
|
|
32375
32882
|
const llm = new LlmEndpointService({ config: repos.config });
|
|
32883
|
+
const sideChatConfig = new SideChatConfigService({ config: repos.config, listAgents: () => runtime.listAgents() });
|
|
32376
32884
|
const packageJson2 = JSON.parse(readFileSync9(new URL("../package.json", import.meta.url), "utf8"));
|
|
32377
32885
|
const selfUpdate = options.cliEntrypoint ? new SelfUpdateService({ currentVersion: packageJson2.version, packageName: packageJson2.name, cliEntrypoint: options.cliEntrypoint, env }) : void 0;
|
|
32378
32886
|
schedules2 = new ScheduleService(repos.schedules, repos.sessions, runtime);
|
|
@@ -32425,7 +32933,7 @@ async function startLocalServer(options = {}) {
|
|
|
32425
32933
|
keepAwake = new KeepAwakeService({ config: repos.config });
|
|
32426
32934
|
await keepAwake.restore();
|
|
32427
32935
|
const shareLinks = new ShareLinkService({ host: config.host, port: config.port, secret: webAuth.secret ?? "", config: repos.config, env });
|
|
32428
|
-
app = await buildApp(runtime, { webRoot, webAuth, shareLinks, schedules: schedules2, ...assistant ? { assistant } : {}, ...selfUpdate ? { selfUpdate } : {}, system: { keepAwake, ...autostart ? { autostart } : {} }, llm: { service: llm }, lark: { env, config: repos.config, agents: repos.agents, cardMappings: repos.channelMappings, runtime, agentTools, listeningDisabled: env.AGENTDOCK_DISABLE_LARK_LISTENER === "true" }, larkAvatar });
|
|
32936
|
+
app = await buildApp(runtime, { webRoot, webAuth, shareLinks, schedules: schedules2, ...assistant ? { assistant } : {}, ...selfUpdate ? { selfUpdate } : {}, system: { keepAwake, ...autostart ? { autostart } : {} }, llm: { service: llm }, sideChatConfig, lark: { env, config: repos.config, agents: repos.agents, cardMappings: repos.channelMappings, runtime, agentTools, listeningDisabled: env.AGENTDOCK_DISABLE_LARK_LISTENER === "true" }, larkAvatar });
|
|
32429
32937
|
await app.listen(listenOptions(config));
|
|
32430
32938
|
schedules2.start();
|
|
32431
32939
|
assistant?.start();
|
|
@@ -32509,7 +33017,7 @@ init_session_cli();
|
|
|
32509
33017
|
init_config();
|
|
32510
33018
|
init_message_content();
|
|
32511
33019
|
init_service();
|
|
32512
|
-
import { existsSync as
|
|
33020
|
+
import { existsSync as existsSync11 } from "node:fs";
|
|
32513
33021
|
var output = (deps) => deps.stdout ?? process.stdout;
|
|
32514
33022
|
var errorOutput = (deps) => deps.stderr ?? process.stderr;
|
|
32515
33023
|
var envOf = (deps) => deps.env ?? process.env;
|
|
@@ -32521,7 +33029,7 @@ var noBotError = () => new Error(
|
|
|
32521
33029
|
async function loadStoredConfigs(deps) {
|
|
32522
33030
|
if (deps.configs) return deps.configs;
|
|
32523
33031
|
const filename = resolveDatabasePath();
|
|
32524
|
-
if (!
|
|
33032
|
+
if (!existsSync11(filename)) return [];
|
|
32525
33033
|
try {
|
|
32526
33034
|
const repositories = createRepositories(filename);
|
|
32527
33035
|
try {
|
|
@@ -33477,25 +33985,25 @@ init_session_cli();
|
|
|
33477
33985
|
|
|
33478
33986
|
// src/dev-sandbox.ts
|
|
33479
33987
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
33480
|
-
import { chmodSync as chmodSync3, existsSync as
|
|
33988
|
+
import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
|
|
33481
33989
|
import { createServer } from "node:net";
|
|
33482
|
-
import { delimiter as delimiter2, dirname as dirname13, join as
|
|
33990
|
+
import { delimiter as delimiter2, dirname as dirname13, join as join22, resolve as resolve15 } from "node:path";
|
|
33483
33991
|
init_daemon();
|
|
33484
33992
|
var SANDBOX_FILE = "sandbox.json";
|
|
33485
33993
|
function findRepoRoot(start = process.cwd()) {
|
|
33486
33994
|
let dir = resolve15(start);
|
|
33487
33995
|
for (; ; ) {
|
|
33488
|
-
if (
|
|
33996
|
+
if (existsSync12(join22(dir, "apps", "server", "package.json")) && existsSync12(join22(dir, "pnpm-workspace.yaml"))) return dir;
|
|
33489
33997
|
const parent = dirname13(dir);
|
|
33490
33998
|
if (parent === dir) throw new Error("\u627E\u4E0D\u5230 agent-dock \u6E90\u7801\u4ED3\u5E93\u3002\u8BF7\u5728\u4ED3\u5E93\u76EE\u5F55\u4E0B\u8FD0\u884C agent-dock dev\uFF0C\u6216\u7528 --repo \u6307\u5B9A\u3002");
|
|
33491
33999
|
dir = parent;
|
|
33492
34000
|
}
|
|
33493
34001
|
}
|
|
33494
34002
|
function sandboxPaths(repo, port) {
|
|
33495
|
-
const root4 =
|
|
33496
|
-
return { root: root4, home:
|
|
34003
|
+
const root4 = join22(repo, ".agentdock", "dev");
|
|
34004
|
+
return { root: root4, home: join22(root4, "home"), work: join22(root4, "work"), database: join22(root4, "agentdock.db"), entrypoint: join22(repo, "apps", "server", "dist", "cli.js"), port };
|
|
33497
34005
|
}
|
|
33498
|
-
var shimDir = (sandbox) =>
|
|
34006
|
+
var shimDir = (sandbox) => join22(sandbox.root, "bin");
|
|
33499
34007
|
function sandboxEnv(sandbox, base = process.env) {
|
|
33500
34008
|
const env = {
|
|
33501
34009
|
...base,
|
|
@@ -33518,7 +34026,7 @@ function writeCliShim(sandbox, node = process.execPath) {
|
|
|
33518
34026
|
if (process.platform === "win32") return;
|
|
33519
34027
|
const dir = shimDir(sandbox);
|
|
33520
34028
|
mkdirSync6(dir, { recursive: true });
|
|
33521
|
-
const file =
|
|
34029
|
+
const file = join22(dir, "agent-dock");
|
|
33522
34030
|
writeFileSync5(file, `#!/bin/sh
|
|
33523
34031
|
exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
33524
34032
|
`);
|
|
@@ -33526,7 +34034,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
|
33526
34034
|
}
|
|
33527
34035
|
function readSandbox(repo) {
|
|
33528
34036
|
try {
|
|
33529
|
-
return JSON.parse(readFileSync13(
|
|
34037
|
+
return JSON.parse(readFileSync13(join22(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
|
|
33530
34038
|
} catch {
|
|
33531
34039
|
return void 0;
|
|
33532
34040
|
}
|
|
@@ -33551,9 +34059,9 @@ async function devUp(options = {}) {
|
|
|
33551
34059
|
const existing = readSandbox(repo);
|
|
33552
34060
|
const port = existing?.port ?? options.port ?? await freePort(4399);
|
|
33553
34061
|
const sandbox = sandboxPaths(repo, port);
|
|
33554
|
-
if (!
|
|
34062
|
+
if (!existsSync12(sandbox.entrypoint)) throw new Error(`\u6CA1\u6709\u6784\u5EFA\u4EA7\u7269\uFF1A${sandbox.entrypoint}\u3002\u5148\u5728\u4ED3\u5E93\u6839\u76EE\u5F55\u8FD0\u884C pnpm build\u3002`);
|
|
33555
34063
|
for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
|
|
33556
|
-
writeFileSync5(
|
|
34064
|
+
writeFileSync5(join22(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
|
|
33557
34065
|
`);
|
|
33558
34066
|
writeCliShim(sandbox);
|
|
33559
34067
|
const run2 = options.run ?? defaultRun;
|
|
@@ -35166,7 +35674,7 @@ async function serve(options, onReady) {
|
|
|
35166
35674
|
});
|
|
35167
35675
|
}
|
|
35168
35676
|
async function restartWithInstalledCli(entrypoint) {
|
|
35169
|
-
if (!
|
|
35677
|
+
if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
|
|
35170
35678
|
const previousPid = daemonStatus().pid;
|
|
35171
35679
|
const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
|
|
35172
35680
|
await new Promise((resolve17, reject2) => {
|