maritime-cli 1.6.1 → 1.6.2

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/dist/api.js CHANGED
@@ -124,7 +124,12 @@ async function parseJson(response) {
124
124
  return JSON.parse(text);
125
125
  }
126
126
  catch {
127
- throw new CliHttpError(response.status, `Invalid JSON response from ${response.url}`);
127
+ // A non-JSON body is almost always an edge/proxy error page (502/503
128
+ // HTML, plain-text 500). Surface the status and a snippet so the
129
+ // operator sees WHAT the server said instead of a bare parse failure.
130
+ const snippet = text.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160);
131
+ throw new CliHttpError(response.status, `Non-JSON response (HTTP ${response.status}) from ${response.url}` +
132
+ (snippet ? `: ${snippet}` : ''));
128
133
  }
129
134
  }
130
135
  async function handleResponse(response) {
@@ -7,12 +7,19 @@ import { outputResult, fail, handleError, makeSpinner } from '../output.js';
7
7
  function readStdin() {
8
8
  return new Promise((resolve) => {
9
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
+ };
10
17
  process.stdin.setEncoding('utf8');
11
18
  process.stdin.on('data', (chunk) => {
12
19
  data += chunk;
13
20
  });
14
- process.stdin.on('end', () => resolve(data));
15
- process.stdin.on('error', () => resolve(data));
21
+ process.stdin.once('end', done);
22
+ process.stdin.once('error', done);
16
23
  });
17
24
  }
18
25
  /**
@@ -210,7 +210,7 @@ Examples:
210
210
  });
211
211
  // Exit contract: 0 = all created, 1 = partial or none.
212
212
  if (!allCreated)
213
- process.exit(EXIT.ERROR);
213
+ process.exitCode = EXIT.ERROR;
214
214
  return;
215
215
  }
216
216
  const body = { name };
@@ -5,6 +5,9 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { getConfig, getLinkedAgentId, writeLink } from '../context.js';
6
6
  import { isJsonMode, outputJson, fail, handleError, makeSpinner, EXIT } from '../output.js';
7
7
  import { connectWs } from '../websocket.js';
8
+ // Upper bound for `deploy --wait`. Repo builds + micro-VM ship normally
9
+ // finish in 1-3 minutes; 15 minutes covers cold image pulls with margin.
10
+ const WAIT_TIMEOUT_MS = 15 * 60 * 1000;
8
11
  export const deployCommand = new Command('deploy')
9
12
  .description('Deploy this directory: reconcile the agent to maritime.json, then ship it')
10
13
  .argument('[agent]', 'Agent name or ID (defaults to the linked agent / maritime.json)')
@@ -71,25 +74,51 @@ Explicit sources still work: \`maritime deploy --source github --repo <url>\`.`)
71
74
  });
72
75
  return;
73
76
  }
74
- // --wait: stream deploy progress via WebSocket
77
+ // --wait: stream deploy progress via WebSocket. The server closes
78
+ // the socket on terminal status; the client-side timeout is the
79
+ // last-resort bound so --wait can never hang a script forever.
75
80
  if (spinner)
76
81
  spinner.text = `Building ${chalk.bold(agent.name)}...`;
82
+ let gatewayUnconfirmed = false;
77
83
  await new Promise((resolve, reject) => {
84
+ let settled = false;
85
+ const settle = (fn) => {
86
+ if (settled)
87
+ return;
88
+ settled = true;
89
+ clearTimeout(timer);
90
+ fn();
91
+ };
92
+ const timer = setTimeout(() => {
93
+ settle(() => {
94
+ cleanup();
95
+ spinner?.fail('Timed out waiting for the deployment');
96
+ reject(new Error(`Timed out after ${WAIT_TIMEOUT_MS / 60000} minutes waiting for the deployment. ` +
97
+ 'It may still complete: check `maritime status` / `maritime logs`.'));
98
+ });
99
+ }, WAIT_TIMEOUT_MS);
78
100
  const cleanup = connectWs(`/api/deploy/${agent.id}/status`, {
79
101
  onMessage(data) {
80
102
  try {
81
103
  const msg = JSON.parse(data);
82
104
  if (msg.message && spinner)
83
105
  spinner.text = msg.message;
106
+ if (msg.build_log && /did not confirm ready/i.test(msg.build_log)) {
107
+ gatewayUnconfirmed = true;
108
+ }
84
109
  if (msg.status === 'success' || msg.status === 'completed') {
85
110
  spinner?.succeed(chalk.green('Deployment complete: ') + chalk.bold(agent.name));
86
- cleanup();
87
- resolve();
111
+ settle(() => {
112
+ cleanup();
113
+ resolve();
114
+ });
88
115
  }
89
116
  else if (msg.status === 'failed') {
90
117
  spinner?.fail(chalk.red('Deployment failed: ') + (msg.message || 'unknown error'));
91
- cleanup();
92
- reject(new Error('Deployment failed'));
118
+ settle(() => {
119
+ cleanup();
120
+ reject(new Error('Deployment failed'));
121
+ });
93
122
  }
94
123
  }
95
124
  catch {
@@ -98,12 +127,20 @@ Explicit sources still work: \`maritime deploy --source github --repo <url>\`.`)
98
127
  }
99
128
  },
100
129
  onClose() {
101
- resolve();
130
+ settle(resolve);
102
131
  },
103
132
  maxReconnects: 3,
104
133
  });
105
134
  });
106
- finish(deployment, () => { });
135
+ // Deploy success with an unconfirmed gateway means the VM booted but
136
+ // the app never answered on $PORT: historically that is a dead-on-
137
+ // arrival agent. Say so instead of reporting a clean success.
138
+ if (gatewayUnconfirmed && !isJsonMode()) {
139
+ console.log(chalk.yellow('Warning:') +
140
+ ' the app never confirmed it was listening on $PORT. If the public URL 502s,' +
141
+ ' check `maritime logs` for the container output (a crashed process takes the whole micro-VM down).');
142
+ }
143
+ finish({ ...deployment, gatewayUnconfirmed }, () => { });
107
144
  }
108
145
  catch (error) {
109
146
  spinner?.fail('Deployment failed');
@@ -150,7 +150,7 @@ envCommand
150
150
  console.log(chalk.yellow(' Reload skipped or failed; changes land on next boot.'));
151
151
  });
152
152
  if (failed.length > 0)
153
- process.exit(EXIT.ERROR);
153
+ process.exitCode = EXIT.ERROR;
154
154
  }
155
155
  catch (error) {
156
156
  handleError(error);
@@ -229,7 +229,7 @@ envCommand
229
229
  console.log(chalk.yellow(' Reload skipped or failed; changes land on next boot.'));
230
230
  });
231
231
  if (failed.length > 0)
232
- process.exit(EXIT.ERROR);
232
+ process.exitCode = EXIT.ERROR;
233
233
  }
234
234
  catch (error) {
235
235
  handleError(error);
@@ -20,7 +20,10 @@ export const execCommand = new Command('exec')
20
20
  process.stdout.write(result.stdout);
21
21
  if (result.stderr)
22
22
  process.stderr.write(result.stderr);
23
- process.exit(result.exitCode ?? 0);
23
+ // exitCode + return (NOT process.exit): letting the loop drain flushes
24
+ // stdout on Windows pipes and avoids the libuv teardown assertion that
25
+ // intermittently killed `maritime exec` right after printing.
26
+ process.exitCode = result.exitCode ?? 0;
24
27
  }
25
28
  catch (error) {
26
29
  handleError(error);
@@ -90,12 +90,14 @@ export const loginCommand = new Command('login')
90
90
  if (!payload) {
91
91
  console.log(chalk.red('Error:') + ' that does not look like a valid token.');
92
92
  console.log(chalk.dim(` Copy a fresh one from ${APP_URL}/cli/auth`));
93
- process.exit(1);
93
+ process.exitCode = 1;
94
+ return;
94
95
  }
95
96
  if (payload.exp && Date.now() >= payload.exp * 1000) {
96
97
  console.log(chalk.red('Error:') + ' that token has expired.');
97
98
  console.log(chalk.dim(` Generate a new one at ${APP_URL}/cli/auth`));
98
- process.exit(1);
99
+ process.exitCode = 1;
100
+ return;
99
101
  }
100
102
  persistToken(token, payload);
101
103
  console.log(chalk.green('Authenticated as ') + chalk.bold(payload.email || 'your account'));
@@ -113,7 +115,8 @@ export const loginCommand = new Command('login')
113
115
  const password = await promptForPassword(opts.password);
114
116
  if (!email || !password) {
115
117
  console.log(chalk.red('Error:') + ' email and password are required');
116
- process.exit(1);
118
+ process.exitCode = 1;
119
+ return;
117
120
  }
118
121
  const spinner = await makeSpinner('Authenticating...');
119
122
  try {
@@ -142,10 +145,12 @@ export const loginCommand = new Command('login')
142
145
  console.log('\nAuthenticate one of these ways instead:');
143
146
  console.log(' ' + chalk.bold('maritime login') + chalk.dim(' open the browser and approve'));
144
147
  console.log(' ' + chalk.bold('maritime login --token <token>') + chalk.dim(` paste a token from ${APP_URL}/cli/auth`));
145
- process.exit(2);
148
+ process.exitCode = 2;
149
+ return;
146
150
  }
147
151
  console.log(chalk.red('Error:') + ` ${error.detail}`);
148
- process.exit(error.status === 401 ? 2 : 1);
152
+ process.exitCode = error.status === 401 ? 2 : 1;
153
+ return;
149
154
  }
150
155
  throw error;
151
156
  }
@@ -170,6 +175,6 @@ export const loginCommand = new Command('login')
170
175
  console.log(chalk.dim('\nOn a headless / SSH box? Run ') +
171
176
  chalk.bold('maritime login --token <token>') +
172
177
  chalk.dim(` with a token from ${APP_URL}/cli/auth`));
173
- process.exit(1);
178
+ process.exitCode = 1;
174
179
  }
175
180
  });
@@ -2,7 +2,7 @@ import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import { authGet } from '../api.js';
4
4
  import { resolveAgent } from '../resolve.js';
5
- import { isJsonMode, outputJson, handleError } from '../output.js';
5
+ import { isJsonMode, outputJson, handleError, fail, EXIT } from '../output.js';
6
6
  import { connectWs } from '../websocket.js';
7
7
  const VALID_LEVELS = ['info', 'warn', 'error', 'debug'];
8
8
  const levelColors = {
@@ -29,14 +29,18 @@ export const logsCommand = new Command('logs')
29
29
  .action(async (agentArg, opts) => {
30
30
  // Validate --level
31
31
  if (opts.level && !VALID_LEVELS.includes(opts.level)) {
32
- console.log(chalk.red('Error:') + ' --level must be one of info, warn, error, debug');
33
- process.exit(1);
32
+ fail('--level must be one of info, warn, error, debug', {
33
+ code: 'usage',
34
+ exitCode: EXIT.USAGE,
35
+ });
34
36
  }
35
37
  // Validate --lines
36
38
  const lines = parseInt(opts.lines, 10);
37
39
  if (isNaN(lines) || lines <= 0) {
38
- console.log(chalk.red('Error:') + ' --lines must be a positive integer');
39
- process.exit(1);
40
+ fail('--lines must be a positive integer', {
41
+ code: 'usage',
42
+ exitCode: EXIT.USAGE,
43
+ });
40
44
  }
41
45
  const agent = await resolveAgent(agentArg);
42
46
  let path = `/api/agents/${agent.id}/logs?limit=${lines}`;
@@ -55,22 +59,27 @@ export const logsCommand = new Command('logs')
55
59
  for (const entry of entries) {
56
60
  console.log(formatEntry(entry));
57
61
  }
58
- // --follow: stream logs via WebSocket
62
+ // --follow: stream logs via WebSocket. Await the stream's end so the
63
+ // action only resolves when following is done: the command finishes
64
+ // through the normal exit path (loop drains, no hard process.exit
65
+ // from inside a socket callback).
59
66
  if (opts.follow) {
60
- connectWs(`/api/agents/${agent.id}/logs`, {
61
- onMessage(data) {
62
- try {
63
- const entry = JSON.parse(data);
64
- console.log(formatEntry(entry));
65
- }
66
- catch {
67
- // Plain text message
68
- console.log(data);
69
- }
70
- },
71
- onClose() {
72
- process.exit(0);
73
- },
67
+ await new Promise((resolve) => {
68
+ connectWs(`/api/agents/${agent.id}/logs`, {
69
+ onMessage(data) {
70
+ try {
71
+ const entry = JSON.parse(data);
72
+ console.log(formatEntry(entry));
73
+ }
74
+ catch {
75
+ // Plain text message
76
+ console.log(data);
77
+ }
78
+ },
79
+ onClose() {
80
+ resolve();
81
+ },
82
+ });
74
83
  });
75
84
  }
76
85
  }
@@ -17,7 +17,8 @@ export const openCommand = new Command('open')
17
17
  catch (error) {
18
18
  if (error instanceof CliHttpError) {
19
19
  console.log(chalk.red('Error:') + ` ${error.detail}`);
20
- process.exit(1);
20
+ process.exitCode = 1;
21
+ return;
21
22
  }
22
23
  throw error;
23
24
  }
@@ -2,7 +2,7 @@ import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import { authPut } from '../api.js';
4
4
  import { resolveAgent } from '../resolve.js';
5
- import { isJsonMode, outputJson, handleError } from '../output.js';
5
+ import { isJsonMode, outputJson, handleError, fail, EXIT } from '../output.js';
6
6
  const VALID_TIERS = ['smart', 'extended', 'always_on'];
7
7
  export const scaleCommand = new Command('scale')
8
8
  .description('Change an agent tier')
@@ -10,8 +10,10 @@ export const scaleCommand = new Command('scale')
10
10
  .argument('<tier>', 'Target tier (smart, extended, always_on)')
11
11
  .action(async (agentArg, tier) => {
12
12
  if (!VALID_TIERS.includes(tier)) {
13
- console.log(chalk.red('Error:') + ` Invalid tier "${tier}". Must be one of: ${VALID_TIERS.join(', ')}`);
14
- process.exit(1);
13
+ fail(`Invalid tier "${tier}". Must be one of: ${VALID_TIERS.join(', ')}`, {
14
+ code: 'usage',
15
+ exitCode: EXIT.USAGE,
16
+ });
15
17
  }
16
18
  try {
17
19
  const agent = await resolveAgent(agentArg);
@@ -15,7 +15,8 @@ export const signupCommand = new Command('signup')
15
15
  const name = await promptForValue('Name (optional)', opts.name);
16
16
  if (!email || !password) {
17
17
  console.log(chalk.red('Error:') + ' email and password are required');
18
- process.exit(1);
18
+ process.exitCode = 1;
19
+ return;
19
20
  }
20
21
  const spinner = await makeSpinner('Creating account...');
21
22
  try {
@@ -35,7 +36,8 @@ export const signupCommand = new Command('signup')
35
36
  spinner.fail('Signup failed');
36
37
  if (error instanceof CliHttpError) {
37
38
  console.log(chalk.red('Error:') + ` ${error.detail}`);
38
- process.exit(error.status >= 500 ? 1 : 2);
39
+ process.exitCode = error.status >= 500 ? 1 : 2;
40
+ return;
39
41
  }
40
42
  throw error;
41
43
  }
@@ -23,7 +23,8 @@ export const whoamiCommand = new Command('whoami')
23
23
  if (isJsonMode()) {
24
24
  // Not an error per se, but exit non-zero so scripts can branch.
25
25
  process.stdout.write(JSON.stringify({ authenticated: false }, null, 2) + '\n');
26
- process.exit(EXIT.AUTH);
26
+ process.exitCode = EXIT.AUTH;
27
+ return;
27
28
  }
28
29
  fail('Not logged in. Run `maritime login`, or set MARITIME_TOKEN.', {
29
30
  code: 'not_authenticated',
@@ -71,5 +72,5 @@ export const whoamiCommand = new Command('whoami')
71
72
  }
72
73
  });
73
74
  if (expired)
74
- process.exit(EXIT.AUTH);
75
+ process.exitCode = EXIT.AUTH;
75
76
  });
package/dist/index.js CHANGED
@@ -30,24 +30,31 @@ import { triggersCommand } from './commands/triggers.js';
30
30
  import { blueprintCommand } from './commands/blueprint.js';
31
31
  import { scaleCommand } from './commands/scale.js';
32
32
  import { sleepCommand } from './commands/sleep.js';
33
- import { checkForUpdates, printUpdateNotice } from './version-check.js';
33
+ import { checkForUpdates, printUpdateNotice, versionCheckSettled } from './version-check.js';
34
34
  import { guideCommand } from './commands/guide.js';
35
35
  import { initCommand } from './commands/init.js';
36
36
  import { linkCommand } from './commands/link.js';
37
37
  import { getLink } from './context.js';
38
- import { handleError } from './output.js';
38
+ import { ExitSignal, handleError } from './output.js';
39
39
  const __dirname = dirname(fileURLToPath(import.meta.url));
40
40
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
41
- // Non-blocking version check
41
+ // Daily update check (skipped in --json / non-TTY / CI; awaited in finishRun
42
+ // so its network work can never race process teardown).
42
43
  checkForUpdates(pkg.version);
43
44
  const program = new Command();
45
+ // Commander's default help/version/usage-error paths call process.exit()
46
+ // internally, which is exactly the hard-exit-with-live-handles pattern that
47
+ // crashes on Windows (see ExitSignal). Route them through ExitSignal too.
48
+ program.exitOverride((err) => {
49
+ throw new ExitSignal(err.exitCode ?? 0);
50
+ });
44
51
  program
45
52
  .name('maritime')
46
- .description(chalk.hex('#8B5CF6')('Maritime') + ' \u2014 Deploy AI agents from your terminal')
53
+ .description(chalk.hex('#8B5CF6')('Maritime') + ' · Deploy AI agents from your terminal')
47
54
  .version(pkg.version)
48
55
  .option('--json', 'Output raw JSON instead of formatted tables')
49
56
  .option('--verbose', 'Show detailed request/response info');
50
- // The lean surface — what shows in `maritime --help`. Everything a human or an
57
+ // The lean surface: what shows in `maritime --help`. Everything a human or an
51
58
  // AI agent needs on the happy path: authenticate, create, deploy, talk, observe.
52
59
  const HIDDEN = { hidden: true };
53
60
  // Auth
@@ -55,7 +62,7 @@ program.addCommand(loginCommand);
55
62
  program.addCommand(logoutCommand);
56
63
  program.addCommand(whoamiCommand);
57
64
  program.addCommand(keysCommand);
58
- // Project — link a directory to an agent (the Vercel/Railway model)
65
+ // Project: link a directory to an agent (the Vercel/Railway model)
59
66
  program.addCommand(initCommand);
60
67
  program.addCommand(linkCommand);
61
68
  // Agent lifecycle
@@ -100,11 +107,44 @@ Quickstart (a directory is an agent):
100
107
 
101
108
  For scripts & AI agents:
102
109
  Auth set MARITIME_TOKEN (mk_… key from \`maritime keys create\`)
103
- Output pass --json — results on stdout, errors as JSON on stderr
110
+ Output pass --json: results on stdout, errors as JSON on stderr
104
111
  Exit code 0 ok · 1 error · 2 auth · 3 not-found · 4 usage
105
112
  Talk maritime chat <agent> "..." (or pipe the message via stdin)
106
113
  Full spec maritime guide (human) · maritime guide --json (manifest)`);
107
114
  const noArgs = process.argv.length <= 2;
115
+ /**
116
+ * Map any escaped error to an exit code WITHOUT calling process.exit().
117
+ * ExitSignal carries an explicit code (fail(), commander overrides); anything
118
+ * else goes through handleError, which prints a structured failure and
119
+ * throws its own ExitSignal.
120
+ */
121
+ function settleFatal(error) {
122
+ if (error instanceof ExitSignal) {
123
+ process.exitCode = error.exitCode;
124
+ return;
125
+ }
126
+ try {
127
+ handleError(error);
128
+ }
129
+ catch (signal) {
130
+ process.exitCode = signal instanceof ExitSignal ? signal.exitCode : 1;
131
+ }
132
+ }
133
+ /**
134
+ * End-of-run: wait for the (bounded, at most daily) update check so no
135
+ * network work is in flight at teardown, print the notice, then arm an
136
+ * unref'd failsafe timer. Normal runs exit the moment the loop drains and
137
+ * never see the timer; if a stray handle (raw-mode stdin left by a prompt
138
+ * library, a wedged socket) keeps the loop alive, the timer force-exits
139
+ * after 2s. By then nothing is in flight, so even the hard exit is safe
140
+ * from the Windows uv_async_send-during-close assertion.
141
+ */
142
+ async function finishRun() {
143
+ await versionCheckSettled();
144
+ printUpdateNotice(pkg.version);
145
+ const failsafe = setTimeout(() => process.exit(process.exitCode ?? 0), 2000);
146
+ failsafe.unref();
147
+ }
108
148
  // In a linked directory, the bare `maritime` shows the linked agent's status
109
149
  // (the Vercel/Railway "context-aware default"). Outside one, fall back to the
110
150
  // interactive picker in a TTY.
@@ -112,8 +152,10 @@ if (noArgs && getLink()) {
112
152
  process.argv = [process.argv[0], process.argv[1], 'status'];
113
153
  program
114
154
  .parseAsync()
115
- .then(() => printUpdateNotice(pkg.version))
116
- .catch((error) => handleError(error));
155
+ .catch(settleFatal)
156
+ .finally(() => {
157
+ void finishRun();
158
+ });
117
159
  }
118
160
  else if (noArgs && process.stdin.isTTY) {
119
161
  import('./interactive.js').then(async ({ runInteractive }) => {
@@ -123,24 +165,26 @@ else if (noArgs && process.stdin.isTTY) {
123
165
  process.argv = [process.argv[0], process.argv[1], ...args];
124
166
  await program.parseAsync();
125
167
  }
126
- catch {
127
- // User cancelled (Ctrl+C)
128
- process.exit(130);
168
+ catch (error) {
169
+ // Inquirer signals Ctrl-C with ExitPromptError: conventional 130,
170
+ // no error output. Everything else is a real failure.
171
+ if (error?.name === 'ExitPromptError') {
172
+ process.exitCode = 130;
173
+ }
174
+ else {
175
+ settleFatal(error);
176
+ }
129
177
  }
130
178
  finally {
131
- printUpdateNotice(pkg.version);
179
+ void finishRun();
132
180
  }
133
181
  });
134
182
  }
135
183
  else {
136
184
  program
137
185
  .parseAsync()
138
- .then(() => {
139
- printUpdateNotice(pkg.version);
140
- })
141
- .catch((error) => {
142
- // Safety net: any error that escapes a command handler becomes a
143
- // structured failure rather than an uncaught stack trace.
144
- handleError(error);
186
+ .catch(settleFatal)
187
+ .finally(() => {
188
+ void finishRun();
145
189
  });
146
190
  }
package/dist/output.d.ts CHANGED
@@ -21,6 +21,21 @@ export declare const EXIT: {
21
21
  readonly NOT_FOUND: 3;
22
22
  readonly USAGE: 4;
23
23
  };
24
+ /**
25
+ * Thrown instead of calling process.exit(). The entrypoint catches it, sets
26
+ * process.exitCode, and lets the event loop drain naturally.
27
+ *
28
+ * Why: hard process.exit() while libuv handles are still live (undici
29
+ * keep-alive sockets, an in-flight fetch, raw-mode stdin) races handle
30
+ * teardown on Windows and dies with
31
+ * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), src\\win\\async.c"
32
+ * (nodejs/node#56645). Draining the loop is the fix; unwinding via a throw
33
+ * also runs finally blocks (spinners, tty restore) that process.exit skips.
34
+ */
35
+ export declare class ExitSignal extends Error {
36
+ readonly exitCode: number;
37
+ constructor(exitCode: number);
38
+ }
24
39
  export declare function isJsonMode(): boolean;
25
40
  /** Emit a success payload on stdout (used by --json). */
26
41
  export declare function outputJson(data: unknown): void;
@@ -38,8 +53,10 @@ interface FailOptions {
38
53
  status?: number;
39
54
  }
40
55
  /**
41
- * Print an error and exit. JSON mode → `{ok:false, error:{...}}` on stderr.
42
- * Human mode → red "Error:" line on stderr. Always terminates the process.
56
+ * Print an error and end the command. JSON mode → `{ok:false, error:{...}}`
57
+ * on stderr. Human mode → red "Error:" line on stderr. Never returns: it
58
+ * throws ExitSignal, which the entrypoint turns into process.exitCode so the
59
+ * event loop drains before the process ends (see ExitSignal).
43
60
  */
44
61
  export declare function fail(message: string, opts?: FailOptions): never;
45
62
  /**
package/dist/output.js CHANGED
@@ -23,6 +23,25 @@ export const EXIT = {
23
23
  NOT_FOUND: 3,
24
24
  USAGE: 4,
25
25
  };
26
+ /**
27
+ * Thrown instead of calling process.exit(). The entrypoint catches it, sets
28
+ * process.exitCode, and lets the event loop drain naturally.
29
+ *
30
+ * Why: hard process.exit() while libuv handles are still live (undici
31
+ * keep-alive sockets, an in-flight fetch, raw-mode stdin) races handle
32
+ * teardown on Windows and dies with
33
+ * "Assertion failed: !(handle->flags & UV_HANDLE_CLOSING), src\\win\\async.c"
34
+ * (nodejs/node#56645). Draining the loop is the fix; unwinding via a throw
35
+ * also runs finally blocks (spinners, tty restore) that process.exit skips.
36
+ */
37
+ export class ExitSignal extends Error {
38
+ exitCode;
39
+ constructor(exitCode) {
40
+ super(`exit ${exitCode}`);
41
+ this.exitCode = exitCode;
42
+ this.name = 'ExitSignal';
43
+ }
44
+ }
26
45
  export function isJsonMode() {
27
46
  return process.argv.includes('--json');
28
47
  }
@@ -71,8 +90,10 @@ function errorCodeForStatus(status) {
71
90
  }
72
91
  }
73
92
  /**
74
- * Print an error and exit. JSON mode → `{ok:false, error:{...}}` on stderr.
75
- * Human mode → red "Error:" line on stderr. Always terminates the process.
93
+ * Print an error and end the command. JSON mode → `{ok:false, error:{...}}`
94
+ * on stderr. Human mode → red "Error:" line on stderr. Never returns: it
95
+ * throws ExitSignal, which the entrypoint turns into process.exitCode so the
96
+ * event loop drains before the process ends (see ExitSignal).
76
97
  */
77
98
  export function fail(message, opts = {}) {
78
99
  const exitCode = opts.exitCode ?? EXIT.ERROR;
@@ -89,7 +110,7 @@ export function fail(message, opts = {}) {
89
110
  else {
90
111
  process.stderr.write(chalk.red('Error:') + ` ${message}\n`);
91
112
  }
92
- process.exit(exitCode);
113
+ throw new ExitSignal(exitCode);
93
114
  }
94
115
  /**
95
116
  * Centralized catch-block handler. Maps CliHttpError → fail() with the right
@@ -97,6 +118,12 @@ export function fail(message, opts = {}) {
97
118
  * AI agent never has to scrape an uncaught stack trace.
98
119
  */
99
120
  export function handleError(error) {
121
+ // ExitSignal is control flow, not a failure to report: a nested fail()
122
+ // already printed its message and chose its exit code. Re-wrapping it
123
+ // here would clobber the code (usage errors became exit 1) and print a
124
+ // second, useless "exit 4" error line.
125
+ if (error instanceof ExitSignal)
126
+ throw error;
100
127
  if (error instanceof CliHttpError) {
101
128
  fail(error.detail, {
102
129
  status: error.status,
package/dist/prompt.js CHANGED
@@ -41,6 +41,10 @@ export async function promptForPassword(preset) {
41
41
  const value = buffer.toString('utf8');
42
42
  if (value === '\u0003') {
43
43
  cleanup();
44
+ // Deliberate hard exit: Ctrl-C during a password prompt must be
45
+ // immediate. Pause stdin first so the only live handle is gone;
46
+ // this path runs before any network work, so nothing is in flight.
47
+ input.pause();
44
48
  process.exit(130);
45
49
  }
46
50
  if (value === '\r' || value === '\n') {
@@ -1,8 +1,18 @@
1
1
  /**
2
- * Non-blocking daily check against npm registry.
3
- * Prints a one-line update notice after command output if a newer version exists.
2
+ * Daily check against the npm registry.
3
+ *
4
+ * Runs at most once per 24h (throttled at ATTEMPT time, not success time,
5
+ * so an offline machine doesn't re-fire the request on every command), and
6
+ * never in machine/CI contexts where the notice would not be printed
7
+ * anyway. Returns immediately; await versionCheckSettled() before exit.
4
8
  */
5
9
  export declare function checkForUpdates(currentVersion: string): void;
10
+ /**
11
+ * Resolves when the (at most one) in-flight update check has settled.
12
+ * Bounded by the fetch's own 3s AbortSignal; resolves immediately when no
13
+ * check ran this invocation (the usual case, 24h throttle).
14
+ */
15
+ export declare function versionCheckSettled(): Promise<void>;
6
16
  /**
7
17
  * Print update notice if a newer version was found.
8
18
  * Call at the end of command execution.
@@ -11,25 +11,39 @@ function isNewer(a, b) {
11
11
  }
12
12
  return false;
13
13
  }
14
+ // The single in-flight registry request (at most one per day). The
15
+ // entrypoint awaits this before finishing so the process never exits with
16
+ // the fetch's DNS/TLS work still on the libuv threadpool: that in-flight
17
+ // work racing a hard exit was the most common trigger of the Windows
18
+ // `uv_async_send during close` assertion, because this check used to run
19
+ // unawaited on EVERY command.
20
+ let inflight = null;
14
21
  /**
15
- * Non-blocking daily check against npm registry.
16
- * Prints a one-line update notice after command output if a newer version exists.
22
+ * Daily check against the npm registry.
23
+ *
24
+ * Runs at most once per 24h (throttled at ATTEMPT time, not success time,
25
+ * so an offline machine doesn't re-fire the request on every command), and
26
+ * never in machine/CI contexts where the notice would not be printed
27
+ * anyway. Returns immediately; await versionCheckSettled() before exit.
17
28
  */
18
29
  export function checkForUpdates(currentVersion) {
30
+ // Machine mode / non-interactive: the notice is suppressed there, so the
31
+ // network request is pure liability (latency + teardown race).
32
+ if (process.argv.includes('--json') || !process.stderr.isTTY || process.env.CI)
33
+ return;
19
34
  const lastCheck = config.get('lastVersionCheck');
20
35
  if (lastCheck && Date.now() - lastCheck < ONE_DAY)
21
36
  return;
22
- // Fire-and-forget: don't block CLI execution
23
- fetch('https://registry.npmjs.org/maritime-cli/latest', {
37
+ config.set('lastVersionCheck', Date.now());
38
+ inflight = fetch('https://registry.npmjs.org/maritime-cli/latest', {
24
39
  signal: AbortSignal.timeout(3000),
25
40
  })
26
41
  .then((r) => r.json())
27
42
  .then((data) => {
28
- config.set('lastVersionCheck', Date.now());
29
43
  const latest = data.version;
30
- // Store only genuinely-newer versions, and clear anything stale —
44
+ // Store only genuinely-newer versions, and clear anything stale;
31
45
  // otherwise an old cached value survives upgrades forever and the
32
- // banner suggests a "downgrade" (the 1.x → 0.2.1 bug).
46
+ // banner suggests a "downgrade" (the 1.x to 0.2.1 bug).
33
47
  if (latest && isNewer(latest, currentVersion)) {
34
48
  config.set('latestVersion', latest);
35
49
  }
@@ -38,9 +52,17 @@ export function checkForUpdates(currentVersion) {
38
52
  }
39
53
  })
40
54
  .catch(() => {
41
- // Silently ignore — this is a non-blocking check
55
+ // Silently ignore: this is a best-effort check.
42
56
  });
43
57
  }
58
+ /**
59
+ * Resolves when the (at most one) in-flight update check has settled.
60
+ * Bounded by the fetch's own 3s AbortSignal; resolves immediately when no
61
+ * check ran this invocation (the usual case, 24h throttle).
62
+ */
63
+ export function versionCheckSettled() {
64
+ return inflight ?? Promise.resolve();
65
+ }
44
66
  /**
45
67
  * Print update notice if a newer version was found.
46
68
  * Call at the end of command execution.
@@ -9,5 +9,14 @@ export interface WsOptions {
9
9
  /**
10
10
  * Connect to a Maritime WebSocket endpoint with auth token.
11
11
  * Returns a cleanup function that closes the connection.
12
+ *
13
+ * Teardown rules (Windows-safe: no handle may outlive the command):
14
+ * - a pending reconnect timer is cleared on cleanup;
15
+ * - CONNECTING sockets are terminated, not orphaned;
16
+ * - a server close with code 1000 is final (the deploy-status endpoint
17
+ * closes with 1000 on terminal status): reconnecting would just replay
18
+ * the terminal frame and burn the backoff;
19
+ * - the SIGINT listener is removed as soon as the connection is done,
20
+ * whether via cleanup() or the server ending the stream.
12
21
  */
13
22
  export declare function connectWs(path: string, opts: WsOptions): () => void;
package/dist/websocket.js CHANGED
@@ -4,6 +4,15 @@ import { getApiUrl, requireAuth } from './api.js';
4
4
  /**
5
5
  * Connect to a Maritime WebSocket endpoint with auth token.
6
6
  * Returns a cleanup function that closes the connection.
7
+ *
8
+ * Teardown rules (Windows-safe: no handle may outlive the command):
9
+ * - a pending reconnect timer is cleared on cleanup;
10
+ * - CONNECTING sockets are terminated, not orphaned;
11
+ * - a server close with code 1000 is final (the deploy-status endpoint
12
+ * closes with 1000 on terminal status): reconnecting would just replay
13
+ * the terminal frame and burn the backoff;
14
+ * - the SIGINT listener is removed as soon as the connection is done,
15
+ * whether via cleanup() or the server ending the stream.
7
16
  */
8
17
  export function connectWs(path, opts) {
9
18
  const token = requireAuth();
@@ -13,23 +22,32 @@ export function connectWs(path, opts) {
13
22
  const maxReconnects = opts.maxReconnects ?? 2;
14
23
  let reconnects = 0;
15
24
  let closed = false;
25
+ let finished = false;
26
+ let reconnectTimer;
16
27
  let ws;
28
+ function finish() {
29
+ if (finished)
30
+ return;
31
+ finished = true;
32
+ process.removeListener('SIGINT', sigHandler);
33
+ opts.onClose?.();
34
+ }
17
35
  function connect() {
18
36
  ws = new WebSocket(url);
19
37
  ws.on('message', (raw) => {
20
38
  opts.onMessage(raw.toString());
21
39
  });
22
- ws.on('close', () => {
23
- if (closed) {
24
- opts.onClose?.();
40
+ ws.on('close', (code) => {
41
+ if (closed || code === 1000) {
42
+ finish();
25
43
  return;
26
44
  }
27
45
  if (reconnects < maxReconnects) {
28
46
  reconnects++;
29
- setTimeout(connect, 1000 * reconnects);
47
+ reconnectTimer = setTimeout(connect, 1000 * reconnects);
30
48
  }
31
49
  else {
32
- opts.onClose?.();
50
+ finish();
33
51
  }
34
52
  });
35
53
  ws.on('error', (err) => {
@@ -46,9 +64,25 @@ export function connectWs(path, opts) {
46
64
  process.on('SIGINT', sigHandler);
47
65
  function cleanup() {
48
66
  closed = true;
49
- process.removeListener('SIGINT', sigHandler);
50
- if (ws && ws.readyState === WebSocket.OPEN) {
51
- ws.close();
67
+ if (reconnectTimer) {
68
+ clearTimeout(reconnectTimer);
69
+ reconnectTimer = undefined;
70
+ // No socket is open when a reconnect was pending; end the stream now.
71
+ finish();
72
+ return;
73
+ }
74
+ if (ws) {
75
+ if (ws.readyState === WebSocket.OPEN) {
76
+ ws.close();
77
+ }
78
+ else if (ws.readyState === WebSocket.CONNECTING) {
79
+ // close() during the handshake leaves the socket to finish
80
+ // connecting in the background; terminate() drops it now.
81
+ ws.terminate();
82
+ }
83
+ else {
84
+ finish();
85
+ }
52
86
  }
53
87
  }
54
88
  return cleanup;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maritime-cli",
3
- "version": "1.6.1",
3
+ "version": "1.6.2",
4
4
  "description": "Maritime CLI - Deploy and talk to AI agents from your terminal",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,7 @@
24
24
  "AGENTS.md"
25
25
  ],
26
26
  "engines": {
27
- "node": ">=18"
27
+ "node": ">=20.12"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "tsc && chmod +x dist/index.js",