@tnunamak/dalan 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +25 -64
  3. package/bin/dalan.mjs +9 -0
  4. package/bin/dot-worker.mjs +16 -2
  5. package/docs/chatgpt-worker-onboarding.md +10 -14
  6. package/docs/claude-worker-onboarding.md +9 -8
  7. package/docs/codex-to-muse.md +21 -35
  8. package/docs/connect-chatgpt.md +10 -16
  9. package/docs/dalan-upgrade.md +4 -2
  10. package/docs/local-agent-mcp.md +24 -4
  11. package/docs/manual-setup.md +2 -2
  12. package/docs/operations.md +10 -11
  13. package/docs/pull-workers.md +1 -2
  14. package/docs/service-setup.md +99 -145
  15. package/docs/setup-reference.md +5 -5
  16. package/docs/worker-clients.md +4 -4
  17. package/package.json +2 -3
  18. package/scripts/dalan-try-selfcheck.mjs +8 -7
  19. package/scripts/worker-bridge-setup.mjs +91 -81
  20. package/src/as-store.mjs +5 -3
  21. package/src/as.mjs +35 -26
  22. package/src/auth-check.mjs +53 -0
  23. package/src/cli-help.mjs +20 -15
  24. package/src/client-approval.mjs +57 -0
  25. package/src/client-convenience.mjs +166 -0
  26. package/src/client-conveniences.json +106 -0
  27. package/src/client-conveniences.schema.json +97 -0
  28. package/src/connect-cli.mjs +5 -5
  29. package/src/default-home.mjs +36 -0
  30. package/src/follow-current.mjs +25 -0
  31. package/src/gozar-routes.mjs +314 -0
  32. package/src/redirect-policy.mjs +61 -0
  33. package/src/route-setting.mjs +71 -12
  34. package/src/server.mjs +38 -2
  35. package/src/service-auto-update.mjs +68 -0
  36. package/src/service-launchd.mjs +166 -0
  37. package/src/service-update-gate.mjs +20 -0
  38. package/src/service-update-lock.mjs +22 -0
  39. package/src/service-update-runtime.mjs +290 -0
  40. package/src/service-update.mjs +399 -0
  41. package/src/service.mjs +241 -58
  42. package/src/setup.mjs +55 -44
  43. package/src/try-exposure.mjs +7 -657
  44. package/src/try-hosted.mjs +71 -101
  45. package/src/try-selfcheck.mjs +15 -8
  46. package/src/try.mjs +9 -13
  47. package/scripts/lib/expose-tailscale.mjs +0 -408
  48. package/src/try-hosted-clients.mjs +0 -46
package/src/service.mjs CHANGED
@@ -7,12 +7,15 @@ 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 { initAsFiles } from './as-files.mjs';
10
+ import { initAsFiles, writeAtomic } from './as-files.mjs';
11
11
  import { parseWorkers } from './workers.mjs';
12
12
  import { parseArgs } from '../scripts/live-trial/common.mjs';
13
- import { resolveGozarCommand } from './try-exposure.mjs';
13
+ import { buildQuery, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, registerExternalService, resolveGozar, resolveRouteWord } from './gozar-routes.mjs';
14
+ import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
15
+ import { serviceHomeFor, readDefaultHome, recordDefaultHome, forgetDefaultHome, DEFAULT_SERVICE_HOME } from './default-home.mjs';
16
+ import { launchdLabels, launchAgentsDir, servicePlist, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist } from './service-launchd.mjs';
14
17
 
15
- const REPO = fileURLToPath(new URL('..', import.meta.url));
18
+ const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
16
19
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
17
20
  const fail = message => { throw new Error(message); };
18
21
 
@@ -48,19 +51,24 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
48
51
 
49
52
  function parseOptions(argv, env) {
50
53
  const parsed = parseArgs(argv, {
51
- values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--gozar-bin', '--lan-port'],
52
- flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--json', '--help'],
54
+ values: ['--home', '--public-url', '--port', '--target', '--worker', '--verify-cmd', '--route', '--lan-port'],
55
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--yes', '--json', '--help'],
53
56
  });
54
57
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
55
58
  if (parsed['--help']) return { help: true };
56
- const home = path.resolve(parsed['--home'] ?? path.join(os.homedir(), '.local/share/dalan-service'));
57
- if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a systemd unit');
58
- const origin = parseOrigin(parsed['--public-url']);
59
- const port = Number(parsed['--port']);
60
- if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port must be a fixed port from 1024 through 65535');
61
- const target = parseTarget(parsed['--target']);
59
+ if (parsed['--auto-update'] && parsed['--no-auto-update']) fail('choose --auto-update or --no-auto-update');
60
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(env));
61
+ if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a service definition');
62
+ // `--route NAME` alone is the one-command install: Gozar supplies the public address and Dalan picks a loopback port.
63
+ const auto = parsed['--public-url'] === undefined && parsed['--port'] === undefined && parsed['--target'] === undefined;
64
+ 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');
65
+ 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');
66
+ const origin = auto ? null : parseOrigin(parsed['--public-url']);
67
+ const port = auto ? null : Number(parsed['--port']);
68
+ if (!auto && (!Number.isInteger(port) || port < 1024 || port > 65535)) fail('--port must be a fixed port from 1024 through 65535');
69
+ const target = auto ? null : parseTarget(parsed['--target']);
62
70
  const lanPort = parsed['--lan-port'] === undefined ? null : Number(parsed['--lan-port']);
63
- validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
71
+ if (!auto) validateTopology({ port, target, lanPort, verifyCmd: parsed['--verify-cmd'] });
64
72
  const workers = [];
65
73
  for (let i = 0; i < argv.length; i++) {
66
74
  if (argv[i] === '--worker') workers.push(argv[++i]);
@@ -71,10 +79,11 @@ function parseOptions(argv, env) {
71
79
  }
72
80
  if (new Set(workers).size !== workers.length) fail('--worker names must be unique');
73
81
  if (parsed['--verify-cmd']?.length > 4096) fail('--verify-cmd is too long');
74
- const gozarBin = parsed['--gozar-bin'];
75
- if (gozarBin !== undefined && (!gozarBin || gozarBin.startsWith('-'))) fail('--gozar-bin must name a command');
76
- return { home, origin, port, target, lanPort, enableWorkspace: parsed['--enable-workspace'] === true, enableT3: parsed['--enable-t3'] === true, workers, verifyCmd: parsed['--verify-cmd'] ?? null,
77
- gozarBin, writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
82
+ const route = parsed['--route'];
83
+ if (route !== undefined && (!route || route.startsWith('-'))) fail('--route must name a Gozar route');
84
+ 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,
85
+ route, yes: parsed['--yes'] === true, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
86
+ writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
78
87
  }
79
88
 
80
89
  function assertRealDirectoryPath(target, { owner = false } = {}) {
@@ -103,9 +112,26 @@ function nodePath(execPath) {
103
112
  return execPath;
104
113
  }
105
114
 
115
+ function readReceipt(home) {
116
+ const file = path.join(defaultPath(home, '.config/dot-bridge'), 'service-install.json');
117
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
118
+ }
119
+
120
+ function firstFreePort(start) {
121
+ return new Promise((resolve, reject) => {
122
+ const attempt = port => {
123
+ if (port > 65535) return reject(new Error('no free port from 8789 upward'));
124
+ const probe = net.createServer();
125
+ probe.once('error', () => attempt(port + 1));
126
+ probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(port)));
127
+ };
128
+ attempt(start);
129
+ });
130
+ }
131
+
106
132
  function unitName(home) { return `dalan-${createHash('sha256').update(home).digest('hex').slice(0, 10)}`; }
107
133
 
108
- function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null } = {}) {
134
+ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), proxy = null, recover = true } = {}) {
109
135
  const name = unitName(home);
110
136
  for (const [label, value] of [['home', home], ['repo', repo], ['node', node]]) {
111
137
  if (!SAFE_PATH.test(value)) fail(`${label} contains characters that cannot be written safely in a systemd unit`);
@@ -114,6 +140,7 @@ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), pr
114
140
  [`${name}.service`]: [
115
141
  '[Unit]', 'Description=Dalan worker bridge', 'After=network-online.target', '', '[Service]',
116
142
  `WorkingDirectory=${repo}`, `ExecStart=${node} ${path.join(repo, 'src/server.mjs')}`,
143
+ ...(recover ? [`ExecStartPre=${node} ${path.join(repo, 'bin/dalan.mjs')} service recover --home ${home} --quiet`] : []),
117
144
  `Environment=HOME=${home}`, 'Environment=NODE_ENV=production', 'Environment=DALAN_AUTH_MODE=builtin',
118
145
  'Environment=DALAN_BIND_HOST=127.0.0.1', 'Environment=DALAN_GOZAR_SERVICE=1', 'Environment=DALAN_CATALOG_PROFILE=stable',
119
146
  `Environment=DALAN_ENABLE_WORKSPACE=${o.enableWorkspace ? '1' : '0'}`, `Environment=DALAN_ENABLE_T3_TOOLS=${o.enableT3 ? '1' : '0'}`,
@@ -204,7 +231,7 @@ function checkHomeScope(home, configDir, o, workers) {
204
231
  if (!fs.existsSync(home)) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
205
232
  const rootEntries = fs.readdirSync(home);
206
233
  if (!rootEntries.length) return { receiptFile: path.join(configDir, 'service-install.json'), hasReceipt: false };
207
- const rootAllowed = ['.config', '.local', '.tmp', 'resource-url'];
234
+ 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'];
208
235
  if (rootEntries.some(name => !rootAllowed.includes(name))) fail(`${home} contains unrelated data; use a fresh home or one created by dalan service migrate-workers`);
209
236
  if (!rootEntries.includes('.config')) fail(`${home} has no Dalan config directory; refusing to adopt it`);
210
237
  const configRoot = path.join(home, '.config');
@@ -221,6 +248,7 @@ function checkHomeScope(home, configDir, o, workers) {
221
248
  const receiptFile = path.join(configDir, 'service-install.json');
222
249
  const entries = fs.readdirSync(configDir);
223
250
  const hasReceipt = entries.includes('service-install.json');
251
+ if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url', 'logs'].includes(name))) fail(`${home} contains update data without a service receipt`);
224
252
  if (hasReceipt) {
225
253
  const info = fs.lstatSync(receiptFile);
226
254
  if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
@@ -337,61 +365,163 @@ function assertGozarStatePath(env) {
337
365
 
338
366
  export async function installService(o, seams = {}) {
339
367
  const env = seams.env ?? process.env;
340
- if ((seams.platform ?? process.platform) !== 'linux') fail('dalan service install currently requires Linux with a systemd user manager');
341
- if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute systemd-safe path');
368
+ const platform = seams.platform ?? process.platform;
369
+ if (!['linux', 'darwin'].includes(platform)) fail('dalan service install needs Linux with a systemd user manager or macOS with launchd');
370
+ const mac = platform === 'darwin';
371
+ if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute service-safe path');
372
+ assertRealDirectoryPath(path.dirname(o.home), { owner: true });
373
+ assertRealDirectoryPath(o.home, { owner: true });
374
+ let gozar = null;
375
+ if (o.auto) {
376
+ // The one-command install: reuse the port and address a previous run recorded, or pick a free port and ask Gozar for the address.
377
+ const prior = readReceipt(o.home);
378
+ if (prior?.origin && prior.port) o = { ...o, origin: prior.origin, port: prior.port, target: parseTarget(prior.target) };
379
+ else {
380
+ const port = await (seams.freePort ?? firstFreePort)(8789);
381
+ gozar = seams.gozar ?? await resolveGozar();
382
+ const wanted = buildQuery({ home: gozarHomeFor(env), target: `127.0.0.1:${port}`, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, address: 'stable' });
383
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
384
+ 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.')) });
385
+ o = { ...o, origin: parseOrigin(view.origin), port, target: parseTarget(`127.0.0.1:${port}`) };
386
+ }
387
+ }
342
388
  const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
343
389
  o = { ...o, target };
344
390
  validateTopology(o);
345
- assertRealDirectoryPath(path.dirname(o.home), { owner: true });
346
- assertRealDirectoryPath(o.home, { owner: true });
347
391
  const profile = profileFor(o.home, o.workers ?? []);
348
392
  assertRealDirectoryPath(path.dirname(profile.file));
349
- 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');
393
+ 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');
350
394
  assertRealDirectoryPath(unitDir, { owner: true });
351
395
  const configDir = path.dirname(profile.file);
352
396
  const homeScope = checkHomeScope(o.home, configDir, o, profile.workers);
397
+ 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)');
353
398
  const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
354
- const { files, enable, name } = unitFiles(o, { home: o.home, repo: seams.repo ?? REPO, node: seams.node ?? nodePath(process.execPath), proxy });
399
+ const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
400
+ const receiptFile = homeScope.receiptFile;
401
+ const previous = homeScope.hasReceipt ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;
402
+ const autoUpdate = o.autoUpdate ?? previous?.auto_update ?? !homeScope.hasReceipt;
403
+ const current = path.join(o.home, 'current');
404
+ const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
405
+ if (hasCurrent && !fs.lstatSync(current).isSymbolicLink()) fail(`${current} must be the service package symlink`);
406
+ const name = unitName(o.home), labels = launchdLabels(name);
407
+ let files, enable = [];
408
+ if (mac) files = { [`${labels.service}.plist`]: servicePlist({ unit: name, node, home: o.home, port: o.port, enableWorkspace: o.enableWorkspace, enableT3: o.enableT3 }) };
409
+ else {
410
+ ({ files, enable } = unitFiles(o, { home: o.home, repo: current, node, proxy }));
411
+ Object.assign(files, autoUpdateUnits({ home: o.home, unit: name, node }).files);
412
+ }
413
+ let replaceLegacyUnit = false;
355
414
  // Check every collision before creating the bridge home or the first unit file.
356
- for (const [filename, text] of Object.entries(files)) {
415
+ for (const [filename, text] of mac ? [] : Object.entries(files)) {
357
416
  const file = path.join(unitDir, filename);
358
- if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) fail(`${file} already exists with different contents; refusing to overwrite it`);
417
+ if (fs.existsSync(file) && (!fs.lstatSync(file).isFile() || fs.readFileSync(file, 'utf8') !== text)) {
418
+ const actual = fs.lstatSync(file).isFile() ? fs.readFileSync(file, 'utf8') : '';
419
+ const oldRepo = actual.match(/^WorkingDirectory=(.+)$/m)?.[1];
420
+ const oldNode = actual.match(/^ExecStart=(\S+) /m)?.[1];
421
+ const expected = filename === `${name}.service` && previous && oldRepo && oldNode && SAFE_PATH.test(oldRepo) && SAFE_PATH.test(oldNode)
422
+ ? unitFiles(o, { home: o.home, repo: oldRepo, node: oldNode, proxy, recover: false }).files[filename] : null;
423
+ // Only the exact former generated unit can be enrolled or retried after interruption.
424
+ if (expected && actual === expected) replaceLegacyUnit = true;
425
+ else fail(`${file} already exists with different contents; refusing to overwrite it`);
426
+ }
359
427
  }
360
428
  if (o.writeUnitsOnly) {
361
- writeUnits(unitDir, files);
362
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), target: o.target.value, started: false, route: null };
429
+ if (replaceLegacyUnit) fail('rerun without --write-units-only to enroll an existing service for updates');
430
+ if (mac) for (const [filename, text] of Object.entries(files)) writeAgentFile(path.join(unitDir, filename), text); else writeUnits(unitDir, files);
431
+ 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 };
363
432
  }
364
- // An explicit --gozar-bin wins; otherwise the bundled Gozar, GOZAR_BIN, then PATH.
365
- const gozar = o.gozarBin !== undefined ? { binary: o.gozarBin, args: [] }
366
- : resolveGozarCommand({ env, resolveBundled: seams.resolveBundled, which: seams.which });
367
- 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.');
433
+ gozar ??= seams.gozar ?? await resolveGozar();
368
434
  assertGozarStatePath(env);
435
+ const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
369
436
  const spawn = seams.spawn ?? spawnSync;
370
- runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
437
+ if (!mac) runCommand('systemctl', ['--user', 'show-environment'], { env, spawn });
371
438
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
372
- if (!homeScope.hasReceipt) writePrivate(homeScope.receiptFile, `${JSON.stringify(installReceipt(o.home, configDir, o, profile.workers), null, 2)}\n`);
439
+ 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 }, null, 2)}\n`);
440
+ if (!hasCurrent) fs.symlinkSync(repo, current);
373
441
  const homeFiles = prepareHome(o, profile);
374
- writeUnits(unitDir, files);
375
- runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
376
- runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
442
+ if (needsEnrollmentRestart) {
443
+ writeAtomic(receiptFile, `${JSON.stringify({ ...previous, repo: previous.repo ?? repo, node, unit_dir: unitDir, auto_update: autoUpdate, enrollment_pending: true }, null, 2)}\n`);
444
+ }
445
+ if (replaceLegacyUnit) {
446
+ const file = path.join(unitDir, `${name}.service`), mode = fs.statSync(file).mode & 0o777;
447
+ writeAtomic(file, files[`${name}.service`]);
448
+ fs.chmodSync(file, mode);
449
+ }
450
+ if (mac) {
451
+ fs.mkdirSync(path.join(o.home, 'logs'), { recursive: true, mode: 0o700 });
452
+ const plistFile = path.join(unitDir, `${labels.service}.plist`);
453
+ const changed = writeAgentFile(plistFile, files[`${labels.service}.plist`]);
454
+ if (lintPlist(plistFile, seams) === false) fail(`${plistFile} is not a valid property list`);
455
+ if (changed) unloadAgent({ label: labels.service }, seams.launchd);
456
+ loadAgent({ label: labels.service, plistFile }, seams.launchd);
457
+ } else {
458
+ writeUnits(unitDir, files);
459
+ runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn });
460
+ runCommand('systemctl', ['--user', 'enable', '--now', ...enable], { env, spawn });
461
+ if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
462
+ }
377
463
  const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
378
464
  const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
379
- if (!ready) fail(`Dalan did not start on its admin socket; the unit and home remain for inspection: systemctl --user status ${name}.service`);
380
- const gozarArgs = ['service', 'add', '--origin', o.origin, '--target', o.target.value];
381
- if (o.verifyCmd) gozarArgs.push('--verify-cmd', o.verifyCmd);
382
- gozarArgs.push('--json');
383
- const output = runCommand(gozar.binary, [...gozar.args, ...gozarArgs], { env, spawn, timeout: 120000 });
465
+ 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`}`);
466
+ const gozarHome = gozarHomeFor(env);
384
467
  let routeReply;
385
- try { routeReply = JSON.parse(output); } catch { fail('Gozar returned invalid JSON for service add; the bridge is running but its route is unverified'); }
386
- if (routeReply?.schemaVersion !== 1 || routeReply?.route?.origin !== o.origin || routeReply?.route?.target !== o.target.value) {
387
- fail('Gozar returned a service route that does not match the requested origin and target; the bridge is running but its route is unverified');
468
+ if (o.route !== undefined) {
469
+ // A named Gozar route: Gozar allocates or adopts it and pins the origin; nothing here interprets the name.
470
+ const wanted = buildQuery({ home: gozarHome, target: o.target.value, usage: { kind: 'durable', routeId: 'dalan-main' }, route: o.route, origin: o.origin, address: 'stable' });
471
+ const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
472
+ 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.')) });
473
+ if (view.origin !== o.origin) fail(`Gozar pinned ${view.origin}, not the requested ${o.origin}; the bridge is running but its route needs repair`);
474
+ routeReply = view;
475
+ } else {
476
+ routeReply = (await registerExternalService({ gozar, home: gozarHome, origin: o.origin, target: o.target.value, ...(o.verifyCmd ? { verifyCmd: o.verifyCmd } : {}) })).route;
388
477
  }
389
- if (routeReply.route.verification?.status !== 'verified') {
390
- fail(`Gozar did not verify the service route; the bridge is running and the service route needs repair: ${JSON.stringify(routeReply).slice(0, 1500)}`);
478
+ 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)}`);
479
+ { 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`); }
480
+ await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn, platform });
481
+ if (!env.DALAN_HOME) recordDefaultHome(o.home, env);
482
+ if (needsEnrollmentRestart) {
483
+ const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
484
+ delete enrolled.enrollment_pending;
485
+ writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
391
486
  }
392
- return { schema_version: 1, home: o.home, unit: `${name}.service`, units: Object.keys(files), port: o.port,
487
+ 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,
393
488
  workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
394
- target: o.target.value, started: true, route: routeReply.route };
489
+ target: o.target.value, started: true, route: routeReply, auto_update: autoUpdate };
490
+ }
491
+
492
+ // Stop the service and its update job, delete the generated definitions and the public route, and forget the default home.
493
+ // The home itself (secrets, grants, data) stays; delete it by hand if you also want that gone.
494
+ export async function uninstallService({ home }, seams = {}) {
495
+ const env = seams.env ?? process.env, platform = seams.platform ?? process.platform, mac = platform === 'darwin';
496
+ home = path.resolve(home);
497
+ const receipt = readReceipt(home);
498
+ if (!receipt?.unit || receipt.home !== home) fail(`no Dalan service is installed for ${home}`);
499
+ const removed = [];
500
+ const unitDir = receipt.unit_dir;
501
+ if (!unitDir || !path.isAbsolute(unitDir)) fail('the service receipt names no unit directory');
502
+ if (receipt.auto_update) { try { await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform }); removed.push('automatic updates off'); } catch (error) { removed.push(`update job not removed: ${error.message}`); } }
503
+ if (mac) removed.push(...removeAgents({ unit: receipt.unit, unit_dir: unitDir }, seams.launchd));
504
+ else {
505
+ const spawn = seams.spawn ?? spawnSync, name = receipt.unit;
506
+ const units = [`${name}.service`, `${name}-target.socket`, `${name}-target.service`, `${name}-update.service`, `${name}-update.timer`].filter(unit => fs.existsSync(path.join(unitDir, unit)));
507
+ if (units.length) { spawn('systemctl', ['--user', 'disable', '--now', ...units], { encoding: 'utf8', env }); }
508
+ for (const unit of units) { fs.rmSync(path.join(unitDir, unit)); removed.push(`removed ${path.join(unitDir, unit)}`); }
509
+ spawn('systemctl', ['--user', 'daemon-reload'], { encoding: 'utf8', env });
510
+ }
511
+ if (receipt.route_handle) {
512
+ try {
513
+ const gozar = seams.gozar ?? await resolveGozar();
514
+ const closed = await gozar.closeRoute({ home: gozarHomeFor(env), handle: receipt.route_handle, mode: 'remove' });
515
+ removed.push(`public route ${closed.state}`);
516
+ } catch (error) { removed.push(`public route not removed: ${explainRouteError(error).line}`); }
517
+ }
518
+ forgetDefaultHome(home, env);
519
+ // 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.
520
+ const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 12);
521
+ let aside = `${home}.removed-${stamp}`;
522
+ for (let n = 2; fs.existsSync(aside); n++) aside = `${home}.removed-${stamp}-${n}`;
523
+ fs.renameSync(home, aside);
524
+ return { home, removed, kept: `${aside} (secrets and data, moved aside; delete it yourself to remove them)`, moved_to: aside };
395
525
  }
396
526
 
397
527
  export async function serviceMain(argv, seams = {}) {
@@ -400,22 +530,75 @@ export async function serviceMain(argv, seams = {}) {
400
530
  const { migrationMain } = await import('./service-migrate-workers.mjs');
401
531
  return migrationMain(args);
402
532
  }
533
+ if (action === 'recover') {
534
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--quiet', '--help'] });
535
+ if (parsed['--help']) return serviceMain(['help'], seams);
536
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
537
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
538
+ const { recoverService } = await import('./service-update.mjs');
539
+ const result = recoverService({ home });
540
+ if (!parsed['--quiet']) (seams.out ?? console.log)(JSON.stringify(result));
541
+ return result;
542
+ }
543
+ if (['update', 'status', 'auto-update'].includes(action)) {
544
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--check', '--yes', '--retry', '--json', '--help'] });
545
+ if (parsed['--help']) return serviceMain(['help'], seams);
546
+ const home = path.resolve(parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env));
547
+ let result;
548
+ if (action === 'auto-update') {
549
+ 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]');
550
+ result = await setAutoUpdate({ home, enabled: parsed._[0] === 'on' }, seams);
551
+ } else {
552
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
553
+ if (parsed['--check'] && parsed['--retry']) fail('--check cannot be used with --retry');
554
+ if (parsed['--check'] && parsed['--yes']) fail('--check cannot be used with --yes');
555
+ if (action === 'status' && (parsed['--check'] || parsed['--yes'] || parsed['--retry'])) fail('service status does not accept --check, --yes or --retry');
556
+ const updater = await import('./service-update.mjs');
557
+ result = await updater[action === 'status' ? 'serviceStatus' : 'updateService']({ home, check: !!parsed['--check'], yes: !!parsed['--yes'], retry: !!parsed['--retry'] }, seams);
558
+ }
559
+ (seams.out ?? console.log)(parsed['--json'] ? JSON.stringify(result) : JSON.stringify(result, null, 2));
560
+ return result;
561
+ }
403
562
  if (action === 'help' || action === '--help' || !action) {
404
- (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] [--write-units-only]\n dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]');
563
+ (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.');
405
564
  return null;
406
565
  }
407
- if (action !== 'install') fail('use dalan service install or dalan service migrate-workers');
566
+ if (action === 'uninstall') {
567
+ const parsed = parseArgs(args, { values: ['--home'], flags: ['--json', '--help'] });
568
+ if (parsed['--help']) return serviceMain(['help'], seams);
569
+ if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
570
+ const result = await uninstallService({ home: parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env) }, seams);
571
+ const out = seams.out ?? console.log;
572
+ if (parsed['--json']) out(JSON.stringify(result)); else { for (const line of result.removed) out(line); out(`Kept: ${result.kept}`); }
573
+ return result;
574
+ }
575
+ if (action !== 'install') fail('use dalan service install, uninstall, update, auto-update, status, recover or migrate-workers');
408
576
  const o = parseOptions(args, seams.env ?? process.env);
409
577
  if (o.help) return serviceMain(['help'], seams);
410
- const result = await installService(o, seams);
578
+ const out0 = seams.out ?? console.log;
579
+ // Gozar describes the route it would open; the owner approves it once (the answer is kept with the route). `--yes` approves what was printed.
580
+ const consent = seams.consent ?? (async candidate => {
581
+ out0(describeCandidate(candidate).join('\n')); out0(describeDisclosure(candidate).join('\n'));
582
+ if (o.yes) return true;
583
+ if (!process.stdin.isTTY) { out0('Run this in a terminal to approve the route, or add --yes after reading the description above.'); return false; }
584
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
585
+ try { return /^y(es)?$/i.test((await rl.question('Use this route? [y/N] ')).trim()); } finally { rl.close(); }
586
+ });
587
+ const result = await installService(o, { ...seams, consent });
411
588
  if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
412
589
  else {
413
- (seams.out ?? console.log)(`Service: ${result.unit} (${result.started ? 'active' : 'unit files written'})`);
414
- (seams.out ?? console.log)(`Home: ${result.home}`);
415
- (seams.out ?? console.log)(`Public MCP URL: ${result.public_url ?? `${o.origin}/<secret>/mcp`}`);
416
- (seams.out ?? console.log)(`Private URL file: ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
417
- (seams.out ?? console.log)(`Gozar target: ${result.target}`);
418
- if (result.route) (seams.out ?? console.log)(`Gozar route: ${result.route.verification.status}`);
590
+ const out = seams.out ?? console.log;
591
+ out(`Service: ${result.unit} (${result.started ? (result.already_installed ? 'already installed, running' : 'running') : 'files written'})`);
592
+ out(`Home: ${result.home}`);
593
+ out(`Public address: ${result.origin ?? o.origin ?? result.public_url}`);
594
+ out(`Connector URL (keep private): in ${result.resource_url_file ?? path.join(result.home, 'resource-url')}`);
595
+ if (result.route) out(`Route: ${result.route.verification?.status ?? 'unknown'}`);
596
+ if (result.started) {
597
+ out(`Updates: ${result.auto_update ? 'automatic, once a day' : 'off; run dalan service update'}`);
598
+ const worker = result.workers?.[0] ?? 'WORKER';
599
+ out(`Next: dalan connect start --worker ${worker}`);
600
+ out('Check: dalan doctor --auth');
601
+ }
419
602
  }
420
603
  return result;
421
604
  }
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
  }