@tnunamak/dalan 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +25 -68
  3. package/bin/dalan.mjs +9 -0
  4. package/bin/dot-worker.mjs +16 -2
  5. package/docs/chatgpt-worker-onboarding.md +10 -14
  6. package/docs/claude-worker-onboarding.md +9 -8
  7. package/docs/codex-to-muse.md +21 -35
  8. package/docs/connect-chatgpt.md +10 -16
  9. package/docs/dalan-upgrade.md +4 -2
  10. package/docs/local-agent-mcp.md +24 -4
  11. package/docs/manual-setup.md +2 -2
  12. package/docs/operations.md +10 -11
  13. package/docs/pull-workers.md +1 -2
  14. package/docs/service-setup.md +94 -170
  15. package/docs/setup-reference.md +5 -5
  16. package/docs/worker-clients.md +4 -4
  17. package/package.json +2 -3
  18. package/scripts/dalan-try-selfcheck.mjs +8 -7
  19. package/scripts/worker-bridge-setup.mjs +91 -81
  20. package/src/as-store.mjs +5 -3
  21. package/src/as.mjs +35 -26
  22. package/src/auth-check.mjs +53 -0
  23. package/src/cli-help.mjs +13 -14
  24. package/src/client-approval.mjs +57 -0
  25. package/src/client-convenience.mjs +166 -0
  26. package/src/client-conveniences.json +106 -0
  27. package/src/client-conveniences.schema.json +97 -0
  28. package/src/connect-cli.mjs +5 -5
  29. package/src/default-home.mjs +36 -0
  30. package/src/follow-current.mjs +25 -0
  31. package/src/gozar-routes.mjs +314 -0
  32. package/src/redirect-policy.mjs +61 -0
  33. package/src/route-setting.mjs +71 -12
  34. package/src/server.mjs +2 -0
  35. package/src/service-auto-update.mjs +8 -1
  36. package/src/service-launchd.mjs +166 -0
  37. package/src/service-update-runtime.mjs +40 -6
  38. package/src/service-update.mjs +20 -14
  39. package/src/service.mjs +175 -63
  40. package/src/setup.mjs +55 -44
  41. package/src/try-exposure.mjs +7 -657
  42. package/src/try-hosted.mjs +71 -101
  43. package/src/try-selfcheck.mjs +15 -8
  44. package/src/try.mjs +9 -13
  45. package/scripts/lib/expose-tailscale.mjs +0 -408
  46. package/src/try-hosted-clients.mjs +0 -46
@@ -0,0 +1,166 @@
1
+ // The macOS service backend: a LaunchAgent for the bridge and a second one that runs `dalan service update` every day.
2
+ // Everything here is plist text (pure) plus a thin launchctl seam, so Linux tests can fake launchctl. The shape follows the agent
3
+ // that scripts/worker-bridge-setup.mjs already runs on macOS 26 (domain user/UID, Aqua and Background sessions, an explicit kickstart).
4
+ //
5
+ // Rules this backend keeps:
6
+ // - The agent runs node by absolute path. `nodePath()` in service.mjs picks the stable Homebrew or mise symlink when node is one of those, so a
7
+ // node upgrade keeps working; any other node is recorded as is, and a move of that binary needs `dalan service install` again.
8
+ // - It runs the package through the home's `current` symlink, so the updater switches versions by repointing that link and restarting.
9
+ // - launchd has no pre-start step, so the agent runs `dalan service recover` first in a shell, and starts the server only if that succeeds.
10
+ // - KeepAlive restarts after a crash or an error exit, never after a clean exit. Logs live under the service home.
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
16
+
17
+ export const MARKER = 'Generated by dalan service install';
18
+ const SESSION_TYPES = ['Aqua', 'Background'];
19
+ const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
20
+ const fail = message => { throw new Error(message); };
21
+
22
+ export const launchdLabels = unit => ({ service: `org.dalan.${unit}`, update: `org.dalan.${unit}-update` });
23
+ export const launchAgentsDir = (env = process.env) => path.join(env.HOME || os.homedir(), 'Library', 'LaunchAgents');
24
+ const agentPath = (node) => [...new Set([path.dirname(node), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
25
+ const xml = text => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
26
+
27
+ function assertSafe(values) {
28
+ for (const [label, value] of Object.entries(values)) if (!path.isAbsolute(value) || !SAFE_PATH.test(value)) fail(`${label} is not a safe absolute path for a LaunchAgent: ${JSON.stringify(value)}`);
29
+ }
30
+
31
+ const dict = entries => ['<dict>', ...entries.flatMap(([key, value]) => [` <key>${xml(key)}</key>`, ...value.split('\n').map(line => ` ${line}`)]), '</dict>'].join('\n');
32
+ const str = value => `<string>${xml(value)}</string>`;
33
+ const arr = items => ['<array>', ...items.map(item => ` ${str(item)}`), '</array>'].join('\n');
34
+ const plist = (label, body) => ['<?xml version="1.0" encoding="UTF-8"?>',
35
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
36
+ `<!-- ${MARKER}. Remove with: dalan service uninstall -->`, '<plist version="1.0">', body, '</plist>', ''].join('\n');
37
+
38
+ export function servicePlist({ unit, node, home, port, enableWorkspace = false, enableT3 = false }) {
39
+ const current = path.join(home, 'current');
40
+ assertSafe({ home, node, current });
41
+ const { service } = launchdLabels(unit);
42
+ const env = { HOME: home, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_GOZAR_SERVICE: '1', DALAN_CATALOG_PROFILE: 'stable',
43
+ DALAN_ENABLE_WORKSPACE: enableWorkspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: enableT3 ? '1' : '0', DALAN_PORT: String(port), PATH: agentPath(node) };
44
+ const start = `${node} ${current}/bin/dalan.mjs service recover --home ${home} --quiet && exec ${node} ${current}/src/server.mjs`;
45
+ return plist(service, dict([
46
+ ['Label', str(service)],
47
+ ['ProgramArguments', arr(['/bin/sh', '-c', start])],
48
+ ['WorkingDirectory', str(current)],
49
+ ['EnvironmentVariables', dict(Object.entries(env).map(([key, value]) => [key, str(value)]))],
50
+ ['RunAtLoad', '<true/>'],
51
+ ['KeepAlive', dict([['SuccessfulExit', '<false/>']])],
52
+ ['ThrottleInterval', '<integer>5</integer>'],
53
+ ['LimitLoadToSessionType', arr(SESSION_TYPES)],
54
+ ['UMask', '<integer>63</integer>'],
55
+ ['StandardOutPath', str(path.join(home, 'logs', 'bridge.out.log'))],
56
+ ['StandardErrorPath', str(path.join(home, 'logs', 'bridge.err.log'))],
57
+ ]));
58
+ }
59
+
60
+ // The update agent runs once a day at a fixed minute between 03:00 and 03:59 that depends on the home, so many installs do not call the registry together.
61
+ export const updateSchedule = home => ({ Hour: 3, Minute: parseInt(createHash('sha256').update(home).digest('hex').slice(0, 4), 16) % 60 });
62
+
63
+ export function updatePlist({ unit, node, home }) {
64
+ const current = path.join(home, 'current');
65
+ assertSafe({ home, node, current });
66
+ const { update } = launchdLabels(unit), when = updateSchedule(home);
67
+ return plist(update, dict([
68
+ ['Label', str(update)],
69
+ ['ProgramArguments', arr([node, `${current}/bin/dalan.mjs`, 'service', 'update', '--home', home, '--json'])],
70
+ ['EnvironmentVariables', dict([['PATH', str(agentPath(node))]])],
71
+ ['StartCalendarInterval', dict([['Hour', `<integer>${when.Hour}</integer>`], ['Minute', `<integer>${when.Minute}</integer>`]])],
72
+ ['ProcessType', str('Background')],
73
+ ['Nice', '<integer>19</integer>'],
74
+ ['LowPriorityIO', '<true/>'],
75
+ ['LimitLoadToSessionType', arr(SESSION_TYPES)],
76
+ ['UMask', '<integer>63</integer>'],
77
+ ['StandardOutPath', str(path.join(home, 'logs', 'update.out.log'))],
78
+ ['StandardErrorPath', str(path.join(home, 'logs', 'update.err.log'))],
79
+ ]));
80
+ }
81
+
82
+ // ---- launchctl --------------------------------------------------------------------------------------------------------------------------
83
+ export function launchctl(args, { spawn = spawnSync, env = process.env } = {}) {
84
+ const result = spawn('launchctl', args, { encoding: 'utf8', env, timeout: 30000, maxBuffer: 1024 * 1024 });
85
+ return { status: result.error ? -1 : (result.status ?? -1), stdout: result.stdout ?? '', stderr: result.error ? String(result.error.message) : (result.stderr ?? '') };
86
+ }
87
+ const uidOf = seams => (seams.uid ?? process.getuid?.());
88
+ const domainOf = seams => `user/${uidOf(seams)}`;
89
+ export const isLoaded = (label, seams = {}) => launchctl(['print', `${domainOf(seams)}/${label}`], seams).status === 0;
90
+ const must = (result, what) => { if (result.status !== 0) fail(`${what} failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`); };
91
+
92
+ // Load the agent from its plist, then ask launchd to start it: on macOS 26 a bootstrapped agent can stay loaded and never spawn.
93
+ export function loadAgent({ label, plistFile }, seams = {}) {
94
+ const domain = domainOf(seams);
95
+ if (!isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
96
+ const kick = launchctl(['kickstart', `${domain}/${label}`], seams);
97
+ return { kicked: kick.status === 0, detail: kick.status === 0 ? '' : String(kick.stderr).trim() };
98
+ }
99
+
100
+ export function unloadAgent({ label }, seams = {}) {
101
+ if (!isLoaded(label, seams)) return false;
102
+ must(launchctl(['bootout', `${domainOf(seams)}/${label}`], seams), `launchctl bootout ${label}`);
103
+ return true;
104
+ }
105
+
106
+ // The updater's three actions for a launchd service. `daemon-reload` has no launchd meaning: the plist does not change on update.
107
+ export function controlLaunchd(receipt, action, seams = {}) {
108
+ const { service } = launchdLabels(receipt.unit), plistFile = path.join(receipt.unit_dir, `${service}.plist`);
109
+ if (action === 'daemon-reload') return;
110
+ if (action === 'stop') { unloadAgent({ label: service }, seams); return; }
111
+ if (action === 'restart') {
112
+ if (isLoaded(service, seams)) must(launchctl(['kickstart', '-k', `${domainOf(seams)}/${service}`], seams), `launchctl kickstart -k ${service}`);
113
+ else {
114
+ const { kicked, detail } = loadAgent({ label: service, plistFile }, seams);
115
+ if (!kicked) fail(`launchctl kickstart ${service} failed: ${detail}`);
116
+ }
117
+ return;
118
+ }
119
+ fail('unsupported service action');
120
+ }
121
+
122
+ // ---- plist files ------------------------------------------------------------------------------------------------------------------------
123
+ // Write a generated plist. A plist that already has exactly this text is left alone (returns false). A different one that carries our marker
124
+ // is replaced; anything else is refused so a hand-made agent is never overwritten.
125
+ export function writeAgentFile(file, text) {
126
+ let existing = null;
127
+ try { const info = fs.lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) fail(`${file} is not a regular file; refusing to replace it`); existing = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
128
+ if (existing === text) return false;
129
+ if (existing !== null && !existing.includes(MARKER)) fail(`${file} already exists and was not generated by dalan; refusing to overwrite it`);
130
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
131
+ const temp = `${file}.${process.pid}.tmp`;
132
+ fs.writeFileSync(temp, text, { mode: 0o644 });
133
+ fs.renameSync(temp, file);
134
+ return true;
135
+ }
136
+
137
+ export function lintPlist(file, { spawn = spawnSync } = {}) {
138
+ const result = spawn('plutil', ['-lint', file], { encoding: 'utf8' });
139
+ if (result.error) return null; // plutil is not installed (not macOS): not checked
140
+ return result.status === 0;
141
+ }
142
+
143
+ // Turn the daily update agent on or off. Off removes the agent from launchd and deletes its plist.
144
+ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
145
+ const { update } = launchdLabels(receipt.unit), file = path.join(receipt.unit_dir, `${update}.plist`);
146
+ if (enabled) {
147
+ fs.mkdirSync(path.join(home, 'logs'), { recursive: true, mode: 0o700 });
148
+ const changed = writeAgentFile(file, updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home }));
149
+ if (changed) unloadAgent({ label: update }, seams);
150
+ if (!isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
151
+ } else {
152
+ unloadAgent({ label: update }, seams);
153
+ fs.rmSync(file, { force: true });
154
+ }
155
+ return { timer: update };
156
+ }
157
+
158
+ export function removeAgents({ unit, unit_dir: dir }, seams = {}) {
159
+ const { service, update } = launchdLabels(unit), removed = [];
160
+ for (const label of [update, service]) {
161
+ if (unloadAgent({ label }, seams)) removed.push(`unloaded ${label}`);
162
+ const file = path.join(dir, `${label}.plist`);
163
+ if (fs.existsSync(file)) { if (!fs.readFileSync(file, 'utf8').includes(MARKER)) fail(`${file} was not generated by dalan; leaving it`); fs.rmSync(file); removed.push(`removed ${file}`); }
164
+ }
165
+ return removed;
166
+ }
@@ -1,20 +1,39 @@
1
1
  import fs from 'node:fs';
2
+ import { controlLaunchd } from './service-launchd.mjs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import http from 'node:http';
5
6
  import https from 'node:https';
6
7
  import net from 'node:net';
7
8
  import { spawn } from 'node:child_process';
8
- import { randomBytes } from 'node:crypto';
9
+ import { createHash, randomBytes } from 'node:crypto';
9
10
  import { fileURLToPath } from 'node:url';
10
11
  import { defaultPath } from './paths.mjs';
11
12
  import { initAsFiles } from './as-files.mjs';
12
13
 
13
14
  const PACKAGE = '@tnunamak/dalan';
14
15
  const PUBLIC_REGISTRY = 'https://registry.npmjs.org';
15
- const REPO = fileURLToPath(new URL('..', import.meta.url));
16
+ const REPO = path.resolve(fileURLToPath(new URL('..', import.meta.url)));
16
17
  const TIMEOUT = 30_000;
17
18
  const fail = message => { throw new Error(message); };
19
+ const MAX_TARBALL_BYTES = 200 * 1024 * 1024;
20
+
21
+ // npm 12 refuses a remote tarball URL as a dependency (allow-remote defaults to none), so the updater fetches the tarball itself,
22
+ // checks every byte against the registry's sha512 integrity, and hands npm only a local file. Works the same on npm 10, 11 and 12.
23
+ async function fetchTarball(url, integrity, { timeout = 120_000, fetchImpl = fetch } = {}) {
24
+ let bytes;
25
+ if (/^file:\/\//.test(url)) bytes = fs.readFileSync(fileURLToPath(url));
26
+ else {
27
+ const response = await fetchImpl(url, { signal: AbortSignal.timeout(timeout) });
28
+ if (!response.ok) fail(`release tarball download failed (${response.status})`);
29
+ const length = Number(response.headers.get('content-length'));
30
+ if (Number.isFinite(length) && length > MAX_TARBALL_BYTES) fail('release tarball is too large');
31
+ bytes = Buffer.from(await response.arrayBuffer());
32
+ }
33
+ if (bytes.length > MAX_TARBALL_BYTES) fail('release tarball is too large');
34
+ if (`sha512-${createHash('sha512').update(bytes).digest('base64')}` !== integrity) fail('release tarball integrity does not match registry metadata');
35
+ return bytes;
36
+ }
18
37
 
19
38
  function validRelease(value, { allowLocalTarball = false } = {}) {
20
39
  const localTarball = typeof value?.dist?.tarball === 'string' && (/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?\//.test(value.dist.tarball) || /^file:\/\//.test(value.dist.tarball));
@@ -46,7 +65,7 @@ function requestJson(url, { timeout = TIMEOUT, socketPath, headers = {}, allowHt
46
65
  res.on('aborted', () => finish(reject, new Error('response ended before completion')));
47
66
  res.on('error', error => finish(reject, error));
48
67
  res.on('end', () => {
49
- if (res.statusCode !== 200) return finish(reject, new Error(`request failed (${res.statusCode})`));
68
+ if (res.statusCode !== 200) return finish(reject, Object.assign(new Error(`request failed (${res.statusCode})`), { statusCode: res.statusCode }));
50
69
  try { finish(resolve, JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { finish(reject, new Error('invalid JSON response')); }
51
70
  });
52
71
  });
@@ -99,7 +118,9 @@ export async function installRelease(home, input, options = {}) {
99
118
  const registry = options.registry ?? PUBLIC_REGISTRY;
100
119
  if (!/^https:\/\//.test(registry) && !/^http:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/.test(registry)) fail('npm registry must use HTTPS');
101
120
  try {
102
- const pkg = { private: true, name: 'dalan-release-stage', version: '1.0.0', dependencies: { [PACKAGE]: release.dist.tarball } };
121
+ const tarballName = `dalan-${release.version}.tgz`;
122
+ fs.writeFileSync(path.join(staging, tarballName), await fetchTarball(release.dist.tarball, release.dist.integrity, { timeout: options.timeout, fetchImpl: options.fetch }), { mode: 0o600 });
123
+ const pkg = { private: true, name: 'dalan-release-stage', version: '1.0.0', dependencies: { [PACKAGE]: `file:./${tarballName}` } };
103
124
  fs.writeFileSync(path.join(staging, 'package.json'), JSON.stringify(pkg), { mode: 0o600 });
104
125
  const env = installEnv(staging), npm = options.npm ?? 'npm';
105
126
  const base = ['--ignore-scripts', '--no-audit', '--no-fund', '--registry', registry];
@@ -112,6 +133,7 @@ export async function installRelease(home, input, options = {}) {
112
133
  fs.writeFileSync(path.join(staging, '.dalan-release.json'), JSON.stringify({ name: PACKAGE, version: release.version, integrity: release.dist.integrity }), { mode: 0o600 });
113
134
  fs.rmSync(path.join(staging, '.cache'), { recursive: true, force: true });
114
135
  fs.rmSync(path.join(staging, '.npmrc'), { force: true });
136
+ fs.rmSync(path.join(staging, tarballName), { force: true });
115
137
  fs.renameSync(staging, path.join(versions, release.version));
116
138
  return destination;
117
139
  } catch (error) { fs.rmSync(staging, { recursive: true, force: true }); throw error; }
@@ -147,7 +169,18 @@ export async function probeService(home, _receipt, options = {}) {
147
169
  const timeout = options.timeout ?? TIMEOUT;
148
170
  if (!Number.isFinite(timeout) || timeout <= 0) fail('service probe timeout must be positive');
149
171
  const deadline = performance.now() + timeout;
150
- const value = validateProbe(await requestJson('http://localhost/service-check', { socketPath, headers: { 'x-operator-key': operator }, timeout }), expectedProbe(home, _receipt));
172
+ const expected = expectedProbe(home, _receipt);
173
+ let value;
174
+ try { value = validateProbe(await requestJson('http://localhost/service-check', { socketPath, headers: { 'x-operator-key': operator }, timeout }), expected); }
175
+ catch (error) {
176
+ // A 0.6.0 or 0.6.1 server answers on its admin socket but has no /service-check. That is a running legacy server with no update gate:
177
+ // the updater stops it, switches the package and starts it again. Its catalogs are unknown, so none are compared.
178
+ if (error.statusCode !== 404 || !_receipt?.port) throw error;
179
+ const left = deadline - performance.now();
180
+ if (left <= 0) fail('service probe timed out');
181
+ await checkLoopback(_receipt.port, left);
182
+ return { legacy: true, version: expected.expectedVersion, update_protocol: 0, port: _receipt.port, self_check: false, catalogs: null };
183
+ }
151
184
  const remaining = deadline - performance.now();
152
185
  if (remaining <= 0) fail('service probe timed out');
153
186
  await checkLoopback(value.port, remaining);
@@ -250,7 +283,8 @@ export async function probeCandidate(home, receipt, repo, options = {}) {
250
283
  export async function controlService(receipt, action, options = {}) {
251
284
  if (!['stop', 'restart', 'daemon-reload'].includes(action)) fail('unsupported service action');
252
285
  const unit = String(receipt.unit ?? '');
253
- if (!/^[A-Za-z0-9_.@-]+$/.test(unit)) fail('invalid systemd unit name');
286
+ if (!/^[A-Za-z0-9_.@-]+$/.test(unit)) fail('invalid service unit name');
287
+ if (receipt.platform === 'darwin') { (options.launchd ?? controlLaunchd)(receipt, action, options.launchdSeams); return; }
254
288
  const name = unit.endsWith('.service') ? unit : `${unit}.service`;
255
289
  await (options.run ?? run)('systemctl', ['--user', action, ...(action === 'daemon-reload' ? [] : [name])], { timeout: TIMEOUT });
256
290
  }
@@ -51,6 +51,8 @@ function completeCatalogs(a, b, workers) {
51
51
  function catalogsEqual(a, b, workers) {
52
52
  return completeCatalogs(a, b, workers) && canonicalCatalogs(a.catalogs) === canonicalCatalogs(b.catalogs);
53
53
  }
54
+ // A 0.6.0 or 0.6.1 server has no /service-check, so its catalogs are unknown (stored as {}); nothing can be compared against them.
55
+ const hasCatalogs = catalogs => !!catalogs && Object.keys(catalogs).length > 0;
54
56
  function releaseVersion(r, current) {
55
57
  if (!r || r.name !== PACKAGE || typeof r.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(r.version) || typeof r.dist?.integrity !== 'string' || !r.dist.integrity.startsWith('sha512-')) fail('registry returned invalid stable release metadata');
56
58
  const parts = s => s.split('.').map(Number), a = parts(r.version), b = parts(current);
@@ -126,8 +128,10 @@ function adoptInstall(receipt, home) {
126
128
  let text;
127
129
  try { const st = fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink()) fail('not a regular file'); text = fs.readFileSync(file, 'utf8'); }
128
130
  catch { fail(`cannot read the service unit to adopt this install: ${file}`); }
129
- const repo = text.match(/^WorkingDirectory=(.+)$/m)?.[1], exec = text.match(/^ExecStart=(\S+) (\S+)$/m);
130
- if (!repo || !exec || exec[2] !== `${repo}/src/server.mjs` || !path.isAbsolute(repo) || !path.isAbsolute(exec[1])) fail(`service unit does not contain a supported Dalan command: ${file}`);
131
+ // 0.6.0 and 0.6.1 wrote WorkingDirectory with a trailing slash; compare normalized paths and record the normalized repo.
132
+ const written = text.match(/^WorkingDirectory=(.+)$/m)?.[1], exec = text.match(/^ExecStart=(\S+) (\S+)$/m);
133
+ const repo = written && path.isAbsolute(written) ? path.resolve(written) : null;
134
+ if (!repo || !exec || !path.isAbsolute(exec[2]) || path.resolve(exec[2]) !== path.join(repo, 'src/server.mjs') || !path.isAbsolute(exec[1])) fail(`service unit does not contain a supported Dalan command: ${file}`);
131
135
  return { ...receipt, repo: receipt.repo ?? repo, node: receipt.node ?? exec[1], unit_dir: receipt.unit_dir ?? path.dirname(file) };
132
136
  }
133
137
  function rewriteUnit(file, current, home) {
@@ -135,7 +139,8 @@ function rewriteUnit(file, current, home) {
135
139
  const st = fs.lstatSync(file);
136
140
  if (!st.isFile() || st.isSymbolicLink()) fail(`service unit must be a regular file: ${file}`);
137
141
  const before = fs.readFileSync(file, 'utf8');
138
- const oldRepo = before.match(/^WorkingDirectory=(.+)$/m)?.[1];
142
+ const oldRepoWritten = before.match(/^WorkingDirectory=(.+)$/m)?.[1];
143
+ const oldRepo = oldRepoWritten && path.isAbsolute(oldRepoWritten) ? path.resolve(oldRepoWritten) : oldRepoWritten;
139
144
  const exec = before.match(/^ExecStart=(.+)$/m)?.[1];
140
145
  if (!oldRepo || !exec || !exec.endsWith('/src/server.mjs')) fail(`service unit does not contain a supported Dalan command: ${file}`);
141
146
  const after = before.split('\n').map(line => /^WorkingDirectory=/.test(line) ? `WorkingDirectory=${current}` : /^ExecStart=/.test(line) ? line.replace(/\/src\/server\.mjs(?:\s.*)?$/, `${path.sep}src${path.sep}server.mjs`) : line).join('\n');
@@ -182,7 +187,7 @@ function readJournal(home) {
182
187
  const oldReceipt = tx?.oldReceipt;
183
188
  if (tx.home !== home || !oldReceipt || oldReceipt.home !== home || oldReceipt.schema_version !== 1 || !oldReceipt.unit ||
184
189
  !tx.oldRepo || !tx.oldVersion || !tx.snapshot || !['prepared', 'switched', 'committed'].includes(tx.phase)) fail('invalid interrupted update transaction');
185
- if (tx.unitFile !== (oldReceipt.unit ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
190
+ if (tx.unitFile !== (oldReceipt.unit && oldReceipt.platform !== 'darwin' ? unitPath(oldReceipt, home) : null) || !tx.oldCatalogs || typeof tx.oldCatalogs !== 'object') fail('update transaction control data is invalid');
186
191
  if (path.resolve(tx.snapshot) !== path.join(home, 'update-backup', 'snapshot')) fail('update transaction snapshot path is invalid');
187
192
  return { file, tx };
188
193
  }
@@ -228,13 +233,13 @@ async function recover(home, control, probe, healthTimeoutMs) {
228
233
  if (tx.phase === 'prepared') {
229
234
  await control(oldReceipt, 'restart');
230
235
  const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
231
- if (live.version !== tx.oldVersion || tx.oldCatalogs && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs))) fail('interrupted update recovery could not verify old service');
236
+ if (live.version !== tx.oldVersion || hasCatalogs(tx.oldCatalogs) && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs))) fail('interrupted update recovery could not verify old service');
232
237
  } else {
233
238
  validateSnapshot(tx);
234
239
  await control(oldReceipt, 'stop'); restoreFiles(home, tx);
235
240
  await control(oldReceipt, 'daemon-reload'); await control(oldReceipt, 'restart');
236
241
  const live = await probeReady(probe, home, { ...oldReceipt, repo: tx.oldRepo }, healthTimeoutMs);
237
- if (tx.oldCatalogs && (live.version !== tx.oldVersion || !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs)))) fail('interrupted update recovery restored selection but old service health failed');
242
+ if (tx.oldCatalogs && (live.version !== tx.oldVersion || hasCatalogs(tx.oldCatalogs) && !catalogsEqual({ catalogs: tx.oldCatalogs }, live, Object.keys(tx.oldCatalogs)))) fail('interrupted update recovery restored selection but old service health failed');
238
243
  }
239
244
  discardJournal(home, tx);
240
245
  }
@@ -289,13 +294,13 @@ export async function updateService({ home, check = false, yes = false, retry =
289
294
  if (candidate !== path.join(versions, r.version, 'node_modules', '@tnunamak', 'dalan') || !candidate.startsWith(`${versions}${path.sep}`) || fs.realpathSync(candidate) !== candidate) fail('candidate repository does not match exact package version path');
290
295
  const packageInfo = JSON.parse(fs.readFileSync(path.join(candidate, 'package.json'), 'utf8'));
291
296
  if (packageInfo.name !== PACKAGE || packageInfo.version !== r.version) fail('installed candidate package identity does not match registry release');
292
- const base = await probe(home, receipt);
297
+ const base = await probe(home, receipt), legacy = base.legacy === true;
293
298
  const configBeforeCandidate = configurationDigest(home, receipt);
294
299
  const tested = await candidateProbe(home, receipt, candidate);
295
300
  if (configurationDigest(home, receipt) !== configBeforeCandidate) fail('service configuration changed during candidate self-check; retry update');
296
301
  if (base.version !== oldVersion || tested.version !== r.version) fail('service probe returned an unexpected package version');
297
- if (!completeCatalogs(base, tested, workers)) fail('candidate self-check failed or worker catalogs are incomplete');
298
- const changedCatalog = !catalogsEqual(base, tested, workers);
302
+ if (!completeCatalogs(legacy ? tested : base, tested, workers)) fail('candidate self-check failed or worker catalogs are incomplete');
303
+ const changedCatalog = !legacy && !catalogsEqual(base, tested, workers);
299
304
  if (changedCatalog && !yes) {
300
305
  result = { outcome: 'connector_refresh_required', current_version: oldVersion, candidate_version: r.version, connector_refresh_required: true, message: 'Worker tool catalogs changed. Run dalan service update --yes with the same --home to switch, then refresh hosted connectors.' };
301
306
  prune(home, oldVersion, r.version);
@@ -304,11 +309,12 @@ export async function updateService({ home, check = false, yes = false, retry =
304
309
  // A catalog difference requires explicit consent; exact parity may proceed without it.
305
310
  const digestBeforeRecheck = configurationDigest(home, receipt);
306
311
  const liveAgain = await probe(home, receipt);
307
- if (liveAgain.version !== oldVersion || !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
312
+ if (liveAgain.version !== oldVersion || !legacy && !catalogsEqual(base, liveAgain, workers)) fail('live worker catalog changed during update; retry after connector refresh');
308
313
  if (configurationDigest(home, receipt) !== digestBeforeRecheck || digestBeforeRecheck !== configBeforeCandidate) fail('service configuration changed during update; retry after connector refresh');
309
- const unitFile = receipt.unit ? unitPath(receipt, home) : null;
314
+ // A macOS agent runs the package through the home's `current` link, so a switch needs no plist rewrite.
315
+ const unitFile = receipt.unit && receipt.platform !== 'darwin' ? unitPath(receipt, home) : null;
310
316
  const txDir = path.join(home, 'update-backup'); privateDir(txDir);
311
- const tx = { home, oldRepo, candidate, snapshot: path.join(txDir, 'snapshot'), unitFile, oldUnit: unitFile && fs.existsSync(unitFile) ? fs.readFileSync(unitFile, 'utf8') : null, oldCatalogs: base.catalogs, oldVersion, oldReceipt: { ...receipt }, phase: 'prepared' };
317
+ const tx = { home, oldRepo, candidate, snapshot: path.join(txDir, 'snapshot'), unitFile, oldUnit: unitFile && fs.existsSync(unitFile) ? fs.readFileSync(unitFile, 'utf8') : null, oldCatalogs: base.catalogs ?? {}, oldVersion, oldReceipt: { ...receipt }, phase: 'prepared' };
312
318
  if (unitFile && tx.oldUnit == null) fail(`service unit is missing: ${unitFile}`);
313
319
  atomic(path.join(home, 'update-transaction.json'), JSON.stringify(tx));
314
320
  try {
@@ -342,7 +348,7 @@ export async function updateService({ home, check = false, yes = false, retry =
342
348
  throw error;
343
349
  }
344
350
  tx.phase = 'committed';
345
- result = { outcome: 'updated', previous_version: oldVersion, version: r.version };
351
+ result = { outcome: 'updated', previous_version: oldVersion, version: r.version, ...(legacy ? { adopted_legacy_server: true } : {}) };
346
352
  try { fs.rmSync(failedFile(home), { force: true }); } catch { /* stale record only skips the same release */ }
347
353
  const cleanupWarnings = [];
348
354
  try { fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); } catch (error) { cleanupWarnings.push(`transaction marker cleanup failed: ${error.message}`); }
@@ -362,7 +368,7 @@ export async function updateService({ home, check = false, yes = false, retry =
362
368
  if (tx.phase === 'switched') for (const item of ['.config', '.local']) replaceTree(path.join(txDir, 'snapshot', item), path.join(home, item));
363
369
  await control(receipt, 'daemon-reload'); await control(receipt, 'restart');
364
370
  const restored = await probeReady(probe, home, { ...receipt, repo: oldRepo }, healthTimeoutMs);
365
- if (restored.version !== oldVersion || !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
371
+ if (restored.version !== oldVersion || !legacy && !catalogsEqual(base, restored, workers)) fail('old service health verification failed');
366
372
  fs.rmSync(path.join(home, 'update-transaction.json'), { force: true }); fs.rmSync(txDir, { recursive: true, force: true });
367
373
  } catch (e) { rollbackError = e; }
368
374
  if (rollbackError) { const e = new Error(`update failed: ${error.message}; rollback failed: ${rollbackError.message}`); e.updateOutcome = 'rollback_failed'; throw e; }