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
@@ -1,14 +1,16 @@
1
- import { Command } from 'commander';
1
+ import { Command, Option } from 'commander';
2
2
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { authGet, authPost, CliHttpError } from '../api.js';
3
+ import { authGet, authPost } from '../api.js';
5
4
  import { promptForValue } from '../prompt.js';
5
+ import { isJsonMode, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
6
6
  function parseEnvPairs(pairs) {
7
7
  return pairs.map((pair) => {
8
8
  const eqIdx = pair.indexOf('=');
9
9
  if (eqIdx <= 0) {
10
- console.log(chalk.red('Error:') + ` Invalid env var format: "${pair}". Use KEY=value.`);
11
- process.exit(1);
10
+ fail(`Invalid env var format: "${pair}". Use KEY=value.`, {
11
+ code: 'usage',
12
+ exitCode: EXIT.USAGE,
13
+ });
12
14
  }
13
15
  return {
14
16
  key: pair.slice(0, eqIdx),
@@ -19,64 +21,146 @@ function parseEnvPairs(pairs) {
19
21
  }
20
22
  export const createCommand = new Command('create')
21
23
  .description('Create a new agent')
22
- .option('-n, --name <name>', 'Agent name')
23
- .option('-t, --template <template>', 'Template ID')
24
- .option('--framework <framework>', 'Framework (default: custom)')
25
- .option('--tier <tier>', 'Tier (smart, extended, always_on)')
24
+ .argument('[name]', 'Agent name')
25
+ .option('-t, --template <template>', 'Template to base the agent on (see `maritime templates`)')
26
26
  .option('-e, --env <pairs...>', 'Environment variables (KEY=value)')
27
- .action(async (opts) => {
28
- let name = opts.name;
29
- let templateId = opts.template;
30
- // Interactive mode if no name given
31
- if (!name) {
32
- name = await promptForValue('Agent name');
27
+ // Advanced overrides — kept fully working but off the main --help so the
28
+ // happy path stays flag-free. By default the platform picks the applicable
29
+ // size for the framework and auto-sleeps when idle; you only reach for these
30
+ // to hand-tune a specific agent (e.g. a reseller dialing RAM per client).
31
+ .addOption(new Option('-n, --name <name>', 'Agent name (alias for the positional argument)').hideHelp())
32
+ .addOption(new Option('--framework <framework>', 'Framework (default: custom)').hideHelp())
33
+ .addOption(new Option('--tier <tier>', 'Tier (smart, extended, always_on)').hideHelp())
34
+ .addOption(new Option('--ram <mb>', 'RAM in MB (per-agent override of the tier default)').hideHelp())
35
+ .addOption(new Option('--cpu <cores>', 'vCPU cores, e.g. 0.5 or 2 (per-agent override)').hideHelp())
36
+ .addOption(new Option('--idle <seconds>', 'Auto-sleep this many seconds after the last request').hideHelp())
37
+ .addOption(new Option('--always-on', 'Never auto-sleep (mutually exclusive with --idle)').hideHelp())
38
+ .addOption(new Option('--disk <gb>', 'Workspace SSD size in GB (per-agent override)').hideHelp())
39
+ .addOption(new Option('--max-compute <minutes>', 'Hard cap: auto-sleep after N compute-minutes per billing period').hideHelp())
40
+ .addHelpText('after', `
41
+ Examples:
42
+ maritime create researcher
43
+ maritime create acme-bot --template openclaw --json
44
+ maritime create client-x -e OPENAI_API_KEY=sk-...`)
45
+ .action(async (nameArg, opts) => {
46
+ try {
47
+ let name = nameArg || opts.name;
48
+ let templateId = opts.template;
49
+ const interactive = !isJsonMode() && process.stdin.isTTY;
50
+ // Interactive mode if no name given
33
51
  if (!name) {
34
- console.log(chalk.red('Error:') + ' Agent name is required.');
35
- process.exit(1);
36
- }
37
- }
38
- // If no template specified interactively, show available templates
39
- if (!templateId && !opts.framework) {
40
- try {
41
- const templates = await authGet('/api/templates');
42
- if (templates.length > 0) {
43
- console.log(chalk.dim('\nAvailable templates:'));
44
- templates.forEach((t, i) => {
45
- console.log(` ${chalk.bold(String(i + 1))}. ${t.name} (${t.framework})${t.description ? ' — ' + t.description : ''}`);
52
+ if (!interactive) {
53
+ fail('Agent name is required. Pass --name <name>.', {
54
+ code: 'usage',
55
+ exitCode: EXIT.USAGE,
46
56
  });
47
- console.log();
48
- const choice = await promptForValue('Template number (or press Enter to skip)');
49
- const idx = parseInt(choice, 10);
50
- if (idx >= 1 && idx <= templates.length) {
51
- templateId = templates[idx - 1].id;
57
+ }
58
+ name = await promptForValue('Agent name');
59
+ if (!name) {
60
+ fail('Agent name is required.', { code: 'usage', exitCode: EXIT.USAGE });
61
+ }
62
+ }
63
+ // If no template specified interactively, show available templates
64
+ if (interactive && !templateId && !opts.framework) {
65
+ try {
66
+ const templates = await authGet('/api/templates');
67
+ if (templates.length > 0) {
68
+ console.log(chalk.dim('\nAvailable templates:'));
69
+ templates.forEach((t, i) => {
70
+ console.log(` ${chalk.bold(String(i + 1))}. ${t.name} (${t.framework})${t.description ? ' — ' + t.description : ''}`);
71
+ });
72
+ console.log();
73
+ const choice = await promptForValue('Template number (or press Enter to skip)');
74
+ const idx = parseInt(choice, 10);
75
+ if (idx >= 1 && idx <= templates.length) {
76
+ templateId = templates[idx - 1].id;
77
+ }
52
78
  }
53
79
  }
80
+ catch {
81
+ // Templates fetch failed; continue without template
82
+ }
54
83
  }
55
- catch {
56
- // Templates fetch failed; continue without template
84
+ const body = { name };
85
+ if (templateId)
86
+ body.templateId = templateId;
87
+ if (opts.framework)
88
+ body.framework = opts.framework;
89
+ if (opts.tier)
90
+ body.tier = opts.tier;
91
+ if (opts.env)
92
+ body.initialEnvVars = parseEnvPairs(opts.env);
93
+ // Per-agent resource overrides (serverless). Omitted fields inherit the tier.
94
+ if (opts.alwaysOn && opts.idle !== undefined) {
95
+ fail('--always-on and --idle are mutually exclusive.', { code: 'usage', exitCode: 4 });
96
+ }
97
+ if (opts.ram !== undefined) {
98
+ const mb = Number(opts.ram);
99
+ if (!Number.isInteger(mb) || mb < 128) {
100
+ fail('--ram must be an integer >= 128 (MB).', { code: 'usage', exitCode: 4 });
101
+ }
102
+ body.memMb = mb;
103
+ }
104
+ if (opts.cpu !== undefined) {
105
+ const cores = Number(opts.cpu);
106
+ if (!Number.isFinite(cores) || cores <= 0) {
107
+ fail('--cpu must be a positive number of cores (e.g. 0.5, 1, 2).', { code: 'usage', exitCode: 4 });
108
+ }
109
+ body.vcpus = cores;
110
+ }
111
+ if (opts.alwaysOn) {
112
+ body.idleTtlSeconds = 0; // 0 = always-on (never auto-sleep)
113
+ }
114
+ else if (opts.idle !== undefined) {
115
+ const secs = Number(opts.idle);
116
+ if (!Number.isInteger(secs) || secs < 1) {
117
+ fail('--idle must be a positive integer (seconds).', { code: 'usage', exitCode: 4 });
118
+ }
119
+ body.idleTtlSeconds = secs;
120
+ }
121
+ if (opts.disk !== undefined) {
122
+ const gb = Number(opts.disk);
123
+ if (!Number.isFinite(gb) || gb <= 0) {
124
+ fail('--disk must be a positive number of GB.', { code: 'usage', exitCode: 4 });
125
+ }
126
+ body.diskGb = gb;
127
+ }
128
+ if (opts.maxCompute !== undefined) {
129
+ const mins = Number(opts.maxCompute);
130
+ if (!Number.isFinite(mins) || mins <= 0) {
131
+ fail('--max-compute must be a positive number of minutes.', { code: 'usage', exitCode: 4 });
132
+ }
133
+ body.computeMinutesLimit = mins;
134
+ }
135
+ const spinner = await makeSpinner(`Creating agent ${chalk.bold(name)}...`);
136
+ let agent;
137
+ try {
138
+ agent = await authPost('/api/agents', body);
139
+ }
140
+ catch (error) {
141
+ spinner.fail('Failed to create agent');
142
+ throw error;
57
143
  }
58
- }
59
- const body = { name };
60
- if (templateId)
61
- body.templateId = templateId;
62
- if (opts.framework)
63
- body.framework = opts.framework;
64
- if (opts.tier)
65
- body.tier = opts.tier;
66
- if (opts.env)
67
- body.initialEnvVars = parseEnvPairs(opts.env);
68
- const spinner = ora(`Creating agent ${chalk.bold(name)}...`).start();
69
- try {
70
- const agent = await authPost('/api/agents', body);
71
144
  spinner.succeed(chalk.green('Created ') + chalk.bold(agent.name) + chalk.dim(` (${agent.id})`));
72
- console.log(chalk.dim(` Framework: ${agent.framework} | Tier: ${agent.tier} | Status: ${agent.status}`));
145
+ outputResult({ ok: true, action: 'create', ...agent }, () => {
146
+ console.log(chalk.dim(` Framework: ${agent.framework} | Tier: ${agent.tier} | Status: ${agent.status}`));
147
+ const res = [];
148
+ if (agent.memMb)
149
+ res.push(`RAM ${agent.memMb}MB`);
150
+ if (agent.vcpus)
151
+ res.push(`CPU ${agent.vcpus}`);
152
+ if (agent.idleTtlSeconds != null) {
153
+ res.push(agent.idleTtlSeconds <= 0 ? 'always-on' : `idle ${agent.idleTtlSeconds}s`);
154
+ }
155
+ if (agent.diskMb)
156
+ res.push(`disk ${(agent.diskMb / 1024).toFixed(1)}GB`);
157
+ if (agent.computeMinutesLimit)
158
+ res.push(`cap ${agent.computeMinutesLimit}min`);
159
+ if (res.length)
160
+ console.log(chalk.dim(` Resources: ${res.join(' | ')}`));
161
+ });
73
162
  }
74
163
  catch (error) {
75
- spinner.fail('Failed to create agent');
76
- if (error instanceof CliHttpError) {
77
- console.log(chalk.red('Error:') + ` ${error.detail}`);
78
- process.exit(1);
79
- }
80
- throw error;
164
+ handleError(error);
81
165
  }
82
166
  });
@@ -1,33 +1,43 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { authDelete, CliHttpError } from '../api.js';
3
+ import { authDelete } from '../api.js';
5
4
  import { resolveAgent } from '../resolve.js';
6
5
  import { promptForValue } from '../prompt.js';
6
+ import { isJsonMode, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
7
7
  export const deleteCommand = new Command('delete')
8
8
  .description('Delete an agent')
9
9
  .argument('<agent>', 'Agent name or ID')
10
10
  .option('-y, --yes', 'Skip confirmation')
11
11
  .action(async (agentArg, opts) => {
12
- const agent = await resolveAgent(agentArg);
13
- if (!opts.yes) {
14
- const confirm = await promptForValue(`Type "${agent.name}" to confirm deletion`);
15
- if (confirm !== agent.name) {
16
- console.log(chalk.yellow('Cancelled.'));
17
- return;
18
- }
19
- }
20
- const spinner = ora(`Deleting ${chalk.bold(agent.name)}...`).start();
21
12
  try {
22
- await authDelete(`/api/agents/${agent.id}`);
13
+ // Fail fast (before any network/auth) when a non-interactive caller
14
+ // (AI agent, CI, --json) omits --yes and couldn't answer a prompt anyway.
15
+ if (!opts.yes && (isJsonMode() || !process.stdin.isTTY)) {
16
+ fail('Refusing to delete without confirmation. Pass --yes to proceed.', {
17
+ code: 'confirmation_required',
18
+ exitCode: EXIT.USAGE,
19
+ });
20
+ }
21
+ const agent = await resolveAgent(agentArg);
22
+ if (!opts.yes) {
23
+ const confirm = await promptForValue(`Type "${agent.name}" to confirm deletion`);
24
+ if (confirm !== agent.name) {
25
+ console.log(chalk.yellow('Cancelled.'));
26
+ return;
27
+ }
28
+ }
29
+ const spinner = await makeSpinner(`Deleting ${chalk.bold(agent.name)}...`);
30
+ try {
31
+ await authDelete(`/api/agents/${agent.id}`);
32
+ }
33
+ catch (error) {
34
+ spinner.fail('Failed to delete agent');
35
+ throw error;
36
+ }
23
37
  spinner.succeed(chalk.green('Deleted ') + chalk.bold(agent.name));
38
+ outputResult({ ok: true, action: 'delete', agentId: agent.id, name: agent.name }, () => { });
24
39
  }
25
40
  catch (error) {
26
- spinner.fail('Failed to delete agent');
27
- if (error instanceof CliHttpError) {
28
- console.log(chalk.red('Error:') + ` ${error.detail}`);
29
- process.exit(1);
30
- }
31
- throw error;
41
+ handleError(error);
32
42
  }
33
43
  });
@@ -1,8 +1,10 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
- import { authPost, CliHttpError } from '../api.js';
4
+ import { authPost } from '../api.js';
5
5
  import { resolveAgent } from '../resolve.js';
6
+ import { isJsonMode, outputJson, handleError } from '../output.js';
7
+ import { connectWs } from '../websocket.js';
6
8
  export const deployCommand = new Command('deploy')
7
9
  .description('Deploy an agent')
8
10
  .argument('<agent>', 'Agent name or ID')
@@ -10,6 +12,7 @@ export const deployCommand = new Command('deploy')
10
12
  .option('--repo <url>', 'GitHub repository URL')
11
13
  .option('--image <name>', 'Docker image name')
12
14
  .option('--branch <branch>', 'Git branch')
15
+ .option('-w, --wait', 'Wait for deployment to complete')
13
16
  .action(async (agentArg, opts) => {
14
17
  const agent = await resolveAgent(agentArg);
15
18
  const body = {
@@ -25,16 +28,55 @@ export const deployCommand = new Command('deploy')
25
28
  const spinner = ora(`Deploying ${chalk.bold(agent.name)}...`).start();
26
29
  try {
27
30
  const deployment = await authPost('/api/deploy', body);
28
- spinner.succeed(chalk.green('Deployment started for ') + chalk.bold(agent.name));
29
- console.log(chalk.dim(` Deployment ID: ${deployment.id}`));
30
- console.log(chalk.dim(` Status: ${deployment.status}`));
31
+ if (isJsonMode() && !opts.wait) {
32
+ spinner.stop();
33
+ outputJson(deployment);
34
+ return;
35
+ }
36
+ if (!opts.wait) {
37
+ spinner.succeed(chalk.green('Deployment started for ') + chalk.bold(agent.name));
38
+ console.log(chalk.dim(` Deployment ID: ${deployment.id}`));
39
+ console.log(chalk.dim(` Status: ${deployment.status}`));
40
+ return;
41
+ }
42
+ // --wait: stream deploy progress via WebSocket
43
+ spinner.text = `Building ${chalk.bold(agent.name)}...`;
44
+ await new Promise((resolve, reject) => {
45
+ const cleanup = connectWs(`/api/deploy/${agent.id}/status`, {
46
+ onMessage(data) {
47
+ try {
48
+ const msg = JSON.parse(data);
49
+ if (msg.message) {
50
+ spinner.text = msg.message;
51
+ }
52
+ if (msg.status === 'success' || msg.status === 'completed') {
53
+ spinner.succeed(chalk.green('Deployment complete: ') + chalk.bold(agent.name));
54
+ cleanup();
55
+ resolve();
56
+ }
57
+ else if (msg.status === 'failed') {
58
+ spinner.fail(chalk.red('Deployment failed: ') + (msg.message || 'unknown error'));
59
+ cleanup();
60
+ reject(new Error('Deployment failed'));
61
+ }
62
+ }
63
+ catch {
64
+ // Non-JSON message, show as build output
65
+ spinner.text = data.trim();
66
+ }
67
+ },
68
+ onClose() {
69
+ resolve();
70
+ },
71
+ maxReconnects: 3,
72
+ });
73
+ });
74
+ if (isJsonMode()) {
75
+ outputJson(deployment);
76
+ }
31
77
  }
32
78
  catch (error) {
33
79
  spinner.fail('Deployment failed');
34
- if (error instanceof CliHttpError) {
35
- console.log(chalk.red('Error:') + ` ${error.detail}`);
36
- process.exit(1);
37
- }
38
- throw error;
80
+ handleError(error);
39
81
  }
40
82
  });
@@ -1,84 +1,247 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { Command } from 'commander';
2
3
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { authGet, authPost, authDelete, CliHttpError } from '../api.js';
4
+ import { authGet, authPost, authDelete } from '../api.js';
5
5
  import { resolveAgent } from '../resolve.js';
6
+ import { isJsonMode, outputJson, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
7
+ /** Parse a single KEY=value token (as passed on the command line). */
8
+ function parsePair(pair) {
9
+ const eqIdx = pair.indexOf('=');
10
+ if (eqIdx <= 0) {
11
+ fail(`Invalid format: "${pair}". Use KEY=value.`, { code: 'usage', exitCode: EXIT.USAGE });
12
+ }
13
+ return { key: pair.slice(0, eqIdx), value: pair.slice(eqIdx + 1) };
14
+ }
15
+ /**
16
+ * Parse a dotenv-style document into key/value pairs. Supports blank lines,
17
+ * `#` comments, an optional `export ` prefix, and single/double-quoted values.
18
+ */
19
+ function parseDotenv(text) {
20
+ const pairs = [];
21
+ for (const rawLine of text.split('\n')) {
22
+ let line = rawLine.trim();
23
+ if (!line || line.startsWith('#'))
24
+ continue;
25
+ if (line.startsWith('export '))
26
+ line = line.slice('export '.length).trim();
27
+ const eqIdx = line.indexOf('=');
28
+ if (eqIdx <= 0)
29
+ continue; // skip malformed lines rather than abort the batch
30
+ const key = line.slice(0, eqIdx).trim();
31
+ let value = line.slice(eqIdx + 1).trim();
32
+ // Strip matching surrounding quotes; unescape \n only inside double quotes.
33
+ if ((value.startsWith('"') && value.endsWith('"')) ||
34
+ (value.startsWith("'") && value.endsWith("'"))) {
35
+ const quote = value[0];
36
+ value = value.slice(1, -1);
37
+ if (quote === '"')
38
+ value = value.replace(/\\n/g, '\n');
39
+ }
40
+ if (key)
41
+ pairs.push({ key, value });
42
+ }
43
+ return pairs;
44
+ }
45
+ /** Upload a batch of vars sequentially; collect per-key outcomes. */
46
+ async function uploadVars(agentId, pairs, isSecret) {
47
+ const uploaded = [];
48
+ const failed = [];
49
+ for (const { key, value } of pairs) {
50
+ try {
51
+ await authPost(`/api/agents/${agentId}/env`, { key, value, is_secret: isSecret });
52
+ uploaded.push(key);
53
+ }
54
+ catch (error) {
55
+ failed.push({ key, error: error instanceof Error ? error.message : String(error) });
56
+ }
57
+ }
58
+ return { uploaded, failed };
59
+ }
60
+ /** Hot-reload env into the running container (falls back to restart server-side). */
61
+ async function reloadEnv(agentId) {
62
+ await authPost(`/api/agents/${agentId}/reload-env`);
63
+ }
6
64
  export const envCommand = new Command('env')
7
- .description('Manage environment variables');
65
+ .description('Manage environment variables')
66
+ .addHelpText('after', `
67
+ Examples:
68
+ maritime env set my-agent OPENAI_API_KEY=sk-… --json
69
+ maritime env import my-agent ./prod.env --reload --json
70
+ maritime env reload my-agent --json
71
+ Secrets are encrypted and marked secret by default; changes apply on next
72
+ boot unless you pass --reload.`);
73
+ // --- list -----------------------------------------------------------------
8
74
  envCommand
9
75
  .command('list <agent>')
76
+ .alias('ls')
10
77
  .description('List environment variables')
11
78
  .action(async (agentArg) => {
12
- const agent = await resolveAgent(agentArg);
13
79
  try {
80
+ const agent = await resolveAgent(agentArg);
14
81
  const vars = await authGet(`/api/agents/${agent.id}/env`);
82
+ if (isJsonMode()) {
83
+ outputJson(vars);
84
+ return;
85
+ }
15
86
  if (vars.length === 0) {
16
87
  console.log(chalk.dim(`\nNo environment variables set for ${chalk.bold(agent.name)}.`));
17
88
  return;
18
89
  }
19
90
  console.log(chalk.dim(`\nEnvironment variables for ${chalk.bold(agent.name)}:\n`));
20
91
  for (const v of vars) {
21
- const display = v.is_secret ? chalk.dim('\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022') : v.value;
92
+ const display = v.is_secret ? chalk.dim('••••••••') : v.value;
22
93
  console.log(` ${chalk.bold(v.key.padEnd(24))} = ${display}`);
23
94
  }
24
95
  console.log();
25
96
  }
26
97
  catch (error) {
27
- if (error instanceof CliHttpError) {
28
- console.log(chalk.red('Error:') + ` ${error.detail}`);
29
- process.exit(1);
30
- }
31
- throw error;
98
+ handleError(error);
32
99
  }
33
100
  });
101
+ // --- set (one or many pairs) ----------------------------------------------
34
102
  envCommand
35
- .command('set <agent> <pair>')
36
- .description('Set an environment variable (KEY=value)')
37
- .option('-s, --secret', 'Mark as secret (default)', true)
38
- .option('--no-secret', 'Mark as non-secret')
39
- .action(async (agentArg, pair, opts) => {
40
- const eqIdx = pair.indexOf('=');
41
- if (eqIdx <= 0) {
42
- console.log(chalk.red('Error:') + ' Format must be KEY=value');
43
- process.exit(1);
44
- }
45
- const key = pair.slice(0, eqIdx);
46
- const value = pair.slice(eqIdx + 1);
47
- const agent = await resolveAgent(agentArg);
48
- const spinner = ora(`Setting ${key} for ${agent.name}...`).start();
103
+ .command('set <agent> <pairs...>')
104
+ .description('Set one or more environment variables (KEY=value KEY2=value2 …)')
105
+ .option('--no-secret', 'Store as plain (non-secret) values')
106
+ .option('-r, --reload', 'Hot-reload env into the running container afterward')
107
+ .action(async (agentArg, rawPairs, opts) => {
49
108
  try {
50
- await authPost(`/api/agents/${agent.id}/env`, {
51
- key,
52
- value,
53
- is_secret: opts.secret,
109
+ const pairs = rawPairs.map(parsePair);
110
+ const agent = await resolveAgent(agentArg);
111
+ const spinner = await makeSpinner(`Setting ${pairs.length} var${pairs.length === 1 ? '' : 's'} for ${agent.name}...`);
112
+ const { uploaded, failed } = await uploadVars(agent.id, pairs, opts.secret);
113
+ let reloaded = false;
114
+ if (opts.reload && uploaded.length > 0) {
115
+ try {
116
+ await reloadEnv(agent.id);
117
+ reloaded = true;
118
+ }
119
+ catch {
120
+ // Surface reload failure but don't undo the writes.
121
+ }
122
+ }
123
+ if (failed.length > 0)
124
+ spinner.fail(`Set ${uploaded.length}, failed ${failed.length}`);
125
+ else
126
+ spinner.succeed(`Set ${uploaded.length} var${uploaded.length === 1 ? '' : 's'} for ${chalk.bold(agent.name)}`);
127
+ outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded }, () => {
128
+ for (const f of failed)
129
+ console.error(chalk.red(` ${f.key}: ${f.error}`));
130
+ if (reloaded)
131
+ console.log(chalk.dim(' Reloaded into running container.'));
132
+ else if (opts.reload)
133
+ console.log(chalk.yellow(' Reload skipped or failed; changes land on next boot.'));
54
134
  });
55
- spinner.succeed(`Set ${chalk.bold(key)} for ${chalk.bold(agent.name)}`);
135
+ if (failed.length > 0)
136
+ process.exit(EXIT.ERROR);
56
137
  }
57
138
  catch (error) {
58
- spinner.fail(`Failed to set ${key}`);
59
- if (error instanceof CliHttpError) {
60
- console.log(chalk.red('Error:') + ` ${error.detail}`);
61
- process.exit(1);
139
+ handleError(error);
140
+ }
141
+ });
142
+ // --- import (.env file or stdin) ------------------------------------------
143
+ envCommand
144
+ .command('import <agent> [file]')
145
+ .description('Upload all keys from a .env file (or stdin if file is "-" / omitted)')
146
+ .option('--plain', 'Store as plain (non-secret) values')
147
+ .option('-r, --reload', 'Hot-reload env into the running container afterward')
148
+ .action(async (agentArg, file, opts) => {
149
+ try {
150
+ let text;
151
+ if (!file || file === '-') {
152
+ if (process.stdin.isTTY) {
153
+ fail('No input. Pass a .env file path or pipe one via stdin.', {
154
+ code: 'usage',
155
+ exitCode: EXIT.USAGE,
156
+ });
157
+ }
158
+ text = readFileSync(0, 'utf8'); // fd 0 = stdin
159
+ }
160
+ else {
161
+ try {
162
+ text = readFileSync(file, 'utf8');
163
+ }
164
+ catch {
165
+ fail(`Cannot read file: ${file}`, { code: 'usage', exitCode: EXIT.USAGE });
166
+ }
167
+ }
168
+ const pairs = parseDotenv(text);
169
+ if (pairs.length === 0) {
170
+ fail('No KEY=value pairs found in input.', { code: 'usage', exitCode: EXIT.USAGE });
171
+ }
172
+ const agent = await resolveAgent(agentArg);
173
+ const spinner = await makeSpinner(`Importing ${pairs.length} vars into ${agent.name}...`);
174
+ const { uploaded, failed } = await uploadVars(agent.id, pairs, !opts.plain);
175
+ let reloaded = false;
176
+ if (opts.reload && uploaded.length > 0) {
177
+ try {
178
+ await reloadEnv(agent.id);
179
+ reloaded = true;
180
+ }
181
+ catch {
182
+ /* keep writes; report below */
183
+ }
62
184
  }
63
- throw error;
185
+ if (failed.length > 0)
186
+ spinner.fail(`Imported ${uploaded.length}, failed ${failed.length}`);
187
+ else
188
+ spinner.succeed(`Imported ${uploaded.length} vars into ${chalk.bold(agent.name)}`);
189
+ outputResult({ ok: failed.length === 0, agentId: agent.id, uploaded, failed, reloaded }, () => {
190
+ for (const f of failed)
191
+ console.error(chalk.red(` ${f.key}: ${f.error}`));
192
+ if (reloaded)
193
+ console.log(chalk.dim(' Reloaded into running container.'));
194
+ else if (opts.reload)
195
+ console.log(chalk.yellow(' Reload skipped or failed; changes land on next boot.'));
196
+ });
197
+ if (failed.length > 0)
198
+ process.exit(EXIT.ERROR);
199
+ }
200
+ catch (error) {
201
+ handleError(error);
64
202
  }
65
203
  });
204
+ // --- remove ----------------------------------------------------------------
66
205
  envCommand
67
206
  .command('remove <agent> <key>')
207
+ .alias('rm')
68
208
  .description('Remove an environment variable')
69
- .action(async (agentArg, key) => {
70
- const agent = await resolveAgent(agentArg);
71
- const spinner = ora(`Removing ${key} from ${agent.name}...`).start();
209
+ .option('-r, --reload', 'Hot-reload env into the running container afterward')
210
+ .action(async (agentArg, key, opts) => {
72
211
  try {
212
+ const agent = await resolveAgent(agentArg);
213
+ const spinner = await makeSpinner(`Removing ${key} from ${agent.name}...`);
73
214
  await authDelete(`/api/agents/${agent.id}/env/${encodeURIComponent(key)}`);
215
+ let reloaded = false;
216
+ if (opts.reload) {
217
+ try {
218
+ await reloadEnv(agent.id);
219
+ reloaded = true;
220
+ }
221
+ catch {
222
+ /* ignore */
223
+ }
224
+ }
74
225
  spinner.succeed(`Removed ${chalk.bold(key)} from ${chalk.bold(agent.name)}`);
226
+ outputResult({ ok: true, agentId: agent.id, removed: key, reloaded }, () => { });
75
227
  }
76
228
  catch (error) {
77
- spinner.fail(`Failed to remove ${key}`);
78
- if (error instanceof CliHttpError) {
79
- console.log(chalk.red('Error:') + ` ${error.detail}`);
80
- process.exit(1);
81
- }
82
- throw error;
229
+ handleError(error);
230
+ }
231
+ });
232
+ // --- reload ----------------------------------------------------------------
233
+ envCommand
234
+ .command('reload <agent>')
235
+ .description('Hot-reload env vars into the running container')
236
+ .action(async (agentArg) => {
237
+ try {
238
+ const agent = await resolveAgent(agentArg);
239
+ const spinner = await makeSpinner(`Reloading env for ${agent.name}...`);
240
+ await reloadEnv(agent.id);
241
+ spinner.succeed(`Reloaded env for ${chalk.bold(agent.name)}`);
242
+ outputResult({ ok: true, agentId: agent.id, reloaded: true }, () => { });
243
+ }
244
+ catch (error) {
245
+ handleError(error);
83
246
  }
84
247
  });
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const execCommand: Command;