UNPKG

axiom

Version:

Axiom AI SDK provides - an API to wrap your AI calls with observability instrumentation. - offline evals

441 lines (431 loc) 13.6 kB
#!/usr/bin/env node import { extractOverrides, loadEvalCommand } from "./chunk-3EAYJ4JJ.js"; import { OAuth, fetchOrganizations, getActiveProfile, getGlobalConfigPath, loadGlobalConfig, saveGlobalConfig, setupGlobalAuth, startCallbackServer, verifyToken, waitForCallback } from "./chunk-KX7Z2MF4.js"; import "./chunk-PZCJLQFO.js"; import { AxiomCLIError } from "./chunk-S65FSMB3.js"; import "./chunk-X2LH7XLM.js"; import { init_esm_shims } from "./chunk-4VNFFUM5.js"; // src/bin.ts init_esm_shims(); import { Command as Command2 } from "commander"; // src/cli/commands/auth.command.ts init_esm_shims(); // src/cli/commands/auth-login.command.ts init_esm_shims(); var BASE_HOSTNAME = "axiom.co"; var getApiUrl = (hostname) => { return `https://api.${hostname}`; }; var getOauthUrl = (hostname) => { return `https://login.${hostname}`; }; async function promptSelect(message, choices) { console.log(` ${message}`); choices.forEach((choice, index) => { console.log(` ${index + 1}. ${choice.name}`); }); const readline = await import("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => { const askQuestion = () => { rl.question(` Select (1-${choices.length}): `, (answer) => { const index = parseInt(answer.trim(), 10) - 1; if (index >= 0 && index < choices.length) { rl.close(); resolve(choices[index].value); } else { console.log("Invalid selection. Please try again."); askQuestion(); } }); }; askQuestion(); }); } async function promptInput(message, defaultValue) { const readline = await import("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => { const prompt = defaultValue ? `${message} (${defaultValue}): ` : `${message}: `; rl.question(prompt, (answer) => { rl.close(); resolve(answer.trim() || defaultValue || ""); }); }); } async function openBrowser(url) { const { default: open } = await import("open"); await open(url); } async function loginCommand(hostname) { try { console.log("\u{1F510} Starting authentication flow...\n"); const codeVerifier = OAuth.generateCodeVerifier(); const codeChallenge = OAuth.generateCodeChallenge(codeVerifier); const state = OAuth.generateState(); const oauth = new OAuth(getOauthUrl(hostname)); const { server, url: redirectUri } = await startCallbackServer(); console.log(`\u2713 Started local callback server on ${redirectUri} `); const authUrl = oauth.buildAuthUrl({ redirectUri, state, codeChallenge }); console.log("Opening browser for authentication..."); console.log(`If the browser doesn't open, visit: ${authUrl} `); try { await openBrowser(authUrl); } catch { console.log("Could not open browser automatically.\n"); } console.log("Waiting for authentication..."); const { code } = await waitForCallback(server, state); console.log("\u2713 Authentication successful, exchanging code for token...\n"); const accessToken = await oauth.exchangeCodeForToken({ code, redirectUri, codeVerifier }); console.log("\u2713 Token received, fetching organizations...\n"); const organizations = await fetchOrganizations(accessToken, getApiUrl(hostname)); if (organizations.length === 0) { throw new AxiomCLIError("No organizations found for this account"); } let selectedOrgId; if (organizations.length === 1) { selectedOrgId = organizations[0].id; console.log(`\u2713 Using organization: ${organizations[0].name} `); } else { selectedOrgId = await promptSelect( "Select an organization:", organizations.map((org) => ({ name: `${org.name} (${org.id})`, value: org.id })) ); } const selectedOrg = organizations.find((org) => org.id === selectedOrgId); const defaultAlias = selectedOrg.slug || selectedOrg.name.toLowerCase().replace(/\s+/g, "-"); const alias = await promptInput("Enter profile alias", defaultAlias); console.log("\n\u2713 Verifying credentials...\n"); const isValid = await verifyToken(accessToken, selectedOrgId, getApiUrl(hostname)); if (!isValid) { throw new AxiomCLIError("Token verification failed"); } const config = await loadGlobalConfig(); config.active_profile = alias; config.profiles[alias] = { url: getApiUrl(hostname), token: accessToken, org_id: selectedOrgId }; await saveGlobalConfig(config); console.log(`\u2713 Successfully logged in as ${alias}`); console.log(`\u2713 Configuration saved to ${getGlobalConfigPath()} `); } catch (error) { if (error instanceof AxiomCLIError) { throw error; } throw new AxiomCLIError(`Login failed: ${error.message}`); } } function loadAuthLoginCommand(auth, root) { [auth, root].forEach((program2) => { program2.command("login").description("Authenticate with Axiom").option("--hostname <hostname>", "Axiom hostname (default: axiom.co)").action(async (options) => { try { await loginCommand(options.hostname ?? BASE_HOSTNAME); } catch (error) { if (error instanceof AxiomCLIError) { console.error(` \u274C Error: ${error.message} `); } else { console.error(` \u274C Unexpected error: ${error.message} `); } process.exit(1); } }); }); } // src/cli/commands/auth-logout.command.ts init_esm_shims(); async function logoutCommand(alias) { const config = await loadGlobalConfig(); const profileToRemove = alias || config.active_profile; if (!profileToRemove) { throw new AxiomCLIError("No active profile. Use --alias to specify which profile to remove."); } if (!config.profiles[profileToRemove]) { throw new AxiomCLIError(`Profile "${profileToRemove}" not found`); } delete config.profiles[profileToRemove]; if (config.active_profile === profileToRemove) { const remainingProfiles = Object.keys(config.profiles); config.active_profile = remainingProfiles.length > 0 ? remainingProfiles[0] : void 0; } await saveGlobalConfig(config); console.log(`\u2713 Logged out from ${profileToRemove}`); if (config.active_profile) { console.log(`\u2713 Active profile is now: ${config.active_profile}`); } else { console.log('No active profiles remaining. Run "axiom auth login" to authenticate.'); } } function loadAuthLogoutCommand(auth, root) { [auth, root].forEach((program2) => { program2.command("logout").description("Remove authentication credentials").option("-a, --alias <alias>", "Profile alias to remove").action(async (options) => { try { await logoutCommand(options.alias); } catch (error) { if (error instanceof AxiomCLIError) { console.error(` \u274C Error: ${error.message} `); } else { console.error(` \u274C Unexpected error: ${error.message} `); } process.exit(1); } }); }); } // src/cli/commands/auth-status.command.ts init_esm_shims(); async function statusCommand() { const config = await loadGlobalConfig(); if (Object.keys(config.profiles).length === 0) { console.log("No authenticated profiles found."); console.log('Run "axiom auth login" to authenticate.'); return; } console.log("\nAuthentication Status:\n"); for (const [alias, profile] of Object.entries(config.profiles)) { const isActive = config.active_profile === alias; const marker = isActive ? "\u2192" : " "; try { const isValid = await verifyToken(profile.token, profile.org_id, profile.url); const status = isValid ? "\u2713" : "\u2717"; const statusText = isValid ? "Valid" : "Invalid"; console.log(`${marker} ${status} ${alias}`); console.log(` URL: ${profile.url}`); console.log(` Org ID: ${profile.org_id}`); console.log(` Status: ${statusText}`); if (isActive) { console.log(` (Active)`); } console.log(); } catch (error) { console.log(`${marker} \u2717 ${alias}`); console.log(` URL: ${profile.url}`); console.log(` Org ID: ${profile.org_id}`); console.log(` Status: Error - ${error.message}`); if (isActive) { console.log(` (Active)`); } console.log(); } } const activeProfile = getActiveProfile(config); if (process.env.AXIOM_TOKEN) { console.log("Note: Using AXIOM_TOKEN environment variable (overrides config file)\n"); } else if (activeProfile && config.active_profile) { console.log(`Active profile: ${config.active_profile} `); } } function loadAuthStatusCommand(auth, program2) { [auth, program2].forEach((program3) => { program3.command("status").description("Check authentication status for all profiles").action(async () => { try { await statusCommand(); } catch (error) { if (error instanceof AxiomCLIError) { console.error(` \u274C Error: ${error.message} `); } else { console.error(` \u274C Unexpected error: ${error.message} `); } process.exit(1); } }); }); } // src/cli/commands/auth-switch.command.ts init_esm_shims(); async function promptSelect2(message, choices) { console.log(` ${message}`); choices.forEach((choice, index) => { console.log(` ${index + 1}. ${choice.name}`); }); const readline = await import("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => { const askQuestion = () => { rl.question(` Select (1-${choices.length}): `, (answer) => { const index = parseInt(answer.trim(), 10) - 1; if (index >= 0 && index < choices.length) { rl.close(); resolve(choices[index].value); } else { console.log("Invalid selection. Please try again."); askQuestion(); } }); }; askQuestion(); }); } async function switchCommand(alias) { const config = await loadGlobalConfig(); if (Object.keys(config.profiles).length === 0) { throw new AxiomCLIError( 'No authenticated profiles found. Run "axiom auth login" to authenticate.' ); } let selectedAlias; if (alias) { if (!config.profiles[alias]) { throw new AxiomCLIError(`Profile "${alias}" not found`); } selectedAlias = alias; } else { const profiles = Object.entries(config.profiles).map(([alias2, profile]) => ({ name: `${alias2} (${profile.url})`, value: alias2 })); if (profiles.length === 1) { selectedAlias = profiles[0].value; console.log(`\u2713 Using profile: ${selectedAlias} `); } else { selectedAlias = await promptSelect2("Select a profile to switch to:", profiles); } } if (config.active_profile === selectedAlias) { console.log(`\u2713 Profile "${selectedAlias}" is already active `); return; } config.active_profile = selectedAlias; await saveGlobalConfig(config); console.log(`\u2713 Switched to profile: ${selectedAlias} `); } function loadAuthSwitchCommand(auth, root) { [auth, root].forEach((program2) => { program2.command("switch").description("Switch to a different profile").argument("[alias]", "Profile alias to switch to").action(async (alias) => { try { await switchCommand(alias); } catch (error) { if (error instanceof AxiomCLIError) { console.error(` \u274C Error: ${error.message} `); } else { console.error(` \u274C Unexpected error: ${error.message} `); } process.exit(1); } }); }); } // src/cli/commands/auth.command.ts function loadAuthCommand(program2) { const auth = program2.command("auth").description("Manage authentication with Axiom"); loadAuthLoginCommand(auth, program2); loadAuthLogoutCommand(auth, program2); loadAuthStatusCommand(auth, program2); loadAuthSwitchCommand(auth, program2); } // src/bin.ts import pkg from "@next/env"; // src/cli/commands/version.command.ts init_esm_shims(); import { Command } from "commander"; var loadVersionCommand = (program2) => { return program2.addCommand( new Command("version").description("cli version").action(() => { console.log("0.37.0"); }) ); }; // src/bin.ts var { loadEnvConfig } = pkg; loadEnvConfig(process.cwd()); var { cleanedArgv, overrides } = extractOverrides(process.argv.slice(2)); var program = new Command2(); program.name("axiom").description("Axiom's CLI to manage your objects and run evals").version("0.37.0"); program.hook("preAction", async (_, actionCommand) => { const commandName = actionCommand.name(); const parentCommand = actionCommand.parent; const parentName = parentCommand?.name(); if (commandName === "auth" || parentName === "auth" || commandName === "version") { return; } try { await setupGlobalAuth(); } catch (error) { if (error instanceof Error) { console.error(` \u274C ${error.message} `); } else { console.error(` \u274C Unexpected error: ${String(error)} `); } process.exit(1); } }); loadAuthCommand(program); loadEvalCommand(program, overrides); loadVersionCommand(program); program.parse(["node", "axiom", ...cleanedArgv]); export { program }; //# sourceMappingURL=bin.js.map