@tnunamak/dalan 0.8.0 → 0.8.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.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/service.mjs CHANGED
@@ -7,12 +7,16 @@ 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
+ import { adminSocketPath } from './admin-socket.mjs';
11
11
  import { initAsFiles, writeAtomic } from './as-files.mjs';
12
12
  import { parseWorkers } from './workers.mjs';
13
13
  import { loadCapacity } from './projects.mjs';
14
14
  import { parseArgs } from '../scripts/live-trial/common.mjs';
15
- import { buildQuery, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, registerExternalService, resolveGozar, resolveRouteWord } from './gozar-routes.mjs';
15
+ import { buildQuery, closeExactRoute, ensureDurableRoute, explainRouteError, describeCandidate, describeDisclosure, gozarHomeFor, isPublished, requireExternalRoute, resolveGozar, resolveRouteWord, observeRetainedRoute, routeFailure, routeNotDispatched } from './gozar-routes.mjs';
16
+ import { routeCustodyPath } from './route-custody.mjs';
17
+ import { muteableTerminal, runRouteSetup } from './route-setup.mjs';
18
+ import { readRouteSetting } from './route-setting.mjs';
19
+ import { acquirePrivateLock } from './service-update-lock.mjs';
16
20
  import { autoUpdateUnits, setAutoUpdate } from './service-auto-update.mjs';
17
21
  import { serviceHomeFor, readDefaultHome, recordDefaultHome, forgetDefaultHome, DEFAULT_SERVICE_HOME } from './default-home.mjs';
18
22
  import { launchdLabels, launchAgentsDir, servicePlist, updatePlist, preflightAgentFile, writeAgentFile, loadAgent, unloadAgent, removeAgents, lintPlist, isLoaded } from './service-launchd.mjs';
@@ -54,7 +58,7 @@ function validateTopology({ port, target, lanPort = null, verifyCmd }) {
54
58
  function parseOptions(argv, env) {
55
59
  const parsed = parseArgs(argv, {
56
60
  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'],
61
+ flags: ['--write-units-only', '--enable-workspace', '--enable-t3', '--auto-update', '--no-auto-update', '--json', '--help'],
58
62
  });
59
63
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
60
64
  if (parsed['--help']) return { help: true };
@@ -63,7 +67,6 @@ function parseOptions(argv, env) {
63
67
  if (!SAFE_PATH.test(home)) fail('--home contains characters that cannot be written safely in a service definition');
64
68
  // `--route NAME` alone is the one-command install: Gozar supplies the public address and Dalan picks a loopback port.
65
69
  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
70
  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
71
  const origin = auto ? null : parseOrigin(parsed['--public-url']);
69
72
  const port = auto ? null : Number(parsed['--port']);
@@ -84,7 +87,7 @@ function parseOptions(argv, env) {
84
87
  const route = parsed['--route'];
85
88
  if (route !== undefined && (!route || route.startsWith('-'))) fail('--route must name a Gozar route');
86
89
  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,
90
+ route, autoUpdate: parsed['--auto-update'] ? true : parsed['--no-auto-update'] ? false : undefined,
88
91
  writeUnitsOnly: parsed['--write-units-only'] === true, json: parsed['--json'] === true };
89
92
  }
90
93
 
@@ -114,9 +117,46 @@ function nodePath(execPath) {
114
117
  return execPath;
115
118
  }
116
119
 
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
+ function pendingInstallPath(env, home) {
121
+ const config = env.XDG_CONFIG_HOME || path.join(env.HOME ?? os.homedir(), '.config');
122
+ return path.join(config, 'dalan', 'route-installs', createHash('sha256').update(home).digest('hex') + '.json');
123
+ }
124
+
125
+ function readPendingInstall(file) {
126
+ let value;
127
+ try { value = JSON.parse(fs.readFileSync(file, 'utf8')); }
128
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
129
+ if (typeof value?.home !== 'string' || !path.isAbsolute(value.home) || typeof value.operationId !== 'string' ||
130
+ !Number.isInteger(value.port) || value.port < 1024 || value.port > 65535) fail('The pending service route reference is invalid.');
131
+ return value;
132
+ }
133
+
134
+ async function withRouteInstallLock(env, home, action) {
135
+ const file = pendingInstallPath(env, home);
136
+ fs.mkdirSync(path.dirname(file), { mode: 0o700, recursive: true });
137
+ const unlock = acquirePrivateLock(file + '.lock.sqlite', 'another service install or uninstall is already running');
138
+ try { return await action(); } finally { unlock(); }
139
+ }
140
+
141
+ function readReceipt(home, file = defaultPath(home, '.config/dot-bridge', 'service-install.json')) {
142
+ assertRealDirectoryPath(path.dirname(file));
143
+ let fd;
144
+ try { fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); }
145
+ catch (error) {
146
+ if (error.code === 'ENOENT') return null;
147
+ if (error.code === 'ELOOP') fail(`${file} must be a private regular file`);
148
+ fail(`service receipt is missing or invalid: ${file}`);
149
+ }
150
+ try {
151
+ const stat = fs.fstatSync(fd);
152
+ const owned = typeof process.getuid !== 'function' || stat.uid === process.getuid();
153
+ if (!stat.isFile() || !owned || (stat.mode & 0o777) !== 0o600) fail(`${file} must be a private regular file`);
154
+ let value;
155
+ try { value = JSON.parse(fs.readFileSync(fd, 'utf8')); }
156
+ catch { fail(`service receipt is missing or invalid: ${file}`); }
157
+ if (!value || value.schema_version !== 1 || value.home !== home || !value.unit) fail(`${file} has an unsupported service receipt`);
158
+ return value;
159
+ } finally { fs.closeSync(fd); }
120
160
  }
121
161
 
122
162
  function firstFreePort(start) {
@@ -160,7 +200,11 @@ function unitFiles(o, { home, repo = REPO, node = nodePath(process.execPath), pr
160
200
  `ListenStream=${o.target.host}:${o.target.port}`, 'FreeBind=true', '', '[Install]', 'WantedBy=sockets.target', '',
161
201
  ].join('\n');
162
202
  base[`${name}-target.service`] = [
163
- '[Unit]', 'Description=Forward Gozar target to the Dalan bridge', `Requires=${name}.service`, `After=${name}.service`, '', '[Service]',
203
+ // PartOf stops this proxy with the bridge but never starts the bridge (Requires would start the old one in the middle of a
204
+ // deploy). The socket unit stays bound while the bridge restarts; a call that arrives meanwhile activates this unit, which waits
205
+ // for the bridge port, so the caller waits instead of getting a 502.
206
+ '[Unit]', 'Description=Forward Gozar target to the Dalan bridge', `After=${name}.service`, `PartOf=${name}.service`, '', '[Service]',
207
+ `ExecStartPre=/usr/bin/timeout 170 /bin/bash -c 'until exec 3<>/dev/tcp/127.0.0.1/${o.port}; do sleep 0.5; done'`, 'TimeoutStartSec=180',
164
208
  `ExecStart=${proxy} 127.0.0.1:${o.port}`, 'Restart=on-failure', '',
165
209
  ].join('\n');
166
210
  enable.push(`${name}-target.socket`);
@@ -248,7 +292,7 @@ function checkHomeScope(home, configDir, o, workers) {
248
292
  const configInfo = fs.lstatSync(configDir);
249
293
  if (configInfo.isSymbolicLink() || !configInfo.isDirectory()) fail(`${configDir} must be a real directory`);
250
294
  const receiptFile = path.join(configDir, 'service-install.json');
251
- const entries = fs.readdirSync(configDir);
295
+ let entries = fs.readdirSync(configDir);
252
296
  if (entries.includes('limits.json')) {
253
297
  const file = path.join(configDir, 'limits.json'), info = fs.lstatSync(file);
254
298
  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`);
@@ -257,19 +301,19 @@ function checkHomeScope(home, configDir, o, workers) {
257
301
  const hasReceipt = entries.includes('service-install.json');
258
302
  if (!hasReceipt && rootEntries.some(name => !['.config', '.local', '.tmp', 'resource-url', 'logs'].includes(name))) fail(`${home} contains update data without a service receipt`);
259
303
  if (hasReceipt) {
260
- const info = fs.lstatSync(receiptFile);
261
- if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) fail(`${receiptFile} must be a private regular file`);
262
- let existing;
263
- try { existing = JSON.parse(fs.readFileSync(receiptFile, 'utf8')); } catch { fail(`${receiptFile} is not valid JSON`); }
304
+ const existing = readReceipt(home, receiptFile);
305
+ if (!existing) fail(`service receipt changed during install preflight: ${receiptFile}`);
264
306
  const wanted = installReceipt(home, configDir, o, workers);
265
307
  for (const field of ['schema_version', 'home', 'origin', 'port', 'target', 'enable_workspace', 'enable_t3', 'unit', 'workers']) {
266
308
  if (JSON.stringify(existing[field]) !== JSON.stringify(wanted[field])) fail(`${receiptFile} belongs to a different service configuration (${field}); refusing to change it`);
267
309
  }
268
310
  if (rootEntries.includes('.tmp')) validateWorkspaceRuntime(home);
269
311
  if (rootEntries.includes('.local')) assertRealDirectoryPath(defaultPath(home, '.local/share/dot-bridge'));
270
- return { receiptFile, hasReceipt };
312
+ return { receiptFile, hasReceipt, receipt: existing };
271
313
  }
272
314
  if (rootEntries.includes('.local') || rootEntries.includes('.tmp') || rootEntries.includes('resource-url')) fail(`${home} already contains bridge data; use a fresh home or one created by dalan service migrate-workers`);
315
+ // A crash between staging and publishing a receipt leaves service-install.json.<hex>.tmp; it is ours and never adopted.
316
+ entries = entries.filter(name => !/^service-install\.json\.[0-9a-f]{16}\.tmp$/.test(name));
273
317
  for (const name of entries) {
274
318
  if (POLICY_HOME_FILES.has(name) || hasReceipt && name === 'service-install.json') continue;
275
319
  fail(`${configDir}/${name} is outside a fresh or migrated policy-only home; refusing to adopt it`);
@@ -290,6 +334,34 @@ function writePrivate(file, text) {
290
334
  }
291
335
  }
292
336
 
337
+ // The strict receipt reader requires exactly 0600. Set it on the staged inode
338
+ // before publishing, even when the inherited umask masks owner bits.
339
+ function writeServiceReceipt(file, text, create = false) {
340
+ const temp = `${file}.${randomBytes(8).toString('hex')}.tmp`;
341
+ const fd = fs.openSync(temp, 'wx', 0o600);
342
+ try {
343
+ try {
344
+ fs.fchmodSync(fd, 0o600);
345
+ fs.writeFileSync(fd, text);
346
+ fs.fsyncSync(fd);
347
+ } finally {
348
+ fs.closeSync(fd);
349
+ }
350
+ if (create) {
351
+ // Preserve first-install exclusive creation: do not replace an existing receipt.
352
+ try { fs.linkSync(temp, file); }
353
+ catch (error) {
354
+ if (error.code !== 'EEXIST') throw error;
355
+ writePrivate(file, text);
356
+ }
357
+ } else {
358
+ fs.renameSync(temp, file);
359
+ }
360
+ } finally {
361
+ fs.rmSync(temp, { force: true });
362
+ }
363
+ }
364
+
293
365
  function prepareHome(o, profile) {
294
366
  fs.mkdirSync(o.home, { recursive: true, mode: 0o700 });
295
367
  fs.chmodSync(o.home, 0o700);
@@ -304,7 +376,6 @@ function prepareHome(o, profile) {
304
376
  const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})\n?$/.exec(envText)?.[1];
305
377
  if (!envInfo.isFile() || envInfo.isSymbolicLink() || (envInfo.mode & 0o777) !== 0o600 || !secret) fail(`${envFile} is not a private bridge secret file`);
306
378
  const resourceFile = path.join(o.home, 'resource-url');
307
- writePrivate(resourceFile, `${o.origin}/${secret}/mcp\n`);
308
379
  return { config, resourceFile, secret };
309
380
  }
310
381
 
@@ -327,12 +398,12 @@ function runCommand(command, args, { env, spawn = spawnSync, timeout = 30000 } =
327
398
  return result.stdout ?? '';
328
399
  }
329
400
 
330
- function socketIsReady(socketPath, timeoutMs = 30000) {
401
+ export function socketIsReady(socketPath, timeoutMs = 30000) {
331
402
  return new Promise(resolve => {
332
- const started = Date.now();
403
+ const started = performance.now();
333
404
  const attempt = () => {
334
405
  const probe = net.connect(socketPath);
335
- const done = ready => { probe.destroy(); if (ready) resolve(true); else if (Date.now() - started >= timeoutMs) resolve(false); else setTimeout(attempt, 200); };
406
+ const done = ready => { probe.destroy(); if (ready) resolve(true); else if (performance.now() - started >= timeoutMs) resolve(false); else setTimeout(attempt, 200); };
336
407
  probe.once('connect', () => done(true));
337
408
  probe.once('error', () => done(false));
338
409
  probe.setTimeout(1000, () => done(false));
@@ -371,26 +442,33 @@ function assertGozarStatePath(env) {
371
442
  }
372
443
 
373
444
  export async function installService(o, seams = {}) {
445
+ const env = seams.env ?? process.env;
446
+ if (!path.isAbsolute(o.home) || !SAFE_PATH.test(o.home)) fail('--home must be an absolute service-safe path');
447
+ return o.writeUnitsOnly ? installServiceLocked(o, seams) : withRouteInstallLock(env, o.home, () => installServiceLocked(o, seams));
448
+ }
449
+
450
+ async function installServiceLocked(o, seams) {
374
451
  const env = seams.env ?? process.env;
375
452
  const platform = seams.platform ?? process.platform;
376
453
  if (!['linux', 'darwin'].includes(platform)) fail('dalan service install needs Linux with a systemd user manager or macOS with launchd');
377
454
  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
455
  assertRealDirectoryPath(path.dirname(o.home), { owner: true });
380
456
  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;
457
+ // A public route is allocated after the preflight checks pass. Later writes or startup can still fail.
458
+ const saved = o.auto && o.route === undefined ? readRouteSetting(env) : null;
459
+ const gozarHome = saved?.gozarHome ?? gozarHomeFor(env);
460
+ const external = !o.auto;
461
+ const pendingPath = pendingInstallPath(env, o.home);
462
+ const persisted = o.auto ? readReceipt(o.home) : null;
463
+ let pending = readPendingInstall(pendingPath);
464
+ let gozar, allocated, allocate = false;
387
465
  if (o.auto) {
388
466
  // The one-command install: reuse the port and address a previous run recorded, or pick a free port now and ask Gozar for
389
467
  // the address once every check has passed.
390
- const prior = readReceipt(o.home);
468
+ const prior = persisted;
391
469
  if (prior?.origin && prior.port) o = { ...o, origin: prior.origin, port: prior.port, target: parseTarget(prior.target) };
392
470
  else {
393
- const port = await (seams.freePort ?? firstFreePort)(8789);
471
+ const port = pending?.port ?? await (seams.freePort ?? firstFreePort)(8789);
394
472
  o = { ...o, origin: null, port, target: parseTarget(`127.0.0.1:${port}`) };
395
473
  allocate = true;
396
474
  }
@@ -398,6 +476,9 @@ export async function installService(o, seams = {}) {
398
476
  const target = parseTarget(typeof o.target === 'string' ? o.target : `${o.target?.host}:${o.target?.port}`);
399
477
  o = { ...o, target };
400
478
  validateTopology(o);
479
+ if (external && !o.writeUnitsOnly && o.target.port !== o.port) {
480
+ fail('Route proof requires the target and Dalan listener to use the same port. A custom verification command cannot publish the address.');
481
+ }
401
482
  const profile = profileFor(o.home, o.workers ?? []);
402
483
  assertRealDirectoryPath(path.dirname(profile.file));
403
484
  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');
@@ -408,7 +489,7 @@ export async function installService(o, seams = {}) {
408
489
  const proxy = o.target.host === '127.0.0.1' && o.target.port === o.port ? null : (seams.proxy ?? findProxy());
409
490
  const repo = seams.repo ?? REPO, node = seams.node ?? nodePath(process.execPath);
410
491
  const receiptFile = homeScope.receiptFile;
411
- const previous = homeScope.hasReceipt ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;
492
+ const previous = homeScope.receipt ?? null;
412
493
  const autoUpdate = o.autoUpdate ?? previous?.auto_update ?? !homeScope.hasReceipt;
413
494
  const current = path.join(o.home, 'current');
414
495
  const hasCurrent = fs.existsSync(current) || (() => { try { fs.lstatSync(current); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } })();
@@ -449,30 +530,54 @@ export async function installService(o, seams = {}) {
449
530
  if (mac) for (const [filename, text] of Object.entries(files)) writeAgentFile(path.join(unitDir, filename), text); else writeUnits(unitDir, files);
450
531
  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 };
451
532
  }
452
- gozar ??= seams.gozar ?? await resolveGozar();
453
- assertGozarStatePath(env);
533
+ gozar = seams.gozar ?? await resolveGozar({ env, home: previous?.gozar_home ?? pending?.home ?? gozarHome, custody: previous?.route_custody });
534
+ assertGozarStatePath({ ...env, GOZAR_HOME: previous?.gozar_home ?? pending?.home ?? gozarHome });
454
535
  const needsEnrollmentRestart = replaceLegacyUnit || !!previous && (!previous.repo || previous.enrollment_pending === true);
455
536
  const spawn = seams.spawn ?? spawnSync;
456
537
  if (!mac) {
457
538
  try { runCommand('systemctl', ['--user', 'show-environment'], { env, spawn }); }
458
539
  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
540
  }
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' });
541
+ const routeHome = previous?.gozar_home ?? pending?.home ?? gozarHome;
542
+ const custody = previous?.route_custody ?? routeCustodyPath({ HOME: os.homedir(), ...env }, routeHome);
543
+ const consent = seams.consent ?? (async () => fail('A durable route needs your explicit approval in a terminal.'));
544
+ const setup = seams.setup && (candidate => seams.setup({ gozar, candidate, home: routeHome, env }));
545
+ const allocateRoute = async origin => {
546
+ const remember = ref => {
547
+ const next = { ...ref, port: o.port };
548
+ writeAtomic(pendingPath, JSON.stringify(next));
549
+ pending = next;
550
+ };
551
+ if (pending) {
552
+ const observed = await observeRetainedRoute(gozar, pending);
553
+ if (observed.state === 'recorded') {
554
+ const { view } = observed;
555
+ if (view.cleanup.state === 'confirmed') fail('The retained Gozar operation has been closed. Run dalan service uninstall for this home before starting a new install.');
556
+ if (view.hostConfiguration?.target?.known && view.hostConfiguration.target.value !== o.target.value) fail('The retained route targets a different local listener.');
557
+ if (view.operationId !== pending.operationId || !view.handle) fail('The retained Gozar view does not identify the original operation and handle.');
558
+ // Observation recovery needs the same durable pointer as dispatch delivery,
559
+ // before a receipt or service-start failure can split those two records.
560
+ remember({ home: pending.home, operationId: pending.operationId, handle: view.handle });
561
+ return view;
562
+ }
563
+ }
564
+ const wanted = buildQuery({ home: routeHome, target: o.target.value, usage: { kind: 'durable', routeId: saved?.routeId ?? 'dalan-main' },
565
+ route: o.route ?? saved?.routeName ?? undefined, origin, address: 'stable' });
463
566
  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.')) });
567
+ return ensureDurableRoute({ gozar, query, pick, consent, setup, remember, recovery: pending, external });
568
+ };
569
+ if (allocate) {
570
+ const view = await allocateRoute(saved?.origin ?? undefined);
571
+ if (!view.origin) throw routeFailure(view, 'Gozar has not allocated an address for this service.');
465
572
  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;
573
+ allocated = view.handle;
469
574
  }
470
575
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
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`);
576
+ if (!homeScope.hasReceipt) writeServiceReceipt(receiptFile, `${JSON.stringify({ ...installReceipt(o.home, configDir, o, profile.workers), repo, node, unit_dir: unitDir, auto_update: autoUpdate, platform, route: o.route ?? saved?.routeName ?? null, gozar_home: routeHome, route_custody: custody, ...(allocated ? { route_handle: allocated } : {}) }, null, 2)}\n`, true);
472
577
  if (!hasCurrent) fs.symlinkSync(repo, current);
473
578
  const homeFiles = prepareHome(o, profile);
474
579
  if (needsEnrollmentRestart) {
475
- writeAtomic(receiptFile, `${JSON.stringify({ ...previous, repo: previous.repo ?? repo, node, unit_dir: unitDir, auto_update: autoUpdate, enrollment_pending: true }, null, 2)}\n`);
580
+ writeServiceReceipt(receiptFile, `${JSON.stringify({ ...previous, repo: previous.repo ?? repo, node, unit_dir: unitDir, auto_update: autoUpdate, enrollment_pending: true }, null, 2)}\n`);
476
581
  }
477
582
  if (replaceLegacyUnit) {
478
583
  const file = path.join(unitDir, `${name}.service`), mode = fs.statSync(file).mode & 0o777;
@@ -495,61 +600,132 @@ export async function installService(o, seams = {}) {
495
600
  if (needsEnrollmentRestart) runCommand('systemctl', ['--user', 'restart', `${name}.service`], { env, spawn });
496
601
  }
497
602
  const dataDir = defaultPath(o.home, '.local/share/dot-bridge');
498
- const ready = await (seams.waitForSocket ?? socketIsReady)(path.join(dataDir, 'admin.sock'), seams.socketTimeoutMs ?? 30000);
603
+ const ready = await (seams.waitForSocket ?? socketIsReady)(adminSocketPath(dataDir), seams.socketTimeoutMs ?? 30000);
499
604
  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);
501
605
  let routeReply;
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;
606
+ const existingHandle = allocated ?? previous?.route_handle;
607
+ try {
608
+ routeReply = existingHandle ? await gozar.routeStatus({ home: routeHome, handle: existingHandle }) : await allocateRoute(o.origin);
609
+ if (external) requireExternalRoute(routeReply, o.origin, o.target.value);
610
+ if (routeReply.origin !== o.origin) throw routeFailure(routeReply, 'Gozar returned a different address from the saved service origin.');
611
+ } catch (error) {
612
+ fs.rmSync(homeFiles.resourceFile, { force: true });
613
+ throw error;
614
+ }
615
+ const done = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
616
+ if (routeReply.handle && (JSON.stringify(done.route_handle) !== JSON.stringify(routeReply.handle) || done.gozar_home !== routeHome || done.route_custody !== custody)) {
617
+ writeServiceReceipt(receiptFile, `${JSON.stringify({ ...done, route_handle: routeReply.handle, gozar_home: routeHome, route_custody: custody }, null, 2)}\n`);
618
+ }
619
+ if (pending && readPendingInstall(pendingPath)?.operationId === pending.operationId) fs.rmSync(pendingPath, { force: true });
620
+ if (!isPublished(routeReply)) {
621
+ fs.rmSync(homeFiles.resourceFile, { force: true });
622
+ throw routeFailure(routeReply, 'Gozar did not verify the route; the bridge is running and the route needs repair.');
511
623
  }
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
624
  await setAutoUpdate({ home: o.home, enabled: autoUpdate }, { ...seams, env, spawn, platform });
515
625
  if (!env.DALAN_HOME) recordDefaultHome(o.home, env);
516
626
  if (needsEnrollmentRestart) {
517
627
  const enrolled = JSON.parse(fs.readFileSync(receiptFile, 'utf8'));
518
628
  delete enrolled.enrollment_pending;
519
- writeAtomic(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
629
+ writeServiceReceipt(receiptFile, `${JSON.stringify(enrolled, null, 2)}\n`);
630
+ }
631
+ // A prior interrupted install may have left a private staging copy.
632
+ for (const name of fs.readdirSync(configDir)) {
633
+ if (/^service-install\.json\.[0-9a-f]{16}\.tmp$/.test(name)) fs.rmSync(path.join(configDir, name), { force: true });
520
634
  }
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,
635
+ writeAtomic(homeFiles.resourceFile, `${routeReply.published}/${homeFiles.secret}/mcp\n`);
636
+ return { schema_version: 1, origin: routeReply.published, home: o.home, unit: mac ? labels.service : `${name}.service`, already_installed: homeScope.hasReceipt && !needsEnrollmentRestart, units: Object.keys(files), port: o.port,
522
637
  workers: profile.workers, public_url: `${o.origin}/<secret>/mcp`, resource_url_file: homeFiles.resourceFile,
523
638
  target: o.target.value, started: true, route: routeReply, auto_update: autoUpdate };
524
639
  }
525
640
 
526
641
  // Stop the service and its update job, delete the generated definitions and the public route, and forget the default home.
527
642
  // 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';
643
+ export async function uninstallService({ home, confirmRouteStop }, seams = {}) {
644
+ const env = seams.env ?? process.env;
530
645
  home = path.resolve(home);
646
+ return withRouteInstallLock(env, home, () => uninstallServiceLocked({ home, confirmRouteStop }, seams));
647
+ }
648
+
649
+ async function uninstallServiceLocked({ home, confirmRouteStop }, seams) {
650
+ const env = seams.env ?? process.env, platform = seams.platform ?? process.platform, mac = platform === 'darwin';
531
651
  const receipt = readReceipt(home);
532
- if (!receipt?.unit || receipt.home !== home) fail(`no Dalan service is installed for ${home}`);
652
+ const pendingPath = pendingInstallPath(env, home);
653
+ const pending = readPendingInstall(pendingPath);
654
+ if (receipt && (!receipt.unit || receipt.home !== home)) fail(`no Dalan service is installed for ${home}`);
533
655
  const removed = [];
656
+ let releasePending;
657
+ if (pending && !receipt?.route_handle) {
658
+ const gozar = routeNotDispatched(pending) ? null : seams.gozar ?? await resolveGozar({ env, home: pending.home });
659
+ const observed = await observeRetainedRoute(gozar, pending);
660
+ if (observed.state === 'unobserved') fail('Gozar has not confirmed whether the retained operation started. Cleanup is unconfirmed; the reference was kept.');
661
+ const view = observed.view;
662
+ const subject = view?.handle ?? { operationId: pending.operationId };
663
+ if (!confirmRouteStop || !await confirmRouteStop(subject)) fail('The saved route or pending operation requires explicit approval.');
664
+ releasePending = async () => {
665
+ if (view && (view.state !== 'released' || view.cleanup.state !== 'confirmed' || view.published !== null)) {
666
+ const result = await closeExactRoute(gozar, { ...pending, handle: view.handle });
667
+ if (!result.removed) fail(`Public route removal is unconfirmed. Retained the install operation. ${result.detail}`);
668
+ }
669
+ fs.rmSync(pendingPath, { force: true });
670
+ removed.push(view ? 'public route released' : 'pending route operation cancelled before dispatch');
671
+ };
672
+ if (!receipt) {
673
+ await releasePending();
674
+ return { home, removed, kept: 'No service home was created.', moved_to: null };
675
+ }
676
+ }
677
+ if (!receipt) fail(`no Dalan service is installed for ${home}`);
534
678
  const unitDir = receipt.unit_dir;
535
679
  if (!unitDir || !path.isAbsolute(unitDir)) fail('the service receipt names no unit directory');
536
680
  // Verify both jobs before removing either plist or disabling automatic updates.
537
681
  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 });
682
+ if (receipt.route_handle && (!confirmRouteStop || !await confirmRouteStop(receipt.route_handle))) {
683
+ fail('Public route stop requires explicit approval for the saved handle.');
546
684
  }
685
+ const unitNames = mac ? [] : [`${receipt.unit}.service`, `${receipt.unit}-target.socket`, `${receipt.unit}-target.service`, `${receipt.unit}-update.service`, `${receipt.unit}-update.timer`];
686
+ const units = unitNames.filter(unit => fs.existsSync(path.join(unitDir, unit)));
687
+ const spawn = seams.spawn ?? spawnSync;
688
+ if (!mac) {
689
+ // An unavailable user bus does not prove the service is absent. Do not change files or route custody.
690
+ const systemdEnv = { ...env, LC_ALL: 'C' };
691
+ runCommand('systemctl', ['--user', 'show-environment'], { env: systemdEnv, spawn });
692
+ if (units.length) runCommand('systemctl', ['--user', 'disable', '--now', ...units], { env: systemdEnv, spawn });
693
+ // Query even units whose files are missing: systemd can still have them loaded.
694
+ for (const unit of unitNames) {
695
+ const status = runCommand('systemctl', ['--user', 'show', '--property=LoadState', '--property=ActiveState', unit], { env: systemdEnv, spawn });
696
+ const loadState = /^LoadState=(\S+)$/m.exec(status)?.[1];
697
+ const activeState = /^ActiveState=(\S+)$/m.exec(status)?.[1];
698
+ const stopped = activeState === 'inactive' || activeState === 'failed';
699
+ const absent = loadState === 'not-found' && activeState === undefined;
700
+ if (!stopped && !absent) fail(`Could not confirm ${unit} stopped; service files and home were retained.`);
701
+ }
702
+ }
703
+ await releasePending?.();
547
704
  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}`); }
705
+ const home = receipt.gozar_home ?? gozarHomeFor(env);
706
+ const gozar = seams.gozar ?? await resolveGozar({ env, home, custody: receipt.route_custody });
707
+ const result = await closeExactRoute(gozar, { home, handle: receipt.route_handle });
708
+ if (!result.removed) fail(`Public route removal is unconfirmed. Retained the service receipt. ${result.detail}`);
709
+ const file = path.join(defaultPath(receipt.home, '.config/dot-bridge'), 'service-install.json');
710
+ const next = { ...receipt };
711
+ delete next.route_handle;
712
+ writeServiceReceipt(file, `${JSON.stringify(next, null, 2)}\n`);
713
+ if (pending?.handle && JSON.stringify(pending.handle) === JSON.stringify(receipt.route_handle)) fs.rmSync(pendingPath, { force: true });
714
+ removed.push('public route released');
715
+ }
716
+ if (mac) {
717
+ if (receipt.auto_update) {
718
+ await setAutoUpdate({ home, enabled: false }, { ...seams, env, platform });
719
+ removed.push('automatic updates off');
720
+ }
721
+ removed.push(...removeAgents({ unit: receipt.unit, unit_dir: unitDir }, seams.launchd));
722
+ } else {
723
+ for (const unit of units) {
724
+ fs.rmSync(path.join(unitDir, unit));
725
+ removed.push(`removed ${path.join(unitDir, unit)}`);
726
+ }
727
+ try { runCommand('systemctl', ['--user', 'daemon-reload'], { env, spawn }); }
728
+ catch (error) { removed.push(`systemd daemon-reload failed after removal: ${error.message}`); }
553
729
  }
554
730
  forgetDefaultHome(home, env);
555
731
  // 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.
@@ -596,14 +772,23 @@ export async function serviceMain(argv, seams = {}) {
596
772
  return result;
597
773
  }
598
774
  if (action === 'help' || action === '--help' || !action) {
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.');
775
+ (seams.out ?? console.log)('Usage: dalan service install --worker NAME [--route NAME] [--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.');
600
776
  return null;
601
777
  }
602
778
  if (action === 'uninstall') {
603
779
  const parsed = parseArgs(args, { values: ['--home'], flags: ['--json', '--help'] });
604
780
  if (parsed['--help']) return serviceMain(['help'], seams);
605
781
  if (parsed._.length) fail(`unexpected argument ${parsed._[0]}`);
606
- const result = await uninstallService({ home: parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env) }, seams);
782
+ const confirmRouteStop = seams.confirmRouteStop ?? (async handle => {
783
+ if (!process.stdin.isTTY) return false;
784
+ const { createInterface } = await import('node:readline/promises');
785
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
786
+ const question = handle.operationId ? `Cancel prepared Gozar operation ${handle.operationId}? [y/N] `
787
+ : `Remove Gozar route ${handle.kind} ${handle.id} (generation ${handle.generation})? [y/N] `;
788
+ try { return /^y(es)?$/i.test((await rl.question(question)).trim()); }
789
+ finally { rl.close(); }
790
+ });
791
+ const result = await uninstallService({ home: parsed['--home'] ?? serviceHomeFor(seams.env ?? process.env), confirmRouteStop }, seams);
607
792
  const out = seams.out ?? console.log;
608
793
  if (parsed['--json']) out(JSON.stringify(result)); else { for (const line of result.removed) out(line); out(`Kept: ${result.kept}`); }
609
794
  return result;
@@ -612,15 +797,29 @@ export async function serviceMain(argv, seams = {}) {
612
797
  const o = parseOptions(args, seams.env ?? process.env);
613
798
  if (o.help) return serviceMain(['help'], seams);
614
799
  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.
800
+ // Route consent is collected after showing the exact review returned by Gozar.
616
801
  const consent = seams.consent ?? (async candidate => {
617
802
  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; }
803
+ if (!process.stdin.isTTY) { out0('Run this in a terminal to approve the route.'); return false; }
620
804
  const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
621
805
  try { return /^y(es)?$/i.test((await rl.question('Use this route? [y/N] ')).trim()); } finally { rl.close(); }
622
806
  });
623
- const result = await installService(o, { ...seams, consent });
807
+ const setup = async request => {
808
+ const tty = process.stdin.isTTY && process.stdout.isTTY;
809
+ if (!tty) return request.candidate.setup.state === 'ready';
810
+ const { createInterface } = await import('node:readline/promises');
811
+ const terminal = muteableTerminal(process.stdin, process.stdout);
812
+ const rl = createInterface({ input: process.stdin, output: terminal.output, terminal: terminal.terminal });
813
+ try {
814
+ return await runRouteSetup({ ...request, say: out0, ask: message => rl.question(message), async askSecret(label) {
815
+ process.stdout.write(`${label} (hidden): `);
816
+ terminal.mute(true);
817
+ try { return Buffer.from(await rl.question('')); }
818
+ finally { terminal.mute(false); process.stdout.write('\n'); }
819
+ }, handoff: href => process.stdout.write(`${href}\n`) });
820
+ } finally { rl.close(); }
821
+ };
822
+ const result = await installService(o, { ...seams, consent, setup });
624
823
  if (o.json) (seams.out ?? console.log)(JSON.stringify(result));
625
824
  else {
626
825
  const out = seams.out ?? console.log;