@tnunamak/dalan 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +81 -84
  5. package/bin/dalan.mjs +9 -0
  6. package/bin/dot-worker.mjs +29 -4
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +10 -14
  9. package/docs/claude-worker-onboarding.md +9 -8
  10. package/docs/codex-to-muse.md +21 -35
  11. package/docs/connect-chatgpt.md +10 -16
  12. package/docs/dalan-upgrade.md +4 -2
  13. package/docs/local-agent-mcp.md +24 -4
  14. package/docs/local-agent-requester.md +46 -0
  15. package/docs/manual-setup.md +2 -2
  16. package/docs/operations.md +12 -13
  17. package/docs/pull-workers.md +1 -2
  18. package/docs/service-setup.md +110 -163
  19. package/docs/setup-reference.md +6 -6
  20. package/docs/t3-question-relationship.md +43 -0
  21. package/docs/t3-reverse-control.md +12 -8
  22. package/docs/t3-wake-fence-r4.md +42 -0
  23. package/docs/test-suite-isolation.md +204 -0
  24. package/docs/worker-clients.md +6 -4
  25. package/package.json +5 -3
  26. package/qualification/README.md +13 -0
  27. package/qualification/mcp.json +121 -0
  28. package/qualification/protocol-v0.json +127 -0
  29. package/scripts/dalan-try-selfcheck.mjs +8 -7
  30. package/scripts/worker-bridge-setup.mjs +91 -81
  31. package/src/admin-socket.mjs +2 -1
  32. package/src/answer-journal.mjs +200 -0
  33. package/src/as-store.mjs +5 -3
  34. package/src/as.mjs +35 -26
  35. package/src/auth-check.mjs +59 -0
  36. package/src/cli-help.mjs +16 -16
  37. package/src/client-approval.mjs +57 -0
  38. package/src/client-convenience.mjs +166 -0
  39. package/src/client-conveniences.json +106 -0
  40. package/src/client-conveniences.schema.json +97 -0
  41. package/src/connect-cli.mjs +5 -5
  42. package/src/default-home.mjs +36 -0
  43. package/src/destinations/index.mjs +6 -0
  44. package/src/destinations/none.mjs +3 -0
  45. package/src/destinations/t3.mjs +63 -6
  46. package/src/execution.mjs +20 -2
  47. package/src/follow-current.mjs +27 -0
  48. package/src/gozar-routes.mjs +315 -0
  49. package/src/host-budget.mjs +17 -11
  50. package/src/host-execution-policy.mjs +2 -2
  51. package/src/host-stop-reverify.mjs +6 -4
  52. package/src/integrator.mjs +3 -1
  53. package/src/redirect-policy.mjs +61 -0
  54. package/src/route-setting.mjs +71 -12
  55. package/src/server.mjs +64 -12
  56. package/src/service-auto-update.mjs +8 -1
  57. package/src/service-launchd.mjs +186 -0
  58. package/src/service-migrate-workers.mjs +12 -2
  59. package/src/service-update-runtime.mjs +40 -6
  60. package/src/service-update.mjs +20 -14
  61. package/src/service.mjs +211 -63
  62. package/src/setup.mjs +55 -44
  63. package/src/store.mjs +77 -14
  64. package/src/submission-policy.mjs +8 -4
  65. package/src/t3.mjs +21 -2
  66. package/src/tool-registry.mjs +54 -8
  67. package/src/try-exposure.mjs +7 -657
  68. package/src/try-hosted.mjs +71 -101
  69. package/src/try-selfcheck.mjs +15 -8
  70. package/src/try.mjs +9 -13
  71. package/src/workers.mjs +4 -3
  72. package/src/workspace.mjs +94 -15
  73. package/scripts/lib/expose-tailscale.mjs +0 -408
  74. package/src/try-hosted-clients.mjs +0 -46
package/src/service.mjs CHANGED
@@ -7,13 +7,17 @@ import { createHash, randomBytes } from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { isIP } from 'node:net';
9
9
  import { defaultPath } from './paths.mjs';
10
+ import { socketPathLimit } from './admin-socket.mjs';
10
11
  import { initAsFiles, writeAtomic } from './as-files.mjs';
11
12
  import { parseWorkers } from './workers.mjs';
13
+ import { loadCapacity } from './projects.mjs';
12
14
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
- import { resolveGozarCommand } from './try-exposure.mjs';
15
+ import { buildQuery, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, registerExternalService, resolveGozar, resolveRouteWord } from './gozar-routes.mjs';
14
16
  import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
17
+ import { serviceHomeFor, readDefaultHome, recordDefaultHome, forgetDefaultHome, DEFAULT_SERVICE_HOME } from './default-home.mjs';
18
+ import { launchdLabels, launchAgentsDir, servicePlist, updatePlist, preflightAgentFile, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist, isLoaded } from './service-launchd.mjs';
15
19
 
16
- const REPO = fileURLToPath(new URL('..', import.meta.url));
20
+ const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
17
21
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
18
22
  const fail = message => { throw new Error(message); };
19
23
 
@@ -49,20 +53,24 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
49
53
 
50
54
  function parseOptions(argv, env) {
51
55
  const parsed = parseArgs(argv, {
52
- values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
53
- flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--json', '--help'],
56
+ values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--route', '--lan-port'],
57
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--yes', '--json', '--help'],
54
58
  });
55
59
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
56
60
  if (parsed['--help']) return { help: true };
57
61
  if (parsed['--auto-update'] && parsed['--no-auto-update']) fail('choose --auto-update or --no-auto-update');
58
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
59
- if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
60
- const origin = parseOrigin(parsed['--public-url']);
61
- const port = Number(parsed['--port']);
62
- if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
63
- const target = parseTarget(parsed['--target']);
62
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(env));
63
+ if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a service definition');
64
+ // `--route NAME` alone is the one-command install: Gozar supplies the public address and Dalan picks a loopback port.
65
+ const auto = parsed['--public-url'] === undefined && parsed['--port'] === undefined && parsed['--target'] === undefined;
66
+ if (auto && parsed['--route'] === undefined) fail('pass --route NAME to publish through Gozar, or --public-url, --port and --target for a proxy you already run');
67
+ if (auto && (parsed['--lan-port'] !== undefined || parsed['--verify-cmd'] !== undefined)) fail('--lan-port and --verify-cmd belong with an explicit --public-url, --port and --target');
68
+ const origin = auto ? null : parseOrigin(parsed['--public-url']);
69
+ const port = auto ? null : Number(parsed['--port']);
70
+ if (!auto && (!Number.isInteger(port) || port < 1024 || port > 65535)) fail('--port must be a fixed port from 1024 through 65535');
71
+ const target = auto ? null : parseTarget(parsed['--target']);
64
72
  const lanPort = parsed['--lan-port'] === undefined ? null : Number(parsed['--lan-port']);
65
- validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
73
+ if (!auto) validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
66
74
  const workers = [];
67
75
  for (let i = 0; i < argv.length; i++) {
68
76
  if (argv[i] === '--worker') workers.push(argv[++i]);
@@ -73,10 +81,10 @@ function parseOptions(argv, env) {
73
81
  }
74
82
  if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
75
83
  if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
76
- const gozarBin = parsed['--gozar-bin'];
77
- if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
78
- return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
79
- gozarBin, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
84
+ const route = parsed['--route'];
85
+ if (route !== undefined && (!route || route.startsWith('-'))) fail('--route must name a Gozar route');
86
+ return { home, auto, homeExplicit: parsed['--home'] !== undefined, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
87
+ route, yes: parsed['--yes'] === true, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
80
88
  writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
81
89
  }
82
90
 
@@ -106,6 +114,23 @@ function nodePath(execPath) {
106
114
  return execPath;
107
115
  }
108
116
 
117
+ function readReceipt(home) {
118
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
119
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
120
+ }
121
+
122
+ function firstFreePort(start) {
123
+ return new Promise((resolve, reject) => {
124
+ const attempt = port => {
125
+ if (port > 65535) return reject(new Error('no free port from 8789 upward'));
126
+ const probe = net.createServer();
127
+ probe.once('error', () => attempt(port + 1));
128
+ probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(port)));
129
+ };
130
+ attempt(start);
131
+ });
132
+ }
133
+
109
134
  function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
110
135
 
111
136
  function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null, recover = true } = {}) {
@@ -170,7 +195,7 @@ function profileFor(home, workers) {
170
195
 
171
196
  const POLICY_HOME_FILES = new Set([
172
197
  'service-migration.json', 'workers.json', 'workers-audit.jsonl', 'workers-audit-checkpoint.sqlite',
173
- 'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json',
198
+ 'workers-audit-checkpoint.sqlite-wal', 'workers-audit-checkpoint.sqlite-shm', 'workers-repos.json', 'limits.json',
174
199
  ]);
175
200
  const WORKSPACE_RUNTIME_DIRS = new Set(['artifacts', 'caches', 'host-receipts', 'mirrors', 'run', 'worktrees']);
176
201
  const WORKSPACE_RUNTIME_FILES = new Map([['github-askpass', 0o700]]);
@@ -208,7 +233,7 @@ function checkHomeScope(home, configDir, o, workers) {
208
233
  if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
209
234
  const rootEntries = fs.readdirSync(home);
210
235
  if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
211
- const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
236
+ const rootAllowed = ['.config', '.local', '.tmp', 'resource-url', 'logs', 'current', 'versions', 'update-result.json', 'update-failed.json', 'update-transaction.json', 'update-backup', 'update-lock.sqlite', 'update-lock.sqlite-journal'];
212
237
  if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
213
238
  if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
214
239
  const configRoot = path.join(home, '.config');
@@ -224,8 +249,13 @@ function checkHomeScope(home, configDir, o, workers) {
224
249
  if (configInfo.isSymbolicLink() || !configInfo.isDirectory()) fail(`${configDir} must be a real directory`);
225
250
  const receiptFile = path.join(configDir, 'service-install.json');
226
251
  const entries = fs.readdirSync(configDir);
252
+ if (entries.includes('limits.json')) {
253
+ const file = path.join(configDir, 'limits.json'), info = fs.lstatSync(file);
254
+ if (!info.isFile() || info.isSymbolicLink() || (typeof process.getuid === 'function' && info.uid !== process.getuid()) || (info.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
255
+ loadCapacity(file);
256
+ }
227
257
  const hasReceipt = entries.includes('service-install.json');
228
- if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url'].includes(name))) fail(`${home} contains update data without a service receipt`);
258
+ if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url', 'logs'].includes(name))) fail(`${home} contains update data without a service receipt`);
229
259
  if (hasReceipt) {
230
260
  const info = fs.lstatSync(receiptFile);
231
261
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
@@ -342,19 +372,39 @@ function assertGozarStatePath(env) {
342
372
 
343
373
  export async function installService(o, seams = {}) {
344
374
  const env = seams.env ?? process.env;
345
- if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
346
- if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute systemd-safe path');
375
+ const platform = seams.platform ?? process.platform;
376
+ if (!['linux', 'darwin'].includes(platform)) fail('dalan service install needs Linux with a systemd user manager or macOS with launchd');
377
+ const mac = platform === 'darwin';
378
+ if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute service-safe path');
379
+ assertRealDirectoryPath(path.dirname(o.home), { owner: true });
380
+ assertRealDirectoryPath(o.home, { owner: true });
381
+ // Every check up to the route allocation below only reads. A public route is allocated after the last of them passes, so a
382
+ // read-only preflight refusal leaves no route behind. Later writes or startup can still fail.
383
+ const adminSocket = path.join(defaultPath(o.home, '.local/share/dot-bridge'), 'admin.sock');
384
+ const socketBytes = Buffer.byteLength(adminSocket), socketLimit = socketPathLimit(platform);
385
+ if (socketBytes > socketLimit) fail(`--home is too long: the bridge's admin socket ${adminSocket} would be ${socketBytes} bytes, and the limit on ${mac ? 'macOS' : 'Linux'} is ${socketLimit} bytes. Use a shorter --home.`);
386
+ let gozar = null, allocate = false;
387
+ if (o.auto) {
388
+ // The one-command install: reuse the port and address a previous run recorded, or pick a free port now and ask Gozar for
389
+ // the address once every check has passed.
390
+ const prior = readReceipt(o.home);
391
+ if (prior?.origin && prior.port) o = { ...o, origin: prior.origin, port: prior.port, target: parseTarget(prior.target) };
392
+ else {
393
+ const port = await (seams.freePort ?? firstFreePort)(8789);
394
+ o = { ...o, origin: null, port, target: parseTarget(`127.0.0.1:${port}`) };
395
+ allocate = true;
396
+ }
397
+ }
347
398
  const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
348
399
  o = { ...o, target };
349
400
  validateTopology(o);
350
- assertRealDirectoryPath(path.dirname(o.home), { owner: true });
351
- assertRealDirectoryPath(o.home, { owner: true });
352
401
  const profile = profileFor(o.home, o.workers ?? []);
353
402
  assertRealDirectoryPath(path.dirname(profile.file));
354
- const unitDir = path.join(env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config'), 'systemd/user');
403
+ const unitDir = mac ? launchAgentsDir(env) : path.join(env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(os.homedir(), '.config'), 'systemd/user');
355
404
  assertRealDirectoryPath(unitDir, { owner: true });
356
405
  const configDir = path.dirname(profile.file);
357
406
  const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
407
+ if (mac && !(o.target.host === '127.0.0.1' && o.target.port === o.port)) fail('on macOS the target must be 127.0.0.1:<port> (the same as --port)');
358
408
  const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
359
409
  const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
360
410
  const receiptFile = homeScope.receiptFile;
@@ -363,13 +413,22 @@ export async function installService(o, seams = {}) {
363
413
  const current = path.join(o.home, 'current');
364
414
  const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
365
415
  if (hasCurrent && !fs.lstatSync(current).isSymbolicLink()) fail(`${current} must be the service package symlink`);
366
- const { files, enable, name } = unitFiles(o, { home: o.home, repo: current, node, proxy });
367
- const updateUnits = autoUpdateUnits({ home: o.home, unit: name, node });
368
- Object.assign(files, updateUnits.files);
416
+ const name = unitName(o.home), labels = launchdLabels(name);
417
+ let files, enable = [];
418
+ if (mac) files = { [`${labels.service}.plist`]: servicePlist({ unit: name, node, home: o.home, port: o.port, enableWorkspace: o.enableWorkspace, enableT3: o.enableT3 }) };
419
+ else {
420
+ ({ files, enable } = unitFiles(o, { home: o.home, repo: current, node, proxy }));
421
+ Object.assign(files, autoUpdateUnits({ home: o.home, unit: name, node }).files);
422
+ }
369
423
  let replaceLegacyUnit = false;
424
+ let updateNeedsReplace = false;
370
425
  // Check every collision before creating the bridge home or the first unit file.
426
+ if (mac && autoUpdate && !o.writeUnitsOnly) {
427
+ updateNeedsReplace = preflightAgentFile(path.join(unitDir, `${labels.update}.plist`), updatePlist({ unit: name, node, home: o.home }));
428
+ }
371
429
  for (const [filename, text] of Object.entries(files)) {
372
430
  const file = path.join(unitDir, filename);
431
+ if (mac) { preflightAgentFile(file, text); continue; }
373
432
  if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
374
433
  const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
375
434
  const oldRepo = actual.match(/^WorkingDirectory=(.+)$/m)?.[1];
@@ -381,21 +440,35 @@ export async function installService(o, seams = {}) {
381
440
  else fail(`${file} already exists with different contents; refusing to overwrite it`);
382
441
  }
383
442
  }
443
+ if (mac && !o.writeUnitsOnly && preflightAgentFile(path.join(unitDir, `${labels.service}.plist`), files[`${labels.service}.plist`])) {
444
+ isLoaded(labels.service, seams.launchd);
445
+ }
446
+ if (updateNeedsReplace) isLoaded(labels.update, seams.launchd);
384
447
  if (o.writeUnitsOnly) {
385
448
  if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
386
- writeUnits(unitDir, files);
387
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
449
+ if (mac) for (const [filename, text] of Object.entries(files)) writeAgentFile(path.join(unitDir, filename), text); else writeUnits(unitDir, files);
450
+ return { schema_version: 1, home: o.home, unit: mac ? labels.service : `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
388
451
  }
389
- // An explicit --gozar-bin wins; otherwise the bundled Gozar, GOZAR_BIN, then PATH.
390
- const gozar = o.gozarBin !== undefined ? { binary: o.gozarBin, args: [] }
391
- : resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
392
- if (!gozar.binary) fail('Gozar is unavailable; reinstall @tnunamak/dalan with its dependencies, or install gozar on PATH or set GOZAR_BIN to an executable path, then retry service install.');
452
+ gozar ??= seams.gozar ?? await resolveGozar();
393
453
  assertGozarStatePath(env);
394
454
  const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
395
455
  const spawn = seams.spawn ?? spawnSync;
396
- runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
456
+ if (!mac) {
457
+ try { runCommand('systemctl', ['--user', 'show-environment'], { env, spawn }); }
458
+ catch (error) { fail(`the user systemd manager is not reachable (${error.message}). Run \`systemctl --user status\` to see why; a login session or \`loginctl enable-linger\` may be needed.`); }
459
+ }
460
+ let allocated = null;
461
+ if (allocate) {
462
+ const wanted = buildQuery({ home: gozarHomeFor(env), target: o.target.value, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, address: 'stable' });
463
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
464
+ const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
465
+ o = { ...o, origin: parseOrigin(view.origin) };
466
+ // Gozar's reply does not say whether this call created the route or reused one that already existed (from `dalan setup`, or
467
+ // another install), so a failure below never closes it. The receipt keeps its handle, and `dalan service uninstall` releases it.
468
+ allocated = view.handle ?? null;
469
+ }
397
470
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
398
- if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate }, null, 2)}\n`);
471
+ if (!homeScope.hasReceipt) writePrivate(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate, platform, route: o.route ?? null, ...(allocated ? { route_handle: allocated } : {}) }, null, 2)}\n`);
399
472
  if (!hasCurrent) fs.symlinkSync(repo, current);
400
473
  const homeFiles = prepareHome(o, profile);
401
474
  if (needsEnrollmentRestart) {
@@ -406,34 +479,85 @@ export async function installService(o, seams = {}) {
406
479
  writeAtomic(file, files[`${name}.service`]);
407
480
  fs.chmodSync(file, mode);
408
481
  }
409
- writeUnits(unitDir, files);
410
- runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
411
- runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
412
- if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
482
+ if (mac) {
483
+ fs.mkdirSync(path.join(o.home, 'logs'), { recursive: true, mode: 0o700 });
484
+ const plistFile = path.join(unitDir, `${labels.service}.plist`);
485
+ const changed = preflightAgentFile(plistFile, files[`${labels.service}.plist`]);
486
+ if (changed) unloadAgent({ label: labels.service }, seams.launchd);
487
+ writeAgentFile(plistFile, files[`${labels.service}.plist`]);
488
+ if (lintPlist(plistFile, seams) === false) fail(`${plistFile} is not a valid property list`);
489
+ const { kicked, detail } = loadAgent({ label: labels.service, plistFile, knownAbsent: changed }, seams.launchd);
490
+ if (!kicked) fail(`launchctl kickstart ${labels.service} failed: ${detail}`);
491
+ } else {
492
+ writeUnits(unitDir, files);
493
+ runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
494
+ runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
495
+ if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
496
+ }
413
497
  const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
414
498
  const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
415
- if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
416
- const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
417
- if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
418
- gozarArgs.push('--json');
419
- const output = runCommand(gozar.binary, [...gozar.args, ...gozarArgs], { env, spawn, timeout: 120000 });
499
+ if (!ready) fail(`Dalan did not start on its admin socket; the service and home remain for inspection: ${mac ? `tail ${path.join(o.home, 'logs', 'bridge.err.log')}` : `systemctl --user status ${name}.service`}`);
500
+ const gozarHome = gozarHomeFor(env);
420
501
  let routeReply;
421
- try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
422
- if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
423
- fail('Gozar returned a service route that does not match the requested origin and target; the bridge is running but its route is unverified');
502
+ if (o.route !== undefined) {
503
+ // A named Gozar route: Gozar allocates or adopts it and pins the origin; nothing here interprets the name.
504
+ const wanted = buildQuery({ home: gozarHome, target: o.target.value, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, origin: o.origin, address: 'stable' });
505
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
506
+ const view = await ensureDurableRoute({ gozar, query, pick, consent: seams.consent ?? (async () => fail('A durable route needs your approval; run `dalan setup --route NAME` first, then retry.')) });
507
+ if (view.origin !== o.origin) fail(`Gozar pinned ${view.origin}, not the requested ${o.origin}; the bridge is running but its route needs repair`);
508
+ routeReply = view;
509
+ } else {
510
+ routeReply = (await registerExternalService({ gozar, home: gozarHome, origin: o.origin, target: o.target.value, ...(o.verifyCmd ? { verifyCmd: o.verifyCmd } : {}) })).route;
424
511
  }
425
- if (routeReply.route.verification?.status !== 'verified') {
426
- fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
427
- }
428
- await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn });
512
+ if (routeReply.verification?.status !== 'verified') fail(`Gozar did not verify the route; the bridge is running and the route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
513
+ { const done = JSON.parse(fs.readFileSync(receiptFile, 'utf8')); if (routeReply.handle && JSON.stringify(done.route_handle) !== JSON.stringify(routeReply.handle)) writeAtomic(receiptFile, `${JSON.stringify({ ...done, route_handle: routeReply.handle }, null, 2)}\n`); }
514
+ await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn, platform });
515
+ if (!env.DALAN_HOME) recordDefaultHome(o.home, env);
429
516
  if (needsEnrollmentRestart) {
430
517
  const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
431
518
  delete enrolled.enrollment_pending;
432
519
  writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
433
520
  }
434
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
521
+ return { schema_version: 1, origin: routeReply.published ?? o.origin, home: o.home, unit: mac ? labels.service : `${name}.service`, already_installed: homeScope.hasReceipt && !needsEnrollmentRestart, units: Object.keys(files), port: o.port,
435
522
  workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
436
- target: o.target.value, started: true, route: routeReply.route, auto_update: autoUpdate };
523
+ target: o.target.value, started: true, route: routeReply, auto_update: autoUpdate };
524
+ }
525
+
526
+ // Stop the service and its update job, delete the generated definitions and the public route, and forget the default home.
527
+ // The home itself (secrets, grants, data) stays; delete it by hand if you also want that gone.
528
+ export async function uninstallService({ home }, seams = {}) {
529
+ const env = seams.env ?? process.env, platform = seams.platform ?? process.platform, mac = platform === 'darwin';
530
+ home = path.resolve(home);
531
+ const receipt = readReceipt(home);
532
+ if (!receipt?.unit || receipt.home !== home) fail(`no Dalan service is installed for ${home}`);
533
+ const removed = [];
534
+ const unitDir = receipt.unit_dir;
535
+ if (!unitDir || !path.isAbsolute(unitDir)) fail('the service receipt names no unit directory');
536
+ // Verify both jobs before removing either plist or disabling automatic updates.
537
+ if (mac) for (const label of Object.values(launchdLabels(receipt.unit))) isLoaded(label, seams.launchd);
538
+ if (receipt.auto_update) { try { await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform }); removed.push('automatic updates off'); } catch (error) { if (mac) throw error; removed.push(`update job not removed: ${error.message}`); } }
539
+ if (mac) removed.push(...removeAgents({ unit: receipt.unit, unit_dir: unitDir }, seams.launchd));
540
+ else {
541
+ const spawn = seams.spawn ?? spawnSync, name = receipt.unit;
542
+ const units = [`${name}.service`, `${name}-target.socket`, `${name}-target.service`, `${name}-update.service`, `${name}-update.timer`].filter(unit => fs.existsSync(path.join(unitDir, unit)));
543
+ if (units.length) { spawn('systemctl', ['--user', 'disable', '--now', ...units], { encoding: 'utf8', env }); }
544
+ for (const unit of units) { fs.rmSync(path.join(unitDir, unit)); removed.push(`removed ${path.join(unitDir, unit)}`); }
545
+ spawn('systemctl', ['--user', 'daemon-reload'], { encoding: 'utf8', env });
546
+ }
547
+ if (receipt.route_handle) {
548
+ try {
549
+ const gozar = seams.gozar ?? await resolveGozar();
550
+ const closed = await gozar.closeRoute({ home: gozarHomeFor(env), handle: receipt.route_handle, mode: 'remove' });
551
+ removed.push(`public route ${closed.state}`);
552
+ } catch (error) { removed.push(`public route not removed: ${explainRouteError(error).line}`); }
553
+ }
554
+ forgetDefaultHome(home, env);
555
+ // The home holds secrets, grants and data, so it is moved aside, never deleted. A new install then starts from a fresh home at the same path.
556
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
557
+ let aside = `${home}.removed-${stamp}`;
558
+ for (let n = 2; fs.existsSync(aside); n++) aside = `${home}.removed-${stamp}-${n}`;
559
+ fs.renameSync(home, aside);
560
+ return { home, removed, kept: `${aside} (secrets and data, moved aside; delete it yourself to remove them)`, moved_to: aside };
437
561
  }
438
562
 
439
563
  export async function serviceMain(argv, seams = {}) {
@@ -446,7 +570,7 @@ export async function serviceMain(argv, seams = {}) {
446
570
  const parsed = parseArgs(args, { values: ['--home'], flags: ['--quiet', '--help'] });
447
571
  if (parsed['--help']) return serviceMain(['help'], seams);
448
572
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
449
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
573
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
450
574
  const { recoverService } = await import('./service-update.mjs');
451
575
  const result = recoverService({ home });
452
576
  if (!parsed['--quiet']) (seams.out ?? console.log)(JSON.stringify(result));
@@ -455,7 +579,7 @@ export async function serviceMain(argv, seams = {}) {
455
579
  if (['update', 'status', 'auto-update'].includes(action)) {
456
580
  const parsed = parseArgs(args, { values: ['--home'], flags: ['--check', '--yes', '--retry', '--json', '--help'] });
457
581
  if (parsed['--help']) return serviceMain(['help'], seams);
458
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
582
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
459
583
  let result;
460
584
  if (action === 'auto-update') {
461
585
  if (parsed._.length !== 1 || !['on', 'off'].includes(parsed._[0]) || parsed['--check'] || parsed['--yes'] || parsed['--retry']) fail('use dalan service auto-update on|off [--home DIR]');
@@ -472,21 +596,45 @@ export async function serviceMain(argv, seams = {}) {
472
596
  return result;
473
597
  }
474
598
  if (action === 'help' || action === '--help' || !action) {
475
- (seams.out ?? console.log)('Usage: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--auto-update|--no-auto-update] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Linux systemd only.');
599
+ (seams.out ?? console.log)('Usage: dalan service install --worker NAME --route NAME [--yes] [--home DIR] [--enable-workspace] [--enable-t3] [--auto-update|--no-auto-update]\n dalan service install --public-url https://HOST --port N --target HOST:PORT [--home DIR] [--lan-port N] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only] (an address you already serve)\n dalan service uninstall [--home DIR]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]\n dalan service update [--check|--yes] [--retry] [--home DIR] [--json]\n dalan service auto-update on|off [--home DIR]\n dalan service status [--home DIR] [--json]\n dalan service recover --home DIR [--quiet]\nNew installs check daily with jitter. Catalog changes stage until --yes authorizes a connector refresh. --check reports availability without installing. Runs under systemd on Linux and launchd on macOS.');
476
600
  return null;
477
601
  }
478
- if (action !== 'install') fail('use dalan service install, update, auto-update, status, recover or migrate-workers');
602
+ if (action === 'uninstall') {
603
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--json', '--help'] });
604
+ if (parsed['--help']) return serviceMain(['help'], seams);
605
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
606
+ const result = await uninstallService({ home: parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env) }, seams);
607
+ const out = seams.out ?? console.log;
608
+ if (parsed['--json']) out(JSON.stringify(result)); else { for (const line of result.removed) out(line); out(`Kept: ${result.kept}`); }
609
+ return result;
610
+ }
611
+ if (action !== 'install') fail('use dalan service install, uninstall, update, auto-update, status, recover or migrate-workers');
479
612
  const o = parseOptions(args, seams.env ?? process.env);
480
613
  if (o.help) return serviceMain(['help'], seams);
481
- const result = await installService(o, seams);
614
+ const out0 = seams.out ?? console.log;
615
+ // Gozar describes the route it would open; the owner approves it once (the answer is kept with the route). `--yes` approves what was printed.
616
+ const consent = seams.consent ?? (async candidate => {
617
+ out0(describeCandidate(candidate).join('\n')); out0(describeDisclosure(candidate).join('\n'));
618
+ if (o.yes) return true;
619
+ if (!process.stdin.isTTY) { out0('Run this in a terminal to approve the route, or add --yes after reading the description above.'); return false; }
620
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
621
+ try { return /^y(es)?$/i.test((await rl.question('Use this route? [y/N] ')).trim()); } finally { rl.close(); }
622
+ });
623
+ const result = await installService(o, { ...seams, consent });
482
624
  if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
483
625
  else {
484
- (seams.out ?? console.log)(`Service: ${result.unit} (${result.started ? 'active' : 'unit files written'})`);
485
- (seams.out ?? console.log)(`Home: ${result.home}`);
486
- (seams.out ?? console.log)(`Public MCP URL: ${result.public_url ?? `${o.origin}/<secret>/mcp`}`);
487
- (seams.out ?? console.log)(`Private URL file: ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
488
- (seams.out ?? console.log)(`Gozar target: ${result.target}`);
489
- if (result.route) (seams.out ?? console.log)(`Gozar route: ${result.route.verification.status}`);
626
+ const out = seams.out ?? console.log;
627
+ out(`Service: ${result.unit} (${result.started ? (result.already_installed ? 'already installed, running' : 'running') : 'files written'})`);
628
+ out(`Home: ${result.home}`);
629
+ out(`Public address: ${result.origin ?? o.origin ?? result.public_url}`);
630
+ out(`Connector URL (keep private): in ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
631
+ if (result.route) out(`Route: ${result.route.verification?.status ?? 'unknown'}`);
632
+ if (result.started) {
633
+ out(`Updates: ${result.auto_update ? 'automatic, once a day' : 'off; run dalan service update'}`);
634
+ const worker = result.workers?.[0] ?? 'WORKER';
635
+ out(`Next: dalan connect start --worker ${worker}`);
636
+ out('Check: dalan doctor --auth');
637
+ }
490
638
  }
491
639
  return result;
492
640
  }
package/src/setup.mjs CHANGED
@@ -1,63 +1,74 @@
1
- // `dalan setup`: choose the saved public route. It detects what Tailscale can do and asks as little as possible:
2
- // Tailscale ready for Funnel -> one yes/no question; not found -> one short choice. `dalan try --public` asks for relay consent
3
- // before it exposes the temporary demo link.
1
+ // `dalan setup`: choose the saved public route. Gozar owns every route; Dalan asks it what is possible, shows what it returned, asks once,
2
+ // and saves only the requirements, the opaque route name and the pinned origin (route-setting.mjs, version 2).
4
3
  import readline from 'node:readline';
5
- import { INSTALL_URL, defaultTailscale, preflight, whichOnPath } from '../scripts/lib/expose-tailscale.mjs';
6
- import { readRouteSetting, writeRouteSetting } from './route-setting.mjs';
4
+ import {
5
+ RouteError, buildQuery, dalanRequirements, describeCandidate, describeDisclosure, ensureDurableRoute, explainRouteError, gozarHomeFor, resolveGozar, targetFor,
6
+ } from './gozar-routes.mjs';
7
+ import { inspectRouteSetting, writeRouteSetting } from './route-setting.mjs';
7
8
 
8
- // What this computer's Tailscale can do now: { ok, node } or { ok: false, installed, reason }.
9
- // The address is the OAuth issuer, so a new address is a new sign-in identity: nothing from a trial carries over.
10
9
  export const SWITCH_NOTE = 'Next: run `dalan try --public`, then in your MCP client remove the trial connector and add the new URL it prints; a new address cannot reuse the trial sign-in.';
10
+ export const ROUTE_ID = 'dalan-main';
11
+ const DEFAULT_PORT = 8789;
11
12
 
12
- export function detectTailscale({ env = process.env, tailscale = defaultTailscale, which = name => whichOnPath(name, env), platform = process.platform, mac } = {}) {
13
- if (!which('tailscale')) return { ok: false, installed: false, reason: 'Tailscale is not installed.' };
14
- try {
15
- const found = preflight({ tailscale, platform, mac });
16
- return { ok: true, node: found.dnsName.split('.')[0], dnsName: found.dnsName };
17
- } catch (error) { return { ok: false, installed: true, reason: String(error.message).split('\n')[0] }; }
13
+ export function parseSetupArgs(argv) {
14
+ const out = { route: undefined };
15
+ for (let i = 0; i < argv.length; i++) {
16
+ const arg = argv[i];
17
+ if (arg === '--route') { out.route = argv[++i]; if (out.route === undefined) throw new Error('--route needs a name'); } else if (arg.startsWith('--route=')) out.route = arg.slice(8);
18
+ else throw new Error(`unknown option ${arg}; usage: dalan setup [--route NAME]`);
19
+ }
20
+ return out;
18
21
  }
19
22
 
20
- export async function runSetup({ env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), detect = () => detectTailscale({ env }) } = {}) {
23
+ export async function runSetup({
24
+ argv = [], env = process.env, out = process.stdout, input = process.stdin, interactive = Boolean(process.stdin.isTTY), gozar, gozarHome, answers, port = DEFAULT_PORT,
25
+ } = {}) {
21
26
  const say = line => out.write(`${line}\n`);
22
- const found = detect();
23
- const saved = readRouteSetting(env);
24
- const lines = interactive ? readline.createInterface({ input }) : null;
27
+ const { route: routeName } = parseSetupArgs(argv);
28
+ const found = inspectRouteSetting(env);
29
+ if (found.state === 'legacy') {
30
+ say('A saved 0.6 route setting exists. It is left untouched. Moving it to Gozar is a separate, journaled step that keeps the same address; setup never rewrites it.');
31
+ return { route: null, changed: false, legacy: true };
32
+ }
33
+ if (found.state === 'unreadable') { say(`The saved route setting could not be read (${found.reason}). It was left untouched.`); return { route: null, changed: false }; }
34
+ const lines = !answers && interactive ? readline.createInterface({ input }) : null;
35
+ const queued = answers ? [...answers] : null;
25
36
  const ask = question => new Promise(resolve => {
37
+ if (queued) { out.write(question); return resolve(queued.shift() ?? null); }
38
+ if (!lines) return resolve(null);
26
39
  let done = false;
27
40
  const finish = answer => { if (!done) { done = true; lines.off('close', onClose); resolve(answer); } };
28
41
  const onClose = () => finish(null);
29
42
  out.write(question); lines.once('line', finish); lines.once('close', onClose);
30
43
  });
31
44
  try {
32
- if (found.ok) {
33
- if (!interactive) { say(`Tailscale is ready on this computer (${found.node}). Run \`dalan setup\` in a terminal to use it.`); return { route: saved, changed: false }; }
34
- const answer = ((await ask(`Use Tailscale (${found.node}) for a stable address? [Y/n] `)) ?? '').trim().toLowerCase();
35
- if (answer === '' || answer === 'y' || answer === 'yes') {
36
- writeRouteSetting('tailscale', env);
37
- say('Saved Tailscale for public runs. Reuse the same node and public address to keep the connector identity; changing that address requires a new sign-in.');
38
- say(SWITCH_NOTE);
39
- return { route: 'tailscale', changed: saved !== 'tailscale' };
40
- }
41
- writeRouteSetting('gozar', env);
42
- say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning. Run `dalan setup` again to switch.');
43
- return { route: 'gozar', changed: saved !== 'gozar' };
44
- }
45
- say(found.reason);
46
- say('For daily use, pick one:');
47
- say(` 1. Tailscale (recommended): install it from ${INSTALL_URL}, run \`tailscale up\`, then run \`dalan setup\` again.`);
48
- say(' 2. Use Gozar for a temporary demo link: it can change or stop without warning.');
49
- if (!interactive) return { route: saved, changed: false };
50
- const answer = ((await ask('Choose [1]: ')) ?? '').trim();
51
- if (answer === '2') {
52
- writeRouteSetting('gozar', env);
53
- say('Saved. `dalan try --public` uses Gozar for a temporary demo link. It can change or stop without warning.');
54
- return { route: 'gozar', changed: saved !== 'gozar' };
45
+ const runtime = gozar ?? await resolveGozar();
46
+ const home = gozarHome ?? gozarHomeFor(env);
47
+ const query = buildQuery({ home, target: targetFor(port), usage: { kind: 'durable', routeId: ROUTE_ID }, address: 'stable', ...(routeName !== undefined ? { route: routeName } : {}) });
48
+ if (!interactive && !answers) { say('Run `dalan setup` in a terminal to choose a public route.'); return { route: found.setting ?? null, changed: false }; }
49
+ const consent = async candidate => {
50
+ for (const line of describeCandidate(candidate)) say(line);
51
+ for (const line of describeDisclosure(candidate)) say(line);
52
+ const answer = String((await ask('Use this route for public runs? [y/N] ')) ?? '').trim().toLowerCase();
53
+ return answer === 'y' || answer === 'yes';
54
+ };
55
+ let view;
56
+ try { view = await ensureDurableRoute({ gozar: runtime, query, consent }); } catch (error) {
57
+ if (error?.tryKind === 'consent') { say('Nothing saved.'); return { route: found.setting ?? null, changed: false }; }
58
+ if (error?.code === 'setup_required' || error?.nextAction) { const e = explainRouteError(error); say(e.line); if (e.fix) say(`Next: ${e.fix}`); return { route: found.setting ?? null, changed: false }; }
59
+ throw error;
55
60
  }
56
- say('Nothing saved. Install Tailscale, then run `dalan setup` again.');
57
- return { route: saved, changed: false };
61
+ const setting = { version: 2, requirements: dalanRequirements({ address: 'stable' }), gozarHome: home, routeName: routeName ?? null, routeId: ROUTE_ID, origin: view.origin, bridgeHome: null };
62
+ writeRouteSetting(setting, env);
63
+ say(`Saved. Public runs use ${view.origin}. A changed address needs a new sign-in.`);
64
+ say(SWITCH_NOTE);
65
+ return { route: setting, changed: found.state !== 'current' || found.setting.origin !== setting.origin || found.setting.routeName !== setting.routeName };
58
66
  } finally { lines?.close(); }
59
67
  }
60
68
 
61
- export async function main() {
62
- try { await runSetup(); } catch (error) { process.stderr.write(`dalan: ${error.message}\n`); process.exitCode = 1; }
69
+ export async function main(argv = process.argv.slice(2)) {
70
+ try { await runSetup({ argv }); } catch (error) {
71
+ const e = error instanceof RouteError || error?.code ? explainRouteError(error) : { line: error.message, fix: null };
72
+ process.stderr.write(`dalan: ${e.line}\n${e.fix ? `${e.fix}\n` : ''}`); process.exitCode = 1;
73
+ }
63
74
  }