@agent-dock/cli 0.3.6 → 0.3.8

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
@@ -961,9 +961,9 @@ function webAccessCookieNameFor(kind) {
961
961
  }
962
962
  function isLoopbackAddress(address) {
963
963
  if (!address) return false;
964
- const normalized = address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : address;
965
- if (normalized === "::1") return true;
966
- const parts = normalized.split(".");
964
+ const normalized2 = address.toLowerCase().startsWith("::ffff:") ? address.slice(7) : address;
965
+ if (normalized2 === "::1") return true;
966
+ const parts = normalized2.split(".");
967
967
  return parts.length === 4 && parts[0] === "127" && parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) <= 255);
968
968
  }
969
969
  function isLoopbackHostHeader(host) {
@@ -3632,14 +3632,14 @@ ${text3.replaceAll("```", "``\\`")}
3632
3632
  toolPresentation = (entry) => {
3633
3633
  const data = entry.data;
3634
3634
  const name = String(data.name ?? data.title ?? "\u5DE5\u5177").trim();
3635
- const normalized = name.toLowerCase();
3635
+ const normalized2 = name.toLowerCase();
3636
3636
  const command = typeof data.input === "string" ? data.input.trim() : firstValue(data.input, ["command", "cmd"]);
3637
3637
  const url = firstValue(data.input, ["url", "href"]);
3638
3638
  const path5 = firstValue(data.input, ["path", "file_path", "cwd"]);
3639
3639
  const description = firstValue(data.input, ["description"]) ?? (typeof data.description === "string" ? data.description.trim() : void 0);
3640
3640
  let action = /^(?:tool|tool call)$/i.test(name) ? "\u5DE5\u5177\u8C03\u7528" : name;
3641
3641
  let kind = "tool";
3642
- const haystack = `${normalized} ${command ?? ""}`;
3642
+ const haystack = `${normalized2} ${command ?? ""}`;
3643
3643
  if (/\b(?:apply_patch|patch|edit|write|replace|create_file)\b/.test(haystack)) {
3644
3644
  action = "\u4FEE\u6539\u6587\u4EF6";
3645
3645
  kind = "edit";
@@ -3664,7 +3664,7 @@ ${text3.replaceAll("```", "``\\`")}
3664
3664
  } else if (/\b(?:agent|spawn|delegate|group\s+(?:self|peers|messages|send|wait))\b/.test(haystack)) {
3665
3665
  action = "Agent \u534F\u4F5C";
3666
3666
  kind = "agent";
3667
- } else if (command || /shell|bash|terminal|exec|command/.test(normalized)) {
3667
+ } else if (command || /shell|bash|terminal|exec|command/.test(normalized2)) {
3668
3668
  action = "\u8FD0\u884C\u547D\u4EE4";
3669
3669
  kind = "command";
3670
3670
  }
@@ -5723,7 +5723,7 @@ var AutostartService = class {
5723
5723
 
5724
5724
  // src/cli.ts
5725
5725
  init_src();
5726
- import { existsSync as existsSync12, readFileSync as readFileSync14 } from "node:fs";
5726
+ import { existsSync as existsSync12, readFileSync as readFileSync15 } from "node:fs";
5727
5727
  import { spawn as spawn13 } from "node:child_process";
5728
5728
  import { loadEnvFile } from "node:process";
5729
5729
  import { fileURLToPath as fileURLToPath6 } from "node:url";
@@ -5741,6 +5741,12 @@ function createCliProgram(version, handlers = {}) {
5741
5741
  const lark = program.command("lark").description("Send AgentDock cards, or send/read/listen to Lark messages");
5742
5742
  addCardOptions(lark.command("send").description("Send a new AgentDock card").argument("[markdown]", "Final Markdown or fallback card content").option("--receive-id <id>", "Recipient ID; defaults to LARK_RECEIVE_ID").option("--chat-id <id>", "Group chat ID (oc_xxx); defaults to LARK_CHAT_ID").option("--receive-id-type <type>", "ID type; defaults to LARK_RECEIVE_ID_TYPE")).action((markdown, options) => handlers.larkSend?.(markdown, options));
5743
5743
  addCardOptions(lark.command("update").description("Update an existing AgentDock card in place").argument("[markdown]", "Final Markdown or fallback card content").requiredOption("--message-id <id>", "Lark card message ID to update")).action((markdown, options) => handlers.larkUpdate?.(markdown, options));
5744
+ const larkAvatar = lark.command("avatar").description("AI \u98DE\u4E66\u66FF\u8EAB\uFF1A\u7528\u672C\u4EBA\u5DF2\u767B\u5F55\u7684 Web \u4F1A\u8BDD\u53D1\u9001\u6D88\u606F\uFF08\u7FA4\u540D/\u6D88\u606F\u5173\u952E\u5B57/@ \u59D3\u540D\u90FD\u4F1A\u5148\u89E3\u6790\uFF09");
5745
+ larkAvatar.command("send").description("\u53D1\u9001\u6587\u672C\u6D88\u606F\uFF1B\u9ED8\u8BA4\u5F15\u7528\u56DE\u590D\uFF0C--in-thread \u5728\u8BDD\u9898\u5185\u56DE\u590D").requiredOption("--chat <chat>", "\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id").option("--text <text>", "\u6D88\u606F\u6B63\u6587").option("--text-file <file>", "\u6B63\u6587\u6587\u4EF6\uFF1B- \u8868\u793A stdin").option("--reply-to <target>", "om_* \u6D88\u606F ID\u3001\u6570\u5B57 rootId \u6216\u6700\u8FD1\u6D88\u606F\u5173\u952E\u5B57").option("--in-thread", "\u56DE\u5230\u539F\u8BDD\u9898\u5185\u56DE\u590D\uFF08\u9ED8\u8BA4\u5F15\u7528\u56DE\u590D\uFF09").option("--at <user>", "\u8981 @ \u7684\u59D3\u540D\u3001ou_* open_id \u6216\u6570\u5B57 userId\uFF0C\u53EF\u91CD\u590D", collect, []).option("--match <mode>", "\u7FA4\u540D\u5339\u914D\uFF1Aexact \u6216 fuzzy").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.larkAvatarSend?.(options)).addHelpText("after", `
5746
+ Examples:
5747
+ $ agent-dock lark avatar send --chat "\u53D1\u5E03\u7FA4" --text "\u6784\u5EFA\u5B8C\u6210"
5748
+ $ agent-dock lark avatar send --chat oc_xxx --reply-to "\u53D1\u5E03\u8BA1\u5212" --in-thread --at \u5F20\u4E09 --text "@\u5F20\u4E09 \u5DF2\u66F4\u5230\u9884\u53D1"
5749
+ $ echo "\u90E8\u7F72\u5B8C\u6210" | agent-dock lark avatar send --chat 900001 --text-file - --json`);
5744
5750
  const larkMessage = lark.command("message").description("Generic Lark IM messages using a configured bot (does not create AgentDock sessions)");
5745
5751
  larkMessage.command("send").description("Send a text or post message as a configured bot").argument("[text]", "Message text; omit to read from stdin").option("--chat <chatId>", "Group chat ID (oc_xxx); defaults to LARK_CHAT_ID").option("--text <text>", "Message text (alternative to the positional argument)").option("--format <format>", "Message format: text or post", "text").option("--idempotency-key <key>", "Stable retry key (up to 50 characters)").option("--app <appId>", "Select a saved bot by app ID").option("--bot <name>", "Select a saved bot by name or app ID").option("--base-url <url>", "Lark OpenAPI base URL; defaults to LARK_OPEN_API_BASE_URL").option("--json", "Print one JSON object").action((text3, options) => handlers.larkMessageSend?.(text3, options)).addHelpText("after", `
5746
5752
  Examples:
@@ -5853,7 +5859,7 @@ Notes:
5853
5859
  settings.command("show").description("\u67E5\u770B\u8BBE\u7F6E").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.settingsGet?.(options));
5854
5860
  settings.command("quiet-hours").description("\u8BBE\u7F6E\u514D\u6253\u6270\u65F6\u6BB5\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF09").option("--enabled", "\u5F00\u542F\u514D\u6253\u6270").option("--off", "\u5173\u95ED\u514D\u6253\u6270").option("--start <HH:MM>", "\u5F00\u59CB\u65F6\u95F4").option("--end <HH:MM>", "\u7ED3\u675F\u65F6\u95F4").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.settingsQuietHours?.(options));
5855
5861
  const draft = program.command("draft").description("\u5BF9\u5916\u56DE\u590D\u8349\u7A3F\uFF1A\u786E\u8BA4\u540E\u624D\u53D1\u9001");
5856
- draft.command("create").description("\u521B\u5EFA\u8349\u7A3F").requiredOption("--channel <channel>", "github_comment / lark_reply").requiredOption("--target <target>", "\u5982 github:owner/repo#12").option("--body-file <file>", "\u6B63\u6587\u6587\u4EF6\uFF1B- \u8868\u793A stdin").option("--task <task-id>", "\u5173\u8054\u4E8B\u9879").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.draftCreate?.(options));
5862
+ draft.command("create").description("\u521B\u5EFA\u8349\u7A3F").requiredOption("--channel <channel>", "github_comment / lark_reply").option("--target <target>", "\u5982 github:owner/repo#12\uFF1Blark_reply \u53EF\u6539\u7528 --chat").option("--body-file <file>", "\u6B63\u6587\u6587\u4EF6\uFF1B- \u8868\u793A stdin").option("--chat <chat>", "lark_reply \u76EE\u6807\u7FA4\u540D\u6216 chat_id").option("--reply-to <target>", "lark_reply \u56DE\u590D\u76EE\u6807\uFF1Aom_* / \u6570\u5B57 rootId / \u5173\u952E\u5B57").option("--in-thread", "lark_reply \u5728\u8BDD\u9898\u5185\u56DE\u590D").option("--at <user>", "lark_reply \u8981 @ \u7684\u59D3\u540D\u3001ou_* open_id \u6216\u6570\u5B57 userId\uFF0C\u53EF\u91CD\u590D", collect, []).option("--task <task-id>", "\u5173\u8054\u4E8B\u9879").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.draftCreate?.(options));
5857
5863
  draft.command("list").description("\u5217\u51FA\u8349\u7A3F").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.draftList?.(options));
5858
5864
  draft.command("send").description("\u53D1\u9001\u8349\u7A3F").argument("<draft-id>").option("--json", "\u8F93\u51FA JSON").action((id, options) => handlers.draftSend?.(id, options));
5859
5865
  draft.command("discard").description("\u4E22\u5F03\u8349\u7A3F").argument("<draft-id>").option("--json", "\u8F93\u51FA JSON").action((id, options) => handlers.draftDiscard?.(id, options));
@@ -6349,8 +6355,8 @@ function isWsl(options) {
6349
6355
  }
6350
6356
  var WINDOWS_EXECUTABLE_EXTENSION_RE = /\.(?:exe|cmd|bat)$/u;
6351
6357
  function isWindowsExecutableCommand(command) {
6352
- const normalized = command.toLowerCase();
6353
- return WINDOWS_EXECUTABLE_EXTENSION_RE.test(normalized);
6358
+ const normalized2 = command.toLowerCase();
6359
+ return WINDOWS_EXECUTABLE_EXTENSION_RE.test(normalized2);
6354
6360
  }
6355
6361
  async function runWslpath(cwd) {
6356
6362
  return await runTimedExecFile("wslpath", ["-w", cwd]);
@@ -6800,21 +6806,21 @@ function normalizeAgentName(value) {
6800
6806
  return value.trim().toLowerCase();
6801
6807
  }
6802
6808
  function resolveCanonicalAgentName(value) {
6803
- const normalized = normalizeAgentName(value);
6804
- return Object.hasOwn(AGENT_ALIASES, normalized) ? AGENT_ALIASES[normalized] : normalized;
6809
+ const normalized2 = normalizeAgentName(value);
6810
+ return Object.hasOwn(AGENT_ALIASES, normalized2) ? AGENT_ALIASES[normalized2] : normalized2;
6805
6811
  }
6806
6812
  function findAgentEntry(registry, agentName) {
6807
- const normalized = normalizeAgentName(agentName);
6813
+ const normalized2 = normalizeAgentName(agentName);
6808
6814
  const canonical = resolveCanonicalAgentName(agentName);
6809
- return Object.hasOwn(registry, normalized) ? registry[normalized] : Object.hasOwn(registry, canonical) ? registry[canonical] : void 0;
6815
+ return Object.hasOwn(registry, normalized2) ? registry[normalized2] : Object.hasOwn(registry, canonical) ? registry[canonical] : void 0;
6810
6816
  }
6811
6817
  function mergeAgentRegistry(overrides) {
6812
6818
  if (!overrides) return { ...AGENT_REGISTRY };
6813
6819
  const entries = Object.entries(AGENT_REGISTRY);
6814
6820
  for (const [name, command] of Object.entries(overrides)) {
6815
- const normalized = normalizeAgentName(name);
6816
- if (!normalized || !command.trim()) continue;
6817
- entries.push([normalized, command.trim()]);
6821
+ const normalized2 = normalizeAgentName(name);
6822
+ if (!normalized2 || !command.trim()) continue;
6823
+ entries.push([normalized2, command.trim()]);
6818
6824
  }
6819
6825
  return Object.fromEntries(entries);
6820
6826
  }
@@ -6826,8 +6832,8 @@ function resolveAgentArgv(agentName) {
6826
6832
  return argv ? [...argv] : void 0;
6827
6833
  }
6828
6834
  function findBuiltInAgentPackage(agentCommand) {
6829
- const normalized = agentCommand.trim();
6830
- return Object.values(BUILT_IN_AGENT_PACKAGES).find((spec) => spec.fallbackCommand === normalized || spec.legacyFallbackCommands?.includes(normalized));
6835
+ const normalized2 = agentCommand.trim();
6836
+ return Object.values(BUILT_IN_AGENT_PACKAGES).find((spec) => spec.fallbackCommand === normalized2 || spec.legacyFallbackCommands?.includes(normalized2));
6831
6837
  }
6832
6838
  function defaultResolvePackageRoot(packageName) {
6833
6839
  const segments = packageName.split("/");
@@ -6860,12 +6866,12 @@ function resolveInstalledBuiltInAgentLaunch(agentCommand, options = {}) {
6860
6866
  return resolveInstalledBuiltInAgentLaunchForSpec(spec, options);
6861
6867
  }
6862
6868
  function resolveInstalledBuiltInAgentLaunchForSpec(spec, options) {
6863
- const readFileSync15 = options.readFileSync ?? fs.readFileSync;
6869
+ const readFileSync16 = options.readFileSync ?? fs.readFileSync;
6864
6870
  const existsSync13 = options.existsSync ?? fs.existsSync;
6865
6871
  const resolvePackageRoot = options.resolvePackageRoot ?? defaultResolvePackageRoot;
6866
6872
  try {
6867
6873
  const resolved = resolveInstalledBuiltInAgentPackage(spec, {
6868
- readFileSync: readFileSync15,
6874
+ readFileSync: readFileSync16,
6869
6875
  existsSync: existsSync13,
6870
6876
  resolvePackageRoot
6871
6877
  });
@@ -7199,8 +7205,8 @@ function formatUnknownErrorMessage(error) {
7199
7205
  var SESSION_NOT_FOUND_PATTERN = /session\s+["'\w-]+\s+not found/i;
7200
7206
  function isSessionNotFoundText(value) {
7201
7207
  if (typeof value !== "string") return false;
7202
- const normalized = value.toLowerCase();
7203
- return normalized.includes("resource_not_found") || normalized.includes("resource not found") || normalized.includes("session not found") || normalized.includes("unknown session") || normalized.includes("invalid session identifier") || SESSION_NOT_FOUND_PATTERN.test(value);
7208
+ const normalized2 = value.toLowerCase();
7209
+ return normalized2.includes("resource_not_found") || normalized2.includes("resource not found") || normalized2.includes("session not found") || normalized2.includes("unknown session") || normalized2.includes("invalid session identifier") || SESSION_NOT_FOUND_PATTERN.test(value);
7204
7210
  }
7205
7211
  function hasSessionNotFoundHint(value, depth = 0) {
7206
7212
  if (depth > 4) return false;
@@ -7230,7 +7236,7 @@ function asRecord$4(value) {
7230
7236
  }
7231
7237
  function isAuthRequiredMessage(value) {
7232
7238
  if (!value) return false;
7233
- const normalized = value.toLowerCase();
7239
+ const normalized2 = value.toLowerCase();
7234
7240
  return [
7235
7241
  "auth required",
7236
7242
  "authentication required",
@@ -7239,7 +7245,7 @@ function isAuthRequiredMessage(value) {
7239
7245
  "credentials required",
7240
7246
  "token required",
7241
7247
  "login required"
7242
- ].some((needle) => normalized.includes(needle));
7248
+ ].some((needle) => normalized2.includes(needle));
7243
7249
  }
7244
7250
  function isAcpAuthRequiredPayload(acp) {
7245
7251
  if (!acp) return false;
@@ -7506,8 +7512,8 @@ function extractAgentSessionId(meta) {
7506
7512
  const record = asMetaRecord(meta);
7507
7513
  if (!record) return;
7508
7514
  for (const key of AGENT_SESSION_ID_META_KEYS) {
7509
- const normalized = normalizeAgentSessionId(record[key]);
7510
- if (normalized) return normalized;
7515
+ const normalized2 = normalizeAgentSessionId(record[key]);
7516
+ if (normalized2) return normalized2;
7511
7517
  }
7512
7518
  }
7513
7519
  function serializeSessionRecordForDisk(record) {
@@ -8809,8 +8815,8 @@ async function askPermission(options) {
8809
8815
  try {
8810
8816
  const answer = await Promise.race([rl.question(promptForDisplay(options.prompt), { signal }), closed]);
8811
8817
  options.signal?.throwIfAborted();
8812
- const normalized = answer?.trim().toLowerCase();
8813
- return normalized === "y" || normalized === "yes";
8818
+ const normalized2 = answer?.trim().toLowerCase();
8819
+ return normalized2 === "y" || normalized2 === "yes";
8814
8820
  } finally {
8815
8821
  rl.removeListener("close", onClose);
8816
8822
  questionController.abort();
@@ -9124,8 +9130,8 @@ function findPolicyRule(rules, params) {
9124
9130
  if (!rules || rules.length === 0) return;
9125
9131
  const tokens = permissionMatchTokens(params);
9126
9132
  for (const rule of rules) {
9127
- const normalized = normalizeMatcher(rule);
9128
- if (normalized === "*" || tokens.includes(normalized)) return rule;
9133
+ const normalized2 = normalizeMatcher(rule);
9134
+ if (normalized2 === "*" || tokens.includes(normalized2)) return rule;
9129
9135
  }
9130
9136
  }
9131
9137
  function matchPermissionPolicy(params, policy) {
@@ -9331,11 +9337,11 @@ function resolveClaudeAcpSessionCreateTimeoutMs() {
9331
9337
  }
9332
9338
  function parseGeminiVersion(value) {
9333
9339
  if (typeof value !== "string") return;
9334
- const normalized = value.trim();
9335
- const match = normalized.match(/(\d+)\.(\d+)\.(\d+)/);
9340
+ const normalized2 = value.trim();
9341
+ const match = normalized2.match(/(\d+)\.(\d+)\.(\d+)/);
9336
9342
  if (!match) return;
9337
9343
  return {
9338
- raw: normalized,
9344
+ raw: normalized2,
9339
9345
  parts: [
9340
9346
  Number(match[1]),
9341
9347
  Number(match[2]),
@@ -9462,11 +9468,11 @@ function promotePrefixedAuthEnvironment(env) {
9462
9468
  for (const [key, value] of Object.entries(env)) {
9463
9469
  if (!isAuthEnvKey(key)) continue;
9464
9470
  if (typeof value !== "string" || value.trim().length === 0) continue;
9465
- const normalized = toEnvToken(authEnvSuffix(key));
9466
- if (!normalized) continue;
9471
+ const normalized2 = toEnvToken(authEnvSuffix(key));
9472
+ if (!normalized2) continue;
9467
9473
  protectEnvKey(protectedKeys, key);
9468
- protectEnvKey(protectedKeys, normalized);
9469
- assignIfMissing(env, normalized, value);
9474
+ protectEnvKey(protectedKeys, normalized2);
9475
+ assignIfMissing(env, normalized2, value);
9470
9476
  }
9471
9477
  return protectedKeys;
9472
9478
  }
@@ -9500,19 +9506,19 @@ function assignSessionEnv(env, key, value) {
9500
9506
  function addAuthCredentialEnvKeys(protectedKeys, methodId, credential) {
9501
9507
  if (typeof credential !== "string" || credential.trim().length === 0) return;
9502
9508
  if (!methodId.includes("=") && !methodId.includes("\0")) protectEnvKey(protectedKeys, methodId);
9503
- const normalized = toEnvToken(methodId);
9504
- if (normalized) {
9505
- protectEnvKey(protectedKeys, `${AUTH_ENV_PREFIX}${normalized}`);
9506
- protectEnvKey(protectedKeys, normalized);
9509
+ const normalized2 = toEnvToken(methodId);
9510
+ if (normalized2) {
9511
+ protectEnvKey(protectedKeys, `${AUTH_ENV_PREFIX}${normalized2}`);
9512
+ protectEnvKey(protectedKeys, normalized2);
9507
9513
  }
9508
9514
  }
9509
9515
  function assignAuthCredentialEnv(env, methodId, credential) {
9510
9516
  if (typeof credential !== "string" || credential.trim().length === 0) return;
9511
9517
  if (!methodId.includes("=") && !methodId.includes("\0")) assignIfMissing(env, methodId, credential);
9512
- const normalized = toEnvToken(methodId);
9513
- if (normalized) {
9514
- assignIfMissing(env, `${AUTH_ENV_PREFIX}${normalized}`, credential);
9515
- assignIfMissing(env, normalized, credential);
9518
+ const normalized2 = toEnvToken(methodId);
9519
+ if (normalized2) {
9520
+ assignIfMissing(env, `${AUTH_ENV_PREFIX}${normalized2}`, credential);
9521
+ assignIfMissing(env, normalized2, credential);
9516
9522
  }
9517
9523
  }
9518
9524
  function assignIfMissing(env, key, value) {
@@ -12232,13 +12238,13 @@ function appendAgentThinking(agent, text3) {
12232
12238
  }
12233
12239
  function statusIndicatesComplete(status) {
12234
12240
  if (typeof status !== "string") return false;
12235
- const normalized = status.toLowerCase();
12236
- return normalized.includes("complete") || normalized.includes("done") || normalized.includes("success") || normalized.includes("failed") || normalized.includes("error") || normalized.includes("cancel");
12241
+ const normalized2 = status.toLowerCase();
12242
+ return normalized2.includes("complete") || normalized2.includes("done") || normalized2.includes("success") || normalized2.includes("failed") || normalized2.includes("error") || normalized2.includes("cancel");
12237
12243
  }
12238
12244
  function statusIndicatesError(status) {
12239
12245
  if (typeof status !== "string") return false;
12240
- const normalized = status.toLowerCase();
12241
- return normalized.includes("fail") || normalized.includes("error");
12246
+ const normalized2 = status.toLowerCase();
12247
+ return normalized2.includes("fail") || normalized2.includes("error");
12242
12248
  }
12243
12249
  function toToolResultContent(value) {
12244
12250
  if (typeof value === "string") return { Text: value };
@@ -12353,7 +12359,7 @@ function numberField(source2, keys) {
12353
12359
  function sourceToTokenUsage(source2) {
12354
12360
  const usageRecord = asRecord(source2);
12355
12361
  if (!usageRecord) return;
12356
- const normalized = {
12362
+ const normalized2 = {
12357
12363
  input_tokens: numberField(usageRecord, ["input_tokens", "inputTokens"]),
12358
12364
  output_tokens: numberField(usageRecord, ["output_tokens", "outputTokens"]),
12359
12365
  cache_creation_input_tokens: numberField(usageRecord, [
@@ -12369,8 +12375,8 @@ function sourceToTokenUsage(source2) {
12369
12375
  thought_tokens: numberField(usageRecord, ["thought_tokens", "thoughtTokens"]),
12370
12376
  total_tokens: numberField(usageRecord, ["total_tokens", "totalTokens"])
12371
12377
  };
12372
- if (!hasTokenUsageValue(normalized)) return;
12373
- return normalized;
12378
+ if (!hasTokenUsageValue(normalized2)) return;
12379
+ return normalized2;
12374
12380
  }
12375
12381
  function usageToTokenUsage(update) {
12376
12382
  const updateRecord = asRecord(update);
@@ -12668,9 +12674,9 @@ function applyLifecycleSnapshotToRecord(record, snapshot) {
12668
12674
  record.lastAgentDisconnectReason = void 0;
12669
12675
  }
12670
12676
  function reconcileAgentSessionId(record, agentSessionId) {
12671
- const normalized = normalizeAgentSessionId(agentSessionId);
12672
- if (!normalized) return;
12673
- record.agentSessionId = normalized;
12677
+ const normalized2 = normalizeAgentSessionId(agentSessionId);
12678
+ if (!normalized2) return;
12679
+ record.agentSessionId = normalized2;
12674
12680
  }
12675
12681
  function sessionHasAgentMessages(recordOrConversation) {
12676
12682
  return recordOrConversation.messages.some((message) => typeof message === "object" && message !== null && "Agent" in message);
@@ -12704,9 +12710,9 @@ function mergeSessionOptions(preferred, fallback) {
12704
12710
  return Object.keys(merged).length > 0 ? merged : void 0;
12705
12711
  }
12706
12712
  function normalizeSessionOptionShape(options) {
12707
- const normalized = mergeSessionOptions(options, void 0);
12708
- if (normalized?.env !== void 0 && Object.keys(normalized.env).length === 0) delete normalized.env;
12709
- return normalized && Object.keys(normalized).length > 0 ? normalized : void 0;
12713
+ const normalized2 = mergeSessionOptions(options, void 0);
12714
+ if (normalized2?.env !== void 0 && Object.keys(normalized2.env).length === 0) delete normalized2.env;
12715
+ return normalized2 && Object.keys(normalized2).length > 0 ? normalized2 : void 0;
12710
12716
  }
12711
12717
  function mergeEnvRecords(fallback, preferred) {
12712
12718
  if (!fallback && !preferred) return;
@@ -12814,8 +12820,8 @@ function getDesiredConfigOptions(state) {
12814
12820
  }
12815
12821
  function setDesiredModeId(record, modeId) {
12816
12822
  const acpx = ensureAcpxState(record.acpx);
12817
- const normalized = normalizeModeId(modeId);
12818
- if (normalized) acpx.desired_mode_id = normalized;
12823
+ const normalized2 = normalizeModeId(modeId);
12824
+ if (normalized2) acpx.desired_mode_id = normalized2;
12819
12825
  else delete acpx.desired_mode_id;
12820
12826
  record.acpx = acpx;
12821
12827
  }
@@ -13717,8 +13723,8 @@ function normalizePlanEntries(value) {
13717
13723
  if (!Array.isArray(value)) return [];
13718
13724
  const entries = [];
13719
13725
  for (const entry of value) {
13720
- const normalized = normalizePlanEntry(entry);
13721
- if (normalized) entries.push(normalized);
13726
+ const normalized2 = normalizePlanEntry(entry);
13727
+ if (normalized2) entries.push(normalized2);
13722
13728
  }
13723
13729
  return entries;
13724
13730
  }
@@ -15484,14 +15490,14 @@ var AcpRuntimeManager = class {
15484
15490
  failRuntimeTurn(task, error) {
15485
15491
  task.promptStarted.reject(error);
15486
15492
  task.sessionReady.reject(error);
15487
- const normalized = normalizeOutputError(error, { origin: "runtime" });
15493
+ const normalized2 = normalizeOutputError(error, { origin: "runtime" });
15488
15494
  return {
15489
15495
  status: "failed",
15490
15496
  error: {
15491
- message: normalized.message,
15492
- ...normalized.code ? { code: normalized.code } : {},
15493
- ...normalized.detailCode ? { detailCode: normalized.detailCode } : {},
15494
- ...normalized.retryable !== void 0 ? { retryable: normalized.retryable } : {}
15497
+ message: normalized2.message,
15498
+ ...normalized2.code ? { code: normalized2.code } : {},
15499
+ ...normalized2.detailCode ? { detailCode: normalized2.detailCode } : {},
15500
+ ...normalized2.retryable !== void 0 ? { retryable: normalized2.retryable } : {}
15495
15501
  }
15496
15502
  };
15497
15503
  }
@@ -16749,16 +16755,16 @@ var AcpxAdapter = class {
16749
16755
  if (timer) clearTimeout(timer);
16750
16756
  }
16751
16757
  if (next.done) break;
16752
- const normalized = normalizeAcpxEvent(next.value);
16753
- if (normalized) {
16754
- const toolCallId = typeof normalized.data?.id === "string" ? normalized.data.id : void 0;
16755
- if (normalized.type === "tool_call") {
16758
+ const normalized2 = normalizeAcpxEvent(next.value);
16759
+ if (normalized2) {
16760
+ const toolCallId = typeof normalized2.data?.id === "string" ? normalized2.data.id : void 0;
16761
+ if (normalized2.type === "tool_call") {
16756
16762
  if (toolCallId) activeToolCallIds.add(toolCallId);
16757
- } else if (normalized.type === "tool_result") {
16763
+ } else if (normalized2.type === "tool_result") {
16758
16764
  if (toolCallId) activeToolCallIds.delete(toolCallId);
16759
16765
  else activeToolCallIds.clear();
16760
16766
  }
16761
- this.options.onEvent(normalized);
16767
+ this.options.onEvent(normalized2);
16762
16768
  }
16763
16769
  }
16764
16770
  const result = await turn.result;
@@ -17957,19 +17963,19 @@ var AgentDockRuntime = class _AgentDockRuntime {
17957
17963
  return task;
17958
17964
  }
17959
17965
  async updateQueued(id, taskId, prompt, agentPrompt) {
17960
- const normalized = prompt.trim();
17961
- if (!normalized) throw new RuntimeError("INVALID_PROMPT", "Prompt must not be empty", 400);
17966
+ const normalized2 = prompt.trim();
17967
+ if (!normalized2) throw new RuntimeError("INVALID_PROMPT", "Prompt must not be empty", 400);
17962
17968
  const queue = this.queues.get(id) ?? [];
17963
17969
  const task = queue.find((item) => item.id === taskId);
17964
17970
  if (!task) throw new RuntimeError("QUEUED_TASK_NOT_FOUND", `Unknown queued task: ${taskId}`, 404);
17965
- task.prompt = normalized;
17971
+ task.prompt = normalized2;
17966
17972
  task.updatedAt = now();
17967
17973
  if (agentPrompt !== void 0) {
17968
17974
  const normalizedAgentPrompt = agentPrompt.trim();
17969
17975
  if (!normalizedAgentPrompt) throw new RuntimeError("INVALID_PROMPT", "Agent prompt must not be empty", 400);
17970
- if (normalizedAgentPrompt !== normalized) this.queuedAgentPrompts.set(taskId, normalizedAgentPrompt);
17976
+ if (normalizedAgentPrompt !== normalized2) this.queuedAgentPrompts.set(taskId, normalizedAgentPrompt);
17971
17977
  else this.queuedAgentPrompts.delete(taskId);
17972
- } else if (this.queuedAgentPrompts.has(taskId)) this.queuedAgentPrompts.set(taskId, normalized);
17978
+ } else if (this.queuedAgentPrompts.has(taskId)) this.queuedAgentPrompts.set(taskId, normalized2);
17973
17979
  await this.saveTask(task, "queued");
17974
17980
  return task;
17975
17981
  }
@@ -17995,20 +18001,20 @@ var AgentDockRuntime = class _AgentDockRuntime {
17995
18001
  await this.applyRiskPolicy(session, driver, policy);
17996
18002
  }
17997
18003
  async setModel(id, model) {
17998
- const normalized = model.trim();
17999
- if (!normalized) throw new RuntimeError("INVALID_MODEL", "Model must not be empty", 400);
18004
+ const normalized2 = model.trim();
18005
+ if (!normalized2) throw new RuntimeError("INVALID_MODEL", "Model must not be empty", 400);
18000
18006
  const { session } = await this.active(id);
18001
18007
  const driver = await this.reconnect(session);
18002
18008
  if (!driver.setModel) throw new RuntimeError("MODEL_SWITCH_UNSUPPORTED", `Agent ${session.agentId} does not support runtime model switching`, 422);
18003
18009
  try {
18004
- await driver.setModel(normalized);
18010
+ await driver.setModel(normalized2);
18005
18011
  } catch (error) {
18006
18012
  throw new RuntimeError("MODEL_SWITCH_FAILED", error instanceof Error ? error.message : String(error), 422);
18007
18013
  }
18008
- session.model = normalized;
18014
+ session.model = normalized2;
18009
18015
  session.updatedAt = now();
18010
18016
  await this.repos.sessions.save(session);
18011
- await this.emit(id, "status", { state: session.state, model: normalized });
18017
+ await this.emit(id, "status", { state: session.state, model: normalized2 });
18012
18018
  return session;
18013
18019
  }
18014
18020
  /**
@@ -18020,10 +18026,10 @@ var AgentDockRuntime = class _AgentDockRuntime {
18020
18026
  * 列表侧靠 2s 轮询拿到新名字,已经连上 SSE 的页面最多晚 2 秒,不值得为它污染轨迹。
18021
18027
  */
18022
18028
  async setAgentTitle(session, title) {
18023
- const normalized = title ?? "";
18024
- if ((session.agentTitle ?? "") === normalized) return this.titledSession(session);
18025
- await this.repos.sessions.saveTitles(session.id, { agentTitle: normalized || null });
18026
- session.agentTitle = normalized || null;
18029
+ const normalized2 = title ?? "";
18030
+ if ((session.agentTitle ?? "") === normalized2) return this.titledSession(session);
18031
+ await this.repos.sessions.saveTitles(session.id, { agentTitle: normalized2 || null });
18032
+ session.agentTitle = normalized2 || null;
18027
18033
  return this.titledSession(session);
18028
18034
  }
18029
18035
  /**
@@ -18031,31 +18037,31 @@ var AgentDockRuntime = class _AgentDockRuntime {
18031
18037
  * 而不是存一个空标题——否则侧栏会出现一行没有名字的会话。
18032
18038
  */
18033
18039
  async setSessionTitle(id, title) {
18034
- const normalized = (title ?? "").replace(/\s+/g, " ").trim();
18035
- if (normalized.length > SESSION_TITLE_MAX_CHARS) throw new RuntimeError("INVALID_SESSION_TITLE", `\u6807\u9898\u4E0D\u80FD\u8D85\u8FC7 ${SESSION_TITLE_MAX_CHARS} \u4E2A\u5B57\u7B26`, 400);
18040
+ const normalized2 = (title ?? "").replace(/\s+/g, " ").trim();
18041
+ if (normalized2.length > SESSION_TITLE_MAX_CHARS) throw new RuntimeError("INVALID_SESSION_TITLE", `\u6807\u9898\u4E0D\u80FD\u8D85\u8FC7 ${SESSION_TITLE_MAX_CHARS} \u4E2A\u5B57\u7B26`, 400);
18036
18042
  const session = await this.repos.sessions.get(id);
18037
18043
  if (!session) throw new RuntimeError("SESSION_NOT_FOUND", `Unknown session: ${id}`, 404);
18038
- await this.repos.sessions.saveTitles(id, { customTitle: normalized || null, updatedAt: now() });
18039
- session.customTitle = normalized || null;
18044
+ await this.repos.sessions.saveTitles(id, { customTitle: normalized2 || null, updatedAt: now() });
18045
+ session.customTitle = normalized2 || null;
18040
18046
  const titled = await this.titledSession(session);
18041
18047
  await this.emit(id, "status", { state: session.state, title: titled.title ?? null, titleSource: titled.titleSource ?? null });
18042
18048
  return titled;
18043
18049
  }
18044
18050
  async setReasoningEffort(id, reasoningEffort) {
18045
- const normalized = reasoningEffort.trim();
18046
- if (!normalized) throw new RuntimeError("INVALID_REASONING_EFFORT", "Reasoning effort must not be empty", 400);
18051
+ const normalized2 = reasoningEffort.trim();
18052
+ if (!normalized2) throw new RuntimeError("INVALID_REASONING_EFFORT", "Reasoning effort must not be empty", 400);
18047
18053
  const { session } = await this.active(id);
18048
18054
  const driver = await this.reconnect(session);
18049
18055
  if (!driver.setReasoningEffort) throw new RuntimeError("REASONING_SWITCH_UNSUPPORTED", `Agent ${session.agentId} does not support runtime reasoning effort switching`, 422);
18050
18056
  try {
18051
- await driver.setReasoningEffort(normalized);
18057
+ await driver.setReasoningEffort(normalized2);
18052
18058
  } catch (error) {
18053
18059
  throw new RuntimeError("REASONING_SWITCH_FAILED", error instanceof Error ? error.message : String(error), 422);
18054
18060
  }
18055
- session.reasoningEffort = normalized;
18061
+ session.reasoningEffort = normalized2;
18056
18062
  session.updatedAt = now();
18057
18063
  await this.repos.sessions.save(session);
18058
- await this.emit(id, "status", { state: session.state, reasoningEffort: normalized });
18064
+ await this.emit(id, "status", { state: session.state, reasoningEffort: normalized2 });
18059
18065
  return session;
18060
18066
  }
18061
18067
  waitForTurn(id) {
@@ -18648,8 +18654,8 @@ var aliases = {
18648
18654
  pi: "pi"
18649
18655
  };
18650
18656
  var adapterFor = (agentId) => {
18651
- const normalized = agentId ? aliases[agentId.toLowerCase()] : void 0;
18652
- return normalized ? adapters[normalized] : void 0;
18657
+ const normalized2 = agentId ? aliases[agentId.toLowerCase()] : void 0;
18658
+ return normalized2 ? adapters[normalized2] : void 0;
18653
18659
  };
18654
18660
  var markerFor = (adapter) => `agentdock-lark-high-risk-guard-${adapter.id}.mjs`;
18655
18661
  var paths = (adapter, workspace) => ({
@@ -19473,9 +19479,588 @@ data: ${JSON.stringify(data)}
19473
19479
 
19474
19480
  // src/lark-avatar/routes.ts
19475
19481
  init_src2();
19482
+
19483
+ // src/lark-avatar/id-resolution.ts
19484
+ var LarkAvatarResolutionError = class extends Error {
19485
+ constructor(code, message, options = {}) {
19486
+ super(message);
19487
+ this.code = code;
19488
+ this.name = "LarkAvatarResolutionError";
19489
+ this.hint = options.hint;
19490
+ this.candidates = options.candidates;
19491
+ }
19492
+ code;
19493
+ hint;
19494
+ candidates;
19495
+ toJSON() {
19496
+ return {
19497
+ code: this.code,
19498
+ message: this.message,
19499
+ ...this.hint ? { hint: this.hint } : {},
19500
+ ...this.candidates ? { candidates: this.candidates } : {}
19501
+ };
19502
+ }
19503
+ };
19504
+ var larkAvatarResolutionHttpStatus = (code) => {
19505
+ switch (code) {
19506
+ case "NOT_LOGGED_IN":
19507
+ return 401;
19508
+ case "INVALID_INPUT":
19509
+ case "ID_NOT_NUMERIC":
19510
+ case "ID_NOT_SAFE_INTEGER":
19511
+ return 400;
19512
+ case "CHAT_NOT_FOUND":
19513
+ case "ROOT_NOT_FOUND":
19514
+ case "USER_NOT_FOUND":
19515
+ return 404;
19516
+ case "API_UNAVAILABLE":
19517
+ case "CHAT_AMBIGUOUS":
19518
+ case "ROOT_AMBIGUOUS":
19519
+ case "ROOT_NOT_IN_CHAT":
19520
+ case "USER_AMBIGUOUS":
19521
+ return 409;
19522
+ }
19523
+ };
19524
+ var defaultTtlMs = 3e4;
19525
+ var defaultMaxScanMessages = 200;
19526
+ var historyPageSize = 50;
19527
+ var chatIdPattern = /^oc_[A-Za-z0-9_-]+$/;
19528
+ var messageIdPattern = /^om_[A-Za-z0-9_-]+$/;
19529
+ var openUserIdPattern = /^ou_[A-Za-z0-9_-]+$/;
19530
+ var numericIdPattern = /^\d+$/;
19531
+ var normalized = (value) => value.trim().toLowerCase().replace(/\s+/g, "");
19532
+ var chatKind = (value) => value === 1 ? "p2p" : value === 2 ? "group" : value === 3 ? "topic" : "unknown";
19533
+ var chatKindFromText = (value) => value === "p2p" || value === "group" || value === "topic" ? value : "unknown";
19534
+ var messageTime = (value) => {
19535
+ if (!Number.isFinite(value) || value <= 0) return void 0;
19536
+ const ms = value < 1e12 ? value * 1e3 : value;
19537
+ return new Date(ms).toISOString();
19538
+ };
19539
+ var sameChatId = (left, right) => {
19540
+ if (!left || !right) return true;
19541
+ if (left === right) return true;
19542
+ const leftNumeric = numericIdPattern.test(left);
19543
+ const rightNumeric = numericIdPattern.test(right);
19544
+ if (leftNumeric && rightNumeric) return Number(left) === Number(right);
19545
+ return leftNumeric !== rightNumeric;
19546
+ };
19547
+ var notLoggedIn = (message, hint) => new LarkAvatarResolutionError("NOT_LOGGED_IN", message, { hint });
19548
+ var apiUnavailable = (feature) => new LarkAvatarResolutionError(
19549
+ "API_UNAVAILABLE",
19550
+ `\u5F53\u524D\u98DE\u4E66 Web \u7F51\u5173\u5BA2\u6237\u7AEF\u6CA1\u6709\u66B4\u9732${feature}\u63A5\u53E3`,
19551
+ { hint: "\u8BF7\u786E\u8BA4 lark-avatar \u7248\u672C\u4E0E\u767B\u5F55\u72B6\u6001\uFF1B\u8BE5\u89E3\u6790\u53EA\u590D\u7528\u73B0\u6709 Web \u4F1A\u8BDD\uFF0C\u4E0D\u4F1A\u65B0\u5EFA\u767B\u5F55\u6001\u3002" }
19552
+ );
19553
+ var LarkAvatarIdResolver = class {
19554
+ constructor(options) {
19555
+ this.options = options;
19556
+ this.now = options.now ?? (() => Date.now());
19557
+ this.ttlMs = options.ttlMs ?? defaultTtlMs;
19558
+ this.maxScanMessages = options.maxScanMessages ?? defaultMaxScanMessages;
19559
+ this.log = options.log ?? { warn: () => void 0 };
19560
+ }
19561
+ options;
19562
+ cache = /* @__PURE__ */ new Map();
19563
+ knownChats = /* @__PURE__ */ new Map();
19564
+ now;
19565
+ ttlMs;
19566
+ maxScanMessages;
19567
+ log;
19568
+ listChatsAvailable;
19569
+ clear() {
19570
+ this.cache.clear();
19571
+ this.knownChats.clear();
19572
+ this.listChatsAvailable = void 0;
19573
+ }
19574
+ async searchChats(query, options = {}) {
19575
+ this.requireClient();
19576
+ const raw = query.trim();
19577
+ if (!raw) throw new LarkAvatarResolutionError("INVALID_INPUT", "\u7FA4\u540D\u6216 chat_id \u4E0D\u80FD\u4E3A\u7A7A");
19578
+ const directory = await this.chatDirectory();
19579
+ const byId = directory.find((entry) => entry.webChatId === raw);
19580
+ if (byId) {
19581
+ return { match: "id", ambiguous: false, candidates: [this.chatCandidate(byId, "id")] };
19582
+ }
19583
+ const wanted = normalized(raw);
19584
+ const exact = directory.filter((entry) => normalized(entry.name) === wanted);
19585
+ if (exact.length) {
19586
+ return {
19587
+ match: "exact",
19588
+ ambiguous: exact.length > 1,
19589
+ candidates: exact.map((entry) => this.chatCandidate(entry, "exact"))
19590
+ };
19591
+ }
19592
+ if (options.match === "exact") return { match: "none", ambiguous: false, candidates: [] };
19593
+ const fuzzy = directory.filter((entry) => {
19594
+ const name = normalized(entry.name);
19595
+ return Boolean(name) && (name.includes(wanted) || wanted.includes(name));
19596
+ });
19597
+ return {
19598
+ match: fuzzy.length ? "fuzzy" : "none",
19599
+ ambiguous: fuzzy.length > 1,
19600
+ candidates: fuzzy.map((entry) => this.chatCandidate(entry, "fuzzy"))
19601
+ };
19602
+ }
19603
+ async resolveChat(query, options = {}) {
19604
+ this.requireClient();
19605
+ const raw = query.trim();
19606
+ if (!raw) throw new LarkAvatarResolutionError("INVALID_INPUT", "\u7FA4\u540D\u6216 chat_id \u4E0D\u80FD\u4E3A\u7A7A");
19607
+ if (numericIdPattern.test(raw) || chatIdPattern.test(raw)) return this.resolveChatByWebId(raw);
19608
+ const search = await this.searchChats(raw, options);
19609
+ if (!search.candidates.length) {
19610
+ throw new LarkAvatarResolutionError("CHAT_NOT_FOUND", `\u627E\u4E0D\u5230\u7FA4\u300C${raw}\u300D`, {
19611
+ hint: this.listChatsAvailable === false ? "\u5F53\u524D Web \u7F51\u5173\u6CA1\u6709\u4F1A\u8BDD\u5217\u8868\u63A5\u53E3\uFF1B\u8BF7\u6539\u7528 oc_* chat_id \u6216\u6570\u5B57 chat_id\u3002" : "\u53EA\u7D22\u5F15\u6700\u8FD1\u4F1A\u8BDD\uFF08\u6700\u591A 100 \u4E2A\uFF09\u548C\u672C\u673A inbox\uFF1B\u53EF\u4EE5\u5148\u5728\u98DE\u4E66\u91CC\u6253\u5F00\u8BE5\u7FA4\uFF0C\u6216\u6539\u7528 oc_* chat_id\u3002"
19612
+ });
19613
+ }
19614
+ if (search.candidates.length > 1) {
19615
+ throw new LarkAvatarResolutionError("CHAT_AMBIGUOUS", `\u7FA4\u540D\u300C${raw}\u300D\u5339\u914D\u5230 ${search.candidates.length} \u4E2A\u4F1A\u8BDD`, {
19616
+ hint: "\u8BF7\u4ECE\u5019\u9009\u4E2D\u9009\u62E9 chatId\uFF0C\u6216\u6539\u7528\u66F4\u7CBE\u786E\u7684\u7FA4\u540D / oc_* chat_id\u3002",
19617
+ candidates: search.candidates
19618
+ });
19619
+ }
19620
+ const candidate = search.candidates[0];
19621
+ const resolved = await this.resolveChatByWebId(candidate.chatId);
19622
+ return this.rememberChat({
19623
+ ...resolved,
19624
+ name: resolved.name || candidate.name,
19625
+ type: resolved.type === "unknown" ? candidate.type : resolved.type
19626
+ });
19627
+ }
19628
+ async searchMessages(chat, keyword) {
19629
+ this.requireClient();
19630
+ const raw = keyword.trim();
19631
+ if (!raw) throw new LarkAvatarResolutionError("INVALID_INPUT", "\u6D88\u606F\u5173\u952E\u5B57\u4E0D\u80FD\u4E3A\u7A7A");
19632
+ const messages = await this.recentMessages(chat);
19633
+ const wanted = normalized(raw);
19634
+ const matched = messages.filter((message) => normalized(message.content).includes(wanted));
19635
+ return {
19636
+ match: matched.length ? "keyword" : "none",
19637
+ ambiguous: matched.length > 1,
19638
+ candidates: await this.messageCandidates(chat, matched)
19639
+ };
19640
+ }
19641
+ async resolveRoot(chat, root4) {
19642
+ const client2 = this.requireClient();
19643
+ const raw = root4.trim();
19644
+ if (!raw) throw new LarkAvatarResolutionError("INVALID_INPUT", "rootId \u6216\u6D88\u606F\u5173\u952E\u5B57\u4E0D\u80FD\u4E3A\u7A7A");
19645
+ if (numericIdPattern.test(raw)) return this.toNumericId(raw, "rootId");
19646
+ if (messageIdPattern.test(raw)) {
19647
+ if (!client2.messagesByIds) throw apiUnavailable("\u6309\u6D88\u606F ID \u53D6\u6D88\u606F");
19648
+ const messages2 = await client2.messagesByIds([raw]);
19649
+ const message2 = messages2.find((item) => item.messageId === raw) ?? (messages2.length === 1 ? messages2[0] : void 0);
19650
+ if (!message2) {
19651
+ throw new LarkAvatarResolutionError("ROOT_NOT_FOUND", `\u627E\u4E0D\u5230\u6D88\u606F ${raw}`, {
19652
+ hint: "\u786E\u8BA4\u6D88\u606F ID \u5C5E\u4E8E\u5F53\u524D\u767B\u5F55\u8D26\u53F7\u53EF\u89C1\u7684\u4F1A\u8BDD\uFF1B\u5916\u90E8 OpenAPI \u6D88\u606F ID \u4E0D\u4E00\u5B9A\u662F Web \u7F51\u5173\u6D88\u606F ID\u3002"
19653
+ });
19654
+ }
19655
+ if (!sameChatId(message2.chatId, chat.webChatId)) {
19656
+ throw new LarkAvatarResolutionError("ROOT_NOT_IN_CHAT", `\u6D88\u606F ${raw} \u4E0D\u5728\u7FA4\u300C${chat.name || chat.webChatId}\u300D\u91CC`, {
19657
+ hint: "\u8BF7\u6307\u5B9A\u8BE5\u6D88\u606F\u6240\u5728\u7684\u7FA4\uFF0C\u6216\u6539\u7528\u6570\u5B57 chatId \u5BF9\u5E94\u7684\u4F1A\u8BDD\u3002"
19658
+ });
19659
+ }
19660
+ return this.toNumericId(message2.rootId || message2.messageId, "\u6D88\u606F\u7684 rootId");
19661
+ }
19662
+ const search = await this.searchMessages(chat, raw);
19663
+ if (!search.candidates.length) {
19664
+ throw new LarkAvatarResolutionError("ROOT_NOT_FOUND", `\u5728\u7FA4\u300C${chat.name || chat.webChatId}\u300D\u6700\u8FD1\u6D88\u606F\u91CC\u627E\u4E0D\u5230\u5173\u952E\u5B57\u300C${raw}\u300D`, {
19665
+ hint: `\u53EA\u626B\u63CF\u6700\u8FD1 ${this.maxScanMessages} \u6761\u6D88\u606F\uFF1B\u53EF\u4EE5\u6539\u7528 om_* \u6D88\u606F ID \u6216\u6570\u5B57 rootId\u3002`
19666
+ });
19667
+ }
19668
+ if (search.candidates.length > 1) {
19669
+ throw new LarkAvatarResolutionError("ROOT_AMBIGUOUS", `\u5173\u952E\u5B57\u300C${raw}\u300D\u5339\u914D\u5230 ${search.candidates.length} \u6761\u6D88\u606F`, {
19670
+ hint: "\u8BF7\u4ECE\u5019\u9009\u4E2D\u6311\u4E00\u6761\u66F4\u7CBE\u786E\u7684\u5173\u952E\u5B57\uFF0C\u6216\u76F4\u63A5\u4F20\u6D88\u606F ID\u3002",
19671
+ candidates: search.candidates
19672
+ });
19673
+ }
19674
+ const match = search.candidates[0];
19675
+ const messages = await this.recentMessages(chat);
19676
+ const message = messages.find((item) => item.messageId === match.messageId);
19677
+ if (!message) {
19678
+ throw new LarkAvatarResolutionError("ROOT_NOT_FOUND", `\u6D88\u606F ${match.messageId} \u5728\u6700\u8FD1\u6D88\u606F\u7F13\u5B58\u91CC\u5DF2\u5931\u6548`);
19679
+ }
19680
+ return this.toNumericId(message.rootId || message.messageId, "\u6D88\u606F\u7684 rootId");
19681
+ }
19682
+ async searchUsers(chat, query) {
19683
+ this.requireClient();
19684
+ const raw = query.trim().replace(/^@/, "").trim();
19685
+ if (!raw) throw new LarkAvatarResolutionError("INVALID_INPUT", "\u88AB @ \u7684\u7528\u6237\u4E0D\u80FD\u4E3A\u7A7A");
19686
+ if (numericIdPattern.test(raw)) {
19687
+ return {
19688
+ match: "id",
19689
+ ambiguous: false,
19690
+ candidates: [{ userId: raw, name: await this.chatterName(raw), matchedBy: "id" }]
19691
+ };
19692
+ }
19693
+ const directory = await this.chatterDirectory(chat);
19694
+ const wanted = normalized(raw);
19695
+ const emailMatches = directory.filter((entry) => normalized(entry.email ?? "") === wanted);
19696
+ if (emailMatches.length) {
19697
+ return {
19698
+ match: "email",
19699
+ ambiguous: emailMatches.length > 1,
19700
+ candidates: emailMatches.map((entry) => this.userCandidate(entry, "email"))
19701
+ };
19702
+ }
19703
+ const exact = directory.filter((entry) => normalized(entry.name) === wanted);
19704
+ if (exact.length) {
19705
+ return {
19706
+ match: "exact",
19707
+ ambiguous: exact.length > 1,
19708
+ candidates: exact.map((entry) => this.userCandidate(entry, "exact"))
19709
+ };
19710
+ }
19711
+ const fuzzy = directory.filter((entry) => {
19712
+ const name = normalized(entry.name);
19713
+ return Boolean(name) && (name.includes(wanted) || wanted.includes(name));
19714
+ });
19715
+ return {
19716
+ match: fuzzy.length ? "fuzzy" : "none",
19717
+ ambiguous: fuzzy.length > 1,
19718
+ candidates: fuzzy.map((entry) => this.userCandidate(entry, "fuzzy"))
19719
+ };
19720
+ }
19721
+ async resolveMentions(chat, mentions) {
19722
+ const resolved = /* @__PURE__ */ new Map();
19723
+ for (const input of mentions) {
19724
+ const raw = input.trim().replace(/^@/, "").trim();
19725
+ if (!raw) continue;
19726
+ const mention = await this.resolveMention(chat, raw);
19727
+ if (!resolved.has(mention.userId)) resolved.set(mention.userId, mention);
19728
+ }
19729
+ return [...resolved.values()];
19730
+ }
19731
+ async resolveTarget(input) {
19732
+ const chat = await this.resolveChat(input.chat, { ...input.match ? { match: input.match } : {} });
19733
+ const rootId = input.root?.trim() ? await this.resolveRoot(chat, input.root) : void 0;
19734
+ const mentions = input.mentions?.length ? await this.resolveMentions(chat, input.mentions) : [];
19735
+ return {
19736
+ chatId: chat.chatId,
19737
+ ...rootId !== void 0 ? { rootId } : {},
19738
+ mentions
19739
+ };
19740
+ }
19741
+ async resolveMention(chat, raw) {
19742
+ if (numericIdPattern.test(raw)) {
19743
+ return { userId: this.toNumericId(raw, "userId"), name: await this.chatterName(raw) };
19744
+ }
19745
+ if (openUserIdPattern.test(raw)) {
19746
+ const chatter2 = await this.lookupChatter(raw);
19747
+ return {
19748
+ userId: this.toNumericId(chatter2.id, `\u7528\u6237 ${raw} \u7684 userId`),
19749
+ name: chatter2.name || raw
19750
+ };
19751
+ }
19752
+ const search = await this.searchUsers(chat, raw);
19753
+ if (!search.candidates.length) {
19754
+ throw new LarkAvatarResolutionError("USER_NOT_FOUND", `\u5728\u7FA4\u300C${chat.name || chat.webChatId}\u300D\u91CC\u627E\u4E0D\u5230\u7528\u6237\u300C${raw}\u300D`, {
19755
+ hint: `\u53EA\u80FD\u5339\u914D\u672C\u673A inbox \u548C\u6700\u8FD1 ${this.maxScanMessages} \u6761\u6D88\u606F\u7684\u53C2\u4E0E\u8005\uFF1B\u66F4\u7A33\u59A5\u7684\u65B9\u5F0F\u662F\u4F20 ou_* open_id \u6216\u6570\u5B57 userId\u3002`
19756
+ });
19757
+ }
19758
+ if (search.candidates.length > 1) {
19759
+ throw new LarkAvatarResolutionError("USER_AMBIGUOUS", `\u7528\u6237\u300C${raw}\u300D\u5339\u914D\u5230 ${search.candidates.length} \u4E2A\u5019\u9009`, {
19760
+ hint: "\u8BF7\u6539\u7528 ou_* open_id\u3001\u90AE\u7BB1\u6216\u6570\u5B57 userId\u3002",
19761
+ candidates: search.candidates
19762
+ });
19763
+ }
19764
+ const candidate = search.candidates[0];
19765
+ if (numericIdPattern.test(candidate.userId)) {
19766
+ return { userId: this.toNumericId(candidate.userId, "userId"), name: candidate.name || candidate.userId };
19767
+ }
19768
+ const chatter = await this.lookupChatter(candidate.userId);
19769
+ return {
19770
+ userId: this.toNumericId(chatter.id, `\u7528\u6237 ${candidate.userId} \u7684 userId`),
19771
+ name: chatter.name || candidate.name || candidate.userId
19772
+ };
19773
+ }
19774
+ async resolveChatByWebId(webChatId) {
19775
+ return this.cached(`chat:web:${webChatId}`, async () => {
19776
+ if (numericIdPattern.test(webChatId)) {
19777
+ return this.rememberChat({
19778
+ chatId: this.toNumericId(webChatId, "\u4F1A\u8BDD chat_id"),
19779
+ webChatId,
19780
+ name: "",
19781
+ type: "unknown"
19782
+ });
19783
+ }
19784
+ const chat = await this.lookupChat(webChatId);
19785
+ if (!chat) {
19786
+ throw new LarkAvatarResolutionError("CHAT_NOT_FOUND", `\u627E\u4E0D\u5230 chat_id \u4E3A ${webChatId} \u7684\u4F1A\u8BDD`, {
19787
+ hint: "\u786E\u8BA4\u5F53\u524D\u767B\u5F55\u8D26\u53F7\u5728\u8BE5\u7FA4\u91CC\uFF1BOpenAPI chat_id \u9700\u8981 Web \u7F51\u5173\u80FD\u8BC6\u522B\u624D\u53EF\u89E3\u6790\u3002"
19788
+ });
19789
+ }
19790
+ return this.rememberChat(this.fromChatInfo(chat, webChatId));
19791
+ });
19792
+ }
19793
+ fromChatInfo(chat, fallbackWebId) {
19794
+ const webChatId = chat.id || fallbackWebId;
19795
+ return {
19796
+ chatId: this.toNumericId(webChatId, `\u4F1A\u8BDD ${chat.name || webChatId} \u7684 chat_id`),
19797
+ webChatId,
19798
+ name: chat.name,
19799
+ type: chatKind(chat.type),
19800
+ ...chat.memberCount > 0 ? { memberCount: chat.memberCount } : {}
19801
+ };
19802
+ }
19803
+ rememberChat(chat) {
19804
+ this.knownChats.set(chat.webChatId, chat);
19805
+ return chat;
19806
+ }
19807
+ async lookupChat(webChatId) {
19808
+ const client2 = this.requireClient();
19809
+ if (!client2.lookup) throw apiUnavailable("\u4F1A\u8BDD\u8D44\u6599\u67E5\u8BE2");
19810
+ const result = await client2.lookup([webChatId], []);
19811
+ const direct = result.chats.get(webChatId);
19812
+ if (direct) return direct;
19813
+ const values = [...result.chats.values()];
19814
+ return values.length === 1 ? values[0] : void 0;
19815
+ }
19816
+ async lookupChatter(webId) {
19817
+ return this.cached(`chatter:${webId}`, async () => {
19818
+ const client2 = this.requireClient();
19819
+ if (!client2.lookup) throw apiUnavailable("\u7528\u6237\u8D44\u6599\u67E5\u8BE2");
19820
+ const result = await client2.lookup([], [webId]);
19821
+ const direct = result.chatters.get(webId);
19822
+ const values = [...result.chatters.values()];
19823
+ const chatter = direct ?? (values.length === 1 ? values[0] : void 0);
19824
+ if (!chatter) {
19825
+ throw new LarkAvatarResolutionError("USER_NOT_FOUND", `\u627E\u4E0D\u5230\u7528\u6237 ${webId}`, {
19826
+ hint: "\u786E\u8BA4\u8BE5\u7528\u6237\u4E0E\u5F53\u524D\u767B\u5F55\u8D26\u53F7\u5728\u540C\u4E00\u4E2A\u4F1A\u8BDD\uFF1Bou_* open_id \u5FC5\u987B\u80FD\u88AB Web \u7F51\u5173\u8BC6\u522B\u3002"
19827
+ });
19828
+ }
19829
+ return chatter;
19830
+ });
19831
+ }
19832
+ async chatterName(userId) {
19833
+ return this.cached(`name:user:${userId}`, async () => {
19834
+ try {
19835
+ const chatter = await this.lookupChatter(userId);
19836
+ return chatter.name || userId;
19837
+ } catch {
19838
+ return userId;
19839
+ }
19840
+ });
19841
+ }
19842
+ async chatDirectory() {
19843
+ return this.cached("dir:chats", async () => {
19844
+ const client2 = this.requireClient();
19845
+ const entries = /* @__PURE__ */ new Map();
19846
+ for (const item of this.options.inbox()) {
19847
+ if (!item.chatId) continue;
19848
+ entries.set(item.chatId, {
19849
+ webChatId: item.chatId,
19850
+ name: item.chatName || item.senderName || item.chatId,
19851
+ type: chatKindFromText(item.chatType),
19852
+ lastMessageAt: item.occurredAt
19853
+ });
19854
+ }
19855
+ this.listChatsAvailable = Boolean(client2.listChats);
19856
+ if (client2.listChats) {
19857
+ try {
19858
+ for (const chat of await client2.listChats()) this.mergeListedChat(entries, chat);
19859
+ } catch (error) {
19860
+ this.log.warn(`\u98DE\u4E66\u66FF\u8EAB\u89E3\u6790\u7FA4\u540D\u65F6\u8BFB\u53D6\u4F1A\u8BDD\u5217\u8868\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
19861
+ }
19862
+ }
19863
+ for (const chat of this.knownChats.values()) {
19864
+ const current = entries.get(chat.webChatId);
19865
+ entries.set(chat.webChatId, {
19866
+ webChatId: chat.webChatId,
19867
+ name: chat.name || current?.name || "",
19868
+ type: chat.type === "unknown" ? current?.type ?? "unknown" : chat.type,
19869
+ ...chat.memberCount !== void 0 ? { memberCount: chat.memberCount } : current?.memberCount !== void 0 ? { memberCount: current.memberCount } : {},
19870
+ ...current?.lastMessageAt ? { lastMessageAt: current.lastMessageAt } : {}
19871
+ });
19872
+ }
19873
+ return [...entries.values()];
19874
+ });
19875
+ }
19876
+ mergeListedChat(entries, chat) {
19877
+ if (!chat.id) return;
19878
+ const current = entries.get(chat.id);
19879
+ const updateTime = Number.isFinite(chat.updateTime) && chat.updateTime > 0 ? new Date(chat.updateTime < 1e12 ? chat.updateTime * 1e3 : chat.updateTime).toISOString() : current?.lastMessageAt;
19880
+ entries.set(chat.id, {
19881
+ webChatId: chat.id,
19882
+ name: chat.name || current?.name || chat.id,
19883
+ type: chatKind(chat.type) === "unknown" ? current?.type ?? "unknown" : chatKind(chat.type),
19884
+ ...chat.memberCount > 0 ? { memberCount: chat.memberCount } : current?.memberCount !== void 0 ? { memberCount: current.memberCount } : {},
19885
+ ...updateTime ? { lastMessageAt: updateTime } : {}
19886
+ });
19887
+ }
19888
+ chatCandidate(entry, matchedBy) {
19889
+ return {
19890
+ chatId: entry.webChatId,
19891
+ name: entry.name,
19892
+ type: entry.type,
19893
+ ...entry.memberCount !== void 0 ? { memberCount: entry.memberCount } : {},
19894
+ ...entry.lastMessageAt ? { lastMessageAt: entry.lastMessageAt } : {},
19895
+ matchedBy
19896
+ };
19897
+ }
19898
+ async recentMessages(chat) {
19899
+ return this.cached(`messages:${chat.webChatId}`, async () => {
19900
+ const client2 = this.requireClient();
19901
+ if (!client2.history) throw apiUnavailable("\u4F1A\u8BDD\u5386\u53F2");
19902
+ const info = await this.lookupChat(chat.webChatId);
19903
+ let before = info?.lastMessagePosition ?? 0;
19904
+ if (before <= 0) return [];
19905
+ const collected = [];
19906
+ const seen = /* @__PURE__ */ new Set();
19907
+ while (collected.length < this.maxScanMessages && before > 0) {
19908
+ const limit = Math.min(historyPageSize, this.maxScanMessages - collected.length);
19909
+ const page = await client2.history(chat.webChatId, before, limit);
19910
+ if (!page.length) break;
19911
+ for (const message of page) {
19912
+ const key = message.messageId || `${message.chatId}:${message.position}`;
19913
+ if (seen.has(key)) continue;
19914
+ seen.add(key);
19915
+ collected.push(message);
19916
+ }
19917
+ const positions = page.map((message) => message.position).filter((position) => Number.isFinite(position) && position > 0);
19918
+ if (!positions.length) break;
19919
+ const oldest = Math.min(...positions);
19920
+ if (oldest <= 1 || oldest >= before) break;
19921
+ before = oldest - 1;
19922
+ }
19923
+ return collected.sort((left, right) => left.position - right.position).slice(-this.maxScanMessages);
19924
+ });
19925
+ }
19926
+ async messageCandidates(chat, messages) {
19927
+ if (!messages.length) return [];
19928
+ const names = await this.chatterNames(messages.map((message) => message.fromId).filter(Boolean));
19929
+ return messages.slice(-20).map((message) => {
19930
+ const senderName = names.get(message.fromId);
19931
+ const occurredAt = messageTime(message.createTime);
19932
+ return {
19933
+ messageId: message.messageId,
19934
+ content: message.content.trim().slice(0, 160),
19935
+ ...message.position > 0 ? { position: message.position } : {},
19936
+ ...message.fromId ? { senderId: message.fromId } : {},
19937
+ ...senderName ? { senderName } : {},
19938
+ ...occurredAt ? { occurredAt } : {}
19939
+ };
19940
+ });
19941
+ }
19942
+ async chatterNames(userIds) {
19943
+ const names = /* @__PURE__ */ new Map();
19944
+ if (!userIds.length) return names;
19945
+ const client2 = this.requireClient();
19946
+ if (!client2.lookup) return names;
19947
+ try {
19948
+ const result = await client2.lookup([], [...new Set(userIds)]);
19949
+ for (const [id, chatter] of result.chatters) {
19950
+ if (chatter.name) names.set(id, chatter.name);
19951
+ if (chatter.id !== id && chatter.name) names.set(chatter.id, chatter.name);
19952
+ }
19953
+ } catch (error) {
19954
+ this.log.warn(`\u98DE\u4E66\u66FF\u8EAB\u89E3\u6790\u6D88\u606F\u53D1\u9001\u8005\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
19955
+ }
19956
+ return names;
19957
+ }
19958
+ async chatterDirectory(chat) {
19959
+ return this.cached(`dir:users:${chat.webChatId}`, async () => {
19960
+ const entries = /* @__PURE__ */ new Map();
19961
+ for (const item of this.options.inbox()) {
19962
+ if (!sameChatId(item.chatId, chat.webChatId) || !item.senderId) continue;
19963
+ entries.set(item.senderId, {
19964
+ webId: item.senderId,
19965
+ name: item.senderName || item.senderId
19966
+ });
19967
+ }
19968
+ let messages = [];
19969
+ try {
19970
+ messages = await this.recentMessages(chat);
19971
+ } catch (error) {
19972
+ if (!entries.size) throw error;
19973
+ }
19974
+ const ids = /* @__PURE__ */ new Set();
19975
+ for (const message of messages) {
19976
+ if (message.fromId) ids.add(message.fromId);
19977
+ for (const id of message.atUserIds) if (id) ids.add(id);
19978
+ }
19979
+ if (ids.size) {
19980
+ const client2 = this.requireClient();
19981
+ if (client2.lookup) {
19982
+ try {
19983
+ const result = await client2.lookup([], [...ids]);
19984
+ for (const chatter of result.chatters.values()) {
19985
+ if (!chatter.id) continue;
19986
+ entries.set(chatter.id, {
19987
+ webId: chatter.id,
19988
+ name: chatter.name || chatter.id,
19989
+ ...chatter.email ? { email: chatter.email } : {}
19990
+ });
19991
+ }
19992
+ } catch (error) {
19993
+ this.log.warn(`\u98DE\u4E66\u66FF\u8EAB\u89E3\u6790\u7FA4\u6210\u5458\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`);
19994
+ }
19995
+ }
19996
+ }
19997
+ return [...entries.values()];
19998
+ });
19999
+ }
20000
+ userCandidate(entry, matchedBy) {
20001
+ return {
20002
+ userId: entry.webId,
20003
+ name: entry.name,
20004
+ ...entry.email ? { email: entry.email } : {},
20005
+ matchedBy
20006
+ };
20007
+ }
20008
+ requireClient() {
20009
+ if (!this.options.isLoggedIn()) {
20010
+ throw notLoggedIn("\u98DE\u4E66\u66FF\u8EAB\u5C1A\u672A\u767B\u5F55", "\u8BF7\u5148\u626B\u7801\u767B\u5F55\u6216\u5BFC\u5165 Cookie\uFF0C\u518D\u53D1\u8D77\u89E3\u6790\u3002");
20011
+ }
20012
+ const client2 = this.options.client();
20013
+ if (!client2) {
20014
+ throw notLoggedIn("\u98DE\u4E66\u66FF\u8EAB Web \u7F51\u5173\u672A\u8FDE\u63A5", "\u8BF7\u5728\u8BBE\u7F6E\u91CC\u5F00\u542F\u76D1\u542C\uFF08listening\uFF09\u4EE5\u5EFA\u7ACB\u590D\u7528\u73B0\u6709\u767B\u5F55\u6001\u7684 Web \u957F\u8FDE\u63A5\u3002");
20015
+ }
20016
+ return client2;
20017
+ }
20018
+ toNumericId(value, label) {
20019
+ const text3 = value.trim();
20020
+ if (!numericIdPattern.test(text3)) {
20021
+ throw new LarkAvatarResolutionError("ID_NOT_NUMERIC", `${label} \u4E0D\u662F Web \u6570\u5B57 ID\uFF1A${text3 || "(\u7A7A)"}`, {
20022
+ hint: "oc_/om_/ou_ \u524D\u7F00\u662F OpenAPI ID\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F53\u6570\u5B57\u7528\uFF1B\u9700\u8981 Web \u7F51\u5173\u8FD4\u56DE\u5185\u90E8\u6570\u5B57 ID\u3002"
20023
+ });
20024
+ }
20025
+ const parsed = Number(text3);
20026
+ if (!Number.isSafeInteger(parsed)) {
20027
+ throw new LarkAvatarResolutionError("ID_NOT_SAFE_INTEGER", `${label} \u8D85\u51FA JavaScript \u5B89\u5168\u6574\u6570\u8303\u56F4\uFF1A${text3}`, {
20028
+ hint: "\u8BE5 ID \u8D85\u8FC7 2^53-1\uFF0C\u7528 number \u4F1A\u4E22\u7CBE\u5EA6\uFF1B\u9700\u8981\u7F51\u5173\u63D0\u4F9B\u5B57\u7B26\u4E32 ID \u6216\u5206\u6BB5\u5B58\u50A8\u65B9\u6848\u3002"
20029
+ });
20030
+ }
20031
+ return parsed;
20032
+ }
20033
+ cached(key, load) {
20034
+ const now2 = this.now();
20035
+ const hit = this.cache.get(key);
20036
+ if (hit && hit.expiresAt > now2) return hit.value;
20037
+ if (hit) this.cache.delete(key);
20038
+ const entry = {
20039
+ expiresAt: now2 + this.ttlMs,
20040
+ value: load()
20041
+ };
20042
+ entry.value = entry.value.catch((error) => {
20043
+ if (this.cache.get(key) === entry) this.cache.delete(key);
20044
+ throw error;
20045
+ });
20046
+ this.cache.set(key, entry);
20047
+ return entry.value;
20048
+ }
20049
+ };
20050
+
20051
+ // src/lark-avatar/routes.ts
19476
20052
  function registerLarkAvatarRoutes(app, service) {
19477
20053
  const handleError = (reply, error) => {
19478
20054
  if (error instanceof RuntimeError) return reply.code(error.statusCode).send({ error: { code: error.code, message: error.message } });
20055
+ if (error instanceof LarkAvatarResolutionError) {
20056
+ const body = error.toJSON();
20057
+ return reply.code(larkAvatarResolutionHttpStatus(error.code)).send({
20058
+ error: {
20059
+ ...body,
20060
+ message: error.hint && error.hint !== error.message ? `${error.message}\uFF08${error.hint}\uFF09` : error.message
20061
+ }
20062
+ });
20063
+ }
19479
20064
  const message = error instanceof Error ? error.message : String(error);
19480
20065
  return reply.code(500).send({ error: { code: "INTERNAL_ERROR", message } });
19481
20066
  };
@@ -19520,6 +20105,40 @@ function registerLarkAvatarRoutes(app, service) {
19520
20105
  return handleError(reply, error);
19521
20106
  }
19522
20107
  });
20108
+ app.post("/api/lark-avatar/send", async (request, reply) => {
20109
+ try {
20110
+ const body = request.body ?? {};
20111
+ if (typeof body.chat !== "string" || !body.chat.trim()) {
20112
+ throw new RuntimeError("INVALID_INPUT", "chat \u5FC5\u586B\uFF1A\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id", 400);
20113
+ }
20114
+ if (typeof body.text !== "string" || !body.text.trim()) {
20115
+ throw new RuntimeError("INVALID_INPUT", "text \u5FC5\u586B\u4E14\u4E0D\u80FD\u4E3A\u7A7A", 400);
20116
+ }
20117
+ if (body.replyTo !== void 0 && typeof body.replyTo !== "string") {
20118
+ throw new RuntimeError("INVALID_INPUT", "replyTo \u5FC5\u987B\u662F\u5B57\u7B26\u4E32", 400);
20119
+ }
20120
+ if (body.inThread !== void 0 && typeof body.inThread !== "boolean") {
20121
+ throw new RuntimeError("INVALID_INPUT", "inThread \u5FC5\u987B\u662F\u5E03\u5C14\u503C", 400);
20122
+ }
20123
+ if (body.at !== void 0 && (!Array.isArray(body.at) || body.at.some((item) => typeof item !== "string"))) {
20124
+ throw new RuntimeError("INVALID_INPUT", "at \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6570\u7EC4", 400);
20125
+ }
20126
+ if (body.match !== void 0 && body.match !== "exact" && body.match !== "fuzzy") {
20127
+ throw new RuntimeError("INVALID_INPUT", "match \u53EA\u80FD\u662F exact \u6216 fuzzy", 400);
20128
+ }
20129
+ const sent = await service.sendMessage({
20130
+ chat: body.chat,
20131
+ text: body.text,
20132
+ ...body.replyTo ? { replyTo: body.replyTo } : {},
20133
+ ...body.inThread === true ? { inThread: true } : {},
20134
+ ...body.at?.length ? { at: body.at } : {},
20135
+ ...body.match ? { match: body.match } : {}
20136
+ });
20137
+ return { ok: true, ...sent };
20138
+ } catch (error) {
20139
+ return handleError(reply, error);
20140
+ }
20141
+ });
19523
20142
  app.put("/api/lark-avatar/listening", async (request, reply) => {
19524
20143
  const enabled = request.body?.enabled;
19525
20144
  if (typeof enabled !== "boolean") {
@@ -20517,9 +21136,9 @@ var ShareLinkService = class {
20517
21136
  await this.options.config?.set(publicUrlConfigKey, "");
20518
21137
  return this.settings();
20519
21138
  }
20520
- const normalized = normalizePublicUrl(trimmed);
20521
- if (!normalized) throw new RuntimeError("INVALID_PUBLIC_URL", "\u516C\u7F51\u5730\u5740\u5FC5\u987B\u662F\u65E0\u7528\u6237\u540D\u5BC6\u7801\u7684 https:// \u5730\u5740\uFF0C\u4F8B\u5982 https://dock.example.com", 400);
20522
- await this.options.config?.set(publicUrlConfigKey, normalized);
21139
+ const normalized2 = normalizePublicUrl(trimmed);
21140
+ if (!normalized2) throw new RuntimeError("INVALID_PUBLIC_URL", "\u516C\u7F51\u5730\u5740\u5FC5\u987B\u662F\u65E0\u7528\u6237\u540D\u5BC6\u7801\u7684 https:// \u5730\u5740\uFF0C\u4F8B\u5982 https://dock.example.com", 400);
21141
+ await this.options.config?.set(publicUrlConfigKey, normalized2);
20523
21142
  return this.settings();
20524
21143
  }
20525
21144
  async build(sessionId) {
@@ -20916,6 +21535,7 @@ function registerAssistantRoutes(app, assistant) {
20916
21535
  channel: body.channel,
20917
21536
  target: body.target.trim(),
20918
21537
  body: body.body,
21538
+ ...body.payload && typeof body.payload === "object" && !Array.isArray(body.payload) ? { payload: body.payload } : {},
20919
21539
  ...body.taskId ? { taskId: body.taskId } : {},
20920
21540
  ...assistant.mainSessionId ? { createdBy: assistant.mainSessionId } : {}
20921
21541
  }) };
@@ -21435,9 +22055,9 @@ import { isAbsolute as isAbsolute5, relative } from "node:path";
21435
22055
  import { realpathSync as realpathSync2 } from "node:fs";
21436
22056
  import { isAbsolute as isAbsolute4, resolve as resolve7, sep } from "node:path";
21437
22057
  function resolveInsideRoot(root4, userPath) {
21438
- const normalized = (userPath ?? "").trim();
21439
- if (isAbsolute4(normalized)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
21440
- const absolute = resolve7(root4, normalized);
22058
+ const normalized2 = (userPath ?? "").trim();
22059
+ if (isAbsolute4(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
22060
+ const absolute = resolve7(root4, normalized2);
21441
22061
  const rootResolved = resolve7(root4);
21442
22062
  if (absolute !== rootResolved && !absolute.startsWith(`${rootResolved}${sep}`)) {
21443
22063
  throw new WorkspacePathError("\u8DEF\u5F84\u8D85\u51FA\u5DE5\u4F5C\u533A\u8303\u56F4");
@@ -23122,6 +23742,7 @@ import { createHash as createHash6, randomUUID as randomUUID6 } from "node:crypt
23122
23742
  init_src();
23123
23743
  var MAX_INBOX_ITEMS = 60;
23124
23744
  var MAX_DRAFT_ITEMS = 80;
23745
+ var MAX_SEEN_MESSAGES = 1e4;
23125
23746
  var AVATAR_SCHEMA = `
23126
23747
  CREATE TABLE IF NOT EXISTS avatar_state (
23127
23748
  id TEXT PRIMARY KEY, config TEXT NOT NULL, account TEXT, state TEXT NOT NULL,
@@ -23149,6 +23770,11 @@ var AVATAR_SCHEMA = `
23149
23770
  CREATE TABLE IF NOT EXISTS avatar_chat_cursor (
23150
23771
  chat_id TEXT PRIMARY KEY, last_seen_at INTEGER NOT NULL
23151
23772
  );
23773
+ CREATE TABLE IF NOT EXISTS avatar_seen_messages (
23774
+ message_id TEXT PRIMARY KEY, chat_id TEXT NOT NULL,
23775
+ occurred_at INTEGER NOT NULL, seen_at INTEGER NOT NULL
23776
+ );
23777
+ CREATE INDEX IF NOT EXISTS avatar_seen_messages_seen ON avatar_seen_messages(seen_at);
23152
23778
  `;
23153
23779
  function avatarDatabasePath(databaseUrl) {
23154
23780
  if (databaseUrl === ":memory:") return ":memory:";
@@ -23272,8 +23898,14 @@ var LarkAvatarStore = class {
23272
23898
  if (!draftColumns.some((column) => column.name === "reply_root_id")) this.sqlite.exec("ALTER TABLE avatar_drafts ADD COLUMN reply_root_id TEXT");
23273
23899
  if (!draftColumns.some((column) => column.name === "reply_quote")) this.sqlite.exec("ALTER TABLE avatar_drafts ADD COLUMN reply_quote INTEGER");
23274
23900
  if (!draftColumns.some((column) => column.name === "reply_thread_chat")) this.sqlite.exec("ALTER TABLE avatar_drafts ADD COLUMN reply_thread_chat INTEGER");
23901
+ this.sqlite.exec(`
23902
+ INSERT OR IGNORE INTO avatar_seen_messages (message_id, chat_id, occurred_at, seen_at)
23903
+ SELECT message_id, chat_id, 0, CAST(strftime('%s', 'now') AS INTEGER) * 1000
23904
+ FROM avatar_inbox
23905
+ `);
23275
23906
  this.pruneInbox();
23276
23907
  this.pruneDrafts();
23908
+ this.pruneSeenMessages();
23277
23909
  }
23278
23910
  close() {
23279
23911
  this.sqlite.close();
@@ -23310,8 +23942,12 @@ var LarkAvatarStore = class {
23310
23942
  }
23311
23943
  upsertInbox(item) {
23312
23944
  const run2 = this.sqlite.transaction(() => {
23945
+ const occurredAtMs = Number.isFinite(Date.parse(item.occurredAt)) ? Date.parse(item.occurredAt) : 0;
23946
+ const seenAtMs = Number.isFinite(Date.parse(item.receivedAt)) ? Date.parse(item.receivedAt) : Date.now();
23313
23947
  const existing = this.sqlite.prepare("SELECT * FROM avatar_inbox WHERE message_id = ?").get(item.messageId);
23314
23948
  if (existing) {
23949
+ this.sqlite.prepare(`INSERT OR IGNORE INTO avatar_seen_messages (message_id, chat_id, occurred_at, seen_at)
23950
+ VALUES (?, ?, ?, ?)`).run(item.messageId, item.chatId, occurredAtMs, seenAtMs);
23315
23951
  this.sqlite.prepare(`UPDATE avatar_inbox SET
23316
23952
  chat_name = COALESCE(?, chat_name),
23317
23953
  chat_avatar_url = COALESCE(?, chat_avatar_url),
@@ -23327,6 +23963,12 @@ var LarkAvatarStore = class {
23327
23963
  const updated = this.sqlite.prepare("SELECT * FROM avatar_inbox WHERE message_id = ?").get(item.messageId);
23328
23964
  return { record: inboxFromRow(updated), created: false };
23329
23965
  }
23966
+ const seen = this.sqlite.prepare("SELECT 1 FROM avatar_seen_messages WHERE message_id = ?").get(item.messageId);
23967
+ if (seen) {
23968
+ return { record: item, created: false };
23969
+ }
23970
+ this.sqlite.prepare(`INSERT INTO avatar_seen_messages (message_id, chat_id, occurred_at, seen_at)
23971
+ VALUES (?, ?, ?, ?)`).run(item.messageId, item.chatId, occurredAtMs, seenAtMs);
23330
23972
  this.sqlite.prepare(`INSERT INTO avatar_inbox
23331
23973
  (id, thread_key, message_id, chat_id, chat_type, chat_name, chat_avatar_url,
23332
23974
  sender_id, sender_name, sender_avatar_url, title, summary, tier, tier_reason,
@@ -23335,10 +23977,26 @@ var LarkAvatarStore = class {
23335
23977
  @sender_id, @sender_name, @sender_avatar_url, @title, @summary,
23336
23978
  @tier, @tier_reason, @state, @occurred_at, @received_at, @payload)`).run(insertValues(item));
23337
23979
  this.pruneInbox();
23980
+ this.pruneSeenMessages();
23338
23981
  return { record: item, created: true };
23339
23982
  });
23340
23983
  return run2();
23341
23984
  }
23985
+ hasSeenMessage(messageId) {
23986
+ const row = this.sqlite.prepare("SELECT 1 FROM avatar_seen_messages WHERE message_id = ?").get(messageId);
23987
+ return Boolean(row);
23988
+ }
23989
+ pruneSeenMessages(limit = MAX_SEEN_MESSAGES) {
23990
+ const count = Number(this.sqlite.prepare("SELECT count(*) AS count FROM avatar_seen_messages").get()?.count ?? 0);
23991
+ const excess = count - limit;
23992
+ if (excess <= 0) return 0;
23993
+ const result = this.sqlite.prepare(`
23994
+ DELETE FROM avatar_seen_messages WHERE rowid IN (
23995
+ SELECT rowid FROM avatar_seen_messages ORDER BY seen_at ASC, rowid ASC LIMIT ?
23996
+ )
23997
+ `).run(excess);
23998
+ return result.changes;
23999
+ }
23342
24000
  listInbox(states, tier) {
23343
24001
  const filters = [];
23344
24002
  const params = [];
@@ -23453,8 +24111,9 @@ var LarkAvatarStore = class {
23453
24111
  return Number.isFinite(row?.last_seen_at) ? Number(row?.last_seen_at) : void 0;
23454
24112
  }
23455
24113
  setCursor(chatId, lastSeenAt) {
24114
+ const next = Math.max(0, Math.floor(lastSeenAt));
23456
24115
  this.sqlite.prepare(`INSERT INTO avatar_chat_cursor (chat_id, last_seen_at)
23457
- VALUES (?, ?) ON CONFLICT(chat_id) DO UPDATE SET last_seen_at=excluded.last_seen_at`).run(chatId, Math.max(0, Math.floor(lastSeenAt)));
24116
+ VALUES (?, ?) ON CONFLICT(chat_id) DO UPDATE SET last_seen_at = MAX(avatar_chat_cursor.last_seen_at, excluded.last_seen_at)`).run(chatId, next);
23458
24117
  }
23459
24118
  statusCounts() {
23460
24119
  const count = (sql) => Number(this.sqlite.prepare(sql).get().count);
@@ -24062,9 +24721,89 @@ var decodeMessage = (message, atMe) => {
24062
24721
  };
24063
24722
  };
24064
24723
  var encodeCreateReactionRequest = (messageId, type2) => encodeObject("messages.CreateReactionRequest", { messageId, type: type2 });
24724
+ var MAX_INT64 = 9223372036854775807n;
24725
+ var normalizeMentionUserId = (raw) => {
24726
+ if (typeof raw === "number" && !Number.isSafeInteger(raw)) {
24727
+ throw new Error("\u98DE\u4E66 @ \u63D0\u53CA\u7684 userId \u5FC5\u987B\u662F\u5B89\u5168\u6574\u6570\u6216\u5341\u8FDB\u5236\u5B57\u7B26\u4E32");
24728
+ }
24729
+ const value = String(raw).trim();
24730
+ if (value.startsWith("ou_")) {
24731
+ throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA\u9700\u8981\u6570\u5B57 user_id\uFF0C\u4E0D\u80FD\u4F7F\u7528 open_id\uFF08${value}\uFF09\uFF1B\u534F\u8BAE\u5C42\u4E0D\u505A open_id \u5151\u6362`);
24732
+ }
24733
+ if (!/^\d+$/.test(value)) {
24734
+ throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA\u7684 userId \u5FC5\u987B\u662F\u5341\u8FDB\u5236\u6570\u5B57\uFF0C\u6536\u5230 ${JSON.stringify(value)}`);
24735
+ }
24736
+ const id = BigInt(value);
24737
+ if (id <= 0n || id > MAX_INT64) {
24738
+ throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA\u7684 userId \u8D85\u51FA int64 \u8303\u56F4\uFF1A${value}`);
24739
+ }
24740
+ return id.toString();
24741
+ };
24742
+ var normalizeMentionContent = (raw) => {
24743
+ if (typeof raw !== "string") throw new Error("\u98DE\u4E66 @ \u63D0\u53CA\u7684 content \u5FC5\u987B\u662F\u5B57\u7B26\u4E32");
24744
+ const content = raw.startsWith("@") ? raw.slice(1) : raw;
24745
+ if (!content.trim()) throw new Error("\u98DE\u4E66 @ \u63D0\u53CA\u7684 content\uFF08\u663E\u793A\u540D\uFF09\u4E0D\u80FD\u4E3A\u7A7A");
24746
+ return content;
24747
+ };
24748
+ var locateMentions = (text3, mentions) => {
24749
+ let cursor = 0;
24750
+ const located = mentions.map((mention) => {
24751
+ const content = normalizeMentionContent(mention.content);
24752
+ const userId = normalizeMentionUserId(mention.userId);
24753
+ const token = `@${content}`;
24754
+ let offset;
24755
+ if (mention.offset === void 0) {
24756
+ offset = text3.indexOf(token, cursor);
24757
+ if (offset < 0) throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA ${token} \u672A\u5728\u6B63\u6587\u4E2D\u627E\u5230`);
24758
+ } else {
24759
+ offset = mention.offset;
24760
+ if (!Number.isInteger(offset) || offset < 0) {
24761
+ throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA\u7684 offset \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\uFF0C\u6536\u5230 ${String(mention.offset)}`);
24762
+ }
24763
+ if (text3.slice(offset, offset + token.length) !== token) {
24764
+ throw new Error(`\u98DE\u4E66 @ \u63D0\u53CA offset=${offset} \u4E0E\u6B63\u6587\u4E0D\u5339\u914D\uFF0C\u671F\u671B ${token}`);
24765
+ }
24766
+ }
24767
+ if (offset < cursor) throw new Error("\u98DE\u4E66 @ \u63D0\u53CA\u7684 offset \u4E0D\u80FD\u91CD\u53E0\u6216\u4E71\u5E8F");
24768
+ cursor = offset + token.length;
24769
+ return { offset, token, userId, content };
24770
+ });
24771
+ return located;
24772
+ };
24773
+ var buildMessageSegments = (text3, mentions) => {
24774
+ if (!mentions.length) return [{ kind: "text", content: text3 }];
24775
+ const located = locateMentions(text3, mentions);
24776
+ const segments = [];
24777
+ let cursor = 0;
24778
+ for (const mention of located) {
24779
+ if (mention.offset > cursor) segments.push({ kind: "text", content: text3.slice(cursor, mention.offset) });
24780
+ segments.push({ kind: "at", content: mention.content, userId: mention.userId });
24781
+ cursor = mention.offset + mention.token.length;
24782
+ }
24783
+ if (cursor < text3.length) segments.push({ kind: "text", content: text3.slice(cursor) });
24784
+ return segments;
24785
+ };
24065
24786
  var encodePutMessageRequest = (input) => {
24066
- const elementId = generateRequestCid();
24067
- const textProperty = encodeObject("entities.RichTextElement.TextProperty", { content: input.text });
24787
+ const segments = buildMessageSegments(input.text, input.mentions ?? []);
24788
+ const elementIds = [];
24789
+ const dictionary = {};
24790
+ for (const segment of segments) {
24791
+ const elementId = generateRequestCid();
24792
+ elementIds.push(elementId);
24793
+ dictionary[elementId] = segment.kind === "text" ? {
24794
+ tag: TAG.TEXT,
24795
+ property: encodeObject("entities.RichTextElement.TextProperty", { content: segment.content })
24796
+ } : {
24797
+ tag: TAG.AT,
24798
+ property: encodeObject("entities.RichTextElement.AtProperty", {
24799
+ userId: segment.userId,
24800
+ content: segment.content
24801
+ })
24802
+ };
24803
+ }
24804
+ const atUserIds = [...new Set(
24805
+ segments.filter((segment) => segment.kind === "at").map((segment) => segment.userId)
24806
+ )];
24068
24807
  const request = {
24069
24808
  type: 4,
24070
24809
  chatId: input.chatId,
@@ -24073,19 +24812,15 @@ var encodePutMessageRequest = (input) => {
24073
24812
  version: 1,
24074
24813
  content: {
24075
24814
  richText: {
24076
- elementIds: [elementId],
24815
+ elementIds,
24077
24816
  innerText: input.text,
24078
24817
  elements: {
24079
- dictionary: {
24080
- [elementId]: {
24081
- tag: 1,
24082
- property: textProperty
24083
- }
24084
- }
24818
+ dictionary
24085
24819
  }
24086
24820
  }
24087
24821
  }
24088
24822
  };
24823
+ if (atUserIds.length) request.atUserIdList = atUserIds;
24089
24824
  if (input.rootId) {
24090
24825
  request.rootId = input.rootId;
24091
24826
  request.parentId = input.rootId;
@@ -24439,6 +25174,12 @@ var LarkProtocolClient = class {
24439
25174
  const payload = await this.gatewayRequest(CMD_PULL_MESSAGES, encodePullMessagesByIdsRequest(messageIds));
24440
25175
  return decodePullMessagesByIdsResponse(payload);
24441
25176
  }
25177
+ /** 只读:按消息 ID 批量取消息,用于把外部传入的 om_* / 消息 ID 解析成会话内的 root。 */
25178
+ async messagesByIds(messageIds) {
25179
+ const ids = messageIds.map((id) => id.trim()).filter(Boolean);
25180
+ if (!ids.length) return [];
25181
+ return this.pullMessagesByIds(ids);
25182
+ }
24442
25183
  async lookup(chatIds, userIds) {
24443
25184
  const [chats, chatters] = await Promise.all([
24444
25185
  chatIds.length ? this.gatewayRequest(CMD_PULL_CHATS, encodePullChatsRequest(chatIds)).then(decodeChatsResponse).catch(() => []) : Promise.resolve([]),
@@ -24706,6 +25447,7 @@ var LarkAvatarService = class {
24706
25447
  workspace;
24707
25448
  ownsStore;
24708
25449
  clientFactory;
25450
+ idResolver;
24709
25451
  credentials;
24710
25452
  client;
24711
25453
  login;
@@ -24734,6 +25476,13 @@ var LarkAvatarService = class {
24734
25476
  this.agentId = options.agentId ?? "codex";
24735
25477
  this.workspace = options.workspace ?? process.cwd();
24736
25478
  this.clientFactory = options.clientFactory ?? ((credentials) => new LarkProtocolClient({ credentials, fetcher: this.fetcher }));
25479
+ this.idResolver = new LarkAvatarIdResolver({
25480
+ client: () => this.client,
25481
+ isLoggedIn: () => Boolean(this.credentials?.cookies.session),
25482
+ inbox: () => this.store.listInbox(),
25483
+ now: () => this.clock().getTime(),
25484
+ log: this.log
25485
+ });
24737
25486
  this.credentials = this.store.getCredentials();
24738
25487
  const region = this.store.getState()?.config.region;
24739
25488
  if (region) this.loginSnapshot = { ...this.loginSnapshot, region };
@@ -24821,6 +25570,67 @@ var LarkAvatarService = class {
24821
25570
  return groupOrder || (right.lastMessageAt ?? "").localeCompare(left.lastMessageAt ?? "");
24822
25571
  });
24823
25572
  }
25573
+ /**
25574
+ * 解析 OpenAPI ID / 群名 / 消息关键字 / 姓名到 Web 内部数字 ID。
25575
+ * 只读复用当前已登录的 Web 网关,不会新建登录态,也不会发消息。
25576
+ */
25577
+ searchChats(query, options = {}) {
25578
+ return this.idResolver.searchChats(query, options);
25579
+ }
25580
+ resolveChat(query, options = {}) {
25581
+ return this.idResolver.resolveChat(query, options);
25582
+ }
25583
+ async resolveRoot(input) {
25584
+ const chat = await this.idResolver.resolveChat(input.chat);
25585
+ return this.idResolver.resolveRoot(chat, input.root);
25586
+ }
25587
+ async resolveMentions(input) {
25588
+ const chat = await this.idResolver.resolveChat(input.chat);
25589
+ return this.idResolver.resolveMentions(chat, input.mentions);
25590
+ }
25591
+ resolveTarget(input) {
25592
+ return this.idResolver.resolveTarget(input);
25593
+ }
25594
+ /**
25595
+ * 发送文本消息:先按群名 / chat_id / 消息关键字 / 姓名解析,再走现有 Web 网关发送。
25596
+ * `replyTo` 默认按引用回复;`inThread` 时回到原话题,话题群沿用 `threadChat` 语义。
25597
+ */
25598
+ async sendMessage(input) {
25599
+ const text3 = typeof input.text === "string" ? input.text : "";
25600
+ if (!text3.trim()) throw new RuntimeError("INVALID_INPUT", "\u6D88\u606F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A", 400);
25601
+ const options = input.match ? { match: input.match } : {};
25602
+ const chat = await this.idResolver.resolveChat(input.chat, options);
25603
+ const target = await this.idResolver.resolveTarget({
25604
+ chat: input.chat,
25605
+ ...input.replyTo?.trim() ? { root: input.replyTo } : {},
25606
+ ...input.at?.length ? { mentions: input.at } : {},
25607
+ ...options
25608
+ });
25609
+ const missing = target.mentions.find((mention) => !text3.includes(`@${mention.name}`));
25610
+ if (missing) {
25611
+ throw new RuntimeError(
25612
+ "INVALID_INPUT",
25613
+ `\u6B63\u6587\u91CC\u627E\u4E0D\u5230 @${missing.name}\uFF1B--at \u9700\u8981\u6B63\u6587\u540C\u65F6\u5305\u542B\u5BF9\u5E94\u7684 @\u59D3\u540D`,
25614
+ 400
25615
+ );
25616
+ }
25617
+ const client2 = this.client;
25618
+ if (!client2) throw new RuntimeError("NOT_LOGGED_IN", "\u98DE\u4E66\u66FF\u8EAB Web \u7F51\u5173\u672A\u8FDE\u63A5", 401);
25619
+ const result = await client2.sendText({
25620
+ chatId: chat.webChatId,
25621
+ text: text3,
25622
+ ...target.mentions.length ? { mentions: target.mentions.map((mention) => ({ userId: String(mention.userId), content: mention.name })) } : {},
25623
+ ...target.rootId !== void 0 ? { rootId: String(target.rootId) } : {},
25624
+ ...target.rootId !== void 0 && input.inThread !== true ? { quote: true } : {},
25625
+ ...target.rootId !== void 0 && input.inThread === true && chat.type === "topic" ? { threadChat: true } : {}
25626
+ });
25627
+ return {
25628
+ messageId: result.messageId,
25629
+ chatId: chat.webChatId,
25630
+ rootId: target.rootId ?? null,
25631
+ mentions: target.mentions
25632
+ };
25633
+ }
24824
25634
  async saveConfig(input) {
24825
25635
  const now2 = this.clock().toISOString();
24826
25636
  const current = this.store.getState();
@@ -25014,6 +25824,7 @@ var LarkAvatarService = class {
25014
25824
  this.store.saveCredentials(credentials);
25015
25825
  this.chatCache.clear();
25016
25826
  this.chatterCache.clear();
25827
+ this.idResolver.clear();
25017
25828
  if (config.listening !== false) this.startClient(credentials);
25018
25829
  }
25019
25830
  disconnect() {
@@ -25072,6 +25883,7 @@ var LarkAvatarService = class {
25072
25883
  this.store.saveCredentials(void 0);
25073
25884
  this.chatCache.clear();
25074
25885
  this.chatterCache.clear();
25886
+ this.idResolver.clear();
25075
25887
  if (state) this.store.saveState(state);
25076
25888
  }
25077
25889
  setFailure(code, message) {
@@ -25202,6 +26014,8 @@ var LarkAvatarService = class {
25202
26014
  const senderName = names.chatter?.name || message.fromId;
25203
26015
  const chatName = names.chat?.name || (chatTypeNumber === 1 ? senderName : void 0);
25204
26016
  const occurred = timeMs(message.createTime, this.clock().getTime());
26017
+ const previousCursor = this.store.cursor(message.chatId);
26018
+ const staleByCursor = previousCursor !== void 0 && occurred < previousCursor - 6e4;
25205
26019
  const anchor = message.rootId || (chatTypeNumber === 3 ? message.messageId : "");
25206
26020
  const chatType = chatTypeLabel(chatTypeNumber);
25207
26021
  const replyTarget = this.replyTargetFor(message, chatType, state.config);
@@ -25219,7 +26033,7 @@ var LarkAvatarService = class {
25219
26033
  ...names.chatter?.avatarUrl ? { senderAvatarUrl: names.chatter.avatarUrl } : {},
25220
26034
  title: message.content.slice(0, 240) || `[\u6D88\u606F\u7C7B\u578B ${message.type}]`,
25221
26035
  tier: "fyi",
25222
- state: backfill || !isTrigger ? "handled" : "new",
26036
+ state: backfill || staleByCursor || !isTrigger ? "handled" : "new",
25223
26037
  occurredAt: new Date(occurred).toISOString(),
25224
26038
  receivedAt: this.clock().toISOString(),
25225
26039
  payload: {
@@ -25231,7 +26045,10 @@ var LarkAvatarService = class {
25231
26045
  }
25232
26046
  };
25233
26047
  const inserted = this.store.upsertInbox(item);
25234
- if (!inserted.created || backfill || !isSelf || triggerPrompt === void 0) return inserted.created;
26048
+ this.store.setCursor(message.chatId, occurred);
26049
+ if (!inserted.created || backfill || staleByCursor || !isSelf || triggerPrompt === void 0) {
26050
+ return inserted.created && !staleByCursor;
26051
+ }
25235
26052
  if (!triggerPrompt) {
25236
26053
  this.store.setInboxState(item.id, "handled");
25237
26054
  try {
@@ -25278,9 +26095,9 @@ var LarkAvatarService = class {
25278
26095
  }
25279
26096
  matchTrigger(content, prefix) {
25280
26097
  const text3 = content.trim();
25281
- const normalized = normalizeTriggerPrefix(prefix);
25282
- if (!text3.startsWith(normalized)) return void 0;
25283
- const rest = text3.slice(normalized.length);
26098
+ const normalized2 = normalizeTriggerPrefix(prefix);
26099
+ if (!text3.startsWith(normalized2)) return void 0;
26100
+ const rest = text3.slice(normalized2.length);
25284
26101
  if (rest && !/^\s/.test(rest) && /^[A-Za-z0-9_]/.test(rest)) return void 0;
25285
26102
  return rest.replace(/^[\s::,,]+/, "").trim();
25286
26103
  }
@@ -26301,7 +27118,7 @@ var ASSISTANT_SCHEMA = `
26301
27118
  CREATE INDEX IF NOT EXISTS assistant_watches_state ON assistant_watches(state);
26302
27119
  CREATE TABLE IF NOT EXISTS assistant_drafts (
26303
27120
  id TEXT PRIMARY KEY, task_id TEXT, channel TEXT NOT NULL, target TEXT NOT NULL,
26304
- body TEXT NOT NULL, state TEXT NOT NULL, idempotency_key TEXT NOT NULL UNIQUE,
27121
+ body TEXT NOT NULL, payload TEXT, state TEXT NOT NULL, idempotency_key TEXT NOT NULL UNIQUE,
26305
27122
  attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT, created_by TEXT,
26306
27123
  created_at TEXT NOT NULL, sent_at TEXT
26307
27124
  );
@@ -26397,12 +27214,22 @@ var watchFromRow = (row) => ({
26397
27214
  createdAt: row.created_at,
26398
27215
  updatedAt: row.updated_at
26399
27216
  });
27217
+ var draftPayload = (value) => {
27218
+ if (!value) return void 0;
27219
+ try {
27220
+ const parsed = JSON.parse(value);
27221
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
27222
+ } catch {
27223
+ return void 0;
27224
+ }
27225
+ };
26400
27226
  var draftFromRow2 = (row) => ({
26401
27227
  id: row.id,
26402
27228
  ...row.task_id ? { taskId: row.task_id } : {},
26403
27229
  channel: row.channel,
26404
27230
  target: row.target,
26405
27231
  body: row.body,
27232
+ ...draftPayload(row.payload) ? { payload: draftPayload(row.payload) } : {},
26406
27233
  state: row.state,
26407
27234
  idempotencyKey: row.idempotency_key,
26408
27235
  attempts: row.attempts,
@@ -26423,6 +27250,8 @@ var AssistantStore = class {
26423
27250
  if (!columns.has("archived_at")) this.sqlite.exec("ALTER TABLE assistant_tasks ADD COLUMN archived_at TEXT");
26424
27251
  if (!columns.has("archive_batch_id")) this.sqlite.exec("ALTER TABLE assistant_tasks ADD COLUMN archive_batch_id TEXT");
26425
27252
  if (!columns.has("restored_at")) this.sqlite.exec("ALTER TABLE assistant_tasks ADD COLUMN restored_at TEXT");
27253
+ const draftColumns = new Set(this.sqlite.prepare("PRAGMA table_info(assistant_drafts)").all().map((column) => column.name));
27254
+ if (!draftColumns.has("payload")) this.sqlite.exec("ALTER TABLE assistant_drafts ADD COLUMN payload TEXT");
26426
27255
  }
26427
27256
  /** 多步写入要么全成要么全不成(交接回滚、归档批次)。 */
26428
27257
  transaction(work) {
@@ -26625,6 +27454,7 @@ var AssistantStore = class {
26625
27454
  target: input.target,
26626
27455
  body: input.body,
26627
27456
  state: "pending",
27457
+ ...input.payload ? { payload: input.payload } : {},
26628
27458
  idempotencyKey: input.idempotencyKey ?? makeId("adraft-idem"),
26629
27459
  attempts: 0,
26630
27460
  ...input.createdBy ? { createdBy: input.createdBy } : {},
@@ -26635,16 +27465,17 @@ var AssistantStore = class {
26635
27465
  }
26636
27466
  saveDraft(draft) {
26637
27467
  this.sqlite.prepare(`INSERT INTO assistant_drafts
26638
- (id, task_id, channel, target, body, state, idempotency_key, attempts, last_error, created_by, created_at, sent_at)
26639
- VALUES (@id, @taskId, @channel, @target, @body, @state, @idempotencyKey, @attempts, @lastError, @createdBy, @createdAt, @sentAt)
27468
+ (id, task_id, channel, target, body, payload, state, idempotency_key, attempts, last_error, created_by, created_at, sent_at)
27469
+ VALUES (@id, @taskId, @channel, @target, @body, @payload, @state, @idempotencyKey, @attempts, @lastError, @createdBy, @createdAt, @sentAt)
26640
27470
  ON CONFLICT(id) DO UPDATE SET
26641
27471
  state = excluded.state, attempts = excluded.attempts, last_error = excluded.last_error,
26642
- sent_at = excluded.sent_at`).run({
27472
+ payload = excluded.payload, sent_at = excluded.sent_at`).run({
26643
27473
  id: draft.id,
26644
27474
  taskId: draft.taskId ?? null,
26645
27475
  channel: draft.channel,
26646
27476
  target: draft.target,
26647
27477
  body: draft.body,
27478
+ payload: draft.payload ? JSON.stringify(draft.payload) : null,
26648
27479
  state: draft.state,
26649
27480
  idempotencyKey: draft.idempotencyKey,
26650
27481
  attempts: draft.attempts,
@@ -27361,13 +28192,13 @@ function pathsInInput(value, depth = 0) {
27361
28192
  function extractFileRefs(events2, limit = 30) {
27362
28193
  const refs = /* @__PURE__ */ new Map();
27363
28194
  const add = (path5, at, source2) => {
27364
- const normalized = path5.length > 300 ? path5.slice(0, 300) : path5;
27365
- const current = refs.get(normalized);
28195
+ const normalized2 = path5.length > 300 ? path5.slice(0, 300) : path5;
28196
+ const current = refs.get(normalized2);
27366
28197
  if (current) {
27367
28198
  current.count += 1;
27368
28199
  if (at > current.lastSeenAt) current.lastSeenAt = at;
27369
28200
  if (!current.sources.includes(source2)) current.sources.push(source2);
27370
- } else refs.set(normalized, { path: normalized, count: 1, lastSeenAt: at, sources: [source2] });
28201
+ } else refs.set(normalized2, { path: normalized2, count: 1, lastSeenAt: at, sources: [source2] });
27371
28202
  };
27372
28203
  for (const event of events2) {
27373
28204
  const data = event.data ?? {};
@@ -28473,6 +29304,14 @@ function withContext(percent2) {
28473
29304
 
28474
29305
  // src/assistant/service.ts
28475
29306
  var execFileAsync5 = promisify7(execFile7);
29307
+ var defaultPostGithubComment = async (input) => {
29308
+ await execFileAsync5("gh", [
29309
+ "api",
29310
+ `repos/${input.owner}/${input.repo}/issues/${input.number}/comments`,
29311
+ "-f",
29312
+ `body=${input.body}`
29313
+ ], { timeout: 3e4 });
29314
+ };
28476
29315
  var MAIN_SESSION_KEY = "assistant.main";
28477
29316
  var QUIET_HOURS_KEY = "assistant.quietHours";
28478
29317
  var SILENT_EMOJI_KEY = "assistant.silentEmoji";
@@ -28510,6 +29349,8 @@ var AssistantService = class {
28510
29349
  repos;
28511
29350
  log;
28512
29351
  notifyChannel;
29352
+ sendLarkReplyChannel;
29353
+ postGithubComment;
28513
29354
  unsubscribe;
28514
29355
  timer;
28515
29356
  flushTimer;
@@ -28524,6 +29365,8 @@ var AssistantService = class {
28524
29365
  this.repos = options.repos;
28525
29366
  this.log = options.log ?? { info: () => void 0, warn: (message) => console.warn(String(message)) };
28526
29367
  this.notifyChannel = options.notify;
29368
+ this.sendLarkReplyChannel = options.sendLarkReply;
29369
+ this.postGithubComment = options.postGithubComment ?? defaultPostGithubComment;
28527
29370
  this.store = new AssistantStore(options.databaseUrl === ":memory:" ? ":memory:" : `${options.databaseUrl}.assistant.db`);
28528
29371
  this.lifecycle = new AssistantLifecycle({
28529
29372
  store: this.store,
@@ -28656,13 +29499,13 @@ var AssistantService = class {
28656
29499
  }
28657
29500
  async renameCompanion(name) {
28658
29501
  const mainId = this.requireMain();
28659
- const normalized = normalizeCompanionName(name);
28660
- if (!normalized) throw new Error("\u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A");
29502
+ const normalized2 = normalizeCompanionName(name);
29503
+ if (!normalized2) throw new Error("\u540D\u5B57\u4E0D\u80FD\u4E3A\u7A7A");
28661
29504
  const current = await this.getCompanion();
28662
- const profile = { name: normalized, adoptedAt: current?.adoptedAt ?? now() };
29505
+ const profile = { name: normalized2, adoptedAt: current?.adoptedAt ?? now() };
28663
29506
  this.store.setSetting(COMPANION_KEY, JSON.stringify(profile));
28664
- await this.nameSession(mainId, normalized);
28665
- this.lifecycle.renameActiveCat(normalized);
29507
+ await this.nameSession(mainId, normalized2);
29508
+ this.lifecycle.renameActiveCat(normalized2);
28666
29509
  return profile;
28667
29510
  }
28668
29511
  getQuietHours() {
@@ -28680,22 +29523,22 @@ var AssistantService = class {
28680
29523
  }
28681
29524
  }
28682
29525
  setQuietHours(input) {
28683
- const normalized = {
29526
+ const normalized2 = {
28684
29527
  enabled: input.enabled === true,
28685
29528
  start: normalizeClock(input.start, DEFAULT_QUIET_HOURS.start),
28686
29529
  end: normalizeClock(input.end, DEFAULT_QUIET_HOURS.end)
28687
29530
  };
28688
- this.store.setSetting(QUIET_HOURS_KEY, JSON.stringify(normalized));
28689
- return normalized;
29531
+ this.store.setSetting(QUIET_HOURS_KEY, JSON.stringify(normalized2));
29532
+ return normalized2;
28690
29533
  }
28691
29534
  /** 静默触发表情;空串表示关闭。只存一个已规范化的 emoji,校验在 HTTP 入口完成。 */
28692
29535
  getSilentEmoji() {
28693
29536
  return (this.store.getSetting(SILENT_EMOJI_KEY) ?? "").trim();
28694
29537
  }
28695
29538
  setSilentEmoji(value) {
28696
- const normalized = value.trim();
28697
- this.store.setSetting(SILENT_EMOJI_KEY, normalized);
28698
- return normalized;
29539
+ const normalized2 = value.trim();
29540
+ this.store.setSetting(SILENT_EMOJI_KEY, normalized2);
29541
+ return normalized2;
28699
29542
  }
28700
29543
  /**
28701
29544
  * 主会话每一轮开头的状态快照。只对主会话生效;没有变化时整块省略。
@@ -28961,9 +29804,9 @@ ${prompt}` : prompt;
28961
29804
  * 否则刚启动的 idle 会被误判成「这一轮已经结束」。
28962
29805
  */
28963
29806
  async nameSession(sessionId, title) {
28964
- const normalized = title.replace(/\s+/g, " ").trim().slice(0, 120);
28965
- if (!normalized) return;
28966
- await this.repos.sessions.saveTitles(sessionId, { customTitle: normalized, updatedAt: now() });
29807
+ const normalized2 = title.replace(/\s+/g, " ").trim().slice(0, 120);
29808
+ if (!normalized2) return;
29809
+ await this.repos.sessions.saveTitles(sessionId, { customTitle: normalized2, updatedAt: now() });
28967
29810
  }
28968
29811
  async reviewTask(id, verdict, checks = [], note) {
28969
29812
  const task = this.store.getTask(id);
@@ -29140,26 +29983,63 @@ ${prompt}` : prompt;
29140
29983
  if (!draft) throw new Error(`\u8349\u7A3F\u4E0D\u5B58\u5728\uFF1A${id}`);
29141
29984
  if (draft.state === "sent") return draft;
29142
29985
  if (draft.state !== "pending") throw new Error(`\u8349\u7A3F\u72B6\u6001\u662F ${draft.state}\uFF0C\u4E0D\u80FD\u53D1\u9001`);
29143
- if (draft.channel !== "github_comment") throw new Error(`\u6682\u4E0D\u652F\u6301\u53D1\u9001 ${draft.channel}`);
29144
- const target = parseGithubTarget(draft.target);
29145
- if (!target) throw new Error(`GitHub \u76EE\u6807\u683C\u5F0F\u5E94\u4E3A github:owner/repo#123\uFF0C\u6536\u5230\uFF1A${draft.target}`);
29146
- const marker = `
29147
-
29148
- <!-- agentdock:${draft.idempotencyKey} -->`;
29149
- const body = draft.body.includes("<!-- agentdock:") ? draft.body : `${draft.body}${marker}`;
29986
+ if (!draft.body.trim()) throw new Error("\u8349\u7A3F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A");
29987
+ if (draft.channel === "github_comment" && !parseGithubTarget(draft.target)) {
29988
+ throw new Error(`GitHub \u76EE\u6807\u683C\u5F0F\u5E94\u4E3A github:owner/repo#123\uFF0C\u6536\u5230\uFF1A${draft.target}`);
29989
+ }
29150
29990
  draft.attempts += 1;
29151
29991
  try {
29152
- await execFileAsync5("gh", ["api", `repos/${target.owner}/${target.repo}/issues/${target.number}/comments`, "-f", `body=${body}`], { timeout: 3e4 });
29992
+ if (draft.channel === "github_comment") await this.sendGithubDraft(draft);
29993
+ else if (draft.channel === "lark_reply") await this.sendLarkDraft(draft);
29994
+ else throw new Error(`\u6682\u4E0D\u652F\u6301\u53D1\u9001 ${String(draft.channel)}`);
29153
29995
  draft.state = "sent";
29154
29996
  draft.sentAt = now();
29155
29997
  draft.lastError = void 0;
29998
+ this.store.saveDraft(draft);
29999
+ return draft;
29156
30000
  } catch (error) {
29157
30001
  draft.lastError = error instanceof Error ? error.message : String(error);
29158
30002
  if (draft.attempts >= 3) draft.state = "failed";
30003
+ this.store.saveDraft(draft);
30004
+ if (draft.channel === "github_comment" && draft.state !== "failed") return draft;
30005
+ throw error;
30006
+ }
30007
+ }
30008
+ async sendGithubDraft(draft) {
30009
+ const target = parseGithubTarget(draft.target);
30010
+ if (!target) throw new Error(`GitHub \u76EE\u6807\u683C\u5F0F\u5E94\u4E3A github:owner/repo#123\uFF0C\u6536\u5230\uFF1A${draft.target}`);
30011
+ const marker = `
30012
+
30013
+ <!-- agentdock:${draft.idempotencyKey} -->`;
30014
+ const body = draft.body.includes("<!-- agentdock:") ? draft.body : `${draft.body}${marker}`;
30015
+ await this.postGithubComment({ ...target, body });
30016
+ }
30017
+ async sendLarkDraft(draft) {
30018
+ if (!this.sendLarkReplyChannel) {
30019
+ throw new RuntimeError("LARK_AVATAR_UNAVAILABLE", "\u5F53\u524D daemon \u672A\u542F\u7528\u98DE\u4E66\u66FF\u8EAB\u53D1\u9001", 409);
30020
+ }
30021
+ const payload = draft.payload ?? {};
30022
+ const chat = typeof payload.chat === "string" && payload.chat.trim() ? payload.chat.trim() : draft.target.trim();
30023
+ if (!chat) throw new RuntimeError("INVALID_DRAFT", "\u98DE\u4E66\u8349\u7A3F\u7F3A\u5C11\u76EE\u6807\u7FA4\uFF08chat\uFF09", 400);
30024
+ const at = Array.isArray(payload.at) ? payload.at.filter((item) => typeof item === "string" && Boolean(item.trim())) : [];
30025
+ try {
30026
+ await this.sendLarkReplyChannel({
30027
+ chat,
30028
+ text: draft.body,
30029
+ ...typeof payload.replyTo === "string" && payload.replyTo.trim() ? { replyTo: payload.replyTo.trim() } : {},
30030
+ ...payload.inThread === true ? { inThread: true } : {},
30031
+ ...at.length ? { at } : {}
30032
+ });
30033
+ } catch (error) {
30034
+ if (error instanceof LarkAvatarResolutionError) {
30035
+ throw new RuntimeError(
30036
+ error.code,
30037
+ error.hint && error.hint !== error.message ? `${error.message}\uFF08${error.hint}\uFF09` : error.message,
30038
+ larkAvatarResolutionHttpStatus(error.code)
30039
+ );
30040
+ }
30041
+ throw error;
29159
30042
  }
29160
- this.store.saveDraft(draft);
29161
- if (draft.state === "failed") throw new Error(draft.lastError ?? "\u53D1\u9001\u5931\u8D25");
29162
- return draft;
29163
30043
  }
29164
30044
  // ---- 通知 ----
29165
30045
  async notify(input) {
@@ -29335,8 +30215,8 @@ function parseDurationSeconds(value, fallback) {
29335
30215
  }
29336
30216
  function normalizeCompanionName(value) {
29337
30217
  if (typeof value !== "string") return void 0;
29338
- const normalized = [...value.replace(/\s+/g, " ").trim()].slice(0, MAX_COMPANION_NAME).join("").trim();
29339
- return normalized || void 0;
30218
+ const normalized2 = [...value.replace(/\s+/g, " ").trim()].slice(0, MAX_COMPANION_NAME).join("").trim();
30219
+ return normalized2 || void 0;
29340
30220
  }
29341
30221
  function normalizeClock(value, fallback) {
29342
30222
  const match = value.trim().match(/^(\d{1,2}):(\d{2})$/);
@@ -29523,7 +30403,12 @@ async function startLocalServer(options = {}) {
29523
30403
  runtime,
29524
30404
  repos,
29525
30405
  log: { info: () => void 0, warn: (message) => console.warn(String(message)) },
29526
- notify: createLarkNotifier(repos, env)
30406
+ notify: createLarkNotifier(repos, env),
30407
+ // larkAvatar 在下面才构造;回调在真正发草稿时才解析到实例。
30408
+ sendLarkReply: (input) => {
30409
+ if (!larkAvatar) throw new Error("\u98DE\u4E66\u66FF\u8EAB\u5C1A\u672A\u521D\u59CB\u5316");
30410
+ return larkAvatar.sendMessage(input);
30411
+ }
29527
30412
  });
29528
30413
  await assistant.initialize();
29529
30414
  larkAvatar = new LarkAvatarService({
@@ -30029,6 +30914,52 @@ async function runLarkMessageListen(options, deps = {}) {
30029
30914
  return done;
30030
30915
  }
30031
30916
 
30917
+ // src/lark-avatar/cli.ts
30918
+ init_session_cli();
30919
+ import { readFileSync as readFileSync10 } from "node:fs";
30920
+ var readTextFile = (path5) => path5 === "-" ? readFileSync10(0, "utf8") : readFileSync10(path5, "utf8");
30921
+ function buildLarkAvatarSendInput(options, readFile13 = readTextFile) {
30922
+ const chat = options.chat?.trim();
30923
+ if (!chat) throw new Error("--chat \u5FC5\u586B\uFF1A\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id");
30924
+ if (options.text !== void 0 && options.textFile !== void 0) {
30925
+ throw new Error("--text \u548C --text-file \u53EA\u80FD\u7528\u4E00\u4E2A");
30926
+ }
30927
+ const text3 = options.textFile !== void 0 ? readFile13(options.textFile) : options.text;
30928
+ if (text3 === void 0 || !text3.trim()) {
30929
+ throw new Error("\u6D88\u606F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A\uFF1A\u8BF7\u7528 --text <text> \u6216 --text-file <file>");
30930
+ }
30931
+ const at = [...new Set((options.at ?? []).map((item) => item.trim()).filter(Boolean))];
30932
+ if (options.match !== void 0 && options.match !== "exact" && options.match !== "fuzzy") {
30933
+ throw new Error("--match \u53EA\u80FD\u662F exact \u6216 fuzzy");
30934
+ }
30935
+ return {
30936
+ chat,
30937
+ text: text3,
30938
+ ...options.replyTo?.trim() ? { replyTo: options.replyTo.trim() } : {},
30939
+ ...options.inThread === true ? { inThread: true } : {},
30940
+ ...at.length ? { at } : {},
30941
+ ...options.match ? { match: options.match } : {}
30942
+ };
30943
+ }
30944
+ function formatLarkAvatarSendResult(result) {
30945
+ const mentions = Array.isArray(result.mentions) ? result.mentions.map((mention) => {
30946
+ const item = mention;
30947
+ return `@${String(item.name ?? item.userId ?? "")}\uFF08${String(item.userId ?? "")}\uFF09`;
30948
+ }) : [];
30949
+ return [
30950
+ `\u5DF2\u53D1\u9001 ${String(result.messageId ?? "")}`,
30951
+ `\u7FA4\uFF1A${String(result.chatId ?? "")}`,
30952
+ ...result.rootId !== null && result.rootId !== void 0 ? [`\u56DE\u590D\uFF1A${String(result.rootId)}`] : [],
30953
+ ...mentions.length ? [`\u63D0\u53CA\uFF1A${mentions.join("\u3001")}`] : []
30954
+ ].join("\n") + "\n";
30955
+ }
30956
+ async function runLarkAvatarSend(options) {
30957
+ const body = buildLarkAvatarSendInput(options);
30958
+ const result = await callDaemon(requireDaemon(), "/api/lark-avatar/send", "POST", body);
30959
+ return options.json ? `${JSON.stringify(result, null, 2)}
30960
+ ` : formatLarkAvatarSendResult(result);
30961
+ }
30962
+
30032
30963
  // src/acpx.ts
30033
30964
  import { spawn as spawn12 } from "node:child_process";
30034
30965
  function acpxPassThroughArgs(argv) {
@@ -30175,7 +31106,7 @@ init_agent_tools();
30175
31106
  // src/daemon/command.ts
30176
31107
  init_daemon();
30177
31108
  init_time();
30178
- import { readFileSync as readFileSync10 } from "node:fs";
31109
+ import { readFileSync as readFileSync11 } from "node:fs";
30179
31110
  import { resolve as resolve10 } from "node:path";
30180
31111
  var STARTUP_LOG_MAX_BYTES = 16 * 1024;
30181
31112
  var READY_TIMEOUT_MS = 15e3;
@@ -30240,12 +31171,12 @@ async function daemonStart(options, handlers, env = process.env) {
30240
31171
  function readStartupLog(logFile, startOffset, maxBytes = STARTUP_LOG_MAX_BYTES) {
30241
31172
  let size = 0;
30242
31173
  try {
30243
- size = readFileSync10(logFile).length;
31174
+ size = readFileSync11(logFile).length;
30244
31175
  } catch {
30245
31176
  return "";
30246
31177
  }
30247
31178
  const begin = Math.max(0, startOffset, size - maxBytes);
30248
- const buf = readFileSync10(logFile, { encoding: "utf8" });
31179
+ const buf = readFileSync11(logFile, { encoding: "utf8" });
30249
31180
  return buf.slice(begin).trim();
30250
31181
  }
30251
31182
  async function waitUntilReady(dir, logFile, startOffset) {
@@ -30444,7 +31375,7 @@ init_session_cli();
30444
31375
 
30445
31376
  // src/dev-sandbox.ts
30446
31377
  import { spawnSync as spawnSync3 } from "node:child_process";
30447
- import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
31378
+ import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync12, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
30448
31379
  import { createServer } from "node:net";
30449
31380
  import { delimiter, dirname as dirname12, join as join21, resolve as resolve11 } from "node:path";
30450
31381
  init_daemon();
@@ -30483,7 +31414,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
30483
31414
  }
30484
31415
  function readSandbox(repo) {
30485
31416
  try {
30486
- return JSON.parse(readFileSync11(join21(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
31417
+ return JSON.parse(readFileSync12(join21(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
30487
31418
  } catch {
30488
31419
  return void 0;
30489
31420
  }
@@ -30724,7 +31655,7 @@ var runScheduleRemove = (id, options = {}) => control(id, "remove", options);
30724
31655
 
30725
31656
  // src/assistant/cli.ts
30726
31657
  init_session_cli();
30727
- import { readFileSync as readFileSync12 } from "node:fs";
31658
+ import { readFileSync as readFileSync13 } from "node:fs";
30728
31659
  var daemon = () => requireDaemon();
30729
31660
  var currentSessionId = () => process.env.agentdock_session_id?.trim() || void 0;
30730
31661
  var fromFields = (from) => {
@@ -30793,8 +31724,8 @@ function formatDrafts(drafts) {
30793
31724
  return drafts.map((draft) => `${draft.id} [${draft.state}] ${draft.channel} ${draft.target}`).join("\n");
30794
31725
  }
30795
31726
  function readBody(options) {
30796
- if (options.bodyFile === "-") return readFileSync12(0, "utf8");
30797
- if (options.bodyFile) return readFileSync12(options.bodyFile, "utf8");
31727
+ if (options.bodyFile === "-") return readFileSync13(0, "utf8");
31728
+ if (options.bodyFile) return readFileSync13(options.bodyFile, "utf8");
30798
31729
  throw new Error("\u8BF7\u7528 --body-file - \u4ECE\u6807\u51C6\u8F93\u5165\u8BFB\u53D6\uFF0C\u6216 --body-file <file>");
30799
31730
  }
30800
31731
  function parseCheck(value) {
@@ -30818,7 +31749,7 @@ async function runTaskStart(taskId, options) {
30818
31749
  if (!title) throw new Error("--title \u5FC5\u586B");
30819
31750
  const doneWhen = (options.doneWhen ?? []).map((item) => item.trim()).filter(Boolean);
30820
31751
  if (!doneWhen.length) throw new Error("\u81F3\u5C11\u7528 --done-when \u5199\u4E00\u6761\u9A8C\u6536\u6807\u51C6");
30821
- const notes = options.notesFile === "-" ? readFileSync12(0, "utf8") : options.notes;
31752
+ const notes = options.notesFile === "-" ? readFileSync13(0, "utf8") : options.notes;
30822
31753
  const result = await callDaemon(daemon(), "/api/assistant/tasks", "POST", {
30823
31754
  title,
30824
31755
  ...notes ? { notes } : {},
@@ -30947,13 +31878,23 @@ async function runSettingsQuietHours(options) {
30947
31878
  async function runDraftCreate(options) {
30948
31879
  const channel = options.channel;
30949
31880
  if (channel !== "github_comment" && channel !== "lark_reply") throw new Error("--channel \u5FC5\u987B\u662F github_comment \u6216 lark_reply");
30950
- const target = options.target?.trim();
30951
- if (!target) throw new Error("--target \u5FC5\u586B");
31881
+ const chat = channel === "lark_reply" ? options.chat?.trim() || options.target?.trim() : void 0;
31882
+ const target = channel === "lark_reply" ? chat : options.target?.trim();
31883
+ if (!target) throw new Error(channel === "lark_reply" ? "--chat \u6216 --target \u5FC5\u586B" : "--target \u5FC5\u586B");
30952
31884
  const body = readBody(options);
31885
+ const at = (options.at ?? []).map((item) => item.trim()).filter(Boolean);
30953
31886
  return print(await callDaemon(daemon(), "/api/assistant/drafts", "POST", {
30954
31887
  channel,
30955
31888
  target,
30956
31889
  body,
31890
+ ...channel === "lark_reply" ? {
31891
+ payload: {
31892
+ chat,
31893
+ ...options.replyTo?.trim() ? { replyTo: options.replyTo.trim() } : {},
31894
+ ...options.inThread === true ? { inThread: true } : {},
31895
+ ...at.length ? { at } : {}
31896
+ }
31897
+ } : {},
30957
31898
  ...options.task ? { taskId: options.task } : {},
30958
31899
  ...fromFields(options.from)
30959
31900
  }), options.json);
@@ -31271,7 +32212,7 @@ async function runNotesUnarchive(options) {
31271
32212
  init_src();
31272
32213
  init_daemon();
31273
32214
  init_session_cli();
31274
- import { readFileSync as readFileSync13 } from "node:fs";
32215
+ import { readFileSync as readFileSync14 } from "node:fs";
31275
32216
  import { resolve as resolve12 } from "node:path";
31276
32217
 
31277
32218
  // src/sources-router/daemon-call.ts
@@ -32022,7 +32963,7 @@ function runRouterDryRun(fixture, options) {
32022
32963
  return output2({ sourceId: sourceId2, ...result, persisted: false, createdCase: false, createdSession: false, sentAction: false }, options.json);
32023
32964
  }
32024
32965
  function readFixture(fixture) {
32025
- return fixture ? readFileSync13(resolve12(fixture), "utf8") : readFileSync13(0, "utf8");
32966
+ return fixture ? readFileSync14(resolve12(fixture), "utf8") : readFileSync14(0, "utf8");
32026
32967
  }
32027
32968
  function parseFixture(raw) {
32028
32969
  try {
@@ -32036,7 +32977,7 @@ function dryRunViaDaemon(sourceId2, event) {
32036
32977
  }
32037
32978
 
32038
32979
  // src/cli.ts
32039
- var packageJson = JSON.parse(readFileSync14(new URL("../package.json", import.meta.url), "utf8"));
32980
+ var packageJson = JSON.parse(readFileSync15(new URL("../package.json", import.meta.url), "utf8"));
32040
32981
  var interactiveOutput = () => Boolean(process.stdout.isTTY && process.env.NO_COLOR === void 0 && process.env.TERM !== "dumb");
32041
32982
  try {
32042
32983
  loadEnvFile();
@@ -32177,6 +33118,9 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
32177
33118
  larkMessageListen: async (options) => {
32178
33119
  await runLarkMessageListen(options);
32179
33120
  },
33121
+ larkAvatarSend: async (options) => {
33122
+ process.stdout.write(await runLarkAvatarSend(options));
33123
+ },
32180
33124
  groupSelf: async () => {
32181
33125
  output3(await runGroupSelf());
32182
33126
  },