maritime-cli 1.2.0 → 1.3.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.
package/AGENTS.md CHANGED
@@ -62,15 +62,50 @@ Always read stdout for results and branch on the exit code. Never parse human te
62
62
  | `3` | not found (no such agent) |
63
63
  | `4` | usage error (missing/invalid arguments) |
64
64
 
65
+ ## The project model — a directory is an agent
66
+
67
+ Like `vercel` / `railway`, you can link a directory to an agent and then run
68
+ commands without naming it. Two files:
69
+
70
+ - **`maritime.json`** — committed config describing the agent: `name`,
71
+ `template` (or `framework`), persona `instructions`, env `["KEY", …]` (keys
72
+ only), optional `tier`. The source of truth.
73
+ - **`.maritime/project.json`** — machine-local link (git-ignored) pointing at
74
+ the agent this directory operates on.
75
+
76
+ ```bash
77
+ maritime init <name> --json # scaffold maritime.json + AGENTS.md, create + link
78
+ maritime link <agent> --json # link this dir to an existing agent
79
+ maritime deploy --json # reconcile the agent to maritime.json, then ship
80
+ ```
81
+
82
+ Once linked, the `<agent>` argument is **optional on every command** — it falls
83
+ back to the linked agent (resolved by walking up from the cwd):
84
+
85
+ ```bash
86
+ maritime chat "what's open?" --json # talks to the linked agent
87
+ maritime logs --json # linked agent's logs
88
+ maritime env set FOO=bar --json # linked agent's env (KEY=value ⇒ no agent token)
89
+ maritime status --json # linked agent's detail
90
+ ```
91
+
92
+ For automation you can ignore linking entirely and pass `<agent>` on every call
93
+ (below). To target a different agent from inside a linked dir, pass it
94
+ explicitly: `-a/--agent` on `chat`, or the positional name on commands that take
95
+ a single agent.
96
+
65
97
  ## The interaction primitive — `chat`
66
98
 
67
99
  Send a message to a deployed agent and get its reply. Sleeping serverless
68
100
  agents are auto-woken by the backend.
69
101
 
70
102
  ```bash
71
- # message as argument
103
+ # explicit agent + message
72
104
  maritime chat <agent> "summarize today's incidents" --json
73
105
 
106
+ # linked dir: positionals are the message, target = linked agent
107
+ maritime chat "summarize today's incidents" --json
108
+
74
109
  # message piped via stdin (best for long / multi-line prompts)
75
110
  cat prompt.txt | maritime chat <agent> --json
76
111
 
@@ -78,7 +113,7 @@ cat prompt.txt | maritime chat <agent> --json
78
113
  maritime chat <agent> "and the one before that?" --conversation-id abc123 --json
79
114
  ```
80
115
 
81
- `<agent>` is a name (exact match) or an ID prefix.
116
+ `<agent>` is a name (exact match), an ID prefix, or — omitted — the linked agent.
82
117
 
83
118
  Success shape:
84
119
 
@@ -133,17 +168,20 @@ cat prod.env | maritime env import <agent> - --reload --json
133
168
  maritime env list <agent> --json
134
169
  maritime env remove <agent> OPENAI_API_KEY --reload --json
135
170
  maritime env reload <agent> --json # hot-reload without changing values
171
+ maritime env pull <agent> .env --json # write env to a local .env (secret VALUES masked)
136
172
  ```
137
173
 
138
174
  `import`/`set` return `{ok, uploaded:[…], failed:[{key,error}], reloaded}`.
139
- A partial failure exits `1` with the failed keys listed in `failed`.
175
+ A partial failure exits `1` with the failed keys listed in `failed`. In a linked
176
+ dir the agent is implied: `maritime env set FOO=bar --json`, `maritime env pull`.
140
177
 
141
178
  ## Command map
142
179
 
180
+ Project: `init`, `link`, `deploy` (a directory ⇄ an agent)
143
181
  Auth / keys: `login`, `logout`, `whoami`, `keys {create,list,revoke}`
144
182
  Lifecycle: `create`, `list`, `deploy`, `delete`
145
183
  Interaction: `chat`/`send`
146
- Config: `env {set,import,list,remove,reload}`
184
+ Config: `env {set,import,list,remove,reload,pull}`
147
185
  Observe: `status`, `logs`
148
186
 
149
187
  Advanced / ops (hidden from `--help`, still fully supported): `start`, `stop`,
@@ -1,6 +1,7 @@
1
1
  import { Command } from 'commander';
2
2
  import { authPost } from '../api.js';
3
3
  import { resolveAgent } from '../resolve.js';
4
+ import { getLinkedAgentId } from '../context.js';
4
5
  import { outputResult, fail, handleError, makeSpinner } from '../output.js';
5
6
  /** Read all of stdin (used when the message isn't passed as an argument). */
6
7
  function readStdin() {
@@ -36,18 +37,37 @@ function extractReply(response) {
36
37
  export const chatCommand = new Command('chat')
37
38
  .alias('send')
38
39
  .description('Send a message to an agent and print its reply')
39
- .argument('<agent>', 'Agent name or ID')
40
+ .argument('[agent]', 'Agent name or ID (optional in a linked directory)')
40
41
  .argument('[message...]', 'Message to send (reads stdin if omitted)')
42
+ .option('-a, --agent <name>', 'Target a specific agent (overrides the linked one)')
41
43
  .option('-c, --conversation-id <id>', 'Conversation ID for multi-turn context')
42
44
  .addHelpText('after', `
43
45
  Examples:
44
- maritime chat my-agent "what's the status?" --json
45
- cat prompt.txt | maritime chat my-agent --json
46
- maritime chat my-agent "and then?" --conversation-id abc123`)
47
- .action(async (agentArg, messageParts, opts) => {
46
+ maritime chat "what's the status?" # linked agent
47
+ maritime chat my-agent "what's the status?" # explicit agent
48
+ cat prompt.txt | maritime chat --json # linked agent, long prompt
49
+ maritime chat -a other "and then?" --conversation-id abc123`)
50
+ .action(async (agentPos, messageParts, opts) => {
48
51
  try {
49
- // Message comes from args, or stdin when piped (great for long prompts).
50
- let message = (messageParts || []).join(' ').trim();
52
+ // Disambiguate "which agent" vs "the message" using the linked context:
53
+ // in a linked dir all positionals are the message (target = linked agent,
54
+ // overridable with -a); otherwise the first positional is the agent.
55
+ const positionals = [agentPos, ...(messageParts || [])].filter(Boolean);
56
+ let targetArg;
57
+ let message;
58
+ if (opts.agent) {
59
+ targetArg = opts.agent;
60
+ message = positionals.join(' ');
61
+ }
62
+ else if (getLinkedAgentId()) {
63
+ targetArg = undefined;
64
+ message = positionals.join(' ');
65
+ }
66
+ else {
67
+ targetArg = agentPos;
68
+ message = (messageParts || []).join(' ');
69
+ }
70
+ message = message.trim();
51
71
  if (!message && !process.stdin.isTTY) {
52
72
  message = (await readStdin()).trim();
53
73
  }
@@ -57,7 +77,7 @@ Examples:
57
77
  exitCode: 4,
58
78
  });
59
79
  }
60
- const agent = await resolveAgent(agentArg);
80
+ const agent = await resolveAgent(targetArg);
61
81
  const spinner = await makeSpinner(`Waiting for ${agent.name}...`);
62
82
  let result;
63
83
  try {
@@ -6,7 +6,7 @@ import { promptForValue } from '../prompt.js';
6
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
- .argument('<agent>', 'Agent name or ID')
9
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
10
10
  .option('-y, --yes', 'Skip confirmation')
11
11
  .action(async (agentArg, opts) => {
12
12
  try {
@@ -1,82 +1,147 @@
1
1
  import { Command } from 'commander';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
- import { authPost } from '../api.js';
4
+ import { authPost, authPut } from '../api.js';
5
5
  import { resolveAgent } from '../resolve.js';
6
- import { isJsonMode, outputJson, handleError } from '../output.js';
6
+ import { getConfig, getLinkedAgentId, writeLink } from '../context.js';
7
+ import { isJsonMode, outputJson, fail, handleError, EXIT } from '../output.js';
7
8
  import { connectWs } from '../websocket.js';
8
9
  export const deployCommand = new Command('deploy')
9
- .description('Deploy an agent')
10
- .argument('<agent>', 'Agent name or ID')
11
- .option('--source <source>', 'Deploy source (github, docker, template)', 'template')
10
+ .description('Deploy this directory: reconcile the agent to maritime.json, then ship it')
11
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent / maritime.json)')
12
+ .option('--source <source>', 'Deploy source (github, docker, template)')
12
13
  .option('--repo <url>', 'GitHub repository URL')
13
14
  .option('--image <name>', 'Docker image name')
14
15
  .option('--branch <branch>', 'Git branch')
15
16
  .option('-w, --wait', 'Wait for deployment to complete')
17
+ .addHelpText('after', `
18
+ In a linked project, just run \`maritime deploy\` — it reads maritime.json,
19
+ creates the agent if needed, applies the persona/tier, and redeploys.
20
+ Explicit sources still work: \`maritime deploy --source github --repo <url>\`.`)
16
21
  .action(async (agentArg, opts) => {
17
- const agent = await resolveAgent(agentArg);
18
- const body = {
19
- agentId: agent.id,
20
- source: opts.source,
21
- };
22
- if (opts.repo)
23
- body.repoUrl = opts.repo;
24
- if (opts.image)
25
- body.imageName = opts.image;
26
- if (opts.branch)
27
- body.branch = opts.branch;
28
- const spinner = ora(`Deploying ${chalk.bold(agent.name)}...`).start();
29
22
  try {
30
- const deployment = await authPost('/api/deploy', body);
31
- if (isJsonMode() && !opts.wait) {
32
- spinner.stop();
33
- outputJson(deployment);
34
- return;
23
+ const config = getConfig();
24
+ const explicitSource = Boolean(opts.source || opts.repo || opts.image);
25
+ // ── Resolve (or create) the target agent ──────────────────────────
26
+ let agent;
27
+ if (agentArg) {
28
+ agent = await resolveAgent(agentArg);
35
29
  }
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;
30
+ else if (getLinkedAgentId()) {
31
+ agent = await resolveAgent(); // linked
41
32
  }
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();
33
+ else if (config?.name) {
34
+ // First deploy of a configured-but-not-yet-created project: create it
35
+ // from maritime.json and link this directory (the `vercel` first run).
36
+ agent = await createFromConfig(config);
37
+ writeLink({ agentId: agent.id, name: agent.name });
38
+ // create auto-deploys, so we're done unless the user forced a source.
39
+ if (!explicitSource) {
40
+ finish({ ok: true, action: 'deploy', created: true, agentId: agent.id, agentName: agent.name, status: 'deploying' }, () => console.log(chalk.green('Created + deploying ') + chalk.bold(agent.name)));
41
+ return;
42
+ }
43
+ }
44
+ else {
45
+ fail('Nothing to deploy. Pass an agent, link one (`maritime link`), or add maritime.json (`maritime init`).', { code: 'no_agent', exitCode: EXIT.USAGE });
46
+ }
47
+ // ── Reconcile the agent to maritime.json (persona + tier) ─────────
48
+ if (config && !explicitSource) {
49
+ await reconcile(agent.id, config);
50
+ }
51
+ // ── Trigger the deployment ────────────────────────────────────────
52
+ const body = {
53
+ agentId: agent.id,
54
+ source: opts.source || 'template',
55
+ };
56
+ if (opts.repo)
57
+ body.repoUrl = opts.repo;
58
+ if (opts.image)
59
+ body.imageName = opts.image;
60
+ if (opts.branch)
61
+ body.branch = opts.branch;
62
+ const spinner = isJsonMode() ? null : ora(`Deploying ${chalk.bold(agent.name)}...`).start();
63
+ try {
64
+ const deployment = await authPost('/api/deploy', body);
65
+ if (!opts.wait) {
66
+ spinner?.succeed(chalk.green('Deployment started for ') + chalk.bold(agent.name));
67
+ finish(deployment, () => {
68
+ console.log(chalk.dim(` Deployment ID: ${deployment.id}`));
69
+ console.log(chalk.dim(` Status: ${deployment.status}`));
70
+ });
71
+ return;
72
+ }
73
+ // --wait: stream deploy progress via WebSocket
74
+ if (spinner)
75
+ spinner.text = `Building ${chalk.bold(agent.name)}...`;
76
+ await new Promise((resolve, reject) => {
77
+ const cleanup = connectWs(`/api/deploy/${agent.id}/status`, {
78
+ onMessage(data) {
79
+ try {
80
+ const msg = JSON.parse(data);
81
+ if (msg.message && spinner)
82
+ spinner.text = msg.message;
83
+ if (msg.status === 'success' || msg.status === 'completed') {
84
+ spinner?.succeed(chalk.green('Deployment complete: ') + chalk.bold(agent.name));
85
+ cleanup();
86
+ resolve();
87
+ }
88
+ else if (msg.status === 'failed') {
89
+ spinner?.fail(chalk.red('Deployment failed: ') + (msg.message || 'unknown error'));
90
+ cleanup();
91
+ reject(new Error('Deployment failed'));
92
+ }
56
93
  }
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'));
94
+ catch {
95
+ if (spinner)
96
+ spinner.text = data.trim();
61
97
  }
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,
98
+ },
99
+ onClose() {
100
+ resolve();
101
+ },
102
+ maxReconnects: 3,
103
+ });
72
104
  });
73
- });
74
- if (isJsonMode()) {
75
- outputJson(deployment);
105
+ finish(deployment, () => { });
106
+ }
107
+ catch (error) {
108
+ spinner?.fail('Deployment failed');
109
+ throw error;
76
110
  }
77
111
  }
78
112
  catch (error) {
79
- spinner.fail('Deployment failed');
80
113
  handleError(error);
81
114
  }
82
115
  });
116
+ /** Create an agent from a maritime.json config (template/framework + persona). */
117
+ async function createFromConfig(config) {
118
+ const body = { name: config.name };
119
+ if (config.template)
120
+ body.templateId = config.template;
121
+ if (config.framework)
122
+ body.framework = config.framework;
123
+ if (config.tier)
124
+ body.tier = config.tier;
125
+ if (config.instructions)
126
+ body.instructions = config.instructions;
127
+ return authPost('/api/agents', body);
128
+ }
129
+ /** Apply persona + tier from config to an existing agent (env takes effect on redeploy). */
130
+ async function reconcile(agentId, config) {
131
+ if (config.instructions) {
132
+ await authPost(`/api/agents/${agentId}/env`, {
133
+ key: 'MARITIME_INSTRUCTIONS',
134
+ value: config.instructions,
135
+ is_secret: false,
136
+ });
137
+ }
138
+ if (config.tier) {
139
+ await authPut(`/api/agents/${agentId}`, { tier: config.tier });
140
+ }
141
+ }
142
+ function finish(json, human) {
143
+ if (isJsonMode())
144
+ outputJson(json);
145
+ else
146
+ human();
147
+ }
@@ -1,8 +1,9 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
2
2
  import { Command } from 'commander';
3
3
  import chalk from 'chalk';
4
4
  import { authGet, authPost, authDelete } from '../api.js';
5
5
  import { resolveAgent } from '../resolve.js';
6
+ import { getLinkedAgentId } from '../context.js';
6
7
  import { isJsonMode, outputJson, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
7
8
  /** Parse a single KEY=value token (as passed on the command line). */
8
9
  function parsePair(pair) {
@@ -72,7 +73,7 @@ Secrets are encrypted and marked secret by default; changes apply on next
72
73
  boot unless you pass --reload.`);
73
74
  // --- list -----------------------------------------------------------------
74
75
  envCommand
75
- .command('list <agent>')
76
+ .command('list [agent]')
76
77
  .alias('ls')
77
78
  .description('List environment variables')
78
79
  .action(async (agentArg) => {
@@ -100,14 +101,30 @@ envCommand
100
101
  });
101
102
  // --- set (one or many pairs) ----------------------------------------------
102
103
  envCommand
103
- .command('set <agent> <pairs...>')
104
+ .command('set [agent] [pairs...]')
104
105
  .description('Set one or more environment variables (KEY=value KEY2=value2 …)')
105
106
  .option('--no-secret', 'Store as plain (non-secret) values')
106
107
  .option('-r, --reload', 'Hot-reload env into the running container afterward')
107
108
  .action(async (agentArg, rawPairs, opts) => {
108
109
  try {
109
- const pairs = rawPairs.map(parsePair);
110
- const agent = await resolveAgent(agentArg);
110
+ // A leading token without "=" is the agent name; otherwise everything is
111
+ // pairs and the agent comes from the linked directory.
112
+ const positionals = [agentArg, ...(rawPairs || [])].filter(Boolean);
113
+ let target;
114
+ let pairTokens;
115
+ if (positionals.length > 0 && !positionals[0].includes('=')) {
116
+ target = positionals[0];
117
+ pairTokens = positionals.slice(1);
118
+ }
119
+ else {
120
+ target = undefined;
121
+ pairTokens = positionals;
122
+ }
123
+ if (pairTokens.length === 0) {
124
+ fail('No KEY=value pairs given.', { code: 'usage', exitCode: EXIT.USAGE });
125
+ }
126
+ const pairs = pairTokens.map(parsePair);
127
+ const agent = await resolveAgent(target);
111
128
  const spinner = await makeSpinner(`Setting ${pairs.length} var${pairs.length === 1 ? '' : 's'} for ${agent.name}...`);
112
129
  const { uploaded, failed } = await uploadVars(agent.id, pairs, opts.secret);
113
130
  let reloaded = false;
@@ -141,14 +158,26 @@ envCommand
141
158
  });
142
159
  // --- import (.env file or stdin) ------------------------------------------
143
160
  envCommand
144
- .command('import <agent> [file]')
161
+ .command('import [agent] [file]')
145
162
  .description('Upload all keys from a .env file (or stdin if file is "-" / omitted)')
146
163
  .option('--plain', 'Store as plain (non-secret) values')
147
164
  .option('-r, --reload', 'Hot-reload env into the running container afterward')
148
165
  .action(async (agentArg, file, opts) => {
149
166
  try {
167
+ // In a linked dir the single positional is the file (agent = linked);
168
+ // otherwise it's `<agent> [file]`.
169
+ let target;
170
+ let srcFile;
171
+ if (getLinkedAgentId()) {
172
+ target = undefined;
173
+ srcFile = agentArg;
174
+ }
175
+ else {
176
+ target = agentArg;
177
+ srcFile = file;
178
+ }
150
179
  let text;
151
- if (!file || file === '-') {
180
+ if (!srcFile || srcFile === '-') {
152
181
  if (process.stdin.isTTY) {
153
182
  fail('No input. Pass a .env file path or pipe one via stdin.', {
154
183
  code: 'usage',
@@ -159,17 +188,17 @@ envCommand
159
188
  }
160
189
  else {
161
190
  try {
162
- text = readFileSync(file, 'utf8');
191
+ text = readFileSync(srcFile, 'utf8');
163
192
  }
164
193
  catch {
165
- fail(`Cannot read file: ${file}`, { code: 'usage', exitCode: EXIT.USAGE });
194
+ fail(`Cannot read file: ${srcFile}`, { code: 'usage', exitCode: EXIT.USAGE });
166
195
  }
167
196
  }
168
197
  const pairs = parseDotenv(text);
169
198
  if (pairs.length === 0) {
170
199
  fail('No KEY=value pairs found in input.', { code: 'usage', exitCode: EXIT.USAGE });
171
200
  }
172
- const agent = await resolveAgent(agentArg);
201
+ const agent = await resolveAgent(target);
173
202
  const spinner = await makeSpinner(`Importing ${pairs.length} vars into ${agent.name}...`);
174
203
  const { uploaded, failed } = await uploadVars(agent.id, pairs, !opts.plain);
175
204
  let reloaded = false;
@@ -203,13 +232,28 @@ envCommand
203
232
  });
204
233
  // --- remove ----------------------------------------------------------------
205
234
  envCommand
206
- .command('remove <agent> <key>')
235
+ .command('remove [agent] [key]')
207
236
  .alias('rm')
208
237
  .description('Remove an environment variable')
209
238
  .option('-r, --reload', 'Hot-reload env into the running container afterward')
210
- .action(async (agentArg, key, opts) => {
239
+ .action(async (agentArg, keyArg, opts) => {
211
240
  try {
212
- const agent = await resolveAgent(agentArg);
241
+ // In a linked dir the single positional is the key (agent = linked);
242
+ // otherwise it's `<agent> <key>`.
243
+ let target;
244
+ let key;
245
+ if (getLinkedAgentId()) {
246
+ target = undefined;
247
+ key = agentArg;
248
+ }
249
+ else {
250
+ target = agentArg;
251
+ key = keyArg;
252
+ }
253
+ if (!key) {
254
+ fail('No env key given to remove.', { code: 'usage', exitCode: EXIT.USAGE });
255
+ }
256
+ const agent = await resolveAgent(target);
213
257
  const spinner = await makeSpinner(`Removing ${key} from ${agent.name}...`);
214
258
  await authDelete(`/api/agents/${agent.id}/env/${encodeURIComponent(key)}`);
215
259
  let reloaded = false;
@@ -231,7 +275,7 @@ envCommand
231
275
  });
232
276
  // --- reload ----------------------------------------------------------------
233
277
  envCommand
234
- .command('reload <agent>')
278
+ .command('reload [agent]')
235
279
  .description('Hot-reload env vars into the running container')
236
280
  .action(async (agentArg) => {
237
281
  try {
@@ -245,3 +289,55 @@ envCommand
245
289
  handleError(error);
246
290
  }
247
291
  });
292
+ // --- pull ------------------------------------------------------------------
293
+ envCommand
294
+ .command('pull [agent] [file]')
295
+ .description('Write the agent’s env to a local .env file (secret values are masked)')
296
+ .option('-f, --force', 'Overwrite the file if it already exists')
297
+ .action(async (agentArg, fileArg, opts) => {
298
+ try {
299
+ // In a linked dir the single positional is the output file (agent = linked).
300
+ let target;
301
+ let outFile;
302
+ if (getLinkedAgentId()) {
303
+ target = undefined;
304
+ outFile = agentArg || '.env';
305
+ }
306
+ else {
307
+ target = agentArg;
308
+ outFile = fileArg || '.env';
309
+ }
310
+ const agent = await resolveAgent(target);
311
+ const vars = await authGet(`/api/agents/${agent.id}/env`);
312
+ const lines = [];
313
+ const keys = [];
314
+ const secretKeys = [];
315
+ for (const v of vars) {
316
+ keys.push(v.key);
317
+ if (v.is_secret) {
318
+ secretKeys.push(v.key);
319
+ lines.push(`${v.key}= # secret — value not exported; fill it in`);
320
+ }
321
+ else {
322
+ lines.push(`${v.key}=${v.value}`);
323
+ }
324
+ }
325
+ const text = lines.length ? lines.join('\n') + '\n' : '';
326
+ if (existsSync(outFile) && !opts.force) {
327
+ fail(`${outFile} already exists. Pass --force to overwrite.`, {
328
+ code: 'usage',
329
+ exitCode: EXIT.USAGE,
330
+ });
331
+ }
332
+ writeFileSync(outFile, text);
333
+ outputResult({ ok: true, agentId: agent.id, file: outFile, keys, secretKeys }, () => {
334
+ console.log(chalk.green(`Pulled ${keys.length} var(s) → `) + chalk.bold(outFile));
335
+ if (secretKeys.length) {
336
+ console.log(chalk.dim(` ${secretKeys.length} secret value(s) masked — fill in: ${secretKeys.join(', ')}`));
337
+ }
338
+ });
339
+ }
340
+ catch (error) {
341
+ handleError(error);
342
+ }
343
+ });
@@ -15,6 +15,7 @@ const CONTRACT = {
15
15
  exitCodes: { '0': 'ok', '1': 'error', '2': 'auth', '3': 'not_found', '4': 'usage' },
16
16
  interaction: 'Talk to a deployed agent with `maritime chat <agent> <message>` (or pipe the message via stdin). Returns the reply text (or {response} under --json). Sleeping serverless agents auto-wake.',
17
17
  resources: 'create accepts per-agent overrides: --ram <mb>, --cpu <cores>, --idle <seconds> | --always-on, --disk <gb>, --max-compute <minutes>. Omitted = inherit the tier/plan.',
18
+ project: 'A directory can be linked to an agent (like vercel/railway). `maritime init <name>` scaffolds maritime.json + AGENTS.md and links it; `maritime link <agent>` links an existing one; `maritime deploy` reconciles the agent to maritime.json. Once linked, the <agent> argument is optional on every command (resolved from .maritime/project.json, walking up from cwd).',
18
19
  apiBase: 'Override the API base with MARITIME_API_URL (default https://api.maritime.sh).',
19
20
  };
20
21
  /* eslint-disable @typescript-eslint/no-explicit-any */
@@ -5,7 +5,7 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { isJsonMode, outputJson, handleError } from '../output.js';
6
6
  export const infoCommand = new Command('info')
7
7
  .description('Show full details for an agent')
8
- .argument('<agent>', 'Agent name or ID')
8
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
9
9
  .action(async (agentArg) => {
10
10
  try {
11
11
  const summary = await resolveAgent(agentArg);
@@ -0,0 +1,2 @@
1
+ import { Command } from 'commander';
2
+ export declare const initCommand: Command;
@@ -0,0 +1,119 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { Command } from 'commander';
4
+ import chalk from 'chalk';
5
+ import { authPost } from '../api.js';
6
+ import { getConfig, writeConfig, writeLink, configExists, CONFIG_FILENAME, } from '../context.js';
7
+ import { promptForValue } from '../prompt.js';
8
+ import { isJsonMode, outputResult, fail, handleError, makeSpinner, EXIT } from '../output.js';
9
+ const AGENTS_MD = (name, instructions) => `# ${name}
10
+
11
+ ${instructions || 'Describe what this agent does and how it should behave. This file is the agent\'s persona — it is loaded into the agent\'s workspace at boot.'}
12
+
13
+ ## Guidelines
14
+ - Be concise and helpful.
15
+ - Ask for missing information instead of guessing.
16
+ `;
17
+ export const initCommand = new Command('init')
18
+ .description(`Scaffold ${CONFIG_FILENAME}, create the agent, and link this directory to it`)
19
+ .argument('[name]', 'Agent name (defaults to the folder name)')
20
+ .option('-t, --template <id>', 'Template to base the agent on (default: openclaw)')
21
+ .option('--framework <framework>', 'Framework for bring-your-own-code agents (instead of a template)')
22
+ .option('--instructions <text>', 'Plain-English persona for the agent')
23
+ .option('--tier <tier>', 'Tier: smart, extended, always_on')
24
+ .option('--no-create', 'Only write the config files; do not create the agent yet')
25
+ .addHelpText('after', `
26
+ Examples:
27
+ maritime init # scaffold + create, named after the folder
28
+ maritime init support-bot # explicit name
29
+ maritime init bot --no-create # just write ${CONFIG_FILENAME} + AGENTS.md
30
+ After init, run \`maritime deploy\` to push changes, or \`maritime chat "…"\`.`)
31
+ .action(async (nameArg, opts) => {
32
+ try {
33
+ const interactive = !isJsonMode() && process.stdin.isTTY;
34
+ const existing = getConfig() ?? {};
35
+ // Name: arg → existing config → folder name (prompted if interactive).
36
+ let name = nameArg || existing.name || basename(process.cwd());
37
+ if (interactive && !nameArg && !existing.name) {
38
+ name = (await promptForValue('Agent name', undefined)) || name;
39
+ }
40
+ if (!name) {
41
+ fail('Agent name is required.', { code: 'usage', exitCode: EXIT.USAGE });
42
+ }
43
+ // Template/framework: explicit flags win; else keep existing; else default
44
+ // to the openclaw template so a bare `init` yields a *working* agent.
45
+ const framework = opts.framework || existing.framework;
46
+ const template = framework
47
+ ? undefined
48
+ : opts.template || existing.template || 'openclaw';
49
+ const instructions = opts.instructions ?? existing.instructions ?? '';
50
+ const tier = opts.tier || existing.tier;
51
+ const config = {
52
+ name,
53
+ ...(template ? { template } : {}),
54
+ ...(framework ? { framework } : {}),
55
+ ...(instructions ? { instructions } : {}),
56
+ env: existing.env ?? [],
57
+ ...(tier ? { tier } : {}),
58
+ };
59
+ const wroteConfig = !configExists();
60
+ const configPath = writeConfig(config);
61
+ // Scaffold an AGENTS.md persona file if there isn't one already.
62
+ const agentsMdPath = join(process.cwd(), 'AGENTS.md');
63
+ let wroteAgentsMd = false;
64
+ if (!existsSync(agentsMdPath)) {
65
+ writeFileSync(agentsMdPath, AGENTS_MD(name, instructions));
66
+ wroteAgentsMd = true;
67
+ }
68
+ // Create + link unless --no-create.
69
+ let agent = null;
70
+ let linkPath = null;
71
+ if (opts.create !== false) {
72
+ const spinner = await makeSpinner(`Creating ${chalk.bold(name)}...`);
73
+ try {
74
+ const body = { name };
75
+ if (template)
76
+ body.templateId = template;
77
+ if (framework)
78
+ body.framework = framework;
79
+ if (tier)
80
+ body.tier = tier;
81
+ if (instructions)
82
+ body.instructions = instructions;
83
+ agent = await authPost('/api/agents', body);
84
+ }
85
+ catch (error) {
86
+ spinner.fail('Failed to create agent');
87
+ throw error;
88
+ }
89
+ spinner.succeed(chalk.green('Created ') + chalk.bold(agent.name) + chalk.dim(` (${agent.id})`));
90
+ linkPath = writeLink({ agentId: agent.id, name: agent.name });
91
+ }
92
+ outputResult({
93
+ ok: true,
94
+ action: 'init',
95
+ config: configPath,
96
+ wroteConfig,
97
+ wroteAgentsMd,
98
+ agentId: agent?.id ?? null,
99
+ agentName: agent?.name ?? name,
100
+ linked: Boolean(linkPath),
101
+ }, () => {
102
+ console.log(chalk.dim(` ${wroteConfig ? 'wrote' : 'updated'} ${CONFIG_FILENAME}`));
103
+ if (wroteAgentsMd)
104
+ console.log(chalk.dim(' wrote AGENTS.md'));
105
+ if (agent) {
106
+ console.log(chalk.dim(' linked this directory → ') + chalk.bold(agent.name));
107
+ console.log();
108
+ console.log('Next: ' + chalk.bold('maritime chat "hello"') + chalk.dim(' · ') + chalk.bold('maritime deploy') + chalk.dim(' to push edits'));
109
+ }
110
+ else {
111
+ console.log();
112
+ console.log('Next: ' + chalk.bold('maritime deploy') + chalk.dim(' to create + link the agent'));
113
+ }
114
+ });
115
+ }
116
+ catch (error) {
117
+ handleError(error);
118
+ }
119
+ });
@@ -0,0 +1,4 @@
1
+ import { Command } from 'commander';
2
+ export declare const linkCommand: Command;
3
+ /** Read the current link for display (used by whoami/status helpers if needed). */
4
+ export declare function currentLink(): import("../context.js").ProjectLink | null;
@@ -0,0 +1,65 @@
1
+ import { Command } from 'commander';
2
+ import chalk from 'chalk';
3
+ import { authGet } from '../api.js';
4
+ import { resolveAgent } from '../resolve.js';
5
+ import { writeLink, getLink } from '../context.js';
6
+ import { promptForValue } from '../prompt.js';
7
+ import { isJsonMode, outputResult, fail, handleError, EXIT } from '../output.js';
8
+ export const linkCommand = new Command('link')
9
+ .description('Link this directory to an agent, so commands target it without naming it')
10
+ .argument('[agent]', 'Agent name or ID (interactive picker if omitted)')
11
+ .addHelpText('after', `
12
+ Once linked, the agent argument is optional everywhere:
13
+ maritime link support-bot
14
+ maritime chat "what's open?" # talks to support-bot
15
+ maritime logs # support-bot's logs
16
+ The link lives in .maritime/ (git-ignored). Re-run to change it.`)
17
+ .action(async (agentArg, _opts, command) => {
18
+ try {
19
+ let agent;
20
+ if (agentArg) {
21
+ agent = await resolveAgent(agentArg);
22
+ }
23
+ else {
24
+ // Interactive: pick from the caller's agents.
25
+ const interactive = !isJsonMode() && process.stdin.isTTY;
26
+ if (!interactive) {
27
+ fail('Pass an agent name to link to (non-interactive).', {
28
+ code: 'usage',
29
+ exitCode: EXIT.USAGE,
30
+ });
31
+ }
32
+ const agents = await authGet('/api/agents');
33
+ if (agents.length === 0) {
34
+ fail('You have no agents yet. Create one with `maritime create <name>` or `maritime init`.', {
35
+ code: 'not_found',
36
+ exitCode: EXIT.NOT_FOUND,
37
+ });
38
+ }
39
+ console.log(chalk.dim('\nYour agents:'));
40
+ agents.forEach((a, i) => {
41
+ console.log(` ${chalk.bold(String(i + 1))}. ${a.name} ${chalk.dim(`(${a.status})`)}`);
42
+ });
43
+ console.log();
44
+ const choice = await promptForValue('Link to which? (number or name)');
45
+ const idx = parseInt(choice, 10);
46
+ agent =
47
+ idx >= 1 && idx <= agents.length
48
+ ? agents[idx - 1]
49
+ : await resolveAgent(choice);
50
+ }
51
+ const path = writeLink({ agentId: agent.id, name: agent.name });
52
+ outputResult({ ok: true, action: 'link', agentId: agent.id, agentName: agent.name, path }, () => {
53
+ console.log(chalk.green('Linked ') + chalk.dim('this directory → ') + chalk.bold(agent.name));
54
+ console.log(chalk.dim(` ${path}`));
55
+ console.log(chalk.dim(' The agent argument is now optional here: try `maritime status`.'));
56
+ });
57
+ }
58
+ catch (error) {
59
+ handleError(error);
60
+ }
61
+ });
62
+ /** Read the current link for display (used by whoami/status helpers if needed). */
63
+ export function currentLink() {
64
+ return getLink();
65
+ }
@@ -22,7 +22,7 @@ function formatEntry(entry) {
22
22
  }
23
23
  export const logsCommand = new Command('logs')
24
24
  .description('View logs from an agent')
25
- .argument('<agent>', 'Agent name or ID')
25
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
26
26
  .option('-n, --lines <num>', 'Number of lines', '50')
27
27
  .option('--level <level>', 'Filter by level (info, warn, error, debug)')
28
28
  .option('-f, --follow', 'Follow log output')
@@ -6,7 +6,7 @@ import { resolveAgent } from '../resolve.js';
6
6
  const APP_URL = process.env.MARITIME_APP_URL || 'https://maritime.sh';
7
7
  export const openCommand = new Command('open')
8
8
  .description('Open an agent in the dashboard')
9
- .argument('<agent>', 'Agent name or ID')
9
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
10
10
  .action(async (agentArg) => {
11
11
  try {
12
12
  const agent = await resolveAgent(agentArg);
@@ -5,7 +5,7 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { outputResult, handleError, makeSpinner } from '../output.js';
6
6
  export const restartCommand = new Command('restart')
7
7
  .description('Restart an agent')
8
- .argument('<agent>', 'Agent name or ID')
8
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
9
9
  .action(async (agentArg) => {
10
10
  try {
11
11
  const agent = await resolveAgent(agentArg);
@@ -6,7 +6,7 @@ import { resolveAgent } from '../resolve.js';
6
6
  import { isJsonMode, outputJson, handleError } from '../output.js';
7
7
  export const sleepCommand = new Command('sleep')
8
8
  .description('Put an agent to sleep')
9
- .argument('<agent>', 'Agent name or ID')
9
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
10
10
  .action(async (agentArg) => {
11
11
  try {
12
12
  const agent = await resolveAgent(agentArg);
@@ -5,7 +5,7 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { outputResult, handleError, makeSpinner } from '../output.js';
6
6
  export const startCommand = new Command('start')
7
7
  .description('Start an agent')
8
- .argument('<agent>', 'Agent name or ID')
8
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
9
9
  .action(async (agentArg) => {
10
10
  try {
11
11
  const agent = await resolveAgent(agentArg);
@@ -5,7 +5,7 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { isJsonMode, outputJson, handleError } from '../output.js';
6
6
  export const statusCommand = new Command('status')
7
7
  .description('Show detailed status for an agent')
8
- .argument('<agent>', 'Agent name or ID')
8
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
9
9
  .action(async (agentArg) => {
10
10
  try {
11
11
  const summary = await resolveAgent(agentArg);
@@ -5,7 +5,7 @@ import { resolveAgent } from '../resolve.js';
5
5
  import { outputResult, handleError, makeSpinner } from '../output.js';
6
6
  export const stopCommand = new Command('stop')
7
7
  .description('Stop an agent')
8
- .argument('<agent>', 'Agent name or ID')
8
+ .argument('[agent]', 'Agent name or ID (defaults to the linked agent)')
9
9
  .action(async (agentArg) => {
10
10
  try {
11
11
  const agent = await resolveAgent(agentArg);
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Project context — the Vercel/Railway "link a directory to a project" model,
3
+ * applied to agents.
4
+ *
5
+ * .maritime/project.json the LINK: which agent this directory operates on.
6
+ * Machine-local, git-ignored. Written by `link`/`init`.
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
10
+ * the remote agent to it.
11
+ *
12
+ * Both are discovered by walking up from the cwd, so commands work from any
13
+ * subdirectory of a linked project — just like `git`.
14
+ */
15
+ export interface ProjectLink {
16
+ agentId: string;
17
+ name?: string;
18
+ }
19
+ export interface MaritimeConfig {
20
+ name?: string;
21
+ /** A curated template id (e.g. "openclaw"). Mutually exclusive with framework. */
22
+ template?: string;
23
+ /** Framework for bring-your-own-code agents (default "custom"). */
24
+ framework?: string;
25
+ /** Plain-English persona; becomes the agent's workspace AGENTS.md at boot. */
26
+ instructions?: string;
27
+ /** Env var KEYS this agent expects. Values are set via `env`, never committed. */
28
+ env?: string[];
29
+ /** Optional tier override (smart | extended | always_on). */
30
+ tier?: string;
31
+ }
32
+ export declare function findLinkPath(start?: string): string | null;
33
+ export declare function getLink(): ProjectLink | null;
34
+ export declare function getLinkedAgentId(): string | null;
35
+ /** Persist the link for `dir`, and git-ignore `.maritime/` so it stays local. */
36
+ export declare function writeLink(link: ProjectLink, dir?: string): string;
37
+ export declare function findConfigPath(start?: string): string | null;
38
+ export declare function getConfig(): MaritimeConfig | null;
39
+ export declare function configExists(dir?: string): boolean;
40
+ export declare function writeConfig(cfg: MaritimeConfig, dir?: string): string;
41
+ export declare const CONFIG_FILENAME = "maritime.json";
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Project context — the Vercel/Railway "link a directory to a project" model,
3
+ * applied to agents.
4
+ *
5
+ * .maritime/project.json the LINK: which agent this directory operates on.
6
+ * Machine-local, git-ignored. Written by `link`/`init`.
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
10
+ * the remote agent to it.
11
+ *
12
+ * Both are discovered by walking up from the cwd, so commands work from any
13
+ * subdirectory of a linked project — just like `git`.
14
+ */
15
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ const LINK_DIR = '.maritime';
18
+ const LINK_FILE = 'project.json';
19
+ const CONFIG_FILE = 'maritime.json';
20
+ // ---------------------------------------------------------------------------
21
+ // Generic upward-walk lookup
22
+ // ---------------------------------------------------------------------------
23
+ function findUp(relPath, start = process.cwd()) {
24
+ let dir = resolve(start);
25
+ // eslint-disable-next-line no-constant-condition
26
+ while (true) {
27
+ const candidate = join(dir, relPath);
28
+ if (existsSync(candidate))
29
+ return candidate;
30
+ const parent = dirname(dir);
31
+ if (parent === dir)
32
+ return null;
33
+ dir = parent;
34
+ }
35
+ }
36
+ // ---------------------------------------------------------------------------
37
+ // Link (.maritime/project.json)
38
+ // ---------------------------------------------------------------------------
39
+ export function findLinkPath(start = process.cwd()) {
40
+ return findUp(join(LINK_DIR, LINK_FILE), start);
41
+ }
42
+ export function getLink() {
43
+ const p = findLinkPath();
44
+ if (!p)
45
+ return null;
46
+ try {
47
+ const parsed = JSON.parse(readFileSync(p, 'utf-8'));
48
+ return parsed.agentId ? parsed : null;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ export function getLinkedAgentId() {
55
+ return getLink()?.agentId ?? null;
56
+ }
57
+ /** Persist the link for `dir`, and git-ignore `.maritime/` so it stays local. */
58
+ export function writeLink(link, dir = process.cwd()) {
59
+ const linkDir = join(dir, LINK_DIR);
60
+ mkdirSync(linkDir, { recursive: true });
61
+ const p = join(linkDir, LINK_FILE);
62
+ writeFileSync(p, JSON.stringify(link, null, 2) + '\n');
63
+ ensureGitignored(LINK_DIR, dir);
64
+ return p;
65
+ }
66
+ // ---------------------------------------------------------------------------
67
+ // Config (maritime.json)
68
+ // ---------------------------------------------------------------------------
69
+ export function findConfigPath(start = process.cwd()) {
70
+ return findUp(CONFIG_FILE, start);
71
+ }
72
+ export function getConfig() {
73
+ const p = findConfigPath();
74
+ if (!p)
75
+ return null;
76
+ try {
77
+ return JSON.parse(readFileSync(p, 'utf-8'));
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ export function configExists(dir = process.cwd()) {
84
+ return existsSync(join(dir, CONFIG_FILE));
85
+ }
86
+ export function writeConfig(cfg, dir = process.cwd()) {
87
+ const p = join(dir, CONFIG_FILE);
88
+ writeFileSync(p, JSON.stringify(cfg, null, 2) + '\n');
89
+ return p;
90
+ }
91
+ export const CONFIG_FILENAME = CONFIG_FILE;
92
+ // ---------------------------------------------------------------------------
93
+ // Helpers
94
+ // ---------------------------------------------------------------------------
95
+ function ensureGitignored(entry, dir) {
96
+ const gi = join(dir, '.gitignore');
97
+ try {
98
+ const current = existsSync(gi) ? readFileSync(gi, 'utf-8') : '';
99
+ const present = current
100
+ .split('\n')
101
+ .some((l) => l.trim() === entry || l.trim() === `${entry}/`);
102
+ if (!present) {
103
+ const prefix = current && !current.endsWith('\n') ? '\n' : '';
104
+ appendFileSync(gi, `${prefix}${entry}\n`);
105
+ }
106
+ }
107
+ catch {
108
+ // Best-effort; never block on .gitignore.
109
+ }
110
+ }
package/dist/index.js CHANGED
@@ -31,6 +31,9 @@ import { scaleCommand } from './commands/scale.js';
31
31
  import { sleepCommand } from './commands/sleep.js';
32
32
  import { checkForUpdates, printUpdateNotice } from './version-check.js';
33
33
  import { guideCommand } from './commands/guide.js';
34
+ import { initCommand } from './commands/init.js';
35
+ import { linkCommand } from './commands/link.js';
36
+ import { getLink } from './context.js';
34
37
  import { handleError } from './output.js';
35
38
  const __dirname = dirname(fileURLToPath(import.meta.url));
36
39
  const pkg = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8'));
@@ -51,6 +54,9 @@ program.addCommand(loginCommand);
51
54
  program.addCommand(logoutCommand);
52
55
  program.addCommand(whoamiCommand);
53
56
  program.addCommand(keysCommand);
57
+ // Project — link a directory to an agent (the Vercel/Railway model)
58
+ program.addCommand(initCommand);
59
+ program.addCommand(linkCommand);
54
60
  // Agent lifecycle
55
61
  program.addCommand(createCommand);
56
62
  program.addCommand(deployCommand);
@@ -84,14 +90,30 @@ program.addCommand(openCommand, HIDDEN);
84
90
  // Make the programmatic contract discoverable from the first thing an agent
85
91
  // runs (`maritime --help`), and point to the one-shot machine manifest.
86
92
  program.addHelpText('after', `
93
+ Quickstart (a directory is an agent):
94
+ maritime init my-agent create + link this folder to an agent
95
+ maritime chat "hello" talk to the linked agent (no name needed)
96
+ maritime deploy push maritime.json changes (persona, tier)
97
+ maritime logs · status · env · open all act on the linked agent
98
+
87
99
  For scripts & AI agents:
88
100
  Auth set MARITIME_TOKEN (mk_… key from \`maritime keys create\`)
89
101
  Output pass --json — results on stdout, errors as JSON on stderr
90
102
  Exit code 0 ok · 1 error · 2 auth · 3 not-found · 4 usage
91
103
  Talk maritime chat <agent> "..." (or pipe the message via stdin)
92
104
  Full spec maritime guide (human) · maritime guide --json (manifest)`);
93
- // Interactive mode: launch when no args in a TTY
94
- if (process.argv.length <= 2 && process.stdin.isTTY) {
105
+ const noArgs = process.argv.length <= 2;
106
+ // In a linked directory, the bare `maritime` shows the linked agent's status
107
+ // (the Vercel/Railway "context-aware default"). Outside one, fall back to the
108
+ // interactive picker in a TTY.
109
+ if (noArgs && getLink()) {
110
+ process.argv = [process.argv[0], process.argv[1], 'status'];
111
+ program
112
+ .parseAsync()
113
+ .then(() => printUpdateNotice(pkg.version))
114
+ .catch((error) => handleError(error));
115
+ }
116
+ else if (noArgs && process.stdin.isTTY) {
95
117
  import('./interactive.js').then(async ({ runInteractive }) => {
96
118
  try {
97
119
  const args = await runInteractive();
package/dist/resolve.d.ts CHANGED
@@ -6,4 +6,12 @@ export interface AgentSummary {
6
6
  tier?: string;
7
7
  createdAt?: string;
8
8
  }
9
- export declare function resolveAgent(nameOrId: string): Promise<AgentSummary>;
9
+ /**
10
+ * Resolve an agent for a command.
11
+ *
12
+ * - With a name/ID: exact-name match first, then unique ID-prefix match.
13
+ * - Without one: fall back to the agent this directory is linked to
14
+ * (`.maritime/project.json`), so `maritime logs`, `maritime chat "…"`, etc.
15
+ * "just work" in a linked project — the Vercel/Railway model.
16
+ */
17
+ export declare function resolveAgent(nameOrId?: string): Promise<AgentSummary>;
package/dist/resolve.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { authGet } from './api.js';
2
2
  import { fail, EXIT } from './output.js';
3
+ import { getLink } from './context.js';
3
4
  // Simple in-memory cache for the full agent list (5-second TTL)
4
5
  let cachedAgents = null;
5
6
  let cacheTime = 0;
@@ -13,7 +14,18 @@ async function fetchAllAgents() {
13
14
  cacheTime = now;
14
15
  return cachedAgents;
15
16
  }
17
+ /**
18
+ * Resolve an agent for a command.
19
+ *
20
+ * - With a name/ID: exact-name match first, then unique ID-prefix match.
21
+ * - Without one: fall back to the agent this directory is linked to
22
+ * (`.maritime/project.json`), so `maritime logs`, `maritime chat "…"`, etc.
23
+ * "just work" in a linked project — the Vercel/Railway model.
24
+ */
16
25
  export async function resolveAgent(nameOrId) {
26
+ if (!nameOrId || !nameOrId.trim()) {
27
+ return resolveLinkedAgent();
28
+ }
17
29
  // 1. Try server-side exact name match first (single API call, no full list)
18
30
  const byName = await authGet(`/api/agents?name=${encodeURIComponent(nameOrId)}`);
19
31
  if (byName.length === 1)
@@ -30,3 +42,18 @@ export async function resolveAgent(nameOrId) {
30
42
  }
31
43
  fail(`Agent "${nameOrId}" not found.`, { code: 'not_found', exitCode: EXIT.NOT_FOUND });
32
44
  }
45
+ /** The agent linked to the current directory, or a helpful error if none. */
46
+ function resolveLinkedAgent() {
47
+ const link = getLink();
48
+ if (!link) {
49
+ fail("No agent given and this directory isn't linked. Pass an agent name, or run `maritime link` / `maritime init`.", { code: 'no_agent', exitCode: EXIT.USAGE });
50
+ }
51
+ // Return straight from the link file — no API round-trip. Downstream calls
52
+ // that hit the agent will surface a clear 404 if it was deleted.
53
+ return {
54
+ id: link.agentId,
55
+ name: link.name ?? link.agentId,
56
+ status: 'unknown',
57
+ framework: 'unknown',
58
+ };
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "maritime-cli",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Maritime CLI - Deploy and talk to AI agents from your terminal",
5
5
  "type": "module",
6
6
  "license": "MIT",