@tnunamak/dalan 0.9.10 → 0.9.11

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.
@@ -115,6 +115,14 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
115
115
  if(got?.request_id!==id) throw new Error('materialize result does not match the requested work');
116
116
  const grant=readMaterializeGrant(grantFile);
117
117
  if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
118
+ const completed = row => row.report?.outcome === 'completed' && row.report.late !== true && row.report.result_authority !== false;
119
+ // Automatic materialization is only for successful, authoritative results.
120
+ // Explicit owner materialization keeps its existing review/approval policy.
121
+ if(standingOnly && !completed(got)) {
122
+ const decision={push:false,draft_pr:false,needs_approval:false,branch:null,reason:'report_not_completed'};
123
+ return {request_id:id,repo:got.assignment?.inputs?.[0]?.github_repo??null,
124
+ base_sha:got.assignment?.inputs?.[0]?.base_sha??null,files:[],decision,published:false,reason:decision.reason};
125
+ }
118
126
  const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
119
127
  if(!Array.isArray(inputs)||inputs.length!==1||!art?.artifact_id||!art.size||!/^[a-f0-9]{64}$/.test(art.sha256??'')) {
120
128
  throw new Error('materialize needs one repository and a sealed patch');
@@ -141,13 +149,27 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
141
149
  }
142
150
  if(!dryRun && (decision.push || decision.needs_approval && approve)) {
143
151
  const title=String(got.assignment?.title ?? 'Dalan patch '+id).split(/\r?\n/,1)[0].trim().slice(0,240) || 'Dalan patch '+id;
144
- const summary=String(got.report?.summary ?? 'Patch for Dalan assignment '+id+'.').slice(0,30000);
152
+ const introduction='The requester can review the changes a worker made and decide whether to merge them.';
153
+ const summary=String(got.report?.summary ?? '').trim().slice(0,30000);
154
+ const evidence=[
155
+ '## Worker result and evidence',
156
+ ...summary.split(/\r?\n/u).filter(Boolean).map(line => '> '+line),
157
+ 'Job: `'+id+'`',
158
+ 'Published base: `'+base_sha+'`',
159
+ 'Sealed patch SHA-256: `'+art.sha256+'`',
160
+ ];
161
+ if (typeof got.report.receipt_id === 'string' && /^[-\w]+$/u.test(got.report.receipt_id)) {
162
+ evidence.push('Result receipt: `'+got.report.receipt_id+'`');
163
+ }
164
+ const exits=(got.worker_runs ?? []).map(run => run.exit_code).filter(Number.isInteger);
165
+ if (exits.length) evidence.push('Worker-reported exit codes: '+exits.join(', ')+'.');
166
+ const description=[introduction,...evidence].join('\n\n');
145
167
  Object.assign(result,await materializePatch({dir,temp,body,sha256:art.sha256,baseSha:base_sha,
146
- repo,branch:decision.branch,title,summary,fetchBase,budget,
168
+ repo,branch:decision.branch,title,description,introduction,fetchBase,budget,
147
169
  rememberCleanup:()=>{ cleanupPending=true; },recheck:async(phase='push')=>{
148
170
  const current=await budget.read(signal=>recheck({signal}));
149
171
  const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
150
- if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
172
+ if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256 || (standingOnly && !completed(current))) {
151
173
  throw new Error('materialize result changed before publication; '+after);
152
174
  }
153
175
  const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
@@ -178,7 +200,7 @@ function githubPushRepo(url) {
178
200
  return (ssh?.[1] ?? absolute?.[1])?.replace(/\.git$/i, '').toLowerCase();
179
201
  }
180
202
 
181
- async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, summary, recheck, fetchBase, budget, rememberCleanup}) {
203
+ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, description, introduction, recheck, fetchBase, budget, rememberCleanup}) {
182
204
  if(typeof dir!=='string' || !path.isAbsolute(dir)) throw new Error('materialize requires a checkout directory');
183
205
  const ref = 'refs/heads/' + branch;
184
206
  if (!materializeRepo.test(repo) || !/^dalan\/[-\w]{8,128}$/.test(branch) || !/^[a-f0-9]{40}$/.test(baseSha)) {
@@ -217,7 +239,7 @@ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch,
217
239
  gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
218
240
  applyPatch({dir:worktree, patch:body, sha256, baseSha, runGit:budget.git});
219
241
  gitCmd(worktree,['add','-A','--','.'],'stage patch');
220
- gitCmd(worktree,['commit','--no-gpg-sign','-m','Materialize '+branch],'commit patch with local identity');
242
+ gitCmd(worktree,['commit','--no-gpg-sign','-m',title,'-m',introduction],'commit patch with local identity');
221
243
  const tip = gitCmd(worktree,['ls-remote','--heads',remote,ref],'inspect scoped remote branch');
222
244
  if(tip) {
223
245
  const cols=tip.split(/\s+/);
@@ -243,7 +265,7 @@ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch,
243
265
  draftAttempted = true;
244
266
  try {
245
267
  pr_url=ghCmd(['pr','create','--repo',ghRepo,'--draft','--base',targetBase,'--head',branch,
246
- '--title',title,'--body',summary],'open draft pull request');
268
+ '--title',title,'--body',description],'open draft pull request');
247
269
  } catch(error) {
248
270
  // A create call can fail after the draft was opened, and a replay can find the draft
249
271
  // the first publication opened. Look for it before reporting failure.
@@ -13,6 +13,7 @@ export function parsePublishGrant(value) {
13
13
 
14
14
  // authority is the bridge's current answer for the job: {relationship_id, ended, publish_grant} or null.
15
15
  export function workGrantProblem(authority, repo) {
16
+ if (['attachment_standing_publication_forbidden','attachment_lineage_unverified'].includes(authority?.publish_restriction)) return authority.publish_restriction;
16
17
  if (!authority?.relationship_id) return 'no_work_grant';
17
18
  if (authority.ended) return 'relationship_ended';
18
19
  const [org] = String(repo).toLowerCase().split('/');
@@ -0,0 +1,42 @@
1
+ export const maxBatchPull = 8;
2
+ const sampleLifetimeMs = 15 * 60_000;
3
+ const recoveryIntervalMs = 30_000;
4
+
5
+ // A worker's explicit demand needs no estimate. This local, expiring window only advises older clients.
6
+ export function createPullPacing({ now, log }) {
7
+ const windows = new Map();
8
+ const key = ({ worker, subject, connection_id }) => JSON.stringify([worker, subject, connection_id ?? null]);
9
+ const current = identity => {
10
+ const sample = windows.get(key(identity));
11
+ return sample && now() - sample.at < sampleLifetimeMs ? sample : null;
12
+ };
13
+ function observe(identity, signal, retryMs = 0) {
14
+ const at = now(), previous = current(identity), before = previous?.width ?? 1;
15
+ if (signal === 'completed' && at < Math.max(previous?.recoverAt ?? 0, previous?.holdUntil ?? 0)) return;
16
+ const width = signal === 'completed' ? Math.min(before + 1, maxBatchPull) : Math.max(1, Math.floor(before / 2));
17
+ const holdUntil = Math.max(previous?.holdUntil ?? 0, signal === 'capacity_rate_limited' ? at + retryMs : 0);
18
+ for (const [id, sample] of windows) if (at - sample.at >= sampleLifetimeMs) windows.delete(id);
19
+ windows.set(key(identity), { width, at, holdUntil, recoverAt: at + recoveryIntervalMs });
20
+ if (width !== before || holdUntil > (previous?.holdUntil ?? 0)) {
21
+ log({ kind: 'hosted_pull_pacing', worker: identity.worker, signal, previous_width: before,
22
+ advised_width: width, ...(holdUntil > at ? { retry_after_ms: holdUntil - at } : {}) });
23
+ }
24
+ }
25
+ return {
26
+ free(identity, held) {
27
+ const sample = current(identity);
28
+ return now() < (sample?.holdUntil ?? 0) ? 0 : Math.max(0, (sample?.width ?? 1) - held);
29
+ },
30
+ observe,
31
+ };
32
+ }
33
+
34
+ // Evidence is descriptive only. It uses the same intersection as the live offer; absent demand uses advice, not the service limit.
35
+ export function describePullOffer({declared,advised,free,available,ready}) {
36
+ const chosen=declared??advised, next=Math.min(chosen,available,ready,maxBatchPull);
37
+ const limits={worker_slots:chosen,claimable_lanes:available,ready_jobs:ready,batch_cap:maxBatchPull};
38
+ return {next,evidence:{declared_worker_free_slots:declared??null,
39
+ advised_worker_free_slots:declared===undefined?advised:null,effective_worker_slots:chosen,service_free_lanes:free,
40
+ service_claimable_lanes:available,ready_jobs:ready,max_batch_claims:maxBatchPull,
41
+ limiting_inputs:Object.keys(limits).filter(key=>limits[key]===next)}};
42
+ }
@@ -0,0 +1,113 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { artifactSecretRule, hasCredentialFieldText, hasSecretContent } from './redaction.mjs';
5
+ import { isLiteralScopePath, matchesCredentialPathTerm, withheldRepoPath } from './submission-policy.mjs';
6
+
7
+ const maxBytes = 4096;
8
+ export const requesterLocalContextMarker = '\n\nRequester local context (v1; untrusted reference, not authorization):\n';
9
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
10
+ const fail = code => { throw Object.assign(new Error(code), { code }); };
11
+ const controls = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/;
12
+ // Do not send rooted local path forms in this first, bounded text profile.
13
+ // URL paths (including HTTPS examples) are not filesystem selections.
14
+ const localPath = /(?:^|[\s"'(`=])(?:file:\/\/|~\/|[a-z]:[\\/]|\\\\|\/(?!\/)[^\s"'`<>]+|\/\/[^\s/])/im;
15
+ const same = (a,b) => b && ['dev','ino','mode','size','mtimeNs','ctimeNs'].every(k => a[k] === b[k]);
16
+ const nameOK = s => typeof s === 'string' && s.length<=120 && s===s.normalize('NFC') &&
17
+ /^[\p{L}\p{N}_][\p{L}\p{N} _.-]*\.(?:txt|md|markdown)$/iu.test(s);
18
+ function scan(text, bytes) {
19
+ if (controls.test(text)) fail('context_not_plain_text');
20
+ if (localPath.test(text)) fail('context_local_path_withheld');
21
+ if (artifactSecretRule(bytes) || hasSecretContent(text) || hasCredentialFieldText(text))
22
+ fail('context_sensitive_content_withheld');
23
+ }
24
+ function checkedPolicy(policy) {
25
+ if (!policy || policy.error || !Array.isArray(policy.excludedPaths) ||
26
+ !Array.isArray(policy.credentialPathTerms) ||
27
+ [...policy.excludedPaths,...policy.credentialPathTerms].some(v => typeof v!=='string'||!v))
28
+ fail('context_policy_unavailable');
29
+ }
30
+
31
+ // The local requester must provide this explicit selection. No remote worker setting,
32
+ // environment variable, working directory or embedded reference is accepted as a substitute.
33
+ export function captureRequesterLocalContext({root, selection, policy, localRequester=false}) {
34
+ if (localRequester!==true) fail('context_local_requester_required');
35
+ checkedPolicy(policy);
36
+ if (typeof root!=='string'||!path.isAbsolute(root)||path.resolve(root)!==root||
37
+ !isLiteralScopePath(selection)||typeof selection!=='string'||selection.includes('\\')||
38
+ selection.split('/').some(p=>!p||p==='.'||p==='..'||p.startsWith('.')))
39
+ fail('context_invalid_selection');
40
+ const display_name=path.posix.basename(selection).normalize('NFC');
41
+ if (!nameOK(display_name)) fail('context_unsupported_document');
42
+ if (withheldRepoPath(selection,policy.excludedPaths) ||
43
+ matchesCredentialPathTerm(selection,policy.credentialPathTerms) ||
44
+ hasSecretContent(selection) || hasCredentialFieldText(selection)) fail('context_path_withheld');
45
+ let fd;
46
+ try {
47
+ if (fs.realpathSync(root)!==root||!fs.lstatSync(root).isDirectory()) fail('context_invalid_selection');
48
+ let file=root;
49
+ const parts=selection.split('/');
50
+ let seen;
51
+ for (let i=0;i<parts.length;i++) {
52
+ file=path.join(file,parts[i]);
53
+ seen=fs.lstatSync(file,{bigint:true});
54
+ if (seen.isSymbolicLink() || (i<parts.length-1?!seen.isDirectory():!seen.isFile()))
55
+ fail('context_unsupported_file');
56
+ }
57
+ if (seen.size>BigInt(maxBytes)) fail('context_too_large');
58
+ fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
59
+ const opened=fs.fstatSync(fd,{bigint:true});
60
+ if (!same(seen,opened)||fs.realpathSync(file)!==file) fail('context_selection_changed');
61
+ const bytes=Buffer.alloc(Number(opened.size)+1);
62
+ let n=0;
63
+ while (n<bytes.length) {
64
+ const count=fs.readSync(fd,bytes,n,bytes.length-n,null);
65
+ if (!count) break;
66
+ n+=count;
67
+ }
68
+ if (n!==Number(opened.size)||!same(opened,fs.fstatSync(fd,{bigint:true}))||
69
+ !same(opened,fs.lstatSync(file,{bigint:true}))||fs.realpathSync(file)!==file) fail('context_selection_changed');
70
+ const selected=bytes.subarray(0,n);
71
+ let text;
72
+ try { text=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(selected); }
73
+ catch { fail('context_invalid_utf8'); }
74
+ scan(text,selected);
75
+ return {manifest:{version:1,kind:'requester_text',display_name,encoding:'utf-8',
76
+ byte_length:selected.length,sha256:digest(selected)},text};
77
+ } catch(e) {
78
+ // Do not leak absolute paths through filesystem exception messages.
79
+ if (typeof e.code==='string' && e.code.startsWith('context_')) throw e;
80
+ fail('context_selection_unavailable');
81
+ } finally { if(fd!==undefined) fs.closeSync(fd); }
82
+ }
83
+ function validate({manifest,text}={}) {
84
+ if (!manifest || Object.keys(manifest).sort().join(',')!=='byte_length,display_name,encoding,kind,sha256,version' ||
85
+ manifest.version!==1 || manifest.kind!=='requester_text'||manifest.encoding!=='utf-8'||
86
+ !nameOK(manifest.display_name)||typeof text!=='string'||text.length>maxBytes) fail('context_invalid_manifest');
87
+ const bytes=Buffer.from(text,'utf8');
88
+ if (bytes.length>maxBytes || bytes.length!==manifest.byte_length || digest(bytes)!==manifest.sha256 ||
89
+ new TextDecoder('utf-8',{ignoreBOM:true}).decode(bytes)!==text) fail('context_digest_mismatch');
90
+ scan(manifest.display_name,Buffer.from(manifest.display_name));
91
+ scan(text,bytes);
92
+ return {manifest:{version:1,kind:'requester_text',display_name:manifest.display_name,encoding:'utf-8',
93
+ byte_length:bytes.length,sha256:manifest.sha256},text};
94
+ }
95
+ // Render losslessly into the ordinary assignment brief, not unknown side-car fields.
96
+ // The normal submission scanner, instruction limits and exact submit identity still apply.
97
+ export function withRequesterLocalContext(assignment, snapshot) {
98
+ if (typeof assignment?.brief!=='string'||assignment.brief.includes(requesterLocalContextMarker)||assignment.objective!==undefined)
99
+ fail('context_requires_literal_brief');
100
+ const {manifest,text}=validate(snapshot);
101
+ return {...assignment,brief:assignment.brief+requesterLocalContextMarker+JSON.stringify(manifest)+'\n'+text};
102
+ }
103
+ export function decodeRequesterLocalContext(brief) {
104
+ if (typeof brief!=='string') fail('context_requires_literal_brief');
105
+ const start=brief.indexOf(requesterLocalContextMarker);
106
+ if (start<0) return null;
107
+ const at=start+requesterLocalContextMarker.length, end=brief.indexOf('\n',at);
108
+ if (end<0||end-at>1024) fail('context_invalid_manifest');
109
+ let manifest;
110
+ try { manifest=JSON.parse(brief.slice(at,end)); }
111
+ catch { fail('context_invalid_manifest'); }
112
+ return validate({manifest,text:brief.slice(end+1)});
113
+ }
package/src/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { createPullPacing, describePullOffer, maxBatchPull } from './pull-pacing.mjs';
1
2
  import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
2
3
  import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
3
4
  import {inspect} from 'node:util';
@@ -177,7 +178,14 @@ if(t3ToolsEnabled) await loadT3Audit();
177
178
  const absentId=`req_${randomUUID()}`;
178
179
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
179
180
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
181
+ const pullPacing=createPullPacing({now:()=>store.nowMs(),log});
180
182
  const guardArtifactDownload = createArtifactDownloadGuard({log});
183
+ // Hosted claim credentials currently attest claim identity, not an independently
184
+ // registered attachment recipient route/address. Do not fall back to a published
185
+ // bundle when the work has an explicit unpublished attachment binding.
186
+ const hasUnqualifiedLocalAttachment = work => !!store.db.prepare(
187
+ 'SELECT 1 FROM local_attachment_bindings WHERE work=?').get(work);
188
+
181
189
  const scopedSourceChunk=18*1024;
182
190
  function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin) {
183
191
  const {manifest,blobs,refusedPaths}=pinnedScopedSource(mirror,assignment,maxBytes,pin);
@@ -212,6 +220,7 @@ function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_of
212
220
  if(!workerWorkspaceAllowed(worker,requestId)) return {};
213
221
  assertRepoAllowed(worker,assignment);
214
222
  store.assertMutationConnection(requestId,grant,connectionId);
223
+ if(hasUnqualifiedLocalAttachment(requestId))return {pinned_input_error:'attachment_recipient_unavailable'};
215
224
  const input=assignmentInput(assignment);
216
225
  if(input.input_patch) return {};
217
226
  const mirror=mirrorPath(input.github_repo,{worker});
@@ -289,6 +298,7 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
289
298
  if(row.status!=='claimed'||row.cancelled_at) throw new Error('assignment is not claimed');
290
299
  const claim=store.assertClaim(requestId,claimId,subject,worker);
291
300
  store.assertMutationConnection(requestId,claim,connection);
301
+ if(hasUnqualifiedLocalAttachment(requestId))throw new Error('attachment_recipient_unavailable');
292
302
  if(row.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
293
303
  if(!workspaceEnabled||!workerWorkspaceAllowed(worker,requestId)) throw new Error('capability_not_enabled');
294
304
  assertRepoAllowed(worker,row.assignment);
@@ -479,7 +489,7 @@ function maskedForOwner(response) {
479
489
  if(out.claim?.activity) out.claim={...out.claim,activity:{...out.claim.activity,last_tool_error:maskText(out.claim.activity.last_tool_error)}};
480
490
  return out;
481
491
  }
482
- const publicClaimFields=['request_id','claimant','subject','claimed_at','last_progress_at','last_claim_activity_at','worker','epoch','state','abandoned_at','abandon_reason','lease_expires_at','activity','destination_revision'];
492
+ const publicClaimFields=['request_id','claimant','subject','claimed_at','last_progress_at','last_claim_activity_at','worker','epoch','state','abandoned_at','abandon_reason','lease_expires_at','run_deadline_at','heartbeat_interval_ms','activity','destination_revision'];
483
493
  // Worker-visible get must never carry claim capability values. The claim-field
484
494
  // allowlist above already drops claim_id; this recursive pass additionally drops
485
495
  // claim_id, origin_claim_id and acquisition_id from every other generated
@@ -591,8 +601,20 @@ const tools = [
591
601
  ].filter(tool=>((catalogProfile!=='stable'&&!batchClaimProfile)||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
592
602
  if(batchClaimProfile) {
593
603
  const claim=tools.find(item=>item.name==='claim');
594
- claim.description+=' Use next (1 through 8) instead of request_id to claim several queued assignments with one acquisition_id. The reply contains claims and free_lanes.';
595
- claim.inputSchema.properties.next={type:'integer',minimum:1,maximum:8};
604
+ claim.description+=' Use next (1 through 8) instead of request_id to claim as many queued assignments as your own executor has reserved slots for, with one acquisition_id. The reply contains claims and free_lanes.';
605
+ const list=tools.find(item=>item.name==='list_pending');
606
+ list.description+=' Declare free_slots reserved by your local executor, including zero if it cannot start work.';
607
+ list.inputSchema.properties.free_slots={type:'integer',minimum:0,maximum:maxBatchPull};
608
+ Object.assign(claim.inputSchema.properties,{
609
+ next:{type:'integer',minimum:1,maximum:maxBatchPull},
610
+ heartbeat_ms:{type:'integer',minimum:10000,maximum:300000},
611
+ run_timeout_ms:{type:'integer',minimum:10000,maximum:store.limits.leaseMs},
612
+ });
613
+ const finish=tools.find(item=>item.name==='finish');
614
+ Object.assign(finish.inputSchema.properties,{
615
+ capacity_feedback:{type:'string',enum:['capacity_rate_limited','capacity_unavailable']},
616
+ retry_after_ms:{type:'integer',minimum:0,maximum:900000},
617
+ });
596
618
  claim.inputSchema.required=['claimant'];
597
619
  // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
598
620
  // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
@@ -757,6 +779,8 @@ function validate(name,args,definition=tools.find(x=>x.name===name)) { if(!defin
757
779
  if(name==='claim'&&batchClaimProfile) {
758
780
  if(Object.hasOwn(args,'next')===Object.hasOwn(args,'request_id')) throw new Error('supply exactly one of request_id or next');
759
781
  if(Object.hasOwn(args,'next')&&!Object.hasOwn(args,'acquisition_id')) throw refuse('missing','acquisition_id');
782
+ if(Object.hasOwn(args,'heartbeat_ms')!==Object.hasOwn(args,'run_timeout_ms'))
783
+ throw new Error('heartbeat_ms and run_timeout_ms must be declared together');
760
784
  }
761
785
  // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
762
786
  if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
@@ -858,8 +882,16 @@ function notifyStalePrCancellation(requestId) {
858
882
  // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
859
883
  function sweepStaleLeases() {
860
884
  const ids=store.sweepStaleLeases();
861
- if(ids.length) log({kind:'claims_lease_expired',count:ids.length,request_ids:ids.slice(0,20)});
862
- for(const id of ids) phaseTrace.expired(id);
885
+ const idle=[],hard=[];
886
+ for(const id of ids) {
887
+ const claim=store.db.prepare('SELECT worker,subject,connection_id,last_progress_at,run_timeout_ms,claimed_at,lease_deadline_at FROM claims WHERE request_id=?').get(id);
888
+ const hardDeadline=claim?.run_timeout_ms!=null&&Date.parse(claim.lease_deadline_at)>=Date.parse(claim.claimed_at)+claim.run_timeout_ms;
889
+ (hardDeadline?hard:idle).push(id);
890
+ if(batchClaimProfile&&claim?.last_progress_at&&!hardDeadline) pullPacing.observe(claim,'live_idle_lease_lost');
891
+ phaseTrace.expired(id);
892
+ }
893
+ if(idle.length) log({kind:'claims_lease_expired',count:idle.length,request_ids:idle});
894
+ if(hard.length) log({kind:'claims_run_deadline_reached',count:hard.length,request_ids:hard});
863
895
  return ids;
864
896
  }
865
897
  const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
@@ -955,13 +987,14 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
955
987
 
956
988
  // Put the next acquisition before job detail, including after progress and finish.
957
989
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
958
- function batchRoom(subject,worker) {
959
- const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
960
- const hint=store.claimHint(worker);
961
- const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
962
- return {free_lanes,ready,available,hintFree,next:Math.min(available,ready.length,8,hintFree)};
990
+ function batchRoom(principal,freeSlots) {
991
+ const {worker,subject}=principal;
992
+ const {free_lanes,ready,available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
993
+ const advised=freeSlots===undefined?pullPacing.free(principal,store.activeClaims(subject,worker).length):null;
994
+ const {next,evidence}=describePullOffer({declared:freeSlots,advised,free:free_lanes,available,ready:ready.length});
995
+ return {free_lanes,ready,available,desired:evidence.effective_worker_slots,next,evidence};
963
996
  }
964
- function batchCapacityReply(name,reply,principal,callId,onOffer) {
997
+ function batchCapacityReply(name,reply,principal,callId,onOffer,freeSlots) {
965
998
  if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
966
999
  const recordListing=name==='list_pending'&&!!callId;
967
1000
  if(!batchClaimProfile) {
@@ -969,20 +1002,22 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
969
1002
  return reply;
970
1003
  }
971
1004
  const {worker,subject}=principal;
972
- const {free_lanes,ready,available,hintFree,next}=batchRoom(subject,worker);
973
- const ready_queued=ready.length;
1005
+ const {free_lanes,ready,available,desired,next,evidence}=batchRoom(principal,freeSlots);
1006
+ const ready_queued=ready.length, demand_source=freeSlots===undefined?'hosted_advice':'worker_declared';
974
1007
  const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
975
1008
  store.paused()?['paused','Claims are paused; call list_pending again later.']:
976
1009
  next>0?['ready',`claim with next=${next} now`]:
977
1010
  available===0?['lanes_full','Continue held work and finish one before claiming more.']:
978
- ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
1011
+ ready_queued>0&&desired===0?['no_worker_slots',freeSlots===0
1012
+ ?'You declared zero free slots. Continue held work and poll again when you can start another job.'
1013
+ :'The worker capacity advice currently has no free slots. If you actually have room, call list_pending with free_slots.']:
979
1014
  ['no_ready_work','No ready queued work; call list_pending again later.'];
980
1015
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
981
- const response={next_action,free_lanes,claimable_lanes:available,ready_queued,recommended_claims:reason==='ready'?next:0,dispatch_reason:reason,...rest};
1016
+ const recommended_claims=reason==='ready'?next:0;
1017
+ const response={next_action,free_lanes,ready_queued,claimable_lanes:available,recommended_claims,dispatch_reason:reason,demand_source,...rest,...(name==='list_pending'?{claim_offer:evidence}:{})};
982
1018
  if(recordListing) {
983
- const recommended=reason==='ready'?next:0;
984
- const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
985
- logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
1019
+ const readyIds=ready.slice(0,recommended_claims).map(item=>item.request_id);
1020
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims,demand_source,ready_head_ids:readyIds});
986
1021
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
987
1022
  }
988
1023
  return response;
@@ -1272,7 +1307,7 @@ async function tool(name,a,principal,notifyMeta,signal,batchMode=null,registryDe
1272
1307
  try {
1273
1308
  const rid=a?.request_id;
1274
1309
  if(typeof rid==='string'&&rid!==absentId&&(registryDefinition||toolNames.has(name))&&!t3Tools.has(name)&&!notifyTools.has(name)) {
1275
- try { store.recordToolActivity(rid,principal.subject,principal.worker,name,{workspace:disabled.has(name),error,connectionId:principal.builtin?(principal.connection_id??''):null}); } catch { /* activity is diagnostic; never fail the call */ }
1310
+ try { store.recordToolActivity(rid,principal.subject,principal.worker,name,{workspace:disabled.has(name),error,claimId:a?.claim_id??null,connectionId:principal.builtin?(principal.connection_id??''):null}); } catch { /* activity is diagnostic; never fail the call */ }
1276
1311
  }
1277
1312
  } finally { admittedInFlight--; }
1278
1313
  }
@@ -1377,7 +1412,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1377
1412
  sweepExpired();
1378
1413
  // Strict commands validate authority, replay and revision in their transaction.
1379
1414
  // The legacy implicit touch would mutate activity before a rejected CAS.
1380
- if(!strictJob&&typeof a.request_id==='string'&&typeof a.claim_id==='string'&&store.hasAssignment(a.request_id)) store.touchClaim(a.request_id,a.claim_id,subject,worker,connectionId);
1415
+ const touchedLease=!strictJob&&typeof a.request_id==='string'&&typeof a.claim_id==='string'&&store.hasAssignment(a.request_id)
1416
+ ? store.touchClaim(a.request_id,a.claim_id,subject,worker,connectionId) : false;
1381
1417
  if(typeof a.request_id==='string') phaseTrace.action({requestId:a.request_id,tool:name,subject});
1382
1418
  // Workspace tools (every one, reads included) refuse any caller but the live holding connection. Native jobs skip the implicit
1383
1419
  // touch above, so this is their only check; legacy jobs get a second, post-await check. It runs synchronously right before
@@ -1399,7 +1435,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1399
1435
  case 'list_pending': {
1400
1436
  const {free_lanes,worker_max_claims,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1401
1437
  const assignments=store.listPending(worker);
1402
- store.recordListed(assignments,free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1438
+ store.recordListed(assignments,batchClaimProfile?batchRoom(principal,a.free_slots).next:free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1403
1439
  phaseTrace.listed(assignments.map(x=>x.request_id));
1404
1440
  const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1405
1441
  const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
@@ -1414,8 +1450,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1414
1450
  const claimant=str(a.claimant,'claimant',128);
1415
1451
  const lanes=()=>store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
1416
1452
  const {available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1417
- const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1418
- (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));
1453
+ const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms,heartbeatMs:a.heartbeat_ms,runTimeoutMs:a.run_timeout_ms},
1454
+ (request_id,acquisition_id,mode)=>signal?.aborted?null:tool('claim',{request_id,claimant,acquisition_id,...(a.lease_ms===undefined?{}:{lease_ms:a.lease_ms}),...(a.heartbeat_ms===undefined?{}:{heartbeat_ms:a.heartbeat_ms,run_timeout_ms:a.run_timeout_ms})},principal,undefined,signal,mode));
1419
1455
  return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1420
1456
  }
1421
1457
  const requestId=id(a.request_id),claimant=str(a.claimant,'claimant',128),ctx=commandContext('claim',{claimant,acquisition_id:a.acquisition_id??null,lease_ms:a.lease_ms??null}),row=store.get(requestId),held=row.claim?.state==='active'?row.claim:null,retry=holdsLiveGrant(worker,requestId,claimant,subject,a.acquisition_id);
@@ -1452,11 +1488,15 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1452
1488
  // claimant's own connection is still live. The token was verified before
1453
1489
  // the awaited preflight/quiesce above, so a revoke in between must not
1454
1490
  // admit the claim. External-OAuth principals pass null and are unchanged.
1455
- const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
1491
+ const idleLease=a.heartbeat_ms===undefined?a.lease_ms:Math.min(a.heartbeat_ms*3,a.lease_ms??store.limits.leaseMs);
1492
+ const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,idleLease,ctx,principal.builtin?(principal.connection_id??''):null,batchMode,a.run_timeout_ms);
1456
1493
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1457
1494
  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});
1458
1495
  const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1459
- return withAvailableChecks({...claimed,lease_ms:store.claimLeaseMs(grant),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);
1496
+ return withAvailableChecks({...claimed,lease_ms:store.claimLeaseMs(grant),...(grant.run_timeout_ms==null?{}:{
1497
+ heartbeat_interval_ms:Math.max(1,Math.floor(store.claimLeaseMs(grant)/3)),
1498
+ run_deadline_at:new Date(Date.parse(grant.claimed_at)+grant.run_timeout_ms).toISOString()
1499
+ }),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);
1460
1500
  }
1461
1501
  case 'renew_claim': {
1462
1502
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1467,7 +1507,9 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1467
1507
  if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1468
1508
  store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1469
1509
  const row=store.get(requestId);
1470
- return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),
1510
+ const recovery=store.workerRecovery(requestId,a.claim_id,subject,worker,connectionId);
1511
+ return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...(recovery?{recovery}:{}),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),
1512
+ ...store.workerGetLease(requestId,worker,subject,a.claim_id,connectionId,touchedLease),
1471
1513
  ...pinnedSourceReply(row,principal,connectionId,a),guidance:store.guidanceFor(worker)};
1472
1514
  }
1473
1515
  case 'ack_message': {const message=store.ackMessage(id(a.message_id,'message_id'),worker);log({kind:'message_acknowledged',message_id:message.message_id});return {kind:'message',message};}
@@ -1484,7 +1526,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1484
1526
  catch { /* Telemetry never changes a tool result. */ }
1485
1527
  }
1486
1528
  notifyAttachedWaiter(requestId);
1487
- return {...receipt,...repaired.marks};
1529
+ return {...receipt,...(!strictJob?store.workerGetLease(requestId,worker,subject,claimId,connectionId,touchedLease):{}),...repaired.marks};
1488
1530
  }
1489
1531
  case 'ask_question': {
1490
1532
  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);
@@ -1545,6 +1587,10 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1545
1587
  }
1546
1588
  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);
1547
1589
  if(receipt.deferred) return {...receipt,...repaired.marks};
1590
+ if(batchClaimProfile&&!receipt.duplicate&&!receipt.late) {
1591
+ if(a.outcome==='completed') pullPacing.observe(principal,'completed');
1592
+ else if(a.capacity_feedback) pullPacing.observe(principal,a.capacity_feedback,a.retry_after_ms??30000);
1593
+ }
1548
1594
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
1549
1595
  notifyAttachedWaiter(requestId);
1550
1596
  if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
@@ -1620,7 +1666,7 @@ async function dispatch(message,principal,signal,callId,onOffer) {
1620
1666
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1621
1667
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1622
1668
  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};
1623
- 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,onOffer)))}],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; } }
1669
+ 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,onOffer,p.arguments?.free_slots)))}],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; } }
1624
1670
  case 'events/list': return {events:[event]};
1625
1671
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1626
1672
  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 {}; }
@@ -1699,7 +1745,10 @@ const adminServer=http.createServer(async(req,res)=>{
1699
1745
  dryRequested=url.pathname==='/submit-preview';
1700
1746
  log({kind:'admin_call',route:url.pathname,method:req.method});
1701
1747
  if(url.pathname==='/submit'&&(url.searchParams.get('dry_run')==='1'||body.dry_run===true)) throw new Error('dry run requires POST /submit-preview; /submit always submits');
1702
- if((url.pathname==='/submit'||url.pathname==='/submit-preview')&&body.routing!==undefined) return json(res,200,await submitPolicy(body,req,url.pathname==='/submit-preview'));
1748
+ if((url.pathname==='/submit'||url.pathname==='/submit-preview')&&body.routing!==undefined) {
1749
+ if(body.subagent_id!==undefined||req.headers['x-subagent-owner-capability']!==undefined) throw new Error('subagent_unavailable');
1750
+ return json(res,200,await submitPolicy(body,req,url.pathname==='/submit-preview'));
1751
+ }
1703
1752
  if(url.pathname==='/submit'||url.pathname==='/submit-preview') {
1704
1753
  if(typeof body.assignment?.request_id==='string'&&store.pullQueue.row(body.assignment.request_id))throw new Error('request_id reserved for policy work; retry with routing');
1705
1754
  // Set before any check below, so every refusal carries typed reasons, answers a dry run with a verdict and is logged.
@@ -1726,6 +1775,10 @@ const adminServer=http.createServer(async(req,res)=>{
1726
1775
  if(catalogProfile!=='protocol-v0')throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
1727
1776
  validateProtocol(body.assignment.protocol);
1728
1777
  }
1778
+ const subagentOptions={id:body.subagent_id,credential:req.headers['x-subagent-owner-capability']};
1779
+ if(body.subagent_id!==undefined&&Object.hasOwn(body.assignment,'protocol')) throw new Error('subagent_unavailable');
1780
+ store.checkSubagentSubmission(body.assignment.request_id,owner,subagentOptions,
1781
+ [follows?.prior_id,revises?.prior_id,supersedes?.target_id]);
1729
1782
  let payload=renderAssignment(body.assignment);
1730
1783
  if(!payload||payload.schema_version!==1||!payload.brief||!Array.isArray(payload.inputs)||typeof payload.expected_output!=='string'||typeof payload.execution_scope!=='string') {
1731
1784
  const wrong=payload?[payload.schema_version!==1&&'schema_version (must be 1)',!payload.brief&&'brief',!Array.isArray(payload.inputs)&&'inputs (an array)',typeof payload.expected_output!=='string'&&'expected_output (a string)',typeof payload.execution_scope!=='string'&&'execution_scope (a string)'].filter(Boolean):[];
@@ -1856,7 +1909,7 @@ const adminServer=http.createServer(async(req,res)=>{
1856
1909
  }
1857
1910
  admitWorkerAdapter();
1858
1911
  }
1859
- 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);
1912
+ 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,subagentOptions);
1860
1913
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1861
1914
  if(supersedes&&!result.duplicate) {
1862
1915
  const targetId=supersedes.target_id,waiter=waiters.get(targetId);
@@ -1870,6 +1923,12 @@ const adminServer=http.createServer(async(req,res)=>{
1870
1923
  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}:{})});
1871
1924
  }
1872
1925
  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'}:{})}); }
1926
+ if(url.pathname==='/subagent'&&req.method==='GET') {
1927
+ res.setHeader('Cache-Control','no-store');
1928
+ const history=store.subagentHistory(url.searchParams.get('id'),req.headers['x-owner-capability'],
1929
+ Number(url.searchParams.get('after')??0),Number(url.searchParams.get('limit')??30));
1930
+ return json(res,200,{...history,work:history.work.map(maskedForOwner)});
1931
+ }
1873
1932
  if(url.pathname==='/get') {
1874
1933
  const requestId=id(url.searchParams.get('id'));
1875
1934
  if(!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
@@ -1880,6 +1939,10 @@ const adminServer=http.createServer(async(req,res)=>{
1880
1939
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1881
1940
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1882
1941
  Object.assign(got,repositoryReadScope(got.assignment));
1942
+ const membership=store.db.prepare('SELECT subagent_id FROM continuing_subagent_jobs WHERE request_id=?').get(requestId);
1943
+ if(membership)got.subagent_id=membership.subagent_id;
1944
+ const offer=store.offerView(requestId);
1945
+ if(offer)got.offer=offer;
1883
1946
  const manifests=store.scopedInputManifests(requestId);
1884
1947
  if(manifests.length) got.scoped_input_manifests=manifests;
1885
1948
  if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
@@ -1963,7 +2026,7 @@ const adminServer=http.createServer(async(req,res)=>{
1963
2026
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1964
2027
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1965
2028
  }
1966
- 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});
2029
+ if(url.pathname==='/status') return json(res,200,{owner_features:{continuing_subagents:1},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});
1967
2030
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1968
2031
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1969
2032
  const requestId=id(body.id); adminOwner(req,requestId);
@@ -2116,7 +2179,7 @@ const adminServer=http.createServer(async(req,res)=>{
2116
2179
  }
2117
2180
  if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
2118
2181
  const requestId=id(body.id); adminOwner(req,requestId);
2119
- const result=store.cancelIfQueued(requestId);
2182
+ const result=store.cancelIfQueued(requestId,{key:body.command_key,owner:req.headers['x-owner-capability']});
2120
2183
  if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
2121
2184
  return json(res,200,result.cancelled?{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:false})}:result);
2122
2185
  }
@@ -2370,7 +2433,7 @@ setInterval(()=>{
2370
2433
  AND request_id IN (${ids.map(()=>'?').join(',')}) LIMIT 1`).get(...ids);
2371
2434
  if(!queued) return false;
2372
2435
  if(store.paused()||quiescing||store.holdingBreak(worker)||store.capacityHoldUntil(worker)) return null;
2373
- const {ready,next}=batchRoom(subject,worker);
2436
+ const {ready,next}=batchRoom({subject,worker},maxBatchPull);
2374
2437
  return ready.slice(0,next).some(item=>ids.includes(item.request_id))?true:null;
2375
2438
  });
2376
2439
  for(const stall of due) {