@agent-dock/cli 0.3.17 → 0.3.19

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
@@ -244,9 +244,385 @@ var init_native = __esm({
244
244
  }
245
245
  });
246
246
 
247
+ // ../../packages/storage/src/usage.ts
248
+ import { basename } from "node:path";
249
+ function normalizeUsageDateBound(raw, endOfDay) {
250
+ const trimmed = raw?.trim();
251
+ if (!trimmed) return void 0;
252
+ const match = DATE_ONLY_RE.exec(trimmed);
253
+ if (match) {
254
+ const year = Number(match[1]);
255
+ const month = Number(match[2]) - 1;
256
+ const day = Number(match[3]);
257
+ const date = endOfDay ? new Date(year, month, day, 23, 59, 59, 999) : new Date(year, month, day, 0, 0, 0, 0);
258
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
259
+ }
260
+ const parsed = new Date(trimmed);
261
+ return Number.isNaN(parsed.getTime()) ? void 0 : parsed.toISOString();
262
+ }
263
+ function computeTps(outputTokens, thoughtTokens, generationMs) {
264
+ if (!generationMs || !Number.isFinite(generationMs) || generationMs <= 0) return null;
265
+ const generated = Math.max(0, outputTokens) + Math.max(0, thoughtTokens);
266
+ if (generated <= 0) return null;
267
+ return Math.round(generated / (generationMs / 1e3) * 10) / 10;
268
+ }
269
+ function rowToTotals(row) {
270
+ const inputTokens = Number(row?.input_tokens ?? 0);
271
+ const outputTokens = Number(row?.output_tokens ?? 0);
272
+ const cacheReadTokens = Number(row?.cache_read_tokens ?? 0);
273
+ const cacheWriteTokens = Number(row?.cache_write_tokens ?? 0);
274
+ const thoughtTokens = Number(row?.thought_tokens ?? 0);
275
+ const totalTokens = Number(row?.total_tokens ?? 0);
276
+ const costUsd = Math.round(Number(row?.cost_usd ?? 0) * 1e6) / 1e6;
277
+ const turnCount = Number(row?.turn_count ?? 0);
278
+ const sessionCount = Number(row?.session_count ?? 0);
279
+ const totalGenerationMs = Number(row?.total_generation_ms ?? 0);
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);
282
+ return {
283
+ inputTokens,
284
+ outputTokens,
285
+ cacheReadTokens,
286
+ cacheWriteTokens,
287
+ thoughtTokens,
288
+ totalTokens,
289
+ costUsd,
290
+ turnCount,
291
+ sessionCount,
292
+ totalGenerationMs,
293
+ totalDurationMs,
294
+ avgTps
295
+ };
296
+ }
297
+ function buildFilterWhere(filter) {
298
+ const clauses = [];
299
+ const params = [];
300
+ const fromIso = normalizeUsageDateBound(filter?.from, false);
301
+ const toIso = normalizeUsageDateBound(filter?.to, true);
302
+ if (fromIso) {
303
+ clauses.push("u.created_at >= ?");
304
+ params.push(fromIso);
305
+ }
306
+ if (toIso) {
307
+ clauses.push("u.created_at <= ?");
308
+ params.push(toIso);
309
+ }
310
+ if (filter?.agentId?.trim()) {
311
+ clauses.push("u.agent_id = ?");
312
+ params.push(filter.agentId.trim());
313
+ }
314
+ if (filter?.sessionId?.trim()) {
315
+ clauses.push("u.session_id = ?");
316
+ params.push(filter.sessionId.trim());
317
+ }
318
+ if (filter?.model?.trim()) {
319
+ clauses.push("u.model = ?");
320
+ params.push(filter.model.trim());
321
+ }
322
+ if (filter?.project?.trim()) {
323
+ const project = filter.project.trim();
324
+ clauses.push("(u.cwd = ? OR EXISTS (SELECT 1 FROM projects p WHERE p.cwd = u.cwd AND p.name = ?))");
325
+ params.push(project, project);
326
+ }
327
+ const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
328
+ return { where, params, fromIso, toIso };
329
+ }
330
+ function initUsageSchema(sqlite) {
331
+ sqlite.exec(`
332
+ CREATE TABLE IF NOT EXISTS turn_usage (
333
+ id TEXT PRIMARY KEY,
334
+ session_id TEXT NOT NULL,
335
+ task_id TEXT,
336
+ request_id TEXT,
337
+ agent_id TEXT NOT NULL,
338
+ cwd TEXT NOT NULL,
339
+ model TEXT,
340
+ input_tokens INTEGER NOT NULL DEFAULT 0,
341
+ output_tokens INTEGER NOT NULL DEFAULT 0,
342
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
343
+ cache_write_tokens INTEGER NOT NULL DEFAULT 0,
344
+ thought_tokens INTEGER NOT NULL DEFAULT 0,
345
+ total_tokens INTEGER NOT NULL DEFAULT 0,
346
+ cost_usd REAL,
347
+ duration_ms INTEGER,
348
+ generation_ms INTEGER,
349
+ ttft_ms INTEGER,
350
+ source TEXT NOT NULL DEFAULT 'acp',
351
+ created_at TEXT NOT NULL
352
+ );
353
+ CREATE UNIQUE INDEX IF NOT EXISTS turn_usage_session_request ON turn_usage(session_id, request_id) WHERE request_id IS NOT NULL;
354
+ CREATE INDEX IF NOT EXISTS turn_usage_created_at ON turn_usage(created_at);
355
+ CREATE INDEX IF NOT EXISTS turn_usage_session_id ON turn_usage(session_id, created_at);
356
+ CREATE INDEX IF NOT EXISTS turn_usage_agent_id ON turn_usage(agent_id, created_at);
357
+ CREATE INDEX IF NOT EXISTS turn_usage_cwd ON turn_usage(cwd, created_at);
358
+ `);
359
+ }
360
+ function summarizePrompt(prompt) {
361
+ const line = prompt?.trim().split(/\r?\n/)[0]?.trim();
362
+ if (!line) return void 0;
363
+ return line.length > 60 ? `${line.slice(0, 60)}\u2026` : line;
364
+ }
365
+ function createUsageRepository(sqlite) {
366
+ initUsageSchema(sqlite);
367
+ const insertStmt = sqlite.prepare(`
368
+ INSERT OR IGNORE INTO turn_usage (
369
+ id, session_id, task_id, request_id, agent_id, cwd, model,
370
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, thought_tokens, total_tokens,
371
+ cost_usd, duration_ms, generation_ms, ttft_ms, source, created_at
372
+ ) VALUES (
373
+ @id, @sessionId, @taskId, @requestId, @agentId, @cwd, @model,
374
+ @inputTokens, @outputTokens, @cacheReadTokens, @cacheWriteTokens, @thoughtTokens, @totalTokens,
375
+ @costUsd, @durationMs, @generationMs, @ttftMs, @source, @createdAt
376
+ )
377
+ `);
378
+ return {
379
+ async save(record) {
380
+ const info = insertStmt.run({
381
+ id: record.id,
382
+ sessionId: record.sessionId,
383
+ taskId: record.taskId ?? null,
384
+ requestId: record.requestId ?? null,
385
+ agentId: record.agentId,
386
+ cwd: record.cwd,
387
+ model: record.model ?? null,
388
+ inputTokens: Math.max(0, Math.round(record.inputTokens)),
389
+ outputTokens: Math.max(0, Math.round(record.outputTokens)),
390
+ cacheReadTokens: Math.max(0, Math.round(record.cacheReadTokens)),
391
+ cacheWriteTokens: Math.max(0, Math.round(record.cacheWriteTokens)),
392
+ thoughtTokens: Math.max(0, Math.round(record.thoughtTokens)),
393
+ totalTokens: Math.max(0, Math.round(record.totalTokens)),
394
+ costUsd: typeof record.costUsd === "number" && Number.isFinite(record.costUsd) ? record.costUsd : null,
395
+ durationMs: typeof record.durationMs === "number" && Number.isFinite(record.durationMs) ? Math.max(0, Math.round(record.durationMs)) : null,
396
+ generationMs: typeof record.generationMs === "number" && Number.isFinite(record.generationMs) ? Math.max(0, Math.round(record.generationMs)) : null,
397
+ ttftMs: typeof record.ttftMs === "number" && Number.isFinite(record.ttftMs) ? Math.max(0, Math.round(record.ttftMs)) : null,
398
+ source: record.source || "acp",
399
+ createdAt: record.createdAt
400
+ });
401
+ return info.changes === 1;
402
+ },
403
+ async getSessionUsage(sessionId) {
404
+ const session = sqlite.prepare("SELECT agent_id, cwd, model FROM sessions WHERE id = ?").get(sessionId);
405
+ const agg = sqlite.prepare(`SELECT ${AGG_COLUMNS} FROM turn_usage u WHERE u.session_id = ?`).get(sessionId);
406
+ const rows = sqlite.prepare(`
407
+ SELECT id, task_id, model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
408
+ thought_tokens, total_tokens, cost_usd, duration_ms, generation_ms, ttft_ms, created_at
409
+ FROM turn_usage
410
+ WHERE session_id = ?
411
+ ORDER BY created_at ASC
412
+ `).all(sessionId);
413
+ const turns = rows.map((row) => ({
414
+ id: row.id,
415
+ taskId: row.task_id,
416
+ model: row.model,
417
+ inputTokens: row.input_tokens,
418
+ outputTokens: row.output_tokens,
419
+ cacheReadTokens: row.cache_read_tokens,
420
+ cacheWriteTokens: row.cache_write_tokens,
421
+ thoughtTokens: row.thought_tokens,
422
+ totalTokens: row.total_tokens,
423
+ costUsd: row.cost_usd,
424
+ durationMs: row.duration_ms,
425
+ generationMs: row.generation_ms,
426
+ ttftMs: row.ttft_ms,
427
+ tps: computeTps(row.output_tokens, row.thought_tokens, row.generation_ms),
428
+ createdAt: row.created_at
429
+ }));
430
+ let lastTps = null;
431
+ for (let i = turns.length - 1; i >= 0; i -= 1) {
432
+ if (turns[i].tps !== null) {
433
+ lastTps = turns[i].tps;
434
+ break;
435
+ }
436
+ }
437
+ const totals = { ...rowToTotals(agg), lastTps };
438
+ return {
439
+ sessionId,
440
+ ...session ? { agentId: session.agent_id, cwd: session.cwd, model: session.model } : {},
441
+ totals,
442
+ turns
443
+ };
444
+ },
445
+ async summary(filter) {
446
+ const { where, params, fromIso, toIso } = buildFilterWhere(filter);
447
+ const agg = sqlite.prepare(`SELECT ${AGG_COLUMNS} FROM turn_usage u ${where}`).get(...params);
448
+ const dailyRows = sqlite.prepare(`
449
+ SELECT date(u.created_at, 'localtime') AS day, ${AGG_COLUMNS}
450
+ FROM turn_usage u
451
+ ${where}
452
+ GROUP BY day
453
+ ORDER BY day ASC
454
+ `).all(...params);
455
+ const daily = dailyRows.map((row) => {
456
+ const totals = rowToTotals(row);
457
+ return {
458
+ date: row.day,
459
+ inputTokens: totals.inputTokens,
460
+ outputTokens: totals.outputTokens,
461
+ cacheReadTokens: totals.cacheReadTokens,
462
+ cacheWriteTokens: totals.cacheWriteTokens,
463
+ thoughtTokens: totals.thoughtTokens,
464
+ totalTokens: totals.totalTokens,
465
+ costUsd: totals.costUsd,
466
+ turnCount: totals.turnCount,
467
+ avgTps: totals.avgTps
468
+ };
469
+ });
470
+ return {
471
+ ...fromIso ? { from: fromIso } : {},
472
+ ...toIso ? { to: toIso } : {},
473
+ totals: rowToTotals(agg),
474
+ daily
475
+ };
476
+ },
477
+ async breakdown(groupBy, filter, limit = 50) {
478
+ const { where, params, fromIso, toIso } = buildFilterWhere(filter);
479
+ const safeLimit = Math.max(1, Math.min(200, Math.round(limit)));
480
+ if (groupBy === "project") {
481
+ const rows2 = sqlite.prepare(`
482
+ SELECT u.cwd AS group_key, MAX(u.created_at) AS last_active_at, ${AGG_COLUMNS}
483
+ FROM turn_usage u
484
+ ${where}
485
+ GROUP BY u.cwd
486
+ ORDER BY total_tokens DESC
487
+ LIMIT ?
488
+ `).all(...params, safeLimit);
489
+ const projectNames = /* @__PURE__ */ new Map();
490
+ for (const p of sqlite.prepare("SELECT cwd, name FROM projects").all()) {
491
+ projectNames.set(p.cwd, p.name);
492
+ }
493
+ const items2 = rows2.map((row) => ({
494
+ key: row.group_key,
495
+ label: projectNames.get(row.group_key) || basename(row.group_key) || row.group_key,
496
+ sublabel: row.group_key,
497
+ cwd: row.group_key,
498
+ lastActiveAt: row.last_active_at,
499
+ totals: rowToTotals(row)
500
+ }));
501
+ return { groupBy, ...fromIso ? { from: fromIso } : {}, ...toIso ? { to: toIso } : {}, items: items2 };
502
+ }
503
+ if (groupBy === "agent") {
504
+ const rows2 = sqlite.prepare(`
505
+ SELECT u.agent_id AS group_key, MAX(u.created_at) AS last_active_at, ${AGG_COLUMNS}
506
+ FROM turn_usage u
507
+ ${where}
508
+ GROUP BY u.agent_id
509
+ ORDER BY total_tokens DESC
510
+ LIMIT ?
511
+ `).all(...params, safeLimit);
512
+ const agentNames = /* @__PURE__ */ new Map();
513
+ for (const a of sqlite.prepare("SELECT id, json FROM agent_configs").all()) {
514
+ try {
515
+ const parsed = JSON.parse(a.json);
516
+ if (parsed.name) agentNames.set(a.id, parsed.name);
517
+ } catch {
518
+ }
519
+ }
520
+ const items2 = rows2.map((row) => ({
521
+ key: row.group_key,
522
+ label: agentNames.get(row.group_key) || row.group_key,
523
+ sublabel: row.group_key,
524
+ agentId: row.group_key,
525
+ lastActiveAt: row.last_active_at,
526
+ totals: rowToTotals(row)
527
+ }));
528
+ return { groupBy, ...fromIso ? { from: fromIso } : {}, ...toIso ? { to: toIso } : {}, items: items2 };
529
+ }
530
+ if (groupBy === "model") {
531
+ const rows2 = sqlite.prepare(`
532
+ SELECT COALESCE(NULLIF(TRIM(u.model), ''), '\u9ED8\u8BA4\u6A21\u578B') AS group_key,
533
+ MAX(u.agent_id) AS sample_agent_id,
534
+ MAX(u.created_at) AS last_active_at,
535
+ ${AGG_COLUMNS}
536
+ FROM turn_usage u
537
+ ${where}
538
+ GROUP BY group_key
539
+ ORDER BY total_tokens DESC
540
+ LIMIT ?
541
+ `).all(...params, safeLimit);
542
+ const items2 = rows2.map((row) => ({
543
+ key: row.group_key,
544
+ label: row.group_key,
545
+ sublabel: row.sample_agent_id,
546
+ model: row.group_key,
547
+ agentId: row.sample_agent_id,
548
+ lastActiveAt: row.last_active_at,
549
+ totals: rowToTotals(row)
550
+ }));
551
+ return { groupBy, ...fromIso ? { from: fromIso } : {}, ...toIso ? { to: toIso } : {}, items: items2 };
552
+ }
553
+ const rows = sqlite.prepare(`
554
+ SELECT u.session_id AS group_key,
555
+ MAX(u.agent_id) AS agent_id,
556
+ MAX(u.cwd) AS cwd,
557
+ MAX(u.model) AS model,
558
+ MAX(u.created_at) AS last_active_at,
559
+ ${AGG_COLUMNS}
560
+ FROM turn_usage u
561
+ ${where}
562
+ GROUP BY u.session_id
563
+ ORDER BY total_tokens DESC
564
+ LIMIT ?
565
+ `).all(...params, safeLimit);
566
+ const sessionIds = rows.map((r) => r.group_key);
567
+ const titles = /* @__PURE__ */ new Map();
568
+ if (sessionIds.length) {
569
+ const placeholders = sessionIds.map(() => "?").join(",");
570
+ for (const s of sqlite.prepare(`SELECT id, custom_title, agent_title FROM sessions WHERE id IN (${placeholders})`).all(...sessionIds)) {
571
+ const t = s.custom_title?.trim() || s.agent_title?.trim();
572
+ if (t) titles.set(s.id, t);
573
+ }
574
+ for (const t of sqlite.prepare(`
575
+ SELECT session_id, prompt FROM tasks
576
+ WHERE session_id IN (${placeholders})
577
+ ORDER BY created_at ASC
578
+ `).all(...sessionIds)) {
579
+ if (!titles.has(t.session_id)) {
580
+ const summary = summarizePrompt(t.prompt);
581
+ if (summary) titles.set(t.session_id, summary);
582
+ }
583
+ }
584
+ }
585
+ const items = rows.map((row) => ({
586
+ key: row.group_key,
587
+ label: titles.get(row.group_key) || row.group_key,
588
+ sublabel: `${row.agent_id} \xB7 ${basename(row.cwd) || row.cwd}`,
589
+ sessionId: row.group_key,
590
+ agentId: row.agent_id,
591
+ cwd: row.cwd,
592
+ ...row.model ? { model: row.model } : {},
593
+ lastActiveAt: row.last_active_at,
594
+ totals: rowToTotals(row)
595
+ }));
596
+ return { groupBy, ...fromIso ? { from: fromIso } : {}, ...toIso ? { to: toIso } : {}, items };
597
+ }
598
+ };
599
+ }
600
+ var DATE_ONLY_RE, AGG_COLUMNS;
601
+ var init_usage = __esm({
602
+ "../../packages/storage/src/usage.ts"() {
603
+ "use strict";
604
+ DATE_ONLY_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
605
+ AGG_COLUMNS = `
606
+ COALESCE(SUM(u.input_tokens), 0) AS input_tokens,
607
+ COALESCE(SUM(u.output_tokens), 0) AS output_tokens,
608
+ COALESCE(SUM(u.cache_read_tokens), 0) AS cache_read_tokens,
609
+ COALESCE(SUM(u.cache_write_tokens), 0) AS cache_write_tokens,
610
+ COALESCE(SUM(u.thought_tokens), 0) AS thought_tokens,
611
+ COALESCE(SUM(u.total_tokens), 0) AS total_tokens,
612
+ COALESCE(SUM(COALESCE(u.cost_usd, 0)), 0) AS cost_usd,
613
+ COUNT(*) AS turn_count,
614
+ COUNT(DISTINCT u.session_id) AS session_count,
615
+ COALESCE(SUM(CASE WHEN u.generation_ms > 0 THEN u.generation_ms ELSE 0 END), 0) AS total_generation_ms,
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
619
+ `;
620
+ }
621
+ });
622
+
247
623
  // ../../packages/storage/src/schema.ts
248
- import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
249
- var timestamps, agentConfigs, machines, projects, sessions, tasks, events, toolCalls, permissionRequests, errors, channelMappings, schedules, scheduleRuns, configs;
624
+ import { integer, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
625
+ var timestamps, agentConfigs, machines, projects, sessions, tasks, events, toolCalls, permissionRequests, errors, channelMappings, schedules, scheduleRuns, configs, turnUsage;
250
626
  var init_schema = __esm({
251
627
  "../../packages/storage/src/schema.ts"() {
252
628
  "use strict";
@@ -264,6 +640,27 @@ var init_schema = __esm({
264
640
  schedules = sqliteTable("schedules", { id: text("id").primaryKey(), name: text("name").notNull(), sessionId: text("session_id"), delivery: text("delivery").notNull(), sessionTemplate: text("session_template"), cron: text("cron"), runAt: text("run_at"), intervalMinutes: integer("interval_minutes"), timezone: text("timezone").notNull(), prompt: text("prompt").notNull(), enabled: integer("enabled", { mode: "boolean" }).notNull(), nextRunAt: text("next_run_at"), lastRunAt: text("last_run_at"), lastStatus: text("last_status"), runCount: integer("run_count").notNull(), createdBySessionId: text("created_by_session_id"), extra: text("extra"), ...timestamps });
265
641
  scheduleRuns = sqliteTable("schedule_runs", { id: text("id").primaryKey(), scheduleId: text("schedule_id").notNull(), fireAt: text("fire_at").notNull(), status: text("status").notNull(), reason: text("reason"), sessionId: text("session_id"), taskId: text("task_id"), createdAt: text("created_at").notNull() });
266
642
  configs = sqliteTable("configs", { key: text("key").primaryKey(), value: text("value").notNull() });
643
+ turnUsage = sqliteTable("turn_usage", {
644
+ id: text("id").primaryKey(),
645
+ sessionId: text("session_id").notNull(),
646
+ taskId: text("task_id"),
647
+ requestId: text("request_id"),
648
+ agentId: text("agent_id").notNull(),
649
+ cwd: text("cwd").notNull(),
650
+ model: text("model"),
651
+ inputTokens: integer("input_tokens").notNull().default(0),
652
+ outputTokens: integer("output_tokens").notNull().default(0),
653
+ cacheReadTokens: integer("cache_read_tokens").notNull().default(0),
654
+ cacheWriteTokens: integer("cache_write_tokens").notNull().default(0),
655
+ thoughtTokens: integer("thought_tokens").notNull().default(0),
656
+ totalTokens: integer("total_tokens").notNull().default(0),
657
+ costUsd: real("cost_usd"),
658
+ durationMs: integer("duration_ms"),
659
+ generationMs: integer("generation_ms"),
660
+ ttftMs: integer("ttft_ms"),
661
+ source: text("source").notNull().default("acp"),
662
+ createdAt: text("created_at").notNull()
663
+ });
267
664
  }
268
665
  });
269
666
 
@@ -271,7 +668,7 @@ var init_schema = __esm({
271
668
  import { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte } from "drizzle-orm";
272
669
  import { drizzle } from "drizzle-orm/better-sqlite3";
273
670
  import { mkdirSync as mkdirSync3 } from "node:fs";
274
- import { basename, dirname as dirname4 } from "node:path";
671
+ import { basename as basename2, dirname as dirname4 } from "node:path";
275
672
  function* parseEvents(rows) {
276
673
  for (const row of rows) {
277
674
  yield { id: row.id, sessionId: row.session_id, sequence: row.sequence, type: row.type, timestamp: row.timestamp, data: JSON.parse(row.data), raw: row.raw ?? void 0 };
@@ -626,7 +1023,7 @@ function createRepositories(filename, options = {}) {
626
1023
  async ensureLocalProject(cwd) {
627
1024
  const time2 = (/* @__PURE__ */ new Date()).toISOString();
628
1025
  db.insert(machines).values({ id: "local", name: "Local machine", metadata: "{}", createdAt: time2, updatedAt: time2 }).onConflictDoNothing().run();
629
- db.insert(projects).values({ id: `local:${cwd}`, machineId: "local", name: basename(cwd) || cwd, cwd, createdAt: time2, updatedAt: time2 }).onConflictDoUpdate({ target: projects.id, set: { cwd, updatedAt: time2 } }).run();
1026
+ db.insert(projects).values({ id: `local:${cwd}`, machineId: "local", name: basename2(cwd) || cwd, cwd, createdAt: time2, updatedAt: time2 }).onConflictDoUpdate({ target: projects.id, set: { cwd, updatedAt: time2 } }).run();
630
1027
  },
631
1028
  async saveToolCall(sessionId, data) {
632
1029
  const time2 = (/* @__PURE__ */ new Date()).toISOString();
@@ -658,7 +1055,7 @@ function createRepositories(filename, options = {}) {
658
1055
  const time2 = (/* @__PURE__ */ new Date()).toISOString();
659
1056
  const id = `local:${cwd}`;
660
1057
  db.insert(machines).values({ id: "local", name: "Local machine", metadata: "{}", createdAt: time2, updatedAt: time2 }).onConflictDoNothing().run();
661
- db.insert(projects).values({ id, machineId: "local", name: basename(cwd) || cwd, cwd, createdAt: time2, updatedAt: time2 }).onConflictDoUpdate({ target: projects.id, set: { updatedAt: time2 } }).run();
1058
+ db.insert(projects).values({ id, machineId: "local", name: basename2(cwd) || cwd, cwd, createdAt: time2, updatedAt: time2 }).onConflictDoUpdate({ target: projects.id, set: { updatedAt: time2 } }).run();
662
1059
  return await db.select().from(projects).where(eq(projects.id, id)).get();
663
1060
  },
664
1061
  async save(project) {
@@ -668,6 +1065,7 @@ function createRepositories(filename, options = {}) {
668
1065
  db.update(projects).set({ pinnedAt, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(projects.id, id)).run();
669
1066
  }
670
1067
  },
1068
+ usage: createUsageRepository(sqlite),
671
1069
  close() {
672
1070
  sqlite.close();
673
1071
  }
@@ -677,9 +1075,11 @@ var iterateEvents;
677
1075
  var init_src = __esm({
678
1076
  "../../packages/storage/src/index.ts"() {
679
1077
  init_native();
1078
+ init_usage();
680
1079
  init_schema();
681
1080
  init_native();
682
1081
  init_schema();
1082
+ init_usage();
683
1083
  iterateEvents = (sqlite, sessionId, afterSequence) => sqlite.prepare("SELECT id, session_id, sequence, type, timestamp, data, raw FROM events WHERE session_id = ? AND sequence > ? ORDER BY sequence").iterate(sessionId, afterSequence);
684
1084
  }
685
1085
  });
@@ -2132,8 +2532,8 @@ var init_service = __esm({
2132
2532
  return { name, ...avatarUrl ? { avatarUrl } : {} };
2133
2533
  }
2134
2534
  async getUserName(openId) {
2135
- const cached4 = this.userNameCache.get(openId);
2136
- if (cached4 && cached4.expiresAt > Date.now()) return cached4.name;
2535
+ const cached5 = this.userNameCache.get(openId);
2536
+ if (cached5 && cached5.expiresAt > Date.now()) return cached5.name;
2137
2537
  const payload = await this.request(`/open-apis/contact/v3/users/${encodeURIComponent(required(openId, "openId"))}?user_id_type=open_id`, { method: "GET", timeoutMs: 3e3 });
2138
2538
  const name = String(payload.data?.user?.name ?? "").trim();
2139
2539
  const ttl = name ? userNameCacheTtlMs : emptyUserNameCacheTtlMs;
@@ -2963,16 +3363,16 @@ var init_agent_tools = __esm({
2963
3363
  injectedPrompts = /* @__PURE__ */ new Map();
2964
3364
  pollIntervalMs;
2965
3365
  clientFor(config) {
2966
- const cached4 = this.clients.get(config.appId);
2967
- if (cached4?.secret === config.appSecret) return cached4.client;
3366
+ const cached5 = this.clients.get(config.appId);
3367
+ if (cached5?.secret === config.appSecret) return cached5.client;
2968
3368
  const client2 = this.options.clientFactory?.(config) ?? createLarkCardService(this.options.env ?? process.env, this.options.fetcher ?? globalThis.fetch, { appId: config.appId, appSecret: config.appSecret });
2969
3369
  this.clients.set(config.appId, { secret: config.appSecret, client: client2 });
2970
3370
  this.identities.delete(config.appId);
2971
3371
  return client2;
2972
3372
  }
2973
3373
  identityFor(config) {
2974
- const cached4 = this.identities.get(config.appId);
2975
- if (cached4?.secret === config.appSecret) return cached4.info;
3374
+ const cached5 = this.identities.get(config.appId);
3375
+ if (cached5?.secret === config.appSecret) return cached5.info;
2976
3376
  const info = this.clientFor(config).getBotInfo();
2977
3377
  this.identities.set(config.appId, { secret: config.appSecret, info });
2978
3378
  void info.catch(() => {
@@ -3606,7 +4006,7 @@ __export(listener_exports, {
3606
4006
  import { createHash as createHash3 } from "node:crypto";
3607
4007
  import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
3608
4008
  import { tmpdir } from "node:os";
3609
- import { basename as basename3, join as join9 } from "node:path";
4009
+ import { basename as basename4, join as join9 } from "node:path";
3610
4010
  function parseLarkReactionEvent(raw) {
3611
4011
  if (!raw || typeof raw !== "object") return void 0;
3612
4012
  const event = raw;
@@ -3968,7 +4368,7 @@ var init_listener = __esm({
3968
4368
  };
3969
4369
  safeResourceName = (resource, contentType) => {
3970
4370
  const hash2 = createHash3("sha256").update(`${resource.type}:${resource.key}`).digest("hex").slice(0, 12);
3971
- const supplied = resource.fileName ? basename3(resource.fileName).replace(/[^\p{L}\p{N}._ -]/gu, "_").slice(0, 120) : "";
4371
+ const supplied = resource.fileName ? basename4(resource.fileName).replace(/[^\p{L}\p{N}._ -]/gu, "_").slice(0, 120) : "";
3972
4372
  return supplied ? `${hash2}-${supplied}` : `${resource.type}-${hash2}${resourceExtensions[contentType ?? ""] ?? ""}`;
3973
4373
  };
3974
4374
  resourceFailureGuidance = (error) => {
@@ -6036,13 +6436,13 @@ __export(session_cli_exports, {
6036
6436
  streamSessionShow: () => streamSessionShow
6037
6437
  });
6038
6438
  import { existsSync as existsSync10 } from "node:fs";
6039
- import { join as join21, resolve as resolve12 } from "node:path";
6439
+ import { join as join22, resolve as resolve12 } from "node:path";
6040
6440
  function resolveDatabasePath(explicit, cwd = process.cwd()) {
6041
6441
  if (explicit) return resolve12(cwd, explicit);
6042
6442
  if (process.env.AGENTDOCK_DATABASE_URL) return resolve12(cwd, process.env.AGENTDOCK_DATABASE_URL);
6043
6443
  const daemonDir = resolveDaemonDir(cwd);
6044
6444
  const recorded = readDaemonStatus(daemonDir)?.database;
6045
- return recorded ? resolve12(daemonDir, recorded) : join21(daemonDir, "..", "agentdock.db");
6445
+ return recorded ? resolve12(daemonDir, recorded) : join22(daemonDir, "..", "agentdock.db");
6046
6446
  }
6047
6447
  function sessionPeerIds(sessions2, sourceId2) {
6048
6448
  const source2 = sessions2.find((session) => session.id === sourceId2);
@@ -6292,7 +6692,7 @@ var AutostartService = class {
6292
6692
  // src/cli.ts
6293
6693
  init_src();
6294
6694
  import { existsSync as existsSync13, readFileSync as readFileSync16 } from "node:fs";
6295
- import { spawn as spawn13 } from "node:child_process";
6695
+ import { spawn as spawn14 } from "node:child_process";
6296
6696
  import { loadEnvFile } from "node:process";
6297
6697
  import { fileURLToPath as fileURLToPath6 } from "node:url";
6298
6698
 
@@ -6517,6 +6917,17 @@ Changes take effect immediately; no restart needed.`);
6517
6917
  addProcessCommands(program);
6518
6918
  const daemon3 = program.command("daemon").description("Run the AgentDock server in the background and manage it");
6519
6919
  addProcessCommands(daemon3);
6920
+ const usage = program.command("usage").description("\u67E5\u8BE2\u771F\u5B9E\u7684 Token \u6D88\u8017\u3001TPS \u4E0E\u591A\u7EF4\u7EDF\u8BA1\u770B\u677F\uFF08\u4F9B\u4EBA\u4E0E Agent \u8C03\u7528\uFF09");
6921
+ const addUsageFilterOptions = (cmd) => cmd.option("--from <date>", "\u8D77\u59CB\u65F6\u95F4\uFF08\u652F\u6301 today / 7d / 30d / YYYY-MM-DD / ISO \u65F6\u95F4\uFF09").option("--to <date>", "\u7ED3\u675F\u65F6\u95F4\uFF08\u652F\u6301 YYYY-MM-DD / ISO \u65F6\u95F4\uFF09").option("--agent <id>", "\u6309 Agent ID \u7B5B\u9009\uFF08\u5982 claude / codex / antigravity\uFF09").option("--project <pathOrName>", "\u6309\u9879\u76EE\u76EE\u5F55\u6216\u9879\u76EE\u540D\u7B5B\u9009").option("--session <id>", "\u6309\u4F1A\u8BDD ID \u7B5B\u9009").option("--model <name>", "\u6309\u6A21\u578B\u540D\u7B5B\u9009").option("--json", "\u8F93\u51FA JSON");
6922
+ addUsageFilterOptions(usage.command("summary").description("\u67E5\u8BE2\u603B\u6D88\u8017\u3001\u5E73\u5747 TPS \u4E0E\u6309\u65E5\u8D8B\u52BF")).action(async (options) => {
6923
+ await handlers.usageSummary?.(options);
6924
+ });
6925
+ addUsageFilterOptions(usage.command("breakdown").description("\u6309\u9879\u76EE / Agent / \u4F1A\u8BDD / \u6A21\u578B\u7EF4\u5EA6\u5206\u7EC4\u7EDF\u8BA1\u6D88\u8017")).option("--by <dimension>", "\u5206\u7EC4\u7EF4\u5EA6\uFF1Aproject | agent | session | model\uFF08\u9ED8\u8BA4 project\uFF09").option("--limit <n>", "\u6700\u591A\u8FD4\u56DE\u6761\u6570\uFF08\u9ED8\u8BA4 50\uFF09").action(async (options) => {
6926
+ await handlers.usageBreakdown?.(options);
6927
+ });
6928
+ usage.command("session [session-id]").description("\u67E5\u8BE2\u6307\u5B9A\u4F1A\u8BDD\uFF08\u9ED8\u8BA4\u5F53\u524D $agentdock_session_id\uFF09\u7684\u7D2F\u8BA1\u6D88\u8017\u3001TPS \u4E0E\u9010\u8F6E\u660E\u7EC6").option("--json", "\u8F93\u51FA JSON").action(async (sessionId, options) => {
6929
+ await handlers.usageSession?.(sessionId, options);
6930
+ });
6520
6931
  return program.addHelpText("after", `
6521
6932
  Examples:
6522
6933
  $ agent-dock
@@ -6732,7 +7143,7 @@ var KeepAwakeService = class {
6732
7143
  // ../../packages/agent-runtime/src/index.ts
6733
7144
  import { EventEmitter } from "node:events";
6734
7145
  import { createHash as createHash2 } from "node:crypto";
6735
- import { basename as basename2 } from "node:path";
7146
+ import { basename as basename3 } from "node:path";
6736
7147
 
6737
7148
  // ../../packages/agent-runtime/src/project-path.ts
6738
7149
  init_src2();
@@ -6755,9 +7166,9 @@ async function resolveProjectPath(raw, options = {}) {
6755
7166
  if (!isAbsolute(expanded)) {
6756
7167
  throw new RuntimeError("PROJECT_PATH_NOT_ABSOLUTE", "\u8BF7\u586B\u5199\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u4F8B\u5982 /Users/you/code \u6216 C:\\code\uFF1B\u53EF\u7528 ~ \u8868\u793A\u4E3B\u76EE\u5F55\uFF09", 400);
6757
7168
  }
6758
- let real;
7169
+ let real2;
6759
7170
  try {
6760
- real = await fs5.realpath(resolve2(expanded));
7171
+ real2 = await fs5.realpath(resolve2(expanded));
6761
7172
  } catch (error) {
6762
7173
  const code = errorCode2(error);
6763
7174
  if (code === "ENOENT" || code === "ENOTDIR") {
@@ -6767,7 +7178,7 @@ async function resolveProjectPath(raw, options = {}) {
6767
7178
  }
6768
7179
  let info;
6769
7180
  try {
6770
- info = await fs5.stat(real);
7181
+ info = await fs5.stat(real2);
6771
7182
  } catch (error) {
6772
7183
  const code = errorCode2(error);
6773
7184
  if (code === "ENOENT" || code === "ENOTDIR") {
@@ -6779,16 +7190,16 @@ async function resolveProjectPath(raw, options = {}) {
6779
7190
  throw new RuntimeError("PROJECT_PATH_NOT_DIRECTORY", `\u8BE5\u8DEF\u5F84\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${text3}`, 400);
6780
7191
  }
6781
7192
  try {
6782
- await fs5.access(real, constants.R_OK);
7193
+ await fs5.access(real2, constants.R_OK);
6783
7194
  } catch {
6784
7195
  throw new RuntimeError("PROJECT_PATH_NOT_READABLE", `\u6CA1\u6709\u8BFB\u53D6\u6743\u9650\uFF1A${text3}`, 400);
6785
7196
  }
6786
7197
  try {
6787
- await fs5.access(real, constants.W_OK);
7198
+ await fs5.access(real2, constants.W_OK);
6788
7199
  } catch {
6789
7200
  throw new RuntimeError("PROJECT_PATH_NOT_WRITABLE", `\u6CA1\u6709\u5199\u5165\u6743\u9650\uFF1A${text3}`, 400);
6790
7201
  }
6791
- return real;
7202
+ return real2;
6792
7203
  }
6793
7204
 
6794
7205
  // ../../packages/agent-runtime/src/index.ts
@@ -8979,15 +9390,15 @@ async function readLinuxProcessTable(timeoutMs, requiredPids, pid) {
8979
9390
  const clockTicksPerSecond = linuxClockTicks(raw);
8980
9391
  const table = /* @__PURE__ */ new Map();
8981
9392
  for (const value of raw.processStats) {
8982
- const stat6 = parseLinuxStat(value);
8983
- if (stat6 && (pid === void 0 || stat6.pid === pid)) table.set(stat6.pid, {
8984
- pid: stat6.pid,
8985
- parentPid: stat6.parentPid,
8986
- groupPid: stat6.groupPid,
9393
+ const stat7 = parseLinuxStat(value);
9394
+ if (stat7 && (pid === void 0 || stat7.pid === pid)) table.set(stat7.pid, {
9395
+ pid: stat7.pid,
9396
+ parentPid: stat7.parentPid,
9397
+ groupPid: stat7.groupPid,
8987
9398
  birth: {
8988
9399
  kind: "linux-proc",
8989
9400
  ...scope,
8990
- startTicks: stat6.startTicks
9401
+ startTicks: stat7.startTicks
8991
9402
  },
8992
9403
  clockTicksPerSecond
8993
9404
  });
@@ -10075,8 +10486,8 @@ function buildAuthEnvKey(methodId) {
10075
10486
  }
10076
10487
  var authEnvKeyCache = /* @__PURE__ */ new Map();
10077
10488
  function authEnvKey(methodId) {
10078
- const cached4 = authEnvKeyCache.get(methodId);
10079
- if (cached4 !== void 0) return cached4;
10489
+ const cached5 = authEnvKeyCache.get(methodId);
10490
+ if (cached5 !== void 0) return cached5;
10080
10491
  const key = buildAuthEnvKey(methodId);
10081
10492
  authEnvKeyCache.set(methodId, key);
10082
10493
  return key;
@@ -17402,10 +17813,77 @@ var AcpxAdapter = class {
17402
17813
  this.reportedTitle = title;
17403
17814
  this.options.onEvent({ type: "session_title", data: { title } });
17404
17815
  }
17816
+ async reportTurnUsage(prevKeys, prevCostUsd, fallbackRequestId, timing) {
17817
+ let record;
17818
+ try {
17819
+ record = await this.sessionStore.load(this.sessionKey);
17820
+ } catch {
17821
+ return;
17822
+ }
17823
+ const reqMap = record?.request_token_usage;
17824
+ if (!reqMap || typeof reqMap !== "object") return;
17825
+ const newKeys = Object.keys(reqMap).filter((key) => !prevKeys.has(key));
17826
+ if (!newKeys.length) return;
17827
+ let inputTokens = 0;
17828
+ let outputTokens = 0;
17829
+ let cacheReadTokens = 0;
17830
+ let cacheWriteTokens = 0;
17831
+ let thoughtTokens = 0;
17832
+ let totalTokens = 0;
17833
+ for (const key of newKeys) {
17834
+ const entry = reqMap[key];
17835
+ if (!entry || typeof entry !== "object") continue;
17836
+ const inp = Number(entry.input_tokens ?? 0);
17837
+ const out = Number(entry.output_tokens ?? 0);
17838
+ const cRead = Number(entry.cache_read_input_tokens ?? 0);
17839
+ const cWrite = Number(entry.cache_creation_input_tokens ?? 0);
17840
+ const thought = Number(entry.thought_tokens ?? 0);
17841
+ const total = Number(entry.total_tokens ?? inp + out + cRead + cWrite + thought);
17842
+ if (Number.isFinite(inp) && inp > 0) inputTokens += inp;
17843
+ if (Number.isFinite(out) && out > 0) outputTokens += out;
17844
+ if (Number.isFinite(cRead) && cRead > 0) cacheReadTokens += cRead;
17845
+ if (Number.isFinite(cWrite) && cWrite > 0) cacheWriteTokens += cWrite;
17846
+ if (Number.isFinite(thought) && thought > 0) thoughtTokens += thought;
17847
+ if (Number.isFinite(total) && total > 0) totalTokens += total;
17848
+ }
17849
+ if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0) return;
17850
+ if (totalTokens <= 0) totalTokens = inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens;
17851
+ const afterCost = typeof record?.cumulative_cost?.amount === "number" && Number.isFinite(record.cumulative_cost.amount) ? record.cumulative_cost.amount : void 0;
17852
+ const costUsd = afterCost !== void 0 && afterCost > prevCostUsd ? Math.round((afterCost - prevCostUsd) * 1e6) / 1e6 : void 0;
17853
+ this.options.onEvent({
17854
+ type: "turn_usage",
17855
+ data: {
17856
+ requestId: newKeys[newKeys.length - 1] ?? fallbackRequestId,
17857
+ inputTokens,
17858
+ outputTokens,
17859
+ cacheReadTokens,
17860
+ cacheWriteTokens,
17861
+ thoughtTokens,
17862
+ totalTokens,
17863
+ ...costUsd !== void 0 ? { costUsd } : {},
17864
+ durationMs: timing.durationMs,
17865
+ ...timing.generationMs !== void 0 ? { generationMs: timing.generationMs } : {},
17866
+ ...timing.ttftMs !== void 0 ? { ttftMs: timing.ttftMs } : {}
17867
+ }
17868
+ });
17869
+ }
17405
17870
  async sendTurn(prompt) {
17406
17871
  if (!this.handle) await this.start();
17407
17872
  await this.applyCodexPermissionMode();
17408
17873
  const requestId = `req-${crypto.randomUUID()}`;
17874
+ const beforeRecord = await this.sessionStore.load(this.sessionKey).catch(() => void 0);
17875
+ const prevUsageKeys = new Set(Object.keys(beforeRecord?.request_token_usage ?? {}));
17876
+ const prevCostUsd = typeof beforeRecord?.cumulative_cost?.amount === "number" && Number.isFinite(beforeRecord.cumulative_cost.amount) ? beforeRecord.cumulative_cost.amount : 0;
17877
+ const turnStartedAt = Date.now();
17878
+ let firstOutputAt;
17879
+ let activeOutputMs = 0;
17880
+ let outputSegmentStart;
17881
+ const closeOutputSegment = (at) => {
17882
+ if (outputSegmentStart !== void 0) {
17883
+ activeOutputMs += Math.max(0, at - outputSegmentStart);
17884
+ outputSegmentStart = void 0;
17885
+ }
17886
+ };
17409
17887
  const { idle: idleTimeoutMs, toolCall: toolCallTimeoutMs } = resolveTurnTimeouts(this.agent.timeout);
17410
17888
  const turn = this.runtime.startTurn({ handle: this.handle, text: prompt, mode: "prompt", requestId, timeoutMs: 0 });
17411
17889
  this.turn = turn;
@@ -17433,19 +17911,32 @@ var AcpxAdapter = class {
17433
17911
  if (next.done) break;
17434
17912
  const normalized2 = normalizeAcpxEvent(next.value);
17435
17913
  if (normalized2) {
17914
+ const eventAt = Date.now();
17436
17915
  const toolCallId = typeof normalized2.data?.id === "string" ? normalized2.data.id : void 0;
17437
17916
  if (normalized2.type === "tool_call") {
17917
+ if (activeToolCallIds.size === 0) closeOutputSegment(eventAt);
17438
17918
  if (toolCallId) activeToolCallIds.add(toolCallId);
17439
17919
  } else if (normalized2.type === "tool_result") {
17440
17920
  if (toolCallId) activeToolCallIds.delete(toolCallId);
17441
17921
  else activeToolCallIds.clear();
17922
+ } else if ((normalized2.type === "text" || normalized2.type === "thinking") && activeToolCallIds.size === 0) {
17923
+ if (firstOutputAt === void 0) firstOutputAt = eventAt;
17924
+ if (outputSegmentStart === void 0) outputSegmentStart = eventAt;
17442
17925
  }
17443
17926
  this.options.onEvent(normalized2);
17444
17927
  }
17445
17928
  }
17929
+ const streamEndedAt = Date.now();
17930
+ closeOutputSegment(streamEndedAt);
17446
17931
  const result = await turn.result;
17447
17932
  if (result.status === "failed") throw new Error(result.error.message);
17933
+ const finishedAt = Date.now();
17448
17934
  await this.reportAgentTitle();
17935
+ await this.reportTurnUsage(prevUsageKeys, prevCostUsd, requestId, {
17936
+ durationMs: Math.max(1, finishedAt - turnStartedAt),
17937
+ ...activeOutputMs > 0 ? { generationMs: activeOutputMs } : {},
17938
+ ...firstOutputAt !== void 0 ? { ttftMs: Math.max(0, firstOutputAt - turnStartedAt) } : {}
17939
+ });
17449
17940
  this.options.onEvent({ type: "completed", data: { stopReason: result.stopReason ?? result.status } });
17450
17941
  } finally {
17451
17942
  if (this.turn === turn) this.turn = void 0;
@@ -17525,10 +18016,18 @@ var AcpxAdapter = class {
17525
18016
 
17526
18017
  // ../../packages/transports/src/index.ts
17527
18018
  import { spawn as spawn5, spawnSync } from "node:child_process";
18019
+ import { accessSync as accessSync2, constants as constants3, statSync as statSync4 } from "node:fs";
17528
18020
  import readline2 from "node:readline";
17529
18021
  import * as pty from "node-pty";
17530
18022
  function commandExists(command) {
17531
- if (command.includes("/") || command.includes("\\")) return spawnSync("test", ["-x", command]).status === 0;
18023
+ if (command.includes("/") || command.includes("\\")) {
18024
+ try {
18025
+ accessSync2(command, constants3.X_OK);
18026
+ return statSync4(command).isFile();
18027
+ } catch {
18028
+ return false;
18029
+ }
18030
+ }
17532
18031
  return spawnSync(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" }).status === 0;
17533
18032
  }
17534
18033
  function probeAgent(agent, acpxCommand = "acpx") {
@@ -18046,6 +18545,18 @@ var AgentDockRuntime = class _AgentDockRuntime {
18046
18545
  listProjects() {
18047
18546
  return this.repos.projects.list();
18048
18547
  }
18548
+ saveTurnUsage(record) {
18549
+ return this.repos.usage.save(record);
18550
+ }
18551
+ getSessionUsage(sessionId) {
18552
+ return this.repos.usage.getSessionUsage(sessionId);
18553
+ }
18554
+ getUsageSummary(filter) {
18555
+ return this.repos.usage.summary(filter);
18556
+ }
18557
+ getUsageBreakdown(groupBy, filter, limit) {
18558
+ return this.repos.usage.breakdown(groupBy, filter, limit);
18559
+ }
18049
18560
  /**
18050
18561
  * 登记用户导入的项目。路径统一 realpath(`~` 展开、相对路径拒绝、macOS /private 别名归一),
18051
18562
  * 已存在则原样返回并标记 created=false,前端可据此提示「已存在」而不是造出第二条。
@@ -18058,7 +18569,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
18058
18569
  const project = {
18059
18570
  id: `local:${cwd}`,
18060
18571
  machineId: "local",
18061
- name: basename2(cwd) || cwd,
18572
+ name: basename3(cwd) || cwd,
18062
18573
  cwd,
18063
18574
  pinnedAt: null,
18064
18575
  createdAt: time2,
@@ -18335,6 +18846,57 @@ var AgentDockRuntime = class _AgentDockRuntime {
18335
18846
  await this.setAgentTitle(session, typeof event.data?.title === "string" ? event.data.title : void 0);
18336
18847
  return;
18337
18848
  }
18849
+ if (event.type === "turn_usage") {
18850
+ const d = event.data ?? {};
18851
+ const inputTokens = Number(d.inputTokens ?? 0);
18852
+ const outputTokens = Number(d.outputTokens ?? 0);
18853
+ const cacheReadTokens = Number(d.cacheReadTokens ?? 0);
18854
+ const cacheWriteTokens = Number(d.cacheWriteTokens ?? 0);
18855
+ const thoughtTokens = Number(d.thoughtTokens ?? 0);
18856
+ const totalTokens = Number(d.totalTokens ?? inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens);
18857
+ if (totalTokens > 0 || inputTokens > 0 || outputTokens > 0) {
18858
+ const taskId = this.activeTasks.get(session.id)?.id ?? null;
18859
+ const generationMs = typeof d.generationMs === "number" && Number.isFinite(d.generationMs) && d.generationMs > 0 ? Math.round(d.generationMs) : null;
18860
+ const durationMs = typeof d.durationMs === "number" && Number.isFinite(d.durationMs) && d.durationMs > 0 ? Math.round(d.durationMs) : null;
18861
+ const ttftMs = typeof d.ttftMs === "number" && Number.isFinite(d.ttftMs) && d.ttftMs >= 0 ? Math.round(d.ttftMs) : null;
18862
+ const costUsd = typeof d.costUsd === "number" && Number.isFinite(d.costUsd) && d.costUsd >= 0 ? d.costUsd : null;
18863
+ await this.repos.usage.save({
18864
+ id: makeId("tu"),
18865
+ sessionId: session.id,
18866
+ taskId,
18867
+ requestId: typeof d.requestId === "string" && d.requestId.trim() ? d.requestId.trim() : null,
18868
+ agentId: session.agentId,
18869
+ cwd: session.cwd,
18870
+ model: session.model ?? null,
18871
+ inputTokens,
18872
+ outputTokens,
18873
+ cacheReadTokens,
18874
+ cacheWriteTokens,
18875
+ thoughtTokens,
18876
+ totalTokens,
18877
+ costUsd,
18878
+ durationMs,
18879
+ generationMs,
18880
+ ttftMs,
18881
+ source: "acp",
18882
+ createdAt: now()
18883
+ });
18884
+ await this.emit(session.id, "status", {
18885
+ state: "turn_usage",
18886
+ inputTokens,
18887
+ outputTokens,
18888
+ cacheReadTokens,
18889
+ cacheWriteTokens,
18890
+ thoughtTokens,
18891
+ totalTokens,
18892
+ ...costUsd !== null ? { costUsd } : {},
18893
+ ...durationMs !== null ? { durationMs } : {},
18894
+ ...generationMs !== null ? { generationMs } : {},
18895
+ ...ttftMs !== null ? { ttftMs } : {}
18896
+ });
18897
+ }
18898
+ return;
18899
+ }
18338
18900
  let data = event.data;
18339
18901
  if (event.type === "tool_call" || event.type === "tool_result") {
18340
18902
  const completed = data.status === "completed" || data.status === "failed";
@@ -19104,7 +19666,7 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
19104
19666
  init_src2();
19105
19667
  init_daemon();
19106
19668
  import { spawn as spawn7 } from "node:child_process";
19107
- import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync3 } from "node:fs";
19669
+ import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync5, writeFileSync as writeFileSync3 } from "node:fs";
19108
19670
  import { homedir as homedir5 } from "node:os";
19109
19671
  import { dirname as dirname7, join as join8 } from "node:path";
19110
19672
 
@@ -19305,7 +19867,7 @@ var SelfUpdateService = class {
19305
19867
  */
19306
19868
  lockHeld() {
19307
19869
  try {
19308
- if (this.now() - statSync4(this.lockFile).mtimeMs > UPDATE_LOCK_MAX_AGE_MS) return false;
19870
+ if (this.now() - statSync5(this.lockFile).mtimeMs > UPDATE_LOCK_MAX_AGE_MS) return false;
19309
19871
  return pidAlive(Number(readFileSync5(this.lockFile, "utf8").trim()));
19310
19872
  } catch {
19311
19873
  return false;
@@ -19391,9 +19953,9 @@ function registerSelfUpdateRoutes(app, service) {
19391
19953
  init_src2();
19392
19954
  import Fastify from "fastify";
19393
19955
  import cors from "@fastify/cors";
19394
- import { readFile as readFile12, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
19956
+ import { readFile as readFile13, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
19395
19957
  import { Readable as Readable3 } from "node:stream";
19396
- import { extname as extname2, join as join20, resolve as resolve10, sep as sep3 } from "node:path";
19958
+ import { extname as extname2, join as join21, resolve as resolve10, sep as sep3 } from "node:path";
19397
19959
  import { homedir as homedir15 } from "node:os";
19398
19960
  import { randomBytes as randomBytes4 } from "node:crypto";
19399
19961
 
@@ -19409,7 +19971,7 @@ init_listener();
19409
19971
  // src/lark/security-hooks.ts
19410
19972
  init_service();
19411
19973
  import { access as access2, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
19412
- import { constants as constants3 } from "node:fs";
19974
+ import { constants as constants4 } from "node:fs";
19413
19975
  import { dirname as dirname8, join as join10 } from "node:path";
19414
19976
  var guardVersion = "agentdock-high-risk-guard-v2";
19415
19977
  var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
@@ -19533,7 +20095,7 @@ async function larkHookStatus(agentId, workspace) {
19533
20095
  const { hooksPath } = paths(adapter, workspace);
19534
20096
  let writable = true;
19535
20097
  try {
19536
- await access2(workspace, constants3.W_OK);
20098
+ await access2(workspace, constants4.W_OK);
19537
20099
  } catch {
19538
20100
  writable = false;
19539
20101
  }
@@ -21401,8 +21963,8 @@ function agentModelsCacheKey(agent, model) {
21401
21963
  var cache = /* @__PURE__ */ new Map();
21402
21964
  async function discoverAgentModels(agent, model, forceRefresh = false) {
21403
21965
  const cacheKey = agentModelsCacheKey(agent, model);
21404
- const cached4 = cache.get(cacheKey);
21405
- if (!forceRefresh && cached4 && cached4.expiresAt > Date.now()) return cached4.value;
21966
+ const cached5 = cache.get(cacheKey);
21967
+ if (!forceRefresh && cached5 && cached5.expiresAt > Date.now()) return cached5.value;
21406
21968
  let value;
21407
21969
  let warning;
21408
21970
  try {
@@ -21940,15 +22502,317 @@ async function getCursorUsage(refresh = false) {
21940
22502
  return inFlight3;
21941
22503
  }
21942
22504
 
22505
+ // src/antigravity-usage.ts
22506
+ import { spawn as spawn10 } from "node:child_process";
22507
+ import { userInfo as userInfo2 } from "node:os";
22508
+ var SOURCE = "Antigravity CLI";
22509
+ var AUTH_ERROR_RE = /unauthenticated|authentication required|authentication failed|not logged in|please log in|sign in|\b401\b/i;
22510
+ function resolveRealHome() {
22511
+ try {
22512
+ const dir = userInfo2().homedir;
22513
+ return dir?.trim() || void 0;
22514
+ } catch {
22515
+ return void 0;
22516
+ }
22517
+ }
22518
+ function antigravitySpawnEnv(base = process.env, realHome = resolveRealHome()) {
22519
+ const env = {
22520
+ ...base,
22521
+ BROWSER: "true",
22522
+ NO_BROWSER: "1"
22523
+ };
22524
+ if (realHome) {
22525
+ env.HOME = realHome;
22526
+ if (process.platform === "win32") env.USERPROFILE = realHome;
22527
+ }
22528
+ return env;
22529
+ }
22530
+ function groupLabel(name) {
22531
+ const trimmed = name?.trim();
22532
+ if (!trimmed) return "";
22533
+ if (/^gemini\b/i.test(trimmed)) return "Gemini";
22534
+ if (/claude/i.test(trimmed) && /gpt/i.test(trimmed)) return "Claude / GPT";
22535
+ return trimmed;
22536
+ }
22537
+ function windowInfo(bucket) {
22538
+ const key = bucket.window?.trim().toLowerCase();
22539
+ if (key === "5h" || key === "five_hour") return { label: "5 \u5C0F\u65F6", rank: 1 };
22540
+ if (key === "weekly" || key === "7d" || key === "seven_day") return { label: "7 \u5929", rank: 2 };
22541
+ const fallback = bucket.name?.trim() || bucket.window?.trim() || bucket.id?.trim() || "\u989D\u5EA6";
22542
+ return { label: fallback, rank: 3 };
22543
+ }
22544
+ function bucketUsedPercent(bucket) {
22545
+ if (typeof bucket.remaining_fraction === "number" && Number.isFinite(bucket.remaining_fraction) && bucket.remaining_fraction >= 0) {
22546
+ const remaining2 = Math.min(bucket.remaining_fraction, 1);
22547
+ return Math.round((1 - remaining2) * 1e4) / 100;
22548
+ }
22549
+ if (typeof bucket.used_fraction === "number" && Number.isFinite(bucket.used_fraction) && bucket.used_fraction >= 0) {
22550
+ return Math.round(Math.min(bucket.used_fraction, 1) * 1e4) / 100;
22551
+ }
22552
+ const used = percent(bucket.used_percent);
22553
+ if (used !== void 0) return Math.round(used * 100) / 100;
22554
+ const remaining = percent(bucket.remaining_percent);
22555
+ if (remaining !== void 0) return Math.round((100 - remaining) * 100) / 100;
22556
+ return void 0;
22557
+ }
22558
+ function parseJsonOutput(stdout) {
22559
+ const trimmed = stdout.trim();
22560
+ if (!trimmed) return void 0;
22561
+ try {
22562
+ return JSON.parse(trimmed);
22563
+ } catch {
22564
+ const lines = trimmed.split(/\r?\n/);
22565
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
22566
+ const line = lines[i].trim();
22567
+ if (!line.startsWith("{")) continue;
22568
+ try {
22569
+ return JSON.parse(line);
22570
+ } catch {
22571
+ continue;
22572
+ }
22573
+ }
22574
+ return void 0;
22575
+ }
22576
+ }
22577
+ function spawnAntigravity(command, args, options) {
22578
+ return new Promise((resolve17, reject2) => {
22579
+ let settled = false;
22580
+ let stdout = "";
22581
+ let stderr = "";
22582
+ let child;
22583
+ const finish = (err) => {
22584
+ if (settled) return;
22585
+ settled = true;
22586
+ clearTimeout(timer);
22587
+ if (err) {
22588
+ err.stdout = stdout;
22589
+ err.stderr = stderr;
22590
+ reject2(err);
22591
+ } else {
22592
+ resolve17({ stdout, stderr });
22593
+ }
22594
+ };
22595
+ const timer = setTimeout(() => {
22596
+ child?.kill();
22597
+ const err = new Error("Antigravity CLI timed out");
22598
+ err.killed = true;
22599
+ err.code = "ETIMEDOUT";
22600
+ finish(err);
22601
+ }, options.timeout);
22602
+ timer.unref();
22603
+ try {
22604
+ child = spawn10(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: options.windowsHide, env: options.env });
22605
+ } catch (error) {
22606
+ finish(error);
22607
+ return;
22608
+ }
22609
+ child.on("error", (error) => finish(error));
22610
+ child.stdout?.on("data", (chunk) => {
22611
+ stdout += chunk.toString("utf8");
22612
+ if (stdout.length > options.maxBuffer) {
22613
+ child.kill();
22614
+ finish(new Error("Antigravity CLI output exceeded buffer limit"));
22615
+ }
22616
+ });
22617
+ child.stderr?.on("data", (chunk) => {
22618
+ stderr += chunk.toString("utf8");
22619
+ if (AUTH_ERROR_RE.test(stderr)) {
22620
+ child.kill();
22621
+ finish(new Error("Authentication required"));
22622
+ return;
22623
+ }
22624
+ if (stderr.length > options.maxBuffer) stderr = stderr.slice(-options.maxBuffer);
22625
+ });
22626
+ child.on("close", (code) => {
22627
+ if (code === 0) finish();
22628
+ else finish(new Error(`Antigravity CLI exited with code ${code ?? "unknown"}`));
22629
+ });
22630
+ });
22631
+ }
22632
+ function normalizeAntigravityUsage(raw, checkedAt = Date.now()) {
22633
+ if (!raw || typeof raw !== "object") {
22634
+ return { ...unavailableUsage("Antigravity CLI \u8FD4\u56DE\u4E86\u65E0\u6548\u6570\u636E\u3002", SOURCE), checkedAt };
22635
+ }
22636
+ if (typeof raw.status === "string" && raw.status.toUpperCase() !== "SUCCESS") {
22637
+ const errText = [
22638
+ typeof raw.error === "string" ? raw.error : raw.error?.message,
22639
+ raw.response
22640
+ ].filter(Boolean).join(" ");
22641
+ if (AUTH_ERROR_RE.test(errText)) {
22642
+ return { ...unavailableUsage("Antigravity \u5C1A\u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5148\u8FD0\u884C agy \u767B\u5F55\u3002", SOURCE), checkedAt };
22643
+ }
22644
+ return { ...unavailableUsage("Antigravity CLI \u672A\u8FD4\u56DE\u6709\u6548\u989D\u5EA6\u6570\u636E\u3002", SOURCE), checkedAt };
22645
+ }
22646
+ const data = raw.command?.data;
22647
+ const plan = typeof data?.plan === "string" && data.plan.trim() ? data.plan.trim() : typeof data?.tier === "string" && data.tier.trim() ? data.tier.trim() : typeof data?.tier === "object" && typeof data.tier?.name === "string" && data.tier.name.trim() ? data.tier.name.trim() : void 0;
22648
+ const groups = Array.isArray(data?.groups) ? data.groups : [];
22649
+ const windows = [];
22650
+ const seenLabels = /* @__PURE__ */ new Set();
22651
+ for (const group of groups) {
22652
+ const gLabel = groupLabel(group?.name);
22653
+ const buckets = Array.isArray(group?.buckets) ? [...group.buckets] : [];
22654
+ buckets.sort((a, b) => windowInfo(a).rank - windowInfo(b).rank);
22655
+ for (const bucket of buckets) {
22656
+ const usedPercent = bucketUsedPercent(bucket);
22657
+ if (usedPercent === void 0) continue;
22658
+ const wInfo = windowInfo(bucket);
22659
+ const baseLabel = gLabel ? `${gLabel} \xB7 ${wInfo.label}` : wInfo.label;
22660
+ if (seenLabels.has(baseLabel)) continue;
22661
+ seenLabels.add(baseLabel);
22662
+ const resetsAt = resetSeconds(bucket.reset_time);
22663
+ windows.push({ label: baseLabel, usedPercent, ...resetsAt ? { resetsAt } : {} });
22664
+ }
22665
+ }
22666
+ if (!windows.length) {
22667
+ return { ...unavailableUsage("Antigravity \u672A\u8FD4\u56DE\u53EF\u7528\u989D\u5EA6\u7A97\u53E3\u3002", SOURCE), checkedAt };
22668
+ }
22669
+ return { status: "available", ...plan ? { plan } : {}, windows, source: SOURCE, checkedAt };
22670
+ }
22671
+ async function readAntigravityUsage(runner = spawnAntigravity) {
22672
+ const configured = process.env.AGY_PATH?.trim();
22673
+ const candidates = configured ? [configured] : ["agy", "antigravity"];
22674
+ const env = antigravitySpawnEnv();
22675
+ for (const command of candidates) {
22676
+ try {
22677
+ const { stdout } = await runner(command, ["-p", "/usage", "--output-format", "json"], {
22678
+ timeout: 15e3,
22679
+ maxBuffer: 256 * 1024,
22680
+ windowsHide: true,
22681
+ env
22682
+ });
22683
+ const parsed = parseJsonOutput(stdout);
22684
+ if (!parsed) return unavailableUsage("Antigravity CLI \u8FD4\u56DE\u4E86\u65E0\u6548\u6570\u636E\u3002", SOURCE);
22685
+ return normalizeAntigravityUsage(parsed);
22686
+ } catch (error) {
22687
+ const err = error;
22688
+ if (err.code === "ENOENT") continue;
22689
+ const diagnostic = `${err.stderr ?? ""} ${err.stdout ?? ""} ${err.message ?? ""}`;
22690
+ if (AUTH_ERROR_RE.test(diagnostic)) {
22691
+ return unavailableUsage("Antigravity \u5C1A\u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5148\u8FD0\u884C agy \u767B\u5F55\u3002", SOURCE);
22692
+ }
22693
+ if (err.killed || err.signal === "SIGTERM" || err.code === "ETIMEDOUT") {
22694
+ return unavailableUsage("Antigravity \u989D\u5EA6\u67E5\u8BE2\u8D85\u65F6\u3002", SOURCE);
22695
+ }
22696
+ if (typeof err.stdout === "string") {
22697
+ const parsed = parseJsonOutput(err.stdout);
22698
+ if (parsed) return normalizeAntigravityUsage(parsed);
22699
+ }
22700
+ return unavailableUsage("Antigravity CLI \u672A\u8FD4\u56DE\u989D\u5EA6\u6570\u636E\u3002", SOURCE);
22701
+ }
22702
+ }
22703
+ return unavailableUsage("\u627E\u4E0D\u5230 Antigravity CLI\uFF08agy\uFF09\uFF0C\u8BF7\u786E\u8BA4\u5B83\u5DF2\u5B89\u88C5\u5E76\u52A0\u5165 PATH\u3002", SOURCE);
22704
+ }
22705
+ var cached4;
22706
+ var inFlight4;
22707
+ async function getAntigravityUsage(refresh = false) {
22708
+ if (!refresh && cached4 && Date.now() - cached4.checkedAt < 6e4) return cached4;
22709
+ if (!inFlight4) inFlight4 = readAntigravityUsage().then((result) => {
22710
+ cached4 = result;
22711
+ return result;
22712
+ }).finally(() => {
22713
+ inFlight4 = void 0;
22714
+ });
22715
+ return inFlight4;
22716
+ }
22717
+
22718
+ // src/usage-backfill.ts
22719
+ init_src2();
22720
+ import { readFile as readFile9, stat as stat4 } from "node:fs/promises";
22721
+ import { join as join16 } from "node:path";
22722
+ var toNonNegInt = (value) => {
22723
+ const num = Number(value ?? 0);
22724
+ return Number.isFinite(num) && num > 0 ? Math.round(num) : 0;
22725
+ };
22726
+ function createUsageBackfiller(target) {
22727
+ const scannedMtime = /* @__PURE__ */ new Map();
22728
+ let inFlight5;
22729
+ async function runOnce() {
22730
+ const sessions2 = await target.listSessions();
22731
+ let inserted = 0;
22732
+ for (const session of sessions2) {
22733
+ if (!session.cwd) continue;
22734
+ const filePath = join16(session.cwd, ".agentdock", "acpx", "sessions", `${session.id}.json`);
22735
+ let mtimeMs;
22736
+ try {
22737
+ const info = await stat4(filePath);
22738
+ mtimeMs = info.mtimeMs;
22739
+ } catch {
22740
+ continue;
22741
+ }
22742
+ if (scannedMtime.get(filePath) === mtimeMs) continue;
22743
+ let parsed;
22744
+ try {
22745
+ parsed = JSON.parse(await readFile9(filePath, "utf8"));
22746
+ } catch {
22747
+ scannedMtime.set(filePath, mtimeMs);
22748
+ continue;
22749
+ }
22750
+ scannedMtime.set(filePath, mtimeMs);
22751
+ const reqMap = parsed.request_token_usage;
22752
+ if (!reqMap || typeof reqMap !== "object") continue;
22753
+ const entries = Object.entries(reqMap).map(([requestId, raw]) => {
22754
+ const inputTokens = toNonNegInt(raw?.input_tokens);
22755
+ const outputTokens = toNonNegInt(raw?.output_tokens);
22756
+ const cacheReadTokens = toNonNegInt(raw?.cache_read_input_tokens);
22757
+ const cacheWriteTokens = toNonNegInt(raw?.cache_creation_input_tokens);
22758
+ const thoughtTokens = toNonNegInt(raw?.thought_tokens);
22759
+ const rawTotal = toNonNegInt(raw?.total_tokens);
22760
+ const totalTokens = rawTotal > 0 ? rawTotal : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens;
22761
+ return { requestId, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, thoughtTokens, totalTokens };
22762
+ }).filter((item) => item.totalTokens > 0 || item.inputTokens > 0 || item.outputTokens > 0);
22763
+ if (!entries.length) continue;
22764
+ const totalSessionTokens = entries.reduce((sum, item) => sum + item.totalTokens, 0);
22765
+ const totalCost = typeof parsed.cumulative_cost?.amount === "number" && Number.isFinite(parsed.cumulative_cost.amount) && parsed.cumulative_cost.amount > 0 ? parsed.cumulative_cost.amount : void 0;
22766
+ const fallbackTimestamp = parsed.last_prompt_at || parsed.updated_at || session.lastMessageAt || session.updatedAt || session.createdAt;
22767
+ for (const item of entries) {
22768
+ const costUsd = totalCost !== void 0 && totalSessionTokens > 0 ? Math.round(totalCost * (item.totalTokens / totalSessionTokens) * 1e6) / 1e6 : null;
22769
+ const ok = await target.saveTurnUsage({
22770
+ id: makeId("tu"),
22771
+ sessionId: session.id,
22772
+ taskId: null,
22773
+ requestId: item.requestId,
22774
+ agentId: session.agentId,
22775
+ cwd: session.cwd,
22776
+ model: session.model ?? null,
22777
+ inputTokens: item.inputTokens,
22778
+ outputTokens: item.outputTokens,
22779
+ cacheReadTokens: item.cacheReadTokens,
22780
+ cacheWriteTokens: item.cacheWriteTokens,
22781
+ thoughtTokens: item.thoughtTokens,
22782
+ totalTokens: item.totalTokens,
22783
+ costUsd,
22784
+ durationMs: null,
22785
+ generationMs: null,
22786
+ ttftMs: null,
22787
+ source: "acpx-backfill",
22788
+ createdAt: fallbackTimestamp
22789
+ });
22790
+ if (ok) inserted += 1;
22791
+ }
22792
+ }
22793
+ return inserted;
22794
+ }
22795
+ return {
22796
+ async sync() {
22797
+ if (!inFlight5) {
22798
+ inFlight5 = runOnce().finally(() => {
22799
+ inFlight5 = void 0;
22800
+ });
22801
+ }
22802
+ return inFlight5;
22803
+ }
22804
+ };
22805
+ }
22806
+
21943
22807
  // src/system-routes.ts
21944
22808
  import { execFile as execFile6 } from "node:child_process";
21945
22809
  import { homedir as homedir11 } from "node:os";
21946
22810
  import { promisify as promisify5 } from "node:util";
21947
22811
 
21948
22812
  // src/skill-catalog.ts
21949
- import { readFile as readFile9, readdir as readdir2 } from "node:fs/promises";
22813
+ import { readFile as readFile10, readdir as readdir2 } from "node:fs/promises";
21950
22814
  import { homedir as homedir10 } from "node:os";
21951
- import { basename as basename4, dirname as dirname10, join as join16, resolve as resolve8 } from "node:path";
22815
+ import { basename as basename5, dirname as dirname10, join as join17, resolve as resolve8 } from "node:path";
21952
22816
  var ignoredDirectories = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build"]);
21953
22817
  async function findSkillFiles(root4, maxDepth = 5) {
21954
22818
  const found = [];
@@ -21961,8 +22825,8 @@ async function findSkillFiles(root4, maxDepth = 5) {
21961
22825
  return;
21962
22826
  }
21963
22827
  for (const entry of entries) {
21964
- if (entry.isFile() && entry.name === "SKILL.md") found.push(join16(directory, entry.name));
21965
- else if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) await visit(join16(directory, entry.name), depth + 1);
22828
+ if (entry.isFile() && entry.name === "SKILL.md") found.push(join17(directory, entry.name));
22829
+ else if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) await visit(join17(directory, entry.name), depth + 1);
21966
22830
  }
21967
22831
  };
21968
22832
  await visit(root4, 0);
@@ -21976,15 +22840,15 @@ function frontmatterValue(markdown, key) {
21976
22840
  async function discoverSkills(workspace) {
21977
22841
  const workspaceRoot = resolve8(workspace?.trim() || process.cwd());
21978
22842
  const roots = [
21979
- { path: join16(workspaceRoot, ".agents", "skills"), source: "workspace" },
21980
- { path: join16(workspaceRoot, ".codex", "skills"), source: "workspace" },
21981
- { path: join16(homedir10(), ".agents", "skills"), source: "user" },
21982
- { path: join16(homedir10(), ".codex", "skills"), source: "user" }
22843
+ { path: join17(workspaceRoot, ".agents", "skills"), source: "workspace" },
22844
+ { path: join17(workspaceRoot, ".codex", "skills"), source: "workspace" },
22845
+ { path: join17(homedir10(), ".agents", "skills"), source: "user" },
22846
+ { path: join17(homedir10(), ".codex", "skills"), source: "user" }
21983
22847
  ];
21984
22848
  const references = await Promise.all(roots.map(async (root4) => Promise.all((await findSkillFiles(root4.path)).map(async (path5) => {
21985
- const markdown = await readFile9(path5, "utf8").catch(() => "");
22849
+ const markdown = await readFile10(path5, "utf8").catch(() => "");
21986
22850
  return {
21987
- name: frontmatterValue(markdown, "name") || basename4(dirname10(path5)),
22851
+ name: frontmatterValue(markdown, "name") || basename5(dirname10(path5)),
21988
22852
  description: frontmatterValue(markdown, "description"),
21989
22853
  path: path5,
21990
22854
  source: root4.source
@@ -23100,13 +23964,13 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
23100
23964
  // src/fs-routes.ts
23101
23965
  init_src2();
23102
23966
  import { realpathSync as realpathSync3 } from "node:fs";
23103
- import { readdir as readdir3, readFile as readFile10, stat as stat4 } from "node:fs/promises";
23104
- import { basename as basename6, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
23967
+ import { readdir as readdir3, readFile as readFile11, stat as stat5 } from "node:fs/promises";
23968
+ import { basename as basename7, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
23105
23969
 
23106
23970
  // src/fs-paths.ts
23107
23971
  import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
23108
23972
  import { homedir as homedir12, tmpdir as tmpdir3 } from "node:os";
23109
- import { basename as basename5, isAbsolute as isAbsolute6, join as join17, resolve as resolve9, sep } from "node:path";
23973
+ import { basename as basename6, isAbsolute as isAbsolute6, join as join18, resolve as resolve9, sep } from "node:path";
23110
23974
  function resolveInsideRoot(root4, userPath) {
23111
23975
  const normalized2 = (userPath ?? "").trim();
23112
23976
  if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
@@ -23166,7 +24030,7 @@ function isSensitivePath(targetPath) {
23166
24030
  if (seg === ".aws" && segments[i + 1]?.toLowerCase() === "credentials") return true;
23167
24031
  if (seg === ".kube" && segments[i + 1]?.toLowerCase() === "config") return true;
23168
24032
  }
23169
- const name = basename5(normalized2).toLowerCase();
24033
+ const name = basename6(normalized2).toLowerCase();
23170
24034
  if (sensitiveExactNames.has(name)) return true;
23171
24035
  if (name.startsWith(".env.")) return true;
23172
24036
  if (sensitiveKeyPrefixPattern.test(name)) return true;
@@ -23180,12 +24044,12 @@ function allowedReadRoots(options) {
23180
24044
  const candidates = [options.cwd];
23181
24045
  if (options.role === "session") {
23182
24046
  if (options.sessionId) {
23183
- candidates.push(join17(home, ".agentdock", "uploads", options.sessionId));
24047
+ candidates.push(join18(home, ".agentdock", "uploads", options.sessionId));
23184
24048
  }
23185
24049
  } else {
23186
24050
  candidates.push(
23187
- join17(home, ".agentdock", "uploads"),
23188
- join17(home, ".gemini"),
24051
+ join18(home, ".agentdock", "uploads"),
24052
+ join18(home, ".gemini"),
23189
24053
  "/tmp",
23190
24054
  "/private/tmp",
23191
24055
  options.tempDir ?? tmpdir3(),
@@ -23197,10 +24061,10 @@ function allowedReadRoots(options) {
23197
24061
  for (const candidate of candidates) {
23198
24062
  if (!candidate || !existsSync8(candidate)) continue;
23199
24063
  try {
23200
- const real = realpathSync2(candidate);
23201
- if (!seen.has(real)) {
23202
- seen.add(real);
23203
- resolved.push(real);
24064
+ const real2 = realpathSync2(candidate);
24065
+ if (!seen.has(real2)) {
24066
+ seen.add(real2);
24067
+ resolved.push(real2);
23204
24068
  }
23205
24069
  } catch {
23206
24070
  }
@@ -23356,7 +24220,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23356
24220
  await Promise.all(names.map(async (name) => {
23357
24221
  if (name === "node_modules" || name === ".git" || name === ".agentdock") return;
23358
24222
  try {
23359
- const info = await stat4(`${resolved.absolute}/${name}`);
24223
+ const info = await stat5(`${resolved.absolute}/${name}`);
23360
24224
  entries.push({ name, type: info.isDirectory() ? "dir" : "file", size: info.size, mtime: info.mtime.toISOString() });
23361
24225
  } catch {
23362
24226
  }
@@ -23416,12 +24280,12 @@ async function registerFsRoutes(app, runtime, options = {}) {
23416
24280
  }
23417
24281
  let info;
23418
24282
  try {
23419
- info = await stat4(resolved.absolute);
24283
+ info = await stat5(resolved.absolute);
23420
24284
  } catch (error) {
23421
24285
  badPath(error);
23422
24286
  }
23423
24287
  if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
23424
- const filename = basename6(resolved.absolute);
24288
+ const filename = basename7(resolved.absolute);
23425
24289
  const isSvg = filename.toLowerCase().endsWith(".svg");
23426
24290
  const wantDownload = request.query.download === "1" || request.query.download === "true";
23427
24291
  const wantText = request.query.format === "text";
@@ -23429,7 +24293,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23429
24293
  if (info.size > maxDocumentPreviewBytes) {
23430
24294
  throw new RuntimeError("FILE_TOO_LARGE", `\u6587\u4EF6\u8D85\u8FC7 20MB \u4E0B\u8F7D\u4E0A\u9650\uFF08\u5B9E\u9645 ${info.size} \u5B57\u8282\uFF09\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u5904\u7406`, 415);
23431
24295
  }
23432
- const buffer2 = await readFile10(resolved.absolute);
24296
+ const buffer2 = await readFile11(resolved.absolute);
23433
24297
  reply.header("Content-Type", imageMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream"));
23434
24298
  reply.header("Content-Disposition", contentDispositionAttachment(filename));
23435
24299
  reply.header("X-Content-Type-Options", "nosniff");
@@ -23446,7 +24310,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23446
24310
  if (info.size > maxBytes) {
23447
24311
  throw new RuntimeError("FILE_TOO_LARGE", `\u6587\u4EF6\u8D85\u8FC7 ${effectiveKind === "text" ? "1MB" : "20MB"} \u9884\u89C8\u4E0A\u9650\uFF08\u5B9E\u9645 ${info.size} \u5B57\u8282\uFF09\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u4E2D\u67E5\u770B\u6216\u4E0B\u8F7D`, 415);
23448
24312
  }
23449
- const buffer = await readFile10(resolved.absolute);
24313
+ const buffer = await readFile11(resolved.absolute);
23450
24314
  if (effectiveKind === "image" || effectiveKind === "pdf") {
23451
24315
  reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
23452
24316
  reply.header("X-Content-Type-Options", "nosniff");
@@ -23877,13 +24741,13 @@ var LlmClient = class {
23877
24741
  };
23878
24742
 
23879
24743
  // src/llm/detect.ts
23880
- import { readFile as readFile11 } from "node:fs/promises";
24744
+ import { readFile as readFile12 } from "node:fs/promises";
23881
24745
  import { homedir as homedir13 } from "node:os";
23882
- import { join as join18 } from "node:path";
24746
+ import { join as join19 } from "node:path";
23883
24747
  var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
23884
24748
  async function readJson(path5) {
23885
24749
  try {
23886
- const parsed = JSON.parse(await readFile11(path5, "utf8"));
24750
+ const parsed = JSON.parse(await readFile12(path5, "utf8"));
23887
24751
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
23888
24752
  } catch {
23889
24753
  return void 0;
@@ -23891,7 +24755,7 @@ async function readJson(path5) {
23891
24755
  }
23892
24756
  async function readText(path5) {
23893
24757
  try {
23894
- return await readFile11(path5, "utf8");
24758
+ return await readFile12(path5, "utf8");
23895
24759
  } catch {
23896
24760
  return void 0;
23897
24761
  }
@@ -24011,7 +24875,7 @@ async function detectLlmEndpoints(options = {}) {
24011
24875
  const env = options.env ?? process.env;
24012
24876
  const home = options.home ?? homedir13();
24013
24877
  const candidates = [];
24014
- const settings = await readJson(join18(home, ".claude", "settings.json"));
24878
+ const settings = await readJson(join19(home, ".claude", "settings.json"));
24015
24879
  const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
24016
24880
  const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
24017
24881
  if (fromSettings) candidates.push(fromSettings);
@@ -24019,7 +24883,7 @@ async function detectLlmEndpoints(options = {}) {
24019
24883
  if (fromEnv) candidates.push(fromEnv);
24020
24884
  const openai = openAiCandidate(env);
24021
24885
  if (openai) candidates.push(openai);
24022
- const codexConfig = await readText(join18(home, ".codex", "config.toml"));
24886
+ const codexConfig = await readText(join19(home, ".codex", "config.toml"));
24023
24887
  if (codexConfig) {
24024
24888
  const codex = codexCandidate(codexConfig, env);
24025
24889
  if (codex) candidates.push(codex);
@@ -24211,7 +25075,7 @@ init_side_chat_config();
24211
25075
 
24212
25076
  // src/json-compression.ts
24213
25077
  import { promisify as promisify6 } from "node:util";
24214
- import { brotliCompress, constants as constants4, gzip } from "node:zlib";
25078
+ import { brotliCompress, constants as constants5, gzip } from "node:zlib";
24215
25079
  var brotli = promisify6(brotliCompress);
24216
25080
  var gzipAsync = promisify6(gzip);
24217
25081
  var JSON_COMPRESSION_THRESHOLD = 32 * 1024;
@@ -24237,7 +25101,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
24237
25101
  if (size < threshold) return payload;
24238
25102
  const encoding = pickJsonEncoding(request.headers["accept-encoding"]);
24239
25103
  if (!encoding) return payload;
24240
- const body = encoding === "br" ? await brotli(payload, { params: { [constants4.BROTLI_PARAM_MODE]: constants4.BROTLI_MODE_TEXT, [constants4.BROTLI_PARAM_QUALITY]: 4, [constants4.BROTLI_PARAM_SIZE_HINT]: size } }) : await gzipAsync(payload, { level: 6 });
25104
+ const body = encoding === "br" ? await brotli(payload, { params: { [constants5.BROTLI_PARAM_MODE]: constants5.BROTLI_MODE_TEXT, [constants5.BROTLI_PARAM_QUALITY]: 4, [constants5.BROTLI_PARAM_SIZE_HINT]: size } }) : await gzipAsync(payload, { level: 6 });
24241
25105
  reply.header("content-encoding", encoding);
24242
25106
  const vary = String(reply.getHeader("vary") ?? "");
24243
25107
  if (!/(^|,)\s*accept-encoding\s*(,|$)/i.test(vary)) reply.header("vary", vary ? `${vary}, Accept-Encoding` : "Accept-Encoding");
@@ -24250,7 +25114,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
24250
25114
  import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
24251
25115
  import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
24252
25116
  import { homedir as homedir14 } from "node:os";
24253
- import { dirname as dirname11, join as join19 } from "node:path";
25117
+ import { dirname as dirname11, join as join20 } from "node:path";
24254
25118
  var webPasswordFileName = "web-password";
24255
25119
  var SCRYPT_N = 16384;
24256
25120
  var SCRYPT_R = 8;
@@ -24258,7 +25122,7 @@ var SCRYPT_P = 1;
24258
25122
  var KEY_LENGTH = 32;
24259
25123
  var minWebPasswordLength = 6;
24260
25124
  function webPasswordPath(home = homedir14()) {
24261
- return join19(home, ".agentdock", webPasswordFileName);
25125
+ return join20(home, ".agentdock", webPasswordFileName);
24262
25126
  }
24263
25127
  function hashWebPassword(password) {
24264
25128
  const salt = randomBytes3(16);
@@ -24523,8 +25387,8 @@ async function buildApp(runtime, options = {}) {
24523
25387
  if (!config.hosts.some((item) => item.alias === host)) {
24524
25388
  throw new RuntimeError("SSH_HOST_NOT_FOUND", `\u672A\u5728 ${config.configPath} \u4E2D\u627E\u5230 SSH \u4E3B\u673A\uFF1A${host}`, 404);
24525
25389
  }
24526
- const cached4 = sshProbeCache.get(host);
24527
- if (cached4 && Date.now() - cached4.at < 3e4) return cached4.value;
25390
+ const cached5 = sshProbeCache.get(host);
25391
+ if (cached5 && Date.now() - cached5.at < 3e4) return cached5.value;
24528
25392
  const value = await probeSshHost(host);
24529
25393
  sshProbeCache.set(host, { at: Date.now(), value });
24530
25394
  return value;
@@ -24551,6 +25415,34 @@ async function buildApp(runtime, options = {}) {
24551
25415
  app.get("/api/codex/usage", async (request) => getCodexUsage(request.query.refresh === "1"));
24552
25416
  app.get("/api/claude/usage", async (request) => getClaudeUsage(request.query.refresh === "1"));
24553
25417
  app.get("/api/cursor/usage", async (request) => getCursorUsage(request.query.refresh === "1"));
25418
+ app.get("/api/antigravity/usage", async (request) => getAntigravityUsage(request.query.refresh === "1"));
25419
+ const usageBackfiller = createUsageBackfiller(runtime);
25420
+ const parseUsageFilter = (query) => ({
25421
+ ...query.from?.trim() ? { from: query.from.trim() } : {},
25422
+ ...query.to?.trim() ? { to: query.to.trim() } : {},
25423
+ ...query.agentId?.trim() ? { agentId: query.agentId.trim() } : {},
25424
+ ...query.project?.trim() ? { project: query.project.trim() } : {},
25425
+ ...query.sessionId?.trim() ? { sessionId: query.sessionId.trim() } : {},
25426
+ ...query.model?.trim() ? { model: query.model.trim() } : {}
25427
+ });
25428
+ app.get("/api/usage/summary", async (request) => {
25429
+ await usageBackfiller.sync();
25430
+ return runtime.getUsageSummary(parseUsageFilter(request.query));
25431
+ });
25432
+ app.get("/api/usage/breakdown", async (request) => {
25433
+ const rawGroup = request.query.groupBy?.trim() || "project";
25434
+ if (!["project", "agent", "session", "model"].includes(rawGroup)) {
25435
+ throw new RuntimeError("INVALID_GROUP_BY", "groupBy \u5FC5\u987B\u662F project\u3001agent\u3001session \u6216 model", 400);
25436
+ }
25437
+ const rawLimit = request.query.limit ? Number(request.query.limit) : void 0;
25438
+ const limit = rawLimit !== void 0 && Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(200, Math.round(rawLimit)) : 50;
25439
+ await usageBackfiller.sync();
25440
+ return runtime.getUsageBreakdown(rawGroup, parseUsageFilter(request.query), limit);
25441
+ });
25442
+ app.get("/api/sessions/:id/usage", async (request) => {
25443
+ await usageBackfiller.sync();
25444
+ return runtime.getSessionUsage(request.params.id);
25445
+ });
24554
25446
  app.post("/api/agents", async (request) => runtime.createAgent(request.body));
24555
25447
  app.put("/api/agents/:id", async (request) => runtime.updateAgent(request.params.id, request.body));
24556
25448
  app.delete("/api/agents/:id", async (request) => runtime.deleteAgent(request.params.id));
@@ -24580,7 +25472,7 @@ async function buildApp(runtime, options = {}) {
24580
25472
  app.get("/api/sessions", async () => runtime.listSessions());
24581
25473
  app.get("/api/projects", async () => Promise.all((await runtime.listProjects()).map(async (project) => ({
24582
25474
  ...project,
24583
- exists: await stat5(project.cwd).then((info) => info.isDirectory()).catch(() => false)
25475
+ exists: await stat6(project.cwd).then((info) => info.isDirectory()).catch(() => false)
24584
25476
  }))));
24585
25477
  app.post("/api/projects", async (request) => runtime.registerProject(request.body?.path));
24586
25478
  app.patch("/api/projects/pin", async (request) => {
@@ -24797,7 +25689,7 @@ async function buildApp(runtime, options = {}) {
24797
25689
  "audio/flac": ".flac",
24798
25690
  "application/octet-stream": ""
24799
25691
  };
24800
- const globalUploadRoot = join20(homedir15(), ".agentdock", "uploads");
25692
+ const globalUploadRoot = join21(homedir15(), ".agentdock", "uploads");
24801
25693
  const uploadTtlMs = 7 * 24 * 60 * 6e4;
24802
25694
  const collectExpiredUploads = async (now2 = Date.now()) => {
24803
25695
  let removedFiles = 0;
@@ -24808,7 +25700,7 @@ async function buildApp(runtime, options = {}) {
24808
25700
  return { removedFiles };
24809
25701
  }
24810
25702
  for (const sessionDir of sessionDirs) {
24811
- const directory = join20(globalUploadRoot, sessionDir);
25703
+ const directory = join21(globalUploadRoot, sessionDir);
24812
25704
  let names;
24813
25705
  try {
24814
25706
  names = await readdir4(directory);
@@ -24816,9 +25708,9 @@ async function buildApp(runtime, options = {}) {
24816
25708
  continue;
24817
25709
  }
24818
25710
  for (const name of names) {
24819
- const filePath = join20(directory, name);
25711
+ const filePath = join21(directory, name);
24820
25712
  try {
24821
- const info = await stat5(filePath);
25713
+ const info = await stat6(filePath);
24822
25714
  if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
24823
25715
  await rm2(filePath, { force: true });
24824
25716
  removedFiles++;
@@ -24862,10 +25754,10 @@ async function buildApp(runtime, options = {}) {
24862
25754
  originalName = rawName;
24863
25755
  }
24864
25756
  const ext = extFromContentType(contentType, originalName);
24865
- const uploadDir = join20(globalUploadRoot, session.id);
25757
+ const uploadDir = join21(globalUploadRoot, session.id);
24866
25758
  await mkdir4(uploadDir, { recursive: true });
24867
25759
  const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
24868
- const filePath = join20(uploadDir, filename);
25760
+ const filePath = join21(uploadDir, filename);
24869
25761
  await writeFile4(filePath, buffer);
24870
25762
  return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
24871
25763
  });
@@ -24876,9 +25768,9 @@ async function buildApp(runtime, options = {}) {
24876
25768
  if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
24877
25769
  throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
24878
25770
  }
24879
- const filePath = join20(globalUploadRoot, session.id, filename);
25771
+ const filePath = join21(globalUploadRoot, session.id, filename);
24880
25772
  const ext = extname2(filename).toLowerCase();
24881
- const data = await readFile12(filePath);
25773
+ const data = await readFile13(filePath);
24882
25774
  reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
24883
25775
  reply.header("Cache-Control", "public, max-age=31536000, immutable");
24884
25776
  reply.header("Content-Disposition", `attachment; filename="${filename}"`);
@@ -24938,12 +25830,12 @@ data: ${JSON.stringify(event)}
24938
25830
  let file = requestedFile;
24939
25831
  let body;
24940
25832
  try {
24941
- body = await readFile12(file);
25833
+ body = await readFile13(file);
24942
25834
  } catch {
24943
25835
  if (extname2(pathname)) return reply.code(404).send();
24944
25836
  file = indexFile;
24945
25837
  try {
24946
- body = await readFile12(file);
25838
+ body = await readFile13(file);
24947
25839
  } catch {
24948
25840
  return reply.code(404).send({ error: { code: "WEB_UI_NOT_FOUND", message: "Web UI is not installed" } });
24949
25841
  }
@@ -29113,7 +30005,7 @@ function parseTemplate(schedule) {
29113
30005
 
29114
30006
  // src/assistant/service.ts
29115
30007
  init_src2();
29116
- import { spawn as spawn11, execFile as execFile7 } from "node:child_process";
30008
+ import { spawn as spawn12, execFile as execFile7 } from "node:child_process";
29117
30009
  import { createHash as createHash8 } from "node:crypto";
29118
30010
  import { promisify as promisify7 } from "node:util";
29119
30011
 
@@ -30662,8 +31554,8 @@ var AssistantLifecycle = class {
30662
31554
  async collectMetrics(force = false) {
30663
31555
  const mainId = this.host.mainSessionId();
30664
31556
  if (!mainId) return void 0;
30665
- const cached4 = this.metricsCache;
30666
- if (!force && cached4 && cached4.sessionId === mainId && Date.now() - cached4.at < METRICS_TTL_MS) return cached4.value;
31557
+ const cached5 = this.metricsCache;
31558
+ if (!force && cached5 && cached5.sessionId === mainId && Date.now() - cached5.at < METRICS_TTL_MS) return cached5.value;
30667
31559
  const cat = await this.ensureCat();
30668
31560
  if (!cat) return void 0;
30669
31561
  const config = this.getConfig();
@@ -31480,7 +32372,7 @@ function withContext(percent2) {
31480
32372
 
31481
32373
  // src/assistant/cwd.ts
31482
32374
  init_src2();
31483
- import { accessSync as accessSync2, constants as constants5, statSync as statSync5 } from "node:fs";
32375
+ import { accessSync as accessSync3, constants as constants6, statSync as statSync6 } from "node:fs";
31484
32376
  import { homedir as homedir16 } from "node:os";
31485
32377
  import { isAbsolute as isAbsolute8, resolve as resolve11 } from "node:path";
31486
32378
  function expandHomePath(value) {
@@ -31502,7 +32394,7 @@ function validateCwd(value) {
31502
32394
  const absolute = resolve11(expanded);
31503
32395
  let stats;
31504
32396
  try {
31505
- stats = statSync5(absolute);
32397
+ stats = statSync6(absolute);
31506
32398
  } catch {
31507
32399
  throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${absolute}`, 400);
31508
32400
  }
@@ -31510,7 +32402,7 @@ function validateCwd(value) {
31510
32402
  throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${absolute}`, 400);
31511
32403
  }
31512
32404
  try {
31513
- accessSync2(absolute, constants5.R_OK | constants5.X_OK);
32405
+ accessSync3(absolute, constants6.R_OK | constants6.X_OK);
31514
32406
  } catch {
31515
32407
  throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u8BBF\u95EE\uFF08\u9700\u8981\u8BFB\u548C\u6267\u884C\u6743\u9650\uFF09\uFF1A${absolute}`, 400);
31516
32408
  }
@@ -32759,7 +33651,7 @@ function parseGithubTarget(value) {
32759
33651
  async function runWatchCommand(watch) {
32760
33652
  const shell = resolveLoginShell();
32761
33653
  return await new Promise((resolve17) => {
32762
- const child = spawn11(shell.file, [...shell.args, "-c", watch.command], {
33654
+ const child = spawn12(shell.file, [...shell.args, "-c", watch.command], {
32763
33655
  cwd: watch.cwd ?? process.cwd(),
32764
33656
  env: { ...process.env, agentdock_watch_id: watch.id, agentdock_session_id: watch.ownerSessionId },
32765
33657
  detached: process.platform !== "win32",
@@ -33429,13 +34321,13 @@ async function runLarkMessageListen(options, deps = {}) {
33429
34321
  init_session_cli();
33430
34322
  import { readFileSync as readFileSync10 } from "node:fs";
33431
34323
  var readTextFile = (path5) => path5 === "-" ? readFileSync10(0, "utf8") : readFileSync10(path5, "utf8");
33432
- function buildLarkAvatarSendInput(options, readFile13 = readTextFile) {
34324
+ function buildLarkAvatarSendInput(options, readFile14 = readTextFile) {
33433
34325
  const chat = options.chat?.trim();
33434
34326
  if (!chat) throw new Error("--chat \u5FC5\u586B\uFF1A\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id");
33435
34327
  if (options.text !== void 0 && options.textFile !== void 0) {
33436
34328
  throw new Error("--text \u548C --text-file \u53EA\u80FD\u7528\u4E00\u4E2A");
33437
34329
  }
33438
- const text3 = options.textFile !== void 0 ? readFile13(options.textFile) : options.text;
34330
+ const text3 = options.textFile !== void 0 ? readFile14(options.textFile) : options.text;
33439
34331
  if (text3 === void 0 || !text3.trim()) {
33440
34332
  throw new Error("\u6D88\u606F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A\uFF1A\u8BF7\u7528 --text <text> \u6216 --text-file <file>");
33441
34333
  }
@@ -33556,7 +34448,7 @@ async function runLarkAvatarReactionRoute(options) {
33556
34448
  }
33557
34449
 
33558
34450
  // src/acpx.ts
33559
- import { spawn as spawn12 } from "node:child_process";
34451
+ import { spawn as spawn13 } from "node:child_process";
33560
34452
  import { readFileSync as readFileSync11 } from "node:fs";
33561
34453
  import { createRequire as createRequire3 } from "node:module";
33562
34454
  import { dirname as dirname12, resolve as resolve13 } from "node:path";
@@ -33575,7 +34467,7 @@ function resolveAcpxLauncher(moduleUrl = import.meta.url) {
33575
34467
  }
33576
34468
  return { command: "acpx", args: [] };
33577
34469
  }
33578
- function runAcpx(args, spawnProcess = spawn12, launcher = resolveAcpxLauncher()) {
34470
+ function runAcpx(args, spawnProcess = spawn13, launcher = resolveAcpxLauncher()) {
33579
34471
  return new Promise((resolve17, reject2) => {
33580
34472
  const options = { stdio: "inherit", env: process.env };
33581
34473
  const child = spawnProcess(launcher.command, [...launcher.args, ...args], options);
@@ -33987,23 +34879,23 @@ init_session_cli();
33987
34879
  import { spawnSync as spawnSync3 } from "node:child_process";
33988
34880
  import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
33989
34881
  import { createServer } from "node:net";
33990
- import { delimiter as delimiter2, dirname as dirname13, join as join22, resolve as resolve15 } from "node:path";
34882
+ import { delimiter as delimiter2, dirname as dirname13, join as join23, resolve as resolve15 } from "node:path";
33991
34883
  init_daemon();
33992
34884
  var SANDBOX_FILE = "sandbox.json";
33993
34885
  function findRepoRoot(start = process.cwd()) {
33994
34886
  let dir = resolve15(start);
33995
34887
  for (; ; ) {
33996
- if (existsSync12(join22(dir, "apps", "server", "package.json")) && existsSync12(join22(dir, "pnpm-workspace.yaml"))) return dir;
34888
+ if (existsSync12(join23(dir, "apps", "server", "package.json")) && existsSync12(join23(dir, "pnpm-workspace.yaml"))) return dir;
33997
34889
  const parent = dirname13(dir);
33998
34890
  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");
33999
34891
  dir = parent;
34000
34892
  }
34001
34893
  }
34002
34894
  function sandboxPaths(repo, port) {
34003
- const root4 = join22(repo, ".agentdock", "dev");
34004
- return { root: root4, home: join22(root4, "home"), work: join22(root4, "work"), database: join22(root4, "agentdock.db"), entrypoint: join22(repo, "apps", "server", "dist", "cli.js"), port };
34895
+ const root4 = join23(repo, ".agentdock", "dev");
34896
+ return { root: root4, home: join23(root4, "home"), work: join23(root4, "work"), database: join23(root4, "agentdock.db"), entrypoint: join23(repo, "apps", "server", "dist", "cli.js"), port };
34005
34897
  }
34006
- var shimDir = (sandbox) => join22(sandbox.root, "bin");
34898
+ var shimDir = (sandbox) => join23(sandbox.root, "bin");
34007
34899
  function sandboxEnv(sandbox, base = process.env) {
34008
34900
  const env = {
34009
34901
  ...base,
@@ -34016,17 +34908,28 @@ function sandboxEnv(sandbox, base = process.env) {
34016
34908
  AGENTDOCK_ALLOW_REACTION_TEST: "true",
34017
34909
  agentdock_database: sandbox.database
34018
34910
  };
34019
- env.PATH = [shimDir(sandbox), base.PATH].filter(Boolean).join(delimiter2);
34911
+ const pathKey = process.platform === "win32" ? Object.keys(base).find((key) => key.toUpperCase() === "PATH") ?? "PATH" : "PATH";
34912
+ env[pathKey] = [shimDir(sandbox), base[pathKey]].filter(Boolean).join(delimiter2);
34020
34913
  for (const key of ["agentdock_session_id", "agentdock_group_tools_url", "agentdock_group_tools_token"]) delete env[key];
34021
34914
  for (const key of [DAEMON_ENV_FLAG, DAEMON_CWD_ENV, DAEMON_STARTED_AT_ENV, DAEMON_DIR_ENV]) delete env[key];
34022
34915
  return env;
34023
34916
  }
34024
34917
  var shellQuote5 = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
34025
34918
  function writeCliShim(sandbox, node = process.execPath) {
34026
- if (process.platform === "win32") return;
34027
34919
  const dir = shimDir(sandbox);
34028
34920
  mkdirSync6(dir, { recursive: true });
34029
- const file = join22(dir, "agent-dock");
34921
+ if (process.platform === "win32") {
34922
+ const quote2 = (path5) => `"${path5.replace(/%/g, "%%")}"`;
34923
+ writeFileSync5(
34924
+ join23(dir, "agent-dock.cmd"),
34925
+ `@echo off\r
34926
+ setlocal DisableDelayedExpansion\r
34927
+ ${quote2(node)} ${quote2(sandbox.entrypoint)} %*\r
34928
+ `
34929
+ );
34930
+ return;
34931
+ }
34932
+ const file = join23(dir, "agent-dock");
34030
34933
  writeFileSync5(file, `#!/bin/sh
34031
34934
  exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
34032
34935
  `);
@@ -34034,7 +34937,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
34034
34937
  }
34035
34938
  function readSandbox(repo) {
34036
34939
  try {
34037
- return JSON.parse(readFileSync13(join22(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
34940
+ return JSON.parse(readFileSync13(join23(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
34038
34941
  } catch {
34039
34942
  return void 0;
34040
34943
  }
@@ -34061,7 +34964,7 @@ async function devUp(options = {}) {
34061
34964
  const sandbox = sandboxPaths(repo, port);
34062
34965
  if (!existsSync12(sandbox.entrypoint)) throw new Error(`\u6CA1\u6709\u6784\u5EFA\u4EA7\u7269\uFF1A${sandbox.entrypoint}\u3002\u5148\u5728\u4ED3\u5E93\u6839\u76EE\u5F55\u8FD0\u884C pnpm build\u3002`);
34063
34966
  for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
34064
- writeFileSync5(join22(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
34967
+ writeFileSync5(join23(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
34065
34968
  `);
34066
34969
  writeCliShim(sandbox);
34067
34970
  const run2 = options.run ?? defaultRun;
@@ -34273,6 +35176,111 @@ var runScheduleResume = (id, options = {}) => control(id, "resume", options);
34273
35176
  var runScheduleRun = (id, options = {}) => control(id, "run", options);
34274
35177
  var runScheduleRemove = (id, options = {}) => control(id, "remove", options);
34275
35178
 
35179
+ // src/usage-cli.ts
35180
+ init_session_cli();
35181
+ function localDateString(date) {
35182
+ const y = date.getFullYear();
35183
+ const m = String(date.getMonth() + 1).padStart(2, "0");
35184
+ const d = String(date.getDate()).padStart(2, "0");
35185
+ return `${y}-${m}-${d}`;
35186
+ }
35187
+ function resolveUsageFromOption(raw, now2 = /* @__PURE__ */ new Date()) {
35188
+ const trimmed = raw?.trim();
35189
+ if (!trimmed) return void 0;
35190
+ const lower = trimmed.toLowerCase();
35191
+ if (lower === "today") return localDateString(now2);
35192
+ const rel = /^(\d+)d$/.exec(lower);
35193
+ if (rel) {
35194
+ const days = Math.max(1, Number(rel[1]));
35195
+ const start = new Date(now2.getFullYear(), now2.getMonth(), now2.getDate() - (days - 1));
35196
+ return localDateString(start);
35197
+ }
35198
+ return trimmed;
35199
+ }
35200
+ function buildUsageSearchParams(options, extra) {
35201
+ const params = new URLSearchParams();
35202
+ const from = resolveUsageFromOption(options.from);
35203
+ if (from) params.set("from", from);
35204
+ if (options.to?.trim()) params.set("to", options.to.trim());
35205
+ if (options.agent?.trim()) params.set("agentId", options.agent.trim());
35206
+ if (options.project?.trim()) params.set("project", options.project.trim());
35207
+ if (options.session?.trim()) params.set("sessionId", options.session.trim());
35208
+ if (options.model?.trim()) params.set("model", options.model.trim());
35209
+ if (extra) {
35210
+ for (const [key, value] of Object.entries(extra)) {
35211
+ if (value?.trim()) params.set(key, value.trim());
35212
+ }
35213
+ }
35214
+ const qs = params.toString();
35215
+ return qs ? `?${qs}` : "";
35216
+ }
35217
+ function fmtTokens(value) {
35218
+ if (value >= 1e6) return `${(value / 1e6).toFixed(2)}M`;
35219
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
35220
+ return String(value);
35221
+ }
35222
+ function fmtTps(tps) {
35223
+ return tps !== null && tps !== void 0 ? `${tps.toFixed(1)} tok/s` : "\u2014";
35224
+ }
35225
+ function fmtCost(costUsd) {
35226
+ if (!costUsd || costUsd <= 0) return "\u2014";
35227
+ return `$${costUsd.toFixed(costUsd >= 1 ? 2 : 4)}`;
35228
+ }
35229
+ async function runUsageSummary(options = {}) {
35230
+ const state = requireDaemon(options.daemonDir);
35231
+ const qs = buildUsageSearchParams(options);
35232
+ const data = await callDaemon(state, `/api/usage/summary${qs}`, "GET");
35233
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35234
+ `;
35235
+ const t = data.totals;
35236
+ const lines = [
35237
+ `\u603B\u6D88\u8017: ${fmtTokens(t.totalTokens)} tokens\uFF08\u8F93\u5165 ${fmtTokens(t.inputTokens)} \xB7 \u7F13\u5B58 ${fmtTokens(t.cacheReadTokens)} \xB7 \u8F93\u51FA ${fmtTokens(t.outputTokens)}${t.thoughtTokens > 0 ? ` \xB7 \u601D\u8003 ${fmtTokens(t.thoughtTokens)}` : ""}\uFF09`,
35238
+ `\u901F\u5EA6/\u8D39\u7528: \u5E73\u5747 ${fmtTps(t.avgTps)} \xB7 \u8D39\u7528 ${fmtCost(t.costUsd)} \xB7 ${t.turnCount} \u8F6E / ${t.sessionCount} \u4E2A\u4F1A\u8BDD`
35239
+ ];
35240
+ if (data.daily.length) {
35241
+ lines.push("\u6309\u65E5\u660E\u7EC6:");
35242
+ for (const day of data.daily) {
35243
+ lines.push(` ${day.date} ${fmtTokens(day.totalTokens)} tok (${day.turnCount} \u8F6E \xB7 ${fmtTps(day.avgTps)}${day.costUsd > 0 ? ` \xB7 ${fmtCost(day.costUsd)}` : ""})`);
35244
+ }
35245
+ }
35246
+ return `${lines.join("\n")}
35247
+ `;
35248
+ }
35249
+ async function runUsageBreakdown(options = {}) {
35250
+ const by = options.by?.trim() || "project";
35251
+ if (!["project", "agent", "session", "model"].includes(by)) {
35252
+ throw new Error("--by \u5FC5\u987B\u662F project\u3001agent\u3001session \u6216 model\u3002");
35253
+ }
35254
+ const state = requireDaemon(options.daemonDir);
35255
+ const qs = buildUsageSearchParams(options, { groupBy: by, limit: options.limit });
35256
+ const data = await callDaemon(state, `/api/usage/breakdown${qs}`, "GET");
35257
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35258
+ `;
35259
+ if (!data.items.length) return "\u5F53\u524D\u7B5B\u9009\u8303\u56F4\u5185\u6CA1\u6709\u771F\u5B9E\u6D88\u8017\u8BB0\u5F55\u3002\n";
35260
+ const lines = data.items.map((item, idx) => {
35261
+ const t = item.totals;
35262
+ return `${idx + 1}. ${item.label}${item.sublabel && item.sublabel !== item.label ? ` (${item.sublabel})` : ""}
35263
+ ${fmtTokens(t.totalTokens)} tok\uFF08\u8F93\u5165 ${fmtTokens(t.inputTokens)} \xB7 \u7F13\u5B58 ${fmtTokens(t.cacheReadTokens)} \xB7 \u8F93\u51FA ${fmtTokens(t.outputTokens)}\uFF09\xB7 ${fmtTps(t.avgTps)} \xB7 ${t.turnCount} \u8F6E${t.costUsd > 0 ? ` \xB7 ${fmtCost(t.costUsd)}` : ""}`;
35264
+ });
35265
+ return `${lines.join("\n")}
35266
+ `;
35267
+ }
35268
+ async function runUsageSession(sessionId, options = {}) {
35269
+ const targetId = sessionId?.trim() || sourceSessionId(void 0);
35270
+ const state = requireDaemon(options.daemonDir);
35271
+ const data = await callDaemon(state, `/api/sessions/${encodeURIComponent(targetId)}/usage`, "GET");
35272
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35273
+ `;
35274
+ const t = data.totals;
35275
+ const lines = [
35276
+ `\u4F1A\u8BDD ${data.sessionId}${data.agentId ? ` (${data.agentId})` : ""}`,
35277
+ `\u7D2F\u8BA1\u6D88\u8017: ${fmtTokens(t.totalTokens)} tokens\uFF08\u8F93\u5165 ${fmtTokens(t.inputTokens)} \xB7 \u7F13\u5B58 ${fmtTokens(t.cacheReadTokens)} \xB7 \u8F93\u51FA ${fmtTokens(t.outputTokens)}${t.thoughtTokens > 0 ? ` \xB7 \u601D\u8003 ${fmtTokens(t.thoughtTokens)}` : ""}\uFF09`,
35278
+ `\u901F\u5EA6/\u8D39\u7528: \u6700\u8FD1 ${fmtTps(t.lastTps)} \xB7 \u5E73\u5747 ${fmtTps(t.avgTps)} \xB7 \u8D39\u7528 ${fmtCost(t.costUsd)} \xB7 ${t.turnCount} \u8F6E`
35279
+ ];
35280
+ return `${lines.join("\n")}
35281
+ `;
35282
+ }
35283
+
34276
35284
  // src/assistant/cli.ts
34277
35285
  init_session_cli();
34278
35286
  import { readFileSync as readFileSync14 } from "node:fs";
@@ -35676,7 +36684,7 @@ async function serve(options, onReady) {
35676
36684
  async function restartWithInstalledCli(entrypoint) {
35677
36685
  if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
35678
36686
  const previousPid = daemonStatus().pid;
35679
- const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
36687
+ const child = spawn14(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
35680
36688
  await new Promise((resolve17, reject2) => {
35681
36689
  child.once("error", reject2);
35682
36690
  child.once("exit", (code) => code === 0 ? resolve17() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
@@ -36018,6 +37026,15 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
36018
37026
  },
36019
37027
  draftDiscard: async (id, options) => {
36020
37028
  process.stdout.write(await runDraftDiscard(id, options));
37029
+ },
37030
+ usageSummary: async (options) => {
37031
+ process.stdout.write(await runUsageSummary(options));
37032
+ },
37033
+ usageBreakdown: async (options) => {
37034
+ process.stdout.write(await runUsageBreakdown(options));
37035
+ },
37036
+ usageSession: async (sessionId, options) => {
37037
+ process.stdout.write(await runUsageSession(sessionId, options));
36021
37038
  }
36022
37039
  });
36023
37040
  await program.parseAsync();