refactor(cli): run local mode only (P1.1)
Team mode is not part of the community edition (ADR-0003), so the CLI no longer detects or switches to it. - Remove the mode detector, the --local and --team flags, the Clerk browser login (/login, /logout, /whoami) and /mode. - Remove the /admin command and its team-server REST client. - The welcome banner drops the Mode line. - The installed-REPL test starts plain `waggle` and checks that the team commands are gone.
This commit is contained in:
@@ -1,147 +0,0 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { createServer } from 'node:http';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { URL } from 'node:url';
|
||||
|
||||
const DEFAULT_CONFIG_DIR = join(homedir(), '.waggle');
|
||||
const DEFAULT_SERVER_URL = 'http://localhost:3000';
|
||||
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
||||
|
||||
interface AuthData {
|
||||
token: string;
|
||||
email: string;
|
||||
serverUrl: string;
|
||||
}
|
||||
|
||||
interface WaggleConfig {
|
||||
auth?: AuthData;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class AuthManager {
|
||||
private configDir: string;
|
||||
private configPath: string;
|
||||
|
||||
constructor(configDir?: string) {
|
||||
this.configDir = configDir ?? DEFAULT_CONFIG_DIR;
|
||||
this.configPath = join(this.configDir, 'config.json');
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
const auth = this.readAuth();
|
||||
return auth?.token ?? null;
|
||||
}
|
||||
|
||||
getEmail(): string | null {
|
||||
const auth = this.readAuth();
|
||||
return auth?.email ?? null;
|
||||
}
|
||||
|
||||
getServerUrl(): string {
|
||||
const auth = this.readAuth();
|
||||
return auth?.serverUrl ?? DEFAULT_SERVER_URL;
|
||||
}
|
||||
|
||||
isLoggedIn(): boolean {
|
||||
return this.getToken() !== null;
|
||||
}
|
||||
|
||||
saveToken(token: string, email: string): void {
|
||||
const config = this.readConfig();
|
||||
config.auth = {
|
||||
token,
|
||||
email,
|
||||
serverUrl: config.auth?.serverUrl ?? DEFAULT_SERVER_URL,
|
||||
};
|
||||
this.writeConfig(config);
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
const config = this.readConfig();
|
||||
delete config.auth;
|
||||
this.writeConfig(config);
|
||||
}
|
||||
|
||||
async loginWithBrowser(clerkUrl: string): Promise<{ token: string; email: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = createServer((req, res) => {
|
||||
if (!req.url?.startsWith('/callback')) {
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(req.url, `http://127.0.0.1`);
|
||||
const token = url.searchParams.get('token');
|
||||
const email = url.searchParams.get('email');
|
||||
|
||||
if (!token || !email) {
|
||||
res.writeHead(400, { 'Content-Type': 'text/html' });
|
||||
res.end('<html><body><h1>Login failed</h1><p>Missing token or email.</p></body></html>');
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' });
|
||||
res.end('<html><body><h1>Login successful!</h1><p>You can close this tab and return to the terminal.</p></body></html>');
|
||||
|
||||
clearTimeout(timeout);
|
||||
server.close();
|
||||
resolve({ token, email });
|
||||
});
|
||||
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
reject(new Error('Failed to start callback server'));
|
||||
return;
|
||||
}
|
||||
const port = address.port;
|
||||
const redirectUrl = `http://127.0.0.1:${port}/callback`;
|
||||
const loginUrl = `${clerkUrl}?redirect_url=${encodeURIComponent(redirectUrl)}`;
|
||||
openBrowser(loginUrl);
|
||||
});
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
server.close();
|
||||
reject(new Error('Login timed out after 5 minutes'));
|
||||
}, LOGIN_TIMEOUT_MS);
|
||||
});
|
||||
}
|
||||
|
||||
private readAuth(): AuthData | null {
|
||||
const config = this.readConfig();
|
||||
return config.auth ?? null;
|
||||
}
|
||||
|
||||
private readConfig(): WaggleConfig {
|
||||
try {
|
||||
if (!existsSync(this.configPath)) return {};
|
||||
const raw = readFileSync(this.configPath, 'utf-8');
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
return parsed as WaggleConfig;
|
||||
}
|
||||
return {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
private writeConfig(config: WaggleConfig): void {
|
||||
mkdirSync(this.configDir, { recursive: true });
|
||||
writeFileSync(this.configPath, JSON.stringify(config, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
export function openBrowser(url: string): void {
|
||||
const platform = process.platform;
|
||||
if (platform === 'win32') {
|
||||
execFile('cmd.exe', ['/c', 'start', '""', url]);
|
||||
} else if (platform === 'darwin') {
|
||||
execFile('open', [url]);
|
||||
} else {
|
||||
execFile('xdg-open', [url]);
|
||||
}
|
||||
}
|
||||
@@ -39,11 +39,6 @@ export const COMMANDS: Record<string, string> = {
|
||||
clear: '/clear — Clear conversation history',
|
||||
help: '/help — Show this help message',
|
||||
identity: '/identity — Show agent identity',
|
||||
admin: '/admin <cmd> — Admin commands (teams|jobs|cron|audit|stats)',
|
||||
login: '/login — Log in via browser (Clerk OAuth)',
|
||||
logout: '/logout — Log out and clear stored token',
|
||||
whoami: '/whoami — Show current user and mode',
|
||||
mode: '/mode — Show current mode (local/team)',
|
||||
cost: '/cost — Show token usage and estimated cost',
|
||||
plan: '/plan — Show current execution plan',
|
||||
git: '/git — Show git status for workspace',
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* Admin CLI client for Waggle server REST API.
|
||||
*
|
||||
* Provides methods to manage teams, jobs, cron schedules,
|
||||
* audit logs, and usage stats from the CLI.
|
||||
*/
|
||||
|
||||
const DEFAULT_API_BASE = 'http://localhost:3100';
|
||||
|
||||
export class AdminClient {
|
||||
private readonly apiBase: string;
|
||||
private readonly token: string;
|
||||
|
||||
constructor(apiBase?: string, token?: string) {
|
||||
this.apiBase = apiBase ?? process.env.WAGGLE_API_URL ?? DEFAULT_API_BASE;
|
||||
this.token = token ?? process.env.WAGGLE_TOKEN ?? '';
|
||||
}
|
||||
|
||||
private async request<T = unknown>(path: string): Promise<T> {
|
||||
const res = await fetch(`${this.apiBase}${path}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '');
|
||||
throw new Error(`API ${res.status}: ${body || res.statusText}`);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
/** List all teams the authenticated user has access to. */
|
||||
async listTeams(): Promise<unknown> {
|
||||
return this.request('/api/teams');
|
||||
}
|
||||
|
||||
/** List agent jobs, optionally filtered by team slug. */
|
||||
async listJobs(teamSlug: string): Promise<unknown> {
|
||||
return this.request(`/api/jobs?teamSlug=${encodeURIComponent(teamSlug)}`);
|
||||
}
|
||||
|
||||
/** List cron schedules for a team. */
|
||||
async listCron(teamSlug: string): Promise<unknown> {
|
||||
return this.request(`/api/teams/${encodeURIComponent(teamSlug)}/cron`);
|
||||
}
|
||||
|
||||
/** List audit log entries for a team. */
|
||||
async listAudit(teamSlug: string): Promise<unknown> {
|
||||
return this.request(`/api/admin/teams/${encodeURIComponent(teamSlug)}/audit`);
|
||||
}
|
||||
|
||||
/** Get usage statistics for a team. */
|
||||
async getStats(teamSlug: string): Promise<unknown> {
|
||||
return this.request(`/api/admin/teams/${encodeURIComponent(teamSlug)}/usage`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format admin data as a simple table for CLI output.
|
||||
* Takes an array of objects and prints key-value columns.
|
||||
*/
|
||||
export function formatTable(rows: Record<string, unknown>[], columns?: string[]): string {
|
||||
if (rows.length === 0) return ' (no data)';
|
||||
|
||||
const keys = columns ?? Object.keys(rows[0]);
|
||||
const widths = keys.map((k) =>
|
||||
Math.max(k.length, ...rows.map((r) => String(r[k] ?? '').length)),
|
||||
);
|
||||
|
||||
const header = keys.map((k, i) => k.padEnd(widths[i])).join(' ');
|
||||
const separator = widths.map((w) => '-'.repeat(w)).join(' ');
|
||||
const body = rows
|
||||
.map((r) => keys.map((k, i) => String(r[k] ?? '').padEnd(widths[i])).join(' '))
|
||||
.join('\n');
|
||||
|
||||
return ` ${header}\n ${separator}\n ${body}`;
|
||||
}
|
||||
@@ -14,8 +14,6 @@ Waggle CLI — interactive AI agent with persistent memory
|
||||
Usage:
|
||||
waggle Start interactive REPL
|
||||
waggle --model <name> Start with a specific model
|
||||
waggle --local Force local mode (no server)
|
||||
waggle --team Force team mode (requires login)
|
||||
waggle --help Show this help message
|
||||
|
||||
Configuration:
|
||||
@@ -25,7 +23,6 @@ Commands (inside REPL):
|
||||
/model <name> Switch model
|
||||
/models List available models
|
||||
/identity Show agent identity
|
||||
/admin <cmd> Admin commands (teams|jobs|cron|audit|stats)
|
||||
/clear Clear conversation
|
||||
/help Show commands
|
||||
/exit Quit
|
||||
@@ -45,12 +42,9 @@ if (modelIdx !== -1 && args[modelIdx + 1]) {
|
||||
model = args[modelIdx + 1];
|
||||
}
|
||||
|
||||
const local = args.includes('--local');
|
||||
const team = args.includes('--team');
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { startRepl } = await import('./repl.js');
|
||||
await startRepl({ model, local, team });
|
||||
await startRepl({ model });
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
export type WaggleMode = {
|
||||
type: 'local' | 'team' | 'error';
|
||||
warning?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export interface ModeDetectorDeps {
|
||||
hasToken: boolean;
|
||||
serverUrl: string;
|
||||
forceLocal: boolean;
|
||||
forceTeam: boolean;
|
||||
healthCheck: (serverUrl: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
export async function detectMode(deps: ModeDetectorDeps): Promise<WaggleMode> {
|
||||
// 1. --local flag → always local mode
|
||||
if (deps.forceLocal) {
|
||||
return { type: 'local' };
|
||||
}
|
||||
|
||||
// 2. --team flag + no token → error
|
||||
if (deps.forceTeam && !deps.hasToken) {
|
||||
return { type: 'error', error: 'Team mode requires login. Run: waggle login' };
|
||||
}
|
||||
|
||||
// 3. --team flag + token → team mode
|
||||
if (deps.forceTeam && deps.hasToken) {
|
||||
return { type: 'team' };
|
||||
}
|
||||
|
||||
// 4. No token → local mode
|
||||
if (!deps.hasToken) {
|
||||
return { type: 'local' };
|
||||
}
|
||||
|
||||
// 5. Token + server reachable → team mode
|
||||
const reachable = await deps.healthCheck(deps.serverUrl);
|
||||
if (reachable) {
|
||||
return { type: 'team' };
|
||||
}
|
||||
|
||||
// 6. Token + server unreachable → local mode with warning
|
||||
return { type: 'local', warning: 'Server unreachable — running in local mode.' };
|
||||
}
|
||||
|
||||
export async function checkServerHealth(serverUrl: string): Promise<boolean> {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 3000);
|
||||
const response = await fetch(`${serverUrl}/health`, { signal: controller.signal });
|
||||
clearTimeout(timeout);
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -16,14 +16,9 @@ import { createMem0MemoryStore } from '@waggle/memory-mem0';
|
||||
import { Orchestrator, ModelRouter, runAgentLoop, createSystemTools, createPlanTools, createGitTools, Workspace, ensureIdentity, loadSystemPromptWithOverrides, loadSkills, CostTracker, HookRegistry, loadHooksFromConfig, needsConfirmation } from '@waggle/agent';
|
||||
import { parseCommand, COMMANDS } from './commands.js';
|
||||
import { renderMarkdown } from './renderer.js';
|
||||
import { AdminClient, formatTable } from './commands/admin.js';
|
||||
import { AuthManager } from './auth.js';
|
||||
import { detectMode, checkServerHealth } from './mode-detector.js';
|
||||
|
||||
export interface ReplOptions {
|
||||
model?: string;
|
||||
local?: boolean;
|
||||
team?: boolean;
|
||||
}
|
||||
|
||||
export async function startRepl(options: ReplOptions = {}): Promise<void> {
|
||||
@@ -58,21 +53,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
|
||||
const hookRegistry = new HookRegistry();
|
||||
await loadHooksFromConfig(path.join(waggleHome, 'hooks.json'), hookRegistry);
|
||||
|
||||
// Detect mode
|
||||
const auth = new AuthManager();
|
||||
const modeResult = await detectMode({
|
||||
hasToken: auth.isLoggedIn(),
|
||||
serverUrl: auth.getServerUrl(),
|
||||
forceLocal: options.local ?? false,
|
||||
forceTeam: options.team ?? false,
|
||||
healthCheck: checkServerHealth,
|
||||
});
|
||||
|
||||
if (modeResult.type === 'error') {
|
||||
console.log(chalk.red(modeResult.error ?? 'Mode detection failed.'));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Get LiteLLM config from workspace
|
||||
const wsConfig = workspace.getConfig();
|
||||
const litellmUrl = wsConfig.litellmUrl ?? 'http://localhost:4000/v1';
|
||||
@@ -111,14 +91,10 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
|
||||
console.log('');
|
||||
console.log(chalk.bold.magenta(' Waggle') + chalk.dim(' — AI agent with persistent memory'));
|
||||
console.log(chalk.dim(' ─────────────────────────────────────'));
|
||||
console.log(chalk.dim(' Mode: ') + chalk.cyan(modeResult.type));
|
||||
console.log(chalk.dim(' Model: ') + chalk.cyan(currentModel));
|
||||
console.log(chalk.dim(' Memory: ') + chalk.cyan(`${frameCount} memories`));
|
||||
console.log(chalk.dim(' Store: ') + chalk.cyan(path.join(waggleHome, 'memory')));
|
||||
console.log(chalk.dim(' Workspace:') + chalk.cyan(` ${process.cwd()}`));
|
||||
if (modeResult.warning) {
|
||||
console.log(chalk.yellow(' ⚠ ' + modeResult.warning));
|
||||
}
|
||||
console.log(chalk.dim(' Type /help for commands'));
|
||||
console.log('');
|
||||
|
||||
@@ -221,40 +197,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'login': {
|
||||
try {
|
||||
const clerkUrl = process.env.CLERK_URL ?? 'https://waggle.clerk.accounts.dev/sign-in';
|
||||
console.log(chalk.dim('Opening browser for login...'));
|
||||
const { token, email } = await auth.loginWithBrowser(clerkUrl);
|
||||
auth.saveToken(token, email);
|
||||
console.log(chalk.green(`Logged in as ${email}`));
|
||||
} catch (err) {
|
||||
console.log(chalk.red(`Login failed: ${(err as Error).message}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'logout':
|
||||
auth.logout();
|
||||
console.log(chalk.dim('Logged out.'));
|
||||
break;
|
||||
|
||||
case 'whoami': {
|
||||
const email = auth.getEmail();
|
||||
console.log('');
|
||||
console.log(chalk.dim(' User: ') + (email ? chalk.cyan(email) : chalk.dim('not logged in')));
|
||||
console.log(chalk.dim(' Mode: ') + chalk.cyan(modeResult.type));
|
||||
console.log(chalk.dim(' Server: ') + chalk.cyan(auth.getServerUrl()));
|
||||
if (modeResult.warning) console.log(chalk.yellow(' ⚠ ' + modeResult.warning));
|
||||
console.log('');
|
||||
break;
|
||||
}
|
||||
|
||||
case 'mode':
|
||||
console.log(chalk.dim(`Current mode: ${modeResult.type}`));
|
||||
if (modeResult.warning) console.log(chalk.yellow(modeResult.warning));
|
||||
break;
|
||||
|
||||
case 'cost':
|
||||
console.log('');
|
||||
console.log(chalk.dim(costTracker.formatSummary()));
|
||||
@@ -283,67 +225,6 @@ export async function startRepl(options: ReplOptions = {}): Promise<void> {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'admin': {
|
||||
const adminClient = new AdminClient();
|
||||
const parts = cmd.args.split(/\s+/);
|
||||
const subCmd = parts[0] || '';
|
||||
const teamSlug = parts[1] || '';
|
||||
|
||||
if (!subCmd) {
|
||||
console.log('');
|
||||
console.log(chalk.bold('Admin commands:'));
|
||||
console.log(chalk.dim(' /admin teams — List teams'));
|
||||
console.log(chalk.dim(' /admin jobs <team-slug> — List agent jobs'));
|
||||
console.log(chalk.dim(' /admin cron <team-slug> — List cron schedules'));
|
||||
console.log(chalk.dim(' /admin audit <team-slug> — List audit log'));
|
||||
console.log(chalk.dim(' /admin stats <team-slug> — Show usage stats'));
|
||||
console.log('');
|
||||
console.log(chalk.dim(' Set WAGGLE_API_URL and WAGGLE_TOKEN env vars to connect.'));
|
||||
console.log('');
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
let result: unknown;
|
||||
switch (subCmd) {
|
||||
case 'teams':
|
||||
result = await adminClient.listTeams();
|
||||
break;
|
||||
case 'jobs':
|
||||
if (!teamSlug) { console.log(chalk.red('Usage: /admin jobs <team-slug>')); break; }
|
||||
result = await adminClient.listJobs(teamSlug);
|
||||
break;
|
||||
case 'cron':
|
||||
if (!teamSlug) { console.log(chalk.red('Usage: /admin cron <team-slug>')); break; }
|
||||
result = await adminClient.listCron(teamSlug);
|
||||
break;
|
||||
case 'audit':
|
||||
if (!teamSlug) { console.log(chalk.red('Usage: /admin audit <team-slug>')); break; }
|
||||
result = await adminClient.listAudit(teamSlug);
|
||||
break;
|
||||
case 'stats':
|
||||
if (!teamSlug) { console.log(chalk.red('Usage: /admin stats <team-slug>')); break; }
|
||||
result = await adminClient.getStats(teamSlug);
|
||||
break;
|
||||
default:
|
||||
console.log(chalk.red(`Unknown admin command: ${subCmd}`));
|
||||
console.log(chalk.dim('Type /admin for available commands.'));
|
||||
}
|
||||
if (result !== undefined) {
|
||||
console.log('');
|
||||
if (Array.isArray(result)) {
|
||||
console.log(formatTable(result as Record<string, unknown>[]));
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(chalk.red(`Admin error: ${(err as Error).message}`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
console.log(chalk.red(`Unknown command: /${cmd.name}`));
|
||||
console.log(chalk.dim('Type /help for available commands.'));
|
||||
|
||||
Reference in New Issue
Block a user