@aidotnet/astra-gate 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import process5 from "process";
4
+ import process6 from "process";
5
5
  import { Argument, Command } 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: path13, method = "GET", body, runtimeToken, timeoutMs = 1e4 } = options;
39
+ const { base, path: path14, 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 + path13, {
49
+ response = await doFetch(base + path14, {
50
50
  method,
51
51
  headers,
52
52
  body: body === void 0 ? void 0 : JSON.stringify(body),
@@ -199,7 +199,8 @@ var CLIENT_KINDS = [
199
199
  "omp",
200
200
  "mimo-code",
201
201
  "deepseek-harness",
202
- "workbuddy"
202
+ "workbuddy",
203
+ "muse-code"
203
204
  ];
204
205
 
205
206
  // src/commands/manage.ts
@@ -411,12 +412,76 @@ function runCapture(command, args, o = {}) {
411
412
  function npmCommand(o) {
412
413
  return o.npm ?? locateNpm(o);
413
414
  }
415
+ function dirHasExecutable(dir, name) {
416
+ try {
417
+ fs2.accessSync(path3.join(dir, name), fs2.constants.X_OK);
418
+ return true;
419
+ } catch {
420
+ return false;
421
+ }
422
+ }
423
+ var NODE_BIN_DIRS = ["/opt/homebrew/bin", "/usr/local/bin"];
424
+ var SHELL_PATH_MARKER = /__ASTRA_PATH_START__([\s\S]*?)__ASTRA_PATH_END__/;
425
+ var cachedLoginShellPath = null;
426
+ function readLoginShellPath(env, timeoutMs = 5e3) {
427
+ return new Promise((resolve) => {
428
+ let out = "";
429
+ let done = false;
430
+ let timer = null;
431
+ const finish = (value) => {
432
+ if (done) return;
433
+ done = true;
434
+ if (timer) clearTimeout(timer);
435
+ resolve(value);
436
+ };
437
+ let child;
438
+ try {
439
+ child = spawn(env.SHELL || "/bin/zsh", ["-ilc", 'printf "__ASTRA_PATH_START__%s__ASTRA_PATH_END__" "$PATH"'], {
440
+ env,
441
+ stdio: ["ignore", "pipe", "ignore"]
442
+ });
443
+ } catch {
444
+ finish(null);
445
+ return;
446
+ }
447
+ timer = setTimeout(() => {
448
+ try {
449
+ child.kill("SIGKILL");
450
+ } catch {
451
+ }
452
+ finish(null);
453
+ }, timeoutMs);
454
+ child.stdout?.on("data", (d) => {
455
+ out += d.toString();
456
+ });
457
+ child.on("error", () => finish(null));
458
+ child.on("close", () => finish(SHELL_PATH_MARKER.exec(out)?.[1] || null));
459
+ });
460
+ }
461
+ async function withNodeOnPath(env, npm, o = {}) {
462
+ if ((o.platform ?? process.platform) === "win32") return env;
463
+ const current = (env.PATH ?? "").split(path3.delimiter).filter(Boolean);
464
+ const hasNode = (dirs) => dirs.some((d) => dirHasExecutable(d, "node"));
465
+ if (hasNode(current)) return env;
466
+ const extra = [...path3.isAbsolute(npm.command) ? [path3.dirname(npm.command)] : [], ...o.wellKnownBinDirs ?? NODE_BIN_DIRS];
467
+ let merged = [...current, ...extra.filter((d) => !current.includes(d))];
468
+ if (!hasNode(merged)) {
469
+ const lookup = o.loginShellPath ?? (() => cachedLoginShellPath ??= readLoginShellPath(env));
470
+ const shellPath = await lookup();
471
+ if (shellPath) {
472
+ const shellDirs = shellPath.split(path3.delimiter).filter(Boolean);
473
+ merged = [...merged, ...shellDirs.filter((d) => !merged.includes(d))];
474
+ }
475
+ }
476
+ return { ...env, PATH: merged.join(path3.delimiter) };
477
+ }
414
478
  async function npmInstallIntoPrefix(prefix, spec, o = {}) {
415
479
  const npm = npmCommand(o);
480
+ const env = await withNodeOnPath(npmChildEnv(o.env), npm, o);
416
481
  const r = await runCapture(
417
482
  npm.command,
418
483
  [...npm.args, "install", "--prefix", prefix, "--no-audit", "--no-fund", "--loglevel", "error", spec],
419
- { env: npmChildEnv(o.env), platform: o.platform, timeoutMs: o.installTimeoutMs ?? 6e5 }
484
+ { env, platform: o.platform, timeoutMs: o.installTimeoutMs ?? 6e5 }
420
485
  );
421
486
  if (r.code !== 0) {
422
487
  throw new Error(`Failed to install ${spec}: ${r.stderr.trim() || `npm exited with code ${r.code}`}`);
@@ -453,6 +518,14 @@ function writeInstallInfo(home, info2) {
453
518
  fs3.writeFileSync(file, `${JSON.stringify(info2, null, 2)}
454
519
  `);
455
520
  }
521
+ function clearServerInfo(home, existing) {
522
+ const { serverPath: _serverPath, serverVersion: _serverVersion, updatedAt: _updatedAt, ...rest } = existing ?? {};
523
+ if (Object.keys(rest).length > 0) {
524
+ writeInstallInfo(home, { ...rest, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
525
+ } else {
526
+ fs3.rmSync(path4.join(home, "install.json"), { force: true });
527
+ }
528
+ }
456
529
  function applyServerInfo(existing, server) {
457
530
  return {
458
531
  ...existing ?? {},
@@ -757,6 +830,9 @@ async function rollback(o, previousInstall, backupPath, webRootSwapped, setState
757
830
  if (restorePath) {
758
831
  log(`Rolling back to ${restorePath}`);
759
832
  writeInstallInfo(o.home, applyServerInfo(previousInstall, { serverPath: restorePath }));
833
+ } else {
834
+ log("Rolling back to the server bundled with the app");
835
+ clearServerInfo(o.home, previousInstall);
760
836
  }
761
837
  if (await o.control.isRunning()) await o.control.stop();
762
838
  const serverDir = updatePaths(o.home).serverDir;
@@ -971,7 +1047,8 @@ function homePaths(home) {
971
1047
  serverStdoutLog: path8.join(home, "logs", "server-stdout.log"),
972
1048
  dbFile: path8.join(home, "astra.db"),
973
1049
  keysDir: path8.join(home, "keys"),
974
- desktopPrefix: path8.join(home, "desktop")
1050
+ desktopPrefix: path8.join(home, "desktop"),
1051
+ claudeProfilesDir: path8.join(home, "claude-profiles")
975
1052
  };
976
1053
  }
977
1054
 
@@ -1154,7 +1231,7 @@ import { fileURLToPath } from "url";
1154
1231
  // package.json
1155
1232
  var package_default = {
1156
1233
  name: "@aidotnet/astra-gate",
1157
- version: "0.4.0",
1234
+ version: "0.5.1",
1158
1235
  description: "Astra \u2014 a local AI gateway. Install, start, stop and manage the astra-server from the terminal.",
1159
1236
  license: "MIT",
1160
1237
  type: "module",
@@ -1185,12 +1262,12 @@ var package_default = {
1185
1262
  commander: "^12.1.0"
1186
1263
  },
1187
1264
  optionalDependencies: {
1188
- "@aidotnet/server-darwin-arm64": "0.4.0",
1189
- "@aidotnet/server-darwin-x64": "0.4.0",
1190
- "@aidotnet/server-linux-arm64": "0.4.0",
1191
- "@aidotnet/server-linux-x64": "0.4.0",
1192
- "@aidotnet/server-win32-arm64": "0.4.0",
1193
- "@aidotnet/server-win32-x64": "0.4.0"
1265
+ "@aidotnet/server-darwin-arm64": "0.5.1",
1266
+ "@aidotnet/server-darwin-x64": "0.5.1",
1267
+ "@aidotnet/server-linux-arm64": "0.5.1",
1268
+ "@aidotnet/server-linux-x64": "0.5.1",
1269
+ "@aidotnet/server-win32-arm64": "0.5.1",
1270
+ "@aidotnet/server-win32-x64": "0.5.1"
1194
1271
  },
1195
1272
  devDependencies: {
1196
1273
  "@aidotnet/update-core": "workspace:*",
@@ -2127,7 +2204,9 @@ async function updateServer(home, manifest, force) {
2127
2204
  await applyServerUpdate({
2128
2205
  home,
2129
2206
  manifest,
2130
- platformKey: `${plat.platform}-${plat.arch}`,
2207
+ // manifest.platforms is keyed by .NET RID (osx-arm64), not process.platform (darwin-arm64):
2208
+ // a wrong key silently drops the sha256 check.
2209
+ platformKey: plat.rid,
2131
2210
  serverPackage: plat.serverPackage,
2132
2211
  platform: plat.platform,
2133
2212
  currentServerPath: readInstallJson(home)?.serverPath ?? null,
@@ -2196,12 +2275,12 @@ async function runUninstall(opts) {
2196
2275
  }
2197
2276
 
2198
2277
  // src/commands/admin.ts
2199
- async function api(path13, options = {}) {
2278
+ async function api(path14, options = {}) {
2200
2279
  const { base, runtime, started } = await ensureServerRunning();
2201
2280
  if (started) console.log("Server was not running \u2014 started it in the background.");
2202
2281
  return apiRequest({
2203
2282
  base,
2204
- path: path13,
2283
+ path: path14,
2205
2284
  method: options.method ?? "GET",
2206
2285
  body: options.body,
2207
2286
  runtimeToken: runtime?.runtimeToken
@@ -2506,6 +2585,453 @@ async function runRestoreAll(opts) {
2506
2585
  );
2507
2586
  }
2508
2587
 
2588
+ // src/commands/claude.ts
2589
+ import fs16 from "fs";
2590
+ import path13 from "path";
2591
+ import process5 from "process";
2592
+ import { spawn as spawn10 } from "child_process";
2593
+ var LAUNCH_FILE_NAME = "astra-launch.json";
2594
+ var PREPARE_PATH = "/api/clients/claude-code/direct/prepare";
2595
+ var PROFILE_ID_PATTERN = /^[a-f0-9]{32}$/;
2596
+ var SUBSCRIPTION_LOGIN_METHOD = "claudeai";
2597
+ 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;
2601
+ var ENV_PREFIX_DENYLIST = ["ANTHROPIC_", "OTEL_"];
2602
+ var ENV_NAME_DENYLIST = [
2603
+ "CLAUDE_CODE_OAUTH_TOKEN",
2604
+ "CLAUDE_CODE_USE_BEDROCK",
2605
+ "CLAUDE_CODE_USE_VERTEX",
2606
+ "CLAUDE_CODE_USE_FOUNDRY",
2607
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
2608
+ "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
2609
+ "CLAUDE_CODE_OTEL_HEADERS_HELPER",
2610
+ "CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS",
2611
+ "ENABLE_ENHANCED_TELEMETRY_BETA",
2612
+ "ENABLE_BETA_TRACING_DETAILED",
2613
+ "BETA_TRACING_ENDPOINT"
2614
+ ];
2615
+ var LAUNCH_ENV_WHITELIST = [
2616
+ "ANTHROPIC_BASE_URL",
2617
+ "ANTHROPIC_API_KEY",
2618
+ "ANTHROPIC_AUTH_TOKEN",
2619
+ "CLAUDE_CODE_OAUTH_TOKEN",
2620
+ "CLAUDE_CODE_USE_BEDROCK",
2621
+ "CLAUDE_CODE_USE_VERTEX",
2622
+ "CLAUDE_CODE_USE_FOUNDRY",
2623
+ "CLAUDE_CODE_ENABLE_TELEMETRY",
2624
+ "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA",
2625
+ "ENABLE_ENHANCED_TELEMETRY_BETA",
2626
+ "ENABLE_BETA_TRACING_DETAILED",
2627
+ "BETA_TRACING_ENDPOINT",
2628
+ "OTEL_LOGS_EXPORTER",
2629
+ "OTEL_METRICS_EXPORTER",
2630
+ "OTEL_TRACES_EXPORTER",
2631
+ "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL",
2632
+ "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT",
2633
+ "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
2634
+ "OTEL_LOG_USER_PROMPTS",
2635
+ "OTEL_LOG_ASSISTANT_RESPONSES",
2636
+ "OTEL_LOG_TOOL_DETAILS",
2637
+ "OTEL_LOG_TOOL_CONTENT",
2638
+ "OTEL_LOG_RAW_API_BODIES",
2639
+ "OTEL_RESOURCE_ATTRIBUTES"
2640
+ ];
2641
+ var CREDENTIAL_ENV_KEYS = [
2642
+ "ANTHROPIC_API_KEY",
2643
+ "ANTHROPIC_AUTH_TOKEN",
2644
+ "CLAUDE_CODE_OAUTH_TOKEN"
2645
+ ];
2646
+ var EXTERNAL_PROVIDER_ENV_KEYS = [
2647
+ "CLAUDE_CODE_USE_BEDROCK",
2648
+ "CLAUDE_CODE_USE_VERTEX",
2649
+ "CLAUDE_CODE_USE_FOUNDRY"
2650
+ ];
2651
+ var HELPER_SETTING_KEYS = ["apiKeyHelper", "otelHeadersHelper"];
2652
+ var spawnOfficial = (command, args, options) => spawn10(command, [...args], options);
2653
+ var OFFICIAL_CLI = "claude";
2654
+ async function runClaude(opts, deps = {}) {
2655
+ if (opts.login && opts.status) {
2656
+ 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."
2659
+ );
2660
+ }
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;
2669
+ 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}).`));
2683
+ }
2684
+ const result = await runInherit(spawnImpl, args, childEnv, cwd);
2685
+ 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));
2690
+ }
2691
+ }
2692
+ async function prepareLaunch(action, profileId) {
2693
+ const { base, runtime, started } = await ensureServerRunning();
2694
+ if (started) console.log("Server was not running \u2014 started it in the background.");
2695
+ const response = await apiRequest({
2696
+ base,
2697
+ path: PREPARE_PATH,
2698
+ method: "POST",
2699
+ body: { action, ...profileId ? { profileId } : {} },
2700
+ runtimeToken: runtime?.runtimeToken
2701
+ });
2702
+ return validateLaunchResponse(response, astraHome());
2703
+ }
2704
+ function validateLaunchResponse(raw, home) {
2705
+ const expectedDirectory = path13.resolve(homePaths(home).claudeProfilesDir);
2706
+ 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))
2712
+ 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
+ }
2737
+ }
2738
+ const text = readTextOrNull(settingsFile);
2739
+ if (text === null) {
2740
+ throw new AstraError(
2741
+ `The Astra launch settings file is missing: ${settingsFile}`,
2742
+ "Run the command again so the Astra server can recreate it."
2743
+ );
2744
+ }
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;
2758
+ }
2759
+ function buildClaudeEnv(baseEnv, launchEnv, configDirectory) {
2760
+ const env = {};
2761
+ for (const [key, value] of Object.entries(baseEnv)) {
2762
+ if (ENV_PREFIX_DENYLIST.some((prefix) => key.startsWith(prefix))) continue;
2763
+ if (ENV_NAME_DENYLIST.includes(key)) continue;
2764
+ env[key] = value;
2765
+ }
2766
+ for (const key of LAUNCH_ENV_WHITELIST) {
2767
+ const value = launchEnv[key];
2768
+ if (typeof value === "string") env[key] = value;
2769
+ }
2770
+ env.CLAUDE_CONFIG_DIR = path13.resolve(configDirectory);
2771
+ return env;
2772
+ }
2773
+ function assertNoSettingsConflicts(configDirectory, cwd) {
2774
+ const conflicts = [];
2775
+ for (const file of settingsFilesToCheck(configDirectory, cwd)) {
2776
+ const text = readTextOrNull(file);
2777
+ if (text === null) continue;
2778
+ conflicts.push(...settingsConflicts(file, parseSettingsJson(file, text)));
2779
+ }
2780
+ if (conflicts.length === 0) return;
2781
+ const detail = conflicts.map((c) => ` ${c.key} ${c.file}`).join("\n");
2782
+ throw new AstraError(
2783
+ `Claude settings on this machine override the native profile (${conflicts.length} conflict${conflicts.length === 1 ? "" : "s"}):`,
2784
+ `${detail}
2785
+ Astra never edits your settings \u2014 remove or rename these entries yourself.`
2786
+ );
2787
+ }
2788
+ function settingsFilesToCheck(configDirectory, cwd) {
2789
+ const files = [path13.join(configDirectory, "settings.json")];
2790
+ const root = findGitRoot(cwd);
2791
+ let dir = path13.resolve(cwd);
2792
+ for (; ; ) {
2793
+ files.push(path13.join(dir, ".claude", "settings.json"));
2794
+ files.push(path13.join(dir, ".claude", "settings.local.json"));
2795
+ if (root === null || dir === root) break;
2796
+ const parent = path13.dirname(dir);
2797
+ if (parent === dir) break;
2798
+ dir = parent;
2799
+ }
2800
+ return [...new Set(files)];
2801
+ }
2802
+ function findGitRoot(startDir) {
2803
+ let dir = path13.resolve(startDir);
2804
+ for (; ; ) {
2805
+ if (fs16.existsSync(path13.join(dir, ".git"))) return dir;
2806
+ const parent = path13.dirname(dir);
2807
+ if (parent === dir) return null;
2808
+ dir = parent;
2809
+ }
2810
+ }
2811
+ function parseSettingsJson(file, text) {
2812
+ let parsed;
2813
+ try {
2814
+ parsed = JSON.parse(text);
2815
+ } catch {
2816
+ throw new AstraError(
2817
+ `Claude settings are not valid JSON: ${file}`,
2818
+ "Fix or remove the file yourself \u2014 Astra never edits your settings."
2819
+ );
2820
+ }
2821
+ if (!isPlainObject(parsed)) {
2822
+ throw new AstraError(
2823
+ `Claude settings are not a JSON object: ${file}`,
2824
+ "Fix or remove the file yourself \u2014 Astra never edits your settings."
2825
+ );
2826
+ }
2827
+ return parsed;
2828
+ }
2829
+ function settingsConflicts(file, settings) {
2830
+ const conflicts = [];
2831
+ if (settings.env !== void 0 && !isPlainObject(settings.env)) {
2832
+ conflicts.push({ file, key: "env" });
2833
+ }
2834
+ const env = isPlainObject(settings.env) ? settings.env : {};
2835
+ for (const [key, value] of Object.entries(env)) {
2836
+ if ((key.startsWith("OTEL_") || key.startsWith("ANTHROPIC_FEDERATION_") || key === "ANTHROPIC_PROFILE" || key === "ANTHROPIC_ORGANIZATION_ID" || key === "CLAUDE_CONFIG_DIR" || key === "BETA_TRACING_ENDPOINT") && isNonEmptyValue(value)) {
2837
+ conflicts.push({ file, key: `env.${key}` });
2838
+ }
2839
+ }
2840
+ for (const key of CREDENTIAL_ENV_KEYS) {
2841
+ if (isNonEmptyText(env[key])) conflicts.push({ file, key: `env.${key}` });
2842
+ }
2843
+ for (const key of EXTERNAL_PROVIDER_ENV_KEYS) {
2844
+ if (isEnabledFlag(env[key])) conflicts.push({ file, key: `env.${key}` });
2845
+ }
2846
+ if (isNonEmptyText(env.ANTHROPIC_BASE_URL) && String(env.ANTHROPIC_BASE_URL).trim() !== OFFICIAL_BASE_URL) {
2847
+ conflicts.push({ file, key: "env.ANTHROPIC_BASE_URL" });
2848
+ }
2849
+ for (const key of HELPER_SETTING_KEYS) {
2850
+ if (isNonEmptyValue(settings[key])) conflicts.push({ file, key });
2851
+ }
2852
+ if (isNonEmptyText(settings.forceLoginMethod) && String(settings.forceLoginMethod).trim() !== SUBSCRIPTION_LOGIN_METHOD) {
2853
+ conflicts.push({ file, key: "forceLoginMethod" });
2854
+ }
2855
+ if (isNonEmptyValue(settings.forceLoginGatewayUrl))
2856
+ conflicts.push({ file, key: "forceLoginGatewayUrl" });
2857
+ return conflicts;
2858
+ }
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
+ function exitCodeFrom(code) {
2902
+ return code ?? 1;
2903
+ }
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
+ function runInherit(spawnImpl, args, env, cwd) {
2958
+ return new Promise((resolve, reject) => {
2959
+ let child;
2960
+ try {
2961
+ child = spawnImpl(OFFICIAL_CLI, args, {
2962
+ cwd,
2963
+ env,
2964
+ shell: false,
2965
+ stdio: "inherit",
2966
+ windowsHide: true
2967
+ });
2968
+ } catch (err) {
2969
+ reject(spawnFailure(err));
2970
+ return;
2971
+ }
2972
+ const forward = (signal) => {
2973
+ try {
2974
+ child.kill(signal);
2975
+ } catch {
2976
+ }
2977
+ };
2978
+ const onInterrupt = () => forward("SIGINT");
2979
+ const onTerminate = () => forward("SIGTERM");
2980
+ const cleanup = () => {
2981
+ process5.removeListener("SIGINT", onInterrupt);
2982
+ process5.removeListener("SIGTERM", onTerminate);
2983
+ };
2984
+ process5.on("SIGINT", onInterrupt);
2985
+ process5.on("SIGTERM", onTerminate);
2986
+ child.on("error", (err) => {
2987
+ cleanup();
2988
+ reject(spawnFailure(err));
2989
+ });
2990
+ child.on("close", (code) => {
2991
+ cleanup();
2992
+ resolve({ code });
2993
+ });
2994
+ });
2995
+ }
2996
+ function kill(child) {
2997
+ try {
2998
+ child.kill("SIGKILL");
2999
+ } catch {
3000
+ }
3001
+ }
3002
+ function spawnFailure(err) {
3003
+ const code = err.code;
3004
+ if (code === "ENOENT") {
3005
+ return new AstraError(
3006
+ "The official Claude Code CLI was not found on PATH.",
3007
+ "Install it with `npm install -g @anthropic-ai/claude-code`."
3008
+ );
3009
+ }
3010
+ return new AstraError(
3011
+ `Could not start the official Claude Code CLI: ${code ?? (err instanceof Error ? err.message : "unknown error")}`
3012
+ );
3013
+ }
3014
+ function isPlainObject(value) {
3015
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3016
+ }
3017
+ function isNonEmptyText(value) {
3018
+ return typeof value === "string" && value.trim() !== "";
3019
+ }
3020
+ function isEnabledFlag(value) {
3021
+ if (typeof value === "boolean") return value;
3022
+ if (typeof value === "number") return value !== 0;
3023
+ if (typeof value === "string")
3024
+ return !["", "0", "false", "no", "off"].includes(value.trim().toLowerCase());
3025
+ return false;
3026
+ }
3027
+ function isNonEmptyValue(value) {
3028
+ if (typeof value === "string") return value.trim() !== "";
3029
+ if (Array.isArray(value)) return value.length > 0;
3030
+ if (isPlainObject(value)) return Object.keys(value).length > 0;
3031
+ if (typeof value === "number") return true;
3032
+ return value === true;
3033
+ }
3034
+
2509
3035
  // src/index.ts
2510
3036
  function addStartOptions(cmd) {
2511
3037
  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");
@@ -2557,23 +3083,24 @@ provider.command("add").description("Add a provider from a template").requiredOp
2557
3083
  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));
2558
3084
  provider.command("remove").description("Remove a provider").argument("<id>", "Provider id").action((id) => runProviderRemove(id));
2559
3085
  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));
2560
3087
  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));
2561
- program.parseAsync(process5.argv).then(() => {
3088
+ program.parseAsync(process6.argv).then(() => {
2562
3089
  }).catch((err) => {
2563
3090
  if (err instanceof ApiError) {
2564
3091
  fail(`error: ${err.message} (HTTP ${err.status})`);
2565
- process5.exitCode = 1;
3092
+ process6.exitCode = 1;
2566
3093
  return;
2567
3094
  }
2568
3095
  if (err instanceof AstraError) {
2569
3096
  fail(`error: ${err.message}`);
2570
3097
  if (err.hint) console.error(` ${err.hint}`);
2571
- process5.exitCode = 1;
3098
+ process6.exitCode = 1;
2572
3099
  return;
2573
3100
  }
2574
3101
  fail(`error: ${err instanceof Error ? err.message : String(err)}`);
2575
- if (process5.env.ASTRA_DEBUG) console.error(err);
3102
+ if (process6.env.ASTRA_DEBUG) console.error(err);
2576
3103
  else console.error("Run with ASTRA_DEBUG=1 for a stack trace.");
2577
- process5.exitCode = 1;
3104
+ process6.exitCode = 1;
2578
3105
  });
2579
3106
  //# sourceMappingURL=index.js.map