@agent-dock/cli 0.3.14 → 0.3.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +838 -294
- 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-BRhFNVMj.js} +1 -1
- package/public/assets/{PromptEditor-CTuIApSy.js → PromptEditor-BE2x7r9R.js} +1 -1
- package/public/assets/index-Qk8aqJbd.css +1 -0
- package/public/assets/main-Bpox_eUq.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
|
@@ -979,11 +979,11 @@ var init_sdk = __esm({
|
|
|
979
979
|
|
|
980
980
|
// src/abortable.ts
|
|
981
981
|
function abortable(operation, signal) {
|
|
982
|
-
return new Promise((
|
|
982
|
+
return new Promise((resolve17, reject2) => {
|
|
983
983
|
const abort = () => reject2(signal.reason);
|
|
984
984
|
if (signal.aborted) abort();
|
|
985
985
|
else signal.addEventListener("abort", abort, { once: true });
|
|
986
|
-
operation.then(
|
|
986
|
+
operation.then(resolve17, reject2).finally(() => signal.removeEventListener("abort", abort));
|
|
987
987
|
});
|
|
988
988
|
}
|
|
989
989
|
var init_abortable = __esm({
|
|
@@ -994,7 +994,7 @@ var init_abortable = __esm({
|
|
|
994
994
|
|
|
995
995
|
// src/daemon/time.ts
|
|
996
996
|
function sleep(ms) {
|
|
997
|
-
return new Promise((
|
|
997
|
+
return new Promise((resolve17) => setTimeout(resolve17, ms));
|
|
998
998
|
}
|
|
999
999
|
var init_time = __esm({
|
|
1000
1000
|
"src/daemon/time.ts"() {
|
|
@@ -1092,7 +1092,7 @@ function sessionTokenAllows(method, pathname, sessionId, search) {
|
|
|
1092
1092
|
if (pathname === `/api/sessions/${sessionId}` || pathname.startsWith(`/api/sessions/${sessionId}/`)) return true;
|
|
1093
1093
|
if (method !== "GET" && method !== "HEAD") return false;
|
|
1094
1094
|
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";
|
|
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" || pathname === "/api/side-chat/config";
|
|
1096
1096
|
}
|
|
1097
1097
|
var webAccessSecretConfigKey, webAccessCookieName, webAccessSessionCookieName, defaultSessionTokenTtlMs, defaultMasterTokenTtlMs, activeState;
|
|
1098
1098
|
var init_web_access = __esm({
|
|
@@ -2333,7 +2333,7 @@ var init_message_content = __esm({
|
|
|
2333
2333
|
|
|
2334
2334
|
// src/lark/config.ts
|
|
2335
2335
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
2336
|
-
import { isAbsolute as
|
|
2336
|
+
import { isAbsolute as isAbsolute3 } from "node:path";
|
|
2337
2337
|
function normalizeStoredConfig(parsed) {
|
|
2338
2338
|
if (!parsed.appId || !parsed.appSecret) return void 0;
|
|
2339
2339
|
const pushIntervalMs = Number(parsed.pushIntervalMs ?? defaultLarkPushIntervalMs);
|
|
@@ -2466,7 +2466,7 @@ async function saveLarkConfigAttempt(repository, agents, input) {
|
|
|
2466
2466
|
if (!appSecret) throw new LarkServiceError("INVALID_LARK_CONFIG", "App Secret is required", 400);
|
|
2467
2467
|
if (input.stage === "agent" && !defaultAgentId) throw new LarkServiceError("INVALID_LARK_CONFIG", "Default Agent is required", 400);
|
|
2468
2468
|
if (current?.hardGateEnabled && defaultAgentId !== current.defaultAgentId) throw new LarkServiceError("HARD_GATE_AGENT_LOCKED", "Disable and save the hard gate before changing the default Agent", 409);
|
|
2469
|
-
if (workspace && !
|
|
2469
|
+
if (workspace && !isAbsolute3(workspace)) throw new LarkServiceError("INVALID_LARK_CONFIG", "Workspace must be an absolute path", 400);
|
|
2470
2470
|
if (!Number.isInteger(pushIntervalMs) || pushIntervalMs < 500 || pushIntervalMs > 2e4) throw new LarkServiceError("INVALID_LARK_CONFIG", "Push interval must be an integer between 500 and 20000 milliseconds", 400);
|
|
2471
2471
|
if (!Number.isInteger(traceLimit) || traceLimit < 1) throw new LarkServiceError("INVALID_LARK_CONFIG", "Trace limit must be a positive integer", 400);
|
|
2472
2472
|
const patternValidation = validateHighRiskPattern(highRiskPattern);
|
|
@@ -2719,7 +2719,7 @@ var init_access_config = __esm({
|
|
|
2719
2719
|
// src/lark/agent-tools.ts
|
|
2720
2720
|
import { createHmac as createHmac2, randomBytes as randomBytes2, randomUUID as randomUUID4 } from "node:crypto";
|
|
2721
2721
|
import { readFile as readFile3, stat as stat2 } from "node:fs/promises";
|
|
2722
|
-
import { isAbsolute as
|
|
2722
|
+
import { isAbsolute as isAbsolute4, resolve as resolve6 } from "node:path";
|
|
2723
2723
|
function larkAgentSessionBinding(session) {
|
|
2724
2724
|
if (session.source !== "lark" || !session.sourceId) return;
|
|
2725
2725
|
const parts = session.sourceId.split(":");
|
|
@@ -3203,7 +3203,7 @@ ${prompt}`;
|
|
|
3203
3203
|
if (result.messages.length) return result;
|
|
3204
3204
|
const remaining = deadline - Date.now();
|
|
3205
3205
|
if (remaining <= 0) return { ...result, timedOut: true };
|
|
3206
|
-
await new Promise((
|
|
3206
|
+
await new Promise((resolve17) => setTimeout(resolve17, Math.min(this.pollIntervalMs, remaining)));
|
|
3207
3207
|
}
|
|
3208
3208
|
}
|
|
3209
3209
|
/**
|
|
@@ -3248,7 +3248,7 @@ ${prompt}`;
|
|
|
3248
3248
|
const name = (trimmed.split("/").pop() || "").split("?")[0] || filenameHint;
|
|
3249
3249
|
return { bytes: buffer, filename: name };
|
|
3250
3250
|
}
|
|
3251
|
-
const filePath =
|
|
3251
|
+
const filePath = isAbsolute4(trimmed) ? trimmed : baseDir ? resolve6(baseDir, trimmed) : trimmed;
|
|
3252
3252
|
try {
|
|
3253
3253
|
const info = await stat2(filePath);
|
|
3254
3254
|
if (!info.isFile()) throw new Error("not a file");
|
|
@@ -3360,7 +3360,7 @@ ${prompt}`;
|
|
|
3360
3360
|
};
|
|
3361
3361
|
shellQuote2 = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
3362
3362
|
agentDockGroupToolsCommand = (entrypoint, execPath = process.execPath, tsxLoader) => {
|
|
3363
|
-
const absoluteEntrypoint =
|
|
3363
|
+
const absoluteEntrypoint = resolve6(entrypoint);
|
|
3364
3364
|
const loader = absoluteEntrypoint.endsWith(".ts") ? tsxLoader ?? import.meta.resolve("tsx") : void 0;
|
|
3365
3365
|
return `${shellQuote2(execPath)}${loader ? ` --import ${shellQuote2(loader)}` : ""} ${shellQuote2(absoluteEntrypoint)}`;
|
|
3366
3366
|
};
|
|
@@ -3421,6 +3421,157 @@ var init_handover_binding = __esm({
|
|
|
3421
3421
|
}
|
|
3422
3422
|
});
|
|
3423
3423
|
|
|
3424
|
+
// src/side-chat-config.ts
|
|
3425
|
+
import { z as z4 } from "zod";
|
|
3426
|
+
function normalizeSideChatConfig(input) {
|
|
3427
|
+
const base = {
|
|
3428
|
+
targetMode: input.targetMode,
|
|
3429
|
+
openMode: input.openMode,
|
|
3430
|
+
btwEnabled: input.btwEnabled,
|
|
3431
|
+
triggerPrefix: input.triggerPrefix.trim() || defaultSideChatTriggerPrefix,
|
|
3432
|
+
btwSessionReuse: input.btwSessionReuse
|
|
3433
|
+
};
|
|
3434
|
+
if (input.targetMode === "custom_agent") {
|
|
3435
|
+
return {
|
|
3436
|
+
...base,
|
|
3437
|
+
...input.agentId ? { agentId: input.agentId } : {},
|
|
3438
|
+
...input.model ? { model: input.model } : {},
|
|
3439
|
+
...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {}
|
|
3440
|
+
};
|
|
3441
|
+
}
|
|
3442
|
+
return base;
|
|
3443
|
+
}
|
|
3444
|
+
function matchSideChatTrigger(input, triggerPrefix = defaultSideChatTriggerPrefix) {
|
|
3445
|
+
const prefix = triggerPrefix.trim() || defaultSideChatTriggerPrefix;
|
|
3446
|
+
const trimmed = input.trim();
|
|
3447
|
+
if (!trimmed) return { matched: false };
|
|
3448
|
+
const needsBoundary = /[A-Za-z0-9_]$/.test(prefix);
|
|
3449
|
+
const pattern = needsBoundary ? new RegExp(`^${escapeRegExp(prefix)}(?:\\s+([\\s\\S]*))?$`, "i") : new RegExp(`^${escapeRegExp(prefix)}\\s*([\\s\\S]*)$`, "i");
|
|
3450
|
+
const match = pattern.exec(trimmed);
|
|
3451
|
+
if (!match) return { matched: false };
|
|
3452
|
+
return { matched: true, prompt: (match[1] ?? "").trim() };
|
|
3453
|
+
}
|
|
3454
|
+
function buildSideSessionSeed(mainSessionId) {
|
|
3455
|
+
return [
|
|
3456
|
+
`\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`,
|
|
3457
|
+
"\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",
|
|
3458
|
+
`\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`
|
|
3459
|
+
].join("\n");
|
|
3460
|
+
}
|
|
3461
|
+
async function readSideChatConfig(config) {
|
|
3462
|
+
if (!config) return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3463
|
+
const raw = await config.get(sideChatConfigKey);
|
|
3464
|
+
if (!raw?.trim()) return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3465
|
+
try {
|
|
3466
|
+
const parsed = sideChatConfigInputSchema.safeParse(JSON.parse(raw));
|
|
3467
|
+
return parsed.success ? normalizeSideChatConfig(parsed.data) : { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3468
|
+
} catch {
|
|
3469
|
+
return { ...DEFAULT_SIDE_CHAT_CONFIG };
|
|
3470
|
+
}
|
|
3471
|
+
}
|
|
3472
|
+
function registerSideChatConfigRoutes(app, service) {
|
|
3473
|
+
app.get("/api/side-chat/config", async () => service.state());
|
|
3474
|
+
app.put("/api/side-chat/config", async (request) => service.save(request.body));
|
|
3475
|
+
app.delete("/api/side-chat/config", async () => service.reset());
|
|
3476
|
+
}
|
|
3477
|
+
var sideChatConfigKey, sideChatTargetModes, sideChatOpenModes, btwSessionReuseModes, optionalTrimmedString, defaultSideChatTriggerPrefix, triggerPrefixSchema, sideChatConfigInputSchema, DEFAULT_SIDE_CHAT_CONFIG, escapeRegExp, SideChatConfigService;
|
|
3478
|
+
var init_side_chat_config = __esm({
|
|
3479
|
+
"src/side-chat-config.ts"() {
|
|
3480
|
+
"use strict";
|
|
3481
|
+
init_src2();
|
|
3482
|
+
sideChatConfigKey = "side_chat.config";
|
|
3483
|
+
sideChatTargetModes = ["follow_current", "custom_agent"];
|
|
3484
|
+
sideChatOpenModes = ["side_pane", "switch_session"];
|
|
3485
|
+
btwSessionReuseModes = ["new_session", "reuse_latest"];
|
|
3486
|
+
optionalTrimmedString = z4.preprocess(
|
|
3487
|
+
(value) => {
|
|
3488
|
+
if (typeof value !== "string") return value;
|
|
3489
|
+
const trimmed = value.trim();
|
|
3490
|
+
return trimmed ? trimmed : void 0;
|
|
3491
|
+
},
|
|
3492
|
+
z4.string().max(200).optional()
|
|
3493
|
+
);
|
|
3494
|
+
defaultSideChatTriggerPrefix = "/btw";
|
|
3495
|
+
triggerPrefixSchema = z4.preprocess(
|
|
3496
|
+
(value) => {
|
|
3497
|
+
if (value === void 0 || value === null) return defaultSideChatTriggerPrefix;
|
|
3498
|
+
if (typeof value !== "string") return value;
|
|
3499
|
+
const trimmed = value.trim();
|
|
3500
|
+
return trimmed || defaultSideChatTriggerPrefix;
|
|
3501
|
+
},
|
|
3502
|
+
z4.string().min(1).max(32)
|
|
3503
|
+
);
|
|
3504
|
+
sideChatConfigInputSchema = z4.object({
|
|
3505
|
+
targetMode: z4.enum(sideChatTargetModes).default("follow_current"),
|
|
3506
|
+
agentId: optionalTrimmedString,
|
|
3507
|
+
model: optionalTrimmedString,
|
|
3508
|
+
reasoningEffort: optionalTrimmedString,
|
|
3509
|
+
openMode: z4.enum(sideChatOpenModes).default("side_pane"),
|
|
3510
|
+
btwEnabled: z4.boolean().default(true),
|
|
3511
|
+
triggerPrefix: triggerPrefixSchema.default(defaultSideChatTriggerPrefix),
|
|
3512
|
+
btwSessionReuse: z4.enum(btwSessionReuseModes).default("new_session")
|
|
3513
|
+
});
|
|
3514
|
+
DEFAULT_SIDE_CHAT_CONFIG = {
|
|
3515
|
+
targetMode: "follow_current",
|
|
3516
|
+
openMode: "side_pane",
|
|
3517
|
+
btwEnabled: true,
|
|
3518
|
+
triggerPrefix: defaultSideChatTriggerPrefix,
|
|
3519
|
+
btwSessionReuse: "new_session"
|
|
3520
|
+
};
|
|
3521
|
+
escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3522
|
+
SideChatConfigService = class {
|
|
3523
|
+
constructor(options) {
|
|
3524
|
+
this.options = options;
|
|
3525
|
+
}
|
|
3526
|
+
options;
|
|
3527
|
+
/** 读配置;库里没有或损坏时安全回退默认配置,不让前端 500。 */
|
|
3528
|
+
async state() {
|
|
3529
|
+
const raw = await this.options.config.get(sideChatConfigKey);
|
|
3530
|
+
if (!raw?.trim()) return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3531
|
+
try {
|
|
3532
|
+
const parsed = sideChatConfigInputSchema.safeParse(JSON.parse(raw));
|
|
3533
|
+
if (!parsed.success) return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3534
|
+
return { configured: true, config: normalizeSideChatConfig(parsed.data) };
|
|
3535
|
+
} catch {
|
|
3536
|
+
return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3537
|
+
}
|
|
3538
|
+
}
|
|
3539
|
+
async get() {
|
|
3540
|
+
return (await this.state()).config;
|
|
3541
|
+
}
|
|
3542
|
+
async save(input) {
|
|
3543
|
+
const parsed = sideChatConfigInputSchema.safeParse(input);
|
|
3544
|
+
if (!parsed.success) {
|
|
3545
|
+
throw new RuntimeError(
|
|
3546
|
+
"INVALID_SIDE_CHAT_CONFIG",
|
|
3547
|
+
`\u4FA7\u8FB9\u5BF9\u8BDD\u914D\u7F6E\u4E0D\u5408\u6CD5\uFF1A${parsed.error.issues.map((issue) => `${issue.path.join(".") || "body"} ${issue.message}`).join("\uFF1B")}`,
|
|
3548
|
+
400
|
|
3549
|
+
);
|
|
3550
|
+
}
|
|
3551
|
+
const normalized2 = normalizeSideChatConfig(parsed.data);
|
|
3552
|
+
if (normalized2.targetMode === "custom_agent") {
|
|
3553
|
+
if (!normalized2.agentId) {
|
|
3554
|
+
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);
|
|
3555
|
+
}
|
|
3556
|
+
if (this.options.listAgents) {
|
|
3557
|
+
const agents = await this.options.listAgents();
|
|
3558
|
+
const found = agents.find((agent) => agent.id === normalized2.agentId && !agent.disabled);
|
|
3559
|
+
if (!found) {
|
|
3560
|
+
throw new RuntimeError("SIDE_CHAT_AGENT_NOT_FOUND", `\u6307\u5B9A\u7684 Agent \u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528\uFF1A${normalized2.agentId}`, 400);
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
await this.options.config.set(sideChatConfigKey, JSON.stringify(normalized2));
|
|
3565
|
+
return { configured: true, config: normalized2 };
|
|
3566
|
+
}
|
|
3567
|
+
async reset() {
|
|
3568
|
+
await this.options.config.set(sideChatConfigKey, "");
|
|
3569
|
+
return { configured: false, config: { ...DEFAULT_SIDE_CHAT_CONFIG } };
|
|
3570
|
+
}
|
|
3571
|
+
};
|
|
3572
|
+
}
|
|
3573
|
+
});
|
|
3574
|
+
|
|
3424
3575
|
// src/lark/listener.ts
|
|
3425
3576
|
var listener_exports = {};
|
|
3426
3577
|
__export(listener_exports, {
|
|
@@ -3433,6 +3584,7 @@ __export(listener_exports, {
|
|
|
3433
3584
|
isLarkMessageUnupdatable: () => isLarkMessageUnupdatable,
|
|
3434
3585
|
larkHandoverChannel: () => larkHandoverChannel,
|
|
3435
3586
|
larkRateLimitBackoffMs: () => larkRateLimitBackoffMs,
|
|
3587
|
+
larkSideChatThreadChannel: () => larkSideChatThreadChannel,
|
|
3436
3588
|
parseLarkReactionEvent: () => parseLarkReactionEvent,
|
|
3437
3589
|
patchRejectedCardDelta: () => patchRejectedCardDelta,
|
|
3438
3590
|
renderLarkCardElements: () => renderLarkCardElements,
|
|
@@ -3474,12 +3626,16 @@ function renderPromptMentions(text3, mentions, isSelfMention) {
|
|
|
3474
3626
|
return text3;
|
|
3475
3627
|
}
|
|
3476
3628
|
async function parsePrompt(event, selfMention, service, trace) {
|
|
3477
|
-
const { log, appId } = trace ?? {};
|
|
3629
|
+
const { log, appId, stripSideChatTriggerPrefix } = trace ?? {};
|
|
3478
3630
|
const parsed = await parseLarkMessageContent(event.messageType, event.content, {
|
|
3479
3631
|
messageId: event.messageId
|
|
3480
3632
|
});
|
|
3481
3633
|
let text3 = renderPromptMentions(parsed.text, event.mentions, selfMention);
|
|
3482
3634
|
text3 = text3.trim();
|
|
3635
|
+
if (stripSideChatTriggerPrefix) {
|
|
3636
|
+
const matched = matchSideChatTrigger(text3, stripSideChatTriggerPrefix);
|
|
3637
|
+
if (matched.matched) text3 = matched.prompt;
|
|
3638
|
+
}
|
|
3483
3639
|
const quotedResources = [];
|
|
3484
3640
|
const [senderName, parentIdBlock] = await Promise.all([
|
|
3485
3641
|
(async () => {
|
|
@@ -3571,7 +3727,7 @@ async function materializeLarkResources(messageId, prompt, resources, service) {
|
|
|
3571
3727
|
${notes.join("\n")}`.trim();
|
|
3572
3728
|
}
|
|
3573
3729
|
async function sendTaskCard(service, event, input, log) {
|
|
3574
|
-
if (event.chatType === "group" && typeof service.reply === "function") {
|
|
3730
|
+
if ((event.chatType === "group" || input.replyInThread) && typeof service.reply === "function") {
|
|
3575
3731
|
try {
|
|
3576
3732
|
return await service.reply({ ...larkReplyContext(event), ...input });
|
|
3577
3733
|
} catch (error) {
|
|
@@ -3592,11 +3748,11 @@ async function sendPersistedTaskCard(service, persisted, input, log) {
|
|
|
3592
3748
|
}
|
|
3593
3749
|
return await service.send({ chatId: persisted.chat_id, ...input });
|
|
3594
3750
|
}
|
|
3595
|
-
async function sendQuietFinalReply(service, event, text3, log) {
|
|
3751
|
+
async function sendQuietFinalReply(service, event, text3, log, forceReplyInThread) {
|
|
3596
3752
|
const content = text3.trim() || "\uFF08Agent \u672A\u8FD4\u56DE\u6700\u7EC8\u8F93\u51FA\uFF09";
|
|
3597
|
-
if (event.chatType === "group" && typeof service.replyText === "function") {
|
|
3753
|
+
if ((event.chatType === "group" || forceReplyInThread) && typeof service.replyText === "function") {
|
|
3598
3754
|
try {
|
|
3599
|
-
await service.replyText({ messageId: event.messageId, text: content, ...event.threadId?.trim() ? { replyInThread: true } : {} });
|
|
3755
|
+
await service.replyText({ messageId: event.messageId, text: content, ...forceReplyInThread || event.threadId?.trim() ? { replyInThread: true } : {} });
|
|
3600
3756
|
return;
|
|
3601
3757
|
} catch (error) {
|
|
3602
3758
|
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 +3764,7 @@ async function deliverTaskFailure(service, event, config, input, log) {
|
|
|
3608
3764
|
if (config.quietReply) {
|
|
3609
3765
|
const markdown = typeof input.markdown === "string" ? input.markdown : "";
|
|
3610
3766
|
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);
|
|
3767
|
+
await sendQuietFinalReply(service, event, text3, log, input.replyInThread);
|
|
3612
3768
|
return { messageId: "" };
|
|
3613
3769
|
}
|
|
3614
3770
|
return await sendTaskCard(service, event, input, log);
|
|
@@ -3724,7 +3880,7 @@ ${data.message ?? "Agent \u6267\u884C\u5931\u8D25"}`;
|
|
|
3724
3880
|
return "";
|
|
3725
3881
|
}).filter(Boolean).join("\n\n---\n\n");
|
|
3726
3882
|
}
|
|
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;
|
|
3883
|
+
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
3884
|
var init_listener = __esm({
|
|
3729
3885
|
"src/lark/listener.ts"() {
|
|
3730
3886
|
"use strict";
|
|
@@ -3735,6 +3891,7 @@ var init_listener = __esm({
|
|
|
3735
3891
|
init_service();
|
|
3736
3892
|
init_agent_tools();
|
|
3737
3893
|
init_handover_binding();
|
|
3894
|
+
init_side_chat_config();
|
|
3738
3895
|
init_src2();
|
|
3739
3896
|
init_handover_binding();
|
|
3740
3897
|
acknowledgementEmojis = ["OK", "THUMBSUP", "FINGERHEART", "APPLAUSE", "JIAYI"];
|
|
@@ -3744,6 +3901,7 @@ var init_listener = __esm({
|
|
|
3744
3901
|
larkReconnectMultiplier = 2;
|
|
3745
3902
|
larkReconnectCooldownMs = 6e4;
|
|
3746
3903
|
larkCardChannel = (appId) => `lark-card:${appId}`;
|
|
3904
|
+
larkSideChatThreadChannel = (appId) => `lark-side-chat:${appId}`;
|
|
3747
3905
|
terminalTaskStates = /* @__PURE__ */ new Set(["completed", "failed", "interrupted", "cancelled"]);
|
|
3748
3906
|
maxChatNamePages = 5;
|
|
3749
3907
|
chatNamesTimeoutMs = 2e3;
|
|
@@ -4100,6 +4258,8 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4100
4258
|
groups = /* @__PURE__ */ new Map();
|
|
4101
4259
|
tasks = /* @__PURE__ */ new Map();
|
|
4102
4260
|
handledMessages = /* @__PURE__ */ new Set();
|
|
4261
|
+
/** 飞书侧聊话题映射(`${appId}:${rootId|threadId}` -> sideChatSessionId),与 cardMappings 双写。 */
|
|
4262
|
+
sideChatThreads = /* @__PURE__ */ new Map();
|
|
4103
4263
|
reconcileTimer;
|
|
4104
4264
|
reconcileRun;
|
|
4105
4265
|
reconcileConfig;
|
|
@@ -4174,8 +4334,8 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4174
4334
|
try {
|
|
4175
4335
|
const names = await Promise.race([
|
|
4176
4336
|
pending,
|
|
4177
|
-
new Promise((
|
|
4178
|
-
timer = setTimeout(() =>
|
|
4337
|
+
new Promise((resolve17) => {
|
|
4338
|
+
timer = setTimeout(() => resolve17(void 0), chatNamesTimeoutMs);
|
|
4179
4339
|
})
|
|
4180
4340
|
]);
|
|
4181
4341
|
if (names) {
|
|
@@ -4278,9 +4438,9 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4278
4438
|
prompt: task.prompt,
|
|
4279
4439
|
state,
|
|
4280
4440
|
...task.lastSuccessfulElements?.length ? { last_successful_elements: task.lastSuccessfulElements } : {},
|
|
4281
|
-
...task.event.chatType === "group" ? {
|
|
4441
|
+
...task.event.chatType === "group" || task.forceReplyInThread ? {
|
|
4282
4442
|
reply_message_id: task.event.messageId,
|
|
4283
|
-
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
4443
|
+
...task.replyMode ? { reply_in_thread: task.replyMode === "thread" } : task.forceReplyInThread || task.event.threadId?.trim() ? { reply_in_thread: true } : {}
|
|
4284
4444
|
} : {},
|
|
4285
4445
|
started_at: task.startedAt
|
|
4286
4446
|
};
|
|
@@ -4347,7 +4507,7 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4347
4507
|
}
|
|
4348
4508
|
if (attempt < 3) {
|
|
4349
4509
|
const delay = isLarkMessageRateLimit(error) ? larkRateLimitBackoffMs(attempt) : attempt * 300;
|
|
4350
|
-
await new Promise((
|
|
4510
|
+
await new Promise((resolve17) => setTimeout(resolve17, delay));
|
|
4351
4511
|
}
|
|
4352
4512
|
}
|
|
4353
4513
|
}
|
|
@@ -4479,18 +4639,148 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4479
4639
|
isSelfMention(config, mention) {
|
|
4480
4640
|
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
4641
|
}
|
|
4642
|
+
async lookupSideChatThread(appId, event) {
|
|
4643
|
+
const keys = [event.rootId?.trim(), event.threadId?.trim()].filter((value) => Boolean(value));
|
|
4644
|
+
for (const key of keys) {
|
|
4645
|
+
const mem = this.sideChatThreads.get(`${appId}:${key}`);
|
|
4646
|
+
if (mem) return { key, sessionId: mem };
|
|
4647
|
+
if (this.cardMappings) {
|
|
4648
|
+
try {
|
|
4649
|
+
const mapping = await this.cardMappings.get(larkSideChatThreadChannel(appId), key);
|
|
4650
|
+
if (mapping?.sessionId) {
|
|
4651
|
+
this.sideChatThreads.set(`${appId}:${key}`, mapping.sessionId);
|
|
4652
|
+
return { key, sessionId: mapping.sessionId };
|
|
4653
|
+
}
|
|
4654
|
+
} catch (error) {
|
|
4655
|
+
this.log.warn({ error, appId, key }, "\u8BFB\u53D6\u98DE\u4E66\u4FA7\u804A\u8BDD\u9898\u7ED1\u5B9A\u5931\u8D25");
|
|
4656
|
+
}
|
|
4657
|
+
}
|
|
4658
|
+
}
|
|
4659
|
+
return void 0;
|
|
4660
|
+
}
|
|
4661
|
+
async saveSideChatThread(appId, keys, sessionId) {
|
|
4662
|
+
const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter(Boolean))];
|
|
4663
|
+
for (const key of uniqueKeys) {
|
|
4664
|
+
this.sideChatThreads.set(`${appId}:${key}`, sessionId);
|
|
4665
|
+
if (this.sideChatThreads.size > 5e3) this.sideChatThreads.delete(this.sideChatThreads.keys().next().value);
|
|
4666
|
+
if (this.cardMappings) {
|
|
4667
|
+
try {
|
|
4668
|
+
await this.cardMappings.save({
|
|
4669
|
+
id: `${larkSideChatThreadChannel(appId)}:${key}`,
|
|
4670
|
+
channel: larkSideChatThreadChannel(appId),
|
|
4671
|
+
externalId: key,
|
|
4672
|
+
sessionId,
|
|
4673
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
4674
|
+
});
|
|
4675
|
+
} catch (error) {
|
|
4676
|
+
this.log.warn({ error, appId, key, sessionId }, "\u6301\u4E45\u5316\u98DE\u4E66\u4FA7\u804A\u8BDD\u9898\u7ED1\u5B9A\u5931\u8D25");
|
|
4677
|
+
}
|
|
4678
|
+
}
|
|
4679
|
+
}
|
|
4680
|
+
}
|
|
4681
|
+
/** 查找当前聊天对应的主会话(用于侧边会话关联父会话上下文,不新建主会话)。 */
|
|
4682
|
+
async findParentSessionForSideChat(config, event, parentGroupKey, parentSourceId) {
|
|
4683
|
+
const parentGroup = this.groups.get(parentGroupKey);
|
|
4684
|
+
let candidateId = parentGroup?.boundSessionId ?? parentGroup?.sessionId;
|
|
4685
|
+
if (!candidateId && this.cardMappings) {
|
|
4686
|
+
try {
|
|
4687
|
+
const handover = await this.cardMappings.get(larkHandoverChannel(config.appId), event.chatId);
|
|
4688
|
+
if (handover?.sessionId) candidateId = handover.sessionId;
|
|
4689
|
+
} catch {
|
|
4690
|
+
}
|
|
4691
|
+
}
|
|
4692
|
+
if (candidateId) {
|
|
4693
|
+
const existing = await this.runtime.getSession(candidateId);
|
|
4694
|
+
if (existing && !existing.archivedAt) return existing;
|
|
4695
|
+
}
|
|
4696
|
+
if (this.runtime.listSessions) {
|
|
4697
|
+
const sessions2 = await this.runtime.listSessions();
|
|
4698
|
+
const matched = [...sessions2].reverse().find((item) => item.source === "lark" && item.sourceId === parentSourceId && !item.archivedAt);
|
|
4699
|
+
if (matched) return matched;
|
|
4700
|
+
}
|
|
4701
|
+
return void 0;
|
|
4702
|
+
}
|
|
4703
|
+
/**
|
|
4704
|
+
* 按 SideChatConfig 创建飞书侧边会话并绑定话题。
|
|
4705
|
+
* 复用与网页端完全一致的「侧边会话」模型(source: 'side-chat' + buildSideSessionSeed)。
|
|
4706
|
+
*/
|
|
4707
|
+
async sideChatSessionFor(task) {
|
|
4708
|
+
const { group, event, config, sideChat } = task;
|
|
4709
|
+
if (!sideChat) throw new Error("Missing sideChat context");
|
|
4710
|
+
if (group.boundSessionId) {
|
|
4711
|
+
const existing = await this.runtime.getSession(group.boundSessionId);
|
|
4712
|
+
if (existing && !existing.archivedAt && !["failed", "stopped"].includes(existing.state)) return existing;
|
|
4713
|
+
}
|
|
4714
|
+
const parentSession = await this.findParentSessionForSideChat(config, event, sideChat.parentGroupKey, sideChat.parentSourceId);
|
|
4715
|
+
const sideConfig = sideChat.config;
|
|
4716
|
+
let agentId;
|
|
4717
|
+
let model;
|
|
4718
|
+
let reasoningEffort;
|
|
4719
|
+
if (sideConfig.targetMode === "custom_agent" && sideConfig.agentId?.trim()) {
|
|
4720
|
+
const targetId = sideConfig.agentId.trim();
|
|
4721
|
+
const availableAgents = this.runtime.listAgents ? await this.runtime.listAgents() : void 0;
|
|
4722
|
+
const available = !availableAgents || availableAgents.some((agent) => agent.id === targetId && !agent.disabled);
|
|
4723
|
+
if (available) {
|
|
4724
|
+
agentId = targetId;
|
|
4725
|
+
model = sideConfig.model?.trim() || void 0;
|
|
4726
|
+
reasoningEffort = sideConfig.reasoningEffort?.trim() || void 0;
|
|
4727
|
+
}
|
|
4728
|
+
}
|
|
4729
|
+
if (!agentId) {
|
|
4730
|
+
agentId = parentSession?.agentId ?? config.defaultAgentId;
|
|
4731
|
+
model = parentSession ? parentSession.model : config.defaultModel;
|
|
4732
|
+
reasoningEffort = parentSession ? parentSession.reasoningEffort : config.defaultReasoningEffort;
|
|
4733
|
+
}
|
|
4734
|
+
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");
|
|
4735
|
+
const cwd = parentSession?.cwd ?? config.workspace;
|
|
4736
|
+
const session = await this.runtime.start({
|
|
4737
|
+
agentId,
|
|
4738
|
+
...cwd ? { cwd } : {},
|
|
4739
|
+
...model ? { model } : {},
|
|
4740
|
+
...reasoningEffort ? { reasoningEffort } : {},
|
|
4741
|
+
...parentSession ? { systemPrompt: buildSideSessionSeed(parentSession.id) } : {},
|
|
4742
|
+
permissionMode: "full-trust",
|
|
4743
|
+
source: "side-chat",
|
|
4744
|
+
sourceId: parentSession ? parentSession.id : sideChat.parentSourceId
|
|
4745
|
+
});
|
|
4746
|
+
group.boundSessionId = session.id;
|
|
4747
|
+
group.sessionId = session.id;
|
|
4748
|
+
await this.saveSideChatThread(config.appId, [sideChat.triggerRootId, ...event.threadId ? [event.threadId] : []], session.id);
|
|
4749
|
+
return session;
|
|
4750
|
+
}
|
|
4482
4751
|
async handle(event, config) {
|
|
4483
4752
|
const mentionsBot = event.mentions.some((mention) => this.isSelfMention(config, mention));
|
|
4484
|
-
const
|
|
4753
|
+
const existingSideThread = await this.lookupSideChatThread(config.appId, event);
|
|
4754
|
+
const inSideChatFollowUp = Boolean(existingSideThread) && (event.chatType === "p2p" || mentionsBot || event.mentions.length === 0);
|
|
4755
|
+
const shouldWake = event.chatType === "p2p" || event.chatType === "group" && mentionsBot || inSideChatFollowUp;
|
|
4485
4756
|
if (event.chatType === "group" && !shouldWake && event.mentions.length) {
|
|
4486
4757
|
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
4758
|
}
|
|
4488
4759
|
if (this.stopped || !shouldWake || this.handledMessages.has(event.messageId)) return;
|
|
4489
4760
|
this.handledMessages.add(event.messageId);
|
|
4490
4761
|
if (this.handledMessages.size > 5e3) this.handledMessages.delete(this.handledMessages.values().next().value);
|
|
4491
|
-
const
|
|
4762
|
+
const sideChatConfig = await readSideChatConfig(this.configRepository);
|
|
4763
|
+
const mainScopeId = larkGroupScopeId(event, config.groupSessionScope);
|
|
4764
|
+
const mainGroupKey = larkGroupKey(event, config.groupSessionScope);
|
|
4765
|
+
let matchedNewSideChat = false;
|
|
4766
|
+
if (!existingSideThread && sideChatConfig.btwEnabled) {
|
|
4767
|
+
try {
|
|
4768
|
+
const quickParsed = await parseLarkMessageContent(event.messageType, event.content, { messageId: event.messageId });
|
|
4769
|
+
const quickText = renderPromptMentions(quickParsed.text, event.mentions, (mention) => this.isSelfMention(config, mention)).trim();
|
|
4770
|
+
matchedNewSideChat = matchSideChatTrigger(quickText, sideChatConfig.triggerPrefix).matched;
|
|
4771
|
+
} catch {
|
|
4772
|
+
}
|
|
4773
|
+
}
|
|
4774
|
+
const triggerRootId = event.rootId?.trim() || event.messageId;
|
|
4775
|
+
const isSideChat = Boolean(existingSideThread) || matchedNewSideChat;
|
|
4776
|
+
const groupKey = isSideChat ? `side-chat:${event.chatId}:${existingSideThread ? existingSideThread.key : triggerRootId}` : mainGroupKey;
|
|
4492
4777
|
const group = this.groups.get(groupKey) ?? { tail: Promise.resolve() };
|
|
4493
|
-
if (
|
|
4778
|
+
if (existingSideThread) {
|
|
4779
|
+
group.boundSessionId = existingSideThread.sessionId;
|
|
4780
|
+
if (event.threadId?.trim()) {
|
|
4781
|
+
void this.saveSideChatThread(config.appId, [existingSideThread.key, event.threadId.trim()], existingSideThread.sessionId);
|
|
4782
|
+
}
|
|
4783
|
+
} else if (!isSideChat && !group.boundSessionId && this.cardMappings) {
|
|
4494
4784
|
try {
|
|
4495
4785
|
const mapping = await this.cardMappings.get(larkHandoverChannel(config.appId), event.chatId);
|
|
4496
4786
|
if (mapping?.sessionId) group.boundSessionId = mapping.sessionId;
|
|
@@ -4498,12 +4788,36 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
|
|
|
4498
4788
|
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
4789
|
}
|
|
4500
4790
|
}
|
|
4501
|
-
const task = {
|
|
4791
|
+
const task = {
|
|
4792
|
+
id: event.messageId,
|
|
4793
|
+
group,
|
|
4794
|
+
event,
|
|
4795
|
+
prompt: "",
|
|
4796
|
+
resources: [],
|
|
4797
|
+
config,
|
|
4798
|
+
state: "queued",
|
|
4799
|
+
events: [],
|
|
4800
|
+
turn: 0,
|
|
4801
|
+
...isSideChat ? { forceReplyInThread: true } : {},
|
|
4802
|
+
...matchedNewSideChat ? {
|
|
4803
|
+
sideChat: {
|
|
4804
|
+
parentGroupKey: mainGroupKey,
|
|
4805
|
+
parentSourceId: larkSourceId(config, event.chatId, event.chatType, mainScopeId),
|
|
4806
|
+
triggerRootId,
|
|
4807
|
+
config: sideChatConfig
|
|
4808
|
+
}
|
|
4809
|
+
} : {}
|
|
4810
|
+
};
|
|
4502
4811
|
this.tasks.set(task.id, task);
|
|
4503
4812
|
if (this.tasks.size > 5e3) this.tasks.delete(this.tasks.keys().next().value);
|
|
4813
|
+
const stripSideChatTriggerPrefix = isSideChat && sideChatConfig.btwEnabled ? sideChatConfig.triggerPrefix : void 0;
|
|
4504
4814
|
group.tail = group.tail.then(async () => {
|
|
4505
4815
|
if (this.stopped) return;
|
|
4506
|
-
const parsed = await parsePrompt(event, (mention) => this.isSelfMention(config, mention), this.service, {
|
|
4816
|
+
const parsed = await parsePrompt(event, (mention) => this.isSelfMention(config, mention), this.service, {
|
|
4817
|
+
log: this.log,
|
|
4818
|
+
appId: config.appId,
|
|
4819
|
+
...stripSideChatTriggerPrefix ? { stripSideChatTriggerPrefix } : {}
|
|
4820
|
+
});
|
|
4507
4821
|
task.prompt = parsed.prompt;
|
|
4508
4822
|
task.resources = parsed.resources;
|
|
4509
4823
|
await this.runTurn(task);
|
|
@@ -4737,8 +5051,9 @@ ${lines.join("\n")}`;
|
|
|
4737
5051
|
task.resources = [];
|
|
4738
5052
|
}
|
|
4739
5053
|
if (!task.prompt.trim()) {
|
|
4740
|
-
task.prompt = await this.buildEmptyMessageFallback(event, config);
|
|
5054
|
+
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
5055
|
}
|
|
5056
|
+
const replyInThreadOpt = task.forceReplyInThread ? { replyInThread: true } : {};
|
|
4742
5057
|
const prompt = task.prompt;
|
|
4743
5058
|
const firstAttempt = !task.cardMessageId;
|
|
4744
5059
|
const emojiType = acknowledgementEmojis[Math.floor(this.random() * acknowledgementEmojis.length)] ?? acknowledgementEmojis[0];
|
|
@@ -4831,14 +5146,14 @@ ${error instanceof Error ? error.message : String(error)}`, ...config.webBaseUrl
|
|
|
4831
5146
|
};
|
|
4832
5147
|
let session;
|
|
4833
5148
|
try {
|
|
4834
|
-
session = await this.sessionFor(group, config, event.chatId, event.chatType, larkGroupScopeId(event, config.groupSessionScope));
|
|
5149
|
+
session = task.sideChat ? await this.sideChatSessionFor(task) : await this.sessionFor(group, config, event.chatId, event.chatType, larkGroupScopeId(event, config.groupSessionScope));
|
|
4835
5150
|
} catch (error) {
|
|
4836
5151
|
task.state = "failed";
|
|
4837
5152
|
task.startedAt = Date.now();
|
|
4838
5153
|
const markdown = `**Agent \u542F\u52A8\u5931\u8D25**
|
|
4839
5154
|
|
|
4840
5155
|
${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);
|
|
5156
|
+
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
5157
|
if (card.messageId) task.cardMessageId = card.messageId;
|
|
4843
5158
|
if (reactionId && !config.quietReply) await this.service.deleteReaction(event.messageId, reactionId).catch(() => void 0);
|
|
4844
5159
|
return;
|
|
@@ -4855,7 +5170,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
4855
5170
|
if (task.cardMessageId) {
|
|
4856
5171
|
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
5172
|
} 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);
|
|
5173
|
+
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
5174
|
task.cardMessageId = card.messageId;
|
|
4860
5175
|
}
|
|
4861
5176
|
task.lastSuccessfulElements = initialElements;
|
|
@@ -4906,7 +5221,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
4906
5221
|
this.log.warn({ error, messageId: pending.input.messageId, attempt, attempts }, "\u66F4\u65B0\u98DE\u4E66\u670D\u52A1\u5361\u7247\u5931\u8D25");
|
|
4907
5222
|
if (attempt < attempts) {
|
|
4908
5223
|
const retryDelay = isLarkMessageRateLimit(error) ? Math.max(0, cardRateLimitedUntil - Date.now()) : attempt * 300;
|
|
4909
|
-
await new Promise((
|
|
5224
|
+
await new Promise((resolve17) => setTimeout(resolve17, retryDelay));
|
|
4910
5225
|
}
|
|
4911
5226
|
}
|
|
4912
5227
|
}
|
|
@@ -5019,7 +5334,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
5019
5334
|
let lastQuietError;
|
|
5020
5335
|
for (let attempt = 1; attempt <= maxQuietReplyAttempts; attempt++) {
|
|
5021
5336
|
try {
|
|
5022
|
-
await sendQuietFinalReply(this.service, event, reply, this.log);
|
|
5337
|
+
await sendQuietFinalReply(this.service, event, reply, this.log, task.forceReplyInThread);
|
|
5023
5338
|
lastQuietError = void 0;
|
|
5024
5339
|
break;
|
|
5025
5340
|
} catch (error) {
|
|
@@ -5027,7 +5342,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
5027
5342
|
if (attempt < maxQuietReplyAttempts) {
|
|
5028
5343
|
const delay = isLarkMessageRateLimit(error) ? larkRateLimitBackoffMs(attempt) : attempt * 500;
|
|
5029
5344
|
this.log.warn({ error, attempt, chatId: event.chatId, messageId: event.messageId }, "\u53D1\u9001\u9759\u9ED8\u7EC8\u6001\u56DE\u590D\u5931\u8D25\uFF0C\u51C6\u5907\u91CD\u8BD5");
|
|
5030
|
-
await new Promise((
|
|
5345
|
+
await new Promise((resolve17) => setTimeout(resolve17, delay));
|
|
5031
5346
|
}
|
|
5032
5347
|
}
|
|
5033
5348
|
}
|
|
@@ -5036,7 +5351,7 @@ ${error instanceof Error ? error.message : String(error)}`;
|
|
|
5036
5351
|
}
|
|
5037
5352
|
return;
|
|
5038
5353
|
}
|
|
5039
|
-
const defaultReplyInThread = Boolean(event.threadId?.trim());
|
|
5354
|
+
const defaultReplyInThread = Boolean(task.forceReplyInThread || event.threadId?.trim());
|
|
5040
5355
|
const agentReplyInThread = agentReplyMode === "thread";
|
|
5041
5356
|
if (agentReplyMode && agentReplyInThread !== defaultReplyInThread) {
|
|
5042
5357
|
task.replyMode = agentReplyMode;
|
|
@@ -5202,7 +5517,7 @@ ${prompt}` : prompt;
|
|
|
5202
5517
|
buffered = [];
|
|
5203
5518
|
if (runtimeTask.status === "queued" && (runtimeTask.queuedAhead ?? 0) > 0 && task.state === "queued") {
|
|
5204
5519
|
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);
|
|
5520
|
+
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
5521
|
} else {
|
|
5207
5522
|
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
5523
|
}
|
|
@@ -5707,14 +6022,14 @@ __export(session_cli_exports, {
|
|
|
5707
6022
|
sourceSessionId: () => sourceSessionId,
|
|
5708
6023
|
streamSessionShow: () => streamSessionShow
|
|
5709
6024
|
});
|
|
5710
|
-
import { existsSync as
|
|
5711
|
-
import { join as
|
|
6025
|
+
import { existsSync as existsSync10 } from "node:fs";
|
|
6026
|
+
import { join as join21, resolve as resolve12 } from "node:path";
|
|
5712
6027
|
function resolveDatabasePath(explicit, cwd = process.cwd()) {
|
|
5713
|
-
if (explicit) return
|
|
5714
|
-
if (process.env.AGENTDOCK_DATABASE_URL) return
|
|
6028
|
+
if (explicit) return resolve12(cwd, explicit);
|
|
6029
|
+
if (process.env.AGENTDOCK_DATABASE_URL) return resolve12(cwd, process.env.AGENTDOCK_DATABASE_URL);
|
|
5715
6030
|
const daemonDir = resolveDaemonDir(cwd);
|
|
5716
6031
|
const recorded = readDaemonStatus(daemonDir)?.database;
|
|
5717
|
-
return recorded ?
|
|
6032
|
+
return recorded ? resolve12(daemonDir, recorded) : join21(daemonDir, "..", "agentdock.db");
|
|
5718
6033
|
}
|
|
5719
6034
|
function sessionPeerIds(sessions2, sourceId2) {
|
|
5720
6035
|
const source2 = sessions2.find((session) => session.id === sourceId2);
|
|
@@ -5733,7 +6048,7 @@ function sourceSessionId(explicit) {
|
|
|
5733
6048
|
}
|
|
5734
6049
|
async function runSessionPeers(sessionId, options = {}) {
|
|
5735
6050
|
const filename = resolveDatabasePath(options.database);
|
|
5736
|
-
if (!
|
|
6051
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5737
6052
|
const repos = createRepositories(filename);
|
|
5738
6053
|
try {
|
|
5739
6054
|
const sourceId2 = sourceSessionId(sessionId);
|
|
@@ -5808,7 +6123,7 @@ async function runSessionCancel(targetId, taskId, options = {}) {
|
|
|
5808
6123
|
}
|
|
5809
6124
|
async function runSessionList(options = {}) {
|
|
5810
6125
|
const filename = resolveDatabasePath(options.database);
|
|
5811
|
-
if (!
|
|
6126
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5812
6127
|
const repos = createRepositories(filename);
|
|
5813
6128
|
try {
|
|
5814
6129
|
const sessions2 = await repos.sessions.list();
|
|
@@ -5820,7 +6135,7 @@ async function runSessionList(options = {}) {
|
|
|
5820
6135
|
}
|
|
5821
6136
|
async function withSessionView(sessionId, options, view) {
|
|
5822
6137
|
const filename = resolveDatabasePath(options.database);
|
|
5823
|
-
if (!
|
|
6138
|
+
if (!existsSync10(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
|
|
5824
6139
|
const repos = createRepositories(filename);
|
|
5825
6140
|
try {
|
|
5826
6141
|
const session = await repos.sessions.get(sessionId);
|
|
@@ -5963,7 +6278,7 @@ var AutostartService = class {
|
|
|
5963
6278
|
|
|
5964
6279
|
// src/cli.ts
|
|
5965
6280
|
init_src();
|
|
5966
|
-
import { existsSync as
|
|
6281
|
+
import { existsSync as existsSync13, readFileSync as readFileSync16 } from "node:fs";
|
|
5967
6282
|
import { spawn as spawn13 } from "node:child_process";
|
|
5968
6283
|
import { loadEnvFile } from "node:process";
|
|
5969
6284
|
import { fileURLToPath as fileURLToPath6 } from "node:url";
|
|
@@ -6359,8 +6674,8 @@ var KeepAwakeService = class {
|
|
|
6359
6674
|
const child = (this.options.spawn ?? spawn2)(this.caffeinatePath, this.args(), { stdio: "ignore" });
|
|
6360
6675
|
this.child = child;
|
|
6361
6676
|
try {
|
|
6362
|
-
await new Promise((
|
|
6363
|
-
child.once("spawn",
|
|
6677
|
+
await new Promise((resolve17, reject2) => {
|
|
6678
|
+
child.once("spawn", resolve17);
|
|
6364
6679
|
child.once("error", reject2);
|
|
6365
6680
|
});
|
|
6366
6681
|
} catch (error) {
|
|
@@ -6467,8 +6782,8 @@ async function resolveProjectPath(raw, options = {}) {
|
|
|
6467
6782
|
init_src2();
|
|
6468
6783
|
|
|
6469
6784
|
// ../../packages/acp-client/src/index.ts
|
|
6470
|
-
import { dirname as dirname6, join as join6 } from "node:path";
|
|
6471
|
-
import { existsSync as existsSync6 } from "node:fs";
|
|
6785
|
+
import { delimiter, dirname as dirname6, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve3 } from "node:path";
|
|
6786
|
+
import { accessSync, constants as constants2, existsSync as existsSync6, statSync as statSync3 } from "node:fs";
|
|
6472
6787
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
6473
6788
|
|
|
6474
6789
|
// ../../node_modules/.pnpm/acpx@0.20.0_patch_hash=34d804a05175c628ad9877f34a2db2f24bdce786dbb98bacb313e7559b2ca416/node_modules/acpx/dist/agent-registry-Gtwn7nMp.js
|
|
@@ -6480,7 +6795,7 @@ var PROCESS_HELPER_TIMEOUT_MS = 8e3;
|
|
|
6480
6795
|
var PROCESS_HELPER_MAX_BUFFER_BYTES = 33554432;
|
|
6481
6796
|
async function runTimedExecFile(command, args, options = {}) {
|
|
6482
6797
|
const timeoutMs = Math.max(1, Math.round(options.timeoutMs ?? 8e3));
|
|
6483
|
-
return await new Promise((
|
|
6798
|
+
return await new Promise((resolve17, reject2) => {
|
|
6484
6799
|
let settled = false;
|
|
6485
6800
|
let timer;
|
|
6486
6801
|
const child = execFile2(command, [...args], {
|
|
@@ -6497,7 +6812,7 @@ async function runTimedExecFile(command, args, options = {}) {
|
|
|
6497
6812
|
reject2(error);
|
|
6498
6813
|
return;
|
|
6499
6814
|
}
|
|
6500
|
-
|
|
6815
|
+
resolve17(stdout);
|
|
6501
6816
|
});
|
|
6502
6817
|
timer = setTimeout(() => {
|
|
6503
6818
|
if (settled) return;
|
|
@@ -6531,10 +6846,10 @@ function isoNow() {
|
|
|
6531
6846
|
return (/* @__PURE__ */ new Date()).toISOString();
|
|
6532
6847
|
}
|
|
6533
6848
|
function waitForSpawn(child) {
|
|
6534
|
-
return new Promise((
|
|
6849
|
+
return new Promise((resolve17, reject2) => {
|
|
6535
6850
|
const onSpawn = () => {
|
|
6536
6851
|
child.off("error", onError);
|
|
6537
|
-
|
|
6852
|
+
resolve17();
|
|
6538
6853
|
};
|
|
6539
6854
|
const onError = (error) => {
|
|
6540
6855
|
child.off("spawn", onSpawn);
|
|
@@ -6553,7 +6868,7 @@ function requireAgentStdio(child) {
|
|
|
6553
6868
|
}
|
|
6554
6869
|
function waitForChildExit(child, timeoutMs) {
|
|
6555
6870
|
if (!isChildProcessRunning(child)) return Promise.resolve(true);
|
|
6556
|
-
return new Promise((
|
|
6871
|
+
return new Promise((resolve17) => {
|
|
6557
6872
|
let settled = false;
|
|
6558
6873
|
const timer = setTimeout(() => {
|
|
6559
6874
|
finish(false);
|
|
@@ -6564,7 +6879,7 @@ function waitForChildExit(child, timeoutMs) {
|
|
|
6564
6879
|
child.off("close", onExitLike);
|
|
6565
6880
|
child.off("exit", onExitLike);
|
|
6566
6881
|
clearTimeout(timer);
|
|
6567
|
-
|
|
6882
|
+
resolve17(value);
|
|
6568
6883
|
};
|
|
6569
6884
|
const onExitLike = () => {
|
|
6570
6885
|
finish(true);
|
|
@@ -7069,8 +7384,8 @@ function inspectAgent(agentId, override, options = {}) {
|
|
|
7069
7384
|
};
|
|
7070
7385
|
}
|
|
7071
7386
|
function inspectPrerequisites(launch, requiredCommands, options) {
|
|
7072
|
-
const
|
|
7073
|
-
const missingCommands = requiredCommands.filter((command) => !
|
|
7387
|
+
const resolveExecutable2 = options.resolveExecutable ?? resolveInstalledExecutable;
|
|
7388
|
+
const missingCommands = requiredCommands.filter((command) => !resolveExecutable2(command)).map((name) => ({
|
|
7074
7389
|
kind: "command",
|
|
7075
7390
|
name
|
|
7076
7391
|
}));
|
|
@@ -7174,13 +7489,13 @@ function resolveInstalledBuiltInAgentLaunch(agentCommand, options = {}) {
|
|
|
7174
7489
|
return resolveInstalledBuiltInAgentLaunchForSpec(spec, options);
|
|
7175
7490
|
}
|
|
7176
7491
|
function resolveInstalledBuiltInAgentLaunchForSpec(spec, options) {
|
|
7177
|
-
const
|
|
7178
|
-
const
|
|
7492
|
+
const readFileSync17 = options.readFileSync ?? fs.readFileSync;
|
|
7493
|
+
const existsSync14 = options.existsSync ?? fs.existsSync;
|
|
7179
7494
|
const resolvePackageRoot = options.resolvePackageRoot ?? defaultResolvePackageRoot;
|
|
7180
7495
|
try {
|
|
7181
7496
|
const resolved = resolveInstalledBuiltInAgentPackage(spec, {
|
|
7182
|
-
readFileSync:
|
|
7183
|
-
existsSync:
|
|
7497
|
+
readFileSync: readFileSync17,
|
|
7498
|
+
existsSync: existsSync14,
|
|
7184
7499
|
resolvePackageRoot
|
|
7185
7500
|
});
|
|
7186
7501
|
if (!resolved) return;
|
|
@@ -7213,12 +7528,12 @@ function resolveInstalledBuiltInAgentPackage(spec, options) {
|
|
|
7213
7528
|
function resolvePackageExecBuiltInAgentLaunch(agentCommand, options = {}) {
|
|
7214
7529
|
const spec = findBuiltInAgentPackage(agentCommand);
|
|
7215
7530
|
if (!spec) return;
|
|
7216
|
-
const
|
|
7531
|
+
const existsSync14 = options.existsSync ?? fs.existsSync;
|
|
7217
7532
|
const execPath = options.execPath ?? process.execPath;
|
|
7218
7533
|
const resolveNpmCliPath = options.resolveNpmCliPath ?? defaultResolveNpmCliPath;
|
|
7219
7534
|
try {
|
|
7220
7535
|
const npmCliPath = resolveNpmCliPath(execPath);
|
|
7221
|
-
if (!
|
|
7536
|
+
if (!existsSync14(npmCliPath)) return;
|
|
7222
7537
|
return {
|
|
7223
7538
|
source: "package-exec",
|
|
7224
7539
|
command: execPath,
|
|
@@ -9015,7 +9330,7 @@ async function withTimeout(promise, timeoutMs) {
|
|
|
9015
9330
|
}
|
|
9016
9331
|
}
|
|
9017
9332
|
async function withInterrupt(run2, onInterrupt) {
|
|
9018
|
-
return await new Promise((
|
|
9333
|
+
return await new Promise((resolve17, reject2) => {
|
|
9019
9334
|
let settled = false;
|
|
9020
9335
|
const finish = (cb) => {
|
|
9021
9336
|
if (settled) return;
|
|
@@ -9040,7 +9355,7 @@ async function withInterrupt(run2, onInterrupt) {
|
|
|
9040
9355
|
process.once("SIGINT", onSigint);
|
|
9041
9356
|
process.once("SIGTERM", onSigterm);
|
|
9042
9357
|
process.once("SIGHUP", onSighup);
|
|
9043
|
-
run2().then((result) => finish(() =>
|
|
9358
|
+
run2().then((result) => finish(() => resolve17(result)), (error) => finish(() => reject2(error)));
|
|
9044
9359
|
});
|
|
9045
9360
|
}
|
|
9046
9361
|
function preferCodexPermissionRefusal(request, agentName) {
|
|
@@ -9116,8 +9431,8 @@ async function askPermission(options) {
|
|
|
9116
9431
|
const signal = options.signal ? AbortSignal.any([options.signal, questionController.signal]) : questionController.signal;
|
|
9117
9432
|
let onClose = () => {
|
|
9118
9433
|
};
|
|
9119
|
-
const closed = new Promise((
|
|
9120
|
-
onClose = () =>
|
|
9434
|
+
const closed = new Promise((resolve17) => {
|
|
9435
|
+
onClose = () => resolve17(void 0);
|
|
9121
9436
|
rl.once("close", onClose);
|
|
9122
9437
|
});
|
|
9123
9438
|
try {
|
|
@@ -9945,8 +10260,8 @@ function captureCommandProbeOutput(child, timeoutMs, retire) {
|
|
|
9945
10260
|
let disposed = false;
|
|
9946
10261
|
let timer;
|
|
9947
10262
|
let resolveResult;
|
|
9948
|
-
const result = new Promise((
|
|
9949
|
-
resolveResult =
|
|
10263
|
+
const result = new Promise((resolve17) => {
|
|
10264
|
+
resolveResult = resolve17;
|
|
9950
10265
|
});
|
|
9951
10266
|
const finish = (value) => {
|
|
9952
10267
|
if (settled) return;
|
|
@@ -10365,8 +10680,8 @@ function canPromptForPermission() {
|
|
|
10365
10680
|
return process.stdin.isTTY && process.stderr.isTTY;
|
|
10366
10681
|
}
|
|
10367
10682
|
function waitMs2(ms) {
|
|
10368
|
-
return new Promise((
|
|
10369
|
-
setTimeout(
|
|
10683
|
+
return new Promise((resolve17) => {
|
|
10684
|
+
setTimeout(resolve17, Math.max(0, ms));
|
|
10370
10685
|
});
|
|
10371
10686
|
}
|
|
10372
10687
|
function onStreamError() {
|
|
@@ -10425,8 +10740,8 @@ var TerminalManager = class {
|
|
|
10425
10740
|
const { proc, spawnCommand } = await spawnTerminalProcess(params, this.cwd, authority);
|
|
10426
10741
|
let resolveExit = () => {
|
|
10427
10742
|
};
|
|
10428
|
-
const exitPromise = new Promise((
|
|
10429
|
-
resolveExit =
|
|
10743
|
+
const exitPromise = new Promise((resolve17) => {
|
|
10744
|
+
resolveExit = resolve17;
|
|
10430
10745
|
});
|
|
10431
10746
|
const terminal = {
|
|
10432
10747
|
process: proc,
|
|
@@ -10859,8 +11174,8 @@ function elicitationRequestScopeId(request) {
|
|
|
10859
11174
|
}
|
|
10860
11175
|
async function raceWithAbort(signal, pending) {
|
|
10861
11176
|
let onAbort;
|
|
10862
|
-
const aborted = new Promise((
|
|
10863
|
-
onAbort = () =>
|
|
11177
|
+
const aborted = new Promise((resolve17) => {
|
|
11178
|
+
onAbort = () => resolve17(void 0);
|
|
10864
11179
|
if (signal.aborted) onAbort();
|
|
10865
11180
|
else signal.addEventListener("abort", onAbort, { once: true });
|
|
10866
11181
|
});
|
|
@@ -11323,8 +11638,8 @@ var AcpClient = class {
|
|
|
11323
11638
|
async admitSpawnedProcess(child, observe, admit) {
|
|
11324
11639
|
let releaseExitNotification = () => {
|
|
11325
11640
|
};
|
|
11326
|
-
observe(new Promise((
|
|
11327
|
-
releaseExitNotification =
|
|
11641
|
+
observe(new Promise((resolve17) => {
|
|
11642
|
+
releaseExitNotification = resolve17;
|
|
11328
11643
|
}));
|
|
11329
11644
|
try {
|
|
11330
11645
|
await admit();
|
|
@@ -11704,8 +12019,8 @@ var AcpClient = class {
|
|
|
11704
12019
|
const activePromise = active.promise;
|
|
11705
12020
|
if (!activePromise) return;
|
|
11706
12021
|
let timer;
|
|
11707
|
-
const timeoutPromise = new Promise((
|
|
11708
|
-
timer = setTimeout(
|
|
12022
|
+
const timeoutPromise = new Promise((resolve17) => {
|
|
12023
|
+
timer = setTimeout(resolve17, waitMs3);
|
|
11709
12024
|
});
|
|
11710
12025
|
try {
|
|
11711
12026
|
return await Promise.race([activePromise.then((response) => response, () => void 0), timeoutPromise]);
|
|
@@ -12225,7 +12540,7 @@ var AcpClient = class {
|
|
|
12225
12540
|
return error;
|
|
12226
12541
|
}
|
|
12227
12542
|
async runConnectionRequest(run2, authority, mapRequestError) {
|
|
12228
|
-
return await new Promise((
|
|
12543
|
+
return await new Promise((resolve17, reject2) => {
|
|
12229
12544
|
const rejectRequestError = (error) => {
|
|
12230
12545
|
try {
|
|
12231
12546
|
reject2(mapRequestError ? mapRequestError(error) : error);
|
|
@@ -12257,7 +12572,7 @@ var AcpClient = class {
|
|
|
12257
12572
|
value: await run2()
|
|
12258
12573
|
};
|
|
12259
12574
|
}).then((outcome) => {
|
|
12260
|
-
if (outcome.started) finish(() =>
|
|
12575
|
+
if (outcome.started) finish(() => resolve17(outcome.value));
|
|
12261
12576
|
}, (error) => finish(() => rejectRequestError(error)));
|
|
12262
12577
|
});
|
|
12263
12578
|
}
|
|
@@ -12362,8 +12677,8 @@ var AcpClient = class {
|
|
|
12362
12677
|
await this.sessionUpdateChain;
|
|
12363
12678
|
if (this.processedSessionUpdates === this.observedSessionUpdates) return;
|
|
12364
12679
|
}
|
|
12365
|
-
await new Promise((
|
|
12366
|
-
setTimeout(
|
|
12680
|
+
await new Promise((resolve17) => {
|
|
12681
|
+
setTimeout(resolve17, DRAIN_POLL_INTERVAL_MS);
|
|
12367
12682
|
});
|
|
12368
12683
|
}
|
|
12369
12684
|
throw new Error(`Timed out waiting for session replay drain after ${normalizedTimeoutMs}ms`);
|
|
@@ -14613,14 +14928,14 @@ function commandRecord(value) {
|
|
|
14613
14928
|
return value;
|
|
14614
14929
|
}
|
|
14615
14930
|
function createDeferred() {
|
|
14616
|
-
let
|
|
14931
|
+
let resolve17;
|
|
14617
14932
|
let reject2;
|
|
14618
14933
|
return {
|
|
14619
14934
|
promise: new Promise((res, rej) => {
|
|
14620
|
-
|
|
14935
|
+
resolve17 = res;
|
|
14621
14936
|
reject2 = rej;
|
|
14622
14937
|
}),
|
|
14623
|
-
resolve:
|
|
14938
|
+
resolve: resolve17,
|
|
14624
14939
|
reject: reject2
|
|
14625
14940
|
};
|
|
14626
14941
|
}
|
|
@@ -15198,8 +15513,8 @@ var AcpRuntimeManager = class {
|
|
|
15198
15513
|
async serializeManagerOperation(locks, key, run2) {
|
|
15199
15514
|
const previous = locks.get(key) ?? Promise.resolve();
|
|
15200
15515
|
let release;
|
|
15201
|
-
const gate = new Promise((
|
|
15202
|
-
release =
|
|
15516
|
+
const gate = new Promise((resolve17) => {
|
|
15517
|
+
release = resolve17;
|
|
15203
15518
|
});
|
|
15204
15519
|
const tail2 = previous.then(() => gate);
|
|
15205
15520
|
locks.set(key, tail2);
|
|
@@ -16423,7 +16738,7 @@ try {
|
|
|
16423
16738
|
}
|
|
16424
16739
|
`;
|
|
16425
16740
|
function testRegexWithTimeout(pattern, input, timeoutMs = 1e3) {
|
|
16426
|
-
return new Promise((
|
|
16741
|
+
return new Promise((resolve17, reject2) => {
|
|
16427
16742
|
const worker = new Worker(workerSource, { eval: true, workerData: { pattern, input } });
|
|
16428
16743
|
let settled = false;
|
|
16429
16744
|
const finish = (callback) => {
|
|
@@ -16435,7 +16750,7 @@ function testRegexWithTimeout(pattern, input, timeoutMs = 1e3) {
|
|
|
16435
16750
|
callback();
|
|
16436
16751
|
};
|
|
16437
16752
|
const timer = setTimeout(() => finish(() => reject2(new RegexMatchTimeoutError(timeoutMs))), timeoutMs);
|
|
16438
|
-
worker.once("message", (result) => finish(() => result.error ? reject2(new Error(`\u6B63\u5219\u5339\u914D\u5931\u8D25\uFF1A${result.error}`)) :
|
|
16753
|
+
worker.once("message", (result) => finish(() => result.error ? reject2(new Error(`\u6B63\u5219\u5339\u914D\u5931\u8D25\uFF1A${result.error}`)) : resolve17(result.matched === true)));
|
|
16439
16754
|
worker.once("error", (error) => finish(() => reject2(error)));
|
|
16440
16755
|
worker.once("exit", (code) => {
|
|
16441
16756
|
if (code !== 0) finish(() => reject2(new Error(`\u6B63\u5219\u5339\u914D\u9694\u79BB\u4EFB\u52A1\u5F02\u5E38\u9000\u51FA\uFF1A${code}`)));
|
|
@@ -16683,10 +16998,10 @@ async function terminateExternalChild(child, graceMs = 5e3) {
|
|
|
16683
16998
|
} catch {
|
|
16684
16999
|
}
|
|
16685
17000
|
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
16686
|
-
await new Promise((
|
|
17001
|
+
await new Promise((resolve17) => {
|
|
16687
17002
|
const done = () => {
|
|
16688
17003
|
clearTimeout(timer);
|
|
16689
|
-
|
|
17004
|
+
resolve17();
|
|
16690
17005
|
};
|
|
16691
17006
|
const timer = setTimeout(() => {
|
|
16692
17007
|
if (child.exitCode === null) child.kill("SIGKILL");
|
|
@@ -16762,6 +17077,45 @@ function wrapAgentForSsh(agent, host, remoteCwd, options = {}) {
|
|
|
16762
17077
|
}
|
|
16763
17078
|
|
|
16764
17079
|
// ../../packages/acp-client/src/index.ts
|
|
17080
|
+
function isExecutableFile(file, platform2) {
|
|
17081
|
+
try {
|
|
17082
|
+
if (!statSync3(file).isFile()) return false;
|
|
17083
|
+
if (platform2 !== "win32") accessSync(file, constants2.X_OK);
|
|
17084
|
+
return true;
|
|
17085
|
+
} catch {
|
|
17086
|
+
return false;
|
|
17087
|
+
}
|
|
17088
|
+
}
|
|
17089
|
+
function resolveExecutable(command, options = {}) {
|
|
17090
|
+
const env = options.env ?? process.env;
|
|
17091
|
+
const platform2 = options.platform ?? process.platform;
|
|
17092
|
+
const candidates = platform2 === "win32" && !extname(command) ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
|
|
17093
|
+
const hasPathSeparator = command.includes("/") || command.includes("\\");
|
|
17094
|
+
if (hasPathSeparator || isAbsolute2(command)) {
|
|
17095
|
+
const absolute = resolve3(command);
|
|
17096
|
+
for (const extension of candidates) {
|
|
17097
|
+
const candidate = `${absolute}${extension}`;
|
|
17098
|
+
if (isExecutableFile(candidate, platform2)) return candidate;
|
|
17099
|
+
}
|
|
17100
|
+
return void 0;
|
|
17101
|
+
}
|
|
17102
|
+
const pathValue = env.PATH ?? env.Path ?? "";
|
|
17103
|
+
for (const directory of pathValue.split(delimiter).filter(Boolean)) {
|
|
17104
|
+
for (const extension of candidates) {
|
|
17105
|
+
const candidate = resolve3(directory, `${command}${extension}`);
|
|
17106
|
+
if (isExecutableFile(candidate, platform2)) return candidate;
|
|
17107
|
+
}
|
|
17108
|
+
}
|
|
17109
|
+
return void 0;
|
|
17110
|
+
}
|
|
17111
|
+
function antigravityArgv(argv, options) {
|
|
17112
|
+
for (const command of ["agy", "antigravity"]) {
|
|
17113
|
+
const executable = resolveExecutable(command, options);
|
|
17114
|
+
if (executable) return [executable, "acp"];
|
|
17115
|
+
}
|
|
17116
|
+
const legacy = argv[0] ? resolveExecutable(argv[0], options) : void 0;
|
|
17117
|
+
return legacy ? [legacy, ...argv.slice(1)] : argv;
|
|
17118
|
+
}
|
|
16765
17119
|
function agentLauncherPath(name) {
|
|
16766
17120
|
const moduleDirectory = dirname6(fileURLToPath4(import.meta.url));
|
|
16767
17121
|
const adjacent = join6(moduleDirectory, "agents", `${name}-acp.mjs`);
|
|
@@ -16773,13 +17127,14 @@ var flattenRiskText = (value, output3 = []) => {
|
|
|
16773
17127
|
else if (value && typeof value === "object") for (const item of Object.values(value)) flattenRiskText(item, output3);
|
|
16774
17128
|
return output3;
|
|
16775
17129
|
};
|
|
16776
|
-
function listAcpxBuiltinAgents() {
|
|
17130
|
+
function listAcpxBuiltinAgents(options = {}) {
|
|
16777
17131
|
const registry = createAgentRegistry();
|
|
16778
17132
|
return registry.list().map((id) => {
|
|
16779
17133
|
const command = registry.resolve(id);
|
|
16780
17134
|
if (id === "claude") return { id, argv: [process.execPath, agentLauncherPath("claude")] };
|
|
16781
17135
|
const argv = typeof command === "string" ? [command] : [...command];
|
|
16782
17136
|
if (id === "codex") return { id, argv: [process.execPath, agentLauncherPath("codex")] };
|
|
17137
|
+
if (id === "antigravity") return { id, argv: antigravityArgv(argv, options) };
|
|
16783
17138
|
return { id, argv };
|
|
16784
17139
|
});
|
|
16785
17140
|
}
|
|
@@ -16891,7 +17246,7 @@ var AcpxAdapter = class {
|
|
|
16891
17246
|
if (this.permissionMode === "deny-all") return { outcome: "reject_once" };
|
|
16892
17247
|
if (this.permissionMode === "approve-reads" && /read|search|fetch/i.test(String(request.inferredKind ?? ""))) return { outcome: "allow_once" };
|
|
16893
17248
|
this.options.onEvent({ type: "permission_request", data: { id, toolCallId: raw.toolCall?.toolCallId, title: raw.toolCall?.title ?? "Permission required", options: raw.options ?? [], status: "pending" } });
|
|
16894
|
-
return new Promise((
|
|
17249
|
+
return new Promise((resolve17) => this.pendingPermissions.set(id, resolve17));
|
|
16895
17250
|
}
|
|
16896
17251
|
});
|
|
16897
17252
|
}
|
|
@@ -17102,7 +17457,7 @@ var AcpxAdapter = class {
|
|
|
17102
17457
|
await this.start();
|
|
17103
17458
|
}
|
|
17104
17459
|
async stop(options = {}) {
|
|
17105
|
-
for (const
|
|
17460
|
+
for (const resolve17 of this.pendingPermissions.values()) resolve17({ outcome: "reject_once" });
|
|
17106
17461
|
this.pendingPermissions.clear();
|
|
17107
17462
|
const turn = this.turn;
|
|
17108
17463
|
if (turn) {
|
|
@@ -17118,10 +17473,10 @@ var AcpxAdapter = class {
|
|
|
17118
17473
|
if (options.discardSession) await this.resetPersistentState();
|
|
17119
17474
|
}
|
|
17120
17475
|
async resolvePermission(id, approved) {
|
|
17121
|
-
const
|
|
17122
|
-
if (!
|
|
17476
|
+
const resolve17 = this.pendingPermissions.get(id);
|
|
17477
|
+
if (!resolve17) return false;
|
|
17123
17478
|
this.pendingPermissions.delete(id);
|
|
17124
|
-
|
|
17479
|
+
resolve17({ outcome: approved ? "allow_once" : "reject_once" });
|
|
17125
17480
|
return true;
|
|
17126
17481
|
}
|
|
17127
17482
|
async setModel(model) {
|
|
@@ -18040,7 +18395,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18040
18395
|
return await driver.start();
|
|
18041
18396
|
} catch (error) {
|
|
18042
18397
|
if (!this.resumeOptions(session) || attempt >= 4 || !mentionsActiveWriter(error)) throw error;
|
|
18043
|
-
await new Promise((
|
|
18398
|
+
await new Promise((resolve17) => setTimeout(resolve17, 1500));
|
|
18044
18399
|
}
|
|
18045
18400
|
}
|
|
18046
18401
|
}
|
|
@@ -18143,7 +18498,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18143
18498
|
this.activeTurns.delete(id);
|
|
18144
18499
|
this.activeTasks.delete(id);
|
|
18145
18500
|
this.touch(id);
|
|
18146
|
-
for (const
|
|
18501
|
+
for (const resolve17 of this.turnWaiters.get(id) ?? []) resolve17();
|
|
18147
18502
|
this.turnWaiters.delete(id);
|
|
18148
18503
|
if (!hardInterrupted) this.scheduleQueue(id);
|
|
18149
18504
|
}
|
|
@@ -18201,9 +18556,9 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18201
18556
|
}
|
|
18202
18557
|
let timer;
|
|
18203
18558
|
try {
|
|
18204
|
-
return await new Promise((
|
|
18205
|
-
timer = setTimeout(() =>
|
|
18206
|
-
void turn.then(() =>
|
|
18559
|
+
return await new Promise((resolve17) => {
|
|
18560
|
+
timer = setTimeout(() => resolve17(true), timeoutMs);
|
|
18561
|
+
void turn.then(() => resolve17(false));
|
|
18207
18562
|
});
|
|
18208
18563
|
} finally {
|
|
18209
18564
|
if (timer) clearTimeout(timer);
|
|
@@ -18424,9 +18779,9 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18424
18779
|
}
|
|
18425
18780
|
waitForTurn(id) {
|
|
18426
18781
|
if (!this.activeTurns.has(id)) return Promise.resolve();
|
|
18427
|
-
return new Promise((
|
|
18782
|
+
return new Promise((resolve17) => {
|
|
18428
18783
|
const waiters = this.turnWaiters.get(id) ?? /* @__PURE__ */ new Set();
|
|
18429
|
-
waiters.add(
|
|
18784
|
+
waiters.add(resolve17);
|
|
18430
18785
|
this.turnWaiters.set(id, waiters);
|
|
18431
18786
|
});
|
|
18432
18787
|
}
|
|
@@ -18544,7 +18899,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18544
18899
|
this.queuedAgentPrompts.delete(sessionId);
|
|
18545
18900
|
this.queuedRiskPolicies.delete(sessionId);
|
|
18546
18901
|
this.queueRuns.delete(sessionId);
|
|
18547
|
-
for (const
|
|
18902
|
+
for (const resolve17 of this.turnWaiters.get(sessionId) ?? []) resolve17();
|
|
18548
18903
|
this.turnWaiters.delete(sessionId);
|
|
18549
18904
|
for (const key of this.permissions.keys()) if (key.startsWith(`${sessionId}:`)) this.permissions.delete(key);
|
|
18550
18905
|
}
|
|
@@ -18593,7 +18948,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18593
18948
|
this.driverEventChains.clear();
|
|
18594
18949
|
this.driverEventErrors.clear();
|
|
18595
18950
|
this.openToolCalls.clear();
|
|
18596
|
-
for (const waiters of this.turnWaiters.values()) for (const
|
|
18951
|
+
for (const waiters of this.turnWaiters.values()) for (const resolve17 of waiters) resolve17();
|
|
18597
18952
|
this.turnWaiters.clear();
|
|
18598
18953
|
this.queues.clear();
|
|
18599
18954
|
this.queuedAgentPrompts.clear();
|
|
@@ -18607,7 +18962,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18607
18962
|
init_src2();
|
|
18608
18963
|
import { z as z3 } from "zod";
|
|
18609
18964
|
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
18610
|
-
import { resolve as
|
|
18965
|
+
import { resolve as resolve4 } from "node:path";
|
|
18611
18966
|
var appConfigSchema = z3.object({
|
|
18612
18967
|
host: z3.string().default("0.0.0.0"),
|
|
18613
18968
|
port: z3.number().int().positive().default(4310),
|
|
@@ -18641,7 +18996,8 @@ var agentDetails = {
|
|
|
18641
18996
|
qoder: { name: "Qoder", cli: "qodercli" },
|
|
18642
18997
|
qwen: { name: "Qwen Code", cli: "qwen" },
|
|
18643
18998
|
trae: { name: "Trae", cli: "traecli" },
|
|
18644
|
-
zeroclaw: { name: "ZeroClaw", cli: "zeroclaw" }
|
|
18999
|
+
zeroclaw: { name: "ZeroClaw", cli: "zeroclaw" },
|
|
19000
|
+
antigravity: { name: "Google Antigravity", cli: ["agy", "antigravity"], argvExecutable: true }
|
|
18645
19001
|
};
|
|
18646
19002
|
function cliVersion(command, prefixArgs = []) {
|
|
18647
19003
|
for (const args of [["--version"], ["-V"], ["version"]]) {
|
|
@@ -18653,15 +19009,35 @@ ${result.stderr ?? ""}`.split(/\r?\n/).map((value) => value.trim()).find(Boolean
|
|
|
18653
19009
|
return void 0;
|
|
18654
19010
|
}
|
|
18655
19011
|
var scannedBuiltinAgents;
|
|
18656
|
-
|
|
18657
|
-
const
|
|
18658
|
-
|
|
18659
|
-
return
|
|
18660
|
-
|
|
19012
|
+
function discoverBuiltinAgents(entries = listAcpxBuiltinAgents(), dependencies = {}) {
|
|
19013
|
+
const exists = dependencies.commandExists ?? commandExists;
|
|
19014
|
+
const version = dependencies.cliVersion ?? cliVersion;
|
|
19015
|
+
return entries.flatMap(({ id, argv }) => {
|
|
19016
|
+
const detail = agentDetails[id];
|
|
19017
|
+
if (!detail) return [];
|
|
19018
|
+
const commands = Array.isArray(detail.cli) ? detail.cli : [detail.cli];
|
|
19019
|
+
const installed = commands.some(exists) || Boolean(detail.argvExecutable && argv[0] && exists(argv[0]));
|
|
19020
|
+
if (!installed) return [];
|
|
19021
|
+
return [{
|
|
19022
|
+
id,
|
|
19023
|
+
name: detail.name,
|
|
19024
|
+
command: argv[0],
|
|
19025
|
+
args: argv.slice(1),
|
|
19026
|
+
protocol: "acp",
|
|
19027
|
+
env: {},
|
|
19028
|
+
permissionMode: "full-trust",
|
|
19029
|
+
timeout: 600,
|
|
19030
|
+
capabilities: { pause: false, resume: true },
|
|
19031
|
+
builtin: true,
|
|
19032
|
+
version: id === "antigravity" ? version(argv[0]) : id === "codex" ? version(argv[0], argv.slice(1)) : version(commands[0])
|
|
19033
|
+
}];
|
|
19034
|
+
});
|
|
19035
|
+
}
|
|
19036
|
+
var scanBuiltinAgents = () => scannedBuiltinAgents ??= discoverBuiltinAgents();
|
|
18661
19037
|
var builtinAgents = (cwd = process.cwd()) => scanBuiltinAgents().map((agent) => ({ ...agent, cwd }));
|
|
18662
19038
|
function loadConfig(env = process.env) {
|
|
18663
19039
|
const extra = env.AGENTDOCK_AGENTS_JSON ? JSON.parse(env.AGENTDOCK_AGENTS_JSON) : [];
|
|
18664
|
-
const defaultCwd =
|
|
19040
|
+
const defaultCwd = resolve4(env.AGENTDOCK_DEFAULT_CWD ?? process.cwd());
|
|
18665
19041
|
const agents = new Map(builtinAgents(defaultCwd).map((agent) => [agent.id, agent]));
|
|
18666
19042
|
for (const agent of extra) {
|
|
18667
19043
|
const configured = agentConfigSchema.parse(agent);
|
|
@@ -18670,7 +19046,7 @@ function loadConfig(env = process.env) {
|
|
|
18670
19046
|
return appConfigSchema.parse({
|
|
18671
19047
|
host: env.AGENTDOCK_LOCAL_ONLY === "true" ? "127.0.0.1" : env.AGENTDOCK_HOST,
|
|
18672
19048
|
port: env.AGENTDOCK_PORT ? Number(env.AGENTDOCK_PORT) : void 0,
|
|
18673
|
-
databaseUrl:
|
|
19049
|
+
databaseUrl: resolve4(defaultCwd, env.AGENTDOCK_DATABASE_URL ?? "./.agentdock/agentdock.db"),
|
|
18674
19050
|
acpxCommand: env.AGENTDOCK_ACPX_COMMAND,
|
|
18675
19051
|
driverIdleTimeoutMs: env.AGENTDOCK_DRIVER_IDLE_TIMEOUT_MS ? Number(env.AGENTDOCK_DRIVER_IDLE_TIMEOUT_MS) : void 0,
|
|
18676
19052
|
cleanupIntervalMs: env.AGENTDOCK_CLEANUP_INTERVAL_MS ? Number(env.AGENTDOCK_CLEANUP_INTERVAL_MS) : void 0,
|
|
@@ -18688,13 +19064,13 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
|
18688
19064
|
init_src2();
|
|
18689
19065
|
init_daemon();
|
|
18690
19066
|
import { spawn as spawn7 } from "node:child_process";
|
|
18691
|
-
import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as
|
|
19067
|
+
import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync3 } from "node:fs";
|
|
18692
19068
|
import { homedir as homedir5 } from "node:os";
|
|
18693
19069
|
import { dirname as dirname7, join as join8 } from "node:path";
|
|
18694
19070
|
|
|
18695
19071
|
// src/update.ts
|
|
18696
19072
|
import { execFile as execFile3 } from "node:child_process";
|
|
18697
|
-
import { resolve as
|
|
19073
|
+
import { resolve as resolve5 } from "node:path";
|
|
18698
19074
|
import { promisify as promisify2 } from "node:util";
|
|
18699
19075
|
var execFileAsync2 = promisify2(execFile3);
|
|
18700
19076
|
var DEFAULT_PACKAGE_NAME = "@agent-dock/cli";
|
|
@@ -18738,7 +19114,7 @@ async function updateAgentDock(currentVersion, options, dependencies) {
|
|
|
18738
19114
|
}
|
|
18739
19115
|
const globalRoot = (await dependencies.runNpm(["root", "--global"])).trim();
|
|
18740
19116
|
if (!globalRoot) throw new Error("npm did not report its global package directory. The service was not restarted.");
|
|
18741
|
-
await dependencies.restart(
|
|
19117
|
+
await dependencies.restart(resolve5(globalRoot, packageName, "dist/cli.js"));
|
|
18742
19118
|
return {
|
|
18743
19119
|
action: "update",
|
|
18744
19120
|
packageName,
|
|
@@ -18889,7 +19265,7 @@ var SelfUpdateService = class {
|
|
|
18889
19265
|
*/
|
|
18890
19266
|
lockHeld() {
|
|
18891
19267
|
try {
|
|
18892
|
-
if (this.now() -
|
|
19268
|
+
if (this.now() - statSync4(this.lockFile).mtimeMs > UPDATE_LOCK_MAX_AGE_MS) return false;
|
|
18893
19269
|
return pidAlive(Number(readFileSync5(this.lockFile, "utf8").trim()));
|
|
18894
19270
|
} catch {
|
|
18895
19271
|
return false;
|
|
@@ -18977,8 +19353,8 @@ import Fastify from "fastify";
|
|
|
18977
19353
|
import cors from "@fastify/cors";
|
|
18978
19354
|
import { readFile as readFile12, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
|
|
18979
19355
|
import { Readable as Readable3 } from "node:stream";
|
|
18980
|
-
import { extname, join as
|
|
18981
|
-
import { homedir as
|
|
19356
|
+
import { extname as extname2, join as join20, resolve as resolve10, sep as sep3 } from "node:path";
|
|
19357
|
+
import { homedir as homedir15 } from "node:os";
|
|
18982
19358
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
18983
19359
|
|
|
18984
19360
|
// src/lark/routes.ts
|
|
@@ -18993,7 +19369,7 @@ init_listener();
|
|
|
18993
19369
|
// src/lark/security-hooks.ts
|
|
18994
19370
|
init_service();
|
|
18995
19371
|
import { access as access2, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
|
|
18996
|
-
import { constants as
|
|
19372
|
+
import { constants as constants3 } from "node:fs";
|
|
18997
19373
|
import { dirname as dirname8, join as join10 } from "node:path";
|
|
18998
19374
|
var guardVersion = "agentdock-high-risk-guard-v2";
|
|
18999
19375
|
var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
|
|
@@ -19117,7 +19493,7 @@ async function larkHookStatus(agentId, workspace) {
|
|
|
19117
19493
|
const { hooksPath } = paths(adapter, workspace);
|
|
19118
19494
|
let writable = true;
|
|
19119
19495
|
try {
|
|
19120
|
-
await access2(workspace,
|
|
19496
|
+
await access2(workspace, constants3.W_OK);
|
|
19121
19497
|
} catch {
|
|
19122
19498
|
writable = false;
|
|
19123
19499
|
}
|
|
@@ -21016,7 +21392,7 @@ async function discoverAgentModels(agent, model, forceRefresh = false) {
|
|
|
21016
21392
|
import { spawn as spawn8 } from "node:child_process";
|
|
21017
21393
|
import { existsSync as existsSync7, readFileSync as readFileSync6, readdirSync } from "node:fs";
|
|
21018
21394
|
import { homedir as homedir6 } from "node:os";
|
|
21019
|
-
import { dirname as dirname9, isAbsolute as
|
|
21395
|
+
import { dirname as dirname9, isAbsolute as isAbsolute5, join as join12, resolve as resolve7 } from "node:path";
|
|
21020
21396
|
var MAX_INCLUDE_DEPTH = 4;
|
|
21021
21397
|
function isValidSshHost(host) {
|
|
21022
21398
|
return /^[A-Za-z0-9][A-Za-z0-9._@:+-]*$/.test(host);
|
|
@@ -21035,7 +21411,7 @@ function splitDirective(line) {
|
|
|
21035
21411
|
}
|
|
21036
21412
|
function expandInclude(pattern, baseDir) {
|
|
21037
21413
|
const expanded = pattern.replace(/^~(?=$|\/)/, homedir6());
|
|
21038
|
-
const absolute =
|
|
21414
|
+
const absolute = isAbsolute5(expanded) ? expanded : resolve7(baseDir, expanded);
|
|
21039
21415
|
if (!/[*?]/.test(absolute)) return [absolute];
|
|
21040
21416
|
const directory = dirname9(absolute);
|
|
21041
21417
|
const namePattern = absolute.slice(directory.length + 1);
|
|
@@ -21153,7 +21529,7 @@ printf 'codex=%s\\n' "$(command -v codex 2>/dev/null)"
|
|
|
21153
21529
|
printf 'home=%s\\n' "$HOME"
|
|
21154
21530
|
`;
|
|
21155
21531
|
function runSsh(host, script, timeoutMs) {
|
|
21156
|
-
return new Promise((
|
|
21532
|
+
return new Promise((resolve17) => {
|
|
21157
21533
|
let stdout = "";
|
|
21158
21534
|
let stderr = "";
|
|
21159
21535
|
let settled = false;
|
|
@@ -21163,12 +21539,12 @@ function runSsh(host, script, timeoutMs) {
|
|
|
21163
21539
|
if (settled) return;
|
|
21164
21540
|
settled = true;
|
|
21165
21541
|
clearTimeout(timer);
|
|
21166
|
-
|
|
21542
|
+
resolve17(result);
|
|
21167
21543
|
};
|
|
21168
21544
|
try {
|
|
21169
21545
|
child = spawn8("ssh", [...sshArgs(host), `sh -c ${shellQuote3(script)}`], { stdio: ["ignore", "pipe", "pipe"] });
|
|
21170
21546
|
} catch (error) {
|
|
21171
|
-
|
|
21547
|
+
resolve17({ code: null, stdout, stderr, timedOut: false, error: error instanceof Error ? error.message : String(error) });
|
|
21172
21548
|
return;
|
|
21173
21549
|
}
|
|
21174
21550
|
const timer = setTimeout(() => {
|
|
@@ -21265,7 +21641,7 @@ function normalizeCodexUsage(result, checkedAt = Date.now()) {
|
|
|
21265
21641
|
return { status: "available", plan: bucket.planType ?? void 0, windows, checkedAt };
|
|
21266
21642
|
}
|
|
21267
21643
|
function readFromCodex() {
|
|
21268
|
-
return new Promise((
|
|
21644
|
+
return new Promise((resolve17) => {
|
|
21269
21645
|
let settled = false;
|
|
21270
21646
|
let buffer = "";
|
|
21271
21647
|
let child;
|
|
@@ -21274,7 +21650,7 @@ function readFromCodex() {
|
|
|
21274
21650
|
settled = true;
|
|
21275
21651
|
clearTimeout(timer);
|
|
21276
21652
|
child?.kill();
|
|
21277
|
-
|
|
21653
|
+
resolve17(usage);
|
|
21278
21654
|
};
|
|
21279
21655
|
const unavailable = (reason) => ({ status: "unavailable", reason, windows: [], checkedAt: Date.now() });
|
|
21280
21656
|
const timer = setTimeout(() => done(unavailable("Codex \u989D\u5EA6\u67E5\u8BE2\u8D85\u65F6")), 8e3);
|
|
@@ -21532,7 +21908,7 @@ import { promisify as promisify5 } from "node:util";
|
|
|
21532
21908
|
// src/skill-catalog.ts
|
|
21533
21909
|
import { readFile as readFile9, readdir as readdir2 } from "node:fs/promises";
|
|
21534
21910
|
import { homedir as homedir10 } from "node:os";
|
|
21535
|
-
import { basename as basename4, dirname as dirname10, join as join16, resolve as
|
|
21911
|
+
import { basename as basename4, dirname as dirname10, join as join16, resolve as resolve8 } from "node:path";
|
|
21536
21912
|
var ignoredDirectories = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build"]);
|
|
21537
21913
|
async function findSkillFiles(root4, maxDepth = 5) {
|
|
21538
21914
|
const found = [];
|
|
@@ -21558,7 +21934,7 @@ function frontmatterValue(markdown, key) {
|
|
|
21558
21934
|
return value.replace(/^['"]|['"]$/g, "");
|
|
21559
21935
|
}
|
|
21560
21936
|
async function discoverSkills(workspace) {
|
|
21561
|
-
const workspaceRoot =
|
|
21937
|
+
const workspaceRoot = resolve8(workspace?.trim() || process.cwd());
|
|
21562
21938
|
const roots = [
|
|
21563
21939
|
{ path: join16(workspaceRoot, ".agents", "skills"), source: "workspace" },
|
|
21564
21940
|
{ path: join16(workspaceRoot, ".codex", "skills"), source: "workspace" },
|
|
@@ -22217,11 +22593,11 @@ function isSourceIngressRequest(method, pathname) {
|
|
|
22217
22593
|
// src/sources-router/routes.ts
|
|
22218
22594
|
init_src2();
|
|
22219
22595
|
import { Readable as Readable2 } from "node:stream";
|
|
22220
|
-
import { z as
|
|
22596
|
+
import { z as z6 } from "zod";
|
|
22221
22597
|
|
|
22222
22598
|
// src/sources-router/ingress.ts
|
|
22223
22599
|
init_src2();
|
|
22224
|
-
import { z as
|
|
22600
|
+
import { z as z5 } from "zod";
|
|
22225
22601
|
|
|
22226
22602
|
// src/sources-router/types.ts
|
|
22227
22603
|
function publicSource(source2) {
|
|
@@ -22232,22 +22608,22 @@ function publicSource(source2) {
|
|
|
22232
22608
|
// src/sources-router/ingress.ts
|
|
22233
22609
|
var defaultBodyLimitBytes = 1024 * 1024;
|
|
22234
22610
|
var defaultSignatureToleranceMs = 5 * 6e4;
|
|
22235
|
-
var objectSchema =
|
|
22236
|
-
var actorSchema =
|
|
22237
|
-
var envelopeSchema =
|
|
22238
|
-
specVersion:
|
|
22239
|
-
sourceId:
|
|
22240
|
-
eventId:
|
|
22241
|
-
eventType:
|
|
22242
|
-
dedupeKey:
|
|
22243
|
-
occurredAt:
|
|
22611
|
+
var objectSchema = z5.object({ type: z5.string().min(1), id: z5.string().min(1), url: z5.string().optional(), title: z5.string().optional() });
|
|
22612
|
+
var actorSchema = z5.object({ id: z5.string().optional(), name: z5.string().optional(), isBot: z5.boolean().optional() }).optional();
|
|
22613
|
+
var envelopeSchema = z5.object({
|
|
22614
|
+
specVersion: z5.literal("agentdock.source.v1"),
|
|
22615
|
+
sourceId: z5.string().min(1),
|
|
22616
|
+
eventId: z5.string().min(1),
|
|
22617
|
+
eventType: z5.string().min(1),
|
|
22618
|
+
dedupeKey: z5.string().min(1),
|
|
22619
|
+
occurredAt: z5.string().datetime(),
|
|
22244
22620
|
object: objectSchema,
|
|
22245
22621
|
actor: actorSchema,
|
|
22246
|
-
correlationKey:
|
|
22247
|
-
payload:
|
|
22248
|
-
raw:
|
|
22249
|
-
causationId:
|
|
22250
|
-
traceId:
|
|
22622
|
+
correlationKey: z5.string().min(1).optional(),
|
|
22623
|
+
payload: z5.record(z5.string(), z5.unknown()).default({}),
|
|
22624
|
+
raw: z5.string().optional(),
|
|
22625
|
+
causationId: z5.string().nullable().optional(),
|
|
22626
|
+
traceId: z5.string().min(1)
|
|
22251
22627
|
}).strict();
|
|
22252
22628
|
var IngressError = class extends RuntimeError {
|
|
22253
22629
|
constructor(code, message, statusCode) {
|
|
@@ -22257,19 +22633,19 @@ var IngressError = class extends RuntimeError {
|
|
|
22257
22633
|
};
|
|
22258
22634
|
|
|
22259
22635
|
// src/sources-router/routes.ts
|
|
22260
|
-
var createSourceSchema =
|
|
22261
|
-
name:
|
|
22262
|
-
kind:
|
|
22263
|
-
enabled:
|
|
22264
|
-
config:
|
|
22265
|
-
secretRefs:
|
|
22266
|
-
secrets:
|
|
22636
|
+
var createSourceSchema = z6.object({
|
|
22637
|
+
name: z6.string().min(1),
|
|
22638
|
+
kind: z6.enum(["webhook", "poll", "stream", "worker"]).optional(),
|
|
22639
|
+
enabled: z6.boolean().optional(),
|
|
22640
|
+
config: z6.record(z6.string(), z6.unknown()).optional(),
|
|
22641
|
+
secretRefs: z6.array(z6.string()).optional(),
|
|
22642
|
+
secrets: z6.record(z6.string(), z6.string()).optional()
|
|
22267
22643
|
}).strict();
|
|
22268
|
-
var updateSourceSchema =
|
|
22269
|
-
name:
|
|
22270
|
-
config:
|
|
22271
|
-
secretRefs:
|
|
22272
|
-
secrets:
|
|
22644
|
+
var updateSourceSchema = z6.object({
|
|
22645
|
+
name: z6.string().min(1).optional(),
|
|
22646
|
+
config: z6.record(z6.string(), z6.unknown()).optional(),
|
|
22647
|
+
secretRefs: z6.array(z6.string()).optional(),
|
|
22648
|
+
secrets: z6.record(z6.string(), z6.string()).optional()
|
|
22273
22649
|
}).strict();
|
|
22274
22650
|
function asHeaders(request) {
|
|
22275
22651
|
return request.headers;
|
|
@@ -22685,16 +23061,17 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
|
|
|
22685
23061
|
init_src2();
|
|
22686
23062
|
import { realpathSync as realpathSync3 } from "node:fs";
|
|
22687
23063
|
import { readdir as readdir3, readFile as readFile10, stat as stat4 } from "node:fs/promises";
|
|
22688
|
-
import { isAbsolute as
|
|
23064
|
+
import { basename as basename6, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
|
|
22689
23065
|
|
|
22690
23066
|
// src/fs-paths.ts
|
|
22691
|
-
import { realpathSync as realpathSync2 } from "node:fs";
|
|
22692
|
-
import {
|
|
23067
|
+
import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
|
|
23068
|
+
import { homedir as homedir12, tmpdir as tmpdir3 } from "node:os";
|
|
23069
|
+
import { basename as basename5, isAbsolute as isAbsolute6, join as join17, resolve as resolve9, sep } from "node:path";
|
|
22693
23070
|
function resolveInsideRoot(root4, userPath) {
|
|
22694
23071
|
const normalized2 = (userPath ?? "").trim();
|
|
22695
|
-
if (
|
|
22696
|
-
const absolute =
|
|
22697
|
-
const rootResolved =
|
|
23072
|
+
if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
|
|
23073
|
+
const absolute = resolve9(root4, normalized2);
|
|
23074
|
+
const rootResolved = resolve9(root4);
|
|
22698
23075
|
if (absolute !== rootResolved && !absolute.startsWith(`${rootResolved}${sep}`)) {
|
|
22699
23076
|
throw new WorkspacePathError("\u8DEF\u5F84\u8D85\u51FA\u5DE5\u4F5C\u533A\u8303\u56F4");
|
|
22700
23077
|
}
|
|
@@ -22717,6 +23094,95 @@ var WorkspacePathError = class extends Error {
|
|
|
22717
23094
|
this.name = "WorkspacePathError";
|
|
22718
23095
|
}
|
|
22719
23096
|
};
|
|
23097
|
+
var sensitiveExactNames = /* @__PURE__ */ new Set([
|
|
23098
|
+
".env",
|
|
23099
|
+
".npmrc",
|
|
23100
|
+
".netrc",
|
|
23101
|
+
".pypirc",
|
|
23102
|
+
".dockercfg",
|
|
23103
|
+
".htpasswd",
|
|
23104
|
+
"auth.json",
|
|
23105
|
+
"credentials.json",
|
|
23106
|
+
".credentials.json",
|
|
23107
|
+
"secrets.json",
|
|
23108
|
+
"token.json"
|
|
23109
|
+
]);
|
|
23110
|
+
var sensitiveExtensions = /* @__PURE__ */ new Set([
|
|
23111
|
+
".key",
|
|
23112
|
+
".pem",
|
|
23113
|
+
".p12",
|
|
23114
|
+
".pfx",
|
|
23115
|
+
".jks",
|
|
23116
|
+
".keystore"
|
|
23117
|
+
]);
|
|
23118
|
+
var sensitiveKeyPrefixPattern = /^id_(?:rsa|ed25519|ecdsa|dsa)(?:\..+)?$/i;
|
|
23119
|
+
function isSensitivePath(targetPath) {
|
|
23120
|
+
const normalized2 = targetPath.replace(/\\/g, "/");
|
|
23121
|
+
const segments = normalized2.split("/").filter(Boolean);
|
|
23122
|
+
if (!segments.length) return false;
|
|
23123
|
+
for (let i = 0; i < segments.length; i++) {
|
|
23124
|
+
const seg = segments[i].toLowerCase();
|
|
23125
|
+
if (seg === ".ssh" || seg === ".gnupg") return true;
|
|
23126
|
+
if (seg === ".aws" && segments[i + 1]?.toLowerCase() === "credentials") return true;
|
|
23127
|
+
if (seg === ".kube" && segments[i + 1]?.toLowerCase() === "config") return true;
|
|
23128
|
+
}
|
|
23129
|
+
const name = basename5(normalized2).toLowerCase();
|
|
23130
|
+
if (sensitiveExactNames.has(name)) return true;
|
|
23131
|
+
if (name.startsWith(".env.")) return true;
|
|
23132
|
+
if (sensitiveKeyPrefixPattern.test(name)) return true;
|
|
23133
|
+
if (name.startsWith("service-account") && name.endsWith(".json")) return true;
|
|
23134
|
+
const dot = name.lastIndexOf(".");
|
|
23135
|
+
if (dot >= 0 && sensitiveExtensions.has(name.slice(dot))) return true;
|
|
23136
|
+
return false;
|
|
23137
|
+
}
|
|
23138
|
+
function allowedReadRoots(options) {
|
|
23139
|
+
const home = options.homeDir ?? homedir12();
|
|
23140
|
+
const candidates = [options.cwd];
|
|
23141
|
+
if (options.role === "session") {
|
|
23142
|
+
if (options.sessionId) {
|
|
23143
|
+
candidates.push(join17(home, ".agentdock", "uploads", options.sessionId));
|
|
23144
|
+
}
|
|
23145
|
+
} else {
|
|
23146
|
+
candidates.push(
|
|
23147
|
+
join17(home, ".agentdock", "uploads"),
|
|
23148
|
+
join17(home, ".gemini"),
|
|
23149
|
+
"/tmp",
|
|
23150
|
+
"/private/tmp",
|
|
23151
|
+
options.tempDir ?? tmpdir3(),
|
|
23152
|
+
...options.extraMasterRoots ?? []
|
|
23153
|
+
);
|
|
23154
|
+
}
|
|
23155
|
+
const resolved = [];
|
|
23156
|
+
const seen = /* @__PURE__ */ new Set();
|
|
23157
|
+
for (const candidate of candidates) {
|
|
23158
|
+
if (!candidate || !existsSync8(candidate)) continue;
|
|
23159
|
+
try {
|
|
23160
|
+
const real = realpathSync2(candidate);
|
|
23161
|
+
if (!seen.has(real)) {
|
|
23162
|
+
seen.add(real);
|
|
23163
|
+
resolved.push(real);
|
|
23164
|
+
}
|
|
23165
|
+
} catch {
|
|
23166
|
+
}
|
|
23167
|
+
}
|
|
23168
|
+
return resolved;
|
|
23169
|
+
}
|
|
23170
|
+
function isRealPathWithinRoots(realTarget, realRoots) {
|
|
23171
|
+
return realRoots.some((root4) => realTarget === root4 || realTarget.startsWith(`${root4}${sep}`));
|
|
23172
|
+
}
|
|
23173
|
+
function isBinaryBuffer(buffer) {
|
|
23174
|
+
const len = Math.min(buffer.length, 8192);
|
|
23175
|
+
if (len === 0) return false;
|
|
23176
|
+
let suspicious = 0;
|
|
23177
|
+
for (let i = 0; i < len; i++) {
|
|
23178
|
+
const byte = buffer[i];
|
|
23179
|
+
if (byte === 0) return true;
|
|
23180
|
+
if (byte < 7 || byte > 14 && byte < 32 && byte !== 27) {
|
|
23181
|
+
suspicious++;
|
|
23182
|
+
}
|
|
23183
|
+
}
|
|
23184
|
+
return suspicious / len > 0.3;
|
|
23185
|
+
}
|
|
22720
23186
|
var textExtensions = /* @__PURE__ */ new Set([
|
|
22721
23187
|
".txt",
|
|
22722
23188
|
".md",
|
|
@@ -22729,7 +23195,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22729
23195
|
".ini",
|
|
22730
23196
|
".cfg",
|
|
22731
23197
|
".conf",
|
|
22732
|
-
".env",
|
|
22733
23198
|
".csv",
|
|
22734
23199
|
".tsv",
|
|
22735
23200
|
".js",
|
|
@@ -22765,7 +23230,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22765
23230
|
".scss",
|
|
22766
23231
|
".less",
|
|
22767
23232
|
".xml",
|
|
22768
|
-
".svg",
|
|
22769
23233
|
".vue",
|
|
22770
23234
|
".svelte",
|
|
22771
23235
|
".sql",
|
|
@@ -22778,7 +23242,6 @@ var textExtensions = /* @__PURE__ */ new Set([
|
|
|
22778
23242
|
".editorconfig",
|
|
22779
23243
|
".eslintrc",
|
|
22780
23244
|
".prettierrc",
|
|
22781
|
-
".npmrc",
|
|
22782
23245
|
".lock",
|
|
22783
23246
|
".sum",
|
|
22784
23247
|
".mod",
|
|
@@ -22797,8 +23260,8 @@ function previewKindForName(name) {
|
|
|
22797
23260
|
const lower = name.toLowerCase();
|
|
22798
23261
|
const dot = lower.lastIndexOf(".");
|
|
22799
23262
|
const ext = dot >= 0 ? lower.slice(dot) : lower;
|
|
22800
|
-
if (textExtensions.has(ext)) return "text";
|
|
22801
23263
|
if (imageExtensions.has(ext)) return "image";
|
|
23264
|
+
if (textExtensions.has(ext)) return "text";
|
|
22802
23265
|
if (ext === ".pdf") return "pdf";
|
|
22803
23266
|
return "unsupported";
|
|
22804
23267
|
}
|
|
@@ -22819,15 +23282,23 @@ function imageMimeForName(name) {
|
|
|
22819
23282
|
|
|
22820
23283
|
// src/fs-routes.ts
|
|
22821
23284
|
function badPath(error) {
|
|
23285
|
+
if (error instanceof RuntimeError) throw error;
|
|
22822
23286
|
if (error instanceof WorkspacePathError) throw new RuntimeError("INVALID_PATH", error.message, 400);
|
|
22823
23287
|
if (error?.code === "ENOENT") throw new RuntimeError("PATH_NOT_FOUND", "\u8DEF\u5F84\u4E0D\u5B58\u5728", 404);
|
|
22824
23288
|
if (error?.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
|
|
22825
23289
|
throw error;
|
|
22826
23290
|
}
|
|
22827
|
-
|
|
23291
|
+
function contentDispositionAttachment(filename) {
|
|
23292
|
+
const safeAscii = filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
|
|
23293
|
+
return `attachment; filename="${safeAscii}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
|
|
23294
|
+
}
|
|
23295
|
+
async function registerFsRoutes(app, runtime, options = {}) {
|
|
22828
23296
|
app.get("/api/sessions/:id/fs/list", async (request) => {
|
|
22829
23297
|
const session = await runtime.getSession(request.params.id);
|
|
22830
23298
|
if (!session) throw new RuntimeError("SESSION_NOT_FOUND", "Session not found", 404);
|
|
23299
|
+
if (session.sshHost) {
|
|
23300
|
+
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);
|
|
23301
|
+
}
|
|
22831
23302
|
const userPath = request.query.path ?? "";
|
|
22832
23303
|
let resolved;
|
|
22833
23304
|
try {
|
|
@@ -22839,9 +23310,7 @@ async function registerFsRoutes(app, runtime) {
|
|
|
22839
23310
|
try {
|
|
22840
23311
|
names = await readdir3(resolved.absolute);
|
|
22841
23312
|
} catch (error) {
|
|
22842
|
-
|
|
22843
|
-
if (error.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
|
|
22844
|
-
throw error;
|
|
23313
|
+
badPath(error);
|
|
22845
23314
|
}
|
|
22846
23315
|
const entries = [];
|
|
22847
23316
|
await Promise.all(names.map(async (name) => {
|
|
@@ -22858,43 +23327,96 @@ async function registerFsRoutes(app, runtime) {
|
|
|
22858
23327
|
app.get("/api/sessions/:id/fs/read", async (request, reply) => {
|
|
22859
23328
|
const session = await runtime.getSession(request.params.id);
|
|
22860
23329
|
if (!session) throw new RuntimeError("SESSION_NOT_FOUND", "Session not found", 404);
|
|
23330
|
+
if (session.sshHost) {
|
|
23331
|
+
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);
|
|
23332
|
+
}
|
|
22861
23333
|
const userPath = request.query.path;
|
|
22862
23334
|
if (!userPath) throw new RuntimeError("INVALID_PATH", "\u7F3A\u5C11 path \u53C2\u6570", 400);
|
|
23335
|
+
if (isSensitivePath(userPath)) {
|
|
23336
|
+
throw new RuntimeError("SENSITIVE_FILE_BLOCKED", "\u7981\u6B62\u9884\u89C8\u6216\u4E0B\u8F7D\u654F\u611F\u6587\u4EF6", 403);
|
|
23337
|
+
}
|
|
23338
|
+
const claim = request.webClaim;
|
|
23339
|
+
const role = claim?.kind === "session" ? "session" : "master";
|
|
22863
23340
|
let resolved;
|
|
22864
23341
|
try {
|
|
22865
|
-
if (
|
|
23342
|
+
if (isAbsolute7(userPath)) {
|
|
23343
|
+
const realTarget = realpathSync3(userPath);
|
|
23344
|
+
const roots = allowedReadRoots({
|
|
23345
|
+
role,
|
|
23346
|
+
cwd: session.cwd,
|
|
23347
|
+
sessionId: request.params.id,
|
|
23348
|
+
...options.homeDir ? { homeDir: options.homeDir } : {},
|
|
23349
|
+
...options.tempDir ? { tempDir: options.tempDir } : {},
|
|
23350
|
+
...options.extraMasterRoots ? { extraMasterRoots: options.extraMasterRoots } : {}
|
|
23351
|
+
});
|
|
23352
|
+
if (!isRealPathWithinRoots(realTarget, roots)) {
|
|
23353
|
+
throw new RuntimeError(
|
|
23354
|
+
"FORBIDDEN",
|
|
23355
|
+
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",
|
|
23356
|
+
403
|
|
23357
|
+
);
|
|
23358
|
+
}
|
|
23359
|
+
let rel = userPath;
|
|
22866
23360
|
try {
|
|
22867
|
-
|
|
23361
|
+
const realCwd = realpathSync3(session.cwd);
|
|
23362
|
+
if (realTarget === realCwd || realTarget.startsWith(`${realCwd}${sep2}`)) {
|
|
23363
|
+
rel = relative(realCwd, realTarget);
|
|
23364
|
+
}
|
|
22868
23365
|
} catch {
|
|
22869
|
-
const claim = request.webClaim;
|
|
22870
|
-
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);
|
|
22871
|
-
resolved = { absolute: realpathSync3(userPath), relative: userPath };
|
|
22872
23366
|
}
|
|
23367
|
+
resolved = { absolute: realTarget, relative: rel };
|
|
22873
23368
|
} else {
|
|
22874
23369
|
resolved = resolveExistingInside(session.cwd, userPath);
|
|
22875
23370
|
}
|
|
22876
23371
|
} catch (error) {
|
|
22877
23372
|
badPath(error);
|
|
22878
23373
|
}
|
|
23374
|
+
if (isSensitivePath(resolved.absolute)) {
|
|
23375
|
+
throw new RuntimeError("SENSITIVE_FILE_BLOCKED", "\u7981\u6B62\u9884\u89C8\u6216\u4E0B\u8F7D\u654F\u611F\u6587\u4EF6", 403);
|
|
23376
|
+
}
|
|
22879
23377
|
let info;
|
|
22880
23378
|
try {
|
|
22881
23379
|
info = await stat4(resolved.absolute);
|
|
22882
23380
|
} catch (error) {
|
|
22883
|
-
|
|
22884
|
-
throw error;
|
|
23381
|
+
badPath(error);
|
|
22885
23382
|
}
|
|
22886
23383
|
if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
|
|
22887
|
-
const
|
|
22888
|
-
|
|
22889
|
-
const
|
|
22890
|
-
|
|
23384
|
+
const filename = basename6(resolved.absolute);
|
|
23385
|
+
const isSvg = filename.toLowerCase().endsWith(".svg");
|
|
23386
|
+
const wantDownload = request.query.download === "1" || request.query.download === "true";
|
|
23387
|
+
const wantText = request.query.format === "text";
|
|
23388
|
+
if (wantDownload) {
|
|
23389
|
+
if (info.size > maxDocumentPreviewBytes) {
|
|
23390
|
+
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);
|
|
23391
|
+
}
|
|
23392
|
+
const buffer2 = await readFile10(resolved.absolute);
|
|
23393
|
+
reply.header("Content-Type", imageMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream"));
|
|
23394
|
+
reply.header("Content-Disposition", contentDispositionAttachment(filename));
|
|
23395
|
+
reply.header("X-Content-Type-Options", "nosniff");
|
|
23396
|
+
if (isSvg) reply.header("Content-Security-Policy", "sandbox");
|
|
23397
|
+
reply.header("Cache-Control", "private, no-store");
|
|
23398
|
+
return reply.send(buffer2);
|
|
23399
|
+
}
|
|
23400
|
+
const baseKind = previewKindForName(filename);
|
|
23401
|
+
const effectiveKind = wantText && (baseKind === "text" || isSvg) ? "text" : baseKind;
|
|
23402
|
+
if (effectiveKind === "unsupported") {
|
|
23403
|
+
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);
|
|
23404
|
+
}
|
|
23405
|
+
const maxBytes = effectiveKind === "text" ? maxTextPreviewBytes : maxDocumentPreviewBytes;
|
|
23406
|
+
if (info.size > maxBytes) {
|
|
23407
|
+
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);
|
|
23408
|
+
}
|
|
22891
23409
|
const buffer = await readFile10(resolved.absolute);
|
|
22892
|
-
if (
|
|
22893
|
-
reply.header("Content-Type",
|
|
23410
|
+
if (effectiveKind === "image" || effectiveKind === "pdf") {
|
|
23411
|
+
reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
|
|
22894
23412
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
23413
|
+
if (isSvg) reply.header("Content-Security-Policy", "sandbox");
|
|
22895
23414
|
reply.header("Cache-Control", "private, max-age=60");
|
|
22896
23415
|
return reply.send(buffer);
|
|
22897
23416
|
}
|
|
23417
|
+
if (isBinaryBuffer(buffer)) {
|
|
23418
|
+
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);
|
|
23419
|
+
}
|
|
22898
23420
|
return { cwd: session.cwd, path: resolved.relative, size: info.size, content: buffer.toString("utf8") };
|
|
22899
23421
|
});
|
|
22900
23422
|
}
|
|
@@ -22963,7 +23485,7 @@ async function readSseEvents(body, onEach) {
|
|
|
22963
23485
|
}
|
|
22964
23486
|
|
|
22965
23487
|
// src/llm/types.ts
|
|
22966
|
-
import { z as
|
|
23488
|
+
import { z as z7 } from "zod";
|
|
22967
23489
|
var llmFormats = ["openai-chat", "openai-responses", "anthropic-messages"];
|
|
22968
23490
|
var llmAuthTypes = ["api-key", "bearer"];
|
|
22969
23491
|
var llmErrorCodes = {
|
|
@@ -22980,20 +23502,20 @@ var llmErrorCodes = {
|
|
|
22980
23502
|
empty: "LLM_EMPTY_REPLY",
|
|
22981
23503
|
abandoned: "LLM_STREAM_ABANDONED"
|
|
22982
23504
|
};
|
|
22983
|
-
var baseUrlSchema =
|
|
22984
|
-
var apiKeySchema =
|
|
22985
|
-
var modelSchema =
|
|
22986
|
-
var llmEndpointInputSchema =
|
|
22987
|
-
format:
|
|
23505
|
+
var baseUrlSchema = z7.string().trim().min(1, "Base URL \u4E0D\u80FD\u4E3A\u7A7A");
|
|
23506
|
+
var apiKeySchema = z7.string();
|
|
23507
|
+
var modelSchema = z7.string().trim().min(1, "\u6A21\u578B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
23508
|
+
var llmEndpointInputSchema = z7.object({
|
|
23509
|
+
format: z7.enum(llmFormats),
|
|
22988
23510
|
baseUrl: baseUrlSchema,
|
|
22989
23511
|
apiKey: apiKeySchema.optional(),
|
|
22990
|
-
auth:
|
|
23512
|
+
auth: z7.enum(llmAuthTypes).optional(),
|
|
22991
23513
|
model: modelSchema,
|
|
22992
|
-
systemPrompt:
|
|
22993
|
-
maxTokens:
|
|
23514
|
+
systemPrompt: z7.string().optional(),
|
|
23515
|
+
maxTokens: z7.number().int().positive().optional(),
|
|
22994
23516
|
// 区间取三种格式的交集:Anthropic 只接受 0..1,照 0..2 校验会让用户在 anthropic 上撞 400。
|
|
22995
|
-
temperature:
|
|
22996
|
-
timeoutMs:
|
|
23517
|
+
temperature: z7.number().min(0).max(1).optional(),
|
|
23518
|
+
timeoutMs: z7.number().int().positive().optional()
|
|
22997
23519
|
});
|
|
22998
23520
|
function normalizeBaseUrl(input) {
|
|
22999
23521
|
const trimmed = input.trim();
|
|
@@ -23316,8 +23838,8 @@ var LlmClient = class {
|
|
|
23316
23838
|
|
|
23317
23839
|
// src/llm/detect.ts
|
|
23318
23840
|
import { readFile as readFile11 } from "node:fs/promises";
|
|
23319
|
-
import { homedir as
|
|
23320
|
-
import { join as
|
|
23841
|
+
import { homedir as homedir13 } from "node:os";
|
|
23842
|
+
import { join as join18 } from "node:path";
|
|
23321
23843
|
var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
23322
23844
|
async function readJson(path5) {
|
|
23323
23845
|
try {
|
|
@@ -23447,9 +23969,9 @@ function codexCandidate(configText, env) {
|
|
|
23447
23969
|
}
|
|
23448
23970
|
async function detectLlmEndpoints(options = {}) {
|
|
23449
23971
|
const env = options.env ?? process.env;
|
|
23450
|
-
const home = options.home ??
|
|
23972
|
+
const home = options.home ?? homedir13();
|
|
23451
23973
|
const candidates = [];
|
|
23452
|
-
const settings = await readJson(
|
|
23974
|
+
const settings = await readJson(join18(home, ".claude", "settings.json"));
|
|
23453
23975
|
const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
|
|
23454
23976
|
const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
|
|
23455
23977
|
if (fromSettings) candidates.push(fromSettings);
|
|
@@ -23457,7 +23979,7 @@ async function detectLlmEndpoints(options = {}) {
|
|
|
23457
23979
|
if (fromEnv) candidates.push(fromEnv);
|
|
23458
23980
|
const openai = openAiCandidate(env);
|
|
23459
23981
|
if (openai) candidates.push(openai);
|
|
23460
|
-
const codexConfig = await readText(
|
|
23982
|
+
const codexConfig = await readText(join18(home, ".codex", "config.toml"));
|
|
23461
23983
|
if (codexConfig) {
|
|
23462
23984
|
const codex = codexCandidate(codexConfig, env);
|
|
23463
23985
|
if (codex) candidates.push(codex);
|
|
@@ -23644,9 +24166,12 @@ data: ${JSON.stringify(data)}
|
|
|
23644
24166
|
});
|
|
23645
24167
|
}
|
|
23646
24168
|
|
|
24169
|
+
// src/app.ts
|
|
24170
|
+
init_side_chat_config();
|
|
24171
|
+
|
|
23647
24172
|
// src/json-compression.ts
|
|
23648
24173
|
import { promisify as promisify6 } from "node:util";
|
|
23649
|
-
import { brotliCompress, constants as
|
|
24174
|
+
import { brotliCompress, constants as constants4, gzip } from "node:zlib";
|
|
23650
24175
|
var brotli = promisify6(brotliCompress);
|
|
23651
24176
|
var gzipAsync = promisify6(gzip);
|
|
23652
24177
|
var JSON_COMPRESSION_THRESHOLD = 32 * 1024;
|
|
@@ -23672,7 +24197,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
|
|
|
23672
24197
|
if (size < threshold) return payload;
|
|
23673
24198
|
const encoding = pickJsonEncoding(request.headers["accept-encoding"]);
|
|
23674
24199
|
if (!encoding) return payload;
|
|
23675
|
-
const body = encoding === "br" ? await brotli(payload, { params: { [
|
|
24200
|
+
const body = encoding === "br" ? await brotli(payload, { params: { [constants4.BROTLI_PARAM_MODE]: constants4.BROTLI_MODE_TEXT, [constants4.BROTLI_PARAM_QUALITY]: 4, [constants4.BROTLI_PARAM_SIZE_HINT]: size } }) : await gzipAsync(payload, { level: 6 });
|
|
23676
24201
|
reply.header("content-encoding", encoding);
|
|
23677
24202
|
const vary = String(reply.getHeader("vary") ?? "");
|
|
23678
24203
|
if (!/(^|,)\s*accept-encoding\s*(,|$)/i.test(vary)) reply.header("vary", vary ? `${vary}, Accept-Encoding` : "Accept-Encoding");
|
|
@@ -23683,17 +24208,17 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
|
|
|
23683
24208
|
|
|
23684
24209
|
// src/web-password.ts
|
|
23685
24210
|
import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
23686
|
-
import { chmodSync as chmodSync2, existsSync as
|
|
23687
|
-
import { homedir as
|
|
23688
|
-
import { dirname as dirname11, join as
|
|
24211
|
+
import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
24212
|
+
import { homedir as homedir14 } from "node:os";
|
|
24213
|
+
import { dirname as dirname11, join as join19 } from "node:path";
|
|
23689
24214
|
var webPasswordFileName = "web-password";
|
|
23690
24215
|
var SCRYPT_N = 16384;
|
|
23691
24216
|
var SCRYPT_R = 8;
|
|
23692
24217
|
var SCRYPT_P = 1;
|
|
23693
24218
|
var KEY_LENGTH = 32;
|
|
23694
24219
|
var minWebPasswordLength = 6;
|
|
23695
|
-
function webPasswordPath(home =
|
|
23696
|
-
return
|
|
24220
|
+
function webPasswordPath(home = homedir14()) {
|
|
24221
|
+
return join19(home, ".agentdock", webPasswordFileName);
|
|
23697
24222
|
}
|
|
23698
24223
|
function hashWebPassword(password) {
|
|
23699
24224
|
const salt = randomBytes3(16);
|
|
@@ -23733,7 +24258,7 @@ function setWebPassword(password, path5 = webPasswordPath()) {
|
|
|
23733
24258
|
chmodSync2(path5, 384);
|
|
23734
24259
|
}
|
|
23735
24260
|
function clearWebPassword(path5 = webPasswordPath()) {
|
|
23736
|
-
if (!
|
|
24261
|
+
if (!existsSync9(path5)) return false;
|
|
23737
24262
|
rmSync3(path5, { force: true });
|
|
23738
24263
|
return true;
|
|
23739
24264
|
}
|
|
@@ -24068,7 +24593,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24068
24593
|
} catch (error) {
|
|
24069
24594
|
const detail = describeAcpError(error);
|
|
24070
24595
|
if (attempt < 3 && /active writer/i.test(detail)) {
|
|
24071
|
-
await new Promise((
|
|
24596
|
+
await new Promise((resolve17) => setTimeout(resolve17, 1200));
|
|
24072
24597
|
continue;
|
|
24073
24598
|
}
|
|
24074
24599
|
throw error;
|
|
@@ -24153,7 +24678,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24153
24678
|
return await loadExternalSessionTranscript(effective, session.sourceId, session.cwd, { timeoutMs: 6e4 });
|
|
24154
24679
|
} catch (error) {
|
|
24155
24680
|
if (attempt < 3 && /active writer/i.test(describeAcpError(error))) {
|
|
24156
|
-
await new Promise((
|
|
24681
|
+
await new Promise((resolve17) => setTimeout(resolve17, 1200));
|
|
24157
24682
|
continue;
|
|
24158
24683
|
}
|
|
24159
24684
|
throw error;
|
|
@@ -24198,6 +24723,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24198
24723
|
});
|
|
24199
24724
|
await registerFsRoutes(app, runtime);
|
|
24200
24725
|
await registerLlmRoutes(app, options.llm);
|
|
24726
|
+
if (options.sideChatConfig) registerSideChatConfigRoutes(app, options.sideChatConfig);
|
|
24201
24727
|
const mimeToExt = {
|
|
24202
24728
|
"image/png": ".png",
|
|
24203
24729
|
"image/jpeg": ".jpg",
|
|
@@ -24231,7 +24757,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24231
24757
|
"audio/flac": ".flac",
|
|
24232
24758
|
"application/octet-stream": ""
|
|
24233
24759
|
};
|
|
24234
|
-
const globalUploadRoot =
|
|
24760
|
+
const globalUploadRoot = join20(homedir15(), ".agentdock", "uploads");
|
|
24235
24761
|
const uploadTtlMs = 7 * 24 * 60 * 6e4;
|
|
24236
24762
|
const collectExpiredUploads = async (now2 = Date.now()) => {
|
|
24237
24763
|
let removedFiles = 0;
|
|
@@ -24242,7 +24768,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24242
24768
|
return { removedFiles };
|
|
24243
24769
|
}
|
|
24244
24770
|
for (const sessionDir of sessionDirs) {
|
|
24245
|
-
const directory =
|
|
24771
|
+
const directory = join20(globalUploadRoot, sessionDir);
|
|
24246
24772
|
let names;
|
|
24247
24773
|
try {
|
|
24248
24774
|
names = await readdir4(directory);
|
|
@@ -24250,7 +24776,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24250
24776
|
continue;
|
|
24251
24777
|
}
|
|
24252
24778
|
for (const name of names) {
|
|
24253
|
-
const filePath =
|
|
24779
|
+
const filePath = join20(directory, name);
|
|
24254
24780
|
try {
|
|
24255
24781
|
const info = await stat5(filePath);
|
|
24256
24782
|
if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
|
|
@@ -24273,7 +24799,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24273
24799
|
const extFromContentType = (contentType, fallbackName) => {
|
|
24274
24800
|
const known = mimeToExt[contentType];
|
|
24275
24801
|
if (known !== void 0) return known;
|
|
24276
|
-
const suffix = fallbackName ?
|
|
24802
|
+
const suffix = fallbackName ? extname2(fallbackName).toLowerCase() : "";
|
|
24277
24803
|
return /^\.[a-z0-9]{1,8}$/.test(suffix) ? suffix : "";
|
|
24278
24804
|
};
|
|
24279
24805
|
app.post("/api/sessions/:id/uploads", async (request, reply) => {
|
|
@@ -24296,10 +24822,10 @@ async function buildApp(runtime, options = {}) {
|
|
|
24296
24822
|
originalName = rawName;
|
|
24297
24823
|
}
|
|
24298
24824
|
const ext = extFromContentType(contentType, originalName);
|
|
24299
|
-
const uploadDir =
|
|
24825
|
+
const uploadDir = join20(globalUploadRoot, session.id);
|
|
24300
24826
|
await mkdir4(uploadDir, { recursive: true });
|
|
24301
24827
|
const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
|
|
24302
|
-
const filePath =
|
|
24828
|
+
const filePath = join20(uploadDir, filename);
|
|
24303
24829
|
await writeFile4(filePath, buffer);
|
|
24304
24830
|
return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
|
|
24305
24831
|
});
|
|
@@ -24310,13 +24836,14 @@ async function buildApp(runtime, options = {}) {
|
|
|
24310
24836
|
if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
|
|
24311
24837
|
throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
|
|
24312
24838
|
}
|
|
24313
|
-
const filePath =
|
|
24314
|
-
const ext =
|
|
24839
|
+
const filePath = join20(globalUploadRoot, session.id, filename);
|
|
24840
|
+
const ext = extname2(filename).toLowerCase();
|
|
24315
24841
|
const data = await readFile12(filePath);
|
|
24316
24842
|
reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
|
|
24317
24843
|
reply.header("Cache-Control", "public, max-age=31536000, immutable");
|
|
24318
24844
|
reply.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
24319
24845
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
24846
|
+
if (ext === ".svg") reply.header("Content-Security-Policy", "sandbox");
|
|
24320
24847
|
return reply.send(data);
|
|
24321
24848
|
});
|
|
24322
24849
|
app.get("/api/sessions/:id/stream", async (request, reply) => {
|
|
@@ -24333,11 +24860,11 @@ event: ${event.type}
|
|
|
24333
24860
|
data: ${JSON.stringify(event)}
|
|
24334
24861
|
|
|
24335
24862
|
`);
|
|
24336
|
-
const drain = () => new Promise((
|
|
24863
|
+
const drain = () => new Promise((resolve17) => {
|
|
24337
24864
|
const finish = () => {
|
|
24338
24865
|
reply.raw.off("drain", finish);
|
|
24339
24866
|
reply.raw.off("close", finish);
|
|
24340
|
-
|
|
24867
|
+
resolve17();
|
|
24341
24868
|
};
|
|
24342
24869
|
reply.raw.once("drain", finish);
|
|
24343
24870
|
reply.raw.once("close", finish);
|
|
@@ -24355,25 +24882,25 @@ data: ${JSON.stringify(event)}
|
|
|
24355
24882
|
});
|
|
24356
24883
|
});
|
|
24357
24884
|
if (options.webRoot) {
|
|
24358
|
-
const webRoot =
|
|
24359
|
-
const indexFile =
|
|
24885
|
+
const webRoot = resolve10(options.webRoot);
|
|
24886
|
+
const indexFile = resolve10(webRoot, "index.html");
|
|
24360
24887
|
app.setNotFoundHandler(async (request, reply) => {
|
|
24361
24888
|
if (request.method !== "GET" && request.method !== "HEAD") return reply.code(404).send({ error: { code: "NOT_FOUND", message: "Route not found" } });
|
|
24362
24889
|
const pathname = new URL(request.url, "http://agent-dock.local").pathname;
|
|
24363
24890
|
if (pathname.startsWith("/api/") || pathname === "/api") return reply.code(404).send({ error: { code: "NOT_FOUND", message: "API route not found" } });
|
|
24364
24891
|
let requestedFile;
|
|
24365
24892
|
try {
|
|
24366
|
-
requestedFile =
|
|
24893
|
+
requestedFile = resolve10(webRoot, decodeURIComponent(pathname).replace(/^\/+/, ""));
|
|
24367
24894
|
} catch {
|
|
24368
24895
|
return reply.code(400).send({ error: { code: "INVALID_PATH", message: "Invalid URL path" } });
|
|
24369
24896
|
}
|
|
24370
|
-
if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${
|
|
24897
|
+
if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${sep3}`)) return reply.code(404).send();
|
|
24371
24898
|
let file = requestedFile;
|
|
24372
24899
|
let body;
|
|
24373
24900
|
try {
|
|
24374
24901
|
body = await readFile12(file);
|
|
24375
24902
|
} catch {
|
|
24376
|
-
if (
|
|
24903
|
+
if (extname2(pathname)) return reply.code(404).send();
|
|
24377
24904
|
file = indexFile;
|
|
24378
24905
|
try {
|
|
24379
24906
|
body = await readFile12(file);
|
|
@@ -24381,7 +24908,7 @@ data: ${JSON.stringify(event)}
|
|
|
24381
24908
|
return reply.code(404).send({ error: { code: "WEB_UI_NOT_FOUND", message: "Web UI is not installed" } });
|
|
24382
24909
|
}
|
|
24383
24910
|
}
|
|
24384
|
-
const type2 = contentTypes[
|
|
24911
|
+
const type2 = contentTypes[extname2(file).toLowerCase()] ?? "application/octet-stream";
|
|
24385
24912
|
if (pathname.startsWith("/assets/")) reply.header("Cache-Control", "public, max-age=31536000, immutable");
|
|
24386
24913
|
else if (file === indexFile) reply.header("Cache-Control", "no-cache, must-revalidate");
|
|
24387
24914
|
return reply.type(type2).send(request.method === "HEAD" ? void 0 : body);
|
|
@@ -24395,6 +24922,7 @@ init_handover_binding();
|
|
|
24395
24922
|
init_agent_tools();
|
|
24396
24923
|
init_config();
|
|
24397
24924
|
init_service();
|
|
24925
|
+
init_side_chat_config();
|
|
24398
24926
|
|
|
24399
24927
|
// src/lark-avatar/service.ts
|
|
24400
24928
|
init_src2();
|
|
@@ -25958,7 +26486,7 @@ var LarkProtocolClient = class {
|
|
|
25958
26486
|
}
|
|
25959
26487
|
async connectOnce() {
|
|
25960
26488
|
const url = await this.buildWsUrl();
|
|
25961
|
-
return new Promise((
|
|
26489
|
+
return new Promise((resolve17, reject2) => {
|
|
25962
26490
|
const ws = new WebSocket(url, {
|
|
25963
26491
|
headers: { "user-agent": USER_AGENT2 },
|
|
25964
26492
|
handshakeTimeout: 15e3
|
|
@@ -25986,7 +26514,7 @@ var LarkProtocolClient = class {
|
|
|
25986
26514
|
this.clearHeartbeat();
|
|
25987
26515
|
});
|
|
25988
26516
|
this.startHeartbeat(ws);
|
|
25989
|
-
|
|
26517
|
+
resolve17(ws);
|
|
25990
26518
|
});
|
|
25991
26519
|
ws.once("error", (error) => fail(error));
|
|
25992
26520
|
ws.once("close", () => fail(new Error("WebSocket closed before open")));
|
|
@@ -25994,14 +26522,14 @@ var LarkProtocolClient = class {
|
|
|
25994
26522
|
}
|
|
25995
26523
|
waitForClose(ws) {
|
|
25996
26524
|
if (ws.readyState === WebSocket.CLOSED) return Promise.resolve();
|
|
25997
|
-
return new Promise((
|
|
25998
|
-
ws.once("close", () =>
|
|
26525
|
+
return new Promise((resolve17) => {
|
|
26526
|
+
ws.once("close", () => resolve17());
|
|
25999
26527
|
});
|
|
26000
26528
|
}
|
|
26001
26529
|
async sleep(ms) {
|
|
26002
26530
|
const deadline = Date.now() + ms;
|
|
26003
26531
|
while (this.running && Date.now() < deadline) {
|
|
26004
|
-
await new Promise((
|
|
26532
|
+
await new Promise((resolve17) => setTimeout(resolve17, Math.min(250, deadline - Date.now())));
|
|
26005
26533
|
}
|
|
26006
26534
|
}
|
|
26007
26535
|
startHeartbeat(ws) {
|
|
@@ -27330,8 +27858,8 @@ var LarkAvatarService = class {
|
|
|
27330
27858
|
let sentAny = false;
|
|
27331
27859
|
const buffered = [];
|
|
27332
27860
|
let resolveDone;
|
|
27333
|
-
const done = new Promise((
|
|
27334
|
-
resolveDone =
|
|
27861
|
+
const done = new Promise((resolve17) => {
|
|
27862
|
+
resolveDone = resolve17;
|
|
27335
27863
|
});
|
|
27336
27864
|
const flush = () => {
|
|
27337
27865
|
if (flushTimer) {
|
|
@@ -27415,12 +27943,12 @@ var LarkAvatarService = class {
|
|
|
27415
27943
|
const pending = buffered.splice(0);
|
|
27416
27944
|
for (const event of pending) handle(event);
|
|
27417
27945
|
const timeoutMs = input.timeoutMs ?? 0;
|
|
27418
|
-
const timeoutPromise = timeoutMs > 0 ? new Promise((
|
|
27946
|
+
const timeoutPromise = timeoutMs > 0 ? new Promise((resolve17) => {
|
|
27419
27947
|
timeout = setTimeout(() => {
|
|
27420
27948
|
terminal = "timeout";
|
|
27421
27949
|
settled = true;
|
|
27422
27950
|
flush();
|
|
27423
|
-
|
|
27951
|
+
resolve17();
|
|
27424
27952
|
}, timeoutMs);
|
|
27425
27953
|
timeout.unref?.();
|
|
27426
27954
|
}) : void 0;
|
|
@@ -28119,7 +28647,7 @@ ${signature}` : body;
|
|
|
28119
28647
|
if (activeTurns.length) {
|
|
28120
28648
|
await Promise.race([
|
|
28121
28649
|
Promise.allSettled(activeTurns),
|
|
28122
|
-
new Promise((
|
|
28650
|
+
new Promise((resolve17) => setTimeout(resolve17, 5e3))
|
|
28123
28651
|
]);
|
|
28124
28652
|
}
|
|
28125
28653
|
if (this.ownsStore) this.store.close();
|
|
@@ -30912,29 +31440,29 @@ function withContext(percent2) {
|
|
|
30912
31440
|
|
|
30913
31441
|
// src/assistant/cwd.ts
|
|
30914
31442
|
init_src2();
|
|
30915
|
-
import { accessSync, constants as
|
|
30916
|
-
import { homedir as
|
|
30917
|
-
import { isAbsolute as
|
|
31443
|
+
import { accessSync as accessSync2, constants as constants5, statSync as statSync5 } from "node:fs";
|
|
31444
|
+
import { homedir as homedir16 } from "node:os";
|
|
31445
|
+
import { isAbsolute as isAbsolute8, resolve as resolve11 } from "node:path";
|
|
30918
31446
|
function expandHomePath(value) {
|
|
30919
31447
|
const trimmed = value.trim();
|
|
30920
|
-
if (trimmed === "~") return
|
|
30921
|
-
if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return
|
|
31448
|
+
if (trimmed === "~") return homedir16();
|
|
31449
|
+
if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve11(homedir16(), trimmed.slice(2));
|
|
30922
31450
|
return trimmed;
|
|
30923
31451
|
}
|
|
30924
31452
|
function resolveCwdArgument(value, base = process.cwd()) {
|
|
30925
|
-
return
|
|
31453
|
+
return resolve11(base, expandHomePath(value));
|
|
30926
31454
|
}
|
|
30927
31455
|
function validateCwd(value) {
|
|
30928
31456
|
const trimmed = value?.trim();
|
|
30929
31457
|
if (!trimmed) return void 0;
|
|
30930
31458
|
const expanded = expandHomePath(trimmed);
|
|
30931
|
-
if (!
|
|
31459
|
+
if (!isAbsolute8(expanded)) {
|
|
30932
31460
|
throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF1A${trimmed}`, 400);
|
|
30933
31461
|
}
|
|
30934
|
-
const absolute =
|
|
31462
|
+
const absolute = resolve11(expanded);
|
|
30935
31463
|
let stats;
|
|
30936
31464
|
try {
|
|
30937
|
-
stats =
|
|
31465
|
+
stats = statSync5(absolute);
|
|
30938
31466
|
} catch {
|
|
30939
31467
|
throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${absolute}`, 400);
|
|
30940
31468
|
}
|
|
@@ -30942,7 +31470,7 @@ function validateCwd(value) {
|
|
|
30942
31470
|
throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${absolute}`, 400);
|
|
30943
31471
|
}
|
|
30944
31472
|
try {
|
|
30945
|
-
|
|
31473
|
+
accessSync2(absolute, constants5.R_OK | constants5.X_OK);
|
|
30946
31474
|
} catch {
|
|
30947
31475
|
throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u8BBF\u95EE\uFF08\u9700\u8981\u8BFB\u548C\u6267\u884C\u6743\u9650\uFF09\uFF1A${absolute}`, 400);
|
|
30948
31476
|
}
|
|
@@ -32190,7 +32718,7 @@ function parseGithubTarget(value) {
|
|
|
32190
32718
|
}
|
|
32191
32719
|
async function runWatchCommand(watch) {
|
|
32192
32720
|
const shell = resolveLoginShell();
|
|
32193
|
-
return await new Promise((
|
|
32721
|
+
return await new Promise((resolve17) => {
|
|
32194
32722
|
const child = spawn11(shell.file, [...shell.args, "-c", watch.command], {
|
|
32195
32723
|
cwd: watch.cwd ?? process.cwd(),
|
|
32196
32724
|
env: { ...process.env, agentdock_watch_id: watch.id, agentdock_session_id: watch.ownerSessionId },
|
|
@@ -32223,7 +32751,7 @@ async function runWatchCommand(watch) {
|
|
|
32223
32751
|
if (settled) return;
|
|
32224
32752
|
settled = true;
|
|
32225
32753
|
clearTimeout(timer);
|
|
32226
|
-
|
|
32754
|
+
resolve17({ exitCode, output: output3.trim() });
|
|
32227
32755
|
};
|
|
32228
32756
|
child.on("error", (error) => {
|
|
32229
32757
|
append(Buffer.from(String(error)));
|
|
@@ -32312,6 +32840,7 @@ async function startLocalServer(options = {}) {
|
|
|
32312
32840
|
}
|
|
32313
32841
|
const webRoot = options.webRoot ?? fileURLToPath5(new URL("../public", import.meta.url));
|
|
32314
32842
|
const llm = new LlmEndpointService({ config: repos.config });
|
|
32843
|
+
const sideChatConfig = new SideChatConfigService({ config: repos.config, listAgents: () => runtime.listAgents() });
|
|
32315
32844
|
const packageJson2 = JSON.parse(readFileSync9(new URL("../package.json", import.meta.url), "utf8"));
|
|
32316
32845
|
const selfUpdate = options.cliEntrypoint ? new SelfUpdateService({ currentVersion: packageJson2.version, packageName: packageJson2.name, cliEntrypoint: options.cliEntrypoint, env }) : void 0;
|
|
32317
32846
|
schedules2 = new ScheduleService(repos.schedules, repos.sessions, runtime);
|
|
@@ -32364,7 +32893,7 @@ async function startLocalServer(options = {}) {
|
|
|
32364
32893
|
keepAwake = new KeepAwakeService({ config: repos.config });
|
|
32365
32894
|
await keepAwake.restore();
|
|
32366
32895
|
const shareLinks = new ShareLinkService({ host: config.host, port: config.port, secret: webAuth.secret ?? "", config: repos.config, env });
|
|
32367
|
-
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 });
|
|
32896
|
+
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 });
|
|
32368
32897
|
await app.listen(listenOptions(config));
|
|
32369
32898
|
schedules2.start();
|
|
32370
32899
|
assistant?.start();
|
|
@@ -32448,7 +32977,7 @@ init_session_cli();
|
|
|
32448
32977
|
init_config();
|
|
32449
32978
|
init_message_content();
|
|
32450
32979
|
init_service();
|
|
32451
|
-
import { existsSync as
|
|
32980
|
+
import { existsSync as existsSync11 } from "node:fs";
|
|
32452
32981
|
var output = (deps) => deps.stdout ?? process.stdout;
|
|
32453
32982
|
var errorOutput = (deps) => deps.stderr ?? process.stderr;
|
|
32454
32983
|
var envOf = (deps) => deps.env ?? process.env;
|
|
@@ -32460,7 +32989,7 @@ var noBotError = () => new Error(
|
|
|
32460
32989
|
async function loadStoredConfigs(deps) {
|
|
32461
32990
|
if (deps.configs) return deps.configs;
|
|
32462
32991
|
const filename = resolveDatabasePath();
|
|
32463
|
-
if (!
|
|
32992
|
+
if (!existsSync11(filename)) return [];
|
|
32464
32993
|
try {
|
|
32465
32994
|
const repositories = createRepositories(filename);
|
|
32466
32995
|
try {
|
|
@@ -32789,8 +33318,8 @@ async function runLarkMessageListen(options, deps = {}) {
|
|
|
32789
33318
|
let writeChain = Promise.resolve();
|
|
32790
33319
|
let resolveDone;
|
|
32791
33320
|
let rejectDone;
|
|
32792
|
-
const done = new Promise((
|
|
32793
|
-
resolveDone =
|
|
33321
|
+
const done = new Promise((resolve17, reject2) => {
|
|
33322
|
+
resolveDone = resolve17;
|
|
32794
33323
|
rejectDone = reject2;
|
|
32795
33324
|
});
|
|
32796
33325
|
const cleanup = () => {
|
|
@@ -32988,15 +33517,30 @@ async function runLarkAvatarReactionRoute(options) {
|
|
|
32988
33517
|
|
|
32989
33518
|
// src/acpx.ts
|
|
32990
33519
|
import { spawn as spawn12 } from "node:child_process";
|
|
33520
|
+
import { readFileSync as readFileSync11 } from "node:fs";
|
|
33521
|
+
import { createRequire as createRequire3 } from "node:module";
|
|
33522
|
+
import { dirname as dirname12, resolve as resolve13 } from "node:path";
|
|
32991
33523
|
function acpxPassThroughArgs(argv) {
|
|
32992
33524
|
return argv[2] === "acpx" ? argv.slice(3) : void 0;
|
|
32993
33525
|
}
|
|
32994
|
-
function
|
|
32995
|
-
|
|
33526
|
+
function resolveAcpxLauncher(moduleUrl = import.meta.url) {
|
|
33527
|
+
try {
|
|
33528
|
+
const require2 = createRequire3(moduleUrl);
|
|
33529
|
+
const manifestPath = require2.resolve("acpx/package.json");
|
|
33530
|
+
const manifest = JSON.parse(readFileSync11(manifestPath, "utf8"));
|
|
33531
|
+
const relative2 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.acpx;
|
|
33532
|
+
if (relative2) return { command: process.execPath, args: [resolve13(dirname12(manifestPath), relative2)] };
|
|
33533
|
+
} catch {
|
|
33534
|
+
return { command: "acpx", args: [] };
|
|
33535
|
+
}
|
|
33536
|
+
return { command: "acpx", args: [] };
|
|
33537
|
+
}
|
|
33538
|
+
function runAcpx(args, spawnProcess = spawn12, launcher = resolveAcpxLauncher()) {
|
|
33539
|
+
return new Promise((resolve17, reject2) => {
|
|
32996
33540
|
const options = { stdio: "inherit", env: process.env };
|
|
32997
|
-
const child = spawnProcess(
|
|
33541
|
+
const child = spawnProcess(launcher.command, [...launcher.args, ...args], options);
|
|
32998
33542
|
child.once("error", reject2);
|
|
32999
|
-
child.once("exit", (code, signal) =>
|
|
33543
|
+
child.once("exit", (code, signal) => resolve17(code ?? (signal ? 1 : 0)));
|
|
33000
33544
|
});
|
|
33001
33545
|
}
|
|
33002
33546
|
|
|
@@ -33132,8 +33676,8 @@ init_agent_tools();
|
|
|
33132
33676
|
// src/daemon/command.ts
|
|
33133
33677
|
init_daemon();
|
|
33134
33678
|
init_time();
|
|
33135
|
-
import { readFileSync as
|
|
33136
|
-
import { resolve as
|
|
33679
|
+
import { readFileSync as readFileSync12 } from "node:fs";
|
|
33680
|
+
import { resolve as resolve14 } from "node:path";
|
|
33137
33681
|
var STARTUP_LOG_MAX_BYTES = 16 * 1024;
|
|
33138
33682
|
var READY_TIMEOUT_MS = 15e3;
|
|
33139
33683
|
var RESTART_HOST_ENV = "AGENTDOCK_DAEMON_RESTART_HOST";
|
|
@@ -33162,8 +33706,8 @@ function markDaemonReady(dir, patch = {}) {
|
|
|
33162
33706
|
async function daemonStart(options, handlers, env = process.env) {
|
|
33163
33707
|
const invocationCwd = process.cwd();
|
|
33164
33708
|
const dir = isDaemonChild(env) ? defaultDaemonDir(invocationCwd) : resolveDaemonDir(invocationCwd, env.HOME);
|
|
33165
|
-
const cwd = isDaemonChild(env) ? invocationCwd :
|
|
33166
|
-
const database =
|
|
33709
|
+
const cwd = isDaemonChild(env) ? invocationCwd : resolve14(dir, "../..");
|
|
33710
|
+
const database = resolve14(cwd, options.database ?? ".agentdock/agentdock.db");
|
|
33167
33711
|
if (isDaemonChild(env)) {
|
|
33168
33712
|
const meta = childMeta(env);
|
|
33169
33713
|
writePidFile(dir, process.pid);
|
|
@@ -33197,12 +33741,12 @@ async function daemonStart(options, handlers, env = process.env) {
|
|
|
33197
33741
|
function readStartupLog(logFile, startOffset, maxBytes = STARTUP_LOG_MAX_BYTES) {
|
|
33198
33742
|
let size = 0;
|
|
33199
33743
|
try {
|
|
33200
|
-
size =
|
|
33744
|
+
size = readFileSync12(logFile).length;
|
|
33201
33745
|
} catch {
|
|
33202
33746
|
return "";
|
|
33203
33747
|
}
|
|
33204
33748
|
const begin = Math.max(0, startOffset, size - maxBytes);
|
|
33205
|
-
const buf =
|
|
33749
|
+
const buf = readFileSync12(logFile, { encoding: "utf8" });
|
|
33206
33750
|
return buf.slice(begin).trim();
|
|
33207
33751
|
}
|
|
33208
33752
|
async function waitUntilReady(dir, logFile, startOffset) {
|
|
@@ -33401,25 +33945,25 @@ init_session_cli();
|
|
|
33401
33945
|
|
|
33402
33946
|
// src/dev-sandbox.ts
|
|
33403
33947
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
33404
|
-
import { chmodSync as chmodSync3, existsSync as
|
|
33948
|
+
import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
|
|
33405
33949
|
import { createServer } from "node:net";
|
|
33406
|
-
import { delimiter, dirname as
|
|
33950
|
+
import { delimiter as delimiter2, dirname as dirname13, join as join22, resolve as resolve15 } from "node:path";
|
|
33407
33951
|
init_daemon();
|
|
33408
33952
|
var SANDBOX_FILE = "sandbox.json";
|
|
33409
33953
|
function findRepoRoot(start = process.cwd()) {
|
|
33410
|
-
let dir =
|
|
33954
|
+
let dir = resolve15(start);
|
|
33411
33955
|
for (; ; ) {
|
|
33412
|
-
if (
|
|
33413
|
-
const parent =
|
|
33956
|
+
if (existsSync12(join22(dir, "apps", "server", "package.json")) && existsSync12(join22(dir, "pnpm-workspace.yaml"))) return dir;
|
|
33957
|
+
const parent = dirname13(dir);
|
|
33414
33958
|
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");
|
|
33415
33959
|
dir = parent;
|
|
33416
33960
|
}
|
|
33417
33961
|
}
|
|
33418
33962
|
function sandboxPaths(repo, port) {
|
|
33419
|
-
const root4 =
|
|
33420
|
-
return { root: root4, home:
|
|
33963
|
+
const root4 = join22(repo, ".agentdock", "dev");
|
|
33964
|
+
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 };
|
|
33421
33965
|
}
|
|
33422
|
-
var shimDir = (sandbox) =>
|
|
33966
|
+
var shimDir = (sandbox) => join22(sandbox.root, "bin");
|
|
33423
33967
|
function sandboxEnv(sandbox, base = process.env) {
|
|
33424
33968
|
const env = {
|
|
33425
33969
|
...base,
|
|
@@ -33432,7 +33976,7 @@ function sandboxEnv(sandbox, base = process.env) {
|
|
|
33432
33976
|
AGENTDOCK_ALLOW_REACTION_TEST: "true",
|
|
33433
33977
|
agentdock_database: sandbox.database
|
|
33434
33978
|
};
|
|
33435
|
-
env.PATH = [shimDir(sandbox), base.PATH].filter(Boolean).join(
|
|
33979
|
+
env.PATH = [shimDir(sandbox), base.PATH].filter(Boolean).join(delimiter2);
|
|
33436
33980
|
for (const key of ["agentdock_session_id", "agentdock_group_tools_url", "agentdock_group_tools_token"]) delete env[key];
|
|
33437
33981
|
for (const key of [DAEMON_ENV_FLAG, DAEMON_CWD_ENV, DAEMON_STARTED_AT_ENV, DAEMON_DIR_ENV]) delete env[key];
|
|
33438
33982
|
return env;
|
|
@@ -33442,7 +33986,7 @@ function writeCliShim(sandbox, node = process.execPath) {
|
|
|
33442
33986
|
if (process.platform === "win32") return;
|
|
33443
33987
|
const dir = shimDir(sandbox);
|
|
33444
33988
|
mkdirSync6(dir, { recursive: true });
|
|
33445
|
-
const file =
|
|
33989
|
+
const file = join22(dir, "agent-dock");
|
|
33446
33990
|
writeFileSync5(file, `#!/bin/sh
|
|
33447
33991
|
exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
33448
33992
|
`);
|
|
@@ -33450,7 +33994,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
|
33450
33994
|
}
|
|
33451
33995
|
function readSandbox(repo) {
|
|
33452
33996
|
try {
|
|
33453
|
-
return JSON.parse(
|
|
33997
|
+
return JSON.parse(readFileSync13(join22(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
|
|
33454
33998
|
} catch {
|
|
33455
33999
|
return void 0;
|
|
33456
34000
|
}
|
|
@@ -33475,9 +34019,9 @@ async function devUp(options = {}) {
|
|
|
33475
34019
|
const existing = readSandbox(repo);
|
|
33476
34020
|
const port = existing?.port ?? options.port ?? await freePort(4399);
|
|
33477
34021
|
const sandbox = sandboxPaths(repo, port);
|
|
33478
|
-
if (!
|
|
34022
|
+
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`);
|
|
33479
34023
|
for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
|
|
33480
|
-
writeFileSync5(
|
|
34024
|
+
writeFileSync5(join22(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
|
|
33481
34025
|
`);
|
|
33482
34026
|
writeCliShim(sandbox);
|
|
33483
34027
|
const run2 = options.run ?? defaultRun;
|
|
@@ -33526,7 +34070,7 @@ async function readLineFromStdin() {
|
|
|
33526
34070
|
return Buffer.concat(chunks).toString("utf8").split(/\r?\n/)[0] ?? "";
|
|
33527
34071
|
}
|
|
33528
34072
|
function promptHidden(question) {
|
|
33529
|
-
return new Promise((
|
|
34073
|
+
return new Promise((resolve17, reject2) => {
|
|
33530
34074
|
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
33531
34075
|
const output3 = rl;
|
|
33532
34076
|
let prompted = false;
|
|
@@ -33544,7 +34088,7 @@ function promptHidden(question) {
|
|
|
33544
34088
|
rl.question(question, (answer) => {
|
|
33545
34089
|
rl.close();
|
|
33546
34090
|
process.stdout.write("\n");
|
|
33547
|
-
|
|
34091
|
+
resolve17(answer);
|
|
33548
34092
|
});
|
|
33549
34093
|
});
|
|
33550
34094
|
}
|
|
@@ -33691,7 +34235,7 @@ var runScheduleRemove = (id, options = {}) => control(id, "remove", options);
|
|
|
33691
34235
|
|
|
33692
34236
|
// src/assistant/cli.ts
|
|
33693
34237
|
init_session_cli();
|
|
33694
|
-
import { readFileSync as
|
|
34238
|
+
import { readFileSync as readFileSync14 } from "node:fs";
|
|
33695
34239
|
var daemon = () => requireDaemon();
|
|
33696
34240
|
var currentSessionId = () => process.env.agentdock_session_id?.trim() || void 0;
|
|
33697
34241
|
var fromFields = (from) => {
|
|
@@ -33766,8 +34310,8 @@ function formatDrafts(drafts) {
|
|
|
33766
34310
|
return drafts.map((draft) => `${draft.id} [${draft.state}] ${draft.channel} ${draft.target}`).join("\n");
|
|
33767
34311
|
}
|
|
33768
34312
|
function readBody(options) {
|
|
33769
|
-
if (options.bodyFile === "-") return
|
|
33770
|
-
if (options.bodyFile) return
|
|
34313
|
+
if (options.bodyFile === "-") return readFileSync14(0, "utf8");
|
|
34314
|
+
if (options.bodyFile) return readFileSync14(options.bodyFile, "utf8");
|
|
33771
34315
|
throw new Error("\u8BF7\u7528 --body-file - \u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\uFF0C\u6216 --body-file <file>");
|
|
33772
34316
|
}
|
|
33773
34317
|
function parseCheck(value) {
|
|
@@ -33798,7 +34342,7 @@ async function runTaskStart(taskId, options) {
|
|
|
33798
34342
|
if (!title) throw new Error("--title \u5FC5\u586B");
|
|
33799
34343
|
const doneWhen = (options.doneWhen ?? []).map((item) => item.trim()).filter(Boolean);
|
|
33800
34344
|
if (!doneWhen.length) throw new Error("\u81F3\u5C11\u7528 --done-when \u5199\u4E00\u6761\u9A8C\u6536\u6807\u51C6");
|
|
33801
|
-
const notes = options.notesFile === "-" ?
|
|
34345
|
+
const notes = options.notesFile === "-" ? readFileSync14(0, "utf8") : options.notes;
|
|
33802
34346
|
const result = await callDaemon(daemon(), "/api/assistant/tasks", "POST", {
|
|
33803
34347
|
title,
|
|
33804
34348
|
...notes ? { notes } : {},
|
|
@@ -34130,7 +34674,7 @@ async function waitForHandoff(id, options) {
|
|
|
34130
34674
|
if (Date.now() - started > limit) {
|
|
34131
34675
|
throw new Error(`\u4EA4\u63A5 ${id} \u8FD8\u5728\u8FDB\u884C\uFF08${handoffStateLabel[handoff.state] ?? text2(handoff.state)}\uFF09\u3002\u7A0D\u540E\u7528 agent-dock main handoff show ${id} \u67E5\u770B\uFF1B\u5931\u8D25\u4F1A\u81EA\u52A8\u56DE\u6EDA\u3002`);
|
|
34132
34676
|
}
|
|
34133
|
-
await new Promise((
|
|
34677
|
+
await new Promise((resolve17) => setTimeout(resolve17, 1e3));
|
|
34134
34678
|
}
|
|
34135
34679
|
}
|
|
34136
34680
|
async function runMainHandoff(options) {
|
|
@@ -34273,8 +34817,8 @@ async function runNotesUnarchive(options) {
|
|
|
34273
34817
|
init_src();
|
|
34274
34818
|
init_daemon();
|
|
34275
34819
|
init_session_cli();
|
|
34276
|
-
import { readFileSync as
|
|
34277
|
-
import { resolve as
|
|
34820
|
+
import { readFileSync as readFileSync15 } from "node:fs";
|
|
34821
|
+
import { resolve as resolve16 } from "node:path";
|
|
34278
34822
|
|
|
34279
34823
|
// src/sources-router/daemon-call.ts
|
|
34280
34824
|
init_session_cli();
|
|
@@ -35024,7 +35568,7 @@ function runRouterDryRun(fixture, options) {
|
|
|
35024
35568
|
return output2({ sourceId: sourceId2, ...result, persisted: false, createdCase: false, createdSession: false, sentAction: false }, options.json);
|
|
35025
35569
|
}
|
|
35026
35570
|
function readFixture(fixture) {
|
|
35027
|
-
return fixture ?
|
|
35571
|
+
return fixture ? readFileSync15(resolve16(fixture), "utf8") : readFileSync15(0, "utf8");
|
|
35028
35572
|
}
|
|
35029
35573
|
function parseFixture(raw) {
|
|
35030
35574
|
try {
|
|
@@ -35038,7 +35582,7 @@ function dryRunViaDaemon(sourceId2, event) {
|
|
|
35038
35582
|
}
|
|
35039
35583
|
|
|
35040
35584
|
// src/cli.ts
|
|
35041
|
-
var packageJson = JSON.parse(
|
|
35585
|
+
var packageJson = JSON.parse(readFileSync16(new URL("../package.json", import.meta.url), "utf8"));
|
|
35042
35586
|
var interactiveOutput = () => Boolean(process.stdout.isTTY && process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb");
|
|
35043
35587
|
try {
|
|
35044
35588
|
loadEnvFile();
|
|
@@ -35090,12 +35634,12 @@ async function serve(options, onReady) {
|
|
|
35090
35634
|
});
|
|
35091
35635
|
}
|
|
35092
35636
|
async function restartWithInstalledCli(entrypoint) {
|
|
35093
|
-
if (!
|
|
35637
|
+
if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
|
|
35094
35638
|
const previousPid = daemonStatus().pid;
|
|
35095
35639
|
const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
|
|
35096
|
-
await new Promise((
|
|
35640
|
+
await new Promise((resolve17, reject2) => {
|
|
35097
35641
|
child.once("error", reject2);
|
|
35098
|
-
child.once("exit", (code) => code === 0 ?
|
|
35642
|
+
child.once("exit", (code) => code === 0 ? resolve17() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
|
|
35099
35643
|
});
|
|
35100
35644
|
const deadline = Date.now() + 15e3;
|
|
35101
35645
|
while (Date.now() < deadline) {
|