@tnunamak/dalan 0.5.2 → 0.6.1
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.
- package/CHANGELOG.md +37 -25
- package/PROTOCOL.md +16 -4
- package/README.md +127 -260
- package/SECURITY.md +1 -1
- package/bin/dalan.mjs +5 -0
- package/bin/dot-worker.mjs +35 -26
- package/docs/chatgpt-worker-onboarding.md +5 -5
- package/docs/claude-worker-onboarding.md +5 -5
- package/docs/codex-to-muse.md +181 -0
- package/docs/connect-chatgpt.md +9 -4
- package/docs/connection-longevity.md +7 -1
- package/docs/dalan-upgrade.md +18 -14
- package/docs/deadman.md +5 -3
- package/docs/local-agent-mcp.md +8 -6
- package/docs/manual-setup.md +8 -8
- package/docs/mirror-fetch.md +1 -2
- package/docs/operations.md +90 -42
- package/docs/operator-duties.md +1 -1
- package/docs/owner-integrator.md +2 -2
- package/docs/portable-auth-profile.md +12 -14
- package/docs/pr-head-reviewer.md +21 -5
- package/docs/pr-preflight.md +2 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +7 -10
- package/docs/redaction.md +1 -1
- package/docs/service-setup.md +56 -3
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +3 -1
- package/docs/t3-result-retry-delivery.md +2 -2
- package/docs/t3-reverse-control.md +7 -7
- package/docs/usage.md +19 -15
- package/docs/worker-clients.md +18 -13
- package/package.json +3 -1
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +1 -1
- package/scripts/worker-bridge-setup.mjs +1 -1
- package/src/acp-bridge.mjs +18 -12
- package/src/as.mjs +41 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/cli-help.mjs +25 -11
- package/src/demo-worker.mjs +2 -2
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +20 -3
- package/src/mcp-outcome.mjs +10 -1
- package/src/mcp-sse.mjs +62 -0
- package/src/pr-head-reviewer.mjs +3 -3
- package/src/process-inspection.mjs +36 -0
- package/src/pull-queue.mjs +159 -0
- package/src/route-setting.mjs +24 -0
- package/src/server.mjs +157 -29
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +423 -0
- package/src/setup.mjs +63 -0
- package/src/store.mjs +21 -9
- package/src/tool-registry.mjs +3 -1
- package/src/try-exposure.mjs +918 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +63 -17
- package/src/workers.mjs +33 -23
- package/src/workspace.mjs +10 -3
package/src/server.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
1
2
|
import {inspect} from 'node:util';
|
|
2
3
|
import { loopbackRequestAllowed } from './loopback.mjs';
|
|
3
4
|
import { defaultPath,workspaceRoot,rootWarnings } from './paths.mjs';
|
|
@@ -12,7 +13,7 @@ import path from 'node:path';
|
|
|
12
13
|
import os from 'node:os';
|
|
13
14
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
14
15
|
import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
|
|
15
|
-
import { Store, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
|
|
16
|
+
import { Store, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
|
|
16
17
|
import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
|
|
17
18
|
import { sendWebhook, validSecret } from './webhooks.mjs';
|
|
18
19
|
import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
|
|
@@ -34,7 +35,7 @@ import { admitImplementation } from './check-readiness.mjs';
|
|
|
34
35
|
import { parseExecution, parseRequiredCapabilities, admitHostExecution, withEvidence } from './execution.mjs';
|
|
35
36
|
import { loadCapacity } from './projects.mjs';
|
|
36
37
|
import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
|
|
37
|
-
import { beginMcpOutcome, recordMcpResponse, pathShape } from './mcp-outcome.mjs';
|
|
38
|
+
import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
|
|
38
39
|
import { lifecycleMetrics, retainLifecycle } from './lifecycle.mjs';
|
|
39
40
|
import { normalizeMeta } from './objectives.mjs';
|
|
40
41
|
import { createRequestLog } from './request-log.mjs';
|
|
@@ -44,6 +45,8 @@ import { acquireAsOwner, loadAsConfig, loadKeys } from './as-files.mjs';
|
|
|
44
45
|
import { createSignal } from './signal.mjs';
|
|
45
46
|
import { adminSocketPathError } from './admin-socket.mjs';
|
|
46
47
|
import { createToolRegistry, createT3PostHandler, RegistryError } from './tool-registry.mjs';
|
|
48
|
+
import { createServiceVerifier } from '@tnunamak/gozar';
|
|
49
|
+
import { acceptsMcpEventStream, beginMcpEventStream } from './mcp-sse.mjs';
|
|
47
50
|
|
|
48
51
|
export async function main({protocolServiceAdapters,loopbackOnly=false}={}) {
|
|
49
52
|
if(typeof loopbackOnly!=='boolean')throw new Error('loopbackOnly must be boolean');
|
|
@@ -208,7 +211,7 @@ const protocolServices=catalogProfile==='protocol-v0'?createProtocolServices(sto
|
|
|
208
211
|
const iconBytes=fs.readFileSync(new URL('../docs/t3-connector-icon.png',import.meta.url));
|
|
209
212
|
const iconSource=`data:image/png;base64,${iconBytes.toString('base64')}`;
|
|
210
213
|
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.
|
|
214
|
+
const serverInfo={name:catalogProfile==='legacy-v46'?'dot-bridge':'dalan',version:catalogProfile==='legacy-v46'?'0.2.0':'0.6.1',icons:[{src:iconSource,mimeType:'image/png',sizes:['128x128']}]};
|
|
212
215
|
// A quiet-delivery job in profile mode has no T3 thread; its response must not carry the T3 fields. Legacy profile keeps them.
|
|
213
216
|
const withoutT3=response=>{ if(legacyProfile||response.delivery_mode!=='none') return response; const {t3_muted,thread_id,...rest}=response; return rest; };
|
|
214
217
|
function mayPrepareCheckMetadata(response,worker,subject=null) {
|
|
@@ -220,7 +223,15 @@ function mayPrepareCheckMetadata(response,worker,subject=null) {
|
|
|
220
223
|
return response.status==='claimed'&&!response.cancelled_at&&claim?.state==='active'&&claim.worker===target&&
|
|
221
224
|
(subject===null||claim.subject===subject)&&!store.leaseExpired(claim);
|
|
222
225
|
}
|
|
223
|
-
function
|
|
226
|
+
function workerWorkspaceAllowed(worker,requestId=null) { const policy=repoPolicyFor({request_id:requestId});return policy.legacy||policy.workers.get(worker)?.workspaceAllowed===true; }
|
|
227
|
+
function hasWorkspaceFinishEvidence(requestId) {
|
|
228
|
+
return !!store.db.prepare(`SELECT
|
|
229
|
+
EXISTS(SELECT 1 FROM workspaces WHERE request_id=?) OR
|
|
230
|
+
EXISTS(SELECT 1 FROM check_jobs WHERE request_id=?) OR
|
|
231
|
+
EXISTS(SELECT 1 FROM check_runs WHERE request_id=?) OR
|
|
232
|
+
EXISTS(SELECT 1 FROM artifacts WHERE request_id=?) AS present`).get(requestId,requestId,requestId,requestId).present;
|
|
233
|
+
}
|
|
234
|
+
function withAvailableChecks(response,workerSurface=false,worker='dot',subject=null,workspaceAllowed=null) {
|
|
224
235
|
response=withoutT3(response);
|
|
225
236
|
const artifacts=store.sealedUploads(response.request_id,{clientIds:workerSurface});
|
|
226
237
|
// origin_claim_id is a claim capability: worker replies never carry it, and the owner surface keeps it.
|
|
@@ -230,6 +241,15 @@ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=n
|
|
|
230
241
|
const blocker=workerSurface?null:queuedRepositoryBlocker(response);
|
|
231
242
|
const enriched={...response,artifacts,checks,...(blocker?{queue_blocker:blocker}:{}),...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{})};
|
|
232
243
|
if(!workspaceEnabled||response.assignment?.execution_scope!=='implementation') return enriched;
|
|
244
|
+
if(workerSurface&&workspaceAllowed===null) {
|
|
245
|
+
try { workspaceAllowed=workerWorkspaceAllowed(worker,response.request_id); }
|
|
246
|
+
catch(error) {
|
|
247
|
+
// Workspace metadata is optional response enrichment. A damaged current profile
|
|
248
|
+
// must deny workspace preparation without discarding an already-held claim.
|
|
249
|
+
return {...enriched,available_checks:[],available_checks_error:error?.destination?.error??'workspace_policy_unavailable'};
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if(workerSurface&&!workspaceAllowed) return enriched;
|
|
233
253
|
const target=store.db.prepare('SELECT target_worker FROM assignments WHERE request_id=?').get(response.request_id)?.target_worker??worker;
|
|
234
254
|
if(!mayPrepareCheckMetadata(response,target,subject)) return {...enriched,available_checks:[],available_checks_error:'repository_policy_denied'};
|
|
235
255
|
const execution=response.execution??store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(response.request_id).execution;
|
|
@@ -280,8 +300,10 @@ function publicWorkerGet(response) {
|
|
|
280
300
|
function crashAt(point, requestId) { return readEnv('DALAN_CRASH_AT')===point && (!readEnv('DALAN_CRASH_REQUEST_ID') || readEnv('DALAN_CRASH_REQUEST_ID')===requestId); }
|
|
281
301
|
const T3_READ_TOOLS_OFF={off:true,message:'T3 thread tools are off; the needed context is inlined in your assignment.'};
|
|
282
302
|
// 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);
|
|
303
|
+
function json(res, status, value, eventStream = null) { 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]) };
|
|
304
|
+
const body = JSON.stringify(value), bytes = Buffer.byteLength(body);
|
|
305
|
+
if(eventStream) { eventStream.finish(body,streamBytes=>recordMcpResponse(res,value,streamBytes)); return; }
|
|
306
|
+
recordMcpResponse(res,value,bytes); res.writeHead(status, { 'content-type': 'application/json', 'content-length': bytes }); res.end(body); }
|
|
285
307
|
async function readBody(req, outcome) {
|
|
286
308
|
const chunks = []; let size = 0;
|
|
287
309
|
for await (const chunk of req) {
|
|
@@ -310,6 +332,7 @@ const short={type:'string',maxLength:512};
|
|
|
310
332
|
const hashField={type:'string',maxLength:128},keyField={type:'string',minLength:1,maxLength:128};
|
|
311
333
|
const message={type:'string',maxLength:262144};
|
|
312
334
|
const bool={type:'boolean'};
|
|
335
|
+
const maxT3WaitMs=catalogProfile==='legacy-v46'?120000:90000;
|
|
313
336
|
const optionsArray={type:'array',items:string,maxItems:16};
|
|
314
337
|
const tools = [
|
|
315
338
|
{ name:'list_pending',description:'List up to 50 queued assignment IDs and titles.',inputSchema:schema({}) },
|
|
@@ -330,7 +353,7 @@ const tools = [
|
|
|
330
353
|
{ 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
354
|
{ 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
355
|
{ 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:
|
|
356
|
+
{ name:'t3_thread_wait',description:catalogProfile==='legacy-v46'?'Wait at most 120 seconds for a T3 turn; returns partial state on timeout.':'Wait at most 90 seconds for a T3 turn; returns partial state on timeout.',inputSchema:schema({threadId,timeoutMs:{type:'integer',minimum:1,maximum:maxT3WaitMs},detail:{type:'string',enum:['answers','messages','full']},maxChars:{type:'integer',minimum:1,maximum:20000}},['threadId']) },
|
|
334
357
|
{ 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
358
|
{ 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
359
|
{ 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({}) },
|
|
@@ -550,7 +573,14 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
|
|
|
550
573
|
if(waiters.get(requestId)!==waiter) return;
|
|
551
574
|
waiters.delete(requestId);
|
|
552
575
|
let blocker=null;
|
|
553
|
-
try {
|
|
576
|
+
try {
|
|
577
|
+
const row=store.get(requestId);
|
|
578
|
+
if(['finished','cancelled'].includes(row.status)) {
|
|
579
|
+
store.recordFetched(requestId);if(consume)store.recordConsumed(requestId,'wait');
|
|
580
|
+
return json(res,200,waitSummary(requestId));
|
|
581
|
+
}
|
|
582
|
+
blocker=queuedRepositoryBlocker(row);
|
|
583
|
+
} catch { /* the request may have expired while waiting */ }
|
|
554
584
|
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
585
|
},timeoutMs);
|
|
556
586
|
waiter.timer.unref();
|
|
@@ -575,7 +605,7 @@ function holdsLiveGrant(worker,requestId,claimant,subject,acquisitionId) {
|
|
|
575
605
|
return held?.worker===worker&&store.isExactClaimRetry(held,claimant,subject,acquisitionId??null);
|
|
576
606
|
}
|
|
577
607
|
function queuedRepositoryBlocker(row) {
|
|
578
|
-
if(row.status!=='queued') return null;
|
|
608
|
+
if(row.status!=='queued'||row.work_order_id&&!row.target_worker) return null;
|
|
579
609
|
const repo=row.assignment?.inputs?.find(input=>input?.github_repo!==undefined)?.github_repo;
|
|
580
610
|
if(!repo) return null;
|
|
581
611
|
const worker=row.target_worker??'dot';
|
|
@@ -596,8 +626,61 @@ function assertRepoAllowed(worker,assignment) {
|
|
|
596
626
|
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
627
|
}
|
|
598
628
|
}
|
|
629
|
+
function admitPolicyWorker(worker,assignment,execution,approvedRevision) {
|
|
630
|
+
assertTarget(repoPolicyFor(assignment),worker);
|
|
631
|
+
assertRepoAllowed(worker,assignment);
|
|
632
|
+
const snapshot=store.destinationSnapshot(worker,execution,assignment);
|
|
633
|
+
if((snapshot?.revision??null)!==(approvedRevision??null)||snapshot&&!snapshot.policy.allowed||snapshot?.connections_digest==='sha256:'+createHash('sha256').update('[]').digest('hex')) throw new Error('policy destination approval changed or unavailable');
|
|
634
|
+
}
|
|
635
|
+
const policyPage=(worker,cursor=null)=>store.pullQueue.list(worker,admitPolicyWorker,cursor);
|
|
636
|
+
async function submitPolicy(body,req,dryRun) {
|
|
637
|
+
if(req.method!=='POST')throw new Error('policy submit requires POST');
|
|
638
|
+
if(body.background!==undefined&&typeof body.background!=='boolean'||body.review!==undefined&&typeof body.review!=='boolean'||body.allow_main!==undefined&&typeof body.allow_main!=='boolean')throw new Error('invalid policy submit flags');
|
|
639
|
+
if(body.worker!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.required_capabilities!==undefined||body.max_queued!==undefined||body.defer_queued!==undefined||body.destination_revision!==undefined) throw new Error('routing v1 cannot combine single-target, command, supersede or capacity options');
|
|
640
|
+
if(!body.assignment||typeof body.assignment!=='object'||Array.isArray(body.assignment)||typeof body.assignment.request_id!=='string'||!/^[-\w]{8,128}$/.test(body.assignment.request_id)||body.assignment.request_id.startsWith(PULL_PAGE_PREFIX)) throw new Error('invalid assignment request_id');
|
|
641
|
+
if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment inputs');
|
|
642
|
+
if(body.assignment.schema_version!==1||typeof body.assignment.brief!=='string'||!body.assignment.brief.trim()||typeof body.assignment.expected_output!=='string'||typeof body.assignment.execution_scope!=='string')throw new Error('invalid assignment: needs schema_version 1, brief, inputs, expected_output and execution_scope');
|
|
643
|
+
const identity=renderAssignment(body.assignment),routing=routingPolicy(body.routing,identity),owner=str(body.owner_token,'owner_token',128);
|
|
644
|
+
const old=store.pullQueue.row(identity.request_id),oldOptions=old?JSON.parse(old.options):null;
|
|
645
|
+
const execution=body.execution===undefined?oldOptions?.execution??workers.defaultExecution:parseExecution(body.execution);
|
|
646
|
+
if(execution==='host')throw new Error('routing v1 supports execution none or worker only');
|
|
647
|
+
const delivery=parseDelivery(body.delivery??'none'),destination=await destinations.for(delivery);
|
|
648
|
+
if(body.allow_main===true)adminOperator(req);
|
|
649
|
+
destination.admit(delivery,{allowMain:body.allow_main===true});
|
|
650
|
+
if(delivery.mode==='t3'&&!legacyProfile&&!(await (await import('./t3.mjs')).t3Available()))throw new Error('delivery t3 needs T3 Code on the bridge host');
|
|
651
|
+
const meta=normalizeMeta(body.meta),priority=body.background===true?'background':'normal';
|
|
652
|
+
for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,meta.source??'agent');
|
|
653
|
+
if(!old) { const refused=unprovenSource({request_id:identity.request_id,payload:identity,meta},priority);if(refused)throw new Error(refused); }
|
|
654
|
+
const approvals=body.destination_revisions??{};
|
|
655
|
+
if(!approvals||typeof approvals!=='object'||Array.isArray(approvals)||Object.keys(approvals).some(worker=>!routing.allowed_workers.includes(worker)))throw new Error('invalid destination_revisions');
|
|
656
|
+
const options={delivery,environmentId:oldOptions?.environmentId??'',execution,review:body.review===true,priority,meta};
|
|
657
|
+
if(old)return store.pullQueue.submit(JSON.parse(old.payload),identity,options,routing,approvals,owner,{dryRun});
|
|
658
|
+
let payload=identity,preflight=null;
|
|
659
|
+
// Validate scope under each candidate's current repository policy. No candidate
|
|
660
|
+
// is allowed to learn the title or brief before its exact approval is bound.
|
|
661
|
+
const disclosures={};
|
|
662
|
+
for(const worker of routing.allowed_workers) {
|
|
663
|
+
assertTarget(currentRepoPolicy(),worker);assertRepoAllowed(worker,payload);
|
|
664
|
+
payload=await validateSubmissionAsync(identity,{worker,review:body.review===true,warnings:[],excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null});
|
|
665
|
+
assertRepoAllowed(worker,payload);
|
|
666
|
+
disclosures[worker]=store.destinationSnapshot(worker,execution,payload);
|
|
667
|
+
if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
|
|
668
|
+
}
|
|
669
|
+
preflight=await preflightPR(payload);
|
|
670
|
+
options.environmentId=(await destination.validate(delivery)).environmentId??'';
|
|
671
|
+
for(const worker of routing.allowed_workers)if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
|
|
672
|
+
if(dryRun)return {...store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun:true}),destination_disclosures:disclosures};
|
|
673
|
+
// Synchronous checks immediately precede the transaction; acquisition repeats
|
|
674
|
+
// them in its write transaction after its own async preflight.
|
|
675
|
+
const result=store.pullQueue.submit(payload,identity,options,routing,approvals,owner);
|
|
676
|
+
log({kind:'policy_work_submitted',request_id:identity.request_id,work_order_id:result.work_order_id});
|
|
677
|
+
return {...result,execution};
|
|
678
|
+
}
|
|
679
|
+
|
|
599
680
|
// 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
681
|
async function tool(name,a,principal,notifyMeta) {
|
|
682
|
+
if(!toolNames.has(name)) throw new Error('unknown tool');
|
|
683
|
+
// Refuse hidden names before audits, lease touches, sweeps or repository preparation.
|
|
601
684
|
if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
|
|
602
685
|
!holdsLiveGrant(principal.worker,a.request_id,a.claimant,principal.subject,a.acquisition_id)) {
|
|
603
686
|
assertRepoAllowed(principal.worker,store.get(a.request_id).assignment);
|
|
@@ -643,7 +726,8 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
643
726
|
log({kind:'t3_read_tool_blocked',tool:name,subject:principal.subject,call_id:audit.call_id});
|
|
644
727
|
return T3_READ_TOOLS_OFF;
|
|
645
728
|
}
|
|
646
|
-
const
|
|
729
|
+
const t3Arguments=name==='t3_thread_wait'?{...a,timeoutMs:Math.min(a.timeoutMs??90_000,90_000)}:a;
|
|
730
|
+
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,t3Arguments);
|
|
647
731
|
t3Audit.appendT3Audit(store.db,audit,principal.subject,'success',result);
|
|
648
732
|
if(result && typeof result==='object' && Object.hasOwn(result,'_audit_ids')) { const {_audit_ids,...publicResult}=result; return publicResult; }
|
|
649
733
|
return result;
|
|
@@ -653,6 +737,22 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
653
737
|
}
|
|
654
738
|
}
|
|
655
739
|
const worker=principal.worker;
|
|
740
|
+
const policyRow=typeof a?.request_id==='string'?store.pullQueue.row(a.request_id):null;
|
|
741
|
+
const isPolicyPage=name==='get'&&typeof a?.request_id==='string'&&a.request_id.startsWith(PULL_PAGE_PREFIX);
|
|
742
|
+
const isPolicyClaim=policyRow&&name==='claim'&&(!policyRow.child_request_id||a.acquisition_id===policyRow.acquisition_id);
|
|
743
|
+
const isPolicyGet=policyRow&&name==='get'&&!store.hasAssignment(a.request_id);
|
|
744
|
+
if(isPolicyPage||isPolicyClaim||isPolicyGet) {
|
|
745
|
+
validate(name,a);if(oauth)needScope(principal,scopeFor(name));
|
|
746
|
+
if(name==='get')return a.request_id.startsWith(PULL_PAGE_PREFIX)?{policy_work:policyPage(worker,a.request_id)}:store.pullQueue.get(a.request_id,worker,admitPolicyWorker);
|
|
747
|
+
const offered=policyRow.child_request_id?null:store.pullQueue.get(a.request_id,worker,admitPolicyWorker);
|
|
748
|
+
const preflight=offered?await preflightPR(offered.assignment):null;
|
|
749
|
+
const workspaceAllowed=workspaceEnabled&&offered?.assignment?.execution_scope==='implementation'
|
|
750
|
+
?workerWorkspaceAllowed(worker,a.request_id):false;
|
|
751
|
+
const claimed=store.pullQueue.acquire(a.request_id,{worker,subject:principal.subject,connectionId:principal.builtin?(principal.connection_id??''):null,
|
|
752
|
+
claimant:str(a.claimant,'claimant',128),acquisitionId:a.acquisition_id,leaseMs:a.lease_ms,capacity:claimCapacity,preflight,admit:admitPolicyWorker});
|
|
753
|
+
const {free_lanes,queued}=store.laneState(principal.subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
754
|
+
return withAvailableChecks(nonterminalOutcome(claimed.request_id,{...claimed,free_lanes,queued_after_claim:queued}),true,worker,principal.subject,workspaceAllowed);
|
|
755
|
+
}
|
|
656
756
|
if(a&&typeof a==='object') {
|
|
657
757
|
if(typeof a.request_id==='string'&&!store.mayAct(worker,a.request_id)) a={...a,request_id:absentId};
|
|
658
758
|
if(typeof a.message_id==='string'&&!store.mayAct(worker,a.message_id)) a={...a,message_id:absentId};
|
|
@@ -661,7 +761,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
661
761
|
a=repaired.args;
|
|
662
762
|
validate(name,a);
|
|
663
763
|
if(oauth) needScope(principal,scopeFor(name));
|
|
664
|
-
if(disabled.has(name)&&!workspaceEnabled) throw new Error('capability_not_enabled');
|
|
764
|
+
if(disabled.has(name)&&!(workspaceEnabled&&workerWorkspaceAllowed(worker,a?.request_id))) throw new Error('capability_not_enabled');
|
|
665
765
|
if(a.request_id===absentId&&disabled.has(name)) throw new Error('assignment not found');
|
|
666
766
|
const subject=principal.subject,connectionId=principal.builtin?(principal.connection_id??''):null;
|
|
667
767
|
const strictJob=typeof a.request_id==='string'&&store.isProtocolJob(a.request_id);
|
|
@@ -697,18 +797,26 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
697
797
|
const claims_accepted=!store.paused();
|
|
698
798
|
const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
|
|
699
799
|
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};
|
|
800
|
+
return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,claims_accepted,...(claims_accepted?next:{next_action:claimsNote}),guidance};
|
|
701
801
|
}
|
|
702
802
|
case 'claim': {
|
|
703
803
|
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
804
|
if(!retry)assertRepoAllowed(worker,row.assignment);
|
|
805
|
+
const needsWorkspace=workspaceEnabled&&(row.assignment.execution_scope==='implementation'||row.assignment.output_paths?.length);
|
|
806
|
+
let workspaceAllowed=null;
|
|
705
807
|
store.refuseExpired(requestId);
|
|
706
808
|
// Retry a successful claim without a new remote dependency, and skip it for a live rival claim that the Store will refuse.
|
|
707
809
|
// A fresh claim, a claim after abandon and an expired-lease takeover are each a new admission. The Store
|
|
708
810
|
// still validates claimant, subject, lease, cancellation and capacity atomically.
|
|
709
811
|
const admission=!store.paused()&&(row.status==='queued'||row.status==='claimed'&&held&&!(held.claimant===claimant&&held.subject===subject)&&store.leaseExpired(held));
|
|
710
812
|
const preflight=admission?await preflightPR(row.assignment):null;
|
|
711
|
-
if(!retry)
|
|
813
|
+
if(!retry) {
|
|
814
|
+
assertRepoAllowed(worker,row.assignment);
|
|
815
|
+
// Resolve an optional workspace grant after remote preflight but before claim acquisition. A broken
|
|
816
|
+
// profile cannot leave a live claim behind when response enrichment fails, and an exact retry does
|
|
817
|
+
// not depend on the current profile because it adds no workspace authority.
|
|
818
|
+
if(needsWorkspace) workspaceAllowed=workerWorkspaceAllowed(worker,requestId);
|
|
819
|
+
}
|
|
712
820
|
const prior=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
|
|
713
821
|
if(prior&&store.leaseExpired(prior)&&(!strictJob||store.protocolRevision(requestId)===ctx.revision)) await workspace?.quiesce(requestId);
|
|
714
822
|
// Store revalidates after the await: a concurrent claimant may have won.
|
|
@@ -719,7 +827,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
719
827
|
const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null);
|
|
720
828
|
const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
|
|
721
829
|
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);
|
|
830
|
+
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,workspaceAllowed);
|
|
723
831
|
}
|
|
724
832
|
case 'renew_claim': {
|
|
725
833
|
if(!strictJob) throw new Error('renew_claim requires a protocol job');
|
|
@@ -747,13 +855,26 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
747
855
|
let captureEvidence=null;
|
|
748
856
|
if(!existing) {
|
|
749
857
|
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
858
|
const request=store.get(requestId);
|
|
752
|
-
|
|
859
|
+
const needsWorkspace=workspaceEnabled&&(a.artifact_ids?.length||request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length);
|
|
860
|
+
const assignmentNeedsWorkspace=request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length;
|
|
861
|
+
const requiredWorkspaceEvidence=!!(a.artifact_ids?.length||request.assignment.output_paths?.length);
|
|
862
|
+
let workerWorkspaceEnabled=false;
|
|
863
|
+
if(needsWorkspace) {
|
|
864
|
+
try { workerWorkspaceEnabled=workerWorkspaceAllowed(worker,requestId); }
|
|
865
|
+
catch(error) {
|
|
866
|
+
if(error.destination?.error!=='destination_configuration_invalid') throw error;
|
|
867
|
+
if(requiredWorkspaceEvidence||assignmentNeedsWorkspace&&hasWorkspaceFinishEvidence(requestId)) throw error;
|
|
868
|
+
// A failed optional policy read may fall back only when finish has no workspace state, checks,
|
|
869
|
+
// artifacts, output paths, or explicitly requested artifacts. Store.finish still enforces the claim.
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
if(a.artifact_ids?.length) { if(!workerWorkspaceEnabled) throw new Error('capability_not_enabled'); store.assertSealedArtifacts(requestId,claimId,a.artifact_ids); }
|
|
873
|
+
if(workerWorkspaceEnabled) await workspace.makeRoom(requestId);
|
|
753
874
|
// Recheck after the last await. The evidence capture below runs inside the finish transaction, after finishOnce's own
|
|
754
875
|
// connection check, so a patch artifact is never committed for a holder that lost the connection.
|
|
755
876
|
workspaceFence();
|
|
756
|
-
if(
|
|
877
|
+
if(workerWorkspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
|
|
757
878
|
captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
|
|
758
879
|
if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
|
|
759
880
|
const archiveWorkspace=workspace??new Workspace(store,false),snapshot=captureEvidence;
|
|
@@ -815,7 +936,9 @@ async function dispatch(message,principal) {
|
|
|
815
936
|
case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
|
|
816
937
|
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
938
|
case 'ping': return {};
|
|
818
|
-
|
|
939
|
+
// Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
|
|
940
|
+
// legacy-v46 keeps its pinned per-worker surface for compatibility.
|
|
941
|
+
case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):tools};
|
|
819
942
|
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
943
|
case 'events/list': return {events:[event]};
|
|
821
944
|
case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
|
|
@@ -823,18 +946,20 @@ async function dispatch(message,principal) {
|
|
|
823
946
|
default: throw Object.assign(new Error('method not found'),{code:-32601});
|
|
824
947
|
}
|
|
825
948
|
}
|
|
949
|
+
const verifyService=builtinMode&&readEnv('DALAN_GOZAR_SERVICE')==='1'?createServiceVerifier():null;
|
|
826
950
|
const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)=>{
|
|
827
951
|
const outcome=req.url===publicPath?beginMcpOutcome(req,res,log,toolNames,!!oauth):null;
|
|
828
952
|
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
|
-
//
|
|
831
|
-
if(as
|
|
953
|
+
if(loopback && !loopbackRequestAllowed(req, `http://127.0.0.1:${port}`)) { log({kind:'mcp_inbound',status:403,route:'loopback',ua:uaToken(req)}); res.writeHead(403); res.end(); return; }
|
|
954
|
+
// Both authentication modes serve only the configured public Host, including discovery and verifier routes.
|
|
955
|
+
if(as ? !as.hostOk(req) : oauth&&req.headers.host!==new URL(oauth.OAUTH_AUDIENCE).host) { log({kind:'mcp_inbound',status:421,route:'host',ua:uaToken(req)}); res.writeHead(421); res.end(); return; }
|
|
956
|
+
if(verifyService?.(req,res)) return;
|
|
832
957
|
if(!as && req.url==='/.well-known/oauth-protected-resource' && oauthMetadata && req.method==='GET') return json(res,200,protectedResource(oauthMetadata));
|
|
833
958
|
// 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)); }
|
|
959
|
+
if(req.url===`/.well-known/oauth-protected-resource${publicPath}` && oauthMetadata && req.method==='GET') { if(as)res.setHeader('Cache-Control','no-store'); log({kind:'mcp_inbound',status:200,route:'resource_metadata',http_method:req.method,auth_header_present:false,ua:uaToken(req)}); return json(res,200,protectedResource(oauthMetadata,new URL(publicPath,oauthMetadata.OAUTH_AUDIENCE).href)); }
|
|
835
960
|
if(signal&&signal.handle(req,res)) return;
|
|
836
961
|
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; }
|
|
962
|
+
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 '),ua:uaToken(req)}); res.writeHead(404); res.end(); return; }
|
|
838
963
|
let principal={local:true,subject:'local-principal',scopes:new Set(ADVERTISED_SCOPES)};
|
|
839
964
|
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
965
|
try { principal.worker=resolveWorker(workers,principal); } catch(error) {
|
|
@@ -850,11 +975,12 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
|
|
|
850
975
|
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
976
|
outcome.identify(rpc);
|
|
852
977
|
// 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});
|
|
978
|
+
log({kind:'mcp_inbound',call_id:outcome.state.call_id,rpc_method:outcome.state.rpc_method,tool:outcome.state.tool,ua:uaToken(req)});
|
|
854
979
|
if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
|
|
855
980
|
outcome.state.phase='dispatch';
|
|
856
|
-
|
|
857
|
-
|
|
981
|
+
const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
|
|
982
|
+
try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal)}},eventStream); }
|
|
983
|
+
catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
|
|
858
984
|
// Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
|
|
859
985
|
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
986
|
} 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'))); }
|
|
@@ -872,7 +998,9 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
872
998
|
dryRequested=url.pathname==='/submit-preview';
|
|
873
999
|
log({kind:'admin_call',route:url.pathname,method:req.method});
|
|
874
1000
|
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');
|
|
1001
|
+
if((url.pathname==='/submit'||url.pathname==='/submit-preview')&&body.routing!==undefined) return json(res,200,await submitPolicy(body,req,url.pathname==='/submit-preview'));
|
|
875
1002
|
if(url.pathname==='/submit'||url.pathname==='/submit-preview') {
|
|
1003
|
+
if(typeof body.assignment?.request_id==='string'&&store.pullQueue.row(body.assignment.request_id))throw new Error('request_id reserved for policy work; retry with routing');
|
|
876
1004
|
// Set before any check below, so every refusal carries typed reasons, answers a dry run with a verdict and is logged.
|
|
877
1005
|
// Cohort labels can contain private values; logs need equality, not their contents.
|
|
878
1006
|
const labelDigest=value=>typeof value==='string'&&value.trim()?createHash('sha256').update(value.trim()).digest('hex'):null;
|
|
@@ -996,10 +1124,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
996
1124
|
if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
|
|
997
1125
|
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
1126
|
}
|
|
999
|
-
if(url.pathname==='/admission'&&req.method==='GET') { const row=store.db.prepare('SELECT cancelled_reason FROM assignments WHERE request_id=?').get(
|
|
1127
|
+
if(url.pathname==='/admission'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));const row=store.db.prepare('SELECT cancelled_reason FROM assignments WHERE request_id=?').get(requestId)??store.pullQueue.row(requestId); return json(res,200,{exists:!!row,...(row?.cancelled_reason==='expired'?{cancelled_reason:'expired'}:{})}); }
|
|
1000
1128
|
if(url.pathname==='/get') {
|
|
1001
1129
|
const requestId=id(url.searchParams.get('id'));
|
|
1002
|
-
if(!store.hasAssignment(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
|
|
1130
|
+
if(!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
|
|
1003
1131
|
adminOwner(req,requestId);
|
|
1004
1132
|
store.assertProtocolAvailable(requestId);
|
|
1005
1133
|
store.recordFetched(requestId);
|
|
@@ -1045,7 +1173,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1045
1173
|
const states=body.items.map(item=>{
|
|
1046
1174
|
const requestId=id(item?.id);
|
|
1047
1175
|
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);
|
|
1176
|
+
const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)??(store.pullQueue.row(requestId)?store.get(requestId):null);
|
|
1049
1177
|
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
1178
|
return {request_id:requestId,status:row.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
|
|
1051
1179
|
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// Import policy into a NEW home. Source loaders are read-only: no jobs, connections or keys carry over.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import { loadEffectiveOwnerWorkers, parseWorkers, updateWorkerRepoPolicy, workerRepoMigrationFile } from './workers.mjs';
|
|
6
|
+
|
|
7
|
+
function reenrollmentIntent(files, workers) {
|
|
8
|
+
const subscriptions = [], destinationApprovals = [];
|
|
9
|
+
for (const file of files) {
|
|
10
|
+
const db = new DatabaseSync(path.resolve(file), { readOnly: true });
|
|
11
|
+
try {
|
|
12
|
+
const hasTable = name => !!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name);
|
|
13
|
+
if (hasTable('subscriptions')) {
|
|
14
|
+
// Never select encrypted connection/secret columns. Callback paths and queries can also contain credentials.
|
|
15
|
+
const hasExpiry = db.prepare("SELECT 1 FROM pragma_table_info('subscriptions') WHERE name='expires_at'").get();
|
|
16
|
+
const rows = hasExpiry
|
|
17
|
+
? db.prepare("SELECT worker,url,count(*) count FROM subscriptions WHERE state='active' AND expires_at>? GROUP BY worker,url").all(new Date().toISOString())
|
|
18
|
+
: db.prepare("SELECT worker,url,count(*) count FROM subscriptions WHERE state='active' GROUP BY worker,url").all();
|
|
19
|
+
for (const row of rows) {
|
|
20
|
+
if (!Object.hasOwn(workers, row.worker)) throw new Error(`subscription refers to unknown worker ${row.worker}`);
|
|
21
|
+
let callbackOrigin = null;
|
|
22
|
+
try { const url = new URL(row.url); if (['https:', 'http:'].includes(url.protocol)) callbackOrigin = url.origin; } catch { /* manual re-enrolment required */ }
|
|
23
|
+
const old = subscriptions.find(item => item.worker === row.worker && item.callback_origin === callbackOrigin);
|
|
24
|
+
if (old) old.count += Number(row.count);
|
|
25
|
+
else subscriptions.push({ worker: row.worker, callback_origin: callbackOrigin, count: Number(row.count), action: 'reconnect_then_events_subscribe' });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (hasTable('destination_approvals')) {
|
|
29
|
+
for (const row of db.prepare("SELECT json_extract(snapshot,'$.worker') worker,count(*) count FROM destination_approvals GROUP BY json_extract(snapshot,'$.worker')").all()) {
|
|
30
|
+
if (!Object.hasOwn(workers, row.worker)) throw new Error(`destination approval refers to unknown worker ${row.worker}`);
|
|
31
|
+
const old = destinationApprovals.find(item => item.worker === row.worker);
|
|
32
|
+
if (old) old.count += Number(row.count);
|
|
33
|
+
else destinationApprovals.push({ worker: row.worker, count: Number(row.count), action: 'review_new_destination_revision_on_each_new_job' });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
} finally { db.close(); }
|
|
37
|
+
}
|
|
38
|
+
return { subscriptions, destination_approvals: destinationApprovals };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function migrateWorkers({ home, sources, sourceDbs = [], workspaceWorkers = [] }) {
|
|
42
|
+
if (!home || !Array.isArray(sources) || !sources.length) throw new Error('--home and at least one --source workers.json are required');
|
|
43
|
+
if (!Array.isArray(sourceDbs) || !Array.isArray(workspaceWorkers)) throw new Error('sourceDbs and workspaceWorkers must be arrays');
|
|
44
|
+
home = path.resolve(home);
|
|
45
|
+
const workers = {};
|
|
46
|
+
const grants = new Map();
|
|
47
|
+
const deniedRepositories = [];
|
|
48
|
+
for (const source of sources) {
|
|
49
|
+
const file = path.resolve(source);
|
|
50
|
+
if (!fs.existsSync(file) && !fs.existsSync(workerRepoMigrationFile(file))) throw new Error(`no worker policy at ${file}`);
|
|
51
|
+
const profile = loadEffectiveOwnerWorkers(file);
|
|
52
|
+
deniedRepositories.push(...profile.deniedRepoGrants.map(item => ({ source: file, ...item })));
|
|
53
|
+
for (const [name, worker] of profile.workers) {
|
|
54
|
+
if (Object.hasOwn(workers, name)) throw new Error(`duplicate worker ${name} in sources`);
|
|
55
|
+
workers[name] = {
|
|
56
|
+
repos: [],
|
|
57
|
+
workspaceAllowed: worker.workspaceAllowed === true || workspaceWorkers.includes(name),
|
|
58
|
+
...(worker.capabilities.size ? { capabilities: [...worker.capabilities] } : {}),
|
|
59
|
+
...(worker.guidance ? { guidance: worker.guidance } : {}),
|
|
60
|
+
...(worker.destination ? { destination: worker.destination } : {}),
|
|
61
|
+
};
|
|
62
|
+
grants.set(name, profile.repoPolicy(name).repos);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
for (const name of workspaceWorkers) if (!Object.hasOwn(workers, name)) throw new Error(`unknown workspace worker ${name}`);
|
|
66
|
+
const value = { workers, default_execution: 'none' };
|
|
67
|
+
parseWorkers(value, { builtin: true });
|
|
68
|
+
const intent = reenrollmentIntent(sourceDbs, workers);
|
|
69
|
+
const manifest = {
|
|
70
|
+
schema_version: 1, authoritative: false, ...intent,
|
|
71
|
+
required_actions: [
|
|
72
|
+
'Pair and approve every connector in the new home; old connections and tokens are not valid here.',
|
|
73
|
+
'Each connector must call events/subscribe again with its callback and a fresh signing key; callback paths and credentials were omitted.',
|
|
74
|
+
'Review the new destination disclosure and approve its current destination_revision when submitting each new job; old approvals bind old jobs and connections.',
|
|
75
|
+
],
|
|
76
|
+
};
|
|
77
|
+
// mkdir without recursive fails for any existing destination, including symlinks and empty homes.
|
|
78
|
+
fs.mkdirSync(path.dirname(home), { recursive: true, mode: 0o700 });
|
|
79
|
+
fs.mkdirSync(home, { mode: 0o700 });
|
|
80
|
+
const config = path.join(home, '.config/dalan');
|
|
81
|
+
const workersFile = path.join(config, 'workers.json');
|
|
82
|
+
const manifestFile = path.join(config, 'service-migration.json');
|
|
83
|
+
try {
|
|
84
|
+
fs.mkdirSync(config, { recursive: true, mode: 0o700 });
|
|
85
|
+
fs.writeFileSync(workersFile, JSON.stringify(value, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
86
|
+
for (const [name, repos] of grants) for (const repo of repos) updateWorkerRepoPolicy(workersFile, name, 'allow', repo);
|
|
87
|
+
fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
88
|
+
} catch (error) {
|
|
89
|
+
fs.rmSync(home, { recursive: true, force: true });
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
return { home, workers_file: workersFile, migration_manifest: manifestFile,
|
|
93
|
+
workers: [...grants].map(([worker, repos]) => ({ worker, repos, workspaceAllowed: workers[worker].workspaceAllowed })),
|
|
94
|
+
default_execution: 'none', reenrollment_required: true, denied_repositories: deniedRepositories };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function migrationMain(args = process.argv.slice(4)) {
|
|
98
|
+
let home;
|
|
99
|
+
let json = false;
|
|
100
|
+
const sources = [], sourceDbs = [], workspaceWorkers = [];
|
|
101
|
+
for (let i = 0; i < args.length; i++) {
|
|
102
|
+
if (args[i] === '--json') { json = true; continue; }
|
|
103
|
+
if (!['--home', '--source', '--source-db', '--workspace-worker'].includes(args[i]) || !args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`invalid migration option ${args[i]}`);
|
|
104
|
+
const option = args[i++];
|
|
105
|
+
if (option === '--home') { if (home) throw new Error('duplicate --home'); home = args[i]; }
|
|
106
|
+
else if (option === '--source') sources.push(args[i]);
|
|
107
|
+
else if (option === '--source-db') sourceDbs.push(args[i]);
|
|
108
|
+
else workspaceWorkers.push(args[i]);
|
|
109
|
+
}
|
|
110
|
+
const result = migrateWorkers({ home, sources, sourceDbs, workspaceWorkers });
|
|
111
|
+
process.stdout.write(json ? JSON.stringify(result) + '\n' : `Created ${result.workers.length} workers in ${result.home}; execution defaults to none. Re-enrol connectors, subscriptions and destination approvals using ${result.migration_manifest}. No sign-ins or jobs were copied.${result.denied_repositories.length ? ` Denied unaudited additions: ${result.denied_repositories.map(item => `${item.worker}: ${item.repos.join(', ')}`).join('; ')}.` : ''}\n`);
|
|
112
|
+
return result;
|
|
113
|
+
}
|