@volter/world 2.0.0 → 2.0.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/src/cli.ts CHANGED
@@ -3,27 +3,41 @@
3
3
  // verb. `volter world …` acts on the world of the cwd the way git acts on the repository of the
4
4
  // cwd; `volter twin <vendor> …` runs one twin on its own; `volter remote …` is the hosted remote.
5
5
  // One client of `World`; it adds nothing the SDK does not have.
6
- import { formatInitReport, resolveCatalog, findInstalledPackage, packCli, serveConsoleFor } from '@volter/world-runtime';
6
+ import { detectRepoVendors, formatInitReport, resolveCatalog, findInstalledPackage, packCli, serveConsoleFor } from '@volter/world-runtime';
7
7
  import { readFileSync, realpathSync } from 'node:fs';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { spawn } from 'node:child_process';
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { createHash } from 'node:crypto';
11
+ import { hostname } from 'node:os';
10
12
  import { formatLedgerDelta } from '@volter/world-core';
11
13
  import { existsSync } from 'node:fs';
12
14
  import { join, relative, resolve } from 'node:path';
13
- import { platformOrigin, requireToken, storePlatform, storeToken, tokenFor } from './credentials.ts';
15
+ import { forgetPlatform, forgetToken, platformOrigin, requireToken, storePlatform, storeToken, tokenFor } from './credentials.ts';
14
16
  import { parseOriginUrl, World } from './world.ts';
15
17
  import { waitForServeShutdown } from './serve-shutdown.ts';
18
+ import { startUpdateCheck } from './update-notice.ts';
19
+ import type { ViewConsole } from '@volter/world-runtime';
20
+
21
+ /** Open a URL in the person's browser; a machine without one only loses the convenience. */
22
+ function openInBrowser(url: string): void {
23
+ // an http(s) URL only, and on Windows through the URL handler rather than cmd.exe, which would read `"`, `&` or `%VAR%`
24
+ // in it as commands
25
+ let target: string; try { const u = new URL(url); if (u.protocol !== 'http:' && u.protocol !== 'https:') return; target = u.href; } catch { return; }
26
+ const [cmd, ...pre] = process.platform === 'darwin' ? ['open'] : process.platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler'] : ['xdg-open'];
27
+ try { spawn(cmd!, [...pre, target], { windowsHide: true, stdio: 'ignore', detached: true }).on('error', () => undefined).unref(); } catch { /* no browser here */ }
28
+ }
16
29
 
17
30
  export const HELP = `volter — run your app against a world of twins
18
31
 
19
32
  world — the twins your app needs, running together (the world of the current directory)
20
- volter world init [--name <world>] [--allow-unknown] detect the app's vendors, write .volter/world.json
33
+ volter world init [--install] [--name <world>] [--allow-unknown] detect the app's vendors (installing their twins when none are), write .volter/world.json
21
34
  volter world up [--sandbox] [--no-seed] start the twins on this branch (loads the default data the first time)
22
35
  volter world run [--verbose] -- <command...> run the app or its tests inside the world
23
36
  volter world activate eval "$(volter world activate)": vendor CLIs and curl in this shell reach the twins
24
37
  volter world shell a subshell with the world active
25
38
  volter world init --bare <org>/<world> --twins a,b a world with no app: a shared world for a team, or one standing in for a vendor
26
- volter world serve [--port <p>] [--console-port <c>] serve this world on a URL under /<org>/<world>/; prints the token and the console (its own origin, port p+1 by default)
39
+ volter world serve [--port <p>] [--console-port <c>] serve this world on a URL under /<org>/<world>/ for apps; prints the token and the console (on loopback: view's front, no token in the browser)
40
+ volter world view [--port <p>] [--host <h>] [--no-open] [--no-origins] step into this world in a browser: its twins' own UIs, timeline, clock, branches (a non-loopback --host serves them on one origin)
27
41
  volter world console [<https://host/org/world>] [--port <p>] the console on this machine for a World served elsewhere (default: this world's origin); needs @volter/world-console
28
42
  volter world status world, branch, origin, unpushed changes, what is running
29
43
  volter world log [--receipts] [--json] every write the app made; --receipts adds each change's receipt
@@ -34,7 +48,7 @@ world — the twins your app needs, running together (the world of the current
34
48
  volter world branch [<name>] list branches, or make one from here and check it out
35
49
  volter world checkout <name> switch branches
36
50
  volter world replay <changeset> --into <branch> feed a changeset's changes into another branch's twins
37
- volter world clock show | set <iso> | advance <N s|m|h|d> the world's clock: set, not observed
51
+ volter world clock show | set <iso> | advance <N s|m|h|d> | shift <N s|m|h|d> | clear the world's clock: set, not observed
38
52
  volter world clone <url> --token <token> [--admin-token <t>] connect this world to a remote and fetch its history (the admin token copies the whole tree at once)
39
53
  volter world fetch what the remote observed since the last fetch
40
54
  volter world origin where this world clones from and pushes to
@@ -55,9 +69,17 @@ twin — one twin: in this world, or on its own
55
69
  volter twin <vendor> mirror [--port <p>] the twin's UI mirror
56
70
  volter twin <vendor> conformance check the twin against the vendor's spec
57
71
 
72
+ agents — your coding agent, driving the same verbs
73
+ volter agents install [--claude] [--cursor] [--vscode] [--codex] [--yes] put the volter-world skill and the MCP server into the agents found here
74
+ volter mcp the MCP server (stdio) an agent starts: the verbs above as tools
75
+
58
76
  remote — the worlds this one pushes to and fetches from, by name
59
- volter login <platform url> --token <personal token> sign the CLI into the hosted platform (a personal token from the console)
60
- volter remote add <name> <url|path|org/world> [--token <token>] name a remote; org/world resolves through the platform you logged into
77
+ volter login <platform url> [--token <personal token>] sign the CLI into the hosted platform: approve it in the browser (or a token made under Account, for CI)
78
+ volter whoami the platform the CLI is signed into, as whom, and its orgs
79
+ volter logout revoke the CLI's token at the platform and forget it here
80
+ volter remote add <name> <url|path|org/world> [--token <token>] [--create] name a remote; org/world (or world, in one org) resolves through the platform you logged into; --create makes it there from this world's twins
81
+ volter open [<org>/<world>] [--no-open] a World's dashboard: a hosted one through the platform, else this world's (as view)
82
+ volter completion bash|zsh|fish|powershell print a completion script for your shell
61
83
  volter remote remove <name> forget it
62
84
  volter remote list every remote, with its URL and whether a token is stored
63
85
  (the hosting product's serve answers here for one release: volter remote serve)
@@ -96,7 +118,7 @@ function when(iso: string): string { return iso.slice(11, 23); }
96
118
 
97
119
  /** Run another CLI in the foreground and adopt its exit code; a signal to us is a signal to it. */
98
120
  async function passthrough(cmd: string[], cwd = process.cwd()): Promise<number> {
99
- const child = spawn(cmd[0]!, cmd.slice(1), { cwd, stdio: 'inherit' });
121
+ const child = spawn(cmd[0]!, cmd.slice(1), { windowsHide: true, cwd, stdio: 'inherit' });
100
122
  const forward = (signal: NodeJS.Signals) => () => { try { child.kill(signal); } catch { /* already gone */ } };
101
123
  for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) process.on(signal, forward(signal));
102
124
  return await new Promise<number>((resolve, reject) => { child.once('error', reject); child.once('exit', (code, signal) => resolve(code ?? (signal ? 128 : 1))); });
@@ -123,12 +145,14 @@ async function worldCommand(verb: string, args: string[]): Promise<void> {
123
145
  }
124
146
  if (verb === 'init') {
125
147
  const app = resolve(worldDir ?? process.cwd());
148
+ await installDetectedTwins(app, flag(args, '--install'));
126
149
  const { result } = World.init(app, { ...(value(args, '--name') ? { name: value(args, '--name')! } : {}), force: flag(args, '--force'), allowUnknown: flag(args, '--allow-unknown') });
127
150
  if (asJson) json({ ok: result.ok, plan: result.plan, coverage: result.coverage, next: result.next });
128
151
  else {
129
152
  const twins = result.plan.vendors.filter((v) => v.service !== null).map((v) => v.vendor).sort();
130
153
  out(`twins ${twins.join(', ') || '(none)'}\nwrote ${relative(process.cwd(), result.plan.configPath) || result.plan.configPath}`);
131
154
  out(formatInitReport(result));
155
+ if (result.ok) await offerAgents();
132
156
  }
133
157
  if (!result.ok) process.exitCode = 1;
134
158
  return;
@@ -248,8 +272,10 @@ async function worldCommand(verb: string, args: string[]): Promise<void> {
248
272
  const [action, arg] = pos;
249
273
  if (action === 'set') { if (!arg) throw new Error('volter world clock set <iso-8601>'); out(world.setClock(arg)); return; }
250
274
  if (action === 'advance') { if (!arg) throw new Error('volter world clock advance <N s|m|h|d>'); out(world.advanceClock(arg)); return; }
251
- if (action === undefined || action === 'show') { const c = world.clock(); out(`${c.at}${c.frozen ? '' : ' (wall clock — not set)'}`); return; }
252
- throw new Error('volter world clock show | set <iso> | advance <N s|m|h|d>');
275
+ if (action === 'shift') { if (!arg) throw new Error('volter world clock shift <N s|m|h|d>'); out(world.shiftClock(arg)); return; }
276
+ if (action === 'clear') { out(world.clearClock()); return; }
277
+ if (action === undefined || action === 'show') { const c = world.clock(); out(`${c.at}${c.frozen ? '' : c.running ? ' (running)' : ' (wall clock — not set)'}`); return; }
278
+ throw new Error('volter world clock show | set <iso> | advance <N s|m|h|d> | shift <N s|m|h|d> | clear');
253
279
  }
254
280
  case 'replay': {
255
281
  const name = pos[0]; const into = value(args, '--into');
@@ -297,10 +323,45 @@ async function worldCommand(verb: string, args: string[]): Promise<void> {
297
323
  out(`changeset ${cs.name} ${cs.actions.length} change${cs.actions.length === 1 ? '' : 's'}\n ${message}${cs.narration ? `\n${cs.narration.split('\n').map((l) => ` ${l}`).join('\n')}` : ''}`);
298
324
  return;
299
325
  }
326
+ case 'view':
300
327
  case 'serve': {
301
- const served = await world.serve({ ...(value(args, '--port') ? { port: Number(value(args, '--port')) } : {}), ...(value(args, '--console-port') ? { consolePort: Number(value(args, '--console-port')) } : {}), ...(value(args, '--host') ? { host: value(args, '--host') } : {}), announce: (info) => out(`serving ${info.name} ${info.base}\ntoken ${info.token}\nread ${info.readToken}${info.console ? `\nconsole ${info.console}` : ''}`) });
302
- await waitForServeShutdown(() => served.stop());
303
- process.exit(0); // success follows confirmed shutdown; failures reach main's error path
328
+ // `view` steps into the World in a browser; `serve` serves it for apps and scripts. Bound to this machine's
329
+ // loopback both are the same local front (the World's own origin, its console beside it) and the browser never
330
+ // needs a token (served-world.ts localSession); `serve` only leaves the browser closed. A non-loopback --host,
331
+ // or `serve --console-port`, is a World served for others: its console asks for a token.
332
+ const host = value(args, '--host');
333
+ const local = host === undefined || host === '127.0.0.1' || host === 'localhost' || host === '::1';
334
+ if (verb === 'serve' && (!local || value(args, '--console-port') !== undefined)) {
335
+ const served = await world.serve({ ...(value(args, '--port') ? { port: Number(value(args, '--port')) } : {}), ...(value(args, '--console-port') ? { consolePort: Number(value(args, '--console-port')) } : {}), ...(value(args, '--host') ? { host: value(args, '--host') } : {}), announce: (info) => out(`serving ${info.name} ${info.base}\ntoken ${info.token}\nread ${info.readToken}${info.console ? `\nconsole ${info.console}` : ''}`) });
336
+ await waitForServeShutdown(() => served.stop());
337
+ process.exit(0); // success follows confirmed shutdown; failures reach main's error path
338
+ return;
339
+ }
340
+ // the console mounts when it is installed beside the CLI; without it the World serves its doors and mirrors
341
+ const console = await (async (): Promise<ViewConsole | undefined> => {
342
+ try { const mod = await import('@volter/world-console') as { createConsole: () => ViewConsole }; return mod.createConsole(); } catch (error) {
343
+ // not installed is one thing; installed and broken is another, and says why
344
+ const missing = /ERR_MODULE_NOT_FOUND|Cannot find (package|module)/.test(`${(error as { code?: string }).code ?? ''} ${String(error)}`);
345
+ if (!missing) process.stderr.write(`the console failed to load (the World is served without it): ${error instanceof Error ? error.message : String(error)}\n`);
346
+ return undefined;
347
+ }
348
+ })();
349
+ // `serve` says what it always said first (`serving <name> <url>`, then the tokens: scripts and the guides read
350
+ // those lines), and the local front's own lines after them; `view` says `viewing` as it goes
351
+ const later: string[] = [];
352
+ const view = await world.view({ ...(value(args, '--port') ? { port: Number(value(args, '--port')) } : {}), ...(host ? { host } : {}), ...(console ? { console } : {}), ...(args.includes('--no-origins') ? { origins: false } : {}), announce: (line) => { if (verb !== 'serve') out(line); else if (!line.startsWith('viewing')) later.push(line); } });
353
+ if (verb === 'serve') { out(`serving ${view.served} ${view.base}\ntoken ${view.token}\nread ${view.readToken}`); for (const line of later) out(line); }
354
+ // a local World's page opens itself; a World served for others is handed its token in the URL's fragment
355
+ // (which the browser never sends), taken once
356
+ // (with --no-origins every World shares one origin, where no page is handed a session: the token again)
357
+ const open = view.console ? (local && view.origin ? view.console : `${view.console}#token=${encodeURIComponent(view.token)}`) : null;
358
+ // the read token's own one-line way in, for handing to someone who should look and not touch
359
+ // (not on a local World: any of its pages can open a write session there, so a read-only link restricts nothing)
360
+ const readOnly = view.console && !(local && view.origin) ? `${view.console}#token=${encodeURIComponent(view.readToken)}` : null;
361
+ out(`${local && view.origin ? `apps the World's tokens are in .volter/token and .volter/token.read (apps and scripts present them; the browser needs none)` : verb === 'serve' ? '' : `token ${view.token}\nread ${view.readToken}`}${readOnly ? `\nread-only view ${readOnly}` : ''}${view.console ? '' : '\n(no console installed: `npm install -D @volter/world-console` to look around in a browser)'}${view.origin ? '\n(the World opens at its own *.localhost origin; if your browser cannot reach *.localhost, run again with --no-origins)' : ''}`);
362
+ if (open && verb === 'view' && !args.includes('--no-open')) openInBrowser(open);
363
+ await waitForServeShutdown(() => view.stop());
364
+ process.exit(0);
304
365
  return;
305
366
  }
306
367
  case 'rebase': {
@@ -408,17 +469,90 @@ function remoteCli(): string {
408
469
  throw new Error('volter remote: the hosting product (@volter/world-host) is not installed — `bun add -d @volter/world-host`');
409
470
  }
410
471
 
411
- /** `volter login <platform url> --token <personal token>`: the CLI signed into the hosted platform as you — the
412
- * token is a personal access token from the console (shown once there), kept in your config directory. */
472
+ /** `volter login <platform url>`: the CLI signed into the hosted platform as you, through the browser (the device
473
+ * authorization grant, as `gh auth login`): the platform shows a code, you approve it there signed in as yourself,
474
+ * and the command collects a personal token named for this machine. `--token <personal token>` (one made in the
475
+ * platform under Account) signs in without a browser, for CI. Either way it is kept in your config directory. */
413
476
  async function loginCommand(args: string[]): Promise<void> {
414
- const url = positionals(args, VALUE_FLAGS)[0]; const token = value(args, '--token');
415
- if (!url || !token) throw new Error('volter login <platform url> --token <personal token> (make one in the console under "You")');
416
- const origin = url.replace(/\/+$/, '');
477
+ const url = positionals(args, VALUE_FLAGS)[0];
478
+ if (!url) throw new Error('volter login <platform url> [--token <personal token>] [--no-open]');
479
+ let origin: string; try { const u = new URL(url); if (u.protocol !== 'https:' && u.protocol !== 'http:') throw new Error(); origin = u.origin; } catch { throw new Error(`${url} is not a platform address (https://…)`); }
480
+ const token = value(args, '--token') ?? await deviceSignIn(origin, !flag(args, '--no-open'));
417
481
  const res = await fetch(`${origin}/-/orgs`, { headers: { authorization: `Bearer ${token}` } });
418
482
  const body = (await res.json().catch(() => ({}))) as { person?: { email?: string; id?: string }; orgs?: Array<{ slug: string | null; name: string }>; error?: string };
419
483
  if (!res.ok) throw new Error(`${origin} answered ${res.status}: ${body.error ?? 'not signed in'}`);
420
484
  storeToken(origin, token); storePlatform(origin);
421
- out(`signed in ${origin} as ${body.person?.email ?? body.person?.id ?? 'you'}\norgs ${(body.orgs ?? []).map((o) => o.slug ?? o.name).join(', ') || '(none yet)'}\nnext volter remote add origin <org>/<world>`);
485
+ out(`signed in ${origin} as ${body.person?.email ?? body.person?.id ?? 'you'}\norgs ${(body.orgs ?? []).map((o) => o.slug ?? o.name).join(', ') || '(none yet)'}\nnext in your app's folder: volter world init, then volter remote add origin ${(body.orgs ?? [])[0]?.slug ?? '<org>'}/<world> --create`);
486
+ }
487
+
488
+ /** `volter whoami`: which platform the command is signed into, as whom, and the orgs it reaches. */
489
+ async function whoamiCommand(): Promise<void> {
490
+ const origin = platformOrigin(); const token = origin ? tokenFor(origin) : undefined;
491
+ if (!origin || !token) { out('not signed in (volter login <platform url>)'); process.exitCode = 1; return; }
492
+ const res = await fetch(`${origin}/-/orgs`, { headers: { authorization: `Bearer ${token}` } }).catch(() => null);
493
+ if (!res) throw new Error(`${origin} did not answer`);
494
+ const body = (await res.json().catch(() => ({}))) as { person?: { email?: string; id?: string }; orgs?: Array<{ slug: string | null; name: string; role?: string }>; error?: string };
495
+ // a token the platform no longer takes is signed out; one it takes but that may not read orgs is still signed in
496
+ if (res.status === 403) { out(`signed in ${origin} (this token may not read your orgs: ${body.error ?? 'refused'})`); return; }
497
+ if (!res.ok) { out(`signed out ${origin}: ${body.error ?? res.status} — volter login ${origin}`); process.exitCode = 1; return; }
498
+ out(`signed in ${origin} as ${body.person?.email ?? body.person?.id ?? 'you'}\norgs ${(body.orgs ?? []).map((o) => `${o.slug ?? o.name}${o.role === 'org:admin' ? ' (admin)' : ''}`).join(', ') || '(none yet)'}`);
499
+ }
500
+
501
+ /** `volter logout`: the command's token is revoked at the platform (a token may always revoke itself) and forgotten here. */
502
+ async function logoutCommand(): Promise<void> {
503
+ const origin = platformOrigin(); const token = origin ? tokenFor(origin) : undefined;
504
+ if (!origin || !token) { out('not signed in'); return; }
505
+ const id = createHash('sha256').update(token).digest('hex');
506
+ const res = await fetch(`${origin}/-/tokens/${id}`, { method: 'DELETE', headers: { authorization: `Bearer ${token}` } }).catch(() => null);
507
+ forgetToken(origin); forgetPlatform();
508
+ out(res?.ok ? `signed out ${origin} (its token is revoked)` : `signed out ${origin} (forgotten here; the platform did not revoke the token${res ? ` — ${res.status}` : ''}, so revoke it under Account)`);
509
+ }
510
+
511
+ /** The browser half of `volter login`: ask the platform for a code, send the person to approve it, and wait (at the
512
+ * platform's pace) for the personal token it hands over once they do. */
513
+ async function deviceSignIn(origin: string, openBrowser: boolean): Promise<string> {
514
+ const started = await fetch(`${origin}/-/cli/device`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: hostname() }) }).catch((e: unknown) => { throw new Error(`${origin} did not answer: ${e instanceof Error ? e.message : String(e)}`); });
515
+ const grant = (await started.json().catch(() => ({}))) as { device_code?: string; user_code?: string; verification_uri_complete?: string; expires_in?: number; interval?: number; error?: string };
516
+ if (!started.ok || !grant.device_code || !grant.user_code || !/^[A-Z]{4}-[A-Z]{4}$/.test(grant.user_code)) throw new Error(`${origin} cannot sign the command in through the browser (${started.status}${grant.error ? `: ${grant.error}` : ''}) — make a token on the platform under Account and use --token`);
517
+ // the page is this platform's own, built here from the address you gave and the code: nothing the platform answers is
518
+ // opened as it stands
519
+ const page = `${origin}/-/cli/approve?code=${grant.user_code}`;
520
+ process.stderr.write(`approve ${page}\ncode ${grant.user_code} (check the page shows the same)\n`);
521
+ if (openBrowser) openInBrowser(page);
522
+ const until = Date.now() + (grant.expires_in ?? 600) * 1000; const every = Math.max(1, grant.interval ?? 5) * 1000;
523
+ while (Date.now() < until) {
524
+ await new Promise((r) => setTimeout(r, every));
525
+ const res = await fetch(`${origin}/-/cli/token`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ device_code: grant.device_code }) }).catch(() => null);
526
+ if (!res) continue;
527
+ const body = (await res.json().catch(() => ({}))) as { token?: string; error?: string };
528
+ if (res.ok && body.token) return body.token;
529
+ if (body.error === 'authorization_pending' || body.error === 'slow_down') continue;
530
+ if (body.error === 'access_denied') throw new Error('refused in the browser: the command was not signed in');
531
+ throw new Error(`the code expired or was already used (${body.error ?? res.status}) — run volter login again`);
532
+ }
533
+ throw new Error('the code expired before it was approved — run volter login again');
534
+ }
535
+
536
+ /** "a, b and c". */
537
+ const listed = (names: string[]): string => (names.length <= 1 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`);
538
+
539
+ /** A yes from the person at the terminal; no terminal is a no (a script says --create instead). */
540
+ async function confirm(question: string): Promise<boolean> {
541
+ if (!process.stdin.isTTY || !process.stderr.isTTY) return false;
542
+ const { createInterface } = await import('node:readline/promises');
543
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
544
+ try { return /^y(es)?$/i.test((await rl.question(question)).trim()); } finally { rl.close(); }
545
+ }
546
+
547
+ /** The org a bare world name belongs to: the one org the person is in, else a question they answer by naming it. */
548
+ async function onlyOrg(platform: string, personal: string, world: string): Promise<string> {
549
+ const res = await fetch(`${platform}/-/orgs`, { headers: { authorization: `Bearer ${personal}` } });
550
+ const body = (await res.json().catch(() => ({}))) as { orgs?: Array<{ slug: string | null; id?: string }>; error?: string };
551
+ if (!res.ok) throw new Error(`${platform} answered ${res.status}: ${body.error ?? 'not signed in'} — volter login ${platform}`);
552
+ const orgs = (body.orgs ?? []).map((o) => o.slug ?? o.id ?? '').filter(Boolean);
553
+ if (orgs.length === 1) return orgs[0]!;
554
+ if (orgs.length === 0) throw new Error(`you are in no org on ${platform} yet — make one there, then volter remote add origin <org>/${world}`);
555
+ throw new Error(`you are in ${orgs.length} orgs (${listed(orgs)}): say which, volter remote add origin <org>/${world}`);
422
556
  }
423
557
 
424
558
  async function remoteCommand(verb: string, args: string[]): Promise<void> {
@@ -427,16 +561,35 @@ async function remoteCommand(verb: string, args: string[]): Promise<void> {
427
561
  const pos = positionals(args, VALUE_FLAGS);
428
562
  if (verb === 'add') {
429
563
  const [name, target] = pos;
430
- if (!name || !target) throw new Error('volter remote add <name> <url|path|org/world> [--token <token>]');
431
- // `org/world`: a world the hosted platform serves for your org — its address and token come through the platform, never by hand
432
- if (/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(target) && !existsSync(target)) {
433
- const platform = platformOrigin(); if (!platform) throw new Error(`${target} looks like a hosted world (org/world) — \`volter login <platform url> --token <personal token>\` first`);
564
+ if (!name || !target) throw new Error('volter remote add <name> <url|path|org/world> [--token <token>] [--create]');
565
+ // `org/world` (or `world`, when you are in one org): a world the hosted platform serves for your org — its address
566
+ // and token come through the platform, never by hand; one that is not there yet is made there from this world's
567
+ // vendors, asked first, or at once with --create (a script's or an agent's way)
568
+ // a bare word is a hosted world only when this command is signed into a platform; otherwise it is a folder, as ever
569
+ const hosted = !existsSync(target) && (/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(target) || (/^[a-z0-9][a-z0-9-]*$/.test(target) && Boolean(platformOrigin())));
570
+ if (hosted) {
571
+ const platform = platformOrigin(); if (!platform) throw new Error(`${target} looks like a hosted world (org/world) — \`volter login <platform url>\` first`);
434
572
  const personal = tokenFor(platform); if (!personal) throw new Error(`no personal token stored for ${platform} — \`volter login\` again`);
435
- const res = await fetch(`${platform}/-/worlds/${target}/token`, { headers: { authorization: `Bearer ${personal}` } });
436
- const body = (await res.json().catch(() => ({}))) as { base?: string; token?: string; error?: string };
573
+ const served = target.includes('/') ? target : `${await onlyOrg(platform, personal, target)}/${target}`;
574
+ const key = (): Promise<Response> => fetch(`${platform}/-/worlds/${served}/token`, { headers: { authorization: `Bearer ${personal}` } });
575
+ let res = await key();
576
+ let body = (await res.clone().json().catch(() => ({}))) as { base?: string; token?: string; scope?: string; error?: string };
577
+ if (res.status === 404 && /^no world /.test(body.error ?? '')) {
578
+ const vendors = world.vendors();
579
+ if (vendors.length === 0) throw new Error(`${served} is not on ${platform} yet, and this world names no twins to make it with — \`volter world init\` first`);
580
+ if (!flag(args, '--create') && !(await confirm(`${served} is not on ${platform}. Make it there with ${listed(vendors)}? [y/N] `))) {
581
+ throw new Error(`${served} is not on ${platform}${process.stdin.isTTY ? '' : ' — add --create to make it with this world\'s twins'}${target.includes('/') ? '' : ` (a folder? name it ./${target})`}`);
582
+ }
583
+ const [org, worldName] = served.split('/') as [string, string];
584
+ const made = await fetch(`${platform}/-/worlds`, { method: 'POST', headers: { authorization: `Bearer ${personal}`, 'content-type': 'application/json' }, body: JSON.stringify({ org, world: worldName, vendors }) });
585
+ const madeBody = (await made.json().catch(() => ({}))) as { name?: string; error?: string };
586
+ if (!made.ok) throw new Error(`the platform did not make ${served} (${made.status}): ${madeBody.error ?? 'refused'}`);
587
+ out(`made ${madeBody.name ?? served} on ${platform} (${listed(vendors)})`);
588
+ res = await key(); body = (await res.json().catch(() => ({}))) as typeof body;
589
+ }
437
590
  if (!res.ok || !body.base || !body.token) throw new Error(`the platform answered ${res.status}: ${body.error ?? 'no such world in your orgs'}`);
438
591
  world.addRemote(name, body.base, { token: body.token });
439
- out(`remote ${name} ${body.base} (through ${platform})`);
592
+ out(`remote ${name} ${body.base} (through ${platform}${body.scope === 'read' ? ', read only: this token may not write Worlds' : ''})`);
440
593
  return;
441
594
  }
442
595
  world.addRemote(name, target, { ...(value(args, '--token') ? { token: value(args, '--token') } : {}) });
@@ -454,8 +607,133 @@ async function remoteCommand(verb: string, args: string[]): Promise<void> {
454
607
  throw new Error(`volter remote: unknown verb "${verb}"\n\n${HELP}`);
455
608
  }
456
609
 
610
+ /** `volter open [<org>/<world>] [--no-open]`: a World's dashboard. A hosted World (named, or this world's origin on the
611
+ * platform the command is signed into) opens through the platform, which signs the person in with a pass; otherwise
612
+ * it is this world's own, as `volter world view` serves it. */
613
+ async function openCommand(args: string[]): Promise<void> {
614
+ const named = positionals(args, VALUE_FLAGS)[0];
615
+ const platform = platformOrigin();
616
+ let served = named && /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(named) ? named : null;
617
+ if (!served && !named && platform) {
618
+ // this world's origin, when it is a World the platform serves: its namespace is <org>/<world>
619
+ try { const origin = World.open({ ...(value(args, '--world') ? { root: value(args, '--world') } : {}) }).remote(); if (origin && tokenFor(origin.url) && /^[a-z0-9-]+\/[a-z0-9-]+$/.test(origin.namespace)) served = origin.namespace; } catch { /* no world here */ }
620
+ }
621
+ if (named && !served) throw new Error(`volter open ${named}: name a hosted World as <org>/<world>, or run it in the app's folder for this world`);
622
+ if (served) {
623
+ if (!platform) throw new Error(`${served} is a hosted World — \`volter login <platform url>\` first`);
624
+ const url = `${platform}/-/worlds/${served}/open`;
625
+ out(url);
626
+ if (!flag(args, '--no-open')) openInBrowser(url);
627
+ return;
628
+ }
629
+ await worldCommand('view', args);
630
+ }
631
+
632
+ /** The command tree for completion, read from HELP (the one list of commands): noun → its verbs. */
633
+ function commandTree(): Record<string, string[]> {
634
+ const tree: Record<string, string[]> = { open: [], completion: ['bash', 'zsh', 'fish', 'powershell'] };
635
+ for (const m of HELP.matchAll(/^\s+volter ([a-z]+)(?: ([a-z][a-z-]*))?/gm)) {
636
+ const [, noun, verb] = m; (tree[noun!] ??= []);
637
+ if (verb && !tree[noun!]!.includes(verb)) tree[noun!]!.push(verb);
638
+ }
639
+ return tree;
640
+ }
641
+
642
+ /** `volter completion bash|zsh|fish|powershell`: a script that completes volter's nouns and verbs in that shell. */
643
+ function completionScript(shell: string | undefined): string {
644
+ const tree = commandTree(); const nouns = Object.keys(tree).join(' ');
645
+ const cases = (fmt: (noun: string, verbs: string) => string): string => Object.entries(tree).filter(([, v]) => v.length).map(([n, v]) => fmt(n, v.join(' '))).join('\n');
646
+ switch (shell) {
647
+ case 'bash': case 'zsh':
648
+ return `${shell === 'zsh' ? 'autoload -U +X bashcompinit && bashcompinit\n' : ''}# volter completion (${shell}): eval "$(volter completion ${shell})"
649
+ _volter() {
650
+ local cur=\${COMP_WORDS[COMP_CWORD]}
651
+ if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=($(compgen -W "${nouns}" -- "$cur")); return; fi
652
+ if [ "$COMP_CWORD" -eq 2 ]; then
653
+ case "\${COMP_WORDS[1]}" in
654
+ ${cases((n, v) => ` ${n}) COMPREPLY=($(compgen -W "${v}" -- "$cur")) ;;`)}
655
+ esac
656
+ fi
657
+ }
658
+ complete -o default -F _volter volter
659
+ `;
660
+ case 'fish':
661
+ return `# volter completion (fish): volter completion fish | source
662
+ complete -c volter -f -n '__fish_use_subcommand' -a '${nouns}'
663
+ ${cases((n, v) => `complete -c volter -f -n '__fish_seen_subcommand_from ${n}; and test (count (commandline -opc)) -eq 2' -a '${v}'`)}
664
+ `;
665
+ case 'powershell':
666
+ return `# volter completion (PowerShell): volter completion powershell | Out-String | Invoke-Expression
667
+ Register-ArgumentCompleter -Native -CommandName volter -ScriptBlock {
668
+ param($wordToComplete, $commandAst, $cursorPosition)
669
+ $words = @($commandAst.CommandElements | ForEach-Object { $_.ToString() })
670
+ $tree = @{
671
+ ${Object.entries(tree).map(([n, v]) => ` '${n}' = @(${v.map((x) => `'${x}'`).join(', ')})`).join('\n')}
672
+ }
673
+ $choices = if ($words.Count -le 1 -or ($words.Count -eq 2 -and $wordToComplete)) { $tree.Keys } elseif ($tree.ContainsKey($words[1])) { $tree[$words[1]] } else { @() }
674
+ $choices | Where-Object { $_ -like "$wordToComplete*" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }
675
+ }
676
+ `;
677
+ default:
678
+ throw new Error('volter completion bash|zsh|fish|powershell');
679
+ }
680
+ }
681
+
682
+ /** A fresh app has no twins installed, so `init` has nothing to plan with: its vendors are found from what the app
683
+ * depends on and names in its env (the signatures ship with the command), and the twins for them are installed with
684
+ * the app's own package manager: asked at a terminal, or at once with `--install` (a script's or an agent's way). */
685
+ async function installDetectedTwins(app: string, install: boolean): Promise<void> {
686
+ try { if (resolveCatalog(app).vendors().length > 0) return; } catch { /* no twins here yet */ }
687
+ const found = detectRepoVendors(app).detected;
688
+ const vendors = [...found.keys()].filter((v) => /^[a-z0-9][a-z0-9-]*$/.test(v)).sort();
689
+ if (vendors.length === 0) return; // init says what it found and how to add a twin by hand
690
+ const pkgs = vendors.map((v) => `@volter/twin-${v}`);
691
+ const has = (file: string): boolean => existsSync(join(app, file));
692
+ // the app's own package manager, by its lockfile; npm where there is none
693
+ const command = has('bun.lock') || has('bun.lockb') ? `bun add -d ${pkgs.join(' ')}` : has('pnpm-lock.yaml') ? `pnpm add -D ${pkgs.join(' ')}` : has('yarn.lock') ? `yarn add -D ${pkgs.join(' ')}` : `npm install -D ${pkgs.join(' ')}`;
694
+ out(`detected ${vendors.map((v) => `${v} (${(found.get(v) ?? []).slice(0, 2).join(', ')})`).join('; ')}`);
695
+ out(`twins ${pkgs.join(' ')}`);
696
+ let yes = install;
697
+ if (!yes && process.stdin.isTTY && process.stdout.isTTY) {
698
+ process.stdout.write(`Install them now (${command})? [Y/n] `);
699
+ const answer = await new Promise<string>((done) => { process.stdin.once('data', (d) => done(String(d).trim().toLowerCase())); });
700
+ process.stdin.pause();
701
+ yes = answer === '' || answer === 'y' || answer === 'yes';
702
+ }
703
+ if (!yes) throw new Error(`install the twins first: ${command}
704
+ then run volter world init again (or volter world init --install does both)`);
705
+ // one command line built from the checked names above: nothing of anyone's input reaches the shell
706
+ const ran = spawnSync(command, { cwd: app, stdio: 'inherit', shell: true, windowsHide: true });
707
+ if (ran.status !== 0) throw new Error(`${command} failed (exit ${ran.status ?? 'none'})`);
708
+ }
709
+
710
+ /** After `volter world init`: a person at a terminal is asked whether to set up their coding agents; anyone else is
711
+ * told the command. */
712
+ async function offerAgents(): Promise<void> {
713
+ const { detectAgents, installAgents } = await import('./agents.ts');
714
+ const found = detectAgents(process.cwd());
715
+ if (found.length === 0) return;
716
+ if (!process.stdin.isTTY || !process.stdout.isTTY) { out('\nagents volter agents install --yes (the volter-world skill and MCP server for your coding agents)'); return; }
717
+ process.stdout.write(`\nSet up your coding agent${found.length === 1 ? '' : 's'} (${found.join(', ')}) to drive this World? [y/N] `);
718
+ const answer = await new Promise<string>((done) => { process.stdin.once('data', (d) => done(String(d).trim().toLowerCase())); });
719
+ process.stdin.pause();
720
+ if (answer === 'y' || answer === 'yes') for (const line of installAgents(found, process.cwd())) out(` ${line}`);
721
+ else out('later: volter agents install');
722
+ }
723
+
724
+ /** This package's version, for the MCP server's handshake. */
725
+ function ownVersion(): string {
726
+ try { return (JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')) as { version?: string }).version ?? '0.0.0'; } catch { return '0.0.0'; }
727
+ }
728
+
457
729
  async function main(): Promise<void> {
458
730
  const [noun, verb, ...args] = process.argv.slice(2);
731
+ const notice = startUpdateCheck(process.argv.slice(2));
732
+ await dispatch(noun, verb, args);
733
+ await notice();
734
+ }
735
+
736
+ async function dispatch(noun: string | undefined, verb: string | undefined, args: string[]): Promise<void> {
459
737
  if (!noun || noun === '--help' || noun === '-h' || noun === 'help') { out(HELP); return; }
460
738
  if (verb === '--help' || verb === '-h') { out(HELP); return; }
461
739
  switch (noun) {
@@ -465,14 +743,22 @@ async function main(): Promise<void> {
465
743
  return;
466
744
  }
467
745
  case 'login': await loginCommand([verb, ...args].filter((a): a is string => a !== undefined)); return;
746
+ case 'logout': await logoutCommand(); return;
747
+ case 'whoami': await whoamiCommand(); return;
468
748
  case 'twin': await twinCommand([verb, ...args].filter((a): a is string => a !== undefined)); return;
749
+ case 'mcp': { const { serveMcp } = await import('./mcp.ts'); await serveMcp(ownVersion()); return; }
750
+ case 'agents': { const { agentsCommand } = await import('./agents.ts'); await agentsCommand(verb, args, out); return; }
469
751
  case 'remote': {
470
752
  if (!verb) throw new Error('volter remote: which verb? add | remove | list | serve');
471
753
  await remoteCommand(verb, args);
472
754
  return;
473
755
  }
756
+ case 'open': await openCommand([verb, ...args].filter((a): a is string => a !== undefined)); return;
757
+ case 'completion': process.stdout.write(completionScript(verb)); return;
474
758
  default:
475
- throw new Error(`volter: unknown noun "${noun}" — world, twin or remote\n\n${HELP}`);
759
+ throw new Error(`volter: unknown noun "${noun}" — world, twin, remote, open, completion, agents or mcp
760
+
761
+ ${HELP}`);
476
762
  }
477
763
  }
478
764
 
@@ -36,12 +36,23 @@ export function storeToken(origin: string, token: string, path: string = credent
36
36
  chmodSync(path, 0o600);
37
37
  }
38
38
 
39
+ /** Forget the token stored for an origin; whether one was stored. */
40
+ export function forgetToken(origin: string, path: string = credentialsPath()): boolean {
41
+ const store = readStore(path); const key = normalizeOrigin(origin);
42
+ if (!(key in store)) return false;
43
+ delete store[key];
44
+ writeFileSync(path, `${JSON.stringify(store, null, 2)}\n`, { mode: 0o600 });
45
+ return true;
46
+ }
47
+
39
48
  /** `volter login`: the hosted platform a person signed the CLI into — its origin, beside the credentials. */
40
49
  export function platformPath(): string { return join(dirname(credentialsPath()), 'platform.json'); }
41
50
  export function storePlatform(origin: string, path: string = platformPath()): void {
42
51
  mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
43
52
  writeFileSync(path, `${JSON.stringify({ url: normalizeOrigin(origin), savedAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
44
53
  }
54
+ /** Forget which platform the CLI is signed into. */
55
+ export function forgetPlatform(path: string = platformPath()): void { if (existsSync(path)) writeFileSync(path, '{}\n', { mode: 0o600 }); }
45
56
  export function platformOrigin(path: string = platformPath()): string | undefined {
46
57
  if (!existsSync(path)) return undefined;
47
58
  try { return (JSON.parse(readFileSync(path, 'utf8')) as { url?: string }).url; } catch { return undefined; }