astragate 0.14.3102 → 0.14.3104

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
@@ -36,7 +36,7 @@ function adminHeaders(mutating, runtimeToken) {
36
36
  return headers;
37
37
  }
38
38
  async function apiRequest(options) {
39
- const { base, path: path14, method = "GET", body, runtimeToken, timeoutMs = 1e4 } = options;
39
+ const { base, path: path15, 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 + path14, {
49
+ response = await doFetch(base + path15, {
50
50
  method,
51
51
  headers,
52
52
  body: body === void 0 ? void 0 : JSON.stringify(body),
@@ -1129,6 +1129,7 @@ function homePaths(home) {
1129
1129
  keysDir: path8.join(home, "keys"),
1130
1130
  pluginsDir: path8.join(home, "plugins"),
1131
1131
  toolsDir: path8.join(home, "tools"),
1132
+ libraryDir: path8.join(home, "library"),
1132
1133
  connectDir: path8.join(home, "connect"),
1133
1134
  desktopPrefix: path8.join(home, "desktop")
1134
1135
  };
@@ -1313,7 +1314,7 @@ import { fileURLToPath } from "url";
1313
1314
  // package.json
1314
1315
  var package_default = {
1315
1316
  name: "astragate",
1316
- version: "0.14.3102",
1317
+ version: "0.14.3104",
1317
1318
  description: "Astra \u2014 a local AI gateway. Install, start, stop and manage the astra-server from the terminal.",
1318
1319
  license: "MIT",
1319
1320
  type: "module",
@@ -1344,12 +1345,12 @@ var package_default = {
1344
1345
  commander: "^12.1.0"
1345
1346
  },
1346
1347
  optionalDependencies: {
1347
- "@aidotnet/server-darwin-arm64": "0.14.3102",
1348
- "@aidotnet/server-darwin-x64": "0.14.3102",
1349
- "@aidotnet/server-linux-arm64": "0.14.3102",
1350
- "@aidotnet/server-linux-x64": "0.14.3102",
1351
- "@aidotnet/server-win32-arm64": "0.14.3102",
1352
- "@aidotnet/server-win32-x64": "0.14.3102"
1348
+ "@aidotnet/server-darwin-arm64": "0.14.3104",
1349
+ "@aidotnet/server-darwin-x64": "0.14.3104",
1350
+ "@aidotnet/server-linux-arm64": "0.14.3104",
1351
+ "@aidotnet/server-linux-x64": "0.14.3104",
1352
+ "@aidotnet/server-win32-arm64": "0.14.3104",
1353
+ "@aidotnet/server-win32-x64": "0.14.3104"
1353
1354
  },
1354
1355
  devDependencies: {
1355
1356
  "@aidotnet/update-core": "workspace:*",
@@ -2354,6 +2355,9 @@ async function updateServer(home, manifest, force) {
2354
2355
  // src/commands/uninstall.ts
2355
2356
  import fs15 from "fs";
2356
2357
  import { spawn as spawn7 } from "child_process";
2358
+ var SKILLS_NOT_RETURNED = 3;
2359
+ var SkillsNotReturnedError = class extends AstraError {
2360
+ };
2357
2361
  async function restoreAllOffline(purge) {
2358
2362
  const command = resolveServerBinary();
2359
2363
  const child = spawn7(
@@ -2362,16 +2366,21 @@ async function restoreAllOffline(purge) {
2362
2366
  { stdio: "inherit", windowsHide: true }
2363
2367
  );
2364
2368
  const code = await exitCodeOf(child);
2369
+ if (code === SKILLS_NOT_RETURNED) {
2370
+ throw new SkillsNotReturnedError("some Skills could not be given back to their client directories.");
2371
+ }
2365
2372
  if (code !== 0) throw new AstraError(`restore-all exited with code ${code}.`);
2366
2373
  }
2367
2374
  async function runUninstall(opts) {
2368
2375
  const home = astraHome();
2369
2376
  info("Uninstalling Astra\u2026");
2370
2377
  info("\u2022 Restoring client configurations\u2026");
2378
+ let skillsKept = false;
2371
2379
  try {
2372
2380
  await restoreAllOffline(opts.purge === true);
2373
2381
  } catch (err) {
2374
2382
  warn(`restore-all failed: ${err.message}`);
2383
+ skillsKept = err instanceof SkillsNotReturnedError;
2375
2384
  }
2376
2385
  info("\u2022 Disabling autostart\u2026");
2377
2386
  try {
@@ -2391,7 +2400,9 @@ async function runUninstall(opts) {
2391
2400
  } catch (err) {
2392
2401
  warn(`Could not stop the server: ${err.message}`);
2393
2402
  }
2394
- if (opts.purge) {
2403
+ if (opts.purge && skillsKept) {
2404
+ warn(`Kept ${home}: some Skills are still links into it. Fix the errors above, then run \`astra uninstall --purge\` again.`);
2405
+ } else if (opts.purge) {
2395
2406
  if (process.stdin.isTTY) {
2396
2407
  const ok = await confirmPrompt(`Delete all Astra data in ${home}? [y/N] `);
2397
2408
  if (!ok) {
@@ -2406,12 +2417,15 @@ async function runUninstall(opts) {
2406
2417
  }
2407
2418
 
2408
2419
  // src/commands/admin.ts
2409
- async function api(path14, options = {}) {
2420
+ import { existsSync } from "fs";
2421
+ import { chmod, readFile, stat, writeFile } from "fs/promises";
2422
+ import path13 from "path";
2423
+ async function api(path15, options = {}) {
2410
2424
  const { base, runtime, started } = await ensureServerRunning();
2411
2425
  if (started) console.log("Server was not running \u2014 started it in the background.");
2412
2426
  return apiRequest({
2413
2427
  base,
2414
- path: path14,
2428
+ path: path15,
2415
2429
  method: options.method ?? "GET",
2416
2430
  body: options.body,
2417
2431
  runtimeToken: runtime?.runtimeToken
@@ -2587,10 +2601,7 @@ async function runProviderRemove(id) {
2587
2601
  await api(`/api/providers/${encodeURIComponent(id)}`, { method: "DELETE" });
2588
2602
  } catch (err) {
2589
2603
  if (err instanceof ApiError && err.status === 409) {
2590
- throw new AstraError(
2591
- `Provider "${id}" is still bound to one or more clients.`,
2592
- "Disable the client or bind it to another provider first (`astra client disable <kind>`)."
2593
- );
2604
+ throw new AstraError(`A client was bound to provider "${id}" while it was being removed.`, "Run the command again.");
2594
2605
  }
2595
2606
  throw err;
2596
2607
  }
@@ -2674,14 +2685,124 @@ async function runProviderImport(opts) {
2674
2685
  for (const a of result.added) success(`Imported: ${a.name} (id: ${a.id}).`);
2675
2686
  for (const k of result.skipped) console.log(`Skipped ${k.ref}: ${SKIP_TEXT[k.reason] ?? k.reason}`);
2676
2687
  }
2688
+ var BACKUP_PASSPHRASE_ENV = "ASTRA_BACKUP_PASSPHRASE";
2689
+ var BACKUP_MAX_BYTES = 32 * 1024 * 1024;
2690
+ async function readBackupPassphrase(question) {
2691
+ const fromEnv = process.env[BACKUP_PASSPHRASE_ENV];
2692
+ if (fromEnv) return fromEnv;
2693
+ const entered = await promptHidden(question);
2694
+ if (!entered) throw new AstraError("No passphrase given.", `Pipe it on stdin or set ${BACKUP_PASSPHRASE_ENV}.`);
2695
+ return entered;
2696
+ }
2697
+ function backupNote(r) {
2698
+ const notes = [];
2699
+ if (r.error) notes.push(r.error);
2700
+ if (r.status === "same" && r.existing) notes.push(`already added as "${r.existing.name}"`);
2701
+ if (r.status === "sameHost" && r.existing) notes.push(`same address as "${r.existing.name}"`);
2702
+ if (r.ignored.length > 0) notes.push(`ignores ${r.ignored.join(", ")}`);
2703
+ return notes.join("; ");
2704
+ }
2705
+ async function runProviderExport(opts) {
2706
+ const sealed = Boolean(opts.passphraseStdin) || Boolean(process.env[BACKUP_PASSPHRASE_ENV]);
2707
+ if (sealed && opts.includeKeys) {
2708
+ throw new AstraError("--include-keys and a passphrase exclude each other.", "Choose plaintext keys or an encrypted file, not both.");
2709
+ }
2710
+ const out = path13.resolve(opts.out ?? `astra-providers-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.json`);
2711
+ if (!opts.force && existsSync(out)) {
2712
+ throw new AstraError(`${out} already exists.`, "Pass --force to replace it, or choose another file with --out.");
2713
+ }
2714
+ const secrets = sealed ? "passphrase" : opts.includeKeys ? "plaintext" : "none";
2715
+ const passphrase = sealed ? await readBackupPassphrase("Passphrase for the backup: ") : void 0;
2716
+ const file = await api("/api/providers/backup/export", {
2717
+ method: "POST",
2718
+ body: { secrets, passphrase, ids: opts.id?.length ? opts.id : void 0 }
2719
+ });
2720
+ await writeFile(out, `${JSON.stringify(file, null, 2)}
2721
+ `, { mode: 384 });
2722
+ await chmod(out, 384);
2723
+ const count = file.providers?.length ?? 0;
2724
+ success(`Exported ${count} provider${count === 1 ? "" : "s"} to ${out}.`);
2725
+ if (secrets === "none") console.log("The file has no API keys; enter them again after importing.");
2726
+ else if (secrets === "passphrase") console.log("API keys are encrypted with your passphrase; it cannot be recovered if lost.");
2727
+ else console.log("Warning: API keys are in the file in plain text. Keep it where only you can read it.");
2728
+ }
2729
+ async function runProviderImportFile(file, opts) {
2730
+ const only = opts.only?.map((n) => Number(n));
2731
+ if (only?.length && !opts.yes) {
2732
+ throw new AstraError("--only needs --yes.", "Run without options first to see the row numbers, then add --yes.");
2733
+ }
2734
+ if (only?.some((n) => !Number.isInteger(n) || n < 0)) {
2735
+ throw new AstraError("--only takes the row numbers shown by the preview.");
2736
+ }
2737
+ const abs = path13.resolve(file);
2738
+ let doc;
2739
+ try {
2740
+ if ((await stat(abs)).size > BACKUP_MAX_BYTES) throw new AstraError(`${abs} is too large to be a provider backup.`);
2741
+ doc = JSON.parse(await readFile(abs, "utf8"));
2742
+ } catch (e) {
2743
+ if (e instanceof AstraError) throw e;
2744
+ throw new AstraError(`Cannot read ${abs} as a backup file.`, e instanceof Error ? e.message : void 0);
2745
+ }
2746
+ if (doc.format !== "astra-providers" || !Array.isArray(doc.providers)) {
2747
+ throw new AstraError(`${abs} is not an Astra provider backup file.`);
2748
+ }
2749
+ const passphrase = doc.secrets === "passphrase" ? await readBackupPassphrase("Passphrase of the backup: ") : void 0;
2750
+ const preview = await api("/api/providers/backup/preview", {
2751
+ method: "POST",
2752
+ body: { file: doc, passphrase }
2753
+ });
2754
+ printTable(
2755
+ preview.items.map((r) => [
2756
+ String(r.index),
2757
+ r.status,
2758
+ r.name,
2759
+ (r.endpoints ?? []).map((e) => `${e.protocol} ${e.baseUrl}`).join(" | "),
2760
+ r.hasKey ? r.keyMasked ?? "\u2022\u2022\u2022\u2022" : "-",
2761
+ String(r.modelCount),
2762
+ backupNote(r)
2763
+ ]),
2764
+ ["ROW", "STATUS", "NAME", "ENDPOINTS", "KEY", "MODELS", "NOTE"]
2765
+ );
2766
+ const importable = (r) => r.status === "new" || r.status === "sameHost";
2767
+ if (!opts.yes) {
2768
+ const fresh = preview.items.filter((r) => r.status === "new").length;
2769
+ console.log("");
2770
+ console.log(
2771
+ fresh > 0 ? `Nothing was changed. Run again with --yes to import the ${fresh} new entr${fresh === 1 ? "y" : "ies"}, or --yes --only <row>\u2026 to pick.` : "Nothing new to import."
2772
+ );
2773
+ return;
2774
+ }
2775
+ let indexes;
2776
+ if (only?.length) {
2777
+ indexes = [];
2778
+ for (const n of only) {
2779
+ const row = preview.items.find((r) => r.index === n);
2780
+ if (!row) throw new AstraError(`No row ${n} in this backup.`);
2781
+ if (!importable(row)) throw new AstraError(`Row ${n} cannot be imported (${row.status === "same" ? "already added" : backupNote(row) || row.status}).`);
2782
+ indexes.push(n);
2783
+ }
2784
+ } else {
2785
+ indexes = preview.items.filter((r) => r.status === "new").map((r) => r.index);
2786
+ }
2787
+ if (indexes.length === 0) {
2788
+ console.log("Nothing to import.");
2789
+ return;
2790
+ }
2791
+ const result = await api(
2792
+ "/api/providers/backup/import",
2793
+ { method: "POST", body: { file: doc, passphrase, indexes } }
2794
+ );
2795
+ for (const a of result.added) success(`Imported: ${a.name} (id: ${a.id}).`);
2796
+ for (const k of result.skipped) console.log(`Skipped row ${k.index}: ${k.reason}`);
2797
+ }
2677
2798
 
2678
2799
  // src/commands/config.ts
2679
2800
  import { spawn as spawn8 } from "child_process";
2680
2801
  async function runSetPassword() {
2681
2802
  const password = await promptHidden("Enter new admin password: ");
2682
2803
  if (!password) throw new AstraError("Password must not be empty.");
2683
- const confirm = await promptHidden("Repeat password: ");
2684
- if (confirm !== password) throw new AstraError("Passwords do not match.");
2804
+ const confirm2 = await promptHidden("Repeat password: ");
2805
+ if (confirm2 !== password) throw new AstraError("Passwords do not match.");
2685
2806
  const command = resolveServerBinary();
2686
2807
  const child = spawn8(command.command, [...command.args, "set-password"], {
2687
2808
  stdio: ["pipe", "inherit", "inherit"],
@@ -2702,10 +2823,10 @@ async function runSetPassword() {
2702
2823
  }
2703
2824
 
2704
2825
  // src/commands/plugin.ts
2705
- async function api2(path14, method = "GET", body) {
2826
+ async function api2(path15, method = "GET", body) {
2706
2827
  const { base, runtime, started } = await ensureServerRunning();
2707
2828
  if (started) console.log("Server was not running \u2014 started it in the background.");
2708
- return apiRequest({ base, path: path14, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 6e4 });
2829
+ return apiRequest({ base, path: path15, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 6e4 });
2709
2830
  }
2710
2831
  async function find(name) {
2711
2832
  const { plugins } = await api2("/api/plugins");
@@ -2819,6 +2940,214 @@ async function runPluginMarket(query) {
2819
2940
  );
2820
2941
  info("Install one with `astra plugin add <package>`.");
2821
2942
  }
2943
+ async function findV2(id) {
2944
+ const { plugins } = await api2("/api/plugins/v2");
2945
+ const hit = plugins.find((p) => p.id === id || p.spec === id || p.name === id);
2946
+ if (!hit) throw new AstraError(`No v2 plugin "${id}".`, "See `astra plugin v2`.");
2947
+ return hit;
2948
+ }
2949
+ async function runPluginV2List(opts) {
2950
+ const list = await api2("/api/plugins/v2");
2951
+ if (opts.json) {
2952
+ console.log(JSON.stringify(list, null, 2));
2953
+ return;
2954
+ }
2955
+ if (list.plugins.length === 0) {
2956
+ info("No v2 plugins installed.");
2957
+ return;
2958
+ }
2959
+ 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]),
2961
+ ["ID", "VERSION", "STATE", "PERMISSIONS", "SPEC"]
2962
+ );
2963
+ for (const p of list.plugins) {
2964
+ if (p.problem) warn(`${p.id}: ${p.problem}`);
2965
+ if (p.lastError) warn(`${p.id}: ${p.lastError}`);
2966
+ if (p.contributes.commands.length) console.log(` ${p.id} commands: ${p.contributes.commands.map((c) => c.id).join(", ")}`);
2967
+ }
2968
+ }
2969
+ async function runPluginGrant(id, opts) {
2970
+ const p = await findV2(id);
2971
+ const asked = opts.permission?.length ? opts.permission : p.missing;
2972
+ if (asked.length === 0) {
2973
+ info(`${p.id} has every permission it asks for: ${p.granted.join(", ") || "(none)"}.`);
2974
+ return;
2975
+ }
2976
+ console.log(`${p.name} asks for:`);
2977
+ for (const perm of asked) console.log(` ${p.sensitive.includes(perm) ? "!" : "-"} ${perm}`);
2978
+ if (!opts.yes && !await confirm("Grant these permissions?")) return;
2979
+ await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/grant`, "POST", { permissions: asked });
2980
+ success(`Granted ${asked.length} permission(s) to ${p.id}.`);
2981
+ }
2982
+ async function runPluginRun(id, command, args) {
2983
+ let parsed = null;
2984
+ if (args) {
2985
+ try {
2986
+ parsed = JSON.parse(args);
2987
+ } catch (e) {
2988
+ throw new AstraError(`The arguments aren't JSON: ${e instanceof Error ? e.message : String(e)}`);
2989
+ }
2990
+ }
2991
+ const p = await findV2(id);
2992
+ const r = await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/commands/${encodeURIComponent(command)}`, "POST", { args: parsed });
2993
+ console.log(typeof r.result === "string" ? r.result : JSON.stringify(r.result, null, 2));
2994
+ }
2995
+ async function runPluginSettings(id, values, opts = {}) {
2996
+ const p = await findV2(id);
2997
+ let parsed = null;
2998
+ if (values) {
2999
+ try {
3000
+ parsed = JSON.parse(values);
3001
+ } catch (e) {
3002
+ throw new AstraError(`The settings aren't JSON: ${e instanceof Error ? e.message : String(e)}`);
3003
+ }
3004
+ }
3005
+ const secrets = {};
3006
+ for (const s of opts.secret ?? []) {
3007
+ const at = s.indexOf("=");
3008
+ if (at <= 0) throw new AstraError(`--secret takes name=value, not "${s}".`);
3009
+ secrets[s.slice(0, at)] = s.slice(at + 1) || null;
3010
+ }
3011
+ if (!parsed && Object.keys(secrets).length === 0) {
3012
+ const detail = await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}`);
3013
+ console.log(JSON.stringify(detail.plugin.settings, null, 2));
3014
+ if (detail.plugin.secretsSet.length) info(`Secrets set: ${detail.plugin.secretsSet.join(", ")}`);
3015
+ return;
3016
+ }
3017
+ await api2(`/api/plugins/v2/${encodeURIComponent(p.id)}/settings`, "PUT", { values: parsed, secrets });
3018
+ success(`Saved ${p.id}'s settings.`);
3019
+ }
3020
+ async function runPluginUpgrade(name, opts) {
3021
+ const successors = await api2("/api/plugins/v2/successors");
3022
+ if (!name) {
3023
+ if (successors.length === 0) {
3024
+ info("No installed plugin has a v2 version in the market.");
3025
+ return;
3026
+ }
3027
+ printTable(
3028
+ successors.map((s2) => [s2.v1Name, `${s2.name} ${s2.version}`, s2.permissions.join(", ")]),
3029
+ ["V1 PLUGIN", "V2 VERSION", "PERMISSIONS"]
3030
+ );
3031
+ info("Upgrade one with `astra plugin upgrade <name>`.");
3032
+ return;
3033
+ }
3034
+ const s = successors.find((x) => x.v1Name === name || x.spec === name);
3035
+ if (!s) throw new AstraError(`"${name}" has no v2 version in the market.`, "See `astra plugin upgrade`.");
3036
+ if (s.notes) console.log(s.notes);
3037
+ console.log(`${s.name} ${s.version} asks for:`);
3038
+ for (const perm of s.permissions) console.log(` ${s.sensitive.includes(perm) ? "!" : "-"} ${perm}`);
3039
+ 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 }));
3041
+ success(`Upgraded ${s.v1Name} to ${s.name} ${s.version}.`);
3042
+ }
3043
+ async function runPluginDev(dir, opts) {
3044
+ const { readFileSync } = await import("fs");
3045
+ const { resolve } = await import("path");
3046
+ const root = resolve(dir);
3047
+ let id;
3048
+ try {
3049
+ id = JSON.parse(readFileSync(resolve(root, "astra.plugin.json"), "utf8")).id ?? "";
3050
+ } catch {
3051
+ throw new AstraError(`${root} has no readable astra.plugin.json.`, "Start one with `npx @astragate/plugin-sdk init`.");
3052
+ }
3053
+ 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 }));
3057
+ let p;
3058
+ for (let i = 0; i < 20 && !p; i++) {
3059
+ p = (await api2("/api/plugins/v2")).plugins.find((x) => x.id === id);
3060
+ if (!p) await new Promise((r) => setTimeout(r, 500));
3061
+ }
3062
+ if (!p) throw new AstraError(`Astra didn't load ${id}.`, "Run `astra-plugin validate` in the folder, or see `astra plugin v2`.");
3063
+ if (p.missing.length > 0) await runPluginGrant(id, { yes: opts.yes });
3064
+ info(`Developing ${id} from ${root}: it reloads on save. Ctrl+C to stop${opts.keep || mounted ? "" : " (and unmount it)"}.`);
3065
+ let stop = false;
3066
+ const done = new Promise(
3067
+ (resolveDone) => process.once("SIGINT", () => {
3068
+ stop = true;
3069
+ resolveDone();
3070
+ })
3071
+ );
3072
+ let last = "";
3073
+ let lastProblem;
3074
+ while (!stop) {
3075
+ try {
3076
+ const detail = await api2(`/api/plugins/v2/${encodeURIComponent(id)}`);
3077
+ for (const l of detail.lines.filter((l2) => l2.at > last)) {
3078
+ const line = `${l.at.slice(11, 19)} ${l.level.padEnd(5)} ${l.text}`;
3079
+ if (l.level === "error") warn(line);
3080
+ else console.log(line);
3081
+ }
3082
+ if (detail.lines.length > 0) last = detail.lines[detail.lines.length - 1].at > last ? detail.lines[detail.lines.length - 1].at : last;
3083
+ const problem = detail.plugin.problem ?? detail.plugin.lastError;
3084
+ if (problem !== lastProblem && problem) warn(problem);
3085
+ lastProblem = problem;
3086
+ } catch (e) {
3087
+ if (e instanceof AstraError) warn(e.message);
3088
+ else throw e;
3089
+ }
3090
+ await Promise.race([done, new Promise((r) => setTimeout(r, 1e3))]);
3091
+ }
3092
+ if (!opts.keep && !mounted) {
3093
+ await follow(await api2(`/api/plugins${q(root)}`, "DELETE"));
3094
+ success(`Unmounted ${id}.`);
3095
+ }
3096
+ }
3097
+ async function runPluginTest(dir, opts) {
3098
+ const { readFileSync } = await import("fs");
3099
+ const { resolve } = await import("path");
3100
+ const root = resolve(dir);
3101
+ let id;
3102
+ try {
3103
+ id = JSON.parse(readFileSync(resolve(root, "astra.plugin.json"), "utf8")).id ?? "";
3104
+ } catch {
3105
+ throw new AstraError(`${root} has no readable astra.plugin.json.`);
3106
+ }
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 }));
3109
+ try {
3110
+ const results = await api2(
3111
+ `/api/plugins/v2/${encodeURIComponent(id)}/test`,
3112
+ "POST",
3113
+ {}
3114
+ );
3115
+ if (opts.json) console.log(JSON.stringify(results, null, 2));
3116
+ else {
3117
+ let file = "";
3118
+ for (const r of results) {
3119
+ if (r.file !== file) console.log(file = r.file);
3120
+ const mark = r.status === "passed" ? "\u2713" : r.status === "skipped" ? "-" : "\u2717";
3121
+ console.log(` ${mark} ${r.name}${r.ms != null ? ` (${Math.round(r.ms)} ms)` : ""}`);
3122
+ if (r.error) console.log(` ${r.error}`);
3123
+ }
3124
+ }
3125
+ const failed = results.filter((r) => r.status === "failed").length;
3126
+ const passed = results.filter((r) => r.status === "passed").length;
3127
+ if (results.length === 0) warn("No tests: put them in test/**/*.test.js (or .mjs).");
3128
+ else if (failed) {
3129
+ warn(`${failed} failed, ${passed} passed (in Astra's sandbox).`);
3130
+ process.exitCode = 1;
3131
+ } else success(`${passed} passed in Astra's sandbox.`);
3132
+ } finally {
3133
+ if (!mounted) await follow(await api2(`/api/plugins${q(root)}`, "DELETE"));
3134
+ }
3135
+ }
3136
+ async function runPluginRollback(id, opts) {
3137
+ 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", {}));
3139
+ success(`${id} is back on its v1 plugin.`);
3140
+ }
3141
+ async function confirm(question) {
3142
+ if (!process.stdin.isTTY) throw new AstraError(`${question} (not a terminal: pass --yes)`);
3143
+ const { createInterface } = await import("readline/promises");
3144
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3145
+ try {
3146
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
3147
+ } finally {
3148
+ rl.close();
3149
+ }
3150
+ }
2822
3151
 
2823
3152
  // src/commands/restore-all.ts
2824
3153
  import { spawn as spawn9 } from "child_process";
@@ -2838,7 +3167,7 @@ async function runRestoreAll(opts) {
2838
3167
  // src/commands/claude.ts
2839
3168
  import fs16 from "fs";
2840
3169
  import os6 from "os";
2841
- import path13 from "path";
3170
+ import path14 from "path";
2842
3171
  import process5 from "process";
2843
3172
  import { spawn as spawn10 } from "child_process";
2844
3173
  var PREPARE_PATH = "/api/clients/claude-code/direct/prepare";
@@ -2954,9 +3283,9 @@ async function prepareLaunch(accountId) {
2954
3283
  return validateLaunchResponse(response);
2955
3284
  }
2956
3285
  function claudeConfigDir(env, override) {
2957
- if (override) return path13.resolve(override);
3286
+ if (override) return path14.resolve(override);
2958
3287
  const configured = env.CLAUDE_CONFIG_DIR?.trim();
2959
- return configured ? configured : path13.join(os6.homedir(), ".claude");
3288
+ return configured ? configured : path14.join(os6.homedir(), ".claude");
2960
3289
  }
2961
3290
  function validateLaunchResponse(raw) {
2962
3291
  if (!isPlainObject(raw)) throw invalidLaunch();
@@ -3023,24 +3352,24 @@ function assertNoSettingsConflicts(configDirectory, cwd) {
3023
3352
  );
3024
3353
  }
3025
3354
  function settingsFilesToCheck(configDirectory, cwd) {
3026
- const files = [path13.join(configDirectory, "settings.json")];
3355
+ const files = [path14.join(configDirectory, "settings.json")];
3027
3356
  const root = findGitRoot(cwd);
3028
- let dir = path13.resolve(cwd);
3357
+ let dir = path14.resolve(cwd);
3029
3358
  for (; ; ) {
3030
- files.push(path13.join(dir, ".claude", "settings.json"));
3031
- files.push(path13.join(dir, ".claude", "settings.local.json"));
3359
+ files.push(path14.join(dir, ".claude", "settings.json"));
3360
+ files.push(path14.join(dir, ".claude", "settings.local.json"));
3032
3361
  if (root === null || dir === root) break;
3033
- const parent = path13.dirname(dir);
3362
+ const parent = path14.dirname(dir);
3034
3363
  if (parent === dir) break;
3035
3364
  dir = parent;
3036
3365
  }
3037
3366
  return [...new Set(files)];
3038
3367
  }
3039
3368
  function findGitRoot(startDir) {
3040
- let dir = path13.resolve(startDir);
3369
+ let dir = path14.resolve(startDir);
3041
3370
  for (; ; ) {
3042
- if (fs16.existsSync(path13.join(dir, ".git"))) return dir;
3043
- const parent = path13.dirname(dir);
3371
+ if (fs16.existsSync(path14.join(dir, ".git"))) return dir;
3372
+ const parent = path14.dirname(dir);
3044
3373
  if (parent === dir) return null;
3045
3374
  dir = parent;
3046
3375
  }
@@ -3225,8 +3554,20 @@ provider.command("add").description("Add a provider from a template").requiredOp
3225
3554
  (opts) => runProviderAdd(opts)
3226
3555
  );
3227
3556
  provider.command("import").description("Import providers from CC Switch, Alma, Claude Code, Codex or Magpie (lists only, unless --yes)").option("--from <source>", "Only this source: cc-switch | alma | claude-code | codex | magpie").option("--yes", "Import the new entries (or those named with --only)").option("--only <ref...>", "With --yes: import only these refs (see the listing)").action((opts) => runProviderImport(opts));
3557
+ provider.command("export").description("Export providers and their models to a backup file (no API keys unless asked)").option("--out <file>", "File to write (default: ./astra-providers-<date>.json)").option("--force", "Replace the file when it already exists").option("--include-keys", "Write API keys in plain text (this machine only)").option("--passphrase-stdin", "Encrypt API keys with a passphrase read from stdin (or ASTRA_BACKUP_PASSPHRASE)").option("--id <id...>", "Only these provider ids").action(
3558
+ (opts) => runProviderExport(opts)
3559
+ );
3560
+ 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));
3228
3561
  provider.command("remove").description("Remove a provider").argument("<id>", "Provider id").action((id) => runProviderRemove(id));
3229
3562
  var plugin = program.command("plugin").alias("plugins").description("Manage plugins (magpie-compatible provider plugins, gateway middleware and clients)");
3563
+ plugin.command("v2").description("List v2 plugins: state, permissions waiting for a grant, commands").option("--json", "Print JSON").action((opts) => runPluginV2List(opts));
3564
+ 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));
3565
+ plugin.command("run").description("Run a v2 plugin's command").argument("<id>").argument("<command>").argument("[args]", "Arguments as JSON").action((id, command, args) => runPluginRun(id, command, args));
3566
+ plugin.command("settings").description("Show a v2 plugin's settings, or set them from JSON").argument("<id>").argument("[values]", "Settings as a JSON object").option("-s, --secret <name=value...>", "Set a secret setting (empty value clears it)").action((id, values, opts) => runPluginSettings(id, values, opts));
3567
+ plugin.command("upgrade").description("List v1 plugins that have a v2 version, or upgrade one").argument("[name]").option("-y, --yes", "Don't ask").action((name, opts) => runPluginUpgrade(name, opts));
3568
+ plugin.command("dev").description("Develop a v2 plugin from a folder: reloads on save, prints its log, unmounts on Ctrl+C (this machine only)").argument("[dir]", "The plugin folder (with astra.plugin.json)", ".").option("-y, --yes", "Grant the permissions it asks for without asking").option("--keep", "Leave it mounted after Ctrl+C").action((dir, opts) => runPluginDev(dir, opts));
3569
+ plugin.command("test").description("Run a v2 plugin folder's tests in Astra's own sandbox (the real astra module and host calls; this machine only)").argument("[dir]", "The plugin folder (with astra.plugin.json)", ".").option("--json", "Print JSON").action((dir, opts) => runPluginTest(dir, opts));
3570
+ plugin.command("rollback").description("Go back to the v1 plugin a v2 one replaced (within 30 days of the upgrade)").argument("<id>").option("-y, --yes", "Don't ask").action((id, opts) => runPluginRollback(id, opts));
3230
3571
  plugin.command("list").alias("ls").description("List installed plugins").option("--json", "Print JSON").action((opts) => runPluginList(opts));
3231
3572
  plugin.command("add").alias("install").description("Install a plugin: an npm package, a git repository (github:owner/repo) or a path").argument("<spec>", "What to install").action((spec) => runPluginAdd(spec));
3232
3573
  plugin.command("remove").aliases(["rm", "uninstall"]).description("Remove a plugin (a client it added gets its configuration back first)").argument("<name>", "Spec, package name or short name").action((name) => runPluginRemove(name));