maritime-cli 0.2.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/AGENTS.md +182 -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 +138 -54
  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 +90 -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 +86 -10
  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
package/AGENTS.md ADDED
@@ -0,0 +1,182 @@
1
+ # Maritime CLI — machine interface
2
+
3
+ This document is the contract for driving the `maritime` CLI from a program or
4
+ an AI agent (not a human at a keyboard). It is safe to paste into an agent's
5
+ system prompt as a tool spec.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i -g maritime-cli
11
+ maritime --version
12
+ ```
13
+
14
+ ## Authentication (non-interactive)
15
+
16
+ The CLI reads a bearer token from the `MARITIME_TOKEN` environment variable
17
+ before anything else. An agent must set this and never run the interactive
18
+ `login` flow.
19
+
20
+ Prefer a **long-lived API key** (`mk_…`) over the JWT from `maritime login`,
21
+ which expires. Mint one once as a human:
22
+
23
+ ```bash
24
+ maritime login # human, one time
25
+ maritime keys create --name my-agent --json
26
+ # → { "key": "mk_...", ... } (shown ONCE — store it)
27
+ ```
28
+
29
+ Then give the agent only the key:
30
+
31
+ ```bash
32
+ export MARITIME_TOKEN=mk_xxxxxxxxxxxxxxxxxxxxxxxx
33
+ ```
34
+
35
+ `mk_` keys do not expire. Rotate with `maritime keys list` / `maritime keys revoke <id>`.
36
+
37
+ ## Output contract — always pass `--json`
38
+
39
+ With `--json`, every command obeys a strict contract:
40
+
41
+ | Channel | On success | On failure |
42
+ |---|---|---|
43
+ | **stdout** | a single JSON value, nothing else | empty |
44
+ | **stderr** | empty | a single JSON error object |
45
+ | **exit code** | `0` | non-zero (see below) |
46
+
47
+ The failure object is:
48
+
49
+ ```json
50
+ { "ok": false, "error": { "code": "not_authenticated", "message": "…", "status": 401 } }
51
+ ```
52
+
53
+ Always read stdout for results and branch on the exit code. Never parse human text.
54
+
55
+ ### Exit codes
56
+
57
+ | Code | Meaning |
58
+ |---|---|
59
+ | `0` | success |
60
+ | `1` | generic error (request failed, server error, network) |
61
+ | `2` | auth error (not logged in, token expired/invalid) |
62
+ | `3` | not found (no such agent) |
63
+ | `4` | usage error (missing/invalid arguments) |
64
+
65
+ ## The interaction primitive — `chat`
66
+
67
+ Send a message to a deployed agent and get its reply. Sleeping serverless
68
+ agents are auto-woken by the backend.
69
+
70
+ ```bash
71
+ # message as argument
72
+ maritime chat <agent> "summarize today's incidents" --json
73
+
74
+ # message piped via stdin (best for long / multi-line prompts)
75
+ cat prompt.txt | maritime chat <agent> --json
76
+
77
+ # multi-turn: thread a conversation id
78
+ maritime chat <agent> "and the one before that?" --conversation-id abc123 --json
79
+ ```
80
+
81
+ `<agent>` is a name (exact match) or an ID prefix.
82
+
83
+ Success shape:
84
+
85
+ ```json
86
+ { "ok": true, "agentId": "…", "agentName": "…", "conversationId": null, "response": "…the agent's reply…" }
87
+ ```
88
+
89
+ Without `--json`, `chat` prints only the reply text on stdout (clean for piping).
90
+
91
+ ## Sizing (optional)
92
+
93
+ You don't size agents. `maritime create <name>` picks an applicable size for the
94
+ framework, and the agent auto-sleeps when idle and wakes on the next `chat`.
95
+
96
+ For hand-tuning one agent (e.g. a reseller dialing resources per client), `create`
97
+ accepts optional per-agent overrides. They're hidden from `--help` but fully
98
+ supported; omitted flags inherit the tier default.
99
+
100
+ ```bash
101
+ maritime create my-agent \
102
+ --ram 2048 \ # RAM in MB
103
+ --cpu 1.5 \ # vCPU cores (fractional OK)
104
+ --idle 600 \ # auto-sleep 600s after the last request
105
+ --disk 20 \ # workspace SSD in GB (clamped to the plan cap)
106
+ --max-compute 120 # hard cap: sleep after 120 compute-min / billing period
107
+ # …or keep it resident:
108
+ maritime create my-agent --always-on # never auto-sleep (mutually exclusive with --idle)
109
+ ```
110
+
111
+ `--idle`/`--always-on` control how long the agent stays up after a request —
112
+ this overrides the platform's default serverless idle cap, so an orchestrator
113
+ that dispatches a long job and waits for a webhook won't be slept out from under
114
+ the wait. `--disk` and `--max-compute` are per-agent overrides on top of the
115
+ owner's account plan (disk is clamped to the plan's storage cap; the compute cap
116
+ auto-sleeps the agent for the rest of the billing period when hit).
117
+ `status <agent> --json` echoes `memMb`, `vcpus`, `idleTtlSeconds`
118
+ (`0` = always-on, `null` = inherits tier), `diskMb`, and `computeMinutesLimit`.
119
+
120
+ ## Environment variables
121
+
122
+ Values are secret (encrypted) by default. Env changes apply on the next
123
+ container boot unless you `--reload` (hot-reload into the running container).
124
+
125
+ ```bash
126
+ # one or many at once
127
+ maritime env set <agent> OPENAI_API_KEY=sk-… LOG_LEVEL=debug --no-secret --json
128
+
129
+ # bulk upload a whole .env file (or pipe one via stdin), then hot-reload
130
+ maritime env import <agent> ./prod.env --reload --json
131
+ cat prod.env | maritime env import <agent> - --reload --json
132
+
133
+ maritime env list <agent> --json
134
+ maritime env remove <agent> OPENAI_API_KEY --reload --json
135
+ maritime env reload <agent> --json # hot-reload without changing values
136
+ ```
137
+
138
+ `import`/`set` return `{ok, uploaded:[…], failed:[{key,error}], reloaded}`.
139
+ A partial failure exits `1` with the failed keys listed in `failed`.
140
+
141
+ ## Command map
142
+
143
+ Auth / keys: `login`, `logout`, `whoami`, `keys {create,list,revoke}`
144
+ Lifecycle: `create`, `list`, `deploy`, `delete`
145
+ Interaction: `chat`/`send`
146
+ Config: `env {set,import,list,remove,reload}`
147
+ Observe: `status`, `logs`
148
+
149
+ Advanced / ops (hidden from `--help`, still fully supported): `start`, `stop`,
150
+ `restart`, `sleep`, `scale <tier>`, `exec <agent> <cmd...>`, `info`, `history`,
151
+ `triggers`, `blueprint`, `templates`. You rarely need these — lifecycle is
152
+ automatic (idle-sleep + auto-wake on `chat`).
153
+
154
+ Run `maritime <cmd> --help` for flags. Every command accepts the global
155
+ `--json` and `--verbose`.
156
+
157
+ ## Recipes
158
+
159
+ ```bash
160
+ # Is an agent healthy?
161
+ maritime status my-agent --json | jq -r '.status'
162
+
163
+ # Create, then talk to it
164
+ ID=$(maritime create researcher --template openclaw --json | jq -r '.id')
165
+ maritime chat "$ID" "introduce yourself" --json | jq -r '.response'
166
+
167
+ # Run a shell command inside the container
168
+ maritime exec my-agent ls /data --json | jq -r '.stdout'
169
+
170
+ # Tail recent error logs as JSON
171
+ maritime logs my-agent --level error --json
172
+ ```
173
+
174
+ ## Notes for agents
175
+
176
+ - `delete` refuses to run non-interactively without `--yes` (exit `4`); pass
177
+ `--yes` deliberately.
178
+ - `create` needs a name (positional `<name>`, or `--name`) when non-interactive (exit `4`).
179
+ - Non-2xx that the backend reports inside a body (e.g. agent not running for
180
+ `chat`) surfaces as `error.code = "agent_unavailable"`, exit `1`.
181
+ - The API base URL can be overridden with `MARITIME_API_URL` (default
182
+ `https://api.maritime.sh`).
package/dist/api.d.ts CHANGED
@@ -16,6 +16,7 @@ export interface CliAuthResponse {
16
16
  }
17
17
  export declare function getApiUrl(): string;
18
18
  export declare function requireAuth(): string;
19
+ export declare function isVerbose(): boolean;
19
20
  export declare function postJson<T>(path: string, body: JsonRecord): Promise<T>;
20
21
  export declare function authGet<T>(path: string): Promise<T>;
21
22
  export declare function authPost<T>(path: string, body?: JsonRecord): Promise<T>;
package/dist/api.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import chalk from 'chalk';
2
2
  import { config } from './config.js';
3
+ import { fail, EXIT } from './output.js';
3
4
  export class CliHttpError extends Error {
4
5
  status;
5
6
  detail;
@@ -19,14 +20,101 @@ export function getApiUrl() {
19
20
  process.env.NEXT_PUBLIC_API_URL ||
20
21
  'https://api.maritime.sh').replace(/\/+$/, '');
21
22
  }
23
+ // ---------------------------------------------------------------------------
24
+ // Token helpers
25
+ // ---------------------------------------------------------------------------
26
+ function decodeTokenPayload(token) {
27
+ try {
28
+ const parts = token.split('.');
29
+ if (parts.length !== 3)
30
+ return null;
31
+ return JSON.parse(Buffer.from(parts[1], 'base64url').toString());
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ function getTokenExpiry(token) {
38
+ const payload = decodeTokenPayload(token);
39
+ if (!payload || typeof payload.exp !== 'number')
40
+ return null;
41
+ return payload.exp * 1000; // convert to ms
42
+ }
43
+ function isTokenExpired(token) {
44
+ const exp = getTokenExpiry(token);
45
+ if (exp === null)
46
+ return false;
47
+ return Date.now() >= exp;
48
+ }
49
+ function isTokenExpiringSoon(token, thresholdMs = 7 * 24 * 60 * 60 * 1000) {
50
+ const exp = getTokenExpiry(token);
51
+ if (exp === null)
52
+ return false;
53
+ return Date.now() + thresholdMs >= exp;
54
+ }
55
+ async function maybeRefreshToken(token) {
56
+ if (!isTokenExpiringSoon(token))
57
+ return token;
58
+ try {
59
+ const url = `${getApiUrl()}/api/auth/cli-refresh`;
60
+ const response = await fetch(url, {
61
+ method: 'POST',
62
+ headers: {
63
+ Authorization: `Bearer ${token}`,
64
+ 'Content-Type': 'application/json',
65
+ },
66
+ });
67
+ if (!response.ok)
68
+ return token;
69
+ const data = (await response.json());
70
+ if (data.token) {
71
+ config.set('token', data.token);
72
+ if (data.user) {
73
+ config.set('user', data.user.email);
74
+ config.set('userId', data.user.id);
75
+ }
76
+ return data.token;
77
+ }
78
+ }
79
+ catch {
80
+ // Refresh failed silently — continue with current token
81
+ }
82
+ return token;
83
+ }
84
+ // ---------------------------------------------------------------------------
85
+ // Auth
86
+ // ---------------------------------------------------------------------------
22
87
  export function requireAuth() {
88
+ // 1. Check env var first (for CI/CD usage)
89
+ const envToken = process.env.MARITIME_TOKEN;
90
+ if (envToken)
91
+ return envToken;
92
+ // 2. Fall back to stored token
23
93
  const token = config.get('token');
24
94
  if (!token) {
25
- console.log(chalk.red('Not logged in.') + ' Run `maritime login` first.');
26
- process.exit(1);
95
+ fail('Not logged in. Run `maritime login`, or set the MARITIME_TOKEN env var.', {
96
+ code: 'not_authenticated',
97
+ exitCode: EXIT.AUTH,
98
+ });
99
+ }
100
+ // 3. Check expiry
101
+ if (isTokenExpired(token)) {
102
+ fail('Token expired. Run `maritime login` to re-authenticate, or set the MARITIME_TOKEN env var.', {
103
+ code: 'token_expired',
104
+ exitCode: EXIT.AUTH,
105
+ });
27
106
  }
28
107
  return token;
29
108
  }
109
+ // ---------------------------------------------------------------------------
110
+ // Verbose mode
111
+ // ---------------------------------------------------------------------------
112
+ export function isVerbose() {
113
+ return process.argv.includes('--verbose');
114
+ }
115
+ // ---------------------------------------------------------------------------
116
+ // HTTP client
117
+ // ---------------------------------------------------------------------------
30
118
  async function parseJson(response) {
31
119
  const text = await response.text();
32
120
  if (!text) {
@@ -51,15 +139,40 @@ async function handleResponse(response) {
51
139
  }
52
140
  async function requestJson(path, init) {
53
141
  const url = `${getApiUrl()}${path}`;
54
- let response;
55
- try {
56
- response = await fetch(url, init);
142
+ const verbose = isVerbose();
143
+ const start = verbose ? Date.now() : 0;
144
+ if (verbose) {
145
+ console.log(chalk.dim(` → ${init.method ?? 'GET'} ${url}`));
57
146
  }
58
- catch (error) {
59
- const detail = isErrorWithMessage(error) ? error.message : 'Unknown network error';
60
- throw new CliHttpError(0, `Unable to reach Maritime API at ${getApiUrl()}: ${detail}`);
147
+ let lastError;
148
+ const maxAttempts = 3;
149
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
150
+ try {
151
+ const response = await fetch(url, init);
152
+ if (verbose) {
153
+ console.log(chalk.dim(` ← ${response.status} (${Date.now() - start}ms)`));
154
+ }
155
+ // Retry on 503 (service unavailable)
156
+ if (response.status === 503 && attempt < maxAttempts) {
157
+ lastError = new CliHttpError(503, 'Service temporarily unavailable');
158
+ await new Promise((r) => setTimeout(r, 1000 * attempt));
159
+ continue;
160
+ }
161
+ return await handleResponse(response);
162
+ }
163
+ catch (error) {
164
+ // Only retry network errors, not HTTP errors
165
+ if (error instanceof CliHttpError)
166
+ throw error;
167
+ lastError = error;
168
+ if (attempt < maxAttempts) {
169
+ await new Promise((r) => setTimeout(r, 1000 * attempt));
170
+ continue;
171
+ }
172
+ }
61
173
  }
62
- return handleResponse(response);
174
+ const detail = isErrorWithMessage(lastError) ? lastError.message : 'Unknown network error';
175
+ throw new CliHttpError(0, `Unable to reach Maritime API at ${getApiUrl()}: ${detail}`);
63
176
  }
64
177
  export async function postJson(path, body) {
65
178
  return requestJson(path, {
@@ -75,14 +188,16 @@ function authHeaders(token) {
75
188
  };
76
189
  }
77
190
  export async function authGet(path) {
78
- const token = requireAuth();
191
+ let token = requireAuth();
192
+ token = await maybeRefreshToken(token);
79
193
  return requestJson(path, {
80
194
  method: 'GET',
81
195
  headers: authHeaders(token),
82
196
  });
83
197
  }
84
198
  export async function authPost(path, body = {}) {
85
- const token = requireAuth();
199
+ let token = requireAuth();
200
+ token = await maybeRefreshToken(token);
86
201
  return requestJson(path, {
87
202
  method: 'POST',
88
203
  headers: authHeaders(token),
@@ -90,7 +205,8 @@ export async function authPost(path, body = {}) {
90
205
  });
91
206
  }
92
207
  export async function authPut(path, body = {}) {
93
- const token = requireAuth();
208
+ let token = requireAuth();
209
+ token = await maybeRefreshToken(token);
94
210
  return requestJson(path, {
95
211
  method: 'PUT',
96
212
  headers: authHeaders(token),
@@ -98,7 +214,8 @@ export async function authPut(path, body = {}) {
98
214
  });
99
215
  }
100
216
  export async function authDelete(path) {
101
- const token = requireAuth();
217
+ let token = requireAuth();
218
+ token = await maybeRefreshToken(token);
102
219
  return requestJson(path, {
103
220
  method: 'DELETE',
104
221
  headers: authHeaders(token),
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const blueprintCommand: Command;
@@ -0,0 +1,93 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import ora from 'ora';
4
+ import { authGet, authPost } from '../api.js';
5
+ import { resolveAgent } from '../resolve.js';
6
+ import { isJsonMode, outputJson, handleError } from '../output.js';
7
+ const blueprintListCmd = new Command('list')
8
+ .description('List your blueprints')
9
+ .action(async () => {
10
+ try {
11
+ const blueprints = await authGet('/api/blueprints');
12
+ if (isJsonMode()) {
13
+ outputJson(blueprints);
14
+ return;
15
+ }
16
+ if (blueprints.length === 0) {
17
+ console.log(chalk.dim('No blueprints found.'));
18
+ return;
19
+ }
20
+ console.log('\n ' +
21
+ chalk.dim('NAME'.padEnd(24)) +
22
+ chalk.dim('STATUS'.padEnd(12)) +
23
+ chalk.dim('VISIBILITY'.padEnd(14)) +
24
+ chalk.dim('FRAMEWORK'));
25
+ console.log(chalk.dim(' ' + '\u2500'.repeat(62)));
26
+ for (const bp of blueprints) {
27
+ console.log(' ' +
28
+ chalk.bold(bp.name.padEnd(24)) +
29
+ bp.status.padEnd(12) +
30
+ bp.visibility.padEnd(14) +
31
+ bp.framework);
32
+ }
33
+ console.log();
34
+ }
35
+ catch (error) {
36
+ handleError(error);
37
+ }
38
+ });
39
+ const blueprintCreateCmd = new Command('create')
40
+ .description('Create a blueprint from an agent')
41
+ .argument('<agent>', 'Agent name or ID')
42
+ .option('--name <name>', 'Blueprint name')
43
+ .option('--visibility <vis>', 'Visibility (private, unlisted, public)', 'private')
44
+ .action(async (agentArg, opts) => {
45
+ try {
46
+ const agent = await resolveAgent(agentArg);
47
+ const spinner = ora('Creating blueprint...').start();
48
+ const blueprint = await authPost('/api/blueprints', {
49
+ agentId: agent.id,
50
+ name: opts.name || agent.name,
51
+ visibility: opts.visibility,
52
+ });
53
+ spinner.succeed(chalk.green('Blueprint created: ') + chalk.bold(blueprint.name));
54
+ if (isJsonMode()) {
55
+ outputJson(blueprint);
56
+ }
57
+ else {
58
+ console.log(chalk.dim(` ID: ${blueprint.id}`));
59
+ }
60
+ }
61
+ catch (error) {
62
+ handleError(error);
63
+ }
64
+ });
65
+ const blueprintDeployCmd = new Command('deploy')
66
+ .description('Deploy a new agent from a blueprint')
67
+ .argument('<slug>', 'Blueprint slug or ID')
68
+ .option('--name <name>', 'Name for the new agent')
69
+ .action(async (slug, opts) => {
70
+ try {
71
+ const spinner = ora('Deploying from blueprint...').start();
72
+ const body = {};
73
+ if (opts.name)
74
+ body.name = opts.name;
75
+ const result = await authPost(`/api/marketplace/${encodeURIComponent(slug)}/deploy`, body);
76
+ spinner.succeed(chalk.green('Agent created: ') + chalk.bold(result.name));
77
+ if (isJsonMode()) {
78
+ outputJson(result);
79
+ }
80
+ else {
81
+ console.log(chalk.dim(` Agent ID: ${result.agentId}`));
82
+ }
83
+ }
84
+ catch (error) {
85
+ handleError(error);
86
+ }
87
+ });
88
+ export const blueprintCommand = new Command('blueprint')
89
+ .alias('bp')
90
+ .description('Manage blueprints')
91
+ .addCommand(blueprintListCmd)
92
+ .addCommand(blueprintCreateCmd)
93
+ .addCommand(blueprintDeployCmd);
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const chatCommand: Command;
@@ -0,0 +1,93 @@
1
+ import { Command } from 'commander';
2
+ import { authPost } from '../api.js';
3
+ import { resolveAgent } from '../resolve.js';
4
+ import { outputResult, fail, handleError, makeSpinner } from '../output.js';
5
+ /** Read all of stdin (used when the message isn't passed as an argument). */
6
+ function readStdin() {
7
+ return new Promise((resolve) => {
8
+ let data = '';
9
+ process.stdin.setEncoding('utf8');
10
+ process.stdin.on('data', (chunk) => {
11
+ data += chunk;
12
+ });
13
+ process.stdin.on('end', () => resolve(data));
14
+ process.stdin.on('error', () => resolve(data));
15
+ });
16
+ }
17
+ /**
18
+ * The agent gateway's reply may be a plain string or a nested object
19
+ * ({response}, {message}, {text}, ...). Normalize to the human-readable text.
20
+ */
21
+ function extractReply(response) {
22
+ if (response == null)
23
+ return '';
24
+ if (typeof response === 'string')
25
+ return response;
26
+ if (typeof response === 'object') {
27
+ const obj = response;
28
+ for (const key of ['response', 'message', 'text', 'content', 'output']) {
29
+ if (typeof obj[key] === 'string')
30
+ return obj[key];
31
+ }
32
+ return JSON.stringify(response);
33
+ }
34
+ return String(response);
35
+ }
36
+ export const chatCommand = new Command('chat')
37
+ .alias('send')
38
+ .description('Send a message to an agent and print its reply')
39
+ .argument('<agent>', 'Agent name or ID')
40
+ .argument('[message...]', 'Message to send (reads stdin if omitted)')
41
+ .option('-c, --conversation-id <id>', 'Conversation ID for multi-turn context')
42
+ .addHelpText('after', `
43
+ Examples:
44
+ maritime chat my-agent "what's the status?" --json
45
+ cat prompt.txt | maritime chat my-agent --json
46
+ maritime chat my-agent "and then?" --conversation-id abc123`)
47
+ .action(async (agentArg, messageParts, opts) => {
48
+ try {
49
+ // Message comes from args, or stdin when piped (great for long prompts).
50
+ let message = (messageParts || []).join(' ').trim();
51
+ if (!message && !process.stdin.isTTY) {
52
+ message = (await readStdin()).trim();
53
+ }
54
+ if (!message) {
55
+ fail('No message provided. Pass it as an argument or pipe it via stdin.', {
56
+ code: 'usage',
57
+ exitCode: 4,
58
+ });
59
+ }
60
+ const agent = await resolveAgent(agentArg);
61
+ const spinner = await makeSpinner(`Waiting for ${agent.name}...`);
62
+ let result;
63
+ try {
64
+ result = await authPost(`/api/agents/${agent.id}/chat`, {
65
+ message,
66
+ conversation_id: opts.conversationId,
67
+ });
68
+ }
69
+ catch (error) {
70
+ spinner.fail('Chat failed');
71
+ throw error;
72
+ }
73
+ spinner.stop();
74
+ // Backend surfaces upstream problems (e.g. agent not running) as `error`.
75
+ if (result.error) {
76
+ fail(result.error, { code: 'agent_unavailable' });
77
+ }
78
+ const reply = extractReply(result.response);
79
+ outputResult({
80
+ ok: true,
81
+ agentId: agent.id,
82
+ agentName: agent.name,
83
+ conversationId: opts.conversationId ?? null,
84
+ response: reply,
85
+ }, () => {
86
+ // Plain text on stdout — clean for piping into another tool.
87
+ process.stdout.write(reply + (reply.endsWith('\n') ? '' : '\n'));
88
+ });
89
+ }
90
+ catch (error) {
91
+ handleError(error);
92
+ }
93
+ });