@agent-dock/cli 0.3.15 → 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 CHANGED
@@ -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({
@@ -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;
@@ -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
  };
@@ -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 shouldWake = event.chatType === "p2p" || event.chatType === "group" && mentionsBot;
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 groupKey = larkGroupKey(event, config.groupSessionScope);
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 (!group.boundSessionId && this.cardMappings) {
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 = { id: event.messageId, group, event, prompt: "", resources: [], config, state: "queued", events: [], turn: 0 };
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, { log: this.log, appId: config.appId });
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;
@@ -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) {
@@ -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 existsSync9 } from "node:fs";
5711
- import { join as join20, resolve as resolve12 } from "node:path";
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
6028
  if (explicit) return resolve12(cwd, explicit);
5714
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 ? resolve12(daemonDir, recorded) : join20(daemonDir, "..", "agentdock.db");
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 (!existsSync9(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
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 (!existsSync9(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
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 (!existsSync9(filename)) throw new Error(`\u672A\u627E\u5230 AgentDock \u6570\u636E\u5E93\uFF1A${filename}\u3002daemon \u662F\u5426\u542F\u52A8\u8FC7\uFF1F`);
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 existsSync12, readFileSync as readFileSync16 } from "node:fs";
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";
@@ -7175,12 +7490,12 @@ function resolveInstalledBuiltInAgentLaunch(agentCommand, options = {}) {
7175
7490
  }
7176
7491
  function resolveInstalledBuiltInAgentLaunchForSpec(spec, options) {
7177
7492
  const readFileSync17 = options.readFileSync ?? fs.readFileSync;
7178
- const existsSync13 = options.existsSync ?? fs.existsSync;
7493
+ const existsSync14 = options.existsSync ?? fs.existsSync;
7179
7494
  const resolvePackageRoot = options.resolvePackageRoot ?? defaultResolvePackageRoot;
7180
7495
  try {
7181
7496
  const resolved = resolveInstalledBuiltInAgentPackage(spec, {
7182
7497
  readFileSync: readFileSync17,
7183
- existsSync: existsSync13,
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 existsSync13 = options.existsSync ?? fs.existsSync;
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 (!existsSync13(npmCliPath)) return;
7536
+ if (!existsSync14(npmCliPath)) return;
7222
7537
  return {
7223
7538
  source: "package-exec",
7224
7539
  command: execPath,
@@ -19038,8 +19353,8 @@ import Fastify from "fastify";
19038
19353
  import cors from "@fastify/cors";
19039
19354
  import { readFile as readFile12, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
19040
19355
  import { Readable as Readable3 } from "node:stream";
19041
- import { extname as extname2, join as join19, resolve as resolve10, sep as sep2 } from "node:path";
19042
- import { homedir as homedir14 } from "node:os";
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";
19043
19358
  import { randomBytes as randomBytes4 } from "node:crypto";
19044
19359
 
19045
19360
  // src/lark/routes.ts
@@ -22278,11 +22593,11 @@ function isSourceIngressRequest(method, pathname) {
22278
22593
  // src/sources-router/routes.ts
22279
22594
  init_src2();
22280
22595
  import { Readable as Readable2 } from "node:stream";
22281
- import { z as z5 } from "zod";
22596
+ import { z as z6 } from "zod";
22282
22597
 
22283
22598
  // src/sources-router/ingress.ts
22284
22599
  init_src2();
22285
- import { z as z4 } from "zod";
22600
+ import { z as z5 } from "zod";
22286
22601
 
22287
22602
  // src/sources-router/types.ts
22288
22603
  function publicSource(source2) {
@@ -22293,22 +22608,22 @@ function publicSource(source2) {
22293
22608
  // src/sources-router/ingress.ts
22294
22609
  var defaultBodyLimitBytes = 1024 * 1024;
22295
22610
  var defaultSignatureToleranceMs = 5 * 6e4;
22296
- var objectSchema = z4.object({ type: z4.string().min(1), id: z4.string().min(1), url: z4.string().optional(), title: z4.string().optional() });
22297
- var actorSchema = z4.object({ id: z4.string().optional(), name: z4.string().optional(), isBot: z4.boolean().optional() }).optional();
22298
- var envelopeSchema = z4.object({
22299
- specVersion: z4.literal("agentdock.source.v1"),
22300
- sourceId: z4.string().min(1),
22301
- eventId: z4.string().min(1),
22302
- eventType: z4.string().min(1),
22303
- dedupeKey: z4.string().min(1),
22304
- occurredAt: z4.string().datetime(),
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(),
22305
22620
  object: objectSchema,
22306
22621
  actor: actorSchema,
22307
- correlationKey: z4.string().min(1).optional(),
22308
- payload: z4.record(z4.string(), z4.unknown()).default({}),
22309
- raw: z4.string().optional(),
22310
- causationId: z4.string().nullable().optional(),
22311
- traceId: z4.string().min(1)
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)
22312
22627
  }).strict();
22313
22628
  var IngressError = class extends RuntimeError {
22314
22629
  constructor(code, message, statusCode) {
@@ -22318,19 +22633,19 @@ var IngressError = class extends RuntimeError {
22318
22633
  };
22319
22634
 
22320
22635
  // src/sources-router/routes.ts
22321
- var createSourceSchema = z5.object({
22322
- name: z5.string().min(1),
22323
- kind: z5.enum(["webhook", "poll", "stream", "worker"]).optional(),
22324
- enabled: z5.boolean().optional(),
22325
- config: z5.record(z5.string(), z5.unknown()).optional(),
22326
- secretRefs: z5.array(z5.string()).optional(),
22327
- secrets: z5.record(z5.string(), z5.string()).optional()
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()
22328
22643
  }).strict();
22329
- var updateSourceSchema = z5.object({
22330
- name: z5.string().min(1).optional(),
22331
- config: z5.record(z5.string(), z5.unknown()).optional(),
22332
- secretRefs: z5.array(z5.string()).optional(),
22333
- secrets: z5.record(z5.string(), z5.string()).optional()
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()
22334
22649
  }).strict();
22335
22650
  function asHeaders(request) {
22336
22651
  return request.headers;
@@ -22746,11 +23061,12 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
22746
23061
  init_src2();
22747
23062
  import { realpathSync as realpathSync3 } from "node:fs";
22748
23063
  import { readdir as readdir3, readFile as readFile10, stat as stat4 } from "node:fs/promises";
22749
- import { isAbsolute as isAbsolute7, relative } from "node:path";
23064
+ import { basename as basename6, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
22750
23065
 
22751
23066
  // src/fs-paths.ts
22752
- import { realpathSync as realpathSync2 } from "node:fs";
22753
- import { isAbsolute as isAbsolute6, resolve as resolve9, sep } from "node:path";
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";
22754
23070
  function resolveInsideRoot(root4, userPath) {
22755
23071
  const normalized2 = (userPath ?? "").trim();
22756
23072
  if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
@@ -22778,6 +23094,95 @@ var WorkspacePathError = class extends Error {
22778
23094
  this.name = "WorkspacePathError";
22779
23095
  }
22780
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
+ }
22781
23186
  var textExtensions = /* @__PURE__ */ new Set([
22782
23187
  ".txt",
22783
23188
  ".md",
@@ -22790,7 +23195,6 @@ var textExtensions = /* @__PURE__ */ new Set([
22790
23195
  ".ini",
22791
23196
  ".cfg",
22792
23197
  ".conf",
22793
- ".env",
22794
23198
  ".csv",
22795
23199
  ".tsv",
22796
23200
  ".js",
@@ -22826,7 +23230,6 @@ var textExtensions = /* @__PURE__ */ new Set([
22826
23230
  ".scss",
22827
23231
  ".less",
22828
23232
  ".xml",
22829
- ".svg",
22830
23233
  ".vue",
22831
23234
  ".svelte",
22832
23235
  ".sql",
@@ -22839,7 +23242,6 @@ var textExtensions = /* @__PURE__ */ new Set([
22839
23242
  ".editorconfig",
22840
23243
  ".eslintrc",
22841
23244
  ".prettierrc",
22842
- ".npmrc",
22843
23245
  ".lock",
22844
23246
  ".sum",
22845
23247
  ".mod",
@@ -22858,8 +23260,8 @@ function previewKindForName(name) {
22858
23260
  const lower = name.toLowerCase();
22859
23261
  const dot = lower.lastIndexOf(".");
22860
23262
  const ext = dot >= 0 ? lower.slice(dot) : lower;
22861
- if (textExtensions.has(ext)) return "text";
22862
23263
  if (imageExtensions.has(ext)) return "image";
23264
+ if (textExtensions.has(ext)) return "text";
22863
23265
  if (ext === ".pdf") return "pdf";
22864
23266
  return "unsupported";
22865
23267
  }
@@ -22880,15 +23282,23 @@ function imageMimeForName(name) {
22880
23282
 
22881
23283
  // src/fs-routes.ts
22882
23284
  function badPath(error) {
23285
+ if (error instanceof RuntimeError) throw error;
22883
23286
  if (error instanceof WorkspacePathError) throw new RuntimeError("INVALID_PATH", error.message, 400);
22884
23287
  if (error?.code === "ENOENT") throw new RuntimeError("PATH_NOT_FOUND", "\u8DEF\u5F84\u4E0D\u5B58\u5728", 404);
22885
23288
  if (error?.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
22886
23289
  throw error;
22887
23290
  }
22888
- async function registerFsRoutes(app, runtime) {
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 = {}) {
22889
23296
  app.get("/api/sessions/:id/fs/list", async (request) => {
22890
23297
  const session = await runtime.getSession(request.params.id);
22891
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
+ }
22892
23302
  const userPath = request.query.path ?? "";
22893
23303
  let resolved;
22894
23304
  try {
@@ -22900,9 +23310,7 @@ async function registerFsRoutes(app, runtime) {
22900
23310
  try {
22901
23311
  names = await readdir3(resolved.absolute);
22902
23312
  } catch (error) {
22903
- if (error.code === "ENOENT") throw new RuntimeError("PATH_NOT_FOUND", "\u8DEF\u5F84\u4E0D\u5B58\u5728", 404);
22904
- if (error.code === "ENOTDIR") throw new RuntimeError("NOT_A_DIRECTORY", "\u76EE\u6807\u4E0D\u662F\u76EE\u5F55", 400);
22905
- throw error;
23313
+ badPath(error);
22906
23314
  }
22907
23315
  const entries = [];
22908
23316
  await Promise.all(names.map(async (name) => {
@@ -22919,43 +23327,96 @@ async function registerFsRoutes(app, runtime) {
22919
23327
  app.get("/api/sessions/:id/fs/read", async (request, reply) => {
22920
23328
  const session = await runtime.getSession(request.params.id);
22921
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
+ }
22922
23333
  const userPath = request.query.path;
22923
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";
22924
23340
  let resolved;
22925
23341
  try {
22926
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;
22927
23360
  try {
22928
- resolved = resolveExistingInside(session.cwd, relative(session.cwd, userPath));
23361
+ const realCwd = realpathSync3(session.cwd);
23362
+ if (realTarget === realCwd || realTarget.startsWith(`${realCwd}${sep2}`)) {
23363
+ rel = relative(realCwd, realTarget);
23364
+ }
22929
23365
  } catch {
22930
- const claim = request.webClaim;
22931
- if (claim?.kind === "session") throw new RuntimeError("FORBIDDEN", "\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5\u53EA\u80FD\u9884\u89C8\u8BE5\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u5185\u7684\u6587\u4EF6", 403);
22932
- resolved = { absolute: realpathSync3(userPath), relative: userPath };
22933
23366
  }
23367
+ resolved = { absolute: realTarget, relative: rel };
22934
23368
  } else {
22935
23369
  resolved = resolveExistingInside(session.cwd, userPath);
22936
23370
  }
22937
23371
  } catch (error) {
22938
23372
  badPath(error);
22939
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
+ }
22940
23377
  let info;
22941
23378
  try {
22942
23379
  info = await stat4(resolved.absolute);
22943
23380
  } catch (error) {
22944
- if (error.code === "ENOENT") throw new RuntimeError("PATH_NOT_FOUND", "\u8DEF\u5F84\u4E0D\u5B58\u5728", 404);
22945
- throw error;
23381
+ badPath(error);
22946
23382
  }
22947
23383
  if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
22948
- const kind = previewKindForName(resolved.absolute.split("/").pop() ?? "");
22949
- if (kind === "unsupported") 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);
22950
- const maxBytes = kind === "text" ? maxTextPreviewBytes : maxDocumentPreviewBytes;
22951
- if (info.size > maxBytes) throw new RuntimeError("FILE_TOO_LARGE", `\u6587\u4EF6\u8D85\u8FC7 ${kind === "text" ? "1MB" : "20MB"} \u9884\u89C8\u4E0A\u9650\uFF08\u5B9E\u9645 ${info.size} \u5B57\u8282\uFF09\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u67E5\u770B`, 415);
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
+ }
22952
23409
  const buffer = await readFile10(resolved.absolute);
22953
- if (kind === "image" || kind === "pdf") {
22954
- reply.header("Content-Type", kind === "pdf" ? "application/pdf" : imageMimeForName(resolved.absolute) ?? "application/octet-stream");
23410
+ if (effectiveKind === "image" || effectiveKind === "pdf") {
23411
+ reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
22955
23412
  reply.header("X-Content-Type-Options", "nosniff");
23413
+ if (isSvg) reply.header("Content-Security-Policy", "sandbox");
22956
23414
  reply.header("Cache-Control", "private, max-age=60");
22957
23415
  return reply.send(buffer);
22958
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
+ }
22959
23420
  return { cwd: session.cwd, path: resolved.relative, size: info.size, content: buffer.toString("utf8") };
22960
23421
  });
22961
23422
  }
@@ -23024,7 +23485,7 @@ async function readSseEvents(body, onEach) {
23024
23485
  }
23025
23486
 
23026
23487
  // src/llm/types.ts
23027
- import { z as z6 } from "zod";
23488
+ import { z as z7 } from "zod";
23028
23489
  var llmFormats = ["openai-chat", "openai-responses", "anthropic-messages"];
23029
23490
  var llmAuthTypes = ["api-key", "bearer"];
23030
23491
  var llmErrorCodes = {
@@ -23041,20 +23502,20 @@ var llmErrorCodes = {
23041
23502
  empty: "LLM_EMPTY_REPLY",
23042
23503
  abandoned: "LLM_STREAM_ABANDONED"
23043
23504
  };
23044
- var baseUrlSchema = z6.string().trim().min(1, "Base URL \u4E0D\u80FD\u4E3A\u7A7A");
23045
- var apiKeySchema = z6.string();
23046
- var modelSchema = z6.string().trim().min(1, "\u6A21\u578B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
23047
- var llmEndpointInputSchema = z6.object({
23048
- format: z6.enum(llmFormats),
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),
23049
23510
  baseUrl: baseUrlSchema,
23050
23511
  apiKey: apiKeySchema.optional(),
23051
- auth: z6.enum(llmAuthTypes).optional(),
23512
+ auth: z7.enum(llmAuthTypes).optional(),
23052
23513
  model: modelSchema,
23053
- systemPrompt: z6.string().optional(),
23054
- maxTokens: z6.number().int().positive().optional(),
23514
+ systemPrompt: z7.string().optional(),
23515
+ maxTokens: z7.number().int().positive().optional(),
23055
23516
  // 区间取三种格式的交集:Anthropic 只接受 0..1,照 0..2 校验会让用户在 anthropic 上撞 400。
23056
- temperature: z6.number().min(0).max(1).optional(),
23057
- timeoutMs: z6.number().int().positive().optional()
23517
+ temperature: z7.number().min(0).max(1).optional(),
23518
+ timeoutMs: z7.number().int().positive().optional()
23058
23519
  });
23059
23520
  function normalizeBaseUrl(input) {
23060
23521
  const trimmed = input.trim();
@@ -23377,8 +23838,8 @@ var LlmClient = class {
23377
23838
 
23378
23839
  // src/llm/detect.ts
23379
23840
  import { readFile as readFile11 } from "node:fs/promises";
23380
- import { homedir as homedir12 } from "node:os";
23381
- import { join as join17 } from "node:path";
23841
+ import { homedir as homedir13 } from "node:os";
23842
+ import { join as join18 } from "node:path";
23382
23843
  var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
23383
23844
  async function readJson(path5) {
23384
23845
  try {
@@ -23508,9 +23969,9 @@ function codexCandidate(configText, env) {
23508
23969
  }
23509
23970
  async function detectLlmEndpoints(options = {}) {
23510
23971
  const env = options.env ?? process.env;
23511
- const home = options.home ?? homedir12();
23972
+ const home = options.home ?? homedir13();
23512
23973
  const candidates = [];
23513
- const settings = await readJson(join17(home, ".claude", "settings.json"));
23974
+ const settings = await readJson(join18(home, ".claude", "settings.json"));
23514
23975
  const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
23515
23976
  const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
23516
23977
  if (fromSettings) candidates.push(fromSettings);
@@ -23518,7 +23979,7 @@ async function detectLlmEndpoints(options = {}) {
23518
23979
  if (fromEnv) candidates.push(fromEnv);
23519
23980
  const openai = openAiCandidate(env);
23520
23981
  if (openai) candidates.push(openai);
23521
- const codexConfig = await readText(join17(home, ".codex", "config.toml"));
23982
+ const codexConfig = await readText(join18(home, ".codex", "config.toml"));
23522
23983
  if (codexConfig) {
23523
23984
  const codex = codexCandidate(codexConfig, env);
23524
23985
  if (codex) candidates.push(codex);
@@ -23705,6 +24166,9 @@ data: ${JSON.stringify(data)}
23705
24166
  });
23706
24167
  }
23707
24168
 
24169
+ // src/app.ts
24170
+ init_side_chat_config();
24171
+
23708
24172
  // src/json-compression.ts
23709
24173
  import { promisify as promisify6 } from "node:util";
23710
24174
  import { brotliCompress, constants as constants4, gzip } from "node:zlib";
@@ -23744,17 +24208,17 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
23744
24208
 
23745
24209
  // src/web-password.ts
23746
24210
  import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
23747
- import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
23748
- import { homedir as homedir13 } from "node:os";
23749
- import { dirname as dirname11, join as join18 } from "node:path";
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";
23750
24214
  var webPasswordFileName = "web-password";
23751
24215
  var SCRYPT_N = 16384;
23752
24216
  var SCRYPT_R = 8;
23753
24217
  var SCRYPT_P = 1;
23754
24218
  var KEY_LENGTH = 32;
23755
24219
  var minWebPasswordLength = 6;
23756
- function webPasswordPath(home = homedir13()) {
23757
- return join18(home, ".agentdock", webPasswordFileName);
24220
+ function webPasswordPath(home = homedir14()) {
24221
+ return join19(home, ".agentdock", webPasswordFileName);
23758
24222
  }
23759
24223
  function hashWebPassword(password) {
23760
24224
  const salt = randomBytes3(16);
@@ -23794,7 +24258,7 @@ function setWebPassword(password, path5 = webPasswordPath()) {
23794
24258
  chmodSync2(path5, 384);
23795
24259
  }
23796
24260
  function clearWebPassword(path5 = webPasswordPath()) {
23797
- if (!existsSync8(path5)) return false;
24261
+ if (!existsSync9(path5)) return false;
23798
24262
  rmSync3(path5, { force: true });
23799
24263
  return true;
23800
24264
  }
@@ -24259,6 +24723,7 @@ async function buildApp(runtime, options = {}) {
24259
24723
  });
24260
24724
  await registerFsRoutes(app, runtime);
24261
24725
  await registerLlmRoutes(app, options.llm);
24726
+ if (options.sideChatConfig) registerSideChatConfigRoutes(app, options.sideChatConfig);
24262
24727
  const mimeToExt = {
24263
24728
  "image/png": ".png",
24264
24729
  "image/jpeg": ".jpg",
@@ -24292,7 +24757,7 @@ async function buildApp(runtime, options = {}) {
24292
24757
  "audio/flac": ".flac",
24293
24758
  "application/octet-stream": ""
24294
24759
  };
24295
- const globalUploadRoot = join19(homedir14(), ".agentdock", "uploads");
24760
+ const globalUploadRoot = join20(homedir15(), ".agentdock", "uploads");
24296
24761
  const uploadTtlMs = 7 * 24 * 60 * 6e4;
24297
24762
  const collectExpiredUploads = async (now2 = Date.now()) => {
24298
24763
  let removedFiles = 0;
@@ -24303,7 +24768,7 @@ async function buildApp(runtime, options = {}) {
24303
24768
  return { removedFiles };
24304
24769
  }
24305
24770
  for (const sessionDir of sessionDirs) {
24306
- const directory = join19(globalUploadRoot, sessionDir);
24771
+ const directory = join20(globalUploadRoot, sessionDir);
24307
24772
  let names;
24308
24773
  try {
24309
24774
  names = await readdir4(directory);
@@ -24311,7 +24776,7 @@ async function buildApp(runtime, options = {}) {
24311
24776
  continue;
24312
24777
  }
24313
24778
  for (const name of names) {
24314
- const filePath = join19(directory, name);
24779
+ const filePath = join20(directory, name);
24315
24780
  try {
24316
24781
  const info = await stat5(filePath);
24317
24782
  if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
@@ -24357,10 +24822,10 @@ async function buildApp(runtime, options = {}) {
24357
24822
  originalName = rawName;
24358
24823
  }
24359
24824
  const ext = extFromContentType(contentType, originalName);
24360
- const uploadDir = join19(globalUploadRoot, session.id);
24825
+ const uploadDir = join20(globalUploadRoot, session.id);
24361
24826
  await mkdir4(uploadDir, { recursive: true });
24362
24827
  const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
24363
- const filePath = join19(uploadDir, filename);
24828
+ const filePath = join20(uploadDir, filename);
24364
24829
  await writeFile4(filePath, buffer);
24365
24830
  return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
24366
24831
  });
@@ -24371,13 +24836,14 @@ async function buildApp(runtime, options = {}) {
24371
24836
  if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
24372
24837
  throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
24373
24838
  }
24374
- const filePath = join19(globalUploadRoot, session.id, filename);
24839
+ const filePath = join20(globalUploadRoot, session.id, filename);
24375
24840
  const ext = extname2(filename).toLowerCase();
24376
24841
  const data = await readFile12(filePath);
24377
24842
  reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
24378
24843
  reply.header("Cache-Control", "public, max-age=31536000, immutable");
24379
24844
  reply.header("Content-Disposition", `attachment; filename="${filename}"`);
24380
24845
  reply.header("X-Content-Type-Options", "nosniff");
24846
+ if (ext === ".svg") reply.header("Content-Security-Policy", "sandbox");
24381
24847
  return reply.send(data);
24382
24848
  });
24383
24849
  app.get("/api/sessions/:id/stream", async (request, reply) => {
@@ -24428,7 +24894,7 @@ data: ${JSON.stringify(event)}
24428
24894
  } catch {
24429
24895
  return reply.code(400).send({ error: { code: "INVALID_PATH", message: "Invalid URL path" } });
24430
24896
  }
24431
- if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${sep2}`)) return reply.code(404).send();
24897
+ if (requestedFile !== webRoot && !requestedFile.startsWith(`${webRoot}${sep3}`)) return reply.code(404).send();
24432
24898
  let file = requestedFile;
24433
24899
  let body;
24434
24900
  try {
@@ -24456,6 +24922,7 @@ init_handover_binding();
24456
24922
  init_agent_tools();
24457
24923
  init_config();
24458
24924
  init_service();
24925
+ init_side_chat_config();
24459
24926
 
24460
24927
  // src/lark-avatar/service.ts
24461
24928
  init_src2();
@@ -30974,12 +31441,12 @@ function withContext(percent2) {
30974
31441
  // src/assistant/cwd.ts
30975
31442
  init_src2();
30976
31443
  import { accessSync as accessSync2, constants as constants5, statSync as statSync5 } from "node:fs";
30977
- import { homedir as homedir15 } from "node:os";
31444
+ import { homedir as homedir16 } from "node:os";
30978
31445
  import { isAbsolute as isAbsolute8, resolve as resolve11 } from "node:path";
30979
31446
  function expandHomePath(value) {
30980
31447
  const trimmed = value.trim();
30981
- if (trimmed === "~") return homedir15();
30982
- if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve11(homedir15(), trimmed.slice(2));
31448
+ if (trimmed === "~") return homedir16();
31449
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve11(homedir16(), trimmed.slice(2));
30983
31450
  return trimmed;
30984
31451
  }
30985
31452
  function resolveCwdArgument(value, base = process.cwd()) {
@@ -32373,6 +32840,7 @@ async function startLocalServer(options = {}) {
32373
32840
  }
32374
32841
  const webRoot = options.webRoot ?? fileURLToPath5(new URL("../public", import.meta.url));
32375
32842
  const llm = new LlmEndpointService({ config: repos.config });
32843
+ const sideChatConfig = new SideChatConfigService({ config: repos.config, listAgents: () => runtime.listAgents() });
32376
32844
  const packageJson2 = JSON.parse(readFileSync9(new URL("../package.json", import.meta.url), "utf8"));
32377
32845
  const selfUpdate = options.cliEntrypoint ? new SelfUpdateService({ currentVersion: packageJson2.version, packageName: packageJson2.name, cliEntrypoint: options.cliEntrypoint, env }) : void 0;
32378
32846
  schedules2 = new ScheduleService(repos.schedules, repos.sessions, runtime);
@@ -32425,7 +32893,7 @@ async function startLocalServer(options = {}) {
32425
32893
  keepAwake = new KeepAwakeService({ config: repos.config });
32426
32894
  await keepAwake.restore();
32427
32895
  const shareLinks = new ShareLinkService({ host: config.host, port: config.port, secret: webAuth.secret ?? "", config: repos.config, env });
32428
- app = await buildApp(runtime, { webRoot, webAuth, shareLinks, schedules: schedules2, ...assistant ? { assistant } : {}, ...selfUpdate ? { selfUpdate } : {}, system: { keepAwake, ...autostart ? { autostart } : {} }, llm: { service: llm }, lark: { env, config: repos.config, agents: repos.agents, cardMappings: repos.channelMappings, runtime, agentTools, listeningDisabled: env.AGENTDOCK_DISABLE_LARK_LISTENER === "true" }, larkAvatar });
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 });
32429
32897
  await app.listen(listenOptions(config));
32430
32898
  schedules2.start();
32431
32899
  assistant?.start();
@@ -32509,7 +32977,7 @@ init_session_cli();
32509
32977
  init_config();
32510
32978
  init_message_content();
32511
32979
  init_service();
32512
- import { existsSync as existsSync10 } from "node:fs";
32980
+ import { existsSync as existsSync11 } from "node:fs";
32513
32981
  var output = (deps) => deps.stdout ?? process.stdout;
32514
32982
  var errorOutput = (deps) => deps.stderr ?? process.stderr;
32515
32983
  var envOf = (deps) => deps.env ?? process.env;
@@ -32521,7 +32989,7 @@ var noBotError = () => new Error(
32521
32989
  async function loadStoredConfigs(deps) {
32522
32990
  if (deps.configs) return deps.configs;
32523
32991
  const filename = resolveDatabasePath();
32524
- if (!existsSync10(filename)) return [];
32992
+ if (!existsSync11(filename)) return [];
32525
32993
  try {
32526
32994
  const repositories = createRepositories(filename);
32527
32995
  try {
@@ -33477,25 +33945,25 @@ init_session_cli();
33477
33945
 
33478
33946
  // src/dev-sandbox.ts
33479
33947
  import { spawnSync as spawnSync3 } from "node:child_process";
33480
- import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
33948
+ import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
33481
33949
  import { createServer } from "node:net";
33482
- import { delimiter as delimiter2, dirname as dirname13, join as join21, resolve as resolve15 } from "node:path";
33950
+ import { delimiter as delimiter2, dirname as dirname13, join as join22, resolve as resolve15 } from "node:path";
33483
33951
  init_daemon();
33484
33952
  var SANDBOX_FILE = "sandbox.json";
33485
33953
  function findRepoRoot(start = process.cwd()) {
33486
33954
  let dir = resolve15(start);
33487
33955
  for (; ; ) {
33488
- if (existsSync11(join21(dir, "apps", "server", "package.json")) && existsSync11(join21(dir, "pnpm-workspace.yaml"))) return dir;
33956
+ if (existsSync12(join22(dir, "apps", "server", "package.json")) && existsSync12(join22(dir, "pnpm-workspace.yaml"))) return dir;
33489
33957
  const parent = dirname13(dir);
33490
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");
33491
33959
  dir = parent;
33492
33960
  }
33493
33961
  }
33494
33962
  function sandboxPaths(repo, port) {
33495
- const root4 = join21(repo, ".agentdock", "dev");
33496
- return { root: root4, home: join21(root4, "home"), work: join21(root4, "work"), database: join21(root4, "agentdock.db"), entrypoint: join21(repo, "apps", "server", "dist", "cli.js"), port };
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 };
33497
33965
  }
33498
- var shimDir = (sandbox) => join21(sandbox.root, "bin");
33966
+ var shimDir = (sandbox) => join22(sandbox.root, "bin");
33499
33967
  function sandboxEnv(sandbox, base = process.env) {
33500
33968
  const env = {
33501
33969
  ...base,
@@ -33518,7 +33986,7 @@ function writeCliShim(sandbox, node = process.execPath) {
33518
33986
  if (process.platform === "win32") return;
33519
33987
  const dir = shimDir(sandbox);
33520
33988
  mkdirSync6(dir, { recursive: true });
33521
- const file = join21(dir, "agent-dock");
33989
+ const file = join22(dir, "agent-dock");
33522
33990
  writeFileSync5(file, `#!/bin/sh
33523
33991
  exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
33524
33992
  `);
@@ -33526,7 +33994,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
33526
33994
  }
33527
33995
  function readSandbox(repo) {
33528
33996
  try {
33529
- return JSON.parse(readFileSync13(join21(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
33997
+ return JSON.parse(readFileSync13(join22(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
33530
33998
  } catch {
33531
33999
  return void 0;
33532
34000
  }
@@ -33551,9 +34019,9 @@ async function devUp(options = {}) {
33551
34019
  const existing = readSandbox(repo);
33552
34020
  const port = existing?.port ?? options.port ?? await freePort(4399);
33553
34021
  const sandbox = sandboxPaths(repo, port);
33554
- if (!existsSync11(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`);
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`);
33555
34023
  for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
33556
- writeFileSync5(join21(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
34024
+ writeFileSync5(join22(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
33557
34025
  `);
33558
34026
  writeCliShim(sandbox);
33559
34027
  const run2 = options.run ?? defaultRun;
@@ -35166,7 +35634,7 @@ async function serve(options, onReady) {
35166
35634
  });
35167
35635
  }
35168
35636
  async function restartWithInstalledCli(entrypoint) {
35169
- if (!existsSync12(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
35637
+ if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
35170
35638
  const previousPid = daemonStatus().pid;
35171
35639
  const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
35172
35640
  await new Promise((resolve17, reject2) => {