@tnunamak/dalan 0.8.1 → 0.8.3

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 +61 -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 +136 -21
  100. package/src/service-update.mjs +207 -51
  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
@@ -19,7 +19,10 @@ const SESSION_TYPES = ['Aqua', 'Background'];
19
19
  const SAFE_PATH = /^[A-Za-z0-9_@+=:,./-]+$/;
20
20
  const fail = message => { throw new Error(message); };
21
21
 
22
- export const launchdLabels = unit => ({ service: `org.dalan.${unit}`, update: `org.dalan.${unit}-update` });
22
+ export const launchdLabels = unit => {
23
+ if (typeof unit !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.@-]*$/.test(unit)) fail('invalid LaunchAgent unit name');
24
+ return { service: `org.dalan.${unit}`, update: `org.dalan.${unit}-update` };
25
+ };
23
26
  export const launchAgentsDir = (env = process.env) => path.join(env.HOME || os.homedir(), 'Library', 'LaunchAgents');
24
27
  const agentPath = (node) => [...new Set([path.dirname(node), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
25
28
  const xml = text => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -36,6 +39,7 @@ const plist = (label, body) => ['<?xml version="1.0" encoding="UTF-8"?>',
36
39
  `<!-- ${MARKER}. Remove with: dalan service uninstall -->`, '<plist version="1.0">', body, '</plist>', ''].join('\n');
37
40
 
38
41
  export function servicePlist({ unit, node, home, port, enableWorkspace = false, enableT3 = false }) {
42
+ if (!Number.isInteger(port) || port < 1 || port > 65535) fail('LaunchAgent port must be an integer from 1 to 65535');
39
43
  const current = path.join(home, 'current');
40
44
  assertSafe({ home, node, current });
41
45
  const { service } = launchdLabels(unit);
@@ -5,14 +5,17 @@ import { DatabaseSync } from 'node:sqlite';
5
5
  // Keep the inode: deleting a lock file would let a new caller lock a different file.
6
6
  // SQLite's exclusive lock is released by the kernel even if the updater is killed.
7
7
  export function acquireUpdateLock(home) {
8
- const file = path.join(home, 'update-lock.sqlite');
9
- const fd = fs.openSync(file, 'a', 0o600);
8
+ return acquirePrivateLock(path.join(home, 'update-lock.sqlite'), 'another service update is already running');
9
+ }
10
+
11
+ export function acquirePrivateLock(file, busyMessage) {
12
+ const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW, 0o600);
10
13
  fs.closeSync(fd);
11
14
  const info = fs.lstatSync(file);
12
- if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service update lock must be a private regular file');
15
+ if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600) throw new Error('service lock must be a private regular file');
13
16
  const db = new DatabaseSync(file);
14
17
  try { db.exec('PRAGMA busy_timeout=0; BEGIN EXCLUSIVE'); }
15
- catch (error) { db.close(); if (error.errcode === 5 || error.errcode === 6) throw new Error('another service update is already running'); throw error; }
18
+ catch (error) { db.close(); if (error.errcode === 5 || error.errcode === 6) throw new Error(busyMessage); throw error; }
16
19
  let held = true;
17
20
  return () => {
18
21
  if (!held) return;
@@ -5,10 +5,11 @@ import path from 'node:path';
5
5
  import http from 'node:http';
6
6
  import https from 'node:https';
7
7
  import net from 'node:net';
8
- import { spawn } from 'node:child_process';
8
+ import { execFileSync, spawn } from 'node:child_process';
9
9
  import { createHash, randomBytes } from 'node:crypto';
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { defaultPath } from './paths.mjs';
12
+ import { adminSocketPath } from './admin-socket.mjs';
12
13
  import { initAsFiles } from './as-files.mjs';
13
14
 
14
15
  const PACKAGE = '@tnunamak/dalan';
@@ -18,13 +19,87 @@ const TIMEOUT = 30_000;
18
19
  const fail = message => { throw new Error(message); };
19
20
  const MAX_TARBALL_BYTES = 200 * 1024 * 1024;
20
21
 
22
+ function splitSystemdWords(value) {
23
+ const words = [];
24
+ let word = '', quote = null;
25
+ for (let i = 0; i < value.length; i++) {
26
+ const char = value[i];
27
+ if (char === '\\' && i + 1 < value.length) { word += char + value[++i]; continue; }
28
+ if (quote) {
29
+ if (char === quote) quote = null;
30
+ else word += char;
31
+ } else if (char === '"' || char === "'") quote = char;
32
+ else if (/\s/.test(char)) { if (word) { words.push(word); word = ''; } }
33
+ else word += char;
34
+ }
35
+ if (quote) fail('systemd returned an invalid service environment');
36
+ if (word) words.push(word);
37
+ return words;
38
+ }
39
+
40
+ function unescapeSystemdValue(value) {
41
+ return value.replace(/\\(x[0-9a-fA-F]{2}|[\\nrtse])/g, (_, code) => {
42
+ if (code[0] === 'x') return String.fromCharCode(Number.parseInt(code.slice(1), 16));
43
+ return ({ '\\': '\\', n: '\n', r: '\r', t: '\t', s: ' ', e: '\x1b' })[code];
44
+ });
45
+ }
46
+
47
+ function effectiveServiceEnvironment(receipt, options = {}) {
48
+ if (receipt.platform === 'darwin' || !receipt.unit) return {};
49
+ const unit = String(receipt.unit).endsWith('.service') ? String(receipt.unit) : `${receipt.unit}.service`;
50
+ if (!/^[A-Za-z0-9_.@-]+\.service$/.test(unit)) fail('invalid service unit name in receipt');
51
+ let output;
52
+ try {
53
+ output = (options.execFileSync ?? execFileSync)('systemctl', ['--user', 'show', '--property=Environment', '--value', unit], {
54
+ encoding: 'utf8', timeout: 10_000, env: { ...process.env, LC_ALL: 'C' },
55
+ });
56
+ } catch { fail('could not read the effective service environment'); }
57
+ const result = {};
58
+ for (const assignment of splitSystemdWords(String(output))) {
59
+ const equals = assignment.indexOf('=');
60
+ if (equals < 1) continue;
61
+ const name = assignment.slice(0, equals);
62
+ if (Object.hasOwn(CATALOG_SETTINGS, name)) result[name] = unescapeSystemdValue(assignment.slice(equals + 1));
63
+ }
64
+ return result;
65
+ }
66
+
67
+ // Only settings that shape the tool catalog reach the candidate; paths, ports, credentials and every other unit value stay behind.
68
+ const CATALOG_SETTINGS = Object.freeze({
69
+ DALAN_CATALOG_PROFILE: ['stable', 'questions-v1', 'protocol-v0', 'legacy-v46', 'batch-claim-v1'],
70
+ DALAN_GOZAR_SERVICE: ['0', '1'],
71
+ DALAN_ENABLE_T3_TOOLS: ['0', '1'],
72
+ DALAN_ENABLE_WORKSPACE: ['0', '1'],
73
+ });
74
+
75
+ function catalogSettings(serviceEnv) {
76
+ const result = {};
77
+ for (const [key, value] of Object.entries(serviceEnv ?? {})) {
78
+ if (!Object.hasOwn(CATALOG_SETTINGS, key)) continue;
79
+ if (!CATALOG_SETTINGS[key].includes(value)) fail(`service unit sets an unsupported ${key}`);
80
+ result[key] = value;
81
+ }
82
+ return result;
83
+ }
84
+
21
85
  // npm 12 refuses a remote tarball URL as a dependency (allow-remote defaults to none), so the updater fetches the tarball itself,
22
86
  // 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 } = {}) {
87
+ export async function fetchTarball(url, integrity, { timeout = 120_000, fetchImpl = fetch } = {}) {
24
88
  let bytes;
25
89
  if (/^file:\/\//.test(url)) bytes = fs.readFileSync(fileURLToPath(url));
26
90
  else {
27
- const response = await fetchImpl(url, { signal: AbortSignal.timeout(timeout) });
91
+ const signal = AbortSignal.timeout(timeout);
92
+ const origin = new URL(url).origin;
93
+ let target = new URL(url), response;
94
+ for (let hops = 0; ; hops++) {
95
+ if (target.origin !== origin || target.username || target.password) fail('release tarball redirect left its approved origin');
96
+ response = await fetchImpl(target.href, { signal, redirect: 'manual' });
97
+ if (![301, 302, 303, 307, 308].includes(response.status)) break;
98
+ const location = response.headers.get('location');
99
+ await response.body?.cancel();
100
+ if (hops >= 5 || !location) fail('release tarball redirect did not resolve');
101
+ target = new URL(location, target);
102
+ }
28
103
  if (!response.ok) fail(`release tarball download failed (${response.status})`);
29
104
  const length = Number(response.headers.get('content-length'));
30
105
  if (Number.isFinite(length) && length > MAX_TARBALL_BYTES) fail('release tarball is too large');
@@ -163,7 +238,7 @@ function expectedProbe(home, receipt, repo) {
163
238
  }
164
239
 
165
240
  export async function probeService(home, _receipt, options = {}) {
166
- const socketPath = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
241
+ const socketPath = adminSocketPath(defaultPath(home, '.local/share/dot-bridge'));
167
242
  const operator = fs.readFileSync(defaultPath(home, '.config/dot-bridge', 'operator.key'), 'utf8').trim();
168
243
  if (!operator || operator.length > 1024) fail('service operator key is invalid');
169
244
  const timeout = options.timeout ?? TIMEOUT;
@@ -212,15 +287,29 @@ function prepareProbeConfig(from, to) {
212
287
  fs.writeFileSync(path.join(target, 'operator.key'), `${randomBytes(32).toString('hex')}\n`, { mode: 0o600 });
213
288
  }
214
289
 
215
- async function stopChild(child) {
216
- if (!child || child.exitCode !== null || child.signalCode !== null || child.spawned === false) return;
217
- if (!child.pid) return;
218
- child.kill('SIGTERM');
219
- let timer;
220
- await Promise.race([new Promise(resolve => child.once('close', resolve)), new Promise(resolve => { timer = setTimeout(resolve, 3000); })]);
221
- clearTimeout(timer);
222
- if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
223
- if (child.exitCode === null && child.signalCode === null && child.spawned !== false) await new Promise(resolve => child.once('close', resolve));
290
+ function waitForChildClose(child, timeoutMs) {
291
+ return new Promise(resolve => {
292
+ let timer;
293
+ const finish = closed => {
294
+ clearTimeout(timer);
295
+ child.removeListener('close', onClose);
296
+ resolve(closed);
297
+ };
298
+ const onClose = () => finish(true);
299
+ child.once('close', onClose);
300
+ timer = setTimeout(() => finish(false), timeoutMs);
301
+ });
302
+ }
303
+
304
+ export async function stopChild(child, { termTimeoutMs = 3000, killTimeoutMs = 5000 } = {}) {
305
+ if (!child || child.exitCode !== null || child.signalCode !== null || child.spawned === false || !child.pid) return true;
306
+ const termWait = waitForChildClose(child, termTimeoutMs);
307
+ try { child.kill('SIGTERM'); } catch { /* a probe child may exit while it is being stopped */ }
308
+ if (await termWait) return true;
309
+ if (child.exitCode !== null || child.signalCode !== null || child.spawned === false) return true;
310
+ const killWait = waitForChildClose(child, killTimeoutMs);
311
+ try { child.kill('SIGKILL'); } catch { /* bounded cleanup must not replace the probe result */ }
312
+ return await killWait || child.exitCode !== null || child.signalCode !== null || child.spawned === false;
224
313
  }
225
314
 
226
315
  async function requireCatalogGuard(repo, env, receipt, options) {
@@ -232,8 +321,8 @@ async function requireCatalogGuard(repo, env, receipt, options) {
232
321
  child.stdout?.on('data', chunk => { if (stdout.length < 8192) stdout += chunk.toString().slice(0, 8192 - stdout.length); });
233
322
  child.stderr?.on('data', chunk => { if (stderr.length < 8192) stderr += chunk.toString().slice(0, 8192 - stderr.length); });
234
323
  try {
235
- const deadline = Date.now() + (options.guardTimeoutMs ?? 10_000);
236
- while (Date.now() < deadline) {
324
+ const deadline = performance.now() + (options.guardTimeoutMs ?? 10_000);
325
+ while (performance.now() < deadline) {
237
326
  if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
238
327
  if (/MCP listening|admin socket/.test(stdout)) fail('candidate started despite mismatched service catalog pin');
239
328
  if (closed) break;
@@ -245,6 +334,18 @@ async function requireCatalogGuard(repo, env, receipt, options) {
245
334
  } finally { await stopChild(child); }
246
335
  }
247
336
 
337
+ // Only fixed diagnostics authored by this module; never propagate socket or filesystem data.
338
+ const SAFE_CANDIDATE_PROBE_FAILURES = new Set([
339
+ 'service self-check response is incomplete',
340
+ 'service self-check returned an invalid worker catalog',
341
+ 'service self-check worker set does not match configuration',
342
+ 'service self-check version does not match selected package',
343
+ 'worker configuration is invalid for service self-check',
344
+ 'service operator key is invalid',
345
+ 'service probe timeout must be positive',
346
+ 'service probe timed out',
347
+ ]);
348
+
248
349
  export async function probeCandidate(home, receipt, repo, options = {}) {
249
350
  const scratchBase = path.join(os.homedir(), '.tmp');
250
351
  fs.mkdirSync(scratchBase, { recursive: true, mode: 0o700 });
@@ -253,7 +354,14 @@ export async function probeCandidate(home, receipt, repo, options = {}) {
253
354
  let child;
254
355
  try {
255
356
  prepareProbeConfig(home, scratch);
256
- const env = { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: scratch, NODE_ENV: 'production', DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_PORT: '0', DALAN_CATALOG_PROFILE: 'stable', DALAN_ENABLE_WORKSPACE: receipt.enable_workspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: receipt.enable_t3 ? '1' : '0' };
357
+ const serviceEnv = await (options.serviceEnvironment?.(receipt) ?? effectiveServiceEnvironment(receipt, options));
358
+ const inherited = catalogSettings(serviceEnv);
359
+ const env = {
360
+ PATH: process.env.PATH ?? '/usr/bin:/bin', NODE_ENV: 'production',
361
+ DALAN_ENABLE_WORKSPACE: receipt.enable_workspace ? '1' : '0', DALAN_ENABLE_T3_TOOLS: receipt.enable_t3 ? '1' : '0',
362
+ ...inherited,
363
+ HOME: scratch, DALAN_HOME: scratch, DALAN_AUTH_MODE: 'builtin', DALAN_BIND_HOST: '127.0.0.1', DALAN_PORT: '0',
364
+ };
257
365
  const configDir = defaultPath(scratch, '.config/dot-bridge');
258
366
  const pinFile = path.join(configDir, 'service-catalog.json');
259
367
  const version = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version;
@@ -264,15 +372,22 @@ export async function probeCandidate(home, receipt, repo, options = {}) {
264
372
  let spawnError = null, closed = false;
265
373
  child.on('error', error => { spawnError = error; });
266
374
  child.once('close', () => { closed = true; });
267
- const deadline = Date.now() + (options.startupTimeoutMs ?? 20_000);
268
- let result;
269
- while (Date.now() < deadline) {
375
+ const deadline = performance.now() + (options.startupTimeoutMs ?? 20_000);
376
+ let result, lastSafeProbeFailure;
377
+ const probe = options.probeService ?? probeService;
378
+ while (performance.now() < deadline) {
270
379
  if (spawnError) fail(`candidate service could not start: ${spawnError.message}`);
271
380
  if (closed) fail('candidate service exited before self-check');
272
381
  if (child.exitCode !== null || child.signalCode !== null) fail('candidate service exited before self-check');
273
- try { result = await probeService(scratch, { ...receipt, repo }); break; } catch { await new Promise(resolve => setTimeout(resolve, 150)); }
382
+ try { result = await probe(scratch, { ...receipt, repo }); break; }
383
+ catch (error) {
384
+ if (error instanceof Error && SAFE_CANDIDATE_PROBE_FAILURES.has(error.message)) lastSafeProbeFailure = error.message;
385
+ await new Promise(resolve => setTimeout(resolve, 150));
386
+ }
274
387
  }
275
- if (!result) fail('candidate service did not pass its self-check before timeout');
388
+ if (!result) fail(lastSafeProbeFailure
389
+ ? `candidate service did not pass its self-check: ${lastSafeProbeFailure}`
390
+ : 'candidate service did not pass its self-check before timeout');
276
391
  return result;
277
392
  } finally {
278
393
  await stopChild(child);