maritime-cli 1.8.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.
package/AGENTS.md CHANGED
@@ -34,6 +34,58 @@ export MARITIME_TOKEN=mk_xxxxxxxxxxxxxxxxxxxxxxxx
34
34
 
35
35
  `mk_` keys do not expire. Rotate with `maritime keys list` / `maritime keys revoke <id>`.
36
36
 
37
+ ### No browser: `maritime login --device`
38
+
39
+ When the machine has no browser and no reachable localhost callback (a
40
+ headless box, a container, an AI coding agent's sandbox), sign in with a
41
+ device code. `maritime login` with no flags switches to this flow by itself
42
+ when there is no TTY, when `SSH_CONNECTION` or `CI` is set, when `--json` is
43
+ passed, or when the browser cannot be opened.
44
+
45
+ ```bash
46
+ maritime login --device --json
47
+ ```
48
+
49
+ The CLI prints one JSON line on **stderr** first, so a program can show the
50
+ code to its human:
51
+
52
+ ```json
53
+ {"ok":true,"action":"device_code","user_code":"XXXX-XXXX","verification_uri_complete":"https://maritime.sh/cli/device?code=XXXX-XXXX","expires_in":900}
54
+ ```
55
+
56
+ The human opens that URL while signed in and clicks Approve. The CLI polls
57
+ every 5 seconds, stores the token, and then prints the single result on
58
+ stdout:
59
+
60
+ ```json
61
+ { "ok": true, "action": "login", "method": "device", "user": "you@example.com" }
62
+ ```
63
+
64
+ The code expires after 15 minutes. Denial or expiry ends the command with
65
+ exit `2` and `error.code` = `access_denied` or `expired_token`. The token it
66
+ stores is the 30-day login JWT; mint an `mk_` key afterwards for anything
67
+ long-lived.
68
+
69
+ ### New account: `maritime signup`
70
+
71
+ ```bash
72
+ maritime signup -e you@example.com -p '<password>' --json
73
+ ```
74
+
75
+ Non-interactive (`--json` or no TTY) with email or password missing is a
76
+ usage error (exit `4`); the command never prompts in that case. Success
77
+ stores the token and prints:
78
+
79
+ ```json
80
+ { "ok": true, "action": "signup", "user": "you@example.com", "emailVerified": false,
81
+ "next": "Verify your email: we sent a link to you@example.com. Deploys and API keys are refused until the link is clicked. Run `maritime login --resend` to send it again." }
82
+ ```
83
+
84
+ The account is signed in but unverified: `deploy`, `start`, `restart`, key
85
+ creation and computer creation answer `403 email_not_verified` until the
86
+ human clicks the link in the email (see above). `create` and `chat` work
87
+ before that.
88
+
37
89
  ## Output contract: always pass `--json`
38
90
 
39
91
  With `--json`, every command obeys a strict contract:
package/SKILL.md ADDED
@@ -0,0 +1,181 @@
1
+ ---
2
+ name: maritime
3
+ description: Deploy and operate AI agents on Maritime (maritime.sh), a cloud that gives every agent its own persistent Firecracker micro-VM that sleeps when idle and wakes in about a second. Use when asked to host, deploy, run, or manage an agent on Maritime, to give an agent a persistent computer, to provision one agent per end user from a backend, or to move a bot, worker, or scheduled job onto Maritime. Covers signup, headless login, the JSON output contract, exit codes, deploy recipes, and the email verification wall.
4
+ metadata:
5
+ author: maritime-sh
6
+ version: "1.0"
7
+ ---
8
+
9
+ # Maritime
10
+
11
+ Maritime hosts AI agents. Each agent runs in its own micro-VM with a persistent
12
+ disk at `/data`. It sleeps when idle (free while asleep), wakes in about a
13
+ second on the next message or trigger, and hosting is a flat monthly plan with
14
+ no metering. The free plan includes 3 machines, no card.
15
+
16
+ This skill is for driving Maritime as a program or an AI agent, not as a
17
+ human at a keyboard. Every command speaks JSON and every failure is
18
+ structured.
19
+
20
+ ## Rules
21
+
22
+ 1. Pass `--json` on every command. Success: one JSON value on stdout, stderr
23
+ empty. Failure: `{"ok": false, "error": {"code", "message", "status"}}` on
24
+ stderr, stdout empty. Read stdout, branch on the exit code, never scrape
25
+ human text.
26
+ 2. Exit codes: `0` ok, `1` error, `2` auth, `3` not found, `4` usage.
27
+ 3. Never guess flags. `maritime guide --json` prints the full command and flag
28
+ manifest, introspected from the installed CLI.
29
+ 4. Never paste a secret into chat. Keys go into env vars or `maritime env set`.
30
+ 5. Confirm with the user before a paid create. On the free plan a create is
31
+ free (3 machines). A refused create exits `1` with `error.status` 402 and
32
+ `error.code` `seat_limit`; show `error.message` unchanged, it names the fix.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ npm install -g maritime-cli # Node 20.12 or later; the command is `maritime`
38
+ maritime --version # 1.9.0 or later has `login --device` and `signup` in --help
39
+ ```
40
+
41
+ If a flag below is unknown, the CLI is old: `npm install -g maritime-cli@latest`.
42
+
43
+ ## Authenticate
44
+
45
+ Try these in order and stop at the first that works.
46
+
47
+ 1. A token is already present: `MARITIME_TOKEN` in the environment, or a
48
+ saved login. Check with `maritime whoami --json` (exit `2` means no token).
49
+ 2. The user has an account and you have no browser: `maritime login --device
50
+ --json`. It prints a code on stderr as one JSON line
51
+ (`{"action":"device_code","user_code":"XXXX-XXXX","verification_uri_complete":"..."}`).
52
+ Show the user the URL and the code, then wait; the command returns when
53
+ they approve.
54
+ 3. The user has an account and a browser on this machine: `maritime login`.
55
+ 4. No account: `maritime signup -e <email> -p <password> -n <name> --json`.
56
+ Ask the user for the email and password; never invent them. Signup saves a
57
+ token and returns `emailVerified: false`.
58
+
59
+ The email verification wall: until the user clicks the link Maritime emailed
60
+ them, `create`, `deploy`, `start`, `restart`, `keys create` and computer
61
+ creation are refused with status `403` and `error.code`
62
+ `email_not_verified`. When you see it, tell the user to open the email and
63
+ click the link, offer `maritime login --resend` to send it again, then retry
64
+ the same command. Everything else (list, status, logs, templates) works
65
+ before verification.
66
+
67
+ For long-running automation mint a key once the account is verified:
68
+ `maritime keys create --name <purpose> --json` returns `raw_key` (`mk_...`,
69
+ shown once, never expires). Export it as `MARITIME_TOKEN`.
70
+
71
+ `MARITIME_API_URL` overrides the API base (default `https://api.maritime.sh`).
72
+
73
+ ## Deploy
74
+
75
+ Pick the recipe that matches what the user has.
76
+
77
+ ### A ready-made agent from a template
78
+
79
+ ```bash
80
+ maritime templates --json # ids: openclaw, hermes, zeroclaw, claude_code, codex, dsh
81
+ maritime create my-agent --template openclaw --json
82
+ maritime status my-agent --json # poll until .status is "active"
83
+ maritime chat my-agent "introduce yourself" --json | jq -r '.response'
84
+ ```
85
+
86
+ Most templates need no model key (Maritime's metered LLM proxy). `claude_code`
87
+ is the exception: it needs `ANTHROPIC_API_KEY` as a secret env var.
88
+
89
+ ### The user's own code (any framework, Dockerfile at the repo root)
90
+
91
+ ```bash
92
+ maritime create my-bot --repo https://github.com/you/agent --json
93
+ maritime status my-bot --json # builds take 1 to 3 minutes
94
+ maritime logs my-bot --json
95
+ ```
96
+
97
+ The container contract: listen on `0.0.0.0:$PORT` (injected, never hardcode
98
+ 8080), answer `GET /health` with any 2xx, answer `POST /chat` with JSON
99
+ `{"message": "..."}` within 30 seconds returning text or JSON with one of
100
+ `response`, `reply`, `message`, `text`, `output`. Persist under `/data` only.
101
+ Never use a shell-string `CMD`; launch a real program. Full contract:
102
+ https://maritime.sh/docs/frameworks/custom.md
103
+
104
+ Private GitHub repos need the Maritime GitHub App installed from the
105
+ dashboard. Pre-built public images: `POST /api/agents` with
106
+ `{"framework": "custom", "imageName": "ghcr.io/acme/img:tag"}`.
107
+
108
+ ### A public web app on its own HTTPS URL
109
+
110
+ ```bash
111
+ maritime create my-app --repo https://github.com/you/app --public --port 3000 --json
112
+ ```
113
+
114
+ It sleeps when idle and wakes on the next visit.
115
+
116
+ ### Secrets and env vars
117
+
118
+ ```bash
119
+ maritime env set my-agent OPENAI_API_KEY=sk-... --reload --json # secret by default
120
+ maritime env import my-agent ./prod.env --reload --json
121
+ ```
122
+
123
+ Without `--reload` the change applies on the next boot.
124
+
125
+ ### Schedules
126
+
127
+ Timers inside a sleeping VM do not fire. Use platform triggers:
128
+
129
+ ```bash
130
+ maritime triggers create my-agent --type cron --cron "0 9 * * *" --json
131
+ ```
132
+
133
+ ### One agent per end user, from a backend
134
+
135
+ Use the SDK instead of the CLI: `npm install maritime-sdk` or
136
+ `pip install maritime`, key in `MARITIME_API_KEY`. `provision({externalId})`
137
+ is idempotent. Docs: https://maritime.sh/docs/build.md
138
+
139
+ ### A persistent desktop for an existing agent (Computers, paid plan)
140
+
141
+ One MCP server, one Linux desktop per end user id:
142
+
143
+ ```bash
144
+ claude mcp add --transport http maritime-computers https://mcp.maritime.sh/mcp \
145
+ --header "Authorization: Bearer mk_..."
146
+ ```
147
+
148
+ Docs: https://maritime.sh/docs/computers.md
149
+
150
+ ## Verify before you finish
151
+
152
+ 1. `maritime status <agent> --json` reports `active` (or `sleeping` after
153
+ idle; both are healthy).
154
+ 2. `maritime chat <agent> "hello" --json` returns a reply, or for a custom
155
+ container `maritime logs <agent> --json` shows the server listening.
156
+ 3. Tell the user the agent name, the dashboard URL
157
+ `https://maritime.sh/agents`, and what you changed in their repo.
158
+
159
+ ## Inspect and repair
160
+
161
+ ```bash
162
+ maritime list --json
163
+ maritime info my-agent --json # env count, triggers, last deploy
164
+ maritime history my-agent --json # build and deploy attempts with buildLog
165
+ maritime exec my-agent ls /data --json | jq -r '.stdout'
166
+ maritime restart my-agent --json # also picks up new env vars
167
+ maritime delete my-agent --yes --json # --yes is required non-interactively
168
+ ```
169
+
170
+ `error.code` `agent_unavailable` on chat means the agent is not running:
171
+ `maritime start <agent>`, wait a few seconds, retry. A 404 on exec or files
172
+ usually means the agent is asleep or errored: start it, do not recreate it.
173
+
174
+ ## Reference
175
+
176
+ - Contract file: https://maritime.sh/docs/cli/llms.txt
177
+ - Setup procedure for agents: https://maritime.sh/agents.md
178
+ - Everything: https://maritime.sh/llms.txt (index) and https://maritime.sh/llms-full.txt
179
+ - REST API: https://api.maritime.sh/openapi.json (bearer `mk_` key)
180
+ - Any docs page as markdown: append `.md` to its URL, for example
181
+ https://maritime.sh/docs/quickstart.md
package/dist/api.js CHANGED
@@ -143,7 +143,13 @@ async function handleResponse(response) {
143
143
  const detail = typeof payload.detail === 'string'
144
144
  ? payload.detail
145
145
  : `Request failed with status ${response.status}`;
146
- const code = typeof payload.code === 'string' ? payload.code : undefined;
146
+ // `code` is Maritime's own field; `error` is the RFC 8628 shape the
147
+ // device-login endpoints answer with ({"error": "authorization_pending"}).
148
+ const code = typeof payload.code === 'string'
149
+ ? payload.code
150
+ : typeof payload.error === 'string'
151
+ ? payload.error
152
+ : undefined;
147
153
  throw new CliHttpError(response.status, detail, code);
148
154
  }
149
155
  return payload;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Reads a file shipped at the package root (the `files` list in package.json),
3
+ * such as AGENTS.md or SKILL.md.
4
+ *
5
+ * Works from both the built layout (dist/bundled.js, one level below the
6
+ * root) and the tsx dev layout (src/bundled.ts). Returns null when the file
7
+ * was not shipped.
8
+ *
9
+ * @param name The file name at the package root.
10
+ */
11
+ export declare function readBundledFile(name: string): string | null;
@@ -0,0 +1,25 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, join } from 'node:path';
4
+ const __dirname = dirname(fileURLToPath(import.meta.url));
5
+ /**
6
+ * Reads a file shipped at the package root (the `files` list in package.json),
7
+ * such as AGENTS.md or SKILL.md.
8
+ *
9
+ * Works from both the built layout (dist/bundled.js, one level below the
10
+ * root) and the tsx dev layout (src/bundled.ts). Returns null when the file
11
+ * was not shipped.
12
+ *
13
+ * @param name The file name at the package root.
14
+ */
15
+ export function readBundledFile(name) {
16
+ for (const rel of [['..', name], ['..', '..', name]]) {
17
+ try {
18
+ return readFileSync(join(__dirname, ...rel), 'utf-8');
19
+ }
20
+ catch {
21
+ // try the next candidate
22
+ }
23
+ }
24
+ return null;
25
+ }
@@ -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
@@ -43,16 +40,7 @@ function serializeCommand(cmd) {
43
40
  }
44
41
  /* eslint-enable @typescript-eslint/no-explicit-any */
45
42
  function readBundledGuide() {
46
- // dist/commands/guide.js → package root is two levels up.
47
- for (const rel of [['..', '..', 'AGENTS.md'], ['..', '..', '..', 'AGENTS.md']]) {
48
- try {
49
- return readFileSync(join(__dirname, ...rel), 'utf-8');
50
- }
51
- catch {
52
- // try next candidate
53
- }
54
- }
55
- return null;
43
+ return readBundledFile('AGENTS.md');
56
44
  }
57
45
  export const guideCommand = new Command('guide')
58
46
  .alias('agent-guide')
@@ -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();
@@ -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 { EXIT, fail, handleError, makeSpinner, outputResult } 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,14 +99,125 @@ 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
+ }
78
221
  /**
79
222
  * Asks the server to send the email verification link again.
80
223
  *
@@ -104,13 +247,14 @@ export const loginCommand = new Command('login')
104
247
  .option('-e, --email <email>', 'Email address (for non-interactive login)')
105
248
  .option('-p, --password <password>', 'Password (for non-interactive login)')
106
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`)
107
251
  .option('--resend', 'Send the email verification link again (uses -e, else the logged-in email)')
108
252
  .action(async (opts) => {
109
253
  if (opts.resend) {
110
254
  await resendVerification(opts.email);
111
255
  return;
112
256
  }
113
- // 1. Token paste — the universal path. Works for any account, including
257
+ // 1. Token paste: the universal path. Works for any account, including
114
258
  // OAuth-only (Google/GitHub) users who have no password to type.
115
259
  // Generate one at <app>/cli/auth.
116
260
  if (opts.token) {
@@ -133,7 +277,7 @@ export const loginCommand = new Command('login')
133
277
  return;
134
278
  }
135
279
  // 2. Email/password (non-interactive). OAuth-only accounts have no
136
- // password — they get pointed at the browser / token flow below.
280
+ // password, so they get pointed at the browser / token flow below.
137
281
  if (opts.email || opts.password) {
138
282
  if (opts.password) {
139
283
  console.log(chalk.yellow('Warning:') +
@@ -162,7 +306,7 @@ export const loginCommand = new Command('login')
162
306
  catch (error) {
163
307
  spinner.fail('Authentication failed');
164
308
  if (error instanceof CliHttpError) {
165
- // 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
166
310
  // actually works for them instead of the raw "oauth_only:google".
167
311
  if (error.detail.startsWith('oauth_only:')) {
168
312
  const providers = error.detail
@@ -173,6 +317,7 @@ export const loginCommand = new Command('login')
173
317
  ` this account signs in with ${chalk.bold(providers)}. There's no password to use here.`);
174
318
  console.log('\nAuthenticate one of these ways instead:');
175
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'));
176
321
  console.log(' ' + chalk.bold('maritime login --token <token>') + chalk.dim(` paste a token from ${APP_URL}/cli/auth`));
177
322
  process.exitCode = 2;
178
323
  return;
@@ -185,7 +330,13 @@ export const loginCommand = new Command('login')
185
330
  }
186
331
  return;
187
332
  }
188
- // 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.
189
340
  const spinner = await makeSpinner('Opening browser for authentication...');
190
341
  try {
191
342
  const token = await browserLogin();
@@ -197,11 +348,19 @@ export const loginCommand = new Command('login')
197
348
  spinner.succeed(chalk.green('Authenticated as ') + chalk.bold(payload.email || 'your account'));
198
349
  }
199
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
+ }
200
357
  spinner.fail('Authentication failed');
201
358
  if (error instanceof Error) {
202
359
  console.log(chalk.red('Error:') + ` ${error.message}`);
203
360
  }
204
361
  console.log(chalk.dim('\nOn a headless / SSH box? Run ') +
362
+ chalk.bold('maritime login --device') +
363
+ chalk.dim(' or ') +
205
364
  chalk.bold('maritime login --token <token>') +
206
365
  chalk.dim(` with a token from ${APP_URL}/cli/auth`));
207
366
  process.exitCode = 1;
@@ -1,45 +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.'));
34
- console.log(`Verify your email to deploy: we sent a link to ${auth.user.email}.`);
35
45
  }
36
46
  catch (error) {
37
47
  spinner.fail('Signup failed');
38
48
  if (error instanceof CliHttpError) {
39
- console.log(chalk.red('Error:') + ` ${error.detail}`);
40
- process.exitCode = error.status >= 500 ? 1 : 2;
41
- 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
+ });
42
54
  }
43
- throw error;
55
+ handleError(error);
44
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
+ });
45
72
  });
package/dist/index.js CHANGED
@@ -57,6 +57,7 @@ program
57
57
  const HIDDEN = { hidden: true };
58
58
  // Auth
59
59
  program.addCommand(loginCommand);
60
+ program.addCommand(signupCommand);
60
61
  program.addCommand(logoutCommand);
61
62
  program.addCommand(whoamiCommand);
62
63
  program.addCommand(keysCommand);
@@ -81,7 +82,6 @@ program.addCommand(guideCommand);
81
82
  // surface small. Lifecycle is mostly automatic (idle-sleep + auto-wake on
82
83
  // chat), so these are ops/debug + power-user/reseller tools, not the happy
83
84
  // path. They still work exactly as before; `maritime <cmd> --help` shows them. ---
84
- program.addCommand(signupCommand, HIDDEN);
85
85
  program.addCommand(startCommand, HIDDEN);
86
86
  program.addCommand(stopCommand, HIDDEN);
87
87
  program.addCommand(restartCommand, HIDDEN);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maritime-cli",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Maritime CLI - Deploy and talk to AI agents from your terminal",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -21,7 +21,8 @@
21
21
  },
22
22
  "files": [
23
23
  "dist",
24
- "AGENTS.md"
24
+ "AGENTS.md",
25
+ "SKILL.md"
25
26
  ],
26
27
  "engines": {
27
28
  "node": ">=20.12"