@tnunamak/dalan 0.0.0-stage → 0.5.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 (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -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 +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
package/src/server.mjs ADDED
@@ -0,0 +1,1340 @@
1
+ import {inspect} from 'node:util';
2
+ import { loopbackRequestAllowed } from './loopback.mjs';
3
+ import { defaultPath,workspaceRoot,rootWarnings } from './paths.mjs';
4
+ import { readEnv } from './env.mjs';
5
+ import http from 'node:http';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { createBuiltinHttpServer } from './builtin-http.mjs';
8
+ import { createProtocolOwnerWaiters } from './protocol-owner-waiters.mjs';
9
+ import {createProtocolServices} from './protocol-services.mjs';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import os from 'node:os';
13
+ import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
14
+ import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
15
+ import { Store, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
16
+ import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
17
+ import { sendWebhook, validSecret } from './webhooks.mjs';
18
+ import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
19
+ import { redactOutput, redactSinkText, redactLogEntry, registerSecret } from './redaction.mjs';
20
+ import { isCrash, safeDiagnostic } from './diagnostic.mjs';
21
+ import { Workspace, NOT_IDENTIFIED } from './workspace.mjs';
22
+ import { captureOwnerReportArtifact } from './owner-report-artifact.mjs';
23
+ import { loadBackgroundMaxInFlight, loadMainThreadIds, t3ReadToolsOff } from './limits.mjs';
24
+ import { parseDelivery } from './delivery.mjs';
25
+ import { createDestinations } from './destinations/index.mjs';
26
+ import { AckLedger } from './ack-ledger.mjs';
27
+ import { NotifyLedger, notifyKey } from './notify-ledger.mjs';
28
+ import { createDrainRunner } from './drain-runner.mjs';
29
+ import { renderAssignment, validateSubmissionAsync } from './submission-policy.mjs';
30
+ import { compileWorkOrder, reasonsFromError, strongest } from './work-order.mjs';
31
+ import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
32
+ import { preflightPR } from './pr-preflight.mjs';
33
+ import { admitImplementation } from './check-readiness.mjs';
34
+ import { parseExecution, parseRequiredCapabilities, admitHostExecution, withEvidence } from './execution.mjs';
35
+ import { loadCapacity } from './projects.mjs';
36
+ import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
37
+ import { beginMcpOutcome, recordMcpResponse, pathShape } from './mcp-outcome.mjs';
38
+ import { lifecycleMetrics, retainLifecycle } from './lifecycle.mjs';
39
+ import { normalizeMeta } from './objectives.mjs';
40
+ import { createRequestLog } from './request-log.mjs';
41
+ import { logShutdownSignals } from './shutdown-signal.mjs';
42
+ import { ADVERTISED_SCOPES, legacyScopeNames, wireScope } from './scopes.mjs';
43
+ import { acquireAsOwner, loadAsConfig, loadKeys } from './as-files.mjs';
44
+ import { createSignal } from './signal.mjs';
45
+ import { adminSocketPathError } from './admin-socket.mjs';
46
+ import { createToolRegistry, createT3PostHandler, RegistryError } from './tool-registry.mjs';
47
+
48
+ export async function main({protocolServiceAdapters,loopbackOnly=false}={}) {
49
+ if(typeof loopbackOnly!=='boolean')throw new Error('loopbackOnly must be boolean');
50
+ process.umask(0o077);
51
+ const home = os.homedir();
52
+ const configDir = defaultPath(home,'.config/dot-bridge');
53
+ const dataDir = defaultPath(home,'.local/share/dot-bridge');
54
+ const stateDir = defaultPath(home,'.local/state/dot-bridge');
55
+ const socketPathError=adminSocketPathError(path.join(dataDir,'admin.sock'));
56
+ if(socketPathError) throw socketPathError;
57
+ const pathWarnings=rootWarnings(home); // Capture before startup creates any files.
58
+ const loopback=readEnv('DALAN_LOOPBACK')==='1';
59
+ if(loopback && readEnv('DALAN_AUTH_MODE')!=='builtin') throw new Error('DALAN_LOOPBACK=1 requires DALAN_AUTH_MODE=builtin and valid bearer tokens');
60
+ const builtinMode=readEnv('DALAN_AUTH_MODE')==='builtin';
61
+ // Refuse a second owner before creating or changing env, operator keys, databases, logs or sockets.
62
+ const configuredBind=readEnv('DALAN_BIND_HOST');
63
+ if((loopback||builtinMode||loopbackOnly) && configuredBind!==undefined && configuredBind!=='127.0.0.1') throw new Error('loopback mode requires DALAN_BIND_HOST=127.0.0.1');
64
+ const testHttpAllowed=process.env.NODE_ENV!=='production'&&readEnv('DALAN_TEST_OAUTH')==='1';
65
+ // The effective listener host: loopback modes bind 127.0.0.1, otherwise the configured host or the 0.0.0.0 default.
66
+ const effectiveBindHost=(loopback||builtinMode||loopbackOnly)?'127.0.0.1':(configuredBind||'0.0.0.0');
67
+ const externalPublicBind=readEnv('DALAN_AUTH_MODE')==='oauth'&&!loopback&&!loopbackOnly&&!isLoopbackBindHost(configuredBind||'0.0.0.0');
68
+ const insecureFlags=['DALAN_DEV_ALLOW_UNAUTHENTICATED','DALAN_ALLOW_INSECURE_PUBLIC'].filter(name=>process.env.NODE_ENV!=='production'&&readEnv(name)==='1');
69
+ if(externalPublicBind && readEnv('DALAN_TRUST_PROXY')!=='1' && !testHttpAllowed) {
70
+ if(insecureFlags.length) throw new Error(`refusing to start on a non-loopback bind with ${insecureFlags.join(' and ')} set: neither flag bypasses the TLS reverse proxy requirement; unset the flag, bind to loopback (DALAN_BIND_HOST=127.0.0.1, ::1 or localhost), or put a TLS reverse proxy in front and set DALAN_TRUST_PROXY=1`);
71
+ throw new Error('non-loopback HTTP requires a TLS reverse proxy and DALAN_TRUST_PROXY=1; use DALAN_LOOPBACK=1 for local HTTP');
72
+ }
73
+ const asOwner=builtinMode?acquireAsOwner(configDir):null;
74
+ for (const dir of [configDir, dataDir, stateDir]) fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
75
+ const envPath = path.join(configDir, 'env');
76
+ if (!fs.existsSync(envPath)) fs.writeFileSync(envPath, `BRIDGE_PATH_SECRET=${randomBytes(32).toString('hex')}\n`, { mode: 0o600, flag: 'wx' });
77
+ fs.chmodSync(envPath, 0o600);
78
+ const secret = /^BRIDGE_PATH_SECRET=(.+)$/m.exec(fs.readFileSync(envPath, 'utf8'))?.[1];
79
+ if (!secret || !/^[a-f0-9]{64}$/.test(secret)) throw new Error('invalid BRIDGE_PATH_SECRET');
80
+ const operatorFile=path.join(configDir,'operator.key');
81
+ if (!fs.existsSync(operatorFile)) fs.writeFileSync(operatorFile,randomBytes(32).toString('hex')+'\n',{mode:0o600,flag:'wx'});
82
+ fs.chmodSync(operatorFile,0o600);
83
+ const operatorKey=fs.readFileSync(operatorFile,'utf8').trim();
84
+ // The path secret and operator key are credentials this process holds: every sink masks them by value.
85
+ registerSecret(secret);registerSecret(operatorKey);
86
+ const externalOauth=builtinMode?null:authConfig();
87
+ const workersFile=readEnv('DALAN_WORKERS_FILE')||path.join(configDir,'workers.json');
88
+ const workers=loadWorkers(workersFile,{builtin:builtinMode,auditGrants:true}),legacyProfile=workers.legacy===true;
89
+ const redeliveryLimits=loadRedeliveryLimits();
90
+ const asConfig=builtinMode?loadAsConfig(configDir,{loopback,allowHttp:process.env.NODE_ENV!=='production'&&readEnv('DALAN_TEST_OAUTH')==='1'}):null;
91
+ if(builtinMode) loadKeys(configDir);
92
+ const oauth= builtinMode ? {builtin:true,OAUTH_AUDIENCE:new URL(`/${secret}/mcp`,asConfig.public_url).href,OAUTH_CHALLENGE_SCOPE:'dalan.read dalan.work'} : externalOauth;
93
+ assertPublicRouteAuth(oauth,undefined,{bindHost:effectiveBindHost});
94
+ const oauthMetadata=oauth??authConfig(undefined,false);
95
+ if(oauthMetadata&&readEnv('DALAN_CATALOG_PROFILE')==='legacy-v46') oauthMetadata.legacyScopeNames=true;
96
+ if(oauthMetadata) oauthMetadata.OAUTH_RESOURCE_METADATA=new URL(`/.well-known/oauth-protected-resource/${secret}/mcp`,oauthMetadata.OAUTH_AUDIENCE).href;
97
+ const claimCapacity=loadCapacity();
98
+ const backgroundMaxInFlight=loadBackgroundMaxInFlight();
99
+ const catalogProfile=readEnv('DALAN_CATALOG_PROFILE')||'stable';
100
+ const t3ToolsSetting=readEnv('DALAN_ENABLE_T3_TOOLS')??'0';
101
+ if(!['0','1'].includes(t3ToolsSetting))throw new Error('DALAN_ENABLE_T3_TOOLS must be 0 or 1');
102
+ const t3ToolsEnabled=t3ToolsSetting==='1';
103
+ if(!['stable','questions-v1','protocol-v0','legacy-v46'].includes(catalogProfile)) throw new Error('DALAN_CATALOG_PROFILE must be stable, questions-v1 or protocol-v0; legacy-v46 is also supported');
104
+ if(protocolServiceAdapters&&catalogProfile!=='protocol-v0')throw new Error('protocol dependencies require protocol-v0 profile');
105
+ const port=Number(readEnv('DALAN_PORT')||8787);
106
+ if(!Number.isInteger(port)||port<0||port>65535) { const error=new RangeError(`options.port should be >= 0 and < 65536. Received ${port}`); error.code='ERR_SOCKET_BAD_PORT'; throw error; }
107
+ if(loopback && (new URL(asConfig.public_url).origin!==`http://127.0.0.1:${port}` || port===0)) throw new Error('loopback public_url must be http://127.0.0.1:<DALAN_PORT> with a fixed port');
108
+ const envDeferQueued=readEnv('DALAN_DEFER_QUEUED')===undefined?null:Number(readEnv('DALAN_DEFER_QUEUED'));
109
+ if(envDeferQueued!==null&&(!Number.isSafeInteger(envDeferQueued)||envDeferQueued<1)) throw new Error('DALAN_DEFER_QUEUED must be a positive integer');
110
+ loadMainThreadIds();
111
+ t3ReadToolsOff();
112
+ if(t3ToolsEnabled&&!legacyProfile) {
113
+ const t3Workers=[...workers.workers].filter(([,worker])=>worker.capabilities.has('t3'));
114
+ if(t3Workers.length) {
115
+ const {t3Available}=await import('./t3.mjs');
116
+ for(const [name] of t3Workers) if(!t3Available()) { console.error(`dalan: startup: worker ${name} has capability t3 but t3code was not found on PATH; install T3 Code or remove the capability`); process.exit(1); }
117
+ }
118
+ }
119
+ function currentRepoPolicy() {
120
+ if(!legacyProfile&&!fs.existsSync(workersFile)) throw new Error('worker profile disappeared; repository policy is unavailable');
121
+ return loadWorkers(workersFile,{builtin:builtinMode,auditGrants:true,
122
+ builtinConnectionIds:worker=>as.store.liveConnectionIds(worker)});
123
+ }
124
+ // Owner-only log line: keep nested causes, but bound the size and never run a custom inspect hook from a loaded error.
125
+ const CONFIG_ERROR_INSPECT={depth:6,maxStringLength:8192,maxArrayLength:50,breakLength:Infinity,customInspect:false};
126
+ const existingInstall=hasInstalledDatabase(path.join(dataDir,'bridge.db'));
127
+ const explicitLegacy=readEnv('DALAN_LEGACY_PROFILE')==='1'||fs.existsSync(legacyMarkerPath(configDir));
128
+ // A start with no workers.json used to invent a worker named "dot". Only an install that already has a database keeps
129
+ // that behavior; a fresh install must name its worker. `dalan init --legacy` (which writes the legacy-profile marker) or
130
+ // DALAN_LEGACY_PROFILE=1 opts back in for hand-run setups. An empty or schema-less bridge.db does not count as an install.
131
+ if(legacyProfile&&!existingInstall&&!explicitLegacy) {
132
+ asOwner?.release();
133
+ console.error(`dalan: startup: no worker is configured (${workersFile} is missing); run \`dalan init --worker NAME\` to create one, or \`dalan init --legacy\` (or set DALAN_LEGACY_PROFILE=1) to keep the single-worker legacy profile`);
134
+ process.exit(1);
135
+ }
136
+ const store = new Store(path.join(dataDir, 'bridge.db'),{
137
+ // The caller sees one fixed configuration error; the real one stays in this server's log.
138
+ onConfigError:error=>log({kind:'destination_configuration_error',reason:inspect(error,CONFIG_ERROR_INSPECT)}),
139
+ workers,destinationProfile:currentRepoPolicy,allowedDotSubjects:externalOauth?externalOauth.OAUTH_ALLOWED_SUBJECTS.split(','):['local-principal'],
140
+ limits:redeliveryLimits,
141
+ ...(process.env.CONFORMANCE_CLOCK_FILE?{elapsedNow:Date.now,bootId:'conformance-clock'}:{}),
142
+ skipExpireMs:(h=>Number.isFinite(h)&&h>0?h*3600000:undefined)(Number(readEnv('DALAN_SKIP_EXPIRE_HOURS'))),
143
+ // Intentional service startup opts past Store's accidental-migration footgun guard.
144
+ deferSubscriptionRetirement:true,markProfileModeSeen:!legacyProfile,allowDefaultHomeMigration:true
145
+ });
146
+ const ackLedger=new AckLedger(path.join(dataDir,'delivery-acks.db'));
147
+ const notifyLedger=new NotifyLedger(path.join(dataDir,'notify-sent.db'));
148
+ process.on('exit',()=>{try{ackLedger.close();}catch{}try{notifyLedger.close();}catch{}});
149
+ if(legacyProfile&&store.profileModeSeen()&&readEnv('DALAN_LEGACY_PROFILE')!=='1') {
150
+ store.db.close();
151
+ asOwner?.release();
152
+ console.error(`dalan: startup: worker profile file ${workersFile} is missing after a profile was loaded; restore it or set DALAN_LEGACY_PROFILE=1 to allow legacy mode`);
153
+ process.exit(1);
154
+ }
155
+ seedWorkerRepos(workersFile,store.db,{existingInstall});
156
+ let t3AuditPromise;
157
+ const loadT3Audit=()=>t3AuditPromise??=import('./t3-audit.mjs').then(audit=>{audit.initT3Audit(store.db);return audit;});
158
+ if(t3ToolsEnabled) await loadT3Audit();
159
+ // A valid but unallocated ID preserves each tool's existing absent-request errors. Never accept it as an owner target.
160
+ const absentId=`req_${randomUUID()}`;
161
+ if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
162
+ const socket = path.join(dataDir, 'admin.sock');
163
+ const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
164
+ logShutdownSignals(log);
165
+ // The owner-side tool registry. It has no MCP surface here: changing it never changes tools/list.
166
+ const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
167
+ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{t3_post:t3PostHandler},
168
+ audit:entry=>log({kind:'tool_registry',...entry})});
169
+ for(const warning of pathWarnings) {
170
+ const entry={kind:'root_passed_over',...warning};
171
+ log(entry);console.error(JSON.stringify(redactLogEntry(entry)));
172
+ }
173
+ const publicPath = `/${secret}/mcp`;
174
+ if(!t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) {
175
+ log({kind:'t3_tools_disabled',worker,setting:'DALAN_ENABLE_T3_TOOLS=1'});
176
+ console.error(`dalan: startup WARNING: worker "${worker}" has t3 capability but reverse-control tools are off; set DALAN_ENABLE_T3_TOOLS=1`);
177
+ }
178
+ if(t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capabilities.has('t3')) console.error(`dalan: startup NOTICE: worker "${worker}" holds the t3 capability: it can list, read and send to any T3 thread and project on this computer. Grant it only to your own harness.`);
179
+ const startupPolicy=currentRepoPolicy();
180
+ for(const worker of workers.workers.keys()) if(startupPolicy.repoPolicy(worker)?.repos.length===0) {
181
+ const blocked=store.db.prepare("SELECT count(*) n FROM assignments WHERE target_worker=? AND status='queued' AND json_type(payload,'$.inputs[0].github_repo')='text'").get(worker).n;
182
+ const entry={kind:'repository_policy_empty',worker,queued_repo_jobs_blocked:blocked};
183
+ log(entry);console.error(JSON.stringify(redactLogEntry(entry)));
184
+ }
185
+ // Built-in authorization server (DALAN_AUTH_MODE=builtin): the bridge issues and checks its own opaque tokens. Without it,
186
+ // DALAN_AUTH_MODE=oauth keeps the external-issuer path (Keycloak JWTs) exactly as it was.
187
+ let as=null;
188
+ if(builtinMode) {
189
+ const { createAs } = await import('./as.mjs');
190
+ const testHttp=process.env.NODE_ENV!=='production'&&readEnv('DALAN_TEST_OAUTH')==='1';
191
+ const mcpUrl=oauth.OAUTH_AUDIENCE;
192
+ as=createAs({owner:asOwner,dir:configDir,resource:mcpUrl,allowHttp:testHttp,loopback,workerNames:()=>[...workers.workers.keys()],log,
193
+ onConnectionRevoked:(connectionId,reason)=>store.retireConnectionSubscriptions(connectionId,`connection ${reason}`)});
194
+ oauth.OAUTH_ISSUER=as.issuer; oauth.OAUTH_AUDIENCE=as.resource;
195
+ store.connectionIsLive=connectionId=>as.store.connectionIsLive(connectionId);
196
+ }
197
+ // Wake signal for hook-driven workers: built-in mode only, so oauth and legacy modes have no such route.
198
+ const signal=as?createSignal({dir:configDir,store,workerNames:()=>[...workers.workers.keys()],publicUrl:as.publicUrl,log}):null;
199
+ store.retireUnknownSubscriptions();
200
+ // Config and auth validation above must finish before Store opens or migrates the database.
201
+ store.capacity=claimCapacity; store.limits=redeliveryLimits; store.backgroundMaxInFlight=backgroundMaxInFlight;
202
+ const workspaceEnabled=!!oauth && readEnv('DALAN_ENABLE_WORKSPACE')==='1';
203
+ const workspace=workspaceEnabled?new Workspace(store):null;
204
+ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(store,{
205
+ operatorKey,receiptDir:path.join(workspaceRoot(home),'host-receipts'),
206
+ transport:protocolServiceAdapters?.transport,resolveStopEvidence:protocolServiceAdapters?.resolveStopEvidence,
207
+ }):null;
208
+ const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
209
+ const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
210
+ if(Buffer.byteLength(iconSource)>10000) throw new Error('server icon exceeds 10 KB');
211
+ const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':'0.5.2',icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
212
+ // A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
213
+ const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
214
+ function mayPrepareCheckMetadata(response,worker,subject=null) {
215
+ const target=response.target_worker??worker;
216
+ const repo=response.assignment.inputs?.find(input=>input?.github_repo!==undefined)?.github_repo;
217
+ if(repo===undefined||repoPolicyFor(response.assignment).allowsRepo(target,repo)) return true;
218
+ // Revocation blocks new preparation, but an existing live grant may still finish.
219
+ const claim=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(response.request_id);
220
+ return response.status==='claimed'&&!response.cancelled_at&&claim?.state==='active'&&claim.worker===target&&
221
+ (subject===null||claim.subject===subject)&&!store.leaseExpired(claim);
222
+ }
223
+ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=null) {
224
+ response=withoutT3(response);
225
+ const artifacts=store.sealedUploads(response.request_id,{clientIds:workerSurface});
226
+ // origin_claim_id is a claim capability: worker replies never carry it, and the owner surface keeps it.
227
+ if(workerSurface) for(const artifact of artifacts) delete artifact.origin_claim_id;
228
+ if(!workerSurface) artifacts.push(...store.db.prepare("SELECT id,kind,size,sha256 FROM artifacts WHERE request_id=? AND sealed=1 AND kind='owner-report' ORDER BY created_at,id").all(response.request_id));
229
+ const checks=store.db.prepare("SELECT j.id check_run_id,j.check_id,CASE WHEN j.status='completed' THEN COALESCE(r.diff_sha256,j.diff_sha256) ELSE j.diff_sha256 END diff_sha256,j.status,j.error,j.output_preview,r.exit_code,r.timed_out,r.output_artifact_id,r.output_sha256,r.duration_ms,r.evidence FROM check_jobs j LEFT JOIN check_runs r ON r.id=j.id WHERE j.request_id=? ORDER BY j.started_at").all(response.request_id).map(withEvidence);
230
+ const blocker=workerSurface?null:queuedRepositoryBlocker(response);
231
+ const enriched={...response,artifacts,checks,...(blocker?{queue_blocker:blocker}:{}),...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{})};
232
+ if(!workspaceEnabled||response.assignment?.execution_scope!=='implementation') return enriched;
233
+ const target=store.db.prepare('SELECT target_worker FROM assignments WHERE request_id=?').get(response.request_id)?.target_worker??worker;
234
+ if(!mayPrepareCheckMetadata(response,target,subject)) return {...enriched,available_checks:[],available_checks_error:'repository_policy_denied'};
235
+ const execution=response.execution??store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(response.request_id).execution;
236
+ return {...enriched,...workspace.availableChecksResponse(response.assignment,null,execution,target)};
237
+ }
238
+ // Worker-written text in an owner read is masked on the way out. The database keeps the exact text, so a retried finish
239
+ // with the same body stays the same finish.
240
+ const maskText=value=>typeof value==='string'?redactOutput(value):value;
241
+ function maskedForOwner(response) {
242
+ const out={...response};
243
+ if(out.report) out.report={...out.report,summary:maskText(out.report.summary),result:maskText(out.report.result)};
244
+ if(out.late_evidence) out.late_evidence={...out.late_evidence,summary:maskText(out.late_evidence.summary)};
245
+ if(Array.isArray(out.progress)) out.progress=out.progress.map(row=>({...row,note:maskText(row.note)}));
246
+ if(out.claim?.activity) out.claim={...out.claim,activity:{...out.claim.activity,last_tool_error:maskText(out.claim.activity.last_tool_error)}};
247
+ return out;
248
+ }
249
+ const publicClaimFields=['request_id','claimant','subject','claimed_at','last_progress_at','last_claim_activity_at','worker','epoch','state','abandoned_at','abandon_reason','lease_expires_at','activity','destination_revision'];
250
+ // Worker-visible get must never carry claim capability values. The claim-field
251
+ // allowlist above already drops claim_id; this recursive pass additionally drops
252
+ // claim_id, origin_claim_id and acquisition_id from every other generated
253
+ // worker-get field (claim activity, sealed-upload metadata, check and report
254
+ // evidence, delivery arguments, nested objects and arrays included). The
255
+ // submitted assignment is split out first and restored unchanged: same-named
256
+ // keys inside assignment inputs or prose are ordinary data, not capability
257
+ // values. Key-based redaction does not remove capability values embedded in
258
+ // arbitrary strings or assignment prose. Owner reads do not use this
259
+ // projection and keep the full evidence, as do stored reports, artifact
260
+ // provenance and database rows. A successful claim response still returns the
261
+ // newly acquired grant; that delivery is not a worker get.
262
+ const workerHiddenMetadataKeys=new Set(['claim_id','origin_claim_id','acquisition_id']);
263
+ function omitWorkerCapabilityKeys(value) {
264
+ if(Array.isArray(value)) return value.map(omitWorkerCapabilityKeys);
265
+ if(value&&typeof value==='object') return Object.fromEntries(Object.entries(value).filter(([key])=>!workerHiddenMetadataKeys.has(key)).map(([key,child])=>[key,omitWorkerCapabilityKeys(child)]));
266
+ return value;
267
+ }
268
+ function publicWorkerGet(response) {
269
+ if(response.destination_approval) {
270
+ const {actor,...approval}=response.destination_approval;
271
+ response={...response,destination_approval:approval};
272
+ }
273
+ const questions=store.questions(response.request_id).map(({claim_id,subject,...question})=>question);
274
+ if(questions.length) response={...response,questions};
275
+ const {assignment,...rest}=response;
276
+ const projected=rest.claim?{...rest,claim:Object.fromEntries(publicClaimFields.filter(key=>Object.hasOwn(rest.claim,key)).map(key=>[key,rest.claim[key]]))}:rest;
277
+ const redacted=omitWorkerCapabilityKeys(projected);
278
+ return Object.hasOwn(response,'assignment')?{...redacted,assignment}:redacted;
279
+ }
280
+ function crashAt(point, requestId) { return readEnv('DALAN_CRASH_AT')===point && (!readEnv('DALAN_CRASH_REQUEST_ID') || readEnv('DALAN_CRASH_REQUEST_ID')===requestId); }
281
+ const T3_READ_TOOLS_OFF={off:true,message:'T3 thread tools are off; the needed context is inlined in your assignment.'};
282
+ // The final boundary for every HTTP response: error text and error data pass the redactor whatever path built them.
283
+ function json(res, status, value) { if (value && typeof value === 'object' && !Array.isArray(value)) for (const key of ['error', 'reason', 'check_metadata_error']) if (value[key] !== undefined) value = { ...value, [key]: redactOutput(value[key]) };
284
+ const body = JSON.stringify(value), bytes = Buffer.byteLength(body); recordMcpResponse(res,value,bytes); res.writeHead(status, { 'content-type': 'application/json', 'content-length': bytes }); res.end(body); }
285
+ async function readBody(req, outcome) {
286
+ const chunks = []; let size = 0;
287
+ for await (const chunk of req) {
288
+ size += chunk.length;
289
+ if (size > 1024 * 1024) { if(outcome)outcome.error_type='body_too_large';throw new Error('body too large'); }
290
+ chunks.push(chunk);
291
+ }
292
+ return Buffer.concat(chunks).toString('utf8');
293
+ }
294
+ function rpcError(id, code, message, data) { return { jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } }; }
295
+ function str(value, name, max = 65536) { if (typeof value !== 'string' || !value || Buffer.byteLength(value) > max) throw new Error(`invalid ${name}`); return value; }
296
+ function id(value,name='request_id') { const s=str(value,name,128); if(!/^[-\w]{8,128}$/.test(s)) throw new Error(`invalid ${name}`); return s; }
297
+ function authorize(received,expected,label) { const a=Buffer.from(received||''),b=Buffer.from(expected); if(a.length!==b.length||!timingSafeEqual(a,b)) throw new Error(`invalid ${label}`); }
298
+ function adminOwner(req,idValue) { store.owner(id(idValue),req.headers['x-owner-capability']); }
299
+ function adminOperator(req) { authorize(req.headers['x-operator-key'],operatorKey,'operator key'); }
300
+
301
+ const event = {
302
+ name: 'assignment.available', description: 'An assignment or lightweight message is available. Claim assignments by request_id; read messages by message_id. Use list_pending after missed events.',
303
+ delivery: ['webhook'], inputSchema: { type: 'object', properties: {}, additionalProperties: false },
304
+ payloadSchema: { type: 'object', properties: { request_id: { type: 'string' }, message_id: { type: 'string' }, title: { type: 'string' } }, required: ['title'], additionalProperties: false }
305
+ };
306
+ const schema=(properties,required=[])=>({type:'object',properties,required,additionalProperties:false});
307
+ const string={type:'string'}, integer={type:'integer'};
308
+ const threadId={type:'string',maxLength:128};
309
+ const short={type:'string',maxLength:512};
310
+ const hashField={type:'string',maxLength:128},keyField={type:'string',minLength:1,maxLength:128};
311
+ const message={type:'string',maxLength:262144};
312
+ const bool={type:'boolean'};
313
+ const optionsArray={type:'array',items:string,maxItems:16};
314
+ const tools = [
315
+ { name:'list_pending',description:'List up to 50 queued assignment IDs and titles.',inputSchema:schema({}) },
316
+ { name:'claim',description:'Claim one immutable assignment and see available_checks before choosing run_check.check_id. lease_ms sets this grant’s duration, up to the owner-configured maximum. An exact live retry retains the grant and its stored duration.',inputSchema:schema({request_id:string,claimant:string,acquisition_id:{type:'string',minLength:1,maxLength:128,pattern:'^[A-Za-z0-9_-]+$'},lease_ms:{type:'integer',minimum:1,maximum:store.limits.leaseMs}},['request_id','claimant']) },
317
+ { name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
318
+ { name:'ack_message',description:'Acknowledge a lightweight message after reading it; no claim or finish is needed.',inputSchema:schema({message_id:string},['message_id']) },
319
+ { name:'progress',description:'Append progress. Set blocker:true or start note with BLOCKED: or QUESTION: to forward a question to the owner thread. A note over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,note:message,blocker:bool},['request_id','claim_id','note']) },
320
+ { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096}},['request_id','claim_id','question_id','text']) },
321
+ { name:'consume_answer',description:'Read and durably consume the identified question answer under its original current grant. Refuses unanswered or stale-epoch questions.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128}},['request_id','claim_id','question_id']) },
322
+ { name:'finish',description:'Store a terminal worker report; completion is not owner acceptance. summary is optional: when absent it is the first line of result, and one over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,outcome:{type:'string',enum:['completed','blocked','failed']},summary:message,result:{type:'string',maxLength:262144},artifact_ids:{type:'array',items:string,maxItems:8}},['request_id','claim_id','outcome','result']) },
323
+ { name:'list_files',description:"List files in this assignment's checked-out repository workspace. Read-only; scoped to the assignment. When truncated is true, pass next_cursor as cursor to get the next page.",inputSchema:schema({request_id:string,claim_id:string,path:string,limit:{type:'integer',minimum:1,maximum:200},cursor:{type:'string',maxLength:1024}},['request_id','claim_id']) },
324
+ { name:'read_file',description:"Read a file from this assignment's checked-out repository workspace. Read-only; scoped to the assignment. The result has end_line (the last line included) and truncated (true when the 32 KiB cap cut the requested window).",inputSchema:schema({request_id:string,claim_id:string,path:string,start_line:{type:'integer',minimum:1},max_lines:{type:'integer',minimum:1,maximum:200}},['request_id','claim_id','path']) },
325
+ { name:'apply_patch',description:"Apply a unified diff to this assignment's private workspace copy. Changes stay local until the owner reviews them; nothing is pushed.",inputSchema:schema({request_id:string,claim_id:string,patch:{type:'string',maxLength:262144}},['request_id','claim_id','patch']) },
326
+ { name:'run_check',description:'Start a listed repository check. Returns immediately for long checks; poll workspace_result for status and result. Fast checks may return a completed receipt. Unknown check_id returns available IDs.',inputSchema:schema({request_id:string,claim_id:string,check_id:string},['request_id','claim_id','check_id']) },
327
+ { name:'workspace_result',description:'Read the current diff, available_checks, check receipts, and artifact references.',inputSchema:schema({request_id:string,claim_id:string},['request_id','claim_id']) },
328
+ { name:'artifact_chunk',description:'Upload a sealed artifact for any claimed assignment, including read-only assignments.',inputSchema:schema({request_id:string,claim_id:string,artifact_id:string,offset:{type:'integer',minimum:0},data_base64:string,final:{type:'boolean'},sha256:{type:'string',pattern:'^[a-fA-F0-9]{64}$'}},['request_id','claim_id','artifact_id','offset','data_base64']) },
329
+ { name:'t3_thread_list',description:'List T3 threads across projects or filter by project/cwd and status.',inputSchema:schema({projectId:threadId,cwd:short,workspaceMode:short,status:{type:'string',enum:['active','settled','all']}}) },
330
+ { name:'t3_thread_read',description:'Read a bounded T3 thread transcript.',inputSchema:schema({threadId,detail:{type:'string',enum:['answers','messages','full']},turns:{type:'integer',minimum:1,maximum:100},firstTurn:bool,maxChars:{type:'integer',minimum:1,maximum:20000}},['threadId']) },
331
+ { name:'t3_thread_create',description:'Create a T3 thread in any project or directory and start its first turn.',inputSchema:schema({projectId:threadId,cwd:short,prompt:message,workspaceMode:short,projectPolicy:short,provider:short,model:short,thinkingEffort:short,permission:short,interactionMode:short,environmentMode:short,speedMode:short,open:short,options:optionsArray},['prompt']) },
332
+ { name:'t3_thread_send',description:'Send to any T3 thread, including settled threads when wakeSettled is true.',inputSchema:schema({threadId,message,mode:{type:'string',enum:['refuse','queue','steer','restart']},wakeSettled:bool,provider:short,model:short,thinkingEffort:short,permission:short,interactionMode:short,speedMode:short,options:optionsArray},['threadId','message']) },
333
+ { name:'t3_thread_wait',description:'Wait at most 120 seconds for a T3 turn; returns partial state on timeout.',inputSchema:schema({threadId,timeoutMs:{type:'integer',minimum:1,maximum:120000},detail:{type:'string',enum:['answers','messages','full']},maxChars:{type:'integer',minimum:1,maximum:20000}},['threadId']) },
334
+ { name:'t3_thread_set',description:'Change a T3 thread provider, model, effort, permission, or mode.',inputSchema:schema({threadId,provider:short,model:short,thinkingEffort:short,permission:short,interactionMode:short,speedMode:short,options:optionsArray},['threadId']) },
335
+ { name:'notify_owner',description:'Send a short notification to the owner through the configured ntfy alert path.',inputSchema:schema({text:{type:'string',maxLength:1000}},['text']) },
336
+ { name:'list_tools',description:'Call this first to learn which tools you can use. Returns registry_version and each available tool with its description, input schema, class (read or write) and schema_hash.',inputSchema:schema({}) },
337
+ { name:'call_tool_read',description:'Run an available read-only tool by name, as listed by list_tools. Pass its schema_hash from list_tools.',inputSchema:schema({tool:short,arguments:{type:'object',additionalProperties:true},schema_hash:hashField,idempotency_key:keyField},['tool','arguments']) },
338
+ { name:'call_tool_write',description:'Run an available tool that changes state or sends something, by name, as listed by list_tools. Requires its schema_hash from list_tools and an idempotency_key that is new for each distinct request.',inputSchema:schema({tool:short,arguments:{type:'object',additionalProperties:true},schema_hash:hashField,idempotency_key:keyField},['tool','arguments','schema_hash','idempotency_key']) }
339
+ ].filter(tool=>(catalogProfile!=='stable'||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
340
+ // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
341
+ if(catalogProfile==='legacy-v46') {
342
+ const names=new Set(['list_pending','claim','get','ack_message','progress','finish',
343
+ 'list_files','read_file','apply_patch','run_check','workspace_result','artifact_chunk']);
344
+ for(let i=tools.length-1;i>=0;i--) if(!names.has(tools[i].name)) tools.splice(i,1);
345
+ const claim=tools.find(tool=>tool.name==='claim');
346
+ claim.description='Claim one immutable assignment and see available_checks before choosing run_check.check_id. With resume wake enabled, only a retry with the same claimant and acquisition_id receives the same active claim.';
347
+ delete claim.inputSchema.properties.lease_ms;
348
+ // The frozen v46 catalog predates optional summaries and the uncapped summary and note fields; the server still repairs them.
349
+ const frozenProgress=tools.find(tool=>tool.name==='progress'),frozenFinish=tools.find(tool=>tool.name==='finish');
350
+ frozenProgress.description='Append progress. Set blocker:true or start note with BLOCKED: or QUESTION: to forward a question to the owner thread.';
351
+ frozenProgress.inputSchema.properties.note={type:'string',maxLength:4096};
352
+ frozenFinish.description='Store a terminal worker report; completion is not owner acceptance.';
353
+ frozenFinish.inputSchema.properties.summary={type:'string',maxLength:4096};
354
+ frozenFinish.inputSchema.required=['request_id','claim_id','outcome','summary','result'];
355
+ // The frozen v46 catalog predates list_files paging.
356
+ const listing=tools.find(tool=>tool.name==='list_files');
357
+ listing.description="List files in this assignment's checked-out repository workspace. Read-only; scoped to the assignment.";
358
+ delete listing.inputSchema.properties.cursor;
359
+ // The frozen v46 catalog predates the end_line and truncated result fields.
360
+ tools.find(tool=>tool.name==='read_file').description="Read a file from this assignment's checked-out repository workspace. Read-only; scoped to the assignment.";
361
+ }
362
+ // Protocol fields are an explicit catalog release. Existing profiles retain their
363
+ // definitions byte for byte, including their argument validation.
364
+ if(catalogProfile==='protocol-v0') {
365
+ tools.push({name:'renew_claim',description:'Renew a current protocol grant using a durable command key and expected revision. An exact retry returns the original deadline; expired grants cannot renew.',inputSchema:schema({request_id:string,claim_id:string,lease_ms:{type:'integer',minimum:1,maximum:store.limits.leaseMs}},['request_id','claim_id','lease_ms'])});
366
+ const commands=new Set(['claim','progress','ask_question','consume_answer','finish','artifact_chunk','renew_claim']);
367
+ for(const tool of tools) if(commands.has(tool.name)) Object.assign(tool.inputSchema.properties,{
368
+ command_key:{type:'string',minLength:1,maxLength:512},
369
+ expected_revision:{type:'integer',minimum:0},
370
+ epoch:{type:'integer',minimum:1},
371
+ });
372
+ tools.find(tool=>tool.name==='artifact_chunk').inputSchema.properties.size={type:'integer',minimum:0};
373
+ }
374
+ // Catalog v2: MCP annotations and three fixed registry tools. The four T3 worker tools (create, send, wait, set) stay
375
+ // top-level tools, advertised only with DALAN_ENABLE_T3_TOOLS=1.
376
+ // legacy-v46 stays byte for byte. New abilities are registered tools behind call_tool_read and call_tool_write,
377
+ // never new tool names, descriptions or schemas.
378
+ const READ={readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false};
379
+ const WRITE=idempotentHint=>({readOnlyHint:false,destructiveHint:false,idempotentHint,openWorldHint:false});
380
+ const toolAnnotations={
381
+ list_pending:READ,get:READ,list_files:READ,read_file:READ,workspace_result:READ,t3_thread_list:READ,t3_thread_read:READ,t3_thread_wait:READ,t3_thread_create:WRITE(false),t3_thread_send:WRITE(false),t3_thread_set:WRITE(true),list_tools:READ,call_tool_read:READ,call_tool_write:WRITE(false),
382
+ claim:WRITE(true),ack_message:WRITE(true),progress:WRITE(false),ask_question:WRITE(true),consume_answer:WRITE(true),finish:WRITE(true),
383
+ apply_patch:WRITE(false),run_check:WRITE(false),artifact_chunk:WRITE(true),renew_claim:WRITE(true),
384
+ notify_owner:{...WRITE(false),openWorldHint:true},
385
+ };
386
+ if(catalogProfile!=='legacy-v46') for(const item of tools) {
387
+ if(!toolAnnotations[item.name]) throw new Error(`tool ${item.name} has no annotations`);
388
+ item.annotations={...toolAnnotations[item.name]};
389
+ }
390
+ // Hidden tools also stay out of validation, so knowing a name cannot bypass the profile.
391
+ const toolNames=new Set(tools.map(item=>item.name));
392
+ const disabled=new Set(['list_files','read_file','apply_patch','run_check','workspace_result','artifact_chunk']);
393
+ const readTools=new Set(['list_pending','get','list_files','read_file','workspace_result','list_tools','call_tool_read']);
394
+ const t3ReadTools=new Set(['t3_thread_list','t3_thread_read','t3_thread_wait']);
395
+ const t3Tools=new Set([...t3ReadTools,'t3_thread_create','t3_thread_send','t3_thread_set']);
396
+ const notifyTools=new Set(['notify_owner']);
397
+ // T3 tools use the existing scopes to preserve the current grant behavior.
398
+ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'dalan.work';
399
+ // Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
400
+ const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
401
+ if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
402
+ // A refusal that must stay tells the worker the next call and what to change; workers often do not retry a bare "invalid X".
403
+ const argumentFixes={
404
+ finish:{
405
+ result:'send result as 1 to 262144 bytes of text (put the verdict on the first line), then call finish again with the same claim_id',
406
+ outcome:'outcome must be completed, blocked or failed; call finish again with one of them',
407
+ artifact_ids:'artifact_ids must be at most 8 strings; call finish again with fewer ids',
408
+ summary:'summary must be text; call finish again with a string or leave summary out'
409
+ },
410
+ progress:{note:'send note as 1 to 4096 bytes of text; call progress again with a shorter note'}
411
+ };
412
+ const SUMMARY_MAX=4096,NOTE_MAX=4096;
413
+ const clipWithMarker=(text,max,marker)=>`${Store.clipBytes(text,max-Buffer.byteLength(marker))}${marker}`;
414
+ // Fixable summary and note problems are repaired, not refused: the worker already has its result and may never retry.
415
+ // Returns the repaired arguments and the marks to put in the receipt. Anything not repairable is left for validate() to refuse.
416
+ function repairArguments(name,args) {
417
+ const marks={};
418
+ if(!args||typeof args!=='object'||Array.isArray(args)) return {args,marks};
419
+ if(name==='progress'&&typeof args.note==='string'&&Buffer.byteLength(args.note)>NOTE_MAX) {
420
+ marks.note_truncated=true;
421
+ return {args:{...args,note:clipWithMarker(args.note,NOTE_MAX,' [note truncated]')},marks};
422
+ }
423
+ if(name!=='finish') return {args,marks};
424
+ const given=args.summary;
425
+ if(typeof given==='string'&&given.trim()) {
426
+ if(Buffer.byteLength(given)<=SUMMARY_MAX) return {args,marks};
427
+ marks.summary_truncated=true;
428
+ return {args:{...args,summary:clipWithMarker(given,SUMMARY_MAX,' [summary truncated]')},marks};
429
+ }
430
+ if(given!==undefined&&typeof given!=='string') return {args,marks};
431
+ const first=typeof args.result==='string'?args.result.split(/\r?\n/).map(line=>line.trim()).find(Boolean):undefined;
432
+ if(!first) return {args,marks};
433
+ marks.summary_derived=true;
434
+ return {args:{...args,summary:Store.clipBytes(first,SUMMARY_MAX)},marks};
435
+ }
436
+ function validate(name,args) {
437
+ const definition=tools.find(x=>x.name===name); if(!definition) throw new Error('unknown tool');
438
+ const refuse=(kind,field)=>{
439
+ const fix=argumentFixes[name]?.[field];
440
+ // repairArguments already derives a missing summary, so a summary that is still missing means the result cannot supply one.
441
+ if(name==='finish'&&field==='summary'&&kind==='missing') return new Error(`missing summary and no result to derive it from: ${argumentFixes.finish.result}`);
442
+ return new Error(fix?`${kind} ${field}: ${fix}`:`${kind} ${field}`);
443
+ };
444
+ if(!args||typeof args!=='object'||Array.isArray(args)) throw new Error('invalid arguments');
445
+ const s=definition.inputSchema;
446
+ for(const field of Object.keys(args)) if(!Object.hasOwn(s.properties,field)) throw new Error(`unknown field ${field}`);
447
+ for(const field of s.required) if(!Object.hasOwn(args,field)) throw refuse('missing',field);
448
+ // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
449
+ if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
450
+ for(const [field,value] of Object.entries(args)) {
451
+ const rule=s.properties[field];
452
+ if(rule.type==='string'&&value===''&&argumentFixes[name]?.[field]) throw refuse('invalid',field);
453
+ if(rule.type==='string'&&(typeof value!=='string'||Buffer.byteLength(value)> (rule.maxLength||256*1024))) throw refuse('invalid',field);
454
+ if(rule.type==='integer'&&(!Number.isInteger(value)||(rule.minimum!==undefined&&value<rule.minimum)||(rule.maximum!==undefined&&value>rule.maximum))) throw refuse('invalid',field);
455
+ if(rule.type==='boolean'&&typeof value!=='boolean') throw refuse('invalid',field);
456
+ if(rule.type==='object'&&(!value||typeof value!=='object'||Array.isArray(value))) throw refuse('invalid',field);
457
+ if(rule.type==='array'&&(!Array.isArray(value)||value.length>rule.maxItems||value.some(x=>typeof x!=='string'))) throw refuse('invalid',field);
458
+ if(rule.enum&&!rule.enum.includes(value)||rule.pattern&&!new RegExp(rule.pattern).test(value)) throw refuse('invalid',field);
459
+ }
460
+ }
461
+ // A waiter is only a live HTTP response. Its actual attention event remains in
462
+ // `notifications` until that response completes, so a disconnect falls back to
463
+ // the existing durable T3 delivery path.
464
+ const waiters=new Map();
465
+ function artifactIdsFor(requestId, report) {
466
+ const ids=new Set(store.db.prepare("SELECT id FROM artifacts WHERE request_id=? AND sealed=1 ORDER BY id").all(requestId).map(row=>row.id));
467
+ const evidence=report?.workspace_evidence;
468
+ if(evidence?.patch_artifact?.artifact_id) ids.add(evidence.patch_artifact.artifact_id);
469
+ for(const artifact of evidence?.artifacts??[]) if(artifact?.id) ids.add(artifact.id);
470
+ for(const check of evidence?.checks??[]) if(check?.output_artifact_id) ids.add(check.output_artifact_id);
471
+ return [...ids];
472
+ }
473
+ function waitSummary(requestId, attention=null) {
474
+ const row=store.get(requestId);
475
+ const body=attention?.body?JSON.parse(attention.body):null, note=body?.note??null;
476
+ // A usage-break notice: the request stays queued; the owner may do it elsewhere or wait again.
477
+ if(body?.break_id) return {status:'worker_break',report_summary:null,blocker_text:null,notice:maskText(note),request_ids:body.request_ids,artifact_ids:[]};
478
+ const status=row.status==='finished'?'finished':row.status==='cancelled'?'cancelled':/^\s*QUESTION:/im.test(note??'')?'question':'blocker';
479
+ const failure=store.failureFields(requestId);
480
+ return {status,report_summary:maskText(row.report?.summary??null),blocker_text:maskText(note),artifact_ids:artifactIdsFor(requestId,row.report),...(status==='cancelled'&&row.cancelled_reason?{cancelled_reason:row.cancelled_reason}:{}),failure_type:failure.failure_type,failure_type_source:failure.failure_type_source,...(failure.failure_type==='expired'?{expired:true}:{})};
481
+ }
482
+ function notifyAttachedWaiter(requestId) {
483
+ const waiter=waiters.get(requestId);
484
+ if(!waiter) return false;
485
+ const attention=store.claimWaiterDelivery(requestId,waiter.cursor);
486
+ if(!attention) return false;
487
+ waiters.delete(requestId);
488
+ clearTimeout(waiter.timer);
489
+ let settled=false;
490
+ const release=()=>{
491
+ if(settled) return;
492
+ settled=true;
493
+ store.releaseWaiterDelivery(attention.id);
494
+ runDrain();
495
+ };
496
+ waiter.res.once('close',release);
497
+ waiter.res.socket?.once('close',release);
498
+ waiter.res.once('finish',()=>{
499
+ if(settled) return;
500
+ settled=true;
501
+ store.settleWaiterDelivery(attention.id,waiter.consume);
502
+ });
503
+ const respond=()=>{ if(!settled) { store.recordFetched(requestId);json(waiter.res,200,waitSummary(requestId,attention)); } };
504
+ const responseDelay=Number(readEnv('DALAN_WAIT_RESPONSE_DELAY_MS')||0);
505
+ if(Number.isInteger(responseDelay)&&responseDelay>0&&responseDelay<=10000) setTimeout(respond,responseDelay);
506
+ else respond();
507
+ return true;
508
+ }
509
+ // Cancel queued assignments whose preparation expired (Store.sweepExpired) and answer an attached owner waiter as /cancel does.
510
+ // This timer is independent of delivery so pause and slow destinations cannot hold expiry work.
511
+ function sweepExpired() {
512
+ const ids=store.sweepExpired();
513
+ if(ids.length) log({kind:'assignments_expired',count:ids.length,request_ids:ids.slice(0,20)});
514
+ if(ids.requeued?.length) log({kind:'assignments_expired_requeued',count:ids.requeued.length,request_ids:ids.requeued.slice(0,20)});
515
+ for(const requestId of ids) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
516
+ return ids;
517
+ }
518
+ // Cancel queued assignments the worker skipped for DALAN_SKIP_EXPIRE_HOURS (Store.sweepSkipped), so the sender sees the reason.
519
+ function sweepSkipped() {
520
+ const ids=store.sweepSkipped();
521
+ if(ids.length) log({kind:'skip_expired',count:ids.length,request_ids:ids.slice(0,20)});
522
+ for(const requestId of ids) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
523
+ return ids;
524
+ }
525
+ // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
526
+ function sweepStaleLeases() {
527
+ const ids=store.sweepStaleLeases();
528
+ if(ids.length) log({kind:'claims_lease_expired',count:ids.length,request_ids:ids.slice(0,20)});
529
+ return ids;
530
+ }
531
+ const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
532
+ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
533
+ const immediate=store.get(requestId);
534
+ if(['finished','cancelled'].includes(immediate.status)) { store.recordFetched(requestId);if(consume) store.recordConsumed(requestId,'wait'); return json(res,200,waitSummary(requestId)); }
535
+ if(waiters.has(requestId)) return json(res,409,{error:'waiter already attached'});
536
+ const queueBlocker=queuedRepositoryBlocker(immediate);
537
+ if(queueBlocker) return json(res,200,{status:'blocker',report_summary:null,blocker_text:queueBlocker.message,artifact_ids:[],queue_blocker:queueBlocker});
538
+ // `none` has no fallback delivery channel, so a newly attached waiter must
539
+ // also observe attention recorded before it attached.
540
+ const destination=await destinations.for(immediate.delivery_mode);
541
+ const waiter={res,timer:null,consume,cursor:immediate.delivery_mode==='none'||destination.quietReason(immediate)?0:store.deliveryCursor(requestId)};
542
+ const detach=()=>{
543
+ if(waiters.get(requestId)!==waiter) return;
544
+ waiters.delete(requestId);
545
+ clearTimeout(waiter.timer);
546
+ };
547
+ req.once('aborted',detach);
548
+ res.once('close',detach);
549
+ waiter.timer=setTimeout(()=>{
550
+ if(waiters.get(requestId)!==waiter) return;
551
+ waiters.delete(requestId);
552
+ let blocker=null;
553
+ try { blocker=queuedRepositoryBlocker(store.get(requestId)); } catch { /* the request may have expired while waiting */ }
554
+ json(res,200,blocker?{status:'blocker',report_summary:null,blocker_text:blocker.message,artifact_ids:[],queue_blocker:blocker}:{status:'timeout',report_summary:null,blocker_text:null,artifact_ids:[]});
555
+ },timeoutMs);
556
+ waiter.timer.unref();
557
+ waiters.set(requestId,waiter);
558
+ notifyAttachedWaiter(requestId);
559
+ }
560
+ // Result guidance only; tool descriptions stay fixed.
561
+ const listGuidance='Claim every listed assignment you can start now, up to free_lanes, in this turn. Do not claim one and stop. Never exceed free_lanes.';
562
+ const claimMoreGuidance='If free_lanes > 0 and work is queued, claim more now.';
563
+ // A finishing lane takes the next queued item itself; an error on any claim means the list changed, so list again.
564
+ const finishNextGuidance=next=>`Claim ${next[0].request_id} yourself before you end this run, then keep claiming up to free lanes. After any claim error such as assignment_expired, call list_pending and claim from that list.`;
565
+ // A loader failure carries host paths or quotes the file. Every caller of this policy gets the Store's fixed error instead.
566
+ function repoPolicyFor(assignment) {
567
+ try { return currentRepoPolicy(); }
568
+ catch(error) { throw store.destinationConfigurationError(assignment?.request_id??null,error); }
569
+ }
570
+ // An exact retry of a live grant is not a new grant. A repository edit after the grant must not strand its holder,
571
+ // the same rule that lets a live grant finish after revocation. The Store still checks the holder's connection
572
+ // and approved connection set, and refuses anything that is not that exact retry.
573
+ function holdsLiveGrant(worker,requestId,claimant,subject,acquisitionId) {
574
+ const held=store.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(requestId);
575
+ return held?.worker===worker&&store.isExactClaimRetry(held,claimant,subject,acquisitionId??null);
576
+ }
577
+ function queuedRepositoryBlocker(row) {
578
+ if(row.status!=='queued') return null;
579
+ const repo=row.assignment?.inputs?.find(input=>input?.github_repo!==undefined)?.github_repo;
580
+ if(!repo) return null;
581
+ const worker=row.target_worker??'dot';
582
+ try {
583
+ if(repoPolicyFor(row.assignment).allowsRepo(worker,repo)) return null;
584
+ } catch {
585
+ return {code:'repository_policy_unavailable',message:'Repository access policy is unavailable. Check the bridge worker configuration.'};
586
+ }
587
+ return {code:'repository_policy_denied',message:`Repository ${repo} is not allowed for worker "${worker}". Grant it with dalan worker allow ${worker} ${repo}, or cancel the job.`};
588
+ }
589
+ function assertRepoAllowed(worker,assignment) {
590
+ const inputs=assignment?.inputs;
591
+ if(!Array.isArray(inputs)||!inputs.some(input=>input?.github_repo!==undefined)) return;
592
+ const policy=repoPolicyFor(assignment);
593
+ if(inputs.length!==1) throw new Error('one repository input per job');
594
+ if(typeof inputs[0]?.github_repo!=='string'||!policy.allowsRepo(worker,inputs[0].github_repo)) {
595
+ const repo=typeof inputs[0]?.github_repo==='string'?inputs[0].github_repo:'(invalid repository)';
596
+ throw new Error(`repository ${repo} is not allowed for worker "${worker}"; update it with dalan worker allow ${worker} OWNER/REPO, or choose another worker${!fs.existsSync(workersFile)?'; no workers.json: see docs/operations.md#legacy-repository-policy-migration':''}`);
597
+ }
598
+ }
599
+ // Record the call on the claim it names (one UPDATE); a thrown error or a structured {error} result is kept as the last tool error.
600
+ async function tool(name,a,principal,notifyMeta) {
601
+ if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
602
+ !holdsLiveGrant(principal.worker,a.request_id,a.claimant,principal.subject,a.acquisition_id)) {
603
+ assertRepoAllowed(principal.worker,store.get(a.request_id).assignment);
604
+ }
605
+ let error=null;
606
+ try {
607
+ const result=await dispatchTool(name,a,principal,notifyMeta);
608
+ if(typeof result?.error==='string') error=redactNote(result.error);
609
+ return result;
610
+ } catch(e) { error=redactNote(String(e?.message??e)); if(e.destination&&typeof a?.request_id==='string')notifyAttachedWaiter(a.request_id); throw e; }
611
+ finally {
612
+ const rid=a?.request_id;
613
+ if(typeof rid==='string'&&rid!==absentId&&toolNames.has(name)&&!t3Tools.has(name)&&!notifyTools.has(name)) {
614
+ try { store.recordToolActivity(rid,principal.subject,principal.worker,name,{workspace:disabled.has(name),error,connectionId:principal.builtin?(principal.connection_id??''):null}); } catch { /* activity is diagnostic; never fail the call */ }
615
+ }
616
+ }
617
+ }
618
+ async function dispatchTool(name,a,principal,notifyMeta) {
619
+ const t3Audit=(t3Tools.has(name)||notifyTools.has(name))?await loadT3Audit():null;
620
+ if(t3Audit) t3Audit.admitT3Audit(store.db,principal.worker,principal.subject);
621
+ store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
622
+ sweepExpired();
623
+ if(t3Tools.has(name)||notifyTools.has(name)) {
624
+ // Denials carry only verified identity, tool and a fixed reason. Never prepare
625
+ // an argument-bearing audit until capability, scope and schema all pass.
626
+ let denial='worker_capability_denied',notificationKey;
627
+ try {
628
+ if(!hasCapability(workers,principal.worker,'t3')) throw new Error(denial);
629
+ denial='insufficient_scope';
630
+ if(oauth) needScope(principal,scopeFor(name));
631
+ denial='invalid_arguments';
632
+ validate(name,a);
633
+ if(notifyTools.has(name)) notificationKey=notifyKey(notifyMeta);
634
+ } catch(error) {
635
+ t3Audit.appendT3Audit(store.db,t3Audit.prepareT3Audit(name,{},principal.worker),principal.subject,`denied: ${denial}`);
636
+ throw error;
637
+ }
638
+ const audit=t3Audit.prepareT3Audit(name,a,principal.worker);
639
+ t3Audit.appendT3Audit(store.db,audit,principal.subject,'started');
640
+ try {
641
+ if((name==='t3_thread_list'||name==='t3_thread_read')&&t3ReadToolsOff()) {
642
+ t3Audit.appendT3Audit(store.db,audit,principal.subject,'blocked: t3_read_tools=off');
643
+ log({kind:'t3_read_tool_blocked',tool:name,subject:principal.subject,call_id:audit.call_id});
644
+ return T3_READ_TOOLS_OFF;
645
+ }
646
+ const result=notifyTools.has(name) ? await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey})) : await (await import('./t3-control.mjs')).runT3Tool(name,a);
647
+ t3Audit.appendT3Audit(store.db,audit,principal.subject,'success',result);
648
+ if(result && typeof result==='object' && Object.hasOwn(result,'_audit_ids')) { const {_audit_ids,...publicResult}=result; return publicResult; }
649
+ return result;
650
+ } catch(error) {
651
+ t3Audit.appendT3Audit(store.db,audit,principal.subject,`error: ${redactSinkText(error.message).slice(0,300)}`);
652
+ throw error;
653
+ }
654
+ }
655
+ const worker=principal.worker;
656
+ if(a&&typeof a==='object') {
657
+ if(typeof a.request_id==='string'&&!store.mayAct(worker,a.request_id)) a={...a,request_id:absentId};
658
+ if(typeof a.message_id==='string'&&!store.mayAct(worker,a.message_id)) a={...a,message_id:absentId};
659
+ }
660
+ const repaired=repairArguments(name,a);
661
+ a=repaired.args;
662
+ validate(name,a);
663
+ if(oauth) needScope(principal,scopeFor(name));
664
+ if(disabled.has(name)&&!workspaceEnabled) throw new Error('capability_not_enabled');
665
+ if(a.request_id===absentId&&disabled.has(name)) throw new Error('assignment not found');
666
+ const subject=principal.subject,connectionId=principal.builtin?(principal.connection_id??''):null;
667
+ const strictJob=typeof a.request_id==='string'&&store.isProtocolJob(a.request_id);
668
+ if(strictJob&&catalogProfile!=='protocol-v0') throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
669
+ if(strictJob)store.assertProtocolAvailable(a.request_id);
670
+ // Strict commands validate authority, replay and revision in their transaction.
671
+ // The legacy implicit touch would mutate activity before a rejected CAS.
672
+ if(!strictJob&&typeof a.request_id==='string'&&typeof a.claim_id==='string'&&store.hasAssignment(a.request_id)) store.touchClaim(a.request_id,a.claim_id,subject,worker,connectionId);
673
+ // Workspace tools (every one, reads included) refuse any caller but the live holding connection. Native jobs skip the implicit
674
+ // touch above, so this is their only check; legacy jobs get a second, post-await check. It runs synchronously right before
675
+ // the tool body, after the tool's last await, so no revoke can land between the check and the write.
676
+ const workspaceFence=()=>{ if(typeof a.claim_id==='string'&&typeof a.request_id==='string')store.assertWorkerConnection(a.request_id,a.claim_id,subject,worker,connectionId); };
677
+ const commandContext=(operation,args)=>{
678
+ if(!strictJob) return undefined;
679
+ if(typeof a.command_key!=='string'||!a.command_key.length||a.command_key.length>512) throw new Error('command_key required for protocol job');
680
+ if(!Number.isSafeInteger(a.expected_revision)||a.expected_revision<0) throw new Error('expected_revision required for protocol job');
681
+ return {key:a.command_key,revision:a.expected_revision,operation,args,...(a.epoch===undefined?{}:{epoch:a.epoch})};
682
+ };
683
+ switch(name) {
684
+ case 'list_tools': return toolRegistry.listTools(worker);
685
+ case 'call_tool_read': case 'call_tool_write': {
686
+ // The registry owns policy: grants, class match, argument validation, rate limits and audit.
687
+ try { return (await toolRegistry.callTool({worker,tool:a.tool,class:name==='call_tool_read'?'read':'write',args:a.arguments,schema_hash:a.schema_hash,idempotency_key:a.idempotency_key})).result; }
688
+ catch(e) { if(e instanceof RegistryError) throw new Error(e.message.startsWith(e.code)?e.message:`${e.code}: ${e.message}`); throw e; }
689
+ }
690
+ case 'list_pending': {
691
+ const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
692
+ const assignments=store.listPending(worker);
693
+ store.recordListed(assignments,free_lanes,worker);
694
+ log({kind:'list_pending_result',subject,free_lanes,total:assignments.length,request_ids:assignments.slice(0,20).map(x=>x.request_id)});
695
+ const guidance=workers.workers.get(worker)?.guidance==='resume'?`${listGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:listGuidance;
696
+ // Say outright whether a claim would be accepted now: a worker that once saw a pause refusal must not keep listing without claiming.
697
+ const claims_accepted=!store.paused();
698
+ const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
699
+ const claimsNote=claims_accepted?'':'Claims are paused (temporary): do not claim now; call list_pending again later and claim once claims_accepted is true.';
700
+ return {assignments,attention:store.attention(subject,worker),free_lanes,claims_accepted,...(claims_accepted?next:{next_action:claimsNote}),guidance};
701
+ }
702
+ case 'claim': {
703
+ const requestId=id(a.request_id),claimant=str(a.claimant,'claimant',128),ctx=commandContext('claim',{claimant,acquisition_id:a.acquisition_id??null,lease_ms:a.lease_ms??null}),row=store.get(requestId),held=row.claim?.state==='active'?row.claim:null,retry=holdsLiveGrant(worker,requestId,claimant,subject,a.acquisition_id);
704
+ if(!retry)assertRepoAllowed(worker,row.assignment);
705
+ store.refuseExpired(requestId);
706
+ // Retry a successful claim without a new remote dependency, and skip it for a live rival claim that the Store will refuse.
707
+ // A fresh claim, a claim after abandon and an expired-lease takeover are each a new admission. The Store
708
+ // still validates claimant, subject, lease, cancellation and capacity atomically.
709
+ const admission=!store.paused()&&(row.status==='queued'||row.status==='claimed'&&held&&!(held.claimant===claimant&&held.subject===subject)&&store.leaseExpired(held));
710
+ const preflight=admission?await preflightPR(row.assignment):null;
711
+ if(!retry)assertRepoAllowed(worker,row.assignment);
712
+ const prior=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
713
+ if(prior&&store.leaseExpired(prior)&&(!strictJob||store.protocolRevision(requestId)===ctx.revision)) await workspace?.quiesce(requestId);
714
+ // Store revalidates after the await: a concurrent claimant may have won.
715
+ // Built-in mode only: re-check inside the claim transaction that the
716
+ // claimant's own connection is still live. The token was verified before
717
+ // the awaited preflight/quiesce above, so a revoke in between must not
718
+ // admit the claim. External-OAuth principals pass null and are unchanged.
719
+ const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null);
720
+ const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
721
+ const {free_lanes,queued}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
722
+ return withAvailableChecks({...claimed,lease_expires_at:claimed.lease_expires_at??store.leaseExpiresAt(grant),queued_after_claim:queued,free_lanes,...store.nextQueued(free_lanes,requestId,worker),guidance:`${claimed.guidance} ${claimMoreGuidance}`},true,worker,subject);
723
+ }
724
+ case 'renew_claim': {
725
+ if(!strictJob) throw new Error('renew_claim requires a protocol job');
726
+ return store.renewClaim(id(a.request_id),id(a.claim_id,'claim_id'),a.lease_ms,commandContext('renew',{leaseMs:a.lease_ms}),subject,worker,connectionId);
727
+ }
728
+ case 'get': { const requestId=id(a.request_id); if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)}; store.markNotesSeenByHolder(requestId,subject,worker,connectionId); return {...publicWorkerGet(withAvailableChecks(store.get(requestId),true,worker,subject)),guidance:store.guidanceFor(worker)}; }
729
+ case 'ack_message': {const message=store.ackMessage(id(a.message_id,'message_id'),worker);log({kind:'message_acknowledged',message_id:message.message_id});return {kind:'message',message};}
730
+ case 'progress': {
731
+ const requestId=id(a.request_id),note=str(a.note,'note',4096),receipt=store.progress(requestId,id(a.claim_id,'claim_id'),note,subject,a.blocker===true,worker,null,commandContext('progress',{note,blocker:a.blocker===true}),connectionId);
732
+ notifyAttachedWaiter(requestId);
733
+ return {...receipt,...repaired.marks};
734
+ }
735
+ case 'ask_question': {
736
+ const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text}),connectionId);
737
+ notifyAttachedWaiter(requestId);
738
+ return receipt;
739
+ }
740
+ case 'consume_answer': return store.consumeAnswer(id(a.request_id),id(a.claim_id,'claim_id'),str(a.question_id,'question_id',128),subject,worker,commandContext('consume',{question_id:a.question_id}),connectionId);
741
+ case 'finish':
742
+ { const requestId=id(a.request_id),claimId=id(a.claim_id,'claim_id');
743
+ store.assertFinishClaim(requestId,claimId,subject,worker);
744
+ // A replaced or revoked connection learns connection_not_live before any question or artifact error. Read-only; expired and foreign claims return early.
745
+ workspaceFence();
746
+ const existing=store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(requestId);
747
+ let captureEvidence=null;
748
+ if(!existing) {
749
+ store.assertQuestionsResolved(requestId,claimId,a.outcome);
750
+ if(a.artifact_ids?.length) { if(!workspaceEnabled) throw new Error('capability_not_enabled'); store.assertSealedArtifacts(requestId,claimId,a.artifact_ids); }
751
+ const request=store.get(requestId);
752
+ if(workspaceEnabled) await workspace.makeRoom(requestId);
753
+ // Recheck after the last await. The evidence capture below runs inside the finish transaction, after finishOnce's own
754
+ // connection check, so a patch artifact is never committed for a holder that lost the connection.
755
+ workspaceFence();
756
+ if(workspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
757
+ captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
758
+ if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
759
+ const archiveWorkspace=workspace??new Workspace(store,false),snapshot=captureEvidence;
760
+ captureEvidence=onRollback=>{
761
+ const base=snapshot?snapshot(onRollback):null;
762
+ const archive=captureOwnerReportArtifact(store,archiveWorkspace,{requestId,claimId,outcome:a.outcome,summary:a.summary,result:a.result,onRollback});
763
+ return archive?{...(base??{}),owner_report_artifact:archive}:base;
764
+ };
765
+ }
766
+ }
767
+ const receipt=store.finish(requestId,claimId,a.outcome,str(a.summary,'summary',4096),str(a.result,'result',256*1024),subject,null,worker,commandContext('finish',{artifact_ids:a.artifact_ids??[]}),captureEvidence,connectionId);
768
+ if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
769
+ notifyAttachedWaiter(requestId);
770
+ if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
771
+ const marked={...receipt,...repaired.marks};
772
+ return receipt.next_queued?.length&&!store.paused()?{...marked,guidance:finishNextGuidance(receipt.next_queued)}:marked; }
773
+ case 'list_files': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.list(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.limit??200,worker,a.cursor);
774
+ case 'read_file': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.read(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.start_line??1,a.max_lines??200,worker);
775
+ case 'apply_patch': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.apply(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.patch,worker);
776
+ case 'run_check': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.check(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.check_id,worker);
777
+ case 'artifact_chunk': return strictJob?protocolArtifactChunk(store,workspace,{requestId:id(a.request_id),claimId:id(a.claim_id,'claim_id'),subject,worker,artifactId:a.artifact_id,offset:a.offset,base64:a.data_base64,final:a.final,expected:a.sha256,expectedSize:a.size,connectionId},commandContext(a.final?'seal':'upload',{})):workspace.chunk(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.artifact_id,a.offset,a.data_base64,a.final,a.sha256,worker);
778
+ case 'workspace_result': workspaceFence();return workspace.result(id(a.request_id),id(a.claim_id,'claim_id'),subject,worker);
779
+ }
780
+ }
781
+ function subId(url,subject,worker) { const identity=worker==='dot'?subject:`${subject}\0${worker}`;return 'sub_' + createHash('sha256').update(`${identity}\0${url}\0assignment.available\0{}`).digest('hex').slice(0, 32); }
782
+ function validEventParams(p) { return p.name === 'assignment.available' && JSON.stringify(p.arguments ?? {}) === '{}' && p.delivery?.mode === 'webhook'; }
783
+ async function subscribe(p,principal) {
784
+ if (!validEventParams(p)) throw new Error('invalid subscription');
785
+ const url = str(p.delivery.url, 'url', 2048), signingSecret=p.delivery.secret;
786
+ if (!validSecret(signingSecret)) throw new Error('invalid signing secret');
787
+ const sub=subId(url,principal.subject,principal.worker),challenge=randomBytes(24).toString('base64url');
788
+ try {
789
+ const response=await sendWebhook(url,signingSecret,`msg_verification_${randomUUID()}`,sub,JSON.stringify({type:'verification',challenge}));
790
+ const received=JSON.parse(response.body).challenge;
791
+ const left=Buffer.from(challenge),right=Buffer.from(received||'');
792
+ if(response.status<200||response.status>=300||left.length!==right.length||!timingSafeEqual(left,right)) throw new Error('challenge_failed');
793
+ } catch(error) {
794
+ log({kind:'verification_failed',subscription_id:sub,reason:error.message});
795
+ const e=new Error('CallbackEndpointError'); e.code=-32015; e.data={reason:error.message==='challenge_failed'?'challenge_failed':error.message==='timeout'?'timeout':'callback_error'}; throw e;
796
+ }
797
+ const ttl=Math.min(Number.isFinite(p.ttlMs)?Math.max(60000,p.ttlMs):7*86400000,7*86400000),expires=new Date(Date.now()+ttl).toISOString();
798
+ const connection=principal.builtin
799
+ ? {issuer:principal.issuer,connection_id:principal.connection_id,builtin:true,connection:principal.connection}
800
+ : {issuer:principal.issuer,subject:principal.subject,client_id:principal.client_id,connection_id:principal.connection_id,local:principal.local};
801
+ store.subscribe(sub,url,signingSecret,expires,principal.subject,principal.worker,connection);
802
+ return {id:sub,refreshBefore:expires,cursor:null,truncated:p.cursor!=null};
803
+ }
804
+ // Errors written by Dalan reach the client redacted; a crash returns only what failed and an error id, and the
805
+ // redacted detail goes to the request log.
806
+ function publicErrorText(error,what) {
807
+ if(!isCrash(error)) return redactSinkText(error.message);
808
+ const errorId=randomUUID().slice(0,8);
809
+ log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
810
+ return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
811
+ }
812
+ async function dispatch(message,principal) {
813
+ const p=message.params??{};
814
+ switch(message.method) {
815
+ case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
816
+ case 'initialize': return {protocolVersion:['2025-11-25','2025-06-18','2025-03-26','2024-11-05'].includes(p.protocolVersion)?p.protocolVersion:'2025-11-25',capabilities:{tools:{},events:{}},serverInfo};
817
+ case 'ping': return {};
818
+ case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3'))};
819
+ case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
820
+ case 'events/list': return {events:[event]};
821
+ case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
822
+ case 'events/unsubscribe': { if(oauth)needScope(principal,'dalan.read');if(!validEventParams(p)) throw new Error('invalid subscription'); store.unsubscribe(subId(p.delivery.url,principal.subject,principal.worker)); return {}; }
823
+ default: throw Object.assign(new Error('method not found'),{code:-32601});
824
+ }
825
+ }
826
+ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)=>{
827
+ const outcome=req.url===publicPath?beginMcpOutcome(req,res,log,toolNames,!!oauth):null;
828
+ try {
829
+ if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback'}); res.writeHead(403); res.end(); return; }
830
+ // Built-in mode serves only its configured host, which also blocks DNS rebinding of the loopback listener.
831
+ if(as&&!as.hostOk(req)) { log({kind:'mcp_inbound',status:421,route:'host'}); res.writeHead(421); res.end(); return; }
832
+ if(!as && req.url==='/.well-known/oauth-protected-resource' && oauthMetadata && req.method==='GET') return json(res,200,protectedResource(oauthMetadata));
833
+ // RFC 9728 / MCP auth: clients first try metadata suffixed with the MCP path, whose resource is the exact MCP URL.
834
+ if(req.url===`/.well-known/oauth-protected-resource${publicPath}` && oauthMetadata && req.method==='GET') { if(as)res.setHeader('Cache-Control','no-store'); return json(res,200,protectedResource(oauthMetadata,new URL(publicPath,oauthMetadata.OAUTH_AUDIENCE).href)); }
835
+ if(signal&&signal.handle(req,res)) return;
836
+ if(as&&await as.handle(req,res)) return;
837
+ if(req.url!==publicPath) { log({kind:'mcp_inbound',status:404,route:'other',http_method:req.method,path_shape:pathShape(req.url),auth_header_present:(req.headers.authorization??'').startsWith('Bearer ')}); res.writeHead(404); res.end(); return; }
838
+ let principal={local:true,subject:'local-principal',scopes:new Set(ADVERTISED_SCOPES)};
839
+ if(oauth) { try { principal=as?await as.verifyBearer(req.headers.authorization,outcome.state):await verifyBearer(req.headers.authorization,oauth,outcome.state); } catch { res.writeHead(401,{'WWW-Authenticate':challenge(oauth)});res.end();return; } }
840
+ try { principal.worker=resolveWorker(workers,principal); } catch(error) {
841
+ outcome.state.auth_reason=error.code??'unknown_connection';
842
+ log({kind:'connection_denied',reason:error.code??'unknown_connection',client_id:principal.client_id??null});
843
+ res.writeHead(403,{'content-type':'application/json'});res.end(JSON.stringify({error:error.code??'unknown_connection'}));return;
844
+ }
845
+ outcome.state.phase='body';
846
+ const body=await readBody(req,outcome.state);
847
+ if(req.method!=='POST') { res.writeHead(405,{allow:'POST'}); res.end(); return; }
848
+ outcome.state.phase='parse';
849
+ let rpc; try { rpc=JSON.parse(body); } catch { return json(res,400,rpcError(null,-32700,'Parse error')); }
850
+ if(!rpc||typeof rpc!=='object'||Array.isArray(rpc)||rpc.jsonrpc!=='2.0'||typeof rpc.method!=='string') return json(res,400,rpcError(rpc?.id??null,-32600,'Invalid Request'));
851
+ outcome.identify(rpc);
852
+ // Metadata only: bodies can carry webhook secrets and worker results.
853
+ log({kind:'mcp_inbound',call_id:outcome.state.call_id,rpc_method:outcome.state.rpc_method,tool:outcome.state.tool});
854
+ if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
855
+ outcome.state.phase='dispatch';
856
+ try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal)}}); }
857
+ catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data)); }
858
+ // Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
859
+ if(outcome.state.tool) try { store.recordResponseBytes(principal.subject,outcome.state.tool,outcome.state.response_bytes,principal.worker); } catch(e) { log({kind:'response_bytes_error',call_id:outcome.state.call_id,reason:e.message}); }
860
+ } catch(e) { const errorType=e.message==='body too large'?'body_too_large':req.aborted?'request_aborted':'request_error';if(outcome)outcome.state.error_type=errorType;log({kind:'inbound_error',call_id:outcome?.state.call_id,error_type:errorType}); if(!res.headersSent&&!res.destroyed) json(res,400,rpcError(null,-32700,publicErrorText(e,'request'))); }
861
+ });
862
+ const adminServer=http.createServer(async(req,res)=>{
863
+ // A refused submit is logged with its reason so the owner can distinguish rejected requests from stored assignments.
864
+ const requestStartedAt=Date.now();
865
+ let rejected=null, dryRequested=false;
866
+ try {
867
+ const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
868
+ if(url.pathname.startsWith('/protocol/service/')) {
869
+ if(!protocolServices||req.method!=='POST')return json(res,404,{error:'not found'});
870
+ return json(res,200,await protocolServices.invoke(url.pathname.slice('/protocol/service/'.length),req.headers['x-protocol-service-capability'],body));
871
+ }
872
+ dryRequested=url.pathname==='/submit-preview';
873
+ log({kind:'admin_call',route:url.pathname,method:req.method});
874
+ if(url.pathname==='/submit'&&(url.searchParams.get('dry_run')==='1'||body.dry_run===true)) throw new Error('dry run requires POST /submit-preview; /submit always submits');
875
+ if(url.pathname==='/submit'||url.pathname==='/submit-preview') {
876
+ // Set before any check below, so every refusal carries typed reasons, answers a dry run with a verdict and is logged.
877
+ // Cohort labels can contain private values; logs need equality, not their contents.
878
+ const labelDigest=value=>typeof value==='string'&&value.trim()?createHash('sha256').update(value.trim()).digest('hex'):null;
879
+ rejected={request_id:typeof body.assignment?.request_id==='string'?body.assignment.request_id.slice(0,128):null,task_kind:body.meta?.task_kind??null,source:body.meta?.source??null,objective_key_sha256:labelDigest(body.meta?.objective_key),revision_sha256:labelDigest(body.meta?.revision)};
880
+ if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
881
+ const commandKey=body.command_key===undefined?null:body.command_key;
882
+ const supersedes=body.supersedes===undefined?null:body.supersedes;
883
+ const destinationRevision=body.destination_revision??null;
884
+ if(body.destination_revision!==undefined&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
885
+ if(body.command_key!==undefined&&(typeof commandKey!=='string'||commandKey.length<1||commandKey.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
886
+ const retry=typeof body.assignment?.request_id==='string'&&store.hasAssignment(body.assignment.request_id);
887
+ const delivery=parseDelivery(body.delivery===undefined?'none':body.delivery), destination=await destinations.for(delivery), owner=str(body.owner_token,'owner_token',128);
888
+ // Profile mode: T3 delivery needs t3code on this host. Refuse before anything is stored, with the recovery in the message.
889
+ if(delivery.mode==='t3'&&!legacyProfile&&!(await (await import('./t3.mjs')).t3Available())) throw new Error('delivery t3:... needs T3 Code, but t3code was not found on PATH on the bridge host; submit without --deliver/--thread (quiet delivery) or install T3 Code');
890
+ if(!body.assignment||typeof body.assignment!=='object'||Array.isArray(body.assignment)) throw new Error('invalid assignment: must be a JSON object');
891
+ if(typeof body.assignment.request_id!=='string'||!/^[-\w]{8,128}$/.test(body.assignment.request_id)) throw new Error('invalid assignment: request_id is required and must be 8-128 letters, digits, _ or -');
892
+ if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment: inputs must be an array (use [] when the assignment has no repository input)');
893
+ if(Object.hasOwn(body.assignment,'protocol')&&(!retry||store.isProtocolJob(body.assignment.request_id))) {
894
+ if(catalogProfile!=='protocol-v0')throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
895
+ validateProtocol(body.assignment.protocol);
896
+ }
897
+ let payload=renderAssignment(body.assignment);
898
+ if(!payload||payload.schema_version!==1||!payload.brief||!Array.isArray(payload.inputs)||typeof payload.expected_output!=='string'||typeof payload.execution_scope!=='string') {
899
+ const wrong=payload?[payload.schema_version!==1&&'schema_version (must be 1)',!payload.brief&&'brief',!Array.isArray(payload.inputs)&&'inputs (an array)',typeof payload.expected_output!=='string'&&'expected_output (a string)',typeof payload.execution_scope!=='string'&&'execution_scope (a string)'].filter(Boolean):[];
900
+ throw new Error(`invalid assignment: needs schema_version 1, brief, inputs, expected_output and execution_scope${wrong.length?`; missing or wrong: ${wrong.join(', ')}`:''}`);
901
+ }
902
+ // Profile mode never falls back to the legacy default worker: retries retain their stored target and policy check.
903
+ const existingRequest=retry?store.get(payload.request_id):null,storedTarget=existingRequest?.target_worker;
904
+ const target=retry?(body.worker===undefined?storedTarget:submitTarget(workers,body.worker)):submitTarget(workers,body.worker);
905
+ if(!retry) assertTarget(workers,target??'dot');
906
+ if(existingRequest) {
907
+ assertRepoAllowed(storedTarget,existingRequest.assignment);
908
+ }
909
+ assertRepoAllowed(storedTarget??target??'dot',payload);
910
+ if(body.max_queued!==undefined&&(!Number.isSafeInteger(body.max_queued)||body.max_queued<1)) throw new Error('invalid max_queued');
911
+ if(body.review!==undefined&&typeof body.review!=='boolean') throw new Error('invalid review');
912
+ if(body.background!==undefined&&body.background!==true) throw new Error('invalid background');
913
+ if(body.allow_main!==undefined&&typeof body.allow_main!=='boolean') throw new Error('invalid allow_main');
914
+ if(body.exclude_sensitive!==undefined&&typeof body.exclude_sensitive!=='boolean') throw new Error('invalid exclude_sensitive');
915
+ // Execution capability (design section 3). Omitted: the profile default, which is host for the legacy profile. A retry that omits it is not judged.
916
+ const explicitExecution=body.execution===undefined?null:parseExecution(body.execution);
917
+ const requiredCapabilities=parseRequiredCapabilities(body.required_capabilities);
918
+ const jobExecution=explicitExecution??workers.defaultExecution;
919
+ if(body.queue_anyway!==undefined&&typeof body.queue_anyway!=='boolean') throw new Error('invalid queue_anyway');
920
+ if(body.refuse_defer!==undefined&&typeof body.refuse_defer!=='boolean') throw new Error('invalid refuse_defer');
921
+ if(body.defer_queued!==undefined&&(!Number.isSafeInteger(body.defer_queued)||body.defer_queued<1)) throw new Error('invalid defer_queued');
922
+ const dryRun=url.pathname==='/submit-preview';
923
+ if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
924
+ if(body.assignment&&Object.hasOwn(body.assignment,'scope_excluded')) throw new Error('assignment declares scope_excluded; only the bridge records what it dropped from a scope');
925
+ const declaredSource=body.meta?.source??'agent';
926
+ for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,declaredSource);
927
+ const meta=normalizeMeta(body.meta);
928
+ // A retry of an older row is not judged again; only a new submission has to prove the source it claims.
929
+ if(!store.hasAssignment(payload.request_id)) {const refused=unprovenSource({request_id:payload.request_id,payload,meta},body.background===true?'background':'normal'); if(refused) throw new Error(refused);}
930
+ {const input=payload.inputs[0];if(!store.hasAssignment(payload.request_id)&&payload.execution_scope==='implementation'&&body.review!==true&&input?.head_sha&&input.head_sha!==input.base_sha) throw new Error('head_sha_unsupported: implementation scope checks out base_sha; pin base_sha to the revision to work on, or use --review or read-only scope for head_sha');}
931
+ if(body.allow_main===true) adminOperator(req);
932
+ destination.admit(delivery,{allowMain:body.allow_main===true});
933
+ if(body.sensitive_scope_override!==undefined&&(typeof body.sensitive_scope_override!=='string'||!body.sensitive_scope_override)) throw new Error('invalid sensitive scope override');
934
+ // A retry validates nothing and sends the original assignment, so the identity of a request is the assignment as submitted,
935
+ // even when validation changed the stored brief (scope narrowing, the appended allow-list).
936
+ const submitted=payload;
937
+ const isNew=!store.hasAssignment(payload.request_id);
938
+ // Reject immutable retry conflicts using the persisted binding before any external destination inspection.
939
+ // A matching retry still validates the current destination below; this does not accept stale environment evidence.
940
+ store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
941
+ let order=null;
942
+ if(isNew) {
943
+ order=await compileWorkOrder({assignment:payload,review:body.review===true,priority:body.background===true?'background':'normal',jobExecution,requiredCapabilities,meta,maxQueued:body.max_queued??null,deferQueued:body.defer_queued??null,
944
+ excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
945
+ render:renderAssignment,
946
+ admitExecution:(p,r)=>{
947
+ if(r.requiredCapabilities&&r.jobExecution!=='host') throw new Error(`invalid required_capabilities: only execution=host jobs can require bridge capabilities (this job has execution=${r.jobExecution})`);
948
+ // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
949
+ if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities);
950
+ },
951
+ validate:(p,{warnings})=>validateSubmissionAsync(p,{sensitiveScopeOverride:body.sensitive_scope_override??null,warnings,excludeSensitive:body.exclude_sensitive===true,review:body.review===true,worker:storedTarget??target??'dot'}),
952
+ admitReadiness:p=>{
953
+ if(p.execution_scope!=='implementation') return null;
954
+ const readiness=admitImplementation(p,{execution:jobExecution,worker:storedTarget??target??'dot'});
955
+ if(!dryRun) log({kind:'check_readiness',request_id:p.request_id,...readiness});
956
+ return readiness;
957
+ },
958
+ preflight:p=>preflightPR(p),
959
+ // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
960
+ state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:(r.target==='dot'?store.holdingBreak():null),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
961
+ kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
962
+ defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
963
+ retryAfterSeconds:r=>{const w=store.queueWaitsMs(r.target,r.meta?.task_kind??(r.review?'review':'unknown'));return w.length?Math.min(3600,Math.max(60,Math.round(w[Math.floor(w.length/2)]/1000))):300;},
964
+ deferQueued:envDeferQueued});
965
+ // A refusal keeps the message the old path threw; the typed reasons ride along on it. A dry run reports every verdict as a 200.
966
+ if(!dryRun&&(order.verdict==='reject'||order.verdict==='clarify'||order.blocking)) throw Object.assign(order.refusal,{verdict:order.verdict,reasons:order.reasons,bytes:order.bytes});
967
+ payload=order.payload;
968
+ }
969
+ const {environmentId}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
970
+ // An awaited repository/destination lookup may outlive a host policy edit.
971
+ assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
972
+ if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
973
+ const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
974
+ if(dryRun) {
975
+ log({kind:'submit_dry_run',request_id:submitted.request_id,task_kind:meta.task_kind??null,source:meta.source??null,verdict:order?.verdict??'admissible',reason_codes:(order?.reasons??[]).map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt});
976
+ return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
977
+ }
978
+ // Defer refuses only for a requester that opts in; both the CLI and HTTP API queue by default.
979
+ if(order?.verdict==='defer'&&body.refuse_defer===true&&body.queue_anyway!==true) {
980
+ log({kind:'submit_deferred',...rejected,reason_codes:order.reasons.map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt});
981
+ return json(res,409,{error:`deferred: ${order.reasons.map(r=>r.message).join('; ')}`,verdict:'defer',reasons:order.reasons,bytes:order.bytes,retry_after_seconds:order.retry_after_seconds});
982
+ }
983
+ const submissionWarnings=order?.warnings??[];
984
+ const readiness=order?.check_readiness??null;
985
+ const preflight=order?.preflight??null;
986
+ const defaultValidity=order?.defaultValidity??null;
987
+ const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision);
988
+ // Only a committed first replacement wakes the TARGET's already-attached waiter.
989
+ if(supersedes&&!result.duplicate) {
990
+ const targetId=supersedes.target_id,waiter=waiters.get(targetId);
991
+ if(waiter) { waiters.delete(targetId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(targetId)); }
992
+ }
993
+ log({kind:'submit_admitted',...rejected,duplicate:result.duplicate,attempt_latency_ms:Date.now()-requestStartedAt,bytes:order?.bytes??null});
994
+ // A retry validates nothing, so the narrowing it reports comes from the stored assignment.
995
+ const stored=result.duplicate?JSON.parse(store.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(payload.request_id).payload):payload;
996
+ if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
997
+ return json(res,200,{...result,execution:store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(payload.request_id).execution,...(stored.scope_excluded?.length?{scope_excluded:stored.scope_excluded,scope_paths:stored.scope_paths}:{}),...(readiness?{check_readiness:readiness}:{}),...(submissionWarnings.length?{submission_warnings:submissionWarnings}:{})});
998
+ }
999
+ if(url.pathname==='/admission'&&req.method==='GET') { const row=store.db.prepare('SELECT cancelled_reason FROM assignments WHERE request_id=?').get(id(url.searchParams.get('id'))); return json(res,200,{exists:!!row,...(row?.cancelled_reason==='expired'?{cancelled_reason:'expired'}:{})}); }
1000
+ if(url.pathname==='/get') {
1001
+ const requestId=id(url.searchParams.get('id'));
1002
+ if(!store.hasAssignment(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
1003
+ adminOwner(req,requestId);
1004
+ store.assertProtocolAvailable(requestId);
1005
+ store.recordFetched(requestId);
1006
+ // Read before recording consumption: the response then matches a peek read, which records no consumption.
1007
+ const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1008
+ if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
1009
+ if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
1010
+ if(!workspaceEnabled||got.assignment?.execution_scope!=='implementation'||got.available_checks_error==='repository_policy_denied') return json(res,200,got);
1011
+ try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
1012
+ catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
1013
+ }
1014
+ if(url.pathname==='/artifact') { const artifactId=id(url.searchParams.get('id'),'artifact_id');const row=store.db.prepare('SELECT request_id FROM artifacts WHERE id=? AND sealed=1').get(artifactId);if(!row) throw new Error('artifact not found');adminOwner(req,row.request_id);const bytes=(workspace||new Workspace(store,false)).artifact(artifactId,row.request_id);res.writeHead(200,{'content-type':'application/octet-stream','content-length':bytes.bytes.length,'x-artifact-sha256':bytes.row.sha256});res.end(bytes.bytes);return; }
1015
+ if(['/protocol/wait','/protocol/inbox','/protocol/ack'].includes(url.pathname)&&req.method==='POST') {
1016
+ if(catalogProfile!=='protocol-v0') throw new Error('protocol owner routes require DALAN_CATALOG_PROFILE=protocol-v0');
1017
+ const requestId=id(body.id),owner=req.headers['x-owner-capability'];
1018
+ const waiters=createProtocolOwnerWaiters(store);
1019
+ if(url.pathname==='/protocol/wait') return json(res,200,waiters.register(requestId,owner,{
1020
+ key:body.command_key,revision:body.expected_revision,waiter:body.waiter,predicate:body.predicate,afterSeq:body.after_seq,expiresAt:body.expires_at,
1021
+ }));
1022
+ if(url.pathname==='/protocol/inbox') return json(res,200,waiters.inbox(requestId,owner,body.waiter));
1023
+ return json(res,200,waiters.ack(requestId,owner,body.waiter,body.delivery));
1024
+ }
1025
+ if(url.pathname==='/wait'&&req.method==='GET') {
1026
+ const requestId=id(url.searchParams.get('id')); adminOwner(req,requestId);
1027
+ const seconds=Number(url.searchParams.get('timeout')??300);
1028
+ if(!Number.isInteger(seconds)||seconds<1||seconds>3600) throw new Error('timeout must be an integer from 1 to 3600 seconds');
1029
+ return attachWaiter(req,res,requestId,seconds*1000,url.searchParams.get('peek')!=='1');
1030
+ }
1031
+ // `dalan inbox --mark-read`: record the owner read (the same marker as /get) for each owned request, returning no results.
1032
+ if(url.pathname==='/owner-mark-read'&&req.method==='POST') {
1033
+ if(!Array.isArray(body.items)||body.items.length>500) throw new Error('items must be an array of at most 500');
1034
+ const results=body.items.map(item=>{
1035
+ const requestId=id(item?.id);
1036
+ try { store.owner(requestId,item.capability); } catch { return {request_id:requestId,error:'not_owned'}; }
1037
+ return {request_id:requestId,marked:store.markInboxRead(requestId,'inbox-mark-read')};
1038
+ });
1039
+ return json(res,200,{results,marked:results.filter(r=>r.marked).length});
1040
+ }
1041
+ // Batch owner read for `dalan wait --drained`: status and blocker notes for each owned request plus whether a refill
1042
+ // would be held. Unlike /get it records no 'consumed' event, so a polling waiter does not fake owner reads.
1043
+ if(url.pathname==='/owner-states'&&req.method==='POST') {
1044
+ if(!Array.isArray(body.items)||body.items.length>500) throw new Error('items must be an array of at most 500');
1045
+ const states=body.items.map(item=>{
1046
+ const requestId=id(item?.id);
1047
+ try { store.owner(requestId,item.capability); } catch { return {request_id:requestId,error:'not_owned'}; }
1048
+ const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId);
1049
+ const blockers=store.db.prepare('SELECT note FROM progress WHERE request_id=? ORDER BY id').all(requestId).map(p=>p.note).filter(note=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(note));
1050
+ return {request_id:requestId,status:row.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
1051
+ });
1052
+ // Only evidence holds refill: a pause or an owner-confirmed break. throttled stays false for older readers.
1053
+ const paused=store.paused(), dotBreak=!!store.holdingBreak();
1054
+ const held=paused?'paused':dotBreak?'worker_break':null;
1055
+ return json(res,200,{states,refill:{held,paused,worker_break:dotBreak,throttled:false}});
1056
+ }
1057
+ if(url.pathname==='/tools'&&req.method==='GET') { adminOperator(req); return json(res,200,{tools:toolRegistry.list()}); }
1058
+ if(url.pathname.startsWith('/tools/')&&req.method==='POST') {
1059
+ adminOperator(req);
1060
+ try {
1061
+ const action=url.pathname.slice(7);
1062
+ if(action==='add') return json(res,200,toolRegistry.register(body.spec));
1063
+ if(action==='remove') return json(res,200,toolRegistry.remove(body.name));
1064
+ if(action==='grant') { toolRegistry.grant(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
1065
+ if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1066
+ } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1067
+ }
1068
+ if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,owner_waiter_count:waiters.size});
1069
+ if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1070
+ if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1071
+ const requestId=id(body.id); adminOwner(req,requestId);
1072
+ const note=body.note===undefined||body.note===null?null:str(body.note,'note',4096);
1073
+ return json(res,200,store.verdict(requestId,url.pathname==='/accept',note));
1074
+ }
1075
+ if(url.pathname==='/decide'&&req.method==='POST') {
1076
+ const requestId=id(body.id); adminOwner(req,requestId);
1077
+ if(body.decision==='stale') throw new Error('stale is recorded by the sweep only');
1078
+ const via=['cli','apply','adapter'].includes(body.via)?body.via:'cli';
1079
+ return json(res,200,store.decide(requestId,String(body.decision),{note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
1080
+ }
1081
+ if(url.pathname==='/lifecycle'&&req.method==='POST') {
1082
+ adminOperator(req);
1083
+ if(body.type!=='integrated') throw new Error('only type integrated is accepted');
1084
+ return json(res,200,store.integrated(id(body.id),body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)));
1085
+ }
1086
+ if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
1087
+ if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);return json(res,200,store.answerQuestion(requestId,str(body.question_id,'question_id',128),str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1088
+ if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1089
+ if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1090
+ if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
1091
+ if(url.pathname.startsWith('/connect/')) {
1092
+ adminOperator(req);
1093
+ if(!as) throw new Error('built-in authorization server is not enabled (DALAN_AUTH_MODE=builtin)');
1094
+ const ops=as.ops;
1095
+ if(url.pathname==='/connect/add-client'&&req.method==='POST') return json(res,200,ops.addClient({redirectUri:body.redirect_uri,...(body.name!==undefined?{name:body.name}:{})}));
1096
+ if(url.pathname==='/connect/clients'&&req.method==='GET') return json(res,200,ops.clients());
1097
+ if(url.pathname==='/connect/remove-client'&&req.method==='POST') return json(res,200,ops.removeClient({clientId:body.client_id}));
1098
+ if(url.pathname==='/connect/start'&&req.method==='POST') return json(res,200,ops.start({worker:body.worker,...(body.minutes!==undefined?{minutes:body.minutes}:{})}));
1099
+ if(url.pathname==='/connect/reset'&&req.method==='POST') return json(res,200,ops.reset());
1100
+ if(url.pathname==='/connect/stop'&&req.method==='POST') return json(res,200,ops.stop());
1101
+ if(url.pathname==='/connect/pending'&&req.method==='GET') return json(res,200,ops.pending());
1102
+ if(url.pathname==='/connect/approve'&&req.method==='POST') return json(res,200,await ops.approve({code:body.code,worker:body.worker,replace:body.replace===true?true:body.replace===undefined?false:body.replace,confirm_redirect:body.confirm_redirect}));
1103
+ if(url.pathname==='/connect/list'&&req.method==='GET') return json(res,200,ops.list());
1104
+ if(url.pathname==='/connect/revoke'&&req.method==='POST') return json(res,200,ops.revoke({worker:body.worker}));
1105
+ if(url.pathname==='/connect/signal-token'&&req.method==='POST') return json(res,200,signal.tokenUrl({worker:body.worker,rotate:body.rotate===true}));
1106
+ if(url.pathname==='/connect/allow-callback'&&req.method==='POST') return json(res,200,ops.allowCallback({pattern:body.pattern}));
1107
+ return json(res,404,{error:'not found'});
1108
+ }
1109
+ if(url.pathname==='/audit') { adminOperator(req); return json(res,200,{entries:(await loadT3Audit()).listT3Audit(store.db,url.searchParams.get('since'))}); }
1110
+ if(url.pathname==='/notify-pending'&&req.method==='GET') {
1111
+ adminOperator(req);
1112
+ return json(res,200,{notifications:notifyLedger.pending()});
1113
+ }
1114
+ if(url.pathname==='/notify-reconcile'&&req.method==='POST') {
1115
+ adminOperator(req);
1116
+ const result=notifyLedger.reconcile({key_sha256:body.key_sha256,outcome:body.outcome,evidence:body.evidence});
1117
+ log({kind:'notification_reconciled',key_sha256:result.key_sha256,outcome:result.outcome});
1118
+ return json(res,200,result);
1119
+ }
1120
+ if(url.pathname==='/backfill-objectives'&&req.method==='POST') {
1121
+ adminOperator(req);
1122
+ if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
1123
+ return json(res,200,store.backfillObjectives(body.tuples,{dryRun:body.dry_run===true}));
1124
+ }
1125
+ if(url.pathname==='/claims'&&req.method==='GET') { adminOperator(req); return json(res,200,{lease_ms:store.limits.leaseMs,claims:store.claims()}); }
1126
+ if(url.pathname==='/abandon'&&req.method==='POST') {
1127
+ adminOperator(req);
1128
+ const requestId=id(body.id),result=store.abandon(requestId,{actor:'operator',reason:body.reason===undefined||body.reason===null?'operator_abandon':str(body.reason,'reason',512)});
1129
+ log({kind:'claim_abandoned',request_id:requestId,epoch:result.abandoned.epoch,actor:'operator'});
1130
+ runDrain();
1131
+ return json(res,200,result);
1132
+ }
1133
+ if(url.pathname==='/cancel') {
1134
+ const requestId=id(body.id); adminOwner(req,requestId);
1135
+ const result=store.cancel(requestId,body.reason===undefined||body.reason===null?null:str(body.reason,'reason',64),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability']); const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } return json(res,200,result);
1136
+ }
1137
+ if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
1138
+ const requestId=id(body.id); adminOwner(req,requestId);
1139
+ const result=store.cancelIfQueued(requestId);
1140
+ if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
1141
+ return json(res,200,result);
1142
+ }
1143
+ if(url.pathname==='/break'&&req.method==='POST') {
1144
+ adminOperator(req);
1145
+ if(body.clear===true) { const cleared=store.clearBreak(); sweepExpired(); return json(res,200,cleared); }
1146
+ if(body.since!==undefined&&body.since!==null&&(typeof body.since!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(body.since)||!Number.isFinite(Date.parse(body.since)))) throw new Error('since must be an RFC 3339 time with offset');
1147
+ const result=store.setBreak(str(body.reason,'reason',512),body.since?new Date(body.since).toISOString():null);
1148
+ log({kind:'worker_break_set',source:'owner',since:result.since});
1149
+ return json(res,200,result);
1150
+ }
1151
+ if(url.pathname==='/break-usage-backfill'&&req.method==='POST') { adminOperator(req); return json(res,200,store.mergeBreakUsage(body.id,body.since,body.windows)); }
1152
+ if(url.pathname==='/learned'&&req.method==='GET') { adminOperator(req); return json(res,200,{learned:store.learnedLimits(),over_estimate:store.overEstimate(redeliveryLimits)}); }
1153
+ if(url.pathname==='/learned'&&req.method==='POST') {
1154
+ adminOperator(req); if(body.clear!==true) throw new Error('learned accepts only {clear:true}');
1155
+ const result=store.clearLearnedLimits(); log({kind:'learned_limits_cleared',source:'owner',removed:result.removed}); return json(res,200,result);
1156
+ }
1157
+ if(url.pathname==='/breaks'&&req.method==='GET') { adminOperator(req); return json(res,200,{worker_break:store.breakState(),breaks:store.breaks()}); }
1158
+ if(url.pathname==='/verify-stops'&&req.method==='POST') {
1159
+ adminOperator(req);
1160
+ const requestId=body.id===undefined?undefined:id(body.id);
1161
+ return json(res,200,{request_id:requestId??null,stops:workspace?workspace.reconcileHostStops(requestId):[]});
1162
+ }
1163
+ if(['/pause','/resume','/reconcile'].includes(url.pathname)) {
1164
+ adminOperator(req);
1165
+ if(url.pathname==='/pause') return json(res,200,store.setPause(str(body.reason,'reason',512)));
1166
+ if(url.pathname==='/resume') return json(res,200,store.setPause(null));
1167
+ const requestId=id(body.id),adopt=body.adopt===true;
1168
+ if(adopt) store.adopt(requestId,str(body.owner_token,'owner_token',128));
1169
+ return json(res,200,{request_id:requestId,adopted:adopt,reconciliation:await reconcileRequest(requestId),assignment:(row=>row&&withoutT3(row))(store.get(requestId))});
1170
+ }
1171
+ json(res,404,{error:'not found'});
1172
+ } catch(e) {
1173
+ const infrastructure=e.code==='DOT_BRIDGE_INFRASTRUCTURE'||e.code==='ERR_SQLITE_ERROR'||['EIO','ENOSPC','EMFILE','ENFILE','EROFS','ENOENT','EACCES','EPERM'].includes(e.code);
1174
+ // Every refusal of a submit carries typed reasons and a verdict, whichever check threw (the compiler or an earlier request check).
1175
+ const reasons=!infrastructure&&rejected?(e.reasons??reasonsFromError(e).map(({verdict,retry,blocking,...r})=>r)):null;
1176
+ const verdict=reasons?(e.verdict??strongest(reasonsFromError(e))):null;
1177
+ // A dry run answers every verdict with a 200 and stores nothing, including a refusal raised before the compiler ran.
1178
+ if(dryRequested&&reasons) { log({kind:'submit_dry_run',...rejected,verdict,reason_codes:reasons.map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt}); return json(res,200,{dry_run:true,stored:false,request_id:rejected?.request_id??null,verdict,reasons,bytes:e.bytes??null,warnings:[]}); }
1179
+ if(rejected) log({kind:'submit_rejected',...rejected,status:infrastructure?503:400,reason:e.message.slice(0,300),...(reasons?{verdict,reason_codes:reasons.map(r=>r.code)}:{}),bytes:e.bytes??null,attempt_latency_ms:Date.now()-requestStartedAt,...(e.suggested_scope_paths?{suggested_scope_count:e.suggested_scope_paths.length}:{})});
1180
+ if(infrastructure&&!rejected) log({kind:'admin_infrastructure_error',route:String(req.url).split('?')[0],code:e.code??null,reason:e.message.slice(0,300)});
1181
+ const shown=publicErrorText(e,'admin request');
1182
+ json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(infrastructure?{code:e.code??null,reason:shown.slice(0,300)}:{}),...(!infrastructure&&e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(reasons?{verdict,reasons,...(e.bytes?{bytes:e.bytes}:{})}:{})});
1183
+ }
1184
+ });
1185
+
1186
+ let reconciliationFlight=null;
1187
+ async function withReconcileLock(work) {
1188
+ while(reconciliationFlight) await reconciliationFlight.catch(()=>{});
1189
+ const flight=Promise.resolve().then(work); reconciliationFlight=flight;
1190
+ try { return await flight; } finally { if(reconciliationFlight===flight) reconciliationFlight=null; }
1191
+ }
1192
+ const reconciliationFence=(item,row)=>({attemptId:item.attempt_id,attemptStartedAt:item.attempt_started_at,body:item.body,argv:item.argv,threadId:row?.thread_id??null,environmentId:row?.environment_id??null,targetWorker:row?.target_worker??null,assignmentStatus:row?.status??null,deliveryMode:row?.delivery_mode??null,reportSnapshot:JSON.stringify(row?.report?{outcome:row.report.outcome,summary:row.report.summary,result:row.report.result}:null)});
1193
+ async function reconcileRequest(requestId) {
1194
+ return withReconcileLock(async()=>{
1195
+ const item=store.uncertainOne(requestId); if(!item) return [];
1196
+ const now=store.nowMs();
1197
+ if(!Number.isFinite(now)||!Number.isInteger(now)||!Number.isFinite(new Date(now).getTime()))
1198
+ return [{id:item.id,state:'deferred',reason:'clock is invalid; reconciliation remains conservative'}];
1199
+ if(item.last_reconciled_at) {
1200
+ const last=Date.parse(item.last_reconciled_at);
1201
+ if(!Number.isFinite(last)||!Number.isFinite(now)||!Number.isFinite(new Date(now).getTime())||now<last+60000)
1202
+ return [{id:item.id,state:'deferred',reason:'minimum observation interval is 60 seconds; clock or prior observation is invalid'}];
1203
+ }
1204
+ const row=store.get(item.request_id),destination=await destinations.for(row.delivery_mode);
1205
+ const outcome=await destination.reconcile(item,row);
1206
+ store.reconciled(item.id,outcome.state==='confirmed'?'delivered':'uncertain',outcome.reason||'marker found',reconciliationFence(item,row));
1207
+ return [{id:item.id,state:outcome.state,reason:outcome.reason||null}];
1208
+ });
1209
+ }
1210
+ async function reconcileTick() {
1211
+ return withReconcileLock(async()=>{
1212
+ const unknown=[];
1213
+ // These probes read only the local ACK ledger; no transcript/network lookup.
1214
+ // Check positive evidence for every candidate before applying its age policy.
1215
+ for(const item of store.uncertainBatch()) {
1216
+ const row=item.request_id?store.get(item.request_id):null;
1217
+ let outcome={state:'ambiguous',reason:'bounded positive observation unsupported'};
1218
+ if(item.kind==='event') {
1219
+ const sub=store.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(item.subscription_id);
1220
+ if(sub&&store.subscriptionActive(sub)&&store.mayAct(sub.worker,item.request_id??item.message_id)) {
1221
+ const binding=`webhook\0${sub.id}\0${sub.url}\0${sub.worker}\0${sub.principal}\0${readEnv('DALAN_ENVIRONMENT_ID')??os.hostname()}`;
1222
+ const key=ackLedger.key(item.id,item.body,binding);
1223
+ if(ackLedger.has(key)) outcome={state:'confirmed',reason:'recovered from durable webhook acceptance acknowledgment'};
1224
+ else outcome={state:'ambiguous',reason:'no durable webhook acceptance acknowledgment'};
1225
+ } else outcome={state:'ambiguous',reason:'target webhook subscription is no longer active or authorized'};
1226
+ } else {
1227
+ const destination=row&&await destinations.for(row.delivery_mode);
1228
+ if(typeof destination?.reconcilePositiveAck==='function') outcome=await destination.reconcilePositiveAck(item,row);
1229
+ }
1230
+ const changed=store.reconciled(item.id,outcome.state==='confirmed'?'delivered':'uncertain',outcome.reason||'positive acknowledgment found',reconciliationFence(item,row));
1231
+ if(changed&&outcome.state!=='confirmed') unknown.push(item.id);
1232
+ }
1233
+ for(const item of store.releaseAgedUncertain(unknown)) log({kind:'uncertain_delivery_terminal',...item,policy:'uncertain_delivery_age_limit'});
1234
+ });
1235
+ }
1236
+ let delivering=false;
1237
+ async function drain() {
1238
+ if(delivering||store.paused()) return; delivering=true;
1239
+ try {
1240
+ store.reannounceQueued(redeliveryLimits);
1241
+ for(const item of store.due()) {
1242
+ if(store.paused()) break;
1243
+ const row=item.kind==='event'?null:store.get(item.request_id);
1244
+ let destination=null;
1245
+ if(row) {
1246
+ try { destination=await destinations.for(row.delivery_mode); }
1247
+ catch(error) {
1248
+ const reason=`destination unavailable: ${String(error?.message??error).slice(0,300)}`;
1249
+ if(error?.code==='INVALID_DELIVERY_MODE') {
1250
+ if(store.quarantineDelivery(item.id,reason)) log({kind:'delivery_quarantined',event_id:item.id,request_id:item.request_id,reason});
1251
+ } else if(store.retryDelivery(item.id,reason)) log({kind:'delivery_retry_scheduled',event_id:item.id,request_id:item.request_id,reason,retry_in_ms:1000});
1252
+ continue;
1253
+ }
1254
+ }
1255
+ if(row) {
1256
+ const reason=destination.quietReason(row);
1257
+ if(reason) { store.quietDelivery(item.id,reason); notifyAttachedWaiter(item.request_id); continue; }
1258
+ }
1259
+ const argv=row?destination.argv(item,row):null;
1260
+ const started=store.startAttempt(item.id,argv); if(!started) continue;
1261
+ if(crashAt('after_attempt_commit',item.request_id)) process.exit(71);
1262
+ let state='failed',reason='';
1263
+ // The adapter settles every failure it can classify. Anything it rethrows (a failed log write inside its
1264
+ // own catch) must escape drain and leave the row 'sending' for startup recovery, as before the refactor.
1265
+ let positiveAckObserved=false,ackDurablyRecorded=false;
1266
+ if(row) ({state,reason}=await destination.send(item,{started,argv}));
1267
+ else try {
1268
+ {
1269
+ const sub=store.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(item.subscription_id);
1270
+ if(!store.subscriptionActive(sub)) {
1271
+ if(sub) store.retireUnusableSubscription(sub);
1272
+ state='suppressed'; reason='subscription inactive';
1273
+ }
1274
+ else if(!store.mayAct(sub.worker,item.request_id??item.message_id)) { state='suppressed'; reason='worker cannot see event'; }
1275
+ else {
1276
+ const binding=`webhook\0${sub.id}\0${sub.url}\0${sub.worker}\0${sub.principal}\0${readEnv('DALAN_ENVIRONMENT_ID')??os.hostname()}`;
1277
+ const ack=ackLedger.key(item.id,item.body,binding);
1278
+ // An earlier ACK is not a new callback and must not clear callback failures.
1279
+ if(ackLedger.has(ack)) { ackDurablyRecorded=true; state='delivered'; reason='recovered from durable webhook acceptance acknowledgment'; }
1280
+ else {
1281
+ const response=await sendWebhook(sub.url,store.subscriptionSecret(sub),item.id,sub.id,item.body);
1282
+ if(response.status>=200&&response.status<300) { positiveAckObserved=true; ackLedger.record(ack); ackDurablyRecorded=true; }
1283
+ store.eventResult(sub.id,response.status);
1284
+ state=response.status>=200&&response.status<300?'delivered':response.status===410||response.status===413?'suppressed':'failed';
1285
+ reason=state==='delivered'?'':`HTTP ${response.status}`;
1286
+ if(item.message_id) log({kind:'message_event',message_id:item.message_id,event_id:item.id,state,http_status:response.status});
1287
+ }
1288
+ }
1289
+ }
1290
+ } catch(e) { reason=e.message; state=ackDurablyRecorded?'delivered':positiveAckObserved?'uncertain':'failed'; log({kind:'delivery_error',event_id:item.id,reason}); }
1291
+ store.finishAttempt(item.id,started.attempt_id,state,reason);
1292
+
1293
+ }
1294
+ } finally { delivering=false; }
1295
+ }
1296
+ function maintain() {
1297
+ try {
1298
+ sweepExpired();
1299
+ sweepSkipped();
1300
+ sweepStaleLeases();
1301
+ store.retireUnknownSubscriptions();
1302
+ } catch(error) { log({kind:'maintenance_error',reason:error.message}); }
1303
+ }
1304
+ const runDrain=createDrainRunner(drain,log);
1305
+ store.recoverSends();
1306
+ try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
1307
+ const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
1308
+ // Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
1309
+ const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
1310
+ const publicListening=new Promise(resolve=>publicServer.listen(port,bindHost,()=>{console.log(`MCP listening on ${bindHost}:${publicServer.address().port}`);resolve();}));
1311
+ // Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
1312
+ // cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
1313
+ if(workspace) {
1314
+ const cleanup=()=>workspace.cleanupExpired({log}).then(s=>{if(s.artifacts_removed||s.workspaces_removed||s.errors)log({kind:'workspace_cleanup',...s});},error=>log({kind:'artifact_cleanup_error',request_id:error.request_id,reason:error.message}));
1315
+ Promise.all([adminListening,publicListening]).then(()=>{setTimeout(cleanup,1000).unref();setInterval(cleanup,3600000).unref();});
1316
+ }
1317
+ setInterval(()=>{if(t3PostHandler.hasHeld())t3PostHandler.flushDue().catch(()=>{});},60000).unref();
1318
+ setInterval(maintain,500).unref(); maintain();
1319
+ setInterval(runDrain,500).unref(); runDrain();
1320
+ reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message}));
1321
+ setInterval(()=>reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message})),60000).unref();
1322
+ const retain=()=>{try{const r=retainLifecycle(store);if(r.rolled_up)log({kind:'lifecycle_rollup',...r});}catch(error){log({kind:'lifecycle_rollup_error',reason:error.message});}};
1323
+ retain(); setInterval(retain,3600000).unref();
1324
+ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_STALE_DAYS')));
1325
+ const sweepStale=()=>{try{const ids=store.sweepStaleDecisions(staleDays);if(ids.length)log({kind:'decisions_stale',count:ids.length,request_ids:ids.slice(0,20)});}catch(error){log({kind:'decisions_stale_error',reason:error.message});}};
1326
+ sweepStale(); setInterval(sweepStale,3600000).unref();
1327
+ setInterval(()=>checkAlerts(store,log).catch(e=>log({kind:'alert_error',reason:e.message})),60000).unref();
1328
+
1329
+ }
1330
+
1331
+ let directEntry=false;
1332
+ if(process.argv[1]) {
1333
+ try { directEntry=import.meta.url===pathToFileURL(fs.realpathSync(process.argv[1])).href; } catch {}
1334
+ }
1335
+ // An error that carries a fix is the operator's to correct: print it as one plain message, not a stack trace.
1336
+ if(directEntry) await main().catch(error=>{
1337
+ if(!Array.isArray(error?.fix)) throw error;
1338
+ console.error(`dalan: ${error.message}`); for(const line of error.fix) console.error(`dalan: fix: ${line}`);
1339
+ process.exitCode=1;
1340
+ });