@aidotnet/astra-gate 0.5.2 → 0.7.0

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import process6 from "process";
5
- import { Argument, Command } from "commander";
5
+ import { Argument, Command, InvalidArgumentError } from "commander";
6
6
 
7
7
  // src/errors.ts
8
8
  var AstraError = class extends Error {
@@ -202,6 +202,10 @@ var CLIENT_KINDS = [
202
202
  "workbuddy",
203
203
  "muse-code"
204
204
  ];
205
+ var PLUGIN_CLIENT_KIND = /^plugin-[a-z0-9][a-z0-9._-]{0,63}$/;
206
+ function isClientKind(kind) {
207
+ return CLIENT_KINDS.includes(kind) || PLUGIN_CLIENT_KIND.test(kind);
208
+ }
205
209
 
206
210
  // src/commands/manage.ts
207
211
  import process3 from "process";
@@ -1047,8 +1051,8 @@ function homePaths(home) {
1047
1051
  serverStdoutLog: path8.join(home, "logs", "server-stdout.log"),
1048
1052
  dbFile: path8.join(home, "astra.db"),
1049
1053
  keysDir: path8.join(home, "keys"),
1050
- desktopPrefix: path8.join(home, "desktop"),
1051
- claudeProfilesDir: path8.join(home, "claude-profiles")
1054
+ pluginsDir: path8.join(home, "plugins"),
1055
+ desktopPrefix: path8.join(home, "desktop")
1052
1056
  };
1053
1057
  }
1054
1058
 
@@ -1231,7 +1235,7 @@ import { fileURLToPath } from "url";
1231
1235
  // package.json
1232
1236
  var package_default = {
1233
1237
  name: "@aidotnet/astra-gate",
1234
- version: "0.5.2",
1238
+ version: "0.7.0",
1235
1239
  description: "Astra \u2014 a local AI gateway. Install, start, stop and manage the astra-server from the terminal.",
1236
1240
  license: "MIT",
1237
1241
  type: "module",
@@ -1262,12 +1266,12 @@ var package_default = {
1262
1266
  commander: "^12.1.0"
1263
1267
  },
1264
1268
  optionalDependencies: {
1265
- "@aidotnet/server-darwin-arm64": "0.5.2",
1266
- "@aidotnet/server-darwin-x64": "0.5.2",
1267
- "@aidotnet/server-linux-arm64": "0.5.2",
1268
- "@aidotnet/server-linux-x64": "0.5.2",
1269
- "@aidotnet/server-win32-arm64": "0.5.2",
1270
- "@aidotnet/server-win32-x64": "0.5.2"
1269
+ "@aidotnet/server-darwin-arm64": "0.7.0",
1270
+ "@aidotnet/server-darwin-x64": "0.7.0",
1271
+ "@aidotnet/server-linux-arm64": "0.7.0",
1272
+ "@aidotnet/server-linux-x64": "0.7.0",
1273
+ "@aidotnet/server-win32-arm64": "0.7.0",
1274
+ "@aidotnet/server-win32-x64": "0.7.0"
1271
1275
  },
1272
1276
  devDependencies: {
1273
1277
  "@aidotnet/update-core": "workspace:*",
@@ -2570,6 +2574,121 @@ async function runSetPassword() {
2570
2574
  }
2571
2575
  }
2572
2576
 
2577
+ // src/commands/plugin.ts
2578
+ async function api2(path14, method = "GET", body) {
2579
+ const { base, runtime, started } = await ensureServerRunning();
2580
+ if (started) console.log("Server was not running \u2014 started it in the background.");
2581
+ return apiRequest({ base, path: path14, method, body, runtimeToken: runtime?.runtimeToken, timeoutMs: 6e4 });
2582
+ }
2583
+ async function find(name) {
2584
+ const { plugins } = await api2("/api/plugins");
2585
+ const hit = plugins.find((p) => p.spec === name) ?? plugins.find((p) => p.name === name) ?? plugins.find((p) => p.shortName === name);
2586
+ if (!hit) throw new AstraError(`No plugin "${name}".`, "See `astra plugin list`.");
2587
+ return hit;
2588
+ }
2589
+ async function follow(job) {
2590
+ let printed = 0;
2591
+ for (; ; ) {
2592
+ for (const line of job.log.slice(printed)) console.log(` ${line}`);
2593
+ printed = Math.max(printed, job.log.length);
2594
+ if (job.state !== "running") break;
2595
+ await new Promise((r) => setTimeout(r, 800));
2596
+ job = await api2(`/api/plugins/jobs/${encodeURIComponent(job.id)}`);
2597
+ }
2598
+ if (job.state === "failed") throw new AstraError(job.error ?? "The plugin task failed.");
2599
+ return job;
2600
+ }
2601
+ var q = (spec) => `?spec=${encodeURIComponent(spec)}`;
2602
+ async function runPluginList(opts) {
2603
+ const list = await api2("/api/plugins");
2604
+ if (opts.json) {
2605
+ console.log(JSON.stringify(list, null, 2));
2606
+ return;
2607
+ }
2608
+ if (list.plugins.length === 0) {
2609
+ info("No plugins installed. Try `astra plugin market`.");
2610
+ } else {
2611
+ printTable(
2612
+ list.plugins.map((p) => [p.shortName, p.version ?? "", p.kinds.join(","), p.enabled ? "on" : "off", p.spec]),
2613
+ ["NAME", "VERSION", "KINDS", "STATE", "SPEC"]
2614
+ );
2615
+ for (const p of list.plugins) {
2616
+ if (p.error) warn(`${p.shortName}: ${p.error}`);
2617
+ if (p.middleware?.error) warn(`${p.shortName}: middleware didn't load: ${p.middleware.error}`);
2618
+ else if (p.middleware)
2619
+ console.log(
2620
+ ` ${p.shortName}: ${p.middleware.hooks.join(", ")} \xB7 ${p.middleware.calls} calls \xB7 ${p.middleware.avgMicros.toFixed(1)} \xB5s \xB7 ${p.middleware.failures} failures`
2621
+ );
2622
+ if (p.agent?.kind) console.log(` ${p.shortName}: adds the client ${p.agent.kind} (astra client enable ${p.agent.kind} \u2026)`);
2623
+ else if (p.agent?.error) warn(`${p.shortName}: its client didn't load: ${p.agent.error}`);
2624
+ }
2625
+ }
2626
+ const bun = list.runtime;
2627
+ console.log(`Bun: ${bun.path ?? `not downloaded yet (${bun.version ?? "?"}; fetched when a provider plugin needs it)`}`);
2628
+ }
2629
+ async function runPluginAdd(spec) {
2630
+ const job = await follow(await api2("/api/plugins", "POST", { spec }));
2631
+ success(`Added ${job.result ?? spec}.`);
2632
+ }
2633
+ async function runPluginRemove(name) {
2634
+ const p = await find(name);
2635
+ await follow(await api2(`/api/plugins${q(p.spec)}`, "DELETE"));
2636
+ success(`Removed ${p.spec}.`);
2637
+ }
2638
+ async function runPluginSwitch(name, enabled) {
2639
+ const p = await find(name);
2640
+ await api2(`/api/plugins${q(p.spec)}`, "PATCH", { enabled });
2641
+ success(`${p.shortName} is ${enabled ? "on" : "off"}.`);
2642
+ }
2643
+ async function runPluginUpdate(name) {
2644
+ const spec = name ? (await find(name)).spec : void 0;
2645
+ await follow(await api2("/api/plugins/update", "POST", { spec }));
2646
+ success(name ? `Updated ${name}.` : "Updated every plugin.");
2647
+ }
2648
+ async function runPluginOptions(name, value) {
2649
+ const p = await find(name);
2650
+ if (value === void 0) {
2651
+ if (p.options) console.log(JSON.stringify(p.options, null, 2));
2652
+ else if (p.optionsExample) {
2653
+ info(`${p.shortName} has no options set; its package suggests:`);
2654
+ console.log(JSON.stringify(p.optionsExample, null, 2));
2655
+ } else info(`${p.shortName} has no options set.`);
2656
+ return;
2657
+ }
2658
+ let options = null;
2659
+ if (value !== "off") {
2660
+ try {
2661
+ options = JSON.parse(value);
2662
+ } catch (e) {
2663
+ throw new AstraError(`The options aren't JSON: ${e instanceof Error ? e.message : String(e)}`);
2664
+ }
2665
+ if (options === null || typeof options !== "object" || Array.isArray(options)) throw new AstraError("The options must be a JSON object.");
2666
+ }
2667
+ await api2(`/api/plugins${q(p.spec)}`, "PATCH", { options });
2668
+ success(options === null ? `Cleared ${p.shortName}'s options.` : `Set ${p.shortName}'s options.`);
2669
+ }
2670
+ async function runPluginUse(name, provider2) {
2671
+ const p = await find(name);
2672
+ await api2("/api/plugins/prefer", "POST", { spec: p.spec, provider: provider2 });
2673
+ success(`${p.shortName} serves ${provider2} now.`);
2674
+ }
2675
+ async function runPluginMarket(query) {
2676
+ if (query) {
2677
+ const results = await api2(`/api/plugins/search?q=${encodeURIComponent(query)}`);
2678
+ printTable(
2679
+ results.map((r) => [r.spec, r.kind, r.version ?? "", r.source, (r.description ?? "").slice(0, 60)]),
2680
+ ["SPEC", "KIND", "VERSION", "FROM", "DESCRIPTION"]
2681
+ );
2682
+ return;
2683
+ }
2684
+ const listings = await api2("/api/plugins/market");
2685
+ printTable(
2686
+ listings.map((l) => [l.package, l.kind, l.latest ?? "", l.summary.en ?? ""]),
2687
+ ["PACKAGE", "KIND", "LATEST", "SUMMARY"]
2688
+ );
2689
+ info("Install one with `astra plugin add <package>`.");
2690
+ }
2691
+
2573
2692
  // src/commands/restore-all.ts
2574
2693
  import { spawn as spawn9 } from "child_process";
2575
2694
  async function runRestoreAll(opts) {
@@ -2587,17 +2706,14 @@ async function runRestoreAll(opts) {
2587
2706
 
2588
2707
  // src/commands/claude.ts
2589
2708
  import fs16 from "fs";
2709
+ import os6 from "os";
2590
2710
  import path13 from "path";
2591
2711
  import process5 from "process";
2592
2712
  import { spawn as spawn10 } from "child_process";
2593
- var LAUNCH_FILE_NAME = "astra-launch.json";
2594
2713
  var PREPARE_PATH = "/api/clients/claude-code/direct/prepare";
2595
- var PROFILE_ID_PATTERN = /^[a-f0-9]{32}$/;
2596
- var SUBSCRIPTION_LOGIN_METHOD = "claudeai";
2714
+ var ACCOUNT_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
2597
2715
  var OFFICIAL_BASE_URL = "https://api.anthropic.com";
2598
- var SUBSCRIPTION_AUTH_METHOD = "claude.ai";
2599
- var AUTH_STATUS_TIMEOUT_MS = 15e3;
2600
- var AUTH_STATUS_MAX_BYTES = 64 * 1024;
2716
+ var TOKEN_LIFETIME_WARNING_MINUTES = 30;
2601
2717
  var ENV_PREFIX_DENYLIST = ["ANTHROPIC_", "OTEL_"];
2602
2718
  var ENV_NAME_DENYLIST = [
2603
2719
  "CLAUDE_CODE_OAUTH_TOKEN",
@@ -2638,6 +2754,7 @@ var LAUNCH_ENV_WHITELIST = [
2638
2754
  "OTEL_LOG_RAW_API_BODIES",
2639
2755
  "OTEL_RESOURCE_ATTRIBUTES"
2640
2756
  ];
2757
+ var REQUIRED_LAUNCH_ENV_KEY = "CLAUDE_CODE_OAUTH_TOKEN";
2641
2758
  var CREDENTIAL_ENV_KEYS = [
2642
2759
  "ANTHROPIC_API_KEY",
2643
2760
  "ANTHROPIC_AUTH_TOKEN",
@@ -2649,114 +2766,103 @@ var EXTERNAL_PROVIDER_ENV_KEYS = [
2649
2766
  "CLAUDE_CODE_USE_FOUNDRY"
2650
2767
  ];
2651
2768
  var HELPER_SETTING_KEYS = ["apiKeyHelper", "otelHeadersHelper"];
2769
+ var SUBSCRIPTION_LOGIN_METHOD = "claudeai";
2652
2770
  var spawnOfficial = (command, args, options) => spawn10(command, [...args], options);
2653
2771
  var OFFICIAL_CLI = "claude";
2654
2772
  async function runClaude(opts, deps = {}) {
2655
- if (opts.login && opts.status) {
2773
+ if (opts.account !== void 0 && !ACCOUNT_ID_PATTERN.test(opts.account)) {
2656
2774
  throw new AstraError(
2657
- "--login and --status cannot be combined.",
2658
- "Use `astra claude --login` to sign in, or `astra claude --status` to check the sign-in state."
2775
+ '--account expects an account id of up to 64 letters, digits, "_" or "-".',
2776
+ "Pick the subscription account in the Astra web UI (Clients \u2192 Claude Code) and copy its id."
2659
2777
  );
2660
2778
  }
2661
- if (opts.profile !== void 0 && !PROFILE_ID_PATTERN.test(opts.profile)) {
2662
- throw new AstraError(
2663
- "--profile expects a 32-character profile id.",
2664
- "Pick a native profile in the Astra web UI (Clients \u2192 Claude Code) and copy its id."
2665
- );
2666
- }
2667
- const action = opts.login ? "login" : opts.status ? "status" : "run";
2668
- const spawnImpl = deps.spawn ?? spawnOfficial;
2779
+ const env = deps.env ?? process5.env;
2669
2780
  const cwd = deps.cwd ?? process5.cwd();
2670
- const launch = await prepareLaunch(action, opts.profile);
2671
- const childEnv = buildClaudeEnv(
2672
- deps.env ?? process5.env,
2673
- readLaunchEnv(launch.settingsFile),
2674
- launch.configDirectory
2675
- );
2676
- assertNoSettingsConflicts(launch.configDirectory, cwd);
2677
- if (action === "run") {
2678
- assertSubscriptionAuth(await probeAuthStatus(spawnImpl, childEnv, cwd));
2679
- }
2680
- const args = action === "login" ? ["auth", "login"] : action === "status" ? ["auth", "status"] : ["--settings", launch.settingsFile];
2681
- if (action === "login") {
2682
- info(style.dim(`Signing in the official Claude Code CLI (profile ${launch.profileId}).`));
2781
+ if (opts.status) {
2782
+ printStatus(await prepareLaunch(opts.account));
2783
+ return;
2683
2784
  }
2684
- const result = await runInherit(spawnImpl, args, childEnv, cwd);
2785
+ assertNoSettingsConflicts(claudeConfigDir(env, deps.configDir), cwd);
2786
+ const launch = await prepareLaunch(opts.account);
2787
+ const childEnv = buildClaudeEnv(env, launch.env);
2788
+ printLaunch(launch);
2789
+ const spawnImpl = deps.spawn ?? spawnOfficial;
2790
+ const result = await runInherit(spawnImpl, [], childEnv, cwd);
2685
2791
  process5.exitCode = exitCodeFrom(result.code);
2686
- if (action === "login" && result.code === 0) {
2687
- assertSubscriptionAuth(await probeAuthStatus(spawnImpl, childEnv, cwd));
2688
- success("Signed in \u2014 the Claude subscription profile is ready.");
2689
- info(style.dim(launch.configDirectory));
2792
+ }
2793
+ function printLaunch(launch) {
2794
+ info(
2795
+ `Using Claude subscription account "${launch.accountName}" (token valid until ${formatLocalTime(launch.expiresAt)}) \u2014 requests go straight to Anthropic, not through the Astra gateway.`
2796
+ );
2797
+ if (launch.expiresAt.getTime() - Date.now() < TOKEN_LIFETIME_WARNING_MINUTES * 6e4) {
2798
+ warn(
2799
+ `The access token expires in less than ${TOKEN_LIFETIME_WARNING_MINUTES} minutes; restart this command when it does.`
2800
+ );
2690
2801
  }
2691
2802
  }
2692
- async function prepareLaunch(action, profileId) {
2803
+ function printStatus(launch) {
2804
+ info(`Account: ${launch.accountName}`);
2805
+ info(`Token valid until: ${formatLocalTime(launch.expiresAt)}`);
2806
+ info(
2807
+ `Statistics (OpenTelemetry): ${launch.env["CLAUDE_CODE_ENABLE_TELEMETRY"] === "1" ? "enabled" : "disabled"}`
2808
+ );
2809
+ }
2810
+ function formatLocalTime(date) {
2811
+ return date.toLocaleString();
2812
+ }
2813
+ async function prepareLaunch(accountId) {
2693
2814
  const { base, runtime, started } = await ensureServerRunning();
2694
2815
  if (started) console.log("Server was not running \u2014 started it in the background.");
2695
2816
  const response = await apiRequest({
2696
2817
  base,
2697
2818
  path: PREPARE_PATH,
2698
2819
  method: "POST",
2699
- body: { action, ...profileId ? { profileId } : {} },
2820
+ body: accountId === void 0 ? {} : { accountId },
2700
2821
  runtimeToken: runtime?.runtimeToken
2701
2822
  });
2702
- return validateLaunchResponse(response, astraHome());
2823
+ return validateLaunchResponse(response);
2703
2824
  }
2704
- function validateLaunchResponse(raw, home) {
2705
- const expectedDirectory = path13.resolve(homePaths(home).claudeProfilesDir);
2825
+ function claudeConfigDir(env, override) {
2826
+ if (override) return path13.resolve(override);
2827
+ const configured = env.CLAUDE_CONFIG_DIR?.trim();
2828
+ return configured ? configured : path13.join(os6.homedir(), ".claude");
2829
+ }
2830
+ function validateLaunchResponse(raw) {
2706
2831
  if (!isPlainObject(raw)) throw invalidLaunch();
2707
- const { profileId, configDirectory, settingsFile } = raw;
2708
- if (typeof profileId !== "string" || !PROFILE_ID_PATTERN.test(profileId)) throw invalidLaunch();
2709
- if (typeof configDirectory !== "string" || typeof settingsFile !== "string")
2710
- throw invalidLaunch();
2711
- if (path13.resolve(configDirectory) !== path13.join(expectedDirectory, profileId))
2832
+ const { accountId, accountName, expiresAtUtc, env } = raw;
2833
+ if (typeof accountId !== "string" || typeof accountName !== "string" || !isPlainObject(env))
2712
2834
  throw invalidLaunch();
2713
- const expectedSettings = path13.join(expectedDirectory, profileId, LAUNCH_FILE_NAME);
2714
- if (path13.resolve(settingsFile) !== expectedSettings) throw invalidLaunch();
2715
- return {
2716
- profileId,
2717
- configDirectory: path13.dirname(expectedSettings),
2718
- settingsFile: expectedSettings
2719
- };
2720
- }
2721
- function invalidLaunch() {
2722
- return new AstraError(
2723
- "The Astra server returned a Claude profile outside this machine's Astra data directory.",
2724
- "Astra only runs profiles it created under <astra home>/claude-profiles. Restart the server and try again."
2725
- );
2726
- }
2727
- function readLaunchEnv(settingsFile) {
2728
- for (const candidate of [settingsFile, path13.dirname(settingsFile), path13.dirname(path13.dirname(settingsFile))]) {
2729
- try {
2730
- const stat = fs16.lstatSync(candidate);
2731
- if (stat.isSymbolicLink() || candidate === settingsFile && (!stat.isFile() || stat.size > 64 * 1024)) {
2732
- throw new AstraError("The native Claude launch path must be a regular, bounded local file.");
2733
- }
2734
- } catch (error) {
2735
- if (error.code !== "ENOENT") throw error;
2736
- }
2835
+ const expiresAt = parseExpiry(expiresAtUtc);
2836
+ for (const [key, value] of Object.entries(env)) {
2837
+ if (!isAllowedEnvKey(key))
2838
+ throw invalidLaunch(`The Astra server returned an unknown Claude launch variable: ${key}`);
2839
+ if (typeof value !== "string")
2840
+ throw invalidLaunch(`The Astra server returned a non-text Claude launch variable: ${key}`);
2737
2841
  }
2738
- const text = readTextOrNull(settingsFile);
2739
- if (text === null) {
2842
+ if (typeof env[REQUIRED_LAUNCH_ENV_KEY] !== "string" || env[REQUIRED_LAUNCH_ENV_KEY] === "") {
2740
2843
  throw new AstraError(
2741
- `The Astra launch settings file is missing: ${settingsFile}`,
2742
- "Run the command again so the Astra server can recreate it."
2844
+ "The Astra server returned no Claude subscription token.",
2845
+ "Select the subscription account in the Astra web UI (Clients \u2192 Claude Code) and try again."
2743
2846
  );
2744
2847
  }
2745
- let parsed;
2746
- try {
2747
- parsed = JSON.parse(text);
2748
- } catch {
2749
- throw new AstraError(`The Astra launch settings file is not valid JSON: ${settingsFile}`);
2750
- }
2751
- if (!isPlainObject(parsed)) {
2752
- throw new AstraError(`The Astra launch settings file is not a JSON object: ${settingsFile}`);
2753
- }
2754
- if (parsed.forceLoginMethod !== SUBSCRIPTION_LOGIN_METHOD || !isPlainObject(parsed.env) || Object.keys(parsed).some((key) => key !== "forceLoginMethod" && key !== "env") || Object.entries(parsed.env).some(([key, value]) => !LAUNCH_ENV_WHITELIST.includes(key) || typeof value !== "string")) {
2755
- throw new AstraError(`The Astra launch settings file contains unexpected settings: ${settingsFile}`);
2756
- }
2757
- return parsed.env;
2848
+ return { accountId, accountName, expiresAt, env: { ...env } };
2758
2849
  }
2759
- function buildClaudeEnv(baseEnv, launchEnv, configDirectory) {
2850
+ function parseExpiry(value) {
2851
+ if (typeof value !== "string") throw invalidLaunch();
2852
+ const expiresAt = new Date(value);
2853
+ if (Number.isNaN(expiresAt.getTime())) throw invalidLaunch();
2854
+ return expiresAt;
2855
+ }
2856
+ function isAllowedEnvKey(key) {
2857
+ return LAUNCH_ENV_WHITELIST.includes(key);
2858
+ }
2859
+ function invalidLaunch(detail) {
2860
+ return new AstraError(
2861
+ detail ?? "The Astra server returned an unexpected Claude launch environment.",
2862
+ "Restart the server (`astra restart`) and try again with an up-to-date Astra."
2863
+ );
2864
+ }
2865
+ function buildClaudeEnv(baseEnv, launchEnv) {
2760
2866
  const env = {};
2761
2867
  for (const [key, value] of Object.entries(baseEnv)) {
2762
2868
  if (ENV_PREFIX_DENYLIST.some((prefix) => key.startsWith(prefix))) continue;
@@ -2767,7 +2873,6 @@ function buildClaudeEnv(baseEnv, launchEnv, configDirectory) {
2767
2873
  const value = launchEnv[key];
2768
2874
  if (typeof value === "string") env[key] = value;
2769
2875
  }
2770
- env.CLAUDE_CONFIG_DIR = path13.resolve(configDirectory);
2771
2876
  return env;
2772
2877
  }
2773
2878
  function assertNoSettingsConflicts(configDirectory, cwd) {
@@ -2780,9 +2885,10 @@ function assertNoSettingsConflicts(configDirectory, cwd) {
2780
2885
  if (conflicts.length === 0) return;
2781
2886
  const detail = conflicts.map((c) => ` ${c.key} ${c.file}`).join("\n");
2782
2887
  throw new AstraError(
2783
- `Claude settings on this machine override the native profile (${conflicts.length} conflict${conflicts.length === 1 ? "" : "s"}):`,
2888
+ `Claude settings on this machine override the subscription connection (${conflicts.length} conflict${conflicts.length === 1 ? "" : "s"}):`,
2784
2889
  `${detail}
2785
- Astra never edits your settings \u2014 remove or rename these entries yourself.`
2890
+ Astra never edits your settings \u2014 remove or rename these entries yourself.
2891
+ If a conflict comes from the Astra gateway takeover (ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN pointing at Astra), disable it first in the Astra web UI under Clients \u2192 Claude Code.`
2786
2892
  );
2787
2893
  }
2788
2894
  function settingsFilesToCheck(configDirectory, cwd) {
@@ -2856,104 +2962,9 @@ function settingsConflicts(file, settings) {
2856
2962
  conflicts.push({ file, key: "forceLoginGatewayUrl" });
2857
2963
  return conflicts;
2858
2964
  }
2859
- async function probeAuthStatus(spawnImpl, env, cwd) {
2860
- const result = await capture(spawnImpl, ["auth", "status"], env, cwd);
2861
- if (result.code !== 0) {
2862
- throw new AstraError(
2863
- "The official Claude Code CLI could not report the sign-in state of this profile.",
2864
- "Run `astra claude --status` to see the official output."
2865
- );
2866
- }
2867
- return parseAuthStatus(result.stdout);
2868
- }
2869
- function assertSubscriptionAuth(status) {
2870
- if (status.loggedIn && status.authMethod === SUBSCRIPTION_AUTH_METHOD) return;
2871
- if (!status.loggedIn) {
2872
- throw new AstraError(
2873
- "This Claude profile is not signed in.",
2874
- "Run `astra claude --login` to sign in with a Claude subscription."
2875
- );
2876
- }
2877
- throw new AstraError(
2878
- `This Claude profile is signed in with "${status.authMethod ?? "an unknown method"}", not a Claude subscription.`,
2879
- "Sign in with a subscription: run `astra claude --login` after clearing the other credential."
2880
- );
2881
- }
2882
- function parseAuthStatus(text) {
2883
- let parsed;
2884
- try {
2885
- parsed = JSON.parse(text.trim());
2886
- } catch {
2887
- throw unreadableAuthStatus();
2888
- }
2889
- if (!isPlainObject(parsed) || typeof parsed.loggedIn !== "boolean") throw unreadableAuthStatus();
2890
- return {
2891
- loggedIn: parsed.loggedIn,
2892
- authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null
2893
- };
2894
- }
2895
- function unreadableAuthStatus() {
2896
- return new AstraError(
2897
- "Could not read the sign-in state of the official Claude Code CLI.",
2898
- "Run `astra claude --status` to see the official output."
2899
- );
2900
- }
2901
2965
  function exitCodeFrom(code) {
2902
2966
  return code ?? 1;
2903
2967
  }
2904
- function capture(spawnImpl, args, env, cwd) {
2905
- return new Promise((resolve, reject) => {
2906
- let child;
2907
- try {
2908
- child = spawnImpl(OFFICIAL_CLI, args, {
2909
- cwd,
2910
- env,
2911
- shell: false,
2912
- stdio: "pipe",
2913
- windowsHide: true
2914
- });
2915
- } catch (err) {
2916
- reject(spawnFailure(err));
2917
- return;
2918
- }
2919
- let stdout = "";
2920
- let bytes = 0;
2921
- let settled = false;
2922
- const finish = (action) => {
2923
- if (settled) return;
2924
- settled = true;
2925
- clearTimeout(timer);
2926
- action();
2927
- };
2928
- const timer = setTimeout(() => {
2929
- kill(child);
2930
- finish(
2931
- () => reject(
2932
- new AstraError(
2933
- `The official Claude Code CLI did not answer within ${AUTH_STATUS_TIMEOUT_MS / 1e3} seconds.`
2934
- )
2935
- )
2936
- );
2937
- }, AUTH_STATUS_TIMEOUT_MS);
2938
- child.stdout?.on("data", (chunk) => {
2939
- if (settled) return;
2940
- bytes += Buffer.byteLength(chunk);
2941
- if (bytes > AUTH_STATUS_MAX_BYTES) {
2942
- kill(child);
2943
- finish(
2944
- () => reject(new AstraError("The official Claude Code CLI printed more than expected."))
2945
- );
2946
- return;
2947
- }
2948
- stdout += chunk.toString();
2949
- });
2950
- child.stderr?.on("data", () => {
2951
- });
2952
- child.stdin?.end();
2953
- child.on("error", (err) => finish(() => reject(spawnFailure(err))));
2954
- child.on("close", (code) => finish(() => resolve({ code, stdout })));
2955
- });
2956
- }
2957
2968
  function runInherit(spawnImpl, args, env, cwd) {
2958
2969
  return new Promise((resolve, reject) => {
2959
2970
  let child;
@@ -2993,12 +3004,6 @@ function runInherit(spawnImpl, args, env, cwd) {
2993
3004
  });
2994
3005
  });
2995
3006
  }
2996
- function kill(child) {
2997
- try {
2998
- child.kill("SIGKILL");
2999
- } catch {
3000
- }
3001
- }
3002
3007
  function spawnFailure(err) {
3003
3008
  const code = err.code;
3004
3009
  if (code === "ENOENT") {
@@ -3033,6 +3038,14 @@ function isNonEmptyValue(value) {
3033
3038
  }
3034
3039
 
3035
3040
  // src/index.ts
3041
+ function clientKindArgument() {
3042
+ return new Argument("<kind>", `Client kind (${CLIENT_KINDS.join(", ")}, or plugin-<id>)`).argParser(
3043
+ (value) => {
3044
+ if (!isClientKind(value)) throw new InvalidArgumentError(`Unknown client kind "${value}".`);
3045
+ return value;
3046
+ }
3047
+ );
3048
+ }
3036
3049
  function addStartOptions(cmd) {
3037
3050
  return cmd.option("--port <port>", "TCP port to listen on (default 17321)").option("--host <host>", "Address to bind (default 127.0.0.1)").option("--foreground", "Run the server in the foreground instead of detached").option("--open", "Open the web UI in the default browser");
3038
3051
  }
@@ -3065,14 +3078,14 @@ program.command("update").description("Update astra (and the desktop app when in
3065
3078
  );
3066
3079
  var client = program.command("client").description("Manage AI clients (Codex, Claude Code, \u2026)");
3067
3080
  client.command("list").description("List clients and their status").action(() => runClientList());
3068
- client.command("status").description("Show one client in detail").addArgument(new Argument("<kind>", "Client kind").choices([...CLIENT_KINDS])).action((kind) => runClientStatus(kind));
3069
- client.command("enable").description("Enable a client and point it at Astra").addArgument(new Argument("<kind>", "Client kind").choices([...CLIENT_KINDS])).requiredOption("--provider <id-or-name>", "Provider id or name to bind").option("--model <model>", "Model to write into the client configuration").option(
3081
+ client.command("status").description("Show one client in detail").addArgument(clientKindArgument()).action((kind) => runClientStatus(kind));
3082
+ client.command("enable").description("Enable a client and point it at Astra").addArgument(clientKindArgument()).requiredOption("--provider <id-or-name>", "Provider id or name to bind").option("--model <model>", "Model to write into the client configuration").option(
3070
3083
  "--token <id-or-name>",
3071
3084
  "Token to write into the client configuration (default: the client's current token, else the default token)"
3072
3085
  ).action(
3073
3086
  (kind, opts) => runClientEnable(kind, opts)
3074
3087
  );
3075
- client.command("disable").description("Disable a client and restore its original configuration").addArgument(new Argument("<kind>", "Client kind").choices([...CLIENT_KINDS])).action((kind) => runClientDisable(kind));
3088
+ client.command("disable").description("Disable a client and restore its original configuration").addArgument(clientKindArgument()).action((kind) => runClientDisable(kind));
3076
3089
  var token = program.command("token").description("Manage tokens (credentials clients use to reach Astra)");
3077
3090
  token.command("list").description("List tokens with today's and lifetime usage").action(() => runTokenList());
3078
3091
  var provider = program.command("provider").description("Manage providers (upstream AI accounts)");
@@ -3082,8 +3095,18 @@ provider.command("add").description("Add a provider from a template").requiredOp
3082
3095
  );
3083
3096
  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));
3084
3097
  provider.command("remove").description("Remove a provider").argument("<id>", "Provider id").action((id) => runProviderRemove(id));
3098
+ var plugin = program.command("plugin").alias("plugins").description("Manage plugins (magpie-compatible provider plugins, gateway middleware and clients)");
3099
+ plugin.command("list").alias("ls").description("List installed plugins").option("--json", "Print JSON").action((opts) => runPluginList(opts));
3100
+ 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));
3101
+ 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));
3102
+ plugin.command("on").description("Switch a plugin on").argument("<name>").action((name) => runPluginSwitch(name, true));
3103
+ plugin.command("off").description("Switch a plugin off").argument("<name>").action((name) => runPluginSwitch(name, false));
3104
+ plugin.command("update").alias("upgrade").description("Update a plugin to npm's newest (every plugin when none is named)").argument("[name]").action((name) => runPluginUpdate(name));
3105
+ plugin.command("options").alias("config").description(`Show a plugin's options, set them from JSON, or clear them with "off"`).argument("<name>").argument("[json]").action((name, json) => runPluginOptions(name, json));
3106
+ plugin.command("use").alias("prefer").description("Have a plugin serve a provider another plugin signs in to as well").argument("<name>").argument("<provider>", "The provider's id, as OpenCode knows it").action((name, provider2) => runPluginUse(name, provider2));
3107
+ plugin.command("market").description("List the market's plugins, or search npm and GitHub").argument("[query]").action((query) => runPluginMarket(query));
3085
3108
  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());
3086
- program.command("claude").description("Run the official Claude Code CLI with a native Astra profile").option("--profile <id>", "Native Claude profile id (32 hex characters)").option("--login", "Sign the profile in with a Claude subscription").option("--status", "Show the official sign-in state of the profile").action((opts) => runClaude(opts));
3109
+ 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));
3087
3110
  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));
3088
3111
  program.parseAsync(process6.argv).then(() => {
3089
3112
  }).catch((err) => {