@agent-dock/cli 0.3.16 → 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 +1152 -114
- package/dist/cli.js.map +4 -4
- package/package.json +1 -1
- package/public/assets/{ImageLightbox-BRhFNVMj.js → ImageLightbox-CMWUKqZT.js} +1 -1
- package/public/assets/{PromptEditor-BE2x7r9R.js → PromptEditor-BG3-xcV2.js} +1 -1
- package/public/assets/index-CjxH5qGO.css +1 -0
- package/public/assets/{main-Bpox_eUq.js → main-BK1MsO-r.js} +287 -277
- package/public/assets/{sourcesRouter-DJG5qPtX.js → sourcesRouter-0alkUGCE.js} +1 -1
- package/public/index.html +3 -3
- package/public/sources-router.html +3 -3
- package/public/assets/index-Qk8aqJbd.css +0 -1
- /package/public/assets/{index-CB32HX8U.js → index-DmdDXpGt.js} +0 -0
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:
|
|
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:
|
|
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
|
});
|
|
@@ -738,6 +1138,14 @@ function pickFinalAssistantEntry(entries) {
|
|
|
738
1138
|
const picked = folded[index];
|
|
739
1139
|
return picked.origin ?? picked;
|
|
740
1140
|
}
|
|
1141
|
+
function isAgentAuthErrorText(text3, pattern) {
|
|
1142
|
+
if (!pattern) return false;
|
|
1143
|
+
try {
|
|
1144
|
+
return new RegExp(pattern, "i").test(text3);
|
|
1145
|
+
} catch {
|
|
1146
|
+
return false;
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
741
1149
|
function stripAgentStreamErrorSuffix(text3) {
|
|
742
1150
|
return agentStreamErrorSuffix.test(text3) ? text3.replace(agentStreamErrorSuffix, "").trimEnd() : text3;
|
|
743
1151
|
}
|
|
@@ -781,7 +1189,7 @@ function pickFinalAssistantText(entries) {
|
|
|
781
1189
|
const text3 = index >= 0 ? folded[index]?.data?.text : void 0;
|
|
782
1190
|
return typeof text3 === "string" ? text3 : "";
|
|
783
1191
|
}
|
|
784
|
-
var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText;
|
|
1192
|
+
var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText, antigravityAuthErrorPattern;
|
|
785
1193
|
var init_turn_outcome = __esm({
|
|
786
1194
|
"../../packages/shared/src/turn-outcome.ts"() {
|
|
787
1195
|
"use strict";
|
|
@@ -797,6 +1205,7 @@ var init_turn_outcome = __esm({
|
|
|
797
1205
|
agentStreamErrorPrefix = /^\s*Error:\s*(?:RetriableError|T):/i;
|
|
798
1206
|
agentStreamErrorSuffix = /(?:\r?\n){1,2}Error:\s*(?:RetriableError|T):[^\n]*\s*$/i;
|
|
799
1207
|
isAgentStreamErrorText = (text3) => agentStreamErrorPrefix.test(text3);
|
|
1208
|
+
antigravityAuthErrorPattern = "^\\s*(?:\u26A0\\s*)?UNAUTHENTICATED\\s*\\(code\\s+401\\)";
|
|
800
1209
|
}
|
|
801
1210
|
});
|
|
802
1211
|
|
|
@@ -934,7 +1343,11 @@ var init_src2 = __esm({
|
|
|
934
1343
|
capabilities: z.object({ pause: z.boolean().default(false), resume: z.boolean().default(true) }).default({ pause: false, resume: true }),
|
|
935
1344
|
builtin: z.boolean().default(false),
|
|
936
1345
|
// 可选以保持既有 AgentConfig 字面量与行 JSON 兼容;读取方一律按 undefined === false 处理。
|
|
937
|
-
disabled: z.boolean().optional()
|
|
1346
|
+
disabled: z.boolean().optional(),
|
|
1347
|
+
/** 空闲驱动回收阈值(毫秒);未设置时回落到 runtime 全局默认值,0 表示不按空闲回收。 */
|
|
1348
|
+
idleTimeoutMs: z.number().nonnegative().optional(),
|
|
1349
|
+
/** 认证失效错误匹配正则;命中时驱逐旧驱动并重连重试一次,仍失败则判 failed。 */
|
|
1350
|
+
authErrorPattern: z.string().optional()
|
|
938
1351
|
});
|
|
939
1352
|
RuntimeError = class extends Error {
|
|
940
1353
|
constructor(code, message, statusCode = 400) {
|
|
@@ -2119,8 +2532,8 @@ var init_service = __esm({
|
|
|
2119
2532
|
return { name, ...avatarUrl ? { avatarUrl } : {} };
|
|
2120
2533
|
}
|
|
2121
2534
|
async getUserName(openId) {
|
|
2122
|
-
const
|
|
2123
|
-
if (
|
|
2535
|
+
const cached5 = this.userNameCache.get(openId);
|
|
2536
|
+
if (cached5 && cached5.expiresAt > Date.now()) return cached5.name;
|
|
2124
2537
|
const payload = await this.request(`/open-apis/contact/v3/users/${encodeURIComponent(required(openId, "openId"))}?user_id_type=open_id`, { method: "GET", timeoutMs: 3e3 });
|
|
2125
2538
|
const name = String(payload.data?.user?.name ?? "").trim();
|
|
2126
2539
|
const ttl = name ? userNameCacheTtlMs : emptyUserNameCacheTtlMs;
|
|
@@ -2950,16 +3363,16 @@ var init_agent_tools = __esm({
|
|
|
2950
3363
|
injectedPrompts = /* @__PURE__ */ new Map();
|
|
2951
3364
|
pollIntervalMs;
|
|
2952
3365
|
clientFor(config) {
|
|
2953
|
-
const
|
|
2954
|
-
if (
|
|
3366
|
+
const cached5 = this.clients.get(config.appId);
|
|
3367
|
+
if (cached5?.secret === config.appSecret) return cached5.client;
|
|
2955
3368
|
const client2 = this.options.clientFactory?.(config) ?? createLarkCardService(this.options.env ?? process.env, this.options.fetcher ?? globalThis.fetch, { appId: config.appId, appSecret: config.appSecret });
|
|
2956
3369
|
this.clients.set(config.appId, { secret: config.appSecret, client: client2 });
|
|
2957
3370
|
this.identities.delete(config.appId);
|
|
2958
3371
|
return client2;
|
|
2959
3372
|
}
|
|
2960
3373
|
identityFor(config) {
|
|
2961
|
-
const
|
|
2962
|
-
if (
|
|
3374
|
+
const cached5 = this.identities.get(config.appId);
|
|
3375
|
+
if (cached5?.secret === config.appSecret) return cached5.info;
|
|
2963
3376
|
const info = this.clientFor(config).getBotInfo();
|
|
2964
3377
|
this.identities.set(config.appId, { secret: config.appSecret, info });
|
|
2965
3378
|
void info.catch(() => {
|
|
@@ -3593,7 +4006,7 @@ __export(listener_exports, {
|
|
|
3593
4006
|
import { createHash as createHash3 } from "node:crypto";
|
|
3594
4007
|
import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
|
|
3595
4008
|
import { tmpdir } from "node:os";
|
|
3596
|
-
import { basename as
|
|
4009
|
+
import { basename as basename4, join as join9 } from "node:path";
|
|
3597
4010
|
function parseLarkReactionEvent(raw) {
|
|
3598
4011
|
if (!raw || typeof raw !== "object") return void 0;
|
|
3599
4012
|
const event = raw;
|
|
@@ -3955,7 +4368,7 @@ var init_listener = __esm({
|
|
|
3955
4368
|
};
|
|
3956
4369
|
safeResourceName = (resource, contentType) => {
|
|
3957
4370
|
const hash2 = createHash3("sha256").update(`${resource.type}:${resource.key}`).digest("hex").slice(0, 12);
|
|
3958
|
-
const supplied = resource.fileName ?
|
|
4371
|
+
const supplied = resource.fileName ? basename4(resource.fileName).replace(/[^\p{L}\p{N}._ -]/gu, "_").slice(0, 120) : "";
|
|
3959
4372
|
return supplied ? `${hash2}-${supplied}` : `${resource.type}-${hash2}${resourceExtensions[contentType ?? ""] ?? ""}`;
|
|
3960
4373
|
};
|
|
3961
4374
|
resourceFailureGuidance = (error) => {
|
|
@@ -6023,13 +6436,13 @@ __export(session_cli_exports, {
|
|
|
6023
6436
|
streamSessionShow: () => streamSessionShow
|
|
6024
6437
|
});
|
|
6025
6438
|
import { existsSync as existsSync10 } from "node:fs";
|
|
6026
|
-
import { join as
|
|
6439
|
+
import { join as join22, resolve as resolve12 } from "node:path";
|
|
6027
6440
|
function resolveDatabasePath(explicit, cwd = process.cwd()) {
|
|
6028
6441
|
if (explicit) return resolve12(cwd, explicit);
|
|
6029
6442
|
if (process.env.AGENTDOCK_DATABASE_URL) return resolve12(cwd, process.env.AGENTDOCK_DATABASE_URL);
|
|
6030
6443
|
const daemonDir = resolveDaemonDir(cwd);
|
|
6031
6444
|
const recorded = readDaemonStatus(daemonDir)?.database;
|
|
6032
|
-
return recorded ? resolve12(daemonDir, recorded) :
|
|
6445
|
+
return recorded ? resolve12(daemonDir, recorded) : join22(daemonDir, "..", "agentdock.db");
|
|
6033
6446
|
}
|
|
6034
6447
|
function sessionPeerIds(sessions2, sourceId2) {
|
|
6035
6448
|
const source2 = sessions2.find((session) => session.id === sourceId2);
|
|
@@ -6279,7 +6692,7 @@ var AutostartService = class {
|
|
|
6279
6692
|
// src/cli.ts
|
|
6280
6693
|
init_src();
|
|
6281
6694
|
import { existsSync as existsSync13, readFileSync as readFileSync16 } from "node:fs";
|
|
6282
|
-
import { spawn as
|
|
6695
|
+
import { spawn as spawn14 } from "node:child_process";
|
|
6283
6696
|
import { loadEnvFile } from "node:process";
|
|
6284
6697
|
import { fileURLToPath as fileURLToPath6 } from "node:url";
|
|
6285
6698
|
|
|
@@ -6504,6 +6917,17 @@ Changes take effect immediately; no restart needed.`);
|
|
|
6504
6917
|
addProcessCommands(program);
|
|
6505
6918
|
const daemon3 = program.command("daemon").description("Run the AgentDock server in the background and manage it");
|
|
6506
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
|
+
});
|
|
6507
6931
|
return program.addHelpText("after", `
|
|
6508
6932
|
Examples:
|
|
6509
6933
|
$ agent-dock
|
|
@@ -6719,7 +7143,7 @@ var KeepAwakeService = class {
|
|
|
6719
7143
|
// ../../packages/agent-runtime/src/index.ts
|
|
6720
7144
|
import { EventEmitter } from "node:events";
|
|
6721
7145
|
import { createHash as createHash2 } from "node:crypto";
|
|
6722
|
-
import { basename as
|
|
7146
|
+
import { basename as basename3 } from "node:path";
|
|
6723
7147
|
|
|
6724
7148
|
// ../../packages/agent-runtime/src/project-path.ts
|
|
6725
7149
|
init_src2();
|
|
@@ -6742,9 +7166,9 @@ async function resolveProjectPath(raw, options = {}) {
|
|
|
6742
7166
|
if (!isAbsolute(expanded)) {
|
|
6743
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);
|
|
6744
7168
|
}
|
|
6745
|
-
let
|
|
7169
|
+
let real2;
|
|
6746
7170
|
try {
|
|
6747
|
-
|
|
7171
|
+
real2 = await fs5.realpath(resolve2(expanded));
|
|
6748
7172
|
} catch (error) {
|
|
6749
7173
|
const code = errorCode2(error);
|
|
6750
7174
|
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
@@ -6754,7 +7178,7 @@ async function resolveProjectPath(raw, options = {}) {
|
|
|
6754
7178
|
}
|
|
6755
7179
|
let info;
|
|
6756
7180
|
try {
|
|
6757
|
-
info = await fs5.stat(
|
|
7181
|
+
info = await fs5.stat(real2);
|
|
6758
7182
|
} catch (error) {
|
|
6759
7183
|
const code = errorCode2(error);
|
|
6760
7184
|
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
@@ -6766,16 +7190,16 @@ async function resolveProjectPath(raw, options = {}) {
|
|
|
6766
7190
|
throw new RuntimeError("PROJECT_PATH_NOT_DIRECTORY", `\u8BE5\u8DEF\u5F84\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${text3}`, 400);
|
|
6767
7191
|
}
|
|
6768
7192
|
try {
|
|
6769
|
-
await fs5.access(
|
|
7193
|
+
await fs5.access(real2, constants.R_OK);
|
|
6770
7194
|
} catch {
|
|
6771
7195
|
throw new RuntimeError("PROJECT_PATH_NOT_READABLE", `\u6CA1\u6709\u8BFB\u53D6\u6743\u9650\uFF1A${text3}`, 400);
|
|
6772
7196
|
}
|
|
6773
7197
|
try {
|
|
6774
|
-
await fs5.access(
|
|
7198
|
+
await fs5.access(real2, constants.W_OK);
|
|
6775
7199
|
} catch {
|
|
6776
7200
|
throw new RuntimeError("PROJECT_PATH_NOT_WRITABLE", `\u6CA1\u6709\u5199\u5165\u6743\u9650\uFF1A${text3}`, 400);
|
|
6777
7201
|
}
|
|
6778
|
-
return
|
|
7202
|
+
return real2;
|
|
6779
7203
|
}
|
|
6780
7204
|
|
|
6781
7205
|
// ../../packages/agent-runtime/src/index.ts
|
|
@@ -8966,15 +9390,15 @@ async function readLinuxProcessTable(timeoutMs, requiredPids, pid) {
|
|
|
8966
9390
|
const clockTicksPerSecond = linuxClockTicks(raw);
|
|
8967
9391
|
const table = /* @__PURE__ */ new Map();
|
|
8968
9392
|
for (const value of raw.processStats) {
|
|
8969
|
-
const
|
|
8970
|
-
if (
|
|
8971
|
-
pid:
|
|
8972
|
-
parentPid:
|
|
8973
|
-
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,
|
|
8974
9398
|
birth: {
|
|
8975
9399
|
kind: "linux-proc",
|
|
8976
9400
|
...scope,
|
|
8977
|
-
startTicks:
|
|
9401
|
+
startTicks: stat7.startTicks
|
|
8978
9402
|
},
|
|
8979
9403
|
clockTicksPerSecond
|
|
8980
9404
|
});
|
|
@@ -10062,8 +10486,8 @@ function buildAuthEnvKey(methodId) {
|
|
|
10062
10486
|
}
|
|
10063
10487
|
var authEnvKeyCache = /* @__PURE__ */ new Map();
|
|
10064
10488
|
function authEnvKey(methodId) {
|
|
10065
|
-
const
|
|
10066
|
-
if (
|
|
10489
|
+
const cached5 = authEnvKeyCache.get(methodId);
|
|
10490
|
+
if (cached5 !== void 0) return cached5;
|
|
10067
10491
|
const key = buildAuthEnvKey(methodId);
|
|
10068
10492
|
authEnvKeyCache.set(methodId, key);
|
|
10069
10493
|
return key;
|
|
@@ -17389,10 +17813,77 @@ var AcpxAdapter = class {
|
|
|
17389
17813
|
this.reportedTitle = title;
|
|
17390
17814
|
this.options.onEvent({ type: "session_title", data: { title } });
|
|
17391
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
|
+
}
|
|
17392
17870
|
async sendTurn(prompt) {
|
|
17393
17871
|
if (!this.handle) await this.start();
|
|
17394
17872
|
await this.applyCodexPermissionMode();
|
|
17395
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
|
+
};
|
|
17396
17887
|
const { idle: idleTimeoutMs, toolCall: toolCallTimeoutMs } = resolveTurnTimeouts(this.agent.timeout);
|
|
17397
17888
|
const turn = this.runtime.startTurn({ handle: this.handle, text: prompt, mode: "prompt", requestId, timeoutMs: 0 });
|
|
17398
17889
|
this.turn = turn;
|
|
@@ -17420,19 +17911,32 @@ var AcpxAdapter = class {
|
|
|
17420
17911
|
if (next.done) break;
|
|
17421
17912
|
const normalized2 = normalizeAcpxEvent(next.value);
|
|
17422
17913
|
if (normalized2) {
|
|
17914
|
+
const eventAt = Date.now();
|
|
17423
17915
|
const toolCallId = typeof normalized2.data?.id === "string" ? normalized2.data.id : void 0;
|
|
17424
17916
|
if (normalized2.type === "tool_call") {
|
|
17917
|
+
if (activeToolCallIds.size === 0) closeOutputSegment(eventAt);
|
|
17425
17918
|
if (toolCallId) activeToolCallIds.add(toolCallId);
|
|
17426
17919
|
} else if (normalized2.type === "tool_result") {
|
|
17427
17920
|
if (toolCallId) activeToolCallIds.delete(toolCallId);
|
|
17428
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;
|
|
17429
17925
|
}
|
|
17430
17926
|
this.options.onEvent(normalized2);
|
|
17431
17927
|
}
|
|
17432
17928
|
}
|
|
17929
|
+
const streamEndedAt = Date.now();
|
|
17930
|
+
closeOutputSegment(streamEndedAt);
|
|
17433
17931
|
const result = await turn.result;
|
|
17434
17932
|
if (result.status === "failed") throw new Error(result.error.message);
|
|
17933
|
+
const finishedAt = Date.now();
|
|
17435
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
|
+
});
|
|
17436
17940
|
this.options.onEvent({ type: "completed", data: { stopReason: result.stopReason ?? result.status } });
|
|
17437
17941
|
} finally {
|
|
17438
17942
|
if (this.turn === turn) this.turn = void 0;
|
|
@@ -17870,13 +18374,13 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
17870
18374
|
const range = await this.repos.events.turnRange(sessionId, taskId);
|
|
17871
18375
|
return range ? this.repos.events.listRange(sessionId, { after: range.startSequence, before: range.endSequence }) : [];
|
|
17872
18376
|
}
|
|
17873
|
-
async resolveTaskOutcome(session, task) {
|
|
18377
|
+
async resolveTaskOutcome(session, task, afterSequence = this.turnAnchors.get(task.id)) {
|
|
17874
18378
|
const stopReason = this.driverStopReasons.get(session.id);
|
|
17875
18379
|
if (this.interruptedTurns.has(session.id) || stopReason === "cancelled") return { status: "interrupted", stopReason };
|
|
17876
18380
|
if (_AgentDockRuntime.isTruncatedStopReason(stopReason)) {
|
|
17877
18381
|
return { status: "failed", stopReason, message: `\u8F93\u51FA\u56E0\u8FBE\u5230 token \u4E0A\u9650\u88AB\u622A\u65AD\uFF08stopReason: ${stopReason}\uFF09\uFF0C\u672A\u4EA7\u751F\u5B8C\u6574\u6700\u7EC8\u8F93\u51FA` };
|
|
17878
18382
|
}
|
|
17879
|
-
const turnEvents = await this.turnEventsFor(session.id, task.id,
|
|
18383
|
+
const turnEvents = await this.turnEventsFor(session.id, task.id, afterSequence);
|
|
17880
18384
|
const finalText = pickFinalAssistantText(turnEvents);
|
|
17881
18385
|
if (unresolvedToolCallsAfterAnswer(turnEvents).length) {
|
|
17882
18386
|
return { status: "failed", stopReason, message: "Agent \u5B58\u5728\u672A\u8FD4\u56DE\u7ED3\u679C\u7684\u5DE5\u5177\u8C03\u7528\uFF0C\u672C\u8F6E\u4EFB\u52A1\u672A\u6B63\u5E38\u7ED3\u675F", finalText };
|
|
@@ -17884,6 +18388,10 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
17884
18388
|
if (!finalText) {
|
|
17885
18389
|
return { status: "failed", stopReason, message: "Agent \u672A\u8FD4\u56DE\u6700\u7EC8\u8F93\u51FA", finalText };
|
|
17886
18390
|
}
|
|
18391
|
+
const agent = await this.repos.agents.get(session.agentId);
|
|
18392
|
+
if (agent?.authErrorPattern && isAgentAuthErrorText(finalText, agent.authErrorPattern)) {
|
|
18393
|
+
return { status: "failed", stopReason, message: `${agent.name} \u8BA4\u8BC1\u5DF2\u5931\u6548\uFF08401 UNAUTHENTICATED\uFF09\uFF0C\u8BF7\u91CD\u65B0\u8BA4\u8BC1\u540E\u91CD\u8BD5`, authError: true, finalText };
|
|
18394
|
+
}
|
|
17887
18395
|
return { status: "completed", stopReason, finalText };
|
|
17888
18396
|
}
|
|
17889
18397
|
onDriverEvent(session) {
|
|
@@ -18029,6 +18537,18 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18029
18537
|
listProjects() {
|
|
18030
18538
|
return this.repos.projects.list();
|
|
18031
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
|
+
}
|
|
18032
18552
|
/**
|
|
18033
18553
|
* 登记用户导入的项目。路径统一 realpath(`~` 展开、相对路径拒绝、macOS /private 别名归一),
|
|
18034
18554
|
* 已存在则原样返回并标记 created=false,前端可据此提示「已存在」而不是造出第二条。
|
|
@@ -18041,7 +18561,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18041
18561
|
const project = {
|
|
18042
18562
|
id: `local:${cwd}`,
|
|
18043
18563
|
machineId: "local",
|
|
18044
|
-
name:
|
|
18564
|
+
name: basename3(cwd) || cwd,
|
|
18045
18565
|
cwd,
|
|
18046
18566
|
pinnedAt: null,
|
|
18047
18567
|
createdAt: time2,
|
|
@@ -18318,6 +18838,57 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18318
18838
|
await this.setAgentTitle(session, typeof event.data?.title === "string" ? event.data.title : void 0);
|
|
18319
18839
|
return;
|
|
18320
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
|
+
}
|
|
18321
18892
|
let data = event.data;
|
|
18322
18893
|
if (event.type === "tool_call" || event.type === "tool_result") {
|
|
18323
18894
|
const completed = data.status === "completed" || data.status === "failed";
|
|
@@ -18424,6 +18995,21 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18424
18995
|
await mkdir(directory, { recursive: true });
|
|
18425
18996
|
await writeFile(join7(directory, `${session.id}.json`), JSON.stringify(policy ?? { enabled: false }), { mode: 384 });
|
|
18426
18997
|
}
|
|
18998
|
+
async evictDriver(sessionId, driver) {
|
|
18999
|
+
try {
|
|
19000
|
+
await driver.stop();
|
|
19001
|
+
} catch {
|
|
19002
|
+
} finally {
|
|
19003
|
+
if (this.drivers.get(sessionId) === driver) this.drivers.delete(sessionId);
|
|
19004
|
+
}
|
|
19005
|
+
}
|
|
19006
|
+
async executeTurnAndResolve(id, session, task, driver, prompt, afterSequence) {
|
|
19007
|
+
this.driverStopReasons.delete(id);
|
|
19008
|
+
await driver.send(prompt);
|
|
19009
|
+
await this.flushDriverEvents(id);
|
|
19010
|
+
await this.flushStream(id);
|
|
19011
|
+
return this.resolveTaskOutcome(session, task, afterSequence);
|
|
19012
|
+
}
|
|
18427
19013
|
async runTask(id, task, agentPrompt = task.prompt, riskPolicy) {
|
|
18428
19014
|
const { session } = await this.active(id);
|
|
18429
19015
|
if (["stopped", "failed"].includes(session.state)) throw new RuntimeError("INVALID_STATE", `Cannot send while session is ${session.state}`, 409);
|
|
@@ -18454,11 +19040,14 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18454
19040
|
const resolvedAgentPrompt = await this.options.sessionPrompt?.(session, agentPrompt, task.origin ?? void 0) ?? agentPrompt;
|
|
18455
19041
|
task.sentPrompt = resolvedAgentPrompt;
|
|
18456
19042
|
await this.repos.tasks.save(task);
|
|
18457
|
-
this.
|
|
18458
|
-
|
|
18459
|
-
|
|
18460
|
-
|
|
18461
|
-
|
|
19043
|
+
let outcome = await this.executeTurnAndResolve(id, session, task, driver, resolvedAgentPrompt);
|
|
19044
|
+
if (outcome.status === "failed" && outcome.authError) {
|
|
19045
|
+
const retryAfterSequence = this.sequences.get(id);
|
|
19046
|
+
await this.evictDriver(id, driver);
|
|
19047
|
+
driver = await this.reconnect(session);
|
|
19048
|
+
if (riskPolicy) await this.applyRiskPolicy(session, driver, riskPolicy);
|
|
19049
|
+
outcome = await this.executeTurnAndResolve(id, session, task, driver, resolvedAgentPrompt, retryAfterSequence);
|
|
19050
|
+
}
|
|
18462
19051
|
task.finalText = outcome.finalText;
|
|
18463
19052
|
session.lastMessageAt = now();
|
|
18464
19053
|
if (outcome.status === "interrupted") {
|
|
@@ -18904,12 +19493,15 @@ var AgentDockRuntime = class _AgentDockRuntime {
|
|
|
18904
19493
|
for (const key of this.permissions.keys()) if (key.startsWith(`${sessionId}:`)) this.permissions.delete(key);
|
|
18905
19494
|
}
|
|
18906
19495
|
async cleanupIdleDriversOnce(at) {
|
|
18907
|
-
|
|
18908
|
-
|
|
19496
|
+
if (!this.drivers.size) return;
|
|
19497
|
+
const defaultTimeout = this.options.driverIdleTimeoutMs ?? 6 * 60 * 6e4;
|
|
19498
|
+
const agentsById = new Map((await this.repos.agents.list()).map((agent) => [agent.id, agent]));
|
|
18909
19499
|
for (const [sessionId, driver] of this.drivers) {
|
|
18910
|
-
if (this.activeTurns.has(sessionId)
|
|
19500
|
+
if (this.activeTurns.has(sessionId)) continue;
|
|
18911
19501
|
const session = await this.repos.sessions.get(sessionId);
|
|
18912
19502
|
if (!session || !["idle", "completed", "interrupted"].includes(session.state)) continue;
|
|
19503
|
+
const timeout = agentsById.get(session.agentId)?.idleTimeoutMs ?? defaultTimeout;
|
|
19504
|
+
if (timeout <= 0 || at - (this.lastActivity.get(sessionId) ?? at) < timeout) continue;
|
|
18913
19505
|
try {
|
|
18914
19506
|
await driver.stop();
|
|
18915
19507
|
} catch {
|
|
@@ -18997,7 +19589,7 @@ var agentDetails = {
|
|
|
18997
19589
|
qwen: { name: "Qwen Code", cli: "qwen" },
|
|
18998
19590
|
trae: { name: "Trae", cli: "traecli" },
|
|
18999
19591
|
zeroclaw: { name: "ZeroClaw", cli: "zeroclaw" },
|
|
19000
|
-
antigravity: { name: "Google Antigravity", cli: ["agy", "antigravity"], argvExecutable: true }
|
|
19592
|
+
antigravity: { name: "Google Antigravity", cli: ["agy", "antigravity"], argvExecutable: true, idleTimeoutMs: 15 * 6e4, authErrorPattern: antigravityAuthErrorPattern }
|
|
19001
19593
|
};
|
|
19002
19594
|
function cliVersion(command, prefixArgs = []) {
|
|
19003
19595
|
for (const args of [["--version"], ["-V"], ["version"]]) {
|
|
@@ -19029,7 +19621,9 @@ function discoverBuiltinAgents(entries = listAcpxBuiltinAgents(), dependencies =
|
|
|
19029
19621
|
timeout: 600,
|
|
19030
19622
|
capabilities: { pause: false, resume: true },
|
|
19031
19623
|
builtin: true,
|
|
19032
|
-
version: id === "antigravity" ? version(argv[0]) : id === "codex" ? version(argv[0], argv.slice(1)) : version(commands[0])
|
|
19624
|
+
version: id === "antigravity" ? version(argv[0]) : id === "codex" ? version(argv[0], argv.slice(1)) : version(commands[0]),
|
|
19625
|
+
...detail.idleTimeoutMs !== void 0 ? { idleTimeoutMs: detail.idleTimeoutMs } : {},
|
|
19626
|
+
...detail.authErrorPattern !== void 0 ? { authErrorPattern: detail.authErrorPattern } : {}
|
|
19033
19627
|
}];
|
|
19034
19628
|
});
|
|
19035
19629
|
}
|
|
@@ -19351,9 +19945,9 @@ function registerSelfUpdateRoutes(app, service) {
|
|
|
19351
19945
|
init_src2();
|
|
19352
19946
|
import Fastify from "fastify";
|
|
19353
19947
|
import cors from "@fastify/cors";
|
|
19354
|
-
import { readFile as
|
|
19948
|
+
import { readFile as readFile13, mkdir as mkdir4, readdir as readdir4, rm as rm2, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
|
|
19355
19949
|
import { Readable as Readable3 } from "node:stream";
|
|
19356
|
-
import { extname as extname2, join as
|
|
19950
|
+
import { extname as extname2, join as join21, resolve as resolve10, sep as sep3 } from "node:path";
|
|
19357
19951
|
import { homedir as homedir15 } from "node:os";
|
|
19358
19952
|
import { randomBytes as randomBytes4 } from "node:crypto";
|
|
19359
19953
|
|
|
@@ -21361,8 +21955,8 @@ function agentModelsCacheKey(agent, model) {
|
|
|
21361
21955
|
var cache = /* @__PURE__ */ new Map();
|
|
21362
21956
|
async function discoverAgentModels(agent, model, forceRefresh = false) {
|
|
21363
21957
|
const cacheKey = agentModelsCacheKey(agent, model);
|
|
21364
|
-
const
|
|
21365
|
-
if (!forceRefresh &&
|
|
21958
|
+
const cached5 = cache.get(cacheKey);
|
|
21959
|
+
if (!forceRefresh && cached5 && cached5.expiresAt > Date.now()) return cached5.value;
|
|
21366
21960
|
let value;
|
|
21367
21961
|
let warning;
|
|
21368
21962
|
try {
|
|
@@ -21900,15 +22494,317 @@ async function getCursorUsage(refresh = false) {
|
|
|
21900
22494
|
return inFlight3;
|
|
21901
22495
|
}
|
|
21902
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
|
+
|
|
21903
22799
|
// src/system-routes.ts
|
|
21904
22800
|
import { execFile as execFile6 } from "node:child_process";
|
|
21905
22801
|
import { homedir as homedir11 } from "node:os";
|
|
21906
22802
|
import { promisify as promisify5 } from "node:util";
|
|
21907
22803
|
|
|
21908
22804
|
// src/skill-catalog.ts
|
|
21909
|
-
import { readFile as
|
|
22805
|
+
import { readFile as readFile10, readdir as readdir2 } from "node:fs/promises";
|
|
21910
22806
|
import { homedir as homedir10 } from "node:os";
|
|
21911
|
-
import { basename as
|
|
22807
|
+
import { basename as basename5, dirname as dirname10, join as join17, resolve as resolve8 } from "node:path";
|
|
21912
22808
|
var ignoredDirectories = /* @__PURE__ */ new Set([".git", "node_modules", "dist", "build"]);
|
|
21913
22809
|
async function findSkillFiles(root4, maxDepth = 5) {
|
|
21914
22810
|
const found = [];
|
|
@@ -21921,8 +22817,8 @@ async function findSkillFiles(root4, maxDepth = 5) {
|
|
|
21921
22817
|
return;
|
|
21922
22818
|
}
|
|
21923
22819
|
for (const entry of entries) {
|
|
21924
|
-
if (entry.isFile() && entry.name === "SKILL.md") found.push(
|
|
21925
|
-
else if (entry.isDirectory() && !ignoredDirectories.has(entry.name)) await visit(
|
|
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);
|
|
21926
22822
|
}
|
|
21927
22823
|
};
|
|
21928
22824
|
await visit(root4, 0);
|
|
@@ -21936,15 +22832,15 @@ function frontmatterValue(markdown, key) {
|
|
|
21936
22832
|
async function discoverSkills(workspace) {
|
|
21937
22833
|
const workspaceRoot = resolve8(workspace?.trim() || process.cwd());
|
|
21938
22834
|
const roots = [
|
|
21939
|
-
{ path:
|
|
21940
|
-
{ path:
|
|
21941
|
-
{ path:
|
|
21942
|
-
{ path:
|
|
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" }
|
|
21943
22839
|
];
|
|
21944
22840
|
const references = await Promise.all(roots.map(async (root4) => Promise.all((await findSkillFiles(root4.path)).map(async (path5) => {
|
|
21945
|
-
const markdown = await
|
|
22841
|
+
const markdown = await readFile10(path5, "utf8").catch(() => "");
|
|
21946
22842
|
return {
|
|
21947
|
-
name: frontmatterValue(markdown, "name") ||
|
|
22843
|
+
name: frontmatterValue(markdown, "name") || basename5(dirname10(path5)),
|
|
21948
22844
|
description: frontmatterValue(markdown, "description"),
|
|
21949
22845
|
path: path5,
|
|
21950
22846
|
source: root4.source
|
|
@@ -23060,13 +23956,13 @@ function registerTerminalWebSockets(server, runtime, options = {}) {
|
|
|
23060
23956
|
// src/fs-routes.ts
|
|
23061
23957
|
init_src2();
|
|
23062
23958
|
import { realpathSync as realpathSync3 } from "node:fs";
|
|
23063
|
-
import { readdir as readdir3, readFile as
|
|
23064
|
-
import { basename as
|
|
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";
|
|
23065
23961
|
|
|
23066
23962
|
// src/fs-paths.ts
|
|
23067
23963
|
import { existsSync as existsSync8, realpathSync as realpathSync2 } from "node:fs";
|
|
23068
23964
|
import { homedir as homedir12, tmpdir as tmpdir3 } from "node:os";
|
|
23069
|
-
import { basename as
|
|
23965
|
+
import { basename as basename6, isAbsolute as isAbsolute6, join as join18, resolve as resolve9, sep } from "node:path";
|
|
23070
23966
|
function resolveInsideRoot(root4, userPath) {
|
|
23071
23967
|
const normalized2 = (userPath ?? "").trim();
|
|
23072
23968
|
if (isAbsolute6(normalized2)) throw new WorkspacePathError("\u8DEF\u5F84\u5FC5\u987B\u662F\u76F8\u5BF9\u5DE5\u4F5C\u533A\u7684\u76F8\u5BF9\u8DEF\u5F84");
|
|
@@ -23126,7 +24022,7 @@ function isSensitivePath(targetPath) {
|
|
|
23126
24022
|
if (seg === ".aws" && segments[i + 1]?.toLowerCase() === "credentials") return true;
|
|
23127
24023
|
if (seg === ".kube" && segments[i + 1]?.toLowerCase() === "config") return true;
|
|
23128
24024
|
}
|
|
23129
|
-
const name =
|
|
24025
|
+
const name = basename6(normalized2).toLowerCase();
|
|
23130
24026
|
if (sensitiveExactNames.has(name)) return true;
|
|
23131
24027
|
if (name.startsWith(".env.")) return true;
|
|
23132
24028
|
if (sensitiveKeyPrefixPattern.test(name)) return true;
|
|
@@ -23140,12 +24036,12 @@ function allowedReadRoots(options) {
|
|
|
23140
24036
|
const candidates = [options.cwd];
|
|
23141
24037
|
if (options.role === "session") {
|
|
23142
24038
|
if (options.sessionId) {
|
|
23143
|
-
candidates.push(
|
|
24039
|
+
candidates.push(join18(home, ".agentdock", "uploads", options.sessionId));
|
|
23144
24040
|
}
|
|
23145
24041
|
} else {
|
|
23146
24042
|
candidates.push(
|
|
23147
|
-
|
|
23148
|
-
|
|
24043
|
+
join18(home, ".agentdock", "uploads"),
|
|
24044
|
+
join18(home, ".gemini"),
|
|
23149
24045
|
"/tmp",
|
|
23150
24046
|
"/private/tmp",
|
|
23151
24047
|
options.tempDir ?? tmpdir3(),
|
|
@@ -23157,10 +24053,10 @@ function allowedReadRoots(options) {
|
|
|
23157
24053
|
for (const candidate of candidates) {
|
|
23158
24054
|
if (!candidate || !existsSync8(candidate)) continue;
|
|
23159
24055
|
try {
|
|
23160
|
-
const
|
|
23161
|
-
if (!seen.has(
|
|
23162
|
-
seen.add(
|
|
23163
|
-
resolved.push(
|
|
24056
|
+
const real2 = realpathSync2(candidate);
|
|
24057
|
+
if (!seen.has(real2)) {
|
|
24058
|
+
seen.add(real2);
|
|
24059
|
+
resolved.push(real2);
|
|
23164
24060
|
}
|
|
23165
24061
|
} catch {
|
|
23166
24062
|
}
|
|
@@ -23316,7 +24212,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
|
|
|
23316
24212
|
await Promise.all(names.map(async (name) => {
|
|
23317
24213
|
if (name === "node_modules" || name === ".git" || name === ".agentdock") return;
|
|
23318
24214
|
try {
|
|
23319
|
-
const info = await
|
|
24215
|
+
const info = await stat5(`${resolved.absolute}/${name}`);
|
|
23320
24216
|
entries.push({ name, type: info.isDirectory() ? "dir" : "file", size: info.size, mtime: info.mtime.toISOString() });
|
|
23321
24217
|
} catch {
|
|
23322
24218
|
}
|
|
@@ -23376,12 +24272,12 @@ async function registerFsRoutes(app, runtime, options = {}) {
|
|
|
23376
24272
|
}
|
|
23377
24273
|
let info;
|
|
23378
24274
|
try {
|
|
23379
|
-
info = await
|
|
24275
|
+
info = await stat5(resolved.absolute);
|
|
23380
24276
|
} catch (error) {
|
|
23381
24277
|
badPath(error);
|
|
23382
24278
|
}
|
|
23383
24279
|
if (!info.isFile()) throw new RuntimeError("NOT_A_FILE", "\u76EE\u6807\u4E0D\u662F\u6587\u4EF6", 400);
|
|
23384
|
-
const filename =
|
|
24280
|
+
const filename = basename7(resolved.absolute);
|
|
23385
24281
|
const isSvg = filename.toLowerCase().endsWith(".svg");
|
|
23386
24282
|
const wantDownload = request.query.download === "1" || request.query.download === "true";
|
|
23387
24283
|
const wantText = request.query.format === "text";
|
|
@@ -23389,7 +24285,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
|
|
|
23389
24285
|
if (info.size > maxDocumentPreviewBytes) {
|
|
23390
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);
|
|
23391
24287
|
}
|
|
23392
|
-
const buffer2 = await
|
|
24288
|
+
const buffer2 = await readFile11(resolved.absolute);
|
|
23393
24289
|
reply.header("Content-Type", imageMimeForName(filename) ?? (filename.toLowerCase().endsWith(".pdf") ? "application/pdf" : "application/octet-stream"));
|
|
23394
24290
|
reply.header("Content-Disposition", contentDispositionAttachment(filename));
|
|
23395
24291
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
@@ -23406,7 +24302,7 @@ async function registerFsRoutes(app, runtime, options = {}) {
|
|
|
23406
24302
|
if (info.size > maxBytes) {
|
|
23407
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);
|
|
23408
24304
|
}
|
|
23409
|
-
const buffer = await
|
|
24305
|
+
const buffer = await readFile11(resolved.absolute);
|
|
23410
24306
|
if (effectiveKind === "image" || effectiveKind === "pdf") {
|
|
23411
24307
|
reply.header("Content-Type", effectiveKind === "pdf" ? "application/pdf" : imageMimeForName(filename) ?? "application/octet-stream");
|
|
23412
24308
|
reply.header("X-Content-Type-Options", "nosniff");
|
|
@@ -23837,13 +24733,13 @@ var LlmClient = class {
|
|
|
23837
24733
|
};
|
|
23838
24734
|
|
|
23839
24735
|
// src/llm/detect.ts
|
|
23840
|
-
import { readFile as
|
|
24736
|
+
import { readFile as readFile12 } from "node:fs/promises";
|
|
23841
24737
|
import { homedir as homedir13 } from "node:os";
|
|
23842
|
-
import { join as
|
|
24738
|
+
import { join as join19 } from "node:path";
|
|
23843
24739
|
var stringValue = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
23844
24740
|
async function readJson(path5) {
|
|
23845
24741
|
try {
|
|
23846
|
-
const parsed = JSON.parse(await
|
|
24742
|
+
const parsed = JSON.parse(await readFile12(path5, "utf8"));
|
|
23847
24743
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
23848
24744
|
} catch {
|
|
23849
24745
|
return void 0;
|
|
@@ -23851,7 +24747,7 @@ async function readJson(path5) {
|
|
|
23851
24747
|
}
|
|
23852
24748
|
async function readText(path5) {
|
|
23853
24749
|
try {
|
|
23854
|
-
return await
|
|
24750
|
+
return await readFile12(path5, "utf8");
|
|
23855
24751
|
} catch {
|
|
23856
24752
|
return void 0;
|
|
23857
24753
|
}
|
|
@@ -23971,7 +24867,7 @@ async function detectLlmEndpoints(options = {}) {
|
|
|
23971
24867
|
const env = options.env ?? process.env;
|
|
23972
24868
|
const home = options.home ?? homedir13();
|
|
23973
24869
|
const candidates = [];
|
|
23974
|
-
const settings = await readJson(
|
|
24870
|
+
const settings = await readJson(join19(home, ".claude", "settings.json"));
|
|
23975
24871
|
const settingsEnv = settings?.env && typeof settings.env === "object" && !Array.isArray(settings.env) ? settings.env : {};
|
|
23976
24872
|
const fromSettings = anthropicCandidate(settingsEnv, settings?.model, "claude-code:settings", "Claude Code\uFF08settings.json\uFF09");
|
|
23977
24873
|
if (fromSettings) candidates.push(fromSettings);
|
|
@@ -23979,7 +24875,7 @@ async function detectLlmEndpoints(options = {}) {
|
|
|
23979
24875
|
if (fromEnv) candidates.push(fromEnv);
|
|
23980
24876
|
const openai = openAiCandidate(env);
|
|
23981
24877
|
if (openai) candidates.push(openai);
|
|
23982
|
-
const codexConfig = await readText(
|
|
24878
|
+
const codexConfig = await readText(join19(home, ".codex", "config.toml"));
|
|
23983
24879
|
if (codexConfig) {
|
|
23984
24880
|
const codex = codexCandidate(codexConfig, env);
|
|
23985
24881
|
if (codex) candidates.push(codex);
|
|
@@ -24210,7 +25106,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
|
|
|
24210
25106
|
import { randomBytes as randomBytes3, scryptSync, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
24211
25107
|
import { chmodSync as chmodSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync7, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
24212
25108
|
import { homedir as homedir14 } from "node:os";
|
|
24213
|
-
import { dirname as dirname11, join as
|
|
25109
|
+
import { dirname as dirname11, join as join20 } from "node:path";
|
|
24214
25110
|
var webPasswordFileName = "web-password";
|
|
24215
25111
|
var SCRYPT_N = 16384;
|
|
24216
25112
|
var SCRYPT_R = 8;
|
|
@@ -24218,7 +25114,7 @@ var SCRYPT_P = 1;
|
|
|
24218
25114
|
var KEY_LENGTH = 32;
|
|
24219
25115
|
var minWebPasswordLength = 6;
|
|
24220
25116
|
function webPasswordPath(home = homedir14()) {
|
|
24221
|
-
return
|
|
25117
|
+
return join20(home, ".agentdock", webPasswordFileName);
|
|
24222
25118
|
}
|
|
24223
25119
|
function hashWebPassword(password) {
|
|
24224
25120
|
const salt = randomBytes3(16);
|
|
@@ -24483,8 +25379,8 @@ async function buildApp(runtime, options = {}) {
|
|
|
24483
25379
|
if (!config.hosts.some((item) => item.alias === host)) {
|
|
24484
25380
|
throw new RuntimeError("SSH_HOST_NOT_FOUND", `\u672A\u5728 ${config.configPath} \u4E2D\u627E\u5230 SSH \u4E3B\u673A\uFF1A${host}`, 404);
|
|
24485
25381
|
}
|
|
24486
|
-
const
|
|
24487
|
-
if (
|
|
25382
|
+
const cached5 = sshProbeCache.get(host);
|
|
25383
|
+
if (cached5 && Date.now() - cached5.at < 3e4) return cached5.value;
|
|
24488
25384
|
const value = await probeSshHost(host);
|
|
24489
25385
|
sshProbeCache.set(host, { at: Date.now(), value });
|
|
24490
25386
|
return value;
|
|
@@ -24511,6 +25407,34 @@ async function buildApp(runtime, options = {}) {
|
|
|
24511
25407
|
app.get("/api/codex/usage", async (request) => getCodexUsage(request.query.refresh === "1"));
|
|
24512
25408
|
app.get("/api/claude/usage", async (request) => getClaudeUsage(request.query.refresh === "1"));
|
|
24513
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
|
+
});
|
|
24514
25438
|
app.post("/api/agents", async (request) => runtime.createAgent(request.body));
|
|
24515
25439
|
app.put("/api/agents/:id", async (request) => runtime.updateAgent(request.params.id, request.body));
|
|
24516
25440
|
app.delete("/api/agents/:id", async (request) => runtime.deleteAgent(request.params.id));
|
|
@@ -24540,7 +25464,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24540
25464
|
app.get("/api/sessions", async () => runtime.listSessions());
|
|
24541
25465
|
app.get("/api/projects", async () => Promise.all((await runtime.listProjects()).map(async (project) => ({
|
|
24542
25466
|
...project,
|
|
24543
|
-
exists: await
|
|
25467
|
+
exists: await stat6(project.cwd).then((info) => info.isDirectory()).catch(() => false)
|
|
24544
25468
|
}))));
|
|
24545
25469
|
app.post("/api/projects", async (request) => runtime.registerProject(request.body?.path));
|
|
24546
25470
|
app.patch("/api/projects/pin", async (request) => {
|
|
@@ -24757,7 +25681,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24757
25681
|
"audio/flac": ".flac",
|
|
24758
25682
|
"application/octet-stream": ""
|
|
24759
25683
|
};
|
|
24760
|
-
const globalUploadRoot =
|
|
25684
|
+
const globalUploadRoot = join21(homedir15(), ".agentdock", "uploads");
|
|
24761
25685
|
const uploadTtlMs = 7 * 24 * 60 * 6e4;
|
|
24762
25686
|
const collectExpiredUploads = async (now2 = Date.now()) => {
|
|
24763
25687
|
let removedFiles = 0;
|
|
@@ -24768,7 +25692,7 @@ async function buildApp(runtime, options = {}) {
|
|
|
24768
25692
|
return { removedFiles };
|
|
24769
25693
|
}
|
|
24770
25694
|
for (const sessionDir of sessionDirs) {
|
|
24771
|
-
const directory =
|
|
25695
|
+
const directory = join21(globalUploadRoot, sessionDir);
|
|
24772
25696
|
let names;
|
|
24773
25697
|
try {
|
|
24774
25698
|
names = await readdir4(directory);
|
|
@@ -24776,9 +25700,9 @@ async function buildApp(runtime, options = {}) {
|
|
|
24776
25700
|
continue;
|
|
24777
25701
|
}
|
|
24778
25702
|
for (const name of names) {
|
|
24779
|
-
const filePath =
|
|
25703
|
+
const filePath = join21(directory, name);
|
|
24780
25704
|
try {
|
|
24781
|
-
const info = await
|
|
25705
|
+
const info = await stat6(filePath);
|
|
24782
25706
|
if (!info.isFile() || now2 - info.mtimeMs <= uploadTtlMs) continue;
|
|
24783
25707
|
await rm2(filePath, { force: true });
|
|
24784
25708
|
removedFiles++;
|
|
@@ -24822,10 +25746,10 @@ async function buildApp(runtime, options = {}) {
|
|
|
24822
25746
|
originalName = rawName;
|
|
24823
25747
|
}
|
|
24824
25748
|
const ext = extFromContentType(contentType, originalName);
|
|
24825
|
-
const uploadDir =
|
|
25749
|
+
const uploadDir = join21(globalUploadRoot, session.id);
|
|
24826
25750
|
await mkdir4(uploadDir, { recursive: true });
|
|
24827
25751
|
const filename = `${Date.now()}-${randomBytes4(6).toString("hex")}${ext}`;
|
|
24828
|
-
const filePath =
|
|
25752
|
+
const filePath = join21(uploadDir, filename);
|
|
24829
25753
|
await writeFile4(filePath, buffer);
|
|
24830
25754
|
return reply.code(201).send({ path: filePath, url: `/api/sessions/${session.id}/uploads/${filename}`, filename });
|
|
24831
25755
|
});
|
|
@@ -24836,9 +25760,9 @@ async function buildApp(runtime, options = {}) {
|
|
|
24836
25760
|
if (filename.includes("..") || filename.includes("/") || filename.includes("\\")) {
|
|
24837
25761
|
throw new RuntimeError("INVALID_UPLOAD", "Invalid filename", 400);
|
|
24838
25762
|
}
|
|
24839
|
-
const filePath =
|
|
25763
|
+
const filePath = join21(globalUploadRoot, session.id, filename);
|
|
24840
25764
|
const ext = extname2(filename).toLowerCase();
|
|
24841
|
-
const data = await
|
|
25765
|
+
const data = await readFile13(filePath);
|
|
24842
25766
|
reply.header("Content-Type", contentTypes[ext] ?? "application/octet-stream");
|
|
24843
25767
|
reply.header("Cache-Control", "public, max-age=31536000, immutable");
|
|
24844
25768
|
reply.header("Content-Disposition", `attachment; filename="${filename}"`);
|
|
@@ -24898,12 +25822,12 @@ data: ${JSON.stringify(event)}
|
|
|
24898
25822
|
let file = requestedFile;
|
|
24899
25823
|
let body;
|
|
24900
25824
|
try {
|
|
24901
|
-
body = await
|
|
25825
|
+
body = await readFile13(file);
|
|
24902
25826
|
} catch {
|
|
24903
25827
|
if (extname2(pathname)) return reply.code(404).send();
|
|
24904
25828
|
file = indexFile;
|
|
24905
25829
|
try {
|
|
24906
|
-
body = await
|
|
25830
|
+
body = await readFile13(file);
|
|
24907
25831
|
} catch {
|
|
24908
25832
|
return reply.code(404).send({ error: { code: "WEB_UI_NOT_FOUND", message: "Web UI is not installed" } });
|
|
24909
25833
|
}
|
|
@@ -29073,7 +29997,7 @@ function parseTemplate(schedule) {
|
|
|
29073
29997
|
|
|
29074
29998
|
// src/assistant/service.ts
|
|
29075
29999
|
init_src2();
|
|
29076
|
-
import { spawn as
|
|
30000
|
+
import { spawn as spawn12, execFile as execFile7 } from "node:child_process";
|
|
29077
30001
|
import { createHash as createHash8 } from "node:crypto";
|
|
29078
30002
|
import { promisify as promisify7 } from "node:util";
|
|
29079
30003
|
|
|
@@ -30622,8 +31546,8 @@ var AssistantLifecycle = class {
|
|
|
30622
31546
|
async collectMetrics(force = false) {
|
|
30623
31547
|
const mainId = this.host.mainSessionId();
|
|
30624
31548
|
if (!mainId) return void 0;
|
|
30625
|
-
const
|
|
30626
|
-
if (!force &&
|
|
31549
|
+
const cached5 = this.metricsCache;
|
|
31550
|
+
if (!force && cached5 && cached5.sessionId === mainId && Date.now() - cached5.at < METRICS_TTL_MS) return cached5.value;
|
|
30627
31551
|
const cat = await this.ensureCat();
|
|
30628
31552
|
if (!cat) return void 0;
|
|
30629
31553
|
const config = this.getConfig();
|
|
@@ -32719,7 +33643,7 @@ function parseGithubTarget(value) {
|
|
|
32719
33643
|
async function runWatchCommand(watch) {
|
|
32720
33644
|
const shell = resolveLoginShell();
|
|
32721
33645
|
return await new Promise((resolve17) => {
|
|
32722
|
-
const child =
|
|
33646
|
+
const child = spawn12(shell.file, [...shell.args, "-c", watch.command], {
|
|
32723
33647
|
cwd: watch.cwd ?? process.cwd(),
|
|
32724
33648
|
env: { ...process.env, agentdock_watch_id: watch.id, agentdock_session_id: watch.ownerSessionId },
|
|
32725
33649
|
detached: process.platform !== "win32",
|
|
@@ -33389,13 +34313,13 @@ async function runLarkMessageListen(options, deps = {}) {
|
|
|
33389
34313
|
init_session_cli();
|
|
33390
34314
|
import { readFileSync as readFileSync10 } from "node:fs";
|
|
33391
34315
|
var readTextFile = (path5) => path5 === "-" ? readFileSync10(0, "utf8") : readFileSync10(path5, "utf8");
|
|
33392
|
-
function buildLarkAvatarSendInput(options,
|
|
34316
|
+
function buildLarkAvatarSendInput(options, readFile14 = readTextFile) {
|
|
33393
34317
|
const chat = options.chat?.trim();
|
|
33394
34318
|
if (!chat) throw new Error("--chat \u5FC5\u586B\uFF1A\u7FA4\u540D\u3001oc_* chat_id \u6216\u6570\u5B57 chat_id");
|
|
33395
34319
|
if (options.text !== void 0 && options.textFile !== void 0) {
|
|
33396
34320
|
throw new Error("--text \u548C --text-file \u53EA\u80FD\u7528\u4E00\u4E2A");
|
|
33397
34321
|
}
|
|
33398
|
-
const text3 = options.textFile !== void 0 ?
|
|
34322
|
+
const text3 = options.textFile !== void 0 ? readFile14(options.textFile) : options.text;
|
|
33399
34323
|
if (text3 === void 0 || !text3.trim()) {
|
|
33400
34324
|
throw new Error("\u6D88\u606F\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A\uFF1A\u8BF7\u7528 --text <text> \u6216 --text-file <file>");
|
|
33401
34325
|
}
|
|
@@ -33516,7 +34440,7 @@ async function runLarkAvatarReactionRoute(options) {
|
|
|
33516
34440
|
}
|
|
33517
34441
|
|
|
33518
34442
|
// src/acpx.ts
|
|
33519
|
-
import { spawn as
|
|
34443
|
+
import { spawn as spawn13 } from "node:child_process";
|
|
33520
34444
|
import { readFileSync as readFileSync11 } from "node:fs";
|
|
33521
34445
|
import { createRequire as createRequire3 } from "node:module";
|
|
33522
34446
|
import { dirname as dirname12, resolve as resolve13 } from "node:path";
|
|
@@ -33535,7 +34459,7 @@ function resolveAcpxLauncher(moduleUrl = import.meta.url) {
|
|
|
33535
34459
|
}
|
|
33536
34460
|
return { command: "acpx", args: [] };
|
|
33537
34461
|
}
|
|
33538
|
-
function runAcpx(args, spawnProcess =
|
|
34462
|
+
function runAcpx(args, spawnProcess = spawn13, launcher = resolveAcpxLauncher()) {
|
|
33539
34463
|
return new Promise((resolve17, reject2) => {
|
|
33540
34464
|
const options = { stdio: "inherit", env: process.env };
|
|
33541
34465
|
const child = spawnProcess(launcher.command, [...launcher.args, ...args], options);
|
|
@@ -33947,23 +34871,23 @@ init_session_cli();
|
|
|
33947
34871
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
33948
34872
|
import { chmodSync as chmodSync3, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
|
|
33949
34873
|
import { createServer } from "node:net";
|
|
33950
|
-
import { delimiter as delimiter2, dirname as dirname13, join as
|
|
34874
|
+
import { delimiter as delimiter2, dirname as dirname13, join as join23, resolve as resolve15 } from "node:path";
|
|
33951
34875
|
init_daemon();
|
|
33952
34876
|
var SANDBOX_FILE = "sandbox.json";
|
|
33953
34877
|
function findRepoRoot(start = process.cwd()) {
|
|
33954
34878
|
let dir = resolve15(start);
|
|
33955
34879
|
for (; ; ) {
|
|
33956
|
-
if (existsSync12(
|
|
34880
|
+
if (existsSync12(join23(dir, "apps", "server", "package.json")) && existsSync12(join23(dir, "pnpm-workspace.yaml"))) return dir;
|
|
33957
34881
|
const parent = dirname13(dir);
|
|
33958
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");
|
|
33959
34883
|
dir = parent;
|
|
33960
34884
|
}
|
|
33961
34885
|
}
|
|
33962
34886
|
function sandboxPaths(repo, port) {
|
|
33963
|
-
const root4 =
|
|
33964
|
-
return { root: root4, home:
|
|
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 };
|
|
33965
34889
|
}
|
|
33966
|
-
var shimDir = (sandbox) =>
|
|
34890
|
+
var shimDir = (sandbox) => join23(sandbox.root, "bin");
|
|
33967
34891
|
function sandboxEnv(sandbox, base = process.env) {
|
|
33968
34892
|
const env = {
|
|
33969
34893
|
...base,
|
|
@@ -33986,7 +34910,7 @@ function writeCliShim(sandbox, node = process.execPath) {
|
|
|
33986
34910
|
if (process.platform === "win32") return;
|
|
33987
34911
|
const dir = shimDir(sandbox);
|
|
33988
34912
|
mkdirSync6(dir, { recursive: true });
|
|
33989
|
-
const file =
|
|
34913
|
+
const file = join23(dir, "agent-dock");
|
|
33990
34914
|
writeFileSync5(file, `#!/bin/sh
|
|
33991
34915
|
exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
33992
34916
|
`);
|
|
@@ -33994,7 +34918,7 @@ exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
|
|
|
33994
34918
|
}
|
|
33995
34919
|
function readSandbox(repo) {
|
|
33996
34920
|
try {
|
|
33997
|
-
return JSON.parse(readFileSync13(
|
|
34921
|
+
return JSON.parse(readFileSync13(join23(repo, ".agentdock", "dev", SANDBOX_FILE), "utf8"));
|
|
33998
34922
|
} catch {
|
|
33999
34923
|
return void 0;
|
|
34000
34924
|
}
|
|
@@ -34021,7 +34945,7 @@ async function devUp(options = {}) {
|
|
|
34021
34945
|
const sandbox = sandboxPaths(repo, port);
|
|
34022
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`);
|
|
34023
34947
|
for (const dir of [sandbox.home, sandbox.work]) mkdirSync6(dir, { recursive: true });
|
|
34024
|
-
writeFileSync5(
|
|
34948
|
+
writeFileSync5(join23(sandbox.root, SANDBOX_FILE), `${JSON.stringify(sandbox, null, 2)}
|
|
34025
34949
|
`);
|
|
34026
34950
|
writeCliShim(sandbox);
|
|
34027
34951
|
const run2 = options.run ?? defaultRun;
|
|
@@ -34233,6 +35157,111 @@ var runScheduleResume = (id, options = {}) => control(id, "resume", options);
|
|
|
34233
35157
|
var runScheduleRun = (id, options = {}) => control(id, "run", options);
|
|
34234
35158
|
var runScheduleRemove = (id, options = {}) => control(id, "remove", options);
|
|
34235
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
|
+
|
|
34236
35265
|
// src/assistant/cli.ts
|
|
34237
35266
|
init_session_cli();
|
|
34238
35267
|
import { readFileSync as readFileSync14 } from "node:fs";
|
|
@@ -35636,7 +36665,7 @@ async function serve(options, onReady) {
|
|
|
35636
36665
|
async function restartWithInstalledCli(entrypoint) {
|
|
35637
36666
|
if (!existsSync13(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
|
|
35638
36667
|
const previousPid = daemonStatus().pid;
|
|
35639
|
-
const child =
|
|
36668
|
+
const child = spawn14(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
|
|
35640
36669
|
await new Promise((resolve17, reject2) => {
|
|
35641
36670
|
child.once("error", reject2);
|
|
35642
36671
|
child.once("exit", (code) => code === 0 ? resolve17() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
|
|
@@ -35978,6 +37007,15 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
|
|
|
35978
37007
|
},
|
|
35979
37008
|
draftDiscard: async (id, options) => {
|
|
35980
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));
|
|
35981
37019
|
}
|
|
35982
37020
|
});
|
|
35983
37021
|
await program.parseAsync();
|