@tnunamak/dalan 0.9.7 → 0.9.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,12 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.8
8
+
9
+ - Let a worker declare the slots it can start on this poll. Hosted clients without slot declarations get advice that adjusts to observed completion and capacity pressure.
10
+ - Timed claims report an effective heartbeat interval and an independent run deadline.
11
+ - Report a reserved worker slot separately from the moment work starts.
12
+
7
13
  ## 0.9.7
8
14
 
9
15
  - Read a larger pinned input set as one verified bundle over several replies. Each reply requires the current claim.
@@ -335,7 +335,7 @@ function admissionText(admission, attached) {
335
335
  const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
336
336
  const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
337
337
  const window = days => count(days) ? `, ${days} days` : '';
338
- const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'starts now' : ['queued','now'].includes(start) ? 'queued' :
338
+ const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'slot reserved' : ['queued','now'].includes(start) ? 'queued' :
339
339
  ['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
340
340
  if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
341
341
  if (count(ahead?.count)) {
@@ -132,13 +132,14 @@ When a peer speaks A2A, Dalan maps A2A task, message and artifact to work, quest
132
132
 
133
133
  ### 6.1 Worker capacity and pacing
134
134
 
135
- A caller gives the worker a task and a pushed repository anchor. Dalan tells the caller when that job can start, offers the worker exactly the work it can claim, and delivers pinned inputs through the same live claim. The worker uses its own tools and returns its result through the caller's native child route where qualified, or the durable inbox otherwise.
135
+ A caller gives the worker a task and a pushed repository anchor. A single allocator at the worker reserves its own execution slots before polling. The worker declares free slots on the poll, requests up to that many on claim, and uses the same slot reservation and acquisition ID on reconnect or transport retry. Dalan matches that demand to eligible work and delivers pinned inputs through the live claim. Availability events only prompt a poll. A requester reservation, a claim, and a first substantive action are separately recorded facts. The legacy wire value `start: now` names the reservation. It does not prove claimed or started. The worker uses its own tools and returns its result through the caller's native child route where qualified, or the durable inbox otherwise.
136
136
 
137
137
  | Decision | Dalan parity rows from §1.1 | Acceptance |
138
138
  |---|---|---|
139
139
  | Full-feature delegation is the default. A build marker selects implementation of the whole authorized repository. Old file hints describe focus. Exclude known secret paths mechanically. | D1 call, D8 repository access, D9 execution, D16 pushed anchor | The native caller submits one build spanning multiple directories on a pushed commit. The worker can edit across the repository and return a patch. Known secret inputs and writes are withheld. No file-count rule. |
140
- | Each worker gets its own capacity reading. Base a configured ceiling on observed simultaneous claims and genuine provider limits. Use eligible ready work and usable lanes after reservations and holds to compute the one `next_action` on list, claim, progress and finish. | D2 admission, D12 breaks, D14 session length, D17 worker state | Four usable lanes and four ready jobs offer four. Four lanes and one ready job offer one. A hold or reservation reduces the offer with its reason. Recorded claim and session evidence make it possible to verify and revise the ceiling. Silence alone does not establish a provider limit. |
141
- | Activity on the live claim refreshes its idle lease within the worker's configured limit. Publish the effective duration and deadline. Where a negotiated protocol uses explicit renewal, use its renewal command. | D2 admission, D7 progress, D11 recovery | The current holder's activity moves the deadline. Earlier epochs, expired claims and foreign connections cannot renew it. A queue listing or other work cannot extend the lease. |
140
+ | Workers own execution capacity. Dalan offers at most the declared free slots and eligible ready jobs. Its independent admission and in-flight limits protect the shared service; they do not estimate executor capacity. | D2 admission, D12 breaks, D14 session length, D17 worker state | Four declared slots and four claimable jobs offer four; one ready job offers one; zero slots offer zero. Concurrent pulls and exact retries use the existing atomic claim and reservation checks. The negotiated route stores no worker execution width. Legacy admission quotas remain limits on service exposure. |
141
+ | A hosted client without slot declarations receives an advisory offer from the hosted adapter. Start with one. Grow by one on confirmed successful completion, within the batch and broker limits. Reduce on expired live leases and verified retryable provider or capacity pressure. Honor a known retry time; log reductions and recovery. Key short-lived advice by authenticated worker and connection. Reset stale estimates to one. A run ceiling or unexplained session end is excluded from pressure evidence. | D2 admission, D12 breaks, D14 session length, D15 outcomes, D17 worker state | The same replay does not train the estimate twice. A 429 or inability caused by a workload or access problem is recorded with its cause; only capacity-related pressure feeds the estimate. A worker that declares slots bypasses this advisory estimate. The matcher needs no worker names or configured worker widths. |
142
+ | An active attempt has two clocks. The worker negotiates a heartbeat interval, with detection at three heartbeat intervals, and an independent wall-clock run ceiling. Authorized claim activity proves liveness and moves its idle deadline, up to the run ceiling. Legacy clients without timed heartbeats retain their previous lease contract; explicit protocol renewal remains available where negotiated. | D2 admission, D7 progress, D11 recovery | A heartbeat extends the idle deadline without recording a start or extending the run ceiling. Queue polls, earlier epochs, expired claims and foreign connections cannot renew a grant. The reply reports the effective clocks. A rollback to a bridge without timed claims waits for those active attempts to settle. |
142
143
  | Authorized scoped reads get one pinned file bundle and manifest, with a hash per path and a digest for the whole bundle. Deliver it inline if it fits; page the same verified bytes by digest when it does not. | D8 repository access, D11 recovery, D16 pushed anchor | A worker reads several pinned files without per-file forge requests. Retrying the bundle returns the same digest or an explicit discrepancy. The worker must present its current claim and retain read authority on every page. A stale holder or revoked reader receives no further bytes. The owner can distinguish a complete set from omitted inputs. |
143
144
  | A verified result becomes a patch or a draft PR under current publication authority. | D9 execution, D10 result shape, D11 recovery | The owner verifies the anchor and the scoped delivery evidence where required. A standing install policy and the current relationship or work grant constrain publication at the time of push. Revoked or unrelated grants produce patch-only results. Retrying recovers the original draft. Owner acceptance stays separate. |
144
145
  | Known blocked work stays visible with its reason and stays out of ready counts, admission forecasts, dispatch and wakes until verified eligible again or retired. | D2 admission, D12 breaks, D17 worker state | A blocked queue head cannot remove an eligible job from an offer or generate a wake. On reopen, the same rules apply to the persisted block. |
@@ -218,6 +219,15 @@ Captured in the research library (not in this repo): async completion contracts
218
219
 
219
220
  Primary sources behind the claims in sections 4 and 9, as read on 2026-11-27: [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp) (Tasks support and polling); [ACP v2 migration guide](https://agentclientprotocol.com/protocol/v2/migration) (a preview; not an outside completion path); the MCP Tasks extension proposal SEP-2663 (`io.modelcontextprotocol/tasks`, MCP 2026-07-28); T3 Code source at commit 3dbefda28 (files and lines cited where used); Dalan `main` at d0dd670 (files and lines cited where used).
220
221
 
222
+ Queue and worker patterns used in §6.1
223
+
224
+ - Temporal slots, Celery prefetch, SQS visibility renewal and the separate Kafka heartbeat clock. [Consumer prefetch and lease timers](https://github.com/tnunamak/divan/blob/main/queue-systems/queue-consumers-bound-unacked-work-by-prefetch-or-slots-and-set-lease-timers-from-max-job-time-with-heartbeats-at-one-third-or-less-of-the-detection-timeout.md)
225
+ - A transport wake, host activation and job authority are distinct. [Agent delivery by push and pull](https://github.com/tnunamak/divan/blob/main/queue-systems/agent-job-delivery-push-vs-pull-and-what-mcp-lets-a-server-push.md)
226
+ - The amount a consumer asks for provides backpressure, and acceptance is observable. [Consumer demand and bounded queues](https://github.com/tnunamak/divan/blob/main/queue-systems/work-queue-and-review-pipeline-systems-prevent-write-only-output-by-letting-consumer-demand-not-producer-capacity-admit-work-and-by-delivering-findings-inside-the-consumers-workflow.md)
227
+ - Temporal polls after reserving capacity. A reservation does not establish an execution start. [Reservation, execution permission and execution evidence](https://github.com/tnunamak/divan/blob/main/queue-systems/a-reservation-permission-to-execute-and-evidence-of-execution-are-three-different-facts-so-a-lending-app-should-take-the-human-yes-before-the-execution-lease.md)
228
+ - Admission, delivery, authority and verification own different decisions. [Remote delegation taxonomy](https://github.com/tnunamak/divan/blob/main/remote-agent-delegation/taxonomy-v2-remote-coding-delegation-is-a-six-stage-lifecycle-with-twenty-dimensions-each-owning-one-design-decision.md)
229
+ - Measure the inability and unconsumed-work buckets before widening offers. [Remote delegation synthesis](https://github.com/tnunamak/divan/blob/main/remote-agent-delegation/synthesis-remote-coding-delegation-should-first-stop-unconsumed-supply-and-preventable-admission-failures-then-add-owner-side-integration-before-widening-what-workers-can-do.md)
230
+
221
231
  ## 12. Separation: Dalan and the tooling built on it
222
232
 
223
233
  Rule: this repository holds the bridge only: relationship, work, authority, delivery and wake, worker capability, and the surface that requester agents call. Tooling that an operator builds on top (job generators, admission gates, wake scripts, nudges to workers, filler rules, fleet reports) uses only Dalan's public interface. That interface is the CLI and MCP verbs, `status`/`metrics`/`get` JSON, the config files documented in `docs/`, and the requester adapters. Tooling holds no Dalan internals. Dalan holds no operator rules, host thread ids, account names or fleet vocabulary.
@@ -29,7 +29,9 @@ Put this loop in the worker's standing instructions, for example in its schedule
29
29
 
30
30
  ### Claim several ready assignments in one call
31
31
 
32
- The opt-in `batch-claim-v1` catalog advertises `claim({ next, claimant, acquisition_id, lease_ms? })`. Set `next` to 1 through 8 instead of `request_id`. The bridge returns `{ claims, free_lanes }`; each entry is a normal claim reply with the assignment, claim ID and epoch. Treat each entry as a separate grant and start the work before moving on. Save the original acquisition ID and the returned grants across retries. Choose a new acquisition ID for a new batch.
32
+ The opt-in `batch-claim-v1` catalog accepts `list_pending({ free_slots })` and `claim({ next, claimant, acquisition_id, lease_ms? })`. Reserve free slots in your executor before polling. Pass zero if none are free. Claim only slots you reserved for this cycle and reuse the same acquisition ID on a transport retry. On denial, release that local reservation. The bridge reports whether its offer came from declared slots or hosted advice. Hosted advice starts with one and uses observed completions and capacity pressure. Each returned claim is a separate grant with its own ID and epoch.
33
+
34
+ A worker that can send timed heartbeats may pass `heartbeat_ms` and `run_timeout_ms` together on claim. Read the effective heartbeat interval and deadlines from the returned claim. Use authorized activity or `get` with the current claim ID within that interval. A renewal cannot extend the wall-clock run deadline. For confirmed capacity pressure at finish, send `capacity_feedback: capacity_rate_limited` with the retry delay if known, or `capacity_unavailable` for exhausted executor capacity.
33
35
 
34
36
  The bridge takes ordinary, unskipped queued assignments in list order, limited by current free lanes. It stops at the first refusal and returns the admitted prefix. Cancelled, skipped, and resumable grants are not batch candidates. Native protocol jobs and policy work still use the explicit request ID or their existing acquisition path. A retry with the same batch arguments uses the original selection. If the bridge saved a nonempty selection and no grant committed, it can still try those same jobs. Once a grant commits, a retry can only recover grants from that batch that are still live. If the returned batch is partial, call `list_pending` to see what's ready and use a fresh acquisition ID for a new batch.
35
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.7",
3
+ "version": "0.9.8",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,32 @@
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
+ }
package/src/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { createPullPacing, 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,6 +178,7 @@ 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});
181
183
  const scopedSourceChunk=18*1024;
182
184
  function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin) {
@@ -473,7 +475,7 @@ function maskedForOwner(response) {
473
475
  if(out.claim?.activity) out.claim={...out.claim,activity:{...out.claim.activity,last_tool_error:maskText(out.claim.activity.last_tool_error)}};
474
476
  return out;
475
477
  }
476
- 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'];
478
+ 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'];
477
479
  // Worker-visible get must never carry claim capability values. The claim-field
478
480
  // allowlist above already drops claim_id; this recursive pass additionally drops
479
481
  // claim_id, origin_claim_id and acquisition_id from every other generated
@@ -585,8 +587,20 @@ const tools = [
585
587
  ].filter(tool=>((catalogProfile!=='stable'&&!batchClaimProfile)||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
586
588
  if(batchClaimProfile) {
587
589
  const claim=tools.find(item=>item.name==='claim');
588
- 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.';
589
- claim.inputSchema.properties.next={type:'integer',minimum:1,maximum:8};
590
+ 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.';
591
+ const list=tools.find(item=>item.name==='list_pending');
592
+ list.description+=' Declare free_slots reserved by your local executor, including zero if it cannot start work.';
593
+ list.inputSchema.properties.free_slots={type:'integer',minimum:0,maximum:maxBatchPull};
594
+ Object.assign(claim.inputSchema.properties,{
595
+ next:{type:'integer',minimum:1,maximum:maxBatchPull},
596
+ heartbeat_ms:{type:'integer',minimum:10000,maximum:300000},
597
+ run_timeout_ms:{type:'integer',minimum:10000,maximum:store.limits.leaseMs},
598
+ });
599
+ const finish=tools.find(item=>item.name==='finish');
600
+ Object.assign(finish.inputSchema.properties,{
601
+ capacity_feedback:{type:'string',enum:['capacity_rate_limited','capacity_unavailable']},
602
+ retry_after_ms:{type:'integer',minimum:0,maximum:900000},
603
+ });
590
604
  claim.inputSchema.required=['claimant'];
591
605
  // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
592
606
  // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
@@ -751,6 +765,8 @@ function validate(name,args,definition=tools.find(x=>x.name===name)) { if(!defin
751
765
  if(name==='claim'&&batchClaimProfile) {
752
766
  if(Object.hasOwn(args,'next')===Object.hasOwn(args,'request_id')) throw new Error('supply exactly one of request_id or next');
753
767
  if(Object.hasOwn(args,'next')&&!Object.hasOwn(args,'acquisition_id')) throw refuse('missing','acquisition_id');
768
+ if(Object.hasOwn(args,'heartbeat_ms')!==Object.hasOwn(args,'run_timeout_ms'))
769
+ throw new Error('heartbeat_ms and run_timeout_ms must be declared together');
754
770
  }
755
771
  // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
756
772
  if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
@@ -852,8 +868,16 @@ function notifyStalePrCancellation(requestId) {
852
868
  // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
853
869
  function sweepStaleLeases() {
854
870
  const ids=store.sweepStaleLeases();
855
- if(ids.length) log({kind:'claims_lease_expired',count:ids.length,request_ids:ids.slice(0,20)});
856
- for(const id of ids) phaseTrace.expired(id);
871
+ const idle=[],hard=[];
872
+ for(const id of ids) {
873
+ 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);
874
+ const hardDeadline=claim?.run_timeout_ms!=null&&Date.parse(claim.lease_deadline_at)>=Date.parse(claim.claimed_at)+claim.run_timeout_ms;
875
+ (hardDeadline?hard:idle).push(id);
876
+ if(batchClaimProfile&&claim?.last_progress_at&&!hardDeadline) pullPacing.observe(claim,'live_idle_lease_lost');
877
+ phaseTrace.expired(id);
878
+ }
879
+ if(idle.length) log({kind:'claims_lease_expired',count:idle.length,request_ids:idle});
880
+ if(hard.length) log({kind:'claims_run_deadline_reached',count:hard.length,request_ids:hard});
857
881
  return ids;
858
882
  }
859
883
  const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
@@ -949,13 +973,13 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
949
973
 
950
974
  // Put the next acquisition before job detail, including after progress and finish.
951
975
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
952
- function batchRoom(subject,worker) {
953
- const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
954
- const hint=store.claimHint(worker);
955
- const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
956
- return {free_lanes,ready,available,hintFree,next:Math.min(available,ready.length,8,hintFree)};
976
+ function batchRoom(principal,freeSlots) {
977
+ const {worker,subject}=principal;
978
+ const {free_lanes,ready,available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
979
+ const desired=freeSlots??pullPacing.free(principal,store.activeClaims(subject,worker).length);
980
+ return {free_lanes,ready,available,desired,next:Math.min(desired,available,ready.length,maxBatchPull)};
957
981
  }
958
- function batchCapacityReply(name,reply,principal,callId,onOffer) {
982
+ function batchCapacityReply(name,reply,principal,callId,onOffer,freeSlots) {
959
983
  if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
960
984
  const recordListing=name==='list_pending'&&!!callId;
961
985
  if(!batchClaimProfile) {
@@ -963,20 +987,20 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
963
987
  return reply;
964
988
  }
965
989
  const {worker,subject}=principal;
966
- const {free_lanes,ready,available,hintFree,next}=batchRoom(subject,worker);
967
- const ready_queued=ready.length;
990
+ const {free_lanes,ready,available,desired,next}=batchRoom(principal,freeSlots);
991
+ const ready_queued=ready.length, demand_source=freeSlots===undefined?'hosted_advice':'worker_declared';
968
992
  const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
969
993
  store.paused()?['paused','Claims are paused; call list_pending again later.']:
970
994
  next>0?['ready',`claim with next=${next} now`]:
971
995
  available===0?['lanes_full','Continue held work and finish one before claiming more.']:
972
- ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
996
+ ready_queued>0&&desired===0?['no_worker_slots','Continue held work or poll with free_slots when your executor has capacity.']:
973
997
  ['no_ready_work','No ready queued work; call list_pending again later.'];
974
998
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
975
- const response={next_action,free_lanes,claimable_lanes:available,ready_queued,recommended_claims:reason==='ready'?next:0,dispatch_reason:reason,...rest};
999
+ const recommended_claims=reason==='ready'?next:0;
1000
+ const response={next_action,free_lanes,ready_queued,claimable_lanes:available,recommended_claims,dispatch_reason:reason,demand_source,...rest};
976
1001
  if(recordListing) {
977
- const recommended=reason==='ready'?next:0;
978
- const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
979
- logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
1002
+ const readyIds=ready.slice(0,recommended_claims).map(item=>item.request_id);
1003
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims,demand_source,ready_head_ids:readyIds});
980
1004
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
981
1005
  }
982
1006
  return response;
@@ -1393,7 +1417,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1393
1417
  case 'list_pending': {
1394
1418
  const {free_lanes,worker_max_claims,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1395
1419
  const assignments=store.listPending(worker);
1396
- store.recordListed(assignments,free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1420
+ store.recordListed(assignments,batchClaimProfile?batchRoom(principal,a.free_slots).next:free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1397
1421
  phaseTrace.listed(assignments.map(x=>x.request_id));
1398
1422
  const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1399
1423
  const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
@@ -1408,8 +1432,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1408
1432
  const claimant=str(a.claimant,'claimant',128);
1409
1433
  const lanes=()=>store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
1410
1434
  const {available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1411
- const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1412
- (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));
1435
+ 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},
1436
+ (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));
1413
1437
  return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1414
1438
  }
1415
1439
  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);
@@ -1446,11 +1470,15 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1446
1470
  // claimant's own connection is still live. The token was verified before
1447
1471
  // the awaited preflight/quiesce above, so a revoke in between must not
1448
1472
  // admit the claim. External-OAuth principals pass null and are unchanged.
1449
- const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
1473
+ const idleLease=a.heartbeat_ms===undefined?a.lease_ms:Math.min(a.heartbeat_ms*3,a.lease_ms??store.limits.leaseMs);
1474
+ 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);
1450
1475
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1451
1476
  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});
1452
1477
  const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1453
- 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);
1478
+ return withAvailableChecks({...claimed,lease_ms:store.claimLeaseMs(grant),...(grant.run_timeout_ms==null?{}:{
1479
+ heartbeat_interval_ms:Math.max(1,Math.floor(store.claimLeaseMs(grant)/3)),
1480
+ run_deadline_at:new Date(Date.parse(grant.claimed_at)+grant.run_timeout_ms).toISOString()
1481
+ }),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);
1454
1482
  }
1455
1483
  case 'renew_claim': {
1456
1484
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1539,6 +1567,10 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1539
1567
  }
1540
1568
  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);
1541
1569
  if(receipt.deferred) return {...receipt,...repaired.marks};
1570
+ if(batchClaimProfile&&!receipt.duplicate&&!receipt.late) {
1571
+ if(a.outcome==='completed') pullPacing.observe(principal,'completed');
1572
+ else if(a.capacity_feedback) pullPacing.observe(principal,a.capacity_feedback,a.retry_after_ms??30000);
1573
+ }
1542
1574
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
1543
1575
  notifyAttachedWaiter(requestId);
1544
1576
  if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
@@ -1614,7 +1646,7 @@ async function dispatch(message,principal,signal,callId,onOffer) {
1614
1646
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1615
1647
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1616
1648
  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};
1617
- 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; } }
1649
+ 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; } }
1618
1650
  case 'events/list': return {events:[event]};
1619
1651
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1620
1652
  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 {}; }
@@ -2364,7 +2396,7 @@ setInterval(()=>{
2364
2396
  AND request_id IN (${ids.map(()=>'?').join(',')}) LIMIT 1`).get(...ids);
2365
2397
  if(!queued) return false;
2366
2398
  if(store.paused()||quiescing||store.holdingBreak(worker)||store.capacityHoldUntil(worker)) return null;
2367
- const {ready,next}=batchRoom(subject,worker);
2399
+ const {ready,next}=batchRoom({subject,worker},maxBatchPull);
2368
2400
  return ready.slice(0,next).some(item=>ids.includes(item.request_id))?true:null;
2369
2401
  });
2370
2402
  for(const stall of due) {
package/src/store.mjs CHANGED
@@ -1136,6 +1136,8 @@ export class Store {
1136
1136
  prior_id TEXT NOT NULL REFERENCES assignments(request_id),
1137
1137
  at TEXT NOT NULL
1138
1138
  ); PRAGMA user_version=75;`);
1139
+ if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='run_timeout_ms'").get())
1140
+ this.db.exec('ALTER TABLE claims ADD COLUMN run_timeout_ms INTEGER');
1139
1141
  // Older bridges read every open row of worker_breaks as a primary-worker hold.
1140
1142
  // Keep secondary-worker holds out of that table so a rollback can still read current data.
1141
1143
  this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_worker_breaks(
@@ -1951,12 +1953,13 @@ export class Store {
1951
1953
  key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate,
1952
1954
  {leaseCapMs:this.workerClaimLeaseCap(worker)});
1953
1955
  }
1954
- setClaimDeadlineInTransaction(id,leaseMs) {
1955
- const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
1956
- const deadline=Date.parse(activity??this.stamp())+leaseMs;
1956
+ setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs=null) {
1957
+ const claim=this.db.prepare('SELECT last_claim_activity_at,claimed_at FROM claims WHERE request_id=?').get(id);
1958
+ const activity=Date.parse(claim?.last_claim_activity_at??this.stamp());
1959
+ const deadline=Math.min(activity+leaseMs,runTimeoutMs===null?Infinity:Date.parse(claim.claimed_at)+runTimeoutMs);
1957
1960
  if(!protocolNat(deadline))protocolError('invalid_lease');
1958
- this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
1959
- .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id);
1961
+ this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=?,run_timeout_ms=? WHERE request_id=?')
1962
+ .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),runTimeoutMs,id);
1960
1963
  }
1961
1964
  workerClaimLeaseCap(worker) {
1962
1965
  const caps=this.limits.workerClaimLeaseMs;
@@ -2413,9 +2416,9 @@ export class Store {
2413
2416
  this.refreshClaimActivity(id,claimId);
2414
2417
  }
2415
2418
  refreshClaimActivity(id,claimId) {
2416
- const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
2419
+ const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id,claimed_at,run_timeout_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
2417
2420
  const leaseMs=Math.min(this.handoffWorkLeaseMs(claim)??claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
2418
- const deadline=Date.parse(at)+leaseMs;
2421
+ const deadline=Math.min(Date.parse(at)+leaseMs,claim.run_timeout_ms==null?Infinity:Date.parse(claim.claimed_at)+claim.run_timeout_ms);
2419
2422
  if(this.isProtocolJob(id)) this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
2420
2423
  else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
2421
2424
  .run(at,leaseMs,iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id,claimId);
@@ -2710,7 +2713,9 @@ export class Store {
2710
2713
  const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) { const work=this.pullQueue.row(id);if(work)return this.pullQueue.project(work);throw new Error('assignment not found'); }
2711
2714
  this.assertProtocolAvailable(id);
2712
2715
  const claimRow=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
2713
- const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,...rest})=>({...rest,...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
2716
+ const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,run_timeout_ms,...rest})=>({...rest,...(run_timeout_ms==null?{}:{
2717
+ run_deadline_at:iso(Date.parse(rest.claimed_at)+run_timeout_ms),heartbeat_interval_ms:Math.max(1,Math.floor(this.claimLeaseMs(rest)/3))
2718
+ }),...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
2714
2719
  const report=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
2715
2720
  if(report?.workspace_evidence) report.workspace_evidence=JSON.parse(report.workspace_evidence);
2716
2721
  // Everything in a report is the worker's own statement. Only a check row carries bridge_verified, and only when the bridge ran it.
@@ -3059,14 +3064,14 @@ export class Store {
3059
3064
  // Persist selected IDs before asynchronous preflight. A retry can recover
3060
3065
  // live grants, or try the same nonempty plan if it never granted anything.
3061
3066
  // It cannot select different IDs or issue new grants after any grant landed.
3062
- async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs},grant) {
3067
+ async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs,heartbeatMs,runTimeoutMs},grant) {
3063
3068
  if(!Number.isInteger(next)||next<1||next>8) throw new Error('invalid next');
3064
3069
  if(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId)) throw new Error('batch claim requires acquisition_id');
3065
3070
  if(this.paused()) throw new Error(pausedClaimMessage);
3066
3071
  const hash=(...values)=>createHash('sha256').update(JSON.stringify(values)).digest('hex');
3067
3072
  const digest=hash(worker,subject,acquisitionId);
3068
3073
  const key='claim_batch_v1_'+digest;
3069
- const parameters=hash(connectionId,claimant,next,leaseMs??null);
3074
+ const parameters=hash(connectionId,claimant,next,leaseMs??null,...(heartbeatMs===undefined?[]:[heartbeatMs,runTimeoutMs]));
3070
3075
  const plan=this.transaction(()=>{
3071
3076
  const previous=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(key);
3072
3077
  if(previous) {
@@ -3253,7 +3258,7 @@ export class Store {
3253
3258
  } catch(error) { throw this.destinationConfigurationError(id,error); }
3254
3259
  if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
3255
3260
  }
3256
- claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null) {
3261
+ claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null,runTimeoutMs=null) {
3257
3262
  const requestedLeaseMs=arguments[7]??null;
3258
3263
  const claim=this.destinationOutcome(this.transaction(()=>{
3259
3264
  if(batchMode==='queued') {
@@ -3263,13 +3268,14 @@ export class Store {
3263
3268
  if(batchMode==='retry'&&!this.isExactClaimRetry(this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id),claimant,subject,acquisitionId)) throw new Error('batch grant no longer live');
3264
3269
  return this.isProtocolJob(id)
3265
3270
  ?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
3266
- :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId);
3271
+ :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3267
3272
  }));
3268
3273
  return nonterminalOutcome(id,{...claim,...this.heartbeatForHeldClaim(id,claim.claim_id,worker)});
3269
3274
  }
3270
- claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
3275
+ claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
3271
3276
  if(!this.db.isTransaction)protocolError('transaction_required');
3272
3277
  leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
3278
+ if(runTimeoutMs!==null&&(!Number.isSafeInteger(runTimeoutMs)||runTimeoutMs<1||runTimeoutMs>this.limits.leaseMs)) throw new Error('invalid run_timeout_ms');
3273
3279
  if(acquisitionId!==null&&(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId))) throw new Error('invalid acquisition_id: use 1-128 letters, digits, underscores or hyphens');
3274
3280
  if(!this.mayAct(worker,id)) throw new Error('assignment not found');
3275
3281
  if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
@@ -3292,7 +3298,7 @@ export class Store {
3292
3298
  if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
3293
3299
  if(takeover&&old.subject===subject&&this.isIdleClaim(old)) {
3294
3300
  this.assertClaimGap(id,subject,worker);
3295
- return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
3301
+ return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3296
3302
  }
3297
3303
  if(takeover) {
3298
3304
  if(!this.leaseExpired(old)&&old.subject===subject&&this.resumeIdleMs()>0) throw new Error(JSON.stringify({error:'claim_busy',message:`Request ${id}: another run of this worker holds it and is active; pick other work or retry after its lease expires. This affects only ${id}.`,request_id:id}));
@@ -3317,7 +3323,7 @@ export class Store {
3317
3323
  this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,subject=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=epoch+1,state='active',abandoned_at=NULL,abandon_reason=NULL,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,lane_key=?,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,claimedAt,subject,claimedAt,seen,laneKey,acquisitionId,leaseMs,connectionId??null,id);
3318
3324
  this.rebindClaim(id,claimId);
3319
3325
  } else this.db.prepare('INSERT INTO claims(request_id,claimant,claim_id,claimed_at,subject,last_claim_activity_at,last_seen_note_seq,worker,lane_key,lane_scope,acquisition_id,lease_ms,connection_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,claimant,claimId,claimedAt,subject,claimedAt,seen,worker,laneKey,laneScope,acquisitionId,leaseMs,connectionId??null);
3320
- this.setClaimDeadlineInTransaction(id,leaseMs);
3326
+ this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
3321
3327
  if(a.status==='queued') {
3322
3328
  this.recordPassedOver(id,worker);
3323
3329
  this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE target_worker=? AND status='queued' AND request_id<>? AND eligible_since IS NOT NULL").run(worker,id);
@@ -3333,7 +3339,7 @@ export class Store {
3333
3339
  // transaction, so a run still alive under the old claim_id is refused on its next call (claim_superseded). Worktree and sealed
3334
3340
  // uploads move with it (rebindClaim). Lifecycle: a 'claimed' event with reason 'resume' (not counted as a new admission; the
3335
3341
  // event type list is closed, so no 'resumed' type). The previous epoch and the idle time go to the progress history.
3336
- rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null) {
3342
+ rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
3337
3343
  this.assertRegrantReady(old);
3338
3344
  this.assertLiveConnection(old.request_id,worker,connectionId);
3339
3345
  const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
@@ -3342,7 +3348,7 @@ export class Store {
3342
3348
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3343
3349
  if(destinationRefusal)return destinationRefusal;
3344
3350
  this.assertNoUncertainDelivery(id);
3345
- const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId);
3351
+ const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3346
3352
  this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
3347
3353
  this.markBatchGrant(id,acquisitionId);
3348
3354
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
@@ -3350,11 +3356,11 @@ export class Store {
3350
3356
  }
3351
3357
  // The one re-grant of an existing claim row: new claim_id and epoch, and every old-epoch field (progress, tool counters, acquisition, lease) reset.
3352
3358
  // rotateIdleClaim (claim wake) and resume both call it, so the two paths cannot drift.
3353
- startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId) {
3359
+ startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs=null) {
3354
3360
  const id=old.request_id, claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
3355
3361
  const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
3356
3362
  this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
3357
- this.setClaimDeadlineInTransaction(id,leaseMs);
3363
+ this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
3358
3364
  this.rebindClaim(id,claimId);
3359
3365
  return {claimId,at,epoch};
3360
3366
  }
@@ -3371,7 +3377,7 @@ export class Store {
3371
3377
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3372
3378
  if(destinationRefusal)return destinationRefusal;
3373
3379
  this.assertNoUncertainDelivery(id);
3374
- const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
3380
+ const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id,old.run_timeout_ms??null); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
3375
3381
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
3376
3382
  if(this.isProtocolJob(id)) {
3377
3383
  this.advanceProtocolRevisionInTransaction(id);