@aidotnet/astra-gate 0.14.3109 → 0.14.3112

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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import process6 from "process";
4
+ import process8 from "process";
5
5
  import { Argument, Command, InvalidArgumentError } from "commander";
6
6
 
7
7
  // src/errors.ts
@@ -36,7 +36,7 @@ function adminHeaders(mutating, runtimeToken) {
36
36
  return headers;
37
37
  }
38
38
  async function apiRequest(options) {
39
- const { base, path: path15, method = "GET", body, runtimeToken, timeoutMs = 1e4 } = options;
39
+ const { base, path: path16, method = "GET", body, runtimeToken, timeoutMs = 1e4 } = options;
40
40
  const doFetch = options.fetchImpl ?? globalThis.fetch;
41
41
  if (!doFetch) {
42
42
  throw new AstraError("fetch is unavailable. The Astra CLI requires Node.js 18+.");
@@ -46,7 +46,7 @@ async function apiRequest(options) {
46
46
  if (body !== void 0) headers["Content-Type"] = "application/json";
47
47
  let response;
48
48
  try {
49
- response = await doFetch(base + path15, {
49
+ response = await doFetch(base + path16, {
50
50
  method,
51
51
  headers,
52
52
  body: body === void 0 ? void 0 : JSON.stringify(body),
@@ -203,7 +203,54 @@ var CLIENT_KINDS = [
203
203
  "workbuddy-ai",
204
204
  "muse-code",
205
205
  "paseo",
206
- "tkcode"
206
+ "tkcode",
207
+ "openchamber",
208
+ "deveco-code",
209
+ "stepcode",
210
+ "aside",
211
+ "omo",
212
+ "prime-agent",
213
+ "mu",
214
+ "mothx",
215
+ "penguin-harness",
216
+ "antigravity-cli",
217
+ "dim",
218
+ "command-code",
219
+ "fx",
220
+ "goose",
221
+ "zoo-code",
222
+ "jetbrains-air",
223
+ "air-ide",
224
+ "copilot-jetbrains",
225
+ "codebuddy",
226
+ "qoder",
227
+ "qoder-cn",
228
+ "t3code",
229
+ "pencil",
230
+ "openpencil",
231
+ "raycast",
232
+ "obsidian",
233
+ "reasonix",
234
+ "morph",
235
+ "jcode",
236
+ "vibe",
237
+ "empryo",
238
+ "nanobot",
239
+ "miniq",
240
+ "paimon",
241
+ "cline",
242
+ "grok-app",
243
+ "atomcode",
244
+ "snow",
245
+ "ante",
246
+ "craft-agents",
247
+ "tuanjie-cowork",
248
+ "liveagent",
249
+ "openmausbot",
250
+ "astrbot",
251
+ "qwenpaw",
252
+ "openclaw",
253
+ "openbot"
207
254
  ];
208
255
  var PLUGIN_CLIENT_KIND = /^plugin-[a-z0-9][a-z0-9._-]{0,63}$/;
209
256
  function isClientKind(kind) {
@@ -301,8 +348,8 @@ function isNewerVersion(candidate, current) {
301
348
  }
302
349
  function majorOf(v) {
303
350
  const m = /^\s*(\d+)(?:\.|$)/.exec(v ?? "");
304
- const group = m?.[1];
305
- return group ? Number.parseInt(group, 10) : null;
351
+ const group2 = m?.[1];
352
+ return group2 ? Number.parseInt(group2, 10) : null;
306
353
  }
307
354
  function isApiVersionCompatible(serverApiVersion, expectedMajor) {
308
355
  const major = majorOf(serverApiVersion);
@@ -407,7 +454,7 @@ function npmChildEnv(env = process.env) {
407
454
  return Object.fromEntries(Object.entries(env).filter(([key]) => !PARENT_NPM_KEYS.test(key)));
408
455
  }
409
456
  function runCapture(command, args, o = {}) {
410
- return new Promise((resolve, reject) => {
457
+ return new Promise((resolve2, reject) => {
411
458
  const child = spawn(command, [...args], {
412
459
  env: o.env,
413
460
  windowsHide: true,
@@ -436,7 +483,7 @@ function runCapture(command, args, o = {}) {
436
483
  });
437
484
  child.on("close", (code) => {
438
485
  if (timer) clearTimeout(timer);
439
- if (!settled) resolve({ code, stdout, stderr });
486
+ if (!settled) resolve2({ code, stdout, stderr });
440
487
  });
441
488
  });
442
489
  }
@@ -455,7 +502,7 @@ var NODE_BIN_DIRS = ["/opt/homebrew/bin", "/usr/local/bin"];
455
502
  var SHELL_PATH_MARKER = /__ASTRA_PATH_START__([\s\S]*?)__ASTRA_PATH_END__/;
456
503
  var cachedLoginShellPath = null;
457
504
  function readLoginShellPath(env, timeoutMs = 5e3) {
458
- return new Promise((resolve) => {
505
+ return new Promise((resolve2) => {
459
506
  let out = "";
460
507
  let done = false;
461
508
  let timer = null;
@@ -463,7 +510,7 @@ function readLoginShellPath(env, timeoutMs = 5e3) {
463
510
  if (done) return;
464
511
  done = true;
465
512
  if (timer) clearTimeout(timer);
466
- resolve(value);
513
+ resolve2(value);
467
514
  };
468
515
  let child;
469
516
  try {
@@ -873,7 +920,7 @@ async function probeRestartedVersion(control) {
873
920
  for (; ; ) {
874
921
  const reported = await control.probeVersion().catch(() => null);
875
922
  if (reported !== null || Date.now() >= deadline) return reported;
876
- await new Promise((resolve) => setTimeout(resolve, RESTART_PROBE_INTERVAL_MS));
923
+ await new Promise((resolve2) => setTimeout(resolve2, RESTART_PROBE_INTERVAL_MS));
877
924
  }
878
925
  }
879
926
  async function rollback(o, previousInstall, backupPath, webRootSwapped, setState, log) {
@@ -1041,7 +1088,7 @@ Categories=Development;Network;
1041
1088
  `;
1042
1089
  }
1043
1090
  function runCapture2(command, args, timeoutMs) {
1044
- return new Promise((resolve, reject) => {
1091
+ return new Promise((resolve2, reject) => {
1045
1092
  const child = spawn2(command, [...args], { stdio: "ignore", windowsHide: true, shell: command.endsWith(".cmd") });
1046
1093
  let settled = false;
1047
1094
  const timer = setTimeout(() => {
@@ -1054,7 +1101,7 @@ function runCapture2(command, args, timeoutMs) {
1054
1101
  });
1055
1102
  child.on("close", (code) => {
1056
1103
  clearTimeout(timer);
1057
- if (!settled) resolve({ code, stderr: "" });
1104
+ if (!settled) resolve2({ code, stderr: "" });
1058
1105
  });
1059
1106
  });
1060
1107
  }
@@ -1130,6 +1177,7 @@ function homePaths(home) {
1130
1177
  pluginsDir: path8.join(home, "plugins"),
1131
1178
  toolsDir: path8.join(home, "tools"),
1132
1179
  libraryDir: path8.join(home, "library"),
1180
+ autoBackupsDir: path8.join(home, "backups", "auto"),
1133
1181
  connectDir: path8.join(home, "connect"),
1134
1182
  desktopPrefix: path8.join(home, "desktop")
1135
1183
  };
@@ -1314,7 +1362,7 @@ import { fileURLToPath } from "url";
1314
1362
  // package.json
1315
1363
  var package_default = {
1316
1364
  name: "@aidotnet/astra-gate",
1317
- version: "0.14.3109",
1365
+ version: "0.14.3112",
1318
1366
  description: "Astra \u2014 a local AI gateway. Install, start, stop and manage the astra-server from the terminal.",
1319
1367
  license: "MIT",
1320
1368
  type: "module",
@@ -1345,12 +1393,12 @@ var package_default = {
1345
1393
  commander: "^12.1.0"
1346
1394
  },
1347
1395
  optionalDependencies: {
1348
- "@aidotnet/server-darwin-arm64": "0.14.3109",
1349
- "@aidotnet/server-darwin-x64": "0.14.3109",
1350
- "@aidotnet/server-linux-arm64": "0.14.3109",
1351
- "@aidotnet/server-linux-x64": "0.14.3109",
1352
- "@aidotnet/server-win32-arm64": "0.14.3109",
1353
- "@aidotnet/server-win32-x64": "0.14.3109"
1396
+ "@aidotnet/server-darwin-arm64": "0.14.3112",
1397
+ "@aidotnet/server-darwin-x64": "0.14.3112",
1398
+ "@aidotnet/server-linux-arm64": "0.14.3112",
1399
+ "@aidotnet/server-linux-x64": "0.14.3112",
1400
+ "@aidotnet/server-win32-arm64": "0.14.3112",
1401
+ "@aidotnet/server-win32-x64": "0.14.3112"
1354
1402
  },
1355
1403
  devDependencies: {
1356
1404
  "@aidotnet/update-core": "workspace:*",
@@ -1438,7 +1486,7 @@ function findPackagedServerBinary(options = {}) {
1438
1486
  // src/lib/process-utils.ts
1439
1487
  import { spawn as spawn4 } from "child_process";
1440
1488
  function runCapture3(command, args, options = {}) {
1441
- return new Promise((resolve, reject) => {
1489
+ return new Promise((resolve2, reject) => {
1442
1490
  const child = spawn4(command, [...args], {
1443
1491
  cwd: options.cwd,
1444
1492
  env: options.env,
@@ -1472,7 +1520,7 @@ function runCapture3(command, args, options = {}) {
1472
1520
  });
1473
1521
  child.on("close", (code) => {
1474
1522
  if (timer) clearTimeout(timer);
1475
- if (!settled) resolve({ code, stdout, stderr });
1523
+ if (!settled) resolve2({ code, stdout, stderr });
1476
1524
  });
1477
1525
  });
1478
1526
  }
@@ -1482,9 +1530,9 @@ function spawnDetached(command, args, stdio) {
1482
1530
  return child;
1483
1531
  }
1484
1532
  function exitCodeOf(child) {
1485
- return new Promise((resolve, reject) => {
1533
+ return new Promise((resolve2, reject) => {
1486
1534
  child.on("error", reject);
1487
- child.on("close", (code) => resolve(code));
1535
+ child.on("close", (code) => resolve2(code));
1488
1536
  });
1489
1537
  }
1490
1538
  function isPidAlive(pid) {
@@ -1527,7 +1575,7 @@ async function waitForPidExit(pid, timeoutMs, isAlive = isPidAlive) {
1527
1575
  return !isAlive(pid);
1528
1576
  }
1529
1577
  function delay(ms) {
1530
- return new Promise((resolve) => setTimeout(resolve, ms));
1578
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1531
1579
  }
1532
1580
 
1533
1581
  // src/lib/install-json.ts
@@ -2084,7 +2132,7 @@ function usesShell2(command) {
2084
2132
  async function npmInstallGlobal(version) {
2085
2133
  const npm = locateNpm();
2086
2134
  const full = [...npm.args, "install", "-g", `${PACKAGE_NAME}@${version}`, "--no-audit", "--no-fund", "--loglevel", "error"];
2087
- return new Promise((resolve, reject) => {
2135
+ return new Promise((resolve2, reject) => {
2088
2136
  const child = spawn6(npm.command, full, {
2089
2137
  stdio: "inherit",
2090
2138
  env: npmChildEnv(),
@@ -2092,7 +2140,7 @@ async function npmInstallGlobal(version) {
2092
2140
  shell: usesShell2(npm.command)
2093
2141
  });
2094
2142
  child.on("error", reject);
2095
- child.on("close", (code) => resolve({ code, stderr: "" }));
2143
+ child.on("close", (code) => resolve2({ code, stderr: "" }));
2096
2144
  });
2097
2145
  }
2098
2146
 
@@ -2139,7 +2187,7 @@ function ensureDesktopServer(o) {
2139
2187
  import readline from "readline";
2140
2188
  import { Writable } from "stream";
2141
2189
  function promptHidden(question) {
2142
- return new Promise((resolve, reject) => {
2190
+ return new Promise((resolve2, reject) => {
2143
2191
  const stdin = process.stdin;
2144
2192
  if (!stdin.isTTY) {
2145
2193
  let data = "";
@@ -2147,7 +2195,7 @@ function promptHidden(question) {
2147
2195
  stdin.on("data", (chunk) => {
2148
2196
  data += chunk;
2149
2197
  });
2150
- stdin.on("end", () => resolve(data.replace(/\r?\n$/, "")));
2198
+ stdin.on("end", () => resolve2(data.replace(/\r?\n$/, "")));
2151
2199
  stdin.on("error", reject);
2152
2200
  return;
2153
2201
  }
@@ -2161,16 +2209,16 @@ function promptHidden(question) {
2161
2209
  rl.question("", (answer) => {
2162
2210
  rl.close();
2163
2211
  process.stdout.write("\n");
2164
- resolve(answer);
2212
+ resolve2(answer);
2165
2213
  });
2166
2214
  });
2167
2215
  }
2168
2216
  function confirmPrompt(question) {
2169
- return new Promise((resolve) => {
2217
+ return new Promise((resolve2) => {
2170
2218
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2171
2219
  rl.question(question, (answer) => {
2172
2220
  rl.close();
2173
- resolve(/^\s*(y|yes)/i.test(answer.trim()));
2221
+ resolve2(/^\s*(y|yes)/i.test(answer.trim()));
2174
2222
  });
2175
2223
  });
2176
2224
  }
@@ -2420,12 +2468,13 @@ async function runUninstall(opts) {
2420
2468
  import { existsSync } from "fs";
2421
2469
  import { chmod, readFile, stat, writeFile } from "fs/promises";
2422
2470
  import path13 from "path";
2423
- async function api(path15, options = {}) {
2471
+ import process5 from "process";
2472
+ async function api(path16, options = {}) {
2424
2473
  const { base, runtime, started } = await ensureServerRunning();
2425
2474
  if (started) console.log("Server was not running \u2014 started it in the background.");
2426
2475
  return apiRequest({
2427
2476
  base,
2428
- path: path15,
2477
+ path: path16,
2429
2478
  method: options.method ?? "GET",
2430
2479
  body: options.body,
2431
2480
  runtimeToken: runtime?.runtimeToken
@@ -2529,6 +2578,86 @@ async function runClientDisable(kind) {
2529
2578
  await api(`/api/clients/${kind}/disable`, { method: "POST", body: {} });
2530
2579
  success(`Client "${kind}" disabled. Its original configuration was restored.`);
2531
2580
  }
2581
+ async function runClientUse(kind, target) {
2582
+ const providers = await api("/api/providers");
2583
+ const slash = target.indexOf("/");
2584
+ let provider2;
2585
+ let model = target;
2586
+ if (slash > 0) {
2587
+ provider2 = findProvider(providers, target.slice(0, slash));
2588
+ if (provider2) model = target.slice(slash + 1);
2589
+ }
2590
+ if (!provider2) {
2591
+ const row = (await api("/api/clients")).find((r) => r.kind === kind);
2592
+ provider2 = providers.find((p) => p.id === row?.providerId);
2593
+ if (!provider2) {
2594
+ throw new AstraError(
2595
+ `No provider for "${target}".`,
2596
+ "Write <provider>/<model> (see `astra provider list`), or bind the client to a provider first."
2597
+ );
2598
+ }
2599
+ }
2600
+ if (!model) throw new AstraError('Missing the model after "<provider>/".');
2601
+ await runClientEnable(kind, { provider: provider2.id, model });
2602
+ }
2603
+ async function runClientShortlist(kind, models) {
2604
+ await api(`/api/clients/${kind}/shortlist`, { method: "PUT", body: { models } });
2605
+ success(
2606
+ models.length > 0 ? `Client "${kind}" now sees only: ${models.join(", ")}.` : `Client "${kind}" shortlist cleared: it sees every model.`
2607
+ );
2608
+ }
2609
+ async function runProfileList() {
2610
+ const rows = await api("/api/profiles");
2611
+ if (rows.length === 0) {
2612
+ console.log("No profiles yet. Save one with `astra profile save <name>`.");
2613
+ return;
2614
+ }
2615
+ printTable(
2616
+ rows.map((r) => [
2617
+ r.name,
2618
+ String(r.clients.length),
2619
+ String(r.clients.filter((c) => c.enabled).length),
2620
+ r.active ? r.drifted ? "active (changed since)" : "active" : ""
2621
+ ]),
2622
+ ["NAME", "CLIENTS", "ENABLED", "STATE"]
2623
+ );
2624
+ }
2625
+ async function runProfileSave(name) {
2626
+ const existing = (await api("/api/profiles")).find(
2627
+ (p) => p.name.toLowerCase() === name.trim().toLowerCase()
2628
+ );
2629
+ const saved = existing ? await api(`/api/profiles/${encodeURIComponent(existing.id)}`, { method: "PUT", body: { overwrite: true } }) : await api("/api/profiles", { method: "POST", body: { name } });
2630
+ success(`${existing ? "Updated" : "Saved"} profile "${saved.name}" (${saved.clients.length} clients).`);
2631
+ }
2632
+ function printPlan(plan) {
2633
+ for (const step of plan.steps) {
2634
+ const reason = step.reason ? ` (${step.reason})` : "";
2635
+ console.log(` ${step.kind.padEnd(18)} ${step.action}${reason}`);
2636
+ for (const n of step.notes ?? []) console.log(` ${n.replace(/^drifted:/, "left as the user changed it: ")}`);
2637
+ }
2638
+ for (const d of plan.dropped) warn(`${d.kind}: ${d.what} ${d.id} is ${d.reason}, ignored.`);
2639
+ }
2640
+ async function runProfileUse(name, opts = {}) {
2641
+ const id = encodeURIComponent(name);
2642
+ if (opts.dryRun) {
2643
+ printPlan(await api(`/api/profiles/${id}/preview`));
2644
+ return;
2645
+ }
2646
+ const plan = await api(`/api/profiles/${id}/apply`, { method: "POST", body: {} });
2647
+ printPlan(plan);
2648
+ const bad = plan.steps.filter((s) => s.action === "failed").length;
2649
+ if (bad > 0) {
2650
+ process5.exitCode = 1;
2651
+ warn(`Profile "${plan.profile.name}" applied with ${bad} failed client(s).`);
2652
+ return;
2653
+ }
2654
+ success(`Applied profile "${plan.profile.name}".`);
2655
+ console.log("Restart the clients (Codex, Claude Desktop, \u2026) if they do not pick up the change.");
2656
+ }
2657
+ async function runProfileRemove(name) {
2658
+ await api(`/api/profiles/${encodeURIComponent(name)}`, { method: "DELETE" });
2659
+ success(`Deleted profile "${name}". The clients' configurations did not change.`);
2660
+ }
2532
2661
  async function runTokenList() {
2533
2662
  const rows = await api("/api/tokens");
2534
2663
  printTable(
@@ -2607,6 +2736,90 @@ async function runProviderRemove(id) {
2607
2736
  }
2608
2737
  success(`Provider "${id}" removed.`);
2609
2738
  }
2739
+ async function requireProvider(idOrName) {
2740
+ const provider2 = findProvider(await api("/api/providers"), idOrName);
2741
+ if (!provider2) {
2742
+ throw new AstraError(
2743
+ `No provider matches "${idOrName}".`,
2744
+ "Run `astra provider list` to see available providers."
2745
+ );
2746
+ }
2747
+ return provider2;
2748
+ }
2749
+ function findKey(keys, ref) {
2750
+ const needle = ref.toLowerCase();
2751
+ const found = keys.find((k) => k.id.toLowerCase() === needle) ?? keys.find((k) => k.displayName.toLowerCase() === needle) ?? (/^\d+$/.test(ref) ? keys[Number(ref) - 1] : void 0);
2752
+ if (!found) {
2753
+ throw new AstraError(
2754
+ `No key matches "${ref}".`,
2755
+ "Run `astra provider keys list <provider>` to see its keys."
2756
+ );
2757
+ }
2758
+ return found;
2759
+ }
2760
+ function keyState(k) {
2761
+ if (k.enabled === false) return "off";
2762
+ if (k.cooldownUntilUtc && new Date(k.cooldownUntilUtc).getTime() > Date.now()) {
2763
+ const auth = /^40[13] /.test(k.lastError ?? "");
2764
+ return `${auth ? "auth failed" : "cooling"} until ${k.cooldownUntilUtc}`;
2765
+ }
2766
+ return "ok";
2767
+ }
2768
+ async function runProviderKeysList(idOrName) {
2769
+ const provider2 = await requireProvider(idOrName);
2770
+ const keys = await api(`/api/providers/${encodeURIComponent(provider2.id)}/keys`);
2771
+ if (keys.length === 0) {
2772
+ console.log(`${provider2.name ?? provider2.id} holds a single API key (use \`astra provider keys add\` to add more).`);
2773
+ return;
2774
+ }
2775
+ printTable(
2776
+ keys.map((k, i) => [
2777
+ String(i + 1),
2778
+ k.id,
2779
+ k.displayName,
2780
+ k.keyMasked ?? "",
2781
+ k.protocol ?? "all",
2782
+ String(k.weight ?? 1),
2783
+ keyState(k)
2784
+ ]),
2785
+ ["#", "ID", "NAME", "KEY", "PROTOCOL", "WEIGHT", "STATE"]
2786
+ );
2787
+ }
2788
+ async function runProviderKeysAdd(idOrName, opts) {
2789
+ const provider2 = await requireProvider(idOrName);
2790
+ const key = opts.key ?? process5.env.ASTRA_API_KEY ?? await promptHidden("API key: ");
2791
+ if (!key.trim()) throw new AstraError("No key given.", "Pass --key, set ASTRA_API_KEY, or type it at the prompt.");
2792
+ const weight = opts.weight === void 0 ? void 0 : Number(opts.weight);
2793
+ if (weight !== void 0 && !Number.isInteger(weight)) {
2794
+ throw new AstraError(`Invalid weight "${opts.weight}".`, "Use a whole number from 1 to 1000.");
2795
+ }
2796
+ const keys = await api(`/api/providers/${encodeURIComponent(provider2.id)}/keys`, {
2797
+ method: "POST",
2798
+ body: {
2799
+ key: key.trim(),
2800
+ ...opts.name ? { name: opts.name } : {},
2801
+ ...opts.protocol ? { protocol: opts.protocol } : {},
2802
+ ...weight !== void 0 ? { weight } : {},
2803
+ ...opts.proxy ? { httpProxy: opts.proxy } : {},
2804
+ ...opts.notes ? { notes: opts.notes } : {}
2805
+ }
2806
+ });
2807
+ success(`Key added to ${provider2.name ?? provider2.id}; it now holds ${keys.length} keys.`);
2808
+ }
2809
+ async function runProviderKeysRemove(idOrName, ref) {
2810
+ const provider2 = await requireProvider(idOrName);
2811
+ const base = `/api/providers/${encodeURIComponent(provider2.id)}/keys`;
2812
+ const key = findKey(await api(base), ref);
2813
+ await api(`${base}/${encodeURIComponent(key.id)}`, { method: "DELETE" });
2814
+ success(`Key "${key.displayName}" removed from ${provider2.name ?? provider2.id}.`);
2815
+ }
2816
+ async function runProviderKeysSwitch(idOrName, ref, enabled) {
2817
+ const provider2 = await requireProvider(idOrName);
2818
+ const base = `/api/providers/${encodeURIComponent(provider2.id)}/keys`;
2819
+ const key = findKey(await api(base), ref);
2820
+ await api(`${base}/${encodeURIComponent(key.id)}`, { method: "PATCH", body: { enabled } });
2821
+ success(`Key "${key.displayName}" ${enabled ? "enabled" : "disabled"}.`);
2822
+ }
2610
2823
  var IMPORT_SOURCES = ["cc-switch", "alma", "claude-code", "codex", "magpie"];
2611
2824
  var SKIP_TEXT = {
2612
2825
  "official-login": "official login (not importable)",
@@ -2688,7 +2901,7 @@ async function runProviderImport(opts) {
2688
2901
  var BACKUP_PASSPHRASE_ENV = "ASTRA_BACKUP_PASSPHRASE";
2689
2902
  var BACKUP_MAX_BYTES = 32 * 1024 * 1024;
2690
2903
  async function readBackupPassphrase(question) {
2691
- const fromEnv = process.env[BACKUP_PASSPHRASE_ENV];
2904
+ const fromEnv = process5.env[BACKUP_PASSPHRASE_ENV];
2692
2905
  if (fromEnv) return fromEnv;
2693
2906
  const entered = await promptHidden(question);
2694
2907
  if (!entered) throw new AstraError("No passphrase given.", `Pipe it on stdin or set ${BACKUP_PASSPHRASE_ENV}.`);
@@ -2703,7 +2916,7 @@ function backupNote(r) {
2703
2916
  return notes.join("; ");
2704
2917
  }
2705
2918
  async function runProviderExport(opts) {
2706
- const sealed = Boolean(opts.passphraseStdin) || Boolean(process.env[BACKUP_PASSPHRASE_ENV]);
2919
+ const sealed = Boolean(opts.passphraseStdin) || Boolean(process5.env[BACKUP_PASSPHRASE_ENV]);
2707
2920
  if (sealed && opts.includeKeys) {
2708
2921
  throw new AstraError("--include-keys and a passphrase exclude each other.", "Choose plaintext keys or an encrypted file, not both.");
2709
2922
  }
@@ -2796,6 +3009,289 @@ async function runProviderImportFile(file, opts) {
2796
3009
  for (const k of result.skipped) console.log(`Skipped row ${k.index}: ${k.reason}`);
2797
3010
  }
2798
3011
 
3012
+ // src/commands/backup.ts
3013
+ import { chmod as chmod2, readFile as readFile2, stat as stat2, writeFile as writeFile2 } from "fs/promises";
3014
+ import path14 from "path";
3015
+ import process6 from "process";
3016
+ import readline2 from "readline";
3017
+ var BACKUP_PASSPHRASE_ENV2 = "ASTRA_BACKUP_PASSPHRASE";
3018
+ var SYNC_PASSPHRASE_ENV = "ASTRA_SYNC_PASSPHRASE";
3019
+ var SYNC_SECRET_ENV = "ASTRA_SYNC_SECRET";
3020
+ var BACKUP_FILE_MAX_BYTES = 96 * 1024 * 1024;
3021
+ var SYNC_KINDS = ["folder", "webdav", "s3", "github"];
3022
+ var REPLACE_CONFIRM_TEXT = "replace";
3023
+ async function api2(apiPath, method = "GET", body) {
3024
+ const { base, runtime, started } = await ensureServerRunning();
3025
+ if (started) console.log("Server was not running \u2014 started it in the background.");
3026
+ try {
3027
+ return await apiRequest({ base, path: apiPath, method, body, runtimeToken: runtime?.runtimeToken });
3028
+ } catch (e) {
3029
+ throw mapApiError(e);
3030
+ }
3031
+ }
3032
+ function mapApiError(e) {
3033
+ if (!(e instanceof ApiError)) return e;
3034
+ if (e.status === 403) {
3035
+ return new AstraError(e.message || "Forbidden.", "This is only available on the machine Astra runs on (a local request).");
3036
+ }
3037
+ return new AstraError(e.message, `HTTP ${e.status}`);
3038
+ }
3039
+ var stdinLines;
3040
+ async function readStdinLine(question) {
3041
+ if (process6.stdin.isTTY) return promptHidden(question);
3042
+ if (stdinLines === void 0) stdinLines = (await promptHidden(question)).split(/\r?\n/);
3043
+ return stdinLines.shift() ?? "";
3044
+ }
3045
+ async function readSecret(opts) {
3046
+ const what = opts.what ?? "passphrase";
3047
+ const fromEnv = process6.env[opts.env];
3048
+ if (fromEnv) return fromEnv;
3049
+ const value = await readStdinLine(opts.question);
3050
+ if (!value) throw new AstraError(`No ${what} given.`, `Pipe it on stdin, set ${opts.env}, or type it at the prompt.`);
3051
+ if (opts.confirm && process6.stdin.isTTY) {
3052
+ const again = await promptHidden("Repeat it: ");
3053
+ if (again !== value) throw new AstraError(`The two ${what}s differ.`);
3054
+ }
3055
+ return value;
3056
+ }
3057
+ function parseSections(v) {
3058
+ if (v === void 0) return void 0;
3059
+ const list2 = v.split(",").map((s) => s.trim()).filter(Boolean);
3060
+ if (list2.length === 0) throw new AstraError("--sections needs at least one section id.", "Example: --sections providers,tokens");
3061
+ for (const s of list2) if (!/^[a-z0-9][a-z0-9_.-]*$/i.test(s)) throw new AstraError(`Invalid section id "${s}".`);
3062
+ return list2;
3063
+ }
3064
+ function parsePositiveInt(v, flag) {
3065
+ if (v === void 0) return void 0;
3066
+ if (!/^\d+$/.test(v) || Number(v) < 1) throw new AstraError(`${flag} takes a positive whole number.`);
3067
+ return Number(v);
3068
+ }
3069
+ async function runBackupCreate(opts) {
3070
+ const withKeys = opts.keys !== false;
3071
+ const sections = parseSections(opts.sections);
3072
+ const passphrase = withKeys ? await readSecret({ env: BACKUP_PASSPHRASE_ENV2, question: "Passphrase for the backup: ", confirm: !opts.passphraseStdin }) : void 0;
3073
+ const res = await api2("/api/backup/export", "POST", {
3074
+ sections,
3075
+ includeKeys: withKeys,
3076
+ includeUsage: Boolean(opts.includeUsage),
3077
+ passphrase
3078
+ });
3079
+ const out = path14.resolve(opts.out ?? res.name);
3080
+ await writeFile2(out, res.content, { mode: 384 });
3081
+ await chmod2(out, 384);
3082
+ success(`Backup written to ${out}.`);
3083
+ console.log(
3084
+ `${res.documents} document${res.documents === 1 ? "" : "s"}${sections ? ` in sections: ${sections.join(", ")}` : ""}; ${res.encrypted ? "encrypted" : "not encrypted"}, ${res.hasKeys ? "includes API keys" : "no API keys"}${opts.includeUsage ? ", with usage history" : ""}.`
3085
+ );
3086
+ for (const w of res.warnings ?? []) warn(w);
3087
+ if (res.encrypted) console.log("The passphrase cannot be recovered; keep it safe.");
3088
+ }
3089
+ function renderTable(rows, headers) {
3090
+ const all = [headers, ...rows];
3091
+ const widths = headers.map((_, i) => Math.max(...all.map((r) => (r[i] ?? "").length)));
3092
+ return all.map((r) => r.map((c, i) => c.padEnd(widths[i] ?? 0)).join(" ").trimEnd());
3093
+ }
3094
+ function formatPlan(plan) {
3095
+ const lines = [];
3096
+ lines.push(
3097
+ `Backup from ${plan.createdAt} (Astra ${plan.astraVersion}), ${plan.hasKeys ? "with API keys" : "no API keys"}, mode: ${plan.mode}${plan.legacy ? " (providers-only file)" : ""}.`
3098
+ );
3099
+ const rows = plan.sections.map((s) => [s.section, String(s.added), String(s.changed), String(s.removed), String(s.unchanged)]);
3100
+ lines.push(...renderTable(rows, ["SECTION", "ADDED", "CHANGED", "REMOVED", "UNCHANGED"]));
3101
+ const sign = { added: "+", changed: "~", removed: "-" };
3102
+ for (const s of plan.sections) {
3103
+ const items = s.items.filter((i) => i.status !== "unchanged");
3104
+ if (items.length === 0) continue;
3105
+ lines.push("", `${s.section}:`);
3106
+ for (const i of items) lines.push(` ${sign[i.status] ?? "?"} ${i.label || i.id}`);
3107
+ if (s.truncated) lines.push(" \u2026 (list truncated)");
3108
+ }
3109
+ for (const n of plan.notes ?? []) lines.push("", `Note: ${n}`);
3110
+ return lines;
3111
+ }
3112
+ function isEncryptedBackup(text) {
3113
+ return /"kdf"\s*:\s*"pbkdf2-sha256"/.test(text);
3114
+ }
3115
+ function askLine(question) {
3116
+ return new Promise((resolve2) => {
3117
+ const rl = readline2.createInterface({ input: process6.stdin, output: process6.stdout });
3118
+ rl.question(question, (a) => {
3119
+ rl.close();
3120
+ resolve2(a);
3121
+ });
3122
+ });
3123
+ }
3124
+ async function runBackupRestore(file, opts) {
3125
+ const sections = parseSections(opts.sections);
3126
+ const abs = path14.resolve(file);
3127
+ let content;
3128
+ try {
3129
+ if ((await stat2(abs)).size > BACKUP_FILE_MAX_BYTES) throw new AstraError(`${abs} is too large to be an Astra backup.`);
3130
+ content = await readFile2(abs, "utf8");
3131
+ } catch (e) {
3132
+ if (e instanceof AstraError) throw e;
3133
+ throw new AstraError(`Cannot read ${abs}.`, e instanceof Error ? e.message : void 0);
3134
+ }
3135
+ const passphrase = isEncryptedBackup(content) ? await readSecret({ env: BACKUP_PASSPHRASE_ENV2, question: "Passphrase of the backup: " }) : void 0;
3136
+ const body = { source: "file", content, passphrase, sections, mode: opts.replace ? "replace" : "merge" };
3137
+ const plan = await api2("/api/backup/preview", "POST", body);
3138
+ for (const l of formatPlan(plan)) console.log(l);
3139
+ if (opts.dryRun) {
3140
+ console.log("\nDry run: nothing was changed.");
3141
+ return;
3142
+ }
3143
+ if (!opts.yes) {
3144
+ console.log("");
3145
+ if (opts.replace) {
3146
+ warn("--replace makes this Astra match the backup: what the backup does not have is removed.");
3147
+ const typed = await askLine(`Type "${REPLACE_CONFIRM_TEXT}" to continue: `);
3148
+ if (typed.trim().toLowerCase() !== REPLACE_CONFIRM_TEXT) throw new AstraError("Cancelled; nothing was changed.");
3149
+ }
3150
+ if (!await confirmPrompt("Restore this backup now? A safety copy of the current setup is kept first. [y/N] ")) {
3151
+ throw new AstraError("Cancelled; nothing was changed.");
3152
+ }
3153
+ }
3154
+ const res = await api2("/api/backup/restore", "POST", body);
3155
+ success(`Restored: ${res.written} written, ${res.removed} removed.`);
3156
+ if (res.safetyBackup) console.log(`Safety backup of the previous setup: ${res.safetyBackup}`);
3157
+ if (res.skipped?.length) {
3158
+ console.log(`Skipped (${res.skipped.length}):`);
3159
+ for (const s of res.skipped) console.log(` ${s}`);
3160
+ }
3161
+ if (res.errors?.length) {
3162
+ for (const e of res.errors) warn(e);
3163
+ process6.exitCode = 1;
3164
+ }
3165
+ }
3166
+ function printAuto(a) {
3167
+ console.log(
3168
+ `Automatic backups: ${a.enabled ? "on" : "off"}, every ${a.hours} h, keeping ${a.keep}; ${a.hasPassphrase ? "encrypted with keys" : "plain, no keys"}.`
3169
+ );
3170
+ console.log(`Folder: ${a.dir}`);
3171
+ }
3172
+ async function runBackupList() {
3173
+ const a = await api2("/api/backup/auto");
3174
+ printAuto(a);
3175
+ if (a.files.length === 0) {
3176
+ console.log("No backups yet.");
3177
+ return;
3178
+ }
3179
+ printTable(
3180
+ a.files.map((f) => [f.name, f.kind, f.at, `${Math.ceil(f.size / 1024)} KB`, f.encrypted ? "yes" : "no"]),
3181
+ ["NAME", "KIND", "WHEN", "SIZE", "ENCRYPTED"]
3182
+ );
3183
+ }
3184
+ async function runBackupAuto(opts) {
3185
+ if (opts.on && opts.off) throw new AstraError("--on and --off exclude each other.");
3186
+ const hours = parsePositiveInt(opts.hours, "--hours");
3187
+ const keep = parsePositiveInt(opts.keep, "--keep");
3188
+ let a;
3189
+ if (opts.on || opts.off || hours !== void 0 || keep !== void 0) {
3190
+ a = await api2("/api/backup/auto", "PUT", { enabled: opts.on ? true : opts.off ? false : void 0, hours, keep });
3191
+ }
3192
+ if (opts.run) {
3193
+ a = await api2("/api/backup/auto/run", "POST");
3194
+ success("Backup made.");
3195
+ }
3196
+ printAuto(a ?? await api2("/api/backup/auto"));
3197
+ }
3198
+ var PASSPHRASE_NOTE = "The sync passphrase cannot be recovered. Use the same passphrase on every machine; without it the synced data cannot be read.";
3199
+ function formatSyncStatus(s) {
3200
+ const t = s.target;
3201
+ const lines = [
3202
+ `Sync: ${s.enabled ? "on" : "off"}${s.configured ? "" : " (not configured)"}${s.running ? ", running now" : ""}`,
3203
+ `Target: ${t.kind || "-"}${t.url ? ` ${t.url}` : ""}${t.bucket ? ` bucket ${t.bucket}` : ""}${t.region ? ` (${t.region})` : ""}${t.branch ? ` branch ${t.branch}` : ""}${t.folder ? ` folder ${t.folder}` : ""}`,
3204
+ `Secret: ${t.hasSecret ? "set" : "not set"}; passphrase: ${s.hasPassphrase ? "set" : "not set"}`,
3205
+ `Every ${s.intervalMinutes} min; sections: ${s.sections.length ? s.sections.join(", ") : "all"}; API keys ${s.includeKeys ? "included" : "not included"}; sign-ins ${s.includeSignins ? "included" : "not included"}`,
3206
+ `Device: ${s.deviceId}; tracked documents: ${s.tracked}`,
3207
+ `Last sync: ${s.lastSyncAt ?? "never"} (pushed ${s.lastPushed}, pulled ${s.lastPulled})`
3208
+ ];
3209
+ if (s.lastError) lines.push(`Last error: ${s.lastError}`);
3210
+ if (s.conflicts.length) {
3211
+ lines.push("", `Conflicts (${s.conflicts.length}), the newer side was kept:`);
3212
+ for (const c of s.conflicts) lines.push(` ${c.section}/${c.label || c.id}: kept ${c.winner} (${c.at}, ${c.device})`);
3213
+ }
3214
+ return lines;
3215
+ }
3216
+ async function runSyncStatus() {
3217
+ for (const l of formatSyncStatus(await api2("/api/sync/status"))) console.log(l);
3218
+ }
3219
+ async function runSyncNow(opts) {
3220
+ const r = await api2(`/api/sync/now${opts.dryRun ? "?dryRun=true" : ""}`, "POST");
3221
+ console.log(
3222
+ `${r.dryRun ? "Dry run: would push" : "Pushed"} ${r.pushed}, ${r.dryRun ? "would pull" : "pulled"} ${r.pulled}${r.firstSync ? " (first sync)" : ""}.`
3223
+ );
3224
+ for (const i of r.items) console.log(` ${i.status}: ${i.label || i.id}`);
3225
+ for (const c of r.conflicts) console.log(` conflict ${c.section}/${c.label || c.id}: kept ${c.winner}`);
3226
+ for (const e of r.errors) warn(e);
3227
+ if (r.errors.length) process6.exitCode = 1;
3228
+ else if (!r.dryRun) success("Sync finished.");
3229
+ }
3230
+ async function runSyncEnable(enabled) {
3231
+ const s = await api2("/api/sync/config", "PUT", { enabled });
3232
+ success(`Sync is ${s.enabled ? "on" : "off"}.`);
3233
+ }
3234
+ async function runSyncTest() {
3235
+ await api2("/api/sync/test", "POST");
3236
+ success("The sync target is reachable.");
3237
+ }
3238
+ async function runSyncClearConflicts() {
3239
+ await api2("/api/sync/conflicts", "DELETE");
3240
+ success("Conflict list cleared.");
3241
+ }
3242
+ function buildSyncTarget(opts) {
3243
+ if (!opts.kind || !SYNC_KINDS.includes(opts.kind)) {
3244
+ throw new AstraError(`--kind must be one of ${SYNC_KINDS.join(", ")}.`);
3245
+ }
3246
+ if (opts.kind !== "s3" && !opts.url) {
3247
+ const hint = {
3248
+ folder: "The folder path to sync through.",
3249
+ webdav: "The WebDAV address.",
3250
+ github: "The repository, e.g. https://github.com/me/astra-sync."
3251
+ };
3252
+ throw new AstraError(`--url is required for ${opts.kind}.`, hint[opts.kind]);
3253
+ }
3254
+ if (opts.kind === "s3" && !opts.bucket) throw new AstraError("--bucket is required for s3.");
3255
+ return {
3256
+ kind: opts.kind,
3257
+ url: opts.url,
3258
+ username: opts.username,
3259
+ folder: opts.folder,
3260
+ bucket: opts.bucket,
3261
+ region: opts.region,
3262
+ pathStyle: opts.pathStyle,
3263
+ branch: opts.branch
3264
+ };
3265
+ }
3266
+ async function runSyncSetup(opts) {
3267
+ const target = buildSyncTarget(opts);
3268
+ const interval = parsePositiveInt(opts.interval, "--interval");
3269
+ const sections = parseSections(opts.sections);
3270
+ let secret;
3271
+ if (target.kind !== "folder") {
3272
+ if (process6.env[SYNC_SECRET_ENV] || opts.secretStdin) {
3273
+ secret = await readSecret({ env: SYNC_SECRET_ENV, question: "Target password / token: ", what: "secret" });
3274
+ } else if (process6.stdin.isTTY) {
3275
+ secret = await promptHidden("Target password / token (Enter to keep the stored one): ") || void 0;
3276
+ }
3277
+ }
3278
+ const passphrase = await readSecret({
3279
+ env: SYNC_PASSPHRASE_ENV,
3280
+ question: "Sync passphrase: ",
3281
+ confirm: !opts.passphraseStdin
3282
+ });
3283
+ const s = await api2("/api/sync/config", "PUT", {
3284
+ target: { ...target, secret },
3285
+ passphrase,
3286
+ intervalMinutes: interval,
3287
+ sections,
3288
+ includeKeys: opts.keys === false ? false : void 0,
3289
+ includeSignins: opts.signins ? true : void 0
3290
+ });
3291
+ success(`Sync target saved (${s.target.kind}). Run \`astra sync test\`, then \`astra sync enable\`.`);
3292
+ warn(PASSPHRASE_NOTE);
3293
+ }
3294
+
2799
3295
  // src/commands/config.ts
2800
3296
  import { spawn as spawn8 } from "child_process";
2801
3297
  async function runSetPassword() {
@@ -2823,13 +3319,13 @@ async function runSetPassword() {
2823
3319
  }
2824
3320
 
2825
3321
  // src/commands/plugin.ts
2826
- async function api2(path15, method = "GET", body) {
3322
+ async function api3(path16, method = "GET", body) {
2827
3323
  const { base, runtime, started } = await ensureServerRunning();
2828
3324
  if (started) console.log("Server was not running \u2014 started it in the background.");
2829
- return apiRequest({ base, path: path15, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 6e4 });
3325
+ return apiRequest({ base, path: path16, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 6e4 });
2830
3326
  }
2831
3327
  async function find(name) {
2832
- const { plugins } = await api2("/api/plugins");
3328
+ const { plugins } = await api3("/api/plugins");
2833
3329
  const hit = plugins.find((p) => p.spec === name) ?? plugins.find((p) => p.name === name) ?? plugins.find((p) => p.shortName === name);
2834
3330
  if (!hit) throw new AstraError(`No plugin "${name}".`, "See `astra plugin list`.");
2835
3331
  return hit;
@@ -2841,26 +3337,26 @@ async function follow(job) {
2841
3337
  printed = Math.max(printed, job.log.length);
2842
3338
  if (job.state !== "running") break;
2843
3339
  await new Promise((r) => setTimeout(r, 800));
2844
- job = await api2(`/api/plugins/jobs/${encodeURIComponent(job.id)}`);
3340
+ job = await api3(`/api/plugins/jobs/${encodeURIComponent(job.id)}`);
2845
3341
  }
2846
3342
  if (job.state === "failed") throw new AstraError(job.error ?? "The plugin task failed.");
2847
3343
  return job;
2848
3344
  }
2849
3345
  var q = (spec) => `?spec=${encodeURIComponent(spec)}`;
2850
3346
  async function runPluginList(opts) {
2851
- const list = await api2("/api/plugins");
3347
+ const list2 = await api3("/api/plugins");
2852
3348
  if (opts.json) {
2853
- console.log(JSON.stringify(list, null, 2));
3349
+ console.log(JSON.stringify(list2, null, 2));
2854
3350
  return;
2855
3351
  }
2856
- if (list.plugins.length === 0) {
3352
+ if (list2.plugins.length === 0) {
2857
3353
  info("No plugins installed. Try `astra plugin market`.");
2858
3354
  } else {
2859
3355
  printTable(
2860
- list.plugins.map((p) => [p.shortName, p.version ?? "", p.kinds.join(","), p.enabled ? "on" : "off", p.spec]),
3356
+ list2.plugins.map((p) => [p.shortName, p.version ?? "", p.kinds.join(","), p.enabled ? "on" : "off", p.spec]),
2861
3357
  ["NAME", "VERSION", "KINDS", "STATE", "SPEC"]
2862
3358
  );
2863
- for (const p of list.plugins) {
3359
+ for (const p of list2.plugins) {
2864
3360
  if (p.error) warn(`${p.shortName}: ${p.error}`);
2865
3361
  if (p.middleware?.error) warn(`${p.shortName}: middleware didn't load: ${p.middleware.error}`);
2866
3362
  else if (p.middleware)
@@ -2871,26 +3367,26 @@ async function runPluginList(opts) {
2871
3367
  else if (p.agent?.error) warn(`${p.shortName}: its client didn't load: ${p.agent.error}`);
2872
3368
  }
2873
3369
  }
2874
- const bun = list.runtime;
3370
+ const bun = list2.runtime;
2875
3371
  console.log(`Bun: ${bun.path ?? `not downloaded yet (${bun.version ?? "?"}; fetched when a provider plugin needs it)`}`);
2876
3372
  }
2877
3373
  async function runPluginAdd(spec) {
2878
- const job = await follow(await api2("/api/plugins", "POST", { spec }));
3374
+ const job = await follow(await api3("/api/plugins", "POST", { spec }));
2879
3375
  success(`Added ${job.result ?? spec}.`);
2880
3376
  }
2881
3377
  async function runPluginRemove(name) {
2882
3378
  const p = await find(name);
2883
- await follow(await api2(`/api/plugins${q(p.spec)}`, "DELETE"));
3379
+ await follow(await api3(`/api/plugins${q(p.spec)}`, "DELETE"));
2884
3380
  success(`Removed ${p.spec}.`);
2885
3381
  }
2886
3382
  async function runPluginSwitch(name, enabled) {
2887
3383
  const p = await find(name);
2888
- await api2(`/api/plugins${q(p.spec)}`, "PATCH", { enabled });
3384
+ await api3(`/api/plugins${q(p.spec)}`, "PATCH", { enabled });
2889
3385
  success(`${p.shortName} is ${enabled ? "on" : "off"}.`);
2890
3386
  }
2891
3387
  async function runPluginUpdate(name) {
2892
3388
  const spec = name ? (await find(name)).spec : void 0;
2893
- await follow(await api2("/api/plugins/update", "POST", { spec }));
3389
+ await follow(await api3("/api/plugins/update", "POST", { spec }));
2894
3390
  success(name ? `Updated ${name}.` : "Updated every plugin.");
2895
3391
  }
2896
3392
  async function runPluginOptions(name, value) {
@@ -2912,12 +3408,12 @@ async function runPluginOptions(name, value) {
2912
3408
  }
2913
3409
  if (options === null || typeof options !== "object" || Array.isArray(options)) throw new AstraError("The options must be a JSON object.");
2914
3410
  }
2915
- await api2(`/api/plugins${q(p.spec)}`, "PATCH", { options });
3411
+ await api3(`/api/plugins${q(p.spec)}`, "PATCH", { options });
2916
3412
  success(options === null ? `Cleared ${p.shortName}'s options.` : `Set ${p.shortName}'s options.`);
2917
3413
  }
2918
3414
  async function runPluginUse(name, provider2) {
2919
3415
  const p = await find(name);
2920
- await api2("/api/plugins/prefer", "POST", { spec: p.spec, provider: provider2 });
3416
+ await api3("/api/plugins/prefer", "POST", { spec: p.spec, provider: provider2 });
2921
3417
  success(`${p.shortName} serves ${provider2} now.`);
2922
3418
  }
2923
3419
  function marketOrigin(l) {
@@ -2926,14 +3422,14 @@ function marketOrigin(l) {
2926
3422
  }
2927
3423
  async function runPluginMarket(query) {
2928
3424
  if (query) {
2929
- const results = await api2(`/api/plugins/search?q=${encodeURIComponent(query)}`);
3425
+ const results = await api3(`/api/plugins/search?q=${encodeURIComponent(query)}`);
2930
3426
  printTable(
2931
3427
  results.map((r) => [r.spec, r.kind, r.version ?? "", r.source, (r.description ?? "").slice(0, 60)]),
2932
3428
  ["SPEC", "KIND", "VERSION", "FROM", "DESCRIPTION"]
2933
3429
  );
2934
3430
  return;
2935
3431
  }
2936
- const listings = await api2("/api/plugins/market");
3432
+ const listings = await api3("/api/plugins/market");
2937
3433
  printTable(
2938
3434
  listings.map((l) => [l.package, l.kind, l.latest ?? "", marketOrigin(l), l.summary.en ?? ""]),
2939
3435
  ["PACKAGE", "KIND", "LATEST", "FROM", "SUMMARY"]
@@ -2941,26 +3437,26 @@ async function runPluginMarket(query) {
2941
3437
  info("Install one with `astra plugin add <package>`.");
2942
3438
  }
2943
3439
  async function findV2(id) {
2944
- const { plugins } = await api2("/api/plugins/v2");
3440
+ const { plugins } = await api3("/api/plugins/v2");
2945
3441
  const hit = plugins.find((p) => p.id === id || p.spec === id || p.name === id);
2946
3442
  if (!hit) throw new AstraError(`No v2 plugin "${id}".`, "See `astra plugin v2`.");
2947
3443
  return hit;
2948
3444
  }
2949
3445
  async function runPluginV2List(opts) {
2950
- const list = await api2("/api/plugins/v2");
3446
+ const list2 = await api3("/api/plugins/v2");
2951
3447
  if (opts.json) {
2952
- console.log(JSON.stringify(list, null, 2));
3448
+ console.log(JSON.stringify(list2, null, 2));
2953
3449
  return;
2954
3450
  }
2955
- if (list.plugins.length === 0) {
3451
+ if (list2.plugins.length === 0) {
2956
3452
  info("No v2 plugins installed.");
2957
3453
  return;
2958
3454
  }
2959
3455
  printTable(
2960
- list.plugins.map((p) => [p.id, p.version, p.running ? "running" : p.enabled ? "idle" : "off", p.missing.length ? `needs ${p.missing.join(", ")}` : "", p.spec]),
3456
+ list2.plugins.map((p) => [p.id, p.version, p.running ? "running" : p.enabled ? "idle" : "off", p.missing.length ? `needs ${p.missing.join(", ")}` : "", p.spec]),
2961
3457
  ["ID", "VERSION", "STATE", "PERMISSIONS", "SPEC"]
2962
3458
  );
2963
- for (const p of list.plugins) {
3459
+ for (const p of list2.plugins) {
2964
3460
  if (p.problem) warn(`${p.id}: ${p.problem}`);
2965
3461
  if (p.lastError) warn(`${p.id}: ${p.lastError}`);
2966
3462
  if (p.contributes.commands.length) console.log(` ${p.id} commands: ${p.contributes.commands.map((c) => c.id).join(", ")}`);
@@ -2976,7 +3472,7 @@ async function runPluginGrant(id, opts) {
2976
3472
  console.log(`${p.name} asks for:`);
2977
3473
  for (const perm of asked) console.log(` ${p.sensitive.includes(perm) ? "!" : "-"} ${perm}`);
2978
3474
  if (!opts.yes && !await confirm("Grant these permissions?")) return;
2979
- await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/grant`, "POST", { permissions: asked });
3475
+ await api3(`/api/plugins/v2/${encodeURIComponent(p.id)}/grant`, "POST", { permissions: asked });
2980
3476
  success(`Granted ${asked.length} permission(s) to ${p.id}.`);
2981
3477
  }
2982
3478
  async function runPluginRun(id, command, args) {
@@ -2989,7 +3485,7 @@ async function runPluginRun(id, command, args) {
2989
3485
  }
2990
3486
  }
2991
3487
  const p = await findV2(id);
2992
- const r = await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/commands/${encodeURIComponent(command)}`, "POST", { args: parsed });
3488
+ const r = await api3(`/api/plugins/v2/${encodeURIComponent(p.id)}/commands/${encodeURIComponent(command)}`, "POST", { args: parsed });
2993
3489
  console.log(typeof r.result === "string" ? r.result : JSON.stringify(r.result, null, 2));
2994
3490
  }
2995
3491
  async function runPluginSettings(id, values, opts = {}) {
@@ -3009,16 +3505,16 @@ async function runPluginSettings(id, values, opts = {}) {
3009
3505
  secrets[s.slice(0, at)] = s.slice(at + 1) || null;
3010
3506
  }
3011
3507
  if (!parsed && Object.keys(secrets).length === 0) {
3012
- const detail = await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}`);
3508
+ const detail = await api3(`/api/plugins/v2/${encodeURIComponent(p.id)}`);
3013
3509
  console.log(JSON.stringify(detail.plugin.settings, null, 2));
3014
3510
  if (detail.plugin.secretsSet.length) info(`Secrets set: ${detail.plugin.secretsSet.join(", ")}`);
3015
3511
  return;
3016
3512
  }
3017
- await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/settings`, "PUT", { values: parsed, secrets });
3513
+ await api3(`/api/plugins/v2/${encodeURIComponent(p.id)}/settings`, "PUT", { values: parsed, secrets });
3018
3514
  success(`Saved ${p.id}'s settings.`);
3019
3515
  }
3020
3516
  async function runPluginUpgrade(name, opts) {
3021
- const successors = await api2("/api/plugins/v2/successors");
3517
+ const successors = await api3("/api/plugins/v2/successors");
3022
3518
  if (!name) {
3023
3519
  if (successors.length === 0) {
3024
3520
  info("No installed plugin has a v2 version in the market.");
@@ -3037,26 +3533,26 @@ async function runPluginUpgrade(name, opts) {
3037
3533
  console.log(`${s.name} ${s.version} asks for:`);
3038
3534
  for (const perm of s.permissions) console.log(` ${s.sensitive.includes(perm) ? "!" : "-"} ${perm}`);
3039
3535
  if (!opts.yes && !await confirm("Grant these and upgrade?")) return;
3040
- await follow(await api2("/api/plugins/v2/upgrade", "POST", { spec: s.spec, grant: s.permissions }));
3536
+ await follow(await api3("/api/plugins/v2/upgrade", "POST", { spec: s.spec, grant: s.permissions }));
3041
3537
  success(`Upgraded ${s.v1Name} to ${s.name} ${s.version}.`);
3042
3538
  }
3043
3539
  async function runPluginDev(dir, opts) {
3044
3540
  const { readFileSync } = await import("fs");
3045
- const { resolve } = await import("path");
3046
- const root = resolve(dir);
3541
+ const { resolve: resolve2 } = await import("path");
3542
+ const root = resolve2(dir);
3047
3543
  let id;
3048
3544
  try {
3049
- id = JSON.parse(readFileSync(resolve(root, "astra.plugin.json"), "utf8")).id ?? "";
3545
+ id = JSON.parse(readFileSync(resolve2(root, "astra.plugin.json"), "utf8")).id ?? "";
3050
3546
  } catch {
3051
3547
  throw new AstraError(`${root} has no readable astra.plugin.json.`, "Start one with `npx @astragate/plugin-sdk init`.");
3052
3548
  }
3053
3549
  if (!id) throw new AstraError("astra.plugin.json has no id.");
3054
- const list = await api2("/api/plugins/v2");
3055
- const mounted = list.plugins.some((p2) => p2.spec === root);
3056
- if (!mounted) await follow(await api2("/api/plugins", "POST", { spec: root }));
3550
+ const list2 = await api3("/api/plugins/v2");
3551
+ const mounted = list2.plugins.some((p2) => p2.spec === root);
3552
+ if (!mounted) await follow(await api3("/api/plugins", "POST", { spec: root }));
3057
3553
  let p;
3058
3554
  for (let i = 0; i < 20 && !p; i++) {
3059
- p = (await api2("/api/plugins/v2")).plugins.find((x) => x.id === id);
3555
+ p = (await api3("/api/plugins/v2")).plugins.find((x) => x.id === id);
3060
3556
  if (!p) await new Promise((r) => setTimeout(r, 500));
3061
3557
  }
3062
3558
  if (!p) throw new AstraError(`Astra didn't load ${id}.`, "Run `astra-plugin validate` in the folder, or see `astra plugin v2`.");
@@ -3073,7 +3569,7 @@ async function runPluginDev(dir, opts) {
3073
3569
  let lastProblem;
3074
3570
  while (!stop) {
3075
3571
  try {
3076
- const detail = await api2(`/api/plugins/v2/${encodeURIComponent(id)}`);
3572
+ const detail = await api3(`/api/plugins/v2/${encodeURIComponent(id)}`);
3077
3573
  for (const l of detail.lines.filter((l2) => l2.at > last)) {
3078
3574
  const line = `${l.at.slice(11, 19)} ${l.level.padEnd(5)} ${l.text}`;
3079
3575
  if (l.level === "error") warn(line);
@@ -3090,24 +3586,24 @@ async function runPluginDev(dir, opts) {
3090
3586
  await Promise.race([done, new Promise((r) => setTimeout(r, 1e3))]);
3091
3587
  }
3092
3588
  if (!opts.keep && !mounted) {
3093
- await follow(await api2(`/api/plugins${q(root)}`, "DELETE"));
3589
+ await follow(await api3(`/api/plugins${q(root)}`, "DELETE"));
3094
3590
  success(`Unmounted ${id}.`);
3095
3591
  }
3096
3592
  }
3097
3593
  async function runPluginTest(dir, opts) {
3098
3594
  const { readFileSync } = await import("fs");
3099
- const { resolve } = await import("path");
3100
- const root = resolve(dir);
3595
+ const { resolve: resolve2 } = await import("path");
3596
+ const root = resolve2(dir);
3101
3597
  let id;
3102
3598
  try {
3103
- id = JSON.parse(readFileSync(resolve(root, "astra.plugin.json"), "utf8")).id ?? "";
3599
+ id = JSON.parse(readFileSync(resolve2(root, "astra.plugin.json"), "utf8")).id ?? "";
3104
3600
  } catch {
3105
3601
  throw new AstraError(`${root} has no readable astra.plugin.json.`);
3106
3602
  }
3107
- const mounted = (await api2("/api/plugins/v2")).plugins.some((p) => p.spec === root);
3108
- if (!mounted) await follow(await api2("/api/plugins", "POST", { spec: root }));
3603
+ const mounted = (await api3("/api/plugins/v2")).plugins.some((p) => p.spec === root);
3604
+ if (!mounted) await follow(await api3("/api/plugins", "POST", { spec: root }));
3109
3605
  try {
3110
- const results = await api2(
3606
+ const results = await api3(
3111
3607
  `/api/plugins/v2/${encodeURIComponent(id)}/test`,
3112
3608
  "POST",
3113
3609
  {}
@@ -3130,12 +3626,12 @@ async function runPluginTest(dir, opts) {
3130
3626
  process.exitCode = 1;
3131
3627
  } else success(`${passed} passed in Astra's sandbox.`);
3132
3628
  } finally {
3133
- if (!mounted) await follow(await api2(`/api/plugins${q(root)}`, "DELETE"));
3629
+ if (!mounted) await follow(await api3(`/api/plugins${q(root)}`, "DELETE"));
3134
3630
  }
3135
3631
  }
3136
3632
  async function runPluginRollback(id, opts) {
3137
3633
  if (!opts.yes && !await confirm(`Remove ${id} and reinstall the v1 plugin it replaced?`)) return;
3138
- await follow(await api2(`/api/plugins/v2/${encodeURIComponent(id)}/rollback`, "POST", {}));
3634
+ await follow(await api3(`/api/plugins/v2/${encodeURIComponent(id)}/rollback`, "POST", {}));
3139
3635
  success(`${id} is back on its v1 plugin.`);
3140
3636
  }
3141
3637
  async function confirm(question) {
@@ -3149,6 +3645,253 @@ async function confirm(question) {
3149
3645
  }
3150
3646
  }
3151
3647
 
3648
+ // src/commands/tool.ts
3649
+ import { mkdir, writeFile as writeFile3 } from "fs/promises";
3650
+ import { dirname, extname, resolve } from "path";
3651
+ var PRIMARY = { web_search: "query", web_fetch: "url", generate_image: "prompt" };
3652
+ async function api4(path16, method = "GET", body) {
3653
+ const { base, runtime, started } = await ensureServerRunning();
3654
+ if (started) console.log("Server was not running \u2014 started it in the background.");
3655
+ return apiRequest({ base, path: path16, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 18e4 });
3656
+ }
3657
+ async function runToolList(opts) {
3658
+ const tools = await api4("/api/tools");
3659
+ if (opts.json) {
3660
+ console.log(JSON.stringify(tools, null, 2));
3661
+ return;
3662
+ }
3663
+ printTable(
3664
+ tools.map((t) => [t.name, t.source, t.available ? "yes" : `no (${t.reason ?? "not available"})`, t.description ?? ""]),
3665
+ ["Tool", "Source", "Available", "Description"]
3666
+ );
3667
+ }
3668
+ function parseKeyValues(pairs) {
3669
+ const out = {};
3670
+ for (const pair of pairs) {
3671
+ const at = pair.indexOf("=");
3672
+ if (at <= 0) throw new AstraError(`"${pair}" is not key=value`);
3673
+ const key = pair.slice(0, at);
3674
+ const raw = pair.slice(at + 1);
3675
+ try {
3676
+ out[key] = JSON.parse(raw);
3677
+ } catch {
3678
+ out[key] = raw;
3679
+ }
3680
+ }
3681
+ return out;
3682
+ }
3683
+ function buildArgs(name, words, opts) {
3684
+ let args = {};
3685
+ if (opts.json) {
3686
+ let parsed;
3687
+ try {
3688
+ parsed = JSON.parse(opts.json);
3689
+ } catch {
3690
+ throw new AstraError("--json must be a JSON object");
3691
+ }
3692
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new AstraError("--json must be a JSON object");
3693
+ args = { ...parsed };
3694
+ }
3695
+ Object.assign(args, parseKeyValues(opts.arg ?? []));
3696
+ if (words.length > 0) {
3697
+ const primary = PRIMARY[name];
3698
+ if (!primary) throw new AstraError(`${name} takes its arguments as --arg key=value or --json '{...}'`);
3699
+ args[primary] = words.join(" ");
3700
+ }
3701
+ return args;
3702
+ }
3703
+ var EXTENSIONS = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", "image/gif": ".gif" };
3704
+ function imagePath(output, index, mimeType) {
3705
+ const full = resolve(output);
3706
+ const ext = extname(full) || EXTENSIONS[mimeType ?? ""] || ".png";
3707
+ const stem = extname(full) ? full.slice(0, -extname(full).length) : full;
3708
+ return index === 0 ? stem + ext : `${stem}-${index + 1}${ext}`;
3709
+ }
3710
+ async function runToolRun(name, words, opts) {
3711
+ const args = buildArgs(name, words, opts);
3712
+ const token2 = opts.token ?? process.env.ASTRA_API_KEY;
3713
+ const result = await api4("/api/tools/run", "POST", { name, args, ...token2 ? { token: token2 } : {} });
3714
+ if (opts.raw) {
3715
+ console.log(JSON.stringify(result, null, 2));
3716
+ if (result.isError) process.exitCode = 1;
3717
+ return;
3718
+ }
3719
+ let images = 0;
3720
+ for (const block of result.content) {
3721
+ if (block.type === "text") {
3722
+ if (result.isError) console.error(block.text ?? "");
3723
+ else console.log(block.text ?? "");
3724
+ } else if (block.type === "image" && block.data) {
3725
+ const target = imagePath(opts.output ?? `${name.replace(/\W+/g, "-")}-${Date.now()}`, images++, block.mimeType);
3726
+ await mkdir(dirname(target), { recursive: true });
3727
+ await writeFile3(target, Buffer.from(block.data, "base64"));
3728
+ success(`Saved ${target}`);
3729
+ }
3730
+ }
3731
+ if (opts.output && images === 0 && !result.isError) {
3732
+ const text = result.content.filter((b) => b.type === "text").map((b) => b.text ?? "").join("\n");
3733
+ await mkdir(dirname(resolve(opts.output)), { recursive: true });
3734
+ await writeFile3(resolve(opts.output), text);
3735
+ info(`Wrote ${resolve(opts.output)}`);
3736
+ }
3737
+ if (result.isError) process.exitCode = 1;
3738
+ }
3739
+
3740
+ // src/commands/group.ts
3741
+ var GROUP_MODES = ["smart", "order", "rotate", "usage", "pace", "weight"];
3742
+ var GROUP_STAYS = ["auto", "session", "turn", "off", "strict"];
3743
+ var MODE_ALIASES = { fast: "smart", inorder: "order", "in-order": "order", "in-turn": "rotate", "least-used": "usage" };
3744
+ async function api5(path16, method = "GET", body) {
3745
+ const { base, runtime, started } = await ensureServerRunning();
3746
+ if (started) console.log("Server was not running \u2014 started it in the background.");
3747
+ return apiRequest({ base, path: path16, method, body, runtimeToken: runtime?.runtimeToken });
3748
+ }
3749
+ function parseMember(text) {
3750
+ const at = text.indexOf("/");
3751
+ if (at <= 0 || at === text.length - 1)
3752
+ throw new AstraError(`"${text}" is not a member.`, "Write a member as provider/model, or group/<slug> for another group.");
3753
+ const head = text.slice(0, at);
3754
+ const rest = text.slice(at + 1);
3755
+ return head === "group" ? { group: rest, weight: 1 } : { provider: head, model: rest, weight: 1 };
3756
+ }
3757
+ var memberText = (m) => m.group ? `group/${m.group}` : `${m.provider}/${m.model}`;
3758
+ function list(value) {
3759
+ return value.split(",").map((s) => s.trim()).filter(Boolean);
3760
+ }
3761
+ var yes = (v) => {
3762
+ if (["yes", "true", "on", "1"].includes(v.toLowerCase())) return true;
3763
+ if (["no", "false", "off", "0"].includes(v.toLowerCase())) return false;
3764
+ throw new AstraError(`"${v}" is not yes or no.`);
3765
+ };
3766
+ function parseGroupWords(words, current = []) {
3767
+ const edit = {};
3768
+ let members;
3769
+ const weights = /* @__PURE__ */ new Map();
3770
+ let resetWeights = false;
3771
+ for (const word of words) {
3772
+ const m = /^([a-z]+)(\+=|-=|=)(.*)$/i.exec(word);
3773
+ if (!m) throw new AstraError(`"${word}" is not key=value.`, "Example: models=claude/opus,copilot/opus routing=smart");
3774
+ const key = m[1].toLowerCase();
3775
+ const op = m[2];
3776
+ const value = m[3];
3777
+ switch (key) {
3778
+ case "models":
3779
+ case "members": {
3780
+ const items = list(value).map(parseMember);
3781
+ const base = members ?? current;
3782
+ if (op === "=") members = items;
3783
+ else if (op === "+=") members = [...base, ...items.filter((i) => !base.some((b) => memberText(b) === memberText(i)))];
3784
+ else members = base.filter((b) => !items.some((i) => memberText(i) === memberText(b)));
3785
+ break;
3786
+ }
3787
+ case "routing":
3788
+ case "mode": {
3789
+ const mode = MODE_ALIASES[value.toLowerCase()] ?? value.toLowerCase();
3790
+ if (!GROUP_MODES.includes(mode))
3791
+ throw new AstraError(`Unknown routing "${value}".`, `Use one of: ${GROUP_MODES.join(", ")}.`);
3792
+ edit.mode = mode;
3793
+ break;
3794
+ }
3795
+ case "stays": {
3796
+ if (!GROUP_STAYS.includes(value.toLowerCase()))
3797
+ throw new AstraError(`Unknown stays "${value}".`, `Use one of: ${GROUP_STAYS.join(", ")}.`);
3798
+ edit.stays = value.toLowerCase();
3799
+ break;
3800
+ }
3801
+ case "weight": {
3802
+ if (value === "") resetWeights = true;
3803
+ for (const item of list(value)) {
3804
+ const eq = item.lastIndexOf("=");
3805
+ const weight = Number(item.slice(eq + 1));
3806
+ if (eq <= 0 || !Number.isInteger(weight) || weight < 1 || weight > 1e3)
3807
+ throw new AstraError(`"${item}" is not member=weight.`, "A weight is a whole number from 1 to 1000, e.g. weight=claude/opus=3.");
3808
+ weights.set(memberText(parseMember(item.slice(0, eq))), weight);
3809
+ }
3810
+ break;
3811
+ }
3812
+ case "listed":
3813
+ edit.listed = yes(value);
3814
+ break;
3815
+ case "enabled":
3816
+ edit.enabled = yes(value);
3817
+ break;
3818
+ case "name":
3819
+ edit.name = value;
3820
+ break;
3821
+ case "slug":
3822
+ edit.slug = value;
3823
+ break;
3824
+ default:
3825
+ throw new AstraError(`Unknown setting "${key}".`, "Use models, routing, stays, weight, listed, enabled, name or slug.");
3826
+ }
3827
+ }
3828
+ if (members || weights.size > 0 || resetWeights) {
3829
+ const base = (members ?? current).map((x) => ({ ...x }));
3830
+ for (const x of base) {
3831
+ if (resetWeights) x.weight = 1;
3832
+ const w = weights.get(memberText(x));
3833
+ if (w !== void 0) x.weight = w;
3834
+ }
3835
+ for (const key of weights.keys())
3836
+ if (!base.some((x) => memberText(x) === key)) throw new AstraError(`"${key}" is not a member of this group.`, "Set weight= after models=.");
3837
+ edit.members = base;
3838
+ }
3839
+ return edit;
3840
+ }
3841
+ async function findGroup(ref) {
3842
+ const groups = await api5("/api/routing/groups");
3843
+ const needle = ref.toLowerCase().replace(/^group\//, "");
3844
+ const found = groups.find((g) => g.id.toLowerCase() === ref.toLowerCase()) ?? groups.find((g) => g.slug === needle) ?? groups.find((g) => g.name.toLowerCase() === ref.toLowerCase());
3845
+ if (!found) throw new AstraError(`No group matches "${ref}".`, "Run `astra group list` to see the groups.");
3846
+ return found;
3847
+ }
3848
+ async function runGroupList() {
3849
+ const groups = await api5("/api/routing/groups");
3850
+ if (groups.length === 0) {
3851
+ console.log('No routing groups yet. Make one with: astra group add "Opus anywhere" models=claude/claude-opus-5-5,copilot/claude-opus-5.5 routing=smart');
3852
+ return;
3853
+ }
3854
+ printTable(
3855
+ groups.map((g) => [g.modelId, g.name, g.mode, g.stays, String(g.members.length), g.enabled ? g.listed ? "on" : "on, unlisted" : "off"]),
3856
+ ["MODEL", "NAME", "ROUTING", "STAYS", "MEMBERS", "STATE"]
3857
+ );
3858
+ }
3859
+ async function runGroupShow(ref) {
3860
+ const group2 = await findGroup(ref);
3861
+ const status = await api5(`/api/routing/groups/${encodeURIComponent(group2.id)}/status`);
3862
+ console.log(`${group2.name} (${group2.modelId})`);
3863
+ console.log(`routing=${group2.mode} stays=${group2.stays} ${group2.enabled ? "on" : "off"}${group2.listed ? "" : " unlisted"}`);
3864
+ const live = new Map(status.members.map((m) => [m.key, m]));
3865
+ printTable(
3866
+ group2.members.map((m, i) => {
3867
+ const s = live.get(memberText(m));
3868
+ const quota = s?.usedPercent != null ? `${Math.round(s.usedPercent)}% used${s.resetsAt ? `, renews ${s.resetsAt}` : ""}` : "quota unknown";
3869
+ const state = s ? s.health === "cooling" && s.coolingUntil ? `cooling until ${s.coolingUntil}` : s.health : "";
3870
+ return [String(i + 1), memberText(m), group2.mode === "weight" ? String(m.weight) : "", state, quota, s?.problem ?? ""];
3871
+ }),
3872
+ ["#", "MEMBER", "WEIGHT", "STATE", "QUOTA", "PROBLEM"]
3873
+ );
3874
+ if (status.lastReason) console.log(`Last choice: ${status.lastReason}${status.lastDecisionAt ? ` (${status.lastDecisionAt})` : ""}`);
3875
+ }
3876
+ async function runGroupAdd(name, words) {
3877
+ const edit = parseGroupWords(words);
3878
+ if (!edit.members?.length) throw new AstraError("A group needs members.", "Add models=provider/model,provider/model.");
3879
+ const group2 = await api5("/api/routing/groups", "POST", { name, ...edit });
3880
+ success(`Group ${group2.modelId} created with ${group2.members.length} member${group2.members.length === 1 ? "" : "s"} (routing=${group2.mode}).`);
3881
+ }
3882
+ async function runGroupSet(ref, words) {
3883
+ const group2 = await findGroup(ref);
3884
+ const edit = parseGroupWords(words, group2.members);
3885
+ if (Object.keys(edit).length === 0) throw new AstraError("Nothing to change.", "Give key=value words, e.g. routing=usage.");
3886
+ await api5(`/api/routing/groups/${encodeURIComponent(group2.id)}`, "PATCH", edit);
3887
+ success(`Group ${group2.modelId} updated.`);
3888
+ }
3889
+ async function runGroupRemove(ref) {
3890
+ const group2 = await findGroup(ref);
3891
+ await api5(`/api/routing/groups/${encodeURIComponent(group2.id)}`, "DELETE");
3892
+ success(`Group ${group2.modelId} removed.`);
3893
+ }
3894
+
3152
3895
  // src/commands/restore-all.ts
3153
3896
  import { spawn as spawn9 } from "child_process";
3154
3897
  async function runRestoreAll(opts) {
@@ -3167,8 +3910,8 @@ async function runRestoreAll(opts) {
3167
3910
  // src/commands/claude.ts
3168
3911
  import fs16 from "fs";
3169
3912
  import os6 from "os";
3170
- import path14 from "path";
3171
- import process5 from "process";
3913
+ import path15 from "path";
3914
+ import process7 from "process";
3172
3915
  import { spawn as spawn10 } from "child_process";
3173
3916
  var PREPARE_PATH = "/api/clients/claude-code/direct/prepare";
3174
3917
  var ACCOUNT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
@@ -3236,8 +3979,8 @@ async function runClaude(opts, deps = {}) {
3236
3979
  "Pick the subscription account in the Astra web UI (Clients \u2192 Claude Code) and copy its id."
3237
3980
  );
3238
3981
  }
3239
- const env = deps.env ?? process5.env;
3240
- const cwd = deps.cwd ?? process5.cwd();
3982
+ const env = deps.env ?? process7.env;
3983
+ const cwd = deps.cwd ?? process7.cwd();
3241
3984
  if (opts.status) {
3242
3985
  printStatus(await prepareLaunch(opts.account));
3243
3986
  return;
@@ -3248,7 +3991,7 @@ async function runClaude(opts, deps = {}) {
3248
3991
  printLaunch(launch);
3249
3992
  const spawnImpl = deps.spawn ?? spawnOfficial;
3250
3993
  const result = await runInherit(spawnImpl, [], childEnv, cwd);
3251
- process5.exitCode = exitCodeFrom(result.code);
3994
+ process7.exitCode = exitCodeFrom(result.code);
3252
3995
  }
3253
3996
  function printLaunch(launch) {
3254
3997
  info(
@@ -3283,9 +4026,9 @@ async function prepareLaunch(accountId) {
3283
4026
  return validateLaunchResponse(response);
3284
4027
  }
3285
4028
  function claudeConfigDir(env, override) {
3286
- if (override) return path14.resolve(override);
4029
+ if (override) return path15.resolve(override);
3287
4030
  const configured = env.CLAUDE_CONFIG_DIR?.trim();
3288
- return configured ? configured : path14.join(os6.homedir(), ".claude");
4031
+ return configured ? configured : path15.join(os6.homedir(), ".claude");
3289
4032
  }
3290
4033
  function validateLaunchResponse(raw) {
3291
4034
  if (!isPlainObject(raw)) throw invalidLaunch();
@@ -3352,24 +4095,24 @@ function assertNoSettingsConflicts(configDirectory, cwd) {
3352
4095
  );
3353
4096
  }
3354
4097
  function settingsFilesToCheck(configDirectory, cwd) {
3355
- const files = [path14.join(configDirectory, "settings.json")];
4098
+ const files = [path15.join(configDirectory, "settings.json")];
3356
4099
  const root = findGitRoot(cwd);
3357
- let dir = path14.resolve(cwd);
4100
+ let dir = path15.resolve(cwd);
3358
4101
  for (; ; ) {
3359
- files.push(path14.join(dir, ".claude", "settings.json"));
3360
- files.push(path14.join(dir, ".claude", "settings.local.json"));
4102
+ files.push(path15.join(dir, ".claude", "settings.json"));
4103
+ files.push(path15.join(dir, ".claude", "settings.local.json"));
3361
4104
  if (root === null || dir === root) break;
3362
- const parent = path14.dirname(dir);
4105
+ const parent = path15.dirname(dir);
3363
4106
  if (parent === dir) break;
3364
4107
  dir = parent;
3365
4108
  }
3366
4109
  return [...new Set(files)];
3367
4110
  }
3368
4111
  function findGitRoot(startDir) {
3369
- let dir = path14.resolve(startDir);
4112
+ let dir = path15.resolve(startDir);
3370
4113
  for (; ; ) {
3371
- if (fs16.existsSync(path14.join(dir, ".git"))) return dir;
3372
- const parent = path14.dirname(dir);
4114
+ if (fs16.existsSync(path15.join(dir, ".git"))) return dir;
4115
+ const parent = path15.dirname(dir);
3373
4116
  if (parent === dir) return null;
3374
4117
  dir = parent;
3375
4118
  }
@@ -3426,7 +4169,7 @@ function exitCodeFrom(code) {
3426
4169
  return code ?? 1;
3427
4170
  }
3428
4171
  function runInherit(spawnImpl, args, env, cwd) {
3429
- return new Promise((resolve, reject) => {
4172
+ return new Promise((resolve2, reject) => {
3430
4173
  let child;
3431
4174
  try {
3432
4175
  child = spawnImpl(OFFICIAL_CLI, args, {
@@ -3449,18 +4192,18 @@ function runInherit(spawnImpl, args, env, cwd) {
3449
4192
  const onInterrupt = () => forward("SIGINT");
3450
4193
  const onTerminate = () => forward("SIGTERM");
3451
4194
  const cleanup = () => {
3452
- process5.removeListener("SIGINT", onInterrupt);
3453
- process5.removeListener("SIGTERM", onTerminate);
4195
+ process7.removeListener("SIGINT", onInterrupt);
4196
+ process7.removeListener("SIGTERM", onTerminate);
3454
4197
  };
3455
- process5.on("SIGINT", onInterrupt);
3456
- process5.on("SIGTERM", onTerminate);
4198
+ process7.on("SIGINT", onInterrupt);
4199
+ process7.on("SIGTERM", onTerminate);
3457
4200
  child.on("error", (err) => {
3458
4201
  cleanup();
3459
4202
  reject(spawnFailure(err));
3460
4203
  });
3461
4204
  child.on("close", (code) => {
3462
4205
  cleanup();
3463
- resolve({ code });
4206
+ resolve2({ code });
3464
4207
  });
3465
4208
  });
3466
4209
  }
@@ -3545,7 +4288,14 @@ client.command("enable").description("Enable a client and point it at Astra").ad
3545
4288
  ).action(
3546
4289
  (kind, opts) => runClientEnable(kind, opts)
3547
4290
  );
4291
+ client.command("use").description("Switch a client to <provider>/<model> in one step (e.g. `astra client use claude-code deepseek/deepseek-v4-pro`)").addArgument(clientKindArgument()).argument("<target>", "provider/model, or a model of the client's current provider").action((kind, target) => runClientUse(kind, target));
4292
+ client.command("shortlist").description("Limit the models a client sees to the ones listed (none = no limit)").addArgument(clientKindArgument()).argument("[models...]", "Model ids the client should see").action((kind, models) => runClientShortlist(kind, models));
3548
4293
  client.command("disable").description("Disable a client and restore its original configuration").addArgument(clientKindArgument()).action((kind) => runClientDisable(kind));
4294
+ var profile = program.command("profile").description("Profiles: save every client's setup under a name and switch them all at once");
4295
+ profile.command("list").description("List profiles").action(() => runProfileList());
4296
+ profile.command("save").description("Save the clients' current setup as a profile (overwrites a profile of the same name)").argument("<name>").action((name) => runProfileSave(name));
4297
+ profile.command("use").description("Apply a profile: switch every client in it through the normal enable / disable path").argument("<name>").option("--dry-run", "Only show what would change").action((name, opts) => runProfileUse(name, opts));
4298
+ profile.command("rm").description("Delete a profile (the clients' configurations do not change)").argument("<name>").action((name) => runProfileRemove(name));
3549
4299
  var token = program.command("token").description("Manage tokens (credentials clients use to reach Astra)");
3550
4300
  token.command("list").description("List tokens with today's and lifetime usage").action(() => runTokenList());
3551
4301
  var provider = program.command("provider").description("Manage providers (upstream AI accounts)");
@@ -3558,7 +4308,26 @@ provider.command("export").description("Export providers and their models to a b
3558
4308
  (opts) => runProviderExport(opts)
3559
4309
  );
3560
4310
  provider.command("import-file <file>").description("Preview a backup file made by `provider export`, or with --yes import its providers").option("--yes", "Import the new entries (or those named with --only)").option("--only <row...>", "With --yes: import only these preview rows").action((file, opts) => runProviderImportFile(file, opts));
4311
+ var providerKeys = provider.command("keys").description("Several API keys on one provider");
4312
+ providerKeys.command("list").description("List a provider's API keys").argument("<provider>", "Provider id or name").action((id) => runProviderKeysList(id));
4313
+ providerKeys.command("add").description("Add an API key to a provider (the key is read from --key, ASTRA_API_KEY or a hidden prompt)").argument("<provider>", "Provider id or name").option("--key <apiKey>", "The API key").option("--name <name>", "Name shown in the list").option("--protocol <protocol>", "Use the key for this protocol only: openai-chat | openai-responses | anthropic | gemini").option("--weight <n>", "Share of balanced traffic, 1-1000 (default 1)").option("--proxy <url>", "The key's own HTTP proxy").option("--notes <text>", "A note").action(
4314
+ (id, opts) => runProviderKeysAdd(id, opts)
4315
+ );
4316
+ providerKeys.command("remove").description("Remove an API key").argument("<provider>", "Provider id or name").argument("<key>", "Key id, name or its number in the list").action((id, key) => runProviderKeysRemove(id, key));
4317
+ providerKeys.command("enable").description("Switch an API key on").argument("<provider>", "Provider id or name").argument("<key>", "Key id, name or its number in the list").action((id, key) => runProviderKeysSwitch(id, key, true));
4318
+ providerKeys.command("disable").description("Switch an API key off (it stays in the list)").argument("<provider>", "Provider id or name").argument("<key>", "Key id, name or its number in the list").action((id, key) => runProviderKeysSwitch(id, key, false));
3561
4319
  provider.command("remove").description("Remove a provider").argument("<id>", "Provider id").action((id) => runProviderRemove(id));
4320
+ var tool = program.command("tool").description("Run Astra's built-in tools: web search, web fetch, image generation and plugin tools (this machine only)");
4321
+ tool.command("list").alias("ls").description("List the tools").option("--json", "Print JSON").action((opts) => runToolList(opts));
4322
+ tool.command("run", { isDefault: true }).description('Run a tool, e.g. astra tool generate_image "a magpie, watercolor" -o hero.png').argument("<name>", "web_search, web_fetch, generate_image or a plugin tool (see `astra tool list`)").argument("[words...]", "The tool's main argument (query, url or prompt)").option("-o, --output <file>", "Save an image (or the text) here").option("-a, --arg <key=value...>", "Another argument; repeat for more").option("--json <object>", "Arguments as a JSON object").option("--token <key>", "The gateway key an image is generated as (default: $ASTRA_API_KEY)").option("--raw", "Print the tool result as JSON").action(
4323
+ (name, words, opts) => runToolRun(name, words, opts)
4324
+ );
4325
+ var group = program.command("group").alias("groups").description("Routing groups: virtual models group/<slug> over several providers (smart, order, rotate, usage, pace, weight)");
4326
+ group.command("list").description("List the routing groups").action(() => runGroupList());
4327
+ group.command("show").description("Show a group's members with their live state").argument("<group>", "Group id, slug or name").action((ref) => runGroupShow(ref));
4328
+ group.command("add").description('Create a group: astra group add "Opus anywhere" models=claude/claude-opus-5-5,copilot/claude-opus-5.5 routing=smart').argument("<name>", "Display name; the model id is group/<slug of the name>").argument("[settings...]", "models=provider/model,\u2026 routing=smart|order|rotate|usage|pace|weight stays=auto|session|turn|off|strict weight=member=n,\u2026 listed=yes|no slug=\u2026").action((name, words) => runGroupAdd(name, words));
4329
+ group.command("set").description("Change a group: models=\u2026 (replace), models+=\u2026 (add), models-=\u2026 (remove), routing=\u2026, stays=\u2026, weight=\u2026, listed=\u2026, enabled=\u2026, name=\u2026").argument("<group>", "Group id, slug or name").argument("<settings...>", "key=value words").action((ref, words) => runGroupSet(ref, words));
4330
+ group.command("rm").alias("remove").description("Delete a group (one another group contains cannot be deleted)").argument("<group>", "Group id, slug or name").action((ref) => runGroupRemove(ref));
3562
4331
  var plugin = program.command("plugin").alias("plugins").description("Manage plugins (magpie-compatible provider plugins, gateway middleware and clients)");
3563
4332
  plugin.command("v2").description("List v2 plugins: state, permissions waiting for a grant, commands").option("--json", "Print JSON").action((opts) => runPluginV2List(opts));
3564
4333
  plugin.command("grant").description("Grant a v2 plugin the permissions it asks for (after showing them)").argument("<id>").option("-p, --permission <permission...>", "Only these permissions (e.g. one of its optional ones)").option("-y, --yes", "Don't ask").action((id, opts) => runPluginGrant(id, opts));
@@ -3579,23 +4348,40 @@ plugin.command("use").alias("prefer").description("Have a plugin serve a provide
3579
4348
  plugin.command("market").description("List the market's plugins, or search npm and GitHub").argument("[query]").action((query) => runPluginMarket(query));
3580
4349
  program.command("config").description("Manage Astra configuration").command("set-password").description("Set the admin password (required before binding to a non-loopback address)").action(() => runSetPassword());
3581
4350
  program.command("claude").description("Run the official Claude Code CLI with a Claude subscription account Astra holds").option("--account <id>", "Subscription account id (default: the account selected in Astra)").option("--status", "Show the account and token lifetime without starting Claude Code").action((opts) => runClaude(opts));
4351
+ var backup = program.command("backup").description("Back up and restore the whole Astra setup (providers, tokens, clients, settings ...)");
4352
+ backup.command("create").description("Write a backup file; API keys are included, encrypted with a passphrase, unless --no-keys").option("--no-keys", "No API keys and no passphrase: a plain file without secrets").option("-o, --out <file>", "File to write (default: the name the server suggests, in the current directory)").option("--sections <list>", "Comma-separated sections to include (default: all)").option("--include-usage", "Also include usage history").option("--passphrase-stdin", "Read the passphrase from stdin (or ASTRA_BACKUP_PASSPHRASE)").action(
4353
+ (opts) => runBackupCreate(opts)
4354
+ );
4355
+ backup.command("restore <file>").description("Preview a backup file, then restore it (asks first; a safety copy is kept)").option("--sections <list>", "Comma-separated sections to restore (default: all in the file)").option("--replace", "Make this Astra match the backup: remove what the backup does not have").option("--dry-run", "Only show what would change").option("--yes", "Do not ask for confirmation").action(
4356
+ (file, opts) => runBackupRestore(file, opts)
4357
+ );
4358
+ backup.command("list").description("List the automatic backups").action(() => runBackupList());
4359
+ backup.command("auto").description("Show or change the automatic backups").option("--on", "Turn them on").option("--off", "Turn them off").option("--hours <n>", "Hours between backups").option("--keep <n>", "How many to keep").option("--run", "Make a backup now").action((opts) => runBackupAuto(opts));
4360
+ var sync = program.command("sync").description("Keep several machines in step through a folder, WebDAV, S3 or GitHub");
4361
+ sync.command("status").description("Show the sync configuration, state and conflicts").action(() => runSyncStatus());
4362
+ sync.command("now").description("Sync now").option("--dry-run", "Only show what would be pushed and pulled").action((opts) => runSyncNow(opts));
4363
+ sync.command("enable").description("Turn periodic sync on").action(() => runSyncEnable(true));
4364
+ sync.command("disable").description("Turn periodic sync off").action(() => runSyncEnable(false));
4365
+ sync.command("test").description("Check that the sync target is reachable").action(() => runSyncTest());
4366
+ sync.command("clear-conflicts").description("Clear the list of settled conflicts").action(() => runSyncClearConflicts());
4367
+ sync.command("setup").description("Set the sync target (secret and passphrase: ASTRA_SYNC_SECRET / ASTRA_SYNC_PASSPHRASE, --...-stdin, or a prompt; never argv)").requiredOption("--kind <kind>", "folder | webdav | s3 | github").option("--url <url>", "Folder path, WebDAV address, S3 endpoint or GitHub repository").option("--username <name>", "User name (WebDAV) or access key id (S3)").option("--folder <name>", "Folder inside the target (default astra)").option("--bucket <name>", "S3 bucket").option("--region <region>", "S3 region").option("--path-style", "S3 path-style addressing").option("--branch <name>", "GitHub branch").option("--interval <minutes>", "Minutes between syncs").option("--sections <list>", "Comma-separated sections to sync").option("--no-keys", "Do not sync API keys").option("--signins", "Also sync plugin sign-ins").option("--secret-stdin", "Read the target password / token from stdin").option("--passphrase-stdin", "Read the sync passphrase from stdin (the line after the secret when both)").action((opts) => runSyncSetup(opts));
3582
4368
  program.command("restore-all").description("Restore every managed client configuration offline (no server needed)").option("--purge", "Also remove Astra entries from client configs entirely").action((opts) => runRestoreAll(opts));
3583
- program.parseAsync(process6.argv).then(() => {
4369
+ program.parseAsync(process8.argv).then(() => {
3584
4370
  }).catch((err) => {
3585
4371
  if (err instanceof ApiError) {
3586
4372
  fail(`error: ${err.message} (HTTP ${err.status})`);
3587
- process6.exitCode = 1;
4373
+ process8.exitCode = 1;
3588
4374
  return;
3589
4375
  }
3590
4376
  if (err instanceof AstraError) {
3591
4377
  fail(`error: ${err.message}`);
3592
4378
  if (err.hint) console.error(` ${err.hint}`);
3593
- process6.exitCode = 1;
4379
+ process8.exitCode = 1;
3594
4380
  return;
3595
4381
  }
3596
4382
  fail(`error: ${err instanceof Error ? err.message : String(err)}`);
3597
- if (process6.env.ASTRA_DEBUG) console.error(err);
4383
+ if (process8.env.ASTRA_DEBUG) console.error(err);
3598
4384
  else console.error("Run with ASTRA_DEBUG=1 for a stack trace.");
3599
- process6.exitCode = 1;
4385
+ process8.exitCode = 1;
3600
4386
  });
3601
4387
  //# sourceMappingURL=index.js.map