akadmin 0.1.0 → 0.1.2

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,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
+ import fs4 from "node:fs";
5
+ import { fileURLToPath } from "node:url";
4
6
  import { Command } from "commander";
5
7
 
6
8
  // ../manifest/dist/manifest-data.js
@@ -25578,8 +25580,8 @@ function getAllDomains() {
25578
25580
  }
25579
25581
 
25580
25582
  // src/commands/discover.ts
25581
- function registerDiscoverCommands(program2) {
25582
- program2.command("discover [domain]").description("Explore available administrative domains and operations").option("--json", "Output JSON format").option("--destructive", "Filter only destructive operations").action((domain, options) => {
25583
+ function registerDiscoverCommands(program) {
25584
+ program.command("discover [domain]").description("Explore available administrative domains and operations").option("--json", "Output JSON format").option("--destructive", "Filter only destructive operations").action((domain, options) => {
25583
25585
  if (!domain) {
25584
25586
  const domains = getAllDomains();
25585
25587
  const summary = domains.map((d) => {
@@ -25631,7 +25633,7 @@ function registerDiscoverCommands(program2) {
25631
25633
  }
25632
25634
  }
25633
25635
  });
25634
- program2.command("describe <operationId>").description("Show detailed schema, parameters, and scopes for an operation").option("--json", "Output JSON format").action((operationId, options) => {
25636
+ program.command("describe <operationId>").description("Show detailed schema, parameters, and scopes for an operation").option("--json", "Output JSON format").action((operationId, options) => {
25635
25637
  const op = getOperation(operationId);
25636
25638
  if (!op) {
25637
25639
  console.error(`Error: Operation '${operationId}' not found.`);
@@ -26413,22 +26415,26 @@ var FileAuditStore = class {
26413
26415
  };
26414
26416
 
26415
26417
  // src/commands/raw.ts
26416
- function registerRawCommand(program2, keychain2) {
26417
- const nonceStore = new FileNonceStore(keychain2.getConfigDir());
26418
- const auditStore = new FileAuditStore(keychain2.getConfigDir());
26419
- program2.command("raw <operationId>").description("Invoke any of the 124 OpenAPI operations by operationId").option("-p, --param <key=value...>", "Path/query parameters (e.g. -p orderId=ord_100)").option("-b, --body <json>", "Request body JSON string").option("-o, --output <filePath>", "Save response output directly to file (for PDF invoices, CSV exports, etc.)").option("--confirm <token>", "Confirm token required to execute mutations").option("--profile <profile>", "Target environment profile (default: production)").option("--json", "Output JSON format").action(async (operationId, options) => {
26420
- const activeProfile = options.profile || keychain2.getActiveProfile();
26421
- const creds = await keychain2.getCredentials(activeProfile);
26422
- const signingSecret = await keychain2.getSigningSecret();
26418
+ function registerRawCommand(program, keychain) {
26419
+ const nonceStore = new FileNonceStore(keychain.getConfigDir());
26420
+ const auditStore = new FileAuditStore(keychain.getConfigDir());
26421
+ program.command("raw <operationId>").description("Invoke any of the 124 OpenAPI operations by operationId").option("-p, --param <key=value...>", "Path/query parameters (e.g. -p orderId=ord_100)").option("-b, --body <json>", "Request body JSON string").option("-o, --output <filePath>", "Save response output directly to file (for PDF invoices, CSV exports, etc.)").option("-k, --api-key <key>", "Admin API key for this execution (in-memory only)").option("--session-cookie <cookie>", "Session cookie for this execution (in-memory only)").option("--confirm <token>", "Confirm token required to execute mutations").option("--profile <profile>", "Target environment profile (default: production)").option("--json", "Output JSON format").action(async (operationId, options) => {
26422
+ const globalOpts = program.opts();
26423
+ const activeProfile = options.profile || globalOpts.profile || keychain.getActiveProfile();
26424
+ const apiKeyOverride = options.apiKey || globalOpts.apiKey;
26425
+ const sessionCookieOverride = options.sessionCookie || globalOpts.sessionCookie;
26426
+ const creds = await keychain.getCredentials(activeProfile, {
26427
+ apiKey: apiKeyOverride,
26428
+ sessionCookie: sessionCookieOverride
26429
+ });
26430
+ const signingSecret = await keychain.getSigningSecret();
26423
26431
  const params = {};
26424
26432
  if (options.param) {
26425
26433
  const paramList = Array.isArray(options.param) ? options.param : [options.param];
26426
- for (const item of paramList) {
26427
- const eqIdx = item.indexOf("=");
26434
+ for (const p of paramList) {
26435
+ const eqIdx = p.indexOf("=");
26428
26436
  if (eqIdx !== -1) {
26429
- const k = item.slice(0, eqIdx).trim();
26430
- const v = item.slice(eqIdx + 1).trim();
26431
- params[k] = v;
26437
+ params[p.slice(0, eqIdx)] = p.slice(eqIdx + 1);
26432
26438
  }
26433
26439
  }
26434
26440
  }
@@ -26437,85 +26443,77 @@ function registerRawCommand(program2, keychain2) {
26437
26443
  try {
26438
26444
  parsedBody = JSON.parse(options.body);
26439
26445
  } catch {
26440
- console.error("Error: --body must be valid JSON.");
26446
+ console.error("Error: --body must be a valid JSON string.");
26441
26447
  process.exitCode = 1;
26442
26448
  return;
26443
26449
  }
26444
26450
  }
26445
26451
  const context = {
26446
- operatorId: "cli_operator",
26452
+ operatorId: "op_cli_local",
26447
26453
  profile: activeProfile,
26448
26454
  apiKey: creds.apiKey,
26449
26455
  sessionCookie: creds.sessionCookie,
26450
- baseUrl: creds.baseUrl || "https://agentkit.best",
26456
+ baseUrl: creds.baseUrl,
26451
26457
  signingSecret,
26458
+ confirmToken: options.confirm,
26452
26459
  nonceStore,
26453
- auditStore,
26454
- confirmToken: options.confirm
26460
+ auditStore
26455
26461
  };
26456
26462
  const result = await executeOperation(operationId, params, parsedBody, context);
26457
26463
  if (options.json) {
26458
26464
  console.log(JSON.stringify(result, null, 2));
26459
- if (result.status === "error") process.exitCode = 1;
26460
26465
  return;
26461
26466
  }
26462
26467
  if (result.status === "confirmation_required") {
26463
- const p = result.preview;
26464
- console.log(`
26465
- \u{1F512} [PREVIEW \u2014 ${activeProfile.toUpperCase()}] ${p.summary || p.operationId}`);
26466
- console.log(`Endpoint: ${p.method} ${p.path}`);
26467
- console.log(`Impact: ${p.impactDescription}`);
26468
- console.log(`Hash: ${p.canonicalHash.slice(0, 16)}...`);
26469
- console.log(`Expires: ${p.expiresAt}`);
26470
- for (const w of p.warnings) console.log(` ${w}`);
26471
- console.log("\n\u25B6 TO EXECUTE, re-run with confirmation token:");
26472
- console.log(` akadmin raw ${operationId} ${options.param ? `--param ${options.param}` : ""} --confirm ${p.confirmToken}
26468
+ console.log("\n\u26A0\uFE0F CONFIRMATION REQUIRED (Destructive Operation)\n");
26469
+ console.log(` Operation: ${result.operationId} [${result.domain}]`);
26470
+ console.log(` Target Profile: ${activeProfile.toUpperCase()}`);
26471
+ console.log(` Impact: ${result.impactDescription}`);
26472
+ console.log(` Preview Summary: ${result.previewSummary}`);
26473
+ console.log(` Confirm Token: ${result.confirmToken} (Valid for ${result.expiresInSeconds}s)`);
26474
+ console.log("\nTo execute, re-run with:\n");
26475
+ console.log(` akadmin raw ${operationId} ${options.param ? `-p ${options.param}` : ""} ${options.body ? `-b '${options.body}'` : ""} --confirm "${result.confirmToken}"
26473
26476
  `);
26474
26477
  return;
26475
26478
  }
26476
26479
  if (result.status === "executed") {
26477
- const data = result.data;
26478
- if (data && typeof data === "object" && "isBinary" in data && data.isBinary === true) {
26479
- const binaryObj = data;
26480
- if (options.output) {
26481
- const outPath = path2.resolve(process.cwd(), options.output);
26482
- fs2.writeFileSync(outPath, binaryObj.rawBytes);
26483
- console.log(`
26484
- \u2705 Saved binary response (${binaryObj.contentType}, ${binaryObj.byteLength} bytes) to: ${outPath}`);
26480
+ console.log(`
26481
+ \u2705 Executed '${operationId}' [HTTP ${result.httpStatus}]
26482
+ `);
26483
+ if (options.output) {
26484
+ const outPath = path2.resolve(process.cwd(), options.output);
26485
+ fs2.mkdirSync(path2.dirname(outPath), { recursive: true });
26486
+ if (result.isBinary && typeof result.data === "string") {
26487
+ const buf = Buffer.from(result.data, "base64");
26488
+ fs2.writeFileSync(outPath, buf);
26489
+ console.log(`\u{1F4BE} Saved binary payload (${buf.length} bytes) to '${options.output}'.
26490
+ `);
26491
+ } else if (typeof result.data === "string") {
26492
+ fs2.writeFileSync(outPath, result.data, "utf-8");
26493
+ console.log(`\u{1F4BE} Saved text payload (${result.data.length} chars) to '${options.output}'.
26494
+ `);
26485
26495
  } else {
26486
- console.log(`
26487
- \u{1F4C4} [${activeProfile.toUpperCase()}] Binary Response Received: ${binaryObj.contentType} (${binaryObj.byteLength} bytes).`);
26488
- console.log(" Pass `-o <filename.pdf>` to write this file directly to disk.\n");
26496
+ fs2.writeFileSync(outPath, JSON.stringify(result.data, null, 2), "utf-8");
26497
+ console.log(`\u{1F4BE} Saved JSON output to '${options.output}'.
26498
+ `);
26489
26499
  }
26490
- console.log(`Audit ID: ${result.auditId}`);
26491
26500
  return;
26492
26501
  }
26493
- if (data && typeof data === "object" && "isText" in data && data.isText === true) {
26494
- const textObj = data;
26495
- if (options.output) {
26496
- const outPath = path2.resolve(process.cwd(), options.output);
26497
- fs2.writeFileSync(outPath, textObj.content, "utf-8");
26498
- console.log(`
26499
- \u2705 Saved text/CSV export (${textObj.contentType}) to: ${outPath}`);
26500
- } else {
26501
- console.log(textObj.content);
26502
- }
26503
- return;
26502
+ if (typeof result.data === "string") {
26503
+ console.log(result.data);
26504
+ } else {
26505
+ console.log(JSON.stringify(result.data, null, 2));
26504
26506
  }
26505
- console.log(`
26506
- \u2705 [${activeProfile.toUpperCase()}] Operation '${operationId}' executed successfully (Status ${result.statusCode}):`);
26507
- console.log(JSON.stringify(result.data, null, 2));
26508
- console.log(`
26509
- Audit ID: ${result.auditId}${result.idempotencyKey ? ` | Idempotency Key: ${result.idempotencyKey}` : ""}`);
26507
+ console.log("");
26510
26508
  return;
26511
26509
  }
26512
26510
  if (result.status === "error") {
26513
26511
  console.error(`
26514
- \u274C [${activeProfile.toUpperCase()}] Execution Error (Status ${result.statusCode}):`);
26515
- console.error(` ${result.error}`);
26516
- if (result.requiredScopes && result.requiredScopes.length > 0) {
26517
- console.error(` Required scope(s): ${result.requiredScopes.join(", ")}`);
26512
+ \u274C Execution failed: ${result.error}`);
26513
+ if (result.errorDetail) {
26514
+ console.error(`Detail:`, JSON.stringify(result.errorDetail, null, 2));
26518
26515
  }
26516
+ console.error("");
26519
26517
  process.exitCode = 1;
26520
26518
  }
26521
26519
  });
@@ -26559,10 +26557,27 @@ async function promptHidden(questionText) {
26559
26557
  }
26560
26558
  return promise;
26561
26559
  }
26562
- function registerAuthCommands(program2, keychain2) {
26563
- const auth = program2.command("auth").description("Manage credentials and target environments");
26564
- auth.command("login").description("Securely store an admin API key into local encrypted vault").option("-k, --key <apiKey>", "Admin API key (warning: passing in argv may be stored in shell history)").option("-p, --profile <profile>", "Target profile (default: active profile)").action(async (options) => {
26565
- let key = options.key;
26560
+ function registerAuthCommands(program, keychain) {
26561
+ const auth = program.command("auth").description("Manage credentials, target environments, and API keys").action(async () => {
26562
+ const status = await keychain.getStatus();
26563
+ console.log(`
26564
+ \u{1F510} akadmin Auth [Profile: ${status.activeProfile.toUpperCase()}]
26565
+ `);
26566
+ console.log(` Base URL: ${status.baseUrl}`);
26567
+ console.log(` API Key: ${status.hasApiKey ? `Configured (${status.maskedKey})` : "\u274C Not Set"}`);
26568
+ console.log(` Session Cookie: ${status.hasSessionCookie ? "Configured" : "\u274C Not Set"}
26569
+ `);
26570
+ const enteredKey = await promptHidden("Enter Admin API Key (ck_live_...) to store: ");
26571
+ if (enteredKey && enteredKey.trim().length > 0) {
26572
+ await keychain.setApiKey(enteredKey.trim());
26573
+ console.log(`\u2705 Securely stored API key for profile '${status.activeProfile}' in OS Keychain.`);
26574
+ }
26575
+ });
26576
+ auth.command("login [apiKey]").description("Store an admin API key into OS Keychain").option("-k, --key <apiKey>", "Admin API key (ck_live_...)").option("--api-key <apiKey>", "Admin API key (ck_live_...)").option("-p, --profile <profile>", "Target profile (default: active profile)").action(async (apiKeyArg, options) => {
26577
+ const posKey = typeof apiKeyArg === "string" ? apiKeyArg : void 0;
26578
+ const optKey = options && typeof (options["key"] || options["apiKey"]) === "string" ? options["key"] || options["apiKey"] : void 0;
26579
+ const profile = options && typeof options["profile"] === "string" ? options["profile"] : void 0;
26580
+ let key = posKey || optKey;
26566
26581
  if (!key) {
26567
26582
  key = await promptHidden("Enter Admin API Key (hidden): ");
26568
26583
  }
@@ -26571,12 +26586,21 @@ function registerAuthCommands(program2, keychain2) {
26571
26586
  process.exitCode = 1;
26572
26587
  return;
26573
26588
  }
26574
- const target = options.profile || keychain2.getActiveProfile();
26575
- await keychain2.setApiKey(key, options.profile);
26576
- console.log(`\u2705 Securely stored and encrypted API key for profile '${target}'.`);
26589
+ const target = profile || keychain.getActiveProfile();
26590
+ await keychain.setApiKey(key, profile);
26591
+ console.log(`\u2705 Securely stored API key for profile '${target}' in OS Keychain.`);
26592
+ });
26593
+ auth.command("set <apiKey>").alias("key").description("Set the Admin API key directly for the active profile").option("-p, --profile <profile>", "Target profile (default: active profile)").action(async (apiKey, options) => {
26594
+ const profile = options && typeof options["profile"] === "string" ? options["profile"] : void 0;
26595
+ const target = profile || keychain.getActiveProfile();
26596
+ await keychain.setApiKey(apiKey.trim(), profile);
26597
+ console.log(`\u2705 Securely stored API key for profile '${target}' in OS Keychain.`);
26577
26598
  });
26578
- auth.command("session").description("Securely store a session cookie for session-only operations (Payouts, Grants)").option("-c, --cookie <cookie>", "Session cookie value").option("-p, --profile <profile>", "Target profile (default: active profile)").action(async (options) => {
26579
- let cookie = options.cookie;
26599
+ auth.command("session [cookie]").description("Store a session cookie for session-only operations (Payouts, Grants)").option("-c, --cookie <cookie>", "Session cookie value").option("-p, --profile <profile>", "Target profile (default: active profile)").action(async (cookieArg, options) => {
26600
+ const posCookie = typeof cookieArg === "string" ? cookieArg : void 0;
26601
+ const optCookie = options && typeof options["cookie"] === "string" ? options["cookie"] : void 0;
26602
+ const profile = options && typeof options["profile"] === "string" ? options["profile"] : void 0;
26603
+ let cookie = posCookie || optCookie;
26580
26604
  if (!cookie) {
26581
26605
  cookie = await promptHidden("Enter Session Cookie (hidden): ");
26582
26606
  }
@@ -26585,11 +26609,11 @@ function registerAuthCommands(program2, keychain2) {
26585
26609
  process.exitCode = 1;
26586
26610
  return;
26587
26611
  }
26588
- const target = options.profile || keychain2.getActiveProfile();
26589
- await keychain2.setSessionCookie(cookie, options.profile);
26590
- console.log(`\u2705 Securely stored and encrypted session cookie for profile '${target}'.`);
26612
+ const target = profile || keychain.getActiveProfile();
26613
+ await keychain.setSessionCookie(cookie, profile);
26614
+ console.log(`\u2705 Securely stored session cookie for profile '${target}' in OS Keychain.`);
26591
26615
  });
26592
- auth.command("enroll-remote").description("Enroll admin credentials securely into remote Cloudflare Worker vault via authenticated POST /vault/enroll").option("-u, --url <workerUrl>", "Cloudflare Worker URL", "https://akadmin-mcp-worker.hi-7ac.workers.dev").option("-t, --token <jwtToken>", "Operator Bearer / Access token").action(async (options) => {
26616
+ auth.command("enroll-remote").description("Enroll admin credentials securely into remote Cloudflare Worker vault via authenticated POST /vault/enroll").option("-u, --url <workerUrl>", "Cloudflare Worker URL", "https://akadmin.agentkit.best").option("-t, --token <jwtToken>", "Operator Bearer / Access token").action(async (options) => {
26593
26617
  let token = options.token;
26594
26618
  if (!token) {
26595
26619
  token = await promptHidden("Enter Operator Bearer / Access Token (hidden): ");
@@ -26629,11 +26653,11 @@ function registerAuthCommands(program2, keychain2) {
26629
26653
  }
26630
26654
  });
26631
26655
  auth.command("use <profile>").description("Set the active environment profile (production or staging)").action((profile) => {
26632
- keychain2.setActiveProfile(profile);
26656
+ keychain.setActiveProfile(profile);
26633
26657
  console.log(`\u2705 Active profile switched to '${profile}'.`);
26634
26658
  });
26635
26659
  auth.command("status").description("Display active profile and masked credential status").option("--json", "Output JSON format").action(async (options) => {
26636
- const status = await keychain2.getStatus();
26660
+ const status = await keychain.getStatus();
26637
26661
  if (options.json) {
26638
26662
  console.log(JSON.stringify(status, null, 2));
26639
26663
  return;
@@ -26643,14 +26667,14 @@ function registerAuthCommands(program2, keychain2) {
26643
26667
  console.log(` Base URL: ${status.baseUrl}`);
26644
26668
  console.log(` API Key: ${status.hasApiKey ? `Configured (${status.maskedKey})` : "\u274C Not Set"}`);
26645
26669
  console.log(` Session Cookie: ${status.hasSessionCookie ? "Configured" : "\u274C Not Set"}`);
26646
- console.log("\nTo set credentials, use `akadmin auth login` or `akadmin auth enroll-remote`.\n");
26670
+ console.log("\nTo set credentials, use `akadmin auth login` or `akadmin auth set <apiKey>`.\n");
26647
26671
  });
26648
26672
  }
26649
26673
 
26650
26674
  // src/commands/audit.ts
26651
- function registerAuditCommands(program2, keychain2) {
26652
- const auditStore = new FileAuditStore(keychain2.getConfigDir());
26653
- program2.command("audit [tail]").description("View recent audit events and mutation records").option("--limit <number>", "Number of records to show", "20").option("--json", "Output JSON format").action(async (_tail, options) => {
26675
+ function registerAuditCommands(program, keychain) {
26676
+ const auditStore = new FileAuditStore(keychain.getConfigDir());
26677
+ program.command("audit [tail]").description("View recent audit events and mutation records").option("--limit <number>", "Number of records to show", "20").option("--json", "Output JSON format").action(async (_tail, options) => {
26654
26678
  const limit = Number(options.limit) || 20;
26655
26679
  const records = await auditStore.list(limit);
26656
26680
  if (options.json) {
@@ -26677,77 +26701,142 @@ function registerAuditCommands(program2, keychain2) {
26677
26701
  }
26678
26702
 
26679
26703
  // src/commands/domain.ts
26680
- async function buildContext(keychain2, profileOverride, confirmToken) {
26681
- const activeProfile = profileOverride || keychain2.getActiveProfile();
26682
- const creds = await keychain2.getCredentials(activeProfile);
26683
- const signingSecret = await keychain2.getSigningSecret();
26684
- const nonceStore = new FileNonceStore(keychain2.getConfigDir());
26685
- const auditStore = new FileAuditStore(keychain2.getConfigDir());
26704
+ async function buildContext(program, keychain, commandOptions, confirmToken) {
26705
+ const globalOpts = program.opts();
26706
+ const activeProfile = commandOptions?.profile || globalOpts.profile || keychain.getActiveProfile();
26707
+ const apiKeyOverride = commandOptions?.apiKey || globalOpts.apiKey;
26708
+ const sessionCookieOverride = commandOptions?.sessionCookie || globalOpts.sessionCookie;
26709
+ const creds = await keychain.getCredentials(activeProfile, {
26710
+ apiKey: apiKeyOverride,
26711
+ sessionCookie: sessionCookieOverride
26712
+ });
26713
+ const signingSecret = await keychain.getSigningSecret();
26714
+ const nonceStore = new FileNonceStore(keychain.getConfigDir());
26715
+ const auditStore = new FileAuditStore(keychain.getConfigDir());
26686
26716
  return {
26687
- operatorId: "cli_operator",
26717
+ operatorId: "op_cli_curated",
26688
26718
  profile: activeProfile,
26689
26719
  apiKey: creds.apiKey,
26690
26720
  sessionCookie: creds.sessionCookie,
26691
- baseUrl: creds.baseUrl || "https://agentkit.best",
26721
+ baseUrl: creds.baseUrl,
26692
26722
  signingSecret,
26723
+ confirmToken,
26693
26724
  nonceStore,
26694
- auditStore,
26695
- confirmToken
26725
+ auditStore
26696
26726
  };
26697
26727
  }
26698
- function registerDomainCommands(program2, keychain2) {
26699
- const orders = program2.command("orders").description("Orders management workflows");
26700
- orders.command("list").description("List orders").option("-q, --query <search>", "Search keyword").option("-s, --status <status>", "Filter by status").option("--json", "Output JSON format").action(async (options) => {
26701
- const ctx = await buildContext(keychain2);
26702
- const res = await executeOperation("getOrders", { query: options.query, status: options.status }, void 0, ctx);
26703
- console.log(JSON.stringify(res, null, 2));
26728
+ function registerDomainCommands(program, keychain) {
26729
+ const orders = program.command("orders").description("Orders management workflows");
26730
+ orders.command("list").description("List orders").option("-q, --query <search>", "Search keyword").option("-s, --status <status>", "Filter by status").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").option("--json", "Output JSON format").action(async (options) => {
26731
+ const context = await buildContext(program, keychain, options);
26732
+ const params = {};
26733
+ if (options.query) params["q"] = options.query;
26734
+ if (options.status) params["status"] = options.status;
26735
+ const result = await executeOperation("getOrders", params, void 0, context);
26736
+ if (options.json) {
26737
+ console.log(JSON.stringify(result, null, 2));
26738
+ } else if (result.status === "executed") {
26739
+ console.log("\n\u{1F4E6} Orders List:\n");
26740
+ console.log(JSON.stringify(result.data, null, 2));
26741
+ console.log("");
26742
+ } else {
26743
+ console.error(`Error listing orders: ${result.error}`);
26744
+ process.exitCode = 1;
26745
+ }
26704
26746
  });
26705
- orders.command("get <orderId>").description("Get order details by ID").option("--json", "Output JSON format").action(async (orderId) => {
26706
- const ctx = await buildContext(keychain2);
26707
- const res = await executeOperation("getOrdersOrderId", { orderId }, void 0, ctx);
26708
- console.log(JSON.stringify(res, null, 2));
26747
+ orders.command("get <orderId>").description("Get order details by ID").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").option("--json", "Output JSON format").action(async (orderId, options) => {
26748
+ const context = await buildContext(program, keychain, options);
26749
+ const result = await executeOperation("getOrdersOrderId", { orderId }, void 0, context);
26750
+ if (options.json) {
26751
+ console.log(JSON.stringify(result, null, 2));
26752
+ } else if (result.status === "executed") {
26753
+ console.log(`
26754
+ \u{1F4E6} Order Details [${orderId}]:
26755
+ `);
26756
+ console.log(JSON.stringify(result.data, null, 2));
26757
+ console.log("");
26758
+ } else {
26759
+ console.error(`Error: ${result.error}`);
26760
+ process.exitCode = 1;
26761
+ }
26709
26762
  });
26710
- orders.command("refund <orderId>").description("Refund an order (Destructive \u2014 two-phase gate)").requiredOption("-a, --amount <number>", "Refund amount in cents").requiredOption("-r, --reason <string>", "Reason for refund").option("--confirm <token>", "Confirm token required in production").action(async (orderId, options) => {
26711
- const ctx = await buildContext(keychain2, void 0, options.confirm);
26712
- const res = await executeOperation(
26713
- "postOrdersOrderIdRefund",
26714
- { orderId },
26715
- { amount: Number(options.amount), reason: options.reason },
26716
- ctx
26717
- );
26718
- console.log(JSON.stringify(res, null, 2));
26763
+ orders.command("refund <orderId>").description("Refund an order (Destructive \u2014 two-phase gate)").requiredOption("-a, --amount <number>", "Refund amount in cents").requiredOption("-r, --reason <string>", "Reason for refund").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").option("--confirm <token>", "Confirm token required in production").action(async (orderId, options) => {
26764
+ const context = await buildContext(program, keychain, options, options.confirm);
26765
+ const body = { amount: Number(options.amount), reason: options.reason };
26766
+ const result = await executeOperation("postOrdersOrderIdRefund", { orderId }, body, context);
26767
+ if (result.status === "confirmation_required") {
26768
+ console.log("\n\u26A0\uFE0F CONFIRMATION REQUIRED for Refund\n");
26769
+ console.log(` Order: ${orderId}`);
26770
+ console.log(` Amount: $${(Number(options.amount) / 100).toFixed(2)}`);
26771
+ console.log(` Confirm Token: ${result.confirmToken} (Expires in ${result.expiresInSeconds}s)`);
26772
+ console.log(`
26773
+ To execute, re-run with:`);
26774
+ console.log(` akadmin orders refund ${orderId} -a ${options.amount} -r "${options.reason}" --confirm "${result.confirmToken}"
26775
+ `);
26776
+ return;
26777
+ }
26778
+ if (result.status === "executed") {
26779
+ console.log(`
26780
+ \u2705 Refund executed successfully for order ${orderId}.
26781
+ `);
26782
+ } else {
26783
+ console.error(`
26784
+ \u274C Refund failed: ${result.error}
26785
+ `);
26786
+ process.exitCode = 1;
26787
+ }
26719
26788
  });
26720
- const discounts = program2.command("discounts").description("Discounts management workflows");
26721
- discounts.command("list").description("List discount codes").action(async () => {
26722
- const ctx = await buildContext(keychain2);
26723
- const res = await executeOperation("getDiscounts", {}, void 0, ctx);
26724
- console.log(JSON.stringify(res, null, 2));
26789
+ const discounts = program.command("discounts").description("Discounts management workflows");
26790
+ discounts.command("list").description("List discount codes").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").action(async (options) => {
26791
+ const context = await buildContext(program, keychain, options);
26792
+ const result = await executeOperation("getDiscounts", {}, void 0, context);
26793
+ if (result.status === "executed") {
26794
+ console.log("\n\u{1F3F7}\uFE0F Discount Codes:\n");
26795
+ console.log(JSON.stringify(result.data, null, 2));
26796
+ } else {
26797
+ console.error(`Error: ${result.error}`);
26798
+ }
26725
26799
  });
26726
- discounts.command("create").description("Create a discount code (Destructive \u2014 two-phase gate)").requiredOption("-c, --code <string>", "Discount code").option("-p, --percent <number>", "Percent off").option("-m, --max-uses <number>", "Maximum uses").option("--confirm <token>", "Confirm token").action(async (options) => {
26727
- const ctx = await buildContext(keychain2, void 0, options.confirm);
26728
- const res = await executeOperation(
26729
- "postDiscounts",
26730
- {},
26731
- {
26732
- code: options.code,
26733
- percentOff: options.percent ? Number(options.percent) : void 0,
26734
- maxUses: options.maxUses ? Number(options.maxUses) : void 0
26735
- },
26736
- ctx
26737
- );
26738
- console.log(JSON.stringify(res, null, 2));
26800
+ discounts.command("create").description("Create a discount code (Destructive \u2014 two-phase gate)").requiredOption("-c, --code <string>", "Discount code").option("-p, --percent <number>", "Percent off").option("-m, --max-uses <number>", "Maximum uses").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").option("--confirm <token>", "Confirm token").action(async (options) => {
26801
+ const context = await buildContext(program, keychain, options, options.confirm);
26802
+ const body = {
26803
+ code: options.code,
26804
+ percentOff: options.percent ? Number(options.percent) : void 0,
26805
+ maxUses: options.maxUses ? Number(options.maxUses) : void 0
26806
+ };
26807
+ const result = await executeOperation("postDiscounts", {}, body, context);
26808
+ if (result.status === "confirmation_required") {
26809
+ console.log(`
26810
+ \u26A0\uFE0F Confirm creation of discount '${options.code}': Token ${result.confirmToken}
26811
+ `);
26812
+ } else if (result.status === "executed") {
26813
+ console.log(`
26814
+ \u2705 Created discount '${options.code}'.
26815
+ `);
26816
+ } else {
26817
+ console.error(`Error: ${result.error}`);
26818
+ process.exitCode = 1;
26819
+ }
26739
26820
  });
26740
- const payouts = program2.command("payouts").description("Payouts workflows (Session Cookie required)");
26741
- payouts.command("list").description("List payouts").action(async () => {
26742
- const ctx = await buildContext(keychain2);
26743
- const res = await executeOperation("getPayouts", {}, void 0, ctx);
26744
- console.log(JSON.stringify(res, null, 2));
26821
+ const payouts = program.command("payouts").description("Payouts workflows (Session Cookie required)");
26822
+ payouts.command("list").description("List payouts").option("-k, --api-key <key>", "Admin API key").option("--session-cookie <cookie>", "Session cookie (in-memory only)").option("--profile <profile>", "Target environment profile").action(async (options) => {
26823
+ const context = await buildContext(program, keychain, options);
26824
+ const result = await executeOperation("getPayouts", {}, void 0, context);
26825
+ if (result.status === "executed") {
26826
+ console.log("\n\u{1F4B3} Payouts:\n", JSON.stringify(result.data, null, 2));
26827
+ } else {
26828
+ console.error(`Error: ${result.error}`);
26829
+ }
26745
26830
  });
26746
- const revenue = program2.command("revenue").description("Revenue reports");
26747
- revenue.command("summary").description("Get platform revenue summary").action(async () => {
26748
- const ctx = await buildContext(keychain2);
26749
- const res = await executeOperation("getRevenue", {}, void 0, ctx);
26750
- console.log(JSON.stringify(res, null, 2));
26831
+ const revenue = program.command("revenue").description("Revenue reports");
26832
+ revenue.command("summary").description("Get platform revenue summary").option("-k, --api-key <key>", "Admin API key (in-memory only)").option("--profile <profile>", "Target environment profile").action(async (options) => {
26833
+ const context = await buildContext(program, keychain, options);
26834
+ const result = await executeOperation("getRevenueSummary", {}, void 0, context);
26835
+ if (result.status === "executed") {
26836
+ console.log("\n\u{1F4C8} Revenue Summary:\n", JSON.stringify(result.data, null, 2));
26837
+ } else {
26838
+ console.error(`Error: ${result.error}`);
26839
+ }
26751
26840
  });
26752
26841
  }
26753
26842
 
@@ -26758,42 +26847,37 @@ import os from "node:os";
26758
26847
  import path3 from "node:path";
26759
26848
  var DEFAULT_KEYCHAIN_SERVICE = "best.agentkit.akadmin";
26760
26849
  var MacOSKeychainStore = class {
26761
- constructor(service = DEFAULT_KEYCHAIN_SERVICE) {
26762
- this.service = service;
26763
- }
26764
- async getPassword(account) {
26765
- if (process.platform !== "darwin") return null;
26850
+ async getPassword(service, account) {
26766
26851
  try {
26767
26852
  const output = execFileSync(
26768
26853
  "/usr/bin/security",
26769
- ["find-generic-password", "-s", this.service, "-a", account, "-w"],
26770
- { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26854
+ ["find-generic-password", "-s", service, "-a", account, "-w"],
26855
+ { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
26771
26856
  );
26772
26857
  return output.trim() || null;
26773
26858
  } catch {
26774
26859
  return null;
26775
26860
  }
26776
26861
  }
26777
- async setPassword(account, secret) {
26778
- if (process.platform !== "darwin") return false;
26862
+ async setPassword(service, account, secret) {
26779
26863
  try {
26780
26864
  execFileSync(
26781
26865
  "/usr/bin/security",
26782
- ["add-generic-password", "-U", "-s", this.service, "-a", account, "-w", secret],
26783
- { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26866
+ ["add-generic-password", "-U", "-s", service, "-a", account, "-w", secret],
26867
+ { encoding: "utf-8", stdio: "ignore" }
26784
26868
  );
26785
26869
  return true;
26786
- } catch {
26870
+ } catch (err) {
26871
+ console.error(`Keychain write error (macOS security):`, err);
26787
26872
  return false;
26788
26873
  }
26789
26874
  }
26790
- async deletePassword(account) {
26791
- if (process.platform !== "darwin") return false;
26875
+ async deletePassword(service, account) {
26792
26876
  try {
26793
26877
  execFileSync(
26794
26878
  "/usr/bin/security",
26795
- ["delete-generic-password", "-s", this.service, "-a", account],
26796
- { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26879
+ ["delete-generic-password", "-s", service, "-a", account],
26880
+ { encoding: "utf-8", stdio: "ignore" }
26797
26881
  );
26798
26882
  return true;
26799
26883
  } catch {
@@ -26802,42 +26886,36 @@ var MacOSKeychainStore = class {
26802
26886
  }
26803
26887
  };
26804
26888
  var LinuxSecretServiceStore = class {
26805
- constructor(service = DEFAULT_KEYCHAIN_SERVICE) {
26806
- this.service = service;
26807
- }
26808
- async getPassword(account) {
26809
- if (process.platform !== "linux") return null;
26889
+ async getPassword(service, account) {
26810
26890
  try {
26811
26891
  const output = execFileSync(
26812
26892
  "secret-tool",
26813
- ["lookup", "service", this.service, "account", account],
26814
- { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26893
+ ["lookup", "service", service, "account", account],
26894
+ { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
26815
26895
  );
26816
26896
  return output.trim() || null;
26817
26897
  } catch {
26818
26898
  return null;
26819
26899
  }
26820
26900
  }
26821
- async setPassword(account, secret) {
26822
- if (process.platform !== "linux") return false;
26901
+ async setPassword(service, account, secret) {
26823
26902
  try {
26824
26903
  execFileSync(
26825
26904
  "secret-tool",
26826
- ["store", "--label", `akadmin-${account}`, "service", this.service, "account", account],
26827
- { input: secret, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26905
+ ["store", "--label", `akadmin-${account}`, "service", service, "account", account],
26906
+ { input: secret, encoding: "utf-8", stdio: ["pipe", "ignore", "ignore"] }
26828
26907
  );
26829
26908
  return true;
26830
26909
  } catch {
26831
26910
  return false;
26832
26911
  }
26833
26912
  }
26834
- async deletePassword(account) {
26835
- if (process.platform !== "linux") return false;
26913
+ async deletePassword(service, account) {
26836
26914
  try {
26837
26915
  execFileSync(
26838
26916
  "secret-tool",
26839
- ["clear", "service", this.service, "account", account],
26840
- { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }
26917
+ ["clear", "service", service, "account", account],
26918
+ { encoding: "utf-8", stdio: "ignore" }
26841
26919
  );
26842
26920
  return true;
26843
26921
  } catch {
@@ -26846,73 +26924,56 @@ var LinuxSecretServiceStore = class {
26846
26924
  }
26847
26925
  };
26848
26926
  var WindowsCredentialStore = class {
26849
- constructor(service = DEFAULT_KEYCHAIN_SERVICE) {
26850
- this.service = service;
26851
- }
26852
- toBase64(str) {
26853
- return Buffer.from(str, "utf-8").toString("base64");
26927
+ targetName(service, account) {
26928
+ return `${service}:${account}`;
26854
26929
  }
26855
- async getPassword(account) {
26856
- if (process.platform !== "win32") return null;
26930
+ async getPassword(service, account) {
26931
+ const target = this.targetName(service, account);
26932
+ const script = `
26933
+ Add-Type -AssemblyName System.Security
26934
+ $target = "${target}"
26935
+ $cred = [System.Security.Principal.WindowsIdentity]::GetCurrent()
26936
+ $cmd = "cmdkey /generic:$target"
26937
+ # Secure invocation placeholder
26938
+ `;
26857
26939
  try {
26858
- const psScript = `
26859
- Add-Type -AssemblyName System.Security
26860
- $svc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(this.service)}"))
26861
- $acc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(account)}"))
26862
- $vault = [Windows.Security.Credentials.PasswordVault, Windows.Security.Credentials, ContentType = WindowsRuntime]::new()
26863
- try {
26864
- $res = $vault.Retrieve($svc, $acc)
26865
- $res.RetrievePassword()
26866
- Write-Output $res.Password
26867
- } catch { exit 1 }
26868
- `;
26869
- const output = execFileSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", psScript], {
26870
- encoding: "utf-8",
26871
- stdio: ["pipe", "pipe", "pipe"]
26872
- });
26940
+ const output = execFileSync(
26941
+ "powershell",
26942
+ ["-NoProfile", "-NonInteractive", "-Command", `[System.Environment]::GetEnvironmentVariable("AKADMIN_WIN_SECRET_${account}")`],
26943
+ { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
26944
+ );
26873
26945
  return output.trim() || null;
26874
26946
  } catch {
26875
26947
  return null;
26876
26948
  }
26877
26949
  }
26878
- async setPassword(account, secret) {
26879
- if (process.platform !== "win32") return false;
26950
+ async setPassword(service, account, secret) {
26951
+ const target = this.targetName(service, account);
26880
26952
  try {
26953
+ const b64 = Buffer.from(secret, "utf-8").toString("base64");
26881
26954
  const psScript = `
26882
- Add-Type -AssemblyName System.Security
26883
- $svc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(this.service)}"))
26884
- $acc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(account)}"))
26885
- $sec = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(secret)}"))
26886
- $vault = [Windows.Security.Credentials.PasswordVault, Windows.Security.Credentials, ContentType = WindowsRuntime]::new()
26887
- $cred = [Windows.Security.Credentials.PasswordCredential, Windows.Security.Credentials, ContentType = WindowsRuntime]::new($svc, $acc, $sec)
26888
- $vault.Add($cred)
26955
+ $bytes = [System.Convert]::FromBase64String("${b64}")
26956
+ $secret = [System.Text.Encoding]::UTF8.GetString($bytes)
26957
+ cmdkey /generic:"${target}" /user:"${account}" /pass:$secret | Out-Null
26889
26958
  `;
26890
- execFileSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", psScript], {
26891
- encoding: "utf-8",
26892
- stdio: ["pipe", "pipe", "pipe"]
26893
- });
26959
+ execFileSync(
26960
+ "powershell",
26961
+ ["-NoProfile", "-NonInteractive", "-Command", psScript],
26962
+ { encoding: "utf-8", stdio: "ignore" }
26963
+ );
26894
26964
  return true;
26895
26965
  } catch {
26896
26966
  return false;
26897
26967
  }
26898
26968
  }
26899
- async deletePassword(account) {
26900
- if (process.platform !== "win32") return false;
26969
+ async deletePassword(service, account) {
26970
+ const target = this.targetName(service, account);
26901
26971
  try {
26902
- const psScript = `
26903
- Add-Type -AssemblyName System.Security
26904
- $svc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(this.service)}"))
26905
- $acc = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("${this.toBase64(account)}"))
26906
- $vault = [Windows.Security.Credentials.PasswordVault, Windows.Security.Credentials, ContentType = WindowsRuntime]::new()
26907
- try {
26908
- $cred = $vault.Retrieve($svc, $acc)
26909
- $vault.Remove($cred)
26910
- } catch {}
26911
- `;
26912
- execFileSync("powershell", ["-NoProfile", "-NonInteractive", "-Command", psScript], {
26913
- encoding: "utf-8",
26914
- stdio: ["pipe", "pipe", "pipe"]
26915
- });
26972
+ execFileSync(
26973
+ "cmdkey",
26974
+ [`/delete:${target}`],
26975
+ { encoding: "utf-8", stdio: "ignore" }
26976
+ );
26916
26977
  return true;
26917
26978
  } catch {
26918
26979
  return false;
@@ -26920,85 +26981,77 @@ var WindowsCredentialStore = class {
26920
26981
  }
26921
26982
  };
26922
26983
  var MemoryKeychainStore = class {
26923
- secrets = /* @__PURE__ */ new Map();
26924
- async getPassword(account) {
26925
- return this.secrets.get(account) || null;
26984
+ storage = /* @__PURE__ */ new Map();
26985
+ key(service, account) {
26986
+ return `${service}:${account}`;
26987
+ }
26988
+ async getPassword(service, account) {
26989
+ return this.storage.get(this.key(service, account)) || null;
26926
26990
  }
26927
- async setPassword(account, secret) {
26928
- this.secrets.set(account, secret);
26991
+ async setPassword(service, account, secret) {
26992
+ this.storage.set(this.key(service, account), secret);
26929
26993
  return true;
26930
26994
  }
26931
- async deletePassword(account) {
26932
- return this.secrets.delete(account);
26995
+ async deletePassword(service, account) {
26996
+ return this.storage.delete(this.key(service, account));
26933
26997
  }
26934
26998
  };
26935
26999
  function createDefaultOsKeychainStore() {
26936
- if (process.platform === "darwin") {
27000
+ const platform = process.platform;
27001
+ if (platform === "darwin") {
26937
27002
  return new MacOSKeychainStore();
26938
27003
  }
26939
- if (process.platform === "linux") {
27004
+ if (platform === "linux") {
26940
27005
  return new LinuxSecretServiceStore();
26941
27006
  }
26942
- if (process.platform === "win32") {
27007
+ if (platform === "win32") {
26943
27008
  return new WindowsCredentialStore();
26944
27009
  }
26945
27010
  return new MemoryKeychainStore();
26946
27011
  }
26947
27012
  var CliKeychain = class {
26948
- configDir;
27013
+ baseDir;
26949
27014
  configFile;
26950
27015
  keychainStore;
26951
- constructor(customDir, customStore) {
26952
- this.configDir = customDir || path3.join(os.homedir(), ".config", "akadmin");
26953
- this.configFile = path3.join(this.configDir, "config.json");
26954
- this.keychainStore = customStore || createDefaultOsKeychainStore();
27016
+ serviceName;
27017
+ constructor(customBaseDir, customKeychainStore, serviceName = DEFAULT_KEYCHAIN_SERVICE) {
27018
+ this.baseDir = customBaseDir || path3.join(os.homedir(), ".config/akadmin");
27019
+ this.configFile = path3.join(this.baseDir, "config.json");
27020
+ this.keychainStore = customKeychainStore || createDefaultOsKeychainStore();
27021
+ this.serviceName = serviceName;
27022
+ fs3.mkdirSync(this.baseDir, { recursive: true, mode: 448 });
26955
27023
  }
26956
27024
  getConfigDir() {
26957
- return this.configDir;
26958
- }
26959
- async getSigningSecret() {
26960
- const keyAccount = "akadmin:machine:signingKey";
26961
- let existingSecret = await this.keychainStore.getPassword(keyAccount);
26962
- if (!existingSecret) {
26963
- const bytes = crypto.getRandomValues(new Uint8Array(32));
26964
- existingSecret = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
26965
- const stored = await this.keychainStore.setPassword(keyAccount, existingSecret);
26966
- if (!stored) {
26967
- throw new Error(
26968
- "OS Keychain failure: Unable to persist confirmation signing secret to OS credential manager. Ensure keychain/libsecret daemon is running."
26969
- );
26970
- }
26971
- }
26972
- return `cli-signing-${existingSecret}`;
27025
+ return this.baseDir;
26973
27026
  }
26974
27027
  ensureConfig() {
26975
27028
  if (!fs3.existsSync(this.configFile)) {
26976
- const defaultConf = {
27029
+ const initialConfig = {
26977
27030
  activeProfile: "production",
26978
27031
  profiles: {
26979
27032
  production: { baseUrl: "https://agentkit.best" },
26980
27033
  staging: { baseUrl: "https://staging.agentkit.best" }
26981
27034
  }
26982
27035
  };
26983
- fs3.mkdirSync(this.configDir, { recursive: true, mode: 448 });
26984
- fs3.writeFileSync(this.configFile, JSON.stringify(defaultConf, null, 2), {
26985
- mode: 384
26986
- });
26987
- return defaultConf;
27036
+ this.saveConfig(initialConfig);
27037
+ return initialConfig;
26988
27038
  }
26989
27039
  try {
26990
- return JSON.parse(fs3.readFileSync(this.configFile, "utf-8"));
27040
+ const raw = fs3.readFileSync(this.configFile, "utf-8");
27041
+ return JSON.parse(raw);
26991
27042
  } catch {
26992
27043
  return {
26993
27044
  activeProfile: "production",
26994
- profiles: {}
27045
+ profiles: {
27046
+ production: { baseUrl: "https://agentkit.best" }
27047
+ }
26995
27048
  };
26996
27049
  }
26997
27050
  }
26998
27051
  saveConfig(config) {
26999
- fs3.mkdirSync(this.configDir, { recursive: true, mode: 448 });
27000
27052
  fs3.writeFileSync(this.configFile, JSON.stringify(config, null, 2), {
27001
- mode: 384
27053
+ mode: 384,
27054
+ encoding: "utf-8"
27002
27055
  });
27003
27056
  }
27004
27057
  getActiveProfile() {
@@ -27017,20 +27070,20 @@ var CliKeychain = class {
27017
27070
  }
27018
27071
  this.saveConfig(config);
27019
27072
  }
27020
- async getCredentials(profile) {
27073
+ async getCredentials(profile, overrides) {
27021
27074
  const targetProfile = profile || this.getActiveProfile();
27022
27075
  const config = this.ensureConfig();
27023
27076
  const profileMeta = config.profiles[targetProfile] || { baseUrl: "https://agentkit.best" };
27024
27077
  const envApiKey = process.env["AKADMIN_API_KEY"] || process.env["AGENTKIT_ADMIN_KEY"];
27025
27078
  const envSession = process.env["AKADMIN_SESSION_COOKIE"];
27026
27079
  const envBaseUrl = process.env["AKADMIN_BASE_URL"];
27027
- let apiKey = envApiKey;
27028
- let sessionCookie = envSession;
27080
+ let apiKey = overrides?.apiKey?.trim() || envApiKey;
27081
+ let sessionCookie = overrides?.sessionCookie?.trim() || envSession;
27029
27082
  if (!apiKey) {
27030
- apiKey = await this.keychainStore.getPassword(`akadmin:${targetProfile}:apiKey`) || void 0;
27083
+ apiKey = await this.keychainStore.getPassword(this.serviceName, `apiKey:${targetProfile}`) || void 0;
27031
27084
  }
27032
27085
  if (!sessionCookie) {
27033
- sessionCookie = await this.keychainStore.getPassword(`akadmin:${targetProfile}:sessionCookie`) || void 0;
27086
+ sessionCookie = await this.keychainStore.getPassword(this.serviceName, `sessionCookie:${targetProfile}`) || void 0;
27034
27087
  }
27035
27088
  return {
27036
27089
  apiKey,
@@ -27046,7 +27099,7 @@ var CliKeychain = class {
27046
27099
  baseUrl: targetProfile === "production" ? "https://agentkit.best" : "https://staging.agentkit.best"
27047
27100
  };
27048
27101
  }
27049
- const stored = await this.keychainStore.setPassword(`akadmin:${targetProfile}:apiKey`, apiKey);
27102
+ const stored = await this.keychainStore.setPassword(this.serviceName, `apiKey:${targetProfile}`, apiKey);
27050
27103
  if (!stored) {
27051
27104
  throw new Error(
27052
27105
  `OS Keychain failure: Unable to store secret in ${process.platform} credential manager. Ensure keychain/libsecret daemon is available.`
@@ -27063,42 +27116,80 @@ var CliKeychain = class {
27063
27116
  baseUrl: targetProfile === "production" ? "https://agentkit.best" : "https://staging.agentkit.best"
27064
27117
  };
27065
27118
  }
27066
- const stored = await this.keychainStore.setPassword(`akadmin:${targetProfile}:sessionCookie`, sessionCookie);
27119
+ const stored = await this.keychainStore.setPassword(this.serviceName, `sessionCookie:${targetProfile}`, sessionCookie);
27067
27120
  if (!stored) {
27068
27121
  throw new Error(
27069
- `OS Keychain failure: Unable to store session cookie in ${process.platform} credential manager. Ensure keychain/libsecret daemon is available.`
27122
+ `OS Keychain failure: Unable to store session cookie in ${process.platform} credential manager.`
27070
27123
  );
27071
27124
  }
27072
27125
  config.profiles[targetProfile].hasSessionCookie = true;
27073
27126
  this.saveConfig(config);
27074
27127
  }
27128
+ async getSigningSecret() {
27129
+ const account = "signing-secret";
27130
+ let secret = await this.keychainStore.getPassword(this.serviceName, account);
27131
+ if (!secret) {
27132
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
27133
+ const newSecret = `cli-signing-${Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
27134
+ const saved = await this.keychainStore.setPassword(this.serviceName, account, newSecret);
27135
+ if (!saved) {
27136
+ throw new Error("Unable to initialize CLI signing secret in OS Keychain");
27137
+ }
27138
+ secret = newSecret;
27139
+ }
27140
+ return secret;
27141
+ }
27075
27142
  async getStatus() {
27076
27143
  const profile = this.getActiveProfile();
27144
+ const config = this.ensureConfig();
27145
+ const profileMeta = config.profiles[profile] || { baseUrl: "https://agentkit.best" };
27077
27146
  const creds = await this.getCredentials(profile);
27078
27147
  return {
27079
27148
  activeProfile: profile,
27080
27149
  hasApiKey: Boolean(creds.apiKey),
27081
27150
  maskedKey: creds.apiKey ? maskApiKey(creds.apiKey) : void 0,
27082
27151
  hasSessionCookie: Boolean(creds.sessionCookie),
27083
- baseUrl: creds.baseUrl || "https://agentkit.best"
27152
+ baseUrl: creds.baseUrl || profileMeta.baseUrl
27084
27153
  };
27085
27154
  }
27086
27155
  };
27087
27156
 
27088
27157
  // src/index.ts
27089
- var keychain = new CliKeychain();
27090
- var program = new Command();
27091
- program.name("akadmin").description("Operator CLI for AgentKit.best admin platform (124 operations, 17 domains)").version("0.1.0");
27092
- registerDiscoverCommands(program);
27093
- registerRawCommand(program, keychain);
27094
- registerAuthCommands(program, keychain);
27095
- registerAuditCommands(program, keychain);
27096
- registerDomainCommands(program, keychain);
27097
- if (process.argv.length <= 2) {
27098
- const profile = keychain.getActiveProfile();
27099
- console.log(`
27158
+ function createCliProgram(keychain) {
27159
+ const program = new Command();
27160
+ program.name("akadmin").description("Operator CLI for AgentKit.best admin platform (124 operations, 17 domains)").version("0.1.2").option("--api-key <key>", "Admin API key for this command (overrides keychain, in-memory only)").option("--session-cookie <cookie>", "Session cookie for this command (overrides keychain, in-memory only)").option("--profile <profile>", "Target environment profile (production or staging)");
27161
+ registerDiscoverCommands(program);
27162
+ registerRawCommand(program, keychain);
27163
+ registerAuthCommands(program, keychain);
27164
+ registerAuditCommands(program, keychain);
27165
+ registerDomainCommands(program, keychain);
27166
+ return program;
27167
+ }
27168
+ function isMainModule() {
27169
+ if (!process.argv[1]) return false;
27170
+ try {
27171
+ const currentFilePath = fs4.realpathSync(fileURLToPath(import.meta.url));
27172
+ const invokedPath = fs4.realpathSync(process.argv[1]);
27173
+ return currentFilePath === invokedPath;
27174
+ } catch {
27175
+ return false;
27176
+ }
27177
+ }
27178
+ if (isMainModule()) {
27179
+ const keychain = new CliKeychain();
27180
+ const program = createCliProgram(keychain);
27181
+ if (process.argv.length <= 2) {
27182
+ const profile = keychain.getActiveProfile();
27183
+ console.log(`
27100
27184
  \u{1F6E1}\uFE0F akadmin \u2014 AgentKit Operator Tooling [Profile: ${profile.toUpperCase()}]`);
27101
- console.log("Run `akadmin --help` to view commands or `akadmin discover` to explore available domains.\n");
27185
+ console.log("Run `akadmin --help` to view commands or `akadmin discover` to explore available domains.\n");
27186
+ }
27187
+ program.parseAsync(process.argv).catch((err) => {
27188
+ console.error("CLI Error:", err instanceof Error ? err.message : String(err));
27189
+ process.exitCode = 1;
27190
+ });
27102
27191
  }
27103
- program.parse(process.argv);
27192
+ export {
27193
+ createCliProgram
27194
+ };
27104
27195
  //# sourceMappingURL=index.js.map