@tnunamak/dalan 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -1,13 +1,15 @@
1
1
  import { defaultPath } from './paths.mjs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
- import { assertPrivateDir, untrusted, writeAtomic } from './as-files.mjs';
4
+ import { createHash } from 'node:crypto';
5
+ import { request as httpRequest } from 'node:http';
6
+ import { assertPrivateDir, isLoopbackCallback, untrusted, writeAtomic } from './as-files.mjs';
5
7
  import { normalizeCode, PAIRING_MINUTES } from './as-files.mjs';
6
8
  const WAKE_POLL_SECONDS = 60;
7
9
 
8
10
  // `dalan connect ...`: the owner's side of the built-in authorization server. Every call goes through the owner Unix
9
11
  // socket with the operator key; none of it exists on the public listener.
10
- const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
12
+ const USAGE = 'usage: dalan connect add-client --redirect-uri URI [--name NAME] [--json] | clients [--json] | remove-client CLIENT_ID | start --worker NAME [--minutes N] | stop | reset | pending | approve CODE --worker NAME [--confirm-redirect URI] [--replace] | complete URL --worker NAME [--replace] [--json] | list | revoke NAME | allow-callback PATTERN | signal-token [--worker NAME] [--rotate] [--json]';
11
13
 
12
14
  // Terminal-safe text: vendor-supplied strings never reach the terminal as raw bytes.
13
15
  const q = value => JSON.stringify(String(value ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim());
@@ -34,7 +36,153 @@ export function formatClients(result) {
34
36
  ].join('\n')).join('\n\n');
35
37
  }
36
38
 
37
- export async function connectCommand(args, { request, operator, option, json }) {
39
+ const fingerprint = value => createHash('sha256').update(value).digest('base64url');
40
+ const redirectStatus = status => [301, 302, 303, 307, 308].includes(status);
41
+ const authorityEndpoint = url => url.origin + url.pathname;
42
+
43
+ // A short-lived, one-issuer in-memory cookie jar. No cookie or operator header is
44
+ // sent with the final local callback. No redirect is followed by the HTTP client.
45
+ function interactionBrowser(issuer, signal) {
46
+ const jar = new Map();
47
+ return async function get(url, phaseSignal = signal) {
48
+ if (url.origin !== issuer.origin || url.username || url.password || url.hash) throw new Error('Bridge sent an unexpected authorization redirect.');
49
+ const now = Date.now();
50
+ const headers = {};
51
+ const cookies = [...jar.values()].filter(c => c.expires > now && (!c.secure || url.protocol === 'https:')
52
+ && (url.pathname === c.path || url.pathname.startsWith(c.path.endsWith('/') ? c.path : c.path + '/')));
53
+ if (cookies.length) headers.cookie = cookies.sort((a, b) => b.path.length - a.path.length).map(c => c.part).join('; ');
54
+ let response;
55
+ try { response = await fetch(url, { headers, signal: phaseSignal, redirect: 'manual' }); }
56
+ catch { throw new Error('Could not load the bridge authorization page.'); }
57
+ const cookieHeaders = response.headers.getSetCookie();
58
+ for (const line of cookieHeaders) {
59
+ const [part, ...attrs] = line.split(';').map(s => s.trim());
60
+ const name = part.slice(0, part.indexOf('='));
61
+ if (!name || !/^[A-Za-z0-9_.-]+$/.test(name) || /[\r\n]/.test(part)) continue;
62
+ const options = new Map(attrs.map(attr => {
63
+ const i = attr.indexOf('=');
64
+ return i < 0 ? [attr.toLowerCase(), true] : [attr.slice(0, i).toLowerCase(), attr.slice(i + 1)];
65
+ }));
66
+ // The authorization server's interaction cookies are host-only.
67
+ if (options.has('domain')) continue;
68
+ const candidate = options.get('path');
69
+ const cookiePath = typeof candidate === 'string' && candidate.startsWith('/') ? candidate : (url.pathname.slice(0, url.pathname.lastIndexOf('/')) || '/');
70
+ const maxAge = options.has('max-age') ? Number(options.get('max-age')) : NaN;
71
+ const expiresAt = options.has('expires') ? Date.parse(options.get('expires')) : NaN;
72
+ const expires = Number.isFinite(maxAge) ? now + maxAge * 1000 : Number.isFinite(expiresAt) ? expiresAt : Infinity;
73
+ const key = name + '\0' + cookiePath;
74
+ if (expires <= now) jar.delete(key);
75
+ else jar.set(key, { part, path: cookiePath, secure: options.has('secure'), expires });
76
+ }
77
+ const location = response.headers.get('location');
78
+ if (response.body) await response.body.cancel().catch(() => {});
79
+ return { status: response.status, location };
80
+ };
81
+ }
82
+
83
+ function nextUrl(response, base) {
84
+ if (!redirectStatus(response.status) || !response.location) return null;
85
+ try {
86
+ const url = new URL(response.location, base);
87
+ return !url.username && !url.password && !url.hash ? url : null;
88
+ } catch { return null; }
89
+ }
90
+
91
+ function isLocalRedirect(raw) {
92
+ if (typeof raw !== 'string' || !/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?(?:\/|\?|$)/i.test(raw)) return false;
93
+ try { return isLoopbackCallback(new URL(raw)); } catch { return false; }
94
+ }
95
+
96
+ function sameLocalCallback(given, expected, original, issuer) {
97
+ // The callback carries code/state/iss, so check the loopback form without its query; the rest must match the approved redirect.
98
+ if (!given || given.username || given.password || given.hash || !isLocalRedirect(given.origin + given.pathname)
99
+ || given.origin !== expected.origin || given.pathname !== expected.pathname) return false;
100
+ if (given.searchParams.getAll('code').length !== 1 || !given.searchParams.get('code')
101
+ || given.searchParams.has('error') || given.searchParams.getAll('state').length > 1
102
+ || given.searchParams.get('state') !== original.searchParams.get('state')
103
+ || (given.searchParams.has('iss') && (given.searchParams.getAll('iss').length !== 1 || given.searchParams.get('iss') !== issuer.href))) return false;
104
+ const params = new URLSearchParams(given.searchParams);
105
+ for (const key of ['code', 'state', 'iss', 'session_state']) params.delete(key);
106
+ return params.toString() === expected.searchParams.toString();
107
+ }
108
+
109
+ function sendLocalCallback(url, signal) {
110
+ // No proxy, cookie, referrer or redirect handling. localhost is resolved only
111
+ // against literal loopback addresses, regardless of machine DNS configuration.
112
+ const loopbacks = [{ address: '127.0.0.1', family: 4 }, { address: '::1', family: 6 }];
113
+ return new Promise((resolve, reject) => {
114
+ const req = httpRequest(url, { agent: false, signal, autoSelectFamily: true,
115
+ lookup(_host, options, done) { if (options.all) done(null, loopbacks); else done(null, loopbacks[0].address, 4); },
116
+ }, response => {
117
+ const ok = response.statusCode >= 200 && response.statusCode < 400;
118
+ response.destroy();
119
+ if (ok) resolve();
120
+ else reject(new Error('The local client did not accept the callback after approval.'));
121
+ });
122
+ req.on('error', () => reject(new Error('Could not deliver the callback to the local client after approval.')));
123
+ req.end();
124
+ });
125
+ }
126
+
127
+ async function completeLocalConnection(input, worker, replace, request, headers, outerSignal) {
128
+ let auth;
129
+ try { auth = new URL(input); } catch { throw new Error('Use this bridge’s exact authorization endpoint URL.'); }
130
+ if (!['http:', 'https:'].includes(auth.protocol) || auth.username || auth.password || auth.hash) throw new Error('Use this bridge’s exact authorization endpoint URL.');
131
+ const owner = async (route, method, body) => {
132
+ try { return await request(route, method, body, headers()); }
133
+ catch { throw new Error('The bridge owner operation was refused. Check the local operator key and pairing window; use --replace only to replace a connection you own.'); }
134
+ };
135
+ const pending = () => owner('/connect/pending', 'GET', null);
136
+ const view = await pending();
137
+ if (view.authorization_endpoint_fingerprint !== fingerprint(authorityEndpoint(auth))) throw new Error('Use this bridge’s exact authorization endpoint URL.');
138
+ if (view.window?.worker !== worker) throw new Error('No pairing window is open for that worker.');
139
+ const redirects = auth.searchParams.getAll('redirect_uri');
140
+ if (redirects.length !== 1 || !isLocalRedirect(redirects[0])) throw new Error('A canonical loopback callback is required.');
141
+ const issuer = new URL(auth.pathname.slice(0, -'/auth'.length), auth.origin);
142
+ const phaseSignal = () => {
143
+ const budget = AbortSignal.timeout(10000);
144
+ return outerSignal ? AbortSignal.any([outerSignal, budget]) : budget;
145
+ };
146
+ const signal = phaseSignal();
147
+ const get = interactionBrowser(issuer, signal);
148
+ const interaction = nextUrl(await get(auth), auth);
149
+ const interactionPrefix = issuer.pathname + '/interaction/';
150
+ if (!interaction || interaction.origin !== issuer.origin || interaction.search || !interaction.pathname.startsWith(interactionPrefix)
151
+ || !/^[A-Za-z0-9_-]{10,64}$/.test(interaction.pathname.slice(interactionPrefix.length))) {
152
+ throw new Error('The bridge did not start an authorization interaction.');
153
+ }
154
+ if ((await get(interaction)).status !== 200) throw new Error('The bridge did not open a pending pairing.');
155
+ const current = await pending();
156
+ if (current.window?.worker !== worker) throw new Error('No pairing window is open for that worker.');
157
+ const uid = interaction.pathname.slice(interactionPrefix.length);
158
+ const matches = current.pending.filter(p => p.interaction_fingerprint === fingerprint(uid));
159
+ const pairing = matches[0];
160
+ if (matches.length !== 1 || pairing.worker !== worker || !pairing.native || pairing.redirect_uri !== redirects[0]) {
161
+ throw new Error('Could not verify the exact loopback pairing for this authorization request.');
162
+ }
163
+ const result = await owner('/connect/approve', 'POST', { worker, replace, code: pairing.code, confirm_redirect: pairing.redirect_uri });
164
+ // Approval committed. Reuse the same interaction and cookies, with a new bounded
165
+ // callback phase. Do not retry the approval if local notification fails.
166
+ const followUp = phaseSignal();
167
+ const expected = new URL(pairing.redirect_uri);
168
+ try {
169
+ let step = interaction;
170
+ for (let hop = 0; hop < 5; hop++) {
171
+ const target = nextUrl(await get(step, followUp), step);
172
+ if (sameLocalCallback(target, expected, auth, issuer)) {
173
+ await sendLocalCallback(target, followUp);
174
+ return { connection_id: result.connection_id };
175
+ }
176
+ if (!target || target.origin !== issuer.origin || !target.pathname.startsWith(issuer.pathname + '/auth/')) break;
177
+ step = target;
178
+ }
179
+ throw new Error('No verified local callback was returned.');
180
+ } catch (cause) {
181
+ throw new Error(`Connection ${q(result.connection_id)} was approved, but the local callback did not complete. Check the connection before retrying.`, { cause });
182
+ }
183
+ }
184
+
185
+ export async function connectCommand(args, { request, operator, option, json, signal }) {
38
186
  const sub = args.shift();
39
187
  const headers = () => ({ 'x-operator-key': operator() });
40
188
  const flags = new Set(['--json', '--replace', '--rotate']);
@@ -82,7 +230,14 @@ export async function connectCommand(args, { request, operator, option, json })
82
230
  case 'pending': {
83
231
  if (positional.length) throw new Error(USAGE);
84
232
  const result = await request('/connect/pending', 'GET', null, headers());
85
- return json ? { result } : { result: formatPending(result), plain: true };
233
+ const publicView = { window: result.window, pending: result.pending.map(({ interaction_fingerprint, ...item }) => item) };
234
+ return json ? { result: publicView } : { result: formatPending(publicView), plain: true };
235
+ }
236
+ case 'complete': {
237
+ if (positional.length !== 1 || !worker || args.filter(arg => arg === '--worker').length !== 1
238
+ || args.some((arg, i) => arg.startsWith('--') && !['--worker', '--replace', '--json'].includes(arg))) throw new Error(USAGE);
239
+ const result = await completeLocalConnection(positional[0], worker, args.includes('--replace'), request, headers, signal);
240
+ return json ? { result } : { result: 'Connected: ' + q(result.connection_id), plain: true };
86
241
  }
87
242
  case 'approve': {
88
243
  if (positional.length !== 1 || !worker) throw new Error(USAGE);
package/src/deadman.mjs CHANGED
@@ -303,11 +303,14 @@ export class Deadman {
303
303
  });
304
304
  }
305
305
 
306
- async close() {
307
- if (this.timer) clearInterval(this.timer);
308
- if (this.server) await new Promise(resolve => this.server.close(resolve));
309
- await this.tickPromise;
310
- this.db.close();
306
+ close() {
307
+ this.closePromise ??= (async () => {
308
+ if (this.timer) clearInterval(this.timer);
309
+ if (this.server) await new Promise(resolve => this.server.close(resolve));
310
+ await this.tickPromise;
311
+ this.db.close();
312
+ })();
313
+ return this.closePromise;
311
314
  }
312
315
  }
313
316
 
package/src/delivery.mjs CHANGED
@@ -1,19 +1,2 @@
1
- const t3ThreadIdPattern = /^[A-Za-z0-9._:%-]+$/;
2
- export const maxT3ThreadIdLength = 1024;
3
-
4
- // T3 uses UUIDs, `mcp:<uuid>`, and opaque delegated/provider IDs. Keep this
5
- // deliberately bounded while accepting the characters present in those forms.
6
- export function validT3ThreadId(value) {
7
- return typeof value === 'string'
8
- && value.length >= 8
9
- && value.length <= maxT3ThreadIdLength
10
- && t3ThreadIdPattern.test(value);
11
- }
12
-
13
- export function parseDelivery(value) {
14
- if (value === 'none') return { mode: 'none', threadId: null };
15
- if (typeof value === 'string' && value.startsWith('t3:') && validT3ThreadId(value.slice(3))) {
16
- return { mode: 't3', threadId: value.slice(3) };
17
- }
18
- throw new Error('invalid delivery; expected none or t3:<thread-id>');
19
- }
1
+ // The destination registry owns adapter-specific admission and routing; retain the existing API.
2
+ export { maxT3ThreadIdLength, parseDelivery, validT3ThreadId } from './destinations/index.mjs';
@@ -1,17 +1,75 @@
1
1
  import { createNoneDestination } from './none.mjs';
2
2
 
3
- // Stored delivery values are 'none' or 't3:<thread>'; new submissions pass a parsed mode.
3
+ const t3ThreadIdPattern = /^[A-Za-z0-9._:%-]+$/;
4
+ export const maxT3ThreadIdLength = 1024;
5
+
6
+ // T3 uses UUIDs, `mcp:<uuid>`, and opaque delegated/provider IDs. Keep this
7
+ // deliberately bounded while accepting the characters present in those forms.
8
+ export function validT3ThreadId(value) {
9
+ return typeof value === 'string'
10
+ && value.length >= 8
11
+ && value.length <= maxT3ThreadIdLength
12
+ && t3ThreadIdPattern.test(value);
13
+ }
14
+
15
+ const destinations=new Map();
16
+ const split=value=>{
17
+ const colon=value.indexOf(':');
18
+ return colon<0?[value,undefined]:[value.slice(0,colon),value.slice(colon+1)];
19
+ };
20
+
21
+ export function registerDestination(name,{parse,load,version='1',...builtIn}={}) {
22
+ if(typeof name!=='string'||!/^[a-z][a-z0-9-]*$/.test(name)||typeof parse!=='function'||typeof load!=='function'||typeof version!=='string'||!/^\S{1,64}$/.test(version))
23
+ throw new TypeError('invalid destination registration');
24
+ if(destinations.has(name)) throw new Error(`destination already registered: ${name}`);
25
+ destinations.set(name,{parse,load,version,...builtIn});
26
+ }
27
+
28
+ export const destinationVersion=name=>destinations.get(name)?.version;
29
+
30
+ registerDestination('none',{
31
+ version:'1',form:'none', bare:true,
32
+ routes:(value,address)=>address===undefined,
33
+ parse:address=>address===undefined?{mode:'none',threadId:null}:null,
34
+ load:createNoneDestination,
35
+ });
36
+ registerDestination('t3',{
37
+ version:'1',
38
+ form:'t3:<thread-id>',
39
+ // Persisted rows predate strict admission parsing and can carry an opaque short ID.
40
+ routes:(value,address)=>typeof value==='string'?(address===undefined||/^.+$/.test(address)):validT3ThreadId(value?.threadId),
41
+ parse:address=>validT3ThreadId(address)?{mode:'t3',threadId:address}:null,
42
+ load:deps=>deps.loadT3?deps.loadT3():import('./t3.mjs').then(({createT3Destination})=>createT3Destination(deps)),
43
+ });
44
+
45
+ function parseAddress(mode,adapter,address) {
46
+ if(!adapter.bare&&(typeof address!=='string'||!address)) return null;
47
+ try {
48
+ const parsed=adapter.parse(address);
49
+ return parsed?.mode===mode?parsed:null;
50
+ } catch { return null; } // Do not include opaque addresses in parser diagnostics.
51
+ }
52
+
53
+ export function parseDelivery(value) {
54
+ if(typeof value==='string') {
55
+ const [mode,address]=split(value), adapter=destinations.get(mode);
56
+ const parsed=adapter&&parseAddress(mode,adapter,address);
57
+ if(parsed) return parsed;
58
+ }
59
+ const forms=[...destinations].map(([name,adapter])=>adapter.form??`${name}:<address>`);
60
+ throw new Error(`invalid delivery; expected ${forms.join(' or ')}`);
61
+ }
62
+
4
63
  export const destinationName=delivery=>{
5
64
  if(delivery===undefined) return 'none';
6
- if(delivery==='none'||delivery?.mode==='none') return 'none';
7
- if(delivery==='t3') return 't3';
8
- // Persisted rows predate strict admission parsing and use t3:<opaque id>.
9
- if(typeof delivery==='string'&&/^t3:.+$/.test(delivery)) return 't3';
10
- if(delivery?.mode==='t3'&&typeof delivery.threadId==='string') return 't3';
11
- const error=new Error(`invalid delivery mode: ${String(delivery)}`);
65
+ const [mode,address]=typeof delivery==='string'?split(delivery):[delivery?.mode,undefined];
66
+ const adapter=destinations.get(mode);
67
+ if(adapter&&(adapter.routes?adapter.routes(delivery,address):parseAddress(mode,adapter,typeof delivery==='string'?address:delivery?.address))) return mode;
68
+ const error=new Error('invalid delivery mode');
12
69
  error.code='INVALID_DELIVERY_MODE';
13
70
  throw error;
14
71
  };
72
+
15
73
  // A destination is an adapter with this interface. Besides send and reconcile it has three methods for the parent it wakes:
16
74
  // capture(delivery) -> string|null what to record at submit about the parent. One opaque string: the Store keeps
17
75
  // it in assignments.parent_generation and never parses it.
@@ -19,11 +77,14 @@ export const destinationName=delivery=>{
19
77
  // canAdmitContinuation(row) -> {ok,reason} whether the parent may be woken now. Best effort: a read, and the send follows.
20
78
  // validate(delivery) returns {environmentId,generation}, where generation is what capture would return from the same read.
21
79
  export function createDestinations(deps) {
22
- const none=createNoneDestination(deps); let t3Promise;
23
- const loadT3=deps.loadT3??(()=>import('./t3.mjs').then(({createT3Destination})=>createT3Destination(deps)));
24
- const getT3=()=>{
25
- if(!t3Promise) t3Promise=Promise.resolve().then(loadT3).catch(error=>{ t3Promise=null; throw error; });
26
- return t3Promise;
27
- };
28
- return {none,for:async delivery=>destinationName(delivery)==='none'?none:getT3()};
80
+ const none=destinations.get('none').load(deps), loaded=new Map();
81
+ return {none,for:async delivery=>{
82
+ const name=destinationName(delivery);
83
+ if(name==='none') return none;
84
+ if(!loaded.has(name)) loaded.set(name,Promise.resolve().then(()=>destinations.get(name).load(deps)).catch(error=>{
85
+ loaded.delete(name);
86
+ throw error;
87
+ }));
88
+ return loaded.get(name);
89
+ }};
29
90
  }
@@ -1,6 +1,10 @@
1
1
  export function createDrainRunner(drain,log) {
2
2
  const report=error=>{
3
- try { log({kind:'delivery_drain_error',reason:String(error?.message??error).slice(0,300)}); } catch {}
3
+ try {
4
+ const result=log({kind:'delivery_drain_error',reason:String(error?.message??error).slice(0,300)});
5
+ // Logging must not create a second, unhandled failure.
6
+ Promise.resolve(result).catch(()=>{});
7
+ } catch {}
4
8
  };
5
9
  return function runDrain() {
6
10
  try { return Promise.resolve(drain()).catch(error=>{ report(error); }); }
@@ -11,7 +11,9 @@ const real = file => { try { return fs.realpathSync(file); } catch { return null
11
11
  // command line after the script. An explicit --home names a home other than the default one, so this package runs it.
12
12
  export function followTarget({ ownBin, env = process.env, argv = [] }) {
13
13
  if (env.DALAN_NO_FOLLOW === '1' || env.DALAN_FOLLOWED === '1') return null;
14
- if (argv.some(arg => arg === '--home' || arg.startsWith('--home='))) return null;
14
+ const separator = argv.indexOf('--');
15
+ const options = separator === -1 ? argv : argv.slice(0, separator);
16
+ if (options.some(arg => arg === '--home' || arg.startsWith('--home='))) return null;
15
17
  const home = env.DALAN_HOME ? path.resolve(env.DALAN_HOME) : readDefaultHome(env);
16
18
  if (!home) return null;
17
19
  const target = real(path.join(home, 'current', 'bin', 'dalan.mjs')), own = real(ownBin);
@@ -5,6 +5,7 @@ export function formatGetSummary(job, { id, cli }) {
5
5
  const state = job.status ?? 'unknown';
6
6
  const report = job.report ?? null;
7
7
  const lines = [`Job ${id}: ${state}`];
8
+ if (job.revised_by?.request_id) lines.push(`Correction: ${job.revised_by.request_id}`);
8
9
  if (job.target_worker) lines.push(`Worker: ${job.target_worker}`);
9
10
  if (report?.outcome && report.outcome !== 'done') lines.push(`Outcome: ${report.outcome}`);
10
11
  if (report?.summary) lines.push(`Summary: ${report.summary}`);
@@ -15,14 +16,22 @@ export function formatGetSummary(job, { id, cli }) {
15
16
  const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
16
17
  const artifacts = (job.artifacts?.length ?? 0) || (job.artifact_ids?.length ?? 0), checks = job.checks?.length ?? 0;
17
18
  if (artifacts || checks) lines.push('', `Evidence: ${[artifacts && count(artifacts, 'artifact'), checks && count(checks, 'check')].filter(Boolean).join(', ')}`);
18
- const next = state === 'finished' ? `${cli} decide ${id} accepted`
19
+ const next = correctionAction(job, cli) ?? (state === 'finished' ? `${cli} decide ${id} accepted`
19
20
  : state === 'cancelled' ? null
20
- : `${cli} wait ${id} --timeout 3600, then ${cli} get ${id}`;
21
+ : `${cli} wait ${id} --timeout 3600, then ${cli} get ${id}`);
21
22
  if (next) lines.push('', `Next: ${next}`);
22
23
  lines.push(`Full record: ${cli} get ${id} --json`);
23
24
  return lines.join('\n');
24
25
  }
25
26
 
27
+ const correctionAction = (job, cli) => job?.revised_by?.request_id ? `${cli} get ${job.revised_by.request_id}` : null;
28
+
29
+ // Piped human output retains the full JSON record and adds only this stderr guidance.
30
+ export function formatGetEndNote(job, { id, cli, decideWords }) {
31
+ const correction = correctionAction(job, cli);
32
+ return correction ? `Next: ${correction}` : job?.status === 'finished' ? `decide: ${cli} decide ${id} ${decideWords}` : null;
33
+ }
34
+
26
35
  // `dalan wait` on a terminal: one line, in place of the JSON status document.
27
36
  export function formatWaitLine(result, { id, cli, seconds }) {
28
37
  const state = result?.status ?? 'unknown';
package/src/git-env.mjs CHANGED
@@ -9,7 +9,7 @@
9
9
  const kept=new Set(['GIT_ASKPASS','GIT_TERMINAL_PROMPT']);
10
10
  export function gitEnv(base=process.env) {
11
11
  const env=Object.fromEntries(Object.entries(base).filter(([key])=>!key.startsWith('GIT_')||kept.has(key)));
12
- return {...env,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_ATTR_NOSYSTEM:'1',
12
+ return {...env,GIT_PAGER:'cat',GIT_EDITOR:'false',GIT_SEQUENCE_EDITOR:'false',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_ATTR_NOSYSTEM:'1',
13
13
  GIT_CONFIG_COUNT:'4',GIT_CONFIG_KEY_0:'core.hooksPath',GIT_CONFIG_VALUE_0:'/dev/null',GIT_CONFIG_KEY_1:'core.fsmonitor',GIT_CONFIG_VALUE_1:'false',
14
14
  GIT_CONFIG_KEY_2:'core.excludesFile',GIT_CONFIG_VALUE_2:'/dev/null',GIT_CONFIG_KEY_3:'core.attributesFile',GIT_CONFIG_VALUE_3:'/dev/null'};
15
15
  }