@tnunamak/dalan 0.7.0 → 0.8.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 +42 -0
- package/CONTRIBUTING.md +4 -0
- package/PROTOCOL.md +8 -0
- package/README.md +68 -28
- package/bin/dalan.mjs +1 -1
- package/bin/dot-worker.mjs +115 -16
- package/contracts/adapter-qualification.schema.json +170 -0
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/local-agent-requester.md +46 -0
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +4 -3
- package/docs/pull-workers.md +1 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +40 -17
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +2 -0
- package/docs/t3-question-relationship.md +43 -0
- package/docs/t3-reverse-control.md +12 -8
- package/docs/t3-wake-fence-r4.md +42 -0
- package/docs/test-suite-isolation.md +205 -0
- package/docs/usage.md +14 -2
- package/docs/worker-clients.md +3 -1
- package/package.json +6 -3
- package/qualification/README.md +13 -0
- package/qualification/mcp.json +121 -0
- package/qualification/protocol-v0.json +127 -0
- package/src/admin-socket.mjs +2 -1
- package/src/answer-journal.mjs +200 -0
- package/src/auth-check.mjs +8 -2
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +19 -10
- package/src/destinations/index.mjs +6 -0
- package/src/destinations/none.mjs +3 -0
- package/src/destinations/t3.mjs +63 -6
- package/src/execution.mjs +20 -2
- package/src/follow-current.mjs +4 -2
- package/src/gozar-routes.mjs +4 -3
- package/src/host-budget.mjs +17 -11
- package/src/host-execution-policy.mjs +2 -2
- package/src/host-stop-reverify.mjs +6 -4
- package/src/inbox.mjs +13 -3
- package/src/integrator.mjs +3 -1
- package/src/lifecycle.mjs +60 -2
- package/src/patch-apply.mjs +74 -13
- package/src/server.mjs +210 -34
- package/src/service-launchd.mjs +28 -8
- package/src/service-migrate-workers.mjs +12 -2
- package/src/service.mjs +52 -16
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +300 -34
- package/src/submission-policy.mjs +8 -4
- package/src/t3.mjs +21 -2
- package/src/tool-registry.mjs +54 -8
- package/src/workers.mjs +22 -3
- package/src/workspace.mjs +94 -15
package/src/server.mjs
CHANGED
|
@@ -14,8 +14,8 @@ import fs from 'node:fs';
|
|
|
14
14
|
import path from 'node:path';
|
|
15
15
|
import os from 'node:os';
|
|
16
16
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
17
|
-
import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
|
|
18
|
-
import { Store, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
|
|
17
|
+
import { loadWorkers, loadEffectiveOwnerWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget, ensureWorkerRelationship } from './workers.mjs';
|
|
18
|
+
import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
|
|
19
19
|
import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
|
|
20
20
|
import { sendWebhook, validSecret } from './webhooks.mjs';
|
|
21
21
|
import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
|
|
@@ -34,11 +34,11 @@ import { compileWorkOrder, reasonsFromError, strongest } from './work-order.mjs'
|
|
|
34
34
|
import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
|
|
35
35
|
import { preflightPR } from './pr-preflight.mjs';
|
|
36
36
|
import { admitImplementation } from './check-readiness.mjs';
|
|
37
|
-
import { parseExecution, parseRequiredCapabilities, admitHostExecution, withEvidence } from './execution.mjs';
|
|
37
|
+
import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
|
|
38
38
|
import { loadCapacity } from './projects.mjs';
|
|
39
39
|
import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
|
|
40
40
|
import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
|
|
41
|
-
import { lifecycleMetrics, retainLifecycle } from './lifecycle.mjs';
|
|
41
|
+
import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
|
|
42
42
|
import { normalizeMeta } from './objectives.mjs';
|
|
43
43
|
import { createRequestLog } from './request-log.mjs';
|
|
44
44
|
import { logShutdownSignals } from './shutdown-signal.mjs';
|
|
@@ -148,6 +148,9 @@ const store = new Store(path.join(dataDir, 'bridge.db'),{
|
|
|
148
148
|
// Intentional service startup opts past Store's accidental-migration footgun guard.
|
|
149
149
|
deferSubscriptionRetirement:true,markProfileModeSeen:!legacyProfile,allowDefaultHomeMigration:true
|
|
150
150
|
});
|
|
151
|
+
// An offline worker allow can precede the database. Reconcile named profiles at startup;
|
|
152
|
+
// legacy installations retain their pre-relationship behavior until explicitly enrolled.
|
|
153
|
+
if(!legacyProfile) for(const worker of workers.workers.keys()) ensureWorkerRelationship(store.db,worker);
|
|
151
154
|
const ackLedger=new AckLedger(path.join(dataDir,'delivery-acks.db'));
|
|
152
155
|
const notifyLedger=new NotifyLedger(path.join(dataDir,'notify-sent.db'));
|
|
153
156
|
process.on('exit',()=>{try{ackLedger.close();}catch{}try{notifyLedger.close();}catch{}});
|
|
@@ -180,7 +183,7 @@ if(!t3ToolsEnabled)for(const [worker,profile] of workers.workers)if(profile.capa
|
|
|
180
183
|
log({kind:'t3_tools_disabled',worker,setting:'DALAN_ENABLE_T3_TOOLS=1'});
|
|
181
184
|
console.error(`dalan: startup WARNING: worker "${worker}" has t3 capability but reverse-control tools are off; set DALAN_ENABLE_T3_TOOLS=1`);
|
|
182
185
|
}
|
|
183
|
-
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:
|
|
186
|
+
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: its T3 authority is limited by live job destinations and tool grants.`);
|
|
184
187
|
const startupPolicy=currentRepoPolicy();
|
|
185
188
|
for(const worker of workers.workers.keys()) if(startupPolicy.repoPolicy(worker)?.repos.length===0) {
|
|
186
189
|
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;
|
|
@@ -322,6 +325,19 @@ function id(value,name='request_id') { const s=str(value,name,128); if(!/^[-\w]{
|
|
|
322
325
|
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}`); }
|
|
323
326
|
function adminOwner(req,idValue) { store.owner(id(idValue),req.headers['x-owner-capability']); }
|
|
324
327
|
function adminOperator(req) { authorize(req.headers['x-operator-key'],operatorKey,'operator key'); }
|
|
328
|
+
const questionPurpose=value=>{
|
|
329
|
+
if(value===undefined) return 'clarification';
|
|
330
|
+
if(!QUESTION_PURPOSES.includes(value)) throw new Error(`invalid purpose: use ${QUESTION_PURPOSES.join(' or ')}`);
|
|
331
|
+
return value;
|
|
332
|
+
};
|
|
333
|
+
// Any question with a purpose other than clarification is answered by a person holding the operator key. The owner
|
|
334
|
+
// capability alone, which a parent model may hold, is refused before anything is stored.
|
|
335
|
+
function requireOperatorForHumanQuestion(req,requestId,questionId) {
|
|
336
|
+
const purpose=store.questionPurpose(requestId,questionId);
|
|
337
|
+
if(purpose===null||purpose==='clarification') return;
|
|
338
|
+
try { adminOperator(req); }
|
|
339
|
+
catch { throw new Error(`FORBIDDEN: question ${questionId} on ${requestId} has purpose ${purpose}, reserved for a human; answering it needs the operator key, not the owner capability alone`); }
|
|
340
|
+
}
|
|
325
341
|
|
|
326
342
|
const event = {
|
|
327
343
|
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.',
|
|
@@ -343,7 +359,7 @@ const tools = [
|
|
|
343
359
|
{ name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
|
|
344
360
|
{ name:'ack_message',description:'Acknowledge a lightweight message after reading it; no claim or finish is needed.',inputSchema:schema({message_id:string},['message_id']) },
|
|
345
361
|
{ 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']) },
|
|
346
|
-
{ 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']) },
|
|
362
|
+
{ 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. Set purpose to human_decision (a choice only a human may make), authentication (a sign-in only a human can complete) or tool_permission (a permission only a human may grant) when only a human may answer; no model can answer such a question for them.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096},purpose:{type:'string',enum:['clarification','human_decision','authentication','tool_permission']}},['request_id','claim_id','question_id','text']) },
|
|
347
363
|
{ 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']) },
|
|
348
364
|
{ 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']) },
|
|
349
365
|
{ 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']) },
|
|
@@ -419,6 +435,7 @@ const disabled=new Set(['list_files','read_file','apply_patch','run_check','work
|
|
|
419
435
|
const readTools=new Set(['list_pending','get','list_files','read_file','workspace_result','list_tools','call_tool_read']);
|
|
420
436
|
const t3ReadTools=new Set(['t3_thread_list','t3_thread_read','t3_thread_wait']);
|
|
421
437
|
const t3Tools=new Set([...t3ReadTools,'t3_thread_create','t3_thread_send','t3_thread_set']);
|
|
438
|
+
if(t3ToolsEnabled)toolRegistry.initializeT3Grants([...t3Tools],workers.workers.keys());
|
|
422
439
|
const notifyTools=new Set(['notify_owner']);
|
|
423
440
|
// T3 tools use the existing scopes to preserve the current grant behavior.
|
|
424
441
|
const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'dalan.work';
|
|
@@ -606,6 +623,78 @@ const listGuidance='Claim every listed assignment you can start now, up to free_
|
|
|
606
623
|
const claimMoreGuidance='If free_lanes > 0 and work is queued, claim more now.';
|
|
607
624
|
// A finishing lane takes the next queued item itself; an error on any claim means the list changed, so list again.
|
|
608
625
|
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.`;
|
|
626
|
+
// A worker with finish_handoff gets its next job inside the finish reply, or waits a bounded time for work.
|
|
627
|
+
// The claim is the worker's own `claim` call, run by the bridge: same policy, preflight, scope, pause, capacity and
|
|
628
|
+
// connection checks, one claim per job. The claim carries acquisition_id handoff-<finished claim_id>, so a repeated
|
|
629
|
+
// finish gets the same job back, and a second finish by the same claimant name, which would otherwise count as an
|
|
630
|
+
// exact retry of the first claim, is refused that job and takes the next one.
|
|
631
|
+
const HANDOFF_LEASE_MS=600000,HANDOFF_POLL_MS=500,HANDOFF_MAX_ATTEMPTS=5;
|
|
632
|
+
const nap=(ms,signal)=>new Promise(resolve=>{
|
|
633
|
+
const done=()=>{clearTimeout(timer);signal?.removeEventListener('abort',done);resolve();};
|
|
634
|
+
const timer=setTimeout(done,ms);
|
|
635
|
+
signal?.addEventListener('abort',done,{once:true});
|
|
636
|
+
});
|
|
637
|
+
// One handoff per finished claim at a time: a retried finish that arrives while the first is still waiting or
|
|
638
|
+
// claiming queues behind it, then finds the first one's grant instead of taking a second job.
|
|
639
|
+
const handoffsInFlight=new Map();
|
|
640
|
+
async function handOffNextJob(args) {
|
|
641
|
+
const key=`${args.principal.worker}\0${args.principal.subject}\0${args.claimId}`;
|
|
642
|
+
while(handoffsInFlight.has(key)) await handoffsInFlight.get(key);
|
|
643
|
+
const run=runHandoff(args).finally(()=>handoffsInFlight.delete(key));
|
|
644
|
+
handoffsInFlight.set(key,run);
|
|
645
|
+
return run;
|
|
646
|
+
}
|
|
647
|
+
// Returns {job}, {empty,waited_ms} or {} (no handoff: the caller keeps the old hint). Never throws: the finish is stored.
|
|
648
|
+
async function runHandoff({principal,requestId,claimId,waitMs,signal}) {
|
|
649
|
+
try {
|
|
650
|
+
const {worker,subject}=principal;
|
|
651
|
+
const held=store.db.prepare('SELECT claimant FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId);
|
|
652
|
+
if(!held) return {};
|
|
653
|
+
const acquisition_id=`handoff-${claimId}`,lease_ms=Math.min(HANDOFF_LEASE_MS,store.limits.leaseMs);
|
|
654
|
+
const claim=async next=>{
|
|
655
|
+
try {
|
|
656
|
+
const job=await tool('claim',{request_id:next,claimant:held.claimant,acquisition_id,lease_ms},principal,undefined,signal);
|
|
657
|
+
return job&&typeof job.error!=='string'&&job.claim_id?job:null;
|
|
658
|
+
} catch { return null; }
|
|
659
|
+
};
|
|
660
|
+
// A repeated finish gets back the job its first reply carried. If that job is gone (finished, expired), this finish
|
|
661
|
+
// already had its handoff: it takes no second job.
|
|
662
|
+
const prior=store.db.prepare("SELECT c.request_id,c.state,a.status FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.subject=? AND c.acquisition_id=?").get(worker,subject,acquisition_id);
|
|
663
|
+
if(prior) { const job=prior.state==='active'&&prior.status==='claimed'?await claim(prior.request_id):null; return job?{job}:{}; }
|
|
664
|
+
const started=Date.now(),tried=new Set();
|
|
665
|
+
let sawQueued=false;
|
|
666
|
+
for(;;) {
|
|
667
|
+
if(signal?.aborted||store.paused()) return {};
|
|
668
|
+
const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
669
|
+
if(free_lanes<=0) return {};
|
|
670
|
+
if(store.hasQueuedFor([worker])) {
|
|
671
|
+
sawQueued=true;
|
|
672
|
+
const pick=()=>(store.nextQueued(free_lanes+tried.size,null,worker).next_queued??[]).filter(x=>!tried.has(x.request_id));
|
|
673
|
+
// A lost race or an unclaimable head moves on to the next job; an unclaimable queue ends in the old hint.
|
|
674
|
+
for(let fresh=pick();fresh.length&&tried.size<HANDOFF_MAX_ATTEMPTS;fresh=pick()) {
|
|
675
|
+
tried.add(fresh[0].request_id);
|
|
676
|
+
const job=await claim(fresh[0].request_id);
|
|
677
|
+
if(job) return {job};
|
|
678
|
+
}
|
|
679
|
+
if(tried.size) return {};
|
|
680
|
+
}
|
|
681
|
+
const left=started+waitMs-Date.now();
|
|
682
|
+
if(left<=0) return sawQueued?{}:{empty:true,waited_ms:Date.now()-started};
|
|
683
|
+
await nap(Math.min(HANDOFF_POLL_MS,left),signal);
|
|
684
|
+
}
|
|
685
|
+
} catch(error) { log({kind:'finish_handoff_error',request_id:requestId,reason:redactNote(String(error?.message??error))}); return {}; }
|
|
686
|
+
}
|
|
687
|
+
async function finishReply(reply,{principal,requestId,claimId,signal}) {
|
|
688
|
+
const setting=workers.workers.get(principal.worker)?.finishHandoff;
|
|
689
|
+
if(setting&&reply.receipt_id&&!store.isProtocolJob(requestId)) {
|
|
690
|
+
const {job,empty,waited_ms}=await handOffNextJob({principal,requestId,claimId,waitMs:setting.waitMs,signal});
|
|
691
|
+
log({kind:'finish_handoff',request_id:requestId,next_request_id:job?.request_id??null,result:job?'claimed':empty?'empty':'none',waited_ms:waited_ms??0});
|
|
692
|
+
const {next_queued,next_action,...rest}=reply;
|
|
693
|
+
if(job) return {...rest,next_job:job,guidance:`Your next job ${job.request_id} is already claimed for you; its claim result is in next_job. Work on it now, in this turn, and call finish for it. ${job.lease_expires_at?`Its lease ends at ${job.lease_expires_at}`:'Its lease is short'}; every tool call on it renews the lease.`};
|
|
694
|
+
if(empty) return {...rest,queue_empty:true,waited_ms,guidance:waited_ms>=1000?`No job was queued for ${Math.round(waited_ms/1000)} seconds. Nothing is claimed for you. End this run; a new assignment wakes you.`:'No job is queued. Nothing is claimed for you. End this run; a new assignment wakes you.'};
|
|
695
|
+
}
|
|
696
|
+
return reply.next_queued?.length&&!store.paused()?{...reply,guidance:finishNextGuidance(reply.next_queued)}:reply;
|
|
697
|
+
}
|
|
609
698
|
// A loader failure carries host paths or quotes the file. Every caller of this policy gets the Store's fixed error instead.
|
|
610
699
|
function repoPolicyFor(assignment) {
|
|
611
700
|
try { return currentRepoPolicy(); }
|
|
@@ -650,7 +739,7 @@ const policyPage=(worker,cursor=null)=>store.pullQueue.list(worker,admitPolicyWo
|
|
|
650
739
|
async function submitPolicy(body,req,dryRun) {
|
|
651
740
|
if(req.method!=='POST')throw new Error('policy submit requires POST');
|
|
652
741
|
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');
|
|
653
|
-
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');
|
|
742
|
+
if(body.worker!==undefined||body.relationship_id!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.revises!==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, relationship, command, supersede, revise or capacity options');
|
|
654
743
|
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');
|
|
655
744
|
if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment inputs');
|
|
656
745
|
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');
|
|
@@ -668,6 +757,7 @@ async function submitPolicy(body,req,dryRun) {
|
|
|
668
757
|
const approvals=body.destination_revisions??{};
|
|
669
758
|
if(!approvals||typeof approvals!=='object'||Array.isArray(approvals)||Object.keys(approvals).some(worker=>!routing.allowed_workers.includes(worker)))throw new Error('invalid destination_revisions');
|
|
670
759
|
const options={delivery,environmentId:oldOptions?.environmentId??'',execution,review:body.review===true,priority,meta};
|
|
760
|
+
if(oldOptions&&Object.hasOwn(oldOptions,'relationships')) options.relationships=oldOptions.relationships;
|
|
671
761
|
if(old)return store.pullQueue.submit(JSON.parse(old.payload),identity,options,routing,approvals,owner,{dryRun});
|
|
672
762
|
let payload=identity,preflight=null;
|
|
673
763
|
// Validate scope under each candidate's current repository policy. No candidate
|
|
@@ -683,16 +773,23 @@ async function submitPolicy(body,req,dryRun) {
|
|
|
683
773
|
preflight=await preflightPR(payload);
|
|
684
774
|
options.environmentId=(await destination.validate(delivery)).environmentId??'';
|
|
685
775
|
for(const worker of routing.allowed_workers)if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
|
|
686
|
-
|
|
687
|
-
//
|
|
688
|
-
|
|
689
|
-
|
|
776
|
+
// Capture each candidate's relationship at the same transaction boundary as admission.
|
|
777
|
+
// Acquisition uses this binding, so ending it later does not revoke accepted work.
|
|
778
|
+
const result=store.inTransaction(()=>{
|
|
779
|
+
const existing=store.pullQueue.row(identity.request_id);
|
|
780
|
+
if(existing) {
|
|
781
|
+
const saved=JSON.parse(existing.options);
|
|
782
|
+
if(Object.hasOwn(saved,'relationships')) options.relationships=saved.relationships;
|
|
783
|
+
} else options.relationships=Object.fromEntries(routing.allowed_workers.map(worker=>[worker,store.relationshipForSubmission(worker)?.relationship_id??null]));
|
|
784
|
+
return store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun});
|
|
785
|
+
});
|
|
786
|
+
if(dryRun)return {...result,destination_disclosures:disclosures};
|
|
690
787
|
log({kind:'policy_work_submitted',request_id:identity.request_id,work_order_id:result.work_order_id});
|
|
691
788
|
return {...result,execution};
|
|
692
789
|
}
|
|
693
790
|
|
|
694
791
|
// 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.
|
|
695
|
-
async function tool(name,a,principal,notifyMeta) {
|
|
792
|
+
async function tool(name,a,principal,notifyMeta,signal) {
|
|
696
793
|
if(!toolNames.has(name)) throw new Error('unknown tool');
|
|
697
794
|
// Refuse hidden names before audits, lease touches, sweeps or repository preparation.
|
|
698
795
|
if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
|
|
@@ -701,7 +798,7 @@ async function tool(name,a,principal,notifyMeta) {
|
|
|
701
798
|
}
|
|
702
799
|
let error=null;
|
|
703
800
|
try {
|
|
704
|
-
const result=await dispatchTool(name,a,principal,notifyMeta);
|
|
801
|
+
const result=await dispatchTool(name,a,principal,notifyMeta,signal);
|
|
705
802
|
if(typeof result?.error==='string') error=redactNote(result.error);
|
|
706
803
|
return result;
|
|
707
804
|
} catch(e) { error=redactNote(String(e?.message??e)); if(e.destination&&typeof a?.request_id==='string')notifyAttachedWaiter(a.request_id); throw e; }
|
|
@@ -712,7 +809,7 @@ async function tool(name,a,principal,notifyMeta) {
|
|
|
712
809
|
}
|
|
713
810
|
}
|
|
714
811
|
}
|
|
715
|
-
async function dispatchTool(name,a,principal,notifyMeta) {
|
|
812
|
+
async function dispatchTool(name,a,principal,notifyMeta,signal) {
|
|
716
813
|
const t3Audit=(t3Tools.has(name)||notifyTools.has(name))?await loadT3Audit():null;
|
|
717
814
|
if(t3Audit) t3Audit.admitT3Audit(store.db,principal.worker,principal.subject);
|
|
718
815
|
store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
|
|
@@ -741,7 +838,31 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
741
838
|
return T3_READ_TOOLS_OFF;
|
|
742
839
|
}
|
|
743
840
|
const t3Arguments=name==='t3_thread_wait'?{...a,timeoutMs:Math.min(a.timeoutMs??90_000,90_000)}:a;
|
|
744
|
-
|
|
841
|
+
let result;
|
|
842
|
+
if(t3Tools.has(name)) {
|
|
843
|
+
const control=await import('./t3-control.mjs');
|
|
844
|
+
const t3=await import('./t3.mjs');
|
|
845
|
+
const authorize=()=>{
|
|
846
|
+
const threads=toolRegistry.t3Threads(name,principal);
|
|
847
|
+
if(name!=='t3_thread_list' && !threads.has(a.threadId)) throw new RegistryError('tool_unavailable','tool unavailable');
|
|
848
|
+
return threads;
|
|
849
|
+
};
|
|
850
|
+
// Linearization point: this synchronous live-grant read follows the last await before
|
|
851
|
+
// send/set invokes the CLI. A revoke committed before it refuses the effect. No claim
|
|
852
|
+
// is made about revokes after CLI dispatch cancelling an external effect.
|
|
853
|
+
authorize();
|
|
854
|
+
if(name==='t3_thread_list') {
|
|
855
|
+
const data=await t3.callT3(t3.listArgs({cwd:a.cwd,project:a.projectId,status:a.status,workspace_mode:a.workspaceMode}));
|
|
856
|
+
const threads=authorize();
|
|
857
|
+
result=control.compactThreadList({...data,threads:(data.threads??[]).filter(t=>threads.has(t.id))});
|
|
858
|
+
result._audit_ids={threadIds:result.threads.map(t=>t.id),projectIds:result.projects.map(p=>p.id)};
|
|
859
|
+
} else {
|
|
860
|
+
result=await control.runT3Tool(name,t3Arguments);
|
|
861
|
+
// Wait/read results require current authority. Writes linearize at dispatch:
|
|
862
|
+
// revocation afterward cannot turn a successful effect into a denied receipt.
|
|
863
|
+
if(t3ReadTools.has(name)) authorize();
|
|
864
|
+
}
|
|
865
|
+
} else result=await notifyLedger.send(principal.worker,str(a.text,'text',1000),notificationKey,idempotencyKey=>publishAlert('Dalan message',a.text,log,{requirePublisher:true,idempotencyKey}));
|
|
745
866
|
t3Audit.appendT3Audit(store.db,audit,principal.subject,'success',result);
|
|
746
867
|
if(result && typeof result==='object' && Object.hasOwn(result,'_audit_ids')) { const {_audit_ids,...publicResult}=result; return publicResult; }
|
|
747
868
|
return result;
|
|
@@ -855,7 +976,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
855
976
|
return {...receipt,...repaired.marks};
|
|
856
977
|
}
|
|
857
978
|
case 'ask_question': {
|
|
858
|
-
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);
|
|
979
|
+
const requestId=id(a.request_id),question=str(a.question_id,'question_id',128),text=str(a.text,'text',4096),purpose=questionPurpose(a.purpose),receipt=store.askQuestion(requestId,id(a.claim_id,'claim_id'),question,text,subject,worker,commandContext('ask_question',{question,text,...(purpose==='clarification'?{}:{purpose})}),connectionId,purpose);
|
|
859
980
|
notifyAttachedWaiter(requestId);
|
|
860
981
|
return receipt;
|
|
861
982
|
}
|
|
@@ -903,8 +1024,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
|
|
|
903
1024
|
if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
|
|
904
1025
|
notifyAttachedWaiter(requestId);
|
|
905
1026
|
if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
|
|
906
|
-
|
|
907
|
-
return receipt.next_queued?.length&&!store.paused()?{...marked,guidance:finishNextGuidance(receipt.next_queued)}:marked; }
|
|
1027
|
+
return finishReply({...receipt,...repaired.marks},{principal,requestId,claimId,signal}); }
|
|
908
1028
|
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);
|
|
909
1029
|
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);
|
|
910
1030
|
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);
|
|
@@ -944,7 +1064,7 @@ function publicErrorText(error,what) {
|
|
|
944
1064
|
log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
|
|
945
1065
|
return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
|
|
946
1066
|
}
|
|
947
|
-
async function dispatch(message,principal) {
|
|
1067
|
+
async function dispatch(message,principal,signal) {
|
|
948
1068
|
const p=message.params??{};
|
|
949
1069
|
switch(message.method) {
|
|
950
1070
|
case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
|
|
@@ -953,7 +1073,7 @@ async function dispatch(message,principal) {
|
|
|
953
1073
|
// Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
|
|
954
1074
|
// legacy-v46 keeps its pinned per-worker surface for compatibility.
|
|
955
1075
|
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};
|
|
956
|
-
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; } }
|
|
1076
|
+
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,signal)))}],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; } }
|
|
957
1077
|
case 'events/list': return {events:[event]};
|
|
958
1078
|
case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
|
|
959
1079
|
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 {}; }
|
|
@@ -996,7 +1116,9 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
|
|
|
996
1116
|
if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
|
|
997
1117
|
outcome.state.phase='dispatch';
|
|
998
1118
|
const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
|
|
999
|
-
|
|
1119
|
+
// A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
|
|
1120
|
+
const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
|
|
1121
|
+
try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal)}},eventStream); }
|
|
1000
1122
|
catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
|
|
1001
1123
|
// Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
|
|
1002
1124
|
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}); }
|
|
@@ -1038,6 +1160,8 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1038
1160
|
if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
|
|
1039
1161
|
const commandKey=body.command_key===undefined?null:body.command_key;
|
|
1040
1162
|
const supersedes=body.supersedes===undefined?null:body.supersedes;
|
|
1163
|
+
// {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
|
|
1164
|
+
const revises=body.revises===undefined?null:body.revises;
|
|
1041
1165
|
const destinationRevision=body.destination_revision??null;
|
|
1042
1166
|
if(body.destination_revision!==undefined&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
|
|
1043
1167
|
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');
|
|
@@ -1093,18 +1217,20 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1093
1217
|
// even when validation changed the stored brief (scope narrowing, the appended allow-list).
|
|
1094
1218
|
const submitted=payload;
|
|
1095
1219
|
const isNew=!store.hasAssignment(payload.request_id);
|
|
1220
|
+
if(isNew&&dryRun) store.relationshipForSubmission(target,body.relationship_id??null);
|
|
1096
1221
|
// Reject immutable retry conflicts using the persisted binding before any external destination inspection.
|
|
1097
1222
|
// A matching retry still validates the current destination below; this does not accept stale environment evidence.
|
|
1098
|
-
store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1223
|
+
store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
|
|
1099
1224
|
let order=null;
|
|
1100
1225
|
if(isNew) {
|
|
1101
1226
|
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,
|
|
1102
1227
|
excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
|
|
1103
1228
|
render:renderAssignment,
|
|
1104
1229
|
admitExecution:(p,r)=>{
|
|
1105
|
-
|
|
1230
|
+
const adapterRequired=r.jobExecution==='host'?r.requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name)):r.requiredCapabilities;
|
|
1231
|
+
admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
|
|
1106
1232
|
// No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
|
|
1107
|
-
if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities);
|
|
1233
|
+
if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
|
|
1108
1234
|
},
|
|
1109
1235
|
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'}),
|
|
1110
1236
|
admitReadiness:p=>{
|
|
@@ -1124,10 +1250,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1124
1250
|
if(!dryRun&&(order.verdict==='reject'||order.verdict==='clarify'||order.blocking)) throw Object.assign(order.refusal,{verdict:order.verdict,reasons:order.reasons,bytes:order.bytes});
|
|
1125
1251
|
payload=order.payload;
|
|
1126
1252
|
}
|
|
1127
|
-
const {environmentId}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
|
|
1253
|
+
const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
|
|
1128
1254
|
// An awaited repository/destination lookup may outlive a host policy edit.
|
|
1129
1255
|
assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
|
|
1130
|
-
if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1256
|
+
if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
|
|
1131
1257
|
const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
|
|
1132
1258
|
if(dryRun) {
|
|
1133
1259
|
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});
|
|
@@ -1142,7 +1268,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1142
1268
|
const readiness=order?.check_readiness??null;
|
|
1143
1269
|
const preflight=order?.preflight??null;
|
|
1144
1270
|
const defaultValidity=order?.defaultValidity??null;
|
|
1145
|
-
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);
|
|
1271
|
+
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,null,generation??null,body.relationship_id??null,revises);
|
|
1146
1272
|
// Only a committed first replacement wakes the TARGET's already-attached waiter.
|
|
1147
1273
|
if(supersedes&&!result.duplicate) {
|
|
1148
1274
|
const targetId=supersedes.target_id,waiter=waiters.get(targetId);
|
|
@@ -1165,6 +1291,8 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1165
1291
|
const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
|
|
1166
1292
|
if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
|
|
1167
1293
|
if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
|
|
1294
|
+
// The owner needs the current revision to build a keyed, revision-checked command such as `dalan answer`. It is null for a job with no protocol revisions.
|
|
1295
|
+
got.protocol_revision=store.isProtocolJob(requestId)?store.protocolRevision(requestId):null;
|
|
1168
1296
|
if(!workspaceEnabled||got.assignment?.execution_scope!=='implementation'||got.available_checks_error==='repository_policy_denied') return json(res,200,got);
|
|
1169
1297
|
try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
|
|
1170
1298
|
catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
|
|
@@ -1219,7 +1347,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1219
1347
|
const action=url.pathname.slice(7);
|
|
1220
1348
|
if(action==='add') return json(res,200,toolRegistry.register(body.spec));
|
|
1221
1349
|
if(action==='remove') return json(res,200,toolRegistry.remove(body.name));
|
|
1222
|
-
if(action==='grant') { toolRegistry.grant(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
|
|
1350
|
+
if(action==='grant') { toolRegistry.grant(body.name,body.worker,body.scope); return json(res,200,{name:body.name,worker:body.worker,granted:true}); }
|
|
1223
1351
|
if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
|
|
1224
1352
|
} catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
|
|
1225
1353
|
}
|
|
@@ -1234,6 +1362,16 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1234
1362
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1235
1363
|
if(body.decision==='stale') throw new Error('stale is recorded by the sweep only');
|
|
1236
1364
|
const via=['cli','apply','adapter'].includes(body.via)?body.via:'cli';
|
|
1365
|
+
// The two-phase apply: reserve (the stale check), then confirm or release once the patch is written or has failed.
|
|
1366
|
+
if(body.phase!==undefined) {
|
|
1367
|
+
if(body.decision!=='applied'||!['reserve','confirm','release'].includes(body.phase)) throw new Error('phase is reserve, confirm or release, and goes with decision applied');
|
|
1368
|
+
// Every attempt reserves and gets a token; confirm and release must present the current one. force releases an
|
|
1369
|
+
// uncertain reservation on purpose (the owner's own capability, no token).
|
|
1370
|
+
if(body.phase==='reserve') return json(res,200,store.reserveApply(requestId));
|
|
1371
|
+
const attempt=body.attempt===undefined||body.attempt===null?undefined:str(body.attempt,'attempt',128);
|
|
1372
|
+
if(body.phase==='release') return json(res,200,store.releaseApply(requestId,{attempt,force:body.force===true,reason:body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)}));
|
|
1373
|
+
return json(res,200,store.confirmApply(requestId,{attempt,note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
|
|
1374
|
+
}
|
|
1237
1375
|
return json(res,200,store.decide(requestId,String(body.decision),{note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
|
|
1238
1376
|
}
|
|
1239
1377
|
if(url.pathname==='/lifecycle'&&req.method==='POST') {
|
|
@@ -1242,10 +1380,33 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1242
1380
|
return json(res,200,store.integrated(id(body.id),body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)));
|
|
1243
1381
|
}
|
|
1244
1382
|
if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
|
|
1245
|
-
if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);return json(res,200,store.answerQuestion(requestId,
|
|
1383
|
+
if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
|
|
1246
1384
|
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)}); }
|
|
1247
1385
|
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')));
|
|
1248
1386
|
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)));
|
|
1387
|
+
if(url.pathname==='/relationships'&&req.method==='GET') { adminOperator(req); return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all()}); }
|
|
1388
|
+
if(url.pathname==='/relationships/end'&&req.method==='POST') {
|
|
1389
|
+
adminOperator(req);
|
|
1390
|
+
const relationshipId=str(body.relationship_id,'relationship_id',128);
|
|
1391
|
+
const changed=store.db.prepare('UPDATE relationships SET ended_at=COALESCE(ended_at,?) WHERE relationship_id=?').run(new Date(store.nowMs()).toISOString(),relationshipId);
|
|
1392
|
+
if(!changed.changes) throw new Error('relationship_not_found');
|
|
1393
|
+
return json(res,200,{relationship:store.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId)});
|
|
1394
|
+
}
|
|
1395
|
+
if(url.pathname==='/grants'&&req.method==='GET') {
|
|
1396
|
+
adminOperator(req);
|
|
1397
|
+
const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
|
|
1398
|
+
const grants=[
|
|
1399
|
+
...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
|
|
1400
|
+
...store.db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1').all().map(row=>({...row,scope:row.scope===null?null:JSON.parse(row.scope),enforcer:'tool_registry',expires_at:null})),
|
|
1401
|
+
...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
|
|
1402
|
+
...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
|
|
1403
|
+
...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
|
|
1404
|
+
...[...currentWorkers.workers.keys()].flatMap(worker=>(currentWorkers.repoPolicy(worker)?.repos??[]).map(repo=>({worker,repo,enforcer:'repository_policy',expires_at:null}))),
|
|
1405
|
+
...(as?as.store.db.prepare("SELECT c.connection_id,c.worker,c.scopes,c.created_at,o.expires_at FROM connections c JOIN oidc o ON o.model='Grant' AND o.id=c.grant_id WHERE c.revoked_at IS NULL AND (o.expires_at IS NULL OR o.expires_at>?)").all(store.nowMs()).map(row=>({connection_id:row.connection_id,worker:row.worker,scopes:row.scopes.split(' '),created_at:new Date(row.created_at).toISOString(),enforcer:'connection',expires_at:row.expires_at===null?null:new Date(row.expires_at).toISOString()})):
|
|
1406
|
+
[...workers.workers].flatMap(([worker,profile])=>(profile.connections??[]).map(({issuer,subject,client_id,connection_id})=>({worker,issuer,subject,client_id,connection_id,enforcer:'external_connection',expires_at:null,expiry_status:'unknown'})))),
|
|
1407
|
+
];
|
|
1408
|
+
return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all(),grants});
|
|
1409
|
+
}
|
|
1249
1410
|
if(url.pathname.startsWith('/connect/')) {
|
|
1250
1411
|
adminOperator(req);
|
|
1251
1412
|
if(!as) throw new Error('built-in authorization server is not enabled (DALAN_AUTH_MODE=builtin)');
|
|
@@ -1257,7 +1418,11 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1257
1418
|
if(url.pathname==='/connect/reset'&&req.method==='POST') return json(res,200,ops.reset());
|
|
1258
1419
|
if(url.pathname==='/connect/stop'&&req.method==='POST') return json(res,200,ops.stop());
|
|
1259
1420
|
if(url.pathname==='/connect/pending'&&req.method==='GET') return json(res,200,ops.pending());
|
|
1260
|
-
if(url.pathname==='/connect/approve'&&req.method==='POST')
|
|
1421
|
+
if(url.pathname==='/connect/approve'&&req.method==='POST') {
|
|
1422
|
+
const approval=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});
|
|
1423
|
+
ensureWorkerRelationship(store.db,approval.worker);
|
|
1424
|
+
return json(res,200,approval);
|
|
1425
|
+
}
|
|
1261
1426
|
if(url.pathname==='/connect/list'&&req.method==='GET') return json(res,200,ops.list());
|
|
1262
1427
|
if(url.pathname==='/connect/revoke'&&req.method==='POST') return json(res,200,ops.revoke({worker:body.worker}));
|
|
1263
1428
|
if(url.pathname==='/connect/signal-token'&&req.method==='POST') return json(res,200,signal.tokenUrl({worker:body.worker,rotate:body.rotate===true}));
|
|
@@ -1286,17 +1451,19 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1286
1451
|
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)});
|
|
1287
1452
|
log({kind:'claim_abandoned',request_id:requestId,epoch:result.abandoned.epoch,actor:'operator'});
|
|
1288
1453
|
runDrain();
|
|
1289
|
-
return json(res,200,result);
|
|
1454
|
+
return json(res,200,{...result,scope:controlScopeText('detach',{ref:`claim:${result.abandoned.claim_id}@${result.abandoned.epoch}`})});
|
|
1290
1455
|
}
|
|
1291
1456
|
if(url.pathname==='/cancel') {
|
|
1292
1457
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1293
|
-
|
|
1458
|
+
// Read before the cancel: the scope text depends on whether a worker held the job.
|
|
1459
|
+
const wasClaimed=store.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='claimed'").get(requestId)!==undefined;
|
|
1460
|
+
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,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:wasClaimed})});
|
|
1294
1461
|
}
|
|
1295
1462
|
if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
|
|
1296
1463
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
1297
1464
|
const result=store.cancelIfQueued(requestId);
|
|
1298
1465
|
if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
|
|
1299
|
-
return json(res,200,result);
|
|
1466
|
+
return json(res,200,result.cancelled?{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:false})}:result);
|
|
1300
1467
|
}
|
|
1301
1468
|
if(url.pathname==='/break'&&req.method==='POST') {
|
|
1302
1469
|
adminOperator(req);
|
|
@@ -1337,7 +1504,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1337
1504
|
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}:{})});
|
|
1338
1505
|
if(infrastructure&&!rejected) log({kind:'admin_infrastructure_error',route:String(req.url).split('?')[0],code:e.code??null,reason:e.message.slice(0,300)});
|
|
1339
1506
|
const shown=publicErrorText(e,'admin request');
|
|
1340
|
-
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}:{})}:{})});
|
|
1507
|
+
json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(e.stale?{stale:e.stale}:{}),...(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}:{})}:{})});
|
|
1341
1508
|
}
|
|
1342
1509
|
});
|
|
1343
1510
|
|
|
@@ -1478,6 +1645,15 @@ if(workspace) {
|
|
|
1478
1645
|
setInterval(()=>{if(t3PostHandler.hasHeld())t3PostHandler.flushDue().catch(()=>{});},60000).unref();
|
|
1479
1646
|
setInterval(maintain,500).unref(); maintain();
|
|
1480
1647
|
setInterval(runDrain,500).unref(); runDrain();
|
|
1648
|
+
// A wake held because its parent was interrupted goes back to the queue once the parent runs again (see the T3 destination).
|
|
1649
|
+
let releasingHeld=false;
|
|
1650
|
+
const releaseHeldWakes=async()=>{
|
|
1651
|
+
if(releasingHeld||!store.heldDeliveries(1).length) return; releasingHeld=true;
|
|
1652
|
+
try { const destination=await destinations.for('t3'); if((await destination.releaseHeld()).length) runDrain(); }
|
|
1653
|
+
catch(error) { log({kind:'held_release_error',reason:String(error?.message??error).slice(0,300)}); }
|
|
1654
|
+
finally { releasingHeld=false; }
|
|
1655
|
+
};
|
|
1656
|
+
setInterval(releaseHeldWakes,Number(readEnv('DALAN_T3_HELD_RECHECK_MS'))||15000).unref();
|
|
1481
1657
|
reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message}));
|
|
1482
1658
|
setInterval(()=>reconcileTick().catch(e=>log({kind:'reconciliation_error',reason:e.message})),60000).unref();
|
|
1483
1659
|
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});}};
|
package/src/service-launchd.mjs
CHANGED
|
@@ -86,13 +86,24 @@ export function launchctl(args, { spawn = spawnSync, env = process.env } = {}) {
|
|
|
86
86
|
}
|
|
87
87
|
const uidOf = seams => (seams.uid ?? process.getuid?.());
|
|
88
88
|
const domainOf = seams => `user/${uidOf(seams)}`;
|
|
89
|
-
|
|
89
|
+
// Only launchctl's explicit missing-service diagnostic establishes absence.
|
|
90
|
+
export function queryAgent(label, seams = {}) {
|
|
91
|
+
const result = launchctl(['print', `${domainOf(seams)}/${label}`], seams);
|
|
92
|
+
const diagnostic = String(result.stderr || result.stdout).trim();
|
|
93
|
+
const absent = result.status > 0 && diagnostic.includes(`Could not find service "${label}" in domain`);
|
|
94
|
+
return { ...result, state: result.status === 0 ? 'loaded' : absent ? 'absent' : 'unknown' };
|
|
95
|
+
}
|
|
96
|
+
export function isLoaded(label, seams = {}) {
|
|
97
|
+
const result = queryAgent(label, seams);
|
|
98
|
+
if (result.state === 'unknown') fail(`Cannot determine whether launchd service ${label} is loaded; leaving its plist unchanged. launchctl print failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`);
|
|
99
|
+
return result.state === 'loaded';
|
|
100
|
+
}
|
|
90
101
|
const must = (result, what) => { if (result.status !== 0) fail(`${what} failed (exit ${result.status}): ${String(result.stderr || result.stdout).trim().slice(0, 500)}`); };
|
|
91
102
|
|
|
92
103
|
// Load the agent from its plist, then ask launchd to start it: on macOS 26 a bootstrapped agent can stay loaded and never spawn.
|
|
93
|
-
export function loadAgent({ label, plistFile }, seams = {}) {
|
|
104
|
+
export function loadAgent({ label, plistFile, knownAbsent = false }, seams = {}) {
|
|
94
105
|
const domain = domainOf(seams);
|
|
95
|
-
if (!isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
|
|
106
|
+
if (knownAbsent || !isLoaded(label, seams)) must(launchctl(['bootstrap', domain, plistFile], seams), `launchctl bootstrap ${domain} ${plistFile}`);
|
|
96
107
|
const kick = launchctl(['kickstart', `${domain}/${label}`], seams);
|
|
97
108
|
return { kicked: kick.status === 0, detail: kick.status === 0 ? '' : String(kick.stderr).trim() };
|
|
98
109
|
}
|
|
@@ -120,13 +131,18 @@ export function controlLaunchd(receipt, action, seams = {}) {
|
|
|
120
131
|
}
|
|
121
132
|
|
|
122
133
|
// ---- plist files ------------------------------------------------------------------------------------------------------------------------
|
|
123
|
-
//
|
|
124
|
-
|
|
125
|
-
export function writeAgentFile(file, text) {
|
|
134
|
+
// Read-only ownership/collision check. Return whether the generated plist needs writing.
|
|
135
|
+
export function preflightAgentFile(file, text) {
|
|
126
136
|
let existing = null;
|
|
127
137
|
try { const info = fs.lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) fail(`${file} is not a regular file; refusing to replace it`); existing = fs.readFileSync(file, 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
128
138
|
if (existing === text) return false;
|
|
129
139
|
if (existing !== null && !existing.includes(MARKER)) fail(`${file} already exists and was not generated by dalan; refusing to overwrite it`);
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Recheck at write time too, so a collision introduced after preflight is still refused.
|
|
144
|
+
export function writeAgentFile(file, text) {
|
|
145
|
+
if (!preflightAgentFile(file, text)) return false;
|
|
130
146
|
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o755 });
|
|
131
147
|
const temp = `${file}.${process.pid}.tmp`;
|
|
132
148
|
fs.writeFileSync(temp, text, { mode: 0o644 });
|
|
@@ -145,9 +161,11 @@ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
|
|
|
145
161
|
const { update } = launchdLabels(receipt.unit), file = path.join(receipt.unit_dir, `${update}.plist`);
|
|
146
162
|
if (enabled) {
|
|
147
163
|
fs.mkdirSync(path.join(home, 'logs'), { recursive: true, mode: 0o700 });
|
|
148
|
-
const
|
|
164
|
+
const text = updatePlist({ unit: receipt.unit, node: receipt.node ?? node, home });
|
|
165
|
+
const changed = preflightAgentFile(file, text);
|
|
149
166
|
if (changed) unloadAgent({ label: update }, seams);
|
|
150
|
-
|
|
167
|
+
writeAgentFile(file, text);
|
|
168
|
+
if (changed || !isLoaded(update, seams)) must(launchctl(['bootstrap', domainOf(seams), file], seams), `launchctl bootstrap ${file}`);
|
|
151
169
|
} else {
|
|
152
170
|
unloadAgent({ label: update }, seams);
|
|
153
171
|
fs.rmSync(file, { force: true });
|
|
@@ -157,6 +175,8 @@ export function setUpdateAgent({ receipt, home, node, enabled }, seams = {}) {
|
|
|
157
175
|
|
|
158
176
|
export function removeAgents({ unit, unit_dir: dir }, seams = {}) {
|
|
159
177
|
const { service, update } = launchdLabels(unit), removed = [];
|
|
178
|
+
// An unknown job must not allow even the other job's plist to be removed.
|
|
179
|
+
for (const label of [update, service]) isLoaded(label, seams);
|
|
160
180
|
for (const label of [update, service]) {
|
|
161
181
|
if (unloadAgent({ label }, seams)) removed.push(`unloaded ${label}`);
|
|
162
182
|
const file = path.join(dir, `${label}.plist`);
|