@agent-dock/cli 0.2.1 → 0.2.3

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
@@ -13672,6 +13672,7 @@ var SelfUpdateService = class {
13672
13672
  cached;
13673
13673
  checking;
13674
13674
  updating = false;
13675
+ updateStartedAt;
13675
13676
  lastError;
13676
13677
  env;
13677
13678
  lockFile;
@@ -13679,7 +13680,27 @@ var SelfUpdateService = class {
13679
13680
  get distTag() {
13680
13681
  return distTagForVersion(this.options.currentVersion);
13681
13682
  }
13683
+ /**
13684
+ * 桌面壳把打包好的 CLI 当普通前台子进程 spawn,但它自己就是 supervisor。
13685
+ * 先判 desktop:Electron 从终端继承环境时可能带上 AGENTDOCK_DAEMONIZED,
13686
+ * 把桌面实例误认成 daemon 会放开一条完全错误(而且危险)的 npm 升级路径。
13687
+ */
13688
+ get runtime() {
13689
+ if (this.env.AGENTDOCK_DESKTOP_INSTANCE?.trim()) return "desktop";
13690
+ return isDaemonChild(this.env) ? "daemon" : "foreground";
13691
+ }
13682
13692
  async status(refresh = false) {
13693
+ const runtime = this.runtime;
13694
+ if (runtime === "desktop") {
13695
+ return {
13696
+ currentVersion: this.options.currentVersion,
13697
+ distTag: this.distTag,
13698
+ updateAvailable: false,
13699
+ canUpdate: false,
13700
+ updating: false,
13701
+ runtime
13702
+ };
13703
+ }
13683
13704
  const age = this.cached ? this.now() - this.cached.checkedAt : Infinity;
13684
13705
  const ttl = this.cached?.checkError ? CHECK_ERROR_TTL_MS : CHECK_TTL_MS;
13685
13706
  if (refresh || age > ttl) await (this.checking ??= this.check().finally(() => {
@@ -13691,13 +13712,19 @@ var SelfUpdateService = class {
13691
13712
  distTag: this.distTag,
13692
13713
  ...latestVersion ? { latestVersion } : {},
13693
13714
  updateAvailable: Boolean(latestVersion && compareVersions(latestVersion, this.options.currentVersion) > 0),
13694
- canUpdate: isDaemonChild(this.env),
13695
- updating: this.updating || this.lockHeld(),
13715
+ canUpdate: runtime === "daemon",
13716
+ updating: this.updateActive() || this.lockHeld(),
13717
+ runtime,
13696
13718
  ...this.lastError ? { lastError: this.lastError } : {},
13697
13719
  ...this.cached ? { checkedAt: this.cached.checkedAt } : {},
13698
13720
  ...this.cached?.checkError ? { checkError: this.cached.checkError } : {}
13699
13721
  };
13700
13722
  }
13723
+ /** 超过升级最长时限的「进行中」标记视为过期,避免子进程卡死时页面永远转圈。 */
13724
+ updateActive() {
13725
+ if (!this.updating) return false;
13726
+ return this.updateStartedAt !== void 0 && this.now() - this.updateStartedAt < UPDATE_LOCK_MAX_AGE_MS;
13727
+ }
13701
13728
  async check() {
13702
13729
  const runNpm = this.options.runNpm ?? runNpmForAgentDockUpdate;
13703
13730
  try {
@@ -13740,11 +13767,16 @@ var SelfUpdateService = class {
13740
13767
  }
13741
13768
  }
13742
13769
  async start() {
13743
- if (!isDaemonChild(this.env)) throw new RuntimeError("UPDATE_REQUIRES_DAEMON", "\u5F53\u524D\u662F\u524D\u53F0\u8FD0\u884C\uFF08agent-dock serve\uFF09\uFF0C\u754C\u9762\u5347\u7EA7\u540E\u65E0\u6CD5\u81EA\u52A8\u62C9\u8D77\u65B0\u7248\u672C\uFF1B\u8BF7\u5728\u7EC8\u7AEF\u6267\u884C agent-dock update", 409);
13744
- if (this.updating || this.lockHeld()) throw new RuntimeError("UPDATE_IN_PROGRESS", "\u5DF2\u6709\u5347\u7EA7\u5728\u8FDB\u884C\uFF0C\u7A0D\u7B49\u7247\u523B", 409);
13745
- const status = await this.status(true);
13746
- if (!status.updateAvailable) throw new RuntimeError("UPDATE_NOT_AVAILABLE", status.checkError ?? `\u5DF2\u662F\u6700\u65B0\u7248\u672C\uFF08${status.currentVersion}\uFF09`, 409);
13770
+ const runtime = this.runtime;
13771
+ if (runtime === "desktop") throw new RuntimeError("UPDATE_DESKTOP_MANAGED", "\u684C\u9762\u7248\u7531\u5E94\u7528\u5185\u81EA\u52A8\u66F4\u65B0\u8D1F\u8D23\uFF0C\u8BF7\u5728\u4FA7\u8FB9\u680F\u7684\u66F4\u65B0\u5165\u53E3\u5347\u7EA7", 409);
13772
+ if (runtime !== "daemon") throw new RuntimeError("UPDATE_REQUIRES_DAEMON", "\u5F53\u524D\u662F\u524D\u53F0\u8FD0\u884C\uFF08agent-dock serve\uFF09\uFF0C\u754C\u9762\u5347\u7EA7\u540E\u65E0\u6CD5\u81EA\u52A8\u62C9\u8D77\u65B0\u7248\u672C\uFF1B\u8BF7\u5148\u505C\u6B62\u524D\u53F0\u8FDB\u7A0B\uFF0C\u518D\u5728\u7EC8\u7AEF\u6267\u884C npm install -g \u6216\u6539\u7528 agent-dock start", 409);
13773
+ if (!this.updateActive() && this.updating) {
13774
+ this.updating = false;
13775
+ this.updateStartedAt = void 0;
13776
+ }
13777
+ if (this.updateActive() || this.lockHeld()) throw new RuntimeError("UPDATE_IN_PROGRESS", "\u5DF2\u6709\u5347\u7EA7\u5728\u8FDB\u884C\uFF0C\u7A0D\u7B49\u7247\u523B", 409);
13747
13778
  this.updating = true;
13779
+ this.updateStartedAt = this.now();
13748
13780
  this.lastError = void 0;
13749
13781
  const cwd = this.env[DAEMON_CWD_ENV] ?? process.cwd();
13750
13782
  const logFile = join8(cwd, ".agentdock", "daemon", "update.log");
@@ -13753,11 +13785,21 @@ var SelfUpdateService = class {
13753
13785
  delete env[DAEMON_CWD_ENV];
13754
13786
  delete env[DAEMON_STARTED_AT_ENV];
13755
13787
  try {
13788
+ const status = await this.status(true);
13789
+ if (!status.updateAvailable) throw new RuntimeError("UPDATE_NOT_AVAILABLE", status.checkError ?? `\u5DF2\u662F\u6700\u65B0\u7248\u672C\uFF08${status.currentVersion}\uFF09`, 409);
13756
13790
  const child = (this.options.spawnUpdate ?? defaultSpawnUpdate)([this.options.cliEntrypoint, "update", "--dist-tag", this.distTag], { cwd, env, logFile });
13757
- if (!child.pid || !this.acquireLock(child.pid)) throw new Error("\u65E0\u6CD5\u542F\u52A8\u5347\u7EA7\u8FDB\u7A0B");
13791
+ if (!child.pid) throw new Error("\u65E0\u6CD5\u542F\u52A8\u5347\u7EA7\u8FDB\u7A0B");
13792
+ if (!this.acquireLock(child.pid)) {
13793
+ try {
13794
+ process.kill(child.pid, "SIGTERM");
13795
+ } catch {
13796
+ }
13797
+ throw new Error("\u53E6\u4E00\u4E2A\u5B9E\u4F8B\u5DF2\u7ECF\u5728\u5347\u7EA7");
13798
+ }
13758
13799
  const lockedPid = child.pid;
13759
13800
  child.onExit((code) => {
13760
13801
  this.updating = false;
13802
+ this.updateStartedAt = void 0;
13761
13803
  try {
13762
13804
  if (readFileSync5(this.lockFile, "utf8").trim() === String(lockedPid)) rmSync2(this.lockFile, { force: true });
13763
13805
  } catch {
@@ -13766,6 +13808,8 @@ var SelfUpdateService = class {
13766
13808
  });
13767
13809
  } catch (error) {
13768
13810
  this.updating = false;
13811
+ this.updateStartedAt = void 0;
13812
+ if (error instanceof RuntimeError) throw error;
13769
13813
  throw new RuntimeError("UPDATE_FAILED", error instanceof Error ? error.message : String(error), 500);
13770
13814
  }
13771
13815
  return this.status();
@@ -13920,6 +13964,7 @@ function isLoopbackHostHeader(host) {
13920
13964
  }
13921
13965
  function isLocalOwnerRequest(input) {
13922
13966
  if (!isLoopbackAddress(input.address) || !isLoopbackHostHeader(input.host)) return false;
13967
+ if (input.forwardedFor?.trim()) return false;
13923
13968
  const site = input.fetchSite?.trim().toLowerCase();
13924
13969
  return site === void 0 || site === "" || site === "same-origin" || site === "none";
13925
13970
  }
@@ -18483,8 +18528,12 @@ async function registerLarkRoutes(app, options = {}) {
18483
18528
  if (existing) throw new LarkServiceError("SESSION_ALREADY_HANDED_OVER", "\u8BE5\u4F1A\u8BDD\u5DF2\u6258\u7BA1\u5230\u98DE\u4E66\u7FA4\uFF0C\u8BF7\u76F4\u63A5\u6253\u5F00\u5DF2\u6709\u7684\u6258\u7BA1\u7FA4", 409);
18484
18529
  }
18485
18530
  const name = request.body?.name?.trim() || `${cleanChatName(session.title) || session.agentId} \xB7 AgentDock`;
18531
+ const memberOpenIds = (request.body?.memberOpenIds ?? []).map((id2) => id2.trim()).filter(Boolean);
18532
+ if (memberOpenIds.some((id2) => !id2.startsWith("ou_"))) {
18533
+ throw new LarkServiceError("INVALID_HANDOVER_MEMBER", "\u9080\u8BF7\u6210\u5458\u5FC5\u987B\u662F ou_ \u5F00\u5934\u7684 open_id", 400);
18534
+ }
18486
18535
  const bot = await resolveService(void 0, appId);
18487
- const chat = await bot.createChat({ name, memberOpenIds: request.body?.memberOpenIds ?? [] });
18536
+ const chat = await bot.createChat({ name, memberOpenIds });
18488
18537
  await options.cardMappings.save({
18489
18538
  id: `${channel}:${chat.chatId}`,
18490
18539
  channel,
@@ -19569,6 +19618,172 @@ async function registerSystemRoutes(app, options = {}) {
19569
19618
  });
19570
19619
  }
19571
19620
 
19621
+ // src/share-link.ts
19622
+ init_src2();
19623
+
19624
+ // src/access-urls.ts
19625
+ import { hostname as osHostname, networkInterfaces } from "node:os";
19626
+ function isLoopbackV4(address) {
19627
+ const parts = address.split(".");
19628
+ return parts.length === 4 && parts[0] === "127";
19629
+ }
19630
+ function isLoopbackV6(address) {
19631
+ return address.toLowerCase() === "::1";
19632
+ }
19633
+ function isLinkLocalV6(address) {
19634
+ return /^fe[89ab]/.test(address.toLowerCase().split(":")[0] ?? "");
19635
+ }
19636
+ function bindsDualStack(host) {
19637
+ return host === "0.0.0.0" || host === "::";
19638
+ }
19639
+ function bindsLan(host) {
19640
+ return bindsDualStack(host) || !isLoopbackV4(host) && !isLoopbackV6(host) && host !== "localhost";
19641
+ }
19642
+ function origin(host, port) {
19643
+ return `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
19644
+ }
19645
+ function withCredential(url, token) {
19646
+ return token ? `${url}/?t=${encodeURIComponent(token)}` : `${url}/`;
19647
+ }
19648
+ function hostnameEntry(hostname) {
19649
+ const name = (hostname ?? osHostname()).trim().replace(/\.$/, "");
19650
+ if (!name || isLoopbackV4(name) || isLoopbackV6(name) || name.toLowerCase() === "localhost") return void 0;
19651
+ return name;
19652
+ }
19653
+ function accessUrls(input) {
19654
+ const { host, port, token } = input;
19655
+ const locals = [{ kind: "local", url: origin("127.0.0.1", port) }];
19656
+ if (bindsDualStack(host)) locals.push({ kind: "local", url: origin("::1", port) });
19657
+ const lanV4 = [];
19658
+ const lanV6 = [];
19659
+ let stableHostname;
19660
+ if (bindsLan(host)) {
19661
+ stableHostname = hostnameEntry(input.hostname);
19662
+ const seen = /* @__PURE__ */ new Set();
19663
+ const candidates = [bindsDualStack(host) ? "" : host, ...Object.values(input.interfaces ?? networkInterfaces()).flat().map((info) => info?.address ?? "")];
19664
+ for (const address of candidates) {
19665
+ if (!address || seen.has(address)) continue;
19666
+ seen.add(address);
19667
+ if (isLoopbackV4(address) || isLoopbackV6(address)) continue;
19668
+ if (address.includes(":")) {
19669
+ if (!isLinkLocalV6(address)) lanV6.push(address);
19670
+ } else {
19671
+ lanV4.push(address);
19672
+ }
19673
+ }
19674
+ }
19675
+ return [
19676
+ ...locals.map((entry) => ({ ...entry, url: withCredential(entry.url, token) })),
19677
+ ...stableHostname ? [{ kind: "hostname", url: withCredential(origin(stableHostname, port), token) }] : [],
19678
+ ...lanV4.map((address) => ({ kind: "lan-v4", url: withCredential(origin(address, port), token) })),
19679
+ ...lanV6.map((address) => ({ kind: "lan-v6", url: withCredential(origin(address, port), token) }))
19680
+ ];
19681
+ }
19682
+
19683
+ // src/share-link.ts
19684
+ var publicUrlConfigKey = "web.public_url";
19685
+ var labels = {
19686
+ hostname: "\u4E3B\u673A\u540D",
19687
+ "lan-v4": "\u5C40\u57DF\u7F51 IPv4",
19688
+ "lan-v6": "\u5C40\u57DF\u7F51 IPv6",
19689
+ public: "\u516C\u7F51"
19690
+ };
19691
+ function normalizePublicUrl(raw) {
19692
+ const value = raw?.trim();
19693
+ if (!value) return void 0;
19694
+ let url;
19695
+ try {
19696
+ url = new URL(value);
19697
+ } catch {
19698
+ return void 0;
19699
+ }
19700
+ if (url.protocol !== "https:") return void 0;
19701
+ if (url.username || url.password) return void 0;
19702
+ if (!url.hostname) return void 0;
19703
+ if (url.pathname !== "/" && url.pathname !== "") return void 0;
19704
+ url.search = "";
19705
+ url.hash = "";
19706
+ return url.origin;
19707
+ }
19708
+ function bindsLan2(host) {
19709
+ return host !== "127.0.0.1" && host !== "::1" && host.toLowerCase() !== "localhost";
19710
+ }
19711
+ var ShareLinkService = class {
19712
+ constructor(options) {
19713
+ this.options = options;
19714
+ this.now = options.now ?? Date.now;
19715
+ }
19716
+ now;
19717
+ get lanEnabled() {
19718
+ return bindsLan2(this.options.host);
19719
+ }
19720
+ async storedPublicUrl() {
19721
+ const fromEnv = normalizePublicUrl(this.options.env?.AGENTDOCK_PUBLIC_URL);
19722
+ if (fromEnv) return { url: fromEnv, source: "env" };
19723
+ const stored = normalizePublicUrl(await this.options.config?.get(publicUrlConfigKey));
19724
+ return stored ? { url: stored, source: "config" } : void 0;
19725
+ }
19726
+ async settings() {
19727
+ const publicUrl = await this.storedPublicUrl();
19728
+ return {
19729
+ ...publicUrl ? { publicUrl: publicUrl.url, publicUrlSource: publicUrl.source } : {},
19730
+ envLocked: Boolean(normalizePublicUrl(this.options.env?.AGENTDOCK_PUBLIC_URL))
19731
+ };
19732
+ }
19733
+ /** 空串表示清除。非字符串或非 https 地址一律 400,避免把明文 http 公网地址写进二维码。 */
19734
+ async savePublicUrl(raw) {
19735
+ if (typeof raw !== "string") throw new RuntimeError("INVALID_PUBLIC_URL", "publicUrl \u5FC5\u987B\u662F\u5B57\u7B26\u4E32", 400);
19736
+ const trimmed = raw.trim();
19737
+ if (!trimmed) {
19738
+ await this.options.config?.set(publicUrlConfigKey, "");
19739
+ return this.settings();
19740
+ }
19741
+ const normalized = normalizePublicUrl(trimmed);
19742
+ 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);
19743
+ await this.options.config?.set(publicUrlConfigKey, normalized);
19744
+ return this.settings();
19745
+ }
19746
+ async build(sessionId) {
19747
+ if (!this.options.secret) {
19748
+ throw new RuntimeError("SHARE_LINK_DISABLED", "\u672C\u5730 Web \u8BBF\u95EE\u9632\u62A4\u672A\u5F00\u542F\uFF0C\u65E0\u6CD5\u7B7E\u53D1\u626B\u7801\u94FE\u63A5\u3002\u684C\u9762\u5BA2\u6237\u7AEF\u8BF7\u5728\u300C\u5728\u624B\u673A\u4E0A\u6253\u5F00\u300D\u91CC\u5F00\u542F\u5C40\u57DF\u7F51\u8BBF\u95EE\uFF1B\u547D\u4EE4\u884C\u8BF7\u53BB\u6389 AGENTDOCK_WEB_AUTH=off\u3002", 409);
19749
+ }
19750
+ const token = issueMasterToken(this.options.secret, this.options.masterTokenTtlMs ?? defaultMasterTokenTtlMs);
19751
+ const query = `?t=${encodeURIComponent(token)}`;
19752
+ const suffix = `${sessionId ? `/sessions/${encodeURIComponent(sessionId)}` : "/"}${query}`;
19753
+ const urls = accessUrls({
19754
+ host: this.options.host,
19755
+ port: this.options.port,
19756
+ ...this.options.interfaces ? { interfaces: this.options.interfaces } : {},
19757
+ ...this.options.hostname ? { hostname: this.options.hostname } : {}
19758
+ }).filter((entry) => entry.kind !== "local").map((entry) => ({ kind: entry.kind, label: labels[entry.kind], url: `${entry.url.replace(/\/$/, "")}${suffix}` }));
19759
+ const publicUrl = await this.storedPublicUrl();
19760
+ if (publicUrl) urls.push({ kind: "public", label: labels.public, url: `${publicUrl.url}${suffix}` });
19761
+ return {
19762
+ ...sessionId ? { sessionId } : {},
19763
+ expiresAt: this.now() + (this.options.masterTokenTtlMs ?? defaultMasterTokenTtlMs),
19764
+ urls,
19765
+ ...publicUrl ? { publicUrl: publicUrl.url, publicUrlSource: publicUrl.source } : {},
19766
+ lanEnabled: this.lanEnabled
19767
+ };
19768
+ }
19769
+ };
19770
+ function registerShareLinkRoutes(app, service, runtime) {
19771
+ app.get("/api/system/share-link", async (request, reply) => {
19772
+ const sessionId = request.query.sessionId?.trim() || void 0;
19773
+ if (sessionId && !await runtime.getSession(sessionId)) throw new RuntimeError("SESSION_NOT_FOUND", `Session not found: ${sessionId}`, 404);
19774
+ reply.header("cache-control", "no-store");
19775
+ return service.build(sessionId);
19776
+ });
19777
+ app.get("/api/system/share-settings", async (_request, reply) => {
19778
+ reply.header("cache-control", "no-store");
19779
+ return service.settings();
19780
+ });
19781
+ app.put("/api/system/share-settings", async (request, reply) => {
19782
+ reply.header("cache-control", "no-store");
19783
+ return service.savePublicUrl(request.body?.publicUrl);
19784
+ });
19785
+ }
19786
+
19572
19787
  // src/schedules/routes.ts
19573
19788
  function registerScheduleRoutes(app, schedules2) {
19574
19789
  app.get("/api/schedules", async (request) => {
@@ -20027,7 +20242,8 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
20027
20242
  const secret = options.webAuth.secret;
20028
20243
  const queryClaim = verifyWebToken(url.searchParams.get("t") ?? void 0, secret);
20029
20244
  const presented = queryClaim ?? verifyWebToken(parseCookieHeader(request.headers.cookie, webAccessCookieName), secret) ?? verifyWebToken(parseCookieHeader(request.headers.cookie, webAccessSessionCookieName), secret);
20030
- const localOwner = isLocalOwnerRequest({ address: request.socket.remoteAddress, host: request.headers.host, fetchSite: request.headers["sec-fetch-site"] });
20245
+ const forwardedFor = request.headers["x-forwarded-for"];
20246
+ const localOwner = isLocalOwnerRequest({ address: request.socket.remoteAddress, host: request.headers.host, fetchSite: request.headers["sec-fetch-site"], forwardedFor: Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor });
20031
20247
  const claim = !queryClaim && localOwner && presented?.kind !== "master" ? verifyWebToken(issueMasterToken(secret), secret) : presented;
20032
20248
  if (!claim) return reject(socket, 401, '{"error":{"code":"UNAUTHORIZED","message":"\u8BBF\u95EE\u51ED\u8BC1\u7F3A\u5931\u6216\u5DF2\u8FC7\u671F\u3002"}}');
20033
20249
  if (claim.kind === "session" && !sessionTokenAllows("GET", url.pathname, claim.sessionId)) {
@@ -21221,9 +21437,10 @@ async function buildApp(runtime, options = {}) {
21221
21437
  request.webClaim = null;
21222
21438
  const url = new URL(request.url, "http://agent-dock.local");
21223
21439
  const queryToken = url.searchParams.get("t") ?? void 0;
21440
+ const forwardedHttps = request.headers["x-forwarded-proto"] === "https";
21224
21441
  const setCredentialCookie = (token, value) => {
21225
21442
  const maxAge = Math.max(0, Math.floor((value.expiresAt - Date.now()) / 1e3));
21226
- reply.header("set-cookie", `${webAccessCookieNameFor(value.kind)}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}`);
21443
+ reply.header("set-cookie", `${webAccessCookieNameFor(value.kind)}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}${forwardedHttps ? "; Secure" : ""}`);
21227
21444
  };
21228
21445
  let claim = null;
21229
21446
  let explicitCredential = false;
@@ -21243,7 +21460,8 @@ async function buildApp(runtime, options = {}) {
21243
21460
  if (isSourceIngressRequest(request.method, url.pathname)) return;
21244
21461
  if (url.pathname.startsWith("/api/lark/agent-tools/")) return;
21245
21462
  claim ??= verifyWebToken(parseCookieHeader(request.headers.cookie, webAccessCookieName), secret) ?? verifyWebToken(parseCookieHeader(request.headers.cookie, webAccessSessionCookieName), secret);
21246
- if (!explicitCredential && claim?.kind !== "master" && isLocalOwnerRequest({ address: request.ip, host: request.headers.host, fetchSite: request.headers["sec-fetch-site"] })) {
21463
+ const forwardedFor = request.headers["x-forwarded-for"];
21464
+ if (!explicitCredential && claim?.kind !== "master" && isLocalOwnerRequest({ address: request.ip, host: request.headers.host, fetchSite: request.headers["sec-fetch-site"], forwardedFor: Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor })) {
21247
21465
  const token = issueMasterToken(secret);
21248
21466
  const localClaim = verifyWebToken(token, secret);
21249
21467
  if (localClaim) {
@@ -21279,7 +21497,8 @@ async function buildApp(runtime, options = {}) {
21279
21497
  const token = issueMasterToken(secret);
21280
21498
  const claim = verifyWebToken(token, secret);
21281
21499
  const maxAge = Math.max(0, Math.floor((claim.expiresAt - Date.now()) / 1e3));
21282
- reply.header("set-cookie", `${webAccessCookieName}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}`);
21500
+ const secure = request.headers["x-forwarded-proto"] === "https" ? "; Secure" : "";
21501
+ reply.header("set-cookie", `${webAccessCookieName}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${maxAge}${secure}`);
21283
21502
  return { ok: true };
21284
21503
  });
21285
21504
  }
@@ -21308,6 +21527,7 @@ async function buildApp(runtime, options = {}) {
21308
21527
  return value;
21309
21528
  });
21310
21529
  await registerSystemRoutes(app, options.system);
21530
+ if (options.shareLinks) registerShareLinkRoutes(app, options.shareLinks, runtime);
21311
21531
  if (options.selfUpdate) registerSelfUpdateRoutes(app, options.selfUpdate);
21312
21532
  if (options.schedules) registerScheduleRoutes(app, options.schedules);
21313
21533
  if (options.sourcesRouter) registerSourceRouterRoutes(app, options.sourcesRouter);
@@ -23650,7 +23870,7 @@ async function startLocalServer(options = {}) {
23650
23870
  const ttlDays = Number(env.AGENTDOCK_WEB_TOKEN_TTL_DAYS);
23651
23871
  const sessionTokenTtlMs = Number.isFinite(ttlDays) && ttlDays > 0 ? ttlDays * 24 * 60 * 6e4 : defaultSessionTokenTtlMs;
23652
23872
  initWebAccess(secret, sessionTokenTtlMs);
23653
- webAuth = { enabled: true, secret };
23873
+ webAuth = { enabled: true, secret, sessionTokenTtlMs };
23654
23874
  }
23655
23875
  const webRoot = options.webRoot ?? fileURLToPath5(new URL("../public", import.meta.url));
23656
23876
  const llm = new LlmEndpointService({ config: repos.config });
@@ -23664,7 +23884,8 @@ async function startLocalServer(options = {}) {
23664
23884
  }) : void 0;
23665
23885
  sourcesRouter = new SourceRouterService({ databaseUrl: config.databaseUrl, runtime, env, routerDriver, startRouterPoll: false });
23666
23886
  const autostart = options.cliEntrypoint ? new AutostartService({ entrypoint: options.cliEntrypoint, env }) : void 0;
23667
- app = await buildApp(runtime, { webRoot, webAuth, schedules: schedules2, sourcesRouter, ...selfUpdate ? { selfUpdate } : {}, ...autostart ? { system: { autostart } } : {}, llm: { service: llm }, lark: { env, config: repos.config, agents: repos.agents, cardMappings: repos.channelMappings, runtime, agentTools, listeningDisabled: env.AGENTDOCK_DISABLE_LARK_LISTENER === "true" } });
23887
+ const shareLinks = new ShareLinkService({ host: config.host, port: config.port, secret: webAuth.secret ?? "", config: repos.config, env });
23888
+ app = await buildApp(runtime, { webRoot, webAuth, shareLinks, schedules: schedules2, sourcesRouter, ...selfUpdate ? { selfUpdate } : {}, ...autostart ? { system: { autostart } } : {}, llm: { service: llm }, lark: { env, config: repos.config, agents: repos.agents, cardMappings: repos.channelMappings, runtime, agentTools, listeningDisabled: env.AGENTDOCK_DISABLE_LARK_LISTENER === "true" } });
23668
23889
  await app.listen(listenOptions(config));
23669
23890
  schedules2.start();
23670
23891
  sourcesRouter.start();
@@ -24069,11 +24290,11 @@ function padToWidth(text2, width) {
24069
24290
  function formatAccessUrls(result, options = {}) {
24070
24291
  const urls = result.webAccessUrls?.length ? result.webAccessUrls : result.webConsoleUrl ? [{ kind: "local", url: result.webConsoleUrl }] : [];
24071
24292
  if (!urls.length) return [];
24072
- const labels = urls.map((entry) => kindLabels[entry.kind]);
24073
- const width = Math.max(...labels.map(displayWidth));
24293
+ const labels2 = urls.map((entry) => kindLabels[entry.kind]);
24294
+ const width = Math.max(...labels2.map(displayWidth));
24074
24295
  return [
24075
24296
  "\u63A7\u5236\u53F0\uFF08\u542B\u8BBF\u95EE\u51ED\u8BC1\uFF0C\u8BF7\u52FF\u5916\u4F20\uFF09\uFF1A",
24076
- ...urls.map((entry, index) => ` ${padToWidth(labels[index], width)} ${options.interactive ? "\u2197 " : ""}${terminalLink(entry.url, options.interactive ?? false)}`)
24297
+ ...urls.map((entry, index) => ` ${padToWidth(labels2[index], width)} ${options.interactive ? "\u2197 " : ""}${terminalLink(entry.url, options.interactive ?? false)}`)
24077
24298
  ];
24078
24299
  }
24079
24300
  function formatDaemonStatus(status, options = {}) {
@@ -24115,65 +24336,6 @@ function formatDaemonCommandResult(result, options = {}) {
24115
24336
  return lines.join("\n");
24116
24337
  }
24117
24338
 
24118
- // src/access-urls.ts
24119
- import { hostname as osHostname, networkInterfaces } from "node:os";
24120
- function isLoopbackV4(address) {
24121
- const parts = address.split(".");
24122
- return parts.length === 4 && parts[0] === "127";
24123
- }
24124
- function isLoopbackV6(address) {
24125
- return address.toLowerCase() === "::1";
24126
- }
24127
- function isLinkLocalV6(address) {
24128
- return /^fe[89ab]/.test(address.toLowerCase().split(":")[0] ?? "");
24129
- }
24130
- function bindsDualStack(host) {
24131
- return host === "0.0.0.0" || host === "::";
24132
- }
24133
- function bindsLan(host) {
24134
- return bindsDualStack(host) || !isLoopbackV4(host) && !isLoopbackV6(host) && host !== "localhost";
24135
- }
24136
- function origin(host, port) {
24137
- return `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
24138
- }
24139
- function withCredential(url, token) {
24140
- return token ? `${url}/?t=${encodeURIComponent(token)}` : `${url}/`;
24141
- }
24142
- function hostnameEntry(hostname) {
24143
- const name = (hostname ?? osHostname()).trim().replace(/\.$/, "");
24144
- if (!name || isLoopbackV4(name) || isLoopbackV6(name) || name.toLowerCase() === "localhost") return void 0;
24145
- return name;
24146
- }
24147
- function accessUrls(input) {
24148
- const { host, port, token } = input;
24149
- const locals = [{ kind: "local", url: origin("127.0.0.1", port) }];
24150
- if (bindsDualStack(host)) locals.push({ kind: "local", url: origin("::1", port) });
24151
- const lanV4 = [];
24152
- const lanV6 = [];
24153
- let stableHostname;
24154
- if (bindsLan(host)) {
24155
- stableHostname = hostnameEntry(input.hostname);
24156
- const seen = /* @__PURE__ */ new Set();
24157
- const candidates = [bindsDualStack(host) ? "" : host, ...Object.values(input.interfaces ?? networkInterfaces()).flat().map((info) => info?.address ?? "")];
24158
- for (const address of candidates) {
24159
- if (!address || seen.has(address)) continue;
24160
- seen.add(address);
24161
- if (isLoopbackV4(address) || isLoopbackV6(address)) continue;
24162
- if (address.includes(":")) {
24163
- if (!isLinkLocalV6(address)) lanV6.push(address);
24164
- } else {
24165
- lanV4.push(address);
24166
- }
24167
- }
24168
- }
24169
- return [
24170
- ...locals.map((entry) => ({ ...entry, url: withCredential(entry.url, token) })),
24171
- ...stableHostname ? [{ kind: "hostname", url: withCredential(origin(stableHostname, port), token) }] : [],
24172
- ...lanV4.map((address) => ({ kind: "lan-v4", url: withCredential(origin(address, port), token) })),
24173
- ...lanV6.map((address) => ({ kind: "lan-v6", url: withCredential(origin(address, port), token) }))
24174
- ];
24175
- }
24176
-
24177
24339
  // src/cli.ts
24178
24340
  init_daemon();
24179
24341