@agent-dock/cli 0.3.17 → 0.3.18

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;
@@ -18046,6 +18537,18 @@ var AgentDockRuntime = class _AgentDockRuntime {
18046
18537
  listProjects() {
18047
18538
  return this.repos.projects.list();
18048
18539
  }
18540
+ saveTurnUsage(record) {
18541
+ return this.repos.usage.save(record);
18542
+ }
18543
+ getSessionUsage(sessionId) {
18544
+ return this.repos.usage.getSessionUsage(sessionId);
18545
+ }
18546
+ getUsageSummary(filter) {
18547
+ return this.repos.usage.summary(filter);
18548
+ }
18549
+ getUsageBreakdown(groupBy, filter, limit) {
18550
+ return this.repos.usage.breakdown(groupBy, filter, limit);
18551
+ }
18049
18552
  /**
18050
18553
  * 登记用户导入的项目。路径统一 realpath(`~` 展开、相对路径拒绝、macOS /private 别名归一),
18051
18554
  * 已存在则原样返回并标记 created=false,前端可据此提示「已存在」而不是造出第二条。
@@ -18058,7 +18561,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
18058
18561
  const project = {
18059
18562
  id: `local:${cwd}`,
18060
18563
  machineId: "local",
18061
- name: basename2(cwd) || cwd,
18564
+ name: basename3(cwd) || cwd,
18062
18565
  cwd,
18063
18566
  pinnedAt: null,
18064
18567
  createdAt: time2,
@@ -18335,6 +18838,57 @@ var AgentDockRuntime = class _AgentDockRuntime {
18335
18838
  await this.setAgentTitle(session, typeof event.data?.title === "string" ? event.data.title : void 0);
18336
18839
  return;
18337
18840
  }
18841
+ if (event.type === "turn_usage") {
18842
+ const d = event.data ?? {};
18843
+ const inputTokens = Number(d.inputTokens ?? 0);
18844
+ const outputTokens = Number(d.outputTokens ?? 0);
18845
+ const cacheReadTokens = Number(d.cacheReadTokens ?? 0);
18846
+ const cacheWriteTokens = Number(d.cacheWriteTokens ?? 0);
18847
+ const thoughtTokens = Number(d.thoughtTokens ?? 0);
18848
+ const totalTokens = Number(d.totalTokens ?? inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens);
18849
+ if (totalTokens > 0 || inputTokens > 0 || outputTokens > 0) {
18850
+ const taskId = this.activeTasks.get(session.id)?.id ?? null;
18851
+ const generationMs = typeof d.generationMs === "number" && Number.isFinite(d.generationMs) && d.generationMs > 0 ? Math.round(d.generationMs) : null;
18852
+ const durationMs = typeof d.durationMs === "number" && Number.isFinite(d.durationMs) && d.durationMs > 0 ? Math.round(d.durationMs) : null;
18853
+ const ttftMs = typeof d.ttftMs === "number" && Number.isFinite(d.ttftMs) && d.ttftMs >= 0 ? Math.round(d.ttftMs) : null;
18854
+ const costUsd = typeof d.costUsd === "number" && Number.isFinite(d.costUsd) && d.costUsd >= 0 ? d.costUsd : null;
18855
+ await this.repos.usage.save({
18856
+ id: makeId("tu"),
18857
+ sessionId: session.id,
18858
+ taskId,
18859
+ requestId: typeof d.requestId === "string" && d.requestId.trim() ? d.requestId.trim() : null,
18860
+ agentId: session.agentId,
18861
+ cwd: session.cwd,
18862
+ model: session.model ?? null,
18863
+ inputTokens,
18864
+ outputTokens,
18865
+ cacheReadTokens,
18866
+ cacheWriteTokens,
18867
+ thoughtTokens,
18868
+ totalTokens,
18869
+ costUsd,
18870
+ durationMs,
18871
+ generationMs,
18872
+ ttftMs,
18873
+ source: "acp",
18874
+ createdAt: now()
18875
+ });
18876
+ await this.emit(session.id, "status", {
18877
+ state: "turn_usage",
18878
+ inputTokens,
18879
+ outputTokens,
18880
+ cacheReadTokens,
18881
+ cacheWriteTokens,
18882
+ thoughtTokens,
18883
+ totalTokens,
18884
+ ...costUsd !== null ? { costUsd } : {},
18885
+ ...durationMs !== null ? { durationMs } : {},
18886
+ ...generationMs !== null ? { generationMs } : {},
18887
+ ...ttftMs !== null ? { ttftMs } : {}
18888
+ });
18889
+ }
18890
+ return;
18891
+ }
18338
18892
  let data = event.data;
18339
18893
  if (event.type === "tool_call" || event.type === "tool_result") {
18340
18894
  const completed = data.status === "completed" || data.status === "failed";
@@ -19391,9 +19945,9 @@ function registerSelfUpdateRoutes(app, service) {
19391
19945
  init_src2();
19392
19946
  import Fastify from "fastify";
19393
19947
  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";
19948
+ import { readFile as readFile13, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
19395
19949
  import { Readable as Readable3 } from "node:stream";
19396
- import { extname as extname2, join as join20, resolve as resolve10, sep as sep3 } from "node:path";
19950
+ import { extname as extname2, join as join21, resolve as resolve10, sep as sep3 } from "node:path";
19397
19951
  import { homedir as homedir15 } from "node:os";
19398
19952
  import { randomBytes as randomBytes4 } from "node:crypto";
19399
19953
 
@@ -21401,8 +21955,8 @@ function agentModelsCacheKey(agent, model) {
21401
21955
  var cache = /* @__PURE__ */ new Map();
21402
21956
  async function discoverAgentModels(agent, model, forceRefresh = false) {
21403
21957
  const cacheKey = agentModelsCacheKey(agent, model);
21404
- const cached4 = cache.get(cacheKey);
21405
- if (!forceRefresh && cached4 && cached4.expiresAt > Date.now()) return cached4.value;
21958
+ const cached5 = cache.get(cacheKey);
21959
+ if (!forceRefresh && cached5 && cached5.expiresAt > Date.now()) return cached5.value;
21406
21960
  let value;
21407
21961
  let warning;
21408
21962
  try {
@@ -21940,15 +22494,317 @@ async function getCursorUsage(refresh = false) {
21940
22494
  return inFlight3;
21941
22495
  }
21942
22496
 
22497
+ // src/antigravity-usage.ts
22498
+ import { spawn as spawn10 } from "node:child_process";
22499
+ import { userInfo as userInfo2 } from "node:os";
22500
+ var SOURCE = "Antigravity CLI";
22501
+ var AUTH_ERROR_RE = /unauthenticated|authentication required|authentication failed|not logged in|please log in|sign in|\b401\b/i;
22502
+ function resolveRealHome() {
22503
+ try {
22504
+ const dir = userInfo2().homedir;
22505
+ return dir?.trim() || void 0;
22506
+ } catch {
22507
+ return void 0;
22508
+ }
22509
+ }
22510
+ function antigravitySpawnEnv(base = process.env, realHome = resolveRealHome()) {
22511
+ const env = {
22512
+ ...base,
22513
+ BROWSER: "true",
22514
+ NO_BROWSER: "1"
22515
+ };
22516
+ if (realHome) {
22517
+ env.HOME = realHome;
22518
+ if (process.platform === "win32") env.USERPROFILE = realHome;
22519
+ }
22520
+ return env;
22521
+ }
22522
+ function groupLabel(name) {
22523
+ const trimmed = name?.trim();
22524
+ if (!trimmed) return "";
22525
+ if (/^gemini\b/i.test(trimmed)) return "Gemini";
22526
+ if (/claude/i.test(trimmed) && /gpt/i.test(trimmed)) return "Claude / GPT";
22527
+ return trimmed;
22528
+ }
22529
+ function windowInfo(bucket) {
22530
+ const key = bucket.window?.trim().toLowerCase();
22531
+ if (key === "5h" || key === "five_hour") return { label: "5 \u5C0F\u65F6", rank: 1 };
22532
+ if (key === "weekly" || key === "7d" || key === "seven_day") return { label: "7 \u5929", rank: 2 };
22533
+ const fallback = bucket.name?.trim() || bucket.window?.trim() || bucket.id?.trim() || "\u989D\u5EA6";
22534
+ return { label: fallback, rank: 3 };
22535
+ }
22536
+ function bucketUsedPercent(bucket) {
22537
+ if (typeof bucket.remaining_fraction === "number" && Number.isFinite(bucket.remaining_fraction) && bucket.remaining_fraction >= 0) {
22538
+ const remaining2 = Math.min(bucket.remaining_fraction, 1);
22539
+ return Math.round((1 - remaining2) * 1e4) / 100;
22540
+ }
22541
+ if (typeof bucket.used_fraction === "number" && Number.isFinite(bucket.used_fraction) && bucket.used_fraction >= 0) {
22542
+ return Math.round(Math.min(bucket.used_fraction, 1) * 1e4) / 100;
22543
+ }
22544
+ const used = percent(bucket.used_percent);
22545
+ if (used !== void 0) return Math.round(used * 100) / 100;
22546
+ const remaining = percent(bucket.remaining_percent);
22547
+ if (remaining !== void 0) return Math.round((100 - remaining) * 100) / 100;
22548
+ return void 0;
22549
+ }
22550
+ function parseJsonOutput(stdout) {
22551
+ const trimmed = stdout.trim();
22552
+ if (!trimmed) return void 0;
22553
+ try {
22554
+ return JSON.parse(trimmed);
22555
+ } catch {
22556
+ const lines = trimmed.split(/\r?\n/);
22557
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
22558
+ const line = lines[i].trim();
22559
+ if (!line.startsWith("{")) continue;
22560
+ try {
22561
+ return JSON.parse(line);
22562
+ } catch {
22563
+ continue;
22564
+ }
22565
+ }
22566
+ return void 0;
22567
+ }
22568
+ }
22569
+ function spawnAntigravity(command, args, options) {
22570
+ return new Promise((resolve17, reject2) => {
22571
+ let settled = false;
22572
+ let stdout = "";
22573
+ let stderr = "";
22574
+ let child;
22575
+ const finish = (err) => {
22576
+ if (settled) return;
22577
+ settled = true;
22578
+ clearTimeout(timer);
22579
+ if (err) {
22580
+ err.stdout = stdout;
22581
+ err.stderr = stderr;
22582
+ reject2(err);
22583
+ } else {
22584
+ resolve17({ stdout, stderr });
22585
+ }
22586
+ };
22587
+ const timer = setTimeout(() => {
22588
+ child?.kill();
22589
+ const err = new Error("Antigravity CLI timed out");
22590
+ err.killed = true;
22591
+ err.code = "ETIMEDOUT";
22592
+ finish(err);
22593
+ }, options.timeout);
22594
+ timer.unref();
22595
+ try {
22596
+ child = spawn10(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: options.windowsHide, env: options.env });
22597
+ } catch (error) {
22598
+ finish(error);
22599
+ return;
22600
+ }
22601
+ child.on("error", (error) => finish(error));
22602
+ child.stdout?.on("data", (chunk) => {
22603
+ stdout += chunk.toString("utf8");
22604
+ if (stdout.length > options.maxBuffer) {
22605
+ child.kill();
22606
+ finish(new Error("Antigravity CLI output exceeded buffer limit"));
22607
+ }
22608
+ });
22609
+ child.stderr?.on("data", (chunk) => {
22610
+ stderr += chunk.toString("utf8");
22611
+ if (AUTH_ERROR_RE.test(stderr)) {
22612
+ child.kill();
22613
+ finish(new Error("Authentication required"));
22614
+ return;
22615
+ }
22616
+ if (stderr.length > options.maxBuffer) stderr = stderr.slice(-options.maxBuffer);
22617
+ });
22618
+ child.on("close", (code) => {
22619
+ if (code === 0) finish();
22620
+ else finish(new Error(`Antigravity CLI exited with code ${code ?? "unknown"}`));
22621
+ });
22622
+ });
22623
+ }
22624
+ function normalizeAntigravityUsage(raw, checkedAt = Date.now()) {
22625
+ if (!raw || typeof raw !== "object") {
22626
+ return { ...unavailableUsage("Antigravity CLI \u8FD4\u56DE\u4E86\u65E0\u6548\u6570\u636E\u3002", SOURCE), checkedAt };
22627
+ }
22628
+ if (typeof raw.status === "string" && raw.status.toUpperCase() !== "SUCCESS") {
22629
+ const errText = [
22630
+ typeof raw.error === "string" ? raw.error : raw.error?.message,
22631
+ raw.response
22632
+ ].filter(Boolean).join(" ");
22633
+ if (AUTH_ERROR_RE.test(errText)) {
22634
+ return { ...unavailableUsage("Antigravity \u5C1A\u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5148\u8FD0\u884C agy \u767B\u5F55\u3002", SOURCE), checkedAt };
22635
+ }
22636
+ return { ...unavailableUsage("Antigravity CLI \u672A\u8FD4\u56DE\u6709\u6548\u989D\u5EA6\u6570\u636E\u3002", SOURCE), checkedAt };
22637
+ }
22638
+ const data = raw.command?.data;
22639
+ 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;
22640
+ const groups = Array.isArray(data?.groups) ? data.groups : [];
22641
+ const windows = [];
22642
+ const seenLabels = /* @__PURE__ */ new Set();
22643
+ for (const group of groups) {
22644
+ const gLabel = groupLabel(group?.name);
22645
+ const buckets = Array.isArray(group?.buckets) ? [...group.buckets] : [];
22646
+ buckets.sort((a, b) => windowInfo(a).rank - windowInfo(b).rank);
22647
+ for (const bucket of buckets) {
22648
+ const usedPercent = bucketUsedPercent(bucket);
22649
+ if (usedPercent === void 0) continue;
22650
+ const wInfo = windowInfo(bucket);
22651
+ const baseLabel = gLabel ? `${gLabel} \xB7 ${wInfo.label}` : wInfo.label;
22652
+ if (seenLabels.has(baseLabel)) continue;
22653
+ seenLabels.add(baseLabel);
22654
+ const resetsAt = resetSeconds(bucket.reset_time);
22655
+ windows.push({ label: baseLabel, usedPercent, ...resetsAt ? { resetsAt } : {} });
22656
+ }
22657
+ }
22658
+ if (!windows.length) {
22659
+ return { ...unavailableUsage("Antigravity \u672A\u8FD4\u56DE\u53EF\u7528\u989D\u5EA6\u7A97\u53E3\u3002", SOURCE), checkedAt };
22660
+ }
22661
+ return { status: "available", ...plan ? { plan } : {}, windows, source: SOURCE, checkedAt };
22662
+ }
22663
+ async function readAntigravityUsage(runner = spawnAntigravity) {
22664
+ const configured = process.env.AGY_PATH?.trim();
22665
+ const candidates = configured ? [configured] : ["agy", "antigravity"];
22666
+ const env = antigravitySpawnEnv();
22667
+ for (const command of candidates) {
22668
+ try {
22669
+ const { stdout } = await runner(command, ["-p", "/usage", "--output-format", "json"], {
22670
+ timeout: 15e3,
22671
+ maxBuffer: 256 * 1024,
22672
+ windowsHide: true,
22673
+ env
22674
+ });
22675
+ const parsed = parseJsonOutput(stdout);
22676
+ if (!parsed) return unavailableUsage("Antigravity CLI \u8FD4\u56DE\u4E86\u65E0\u6548\u6570\u636E\u3002", SOURCE);
22677
+ return normalizeAntigravityUsage(parsed);
22678
+ } catch (error) {
22679
+ const err = error;
22680
+ if (err.code === "ENOENT") continue;
22681
+ const diagnostic = `${err.stderr ?? ""} ${err.stdout ?? ""} ${err.message ?? ""}`;
22682
+ if (AUTH_ERROR_RE.test(diagnostic)) {
22683
+ return unavailableUsage("Antigravity \u5C1A\u672A\u767B\u5F55\u6216\u767B\u5F55\u5DF2\u5931\u6548\uFF0C\u8BF7\u5148\u8FD0\u884C agy \u767B\u5F55\u3002", SOURCE);
22684
+ }
22685
+ if (err.killed || err.signal === "SIGTERM" || err.code === "ETIMEDOUT") {
22686
+ return unavailableUsage("Antigravity \u989D\u5EA6\u67E5\u8BE2\u8D85\u65F6\u3002", SOURCE);
22687
+ }
22688
+ if (typeof err.stdout === "string") {
22689
+ const parsed = parseJsonOutput(err.stdout);
22690
+ if (parsed) return normalizeAntigravityUsage(parsed);
22691
+ }
22692
+ return unavailableUsage("Antigravity CLI \u672A\u8FD4\u56DE\u989D\u5EA6\u6570\u636E\u3002", SOURCE);
22693
+ }
22694
+ }
22695
+ return unavailableUsage("\u627E\u4E0D\u5230 Antigravity CLI\uFF08agy\uFF09\uFF0C\u8BF7\u786E\u8BA4\u5B83\u5DF2\u5B89\u88C5\u5E76\u52A0\u5165 PATH\u3002", SOURCE);
22696
+ }
22697
+ var cached4;
22698
+ var inFlight4;
22699
+ async function getAntigravityUsage(refresh = false) {
22700
+ if (!refresh && cached4 && Date.now() - cached4.checkedAt < 6e4) return cached4;
22701
+ if (!inFlight4) inFlight4 = readAntigravityUsage().then((result) => {
22702
+ cached4 = result;
22703
+ return result;
22704
+ }).finally(() => {
22705
+ inFlight4 = void 0;
22706
+ });
22707
+ return inFlight4;
22708
+ }
22709
+
22710
+ // src/usage-backfill.ts
22711
+ init_src2();
22712
+ import { readFile as readFile9, stat as stat4 } from "node:fs/promises";
22713
+ import { join as join16 } from "node:path";
22714
+ var toNonNegInt = (value) => {
22715
+ const num = Number(value ?? 0);
22716
+ return Number.isFinite(num) && num > 0 ? Math.round(num) : 0;
22717
+ };
22718
+ function createUsageBackfiller(target) {
22719
+ const scannedMtime = /* @__PURE__ */ new Map();
22720
+ let inFlight5;
22721
+ async function runOnce() {
22722
+ const sessions2 = await target.listSessions();
22723
+ let inserted = 0;
22724
+ for (const session of sessions2) {
22725
+ if (!session.cwd) continue;
22726
+ const filePath = join16(session.cwd, ".agentdock", "acpx", "sessions", `${session.id}.json`);
22727
+ let mtimeMs;
22728
+ try {
22729
+ const info = await stat4(filePath);
22730
+ mtimeMs = info.mtimeMs;
22731
+ } catch {
22732
+ continue;
22733
+ }
22734
+ if (scannedMtime.get(filePath) === mtimeMs) continue;
22735
+ let parsed;
22736
+ try {
22737
+ parsed = JSON.parse(await readFile9(filePath, "utf8"));
22738
+ } catch {
22739
+ scannedMtime.set(filePath, mtimeMs);
22740
+ continue;
22741
+ }
22742
+ scannedMtime.set(filePath, mtimeMs);
22743
+ const reqMap = parsed.request_token_usage;
22744
+ if (!reqMap || typeof reqMap !== "object") continue;
22745
+ const entries = Object.entries(reqMap).map(([requestId, raw]) => {
22746
+ const inputTokens = toNonNegInt(raw?.input_tokens);
22747
+ const outputTokens = toNonNegInt(raw?.output_tokens);
22748
+ const cacheReadTokens = toNonNegInt(raw?.cache_read_input_tokens);
22749
+ const cacheWriteTokens = toNonNegInt(raw?.cache_creation_input_tokens);
22750
+ const thoughtTokens = toNonNegInt(raw?.thought_tokens);
22751
+ const rawTotal = toNonNegInt(raw?.total_tokens);
22752
+ const totalTokens = rawTotal > 0 ? rawTotal : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens + thoughtTokens;
22753
+ return { requestId, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, thoughtTokens, totalTokens };
22754
+ }).filter((item) => item.totalTokens > 0 || item.inputTokens > 0 || item.outputTokens > 0);
22755
+ if (!entries.length) continue;
22756
+ const totalSessionTokens = entries.reduce((sum, item) => sum + item.totalTokens, 0);
22757
+ 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;
22758
+ const fallbackTimestamp = parsed.last_prompt_at || parsed.updated_at || session.lastMessageAt || session.updatedAt || session.createdAt;
22759
+ for (const item of entries) {
22760
+ const costUsd = totalCost !== void 0 && totalSessionTokens > 0 ? Math.round(totalCost * (item.totalTokens / totalSessionTokens) * 1e6) / 1e6 : null;
22761
+ const ok = await target.saveTurnUsage({
22762
+ id: makeId("tu"),
22763
+ sessionId: session.id,
22764
+ taskId: null,
22765
+ requestId: item.requestId,
22766
+ agentId: session.agentId,
22767
+ cwd: session.cwd,
22768
+ model: session.model ?? null,
22769
+ inputTokens: item.inputTokens,
22770
+ outputTokens: item.outputTokens,
22771
+ cacheReadTokens: item.cacheReadTokens,
22772
+ cacheWriteTokens: item.cacheWriteTokens,
22773
+ thoughtTokens: item.thoughtTokens,
22774
+ totalTokens: item.totalTokens,
22775
+ costUsd,
22776
+ durationMs: null,
22777
+ generationMs: null,
22778
+ ttftMs: null,
22779
+ source: "acpx-backfill",
22780
+ createdAt: fallbackTimestamp
22781
+ });
22782
+ if (ok) inserted += 1;
22783
+ }
22784
+ }
22785
+ return inserted;
22786
+ }
22787
+ return {
22788
+ async sync() {
22789
+ if (!inFlight5) {
22790
+ inFlight5 = runOnce().finally(() => {
22791
+ inFlight5 = void 0;
22792
+ });
22793
+ }
22794
+ return inFlight5;
22795
+ }
22796
+ };
22797
+ }
22798
+
21943
22799
  // src/system-routes.ts
21944
22800
  import { execFile as execFile6 } from "node:child_process";
21945
22801
  import { homedir as homedir11 } from "node:os";
21946
22802
  import { promisify as promisify5 } from "node:util";
21947
22803
 
21948
22804
  // src/skill-catalog.ts
21949
- import { readFile as readFile9, readdir as readdir2 } from "node:fs/promises";
22805
+ import { readFile as readFile10, readdir as readdir2 } from "node:fs/promises";
21950
22806
  import { homedir as homedir10 } from "node:os";
21951
- import { basename as basename4, dirname as dirname10, join as join16, resolve as resolve8 } from "node:path";
22807
+ import { basename as basename5, dirname as dirname10, join as join17, resolve as resolve8 } from "node:path";
21952
22808
  var ignoredDirectories = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build"]);
21953
22809
  async function findSkillFiles(root4, maxDepth = 5) {
21954
22810
  const found = [];
@@ -21961,8 +22817,8 @@ async function findSkillFiles(root4, maxDepth = 5) {
21961
22817
  return;
21962
22818
  }
21963
22819
  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);
22820
+ if (entry.isFile() && entry.name === "SKILL.md") found.push(join17(directory, entry.name));
22821
+ else if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) await visit(join17(directory, entry.name), depth + 1);
21966
22822
  }
21967
22823
  };
21968
22824
  await visit(root4, 0);
@@ -21976,15 +22832,15 @@ function frontmatterValue(markdown, key) {
21976
22832
  async function discoverSkills(workspace) {
21977
22833
  const workspaceRoot = resolve8(workspace?.trim() || process.cwd());
21978
22834
  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" }
22835
+ { path: join17(workspaceRoot, ".agents", "skills"), source: "workspace" },
22836
+ { path: join17(workspaceRoot, ".codex", "skills"), source: "workspace" },
22837
+ { path: join17(homedir10(), ".agents", "skills"), source: "user" },
22838
+ { path: join17(homedir10(), ".codex", "skills"), source: "user" }
21983
22839
  ];
21984
22840
  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(() => "");
22841
+ const markdown = await readFile10(path5, "utf8").catch(() => "");
21986
22842
  return {
21987
- name: frontmatterValue(markdown, "name") || basename4(dirname10(path5)),
22843
+ name: frontmatterValue(markdown, "name") || basename5(dirname10(path5)),
21988
22844
  description: frontmatterValue(markdown, "description"),
21989
22845
  path: path5,
21990
22846
  source: root4.source
@@ -23100,13 +23956,13 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
23100
23956
  // src/fs-routes.ts
23101
23957
  init_src2();
23102
23958
  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";
23959
+ import { readdir as readdir3, readFile as readFile11, stat as stat5 } from "node:fs/promises";
23960
+ import { basename as basename7, isAbsolute as isAbsolute7, relative, sep as sep2 } from "node:path";
23105
23961
 
23106
23962
  // src/fs-paths.ts
23107
23963
  import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
23108
23964
  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";
23965
+ import { basename as basename6, isAbsolute as isAbsolute6, join as join18, resolve as resolve9, sep } from "node:path";
23110
23966
  function resolveInsideRoot(root4, userPath) {
23111
23967
  const normalized2 = (userPath ?? "").trim();
23112
23968
  if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
@@ -23166,7 +24022,7 @@ function isSensitivePath(targetPath) {
23166
24022
  if (seg === ".aws" && segments[i + 1]?.toLowerCase() === "credentials") return true;
23167
24023
  if (seg === ".kube" && segments[i + 1]?.toLowerCase() === "config") return true;
23168
24024
  }
23169
- const name = basename5(normalized2).toLowerCase();
24025
+ const name = basename6(normalized2).toLowerCase();
23170
24026
  if (sensitiveExactNames.has(name)) return true;
23171
24027
  if (name.startsWith(".env.")) return true;
23172
24028
  if (sensitiveKeyPrefixPattern.test(name)) return true;
@@ -23180,12 +24036,12 @@ function allowedReadRoots(options) {
23180
24036
  const candidates = [options.cwd];
23181
24037
  if (options.role === "session") {
23182
24038
  if (options.sessionId) {
23183
- candidates.push(join17(home, ".agentdock", "uploads", options.sessionId));
24039
+ candidates.push(join18(home, ".agentdock", "uploads", options.sessionId));
23184
24040
  }
23185
24041
  } else {
23186
24042
  candidates.push(
23187
- join17(home, ".agentdock", "uploads"),
23188
- join17(home, ".gemini"),
24043
+ join18(home, ".agentdock", "uploads"),
24044
+ join18(home, ".gemini"),
23189
24045
  "/tmp",
23190
24046
  "/private/tmp",
23191
24047
  options.tempDir ?? tmpdir3(),
@@ -23197,10 +24053,10 @@ function allowedReadRoots(options) {
23197
24053
  for (const candidate of candidates) {
23198
24054
  if (!candidate || !existsSync8(candidate)) continue;
23199
24055
  try {
23200
- const real = realpathSync2(candidate);
23201
- if (!seen.has(real)) {
23202
- seen.add(real);
23203
- resolved.push(real);
24056
+ const real2 = realpathSync2(candidate);
24057
+ if (!seen.has(real2)) {
24058
+ seen.add(real2);
24059
+ resolved.push(real2);
23204
24060
  }
23205
24061
  } catch {
23206
24062
  }
@@ -23356,7 +24212,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23356
24212
  await Promise.all(names.map(async (name) => {
23357
24213
  if (name === "node_modules" || name === ".git" || name === ".agentdock") return;
23358
24214
  try {
23359
- const info = await stat4(`${resolved.absolute}/${name}`);
24215
+ const info = await stat5(`${resolved.absolute}/${name}`);
23360
24216
  entries.push({ name, type: info.isDirectory() ? "dir" : "file", size: info.size, mtime: info.mtime.toISOString() });
23361
24217
  } catch {
23362
24218
  }
@@ -23416,12 +24272,12 @@ async function registerFsRoutes(app, runtime, options = {}) {
23416
24272
  }
23417
24273
  let info;
23418
24274
  try {
23419
- info = await stat4(resolved.absolute);
24275
+ info = await stat5(resolved.absolute);
23420
24276
  } catch (error) {
23421
24277
  badPath(error);
23422
24278
  }
23423
24279
  if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
23424
- const filename = basename6(resolved.absolute);
24280
+ const filename = basename7(resolved.absolute);
23425
24281
  const isSvg = filename.toLowerCase().endsWith(".svg");
23426
24282
  const wantDownload = request.query.download === "1" || request.query.download === "true";
23427
24283
  const wantText = request.query.format === "text";
@@ -23429,7 +24285,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23429
24285
  if (info.size > maxDocumentPreviewBytes) {
23430
24286
  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
24287
  }
23432
- const buffer2 = await readFile10(resolved.absolute);
24288
+ const buffer2 = await readFile11(resolved.absolute);
23433
24289
  reply.header("Content-Type", imageMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream"));
23434
24290
  reply.header("Content-Disposition", contentDispositionAttachment(filename));
23435
24291
  reply.header("X-Content-Type-Options", "nosniff");
@@ -23446,7 +24302,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
23446
24302
  if (info.size > maxBytes) {
23447
24303
  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
24304
  }
23449
- const buffer = await readFile10(resolved.absolute);
24305
+ const buffer = await readFile11(resolved.absolute);
23450
24306
  if (effectiveKind === "image" || effectiveKind === "pdf") {
23451
24307
  reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
23452
24308
  reply.header("X-Content-Type-Options", "nosniff");
@@ -23877,13 +24733,13 @@ var LlmClient = class {
23877
24733
  };
23878
24734
 
23879
24735
  // src/llm/detect.ts
23880
- import { readFile as readFile11 } from "node:fs/promises";
24736
+ import { readFile as readFile12 } from "node:fs/promises";
23881
24737
  import { homedir as homedir13 } from "node:os";
23882
- import { join as join18 } from "node:path";
24738
+ import { join as join19 } from "node:path";
23883
24739
  var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
23884
24740
  async function readJson(path5) {
23885
24741
  try {
23886
- const parsed = JSON.parse(await readFile11(path5, "utf8"));
24742
+ const parsed = JSON.parse(await readFile12(path5, "utf8"));
23887
24743
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
23888
24744
  } catch {
23889
24745
  return void 0;
@@ -23891,7 +24747,7 @@ async function readJson(path5) {
23891
24747
  }
23892
24748
  async function readText(path5) {
23893
24749
  try {
23894
- return await readFile11(path5, "utf8");
24750
+ return await readFile12(path5, "utf8");
23895
24751
  } catch {
23896
24752
  return void 0;
23897
24753
  }
@@ -24011,7 +24867,7 @@ async function detectLlmEndpoints(options = {}) {
24011
24867
  const env = options.env ?? process.env;
24012
24868
  const home = options.home ?? homedir13();
24013
24869
  const candidates = [];
24014
- const settings = await readJson(join18(home, ".claude", "settings.json"));
24870
+ const settings = await readJson(join19(home, ".claude", "settings.json"));
24015
24871
  const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
24016
24872
  const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
24017
24873
  if (fromSettings) candidates.push(fromSettings);
@@ -24019,7 +24875,7 @@ async function detectLlmEndpoints(options = {}) {
24019
24875
  if (fromEnv) candidates.push(fromEnv);
24020
24876
  const openai = openAiCandidate(env);
24021
24877
  if (openai) candidates.push(openai);
24022
- const codexConfig = await readText(join18(home, ".codex", "config.toml"));
24878
+ const codexConfig = await readText(join19(home, ".codex", "config.toml"));
24023
24879
  if (codexConfig) {
24024
24880
  const codex = codexCandidate(codexConfig, env);
24025
24881
  if (codex) candidates.push(codex);
@@ -24250,7 +25106,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
24250
25106
  import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
24251
25107
  import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
24252
25108
  import { homedir as homedir14 } from "node:os";
24253
- import { dirname as dirname11, join as join19 } from "node:path";
25109
+ import { dirname as dirname11, join as join20 } from "node:path";
24254
25110
  var webPasswordFileName = "web-password";
24255
25111
  var SCRYPT_N = 16384;
24256
25112
  var SCRYPT_R = 8;
@@ -24258,7 +25114,7 @@ var SCRYPT_P = 1;
24258
25114
  var KEY_LENGTH = 32;
24259
25115
  var minWebPasswordLength = 6;
24260
25116
  function webPasswordPath(home = homedir14()) {
24261
- return join19(home, ".agentdock", webPasswordFileName);
25117
+ return join20(home, ".agentdock", webPasswordFileName);
24262
25118
  }
24263
25119
  function hashWebPassword(password) {
24264
25120
  const salt = randomBytes3(16);
@@ -24523,8 +25379,8 @@ async function buildApp(runtime, options = {}) {
24523
25379
  if (!config.hosts.some((item) => item.alias === host)) {
24524
25380
  throw new RuntimeError("SSH_HOST_NOT_FOUND", `\u672A\u5728 ${config.configPath} \u4E2D\u627E\u5230 SSH \u4E3B\u673A\uFF1A${host}`, 404);
24525
25381
  }
24526
- const cached4 = sshProbeCache.get(host);
24527
- if (cached4 && Date.now() - cached4.at < 3e4) return cached4.value;
25382
+ const cached5 = sshProbeCache.get(host);
25383
+ if (cached5 && Date.now() - cached5.at < 3e4) return cached5.value;
24528
25384
  const value = await probeSshHost(host);
24529
25385
  sshProbeCache.set(host, { at: Date.now(), value });
24530
25386
  return value;
@@ -24551,6 +25407,34 @@ async function buildApp(runtime, options = {}) {
24551
25407
  app.get("/api/codex/usage", async (request) => getCodexUsage(request.query.refresh === "1"));
24552
25408
  app.get("/api/claude/usage", async (request) => getClaudeUsage(request.query.refresh === "1"));
24553
25409
  app.get("/api/cursor/usage", async (request) => getCursorUsage(request.query.refresh === "1"));
25410
+ app.get("/api/antigravity/usage", async (request) => getAntigravityUsage(request.query.refresh === "1"));
25411
+ const usageBackfiller = createUsageBackfiller(runtime);
25412
+ const parseUsageFilter = (query) => ({
25413
+ ...query.from?.trim() ? { from: query.from.trim() } : {},
25414
+ ...query.to?.trim() ? { to: query.to.trim() } : {},
25415
+ ...query.agentId?.trim() ? { agentId: query.agentId.trim() } : {},
25416
+ ...query.project?.trim() ? { project: query.project.trim() } : {},
25417
+ ...query.sessionId?.trim() ? { sessionId: query.sessionId.trim() } : {},
25418
+ ...query.model?.trim() ? { model: query.model.trim() } : {}
25419
+ });
25420
+ app.get("/api/usage/summary", async (request) => {
25421
+ await usageBackfiller.sync();
25422
+ return runtime.getUsageSummary(parseUsageFilter(request.query));
25423
+ });
25424
+ app.get("/api/usage/breakdown", async (request) => {
25425
+ const rawGroup = request.query.groupBy?.trim() || "project";
25426
+ if (!["project", "agent", "session", "model"].includes(rawGroup)) {
25427
+ throw new RuntimeError("INVALID_GROUP_BY", "groupBy \u5FC5\u987B\u662F project\u3001agent\u3001session \u6216 model", 400);
25428
+ }
25429
+ const rawLimit = request.query.limit ? Number(request.query.limit) : void 0;
25430
+ const limit = rawLimit !== void 0 && Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(200, Math.round(rawLimit)) : 50;
25431
+ await usageBackfiller.sync();
25432
+ return runtime.getUsageBreakdown(rawGroup, parseUsageFilter(request.query), limit);
25433
+ });
25434
+ app.get("/api/sessions/:id/usage", async (request) => {
25435
+ await usageBackfiller.sync();
25436
+ return runtime.getSessionUsage(request.params.id);
25437
+ });
24554
25438
  app.post("/api/agents", async (request) => runtime.createAgent(request.body));
24555
25439
  app.put("/api/agents/:id", async (request) => runtime.updateAgent(request.params.id, request.body));
24556
25440
  app.delete("/api/agents/:id", async (request) => runtime.deleteAgent(request.params.id));
@@ -24580,7 +25464,7 @@ async function buildApp(runtime, options = {}) {
24580
25464
  app.get("/api/sessions", async () => runtime.listSessions());
24581
25465
  app.get("/api/projects", async () => Promise.all((await runtime.listProjects()).map(async (project) => ({
24582
25466
  ...project,
24583
- exists: await stat5(project.cwd).then((info) => info.isDirectory()).catch(() => false)
25467
+ exists: await stat6(project.cwd).then((info) => info.isDirectory()).catch(() => false)
24584
25468
  }))));
24585
25469
  app.post("/api/projects", async (request) => runtime.registerProject(request.body?.path));
24586
25470
  app.patch("/api/projects/pin", async (request) => {
@@ -24797,7 +25681,7 @@ async function buildApp(runtime, options = {}) {
24797
25681
  "audio/flac": ".flac",
24798
25682
  "application/octet-stream": ""
24799
25683
  };
24800
- const globalUploadRoot = join20(homedir15(), ".agentdock", "uploads");
25684
+ const globalUploadRoot = join21(homedir15(), ".agentdock", "uploads");
24801
25685
  const uploadTtlMs = 7 * 24 * 60 * 6e4;
24802
25686
  const collectExpiredUploads = async (now2 = Date.now()) => {
24803
25687
  let removedFiles = 0;
@@ -24808,7 +25692,7 @@ async function buildApp(runtime, options = {}) {
24808
25692
  return { removedFiles };
24809
25693
  }
24810
25694
  for (const sessionDir of sessionDirs) {
24811
- const directory = join20(globalUploadRoot, sessionDir);
25695
+ const directory = join21(globalUploadRoot, sessionDir);
24812
25696
  let names;
24813
25697
  try {
24814
25698
  names = await readdir4(directory);
@@ -24816,9 +25700,9 @@ async function buildApp(runtime, options = {}) {
24816
25700
  continue;
24817
25701
  }
24818
25702
  for (const name of names) {
24819
- const filePath = join20(directory, name);
25703
+ const filePath = join21(directory, name);
24820
25704
  try {
24821
- const info = await stat5(filePath);
25705
+ const info = await stat6(filePath);
24822
25706
  if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
24823
25707
  await rm2(filePath, { force: true });
24824
25708
  removedFiles++;
@@ -24862,10 +25746,10 @@ async function buildApp(runtime, options = {}) {
24862
25746
  originalName = rawName;
24863
25747
  }
24864
25748
  const ext = extFromContentType(contentType, originalName);
24865
- const uploadDir = join20(globalUploadRoot, session.id);
25749
+ const uploadDir = join21(globalUploadRoot, session.id);
24866
25750
  await mkdir4(uploadDir, { recursive: true });
24867
25751
  const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
24868
- const filePath = join20(uploadDir, filename);
25752
+ const filePath = join21(uploadDir, filename);
24869
25753
  await writeFile4(filePath, buffer);
24870
25754
  return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
24871
25755
  });
@@ -24876,9 +25760,9 @@ async function buildApp(runtime, options = {}) {
24876
25760
  if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
24877
25761
  throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
24878
25762
  }
24879
- const filePath = join20(globalUploadRoot, session.id, filename);
25763
+ const filePath = join21(globalUploadRoot, session.id, filename);
24880
25764
  const ext = extname2(filename).toLowerCase();
24881
- const data = await readFile12(filePath);
25765
+ const data = await readFile13(filePath);
24882
25766
  reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
24883
25767
  reply.header("Cache-Control", "public, max-age=31536000, immutable");
24884
25768
  reply.header("Content-Disposition", `attachment; filename="${filename}"`);
@@ -24938,12 +25822,12 @@ data: ${JSON.stringify(event)}
24938
25822
  let file = requestedFile;
24939
25823
  let body;
24940
25824
  try {
24941
- body = await readFile12(file);
25825
+ body = await readFile13(file);
24942
25826
  } catch {
24943
25827
  if (extname2(pathname)) return reply.code(404).send();
24944
25828
  file = indexFile;
24945
25829
  try {
24946
- body = await readFile12(file);
25830
+ body = await readFile13(file);
24947
25831
  } catch {
24948
25832
  return reply.code(404).send({ error: { code: "WEB_UI_NOT_FOUND", message: "Web UI is not installed" } });
24949
25833
  }
@@ -29113,7 +29997,7 @@ function parseTemplate(schedule) {
29113
29997
 
29114
29998
  // src/assistant/service.ts
29115
29999
  init_src2();
29116
- import { spawn as spawn11, execFile as execFile7 } from "node:child_process";
30000
+ import { spawn as spawn12, execFile as execFile7 } from "node:child_process";
29117
30001
  import { createHash as createHash8 } from "node:crypto";
29118
30002
  import { promisify as promisify7 } from "node:util";
29119
30003
 
@@ -30662,8 +31546,8 @@ var AssistantLifecycle = class {
30662
31546
  async collectMetrics(force = false) {
30663
31547
  const mainId = this.host.mainSessionId();
30664
31548
  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;
31549
+ const cached5 = this.metricsCache;
31550
+ if (!force && cached5 && cached5.sessionId === mainId && Date.now() - cached5.at < METRICS_TTL_MS) return cached5.value;
30667
31551
  const cat = await this.ensureCat();
30668
31552
  if (!cat) return void 0;
30669
31553
  const config = this.getConfig();
@@ -32759,7 +33643,7 @@ function parseGithubTarget(value) {
32759
33643
  async function runWatchCommand(watch) {
32760
33644
  const shell = resolveLoginShell();
32761
33645
  return await new Promise((resolve17) => {
32762
- const child = spawn11(shell.file, [...shell.args, "-c", watch.command], {
33646
+ const child = spawn12(shell.file, [...shell.args, "-c", watch.command], {
32763
33647
  cwd: watch.cwd ?? process.cwd(),
32764
33648
  env: { ...process.env, agentdock_watch_id: watch.id, agentdock_session_id: watch.ownerSessionId },
32765
33649
  detached: process.platform !== "win32",
@@ -33429,13 +34313,13 @@ async function runLarkMessageListen(options, deps = {}) {
33429
34313
  init_session_cli();
33430
34314
  import { readFileSync as readFileSync10 } from "node:fs";
33431
34315
  var readTextFile = (path5) => path5 === "-" ? readFileSync10(0, "utf8") : readFileSync10(path5, "utf8");
33432
- function buildLarkAvatarSendInput(options, readFile13 = readTextFile) {
34316
+ function buildLarkAvatarSendInput(options, readFile14 = readTextFile) {
33433
34317
  const chat = options.chat?.trim();
33434
34318
  if (!chat) throw new Error("--chat \u5FC5\u586B\uFF1A\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id");
33435
34319
  if (options.text !== void 0 && options.textFile !== void 0) {
33436
34320
  throw new Error("--text \u548C --text-file \u53EA\u80FD\u7528\u4E00\u4E2A");
33437
34321
  }
33438
- const text3 = options.textFile !== void 0 ? readFile13(options.textFile) : options.text;
34322
+ const text3 = options.textFile !== void 0 ? readFile14(options.textFile) : options.text;
33439
34323
  if (text3 === void 0 || !text3.trim()) {
33440
34324
  throw new Error("\u6D88\u606F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A\uFF1A\u8BF7\u7528 --text <text> \u6216 --text-file <file>");
33441
34325
  }
@@ -33556,7 +34440,7 @@ async function runLarkAvatarReactionRoute(options) {
33556
34440
  }
33557
34441
 
33558
34442
  // src/acpx.ts
33559
- import { spawn as spawn12 } from "node:child_process";
34443
+ import { spawn as spawn13 } from "node:child_process";
33560
34444
  import { readFileSync as readFileSync11 } from "node:fs";
33561
34445
  import { createRequire as createRequire3 } from "node:module";
33562
34446
  import { dirname as dirname12, resolve as resolve13 } from "node:path";
@@ -33575,7 +34459,7 @@ function resolveAcpxLauncher(moduleUrl = import.meta.url) {
33575
34459
  }
33576
34460
  return { command: "acpx", args: [] };
33577
34461
  }
33578
- function runAcpx(args, spawnProcess = spawn12, launcher = resolveAcpxLauncher()) {
34462
+ function runAcpx(args, spawnProcess = spawn13, launcher = resolveAcpxLauncher()) {
33579
34463
  return new Promise((resolve17, reject2) => {
33580
34464
  const options = { stdio: "inherit", env: process.env };
33581
34465
  const child = spawnProcess(launcher.command, [...launcher.args, ...args], options);
@@ -33987,23 +34871,23 @@ init_session_cli();
33987
34871
  import { spawnSync as spawnSync3 } from "node:child_process";
33988
34872
  import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
33989
34873
  import { createServer } from "node:net";
33990
- import { delimiter as delimiter2, dirname as dirname13, join as join22, resolve as resolve15 } from "node:path";
34874
+ import { delimiter as delimiter2, dirname as dirname13, join as join23, resolve as resolve15 } from "node:path";
33991
34875
  init_daemon();
33992
34876
  var SANDBOX_FILE = "sandbox.json";
33993
34877
  function findRepoRoot(start = process.cwd()) {
33994
34878
  let dir = resolve15(start);
33995
34879
  for (; ; ) {
33996
- if (existsSync12(join22(dir, "apps", "server", "package.json")) && existsSync12(join22(dir, "pnpm-workspace.yaml"))) return dir;
34880
+ if (existsSync12(join23(dir, "apps", "server", "package.json")) && existsSync12(join23(dir, "pnpm-workspace.yaml"))) return dir;
33997
34881
  const parent = dirname13(dir);
33998
34882
  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
34883
  dir = parent;
34000
34884
  }
34001
34885
  }
34002
34886
  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 };
34887
+ const root4 = join23(repo, ".agentdock", "dev");
34888
+ 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
34889
  }
34006
- var shimDir = (sandbox) => join22(sandbox.root, "bin");
34890
+ var shimDir = (sandbox) => join23(sandbox.root, "bin");
34007
34891
  function sandboxEnv(sandbox, base = process.env) {
34008
34892
  const env = {
34009
34893
  ...base,
@@ -34026,7 +34910,7 @@ function writeCliShim(sandbox, node = process.execPath) {
34026
34910
  if (process.platform === "win32") return;
34027
34911
  const dir = shimDir(sandbox);
34028
34912
  mkdirSync6(dir, { recursive: true });
34029
- const file = join22(dir, "agent-dock");
34913
+ const file = join23(dir, "agent-dock");
34030
34914
  writeFileSync5(file, `#!/bin/sh
34031
34915
  exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
34032
34916
  `);
@@ -34034,7 +34918,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
34034
34918
  }
34035
34919
  function readSandbox(repo) {
34036
34920
  try {
34037
- return JSON.parse(readFileSync13(join22(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
34921
+ return JSON.parse(readFileSync13(join23(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
34038
34922
  } catch {
34039
34923
  return void 0;
34040
34924
  }
@@ -34061,7 +34945,7 @@ async function devUp(options = {}) {
34061
34945
  const sandbox = sandboxPaths(repo, port);
34062
34946
  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
34947
  for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
34064
- writeFileSync5(join22(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
34948
+ writeFileSync5(join23(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
34065
34949
  `);
34066
34950
  writeCliShim(sandbox);
34067
34951
  const run2 = options.run ?? defaultRun;
@@ -34273,6 +35157,111 @@ var runScheduleResume = (id, options = {}) => control(id, "resume", options);
34273
35157
  var runScheduleRun = (id, options = {}) => control(id, "run", options);
34274
35158
  var runScheduleRemove = (id, options = {}) => control(id, "remove", options);
34275
35159
 
35160
+ // src/usage-cli.ts
35161
+ init_session_cli();
35162
+ function localDateString(date) {
35163
+ const y = date.getFullYear();
35164
+ const m = String(date.getMonth() + 1).padStart(2, "0");
35165
+ const d = String(date.getDate()).padStart(2, "0");
35166
+ return `${y}-${m}-${d}`;
35167
+ }
35168
+ function resolveUsageFromOption(raw, now2 = /* @__PURE__ */ new Date()) {
35169
+ const trimmed = raw?.trim();
35170
+ if (!trimmed) return void 0;
35171
+ const lower = trimmed.toLowerCase();
35172
+ if (lower === "today") return localDateString(now2);
35173
+ const rel = /^(\d+)d$/.exec(lower);
35174
+ if (rel) {
35175
+ const days = Math.max(1, Number(rel[1]));
35176
+ const start = new Date(now2.getFullYear(), now2.getMonth(), now2.getDate() - (days - 1));
35177
+ return localDateString(start);
35178
+ }
35179
+ return trimmed;
35180
+ }
35181
+ function buildUsageSearchParams(options, extra) {
35182
+ const params = new URLSearchParams();
35183
+ const from = resolveUsageFromOption(options.from);
35184
+ if (from) params.set("from", from);
35185
+ if (options.to?.trim()) params.set("to", options.to.trim());
35186
+ if (options.agent?.trim()) params.set("agentId", options.agent.trim());
35187
+ if (options.project?.trim()) params.set("project", options.project.trim());
35188
+ if (options.session?.trim()) params.set("sessionId", options.session.trim());
35189
+ if (options.model?.trim()) params.set("model", options.model.trim());
35190
+ if (extra) {
35191
+ for (const [key, value] of Object.entries(extra)) {
35192
+ if (value?.trim()) params.set(key, value.trim());
35193
+ }
35194
+ }
35195
+ const qs = params.toString();
35196
+ return qs ? `?${qs}` : "";
35197
+ }
35198
+ function fmtTokens(value) {
35199
+ if (value >= 1e6) return `${(value / 1e6).toFixed(2)}M`;
35200
+ if (value >= 1e3) return `${(value / 1e3).toFixed(1)}k`;
35201
+ return String(value);
35202
+ }
35203
+ function fmtTps(tps) {
35204
+ return tps !== null && tps !== void 0 ? `${tps.toFixed(1)} tok/s` : "\u2014";
35205
+ }
35206
+ function fmtCost(costUsd) {
35207
+ if (!costUsd || costUsd <= 0) return "\u2014";
35208
+ return `$${costUsd.toFixed(costUsd >= 1 ? 2 : 4)}`;
35209
+ }
35210
+ async function runUsageSummary(options = {}) {
35211
+ const state = requireDaemon(options.daemonDir);
35212
+ const qs = buildUsageSearchParams(options);
35213
+ const data = await callDaemon(state, `/api/usage/summary${qs}`, "GET");
35214
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35215
+ `;
35216
+ const t = data.totals;
35217
+ const lines = [
35218
+ `\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`,
35219
+ `\u901F\u5EA6/\u8D39\u7528: \u5E73\u5747 ${fmtTps(t.avgTps)} \xB7 \u8D39\u7528 ${fmtCost(t.costUsd)} \xB7 ${t.turnCount} \u8F6E / ${t.sessionCount} \u4E2A\u4F1A\u8BDD`
35220
+ ];
35221
+ if (data.daily.length) {
35222
+ lines.push("\u6309\u65E5\u660E\u7EC6:");
35223
+ for (const day of data.daily) {
35224
+ lines.push(` ${day.date} ${fmtTokens(day.totalTokens)} tok (${day.turnCount} \u8F6E \xB7 ${fmtTps(day.avgTps)}${day.costUsd > 0 ? ` \xB7 ${fmtCost(day.costUsd)}` : ""})`);
35225
+ }
35226
+ }
35227
+ return `${lines.join("\n")}
35228
+ `;
35229
+ }
35230
+ async function runUsageBreakdown(options = {}) {
35231
+ const by = options.by?.trim() || "project";
35232
+ if (!["project", "agent", "session", "model"].includes(by)) {
35233
+ throw new Error("--by \u5FC5\u987B\u662F project\u3001agent\u3001session \u6216 model\u3002");
35234
+ }
35235
+ const state = requireDaemon(options.daemonDir);
35236
+ const qs = buildUsageSearchParams(options, { groupBy: by, limit: options.limit });
35237
+ const data = await callDaemon(state, `/api/usage/breakdown${qs}`, "GET");
35238
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35239
+ `;
35240
+ if (!data.items.length) return "\u5F53\u524D\u7B5B\u9009\u8303\u56F4\u5185\u6CA1\u6709\u771F\u5B9E\u6D88\u8017\u8BB0\u5F55\u3002\n";
35241
+ const lines = data.items.map((item, idx) => {
35242
+ const t = item.totals;
35243
+ return `${idx + 1}. ${item.label}${item.sublabel && item.sublabel !== item.label ? ` (${item.sublabel})` : ""}
35244
+ ${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)}` : ""}`;
35245
+ });
35246
+ return `${lines.join("\n")}
35247
+ `;
35248
+ }
35249
+ async function runUsageSession(sessionId, options = {}) {
35250
+ const targetId = sessionId?.trim() || sourceSessionId(void 0);
35251
+ const state = requireDaemon(options.daemonDir);
35252
+ const data = await callDaemon(state, `/api/sessions/${encodeURIComponent(targetId)}/usage`, "GET");
35253
+ if (options.json) return `${JSON.stringify(data, null, 2)}
35254
+ `;
35255
+ const t = data.totals;
35256
+ const lines = [
35257
+ `\u4F1A\u8BDD ${data.sessionId}${data.agentId ? ` (${data.agentId})` : ""}`,
35258
+ `\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`,
35259
+ `\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`
35260
+ ];
35261
+ return `${lines.join("\n")}
35262
+ `;
35263
+ }
35264
+
34276
35265
  // src/assistant/cli.ts
34277
35266
  init_session_cli();
34278
35267
  import { readFileSync as readFileSync14 } from "node:fs";
@@ -35676,7 +36665,7 @@ async function serve(options, onReady) {
35676
36665
  async function restartWithInstalledCli(entrypoint) {
35677
36666
  if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
35678
36667
  const previousPid = daemonStatus().pid;
35679
- const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
36668
+ const child = spawn14(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
35680
36669
  await new Promise((resolve17, reject2) => {
35681
36670
  child.once("error", reject2);
35682
36671
  child.once("exit", (code) => code === 0 ? resolve17() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
@@ -36018,6 +37007,15 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
36018
37007
  },
36019
37008
  draftDiscard: async (id, options) => {
36020
37009
  process.stdout.write(await runDraftDiscard(id, options));
37010
+ },
37011
+ usageSummary: async (options) => {
37012
+ process.stdout.write(await runUsageSummary(options));
37013
+ },
37014
+ usageBreakdown: async (options) => {
37015
+ process.stdout.write(await runUsageBreakdown(options));
37016
+ },
37017
+ usageSession: async (sessionId, options) => {
37018
+ process.stdout.write(await runUsageSession(sessionId, options));
36021
37019
  }
36022
37020
  });
36023
37021
  await program.parseAsync();