maritime-cli 1.6.1 → 1.7.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.
@@ -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 {
@@ -138,14 +141,16 @@ export const loginCommand = new Command('login')
138
141
  .split(',')
139
142
  .join(', ');
140
143
  console.log(chalk.red('Error:') +
141
- ` this account signs in with ${chalk.bold(providers)} — there's no password to use here.`);
144
+ ` this account signs in with ${chalk.bold(providers)}. There's no password to use here.`);
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
  }
@@ -22,7 +22,7 @@ Examples:
22
22
  maritime message support-bot --user cust_42 --wait 0 "hi" --json # ack + poll later
23
23
 
24
24
  A 200 with status=replied carries the reply inline. status=provisioning/queued
25
- means the user's agent is still being set up — the reply arrives via the
25
+ means the user's agent is still being set up. The reply arrives via the
26
26
  message.reply webhook (maritime guide: webhooks) or GET the message by id.`)
27
27
  .action(async (agentPos, messageParts, opts) => {
28
28
  try {
@@ -35,7 +35,7 @@ message.reply webhook (maritime guide: webhooks) or GET the message by id.`)
35
35
  // The summary omits projectId — fetch the full record for it.
36
36
  const full = await authGet(`/api/agents/${agent.id}`);
37
37
  if (!full.projectId) {
38
- fail(`Agent ${agent.name} has no project — recreate it or use \`maritime chat\`.`, {
38
+ fail(`Agent ${agent.name} has no project. Recreate it or use \`maritime chat\`.`, {
39
39
  code: 'no_project',
40
40
  });
41
41
  }
@@ -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
  }
@@ -19,7 +19,6 @@ export const statusCommand = new Command('status')
19
19
  console.log(chalk.dim('─'.repeat(40)));
20
20
  console.log(` ${'Status:'.padEnd(16)} ${statusColor(agent.status)}`);
21
21
  console.log(` ${'Framework:'.padEnd(16)} ${agent.framework}`);
22
- console.log(` ${'Tier:'.padEnd(16)} ${agent.tier}`);
23
22
  const resParts = [];
24
23
  if (agent.memMb)
25
24
  resParts.push(`${agent.memMb}MB`);
@@ -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/context.d.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  * .maritime/project.json the LINK: which agent this directory operates on.
6
6
  * Machine-local, git-ignored. Written by `link`/`init`.
7
7
  * maritime.json the CONFIG: the source-of-truth description of the
8
- * agent (name, template/framework, persona, env keys,
9
- * tier). Committed to the repo; `deploy` reconciles
8
+ * agent (name, template/framework, persona, env
9
+ * keys). Committed to the repo; `deploy` reconciles
10
10
  * the remote agent to it.
11
11
  *
12
12
  * Both are discovered by walking up from the cwd, so commands work from any
@@ -26,8 +26,6 @@ export interface MaritimeConfig {
26
26
  instructions?: string;
27
27
  /** Env var KEYS this agent expects. Values are set via `env`, never committed. */
28
28
  env?: string[];
29
- /** Optional tier override (smart | extended | always_on). */
30
- tier?: string;
31
29
  }
32
30
  export declare function findLinkPath(start?: string): string | null;
33
31
  export declare function getLink(): ProjectLink | null;
package/dist/context.js CHANGED
@@ -5,8 +5,8 @@
5
5
  * .maritime/project.json the LINK: which agent this directory operates on.
6
6
  * Machine-local, git-ignored. Written by `link`/`init`.
7
7
  * maritime.json the CONFIG: the source-of-truth description of the
8
- * agent (name, template/framework, persona, env keys,
9
- * tier). Committed to the repo; `deploy` reconciles
8
+ * agent (name, template/framework, persona, env
9
+ * keys). Committed to the repo; `deploy` reconciles
10
10
  * the remote agent to it.
11
11
  *
12
12
  * Both are discovered by walking up from the cwd, so commands work from any
package/dist/index.js CHANGED
@@ -28,26 +28,32 @@ import { messageCommand } from './commands/message.js';
28
28
  import { historyCommand } from './commands/history.js';
29
29
  import { triggersCommand } from './commands/triggers.js';
30
30
  import { blueprintCommand } from './commands/blueprint.js';
31
- import { scaleCommand } from './commands/scale.js';
32
31
  import { sleepCommand } from './commands/sleep.js';
33
- import { checkForUpdates, printUpdateNotice } from './version-check.js';
32
+ import { checkForUpdates, printUpdateNotice, versionCheckSettled } from './version-check.js';
34
33
  import { guideCommand } from './commands/guide.js';
35
34
  import { initCommand } from './commands/init.js';
36
35
  import { linkCommand } from './commands/link.js';
37
36
  import { getLink } from './context.js';
38
- import { handleError } from './output.js';
37
+ import { ExitSignal, handleError } from './output.js';
39
38
  const __dirname = dirname(fileURLToPath(import.meta.url));
40
39
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
41
- // Non-blocking version check
40
+ // Daily update check (skipped in --json / non-TTY / CI; awaited in finishRun
41
+ // so its network work can never race process teardown).
42
42
  checkForUpdates(pkg.version);
43
43
  const program = new Command();
44
+ // Commander's default help/version/usage-error paths call process.exit()
45
+ // internally, which is exactly the hard-exit-with-live-handles pattern that
46
+ // crashes on Windows (see ExitSignal). Route them through ExitSignal too.
47
+ program.exitOverride((err) => {
48
+ throw new ExitSignal(err.exitCode ?? 0);
49
+ });
44
50
  program
45
51
  .name('maritime')
46
- .description(chalk.hex('#8B5CF6')('Maritime') + ' \u2014 Deploy AI agents from your terminal')
52
+ .description(chalk.hex('#8B5CF6')('Maritime') + ' · Deploy AI agents from your terminal')
47
53
  .version(pkg.version)
48
54
  .option('--json', 'Output raw JSON instead of formatted tables')
49
55
  .option('--verbose', 'Show detailed request/response info');
50
- // The lean surface — what shows in `maritime --help`. Everything a human or an
56
+ // The lean surface: what shows in `maritime --help`. Everything a human or an
51
57
  // AI agent needs on the happy path: authenticate, create, deploy, talk, observe.
52
58
  const HIDDEN = { hidden: true };
53
59
  // Auth
@@ -55,7 +61,7 @@ program.addCommand(loginCommand);
55
61
  program.addCommand(logoutCommand);
56
62
  program.addCommand(whoamiCommand);
57
63
  program.addCommand(keysCommand);
58
- // Project — link a directory to an agent (the Vercel/Railway model)
64
+ // Project: link a directory to an agent (the Vercel/Railway model)
59
65
  program.addCommand(initCommand);
60
66
  program.addCommand(linkCommand);
61
67
  // Agent lifecycle
@@ -81,7 +87,6 @@ program.addCommand(startCommand, HIDDEN);
81
87
  program.addCommand(stopCommand, HIDDEN);
82
88
  program.addCommand(restartCommand, HIDDEN);
83
89
  program.addCommand(sleepCommand, HIDDEN);
84
- program.addCommand(scaleCommand, HIDDEN);
85
90
  program.addCommand(execCommand, HIDDEN);
86
91
  program.addCommand(infoCommand, HIDDEN);
87
92
  program.addCommand(historyCommand, HIDDEN);
@@ -95,16 +100,49 @@ program.addHelpText('after', `
95
100
  Quickstart (a directory is an agent):
96
101
  maritime init my-agent create + link this folder to an agent
97
102
  maritime chat "hello" talk to the linked agent (no name needed)
98
- maritime deploy push maritime.json changes (persona, tier)
103
+ maritime deploy push maritime.json changes (persona)
99
104
  maritime logs · status · env · open all act on the linked agent
100
105
 
101
106
  For scripts & AI agents:
102
107
  Auth set MARITIME_TOKEN (mk_… key from \`maritime keys create\`)
103
- Output pass --json — results on stdout, errors as JSON on stderr
108
+ Output pass --json: results on stdout, errors as JSON on stderr
104
109
  Exit code 0 ok · 1 error · 2 auth · 3 not-found · 4 usage
105
110
  Talk maritime chat <agent> "..." (or pipe the message via stdin)
106
111
  Full spec maritime guide (human) · maritime guide --json (manifest)`);
107
112
  const noArgs = process.argv.length <= 2;
113
+ /**
114
+ * Map any escaped error to an exit code WITHOUT calling process.exit().
115
+ * ExitSignal carries an explicit code (fail(), commander overrides); anything
116
+ * else goes through handleError, which prints a structured failure and
117
+ * throws its own ExitSignal.
118
+ */
119
+ function settleFatal(error) {
120
+ if (error instanceof ExitSignal) {
121
+ process.exitCode = error.exitCode;
122
+ return;
123
+ }
124
+ try {
125
+ handleError(error);
126
+ }
127
+ catch (signal) {
128
+ process.exitCode = signal instanceof ExitSignal ? signal.exitCode : 1;
129
+ }
130
+ }
131
+ /**
132
+ * End-of-run: wait for the (bounded, at most daily) update check so no
133
+ * network work is in flight at teardown, print the notice, then arm an
134
+ * unref'd failsafe timer. Normal runs exit the moment the loop drains and
135
+ * never see the timer; if a stray handle (raw-mode stdin left by a prompt
136
+ * library, a wedged socket) keeps the loop alive, the timer force-exits
137
+ * after 2s. By then nothing is in flight, so even the hard exit is safe
138
+ * from the Windows uv_async_send-during-close assertion.
139
+ */
140
+ async function finishRun() {
141
+ await versionCheckSettled();
142
+ printUpdateNotice(pkg.version);
143
+ const failsafe = setTimeout(() => process.exit(process.exitCode ?? 0), 2000);
144
+ failsafe.unref();
145
+ }
108
146
  // In a linked directory, the bare `maritime` shows the linked agent's status
109
147
  // (the Vercel/Railway "context-aware default"). Outside one, fall back to the
110
148
  // interactive picker in a TTY.
@@ -112,8 +150,10 @@ if (noArgs && getLink()) {
112
150
  process.argv = [process.argv[0], process.argv[1], 'status'];
113
151
  program
114
152
  .parseAsync()
115
- .then(() => printUpdateNotice(pkg.version))
116
- .catch((error) => handleError(error));
153
+ .catch(settleFatal)
154
+ .finally(() => {
155
+ void finishRun();
156
+ });
117
157
  }
118
158
  else if (noArgs && process.stdin.isTTY) {
119
159
  import('./interactive.js').then(async ({ runInteractive }) => {
@@ -123,24 +163,26 @@ else if (noArgs && process.stdin.isTTY) {
123
163
  process.argv = [process.argv[0], process.argv[1], ...args];
124
164
  await program.parseAsync();
125
165
  }
126
- catch {
127
- // User cancelled (Ctrl+C)
128
- process.exit(130);
166
+ catch (error) {
167
+ // Inquirer signals Ctrl-C with ExitPromptError: conventional 130,
168
+ // no error output. Everything else is a real failure.
169
+ if (error?.name === 'ExitPromptError') {
170
+ process.exitCode = 130;
171
+ }
172
+ else {
173
+ settleFatal(error);
174
+ }
129
175
  }
130
176
  finally {
131
- printUpdateNotice(pkg.version);
177
+ void finishRun();
132
178
  }
133
179
  });
134
180
  }
135
181
  else {
136
182
  program
137
183
  .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);
184
+ .catch(settleFatal)
185
+ .finally(() => {
186
+ void finishRun();
145
187
  });
146
188
  }
@@ -16,14 +16,13 @@ const COMMANDS = [
16
16
  { name: 'triggers', value: 'triggers', description: 'Manage triggers', needsAgent: false },
17
17
  { name: 'templates', value: 'templates', description: 'Browse templates', needsAgent: false },
18
18
  { name: 'history', value: 'history', description: 'View deploy history', needsAgent: true },
19
- { name: 'blueprint', value: 'blueprint', description: 'Manage blueprints', needsAgent: false },
20
- { name: 'scale', value: 'scale', description: 'Change agent tier', needsAgent: true },
19
+ { name: 'blueprint', value: 'blueprint', description: 'Manage templates', needsAgent: false },
21
20
  { name: 'open', value: 'open', description: 'Open agent in browser', needsAgent: true },
22
21
  { name: 'whoami', value: 'whoami', description: 'Show current user', needsAgent: false },
23
22
  { name: 'logout', value: 'logout', description: 'Log out', needsAgent: false },
24
23
  ];
25
24
  export async function runInteractive() {
26
- console.log(chalk.hex('#8B5CF6')('\n Maritime') + chalk.dim(' — interactive mode\n'));
25
+ console.log(chalk.hex('#8B5CF6')('\n Maritime') + chalk.dim(' · interactive mode\n'));
27
26
  const command = await select({
28
27
  message: 'What would you like to do?',
29
28
  choices: COMMANDS.map((c) => ({
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') {
package/dist/resolve.d.ts CHANGED
@@ -3,7 +3,6 @@ export interface AgentSummary {
3
3
  name: string;
4
4
  status: string;
5
5
  framework: string;
6
- tier?: string;
7
6
  createdAt?: string;
8
7
  }
9
8
  /**
@@ -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.