maritime-cli 0.2.1 → 1.1.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.
Files changed (52) hide show
  1. package/AGENTS.md +174 -0
  2. package/dist/api.d.ts +1 -0
  3. package/dist/api.js +130 -13
  4. package/dist/commands/blueprint.d.ts +2 -0
  5. package/dist/commands/blueprint.js +93 -0
  6. package/dist/commands/chat.d.ts +2 -0
  7. package/dist/commands/chat.js +93 -0
  8. package/dist/commands/create.js +127 -48
  9. package/dist/commands/delete.js +28 -18
  10. package/dist/commands/deploy.js +51 -9
  11. package/dist/commands/env.js +206 -43
  12. package/dist/commands/exec.d.ts +2 -0
  13. package/dist/commands/exec.js +28 -0
  14. package/dist/commands/guide.d.ts +2 -0
  15. package/dist/commands/guide.js +83 -0
  16. package/dist/commands/history.d.ts +2 -0
  17. package/dist/commands/history.js +56 -0
  18. package/dist/commands/info.d.ts +2 -0
  19. package/dist/commands/info.js +74 -0
  20. package/dist/commands/keys.d.ts +2 -0
  21. package/dist/commands/keys.js +78 -0
  22. package/dist/commands/list.js +13 -10
  23. package/dist/commands/login.js +70 -10
  24. package/dist/commands/logs.js +38 -14
  25. package/dist/commands/open.d.ts +2 -0
  26. package/dist/commands/open.js +24 -0
  27. package/dist/commands/restart.js +13 -11
  28. package/dist/commands/scale.d.ts +2 -0
  29. package/dist/commands/scale.js +30 -0
  30. package/dist/commands/sleep.d.ts +2 -0
  31. package/dist/commands/sleep.js +23 -0
  32. package/dist/commands/start.js +14 -11
  33. package/dist/commands/status.d.ts +2 -0
  34. package/dist/commands/status.js +73 -0
  35. package/dist/commands/stop.js +13 -11
  36. package/dist/commands/templates.js +11 -9
  37. package/dist/commands/triggers.d.ts +2 -0
  38. package/dist/commands/triggers.js +79 -0
  39. package/dist/commands/whoami.js +65 -24
  40. package/dist/config.js +8 -0
  41. package/dist/index.js +73 -2
  42. package/dist/interactive.d.ts +1 -0
  43. package/dist/interactive.js +68 -0
  44. package/dist/output.d.ts +61 -0
  45. package/dist/output.js +123 -0
  46. package/dist/resolve.d.ts +2 -3
  47. package/dist/resolve.js +23 -10
  48. package/dist/version-check.d.ts +10 -0
  49. package/dist/version-check.js +43 -0
  50. package/dist/websocket.d.ts +13 -0
  51. package/dist/websocket.js +55 -0
  52. package/package.json +8 -4
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const guideCommand: Command;
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, join } from 'node:path';
4
+ import { Command } from 'commander';
5
+ import { isJsonMode, outputJson } from '../output.js';
6
+ const __dirname = dirname(fileURLToPath(import.meta.url));
7
+ /**
8
+ * The machine contract an AI agent needs that isn't expressible as flags.
9
+ * Kept in sync with AGENTS.md; emitted by `guide --json` so an agent can learn
10
+ * the rules in one structured call.
11
+ */
12
+ const CONTRACT = {
13
+ auth: 'Set the MARITIME_TOKEN env var to a long-lived API key (mk_…, minted via `maritime keys create`) or a login JWT. The CLI reads it before anything else; never run interactive login in automation.',
14
+ json: 'Pass --json on every command. Success → one JSON value on stdout, stderr empty. Failure → one JSON object {ok:false,error:{code,message,status?}} on stderr, stdout empty.',
15
+ exitCodes: { '0': 'ok', '1': 'error', '2': 'auth', '3': 'not_found', '4': 'usage' },
16
+ interaction: 'Talk to a deployed agent with `maritime chat <agent> <message>` (or pipe the message via stdin). Returns the reply text (or {response} under --json). Sleeping serverless agents auto-wake.',
17
+ resources: 'create accepts per-agent overrides: --ram <mb>, --cpu <cores>, --idle <seconds> | --always-on, --disk <gb>, --max-compute <minutes>. Omitted = inherit the tier/plan.',
18
+ apiBase: 'Override the API base with MARITIME_API_URL (default https://api.maritime.sh).',
19
+ };
20
+ /* eslint-disable @typescript-eslint/no-explicit-any */
21
+ function serializeCommand(cmd) {
22
+ const args = (cmd.registeredArguments ?? cmd._args ?? []);
23
+ return {
24
+ name: cmd.name(),
25
+ aliases: typeof cmd.aliases === 'function' ? cmd.aliases() : [],
26
+ description: typeof cmd.description === 'function' ? cmd.description() : '',
27
+ arguments: args.map((a) => ({
28
+ name: typeof a.name === 'function' ? a.name() : a._name ?? String(a),
29
+ required: Boolean(a.required),
30
+ variadic: Boolean(a.variadic),
31
+ })),
32
+ options: (cmd.options ?? []).map((o) => ({
33
+ flags: o.flags,
34
+ description: o.description ?? '',
35
+ })),
36
+ subcommands: (cmd.commands ?? [])
37
+ .filter((c) => c.name() !== 'help')
38
+ .map(serializeCommand),
39
+ };
40
+ }
41
+ /* eslint-enable @typescript-eslint/no-explicit-any */
42
+ function readBundledGuide() {
43
+ // dist/commands/guide.js → package root is two levels up.
44
+ for (const rel of [['..', '..', 'AGENTS.md'], ['..', '..', '..', 'AGENTS.md']]) {
45
+ try {
46
+ return readFileSync(join(__dirname, ...rel), 'utf-8');
47
+ }
48
+ catch {
49
+ // try next candidate
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ export const guideCommand = new Command('guide')
55
+ .alias('agent-guide')
56
+ .description('Print the machine-readable usage guide for driving this CLI from code/an AI agent')
57
+ .action((_opts, command) => {
58
+ if (isJsonMode()) {
59
+ // One structured call gives an agent the entire surface + the contract.
60
+ const root = command.parent ?? command;
61
+ const program = root;
62
+ outputJson({
63
+ name: typeof program.name === 'function' ? program.name() : 'maritime',
64
+ contract: CONTRACT,
65
+ commands: (root.commands ?? [])
66
+ .filter((c) => c.name() !== 'help' && c.name() !== 'guide')
67
+ .map(serializeCommand),
68
+ });
69
+ return;
70
+ }
71
+ const md = readBundledGuide();
72
+ if (md) {
73
+ process.stdout.write(md.endsWith('\n') ? md : md + '\n');
74
+ return;
75
+ }
76
+ // Fallback if AGENTS.md wasn't shipped: print the contract essentials.
77
+ console.log('Maritime CLI — programmatic / AI-agent usage\n');
78
+ console.log(` Auth: ${CONTRACT.auth}`);
79
+ console.log(` JSON: ${CONTRACT.json}`);
80
+ console.log(` Chat: ${CONTRACT.interaction}`);
81
+ console.log(` Limits: ${CONTRACT.resources}`);
82
+ console.log('\n Run `maritime guide --json` for the full structured manifest.');
83
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const historyCommand: Command;
@@ -0,0 +1,56 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { authGet } from '../api.js';
4
+ import { resolveAgent } from '../resolve.js';
5
+ import { isJsonMode, outputJson, handleError } from '../output.js';
6
+ const statusColors = {
7
+ success: chalk.green,
8
+ completed: chalk.green,
9
+ failed: chalk.red,
10
+ pending: chalk.yellow,
11
+ running: chalk.yellow,
12
+ deploying: chalk.yellow,
13
+ };
14
+ export const historyCommand = new Command('history')
15
+ .description('Show deployment history for an agent')
16
+ .argument('<agent>', 'Agent name or ID')
17
+ .option('-n, --limit <num>', 'Number of deployments to show', '10')
18
+ .action(async (agentArg, opts) => {
19
+ try {
20
+ const agent = await resolveAgent(agentArg);
21
+ const deployments = await authGet(`/api/deploy/agent/${agent.id}`);
22
+ const limit = parseInt(opts.limit, 10) || 10;
23
+ const shown = deployments.slice(0, limit);
24
+ if (isJsonMode()) {
25
+ outputJson(shown);
26
+ return;
27
+ }
28
+ if (shown.length === 0) {
29
+ console.log(chalk.dim('No deployments found.'));
30
+ return;
31
+ }
32
+ console.log('\n ' +
33
+ chalk.dim('ID'.padEnd(14)) +
34
+ chalk.dim('STATUS'.padEnd(12)) +
35
+ chalk.dim('SHA'.padEnd(10)) +
36
+ chalk.dim('STARTED'.padEnd(22)) +
37
+ chalk.dim('COMPLETED'));
38
+ console.log(chalk.dim(' ' + '\u2500'.repeat(72)));
39
+ for (const d of shown) {
40
+ const colorFn = statusColors[d.status] || chalk.white;
41
+ const sha = d.commitSha ? d.commitSha.slice(0, 7) : chalk.dim('n/a');
42
+ const started = new Date(d.startedAt).toLocaleString();
43
+ const completed = d.completedAt ? new Date(d.completedAt).toLocaleString() : chalk.dim('—');
44
+ console.log(' ' +
45
+ chalk.dim(d.id.slice(0, 12).padEnd(14)) +
46
+ colorFn(d.status.padEnd(12)) +
47
+ String(sha).padEnd(10) +
48
+ started.padEnd(22) +
49
+ completed);
50
+ }
51
+ console.log();
52
+ }
53
+ catch (error) {
54
+ handleError(error);
55
+ }
56
+ });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const infoCommand: Command;
@@ -0,0 +1,74 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { authGet } from '../api.js';
4
+ import { resolveAgent } from '../resolve.js';
5
+ import { isJsonMode, outputJson, handleError } from '../output.js';
6
+ export const infoCommand = new Command('info')
7
+ .description('Show full details for an agent')
8
+ .argument('<agent>', 'Agent name or ID')
9
+ .action(async (agentArg) => {
10
+ try {
11
+ const summary = await resolveAgent(agentArg);
12
+ const id = summary.id;
13
+ // Fetch all data in parallel
14
+ const [agent, envVars, triggers, deployments] = await Promise.all([
15
+ authGet(`/api/agents/${id}`),
16
+ authGet(`/api/agents/${id}/env`).catch(() => []),
17
+ authGet(`/api/agents/${id}/triggers`).catch(() => []),
18
+ authGet(`/api/deploy/agent/${id}`).catch(() => []),
19
+ ]);
20
+ if (isJsonMode()) {
21
+ outputJson({ agent, envVars: envVars.length, triggers, lastDeploy: deployments[0] ?? null });
22
+ return;
23
+ }
24
+ console.log();
25
+ console.log(chalk.bold(agent.name));
26
+ if (agent.description)
27
+ console.log(chalk.dim(agent.description));
28
+ console.log(chalk.dim('─'.repeat(50)));
29
+ // Core info
30
+ const rows = [
31
+ ['ID', chalk.dim(agent.id)],
32
+ ['Status', statusColor(agent.status)],
33
+ ['Framework', agent.framework],
34
+ ['Tier', agent.tier],
35
+ ['Created', agent.createdAt ? new Date(agent.createdAt).toLocaleString() : 'n/a'],
36
+ ];
37
+ if (agent.githubRepo)
38
+ rows.push(['Repo', agent.githubRepo]);
39
+ if (agent.imageName)
40
+ rows.push(['Image', agent.imageName]);
41
+ if (agent.invocationCount !== undefined)
42
+ rows.push(['Invocations', String(agent.invocationCount)]);
43
+ rows.push(['Env vars', String(envVars.length)]);
44
+ rows.push(['Triggers', String(triggers.length)]);
45
+ for (const [label, value] of rows) {
46
+ console.log(` ${(label + ':').padEnd(16)} ${value}`);
47
+ }
48
+ // Last deployment
49
+ const last = deployments[0];
50
+ if (last) {
51
+ console.log();
52
+ console.log(chalk.bold(' Last deployment'));
53
+ console.log(` ${'Status:'.padEnd(16)} ${last.status}`);
54
+ console.log(` ${'Started:'.padEnd(16)} ${new Date(last.startedAt).toLocaleString()}`);
55
+ if (last.completedAt) {
56
+ console.log(` ${'Completed:'.padEnd(16)} ${new Date(last.completedAt).toLocaleString()}`);
57
+ }
58
+ }
59
+ console.log();
60
+ }
61
+ catch (error) {
62
+ handleError(error);
63
+ }
64
+ });
65
+ function statusColor(status) {
66
+ switch (status) {
67
+ case 'active': return chalk.green(status);
68
+ case 'sleeping': return chalk.blue(status);
69
+ case 'deploying': return chalk.yellow(status);
70
+ case 'error': return chalk.red(status);
71
+ case 'stopped': return chalk.gray(status);
72
+ default: return status;
73
+ }
74
+ }
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const keysCommand: Command;
@@ -0,0 +1,78 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { authGet, authPost, authDelete } from '../api.js';
4
+ import { isJsonMode, outputJson, outputResult, handleError } from '../output.js';
5
+ export const keysCommand = new Command('keys')
6
+ .description('Manage long-lived API keys (mk_…) for non-interactive / AI-agent access');
7
+ keysCommand
8
+ .command('create')
9
+ .description('Mint a new API key. Shown once — save it as MARITIME_TOKEN.')
10
+ .option('-n, --name <name>', 'Label for the key', 'cli-agent')
11
+ .action(async (opts) => {
12
+ try {
13
+ const created = await authPost('/api/admin/api-keys', { name: opts.name });
14
+ outputResult(created, () => {
15
+ console.log(chalk.green('Created API key ') + chalk.bold(created.name));
16
+ console.log();
17
+ console.log(' ' + chalk.bold(created.key));
18
+ console.log();
19
+ console.log(chalk.yellow(' Save this now — it will not be shown again.'));
20
+ console.log(chalk.dim(' Use it non-interactively with:'));
21
+ console.log(chalk.dim(` export MARITIME_TOKEN=${created.key}`));
22
+ });
23
+ }
24
+ catch (error) {
25
+ handleError(error);
26
+ }
27
+ });
28
+ keysCommand
29
+ .command('list')
30
+ .alias('ls')
31
+ .description('List your API keys (values are never shown again)')
32
+ .action(async () => {
33
+ try {
34
+ const keys = await authGet('/api/admin/api-keys');
35
+ if (isJsonMode()) {
36
+ outputJson(keys);
37
+ return;
38
+ }
39
+ if (keys.length === 0) {
40
+ console.log(chalk.dim('No API keys. Run `maritime keys create` to mint one.'));
41
+ return;
42
+ }
43
+ console.log('\n ' +
44
+ chalk.dim('ID'.padEnd(14)) +
45
+ chalk.dim('NAME'.padEnd(24)) +
46
+ chalk.dim('PREFIX'.padEnd(14)) +
47
+ chalk.dim('LAST USED'));
48
+ console.log(chalk.dim(' ' + '─'.repeat(64)));
49
+ for (const k of keys) {
50
+ const prefix = k.prefix || k.key_prefix || '';
51
+ const last = k.lastUsedAt || k.last_used_at;
52
+ const lastStr = last ? new Date(last).toLocaleString() : chalk.dim('never');
53
+ console.log(' ' +
54
+ chalk.dim(String(k.id).slice(0, 12).padEnd(14)) +
55
+ chalk.bold(String(k.name).slice(0, 22).padEnd(24)) +
56
+ (prefix + '…').padEnd(14) +
57
+ lastStr);
58
+ }
59
+ console.log();
60
+ }
61
+ catch (error) {
62
+ handleError(error);
63
+ }
64
+ });
65
+ keysCommand
66
+ .command('revoke')
67
+ .alias('delete')
68
+ .description('Revoke an API key by ID')
69
+ .argument('<id>', 'API key ID (from `maritime keys list`)')
70
+ .action(async (id) => {
71
+ try {
72
+ await authDelete(`/api/admin/api-keys/${id}`);
73
+ outputResult({ ok: true, action: 'revoke', id }, () => console.log(chalk.green('Revoked key ') + chalk.bold(id)));
74
+ }
75
+ catch (error) {
76
+ handleError(error);
77
+ }
78
+ });
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
- import { authGet, CliHttpError } from '../api.js';
3
+ import { authGet } from '../api.js';
4
+ import { isJsonMode, outputJson, handleError } from '../output.js';
4
5
  const statusColors = {
5
6
  active: chalk.green,
6
7
  sleeping: chalk.blue,
@@ -14,6 +15,10 @@ export const listCommand = new Command('list')
14
15
  .action(async () => {
15
16
  try {
16
17
  const agents = await authGet('/api/agents');
18
+ if (isJsonMode()) {
19
+ outputJson(agents);
20
+ return;
21
+ }
17
22
  if (agents.length === 0) {
18
23
  console.log(chalk.yellow('No agents found.') + ' Run `maritime create` to create one.');
19
24
  return;
@@ -21,27 +26,25 @@ export const listCommand = new Command('list')
21
26
  console.log('\n ' +
22
27
  chalk.dim('NAME'.padEnd(24)) +
23
28
  chalk.dim('STATUS'.padEnd(12)) +
24
- chalk.dim('FRAMEWORK'.padEnd(14)) +
29
+ chalk.dim('FRAMEWORK'.padEnd(20)) +
25
30
  chalk.dim('TIER'.padEnd(12)) +
26
31
  chalk.dim('CREATED'));
27
- console.log(chalk.dim(' ' + '\u2500'.repeat(74)));
32
+ console.log(chalk.dim(' ' + '\u2500'.repeat(80)));
28
33
  for (const a of agents) {
29
34
  const colorFn = statusColors[a.status] || chalk.white;
30
35
  const created = a.createdAt ? new Date(a.createdAt).toLocaleDateString() : '';
36
+ const name = a.name.length > 22 ? a.name.slice(0, 21) + '\u2026' : a.name;
37
+ const fw = a.framework.length > 18 ? a.framework.slice(0, 17) + '\u2026' : a.framework;
31
38
  console.log(' ' +
32
- chalk.bold(a.name.padEnd(24)) +
39
+ chalk.bold(name.padEnd(24)) +
33
40
  colorFn(a.status.padEnd(12)) +
34
- a.framework.padEnd(14) +
41
+ fw.padEnd(20) +
35
42
  a.tier.padEnd(12) +
36
43
  chalk.dim(created));
37
44
  }
38
45
  console.log();
39
46
  }
40
47
  catch (error) {
41
- if (error instanceof CliHttpError) {
42
- console.log(chalk.red('Error:') + ` ${error.detail}`);
43
- process.exit(1);
44
- }
45
- throw error;
48
+ handleError(error);
46
49
  }
47
50
  });
@@ -9,6 +9,23 @@ import { CliHttpError, getApiUrl, postJson } from '../api.js';
9
9
  import { promptForPassword, promptForValue } from '../prompt.js';
10
10
  const APP_URL = process.env.MARITIME_APP_URL || 'https://maritime.sh';
11
11
  const TIMEOUT_MS = 120_000;
12
+ function decodeJwt(token) {
13
+ const parts = token.split('.');
14
+ if (parts.length !== 3)
15
+ return null;
16
+ try {
17
+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString());
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ }
23
+ function persistToken(token, payload) {
24
+ config.set('token', token);
25
+ config.set('user', payload.email ?? '');
26
+ config.set('userId', payload.sub ?? payload.id ?? '');
27
+ config.set('apiUrl', getApiUrl());
28
+ }
12
29
  function browserLogin() {
13
30
  return new Promise((resolve, reject) => {
14
31
  const state = crypto.randomBytes(16).toString('hex');
@@ -32,7 +49,7 @@ function browserLogin() {
32
49
  cleanup(null, token);
33
50
  });
34
51
  const timer = setTimeout(() => {
35
- cleanup(new Error('Login timed out. Try `maritime login --email <email> --password <password>` instead.'));
52
+ cleanup(new Error('Login timed out. Try `maritime login --token <token>` (get one at ' + APP_URL + '/cli/auth) instead.'));
36
53
  }, TIMEOUT_MS);
37
54
  function cleanup(err, token) {
38
55
  clearTimeout(timer);
@@ -62,9 +79,36 @@ export const loginCommand = new Command('login')
62
79
  .description('Authenticate with Maritime')
63
80
  .option('-e, --email <email>', 'Email address (for non-interactive login)')
64
81
  .option('-p, --password <password>', 'Password (for non-interactive login)')
82
+ .option('-t, --token <token>', `Paste a token from ${APP_URL}/cli/auth (works for SSO / headless / CI)`)
65
83
  .action(async (opts) => {
66
- // If email/password flags provided, use direct auth
84
+ // 1. Token paste — the universal path. Works for any account, including
85
+ // OAuth-only (Google/GitHub) users who have no password to type.
86
+ // Generate one at <app>/cli/auth.
87
+ if (opts.token) {
88
+ const token = String(opts.token).trim();
89
+ const payload = decodeJwt(token);
90
+ if (!payload) {
91
+ console.log(chalk.red('Error:') + ' that does not look like a valid token.');
92
+ console.log(chalk.dim(` Copy a fresh one from ${APP_URL}/cli/auth`));
93
+ process.exit(1);
94
+ }
95
+ if (payload.exp && Date.now() >= payload.exp * 1000) {
96
+ console.log(chalk.red('Error:') + ' that token has expired.');
97
+ console.log(chalk.dim(` Generate a new one at ${APP_URL}/cli/auth`));
98
+ process.exit(1);
99
+ }
100
+ persistToken(token, payload);
101
+ console.log(chalk.green('Authenticated as ') + chalk.bold(payload.email || 'your account'));
102
+ return;
103
+ }
104
+ // 2. Email/password (non-interactive). OAuth-only accounts have no
105
+ // password — they get pointed at the browser / token flow below.
67
106
  if (opts.email || opts.password) {
107
+ if (opts.password) {
108
+ console.log(chalk.yellow('Warning:') +
109
+ ' Passing --password on the command line may expose it in shell history.' +
110
+ '\n Prefer `maritime login` (browser) or `maritime login --token` for CI.');
111
+ }
68
112
  const email = await promptForValue('Email', opts.email);
69
113
  const password = await promptForPassword(opts.password);
70
114
  if (!email || !password) {
@@ -86,6 +130,20 @@ export const loginCommand = new Command('login')
86
130
  catch (error) {
87
131
  spinner.fail('Authentication failed');
88
132
  if (error instanceof CliHttpError) {
133
+ // OAuth-only accounts (no password) — guide the user to a path that
134
+ // actually works for them instead of the raw "oauth_only:google".
135
+ if (error.detail.startsWith('oauth_only:')) {
136
+ const providers = error.detail
137
+ .slice('oauth_only:'.length)
138
+ .split(',')
139
+ .join(', ');
140
+ console.log(chalk.red('Error:') +
141
+ ` this account signs in with ${chalk.bold(providers)} — there's no password to use here.`);
142
+ console.log('\nAuthenticate one of these ways instead:');
143
+ console.log(' ' + chalk.bold('maritime login') + chalk.dim(' open the browser and approve'));
144
+ console.log(' ' + chalk.bold('maritime login --token <token>') + chalk.dim(` paste a token from ${APP_URL}/cli/auth`));
145
+ process.exit(2);
146
+ }
89
147
  console.log(chalk.red('Error:') + ` ${error.detail}`);
90
148
  process.exit(error.status === 401 ? 2 : 1);
91
149
  }
@@ -93,23 +151,25 @@ export const loginCommand = new Command('login')
93
151
  }
94
152
  return;
95
153
  }
96
- // Default: browser-based login
154
+ // 3. Default: browser-based login.
97
155
  const spinner = ora('Opening browser for authentication...').start();
98
156
  try {
99
157
  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));
158
+ const payload = decodeJwt(token);
159
+ if (!payload) {
160
+ throw new Error('Received a malformed token from the browser.');
161
+ }
162
+ persistToken(token, payload);
163
+ spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(payload.email || 'your account'));
107
164
  }
108
165
  catch (error) {
109
166
  spinner.fail('Authentication failed');
110
167
  if (error instanceof Error) {
111
168
  console.log(chalk.red('Error:') + ` ${error.message}`);
112
169
  }
170
+ console.log(chalk.dim('\nOn a headless / SSH box? Run ') +
171
+ chalk.bold('maritime login --token <token>') +
172
+ chalk.dim(` with a token from ${APP_URL}/cli/auth`));
113
173
  process.exit(1);
114
174
  }
115
175
  });
@@ -1,7 +1,9 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
- import { authGet, CliHttpError } from '../api.js';
3
+ import { authGet } from '../api.js';
4
4
  import { resolveAgent } from '../resolve.js';
5
+ import { isJsonMode, outputJson, handleError } from '../output.js';
6
+ import { connectWs } from '../websocket.js';
5
7
  const VALID_LEVELS = ['info', 'warn', 'error', 'debug'];
6
8
  const levelColors = {
7
9
  info: chalk.blue,
@@ -9,11 +11,21 @@ const levelColors = {
9
11
  error: chalk.red,
10
12
  debug: chalk.gray,
11
13
  };
14
+ function formatEntry(entry) {
15
+ const ts = entry.timestamp
16
+ ? chalk.dim(new Date(entry.timestamp).toLocaleTimeString())
17
+ : chalk.dim('--:--:--');
18
+ const level = entry.level || 'info';
19
+ const colorFn = levelColors[level] || chalk.white;
20
+ const levelStr = colorFn(level.toUpperCase().padEnd(5));
21
+ return `${ts} ${levelStr} ${entry.message}`;
22
+ }
12
23
  export const logsCommand = new Command('logs')
13
24
  .description('View logs from an agent')
14
25
  .argument('<agent>', 'Agent name or ID')
15
26
  .option('-n, --lines <num>', 'Number of lines', '50')
16
27
  .option('--level <level>', 'Filter by level (info, warn, error, debug)')
28
+ .option('-f, --follow', 'Follow log output')
17
29
  .action(async (agentArg, opts) => {
18
30
  // Validate --level
19
31
  if (opts.level && !VALID_LEVELS.includes(opts.level)) {
@@ -32,25 +44,37 @@ export const logsCommand = new Command('logs')
32
44
  path += `&level=${opts.level}`;
33
45
  try {
34
46
  const entries = await authGet(path);
35
- if (entries.length === 0) {
47
+ if (isJsonMode() && !opts.follow) {
48
+ outputJson(entries);
49
+ return;
50
+ }
51
+ if (entries.length === 0 && !opts.follow) {
36
52
  console.log(chalk.dim('No logs found.'));
37
53
  return;
38
54
  }
39
55
  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}`);
56
+ console.log(formatEntry(entry));
57
+ }
58
+ // --follow: stream logs via WebSocket
59
+ if (opts.follow) {
60
+ connectWs(`/api/agents/${agent.id}/logs`, {
61
+ onMessage(data) {
62
+ try {
63
+ const entry = JSON.parse(data);
64
+ console.log(formatEntry(entry));
65
+ }
66
+ catch {
67
+ // Plain text message
68
+ console.log(data);
69
+ }
70
+ },
71
+ onClose() {
72
+ process.exit(0);
73
+ },
74
+ });
47
75
  }
48
76
  }
49
77
  catch (error) {
50
- if (error instanceof CliHttpError) {
51
- console.log(chalk.red('Error:') + ` ${error.detail}`);
52
- process.exit(1);
53
- }
54
- throw error;
78
+ handleError(error);
55
79
  }
56
80
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const openCommand: Command;
@@ -0,0 +1,24 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import open from 'open';
4
+ import { CliHttpError } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ const APP_URL = process.env.MARITIME_APP_URL || 'https://maritime.sh';
7
+ export const openCommand = new Command('open')
8
+ .description('Open an agent in the dashboard')
9
+ .argument('<agent>', 'Agent name or ID')
10
+ .action(async (agentArg) => {
11
+ try {
12
+ const agent = await resolveAgent(agentArg);
13
+ const url = `${APP_URL}/dashboard/agents/${agent.id}`;
14
+ console.log(chalk.dim(`Opening ${url}`));
15
+ await open(url);
16
+ }
17
+ catch (error) {
18
+ if (error instanceof CliHttpError) {
19
+ console.log(chalk.red('Error:') + ` ${error.detail}`);
20
+ process.exit(1);
21
+ }
22
+ throw error;
23
+ }
24
+ });
@@ -1,24 +1,26 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { authPost, CliHttpError } from '../api.js';
3
+ import { authPost } from '../api.js';
5
4
  import { resolveAgent } from '../resolve.js';
5
+ import { outputResult, handleError, makeSpinner } from '../output.js';
6
6
  export const restartCommand = new Command('restart')
7
7
  .description('Restart an agent')
8
8
  .argument('<agent>', 'Agent name or ID')
9
9
  .action(async (agentArg) => {
10
- const agent = await resolveAgent(agentArg);
11
- const spinner = ora(`Restarting ${chalk.bold(agent.name)}...`).start();
12
10
  try {
13
- await authPost(`/api/agents/${agent.id}/restart`);
11
+ const agent = await resolveAgent(agentArg);
12
+ const spinner = await makeSpinner(`Restarting ${chalk.bold(agent.name)}...`);
13
+ try {
14
+ await authPost(`/api/agents/${agent.id}/restart`);
15
+ }
16
+ catch (error) {
17
+ spinner.fail('Failed to restart agent');
18
+ throw error;
19
+ }
14
20
  spinner.succeed(chalk.green('Restarted ') + chalk.bold(agent.name));
21
+ outputResult({ ok: true, action: 'restart', agentId: agent.id, name: agent.name }, () => { });
15
22
  }
16
23
  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;
24
+ handleError(error);
23
25
  }
24
26
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const scaleCommand: Command;