@agent-dock/cli 0.3.21 → 0.3.22

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
  }
@@ -25867,7 +25936,15 @@ async function buildApp(runtime, options = {}) {
25867
25936
  }
25868
25937
  const filePath = join22(globalUploadRoot, session.id, filename);
25869
25938
  const ext = extname2(filename).toLowerCase();
25870
- const data = await readFile13(filePath);
25939
+ let data;
25940
+ try {
25941
+ data = await readFile13(filePath);
25942
+ } catch (error) {
25943
+ if (error?.code === "ENOENT") {
25944
+ throw new RuntimeError("UPLOAD_NOT_FOUND", "Upload not found", 404);
25945
+ }
25946
+ throw error;
25947
+ }
25871
25948
  reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
25872
25949
  reply.header("Cache-Control", "public, max-age=31536000, immutable");
25873
25950
  reply.header("Content-Disposition", `attachment; filename="${filename}"`);