@standardagents/cli 0.25.7 → 0.26.1

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/index.js CHANGED
@@ -242,7 +242,7 @@ function getScaffoldStandardAgentsVersion() {
242
242
  if (process.env.STANDARDAGENTS_WORKSPACE === "1") {
243
243
  return "workspace:*";
244
244
  }
245
- return "0.25.7";
245
+ return "0.26.1";
246
246
  }
247
247
  function findViteConfig(cwd) {
248
248
  const candidates = ["vite.config.ts", "vite.config.js", "vite.config.mts", "vite.config.mjs"];
@@ -1537,7 +1537,7 @@ async function ensurePlatformAuth(options, quietLogs = false, context = {}) {
1537
1537
  return { connected: true, mode: "standardagents" };
1538
1538
  }
1539
1539
  function getCliVersion() {
1540
- return "0.25.7";
1540
+ return "0.26.1";
1541
1541
  }
1542
1542
  function getSipVersion() {
1543
1543
  return "1.0.1";
@@ -5297,6 +5297,365 @@ async function mintGitAccessApiKey(endpoint, sessionCookie, fetchImpl = fetch) {
5297
5297
  }
5298
5298
  }
5299
5299
 
5300
+ // src/commands/diag.ts
5301
+ function resolveDiagConfig(options, env = process.env, fetchImpl) {
5302
+ const endpoint = (options.endpoint || env.STANDARD_AGENTS_INSTANCE_URL || "http://localhost:5173").replace(/\/+$/, "");
5303
+ const token = options.token || env.STANDARD_AGENTS_INSTANCE_TOKEN || null;
5304
+ const resolvedFetch = typeof fetchImpl === "function" ? fetchImpl : fetch;
5305
+ return { endpoint, token, json: Boolean(options.json), fetchImpl: resolvedFetch };
5306
+ }
5307
+ async function apiGet(config, path14) {
5308
+ return apiRequest(config, path14, "GET");
5309
+ }
5310
+ async function apiRequest(config, path14, method) {
5311
+ const headers = { Accept: "application/json" };
5312
+ if (config.token) headers.Authorization = `Bearer ${config.token}`;
5313
+ const response = await config.fetchImpl(`${config.endpoint}${path14}`, { method, headers });
5314
+ const text = await response.text();
5315
+ if (!response.ok) {
5316
+ let detail = text.slice(0, 300);
5317
+ try {
5318
+ const parsed = JSON.parse(text);
5319
+ if (parsed.error) detail = parsed.error;
5320
+ } catch {
5321
+ }
5322
+ throw new Error(`${method} ${path14} \u2192 HTTP ${response.status}: ${detail}`);
5323
+ }
5324
+ try {
5325
+ return JSON.parse(text);
5326
+ } catch {
5327
+ throw new Error(
5328
+ `${method} ${path14} returned non-JSON (is this an AgentBuilder instance URL?): ${text.slice(0, 120)}`
5329
+ );
5330
+ }
5331
+ }
5332
+ function formatAge(ms) {
5333
+ if (ms === null || ms === void 0 || !Number.isFinite(ms) || ms < 0) return "\u2014";
5334
+ const s = Math.floor(ms / 1e3);
5335
+ if (s < 60) return `${s}s`;
5336
+ const m = Math.floor(s / 60);
5337
+ if (m < 60) return `${m}m${String(s % 60).padStart(2, "0")}s`;
5338
+ const h = Math.floor(m / 60);
5339
+ if (h < 24) return `${h}h${String(m % 60).padStart(2, "0")}m`;
5340
+ return `${Math.floor(h / 24)}d`;
5341
+ }
5342
+ function normalizeTimestampMs(value) {
5343
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return null;
5344
+ let ts = value;
5345
+ while (ts > 1e14) ts = ts / 1e3;
5346
+ if (ts < 1e11) ts = ts * 1e3;
5347
+ return ts;
5348
+ }
5349
+ function classifyThreadHealth(diagnostics, now = Date.now()) {
5350
+ if (diagnostics.terminated) return { health: "terminated", detail: "terminated" };
5351
+ const thread = diagnostics.thread;
5352
+ if (!thread) return { health: "unknown", detail: "no diagnostics available" };
5353
+ if (thread.incompleteLogs.length > 0) {
5354
+ const oldest = thread.incompleteLogs.reduce(
5355
+ (min, log) => Math.min(min, normalizeTimestampMs(log.created_at) ?? now),
5356
+ now
5357
+ );
5358
+ const age = now - oldest;
5359
+ const silence = thread.silenceMs;
5360
+ const pastCeiling = age > thread.watchdogCeilingMs && (silence === null || silence > thread.watchdogCeilingMs);
5361
+ if (!thread.executing && pastCeiling) {
5362
+ return {
5363
+ health: "stuck",
5364
+ detail: `open request ${formatAge(age)} old, executor dead \u2014 run: agents diag revive`
5365
+ };
5366
+ }
5367
+ if (thread.executing && pastCeiling) {
5368
+ return {
5369
+ health: "stuck",
5370
+ detail: `executing but silent ${formatAge(silence ?? age)} (ceiling ${formatAge(thread.watchdogCeilingMs)})`
5371
+ };
5372
+ }
5373
+ return { health: "running", detail: `request in flight ${formatAge(age)}` };
5374
+ }
5375
+ if (thread.executing) return { health: "running", detail: "executing (no open request)" };
5376
+ if (thread.stopped) return { health: "stopped", detail: "stopped by user" };
5377
+ if (thread.messageQueueCount > 0) {
5378
+ return { health: "running", detail: `${thread.messageQueueCount} queued message(s)` };
5379
+ }
5380
+ return { health: "idle", detail: "idle" };
5381
+ }
5382
+ function resolveThreadIdFromList(threads, idOrPrefix) {
5383
+ const exact = threads.find((t) => t.id === idOrPrefix);
5384
+ if (exact) return exact.id;
5385
+ const matches = threads.filter((t) => t.id.startsWith(idOrPrefix));
5386
+ if (matches.length === 1) return matches[0].id;
5387
+ if (matches.length === 0) {
5388
+ throw new Error(
5389
+ `No thread matching "${idOrPrefix}" in the ${threads.length} most recent threads (pass a full thread id?)`
5390
+ );
5391
+ }
5392
+ throw new Error(
5393
+ `Ambiguous thread prefix "${idOrPrefix}" \u2014 matches: ${matches.map((t) => t.id.slice(0, 8)).join(", ")}`
5394
+ );
5395
+ }
5396
+ async function resolveThreadId(config, idOrPrefix) {
5397
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(idOrPrefix)) {
5398
+ return idOrPrefix;
5399
+ }
5400
+ const data = await apiGet(config, "/api/threads?limit=100");
5401
+ return resolveThreadIdFromList(data.threads ?? [], idOrPrefix);
5402
+ }
5403
+ function printKeyValues(rows) {
5404
+ const width = Math.max(...rows.map(([k]) => k.length));
5405
+ for (const [key, value] of rows) {
5406
+ console.log(` ${key.padEnd(width)} ${value}`);
5407
+ }
5408
+ }
5409
+ async function diagInstance(options, fetchImpl) {
5410
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5411
+ const data = await apiGet(config, "/api/diagnostics");
5412
+ if (config.json) {
5413
+ console.log(JSON.stringify(data, null, 2));
5414
+ return;
5415
+ }
5416
+ console.log(`Instance ${config.endpoint}`);
5417
+ if (data.runtime) {
5418
+ printKeyValues([
5419
+ ["builder version", data.runtime.builderVersion],
5420
+ ["first-chunk timeout", formatAge(data.runtime.streamFirstChunkTimeoutMs)],
5421
+ ["stall timeout", formatAge(data.runtime.streamStallTimeoutMs)],
5422
+ ["watchdog ceiling", formatAge(data.runtime.watchdogCeilingMs)],
5423
+ ["watchdog companion", data.runtime.watchdogCompanionAvailable ? "available" : "NOT BOUND (pre-0.26 config)"],
5424
+ ["config warnings", String(data.warnings?.length ?? 0)]
5425
+ ]);
5426
+ } else {
5427
+ console.log(" builder version pre-0.26 (no runtime block in /api/diagnostics)");
5428
+ console.log(` config warnings ${data.warnings?.length ?? 0}`);
5429
+ }
5430
+ }
5431
+ async function diagThreads(options, fetchImpl) {
5432
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5433
+ const limit = Math.min(Math.max(Number.parseInt(options.limit ?? "25", 10) || 25, 1), 100);
5434
+ const data = await apiGet(config, `/api/threads?limit=${limit}`);
5435
+ const threads = (data.threads ?? []).filter((t) => !t.terminated);
5436
+ const results = [];
5437
+ const concurrency = 5;
5438
+ for (let i = 0; i < threads.length; i += concurrency) {
5439
+ const batch = threads.slice(i, i + concurrency);
5440
+ const settled = await Promise.all(
5441
+ batch.map(async (thread) => {
5442
+ try {
5443
+ const diagnostics = await apiGet(
5444
+ config,
5445
+ `/api/threads/${thread.id}/diagnostics`
5446
+ );
5447
+ return { thread, ...classifyThreadHealth(diagnostics) };
5448
+ } catch (error) {
5449
+ return {
5450
+ thread,
5451
+ health: "unknown",
5452
+ detail: error instanceof Error ? error.message : String(error)
5453
+ };
5454
+ }
5455
+ })
5456
+ );
5457
+ results.push(...settled);
5458
+ }
5459
+ const filtered = options.stuck ? results.filter((r) => r.health === "stuck") : results;
5460
+ if (config.json) {
5461
+ console.log(
5462
+ JSON.stringify(
5463
+ filtered.map((r) => ({ id: r.thread.id, agent: r.thread.agent_id, health: r.health, detail: r.detail })),
5464
+ null,
5465
+ 2
5466
+ )
5467
+ );
5468
+ return;
5469
+ }
5470
+ if (filtered.length === 0) {
5471
+ console.log(options.stuck ? `No stuck threads in the ${threads.length} most recent.` : "No threads.");
5472
+ return;
5473
+ }
5474
+ for (const { thread, health, detail } of filtered) {
5475
+ const marker = health === "stuck" ? "\u2717" : health === "running" ? "\u25CF" : "\u25CB";
5476
+ console.log(
5477
+ `${marker} ${thread.id.slice(0, 8)} ${String(health).toUpperCase().padEnd(10)} ${(thread.agent_id ?? "").padEnd(24)} ${detail}`
5478
+ );
5479
+ }
5480
+ }
5481
+ async function diagThread(idOrPrefix, options, fetchImpl) {
5482
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5483
+ const threadId = await resolveThreadId(config, idOrPrefix);
5484
+ const data = await apiGet(config, `/api/threads/${threadId}/diagnostics`);
5485
+ if (config.json) {
5486
+ console.log(JSON.stringify(data, null, 2));
5487
+ return;
5488
+ }
5489
+ const { health, detail } = classifyThreadHealth(data);
5490
+ console.log(`Thread ${threadId}`);
5491
+ console.log(`Health: ${health.toUpperCase()} \u2014 ${detail}
5492
+ `);
5493
+ const thread = data.thread;
5494
+ if (thread) {
5495
+ console.log("Execution");
5496
+ printKeyValues([
5497
+ ["executing", String(thread.executing)],
5498
+ ["stopped", String(thread.stopped)],
5499
+ ["last progress", thread.silenceMs === null ? "\u2014" : `${formatAge(thread.silenceMs)} ago`],
5500
+ ["watchdog strikes", String(thread.watchdogStrikes)],
5501
+ ["watchdog ceiling", formatAge(thread.watchdogCeilingMs)],
5502
+ ["queued messages", String(thread.messageQueueCount)]
5503
+ ]);
5504
+ if (thread.contextUsage) {
5505
+ const usage = thread.contextUsage;
5506
+ const pct = usage.inputTokens && usage.maxContextTokens ? ` (${Math.round(usage.inputTokens / usage.maxContextTokens * 100)}% of window)` : "";
5507
+ console.log(`
5508
+ Context: ${usage.inputTokens ?? "?"} tokens on ${usage.model ?? "?"}${pct}`);
5509
+ }
5510
+ console.log(`
5511
+ Open request logs (${thread.incompleteLogs.length})`);
5512
+ for (const log of thread.incompleteLogs) {
5513
+ const age = formatAge(Date.now() - (normalizeTimestampMs(log.created_at) ?? Date.now()));
5514
+ console.log(` ${log.id.slice(0, 8)} ${log.model ?? "?"} via ${log.provider ?? "?"} open ${age}`);
5515
+ }
5516
+ console.log(`
5517
+ Alarm queue (${thread.alarmQueue.length} recent rows)`);
5518
+ for (const row of thread.alarmQueue.slice(0, 12)) {
5519
+ const scheduled = formatAge(Date.now() - (normalizeTimestampMs(row.scheduled_at) ?? Date.now()));
5520
+ const error = row.error ? ` error: ${row.error.slice(0, 60)}` : "";
5521
+ console.log(
5522
+ ` ${row.method.padEnd(18)} ${row.status.padEnd(11)} attempts=${row.attempts} scheduled ${scheduled} ago${error}`
5523
+ );
5524
+ }
5525
+ }
5526
+ console.log(`
5527
+ Watchdog ${data.watchdog ? data.watchdog.armed ? "(armed)" : "(standing down)" : "(companion not available)"}`);
5528
+ for (const checkin of data.watchdog?.history?.slice(0, 5) ?? []) {
5529
+ const at = new Date(checkin.at).toISOString().slice(11, 19);
5530
+ console.log(` ${at} ${checkin.verdict.padEnd(12)} ${checkin.action}`);
5531
+ }
5532
+ }
5533
+ async function diagLogs(idOrPrefix, logId, options, fetchImpl) {
5534
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5535
+ const threadId = await resolveThreadId(config, idOrPrefix);
5536
+ if (logId) {
5537
+ const log = await apiGet(config, `/api/threads/${threadId}/logs/${logId}`);
5538
+ if (config.json) {
5539
+ console.log(JSON.stringify(log, null, 2));
5540
+ return;
5541
+ }
5542
+ const detail = log.log ?? log;
5543
+ printKeyValues(
5544
+ [
5545
+ ["id", String(detail.id ?? logId)],
5546
+ ["complete", String(detail.is_complete)],
5547
+ ["model", `${detail.model ?? "?"} via ${detail.provider ?? "?"} (${detail.actual_provider ?? "?"})`],
5548
+ ["status", String(detail.status_code ?? "\u2014")],
5549
+ ["ttft", detail.time_to_first_token_ms ? formatAge(detail.time_to_first_token_ms) : "\u2014"],
5550
+ ["tokens", `${detail.input_tokens ?? "\u2014"} in / ${detail.output_tokens ?? "\u2014"} out`],
5551
+ ["error", String(detail.error ?? "\u2014")],
5552
+ ["error type", String(detail.error_type ?? "\u2014")]
5553
+ ]
5554
+ );
5555
+ return;
5556
+ }
5557
+ const limit = Math.min(Math.max(Number.parseInt(options.limit ?? "10", 10) || 10, 1), 100);
5558
+ const data = await apiGet(
5559
+ config,
5560
+ `/api/threads/${threadId}/logs?limit=${limit}&order=desc`
5561
+ );
5562
+ if (config.json) {
5563
+ console.log(JSON.stringify(data.logs, null, 2));
5564
+ return;
5565
+ }
5566
+ for (const log of data.logs ?? []) {
5567
+ const open = log.is_complete ? " " : "\u25B6";
5568
+ const err = log.error_type ? ` [${log.error_type}]` : "";
5569
+ console.log(`${open} ${String(log.id).slice(0, 8)} ${log.model} in=${log.input_tokens ?? "\u2014"} out=${log.output_tokens ?? "\u2014"}${err}`);
5570
+ }
5571
+ }
5572
+ async function diagRevive(idOrPrefix, options, fetchImpl) {
5573
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5574
+ const threadId = await resolveThreadId(config, idOrPrefix);
5575
+ const result = await apiRequest(
5576
+ config,
5577
+ `/api/threads/${threadId}/revive`,
5578
+ "POST"
5579
+ );
5580
+ if (config.json) {
5581
+ console.log(JSON.stringify(result, null, 2));
5582
+ return;
5583
+ }
5584
+ console.log(`Verdict: ${result.verdict}`);
5585
+ console.log(`Action: ${result.action}`);
5586
+ if (result.incompleteLogs) console.log(`Finalized/open logs: ${result.incompleteLogs}`);
5587
+ if (result.requestRestart) console.log("A wedged execution was taken over; the DO was restarted.");
5588
+ }
5589
+ async function diagTail(idOrPrefix, options, fetchImpl) {
5590
+ const config = resolveDiagConfig(options, process.env, fetchImpl ?? fetch);
5591
+ const threadId = await resolveThreadId(config, idOrPrefix);
5592
+ const wsUrl = config.endpoint.replace(/^http/, "ws") + `/api/threads/${threadId}/logs` + (config.token ? `?token=${encodeURIComponent(config.token)}` : "");
5593
+ const WebSocketCtor = globalThis.WebSocket;
5594
+ if (!WebSocketCtor) {
5595
+ throw new Error("WebSocket is not available in this Node runtime (need Node 22+)");
5596
+ }
5597
+ console.log(`Tailing ${threadId} \u2014 Ctrl-C to stop`);
5598
+ const ws = new WebSocketCtor(wsUrl);
5599
+ ws.onopen = () => console.log("connected");
5600
+ ws.onclose = () => {
5601
+ console.log("closed");
5602
+ process.exit(0);
5603
+ };
5604
+ ws.onerror = () => {
5605
+ console.error("websocket error");
5606
+ process.exit(1);
5607
+ };
5608
+ ws.onmessage = (event) => {
5609
+ const raw = typeof event.data === "string" ? event.data : "";
5610
+ try {
5611
+ const parsed = JSON.parse(raw);
5612
+ const at = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
5613
+ if (parsed.type === "log_data" && parsed.data) {
5614
+ const summary = Object.keys(parsed.data).filter((k) => k !== "id").slice(0, 6).join(",");
5615
+ console.log(`${at} log ${String(parsed.log_id ?? "").slice(0, 8)} \u2190 ${summary}`);
5616
+ } else {
5617
+ console.log(`${at} ${parsed.type ?? "event"} ${raw.slice(0, 140)}`);
5618
+ }
5619
+ } catch {
5620
+ console.log(raw.slice(0, 160));
5621
+ }
5622
+ };
5623
+ await new Promise(() => {
5624
+ });
5625
+ }
5626
+ function registerDiagCommand(program2) {
5627
+ const diag = program2.command("diag").description("Diagnose a running Standard Agents instance (threads, watchdog, request logs)");
5628
+ const withCommonOptions = (cmd) => cmd.option("--endpoint <url>", "Instance URL (default: $STANDARD_AGENTS_INSTANCE_URL or http://localhost:5173)").option("--token <token>", "Instance API key / session token (default: $STANDARD_AGENTS_INSTANCE_TOKEN)").option("--json", "Print raw JSON");
5629
+ withCommonOptions(
5630
+ diag.command("instance").description("Deployed builder version, watchdog budgets, config warnings")
5631
+ ).action(wrapDiagAction(diagInstance));
5632
+ withCommonOptions(
5633
+ diag.command("threads").description("List recent threads with execution health").option("--stuck", "Only show threads with an unrecovered open request").option("--limit <n>", "How many recent threads to scan (default 25)")
5634
+ ).action(wrapDiagAction(diagThreads));
5635
+ withCommonOptions(
5636
+ diag.command("thread <id>").description("Full doctor view: execution state, open logs, alarm queue, watchdog check-ins")
5637
+ ).action(wrapDiagAction(diagThread));
5638
+ withCommonOptions(
5639
+ diag.command("logs <thread> [logId]").description("Recent request logs for a thread, or one log in detail").option("--limit <n>", "How many logs to list (default 10)")
5640
+ ).action(wrapDiagAction(diagLogs));
5641
+ withCommonOptions(
5642
+ diag.command("tail <thread>").description("Live-tail a thread\u2019s log/telemetry stream (is anything flowing?)")
5643
+ ).action(wrapDiagAction(diagTail));
5644
+ withCommonOptions(
5645
+ diag.command("revive <thread>").description("Run a watchdog check NOW: finalize lost requests and resume a stuck thread")
5646
+ ).action(wrapDiagAction(diagRevive));
5647
+ }
5648
+ function wrapDiagAction(action) {
5649
+ return async (...args) => {
5650
+ try {
5651
+ await action(...args);
5652
+ } catch (error) {
5653
+ console.error(`diag: ${error instanceof Error ? error.message : String(error)}`);
5654
+ process.exitCode = 1;
5655
+ }
5656
+ };
5657
+ }
5658
+
5300
5659
  // src/index.ts
5301
5660
  async function settleStdinForInitHandoff(stdin = process.stdin) {
5302
5661
  if (!stdin.isTTY) return;
@@ -5316,7 +5675,7 @@ async function settleStdinForInitHandoff(stdin = process.stdin) {
5316
5675
  }
5317
5676
  }
5318
5677
  var program = new Command();
5319
- program.name("agents").description("CLI tool for Standard Agents / AgentBuilder").version("0.25.7");
5678
+ program.name("agents").description("CLI tool for Standard Agents / AgentBuilder").version("0.26.1");
5320
5679
  program.command("init [project-name]").description("Create a new Standard Agents project").option("-y, --yes", "Skip prompts and use defaults").option("--local", "Use local project scaffolding instead of browser platform onboarding").option("--cli", "Use classic line-by-line CLI prompts instead of the TUI wizard").option("--api-url <url>", "Standard Agents platform API URL").option("--endpoint <url>", "Platform API endpoint for auth/bootstrap exchange").option("--package-manager <manager>", "Package manager for generated project: npm, pnpm, yarn, or bun").option("--template <template>", "Vite template to use", "vanilla-ts").option("--workspace", "Install @standardagents packages as workspace:* (local pnpm workspace development)").option("--no-dev", "Clone and configure the project without starting the dev server").addOption(new Option("--bootstrap <code>", "Exchange a web onboarding bootstrap code")).action(init);
5321
5680
  program.command("login").description("Authenticate this machine (or use --bootstrap for project bootstrap auth)").option("--bootstrap <code>", "Bootstrap code from web onboarding").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").option("--no-open", "Do not auto-open browser URL").action(login);
5322
5681
  program.command("logout").description("Clear stored StandardAgents auth and local org-scoped project auth").option("--org <org-id-or-slug>", "Org ID or slug to logout (defaults to active org)").option("--endpoint <url>", "Platform API endpoint (default: https://api.standardagents.ai)").action(logout);
@@ -5332,6 +5691,7 @@ program.command("support-files").description("Write generated local support file
5332
5691
  program.command("skill").description("Install the bundled AgentBuilder guidance into a supported coding agent").option("--agent <target>", "Install target: codex or claude").option("--dir <path>", "Install directory override for the selected target").option("--force", "Overwrite an existing installed skill").action(skill);
5333
5692
  program.command("current-models").description("Print the live curated model guide from standardagentspec.com").option("--url <url>", "Override the models markdown URL").action(currentModels);
5334
5693
  program.command("available-models").description("List every available model for one configured provider in the current project").option("--provider <provider>", "Provider to query, for example cerebras or openai").action(availableModels);
5694
+ registerDiagCommand(program);
5335
5695
  async function run() {
5336
5696
  const userArgs = process.argv.slice(2);
5337
5697
  const isInteractiveTerminal2 = Boolean(process.stdin.isTTY && process.stdout.isTTY);