@tnunamak/dalan 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.mjs CHANGED
@@ -25,7 +25,7 @@ import { sendWebhook, validSecret } from './webhooks.mjs';
25
25
  import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
26
26
  import { redactOutput, redactSinkText, redactLogEntry, registerSecret } from './redaction.mjs';
27
27
  import { isCrash, safeDiagnostic } from './diagnostic.mjs';
28
- import { Workspace, NOT_IDENTIFIED } from './workspace.mjs';
28
+ import { Workspace, NOT_IDENTIFIED, pinnedScopedSource, SCOPED_SOURCE_MAX_BYTES } from './workspace.mjs';
29
29
  import { captureOwnerReportArtifact } from './owner-report-artifact.mjs';
30
30
  import { loadBackgroundMaxInFlight, loadMainThreadIds, t3ReadToolsOff } from './limits.mjs';
31
31
  import { parseDelivery } from './delivery.mjs';
@@ -39,7 +39,7 @@ import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
39
39
  import { preflightPR } from './pr-preflight.mjs';
40
40
  import { admitImplementation } from './check-readiness.mjs';
41
41
  import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
42
- import { loadCapacity } from './projects.mjs';
42
+ import { assignmentInput, loadCapacity } from './projects.mjs';
43
43
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
44
44
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
45
45
  import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
@@ -146,11 +146,12 @@ if(legacyProfile&&!existingInstall&&!explicitLegacy) {
146
146
  console.error(`dalan: startup: no worker is configured (${workersFile} is missing); run \`dalan init --worker NAME\` to create one, or \`dalan init --legacy\` (or set DALAN_LEGACY_PROFILE=1) to keep the single-worker legacy profile`);
147
147
  process.exit(1);
148
148
  }
149
+ let quiescing=false;
149
150
  const store = new Store(path.join(dataDir, 'bridge.db'),{
150
151
  // The caller sees one fixed configuration error; the real one stays in this server's log.
151
152
  onConfigError:error=>log({kind:'destination_configuration_error',reason:inspect(error,CONFIG_ERROR_INSPECT)}),
152
153
  workers,destinationProfile:currentRepoPolicy,allowedDotSubjects:externalOauth?externalOauth.OAUTH_ALLOWED_SUBJECTS.split(','):['local-principal'],
153
- limits:redeliveryLimits,
154
+ limits:redeliveryLimits,admissionOpen:()=>!quiescing,
154
155
  ...(process.env.CONFORMANCE_CLOCK_FILE?{elapsedNow:Date.now,bootId:'conformance-clock'}:{}),
155
156
  skipExpireMs:(h=>Number.isFinite(h)&&h>0?h*3600000:undefined)(Number(readEnv('DALAN_SKIP_EXPIRE_HOURS'))),
156
157
  // Intentional service startup opts past Store's accidental-migration footgun guard.
@@ -177,12 +178,62 @@ const absentId=`req_${randomUUID()}`;
177
178
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
178
179
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
179
180
  const guardArtifactDownload = createArtifactDownloadGuard({log});
181
+ const scopedSourceChunk=18*1024;
180
182
  const phaseTrace = createPhaseTrace({ log });
181
183
  logShutdownSignals(log);
182
184
  // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
183
185
  const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
184
186
  const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
185
187
  t3_post:t3PostHandler,
188
+ scoped_input_artifact:{
189
+ effectClass:'read',
190
+ requireCurrentRead:true,
191
+ validateConfig(_config,{name}) {
192
+ if(name!==scopedInputRegistration.name) throw new RegistryError('invalid_tool','unknown scoped input tool');
193
+ },
194
+ authorizeReplay({args,context}) {
195
+ const {worker,subject,builtin,connection_id}=context,connection=builtin?(connection_id??''):null;
196
+ const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
197
+ try {
198
+ if(!store.mayAct(worker,requestId)) throw new Error('assignment not found');
199
+ store.assertProtocolAvailable(requestId);
200
+ const row=store.get(requestId);
201
+ if(row.status!=='claimed'||row.cancelled_at) throw new Error('assignment is not claimed');
202
+ const claim=store.assertClaim(requestId,claimId,subject,worker);
203
+ store.assertMutationConnection(requestId,claim,connection);
204
+ if(row.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
205
+ if(!workspaceEnabled||!workerWorkspaceAllowed(worker,requestId)) throw new Error('capability_not_enabled');
206
+ assertRepoAllowed(worker,row.assignment);
207
+ return [requestId,claim.claim_id,claim.epoch,subject,connection];
208
+ } catch(error) { throw assignmentRegistryRefusal(error); }
209
+ },
210
+ run({args,context:{worker,subject}}) {
211
+ const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
212
+ const offset=args.offset??0;
213
+ if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
214
+ try {
215
+ const {a,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
216
+ if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
217
+ const {manifest,blobs}=pinnedScopedSource(mirror,a.assignment);
218
+ if(!manifest.files.length) throw new Error('no approved scoped input files');
219
+ const files=manifest.files.map(file=>{
220
+ const bytes=blobs.get(file.path);
221
+ guardArtifactDownload({bytes,sha256:file.sha256,id:'scoped-input-file',requestId});
222
+ return {...file,data_base64:bytes.toString('base64')};
223
+ });
224
+ const bytes=Buffer.from(JSON.stringify({...manifest,files}));
225
+ if(bytes.length>SCOPED_SOURCE_MAX_BYTES) throw new Error('scoped input exceeds the download limit; use a smaller scope');
226
+ const hash=createHash('sha256').update(bytes).digest('hex');
227
+ guardArtifactDownload({bytes,sha256:hash,id:'scoped-input',requestId});
228
+ if(args.sha256!==undefined&&args.sha256!==hash) throw new Error('scoped input changed');
229
+ if(offset>=bytes.length) throw new Error('invalid scoped input offset');
230
+ const end=Math.min(offset+scopedSourceChunk,bytes.length);
231
+ const result={sha256:hash,size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
232
+ if(JSON.stringify(redactOutput(result))!==JSON.stringify(result)) throw new Error('scoped input encoding refused');
233
+ return result;
234
+ } catch(error) { throw assignmentRegistryRefusal(error); }
235
+ },
236
+ },
186
237
  worker_refusal:{
187
238
  effectClass:'write',
188
239
  validateConfig(_config,{name}) {
@@ -321,6 +372,17 @@ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=n
321
372
  // Worker-written text in an owner read is masked on the way out. The database keeps the exact text, so a retried finish
322
373
  // with the same body stays the same finish.
323
374
  const maskText=value=>typeof value==='string'?redactOutput(value):value;
375
+ function repositoryReadScope(assignment) {
376
+ if(assignment?.execution_scope!=='read-only'||(!Array.isArray(assignment.read_paths)&&assignment.paged_read_scope!==true)||!assignment.scope_paths?.length) return {};
377
+ // Older stored requests can predate pinned-input validation. Do not claim a verified scope for those rows.
378
+ let input;
379
+ try { input=assignmentInput(assignment); } catch { return {}; }
380
+ const {github_repo,base_sha,head_sha,input_patch}=input;
381
+ const scope=assignment.paged_read_scope===true
382
+ ?{file_count:assignment.scope_paths.length,paged:true}
383
+ :{scope_paths:assignment.scope_paths};
384
+ return {repository_scope:{github_repo,base_sha,...(head_sha?{head_sha}:{}),...scope,...(input_patch?{includes_local_patch:true}:{})}};
385
+ }
324
386
  function maskedForOwner(response) {
325
387
  const out={...response};
326
388
  if(out.report) out.report={...out.report,summary:maskText(out.report.summary),result:maskText(out.report.result)};
@@ -513,6 +575,13 @@ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'da
513
575
  // Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
514
576
  const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
515
577
  if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
578
+ // Existing clients may still report these fields. Keep the frozen discovery schemas stable.
579
+ const advertisedTools=['stable','legacy-v46'].includes(catalogProfile)?tools.map(tool=>{
580
+ if(tool.name!=='finish') return tool;
581
+ const properties=Object.fromEntries(Object.entries(tool.inputSchema.properties)
582
+ .filter(([field])=>!['runs','session','run_limit'].includes(field)));
583
+ return {...tool,inputSchema:{...tool.inputSchema,properties}};
584
+ }):tools;
516
585
  // During an update, refuse a changed catalog before either listener can expose it.
517
586
  const catalogGuardFile=path.join(configDir,'service-catalog.json');
518
587
  if(fs.existsSync(catalogGuardFile)) {
@@ -521,7 +590,7 @@ if(fs.existsSync(catalogGuardFile)) {
521
590
  const guard=JSON.parse(fs.readFileSync(catalogGuardFile,'utf8'));
522
591
  const normalize=value=>Array.isArray(value)?value.map(normalize):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,normalize(value[key])])):value;
523
592
  const ordered=catalogs=>Object.fromEntries(Object.keys(catalogs).sort().map(worker=>[worker,[...catalogs[worker]].sort((a,b)=>a.name.localeCompare(b.name))]));
524
- const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):tools]));
593
+ const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?advertisedTools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):advertisedTools]));
525
594
  if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
526
595
  }
527
596
  const refusalRegistration={
@@ -534,9 +603,15 @@ const refusalRegistration={
534
603
  const refusalFinish={inputSchema:schema({
535
604
  ...refusalRegistration.inputSchema.properties,result:message,summary:message,outcome:{type:'string',enum:[PROVIDER_REFUSAL]},
536
605
  },['request_id','claim_id','result','outcome'])};
606
+ const scopedInputRegistration={
607
+ name:'fetch_scoped_input',
608
+ description:'Read the approved pinned files for this live assignment. Concatenate decoded data_base64 chunks until next_offset is null. For later calls pass that offset and the first sha256. Verify the assembled artifact hash before using the files. Omit idempotency_key.',
609
+ class:'read',handler:{kind:'scoped_input_artifact'},
610
+ inputSchema:schema({request_id:string,claim_id:string,offset:{type:'integer',minimum:0,maximum:SCOPED_SOURCE_MAX_BYTES},sha256:hashField},['request_id','claim_id']),
611
+ };
537
612
  if(toolNames.has('list_tools')) {
538
613
  const specs=[...questionDefinitions.map(definition=>({...definition,class:'write',handler:{kind:'worker_question'}})),refusalRegistration];
539
- for(const name of toolRegistry.initializeWorkerTools(specs,workers.workers.keys()))
614
+ for(const name of [...toolRegistry.initializeWorkerTools(specs,workers.workers.keys()),...toolRegistry.initializeWorkerTools([scopedInputRegistration],[])])
540
615
  log({kind:'worker_tool_registration_conflict',tool:name});
541
616
  }
542
617
  function assignmentRegistryRefusal(error) {
@@ -623,8 +698,8 @@ function breakWaitReply(breakId,requestIds,note) {
623
698
  request_ids:requestIds,artifact_ids:[],...store.breakForecast(breakId)};
624
699
  }
625
700
  function activeBreakWait(row) {
626
- if(row?.target_worker!=='dot'||!['queued','claimed'].includes(row.status)) return null;
627
- const active=store.holdingBreak();
701
+ if(!row||!['queued','claimed'].includes(row.status)) return null;
702
+ const active=store.holdingBreak(row.target_worker??'dot');
628
703
  return active?breakWaitReply(active.id,[row.request_id],'The worker is on a usage break.'):null;
629
704
  }
630
705
  function waitSummary(requestId, attention=null) {
@@ -773,23 +848,40 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
773
848
  waiters.set(requestId,waiter);
774
849
  notifyAttachedWaiter(requestId);
775
850
  }
851
+ function logPendingReply(reply,{worker,subject},callId,batch={}) {
852
+ log({kind:'list_pending_result',call_id:callId,worker,subject,free_lanes:reply.free_lanes,claims_accepted:reply.claims_accepted,
853
+ total:reply.assignments.length,request_ids:reply.assignments.slice(0,20).map(item=>item.request_id),...batch});
854
+ }
855
+
776
856
  // Put the next acquisition before job detail, including after progress and finish.
777
857
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
778
- function batchCapacityReply(name,reply,principal) {
779
- if(!batchClaimProfile||!['list_pending','claim','progress','finish'].includes(name)) return reply;
858
+ function batchCapacityReply(name,reply,principal,callId) {
859
+ if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
860
+ const recordListing=name==='list_pending'&&!!callId;
861
+ if(!batchClaimProfile) {
862
+ if(recordListing) logPendingReply(reply,principal,callId);
863
+ return reply;
864
+ }
780
865
  const {worker,subject}=principal;
781
- const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
782
- const ready_queued=store.listPending(worker,{batch:true}).filter(item=>!item.blocked).length;
866
+ const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
867
+ const ready_queued=ready.length;
783
868
  const hint=store.claimHint(worker);
784
- const hintFree=hint===null?Infinity:Math.max(0,hint-store.recentClaimCount(worker));
785
- const next=Math.min(free_lanes,ready_queued,8,hintFree);
786
- const next_action=quiescing?restartQuiesceText:store.paused()?'Claims are paused; call list_pending again later.':
787
- next>0?`claim with next=${next} now`:
788
- free_lanes===0?'Continue held work and finish one before claiming more.':
789
- ready_queued>0&&hintFree===0?'Lanes are free but the claim hint is full; claim again when the hint allows more.':
790
- 'No ready queued work; call list_pending again later.';
869
+ const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
870
+ const next=Math.min(available,ready_queued,8,hintFree);
871
+ const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
872
+ store.paused()?['paused','Claims are paused; call list_pending again later.']:
873
+ next>0?['ready',`claim with next=${next} now`]:
874
+ available===0?['lanes_full','Continue held work and finish one before claiming more.']:
875
+ ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
876
+ ['no_ready_work','No ready queued work; call list_pending again later.'];
791
877
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
792
- return {next_action,free_lanes,ready_queued,...rest};
878
+ const response={next_action,free_lanes,ready_queued,...rest};
879
+ if(recordListing) {
880
+ const recommended=reason==='ready'?next:0;
881
+ logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,
882
+ ready_head_ids:ready.slice(0,recommended).map(item=>item.request_id)});
883
+ }
884
+ return response;
793
885
  }
794
886
  // Result guidance only; tool descriptions stay fixed.
795
887
  const batchGuidance='Follow next_action for any additional acquisition; use a fresh acquisition_id for each new batch.';
@@ -1050,7 +1142,7 @@ async function submitPolicy(body,req,dryRun) {
1050
1142
  return {...result,execution,excluded_workers:excludedWorkers};
1051
1143
  }
1052
1144
 
1053
- let quiescing=false,admittedInFlight=0;
1145
+ let admittedInFlight=0;
1054
1146
  const restartQuiesceText='bridge_quiescing: bridge paused for a restart; retry after it reopens.';
1055
1147
  function quiesceStatus() {
1056
1148
  return {on:quiescing,admitted_in_flight:admittedInFlight,delivery_in_flight:delivering?1:0,...store.quiesceCounts()};
@@ -1197,24 +1289,24 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1197
1289
  catch(e) { if(e instanceof RegistryError) throw new Error(e.message.startsWith(e.code)?e.message:`${e.code}: ${e.message}`); throw e; }
1198
1290
  }
1199
1291
  case 'list_pending': {
1200
- const {free_lanes,worker_max_claims}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1292
+ const {free_lanes,worker_max_claims,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1201
1293
  const assignments=store.listPending(worker);
1202
- store.recordListed(assignments,free_lanes,worker,!quiescing);
1294
+ store.recordListed(assignments,free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1203
1295
  phaseTrace.listed(assignments.map(x=>x.request_id));
1204
- log({kind:'list_pending_result',subject,free_lanes,total:assignments.length,request_ids:assignments.slice(0,20).map(x=>x.request_id)});
1205
1296
  const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1206
1297
  const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
1207
1298
  // Say outright whether a claim would be accepted now: a worker that once saw a pause refusal must not keep listing without claiming.
1208
1299
  const claims_accepted=!quiescing&&!store.paused();
1209
- const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
1300
+ const next=claims_accepted?store.nextQueued(free_lanes,null,worker,{reservedId:reserved_request_id??null}):{};
1210
1301
  const claimsNote=claims_accepted?'':quiescing?restartQuiesceText:'Claims are paused (temporary): do not claim now; call list_pending again later and claim once claims_accepted is true.';
1211
- return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,...(worker_max_claims===undefined?{}:{worker_max_claims}),claims_accepted,...(claims_accepted?next:{next_action:claimsNote}),guidance};
1302
+ return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,...(worker_max_claims===undefined?{}:{worker_max_claims}),claims_accepted,...(claims_accepted&&reserved_request_id?{reserved_request_id}:{}),...(claims_accepted?next:{next_action:claimsNote}),guidance};
1212
1303
  }
1213
1304
  case 'claim': {
1214
1305
  if(Object.hasOwn(a,'next')) {
1215
1306
  const claimant=str(a.claimant,'claimant',128);
1216
1307
  const lanes=()=>store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
1217
- const {claims,retry}=await store.claimBatch({next:a.next,available:lanes(),worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1308
+ const {available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1309
+ const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1218
1310
  (request_id,acquisition_id,mode)=>signal?.aborted?null:tool('claim',{request_id,claimant,acquisition_id,...(a.lease_ms===undefined?{}:{lease_ms:a.lease_ms})},principal,undefined,signal,mode));
1219
1311
  return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1220
1312
  }
@@ -1245,8 +1337,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1245
1337
  const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
1246
1338
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1247
1339
  if(!retry) phaseTrace.claimed({requestId,worker,subject,claimId:claimed.claim_id,handoff:String(a.acquisition_id??'').startsWith(HANDOFF_ACQUISITION_PREFIX),createdAt:store.db.prepare('SELECT created_at FROM assignments WHERE request_id=?').get(requestId)?.created_at});
1248
- const {free_lanes,queued}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1249
- 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} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1340
+ const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1341
+ 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,{reservedId:reserved_request_id??null}),guidance:`${claimed.guidance} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1250
1342
  }
1251
1343
  case 'renew_claim': {
1252
1344
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1286,12 +1378,15 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1286
1378
  store.assertFinishClaim(requestId,claimId,subject,worker);
1287
1379
  // A replaced or revoked connection learns connection_not_live before any question or artifact error. Read-only; expired and foreign claims return early.
1288
1380
  workspaceFence();
1381
+ store.applyFacadeWithdrawal(requestId);
1289
1382
  const existing=store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(requestId);
1290
1383
  let captureEvidence=null;
1291
1384
  const workerRuns=parseWorkerRuns(a.runs,a.run_limit,redactOutput), workerSession=parseWorkerSession(a.session,store.nowMs());
1292
1385
  if(!existing) {
1293
1386
  store.assertQuestionsResolved(requestId,claimId,a.outcome);
1294
1387
  const request=store.get(requestId);
1388
+ const pagedRead=request.assignment.paged_read_scope===true;
1389
+ if(pagedRead&&a.artifact_ids?.length) throw new Error('paged read scope does not support artifacts');
1295
1390
  const needsWorkspace=workspaceEnabled&&(a.artifact_ids?.length||request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length);
1296
1391
  const assignmentNeedsWorkspace=request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length;
1297
1392
  const requiredWorkspaceEvidence=!!(a.artifact_ids?.length||request.assignment.output_paths?.length);
@@ -1313,7 +1408,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1313
1408
  if(workerWorkspaceEnabled&&request.status==='claimed'&&a.outcome==='completed') { await workspace.checkBeforeFinish(requestId,claimId,subject,worker);workspaceFence(); }
1314
1409
  if(workerWorkspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
1315
1410
  captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
1316
- if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
1411
+ if(!pagedRead&&request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
1317
1412
  const archiveWorkspace=workspace??new Workspace(store,false),snapshot=captureEvidence;
1318
1413
  captureEvidence=onRollback=>{
1319
1414
  const base=snapshot?snapshot(onRollback):null;
@@ -1322,7 +1417,13 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1322
1417
  };
1323
1418
  }
1324
1419
  }
1325
- if(!existing) { store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession); }
1420
+ if(!existing) {
1421
+ const capture=captureEvidence;
1422
+ captureEvidence=onRollback=>{
1423
+ store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession);
1424
+ return capture?.(onRollback)??null;
1425
+ };
1426
+ }
1326
1427
  const receipt=store.finish(requestId,claimId,a.outcome,str(a.summary,'summary',4096),str(a.result,'result',256*1024),subject,null,worker,commandContext('finish',{artifact_ids:a.artifact_ids??[]}),captureEvidence,connectionId);
1327
1428
  if(receipt.deferred) return {...receipt,...repaired.marks};
1328
1429
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
@@ -1391,7 +1492,7 @@ function publicErrorText(error,what) {
1391
1492
  log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
1392
1493
  return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
1393
1494
  }
1394
- async function dispatch(message,principal,signal) {
1495
+ async function dispatch(message,principal,signal,callId) {
1395
1496
  const p=message.params??{};
1396
1497
  switch(message.method) {
1397
1498
  case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
@@ -1399,8 +1500,8 @@ async function dispatch(message,principal,signal) {
1399
1500
  case 'ping': return {};
1400
1501
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1401
1502
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1402
- 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};
1403
- case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal)))}],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; } }
1503
+ case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?advertisedTools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):advertisedTools};
1504
+ case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal,callId)))}],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; } }
1404
1505
  case 'events/list': return {events:[event]};
1405
1506
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1406
1507
  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 {}; }
@@ -1446,7 +1547,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1446
1547
  const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
1447
1548
  // A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
1448
1549
  const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
1449
- try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal)}},eventStream); }
1550
+ try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal,outcome.state.call_id)}},eventStream); }
1450
1551
  catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
1451
1552
  // Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
1452
1553
  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}); }
@@ -1488,7 +1589,7 @@ const adminServer=http.createServer(async(req,res)=>{
1488
1589
  if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
1489
1590
  const commandKey=body.command_key===undefined?null:body.command_key;
1490
1591
  const supersedes=body.supersedes===undefined?null:body.supersedes;
1491
- // {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
1592
+ // The Store checks correction authority before preview, and again in the submit transaction.
1492
1593
  const revises=body.revises===undefined?null:body.revises;
1493
1594
  const follows=body.follows===undefined?null:body.follows;
1494
1595
  const destinationRevision=body.destination_revision??null;
@@ -1534,6 +1635,7 @@ const adminServer=http.createServer(async(req,res)=>{
1534
1635
  const dryRun=url.pathname==='/submit-preview';
1535
1636
  if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
1536
1637
  if(body.assignment&&Object.hasOwn(body.assignment,'scope_excluded')) throw new Error('assignment declares scope_excluded; only the bridge records what it dropped from a scope');
1638
+ if(body.assignment&&Object.hasOwn(body.assignment,'paged_read_scope')) throw new Error('only the bridge can record a paged read scope');
1537
1639
  const declaredSource=body.meta?.source??'agent';
1538
1640
  for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,declaredSource);
1539
1641
  const meta=normalizeMeta(body.meta);
@@ -1563,6 +1665,9 @@ const adminServer=http.createServer(async(req,res)=>{
1563
1665
  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,follows,body.caller_waiting);
1564
1666
  let order=null;
1565
1667
  if(isNew) {
1668
+ // checkRetry has already verified the prior owner's capability and the active worker.
1669
+ const priorAssignment=revises?.require_active_prior===true?store.get(revises.prior_id).assignment:null;
1670
+ const inheritedExclusions=priorAssignment?.scope_excluded;
1566
1671
  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,
1567
1672
  excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
1568
1673
  render:renderAssignment,
@@ -1572,7 +1677,9 @@ const adminServer=http.createServer(async(req,res)=>{
1572
1677
  // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
1573
1678
  if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
1574
1679
  },
1575
- 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'}),
1680
+ 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',inheritedExclusions,
1681
+ allowPagedReadScope:workspaceEnabled&&jobExecution==='none'&&!p.protocol,
1682
+ pagedReadPrior:priorAssignment?.paged_read_scope===true?priorAssignment:null}),
1576
1683
  admitReadiness:p=>{
1577
1684
  if(p.execution_scope!=='implementation') return null;
1578
1685
  const readiness=admitImplementation(p,{execution:jobExecution,worker:storedTarget??target??'dot'});
@@ -1581,7 +1688,7 @@ const adminServer=http.createServer(async(req,res)=>{
1581
1688
  },
1582
1689
  preflight:p=>preflightPR(p),
1583
1690
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1584
- state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:(r.target==='dot'?store.holdingBreak():null),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n,queued_same_priority:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,body.background===true?'background':'normal',body.caller_waiting===true?1:0,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
1691
+ state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:store.holdingBreak(r.target),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n,queued_same_priority:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,body.background===true?'background':'normal',body.caller_waiting===true?1:0,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
1585
1692
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1586
1693
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1587
1694
  retryAfterSeconds:r=>{const w=store.queueWaitsMs(r.target,r.meta?.task_kind??(r.review?'review':'unknown'));return w.length?Math.min(3600,Math.max(60,Math.round(w[Math.floor(w.length/2)]/1000))):300;},
@@ -1597,7 +1704,8 @@ const adminServer=http.createServer(async(req,res)=>{
1597
1704
  const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
1598
1705
  if(dryRun) {
1599
1706
  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});
1600
- return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(payload?{admission:admission()}:{}),...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
1707
+ const scope=!order||order.verdict==='admissible'?repositoryReadScope(existingRequest?.assignment??payload):{};
1708
+ return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(payload?{admission:admission()}:{}),...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...scope,...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
1601
1709
  }
1602
1710
  // Defer refuses only for a requester that opts in; both the CLI and HTTP API queue by default.
1603
1711
  if(order?.verdict==='defer'&&body.refuse_defer===true&&body.queue_anyway!==true) {
@@ -1608,6 +1716,11 @@ const adminServer=http.createServer(async(req,res)=>{
1608
1716
  const readiness=order?.check_readiness??null;
1609
1717
  const preflight=order?.preflight??null;
1610
1718
  const defaultValidity=order?.defaultValidity??null;
1719
+ if(body.facade_submit_until!==undefined&&!store.hasAssignment(payload.request_id)) {
1720
+ const until=body.facade_submit_until;
1721
+ if(!Number.isSafeInteger(until)||until>requestStartedAt+600_000) throw new Error('invalid facade submission deadline');
1722
+ if(until<=store.nowMs()) throw new Error('facade submission deadline expired');
1723
+ }
1611
1724
  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,follows,body.caller_waiting);
1612
1725
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1613
1726
  if(supersedes&&!result.duplicate) {
@@ -1618,7 +1731,8 @@ const adminServer=http.createServer(async(req,res)=>{
1618
1731
  // A retry validates nothing, so the narrowing it reports comes from the stored assignment.
1619
1732
  const stored=result.duplicate?JSON.parse(store.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(payload.request_id).payload):payload;
1620
1733
  if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
1621
- return json(res,200,{...result,admission:admission(),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}:{})});
1734
+ const observedAdmission=store.admissionForQueuedRequest(payload.request_id)??admission();
1735
+ return json(res,200,{...result,admission:observedAdmission,execution:store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(payload.request_id).execution,...repositoryReadScope(stored),...(stored.scope_excluded?.length?{scope_excluded:stored.scope_excluded,scope_paths:stored.scope_paths}:{}),...(readiness?{check_readiness:readiness}:{}),...(submissionWarnings.length?{submission_warnings:submissionWarnings}:{})});
1622
1736
  }
1623
1737
  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'}:{})}); }
1624
1738
  if(url.pathname==='/get') {
@@ -1630,6 +1744,7 @@ const adminServer=http.createServer(async(req,res)=>{
1630
1744
  store.recordFetched(requestId);
1631
1745
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1632
1746
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1747
+ Object.assign(got,repositoryReadScope(got.assignment));
1633
1748
  if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
1634
1749
  const snapshot=store.admissionForQueuedRequest(requestId);
1635
1750
  if(snapshot) got.admission=snapshot;
@@ -1647,6 +1762,7 @@ const adminServer=http.createServer(async(req,res)=>{
1647
1762
  const row=store.db.prepare('SELECT request_id FROM artifacts WHERE id=? AND sealed=1').get(artifactId);
1648
1763
  if(!row) throw new Error('artifact not found');
1649
1764
  adminOwner(req,row.request_id);
1765
+ if(store.get(row.request_id).assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
1650
1766
  const artifact=(workspace||new Workspace(store,false)).artifact(artifactId,row.request_id);
1651
1767
  try {
1652
1768
  guardArtifactDownload({id:artifactId,requestId:row.request_id,sha256:artifact.row.sha256,bytes:artifact.bytes});
@@ -1690,9 +1806,9 @@ const adminServer=http.createServer(async(req,res)=>{
1690
1806
  const states=body.items.map(item=>{
1691
1807
  const requestId=id(item?.id);
1692
1808
  try { store.owner(requestId,item.capability); } catch { return {request_id:requestId,error:'not_owned'}; }
1693
- const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)??(store.pullQueue.row(requestId)?store.get(requestId):null);
1809
+ const row=store.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(requestId)??(store.pullQueue.row(requestId)?store.get(requestId):null);
1694
1810
  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));
1695
- return {request_id:requestId,status:row.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
1811
+ return {request_id:requestId,status:row.status,worker_break:!!activeBreakWait({...row,request_id:requestId}),blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
1696
1812
  });
1697
1813
  // Only evidence holds refill: a pause or an owner-confirmed break. throttled stays false for older readers.
1698
1814
  const paused=store.paused(), dotBreak=!!store.holdingBreak();
@@ -1710,7 +1826,7 @@ const adminServer=http.createServer(async(req,res)=>{
1710
1826
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1711
1827
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1712
1828
  }
1713
- if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),default_worker:workers.legacy ? 'dot' : workers.workers.size === 1 ? [...workers.workers.keys()][0] : null,...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
1829
+ if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),default_worker:workers.legacy ? 'dot' : workers.workers.size === 1 ? [...workers.workers.keys()][0] : null,...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,version:packageVersion,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
1714
1830
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1715
1831
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1716
1832
  const requestId=id(body.id); adminOwner(req,requestId);
@@ -1813,7 +1929,7 @@ const adminServer=http.createServer(async(req,res)=>{
1813
1929
  if(req.method==='POST') {
1814
1930
  if(typeof body.on!=='boolean')return json(res,400,{error:'on must be a boolean'});
1815
1931
  // Clear the old eligibility at entry too: an interrupted quiesce may never receive an off call.
1816
- if(body.on!==quiescing) store.restartSkipClock();
1932
+ if(body.on!==quiescing) store.restartSkipClock({releaseReservations:body.on});
1817
1933
  quiescing=body.on;
1818
1934
  }
1819
1935
  return json(res,200,quiesceStatus());
@@ -1826,6 +1942,28 @@ const adminServer=http.createServer(async(req,res)=>{
1826
1942
  runDrain();
1827
1943
  return json(res,200,{...result,scope:controlScopeText('detach',{ref:`claim:${result.abandoned.claim_id}@${result.abandoned.epoch}`})});
1828
1944
  }
1945
+ if(url.pathname==='/cancel-grace'&&req.method==='POST') {
1946
+ const requestId=id(body.id);
1947
+ const intent=id(body.intent,'intent');
1948
+ if(body.before_admission===true&&!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)&&['arm','keep','state'].includes(body.action)) {
1949
+ const token=str(req.headers['x-owner-capability'],'owner capability',128);
1950
+ if(token.length<32) throw new Error('invalid owner capability');
1951
+ return json(res,200,store.facadeWithdrawalBeforeAdmission(requestId,intent,body.action,token));
1952
+ }
1953
+ adminOwner(req,requestId);
1954
+ if(body.action==='arm') return json(res,200,store.armFacadeWithdrawal(requestId,intent));
1955
+ if(body.action==='keep') return json(res,200,store.keepFacadeWork(requestId,intent));
1956
+ if(body.action==='state') return json(res,200,{kept:!!store.facadeKeepReceipt(requestId,intent)});
1957
+ if(body.action==='settle') {
1958
+ const kept=!!store.facadeKeepReceipt(requestId,intent);
1959
+ const pending=!!store.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=? AND intent=?').get(requestId,intent);
1960
+ if(pending) store.applyFacadeWithdrawal(requestId);
1961
+ const status=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)?.status;
1962
+ if(status==='cancelled') notifyAttachedWaiter(requestId);
1963
+ return json(res,200,{kept,pending,status});
1964
+ }
1965
+ throw new Error('invalid cancellation grace action');
1966
+ }
1829
1967
  if(url.pathname==='/cancel') {
1830
1968
  const requestId=id(body.id); adminOwner(req,requestId);
1831
1969
  // Read before the cancel: the scope text depends on whether a worker held the job.
@@ -1840,7 +1978,8 @@ const adminServer=http.createServer(async(req,res)=>{
1840
1978
  }
1841
1979
  if(url.pathname==='/break'&&req.method==='POST') {
1842
1980
  adminOperator(req);
1843
- if(body.clear===true) { const cleared=store.clearBreak(); sweepExpired(); return json(res,200,cleared); }
1981
+ const worker=body.worker===undefined?'dot':assertTarget(workers,body.worker);
1982
+ if(body.clear===true) { const cleared=store.clearBreak(worker); sweepExpired(); return json(res,200,cleared); }
1844
1983
  const time=field=>{
1845
1984
  const value=body[field];
1846
1985
  if(value==null) return value;
@@ -1848,7 +1987,7 @@ const adminServer=http.createServer(async(req,res)=>{
1848
1987
  throw new Error(`${field} must be an RFC 3339 time with offset`);
1849
1988
  return new Date(value).toISOString();
1850
1989
  };
1851
- const result=store.setBreak(str(body.reason,'reason',512),time('since'),time('until'));
1990
+ const result=store.setBreak(str(body.reason,'reason',512),time('since'),time('until'),worker);
1852
1991
  log({kind:'worker_break_set',source:'owner',since:result.since});
1853
1992
  return json(res,200,result);
1854
1993
  }
@@ -1858,7 +1997,11 @@ const adminServer=http.createServer(async(req,res)=>{
1858
1997
  adminOperator(req); if(body.clear!==true) throw new Error('learned accepts only {clear:true}');
1859
1998
  const result=store.clearLearnedLimits(); log({kind:'learned_limits_cleared',source:'owner',removed:result.removed}); return json(res,200,result);
1860
1999
  }
1861
- if(url.pathname==='/breaks'&&req.method==='GET') { adminOperator(req); return json(res,200,{worker_break:store.breakState(),breaks:store.breaks()}); }
2000
+ if(url.pathname==='/breaks'&&req.method==='GET') {
2001
+ adminOperator(req);
2002
+ const worker=url.searchParams.has('worker')?assertTarget(workers,url.searchParams.get('worker')):'dot';
2003
+ return json(res,200,{worker_break:store.breakState(worker),breaks:worker==='dot'?store.breaks():store.scopedBreaks(worker)});
2004
+ }
1862
2005
  if(url.pathname==='/verify-stops'&&req.method==='POST') {
1863
2006
  adminOperator(req);
1864
2007
  const requestId=body.id===undefined?undefined:id(body.id);
@@ -2012,6 +2155,13 @@ async function drain() {
2012
2155
  }
2013
2156
  function maintain() {
2014
2157
  try {
2158
+ for(const requestId of store.dueFacadeWithdrawals()) {
2159
+ try {
2160
+ if(!store.applyFacadeWithdrawal(requestId)) continue;
2161
+ const waiter=waiters.get(requestId);
2162
+ if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); }
2163
+ } catch(error) { log({kind:'facade_withdrawal_error',request_id:requestId,reason:error.message}); }
2164
+ }
2015
2165
  sweepExpired();
2016
2166
  sweepSkipped();
2017
2167
  sweepStaleLeases();