@agent-dock/cli 0.3.21 → 0.3.23

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
@@ -260,9 +260,9 @@ function normalizeUsageDateBound(raw, endOfDay) {
260
260
  const parsed = new Date(trimmed);
261
261
  return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString();
262
262
  }
263
- function computeTps(outputTokens, thoughtTokens, generationMs) {
263
+ function computeTps(outputTokens, generationMs) {
264
264
  if (!generationMs || !Number.isFinite(generationMs) || generationMs <= 0) return null;
265
- const generated = Math.max(0, outputTokens) + Math.max(0, thoughtTokens);
265
+ const generated = Math.max(0, outputTokens);
266
266
  if (generated <= 0) return null;
267
267
  return Math.round(generated / (generationMs / 1e3) * 10) / 10;
268
268
  }
@@ -278,7 +278,7 @@ function rowToTotals(row) {
278
278
  const sessionCount = Number(row?.session_count ?? 0);
279
279
  const totalGenerationMs = Number(row?.total_generation_ms ?? 0);
280
280
  const totalDurationMs = Number(row?.total_duration_ms ?? 0);
281
- const avgTps = computeTps(Number(row?.gen_output_tokens ?? 0), Number(row?.gen_thought_tokens ?? 0), totalGenerationMs);
281
+ const avgTps = computeTps(Number(row?.gen_output_tokens ?? 0), totalGenerationMs);
282
282
  return {
283
283
  inputTokens,
284
284
  outputTokens,
@@ -424,7 +424,7 @@ function createUsageRepository(sqlite) {
424
424
  durationMs: row.duration_ms,
425
425
  generationMs: row.generation_ms,
426
426
  ttftMs: row.ttft_ms,
427
- tps: computeTps(row.output_tokens, row.thought_tokens, row.generation_ms),
427
+ tps: computeTps(row.output_tokens, row.generation_ms),
428
428
  createdAt: row.created_at
429
429
  }));
430
430
  let lastTps = null;
@@ -614,8 +614,7 @@ var init_usage = __esm({
614
614
  COUNT(DISTINCT u.session_id) AS session_count,
615
615
  COALESCE(SUM(CASE WHEN u.generation_ms > 0 THEN u.generation_ms ELSE 0 END), 0) AS total_generation_ms,
616
616
  COALESCE(SUM(CASE WHEN u.duration_ms > 0 THEN u.duration_ms ELSE 0 END), 0) AS total_duration_ms,
617
- COALESCE(SUM(CASE WHEN u.generation_ms > 0 THEN u.output_tokens ELSE 0 END), 0) AS gen_output_tokens,
618
- COALESCE(SUM(CASE WHEN u.generation_ms > 0 THEN u.thought_tokens ELSE 0 END), 0) AS gen_thought_tokens
617
+ COALESCE(SUM(CASE WHEN u.generation_ms > 0 THEN u.output_tokens ELSE 0 END), 0) AS gen_output_tokens
619
618
  `;
620
619
  }
621
620
  });
@@ -17658,6 +17657,95 @@ var AgentIdleTimeoutError = class extends Error {
17658
17657
  }
17659
17658
  timeoutMs;
17660
17659
  };
17660
+ function normalizeAcpxUsageEntry(entry) {
17661
+ const toNonNeg = (value) => {
17662
+ const n = Number(value ?? 0);
17663
+ return Number.isFinite(n) && n > 0 ? n : 0;
17664
+ };
17665
+ const inputTokens = toNonNeg(entry.input_tokens);
17666
+ const rawOutput = toNonNeg(entry.output_tokens);
17667
+ const cacheReadTokens = toNonNeg(entry.cache_read_input_tokens);
17668
+ const cacheWriteTokens = toNonNeg(entry.cache_creation_input_tokens);
17669
+ const thoughtTokens = toNonNeg(entry.thought_tokens);
17670
+ const rawTotal = toNonNeg(entry.total_tokens);
17671
+ const baseSum = inputTokens + rawOutput + cacheReadTokens + cacheWriteTokens;
17672
+ const thoughtExcludedFromOutput = thoughtTokens > 0 && rawTotal > 0 && rawTotal === baseSum + thoughtTokens;
17673
+ const outputTokens = thoughtExcludedFromOutput ? rawOutput + thoughtTokens : rawOutput;
17674
+ const totalTokens = rawTotal > 0 ? rawTotal : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;
17675
+ return { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, thoughtTokens, totalTokens };
17676
+ }
17677
+ var TurnTimingTracker = class {
17678
+ constructor(turnStartedAt) {
17679
+ this.turnStartedAt = turnStartedAt;
17680
+ }
17681
+ turnStartedAt;
17682
+ firstOutputAt;
17683
+ llmActiveMs = 0;
17684
+ activeSegmentStart;
17685
+ activeToolCallIds = /* @__PURE__ */ new Set();
17686
+ pendingPermissionIds = /* @__PURE__ */ new Set();
17687
+ get activeToolCount() {
17688
+ return this.activeToolCallIds.size;
17689
+ }
17690
+ closeSegment(at) {
17691
+ if (this.activeSegmentStart !== void 0) {
17692
+ this.llmActiveMs += Math.max(0, at - this.activeSegmentStart);
17693
+ this.activeSegmentStart = void 0;
17694
+ }
17695
+ }
17696
+ startSegmentIfReady(at) {
17697
+ if (this.activeSegmentStart !== void 0) return;
17698
+ if (this.activeToolCallIds.size > 0 || this.pendingPermissionIds.size > 0) return;
17699
+ this.activeSegmentStart = at;
17700
+ }
17701
+ onPermissionPending(id, at) {
17702
+ this.pendingPermissionIds.add(id);
17703
+ this.closeSegment(at);
17704
+ }
17705
+ onPermissionResolved(id, at) {
17706
+ this.pendingPermissionIds.delete(id);
17707
+ if (this.firstOutputAt !== void 0) this.startSegmentIfReady(at);
17708
+ }
17709
+ onEvent(event, at) {
17710
+ const toolCallId = typeof event.data?.id === "string" ? event.data.id : void 0;
17711
+ if (event.type === "permission_request") {
17712
+ const status = event.data?.status;
17713
+ if (toolCallId && (!status || status === "pending")) this.onPermissionPending(toolCallId, at);
17714
+ return;
17715
+ }
17716
+ if (event.type === "tool_call") {
17717
+ if (this.firstOutputAt === void 0) this.firstOutputAt = at;
17718
+ this.closeSegment(at);
17719
+ if (toolCallId) this.activeToolCallIds.add(toolCallId);
17720
+ return;
17721
+ }
17722
+ if (event.type === "tool_result") {
17723
+ if (toolCallId) {
17724
+ this.activeToolCallIds.delete(toolCallId);
17725
+ this.pendingPermissionIds.delete(toolCallId);
17726
+ } else {
17727
+ this.activeToolCallIds.clear();
17728
+ }
17729
+ if (this.firstOutputAt !== void 0) this.startSegmentIfReady(at);
17730
+ return;
17731
+ }
17732
+ if (event.type === "text" || event.type === "thinking") {
17733
+ if (this.firstOutputAt === void 0) this.firstOutputAt = at;
17734
+ if (this.pendingPermissionIds.size === 0 && this.activeSegmentStart === void 0) {
17735
+ this.activeSegmentStart = at;
17736
+ }
17737
+ }
17738
+ }
17739
+ finish(streamEndedAt, finishedAt = streamEndedAt) {
17740
+ this.closeSegment(streamEndedAt);
17741
+ const durationMs = Math.max(1, finishedAt - this.turnStartedAt);
17742
+ return {
17743
+ durationMs,
17744
+ ...this.llmActiveMs > 0 ? { generationMs: Math.min(durationMs, this.llmActiveMs) } : {},
17745
+ ...this.firstOutputAt !== void 0 ? { ttftMs: Math.max(0, this.firstOutputAt - this.turnStartedAt) } : {}
17746
+ };
17747
+ }
17748
+ };
17661
17749
  var AcpxAdapter = class {
17662
17750
  constructor(agent, options) {
17663
17751
  this.agent = agent;
@@ -17691,6 +17779,7 @@ var AcpxAdapter = class {
17691
17779
  if (this.permissionMode === "full-trust") return { outcome: "allow_once" };
17692
17780
  if (this.permissionMode === "deny-all") return { outcome: "reject_once" };
17693
17781
  if (this.permissionMode === "approve-reads" && /read|search|fetch/i.test(String(request.inferredKind ?? ""))) return { outcome: "allow_once" };
17782
+ this.activeTiming?.onPermissionPending(id, Date.now());
17694
17783
  this.options.onEvent({ type: "permission_request", data: { id, toolCallId: raw.toolCall?.toolCallId, title: raw.toolCall?.title ?? "Permission required", options: raw.options ?? [], status: "pending" } });
17695
17784
  return new Promise((resolve17) => this.pendingPermissions.set(id, resolve17));
17696
17785
  }
@@ -17702,6 +17791,7 @@ var AcpxAdapter = class {
17702
17791
  sessionStore;
17703
17792
  handle;
17704
17793
  turn;
17794
+ activeTiming;
17705
17795
  pendingPermissions = /* @__PURE__ */ new Map();
17706
17796
  sessionKey;
17707
17797
  reportedTitle;
@@ -17855,21 +17945,16 @@ var AcpxAdapter = class {
17855
17945
  for (const key of newKeys) {
17856
17946
  const entry = reqMap[key];
17857
17947
  if (!entry || typeof entry !== "object") continue;
17858
- const inp = Number(entry.input_tokens ?? 0);
17859
- const out = Number(entry.output_tokens ?? 0);
17860
- const cRead = Number(entry.cache_read_input_tokens ?? 0);
17861
- const cWrite = Number(entry.cache_creation_input_tokens ?? 0);
17862
- const thought = Number(entry.thought_tokens ?? 0);
17863
- const total = Number(entry.total_tokens ?? inp + out + cRead + cWrite + thought);
17864
- if (Number.isFinite(inp) && inp > 0) inputTokens += inp;
17865
- if (Number.isFinite(out) && out > 0) outputTokens += out;
17866
- if (Number.isFinite(cRead) && cRead > 0) cacheReadTokens += cRead;
17867
- if (Number.isFinite(cWrite) && cWrite > 0) cacheWriteTokens += cWrite;
17868
- if (Number.isFinite(thought) && thought > 0) thoughtTokens += thought;
17869
- if (Number.isFinite(total) && total > 0) totalTokens += total;
17948
+ const normalized2 = normalizeAcpxUsageEntry(entry);
17949
+ inputTokens += normalized2.inputTokens;
17950
+ outputTokens += normalized2.outputTokens;
17951
+ cacheReadTokens += normalized2.cacheReadTokens;
17952
+ cacheWriteTokens += normalized2.cacheWriteTokens;
17953
+ thoughtTokens += normalized2.thoughtTokens;
17954
+ totalTokens += normalized2.totalTokens;
17870
17955
  }
17871
17956
  if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0) return;
17872
- if (totalTokens <= 0) totalTokens = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens;
17957
+ if (totalTokens <= 0) totalTokens = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;
17873
17958
  const afterCost = typeof record?.cumulative_cost?.amount === "number" && Number.isFinite(record.cumulative_cost.amount) ? record.cumulative_cost.amount : void 0;
17874
17959
  const costUsd = afterCost !== void 0 && afterCost > prevCostUsd ? Math.round((afterCost - prevCostUsd) * 1e6) / 1e6 : void 0;
17875
17960
  this.options.onEvent({
@@ -17896,25 +17981,16 @@ var AcpxAdapter = class {
17896
17981
  const beforeRecord = await this.sessionStore.load(this.sessionKey).catch(() => void 0);
17897
17982
  const prevUsageKeys = new Set(Object.keys(beforeRecord?.request_token_usage ?? {}));
17898
17983
  const prevCostUsd = typeof beforeRecord?.cumulative_cost?.amount === "number" && Number.isFinite(beforeRecord.cumulative_cost.amount) ? beforeRecord.cumulative_cost.amount : 0;
17899
- const turnStartedAt = Date.now();
17900
- let firstOutputAt;
17901
- let activeOutputMs = 0;
17902
- let outputSegmentStart;
17903
- const closeOutputSegment = (at) => {
17904
- if (outputSegmentStart !== void 0) {
17905
- activeOutputMs += Math.max(0, at - outputSegmentStart);
17906
- outputSegmentStart = void 0;
17907
- }
17908
- };
17984
+ const timing = new TurnTimingTracker(Date.now());
17985
+ this.activeTiming = timing;
17909
17986
  const { idle: idleTimeoutMs, toolCall: toolCallTimeoutMs } = resolveTurnTimeouts(this.agent.timeout);
17910
17987
  const turn = this.runtime.startTurn({ handle: this.handle, text: prompt, mode: "prompt", requestId, timeoutMs: 0 });
17911
17988
  this.turn = turn;
17912
17989
  try {
17913
17990
  const iterator = turn.events[Symbol.asyncIterator]();
17914
- const activeToolCallIds = /* @__PURE__ */ new Set();
17915
17991
  while (true) {
17916
17992
  let timer;
17917
- const effectiveTimeout = activeToolCallIds.size > 0 ? toolCallTimeoutMs : idleTimeoutMs;
17993
+ const effectiveTimeout = timing.activeToolCount > 0 ? toolCallTimeoutMs : idleTimeoutMs;
17918
17994
  const idle = new Promise((_resolve, reject2) => {
17919
17995
  timer = setTimeout(() => reject2(new AgentIdleTimeoutError(effectiveTimeout)), effectiveTimeout);
17920
17996
  });
@@ -17933,35 +18009,20 @@ var AcpxAdapter = class {
17933
18009
  if (next.done) break;
17934
18010
  const normalized2 = normalizeAcpxEvent(next.value);
17935
18011
  if (normalized2) {
17936
- const eventAt = Date.now();
17937
- const toolCallId = typeof normalized2.data?.id === "string" ? normalized2.data.id : void 0;
17938
- if (normalized2.type === "tool_call") {
17939
- if (activeToolCallIds.size === 0) closeOutputSegment(eventAt);
17940
- if (toolCallId) activeToolCallIds.add(toolCallId);
17941
- } else if (normalized2.type === "tool_result") {
17942
- if (toolCallId) activeToolCallIds.delete(toolCallId);
17943
- else activeToolCallIds.clear();
17944
- } else if ((normalized2.type === "text" || normalized2.type === "thinking") && activeToolCallIds.size === 0) {
17945
- if (firstOutputAt === void 0) firstOutputAt = eventAt;
17946
- if (outputSegmentStart === void 0) outputSegmentStart = eventAt;
17947
- }
18012
+ timing.onEvent(normalized2, Date.now());
17948
18013
  this.options.onEvent(normalized2);
17949
18014
  }
17950
18015
  }
17951
18016
  const streamEndedAt = Date.now();
17952
- closeOutputSegment(streamEndedAt);
17953
18017
  const result = await turn.result;
17954
18018
  if (result.status === "failed") throw new Error(result.error.message);
17955
18019
  const finishedAt = Date.now();
17956
18020
  await this.reportAgentTitle();
17957
- await this.reportTurnUsage(prevUsageKeys, prevCostUsd, requestId, {
17958
- durationMs: Math.max(1, finishedAt - turnStartedAt),
17959
- ...activeOutputMs > 0 ? { generationMs: activeOutputMs } : {},
17960
- ...firstOutputAt !== void 0 ? { ttftMs: Math.max(0, firstOutputAt - turnStartedAt) } : {}
17961
- });
18021
+ await this.reportTurnUsage(prevUsageKeys, prevCostUsd, requestId, timing.finish(streamEndedAt, finishedAt));
17962
18022
  this.options.onEvent({ type: "completed", data: { stopReason: result.stopReason ?? result.status } });
17963
18023
  } finally {
17964
18024
  if (this.turn === turn) this.turn = void 0;
18025
+ if (this.activeTiming === timing) this.activeTiming = void 0;
17965
18026
  }
17966
18027
  }
17967
18028
  async send(prompt) {
@@ -18002,6 +18063,7 @@ var AcpxAdapter = class {
18002
18063
  const resolve17 = this.pendingPermissions.get(id);
18003
18064
  if (!resolve17) return false;
18004
18065
  this.pendingPermissions.delete(id);
18066
+ this.activeTiming?.onPermissionResolved(id, Date.now());
18005
18067
  resolve17({ outcome: approved ? "allow_once" : "reject_once" });
18006
18068
  return true;
18007
18069
  }
@@ -22750,8 +22812,10 @@ var toNonNegInt = (value) => {
22750
22812
  const num = Number(value ?? 0);
22751
22813
  return Number.isFinite(num) && num > 0 ? Math.round(num) : 0;
22752
22814
  };
22753
- function createUsageBackfiller(target) {
22815
+ function createUsageBackfiller(target, options = {}) {
22754
22816
  const scannedMtime = /* @__PURE__ */ new Map();
22817
+ const minIntervalMs = Math.max(0, options.minIntervalMs ?? 6e4);
22818
+ let lastSyncedAt = 0;
22755
22819
  let inFlight5;
22756
22820
  async function runOnce() {
22757
22821
  const sessions2 = await target.listSessions();
@@ -22779,12 +22843,14 @@ function createUsageBackfiller(target) {
22779
22843
  if (!reqMap || typeof reqMap !== "object") continue;
22780
22844
  const entries = Object.entries(reqMap).map(([requestId, raw]) => {
22781
22845
  const inputTokens = toNonNegInt(raw?.input_tokens);
22782
- const outputTokens = toNonNegInt(raw?.output_tokens);
22846
+ const rawOutput = toNonNegInt(raw?.output_tokens);
22783
22847
  const cacheReadTokens = toNonNegInt(raw?.cache_read_input_tokens);
22784
22848
  const cacheWriteTokens = toNonNegInt(raw?.cache_creation_input_tokens);
22785
22849
  const thoughtTokens = toNonNegInt(raw?.thought_tokens);
22786
22850
  const rawTotal = toNonNegInt(raw?.total_tokens);
22787
- const totalTokens = rawTotal > 0 ? rawTotal : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens;
22851
+ const baseSum = inputTokens + rawOutput + cacheReadTokens + cacheWriteTokens;
22852
+ const outputTokens = thoughtTokens > 0 && rawTotal > 0 && rawTotal === baseSum + thoughtTokens ? rawOutput + thoughtTokens : rawOutput;
22853
+ const totalTokens = rawTotal > 0 ? rawTotal : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;
22788
22854
  return { requestId, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, thoughtTokens, totalTokens };
22789
22855
  }).filter((item) => item.totalTokens > 0 || item.inputTokens > 0 || item.outputTokens > 0);
22790
22856
  if (!entries.length) continue;
@@ -22820,9 +22886,12 @@ function createUsageBackfiller(target) {
22820
22886
  return inserted;
22821
22887
  }
22822
22888
  return {
22823
- async sync() {
22889
+ async sync(force = false) {
22890
+ const nowMs = Date.now();
22891
+ if (!force && lastSyncedAt > 0 && nowMs - lastSyncedAt < minIntervalMs) return 0;
22824
22892
  if (!inFlight5) {
22825
22893
  inFlight5 = runOnce().finally(() => {
22894
+ lastSyncedAt = Date.now();
22826
22895
  inFlight5 = void 0;
22827
22896
  });
22828
22897
  }
@@ -23993,7 +24062,7 @@ init_src2();
23993
24062
  import { createReadStream, realpathSync as realpathSync3 } from "node:fs";
23994
24063
  import { readdir as readdir3, readFile as readFile11, stat as stat5 } from "node:fs/promises";
23995
24064
  import { homedir as homedir13 } from "node:os";
23996
- import { basename as basename7, isAbsolute as isAbsolute7, join as join19, relative, sep as sep2 } from "node:path";
24065
+ import { basename as basename7, dirname as dirname11, isAbsolute as isAbsolute7, join as join19, relative, sep as sep2 } from "node:path";
23997
24066
 
23998
24067
  // src/fs-paths.ts
23999
24068
  import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
@@ -24236,6 +24305,10 @@ function mediaMimeForName(name) {
24236
24305
  }
24237
24306
 
24238
24307
  // src/fs-routes.ts
24308
+ var DEFAULT_MAX_DIR_ENTRIES = 500;
24309
+ function compareEntryName(left, right) {
24310
+ return left.localeCompare(right, void 0, { numeric: true, sensitivity: "base" });
24311
+ }
24239
24312
  function badPath(error) {
24240
24313
  if (error instanceof RuntimeError) throw error;
24241
24314
  if (error instanceof WorkspacePathError) throw new RuntimeError("INVALID_PATH", error.message, 400);
@@ -24309,36 +24382,36 @@ async function registerFsRoutes(app, runtime, options = {}) {
24309
24382
  }
24310
24383
  const userPath = request.query.path;
24311
24384
  if (!userPath) throw new RuntimeError("INVALID_PATH", "\u7F3A\u5C11 path \u53C2\u6570", 400);
24312
- const expandedPath = userPath.startsWith("~/") ? join19(options.homeDir ?? homedir13(), userPath.slice(2)) : userPath;
24385
+ const homeDir = options.homeDir ?? homedir13();
24386
+ const expandedPath = userPath === "~" ? homeDir : userPath.startsWith("~/") ? join19(homeDir, userPath.slice(2)) : userPath;
24313
24387
  if (isSensitivePath(userPath) || isSensitivePath(expandedPath)) {
24314
24388
  throw new RuntimeError("SENSITIVE_FILE_BLOCKED", "\u7981\u6B62\u9884\u89C8\u6216\u4E0B\u8F7D\u654F\u611F\u6587\u4EF6", 403);
24315
24389
  }
24316
24390
  const claim = request.webClaim;
24317
24391
  const role = claim?.kind === "session" ? "session" : "master";
24392
+ const sessionRoots = role === "session" ? allowedReadRoots({
24393
+ role,
24394
+ cwd: session.cwd,
24395
+ sessionId: request.params.id,
24396
+ ...options.homeDir ? { homeDir: options.homeDir } : {},
24397
+ ...options.tempDir ? { tempDir: options.tempDir } : {},
24398
+ ...options.extraMasterRoots ? { extraMasterRoots: options.extraMasterRoots } : {}
24399
+ }) : void 0;
24400
+ let realCwd;
24401
+ try {
24402
+ realCwd = realpathSync3(session.cwd);
24403
+ } catch {
24404
+ }
24318
24405
  let resolved;
24319
24406
  try {
24320
24407
  if (isAbsolute7(expandedPath)) {
24321
24408
  const realTarget = realpathSync3(expandedPath);
24322
- if (role === "session") {
24323
- const roots = allowedReadRoots({
24324
- role,
24325
- cwd: session.cwd,
24326
- sessionId: request.params.id,
24327
- ...options.homeDir ? { homeDir: options.homeDir } : {},
24328
- ...options.tempDir ? { tempDir: options.tempDir } : {},
24329
- ...options.extraMasterRoots ? { extraMasterRoots: options.extraMasterRoots } : {}
24330
- });
24331
- if (!isRealPathWithinRoots(realTarget, roots)) {
24332
- throw new RuntimeError("FORBIDDEN", "\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5\u53EA\u80FD\u9884\u89C8\u8BE5\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u53CA\u4E0A\u4F20\u76EE\u5F55\u5185\u7684\u6587\u4EF6", 403);
24333
- }
24409
+ if (role === "session" && !isRealPathWithinRoots(realTarget, sessionRoots ?? [])) {
24410
+ throw new RuntimeError("FORBIDDEN", "\u4F1A\u8BDD\u5206\u4EAB\u94FE\u63A5\u53EA\u80FD\u9884\u89C8\u8BE5\u4F1A\u8BDD\u5DE5\u4F5C\u533A\u53CA\u4E0A\u4F20\u76EE\u5F55\u5185\u7684\u6587\u4EF6", 403);
24334
24411
  }
24335
24412
  let rel = expandedPath;
24336
- try {
24337
- const realCwd = realpathSync3(session.cwd);
24338
- if (realTarget === realCwd || realTarget.startsWith(`${realCwd}${sep2}`)) {
24339
- rel = relative(realCwd, realTarget);
24340
- }
24341
- } catch {
24413
+ if (realCwd && (realTarget === realCwd || realTarget.startsWith(`${realCwd}${sep2}`))) {
24414
+ rel = relative(realCwd, realTarget);
24342
24415
  }
24343
24416
  resolved = { absolute: realTarget, relative: rel };
24344
24417
  } else {
@@ -24356,10 +24429,96 @@ async function registerFsRoutes(app, runtime, options = {}) {
24356
24429
  } catch (error) {
24357
24430
  badPath(error);
24358
24431
  }
24432
+ const wantDownload = request.query.download === "1" || request.query.download === "true";
24433
+ if (info.isDirectory()) {
24434
+ if (wantDownload) {
24435
+ throw new RuntimeError("NOT_A_FILE", "\u76EE\u5F55\u4E0D\u652F\u6301\u76F4\u63A5\u4E0B\u8F7D", 400);
24436
+ }
24437
+ const includeHidden = request.query.hidden === "1" || request.query.hidden === "true";
24438
+ let dirents;
24439
+ try {
24440
+ dirents = await readdir3(resolved.absolute, { withFileTypes: true });
24441
+ } catch (error) {
24442
+ badPath(error);
24443
+ }
24444
+ let hiddenCount = 0;
24445
+ const candidates = [];
24446
+ for (const dirent of dirents) {
24447
+ if (dirent.name === ".DS_Store") continue;
24448
+ const isHidden = dirent.name.startsWith(".");
24449
+ if (isHidden) {
24450
+ hiddenCount++;
24451
+ if (!includeHidden) continue;
24452
+ }
24453
+ candidates.push(dirent);
24454
+ }
24455
+ candidates.sort((left, right) => {
24456
+ const leftDir = left.isDirectory();
24457
+ const rightDir = right.isDirectory();
24458
+ if (leftDir !== rightDir) return leftDir ? -1 : 1;
24459
+ return compareEntryName(left.name, right.name);
24460
+ });
24461
+ const limit = Math.max(1, options.maxDirEntries ?? DEFAULT_MAX_DIR_ENTRIES);
24462
+ const totalCount = candidates.length;
24463
+ const sliced = candidates.slice(0, limit);
24464
+ const useAbsoluteEntryPath = !realCwd || !(resolved.absolute === realCwd || resolved.absolute.startsWith(`${realCwd}${sep2}`));
24465
+ const entries = [];
24466
+ await Promise.all(sliced.map(async (dirent) => {
24467
+ const entryAbs = join19(resolved.absolute, dirent.name);
24468
+ const entryPath = useAbsoluteEntryPath ? entryAbs : resolved.relative ? `${resolved.relative}/${dirent.name}` : dirent.name;
24469
+ try {
24470
+ const entryStat = await stat5(entryAbs);
24471
+ entries.push({
24472
+ name: dirent.name,
24473
+ path: entryPath,
24474
+ kind: entryStat.isDirectory() ? "directory" : "file",
24475
+ size: entryStat.isDirectory() ? 0 : entryStat.size,
24476
+ mtime: entryStat.mtime.toISOString()
24477
+ });
24478
+ } catch {
24479
+ if (!dirent.isSymbolicLink()) {
24480
+ entries.push({
24481
+ name: dirent.name,
24482
+ path: entryPath,
24483
+ kind: dirent.isDirectory() ? "directory" : "file",
24484
+ size: 0,
24485
+ mtime: ""
24486
+ });
24487
+ }
24488
+ }
24489
+ }));
24490
+ entries.sort((left, right) => {
24491
+ if (left.kind !== right.kind) return left.kind === "directory" ? -1 : 1;
24492
+ return compareEntryName(left.name, right.name);
24493
+ });
24494
+ const parentAbs = dirname11(resolved.absolute);
24495
+ let parentPath = null;
24496
+ if (parentAbs !== resolved.absolute && !isSensitivePath(parentAbs)) {
24497
+ const parentAllowed = role === "master" || isRealPathWithinRoots(parentAbs, sessionRoots ?? []);
24498
+ if (parentAllowed) {
24499
+ if (realCwd && (parentAbs === realCwd || parentAbs.startsWith(`${realCwd}${sep2}`))) {
24500
+ parentPath = relative(realCwd, parentAbs) || realCwd;
24501
+ } else {
24502
+ parentPath = parentAbs;
24503
+ }
24504
+ }
24505
+ }
24506
+ return {
24507
+ kind: "directory",
24508
+ cwd: session.cwd,
24509
+ path: resolved.relative || resolved.absolute,
24510
+ absolutePath: resolved.absolute,
24511
+ parentPath,
24512
+ entries,
24513
+ totalCount,
24514
+ truncated: totalCount > entries.length,
24515
+ hiddenCount,
24516
+ includeHidden
24517
+ };
24518
+ }
24359
24519
  if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
24360
24520
  const filename = basename7(resolved.absolute);
24361
24521
  const isSvg = filename.toLowerCase().endsWith(".svg");
24362
- const wantDownload = request.query.download === "1" || request.query.download === "true";
24363
24522
  const wantText = request.query.format === "text";
24364
24523
  if (wantDownload) {
24365
24524
  const contentType = imageMimeForName(filename) ?? mediaMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream");
@@ -24418,7 +24577,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
24418
24577
  if (isBinaryBuffer(buffer)) {
24419
24578
  throw new RuntimeError("BINARY_FILE", "\u68C0\u6D4B\u5230\u4E8C\u8FDB\u5236\u6587\u4EF6\u5185\u5BB9\uFF0C\u6682\u4E0D\u652F\u6301\u6587\u672C\u9884\u89C8\uFF0C\u8BF7\u4E0B\u8F7D\u67E5\u770B", 415);
24420
24579
  }
24421
- return { cwd: session.cwd, path: resolved.relative, size: info.size, content: buffer.toString("utf8") };
24580
+ return { kind: "file", cwd: session.cwd, path: resolved.relative, size: info.size, content: buffer.toString("utf8") };
24422
24581
  });
24423
24582
  }
24424
24583
 
@@ -25211,7 +25370,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
25211
25370
  import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
25212
25371
  import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
25213
25372
  import { homedir as homedir15 } from "node:os";
25214
- import { dirname as dirname11, join as join21 } from "node:path";
25373
+ import { dirname as dirname12, join as join21 } from "node:path";
25215
25374
  var webPasswordFileName = "web-password";
25216
25375
  var SCRYPT_N = 16384;
25217
25376
  var SCRYPT_R = 8;
@@ -25253,7 +25412,7 @@ function webPasswordEnabled(path5 = webPasswordPath()) {
25253
25412
  }
25254
25413
  function setWebPassword(password, path5 = webPasswordPath()) {
25255
25414
  if (password.length < minWebPasswordLength) throw new Error(`\u5BC6\u7801\u81F3\u5C11 ${minWebPasswordLength} \u4F4D\u3002`);
25256
- mkdirSync5(dirname11(path5), { recursive: true, mode: 448 });
25415
+ mkdirSync5(dirname12(path5), { recursive: true, mode: 448 });
25257
25416
  writeFileSync4(path5, `${hashWebPassword(password)}
25258
25417
  `, { mode: 384 });
25259
25418
  chmodSync2(path5, 384);
@@ -25867,7 +26026,15 @@ async function buildApp(runtime, options = {}) {
25867
26026
  }
25868
26027
  const filePath = join22(globalUploadRoot, session.id, filename);
25869
26028
  const ext = extname2(filename).toLowerCase();
25870
- const data = await readFile13(filePath);
26029
+ let data;
26030
+ try {
26031
+ data = await readFile13(filePath);
26032
+ } catch (error) {
26033
+ if (error?.code === "ENOENT") {
26034
+ throw new RuntimeError("UPLOAD_NOT_FOUND", "Upload not found", 404);
26035
+ }
26036
+ throw error;
26037
+ }
25871
26038
  reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
25872
26039
  reply.header("Cache-Control", "public, max-age=31536000, immutable");
25873
26040
  reply.header("Content-Disposition", `attachment; filename="${filename}"`);
@@ -34628,7 +34795,7 @@ async function runLarkAvatarReactionRoute(options) {
34628
34795
  import { spawn as spawn13 } from "node:child_process";
34629
34796
  import { readFileSync as readFileSync11 } from "node:fs";
34630
34797
  import { createRequire as createRequire3 } from "node:module";
34631
- import { dirname as dirname12, resolve as resolve13 } from "node:path";
34798
+ import { dirname as dirname13, resolve as resolve13 } from "node:path";
34632
34799
  function acpxPassThroughArgs(argv) {
34633
34800
  return argv[2] === "acpx" ? argv.slice(3) : void 0;
34634
34801
  }
@@ -34638,7 +34805,7 @@ function resolveAcpxLauncher(moduleUrl = import.meta.url) {
34638
34805
  const manifestPath = require2.resolve("acpx/package.json");
34639
34806
  const manifest = JSON.parse(readFileSync11(manifestPath, "utf8"));
34640
34807
  const relative2 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.acpx;
34641
- if (relative2) return { command: process.execPath, args: [resolve13(dirname12(manifestPath), relative2)] };
34808
+ if (relative2) return { command: process.execPath, args: [resolve13(dirname13(manifestPath), relative2)] };
34642
34809
  } catch {
34643
34810
  return { command: "acpx", args: [] };
34644
34811
  }
@@ -35056,14 +35223,14 @@ init_session_cli();
35056
35223
  import { spawnSync as spawnSync3 } from "node:child_process";
35057
35224
  import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
35058
35225
  import { createServer } from "node:net";
35059
- import { delimiter as delimiter2, dirname as dirname13, join as join24, resolve as resolve15 } from "node:path";
35226
+ import { delimiter as delimiter2, dirname as dirname14, join as join24, resolve as resolve15 } from "node:path";
35060
35227
  init_daemon();
35061
35228
  var SANDBOX_FILE = "sandbox.json";
35062
35229
  function findRepoRoot(start = process.cwd()) {
35063
35230
  let dir = resolve15(start);
35064
35231
  for (; ; ) {
35065
35232
  if (existsSync12(join24(dir, "apps", "server", "package.json")) && existsSync12(join24(dir, "pnpm-workspace.yaml"))) return dir;
35066
- const parent = dirname13(dir);
35233
+ const parent = dirname14(dir);
35067
35234
  if (parent === dir) throw new Error("\u627E\u4E0D\u5230 agent-dock \u6E90\u7801\u4ED3\u5E93\u3002\u8BF7\u5728\u4ED3\u5E93\u76EE\u5F55\u4E0B\u8FD0\u884C agent-dock dev\uFF0C\u6216\u7528 --repo \u6307\u5B9A\u3002");
35068
35235
  dir = parent;
35069
35236
  }