astragate 0.2.3 → 0.3.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
@@ -188,7 +188,18 @@ var CLIENT_KINDS = [
188
188
  "hermes-agent",
189
189
  "minimax-code",
190
190
  "copilot-cli",
191
- "vscode-copilot"
191
+ "vscode-copilot",
192
+ "crush",
193
+ "qwen-code",
194
+ "droid",
195
+ "kimi-code",
196
+ "zed",
197
+ "vscode-insiders",
198
+ "vscodium",
199
+ "omp",
200
+ "mimo-code",
201
+ "deepseek-harness",
202
+ "workbuddy"
192
203
  ];
193
204
 
194
205
  // src/commands/manage.ts
@@ -460,6 +471,18 @@ function sha256File(file) {
460
471
  hash.update(fs4.readFileSync(file));
461
472
  return hash.digest("hex");
462
473
  }
474
+ var NATIVE_LIBRARY = /\.(dylib|so(\.\d+)*|dll)$/i;
475
+ function findNativeCompanions(binaryPath) {
476
+ const dir = path5.dirname(binaryPath);
477
+ const binaryName = path5.basename(binaryPath);
478
+ let entries;
479
+ try {
480
+ entries = fs4.readdirSync(dir, { withFileTypes: true });
481
+ } catch {
482
+ return [];
483
+ }
484
+ return entries.filter((e) => e.isFile() && e.name !== binaryName && NATIVE_LIBRARY.test(e.name)).map((e) => path5.join(dir, e.name));
485
+ }
463
486
  async function stageServerBinary(o) {
464
487
  const install = o.installIntoPrefix ?? npmInstallIntoPrefix;
465
488
  fs4.rmSync(o.stagingDir, { recursive: true, force: true });
@@ -480,7 +503,11 @@ async function stageServerBinary(o) {
480
503
  throw new Error(`Checksum mismatch for the staged server binary (expected ${o.sha256}, got ${actual}).`);
481
504
  }
482
505
  }
483
- return { path: staged, version: o.version };
506
+ const nativeLibraries = findNativeCompanions(staged);
507
+ if (nativeLibraries.length === 0) {
508
+ o.log?.("The staged package ships no native companion libraries (normal for a non-AOT build).");
509
+ }
510
+ return { path: staged, version: o.version, nativeLibraries };
484
511
  }
485
512
 
486
513
  // ../packages/update-core/src/swap.ts
@@ -496,6 +523,12 @@ function backupCurrentBinary(o) {
496
523
  const stamp = o.currentVersion ? `-${o.currentVersion}` : `-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
497
524
  const backupPath = path6.join(dir, `astra-server${stamp}${ext}`);
498
525
  fs5.copyFileSync(o.currentPath, backupPath);
526
+ const companions = findNativeCompanions(o.currentPath);
527
+ if (companions.length > 0) {
528
+ const libsDir = `${backupPath}-libs`;
529
+ fs5.mkdirSync(libsDir, { recursive: true });
530
+ for (const lib of companions) fs5.copyFileSync(lib, path6.join(libsDir, path6.basename(lib)));
531
+ }
499
532
  pruneBackups(dir, o.maxBackups ?? MAX_BACKUPS);
500
533
  return backupPath;
501
534
  }
@@ -506,10 +539,13 @@ function pruneBackups(dir, keep = MAX_BACKUPS) {
506
539
  } catch {
507
540
  return;
508
541
  }
509
- const excess = entries.length - keep;
542
+ const LIBS = "-libs";
543
+ const units = entries.filter((e) => !e.endsWith(LIBS) || !entries.includes(e.slice(0, -LIBS.length)));
544
+ const excess = units.length - keep;
510
545
  for (let i = 0; i < excess; i++) {
511
546
  try {
512
- fs5.rmSync(path6.join(dir, entries[i]), { force: true });
547
+ fs5.rmSync(path6.join(dir, units[i]), { recursive: true, force: true });
548
+ fs5.rmSync(`${path6.join(dir, units[i])}${LIBS}`, { recursive: true, force: true });
513
549
  } catch {
514
550
  }
515
551
  }
@@ -521,8 +557,39 @@ function installManagedBinary(o) {
521
557
  fs5.copyFileSync(o.stagedPath, tmp);
522
558
  fs5.renameSync(tmp, target);
523
559
  if (o.platform !== "win32") fs5.chmodSync(target, 493);
560
+ for (const lib of o.nativeLibraries ?? []) installNativeCompanion(lib, o.serverDir);
524
561
  return target;
525
562
  }
563
+ function installNativeCompanion(staged, serverDir) {
564
+ const dest = path6.join(serverDir, path6.basename(staged));
565
+ const tmp = `${dest}.tmp`;
566
+ const prev = `${dest}.prev`;
567
+ fs5.copyFileSync(staged, tmp);
568
+ fs5.rmSync(prev, { force: true });
569
+ if (fs5.existsSync(dest)) fs5.copyFileSync(dest, prev);
570
+ fs5.renameSync(tmp, dest);
571
+ }
572
+ function companionPrevNames(serverDir) {
573
+ let entries = [];
574
+ try {
575
+ entries = fs5.readdirSync(serverDir);
576
+ } catch {
577
+ return [];
578
+ }
579
+ return entries.filter((f) => f.endsWith(".prev") && NATIVE_LIBRARY.test(f.slice(0, -".prev".length)));
580
+ }
581
+ function commitNativeCompanions(serverDir) {
582
+ for (const name of companionPrevNames(serverDir)) {
583
+ fs5.rmSync(path6.join(serverDir, name), { force: true });
584
+ }
585
+ }
586
+ function restoreNativeCompanions(serverDir) {
587
+ for (const name of companionPrevNames(serverDir)) {
588
+ const dest = path6.join(serverDir, name.slice(0, -".prev".length));
589
+ fs5.rmSync(dest, { force: true });
590
+ fs5.renameSync(path6.join(serverDir, name), dest);
591
+ }
592
+ }
526
593
  function pruneManagedBinaries(serverDir, currentTarget, keep = 2) {
527
594
  let entries = [];
528
595
  try {
@@ -637,6 +704,7 @@ async function applyServerUpdate(o) {
637
704
  if (backupPath) log(`Backed up the current binary to ${backupPath}`);
638
705
  const serverPath = installManagedBinary({
639
706
  stagedPath: staged.path,
707
+ nativeLibraries: staged.nativeLibraries,
640
708
  serverDir: paths.serverDir,
641
709
  version: o.manifest.version,
642
710
  platform: o.platform
@@ -663,6 +731,7 @@ async function applyServerUpdate(o) {
663
731
  }
664
732
  fs6.rmSync(paths.stagingDir, { recursive: true, force: true });
665
733
  if (webRootSwapped) commitManagedWebRoot(paths.serverDir);
734
+ commitNativeCompanions(paths.serverDir);
666
735
  writeUpdateState(paths.stateFile, { ...initialState(now), phase: "idle" }, now);
667
736
  log(`Astra updated to ${o.manifest.version}.`);
668
737
  return { from: o.currentVersion, to: o.manifest.version, serverPath };
@@ -690,7 +759,9 @@ async function rollback(o, previousInstall, backupPath, webRootSwapped, setState
690
759
  writeInstallInfo(o.home, applyServerInfo(previousInstall, { serverPath: restorePath }));
691
760
  }
692
761
  if (await o.control.isRunning()) await o.control.stop();
693
- if (webRootSwapped) restoreManagedWebRoot(updatePaths(o.home).serverDir);
762
+ const serverDir = updatePaths(o.home).serverDir;
763
+ if (webRootSwapped) restoreManagedWebRoot(serverDir);
764
+ restoreNativeCompanions(serverDir);
694
765
  await o.control.start();
695
766
  } catch (rollbackErr) {
696
767
  setState("failed", void 0, `Rollback failed: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
@@ -1083,7 +1154,7 @@ import { fileURLToPath } from "url";
1083
1154
  // package.json
1084
1155
  var package_default = {
1085
1156
  name: "astragate",
1086
- version: "0.2.3",
1157
+ version: "0.3.0",
1087
1158
  description: "Astra \u2014 a local AI gateway. Install, start, stop and manage the astra-server from the terminal.",
1088
1159
  license: "MIT",
1089
1160
  type: "module",
@@ -1114,12 +1185,12 @@ var package_default = {
1114
1185
  commander: "^12.1.0"
1115
1186
  },
1116
1187
  optionalDependencies: {
1117
- "@aidotnet/server-darwin-arm64": "0.2.3",
1118
- "@aidotnet/server-darwin-x64": "0.2.3",
1119
- "@aidotnet/server-linux-arm64": "0.2.3",
1120
- "@aidotnet/server-linux-x64": "0.2.3",
1121
- "@aidotnet/server-win32-arm64": "0.2.3",
1122
- "@aidotnet/server-win32-x64": "0.2.3"
1188
+ "@aidotnet/server-darwin-arm64": "0.3.0",
1189
+ "@aidotnet/server-darwin-x64": "0.3.0",
1190
+ "@aidotnet/server-linux-arm64": "0.3.0",
1191
+ "@aidotnet/server-linux-x64": "0.3.0",
1192
+ "@aidotnet/server-win32-arm64": "0.3.0",
1193
+ "@aidotnet/server-win32-x64": "0.3.0"
1123
1194
  },
1124
1195
  devDependencies: {
1125
1196
  "@aidotnet/update-core": "workspace:*",
@@ -1862,11 +1933,13 @@ function ensureDesktopServer(o) {
1862
1933
  const { serverDir } = updatePaths(o.home);
1863
1934
  serverPath = installManagedBinary({
1864
1935
  stagedPath: packaged.path,
1936
+ nativeLibraries: findNativeCompanions(packaged.path),
1865
1937
  serverDir,
1866
1938
  version: o.version,
1867
1939
  platform: o.platform
1868
1940
  });
1869
1941
  if (installManagedWebRoot(packaged.path, serverDir)) commitManagedWebRoot(serverDir);
1942
+ commitNativeCompanions(serverDir);
1870
1943
  pruneManagedBinaries(serverDir, serverPath);
1871
1944
  action = "copied";
1872
1945
  }
@@ -2152,6 +2225,23 @@ function findProvider(providers, idOrName) {
2152
2225
  }
2153
2226
  return void 0;
2154
2227
  }
2228
+ function findToken(tokens, idOrName) {
2229
+ const needle = idOrName.toLowerCase();
2230
+ const byId = tokens.find((t) => t.id.toLowerCase() === needle);
2231
+ if (byId) return byId;
2232
+ const byName = tokens.filter((t) => t.name?.toLowerCase() === needle);
2233
+ if (byName.length === 1) return byName[0];
2234
+ if (byName.length > 1) {
2235
+ throw new AstraError(
2236
+ `Token name "${idOrName}" is ambiguous.`,
2237
+ `Matching ids: ${byName.map((t) => t.id).join(", ")} \u2014 use an id instead.`
2238
+ );
2239
+ }
2240
+ return void 0;
2241
+ }
2242
+ function fmtUsd(v) {
2243
+ return v === void 0 ? "" : `$${v.toFixed(v !== 0 && Math.abs(v) < 0.01 ? 4 : 2)}`;
2244
+ }
2155
2245
  async function runClientList() {
2156
2246
  const rows = await api("/api/clients");
2157
2247
  printTable(
@@ -2177,6 +2267,7 @@ async function runClientStatus(kind) {
2177
2267
  if (row.availability) console.log(` Availability ${row.availability}`);
2178
2268
  if (row.providerId) console.log(` Provider ${row.providerId}`);
2179
2269
  if (row.selectedModel) console.log(` Model ${row.selectedModel}`);
2270
+ if (row.tokenId) console.log(` Token ${row.tokenId}`);
2180
2271
  }
2181
2272
  async function runClientEnable(kind, opts) {
2182
2273
  const providers = await api("/api/providers");
@@ -2187,12 +2278,26 @@ async function runClientEnable(kind, opts) {
2187
2278
  "Run `astra provider list` to see available providers."
2188
2279
  );
2189
2280
  }
2281
+ let token2;
2282
+ if (opts.token) {
2283
+ token2 = findToken(await api("/api/tokens"), opts.token);
2284
+ if (!token2) {
2285
+ throw new AstraError(
2286
+ `No token matches "${opts.token}".`,
2287
+ "Run `astra token list` to see available tokens."
2288
+ );
2289
+ }
2290
+ }
2190
2291
  await api(`/api/clients/${kind}/enable`, {
2191
2292
  method: "POST",
2192
- body: { providerId: provider2.id, ...opts.model ? { model: opts.model } : {} }
2293
+ body: {
2294
+ providerId: provider2.id,
2295
+ ...opts.model ? { model: opts.model } : {},
2296
+ ...token2 ? { tokenId: token2.id } : {}
2297
+ }
2193
2298
  });
2194
2299
  success(
2195
- `Client "${kind}" enabled with provider "${provider2.name ?? provider2.id}"${opts.model ? ` (model: ${opts.model})` : ""}.`
2300
+ `Client "${kind}" enabled with provider "${provider2.name ?? provider2.id}"${opts.model ? ` (model: ${opts.model})` : ""}${token2 ? ` (token: ${token2.name ?? token2.id})` : ""}.`
2196
2301
  );
2197
2302
  console.log("Restart the client (Codex, Claude Desktop, \u2026) if it does not pick up the change.");
2198
2303
  }
@@ -2200,6 +2305,22 @@ async function runClientDisable(kind) {
2200
2305
  await api(`/api/clients/${kind}/disable`, { method: "POST", body: {} });
2201
2306
  success(`Client "${kind}" disabled. Its original configuration was restored.`);
2202
2307
  }
2308
+ async function runTokenList() {
2309
+ const rows = await api("/api/tokens");
2310
+ printTable(
2311
+ rows.map((r) => [
2312
+ r.id,
2313
+ r.name ?? "",
2314
+ fmtBool(r.isDefault),
2315
+ fmtBool(r.enabled),
2316
+ (r.clients ?? []).join(","),
2317
+ fmtUsd(r.today?.costUsd),
2318
+ r.today?.totalTokens === void 0 ? "" : String(r.today.totalTokens),
2319
+ fmtUsd(r.total?.costUsd)
2320
+ ]),
2321
+ ["ID", "NAME", "DEFAULT", "ENABLED", "CLIENTS", "TODAY COST", "TODAY TOKENS", "TOTAL COST"]
2322
+ );
2323
+ }
2203
2324
  async function runProviderList() {
2204
2325
  const rows = await api("/api/providers");
2205
2326
  printTable(
@@ -2265,6 +2386,84 @@ async function runProviderRemove(id) {
2265
2386
  }
2266
2387
  success(`Provider "${id}" removed.`);
2267
2388
  }
2389
+ var IMPORT_SOURCES = ["cc-switch", "alma", "claude-code", "codex", "magpie"];
2390
+ var SKIP_TEXT = {
2391
+ "official-login": "official login (not importable)",
2392
+ "no-base-url": "no base URL",
2393
+ "unsupported-protocol": "unsupported protocol",
2394
+ "points-to-astra": "points at Astra itself",
2395
+ "invalid-base-url": "invalid base URL",
2396
+ "no-inline-key": "key comes from an environment variable"
2397
+ };
2398
+ function importNote(c) {
2399
+ const notes = [];
2400
+ if (c.skipReason) notes.push(SKIP_TEXT[c.skipReason] ?? c.skipReason);
2401
+ if (c.status === "same" && c.existing) notes.push(`already added as "${c.existing.name}"`);
2402
+ if (c.status === "sameHost" && c.existing) notes.push(`same address as "${c.existing.name}"`);
2403
+ if (c.ignoredFields.length > 0) notes.push(`ignores ${c.ignoredFields.join(", ")}`);
2404
+ return notes.join("; ");
2405
+ }
2406
+ async function runProviderImport(opts) {
2407
+ if (opts.from && !IMPORT_SOURCES.includes(opts.from)) {
2408
+ throw new AstraError(`Unknown import source "${opts.from}".`, `Sources: ${IMPORT_SOURCES.join(", ")}`);
2409
+ }
2410
+ if (opts.only?.length && !opts.yes) {
2411
+ throw new AstraError("--only needs --yes.", "Run without options first to see the refs, then add --yes.");
2412
+ }
2413
+ const query = opts.from ? `?source=${encodeURIComponent(opts.from)}` : "";
2414
+ const sources = await api(`/api/providers/import/sources${query}`);
2415
+ const all = sources.flatMap((s) => s.items);
2416
+ if (!opts.yes) {
2417
+ for (const s of sources) {
2418
+ const state = s.error ? `error: ${s.error}` : s.found ? `${s.items.length} found` : "not found";
2419
+ console.log(`${s.name}${s.path ? ` (${s.path})` : ""} \u2014 ${state}`);
2420
+ if (s.items.length > 0) {
2421
+ printTable(
2422
+ s.items.map((c) => [
2423
+ c.ref,
2424
+ c.status,
2425
+ c.name,
2426
+ c.endpoints.map((e) => `${e.protocol} ${e.baseUrl}`).join(" | "),
2427
+ c.hasKey ? c.keyMasked ?? "\u2022\u2022\u2022\u2022" : "-",
2428
+ String(c.models.length),
2429
+ importNote(c)
2430
+ ]),
2431
+ ["REF", "STATUS", "NAME", "ENDPOINTS", "KEY", "MODELS", "NOTE"]
2432
+ );
2433
+ }
2434
+ console.log("");
2435
+ }
2436
+ const fresh = all.filter((c) => c.status === "new").length;
2437
+ console.log(
2438
+ fresh > 0 ? `Nothing was changed (sources are only read). Run again with --yes to import the ${fresh} new entr${fresh === 1 ? "y" : "ies"}, or --yes --only <ref>\u2026 to pick.` : "Nothing new to import."
2439
+ );
2440
+ return;
2441
+ }
2442
+ let chosen;
2443
+ if (opts.only?.length) {
2444
+ chosen = [];
2445
+ for (const ref of opts.only) {
2446
+ const found = all.find((c) => c.ref === ref);
2447
+ if (!found) throw new AstraError(`No importable entry "${ref}".`, "Run `astra provider import` to see the refs.");
2448
+ if (found.status === "skip" || found.status === "same") {
2449
+ throw new AstraError(`"${ref}" cannot be imported (${found.status === "same" ? "already added" : importNote(found)}).`);
2450
+ }
2451
+ chosen.push(found);
2452
+ }
2453
+ } else {
2454
+ chosen = all.filter((c) => c.status === "new");
2455
+ }
2456
+ if (chosen.length === 0) {
2457
+ console.log("Nothing to import.");
2458
+ return;
2459
+ }
2460
+ const result = await api("/api/providers/import", {
2461
+ method: "POST",
2462
+ body: chosen.map((c) => ({ source: c.source, ref: c.ref }))
2463
+ });
2464
+ for (const a of result.added) success(`Imported: ${a.name} (id: ${a.id}).`);
2465
+ for (const k of result.skipped) console.log(`Skipped ${k.ref}: ${SKIP_TEXT[k.reason] ?? k.reason}`);
2466
+ }
2268
2467
 
2269
2468
  // src/commands/config.ts
2270
2469
  import { spawn as spawn8 } from "child_process";
@@ -2341,15 +2540,21 @@ program.command("update").description("Update astra (and the desktop app when in
2341
2540
  var client = program.command("client").description("Manage AI clients (Codex, Claude Code, \u2026)");
2342
2541
  client.command("list").description("List clients and their status").action(() => runClientList());
2343
2542
  client.command("status").description("Show one client in detail").addArgument(new Argument("<kind>", "Client kind").choices([...CLIENT_KINDS])).action((kind) => runClientStatus(kind));
2344
- 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").action(
2543
+ 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(
2544
+ "--token <id-or-name>",
2545
+ "Token to write into the client configuration (default: the client's current token, else the default token)"
2546
+ ).action(
2345
2547
  (kind, opts) => runClientEnable(kind, opts)
2346
2548
  );
2347
2549
  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));
2550
+ var token = program.command("token").description("Manage tokens (credentials clients use to reach Astra)");
2551
+ token.command("list").description("List tokens with today's and lifetime usage").action(() => runTokenList());
2348
2552
  var provider = program.command("provider").description("Manage providers (upstream AI accounts)");
2349
2553
  provider.command("list").description("List providers").action(() => runProviderList());
2350
2554
  provider.command("add").description("Add a provider from a template").requiredOption("--template <id>", "Provider template id (see `astra provider templates`)").option("--variant <id>", "Template variant, when the template has variants").requiredOption("--key <apiKey>", "API key for the provider").option("--name <name>", "Display name for the provider").action(
2351
2555
  (opts) => runProviderAdd(opts)
2352
2556
  );
2557
+ 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));
2353
2558
  provider.command("remove").description("Remove a provider").argument("<id>", "Provider id").action((id) => runProviderRemove(id));
2354
2559
  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());
2355
2560
  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));