@tnunamak/dalan 0.0.0-stage → 0.6.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 (199) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +351 -0
  5. package/README.md +215 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +43 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +764 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/codex-to-muse.md +175 -0
  17. package/docs/connect-chatgpt.md +83 -0
  18. package/docs/connection-longevity.md +43 -0
  19. package/docs/dalan-upgrade.md +246 -0
  20. package/docs/deadman.md +61 -0
  21. package/docs/dot-pr-reviewer.config.example.json +9 -0
  22. package/docs/durability-audit.md +27 -0
  23. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  24. package/docs/keycloak-oauth-setup.md +30 -0
  25. package/docs/local-agent-mcp.md +41 -0
  26. package/docs/manual-setup.md +135 -0
  27. package/docs/mirror-fetch.md +97 -0
  28. package/docs/operations.md +799 -0
  29. package/docs/operator-duties.md +68 -0
  30. package/docs/owner-integrator.md +27 -0
  31. package/docs/portable-auth-profile.md +107 -0
  32. package/docs/pr-head-reviewer.md +70 -0
  33. package/docs/pr-preflight.md +28 -0
  34. package/docs/pull-queue.md +131 -0
  35. package/docs/pull-workers.md +94 -0
  36. package/docs/redaction.md +27 -0
  37. package/docs/service-setup.md +219 -0
  38. package/docs/setup-reference.md +80 -0
  39. package/docs/t3-connector-icon.png +0 -0
  40. package/docs/t3-integration.md +51 -0
  41. package/docs/t3-result-retry-delivery.md +41 -0
  42. package/docs/t3-reverse-control.md +107 -0
  43. package/docs/usage.md +443 -0
  44. package/docs/worker-clients.md +290 -0
  45. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  46. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  47. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  48. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  49. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  50. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  51. package/package.json +67 -4
  52. package/packages/job-core/README.md +18 -0
  53. package/packages/job-core/index.mjs +2 -0
  54. package/packages/job-core/package.json +8 -0
  55. package/packages/job-core/protocol/canonical.mjs +11 -0
  56. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  57. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  58. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  59. package/packages/job-core/transitions.mjs +25 -0
  60. package/scripts/daily-selfcheck.mjs +135 -0
  61. package/scripts/dalan-try-selfcheck.mjs +29 -0
  62. package/scripts/lib/expose-tailscale.mjs +408 -0
  63. package/scripts/live-trial/common.mjs +272 -0
  64. package/scripts/monitor-targets.mjs +44 -0
  65. package/scripts/upgrade-drain.mjs +39 -0
  66. package/scripts/worker-bridge-setup.mjs +925 -0
  67. package/src/ack-ledger.mjs +37 -0
  68. package/src/acp-bridge.mjs +418 -0
  69. package/src/acp-context.mjs +138 -0
  70. package/src/admin-socket.mjs +14 -0
  71. package/src/alerts.mjs +147 -0
  72. package/src/artifact-journal.mjs +75 -0
  73. package/src/as-files.mjs +347 -0
  74. package/src/as-store.mjs +456 -0
  75. package/src/as.mjs +538 -0
  76. package/src/auth.mjs +166 -0
  77. package/src/builtin-http.mjs +22 -0
  78. package/src/check-coverage.mjs +38 -0
  79. package/src/check-lint.mjs +88 -0
  80. package/src/check-readiness.mjs +112 -0
  81. package/src/check-response.mjs +19 -0
  82. package/src/child-exit.mjs +18 -0
  83. package/src/child-registry.mjs +94 -0
  84. package/src/claim-command-ledger.mjs +51 -0
  85. package/src/cli-help.mjs +186 -0
  86. package/src/cli-name.mjs +16 -0
  87. package/src/connect-cli.mjs +126 -0
  88. package/src/consumers.mjs +61 -0
  89. package/src/deadman.mjs +329 -0
  90. package/src/delivery.mjs +19 -0
  91. package/src/demo-worker.mjs +150 -0
  92. package/src/destinations/index.mjs +23 -0
  93. package/src/destinations/none.mjs +15 -0
  94. package/src/destinations/t3.mjs +109 -0
  95. package/src/diagnostic.mjs +78 -0
  96. package/src/docs-url.mjs +9 -0
  97. package/src/drain-runner.mjs +9 -0
  98. package/src/drained-owner.mjs +26 -0
  99. package/src/drained-slot.mjs +70 -0
  100. package/src/drained.mjs +40 -0
  101. package/src/durable-waiters.mjs +236 -0
  102. package/src/env.mjs +19 -0
  103. package/src/execution.mjs +112 -0
  104. package/src/failure-type.mjs +28 -0
  105. package/src/get-summary.mjs +32 -0
  106. package/src/git-env.mjs +15 -0
  107. package/src/host-budget-receipts.mjs +154 -0
  108. package/src/host-budget-seccomp.py +33 -0
  109. package/src/host-budget-service.mjs +54 -0
  110. package/src/host-budget-stop.mjs +26 -0
  111. package/src/host-budget-storage.py +259 -0
  112. package/src/host-budget.mjs +149 -0
  113. package/src/host-cgroup.mjs +23 -0
  114. package/src/host-check-allowlist.mjs +42 -0
  115. package/src/host-execution-policy.mjs +38 -0
  116. package/src/host-health.mjs +34 -0
  117. package/src/host-stop-reverify.mjs +44 -0
  118. package/src/inbox.mjs +55 -0
  119. package/src/integrator.mjs +322 -0
  120. package/src/job-retention.mjs +69 -0
  121. package/src/legacy-names.mjs +8 -0
  122. package/src/lifecycle.mjs +291 -0
  123. package/src/limits.mjs +31 -0
  124. package/src/loopback.mjs +9 -0
  125. package/src/mcp-outcome.mjs +79 -0
  126. package/src/mcp-sse.mjs +62 -0
  127. package/src/mcp-stdio.mjs +191 -0
  128. package/src/mirror-fetch-lock.py +164 -0
  129. package/src/mirror-fetch.mjs +174 -0
  130. package/src/notify-ledger.mjs +82 -0
  131. package/src/objectives.mjs +129 -0
  132. package/src/owner-report-artifact.mjs +66 -0
  133. package/src/patch-apply.mjs +84 -0
  134. package/src/path-syntax.mjs +16 -0
  135. package/src/paths.mjs +67 -0
  136. package/src/pr-head-reviewer.mjs +596 -0
  137. package/src/pr-preflight.mjs +51 -0
  138. package/src/prepared-node-modules.mjs +129 -0
  139. package/src/process-inspection.mjs +36 -0
  140. package/src/projects.mjs +480 -0
  141. package/src/protocol-artifact-commands.mjs +52 -0
  142. package/src/protocol-delivery-driver.mjs +167 -0
  143. package/src/protocol-finish.mjs +100 -0
  144. package/src/protocol-owner-command.mjs +35 -0
  145. package/src/protocol-owner-mutations.mjs +22 -0
  146. package/src/protocol-owner-waiters.mjs +67 -0
  147. package/src/protocol-retention.mjs +52 -0
  148. package/src/protocol-services.mjs +61 -0
  149. package/src/protocol-stop-observer.mjs +131 -0
  150. package/src/publish-plan.mjs +245 -0
  151. package/src/pull-queue.mjs +159 -0
  152. package/src/redaction.mjs +763 -0
  153. package/src/rejections.mjs +18 -0
  154. package/src/request-log.mjs +102 -0
  155. package/src/restore-check.mjs +90 -0
  156. package/src/result-binding.mjs +65 -0
  157. package/src/route-setting.mjs +24 -0
  158. package/src/runtime-check.mjs +13 -0
  159. package/src/sandbox-supervisor.mjs +105 -0
  160. package/src/schema-subset.mjs +186 -0
  161. package/src/scopes.mjs +15 -0
  162. package/src/server.mjs +1468 -0
  163. package/src/service-migrate-workers.mjs +113 -0
  164. package/src/service.mjs +388 -0
  165. package/src/setup.mjs +63 -0
  166. package/src/shutdown-signal.mjs +12 -0
  167. package/src/signal-sandbox-processes.py +56 -0
  168. package/src/signal.mjs +119 -0
  169. package/src/status-evidence.mjs +47 -0
  170. package/src/status-summary.mjs +54 -0
  171. package/src/store.mjs +3069 -0
  172. package/src/submission-policy.mjs +623 -0
  173. package/src/subscription-storage.mjs +64 -0
  174. package/src/t3-audit.mjs +120 -0
  175. package/src/t3-control.mjs +102 -0
  176. package/src/t3-transport.mjs +158 -0
  177. package/src/t3.mjs +209 -0
  178. package/src/terminal-safe.mjs +19 -0
  179. package/src/tool-registry.mjs +453 -0
  180. package/src/try-command.mjs +11 -0
  181. package/src/try-exposure.mjs +908 -0
  182. package/src/try-hosted-clients.mjs +46 -0
  183. package/src/try-hosted.mjs +444 -0
  184. package/src/try-selfcheck.mjs +168 -0
  185. package/src/try.mjs +635 -0
  186. package/src/webhooks.mjs +86 -0
  187. package/src/work-order.mjs +265 -0
  188. package/src/worker-instructions.mjs +26 -0
  189. package/src/worker-prompt.mjs +4 -0
  190. package/src/workers.mjs +632 -0
  191. package/src/workspace.mjs +1065 -0
  192. package/systemd/dot-bridge-heartbeat.service +18 -0
  193. package/systemd/dot-bridge-heartbeat.timer +10 -0
  194. package/systemd/dot-bridge-selfcheck.service +12 -0
  195. package/systemd/dot-bridge-selfcheck.timer +11 -0
  196. package/systemd/dot-bridge.service +17 -0
  197. package/systemd/dot-deadman.service +30 -0
  198. package/systemd/dot-pr-reviewer.service +11 -0
  199. package/systemd/dot-pr-reviewer.timer +10 -0
@@ -0,0 +1,86 @@
1
+ import { readEnv } from './env.mjs';
2
+ import http from 'node:http';
3
+ import https from 'node:https';
4
+ import dns from 'node:dns/promises';
5
+ import net from 'node:net';
6
+ import { createHmac } from 'node:crypto';
7
+
8
+ function publicIp(ip) {
9
+ if (readEnv('DALAN_ALLOW_PRIVATE_WEBHOOKS') === '1') return true;
10
+ if (net.isIP(ip) === 4) {
11
+ const x = ip.split('.').map(Number);
12
+ return !(x[0] === 0 || x[0] === 10 || x[0] === 127 || x[0] >= 224 ||
13
+ x[0] === 169 && x[1] === 254 || x[0] === 172 && x[1] >= 16 && x[1] <= 31 ||
14
+ x[0] === 192 && x[1] === 168 || x[0] === 100 && x[1] >= 64 && x[1] <= 127 ||
15
+ x[0] === 192 && x[1] === 0 || x[0] === 198 && x[1] >= 18 && x[1] <= 19);
16
+ }
17
+ const s = ip.toLowerCase();
18
+ return !(s === '::1' || s === '::' || s.startsWith('fc') || s.startsWith('fd') ||
19
+ s.startsWith('fe8') || s.startsWith('fe9') || s.startsWith('fea') ||
20
+ s.startsWith('feb') || s.startsWith('::ffff:'));
21
+ }
22
+
23
+ async function destination(raw) {
24
+ const url = new URL(raw);
25
+ if (url.protocol !== 'https:' && !(readEnv('DALAN_ALLOW_PRIVATE_WEBHOOKS') === '1' && url.protocol === 'http:')) throw new Error('HTTPS required');
26
+ if (url.username || url.password) throw new Error('URL credentials forbidden');
27
+ const addresses = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true });
28
+ if (!addresses.length || addresses.some(a => !publicIp(a.address))) throw new Error('non-public callback address');
29
+ return { url, address: addresses[0].address };
30
+ }
31
+
32
+ export function validSecret(secret) {
33
+ if (typeof secret !== 'string' || !/^whsec_[A-Za-z0-9+/]+={0,2}$/.test(secret)) return false;
34
+ const bytes = Buffer.from(secret.slice(6), 'base64');
35
+ return bytes.length >= 24 && bytes.length <= 64;
36
+ }
37
+
38
+ export function signature(secret, id, timestamp, body) {
39
+ return 'v1,' + createHmac('sha256', Buffer.from(secret.slice(6), 'base64'))
40
+ .update(`${id}.${timestamp}.${body}`).digest('base64');
41
+ }
42
+
43
+ // `timeout` below is socket inactivity only: a receiver that sends one byte every few seconds never trips it.
44
+ // The deadline bounds the whole request, response body included, because delivery drains subscribers one at a time.
45
+ export const WEBHOOK_DEADLINE_MS = 15000;
46
+
47
+ export async function sendWebhook(rawUrl, secret, id, subId, body, { deadlineMs = WEBHOOK_DEADLINE_MS } = {}) {
48
+ // The deadline also covers the DNS lookup, whose hostname the subscriber controls.
49
+ const started = Date.now();
50
+ let lookupTimer;
51
+ const dest = await Promise.race([
52
+ destination(rawUrl),
53
+ new Promise((_, fail) => { lookupTimer = setTimeout(() => fail(new Error('timeout')), deadlineMs); })
54
+ ]).finally(() => clearTimeout(lookupTimer));
55
+ const timestamp = String(Math.floor(Date.now() / 1000));
56
+ const headers = {
57
+ 'content-type': 'application/json', 'content-length': Buffer.byteLength(body),
58
+ 'webhook-id': id, 'Idempotency-Key': id, 'webhook-timestamp': timestamp,
59
+ 'webhook-signature': signature(secret, id, timestamp, body),
60
+ 'X-MCP-Subscription-Id': subId
61
+ };
62
+ return new Promise((resolve, reject) => {
63
+ let deadline;
64
+ const settle = fn => value => { clearTimeout(deadline); fn(value); };
65
+ resolve = settle(resolve); reject = settle(reject);
66
+ const lib = dest.url.protocol === 'https:' ? https : http;
67
+ const req = lib.request(dest.url, {
68
+ method: 'POST', headers, timeout: 10000,
69
+ lookup: (_host, opts, cb) => opts?.all
70
+ ? cb(null, [{ address: dest.address, family: net.isIP(dest.address) }])
71
+ : cb(null, dest.address, net.isIP(dest.address))
72
+ }, res => {
73
+ const chunks = []; let size = 0;
74
+ res.on('data', c => { size += c.length; if (size <= 8192) chunks.push(c); });
75
+ res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }));
76
+ });
77
+ req.on('timeout', () => req.destroy(new Error('timeout')));
78
+ deadline = setTimeout(() => {
79
+ const error = new Error('timeout');
80
+ reject(error);
81
+ req.destroy(error);
82
+ }, Math.max(0, deadlineMs - (Date.now() - started)));
83
+ req.on('error', reject);
84
+ req.end(body);
85
+ });
86
+ }
@@ -0,0 +1,265 @@
1
+ // Work-order compiler: the one place that turns a submitted assignment into an admission verdict.
2
+ //
3
+ // admissible the bridge will store it and the worker can take it
4
+ // clarify the requester must choose or fix something (ambiguous name, probable typo, missing input); the reason says what
5
+ // reject invalid or forbidden (bad schema, unsafe path, sensitive scope, secret content); retrying unchanged cannot work
6
+ // defer fine as written, but cannot run now (worker paused or on a usage break, capability missing on this host,
7
+ // queue deeper than the requester's threshold); the reason carries a retry hint
8
+ //
9
+ // It runs the checks that already guarded submit (src/submission-policy.mjs, src/execution.mjs, src/check-readiness.mjs, PR
10
+ // preflight) and maps what they throw to typed reasons {code, field, message, fix}. It writes nothing to the store: the same
11
+ // call serves `submit --dry-run` and the real submit, so a preview cannot disagree with the decision. The checks read the pinned
12
+ // repository through the bridge mirror (a fetch may refresh that cache); that is the only side effect.
13
+ import { submissionLimits, instructionBytes } from './submission-policy.mjs';
14
+
15
+ export const VERDICTS = Object.freeze(['admissible', 'clarify', 'reject', 'defer']);
16
+ // Exit codes of `dalan submit` (0 = stored or admissible).
17
+ export const VERDICT_EXIT = Object.freeze({ admissible: 0, reject: 2, clarify: 3, defer: 4 });
18
+ const rank = { admissible: 0, defer: 1, clarify: 2, reject: 3 };
19
+
20
+ const bytes = value => Buffer.byteLength(String(value ?? ''), 'utf8');
21
+ const list = text => String(text).split(', ').map(x => x.trim()).filter(Boolean);
22
+ const fmt = n => n == null || !Number.isFinite(Number(n)) ? 'unknown' : Number(n).toLocaleString('en-US');
23
+
24
+ // A thrown check error to typed reasons. Each rule: [pattern, build(match, error) -> reason | reason[]]; the first match wins.
25
+ // `verdict` is the class the reason belongs to. Unmatched errors are rejections with code 'refused' and the original text.
26
+ const rules = [
27
+ [/^(brief|task instructions|expected output): (\d+) UTF-8 bytes exceeds (\d+)/, m => {
28
+ const field = m[1] === 'brief' ? 'brief' : m[1] === 'expected output' ? 'expected_output' : 'instructions';
29
+ const cut = Number(m[2]) - Number(m[3]);
30
+ return { verdict: 'reject', code: `${field}_too_large`, field, message: `${m[1]} is ${fmt(m[2])} UTF-8 bytes; the limit is ${fmt(m[3])}`,
31
+ fix: `cut at least ${fmt(cut)} bytes${field === 'instructions' ? ' from the brief, expected_output or scope lists' : ''}${field === 'brief' ? ' (the bridge may append a scope allow-list; the count already includes it where it was added)' : ''}` };
32
+ }],
33
+ [/^(?:aggregate )?owner note/, m => ({ verdict: 'reject', code: 'note_too_large', field: 'note', message: m.input, fix: 'shorten the note' })],
34
+ [/^hard sensitive path exclusion: (.+)$/, m => ({ verdict: 'reject', code: 'sensitive_path_hard', field: 'scope_paths', message: `${m[1]} is credential, key or signing material and can never be in scope`, fix: `remove ${m[1]} from scope_paths and from the brief` })],
35
+ [/^sensitive scope path: (.+?)(?: \((.*)\))?$/, m => ({ verdict: 'reject', code: 'sensitive_path', field: 'scope_paths', message: `${m[1]} matches the sensitive-path rules${m[2] ? ` (${m[2]})` : ''}`,
36
+ fix: `remove ${m[1]} from scope_paths, or for read-only work submit with exclude_sensitive (--exclude-sensitive) to drop sensitive files from a directory scope` })],
37
+ [/^hard sensitive (?:patch )?content exclusion$/, m => ({ verdict: 'reject', code: 'secret_content', field: 'brief', message: 'the assignment contains what looks like a secret value (key, token or password URL)', fix: 'remove the secret and refer to it by name' })],
38
+ [/^live-slot or expanded-authority claim in instructions$/, () => ({ verdict: 'reject', code: 'authority_claim', field: 'brief', message: 'the instructions claim live slots or expanded authority', fix: 'remove the claim; the bridge, not the brief, grants capacity and authority' })],
39
+ [/^invalid (scope_paths|read_paths|read_list|brief read-list|mention|sensitive_paths|exception path); explicit repository-relative paths required$/, m => ({ verdict: 'reject', code: 'invalid_path', field: m[1], message: `${m[1]} holds a path that is not repository-relative (absolute, "..", glob or control characters)`, fix: 'name each file or directory by its path from the repository root' })],
40
+ [/^invalid output_paths: (.+)$/s, m => ({ verdict: 'reject', code: 'invalid_output_paths', field: 'output_paths', message: m[1], fix: 'list up to 10 new repository-relative file paths, with no globs or directories' })],
41
+ [/^output_paths are not allowed with --review/, m => ({ verdict: 'reject', code: 'output_paths_in_review', field: 'output_paths', message: m.input, fix: 'remove output_paths, or submit without --review' })],
42
+ [/^output_paths require pinned repository input/, m => ({ verdict: 'clarify', code: 'missing_inputs', field: 'inputs', message: m.input, fix: 'add inputs: [{github_repo, base_sha}] to the assignment' })],
43
+ [/^output_paths cannot be combined with input_patch/, m => ({ verdict: 'reject', code: 'output_paths_with_patch', field: 'output_paths', message: m.input, fix: 'submit the patch as its own job, or push it and pin head_sha' })],
44
+ [/^output_paths: (?:hard sensitive|sensitive scope)/, m => ({ verdict: 'reject', code: 'output_path_sensitive', field: 'output_paths', message: m.input, fix: 'name the new file so that it does not look like credential, auth or signing material' })],
45
+ [/^output_paths: (.+)$/s, m => ({ verdict: 'clarify', code: 'output_path_taken', field: 'output_paths', message: m[1], fix: 'choose output paths that do not exist at the pinned revision; to change an existing file list it in scope_paths' })],
46
+ [/^unknown repository scope; scope_paths required$/, () => ({ verdict: 'clarify', code: 'missing_scope', field: 'scope_paths', message: 'repository work needs scope_paths', fix: 'list the files or directories the worker may read (and change)' })],
47
+ [/^structured repository assignment requires scope_paths$/, () => ({ verdict: 'clarify', code: 'missing_scope', field: 'scope_paths', message: 'a structured repository assignment needs scope_paths', fix: 'add scope_paths' })],
48
+ [/^scope_paths require pinned repository input$/, () => ({ verdict: 'clarify', code: 'missing_inputs', field: 'inputs', message: 'scope_paths are set but the assignment pins no repository', fix: 'add inputs: [{github_repo, base_sha}], or remove scope_paths' })],
49
+ [/^contradictory (read_paths|read_list|brief read-list) and scope_paths: (.+)$/s, m => ({ verdict: 'clarify', code: 'contradictory_scope', field: m[1], message: m.input, fix: `make ${m[1]} equal scope_paths, or drop ${m[1]}` })],
50
+ [/^(?:diff|patch) outside scope_paths: (.+)$/, m => ({ verdict: 'clarify', code: 'diff_outside_scope', field: 'scope_paths', message: m.input, fix: `add ${m[1]} to scope_paths` })],
51
+ [/^symlink in (?:repository scope|input patch scope): ?(.*)$/, m => ({ verdict: 'reject', code: 'symlink_in_scope', field: 'scope_paths', message: m.input, fix: 'name the real files, or exclude the symlink (read-only work can use exclude_sensitive)' })],
52
+ [/^scope growth limit: /, m => ({ verdict: 'reject', code: 'scope_too_wide', field: 'scope_paths', message: m.input, fix: 'list the files in scope_paths' })],
53
+ [/^incomplete input patch/, m => ({ verdict: 'reject', code: 'invalid_input_patch', field: 'inputs', message: m.input, fix: 'send a complete `git diff` as input_patch' })],
54
+ [/^head_sha_unsupported: /, m => ({ verdict: 'reject', code: 'head_sha_unsupported', field: 'inputs', message: m.input, fix: 'pin base_sha to the revision to work on, or use --review or read-only scope for head_sha' })],
55
+ [/^invalid valid_until$/, m => ({ verdict: 'reject', code: 'invalid_valid_until', field: 'valid_until', message: m.input, fix: 'give valid_until as a future RFC 3339 timestamp, or omit it to use the bridge default when evidence is sufficient' })],
56
+ [/^valid_until has expired$/, m => ({ verdict: 'reject', code: 'validity_expired', field: 'valid_until', message: m.input, fix: 'refresh the pinned inputs and provide a new future valid_until; the bridge will not extend a caller deadline' })],
57
+ [/^regression_test_scope: /, m => ({ verdict: 'clarify', code: 'missing_test_scope', field: 'scope_paths', message: m.input, fix: 'add a test path to scope_paths, or drop the regression-test request from expected_output' })],
58
+ [/^BLOCKED: check prerequisites unmet: /, m => ({ verdict: 'defer', code: 'check_prerequisites_unmet', field: 'checks', message: m.input.replace(/^BLOCKED: /, ''), fix: 'install the missing prerequisite on the bridge host, or submit with --execution worker', retry: true, blocking: true })],
59
+ [/^BLOCKED: check metadata unreadable/, m => ({ verdict: 'reject', code: 'check_metadata_unreadable', field: 'checks', message: m.input.replace(/^BLOCKED: /, ''), fix: 'fix the check metadata file at base_sha, or submit with --execution worker' })],
60
+ [/^capability_not_available: (\w+) \((.*)\)$/, m => /declares unsupported/.test(m[2])
61
+ ? { verdict: 'reject', code: 'capability_unsupported', field: 'required_capabilities', message: `${m[1]} ${m[2]}`, fix: 'drop this required capability or run the job where the backend supports it' }
62
+ : { verdict: 'defer', code: 'capability_unavailable', field: 'required_capabilities', message: `${m[1]}: ${m[2]}`, fix: 'wait until the host provides it (install the executor), or submit with --execution worker', retry: true, blocking: true }],
63
+ [/^(?:worker|dot) queue is full \((\d+) queued, in-flight cap (\d+)\)/, m => ({ verdict: 'defer', code: 'queue_full', field: 'max_queued', message: m.input, fix: 'wait for queued work to drain, or raise max_queued', retry: true })],
64
+ [/^background_capacity_full$/, () => ({ verdict: 'defer', code: 'background_capacity_full', field: 'priority', message: 'background lane is full', fix: 'wait for background work to drain', retry: true })],
65
+ [/^invalid (assignment|delivery|max_queued|review|background|allow_main|exclude_sensitive|required_capabilities|execution|sensitive scope override|dry_run|queue_anyway|\w+)\b/, m => ({ verdict: 'reject', code: 'invalid_schema', field: m[1].replace(/ /g, '_'), message: m.input, fix: `correct ${m[1]} (see docs/usage.md, Submit)` })],
66
+ [/^unknown sensitive scope override/, m => ({ verdict: 'reject', code: 'unknown_override', field: 'sensitive_scope_override', message: m.input, fix: 'use an exception id from the submission policy' })],
67
+ [/^(?:structured assignment requires|scope_text)/, m => ({ verdict: 'reject', code: 'invalid_schema', field: 'assignment', message: m.input, fix: 'give objective and stop_rule, or a plain brief' })],
68
+ ];
69
+
70
+ // "a, b, c" or "a, b, ..." candidates out of an ambiguity message.
71
+ const candidatesIn = text => { const m = /\(([^)]*)\)/.exec(text); return m ? m[1].split(', ').filter(x => x && x !== '...') : []; };
72
+
73
+ // One thrown error to its reasons (multi-line refusals split into one reason per problem).
74
+ export function reasonsFromError(error) {
75
+ const message = String(error?.message ?? error);
76
+ const out = [];
77
+ const lines = message.split('\n');
78
+ if (lines.some(l => /^(?:undeclared instruction path|ambiguous |unknown bare filename)/.test(l))) {
79
+ for (const line of lines) {
80
+ let m;
81
+ if ((m = /^undeclared instruction path: (.+)$/.exec(line))) out.push({ verdict: 'clarify', code: 'undeclared_path', field: 'scope_paths', message: line,
82
+ fix: error.suggested_scope_paths ? `add ${list(m[1]).join(', ')} to scope_paths (corrected scope_paths: ${JSON.stringify(error.suggested_scope_paths)}), or remove the mention from the brief` : `remove ${m[1]} from the brief, or name the repository file that scope_paths should hold`, ...(error.suggested_scope_paths ? { suggested_scope_paths: error.suggested_scope_paths } : {}) });
83
+ else if ((m = /^(ambiguous (?:bare filename|abbreviated path)) "([^"]+)"/.exec(line))) out.push({ verdict: 'clarify', code: 'ambiguous_path', field: 'brief', message: line, candidates: candidatesIn(line),
84
+ fix: `write the full repository path of the one you mean instead of "${m[2]}"` });
85
+ else if ((m = /^unknown bare filename "([^"]+)"/.exec(line))) out.push({ verdict: 'clarify', code: 'unknown_path', field: 'brief', message: line, candidates: [], fix: `write the full repository path of ${m[1]} (a new file needs its full path, in output_paths)` });
86
+ }
87
+ return out;
88
+ }
89
+ const unknown = /^unknown scope path: (.+)$/.exec(message);
90
+ if (unknown) {
91
+ const paths = list(unknown[1]);
92
+ return paths.map(p => ({ verdict: 'clarify', code: 'unknown_scope_path', field: 'scope_paths', message: `scope path ${p} is not in the repository at the pinned revision`,
93
+ ...(error.candidates?.[p] ? { candidates: error.candidates[p] } : {}),
94
+ fix: error.candidates?.[p]?.length ? `did you mean ${error.candidates[p].join(' or ')}? Otherwise remove ${p} (a new file belongs in output_paths)` : `remove ${p} from scope_paths (a new file belongs in output_paths), or check the base_sha`,
95
+ ...(error.suggested_scope_paths ? { suggested_scope_paths: error.suggested_scope_paths } : {}) }));
96
+ }
97
+ for (const [pattern, build] of rules) {
98
+ const m = pattern.exec(message);
99
+ if (!m) continue;
100
+ m.input = message;
101
+ const built = build(m, error);
102
+ return (Array.isArray(built) ? built : [built]);
103
+ }
104
+ return [{ verdict: 'reject', code: 'refused', field: 'assignment', message, fix: 'see the message; correct the assignment and submit again' }];
105
+ }
106
+
107
+ export const strongest = reasons => reasons.reduce((v, r) => rank[r.verdict] > rank[v] ? r.verdict : v, 'admissible');
108
+ // Reasons as the public shape {code, field, message, fix, ...hints}.
109
+ // A `blocking` defer is a host that cannot run the job at all (no executor, unmet check prerequisite): it always refuses, and
110
+ // --queue-anyway does not apply, because a queued job would only fail later.
111
+ const publicReason = ({ verdict, retry, blocking, ...r }) => r;
112
+ function inputShape(inputs=[]) {
113
+ const repositoryPins=[];
114
+ for(const input of listOf(inputs)) {
115
+ if(!input||typeof input!=='object'||typeof input.github_repo!=='string'||!/^[-A-Za-z0-9_.]+\/[-A-Za-z0-9_.]+$/.test(input.github_repo)) continue;
116
+ const pin={github_repo:input.github_repo};
117
+ for(const key of ['base_sha','head_sha']) if(typeof input[key]==='string'&&/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i.test(input[key])) pin[key]=input[key];
118
+ repositoryPins.push(pin);
119
+ if(repositoryPins.length===20) break;
120
+ }
121
+ const values=listOf(inputs);
122
+ return {count:values.length,repository_pin_count:values.filter(x=>x&&typeof x==='object'&&typeof x.github_repo==='string').length,repository_pins:repositoryPins};
123
+ }
124
+ function safeRepositoryPaths(value=[]) {
125
+ const list=Array.isArray(value)?value:[];
126
+ const safe=list.filter(p=>typeof p==='string'&&p.length<=256&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(p)&&!p.startsWith('/')&&!p.includes('\\')&&!p.split('/').includes('..')&&!/[\x00-\x1f\x7f*?]/.test(p)&&!/\b(?:token|secret|password|api[_-]?key)=/i.test(p));
127
+ return {paths:safe.slice(0,100),count:list.length,omitted:list.length-Math.min(100,safe.length)};
128
+ }
129
+
130
+ // Fields the byte counter reads as text or as lists. Any other type is a malformed submission, not a size to count.
131
+ const TEXT_FIELDS = ['brief', 'expected_output', 'execution_scope', 'scope_text'];
132
+ const LIST_FIELDS = ['scope_paths', 'output_paths', 'scope_excluded', 'inputs'];
133
+ const listOf = value => (Array.isArray(value) ? value : []);
134
+ function malformedFields(r) {
135
+ if (!r || typeof r !== 'object') return [];
136
+ return [
137
+ ...TEXT_FIELDS.filter(k => r[k] != null && typeof r[k] !== 'string'),
138
+ ...LIST_FIELDS.filter(k => r[k] != null && !Array.isArray(r[k])),
139
+ ];
140
+ }
141
+
142
+ // Byte accounting of what the worker will see. `submitted` is the final adapter assignment after rendering (a structured
143
+ // assignment becomes a brief); `expanded` is what the bridge stores after it appends its allow-list or scope note. Adapter
144
+ // additions already live in `submitted.brief`, so the actual UTF-8 bytes count in both views.
145
+ // A malformed field yields no counts (null) and names the fields in `invalid_fields`; the compiler rejects it separately.
146
+ export function accountBytes(submitted, expanded) {
147
+ const invalid = [...new Set([...malformedFields(submitted), ...malformedFields(expanded)])];
148
+ if (invalid.length) return { brief: null, instructions: null, after_expansion: null, limits: { ...submissionLimits }, over_by: null, invalid_fields: invalid };
149
+ const sub ={ brief: bytes(submitted?.brief), instructions: submitted ? instructionBytes({ ...submitted, brief: submitted.brief ?? '', expected_output: submitted.expected_output ?? '' }) : 0 };
150
+ const after = expanded ? { brief: bytes(expanded.brief), instructions: instructionBytes(expanded) } : null;
151
+ const eff = after ?? sub;
152
+ const over = (n, limit) => Math.max(0, n - limit);
153
+ return {
154
+ brief: sub.brief, instructions: sub.instructions,
155
+ after_expansion: after,
156
+ limits: { ...submissionLimits },
157
+ over_by: { brief: over(eff.brief, submissionLimits.brief), instructions: over(eff.instructions, submissionLimits.instructions) },
158
+ };
159
+ }
160
+
161
+ // request: { assignment, review, backgroundPriority, excludeSensitive, sensitiveScopeOverride, jobExecution, requiredCapabilities,
162
+ // meta, maxQueued, target, deferQueued }
163
+ // deps: { render(assignment), shapeOk(payload), validate(payload, opts), admitExecution(payload, request), admitReadiness(payload, request),
164
+ // preflight(payload), state(request) -> {paused, pause_reason, worker_break, queued, claimed, ...}, kind(request, payload),
165
+ // defaultValidity(kind, request) -> queue-window evidence, retryAfterSeconds(request) }
166
+ // Resolves to {verdict, reasons, bytes, normalized_scope, valid_until, warnings, retry_after_seconds?, refusal?}. `refusal` (a
167
+ // non-enumerable property) is the first thrown error, so a caller that must keep its message can rethrow it.
168
+ // Infrastructure failures (the scanner could not run) are not verdicts: they propagate.
169
+ export async function compileWorkOrder(request, deps) {
170
+ const warnings = [];
171
+ const reasons = [];
172
+ let refusal = null;
173
+ let payload = null, expanded = null, readiness = null, preflight = null;
174
+ const fail = error => {
175
+ if (error?.code === 'DOT_BRIDGE_INFRASTRUCTURE') throw error;
176
+ refusal ??= error;
177
+ reasons.push(...reasonsFromError(error));
178
+ };
179
+ try { payload = deps.render(request.assignment); } catch (error) { fail(error); }
180
+ if(payload&&payload.valid_until!==undefined&&payload.valid_until!==null) {
181
+ const deadline=typeof payload.valid_until==='string'?Date.parse(payload.valid_until):NaN;
182
+ if(!Number.isFinite(deadline)) fail(new Error('invalid valid_until'));
183
+ else if(deadline<=Date.now()) fail(new Error('valid_until has expired'));
184
+ }
185
+ if (payload && !reasons.length && deps.shapeOk) {
186
+ try { deps.shapeOk(payload); } catch (error) { fail(error); }
187
+ }
188
+ // Order matches the old submit path: capability, then scope and size, then check readiness, then PR preflight.
189
+ if (payload && !reasons.length) {
190
+ try { deps.admitExecution(payload, request); } catch (error) { fail(error); }
191
+ }
192
+ if (payload && !reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) {
193
+ try { expanded = await deps.validate(payload, { warnings }); } catch (error) { expanded=error.expandedPayload??null; fail(error); }
194
+ }
195
+ if (expanded && !reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) {
196
+ try { readiness = await deps.admitReadiness(expanded, request); } catch (error) { fail(error); }
197
+ if (!reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) {
198
+ try { preflight = (await deps.preflight?.(expanded)) ?? null; } catch (error) { fail(error); }
199
+ }
200
+ }
201
+ // State-dependent reasons never hide a rejection: they are added only when the order itself is sound.
202
+ let retryAfter = null, state = null;
203
+ if (!reasons.some(r => r.verdict === 'reject' || r.verdict === 'clarify')) {
204
+ state = deps.state(request);
205
+ if (state.paused) reasons.push({ verdict: 'defer', code: 'worker_paused', field: 'worker', message: `the bridge is paused${state.pause_reason ? `: ${state.pause_reason}` : ''}`, fix: 'the work will queue and start after the owner resumes the bridge; use --refuse-defer to leave it unsubmitted', retry: true });
206
+ if (state.worker_break) reasons.push({ verdict: 'defer', code: 'usage_break', field: 'worker', message: `the worker is on a usage break since ${state.worker_break.since}`, fix: 'the work will queue and start after the usage break; use --refuse-defer to leave it unsubmitted', retry: true });
207
+ const threshold = request.deferQueued ?? deps.deferQueued ?? null;
208
+ if (threshold !== null && state.queued >= threshold) reasons.push({ verdict: 'defer', code: 'queue_depth', field: 'worker', message: `${state.queued} items are queued for the worker (defer threshold ${threshold})`, fix: 'the work will queue; use --refuse-defer to leave it unsubmitted', retry: true });
209
+ if (request.maxQueued != null && state.queued >= request.maxQueued && !reasons.some(r => r.code === 'queue_depth')) reasons.push({ verdict: 'defer', code: 'queue_full', field: 'max_queued', message: `worker queue is full (${state.queued} queued, in-flight cap ${request.maxQueued})`, fix: 'wait for queued work to drain, or use --refuse-defer to leave it unsubmitted', retry: true });
210
+ }
211
+ // A malformed field cannot be counted or admitted: a typed rejection, not a crash or a success-shaped count.
212
+ for (const field of new Set([...malformedFields(payload), ...malformedFields(expanded)])) {
213
+ const list = LIST_FIELDS.includes(field);
214
+ reasons.push({ verdict: 'reject', code: 'invalid_field', field, message: `${field} must be ${list ? 'a list' : 'text'}`, fix: `send ${field} as ${list ? 'a JSON array' : 'a string'} and submit again` });
215
+ }
216
+ const verdict = strongest(reasons);
217
+ if (verdict === 'defer') retryAfter = deps.retryAfterSeconds?.(request) ?? 300;
218
+ const effective = expanded ?? payload;
219
+ const kind = payload ? deps.kind(request, payload) : 'unknown';
220
+ const requested = effective?.valid_until ?? null;
221
+ const malformed = [...malformedFields(payload), ...malformedFields(expanded)].length > 0;
222
+ const invalidOrder = malformed || reasons.some(r => ['reject','clarify'].includes(r.verdict) || r.blocking);
223
+ const canSizeDefault = !requested && !invalidOrder && request.priority !== 'background' && !state?.paused && !state?.worker_break;
224
+ const dv = canSizeDefault && deps.defaultValidity ? deps.defaultValidity(kind, request) : null;
225
+ const result = {
226
+ verdict,
227
+ reasons: reasons.map(publicReason),
228
+ bytes: accountBytes(payload, expanded),
229
+ normalized_scope: effective ? {
230
+ ...Object.fromEntries([['scope_paths',effective.scope_paths??[]],['output_paths',effective.output_paths??[]],['scope_excluded',effective.scope_excluded??[]]].map(([name,value])=>{const shaped=safeRepositoryPaths(value);return [name,shaped.paths]})),
231
+ scope_path_count:listOf(effective.scope_paths).length,output_path_count:listOf(effective.output_paths).length,scope_excluded_count:listOf(effective.scope_excluded).length,
232
+ omitted_scope_path_count:safeRepositoryPaths(effective.scope_paths).omitted,omitted_output_path_count:safeRepositoryPaths(effective.output_paths).omitted,
233
+ inputs: inputShape(effective.inputs), execution_scope: effective.execution_scope ?? null,
234
+ } : null,
235
+ valid_until: requested ? { value: requested, source: 'requester' } : dv ? { value: dv.valid_until, source: dv.source??(dv.valid_until?'queue_p90':'insufficient_history'), window_ms: dv.window_ms??null, p90_ms: dv.p90_ms, samples: dv.samples, min_samples: dv.min_samples??null, factor: dv.factor, floor_ms: dv.floor_ms, cap_ms: dv.cap_ms, worker: dv.worker, kind: dv.kind, window_days: dv.window_days, expired_lower_bounds: dv.expired_lower_bounds } : { value: null, source: invalidOrder ? 'suppressed_invalid_order' : request.priority === 'background' ? 'suppressed_background' : state?.paused ? 'suppressed_paused' : state?.worker_break ? 'suppressed_usage_break' : 'insufficient_history' },
236
+ warnings,
237
+ ...(readiness ? { check_readiness: readiness } : {}),
238
+ ...(verdict === 'defer' ? { retry_after_seconds: retryAfter ?? 300 } : {}),
239
+ };
240
+ Object.defineProperties(result, {
241
+ refusal: { value: refusal, enumerable: false },
242
+ payload: { value: expanded, enumerable: false },
243
+ defaultValidity: { value: dv, enumerable: false },
244
+ preflight: { value: preflight, enumerable: false },
245
+ blocking: { value: reasons.some(r => r.blocking), enumerable: false },
246
+ });
247
+ return result;
248
+ }
249
+
250
+ // Text for a human: `dalan submit` prints this on stderr when the verdict is not admissible.
251
+ export function formatVerdict(order) {
252
+ const lines = [`verdict: ${order.verdict}`];
253
+ for (const r of order.reasons) {
254
+ lines.push(` ${r.code} (${r.field}): ${r.message}`);
255
+ if (r.candidates?.length) lines.push(` candidates: ${r.candidates.join(', ')}`);
256
+ lines.push(` fix: ${r.fix}`);
257
+ }
258
+ const b = order.bytes;
259
+ const a = b?.after_expansion;
260
+ if (b) lines.push(` bytes: brief ${fmt(b.brief)}${a ? ` -> ${fmt(a.brief)} after expansion` : ''} (limit ${fmt(b.limits.brief)}); instructions ${fmt(b.instructions)}${a ? ` -> ${fmt(a.instructions)}` : ''} (limit ${fmt(b.limits.instructions)})`);
261
+ if (order.retry_after_seconds) lines.push(` retry after about ${order.retry_after_seconds}s`);
262
+ if (order.valid_until?.value) lines.push(` valid_until: ${order.valid_until.value} (${order.valid_until.source})`);
263
+ else if(order.valid_until?.source==='insufficient_history') lines.push(` valid_until: no default (${order.valid_until.samples??'unknown'}/${order.valid_until.min_samples??'?'} queue samples; insufficient history)`);
264
+ return lines.join('\n');
265
+ }
@@ -0,0 +1,26 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // Guidance for a worker client that loads instruction files, such as opencode's "instructions" list.
5
+ // opencode's own prompt suggests an `execute` tool that the opencode worker recipe denies (it runs code that can
6
+ // reach the network); a model that follows the suggestion writes the call as text and stops. This text prevents that.
7
+ // `dalan try` and the service setup both write it next to resource-url, so one recipe path works for both.
8
+ export const WORKER_INSTRUCTIONS = `# Dalan worker
9
+
10
+ You work for a Dalan bridge. Its tools are MCP tools such as \`list_pending\`, \`get\`, \`claim\`, \`progress\` and \`finish\`. Your client may show them with the server's name in front, such as \`local_claim\`.
11
+
12
+ - Call tools only as structured tool calls. Never write a tool call as text.
13
+ - There is no \`execute\` tool for this worker. Call every tool directly.
14
+ - If no Dalan tool is in your tool list yet, call \`opencode_list_mcp_resources\` once; the Dalan tools are then available.
15
+ `;
16
+
17
+ export const WORKER_INSTRUCTIONS_FILE = 'worker-instructions.md';
18
+
19
+ // Writes the guidance into a bridge home (mode 0600), replacing an older copy.
20
+ export function writeWorkerInstructions(home) {
21
+ const file = path.join(home, WORKER_INSTRUCTIONS_FILE);
22
+ fs.rmSync(file, { force: true });
23
+ fs.writeFileSync(file, WORKER_INSTRUCTIONS, { mode: 0o600 });
24
+ fs.chmodSync(file, 0o600);
25
+ return file;
26
+ }
@@ -0,0 +1,4 @@
1
+ // The sentence a user gives their worker so it does one Dalan job and no other. `dalan try`, `dalan submit --brief` and
2
+ // the README all give this exact prompt, so it lives here once.
3
+ export const workerPrompt = requestId =>
4
+ `Request ${requestId} is your only job: claim it with Dalan, do what its brief asks, report progress and finish it with the claim_id. Stop if it is missing or cancelled. Claim no other job.`;