maritime-cli 1.7.0 → 1.9.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.
@@ -47,16 +47,21 @@ function parseDotenv(text) {
47
47
  async function uploadVars(agentId, pairs, isSecret) {
48
48
  const uploaded = [];
49
49
  const failed = [];
50
+ // The backend warns when a deploy is mid-flight: that boot reads env at
51
+ // container start and may miss these values. One warning covers the batch.
52
+ let warning = null;
50
53
  for (const { key, value } of pairs) {
51
54
  try {
52
- await authPost(`/api/agents/${agentId}/env`, { key, value, is_secret: isSecret });
55
+ const resp = await authPost(`/api/agents/${agentId}/env`, { key, value, is_secret: isSecret });
56
+ if (resp?.warning)
57
+ warning = resp.warning;
53
58
  uploaded.push(key);
54
59
  }
55
60
  catch (error) {
56
61
  failed.push({ key, error: error instanceof Error ? error.message : String(error) });
57
62
  }
58
63
  }
59
- return { uploaded, failed };
64
+ return { uploaded, failed, warning };
60
65
  }
61
66
  /** Hot-reload env into the running container (falls back to restart server-side). */
62
67
  async function reloadEnv(agentId) {
@@ -126,7 +131,7 @@ envCommand
126
131
  const pairs = pairTokens.map(parsePair);
127
132
  const agent = await resolveAgent(target);
128
133
  const spinner = await makeSpinner(`Setting ${pairs.length} var${pairs.length === 1 ? '' : 's'} for ${agent.name}...`);
129
- const { uploaded, failed } = await uploadVars(agent.id, pairs, opts.secret);
134
+ const { uploaded, failed, warning } = await uploadVars(agent.id, pairs, opts.secret);
130
135
  let reloaded = false;
131
136
  if (opts.reload && uploaded.length > 0) {
132
137
  try {
@@ -141,9 +146,11 @@ envCommand
141
146
  spinner.fail(`Set ${uploaded.length}, failed ${failed.length}`);
142
147
  else
143
148
  spinner.succeed(`Set ${uploaded.length} var${uploaded.length === 1 ? '' : 's'} for ${chalk.bold(agent.name)}`);
144
- outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded }, () => {
149
+ outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded, warning }, () => {
145
150
  for (const f of failed)
146
151
  console.error(chalk.red(` ${f.key}: ${f.error}`));
152
+ if (warning)
153
+ console.log(chalk.yellow(` ${warning}`));
147
154
  if (reloaded)
148
155
  console.log(chalk.dim(' Reloaded into running container.'));
149
156
  else if (opts.reload)
@@ -205,7 +212,7 @@ envCommand
205
212
  }
206
213
  const agent = await resolveAgent(target);
207
214
  const spinner = await makeSpinner(`Importing ${pairs.length} vars into ${agent.name}...`);
208
- const { uploaded, failed } = await uploadVars(agent.id, pairs, !opts.plain);
215
+ const { uploaded, failed, warning } = await uploadVars(agent.id, pairs, !opts.plain);
209
216
  let reloaded = false;
210
217
  if (opts.reload && uploaded.length > 0) {
211
218
  try {
@@ -220,9 +227,11 @@ envCommand
220
227
  spinner.fail(`Imported ${uploaded.length}, failed ${failed.length}`);
221
228
  else
222
229
  spinner.succeed(`Imported ${uploaded.length} vars into ${chalk.bold(agent.name)}`);
223
- outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded }, () => {
230
+ outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded, warning }, () => {
224
231
  for (const f of failed)
225
232
  console.error(chalk.red(` ${f.key}: ${f.error}`));
233
+ if (warning)
234
+ console.log(chalk.yellow(` ${warning}`));
226
235
  if (reloaded)
227
236
  console.log(chalk.dim(' Reloaded into running container.'));
228
237
  else if (opts.reload)
@@ -1,9 +1,6 @@
1
- import { readFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { dirname, join } from 'node:path';
4
1
  import { Command } from 'commander';
2
+ import { readBundledFile } from '../bundled.js';
5
3
  import { isJsonMode, outputJson } from '../output.js';
6
- const __dirname = dirname(fileURLToPath(import.meta.url));
7
4
  /**
8
5
  * The machine contract an AI agent needs that isn't expressible as flags.
9
6
  * Kept in sync with AGENTS.md; emitted by `guide --json` so an agent can learn
@@ -13,9 +10,10 @@ const CONTRACT = {
13
10
  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
11
  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
12
  exitCodes: { '0': 'ok', '1': 'error', '2': 'auth', '3': 'not_found', '4': 'usage' },
13
+ billing: 'A plan sets how many machines you may have (the free plan includes 3). A machine is one micro-VM: an agent is a machine and so is a Computer, and both draw on the same count. When a create is refused for a billing reason the CLI exits 1 with error.status 402 and error.code from the server, usually seat_limit. error.message is the server sentence verbatim: it already names the fix (delete an agent, upgrade, renew a lapsed plan, or add your own INKBOX_API_KEY) and carries https://maritime.sh/billing. Surface it to your user unchanged instead of writing your own reason.',
16
14
  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. To message AS one of YOUR end-users (sticky per-user agents via the project front door), use `maritime message <agent> --user <externalUserId> <message>`; status:replied carries .reply inline; provisioning/queued means the reply arrives via the message.reply webhook.',
17
- resources: 'create accepts per-agent overrides: --ram <mb>, --cpu <cores>, --idle <seconds> | --always-on, --disk <gb>, --max-compute <minutes>. Omitted = platform defaults.',
18
- fleet: 'create --count <n> (2-50) spins up n identical agents named <name>-1..<name>-n in one call. Supported alongside --count: --template, --idle/--always-on, --repo, -e/--env; other create flags exit 4. --json returns {created:[{id,name,status}],failed:[{name,error}],requested,monthlyCostCents}. Exit 0 = all created, 1 = partial/none (402 insufficient wallet balance, 403 over the 50-agent cap → exit 1).',
15
+ resources: 'create accepts per-agent overrides: --ram <mb>, --cpu <cores>, --idle <seconds> | --always-on, --disk <gb>. Omitted = platform defaults. Above the included 2 GB RAM / 5 GB SSD, and for --always-on, these are paid add-ons that need a plan; the 402 below says so.',
16
+ fleet: 'create --count <n> (2-50) spins up n identical agents named <name>-1..<name>-n in one call. Supported alongside --count: --template, --idle/--always-on, --repo, -e/--env; other create flags exit 4. --json returns {created:[{id,name,status}],failed:[{name,error}],requested}. Exit 0 = all created, 1 = partial/none. A 402 means a billing gate closed (error.code seat_limit): error.message is the complete server sentence naming the fix and the https://maritime.sh/billing link, so show it as-is. 403 over the 50-agent cap also exits 1.',
19
17
  project: 'A directory can be linked to an agent (like vercel/railway). `maritime init <name>` scaffolds maritime.json + AGENTS.md and links it; `maritime link <agent>` links an existing one; `maritime deploy` reconciles the agent to maritime.json. Once linked, the <agent> argument is optional on every command (resolved from .maritime/project.json, walking up from cwd).',
20
18
  apiBase: 'Override the API base with MARITIME_API_URL (default https://api.maritime.sh).',
21
19
  };
@@ -42,16 +40,7 @@ function serializeCommand(cmd) {
42
40
  }
43
41
  /* eslint-enable @typescript-eslint/no-explicit-any */
44
42
  function readBundledGuide() {
45
- // dist/commands/guide.js → package root is two levels up.
46
- for (const rel of [['..', '..', 'AGENTS.md'], ['..', '..', '..', 'AGENTS.md']]) {
47
- try {
48
- return readFileSync(join(__dirname, ...rel), 'utf-8');
49
- }
50
- catch {
51
- // try next candidate
52
- }
53
- }
54
- return null;
43
+ return readBundledFile('AGENTS.md');
55
44
  }
56
45
  export const guideCommand = new Command('guide')
57
46
  .alias('agent-guide')
@@ -81,5 +70,6 @@ export const guideCommand = new Command('guide')
81
70
  console.log(` JSON: ${CONTRACT.json}`);
82
71
  console.log(` Chat: ${CONTRACT.interaction}`);
83
72
  console.log(` Limits: ${CONTRACT.resources}`);
73
+ console.log(` Billing: ${CONTRACT.billing}`);
84
74
  console.log('\n Run `maritime guide --json` for the full structured manifest.');
85
75
  });
@@ -30,6 +30,11 @@ export const infoCommand = new Command('info')
30
30
  const rows = [
31
31
  ['ID', chalk.dim(agent.id)],
32
32
  ['Status', statusColor(agent.status)],
33
+ [
34
+ 'Sleep',
35
+ agent.sleepPolicy ??
36
+ (agent.idleTtlSeconds != null && agent.idleTtlSeconds <= 0 ? 'always-on' : 'auto-sleep'),
37
+ ],
33
38
  ['Framework', agent.framework],
34
39
  ['Created', agent.createdAt ? new Date(agent.createdAt).toLocaleString() : 'n/a'],
35
40
  ];
@@ -1,11 +1,33 @@
1
- import { existsSync, writeFileSync } from 'node:fs';
2
- import { basename, join } from 'node:path';
1
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
3
3
  import { Command } from 'commander';
4
4
  import chalk from 'chalk';
5
5
  import { authPost } from '../api.js';
6
6
  import { getConfig, writeConfig, writeLink, configExists, CONFIG_FILENAME, } from '../context.js';
7
+ import { readBundledFile } from '../bundled.js';
7
8
  import { promptForValue } from '../prompt.js';
8
9
  import { isJsonMode, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
10
+ /** Where the bundled Claude Code skill is written, relative to the cwd. */
11
+ const SKILL_PATH = join('.claude', 'skills', 'maritime', 'SKILL.md');
12
+ const SKILL_BUNDLED_NAME = 'SKILL.md';
13
+ /**
14
+ * Writes the bundled Maritime skill to `.claude/skills/maritime/SKILL.md`
15
+ * under `cwd` when that file does not exist yet.
16
+ *
17
+ * Returns true when the file was written. Returns false when it already
18
+ * existed or the CLI build did not ship SKILL.md (skipped silently).
19
+ */
20
+ function writeSkillFile(cwd) {
21
+ const target = join(cwd, SKILL_PATH);
22
+ if (existsSync(target))
23
+ return false;
24
+ const content = readBundledFile(SKILL_BUNDLED_NAME);
25
+ if (content === null)
26
+ return false;
27
+ mkdirSync(dirname(target), { recursive: true });
28
+ writeFileSync(target, content);
29
+ return true;
30
+ }
9
31
  const AGENTS_MD = (name, instructions) => `# ${name}
10
32
 
11
33
  ${instructions || 'Describe what this agent does and how it should behave. This file is the agent\'s persona. It is loaded into the agent\'s workspace at boot.'}
@@ -21,6 +43,7 @@ export const initCommand = new Command('init')
21
43
  .option('--framework <framework>', 'Framework for bring-your-own-code agents (instead of a template)')
22
44
  .option('--instructions <text>', 'Plain-English persona for the agent')
23
45
  .option('--no-create', 'Only write the config files; do not create the agent yet')
46
+ .option('--no-skill', `Do not write the Claude Code skill file (${SKILL_PATH})`)
24
47
  .addHelpText('after', `
25
48
  Examples:
26
49
  maritime init # scaffold + create, named after the folder
@@ -62,6 +85,9 @@ After init, run \`maritime deploy\` to push changes, or \`maritime chat "…"\`.
62
85
  writeFileSync(agentsMdPath, AGENTS_MD(name, instructions));
63
86
  wroteAgentsMd = true;
64
87
  }
88
+ // Teach Claude Code (and any agent that reads .claude/skills) how to
89
+ // drive this CLI from inside the project.
90
+ const wroteSkill = opts.skill !== false && writeSkillFile(process.cwd());
65
91
  // Create + link unless --no-create.
66
92
  let agent = null;
67
93
  let linkPath = null;
@@ -90,6 +116,7 @@ After init, run \`maritime deploy\` to push changes, or \`maritime chat "…"\`.
90
116
  config: configPath,
91
117
  wroteConfig,
92
118
  wroteAgentsMd,
119
+ wroteSkill,
93
120
  agentId: agent?.id ?? null,
94
121
  agentName: agent?.name ?? name,
95
122
  linked: Boolean(linkPath),
@@ -97,6 +124,8 @@ After init, run \`maritime deploy\` to push changes, or \`maritime chat "…"\`.
97
124
  console.log(chalk.dim(` ${wroteConfig ? 'wrote' : 'updated'} ${CONFIG_FILENAME}`));
98
125
  if (wroteAgentsMd)
99
126
  console.log(chalk.dim(' wrote AGENTS.md'));
127
+ if (wroteSkill)
128
+ console.log(chalk.dim(` wrote ${SKILL_PATH}`));
100
129
  if (agent) {
101
130
  console.log(chalk.dim(' linked this directory → ') + chalk.bold(agent.name));
102
131
  console.log();
@@ -2,6 +2,11 @@ import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import { authGet } from '../api.js';
4
4
  import { isJsonMode, outputJson, handleError } from '../output.js';
5
+ function sleepPolicyOf(a) {
6
+ if (a.sleepPolicy)
7
+ return a.sleepPolicy;
8
+ return a.idleTtlSeconds != null && a.idleTtlSeconds <= 0 ? 'always-on' : 'auto-sleep';
9
+ }
5
10
  const statusColors = {
6
11
  active: chalk.green,
7
12
  sleeping: chalk.blue,
@@ -26,9 +31,10 @@ export const listCommand = new Command('list')
26
31
  console.log('\n ' +
27
32
  chalk.dim('NAME'.padEnd(24)) +
28
33
  chalk.dim('STATUS'.padEnd(12)) +
34
+ chalk.dim('SLEEP'.padEnd(12)) +
29
35
  chalk.dim('FRAMEWORK'.padEnd(20)) +
30
36
  chalk.dim('CREATED'));
31
- console.log(chalk.dim(' ' + '\u2500'.repeat(80)));
37
+ console.log(chalk.dim(' ' + '\u2500'.repeat(88)));
32
38
  for (const a of agents) {
33
39
  const colorFn = statusColors[a.status] || chalk.white;
34
40
  const created = a.createdAt ? new Date(a.createdAt).toLocaleDateString() : '';
@@ -37,6 +43,7 @@ export const listCommand = new Command('list')
37
43
  console.log(' ' +
38
44
  chalk.bold(name.padEnd(24)) +
39
45
  colorFn(a.status.padEnd(12)) +
46
+ sleepPolicyOf(a).padEnd(12) +
40
47
  fw.padEnd(20) +
41
48
  chalk.dim(created));
42
49
  }
@@ -1,14 +1,32 @@
1
1
  import http from 'node:http';
2
2
  import crypto from 'node:crypto';
3
+ import { readFileSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { dirname, join } from 'node:path';
3
6
  import { Command } from 'commander';
4
7
  import chalk from 'chalk';
5
8
  import open from 'open';
6
9
  import { config } from '../config.js';
7
10
  import { CliHttpError, getApiUrl, postJson } from '../api.js';
8
- import { makeSpinner } from '../output.js';
11
+ import { EXIT, fail, handleError, isJsonMode, makeSpinner, outputResult } from '../output.js';
9
12
  import { promptForPassword, promptForValue } from '../prompt.js';
10
13
  const APP_URL = process.env.MARITIME_APP_URL || 'https://maritime.sh';
11
14
  const TIMEOUT_MS = 120_000;
15
+ const MS_PER_SECOND = 1000;
16
+ const SECONDS_PER_MINUTE = 60;
17
+ /** Added to the poll interval every time the server answers `slow_down`. */
18
+ const DEVICE_SLOW_DOWN_EXTRA_SECONDS = 5;
19
+ const DEVICE_CLIENT_NAME = 'maritime-cli';
20
+ const __dirname = dirname(fileURLToPath(import.meta.url));
21
+ /** Thrown by the browser flow when the browser itself could not be opened. */
22
+ class BrowserOpenError extends Error {
23
+ loginUrl;
24
+ constructor(loginUrl) {
25
+ super('Could not open a browser');
26
+ this.loginUrl = loginUrl;
27
+ this.name = 'BrowserOpenError';
28
+ }
29
+ }
12
30
  function decodeJwt(token) {
13
31
  const parts = token.split('.');
14
32
  if (parts.length !== 3)
@@ -26,6 +44,20 @@ function persistToken(token, payload) {
26
44
  config.set('userId', payload.sub ?? payload.id ?? '');
27
45
  config.set('apiUrl', getApiUrl());
28
46
  }
47
+ /** Returns the installed CLI version from the bundled package.json, or "unknown". */
48
+ function readCliVersion() {
49
+ try {
50
+ // dist/commands/login.js: the package root is two levels up.
51
+ const pkg = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8'));
52
+ return pkg.version ?? 'unknown';
53
+ }
54
+ catch {
55
+ return 'unknown';
56
+ }
57
+ }
58
+ function sleep(ms) {
59
+ return new Promise((resolve) => setTimeout(resolve, ms));
60
+ }
29
61
  function browserLogin() {
30
62
  return new Promise((resolve, reject) => {
31
63
  const state = crypto.randomBytes(16).toString('hex');
@@ -49,7 +81,7 @@ function browserLogin() {
49
81
  cleanup(null, token);
50
82
  });
51
83
  const timer = setTimeout(() => {
52
- cleanup(new Error('Login timed out. Try `maritime login --token <token>` (get one at ' + APP_URL + '/cli/auth) instead.'));
84
+ cleanup(new Error('Login timed out. Try `maritime login --device` or `maritime login --token <token>` (get one at ' + APP_URL + '/cli/auth) instead.'));
53
85
  }, TIMEOUT_MS);
54
86
  function cleanup(err, token) {
55
87
  clearTimeout(timer);
@@ -67,21 +99,162 @@ function browserLogin() {
67
99
  }
68
100
  const port = addr.port;
69
101
  const loginUrl = `${APP_URL}/cli/auth?port=${port}&state=${state}`;
70
- open(loginUrl).catch(() => {
71
- // If open fails, print URL for manual use
72
- console.log(chalk.yellow('\nCould not open browser. Visit this URL manually:'));
73
- console.log(chalk.bold(loginUrl) + '\n');
74
- });
102
+ // No browser here (headless box, container, agent sandbox): the caller
103
+ // falls back to the device flow instead of waiting for a callback
104
+ // that can never arrive.
105
+ open(loginUrl).catch(() => cleanup(new BrowserOpenError(loginUrl)));
75
106
  });
76
107
  });
77
108
  }
109
+ /**
110
+ * Prints the user code and where to enter it.
111
+ *
112
+ * Human mode writes the block to stdout. JSON mode writes one JSON line to
113
+ * stderr so a program driving the CLI can show the code to its user while
114
+ * stdout stays reserved for the single final result.
115
+ */
116
+ function announceDeviceCode(code) {
117
+ if (isJsonMode()) {
118
+ process.stderr.write(JSON.stringify({
119
+ ok: true,
120
+ action: 'device_code',
121
+ user_code: code.user_code,
122
+ verification_uri_complete: code.verification_uri_complete,
123
+ expires_in: code.expires_in,
124
+ }) + '\n');
125
+ return;
126
+ }
127
+ const minutes = Math.round(code.expires_in / SECONDS_PER_MINUTE);
128
+ console.log(`Open ${chalk.bold(code.verification_uri)} and enter the code:\n`);
129
+ console.log(` ${chalk.bold(code.user_code)}\n`);
130
+ console.log(chalk.dim(`Waiting for approval (expires in ${minutes} minutes)...`));
131
+ }
132
+ /**
133
+ * Signs in with a device code: asks the server for a code pair, shows the
134
+ * user code, then polls until the human approves it on the dashboard.
135
+ *
136
+ * Never returns on denial or expiry: those end the command through `fail()`
137
+ * with exit code 2.
138
+ *
139
+ * @returns The token and user the server issued after approval.
140
+ */
141
+ async function deviceLogin() {
142
+ const code = await postJson('/api/auth/device/code', {
143
+ client: DEVICE_CLIENT_NAME,
144
+ version: readCliVersion(),
145
+ });
146
+ announceDeviceCode(code);
147
+ const deadline = Date.now() + code.expires_in * MS_PER_SECOND;
148
+ let intervalSeconds = code.interval;
149
+ while (Date.now() < deadline) {
150
+ await sleep(intervalSeconds * MS_PER_SECOND);
151
+ try {
152
+ return await postJson('/api/auth/device/token', {
153
+ device_code: code.device_code,
154
+ });
155
+ }
156
+ catch (error) {
157
+ if (!(error instanceof CliHttpError))
158
+ throw error;
159
+ if (error.code === 'authorization_pending')
160
+ continue;
161
+ if (error.code === 'slow_down') {
162
+ intervalSeconds += DEVICE_SLOW_DOWN_EXTRA_SECONDS;
163
+ continue;
164
+ }
165
+ if (error.code === 'access_denied') {
166
+ fail('Sign-in was denied in the browser.', {
167
+ code: 'access_denied',
168
+ status: error.status,
169
+ exitCode: EXIT.AUTH,
170
+ });
171
+ }
172
+ if (error.code === 'expired_token') {
173
+ fail('The code expired before it was approved. Run `maritime login --device` again.', {
174
+ code: 'expired_token',
175
+ status: error.status,
176
+ exitCode: EXIT.AUTH,
177
+ });
178
+ }
179
+ throw error;
180
+ }
181
+ }
182
+ fail('The code expired before it was approved. Run `maritime login --device` again.', {
183
+ code: 'expired_token',
184
+ exitCode: EXIT.AUTH,
185
+ });
186
+ }
187
+ /** Runs the device flow and stores the result. */
188
+ async function runDeviceLogin() {
189
+ try {
190
+ const auth = await deviceLogin();
191
+ config.set('token', auth.token);
192
+ config.set('user', auth.user.email);
193
+ config.set('userId', auth.user.id);
194
+ config.set('apiUrl', getApiUrl());
195
+ outputResult({ ok: true, action: 'login', method: 'device', user: auth.user.email }, chalk.green('Authenticated as ') + chalk.bold(auth.user.email));
196
+ }
197
+ catch (error) {
198
+ // Every device-flow failure is an auth failure to the caller (exit 2),
199
+ // also a 404 from a backend that predates the device endpoints.
200
+ if (error instanceof CliHttpError) {
201
+ fail(error.detail, {
202
+ code: error.code ?? 'device_login_failed',
203
+ status: error.status,
204
+ exitCode: EXIT.AUTH,
205
+ });
206
+ }
207
+ handleError(error);
208
+ }
209
+ }
210
+ /**
211
+ * True when a browser callback to 127.0.0.1 cannot work: no terminal, an
212
+ * SSH session, CI, or a program driving the CLI with --json.
213
+ */
214
+ function browserUnavailable() {
215
+ return (!process.stdin.isTTY ||
216
+ !process.stdout.isTTY ||
217
+ Boolean(process.env.SSH_CONNECTION) ||
218
+ Boolean(process.env.CI) ||
219
+ isJsonMode());
220
+ }
221
+ /**
222
+ * Asks the server to send the email verification link again.
223
+ *
224
+ * The server always answers ok, also for an address with no account or an
225
+ * address that is already verified, so "Sent" does not confirm an account.
226
+ *
227
+ * @param emailFlag The value of `-e`. When absent, the email of the stored login is used.
228
+ */
229
+ async function resendVerification(emailFlag) {
230
+ const email = (emailFlag ?? config.get('user') ?? '').trim();
231
+ if (!email) {
232
+ fail('No email to send to. Run `maritime login --resend -e <email>`.', {
233
+ code: 'email_required',
234
+ exitCode: EXIT.USAGE,
235
+ });
236
+ }
237
+ try {
238
+ await postJson('/api/auth/resend-verification', { email });
239
+ }
240
+ catch (error) {
241
+ handleError(error);
242
+ }
243
+ outputResult({ ok: true, action: 'resend_verification', email }, `Sent. Check ${email}.`);
244
+ }
78
245
  export const loginCommand = new Command('login')
79
246
  .description('Authenticate with Maritime')
80
247
  .option('-e, --email <email>', 'Email address (for non-interactive login)')
81
248
  .option('-p, --password <password>', 'Password (for non-interactive login)')
82
249
  .option('-t, --token <token>', `Paste a token from ${APP_URL}/cli/auth (works for SSO / headless / CI)`)
250
+ .option('--device', `Sign in from a machine without a browser: prints a code to enter at ${APP_URL}/cli/device`)
251
+ .option('--resend', 'Send the email verification link again (uses -e, else the logged-in email)')
83
252
  .action(async (opts) => {
84
- // 1. Token paste — the universal path. Works for any account, including
253
+ if (opts.resend) {
254
+ await resendVerification(opts.email);
255
+ return;
256
+ }
257
+ // 1. Token paste: the universal path. Works for any account, including
85
258
  // OAuth-only (Google/GitHub) users who have no password to type.
86
259
  // Generate one at <app>/cli/auth.
87
260
  if (opts.token) {
@@ -104,7 +277,7 @@ export const loginCommand = new Command('login')
104
277
  return;
105
278
  }
106
279
  // 2. Email/password (non-interactive). OAuth-only accounts have no
107
- // password — they get pointed at the browser / token flow below.
280
+ // password, so they get pointed at the browser / token flow below.
108
281
  if (opts.email || opts.password) {
109
282
  if (opts.password) {
110
283
  console.log(chalk.yellow('Warning:') +
@@ -133,7 +306,7 @@ export const loginCommand = new Command('login')
133
306
  catch (error) {
134
307
  spinner.fail('Authentication failed');
135
308
  if (error instanceof CliHttpError) {
136
- // OAuth-only accounts (no password) — guide the user to a path that
309
+ // OAuth-only accounts (no password): guide the user to a path that
137
310
  // actually works for them instead of the raw "oauth_only:google".
138
311
  if (error.detail.startsWith('oauth_only:')) {
139
312
  const providers = error.detail
@@ -144,6 +317,7 @@ export const loginCommand = new Command('login')
144
317
  ` this account signs in with ${chalk.bold(providers)}. There's no password to use here.`);
145
318
  console.log('\nAuthenticate one of these ways instead:');
146
319
  console.log(' ' + chalk.bold('maritime login') + chalk.dim(' open the browser and approve'));
320
+ console.log(' ' + chalk.bold('maritime login --device') + chalk.dim(' enter a code at ' + APP_URL + '/cli/device'));
147
321
  console.log(' ' + chalk.bold('maritime login --token <token>') + chalk.dim(` paste a token from ${APP_URL}/cli/auth`));
148
322
  process.exitCode = 2;
149
323
  return;
@@ -156,7 +330,13 @@ export const loginCommand = new Command('login')
156
330
  }
157
331
  return;
158
332
  }
159
- // 3. Default: browser-based login.
333
+ // 3. Device code: no browser on this machine (headless box, container,
334
+ // an AI coding agent's sandbox). Also the automatic fallback below.
335
+ if (opts.device || browserUnavailable()) {
336
+ await runDeviceLogin();
337
+ return;
338
+ }
339
+ // 4. Default: browser-based login.
160
340
  const spinner = await makeSpinner('Opening browser for authentication...');
161
341
  try {
162
342
  const token = await browserLogin();
@@ -168,11 +348,19 @@ export const loginCommand = new Command('login')
168
348
  spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(payload.email || 'your account'));
169
349
  }
170
350
  catch (error) {
351
+ if (error instanceof BrowserOpenError) {
352
+ spinner.stop();
353
+ console.log(chalk.yellow('Could not open a browser.') + ' Switching to the code flow.\n');
354
+ await runDeviceLogin();
355
+ return;
356
+ }
171
357
  spinner.fail('Authentication failed');
172
358
  if (error instanceof Error) {
173
359
  console.log(chalk.red('Error:') + ` ${error.message}`);
174
360
  }
175
361
  console.log(chalk.dim('\nOn a headless / SSH box? Run ') +
362
+ chalk.bold('maritime login --device') +
363
+ chalk.dim(' or ') +
176
364
  chalk.bold('maritime login --token <token>') +
177
365
  chalk.dim(` with a token from ${APP_URL}/cli/auth`));
178
366
  process.exitCode = 1;
@@ -1,44 +1,72 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import { config } from '../config.js';
4
- import { CliHttpError, postJson } from '../api.js';
5
- import { makeSpinner } from '../output.js';
4
+ import { CliHttpError, getApiUrl, postJson } from '../api.js';
5
+ import { EXIT, fail, handleError, isJsonMode, makeSpinner, outputResult } from '../output.js';
6
6
  import { promptForPassword, promptForValue } from '../prompt.js';
7
+ /** Statuses from this value up are server faults, not a refused signup. */
8
+ const SERVER_ERROR_STATUS = 500;
9
+ /**
10
+ * Returns the sentence that tells a new account what to do about email
11
+ * verification. Deploys and API keys are refused until the link is clicked.
12
+ */
13
+ function verificationNext(email) {
14
+ return (`Verify your email: we sent a link to ${email}. ` +
15
+ 'Deploys and API keys are refused until the link is clicked. ' +
16
+ 'Run `maritime login --resend` to send it again.');
17
+ }
7
18
  export const signupCommand = new Command('signup')
8
19
  .description('Create a Maritime account with email and password')
9
20
  .option('-e, --email <email>', 'Email address')
10
21
  .option('-p, --password <password>', 'Password')
11
22
  .option('-n, --name <name>', 'Display name')
12
23
  .action(async (opts) => {
24
+ const interactive = !isJsonMode() && Boolean(process.stdin.isTTY);
25
+ if (!interactive && (!opts.email || !opts.password)) {
26
+ fail('Email and password are required: pass -e <email> -p <password>.', {
27
+ code: 'usage',
28
+ exitCode: EXIT.USAGE,
29
+ });
30
+ }
13
31
  const email = await promptForValue('Email', opts.email);
14
32
  const password = await promptForPassword(opts.password);
15
- const name = await promptForValue('Name (optional)', opts.name);
33
+ const name = interactive ? await promptForValue('Name (optional)', opts.name) : opts.name;
16
34
  if (!email || !password) {
17
- console.log(chalk.red('Error:') + ' email and password are required');
18
- process.exitCode = 1;
19
- return;
35
+ fail('Email and password are required.', { code: 'usage', exitCode: EXIT.USAGE });
20
36
  }
21
37
  const spinner = await makeSpinner('Creating account...');
38
+ let auth;
22
39
  try {
23
- const auth = await postJson('/api/auth/cli-signup', {
40
+ auth = await postJson('/api/auth/cli-signup', {
24
41
  email,
25
42
  password,
26
43
  name: name || undefined,
27
44
  });
28
- config.set('token', auth.token);
29
- config.set('user', auth.user.email);
30
- config.set('userId', auth.user.id);
31
- config.set('apiUrl', process.env.MARITIME_API_URL || 'https://api.maritime.sh');
32
- spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(auth.user.email));
33
- console.log(chalk.dim('\nToken saved. You can now deploy agents.'));
34
45
  }
35
46
  catch (error) {
36
47
  spinner.fail('Signup failed');
37
48
  if (error instanceof CliHttpError) {
38
- console.log(chalk.red('Error:') + ` ${error.detail}`);
39
- process.exitCode = error.status >= 500 ? 1 : 2;
40
- return;
49
+ fail(error.detail, {
50
+ code: error.code ?? 'signup_failed',
51
+ status: error.status,
52
+ exitCode: error.status >= SERVER_ERROR_STATUS ? EXIT.ERROR : EXIT.AUTH,
53
+ });
41
54
  }
42
- throw error;
55
+ handleError(error);
43
56
  }
57
+ config.set('token', auth.token);
58
+ config.set('user', auth.user.email);
59
+ config.set('userId', auth.user.id);
60
+ config.set('apiUrl', getApiUrl());
61
+ spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(auth.user.email));
62
+ outputResult({
63
+ ok: true,
64
+ action: 'signup',
65
+ user: auth.user.email,
66
+ emailVerified: false,
67
+ next: verificationNext(auth.user.email),
68
+ }, () => {
69
+ console.log(chalk.dim('\nToken saved.'));
70
+ console.log(verificationNext(auth.user.email));
71
+ });
44
72
  });
@@ -32,9 +32,6 @@ export const statusCommand = new Command('status')
32
32
  const idle = agent.idleTtlSeconds <= 0 ? 'always-on' : `${agent.idleTtlSeconds}s after request`;
33
33
  console.log(` ${'Idle:'.padEnd(16)} ${idle}`);
34
34
  }
35
- if (agent.computeMinutesLimit) {
36
- console.log(` ${'Compute cap:'.padEnd(16)} ${agent.computeMinutesLimit} min / period`);
37
- }
38
35
  console.log(` ${'ID:'.padEnd(16)} ${chalk.dim(agent.id)}`);
39
36
  if (agent.invocationCount !== undefined) {
40
37
  console.log(` ${'Invocations:'.padEnd(16)} ${agent.invocationCount}`);
@@ -39,14 +39,24 @@ const triggerListCmd = new Command('list')
39
39
  const triggerCreateCmd = new Command('create')
40
40
  .description('Create a trigger for an agent')
41
41
  .argument('<agent>', 'Agent name or ID')
42
- .requiredOption('--type <type>', 'Trigger type (webhook, cron, email)')
42
+ .requiredOption('--type <type>', 'Trigger type (webhook, cron, telegram, discord)')
43
43
  .option('--cron <expression>', 'Cron expression (for cron triggers)')
44
+ .option('--prompt <text>', 'Message delivered to the agent on each fire (cron triggers only, max 2000 chars)')
44
45
  .action(async (agentArg, opts) => {
45
46
  try {
47
+ if (opts.prompt !== undefined && opts.type !== 'cron') {
48
+ handleError(new Error('--prompt applies to cron triggers only'));
49
+ return;
50
+ }
46
51
  const agent = await resolveAgent(agentArg);
47
52
  const body = { type: opts.type };
53
+ const config = {};
48
54
  if (opts.cron)
49
- body.config = { cron: opts.cron };
55
+ config.cron = opts.cron;
56
+ if (opts.prompt)
57
+ config.prompt = opts.prompt;
58
+ if (Object.keys(config).length > 0)
59
+ body.config = config;
50
60
  const trigger = await authPost(`/api/agents/${agent.id}/triggers`, body);
51
61
  if (isJsonMode()) {
52
62
  outputJson(trigger);