@tnunamak/dalan 0.8.1 → 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 (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { defaultPath } from '../src/paths.mjs';
3
+ import { adminSocketPath } from '../src/admin-socket.mjs';
3
4
  import { readEnv } from '../src/env.mjs';
4
5
  // One command that turns a fresh worker bridge into a durable service: a systemd user service on Linux, a launchd
5
6
  // LaunchAgent on macOS. Separate from scripts/live-trial/setup.mjs on purpose: that script starts a throwaway process
@@ -13,59 +14,10 @@ import { randomBytes } from 'node:crypto';
13
14
  import { DatabaseSync } from 'node:sqlite';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { parseArgs } from './live-trial/common.mjs';
16
- import { loadKeys } from '../src/as-files.mjs';
17
+ import { loadKeys, writeAtomic } from '../src/as-files.mjs';
18
+ import { routeCustodyPath } from '../src/route-custody.mjs';
17
19
  import { writeWorkerInstructions } from '../src/worker-instructions.mjs';
18
- import https from 'node:https';
19
- import { Resolver } from 'node:dns/promises';
20
- import { buildQuery, ensureDurableRoute, gozarHomeFor, resolveGozar, describeCandidate, describeDisclosure } from '../src/gozar-routes.mjs';
21
-
22
- // ---- checking the public address ---------------------------------------------------------------------------------------------------
23
- // Public DNS through three resolvers in parallel (one can keep a negative-cached NXDOMAIN for a new name for >10 min).
24
- const PUBLIC_DNS_SERVERS = ['1.1.1.1', '8.8.8.8', '9.9.9.9'];
25
- const DNS_WAIT_MS = 600_000, DNS_PROGRESS_MS = 30_000, HTTPS_WAIT_MS = 120_000;
26
- function makePublicResolver(resolvers = PUBLIC_DNS_SERVERS.map(server => { const resolver = new Resolver({ timeout: 3000, tries: 1 }); resolver.setServers([server]); return { server, resolver }; })) {
27
- return name => new Promise(resolve => {
28
- let pending = resolvers.length;
29
- const settle = () => { if (--pending === 0) resolve(null); };
30
- for (const { server, resolver } of resolvers) resolver.resolve4(name).then(addresses => (addresses[0] ? resolve({ address: addresses[0], server }) : settle()), settle);
31
- });
32
- }
33
- // GET /admin pinned to the address DNS returned. The bridge answers 404 on its unauthenticated path.
34
- function fetchPinned(url, address, { timeoutMs = 15_000 } = {}) {
35
- const u = new URL(url);
36
- return new Promise((resolve, reject) => {
37
- const req = https.request({ hostname: u.hostname, port: u.port || 443, path: '/admin', method: 'GET', timeout: timeoutMs,
38
- lookup: (_host, options, cb) => (options?.all ? cb(null, [{ address, family: 4 }]) : cb(null, address, 4)) }, res => { res.resume(); resolve(res.statusCode); });
39
- req.on('timeout', () => req.destroy(new Error('timeout')));
40
- req.on('error', reject);
41
- req.end();
42
- });
43
- }
44
- export async function verifyPublic({ url, dnsName, resolve4, request = fetchPinned, sleep = ms => new Promise(r => setTimeout(r, ms)), now = Date.now, timeoutMs = DNS_WAIT_MS, intervalMs = 5_000, progressMs = DNS_PROGRESS_MS, log = console.log }) {
45
- const secs = ms => Math.round(ms / 1000);
46
- const start = now(), end = start + timeoutMs;
47
- let nextProgress = progressMs, found = null;
48
- while (!found) {
49
- found = await resolve4(dnsName);
50
- if (found) break;
51
- const elapsed = now() - start;
52
- if (elapsed >= nextProgress && elapsed < timeoutMs) { log(`waiting for public DNS of ${dnsName} … ${secs(elapsed)} s / ${secs(timeoutMs)} s`); nextProgress += progressMs; }
53
- if (now() >= end) break;
54
- await sleep(intervalMs);
55
- }
56
- if (!found) { log(`FAIL public DNS: no A record for ${dnsName} from 1.1.1.1, 8.8.8.8 or 9.9.9.9 after ${secs(timeoutMs)} s. Next: run \`dig @8.8.8.8 ${dnsName} A\` (also try @1.1.1.1 and @9.9.9.9), check the route's state with Gozar, then retry.`); return false; }
57
- log(`PASS public DNS: ${dnsName} -> ${found.address} (via ${found.server})`);
58
- const httpsEnd = now() + HTTPS_WAIT_MS;
59
- let nextHttpsProgress = now() + progressMs, last;
60
- for (;;) {
61
- try { const code = await request(url, found.address); if (code === 404) break; last = `GET /admin returned ${code}, expected 404 from the bridge`; } catch (e) { last = e.message; }
62
- if (now() >= httpsEnd) { log(`FAIL public HTTPS: ${last} (still failing after ${secs(HTTPS_WAIT_MS)} s). Likely cause: the route is not active yet, or a different service answers on this address. Next: check the route's state with Gozar and the local port, then retry.`); return false; }
63
- if (now() >= nextHttpsProgress) { log(`waiting for public HTTPS of ${dnsName} … last result: ${last}`); nextHttpsProgress += progressMs; }
64
- await sleep(intervalMs);
65
- }
66
- log('PASS public HTTPS: GET /admin returned 404 from the bridge');
67
- return true;
68
- }
20
+ import { buildQuery, ensureDurableRoute, gozarHomeFor, isPublished, observeRetainedRoute, reconcileRouteOperationId, requireExternalRoute, resolveGozar, describeCandidate, describeDisclosure, routeFailure } from '../src/gozar-routes.mjs';
69
21
 
70
22
  const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
71
23
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/; // no space, quote, %, $ or newline: the value goes into a unit or plist as is
@@ -127,9 +79,8 @@ function parseOptions(argv, platform) {
127
79
  if (!Number.isInteger(port) || port < 1024 || port > 65535) fail('--port N is required (1024-65535)');
128
80
  const node = stableNode(process.execPath);
129
81
  const repo = REPO.replace(/\/$/, '');
130
- // Unix socket paths are limited (104 bytes on macOS, 108 on Linux); the owner socket lives under the bridge home.
131
- const socketPath = defaultPath(home,'.local/share/dot-bridge/admin.sock');
132
- if (Buffer.byteLength(socketPath) >= 104) fail(`--home is too long: the owner socket path would be ${Buffer.byteLength(socketPath)} bytes (limit 103); choose a shorter home`);
82
+ // Unix socket paths are limited (104 bytes on macOS, 108 on Linux); a long home gets a short socket path instead.
83
+ const socketPath = adminSocketPath(defaultPath(home,'.local/share/dot-bridge'));
133
84
  for (const [label, value] of [['--home', home], ['node path', node], ['repo path', repo]]) {
134
85
  if (!SAFE_PATH.test(value)) fail(`${label} contains a character that is not safe in a unit file: ${JSON.stringify(value)}`);
135
86
  }
@@ -246,6 +197,7 @@ function unitFiles(o) {
246
197
  `Environment=HOME=${o.home}`,
247
198
  'Environment=NODE_ENV=production',
248
199
  'Environment=DALAN_AUTH_MODE=builtin',
200
+ 'Environment=DALAN_GOZAR_SERVICE=1',
249
201
  ...(o.repoTools ? ['Environment=DALAN_ENABLE_WORKSPACE=1'] : []),
250
202
  `Environment=DALAN_PORT=${o.port}`,
251
203
  `Environment=PATH=${servicePath(o.node)}`,
@@ -298,7 +250,7 @@ function servicePath(node) {
298
250
  function plistText(o) {
299
251
  const name = `dot-bridge-${o.worker}`;
300
252
  const logs = path.join(o.home, 'logs');
301
- const env = { HOME: o.home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', ...(o.repoTools ? { DALAN_ENABLE_WORKSPACE: '1' } : {}), DALAN_PORT: String(o.port), PATH: servicePath(o.node) };
253
+ const env = { HOME: o.home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_GOZAR_SERVICE: '1', ...(o.repoTools ? { DALAN_ENABLE_WORKSPACE: '1' } : {}), DALAN_PORT: String(o.port), PATH: servicePath(o.node) };
302
254
  return [
303
255
  '<?xml version="1.0" encoding="UTF-8"?>',
304
256
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -369,15 +321,12 @@ function writeHome(o, platform, initHome = runDotWorkerInit) {
369
321
  fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
370
322
  const init = initHome({ ...o, home: stage });
371
323
  if (init.status !== 0) fail(`dalan init failed (exit ${init.status}): ${String(init.stderr).trim().split('\n').at(-1)}`);
372
- // Create the path secret now so the private resource URL file exists before the first start. The server keeps an existing env file.
324
+ // Reserve the path secret before startup. Publication writes the connector URL after proof.
373
325
  const envFile = path.join(configDir, 'env');
374
326
  if (!fs.existsSync(envFile)) writeExclusive(envFile, `BRIDGE_PATH_SECRET=${randomBytes(32).toString('hex')}\n`, 0o600, 'bridge environment file');
375
327
  fs.chmodSync(envFile, 0o600);
376
328
  const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})$/m.exec(fs.readFileSync(envFile, 'utf8'))?.[1];
377
329
  if (!secret) fail('bridge path secret is missing or invalid');
378
- const urlFile = path.join(stage, 'resource-url');
379
- fs.writeFileSync(urlFile, `${o.publicUrl}/${secret}/mcp\n`, { mode: 0o600 });
380
- fs.chmodSync(urlFile, 0o600);
381
330
  writeWorkerInstructions(stage);
382
331
  try { fs.mkdirSync(o.home, { mode: 0o700 }); }
383
332
  catch (error) {
@@ -478,7 +427,7 @@ function assertNoSystemdOverrides(unit,env) {
478
427
  }
479
428
 
480
429
  function publicRetryCommand(o,url) {
481
- return `node ${path.join(o.repo,'scripts/worker-bridge-setup.mjs')} --retry-public-check --worker ${o.worker} --public-url ${url} --port ${o.port} --home ${o.home}${o.repoTools?'':' --no-repo-tools'}`;
430
+ return `node ${path.join(o.repo,'scripts/worker-bridge-setup.mjs')} --retry-public-check --worker ${o.worker} --public-url ${url} --port ${o.port} --home ${o.home}${o.lan?` --lan-forward ${o.lan.address}:${o.lan.port}`:''}${o.repoTools?'':' --no-repo-tools'}`;
482
431
  }
483
432
 
484
433
  function recoveryCommand(o) {
@@ -640,6 +589,8 @@ function removeUnit(o, { platform, env, log, spawn = spawnSync, holderProbe = ho
640
589
  if (o.purge && homeExists && !isBridgeHome(o.home, o.worker)) fail(`${o.home} is not a bridge home for worker ${o.worker}; refusing to purge it`);
641
590
  if (!present.length && !(o.purge && homeExists)) { log(`Nothing to remove for worker ${o.worker}.`); return; }
642
591
  if (o.purge && homeExists) {
592
+ const ref = readWorkerRouteReference(o.home, defaultPath(o.home, '.config/dot-bridge', 'route-reference.json'));
593
+ if (ref && !ref.handle) fail('The worker has a pending Gozar route operation. Keep the home and retry the public check to recover its exact route before purging.');
643
594
  const { named: users, unreadable } = unitsNamingHome(unitDir, o.home, present);
644
595
  if (unreadable.length) fail(`${unreadable.join(', ')} could not be read, so it is not known whether a service that uses ${o.home} is defined there. Nothing was removed. Make ${unreadable.length > 1 ? 'them' : 'it'} readable (or delete ${unreadable.length > 1 ? 'them' : 'it'} once the service is stopped), then run this command again.`);
645
596
  if (users.length) {
@@ -692,24 +643,72 @@ function repointUnit(o, { platform, env, log }) {
692
643
  const names = linux ? [`dot-bridge-${o.worker}.service`] : [`${launchLabel(o.worker)}.plist`];
693
644
  const present = names.map(n => path.join(unitDir, n)).filter(f => fs.existsSync(f));
694
645
  if (!present.length) fail(`no service unit for worker ${o.worker} in ${unitDir}; nothing to repoint`);
646
+ // Split a Linux ExecStart value into tokens, keeping each token's span so only the script token is rewritten.
647
+ // Quoted tokens may contain spaces; an unterminated quote is a refusal, not a guess.
648
+ const execTokens = (value, file) => {
649
+ const tokens = [];
650
+ for (let i = 0; i < value.length;) {
651
+ while (i < value.length && /[ \t]/.test(value[i])) i += 1;
652
+ if (i >= value.length) break;
653
+ const start = i, quote = value[i] === '"' || value[i] === "'" ? value[i] : '';
654
+ if (quote) {
655
+ const end = value.indexOf(quote, i + 1);
656
+ if (end < 0) fail(`${file} has an unterminated quote in ExecStart; refusing to guess what to change`);
657
+ if (end + 1 < value.length && !/[ \t]/.test(value[end + 1])) fail(`${file} has joined ExecStart tokens; refusing to guess what to change`);
658
+ tokens.push({ start, end: end + 1, quote, value: value.slice(i + 1, end) });
659
+ i = end + 1;
660
+ } else {
661
+ while (i < value.length && !/[ \t]/.test(value[i])) i += 1;
662
+ tokens.push({ start, end: i, quote, value: value.slice(start, i) });
663
+ }
664
+ }
665
+ return tokens;
666
+ };
667
+ // Compute every file's new text before writing any of them: a refused repoint leaves its original unit intact,
668
+ // and the working directory never moves without the script argument moving with it.
695
669
  const changes = present.map(file => {
696
670
  const text = fs.readFileSync(file, 'utf8');
697
671
  if (!text.includes(MARKER)) fail(`${file} was not created by worker-bridge-setup; refusing to change it`);
698
- const match = linux ? /^WorkingDirectory=(\S+)$/m.exec(text) : /<key>WorkingDirectory<\/key>\s*<string>([^<]+)<\/string>/.exec(text);
699
- if (!match) fail(`${file} has no WorkingDirectory; refusing to guess the old code directory`);
700
- if (!linux && match[1] !== o.repo && !text.includes(`<string>${path.join(match[1], 'src/server.mjs')}</string>`)) fail(`${file} runs a script other than ${path.join(match[1], 'src/server.mjs')}; refusing to guess what to change`);
701
- return { file, text, old: match[1] };
672
+ let old, next = text;
673
+ if (linux) {
674
+ if (/\\[ \t]*\r?\n/.test(text)) fail(`${file} uses continued directives; refusing unsupported service syntax`);
675
+ const directories=[...text.matchAll(/^[ \t]*WorkingDirectory[ \t]*=[ \t]*(.*)$/gm)];
676
+ const starts=[...text.matchAll(/^[ \t]*ExecStart[ \t]*=[ \t]*(.*)$/gm)];
677
+ if(directories.length!==1||!directories[0][1].trim()) fail(`${file} needs one WorkingDirectory; refusing ambiguous service settings`);
678
+ if(starts.length!==1||!starts[0][1].trim()) fail(`${file} needs one ExecStart; refusing ambiguous service settings`);
679
+ const rawOld=directories[0][1].trim();
680
+ old=(rawOld.startsWith('"')&&rawOld.endsWith('"'))||(rawOld.startsWith("'")&&rawOld.endsWith("'")) ? rawOld.slice(1,-1) : rawOld;
681
+ const exec=starts[0][1],tokens=execTokens(exec,file);
682
+ // Validate even when the directory already matches: a partial update may still start old code.
683
+ let scriptIndex=1;
684
+ if(path.basename(tokens[0]?.value??'')==='env') {
685
+ if(!tokens[1]||path.basename(tokens[1].value)!=='node') fail(`${file} starts through an unsupported env form; refusing to guess what to change`);
686
+ scriptIndex=2;
687
+ } else if(path.basename(tokens[0]?.value??'')!=='node') fail(`${file} does not start node directly; refusing to guess what to change`);
688
+ const script=tokens[scriptIndex],oldScript=path.join(old,'src/server.mjs');
689
+ if(!script||(script.value!==oldScript&&script.value!=='src/server.mjs')) fail(`${file} runs a script other than ${oldScript}; refusing to guess what to change`);
690
+ let execNext=exec;
691
+ if(script.value===oldScript) {
692
+ const newScript=path.join(o.repo,'src/server.mjs'),quote=script.quote||(/[ \t]/.test(newScript)?'"':'');
693
+ execNext=exec.slice(0,script.start)+quote+newScript+quote+exec.slice(script.end);
694
+ }
695
+ next=text.replace(/^[ \t]*WorkingDirectory[ \t]*=.*$/m,()=>`WorkingDirectory=${o.repo}`).replace(/^[ \t]*ExecStart[ \t]*=.*$/m,()=>`ExecStart=${execNext}`);
696
+ } else {
697
+ const match = /<key>WorkingDirectory<\/key>\s*<string>([^<]+)<\/string>/.exec(text);
698
+ if (!match) fail(`${file} has no WorkingDirectory; refusing to guess the old code directory`);
699
+ old = match[1];
700
+ if (old !== o.repo && !text.includes(`<string>${path.join(old, 'src/server.mjs')}</string>`)) fail(`${file} runs a script other than ${path.join(old, 'src/server.mjs')}; refusing to guess what to change`);
701
+ if (old !== o.repo) {
702
+ next = text.replace(/(<key>WorkingDirectory<\/key>\s*<string>)[^<]*(<\/string>)/, (_, head, tail) => `${head}${o.repo}${tail}`)
703
+ .replace(`<string>${path.join(old, 'src/server.mjs')}</string>`, () => `<string>${path.join(o.repo, 'src/server.mjs')}</string>`);
704
+ }
705
+ }
706
+ return { file, text, old, next };
702
707
  });
703
- for (const { file, text, old } of changes) {
704
- let next = text;
708
+ for (const { file, text, old, next: computed } of changes) {
709
+ let next = computed;
705
710
  // Change the code directory and the script argument only. HOME, the environment, the interpreter and the log paths can
706
711
  // name a path below the old code directory; they are not code paths and stay as they are.
707
- if (old !== o.repo) {
708
- next = linux
709
- ? next.replace(/^WorkingDirectory=.*$/m, () => `WorkingDirectory=${o.repo}`)
710
- : next.replace(/(<key>WorkingDirectory<\/key>\s*<string>)[^<]*(<\/string>)/, (_, head, tail) => `${head}${o.repo}${tail}`)
711
- .replace(`<string>${path.join(old, 'src/server.mjs')}</string>`, () => `<string>${path.join(o.repo, 'src/server.mjs')}</string>`);
712
- }
713
712
  // A plist from an older release lacks the session types that let launchd load it into the user domain.
714
713
  const addSessionTypes = !linux && !next.includes('<key>LimitLoadToSessionType</key>');
715
714
  if (addSessionTypes) {
@@ -720,7 +719,7 @@ function repointUnit(o, { platform, env, log }) {
720
719
  const tmp = `${file}.repoint-${process.pid}`;
721
720
  fs.writeFileSync(tmp, next, { mode: fs.statSync(file).mode & 0o777, flag: 'wx' });
722
721
  fs.renameSync(tmp, file);
723
- log(old === o.repo ? `Updated ${file}: added the launchd session types (${SESSION_TYPES.join(', ')})` : `Repointed ${file}: ${old} -> ${o.repo}${addSessionTypes ? '; added the launchd session types' : ''}`);
722
+ log(old === o.repo ? `Updated ${file}: ${addSessionTypes ? `added the launchd session types (${SESSION_TYPES.join(', ')})` : 'normalized service settings'}` : `Repointed ${file}: ${old} -> ${o.repo}${addSessionTypes ? '; added the launchd session types' : ''}`);
724
723
  }
725
724
  const [userDomain] = launchDomains(process.getuid?.());
726
725
  log(linux
@@ -742,17 +741,14 @@ function verifyRetryTarget(o, { platform, env }) {
742
741
  const workers=JSON.parse(readOwnedFile(o.home,workersFile,'worker profile'));
743
742
  const as=JSON.parse(readOwnedFile(o.home,asFile,'issuer config'));
744
743
  const envText=readOwnedFile(o.home,envFile,'bridge environment');
745
- const resource=readOwnedFile(o.home,urlFile,'resource URL').trim();
744
+ const resource=fs.existsSync(urlFile) ? readOwnedFile(o.home,urlFile,'resource URL').trim() : null;
746
745
  readOwnedFile(o.home,keysFile,'signing key');
747
746
  readOwnedFile(o.home,cookieKeysFile,'cookie keys');
748
747
  const secretMatch=/^BRIDGE_PATH_SECRET=([a-f0-9]{64})\n?$/.exec(envText);
749
748
  if(!secretMatch) fail('--retry-public-check refused: the saved bridge path secret is missing or invalid');
750
749
  loadKeys(configDir);
751
750
  if(!Object.hasOwn(workers.workers??{},o.worker)) fail(`--retry-public-check refused: ${o.home} has no worker profile named ${o.worker}`);
752
- let saved;
753
- try { saved=new URL(resource); } catch { fail('--retry-public-check refused: the saved resource URL is invalid'); }
754
- if(saved.origin!==o.publicUrl||saved.pathname!==`/${saved.pathname.split('/')[1]}/mcp`||!/^\/[a-f0-9]{64}\/mcp$/.test(saved.pathname)) fail('--retry-public-check refused: --public-url does not match this home resource URL');
755
- if(saved.pathname!==`/${secretMatch[1]}/mcp`) fail('--retry-public-check refused: the saved resource URL does not match this home path secret');
751
+ if (resource && resource !== `${o.publicUrl}/${secretMatch[1]}/mcp`) fail('--retry-public-check refused: the saved resource URL does not match this home and issuer');
756
752
  if(as.public_url!==o.publicUrl) fail('--retry-public-check refused: --public-url does not match this home issuer');
757
753
  const dir=unitDirFor(platform,env), unit=platform==='darwin'?path.join(dir,`${launchLabel(o.worker)}.plist`):path.join(dir,`dot-bridge-${o.worker}.service`);
758
754
  const configRoot=platform==='darwin'?(env.HOME||os.homedir()):(env.XDG_CONFIG_HOME&&path.isAbsolute(env.XDG_CONFIG_HOME)?env.XDG_CONFIG_HOME:path.join(os.homedir(),'.config'));
@@ -762,21 +758,35 @@ function verifyRetryTarget(o, { platform, env }) {
762
758
  // Accept only the previous generator's equivalent setting names; retain every
763
759
  // other byte check so a customized service cannot become a retry target.
764
760
  const compatibleText=text.replace(/^Environment=DOT_BRIDGE_(AUTH_MODE|ENABLE_WORKSPACE|PORT)=/gm,'Environment=DALAN_$1=').replace(/<key>DOT_BRIDGE_(AUTH_MODE|ENABLE_WORKSPACE|PORT)<\/key>/g,'<key>DALAN_$1</key>');
765
- if(compatibleText!==expected) fail(`--retry-public-check refused: ${unit} does not exactly match the generated worker, HOME, executable, working directory and port`);
766
- if(platform==='linux') assertNoSystemdOverrides(unit,env);
767
- return { url:o.publicUrl, dnsName:saved.hostname };
761
+ const oldExpected = expected.replace('Environment=DALAN_GOZAR_SERVICE=1\n', '').replace(' <key>DALAN_GOZAR_SERVICE</key>\n <string>1</string>\n', '');
762
+ if(compatibleText!==expected && compatibleText!==oldExpected) fail(`--retry-public-check refused: ${unit} does not exactly match the generated worker, HOME, executable, working directory and port`);
763
+ if (platform === 'linux') {
764
+ assertNoSystemdOverrides(unit, env);
765
+ const generated = unitFiles(o).files;
766
+ for (const suffix of ['lan.socket', 'lan.service']) {
767
+ const name = `dot-bridge-${o.worker}-${suffix}`, file = path.join(dir, name);
768
+ if (o.lan ? readOwnedFile(configRoot, file, 'forwarding unit') !== generated[name] : fs.existsSync(file)) {
769
+ fail('--retry-public-check refused: --lan-forward must match the generated forwarding units');
770
+ }
771
+ }
772
+ }
773
+ return { url: o.publicUrl, secret: secretMatch[1], urlFile, configDir };
768
774
  }
769
775
 
770
776
  // `--start` returns as soon as the service manager accepts the unit, but the bridge needs a moment more before its admin
771
777
  // socket answers. Commands run in that gap fail with `connect ENOENT .../admin.sock`, so --start waits for a real connection.
772
- const connectsOnce = socketPath => spawnSync(process.execPath, ['-e',
773
- "const s=require('node:net').connect(process.argv[1]);s.on('connect',()=>process.exit(0));s.on('error',()=>process.exit(1));setTimeout(()=>process.exit(1),2000)", socketPath], { stdio: 'ignore' }).status === 0;
778
+ const connectsOnce = (socketPath, remainingMs) => spawnSync(process.execPath, ['-e',
779
+ "const s=require('node:net').connect(process.argv[1]);s.on('connect',()=>process.exit(0));s.on('error',()=>process.exit(1))", socketPath],
780
+ { stdio: 'ignore', timeout: Math.max(1, Math.min(2000, Math.floor(remainingMs))) }).status === 0;
774
781
  export function waitForAdminSocket({ socketPath, timeoutMs = 30000, intervalMs = 250, probe = connectsOnce, now = Date.now, sleep = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) }) {
775
782
  const deadline = now() + timeoutMs;
776
783
  for (;;) {
777
- if (probe(socketPath)) return true;
778
- if (now() >= deadline) return false;
779
- sleep(intervalMs);
784
+ const remaining = deadline - now();
785
+ if (remaining <= 0) return false;
786
+ if (probe(socketPath, remaining)) return now() < deadline;
787
+ const afterProbe = deadline - now();
788
+ if (afterProbe <= 0) return false;
789
+ sleep(Math.min(intervalMs, afterProbe));
780
790
  }
781
791
  }
782
792
  function waitForStartedBridge(o, env, platform, waitForSocket) {
@@ -791,7 +801,7 @@ function waitForStartedBridge(o, env, platform, waitForSocket) {
791
801
  fail(`the service was started but the bridge did not answer on its admin socket ${o.socketPath} within ${Math.round(budget / 1000)} s. Read the service log with ${where}. Generated state is left in place; remove this install with: ${recoveryCommand(o)}`);
792
802
  }
793
803
 
794
- function runUnlocked(argv, { platform = process.platform, env = process.env, log = console.log, verifyPublic: verify = verifyPublic, resolve4 = makePublicResolver(), initHome, spawn = spawnSync, waitForSocket = waitForAdminSocket, holderProbe } = {}, parsed = null) {
804
+ function runUnlocked(argv, { platform = process.platform, env = process.env, log = console.log, gozar: suppliedGozar, consent, initHome, spawn = spawnSync, waitForSocket = waitForAdminSocket, holderProbe } = {}, parsed = null) {
795
805
  const o = parsed ?? parseOptions(argv, platform);
796
806
  if (o.help) {
797
807
  log('usage: node scripts/worker-bridge-setup.mjs --worker NAME --public-url https://HOST --port N [--home DIR] [--lan-forward ADDR:PORT] [--write-units-only] [--start] [--no-repo-tools]');
@@ -811,12 +821,9 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
811
821
  const unitDir = unitDirFor(platform, env);
812
822
  const { files, enable } = linux ? unitFiles(o) : { files: darwin ? { [`${launchLabel(o.worker)}.plist`]: plistText(o) } : {}, enable: [] };
813
823
 
814
- if(o.retryPublicCheck) {
815
- const {url,dnsName}=verifyRetryTarget(o,{platform,env});
816
- if(readEnv('DALAN_EXPOSE_SKIP_PUBLIC_CHECK',env)==='1') { log('SKIPPED public check (DALAN_EXPOSE_SKIP_PUBLIC_CHECK=1; tests only)'); return; }
817
- return verify({url,dnsName,resolve4,log}).then(ok=>{
818
- if(!ok) fail(`public verification failed; the service, home and keys were left in place. Retry after the public route is ready with: ${publicRetryCommand(o,url)}. To remove this install: ${recoveryCommand(o)}`);
819
- });
824
+ if (o.retryPublicCheck) {
825
+ const { url, secret, urlFile, configDir } = verifyRetryTarget(o, { platform, env });
826
+ return publishWorkerRoute({ o, env, gozar: suppliedGozar, url, secret, urlFile, configDir, log, consent, platform });
820
827
  }
821
828
 
822
829
  // Check everything before the first write so a refusal leaves nothing behind.
@@ -829,13 +836,23 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
829
836
  if (unitDir) for (const f of Object.keys(files)) if (fs.existsSync(path.join(unitDir, f))) fail(`${path.join(unitDir, f)} already exists; refusing to overwrite it`);
830
837
  if (darwin && !lintPlist(files[`${launchLabel(o.worker)}.plist`], env)) log('plutil not found: skipped the plist lint');
831
838
  // --route: Gozar allocated or adopted the route before this point (see run()); only the public address is used here.
832
- const exposure = o.route !== undefined ? { route: o.route, url: o.publicUrl, dnsName: new URL(o.publicUrl).hostname } : null;
839
+ const exposure = o.routeView;
833
840
 
834
841
  if (o.start) checkStartReadiness(platform, env);
842
+ if (o.route !== undefined && !exposure) {
843
+ if (o.writeUnitsOnly) fail('--write-units-only requires --public-url; it does not start a route.');
844
+ return allocateRoute(o, { env, gozar: suppliedGozar, consent, log }).then(gozar => runUnlocked(argv,
845
+ { platform, env, log, gozar, consent, initHome, spawn, waitForSocket, holderProbe }, o));
846
+ }
835
847
  if (o.start) warnIfLingeringDisabled(platform, env, log, spawn);
836
848
 
837
849
  let urlFile = path.join(o.home, 'resource-url');
838
- if (!o.writeUnitsOnly) { urlFile = writeHome(o, platform, initHome); log(`Home ready: ${o.home} (mode 0700), worker ${o.worker}, issuer ${o.publicUrl}`); }
850
+ const configDir = defaultPath(o.home, '.config/dot-bridge');
851
+ if (!o.writeUnitsOnly) {
852
+ urlFile = writeHome(o, platform, initHome);
853
+ if (exposure) writeAtomic(path.join(configDir, 'route-reference.json'), JSON.stringify(o.routeRef));
854
+ log(`Home ready: ${o.home} (mode 0700), worker ${o.worker}`);
855
+ }
839
856
 
840
857
  const uid = process.getuid?.();
841
858
  if (!unitDir) {
@@ -865,9 +882,7 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
865
882
  log(`To stop: ${stop}`);
866
883
  } else log(`Not started. To start:\n launchctl bootstrap ${domain} ${plist}\nTo stop:\n ${stop}`);
867
884
  }
868
- if (exposure) log(`Route: ${exposure.url} -> http://127.0.0.1:${o.port} (Gozar route ${exposure.route})`);
869
885
  if (o.lan) log(`LAN forwarder: ${o.lan.address}:${o.lan.port} -> 127.0.0.1:${o.port}. Point the reverse proxy there; anything on that network can reach it.`);
870
- log(`Resource URL file (private, mode 0600): ${urlFile}`);
871
886
  const dw = `dalan() { HOME=${shellQuote(o.home)} ${shellQuote(o.node)} ${shellQuote(path.join(o.repo, 'bin/dalan.mjs'))} "$@"; }`;
872
887
  log('Owner commands (run after the service is up):');
873
888
  log(` ${dw}`);
@@ -875,40 +890,113 @@ function runUnlocked(argv, { platform = process.platform, env = process.env, log
875
890
  log(' dalan connect pending');
876
891
  log(` dalan connect approve CODE --worker ${o.worker}`);
877
892
  log(' dalan connect signal-token # save wake URL privately for hook-driven workers; print path; --rotate replaces it');
878
- if (!exposure) return undefined;
879
- // Public check only after the bridge starts. Returns a promise; the entry point awaits it and exits 1 on failure.
880
- const { dnsName, url } = exposure;
881
- if (!o.start) {
882
- log(`Public check runs with --start. By hand: dig @8.8.8.8 ${dnsName} A (or @1.1.1.1, @9.9.9.9) ; curl -sS -o /dev/null -w '%{http_code}' ${url}/admin (expect 404)`);
883
- return undefined;
884
- }
885
- if (readEnv('DALAN_EXPOSE_SKIP_PUBLIC_CHECK',env) === '1') { log('SKIPPED public check (DALAN_EXPOSE_SKIP_PUBLIC_CHECK=1; tests only)'); return undefined; }
886
- return verify({ url, dnsName, resolve4, log }).then(ok => {
887
- if (!ok) fail(`public verification failed; the service, home and keys were left in place. Retry the check with: ${publicRetryCommand(o,url)}. To remove this install: ${recoveryCommand(o)}`);
893
+ if (o.writeUnitsOnly) return;
894
+ if (!o.start || (!exposure && !consent && !process.stdin.isTTY)) {
895
+ log(`With the bridge running, approve and verify the public route in a terminal: ${publicRetryCommand(o, o.publicUrl)}`);
896
+ return;
897
+ }
898
+ const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})$/m.exec(fs.readFileSync(path.join(configDir, 'env'), 'utf8'))?.[1];
899
+ return publishWorkerRoute({ o, env, gozar: suppliedGozar, url: o.publicUrl, secret, urlFile, configDir, log, consent, platform });
900
+ }
901
+
902
+ function readWorkerRouteReference(home, file) {
903
+ try { fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
904
+ const ref = JSON.parse(readOwnedFile(home, file, 'Gozar route reference'));
905
+ if (typeof ref?.home !== 'string' || !path.isAbsolute(ref.home) || (!ref.handle && typeof ref.operationId !== 'string')) {
906
+ fail('The saved Gozar route reference is invalid.');
907
+ }
908
+ return ref;
909
+ }
910
+
911
+ export function workerRouteReference(home, retained, view, custody) {
912
+ const operationId = reconcileRouteOperationId(retained?.operationId, view.operationId);
913
+ return {
914
+ home, handle: view.handle, custody,
915
+ ...(typeof operationId === 'string' && operationId.length ? { operationId } : {}),
916
+ };
917
+ }
918
+
919
+ export async function publishWorkerRoute({ o, env, gozar, url, secret, urlFile, configDir, log, consent = routeConsent(log), readReference = readWorkerRouteReference, write = writeAtomic, observeRoute = observeRetainedRoute, platform = process.platform }) {
920
+ const reference = path.join(configDir, 'route-reference.json');
921
+ let ref = readReference(o.home, reference);
922
+ const home = ref?.home ?? gozarHomeFor(env);
923
+ const custody = ref?.custody ?? routeCustodyPath({ HOME: os.homedir(), ...env }, home);
924
+ const target = o.lan ? `${o.lan.address}:${o.lan.port}` : `127.0.0.1:${o.port}`;
925
+ const external = !ref?.handle || ref.handle.kind === 'external';
926
+ const remember = value => {
927
+ const next = { ...value, custody };
928
+ write(reference, JSON.stringify(next));
929
+ ref = next;
930
+ };
931
+ gozar ??= await resolveGozar({ env, home, custody });
932
+ const observed = ref && await observeRoute(gozar, ref);
933
+ const view = observed?.state === 'recorded' ? observed.view : await ensureDurableRoute({
934
+ gozar, query: buildQuery({ home, origin: url, target, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${o.worker}` } }),
935
+ consent, remember, recovery: ref, external: true,
888
936
  });
937
+ if (!ref?.handle || (!ref.operationId && view.operationId)) remember(workerRouteReference(home, ref, view, custody));
938
+ const retainedInstall = () => {
939
+ const dir = unitDirFor(platform, env);
940
+ const unit = dir && path.join(dir, platform === 'darwin' ? `${launchLabel(o.worker)}.plist` : `dot-bridge-${o.worker}.service`);
941
+ const entry = file => {
942
+ if (!file) return undefined;
943
+ try { return fs.lstatSync(file, { throwIfNoEntry: false }); }
944
+ catch { return undefined; } // A failed stat cannot establish retention or replace the verification error.
945
+ };
946
+ return { homeRetained: entry(o.home)?.isDirectory() === true, serviceRetained: entry(unit)?.isFile() === true };
947
+ };
948
+ let retained;
949
+ try {
950
+ if (external) requireExternalRoute(view, url, target);
951
+ if (!isPublished(view) || view.published !== url) {
952
+ retained = retainedInstall();
953
+ const status = `Home ${retained.homeRetained ? 'retained' : 'not confirmed'}; service unit ${retained.serviceRetained ? 'retained' : 'not confirmed'}.`;
954
+ const error = routeFailure(view, `Gozar could not verify the public route. ${status} Retry the check with: ${publicRetryCommand(o, url)}. To remove this install: ${recoveryCommand(o)}`);
955
+ if (error.nextAction) log(error.nextAction.instructions ?? error.nextAction.label);
956
+ throw error;
957
+ }
958
+ } catch (error) {
959
+ error.partialSetup = {
960
+ phase: 'public_verification', ...(retained ?? retainedInstall()), resourceUrlRewritten: false,
961
+ };
962
+ throw error;
963
+ }
964
+ // The last atomic write occurs only after public verification succeeds.
965
+ write(urlFile, `${view.published}/${secret}/mcp\n`);
966
+ log(`Resource URL file (private, mode 0600): ${urlFile}`);
967
+ }
968
+
969
+ function routeConsent(log) {
970
+ return async candidate => {
971
+ for (const line of [...describeCandidate(candidate), ...describeDisclosure(candidate)]) log(line);
972
+ if (!process.stdin.isTTY) fail('This route needs your approval. Run the command in a terminal.');
973
+ const rl = (await import('node:readline/promises')).createInterface({ input: process.stdin, output: process.stdout });
974
+ try { return /^y(es)?$/i.test((await rl.question('Use this route? [y/N] ')).trim()); }
975
+ finally { rl.close(); }
976
+ };
889
977
  }
890
978
 
891
979
  // With --route, Gozar allocates (or finds) the durable route first; its origin is the bridge's public address. Nothing is written
892
980
  // before Gozar answers, and an owner who declines leaves nothing behind.
893
981
  async function allocateRoute(parsed, seams) {
894
982
  const env = seams.env ?? process.env;
895
- const gozar = seams.gozar ?? await resolveGozar();
896
- const query = buildQuery({ home: gozarHomeFor(env), target: `127.0.0.1:${parsed.port}`, route: parsed.route, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${parsed.worker}` } });
897
- const consent = seams.consent ?? (async candidate => {
898
- if (!process.stdin.isTTY) fail('this route needs your approval; run this in a terminal, or run `dalan setup --route NAME` first');
899
- for (const line of [...describeCandidate(candidate), ...describeDisclosure(candidate)]) console.log(line);
900
- const rl = (await import('node:readline')).createInterface({ input: process.stdin, output: process.stdout });
901
- const answer = await new Promise(resolve => rl.question('Use this route? [y/N] ', resolve)); rl.close();
902
- return ['y', 'yes'].includes(answer.trim().toLowerCase());
903
- });
904
- parsed.publicUrl = (await ensureDurableRoute({ gozar, query, consent })).origin;
983
+ const home = gozarHomeFor(env);
984
+ const gozar = seams.gozar ?? await resolveGozar({ env, home });
985
+ const query = buildQuery({ home, target: `127.0.0.1:${parsed.port}`, route: parsed.route, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${parsed.worker}` } });
986
+ const consent = seams.consent ?? routeConsent(seams.log ?? console.log);
987
+ const view = await ensureDurableRoute({ gozar, query, consent });
988
+ if (!view.origin) throw routeFailure(view, 'Gozar has not supplied the bridge address.');
989
+ parsed.publicUrl = view.origin;
990
+ parsed.routeView = view;
991
+ parsed.routeRef = workerRouteReference(home, null, view, routeCustodyPath({ HOME: os.homedir(), ...env }, home));
992
+ return gozar;
905
993
  }
906
994
 
907
995
  export function run(argv, seams = {}) {
908
996
  if (argv.includes('--help')) return runUnlocked(argv, seams);
909
997
  // Reject malformed arguments before creating the per-home lock directory.
910
998
  const parsed = parseOptions(argv, seams.platform ?? process.platform);
911
- if (parsed.route !== undefined) return allocateRoute(parsed, seams).then(() => runLocked(argv, seams, parsed));
999
+
912
1000
  return runLocked(argv, seams, parsed);
913
1001
  }
914
1002
 
@@ -931,5 +1019,12 @@ function runLocked(argv, seams, parsed) {
931
1019
 
932
1020
  if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
933
1021
  try { await run(process.argv.slice(2)); }
934
- catch (e) { console.error(`worker-bridge-setup: ${e.message}`); process.exit(1); }
1022
+ catch (e) {
1023
+ console.error(`worker-bridge-setup: ${e.message}`);
1024
+ if (e.partialSetup?.phase === 'public_verification') {
1025
+ const { homeRetained, serviceRetained } = e.partialSetup;
1026
+ console.error(`worker-bridge-setup: partial setup: home ${homeRetained ? 'retained' : 'not retained'}; service unit ${serviceRetained ? 'retained' : 'not retained'}; resource URL not rewritten.`);
1027
+ }
1028
+ process.exit(1);
1029
+ }
935
1030
  }
@@ -12,7 +12,13 @@ export class AckLedger {
12
12
  fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700});
13
13
  const existed=fs.existsSync(file);
14
14
  if(existed&&(fs.statSync(file).mode&0o777)!==0o600) throw new Error('acknowledgment ledger must be mode 0600');
15
- if(!existed) { const fd=fs.openSync(file,'wx',0o600); fs.closeSync(fd); }
15
+ if(!existed) {
16
+ let fd;
17
+ try { fd=fs.openSync(file,'wx',0o600); }
18
+ catch(error) { if(error?.code!=='EEXIST') throw error; }
19
+ if(fd!==undefined) fs.closeSync(fd);
20
+ }
21
+ if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('acknowledgment ledger must be mode 0600');
16
22
  this.db=new DatabaseSync(file);
17
23
  try {
18
24
  if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('acknowledgment ledger must be mode 0600');