maritime-cli 0.1.1 → 0.2.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/api.d.ts CHANGED
@@ -15,5 +15,10 @@ export interface CliAuthResponse {
15
15
  user: CliUser;
16
16
  }
17
17
  export declare function getApiUrl(): string;
18
+ export declare function requireAuth(): string;
18
19
  export declare function postJson<T>(path: string, body: JsonRecord): Promise<T>;
20
+ export declare function authGet<T>(path: string): Promise<T>;
21
+ export declare function authPost<T>(path: string, body?: JsonRecord): Promise<T>;
22
+ export declare function authPut<T>(path: string, body?: JsonRecord): Promise<T>;
23
+ export declare function authDelete<T = JsonRecord>(path: string): Promise<T>;
19
24
  export {};
package/dist/api.js CHANGED
@@ -1,3 +1,5 @@
1
+ import chalk from 'chalk';
2
+ import { config } from './config.js';
1
3
  export class CliHttpError extends Error {
2
4
  status;
3
5
  detail;
@@ -8,10 +10,20 @@ export class CliHttpError extends Error {
8
10
  }
9
11
  }
10
12
  export function getApiUrl() {
11
- return (process.env.MARITIME_API_URL ||
13
+ const stored = config.get('apiUrl');
14
+ return (stored ||
15
+ process.env.MARITIME_API_URL ||
12
16
  process.env.NEXT_PUBLIC_API_URL ||
13
17
  'https://api.maritime.sh').replace(/\/+$/, '');
14
18
  }
19
+ export function requireAuth() {
20
+ const token = config.get('token');
21
+ if (!token) {
22
+ console.log(chalk.red('Not logged in.') + ' Run `maritime login` first.');
23
+ process.exit(1);
24
+ }
25
+ return token;
26
+ }
15
27
  async function parseJson(response) {
16
28
  const text = await response.text();
17
29
  if (!text) {
@@ -24,16 +36,61 @@ async function parseJson(response) {
24
36
  throw new CliHttpError(response.status, `Invalid JSON response from ${response.url}`);
25
37
  }
26
38
  }
39
+ async function handleResponse(response) {
40
+ const payload = await parseJson(response);
41
+ if (!response.ok) {
42
+ const detail = typeof payload.detail === 'string'
43
+ ? payload.detail
44
+ : `Request failed with status ${response.status}`;
45
+ throw new CliHttpError(response.status, detail);
46
+ }
47
+ return payload;
48
+ }
27
49
  export async function postJson(path, body) {
28
50
  const response = await fetch(`${getApiUrl()}${path}`, {
29
51
  method: 'POST',
30
52
  headers: { 'Content-Type': 'application/json' },
31
53
  body: JSON.stringify(body),
32
54
  });
33
- const payload = await parseJson(response);
34
- if (!response.ok) {
35
- const detail = typeof payload.detail === 'string' ? payload.detail : `Request failed with status ${response.status}`;
36
- throw new CliHttpError(response.status, detail);
37
- }
38
- return payload;
55
+ return handleResponse(response);
56
+ }
57
+ function authHeaders(token) {
58
+ return {
59
+ Authorization: `Bearer ${token}`,
60
+ 'Content-Type': 'application/json',
61
+ };
62
+ }
63
+ export async function authGet(path) {
64
+ const token = requireAuth();
65
+ const response = await fetch(`${getApiUrl()}${path}`, {
66
+ method: 'GET',
67
+ headers: authHeaders(token),
68
+ });
69
+ return handleResponse(response);
70
+ }
71
+ export async function authPost(path, body = {}) {
72
+ const token = requireAuth();
73
+ const response = await fetch(`${getApiUrl()}${path}`, {
74
+ method: 'POST',
75
+ headers: authHeaders(token),
76
+ body: JSON.stringify(body),
77
+ });
78
+ return handleResponse(response);
79
+ }
80
+ export async function authPut(path, body = {}) {
81
+ const token = requireAuth();
82
+ const response = await fetch(`${getApiUrl()}${path}`, {
83
+ method: 'PUT',
84
+ headers: authHeaders(token),
85
+ body: JSON.stringify(body),
86
+ });
87
+ return handleResponse(response);
88
+ }
89
+ export async function authDelete(path) {
90
+ const token = requireAuth();
91
+ const response = await fetch(`${getApiUrl()}${path}`, {
92
+ method: 'DELETE',
93
+ headers: authHeaders(token),
94
+ });
95
+ return handleResponse(response);
39
96
  }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const createCommand: Command;
@@ -0,0 +1,82 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authGet, authPost, CliHttpError } from '../api.js';
5
+ import { promptForValue } from '../prompt.js';
6
+ function parseEnvPairs(pairs) {
7
+ return pairs.map((pair) => {
8
+ const eqIdx = pair.indexOf('=');
9
+ if (eqIdx <= 0) {
10
+ console.log(chalk.red('Error:') + ` Invalid env var format: "${pair}". Use KEY=value.`);
11
+ process.exit(1);
12
+ }
13
+ return {
14
+ key: pair.slice(0, eqIdx),
15
+ value: pair.slice(eqIdx + 1),
16
+ isSecret: true,
17
+ };
18
+ });
19
+ }
20
+ export const createCommand = new Command('create')
21
+ .description('Create a new agent')
22
+ .option('-n, --name <name>', 'Agent name')
23
+ .option('-t, --template <template>', 'Template ID')
24
+ .option('--framework <framework>', 'Framework (default: custom)')
25
+ .option('--tier <tier>', 'Tier (smart, extended, always_on)')
26
+ .option('-e, --env <pairs...>', 'Environment variables (KEY=value)')
27
+ .action(async (opts) => {
28
+ let name = opts.name;
29
+ let templateId = opts.template;
30
+ // Interactive mode if no name given
31
+ if (!name) {
32
+ name = await promptForValue('Agent name');
33
+ if (!name) {
34
+ console.log(chalk.red('Error:') + ' Agent name is required.');
35
+ process.exit(1);
36
+ }
37
+ }
38
+ // If no template specified interactively, show available templates
39
+ if (!templateId && !opts.framework) {
40
+ try {
41
+ const templates = await authGet('/api/templates');
42
+ if (templates.length > 0) {
43
+ console.log(chalk.dim('\nAvailable templates:'));
44
+ templates.forEach((t, i) => {
45
+ console.log(` ${chalk.bold(String(i + 1))}. ${t.name} (${t.framework})${t.description ? ' — ' + t.description : ''}`);
46
+ });
47
+ console.log();
48
+ const choice = await promptForValue('Template number (or press Enter to skip)');
49
+ const idx = parseInt(choice, 10);
50
+ if (idx >= 1 && idx <= templates.length) {
51
+ templateId = templates[idx - 1].id;
52
+ }
53
+ }
54
+ }
55
+ catch {
56
+ // Templates fetch failed; continue without template
57
+ }
58
+ }
59
+ const body = { name };
60
+ if (templateId)
61
+ body.templateId = templateId;
62
+ if (opts.framework)
63
+ body.framework = opts.framework;
64
+ if (opts.tier)
65
+ body.tier = opts.tier;
66
+ if (opts.env)
67
+ body.initialEnvVars = parseEnvPairs(opts.env);
68
+ const spinner = ora(`Creating agent ${chalk.bold(name)}...`).start();
69
+ try {
70
+ const agent = await authPost('/api/agents', body);
71
+ spinner.succeed(chalk.green('Created ') + chalk.bold(agent.name) + chalk.dim(` (${agent.id})`));
72
+ console.log(chalk.dim(` Framework: ${agent.framework} | Tier: ${agent.tier} | Status: ${agent.status}`));
73
+ }
74
+ catch (error) {
75
+ spinner.fail('Failed to create agent');
76
+ if (error instanceof CliHttpError) {
77
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
78
+ process.exit(1);
79
+ }
80
+ throw error;
81
+ }
82
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const deleteCommand: Command;
@@ -0,0 +1,33 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authDelete, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ import { promptForValue } from '../prompt.js';
7
+ export const deleteCommand = new Command('delete')
8
+ .description('Delete an agent')
9
+ .argument('<agent>', 'Agent name or ID')
10
+ .option('-y, --yes', 'Skip confirmation')
11
+ .action(async (agentArg, opts) => {
12
+ const agent = await resolveAgent(agentArg);
13
+ if (!opts.yes) {
14
+ const confirm = await promptForValue(`Type "${agent.name}" to confirm deletion`);
15
+ if (confirm !== agent.name) {
16
+ console.log(chalk.yellow('Cancelled.'));
17
+ return;
18
+ }
19
+ }
20
+ const spinner = ora(`Deleting ${chalk.bold(agent.name)}...`).start();
21
+ try {
22
+ await authDelete(`/api/agents/${agent.id}`);
23
+ spinner.succeed(chalk.green('Deleted ') + chalk.bold(agent.name));
24
+ }
25
+ catch (error) {
26
+ spinner.fail('Failed to delete agent');
27
+ if (error instanceof CliHttpError) {
28
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
29
+ process.exit(1);
30
+ }
31
+ throw error;
32
+ }
33
+ });
@@ -1,38 +1,40 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
- import { readFileSync, existsSync } from 'fs';
4
+ import { authPost, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
5
6
  export const deployCommand = new Command('deploy')
6
- .description('Deploy an agent from maritime.toml')
7
- .option('-c, --config <path>', 'Path to maritime.toml', './maritime.toml')
8
- .option('--force', 'Force redeploy')
9
- .option('--no-wait', 'Do not wait for deployment to complete')
10
- .action(async (opts) => {
11
- // Check for config file
12
- if (!existsSync(opts.config)) {
13
- console.log(chalk.red('Error:') + ` ${opts.config} not found`);
14
- console.log(chalk.dim('Run `maritime init` to create one, or specify --config'));
15
- process.exit(1);
7
+ .description('Deploy an agent')
8
+ .argument('<agent>', 'Agent name or ID')
9
+ .option('--source <source>', 'Deploy source (github, docker, template)', 'template')
10
+ .option('--repo <url>', 'GitHub repository URL')
11
+ .option('--image <name>', 'Docker image name')
12
+ .option('--branch <branch>', 'Git branch')
13
+ .action(async (agentArg, opts) => {
14
+ const agent = await resolveAgent(agentArg);
15
+ const body = {
16
+ agentId: agent.id,
17
+ source: opts.source,
18
+ };
19
+ if (opts.repo)
20
+ body.repoUrl = opts.repo;
21
+ if (opts.image)
22
+ body.imageName = opts.image;
23
+ if (opts.branch)
24
+ body.branch = opts.branch;
25
+ const spinner = ora(`Deploying ${chalk.bold(agent.name)}...`).start();
26
+ try {
27
+ const deployment = await authPost('/api/deploy', body);
28
+ spinner.succeed(chalk.green('Deployment started for ') + chalk.bold(agent.name));
29
+ console.log(chalk.dim(` Deployment ID: ${deployment.id}`));
30
+ console.log(chalk.dim(` Status: ${deployment.status}`));
31
+ }
32
+ catch (error) {
33
+ spinner.fail('Deployment failed');
34
+ if (error instanceof CliHttpError) {
35
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
36
+ process.exit(1);
37
+ }
38
+ throw error;
16
39
  }
17
- const configContent = readFileSync(opts.config, 'utf-8');
18
- // Simple TOML parsing for name and framework
19
- const nameMatch = configContent.match(/name\s*=\s*"([^"]+)"/);
20
- const frameworkMatch = configContent.match(/framework\s*=\s*"([^"]+)"/);
21
- const tierMatch = configContent.match(/tier\s*=\s*"([^"]+)"/);
22
- const name = nameMatch?.[1] || 'unnamed-agent';
23
- const framework = frameworkMatch?.[1] || 'custom';
24
- const tier = tierMatch?.[1] || 'smart';
25
- const tierPrice = { smart: '$1/mo', extended: '$5/mo', always_on: '$10/mo' };
26
- console.log(chalk.hex('#8B5CF6')('\n Maritime') + chalk.dim(' Deploy\n'));
27
- const spinner = ora(`Deploying ${chalk.bold(name)} (${framework})...`).start();
28
- // Simulate deployment steps
29
- await new Promise((r) => setTimeout(r, 1000));
30
- spinner.text = 'Building container...';
31
- await new Promise((r) => setTimeout(r, 1500));
32
- spinner.text = 'Pushing image...';
33
- await new Promise((r) => setTimeout(r, 1000));
34
- spinner.text = 'Starting agent...';
35
- await new Promise((r) => setTimeout(r, 800));
36
- spinner.succeed(chalk.green('Agent deployed at ') + chalk.bold(`maritime.sh/${name}`));
37
- console.log(chalk.dim(` Tier: ${tier} (${tierPrice[tier] || '$1/mo'}) | Status: sleeping\n`));
38
40
  });
@@ -1,37 +1,84 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
+ import { authGet, authPost, authDelete, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
4
6
  export const envCommand = new Command('env')
5
7
  .description('Manage environment variables');
8
+ envCommand
9
+ .command('list <agent>')
10
+ .description('List environment variables')
11
+ .action(async (agentArg) => {
12
+ const agent = await resolveAgent(agentArg);
13
+ try {
14
+ const vars = await authGet(`/api/agents/${agent.id}/env`);
15
+ if (vars.length === 0) {
16
+ console.log(chalk.dim(`\nNo environment variables set for ${chalk.bold(agent.name)}.`));
17
+ return;
18
+ }
19
+ console.log(chalk.dim(`\nEnvironment variables for ${chalk.bold(agent.name)}:\n`));
20
+ for (const v of vars) {
21
+ const display = v.is_secret ? chalk.dim('\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022') : v.value;
22
+ console.log(` ${chalk.bold(v.key.padEnd(24))} = ${display}`);
23
+ }
24
+ console.log();
25
+ }
26
+ catch (error) {
27
+ if (error instanceof CliHttpError) {
28
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
29
+ process.exit(1);
30
+ }
31
+ throw error;
32
+ }
33
+ });
6
34
  envCommand
7
35
  .command('set <agent> <pair>')
8
36
  .description('Set an environment variable (KEY=value)')
9
- .action(async (agent, pair) => {
10
- const [key, ...valueParts] = pair.split('=');
11
- const value = valueParts.join('=');
12
- if (!key || !value) {
37
+ .option('-s, --secret', 'Mark as secret (default)', true)
38
+ .option('--no-secret', 'Mark as non-secret')
39
+ .action(async (agentArg, pair, opts) => {
40
+ const eqIdx = pair.indexOf('=');
41
+ if (eqIdx <= 0) {
13
42
  console.log(chalk.red('Error:') + ' Format must be KEY=value');
14
43
  process.exit(1);
15
44
  }
16
- const spinner = ora(`Setting ${key} for ${agent}...`).start();
17
- await new Promise((r) => setTimeout(r, 800));
18
- spinner.succeed(`Set ${chalk.bold(key)} for ${chalk.bold(agent)}`);
19
- });
20
- envCommand
21
- .command('list <agent>')
22
- .description('List environment variables')
23
- .action(async (agent) => {
24
- console.log(chalk.dim(`\nEnvironment variables for ${chalk.bold(agent)}:\n`));
25
- console.log(` ${chalk.bold('OPENAI_API_KEY')} = ${chalk.dim('••••••••')}`);
26
- console.log(` ${chalk.bold('WEBHOOK_URL')} = https://hooks.slack.com/...`);
27
- console.log(` ${chalk.bold('MAX_TOKENS')} = 4096`);
28
- console.log();
45
+ const key = pair.slice(0, eqIdx);
46
+ const value = pair.slice(eqIdx + 1);
47
+ const agent = await resolveAgent(agentArg);
48
+ const spinner = ora(`Setting ${key} for ${agent.name}...`).start();
49
+ try {
50
+ await authPost(`/api/agents/${agent.id}/env`, {
51
+ key,
52
+ value,
53
+ is_secret: opts.secret,
54
+ });
55
+ spinner.succeed(`Set ${chalk.bold(key)} for ${chalk.bold(agent.name)}`);
56
+ }
57
+ catch (error) {
58
+ spinner.fail(`Failed to set ${key}`);
59
+ if (error instanceof CliHttpError) {
60
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
61
+ process.exit(1);
62
+ }
63
+ throw error;
64
+ }
29
65
  });
30
66
  envCommand
31
67
  .command('remove <agent> <key>')
32
68
  .description('Remove an environment variable')
33
- .action(async (agent, key) => {
34
- const spinner = ora(`Removing ${key} from ${agent}...`).start();
35
- await new Promise((r) => setTimeout(r, 600));
36
- spinner.succeed(`Removed ${chalk.bold(key)} from ${chalk.bold(agent)}`);
69
+ .action(async (agentArg, key) => {
70
+ const agent = await resolveAgent(agentArg);
71
+ const spinner = ora(`Removing ${key} from ${agent.name}...`).start();
72
+ try {
73
+ await authDelete(`/api/agents/${agent.id}/env/${encodeURIComponent(key)}`);
74
+ spinner.succeed(`Removed ${chalk.bold(key)} from ${chalk.bold(agent.name)}`);
75
+ }
76
+ catch (error) {
77
+ spinner.fail(`Failed to remove ${key}`);
78
+ if (error instanceof CliHttpError) {
79
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
80
+ process.exit(1);
81
+ }
82
+ throw error;
83
+ }
37
84
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const listCommand: Command;
@@ -0,0 +1,47 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { authGet, CliHttpError } from '../api.js';
4
+ const statusColors = {
5
+ active: chalk.green,
6
+ sleeping: chalk.blue,
7
+ deploying: chalk.yellow,
8
+ error: chalk.red,
9
+ stopped: chalk.gray,
10
+ };
11
+ export const listCommand = new Command('list')
12
+ .alias('ls')
13
+ .description('List your agents')
14
+ .action(async () => {
15
+ try {
16
+ const agents = await authGet('/api/agents');
17
+ if (agents.length === 0) {
18
+ console.log(chalk.yellow('No agents found.') + ' Run `maritime create` to create one.');
19
+ return;
20
+ }
21
+ console.log('\n ' +
22
+ chalk.dim('NAME'.padEnd(24)) +
23
+ chalk.dim('STATUS'.padEnd(12)) +
24
+ chalk.dim('FRAMEWORK'.padEnd(14)) +
25
+ chalk.dim('TIER'.padEnd(12)) +
26
+ chalk.dim('CREATED'));
27
+ console.log(chalk.dim(' ' + '\u2500'.repeat(74)));
28
+ for (const a of agents) {
29
+ const colorFn = statusColors[a.status] || chalk.white;
30
+ const created = a.createdAt ? new Date(a.createdAt).toLocaleDateString() : '';
31
+ console.log(' ' +
32
+ chalk.bold(a.name.padEnd(24)) +
33
+ colorFn(a.status.padEnd(12)) +
34
+ a.framework.padEnd(14) +
35
+ a.tier.padEnd(12) +
36
+ chalk.dim(created));
37
+ }
38
+ console.log();
39
+ }
40
+ catch (error) {
41
+ if (error instanceof CliHttpError) {
42
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
43
+ process.exit(1);
44
+ }
45
+ throw error;
46
+ }
47
+ });
@@ -1,39 +1,115 @@
1
+ import http from 'node:http';
2
+ import crypto from 'node:crypto';
1
3
  import { Command } from 'commander';
2
4
  import chalk from 'chalk';
3
5
  import ora from 'ora';
6
+ import open from 'open';
4
7
  import { config } from '../config.js';
5
- import { CliHttpError, postJson } from '../api.js';
8
+ import { CliHttpError, getApiUrl, postJson } from '../api.js';
6
9
  import { promptForPassword, promptForValue } from '../prompt.js';
10
+ const APP_URL = process.env.MARITIME_APP_URL || 'https://maritime.sh';
11
+ const TIMEOUT_MS = 120_000;
12
+ function browserLogin() {
13
+ return new Promise((resolve, reject) => {
14
+ const state = crypto.randomBytes(16).toString('hex');
15
+ const server = http.createServer((req, res) => {
16
+ const url = new URL(req.url || '/', `http://localhost`);
17
+ if (url.pathname !== '/callback') {
18
+ res.writeHead(404);
19
+ res.end();
20
+ return;
21
+ }
22
+ const token = url.searchParams.get('token');
23
+ const returnedState = url.searchParams.get('state');
24
+ if (returnedState !== state || !token) {
25
+ res.writeHead(400, { 'Content-Type': 'text/html' });
26
+ res.end('<html><body><h2>Authentication failed.</h2><p>State mismatch or missing token. Please try again.</p></body></html>');
27
+ cleanup(new Error('State mismatch or missing token'));
28
+ return;
29
+ }
30
+ res.writeHead(200, { 'Content-Type': 'text/html' });
31
+ res.end('<html><body><h2>Authenticated!</h2><p>You can close this tab and return to the terminal.</p></body></html>');
32
+ cleanup(null, token);
33
+ });
34
+ const timer = setTimeout(() => {
35
+ cleanup(new Error('Login timed out. Try `maritime login --email <email> --password <password>` instead.'));
36
+ }, TIMEOUT_MS);
37
+ function cleanup(err, token) {
38
+ clearTimeout(timer);
39
+ server.close();
40
+ if (err)
41
+ reject(err);
42
+ else
43
+ resolve(token);
44
+ }
45
+ server.listen(0, '127.0.0.1', () => {
46
+ const addr = server.address();
47
+ if (!addr || typeof addr === 'string') {
48
+ cleanup(new Error('Failed to start local server'));
49
+ return;
50
+ }
51
+ const port = addr.port;
52
+ const loginUrl = `${APP_URL}/cli/auth?port=${port}&state=${state}`;
53
+ open(loginUrl).catch(() => {
54
+ // If open fails, print URL for manual use
55
+ console.log(chalk.yellow('\nCould not open browser. Visit this URL manually:'));
56
+ console.log(chalk.bold(loginUrl) + '\n');
57
+ });
58
+ });
59
+ });
60
+ }
7
61
  export const loginCommand = new Command('login')
8
- .description('Authenticate with Maritime using email and password')
9
- .option('-e, --email <email>', 'Email address')
10
- .option('-p, --password <password>', 'Password')
62
+ .description('Authenticate with Maritime')
63
+ .option('-e, --email <email>', 'Email address (for non-interactive login)')
64
+ .option('-p, --password <password>', 'Password (for non-interactive login)')
11
65
  .action(async (opts) => {
12
- const email = await promptForValue('Email', opts.email);
13
- const password = await promptForPassword(opts.password);
14
- if (!email || !password) {
15
- console.log(chalk.red('Error:') + ' email and password are required');
16
- process.exit(1);
66
+ // If email/password flags provided, use direct auth
67
+ if (opts.email || opts.password) {
68
+ const email = await promptForValue('Email', opts.email);
69
+ const password = await promptForPassword(opts.password);
70
+ if (!email || !password) {
71
+ console.log(chalk.red('Error:') + ' email and password are required');
72
+ process.exit(1);
73
+ }
74
+ const spinner = ora('Authenticating...').start();
75
+ try {
76
+ const auth = await postJson('/api/auth/cli-login', {
77
+ email,
78
+ password,
79
+ });
80
+ config.set('token', auth.token);
81
+ config.set('user', auth.user.email);
82
+ config.set('userId', auth.user.id);
83
+ config.set('apiUrl', getApiUrl());
84
+ spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(auth.user.email));
85
+ }
86
+ catch (error) {
87
+ spinner.fail('Authentication failed');
88
+ if (error instanceof CliHttpError) {
89
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
90
+ process.exit(error.status === 401 ? 2 : 1);
91
+ }
92
+ throw error;
93
+ }
94
+ return;
17
95
  }
18
- const spinner = ora('Authenticating...').start();
96
+ // Default: browser-based login
97
+ const spinner = ora('Opening browser for authentication...').start();
19
98
  try {
20
- const auth = await postJson('/api/auth/cli-login', {
21
- email,
22
- password,
23
- });
24
- config.set('token', auth.token);
25
- config.set('user', auth.user.email);
26
- config.set('userId', auth.user.id);
27
- config.set('apiUrl', process.env.MARITIME_API_URL || 'https://api.maritime.sh');
28
- spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(auth.user.email));
29
- console.log(chalk.dim('\nToken saved. You can now deploy agents.'));
99
+ const token = await browserLogin();
100
+ // Decode JWT payload to extract user info (no verification needed)
101
+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
102
+ config.set('token', token);
103
+ config.set('user', payload.email);
104
+ config.set('userId', payload.sub || payload.id);
105
+ config.set('apiUrl', getApiUrl());
106
+ spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(payload.email));
30
107
  }
31
108
  catch (error) {
32
109
  spinner.fail('Authentication failed');
33
- if (error instanceof CliHttpError) {
34
- console.log(chalk.red('Error:') + ` ${error.detail}`);
35
- process.exit(error.status === 401 ? 2 : 1);
110
+ if (error instanceof Error) {
111
+ console.log(chalk.red('Error:') + ` ${error.message}`);
36
112
  }
37
- throw error;
113
+ process.exit(1);
38
114
  }
39
115
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const logoutCommand: Command;
@@ -0,0 +1,12 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { config } from '../config.js';
4
+ export const logoutCommand = new Command('logout')
5
+ .description('Log out of Maritime')
6
+ .action(() => {
7
+ config.delete('token');
8
+ config.delete('user');
9
+ config.delete('userId');
10
+ config.delete('apiUrl');
11
+ console.log(chalk.green('Logged out.'));
12
+ });
@@ -1,5 +1,8 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
+ import { authGet, CliHttpError } from '../api.js';
4
+ import { resolveAgent } from '../resolve.js';
5
+ const VALID_LEVELS = ['info', 'warn', 'error', 'debug'];
3
6
  const levelColors = {
4
7
  info: chalk.blue,
5
8
  warn: chalk.yellow,
@@ -7,35 +10,47 @@ const levelColors = {
7
10
  debug: chalk.gray,
8
11
  };
9
12
  export const logsCommand = new Command('logs')
10
- .description('Stream logs from an agent')
11
- .argument('<agent>', 'Agent name')
12
- .option('-f, --follow', 'Follow log output')
13
- .option('-n, --lines <num>', 'Number of lines', '20')
14
- .option('--level <level>', 'Filter by level')
15
- .action(async (agent, opts) => {
16
- console.log(chalk.dim(`Streaming logs for ${chalk.bold(agent)}...\n`));
17
- const mockLogs = [
18
- { time: '14:32:01', level: 'info', msg: 'Agent started successfully' },
19
- { time: '14:32:02', level: 'info', msg: 'Received webhook invocation from /api/support' },
20
- { time: '14:32:03', level: 'debug', msg: 'Processing ticket #4521 - category: billing' },
21
- { time: '14:32:04', level: 'info', msg: 'Generated response (342 tokens)' },
22
- { time: '14:32:05', level: 'warn', msg: 'Rate limit approaching: 847/1000 invocations' },
23
- { time: '14:32:08', level: 'error', msg: 'Failed to connect to external API: timeout' },
24
- { time: '14:32:09', level: 'info', msg: 'Retrying API connection (attempt 2/3)' },
25
- { time: '14:32:10', level: 'info', msg: 'API connection restored' },
26
- ];
27
- const filtered = opts.level
28
- ? mockLogs.filter((l) => l.level === opts.level)
29
- : mockLogs;
30
- for (const log of filtered) {
31
- const colorFn = levelColors[log.level] || chalk.white;
32
- const levelStr = colorFn(log.level.toUpperCase().padEnd(5));
33
- console.log(`${chalk.dim(log.time)} ${levelStr} ${log.msg}`);
34
- if (opts.follow) {
35
- await new Promise((r) => setTimeout(r, 300));
13
+ .description('View logs from an agent')
14
+ .argument('<agent>', 'Agent name or ID')
15
+ .option('-n, --lines <num>', 'Number of lines', '50')
16
+ .option('--level <level>', 'Filter by level (info, warn, error, debug)')
17
+ .action(async (agentArg, opts) => {
18
+ // Validate --level
19
+ if (opts.level && !VALID_LEVELS.includes(opts.level)) {
20
+ console.log(chalk.red('Error:') + ' --level must be one of info, warn, error, debug');
21
+ process.exit(1);
22
+ }
23
+ // Validate --lines
24
+ const lines = parseInt(opts.lines, 10);
25
+ if (isNaN(lines) || lines <= 0) {
26
+ console.log(chalk.red('Error:') + ' --lines must be a positive integer');
27
+ process.exit(1);
28
+ }
29
+ const agent = await resolveAgent(agentArg);
30
+ let path = `/api/agents/${agent.id}/logs?limit=${lines}`;
31
+ if (opts.level)
32
+ path += `&level=${opts.level}`;
33
+ try {
34
+ const entries = await authGet(path);
35
+ if (entries.length === 0) {
36
+ console.log(chalk.dim('No logs found.'));
37
+ return;
38
+ }
39
+ for (const entry of entries) {
40
+ const ts = entry.timestamp
41
+ ? chalk.dim(new Date(entry.timestamp).toLocaleTimeString())
42
+ : chalk.dim('--:--:--');
43
+ const level = entry.level || 'info';
44
+ const colorFn = levelColors[level] || chalk.white;
45
+ const levelStr = colorFn(level.toUpperCase().padEnd(5));
46
+ console.log(`${ts} ${levelStr} ${entry.message}`);
36
47
  }
37
48
  }
38
- if (opts.follow) {
39
- console.log(chalk.dim('\nWaiting for new logs... (Ctrl+C to exit)'));
49
+ catch (error) {
50
+ if (error instanceof CliHttpError) {
51
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
52
+ process.exit(1);
53
+ }
54
+ throw error;
40
55
  }
41
56
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const restartCommand: Command;
@@ -0,0 +1,24 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authPost, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ export const restartCommand = new Command('restart')
7
+ .description('Restart an agent')
8
+ .argument('<agent>', 'Agent name or ID')
9
+ .action(async (agentArg) => {
10
+ const agent = await resolveAgent(agentArg);
11
+ const spinner = ora(`Restarting ${chalk.bold(agent.name)}...`).start();
12
+ try {
13
+ await authPost(`/api/agents/${agent.id}/restart`);
14
+ spinner.succeed(chalk.green('Restarted ') + chalk.bold(agent.name));
15
+ }
16
+ catch (error) {
17
+ spinner.fail('Failed to restart agent');
18
+ if (error instanceof CliHttpError) {
19
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
20
+ process.exit(1);
21
+ }
22
+ throw error;
23
+ }
24
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const startCommand: Command;
@@ -0,0 +1,24 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authPost, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ export const startCommand = new Command('start')
7
+ .description('Start an agent')
8
+ .argument('<agent>', 'Agent name or ID')
9
+ .action(async (agentArg) => {
10
+ const agent = await resolveAgent(agentArg);
11
+ const spinner = ora(`Starting ${chalk.bold(agent.name)}...`).start();
12
+ try {
13
+ await authPost(`/api/agents/${agent.id}/start`);
14
+ spinner.succeed(chalk.green('Started ') + chalk.bold(agent.name));
15
+ }
16
+ catch (error) {
17
+ spinner.fail('Failed to start agent');
18
+ if (error instanceof CliHttpError) {
19
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
20
+ process.exit(1);
21
+ }
22
+ throw error;
23
+ }
24
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const stopCommand: Command;
@@ -0,0 +1,24 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authPost, CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ export const stopCommand = new Command('stop')
7
+ .description('Stop an agent')
8
+ .argument('<agent>', 'Agent name or ID')
9
+ .action(async (agentArg) => {
10
+ const agent = await resolveAgent(agentArg);
11
+ const spinner = ora(`Stopping ${chalk.bold(agent.name)}...`).start();
12
+ try {
13
+ await authPost(`/api/agents/${agent.id}/stop`);
14
+ spinner.succeed(chalk.green('Stopped ') + chalk.bold(agent.name));
15
+ }
16
+ catch (error) {
17
+ spinner.fail('Failed to stop agent');
18
+ if (error instanceof CliHttpError) {
19
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
20
+ process.exit(1);
21
+ }
22
+ throw error;
23
+ }
24
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const templatesCommand: Command;
@@ -0,0 +1,48 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { CliHttpError, getApiUrl } from '../api.js';
4
+ export const templatesCommand = new Command('templates')
5
+ .description('List available agent templates')
6
+ .action(async () => {
7
+ try {
8
+ const response = await fetch(`${getApiUrl()}/api/templates`, {
9
+ method: 'GET',
10
+ headers: { 'Content-Type': 'application/json' },
11
+ });
12
+ if (!response.ok) {
13
+ const text = await response.text();
14
+ let detail = `Request failed with status ${response.status}`;
15
+ try {
16
+ const json = JSON.parse(text);
17
+ if (typeof json.detail === 'string')
18
+ detail = json.detail;
19
+ }
20
+ catch { /* ignore */ }
21
+ throw new CliHttpError(response.status, detail);
22
+ }
23
+ const templates = await response.json();
24
+ if (templates.length === 0) {
25
+ console.log(chalk.dim('No templates available.'));
26
+ return;
27
+ }
28
+ console.log('\n ' +
29
+ chalk.dim('NAME'.padEnd(20)) +
30
+ chalk.dim('FRAMEWORK'.padEnd(14)) +
31
+ chalk.dim('DESCRIPTION'));
32
+ console.log(chalk.dim(' ' + '\u2500'.repeat(60)));
33
+ for (const t of templates) {
34
+ console.log(' ' +
35
+ chalk.bold(t.name.padEnd(20)) +
36
+ t.framework.padEnd(14) +
37
+ chalk.dim(t.description || ''));
38
+ }
39
+ console.log();
40
+ }
41
+ catch (error) {
42
+ if (error instanceof CliHttpError) {
43
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
44
+ process.exit(1);
45
+ }
46
+ throw error;
47
+ }
48
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const whoamiCommand: Command;
@@ -0,0 +1,34 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { config } from '../config.js';
4
+ export const whoamiCommand = new Command('whoami')
5
+ .description('Show current authenticated user')
6
+ .action(() => {
7
+ const token = config.get('token');
8
+ if (!token) {
9
+ console.log(chalk.yellow('Not logged in.') + ' Run `maritime login` first.');
10
+ process.exit(1);
11
+ }
12
+ try {
13
+ const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
14
+ const email = payload.email || 'unknown';
15
+ const exp = payload.exp ? new Date(payload.exp * 1000) : null;
16
+ console.log(chalk.bold('Email: ') + email);
17
+ if (payload.name) {
18
+ console.log(chalk.bold('Name: ') + payload.name);
19
+ }
20
+ if (exp) {
21
+ const now = Date.now();
22
+ if (exp.getTime() < now) {
23
+ console.log(chalk.bold('Token: ') + chalk.red('expired'));
24
+ }
25
+ else {
26
+ console.log(chalk.bold('Token: ') + chalk.green('valid') + chalk.dim(` (expires ${exp.toLocaleDateString()})`));
27
+ }
28
+ }
29
+ }
30
+ catch {
31
+ console.log(chalk.red('Error:') + ' Failed to decode token. Try logging in again.');
32
+ process.exit(1);
33
+ }
34
+ });
package/dist/index.js CHANGED
@@ -1,21 +1,46 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { dirname, join } from 'node:path';
2
5
  import { Command } from 'commander';
3
6
  import chalk from 'chalk';
4
7
  import { loginCommand } from './commands/login.js';
5
8
  import { signupCommand } from './commands/signup.js';
9
+ import { logoutCommand } from './commands/logout.js';
10
+ import { whoamiCommand } from './commands/whoami.js';
11
+ import { createCommand } from './commands/create.js';
6
12
  import { deployCommand } from './commands/deploy.js';
13
+ import { listCommand } from './commands/list.js';
14
+ import { startCommand } from './commands/start.js';
15
+ import { stopCommand } from './commands/stop.js';
16
+ import { restartCommand } from './commands/restart.js';
17
+ import { deleteCommand } from './commands/delete.js';
7
18
  import { logsCommand } from './commands/logs.js';
8
19
  import { envCommand } from './commands/env.js';
9
- import { statusCommand } from './commands/status.js';
20
+ import { templatesCommand } from './commands/templates.js';
21
+ const __dirname = dirname(fileURLToPath(import.meta.url));
22
+ const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
10
23
  const program = new Command();
11
24
  program
12
25
  .name('maritime')
13
- .description(chalk.hex('#8B5CF6')('Maritime') + ' — Deploy AI agents for $1/month')
14
- .version('0.1.0');
15
- program.addCommand(signupCommand);
26
+ .description(chalk.hex('#8B5CF6')('Maritime') + ' \u2014 Deploy AI agents from your terminal')
27
+ .version(pkg.version);
28
+ // Auth
16
29
  program.addCommand(loginCommand);
30
+ program.addCommand(signupCommand);
31
+ program.addCommand(logoutCommand);
32
+ program.addCommand(whoamiCommand);
33
+ // Agent management
34
+ program.addCommand(createCommand);
35
+ program.addCommand(listCommand);
17
36
  program.addCommand(deployCommand);
37
+ program.addCommand(startCommand);
38
+ program.addCommand(stopCommand);
39
+ program.addCommand(restartCommand);
40
+ program.addCommand(deleteCommand);
41
+ // Observability
18
42
  program.addCommand(logsCommand);
19
43
  program.addCommand(envCommand);
20
- program.addCommand(statusCommand);
44
+ // Discovery
45
+ program.addCommand(templatesCommand);
21
46
  program.parse();
@@ -0,0 +1,10 @@
1
+ interface AgentSummary {
2
+ id: string;
3
+ name: string;
4
+ status: string;
5
+ framework: string;
6
+ tier?: string;
7
+ created_at?: string;
8
+ }
9
+ export declare function resolveAgent(nameOrId: string): Promise<AgentSummary>;
10
+ export {};
@@ -0,0 +1,19 @@
1
+ import chalk from 'chalk';
2
+ import { authGet } from './api.js';
3
+ export async function resolveAgent(nameOrId) {
4
+ const agents = await authGet('/api/agents');
5
+ // Exact name match
6
+ const byName = agents.filter((a) => a.name === nameOrId);
7
+ if (byName.length === 1)
8
+ return byName[0];
9
+ // ID prefix match
10
+ const byId = agents.filter((a) => a.id.startsWith(nameOrId));
11
+ if (byId.length === 1)
12
+ return byId[0];
13
+ if (byName.length > 1 || byId.length > 1) {
14
+ console.log(chalk.red('Error:') + ` Ambiguous agent "${nameOrId}". Multiple matches found.`);
15
+ process.exit(1);
16
+ }
17
+ console.log(chalk.red('Error:') + ` Agent "${nameOrId}" not found.`);
18
+ process.exit(1);
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maritime-cli",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Maritime CLI - Deploy AI agents from your terminal",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,6 +22,9 @@
22
22
  "files": [
23
23
  "dist"
24
24
  ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
25
28
  "scripts": {
26
29
  "build": "tsc && chmod +x dist/index.js",
27
30
  "dev": "tsx src/index.ts",
@@ -31,6 +34,7 @@
31
34
  "chalk": "^5.3.0",
32
35
  "commander": "^12.0.0",
33
36
  "conf": "^12.0.0",
37
+ "open": "^10.0.0",
34
38
  "ora": "^8.0.0"
35
39
  },
36
40
  "devDependencies": {
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export declare const statusCommand: Command;
@@ -1,35 +0,0 @@
1
- import { Command } from 'commander';
2
- import chalk from 'chalk';
3
- export const statusCommand = new Command('status')
4
- .description('Check agent status')
5
- .argument('[agent]', 'Agent name (optional)')
6
- .action(async (agent) => {
7
- console.log(chalk.hex('#8B5CF6')('\n Maritime') + chalk.dim(' Status\n'));
8
- const agents = [
9
- { name: 'support-bot', status: 'active', tier: 'smart', invocations: '847' },
10
- { name: 'data-pipeline', status: 'sleeping', tier: 'extended', invocations: '3,421' },
11
- { name: 'code-reviewer', status: 'sleeping', tier: 'extended', invocations: '1,205' },
12
- { name: 'slack-assistant', status: 'active', tier: 'always_on', invocations: '12,847' },
13
- ];
14
- const filtered = agent ? agents.filter((a) => a.name === agent) : agents;
15
- if (filtered.length === 0) {
16
- console.log(chalk.yellow('No agents found'));
17
- return;
18
- }
19
- // Table header
20
- console.log(' ' +
21
- chalk.dim('NAME'.padEnd(20)) +
22
- chalk.dim('STATUS'.padEnd(12)) +
23
- chalk.dim('TIER'.padEnd(12)) +
24
- chalk.dim('INVOCATIONS'));
25
- console.log(chalk.dim(' ' + '─'.repeat(56)));
26
- for (const a of filtered) {
27
- const statusColor = a.status === 'active' ? chalk.green : a.status === 'error' ? chalk.red : chalk.blue;
28
- console.log(' ' +
29
- chalk.bold(a.name.padEnd(20)) +
30
- statusColor(a.status.padEnd(12)) +
31
- a.tier.padEnd(12) +
32
- a.invocations);
33
- }
34
- console.log();
35
- });