maritime-cli 1.8.0 → 2.0.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 (79) hide show
  1. package/README.md +17 -0
  2. package/bin/maritime.js +40 -0
  3. package/install.js +118 -0
  4. package/package.json +22 -36
  5. package/AGENTS.md +0 -309
  6. package/dist/api.d.ts +0 -30
  7. package/dist/api.js +0 -240
  8. package/dist/commands/chat.d.ts +0 -2
  9. package/dist/commands/chat.js +0 -120
  10. package/dist/commands/create.d.ts +0 -2
  11. package/dist/commands/create.js +0 -310
  12. package/dist/commands/delete.d.ts +0 -2
  13. package/dist/commands/delete.js +0 -43
  14. package/dist/commands/deploy.d.ts +0 -2
  15. package/dist/commands/deploy.js +0 -180
  16. package/dist/commands/env.d.ts +0 -2
  17. package/dist/commands/env.js +0 -368
  18. package/dist/commands/exec.d.ts +0 -2
  19. package/dist/commands/exec.js +0 -31
  20. package/dist/commands/guide.d.ts +0 -2
  21. package/dist/commands/guide.js +0 -87
  22. package/dist/commands/history.d.ts +0 -2
  23. package/dist/commands/history.js +0 -56
  24. package/dist/commands/info.d.ts +0 -2
  25. package/dist/commands/info.js +0 -78
  26. package/dist/commands/init.d.ts +0 -2
  27. package/dist/commands/init.js +0 -114
  28. package/dist/commands/keys.d.ts +0 -2
  29. package/dist/commands/keys.js +0 -90
  30. package/dist/commands/link.d.ts +0 -4
  31. package/dist/commands/link.js +0 -65
  32. package/dist/commands/list.d.ts +0 -2
  33. package/dist/commands/list.js +0 -55
  34. package/dist/commands/login.d.ts +0 -2
  35. package/dist/commands/login.js +0 -209
  36. package/dist/commands/logout.d.ts +0 -2
  37. package/dist/commands/logout.js +0 -12
  38. package/dist/commands/logs.d.ts +0 -2
  39. package/dist/commands/logs.js +0 -89
  40. package/dist/commands/message.d.ts +0 -8
  41. package/dist/commands/message.js +0 -75
  42. package/dist/commands/open.d.ts +0 -2
  43. package/dist/commands/open.js +0 -25
  44. package/dist/commands/restart.d.ts +0 -2
  45. package/dist/commands/restart.js +0 -26
  46. package/dist/commands/signup.d.ts +0 -2
  47. package/dist/commands/signup.js +0 -45
  48. package/dist/commands/sleep.d.ts +0 -2
  49. package/dist/commands/sleep.js +0 -22
  50. package/dist/commands/start.d.ts +0 -2
  51. package/dist/commands/start.js +0 -27
  52. package/dist/commands/status.d.ts +0 -2
  53. package/dist/commands/status.js +0 -69
  54. package/dist/commands/stop.d.ts +0 -2
  55. package/dist/commands/stop.js +0 -26
  56. package/dist/commands/templates.d.ts +0 -2
  57. package/dist/commands/templates.js +0 -40
  58. package/dist/commands/triggers.d.ts +0 -2
  59. package/dist/commands/triggers.js +0 -89
  60. package/dist/commands/whoami.d.ts +0 -2
  61. package/dist/commands/whoami.js +0 -76
  62. package/dist/config.d.ts +0 -2
  63. package/dist/config.js +0 -14
  64. package/dist/context.d.ts +0 -39
  65. package/dist/context.js +0 -110
  66. package/dist/index.d.ts +0 -2
  67. package/dist/index.js +0 -186
  68. package/dist/interactive.d.ts +0 -1
  69. package/dist/interactive.js +0 -66
  70. package/dist/output.d.ts +0 -80
  71. package/dist/output.js +0 -176
  72. package/dist/prompt.d.ts +0 -2
  73. package/dist/prompt.js +0 -62
  74. package/dist/resolve.d.ts +0 -16
  75. package/dist/resolve.js +0 -59
  76. package/dist/version-check.d.ts +0 -20
  77. package/dist/version-check.js +0 -81
  78. package/dist/websocket.d.ts +0 -22
  79. package/dist/websocket.js +0 -89
package/dist/api.js DELETED
@@ -1,240 +0,0 @@
1
- import chalk from 'chalk';
2
- import { config } from './config.js';
3
- import { fail, EXIT } from './output.js';
4
- export class CliHttpError extends Error {
5
- status;
6
- detail;
7
- /** Machine-readable error code from the server when present, e.g.
8
- * 'seat_limit' when the account hit its plan's agent cap, needs a paid
9
- * plan for an add-on, or has a lapsed plan. */
10
- code;
11
- constructor(status, detail, code) {
12
- super(detail);
13
- this.status = status;
14
- this.detail = detail;
15
- this.code = code;
16
- }
17
- }
18
- function isErrorWithMessage(error) {
19
- return typeof error === 'object' && error !== null && 'message' in error;
20
- }
21
- export function getApiUrl() {
22
- const stored = config.get('apiUrl');
23
- return (stored ||
24
- process.env.MARITIME_API_URL ||
25
- process.env.NEXT_PUBLIC_API_URL ||
26
- 'https://api.maritime.sh').replace(/\/+$/, '');
27
- }
28
- // ---------------------------------------------------------------------------
29
- // Token helpers
30
- // ---------------------------------------------------------------------------
31
- function decodeTokenPayload(token) {
32
- try {
33
- const parts = token.split('.');
34
- if (parts.length !== 3)
35
- return null;
36
- return JSON.parse(Buffer.from(parts[1], 'base64url').toString());
37
- }
38
- catch {
39
- return null;
40
- }
41
- }
42
- function getTokenExpiry(token) {
43
- const payload = decodeTokenPayload(token);
44
- if (!payload || typeof payload.exp !== 'number')
45
- return null;
46
- return payload.exp * 1000; // convert to ms
47
- }
48
- function isTokenExpired(token) {
49
- const exp = getTokenExpiry(token);
50
- if (exp === null)
51
- return false;
52
- return Date.now() >= exp;
53
- }
54
- function isTokenExpiringSoon(token, thresholdMs = 7 * 24 * 60 * 60 * 1000) {
55
- const exp = getTokenExpiry(token);
56
- if (exp === null)
57
- return false;
58
- return Date.now() + thresholdMs >= exp;
59
- }
60
- async function maybeRefreshToken(token) {
61
- if (!isTokenExpiringSoon(token))
62
- return token;
63
- try {
64
- const url = `${getApiUrl()}/api/auth/cli-refresh`;
65
- const response = await fetch(url, {
66
- method: 'POST',
67
- headers: {
68
- Authorization: `Bearer ${token}`,
69
- 'Content-Type': 'application/json',
70
- },
71
- });
72
- if (!response.ok)
73
- return token;
74
- const data = (await response.json());
75
- if (data.token) {
76
- config.set('token', data.token);
77
- if (data.user) {
78
- config.set('user', data.user.email);
79
- config.set('userId', data.user.id);
80
- }
81
- return data.token;
82
- }
83
- }
84
- catch {
85
- // Refresh failed silently, continue with current token
86
- }
87
- return token;
88
- }
89
- // ---------------------------------------------------------------------------
90
- // Auth
91
- // ---------------------------------------------------------------------------
92
- export function requireAuth() {
93
- // 1. Check env var first (for CI/CD usage)
94
- const envToken = process.env.MARITIME_TOKEN;
95
- if (envToken)
96
- return envToken;
97
- // 2. Fall back to stored token
98
- const token = config.get('token');
99
- if (!token) {
100
- fail('Not logged in. Run `maritime login`, or set the MARITIME_TOKEN env var.', {
101
- code: 'not_authenticated',
102
- exitCode: EXIT.AUTH,
103
- });
104
- }
105
- // 3. Check expiry
106
- if (isTokenExpired(token)) {
107
- fail('Token expired. Run `maritime login` to re-authenticate, or set the MARITIME_TOKEN env var.', {
108
- code: 'token_expired',
109
- exitCode: EXIT.AUTH,
110
- });
111
- }
112
- return token;
113
- }
114
- // ---------------------------------------------------------------------------
115
- // Verbose mode
116
- // ---------------------------------------------------------------------------
117
- export function isVerbose() {
118
- return process.argv.includes('--verbose');
119
- }
120
- // ---------------------------------------------------------------------------
121
- // HTTP client
122
- // ---------------------------------------------------------------------------
123
- async function parseJson(response) {
124
- const text = await response.text();
125
- if (!text) {
126
- return {};
127
- }
128
- try {
129
- return JSON.parse(text);
130
- }
131
- catch {
132
- // A non-JSON body is almost always an edge/proxy error page (502/503
133
- // HTML, plain-text 500). Surface the status and a snippet so the
134
- // operator sees WHAT the server said instead of a bare parse failure.
135
- const snippet = text.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160);
136
- throw new CliHttpError(response.status, `Non-JSON response (HTTP ${response.status}) from ${response.url}` +
137
- (snippet ? `: ${snippet}` : ''));
138
- }
139
- }
140
- async function handleResponse(response) {
141
- const payload = await parseJson(response);
142
- if (!response.ok) {
143
- const detail = typeof payload.detail === 'string'
144
- ? payload.detail
145
- : `Request failed with status ${response.status}`;
146
- const code = typeof payload.code === 'string' ? payload.code : undefined;
147
- throw new CliHttpError(response.status, detail, code);
148
- }
149
- return payload;
150
- }
151
- async function requestJson(path, init) {
152
- const url = `${getApiUrl()}${path}`;
153
- const verbose = isVerbose();
154
- const start = verbose ? Date.now() : 0;
155
- if (verbose) {
156
- console.log(chalk.dim(` → ${init.method ?? 'GET'} ${url}`));
157
- }
158
- let lastError;
159
- const maxAttempts = 3;
160
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
161
- try {
162
- const response = await fetch(url, init);
163
- if (verbose) {
164
- console.log(chalk.dim(` ← ${response.status} (${Date.now() - start}ms)`));
165
- }
166
- // Retry on 503 (service unavailable)
167
- if (response.status === 503 && attempt < maxAttempts) {
168
- lastError = new CliHttpError(503, 'Service temporarily unavailable');
169
- await new Promise((r) => setTimeout(r, 1000 * attempt));
170
- continue;
171
- }
172
- return await handleResponse(response);
173
- }
174
- catch (error) {
175
- // Only retry network errors, not HTTP errors
176
- if (error instanceof CliHttpError)
177
- throw error;
178
- lastError = error;
179
- if (attempt < maxAttempts) {
180
- await new Promise((r) => setTimeout(r, 1000 * attempt));
181
- continue;
182
- }
183
- }
184
- }
185
- const detail = isErrorWithMessage(lastError) ? lastError.message : 'Unknown network error';
186
- throw new CliHttpError(0, `Unable to reach Maritime API at ${getApiUrl()}: ${detail}`);
187
- }
188
- export async function postJson(path, body) {
189
- return requestJson(path, {
190
- method: 'POST',
191
- headers: { 'Content-Type': 'application/json' },
192
- body: JSON.stringify(body),
193
- });
194
- }
195
- function authHeaders(token) {
196
- return {
197
- Authorization: `Bearer ${token}`,
198
- 'Content-Type': 'application/json',
199
- };
200
- }
201
- export async function authGet(path) {
202
- let token = requireAuth();
203
- token = await maybeRefreshToken(token);
204
- return requestJson(path, {
205
- method: 'GET',
206
- headers: authHeaders(token),
207
- });
208
- }
209
- export async function authPost(path, body = {}) {
210
- let token = requireAuth();
211
- token = await maybeRefreshToken(token);
212
- return requestJson(path, {
213
- method: 'POST',
214
- headers: authHeaders(token),
215
- body: JSON.stringify(body),
216
- });
217
- }
218
- export async function authPut(path, body = {}) {
219
- let token = requireAuth();
220
- token = await maybeRefreshToken(token);
221
- return requestJson(path, {
222
- method: 'PUT',
223
- headers: authHeaders(token),
224
- body: JSON.stringify(body),
225
- });
226
- }
227
- export async function authDelete(path) {
228
- let token = requireAuth();
229
- token = await maybeRefreshToken(token);
230
- return requestJson(path, {
231
- method: 'DELETE',
232
- headers: authHeaders(token),
233
- });
234
- }
235
- export async function publicGet(path) {
236
- return requestJson(path, {
237
- method: 'GET',
238
- headers: { 'Content-Type': 'application/json' },
239
- });
240
- }
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export declare const chatCommand: Command;
@@ -1,120 +0,0 @@
1
- import { Command } from 'commander';
2
- import { authPost } from '../api.js';
3
- import { resolveAgent } from '../resolve.js';
4
- import { getLinkedAgentId } from '../context.js';
5
- import { outputResult, fail, handleError, makeSpinner } from '../output.js';
6
- /** Read all of stdin (used when the message isn't passed as an argument). */
7
- function readStdin() {
8
- return new Promise((resolve) => {
9
- let data = '';
10
- const done = () => {
11
- // Release the handle so the process can exit the moment the command
12
- // finishes (a listening stdin would otherwise hold the event loop).
13
- process.stdin.pause();
14
- process.stdin.removeAllListeners('data');
15
- resolve(data);
16
- };
17
- process.stdin.setEncoding('utf8');
18
- process.stdin.on('data', (chunk) => {
19
- data += chunk;
20
- });
21
- process.stdin.once('end', done);
22
- process.stdin.once('error', done);
23
- });
24
- }
25
- /**
26
- * The agent gateway's reply may be a plain string or a nested object
27
- * ({response}, {message}, {text}, ...). Normalize to the human-readable text.
28
- */
29
- function extractReply(response) {
30
- if (response == null)
31
- return '';
32
- if (typeof response === 'string')
33
- return response;
34
- if (typeof response === 'object') {
35
- const obj = response;
36
- for (const key of ['response', 'message', 'text', 'content', 'output']) {
37
- if (typeof obj[key] === 'string')
38
- return obj[key];
39
- }
40
- return JSON.stringify(response);
41
- }
42
- return String(response);
43
- }
44
- export const chatCommand = new Command('chat')
45
- .alias('send')
46
- .description('Send a message to an agent and print its reply')
47
- .argument('[agent]', 'Agent name or ID (optional in a linked directory)')
48
- .argument('[message...]', 'Message to send (reads stdin if omitted)')
49
- .option('-a, --agent <name>', 'Target a specific agent (overrides the linked one)')
50
- .option('-c, --conversation-id <id>', 'Conversation ID for multi-turn context')
51
- .addHelpText('after', `
52
- Examples:
53
- maritime chat "what's the status?" # linked agent
54
- maritime chat my-agent "what's the status?" # explicit agent
55
- cat prompt.txt | maritime chat --json # linked agent, long prompt
56
- maritime chat -a other "and then?" --conversation-id abc123`)
57
- .action(async (agentPos, messageParts, opts) => {
58
- try {
59
- // Disambiguate "which agent" vs "the message" using the linked context:
60
- // in a linked dir all positionals are the message (target = linked agent,
61
- // overridable with -a); otherwise the first positional is the agent.
62
- const positionals = [agentPos, ...(messageParts || [])].filter(Boolean);
63
- let targetArg;
64
- let message;
65
- if (opts.agent) {
66
- targetArg = opts.agent;
67
- message = positionals.join(' ');
68
- }
69
- else if (getLinkedAgentId()) {
70
- targetArg = undefined;
71
- message = positionals.join(' ');
72
- }
73
- else {
74
- targetArg = agentPos;
75
- message = (messageParts || []).join(' ');
76
- }
77
- message = message.trim();
78
- if (!message && !process.stdin.isTTY) {
79
- message = (await readStdin()).trim();
80
- }
81
- if (!message) {
82
- fail('No message provided. Pass it as an argument or pipe it via stdin.', {
83
- code: 'usage',
84
- exitCode: 4,
85
- });
86
- }
87
- const agent = await resolveAgent(targetArg);
88
- const spinner = await makeSpinner(`Waiting for ${agent.name}...`);
89
- let result;
90
- try {
91
- result = await authPost(`/api/agents/${agent.id}/chat`, {
92
- message,
93
- conversation_id: opts.conversationId,
94
- });
95
- }
96
- catch (error) {
97
- spinner.fail('Chat failed');
98
- throw error;
99
- }
100
- spinner.stop();
101
- // Backend surfaces upstream problems (e.g. agent not running) as `error`.
102
- if (result.error) {
103
- fail(result.error, { code: 'agent_unavailable' });
104
- }
105
- const reply = extractReply(result.response);
106
- outputResult({
107
- ok: true,
108
- agentId: agent.id,
109
- agentName: agent.name,
110
- conversationId: opts.conversationId ?? null,
111
- response: reply,
112
- }, () => {
113
- // Plain text on stdout — clean for piping into another tool.
114
- process.stdout.write(reply + (reply.endsWith('\n') ? '' : '\n'));
115
- });
116
- }
117
- catch (error) {
118
- handleError(error);
119
- }
120
- });
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export declare const createCommand: Command;
@@ -1,310 +0,0 @@
1
- import { Command, Option } from 'commander';
2
- import chalk from 'chalk';
3
- import { authGet, authPost, CliHttpError } from '../api.js';
4
- import { promptForValue } from '../prompt.js';
5
- import { isJsonMode, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
6
- const BATCH_CAP = 50;
7
- function parseEnvPairs(pairs) {
8
- return pairs.map((pair) => {
9
- const eqIdx = pair.indexOf('=');
10
- if (eqIdx <= 0) {
11
- fail(`Invalid env var format: "${pair}". Use KEY=value.`, {
12
- code: 'usage',
13
- exitCode: EXIT.USAGE,
14
- });
15
- }
16
- return {
17
- key: pair.slice(0, eqIdx),
18
- value: pair.slice(eqIdx + 1),
19
- isSecret: true,
20
- };
21
- });
22
- }
23
- export const createCommand = new Command('create')
24
- .description('Create a new agent')
25
- .argument('[name]', 'Agent name')
26
- .option('-t, --template <template>', 'Template to base the agent on (see `maritime templates`)')
27
- .option('-e, --env <pairs...>', 'Environment variables (KEY=value)')
28
- .option('--count <n>', 'Spin up N identical agents in one call. Names become <name>-1..<name>-N')
29
- .option('-r, --repo <url>', 'Deploy from a GitHub repo (must contain a Dockerfile)')
30
- .option('-b, --branch <branch>', 'Git branch to deploy (with --repo)')
31
- .option('--public', 'Serve a public, no-login web URL for this agent (web apps)')
32
- .option('--port <n>', 'Port your app listens on (exposed publicly; default 8080)')
33
- // Advanced overrides, kept fully working but off the main --help so the
34
- // happy path stays flag-free. By default the platform picks the applicable
35
- // size for the framework and auto-sleeps when idle; you only reach for these
36
- // to hand-tune a specific agent (e.g. a reseller dialing RAM per client).
37
- .addOption(new Option('-n, --name <name>', 'Agent name (alias for the positional argument)').hideHelp())
38
- .addOption(new Option('--framework <framework>', 'Framework (default: custom)').hideHelp())
39
- .addOption(new Option('--ram <mb>', 'RAM in MB (2048 included; above that is a paid add-on)').hideHelp())
40
- .addOption(new Option('--cpu <cores>', 'vCPU cores, e.g. 0.5 or 2 (per-agent override)').hideHelp())
41
- .addOption(new Option('--idle <seconds>', 'Auto-sleep this many seconds after the last request').hideHelp())
42
- .addOption(new Option('--always-on', 'Never auto-sleep (a paid add-on; mutually exclusive with --idle)').hideHelp())
43
- .addOption(new Option('--disk <gb>', 'Workspace SSD size in GB (5 included; above that is a paid add-on)').hideHelp())
44
- .addHelpText('after', `
45
- Examples:
46
- maritime create researcher
47
- maritime create acme-bot --template openclaw --json
48
- maritime create my-app --repo https://github.com/you/app --public # public web agent
49
- maritime create client-x -e OPENAI_API_KEY=sk-...
50
- maritime create swarm --template openclaw --count 5 # swarm-1..swarm-5`)
51
- .action(async (nameArg, opts) => {
52
- try {
53
- let name = nameArg || opts.name;
54
- let templateId = opts.template;
55
- // --count: batch spin-up. 1 (default) = the classic single-agent path.
56
- let count = 1;
57
- if (opts.count !== undefined) {
58
- const n = Number(opts.count);
59
- if (!Number.isInteger(n) || n < 1) {
60
- fail('--count must be an integer between 1 and 50.', {
61
- code: 'usage',
62
- exitCode: EXIT.USAGE,
63
- });
64
- }
65
- if (n > BATCH_CAP) {
66
- fail('Batch creates are capped at 50 agents. Contact us if you need more. We keep the cap to protect shared server capacity.', { code: 'usage', exitCode: EXIT.USAGE });
67
- }
68
- count = n;
69
- }
70
- const interactive = !isJsonMode() && process.stdin.isTTY;
71
- // Interactive mode if no name given
72
- if (!name) {
73
- if (!interactive) {
74
- fail('Agent name is required. Pass --name <name>.', {
75
- code: 'usage',
76
- exitCode: EXIT.USAGE,
77
- });
78
- }
79
- name = await promptForValue('Agent name');
80
- if (!name) {
81
- fail('Agent name is required.', { code: 'usage', exitCode: EXIT.USAGE });
82
- }
83
- }
84
- // If no template specified interactively, show available templates
85
- if (interactive && !templateId && !opts.framework) {
86
- try {
87
- const templates = await authGet('/api/templates');
88
- if (templates.length > 0) {
89
- console.log(chalk.dim('\nAvailable templates:'));
90
- templates.forEach((t, i) => {
91
- console.log(` ${chalk.bold(String(i + 1))}. ${t.name} (${t.framework})${t.description ? ' · ' + t.description : ''}`);
92
- });
93
- console.log();
94
- const choice = await promptForValue('Template number (or press Enter to skip)');
95
- const idx = parseInt(choice, 10);
96
- if (idx >= 1 && idx <= templates.length) {
97
- templateId = templates[idx - 1].id;
98
- }
99
- }
100
- }
101
- catch {
102
- // Templates fetch failed; continue without template
103
- }
104
- }
105
- // ── Batch path (--count > 1): one POST /api/fleet/batch call ──
106
- if (count > 1) {
107
- // The batch endpoint only understands a subset of create's flags.
108
- // Anything it can't honor is a hard usage error, never silently dropped.
109
- const unsupported = [];
110
- if (opts.branch !== undefined)
111
- unsupported.push('--branch');
112
- if (opts.public)
113
- unsupported.push('--public');
114
- if (opts.port !== undefined)
115
- unsupported.push('--port');
116
- if (opts.framework !== undefined)
117
- unsupported.push('--framework');
118
- if (opts.ram !== undefined)
119
- unsupported.push('--ram');
120
- if (opts.cpu !== undefined)
121
- unsupported.push('--cpu');
122
- if (opts.disk !== undefined)
123
- unsupported.push('--disk');
124
- if (unsupported.length > 0) {
125
- fail(`${unsupported.join(', ')} cannot be combined with --count > 1. ` +
126
- 'Batch creates support --template, --idle/--always-on, --repo, and -e/--env.', { code: 'usage', exitCode: EXIT.USAGE });
127
- }
128
- if (opts.alwaysOn && opts.idle !== undefined) {
129
- fail('--always-on and --idle are mutually exclusive.', { code: 'usage', exitCode: EXIT.USAGE });
130
- }
131
- const batchBody = { namePrefix: name, count };
132
- if (templateId)
133
- batchBody.templateId = templateId;
134
- if (opts.repo)
135
- batchBody.githubRepo = opts.repo;
136
- if (opts.env)
137
- batchBody.envVars = parseEnvPairs(opts.env);
138
- if (opts.alwaysOn) {
139
- batchBody.idleTtlSeconds = 0; // 0 = always-on (never auto-sleep)
140
- }
141
- else if (opts.idle !== undefined) {
142
- const secs = Number(opts.idle);
143
- if (!Number.isInteger(secs) || secs < 0) {
144
- fail('--idle must be an integer number of seconds (0 = always-on).', {
145
- code: 'usage',
146
- exitCode: EXIT.USAGE,
147
- });
148
- }
149
- batchBody.idleTtlSeconds = secs; // 0 = always-on
150
- }
151
- const spinner = await makeSpinner(`Creating ${chalk.bold(name)} × ${count}...`);
152
- let result;
153
- try {
154
- result = await authPost('/api/fleet/batch', batchBody);
155
- }
156
- catch (error) {
157
- spinner.fail('Failed to create agents');
158
- if (error instanceof CliHttpError && (error.status === 402 || error.status === 403)) {
159
- // 402 = the plan's agent cap (code seat_limit); the server's detail
160
- // is already a complete sentence naming the fix and the billing
161
- // link, so print it verbatim. 403 = the server-enforced batch cap.
162
- // Both are request failures, not auth failures, so exit 1.
163
- fail(error.detail, {
164
- status: error.status,
165
- code: error.code ?? (error.status === 402 ? 'seat_limit' : 'fleet_cap_exceeded'),
166
- exitCode: EXIT.ERROR,
167
- });
168
- }
169
- throw error;
170
- }
171
- const allCreated = result.failed.length === 0 && result.created.length > 0;
172
- if (allCreated) {
173
- spinner.succeed(chalk.green('Created ') + chalk.bold(`${result.created.length} agents`));
174
- }
175
- else {
176
- spinner.stop();
177
- }
178
- // --json → the backend response verbatim on stdout.
179
- outputResult(result, () => {
180
- if (result.created.length > 0) {
181
- console.log('\n ' +
182
- chalk.dim('NAME'.padEnd(24)) +
183
- chalk.dim('ID'.padEnd(28)) +
184
- chalk.dim('STATUS'));
185
- console.log(chalk.dim(' ' + '─'.repeat(62)));
186
- for (const a of result.created) {
187
- const shortName = a.name.length > 22 ? a.name.slice(0, 21) + '…' : a.name;
188
- console.log(' ' + chalk.bold(shortName.padEnd(24)) + chalk.dim(a.id.padEnd(28)) + a.status);
189
- }
190
- }
191
- if (result.failed.length > 0) {
192
- console.log('\n ' + chalk.red(`Failed (${result.failed.length}):`));
193
- for (const f of result.failed) {
194
- console.log(' ' + chalk.bold(f.name.padEnd(24)) + chalk.red(f.error));
195
- }
196
- }
197
- console.log('\n ' + `${result.created.length}/${result.requested} created`);
198
- console.log();
199
- });
200
- // Exit contract: 0 = all created, 1 = partial or none.
201
- if (!allCreated)
202
- process.exitCode = EXIT.ERROR;
203
- return;
204
- }
205
- const body = { name };
206
- if (templateId)
207
- body.templateId = templateId;
208
- if (opts.framework)
209
- body.framework = opts.framework;
210
- if (opts.env)
211
- body.initialEnvVars = parseEnvPairs(opts.env);
212
- if (opts.repo) {
213
- body.githubRepo = opts.repo;
214
- // Source builds need a chance to identify their runtime before boot.
215
- // This preserves an explicit framework or template, while allowing an
216
- // OpenClaw repository to receive its required gateway credential.
217
- if (!templateId && !opts.framework)
218
- body.framework = 'auto';
219
- }
220
- if (opts.branch)
221
- body.branch = opts.branch;
222
- if (opts.public) {
223
- body.publicWeb = true;
224
- // A public web app is a bring-your-own-code agent unless a template was chosen.
225
- if (!templateId && !opts.framework)
226
- body.framework = 'custom';
227
- }
228
- if (opts.port)
229
- body.exposedPort = Number(opts.port);
230
- else if (opts.public)
231
- body.exposedPort = 8080;
232
- // Per-agent resource overrides (serverless). Omitted fields inherit the defaults.
233
- if (opts.alwaysOn && opts.idle !== undefined) {
234
- fail('--always-on and --idle are mutually exclusive.', { code: 'usage', exitCode: 4 });
235
- }
236
- if (opts.ram !== undefined) {
237
- const mb = Number(opts.ram);
238
- if (!Number.isInteger(mb) || mb < 128) {
239
- fail('--ram must be an integer >= 128 (MB).', { code: 'usage', exitCode: 4 });
240
- }
241
- body.memMb = mb;
242
- }
243
- if (opts.cpu !== undefined) {
244
- const cores = Number(opts.cpu);
245
- if (!Number.isFinite(cores) || cores <= 0) {
246
- fail('--cpu must be a positive number of cores (e.g. 0.5, 1, 2).', { code: 'usage', exitCode: 4 });
247
- }
248
- body.vcpus = cores;
249
- }
250
- if (opts.alwaysOn) {
251
- body.idleTtlSeconds = 0; // 0 = always-on (never auto-sleep)
252
- }
253
- else if (opts.idle !== undefined) {
254
- const secs = Number(opts.idle);
255
- if (!Number.isInteger(secs) || secs < 1) {
256
- fail('--idle must be a positive integer (seconds).', { code: 'usage', exitCode: 4 });
257
- }
258
- body.idleTtlSeconds = secs;
259
- }
260
- if (opts.disk !== undefined) {
261
- const gb = Number(opts.disk);
262
- if (!Number.isFinite(gb) || gb <= 0) {
263
- fail('--disk must be a positive number of GB.', { code: 'usage', exitCode: 4 });
264
- }
265
- body.diskGb = gb;
266
- }
267
- const spinner = await makeSpinner(`Creating agent ${chalk.bold(name)}...`);
268
- let agent;
269
- try {
270
- agent = await authPost('/api/agents', body);
271
- }
272
- catch (error) {
273
- spinner.fail('Failed to create agent');
274
- if (error instanceof CliHttpError && error.status === 402) {
275
- // Billing gate, not a crash. The server's detail is already a
276
- // complete user-ready sentence naming the fix (e.g. the free plan
277
- // includes 3 agents: delete one or upgrade) and carrying
278
- // https://maritime.sh/billing, so print it verbatim rather than
279
- // guessing at a reason here.
280
- fail(error.detail, {
281
- status: 402,
282
- code: error.code ?? 'payment_required',
283
- exitCode: EXIT.ERROR,
284
- });
285
- }
286
- throw error;
287
- }
288
- spinner.succeed(chalk.green('Created ') + chalk.bold(agent.name) + chalk.dim(` (${agent.id})`));
289
- outputResult({ ok: true, action: 'create', ...agent }, () => {
290
- console.log(chalk.dim(` Framework: ${agent.framework} | Status: ${agent.status}`));
291
- const res = [];
292
- if (agent.memMb)
293
- res.push(`RAM ${agent.memMb}MB`);
294
- if (agent.vcpus)
295
- res.push(`CPU ${agent.vcpus}`);
296
- if (agent.idleTtlSeconds != null) {
297
- res.push(agent.idleTtlSeconds <= 0 ? 'always-on' : `idle ${agent.idleTtlSeconds}s`);
298
- }
299
- if (agent.diskMb)
300
- res.push(`disk ${(agent.diskMb / 1024).toFixed(1)}GB`);
301
- if (res.length)
302
- console.log(chalk.dim(` Resources: ${res.join(' | ')}`));
303
- if (agent.publicUrl)
304
- console.log(chalk.green(' Public URL: ') + chalk.bold(agent.publicUrl));
305
- });
306
- }
307
- catch (error) {
308
- handleError(error);
309
- }
310
- });
@@ -1,2 +0,0 @@
1
- import { Command } from 'commander';
2
- export declare const deleteCommand: Command;