@tnunamak/dalan 0.9.6 → 0.9.7
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 +6 -0
- package/docs/design/target-architecture-v2.md +24 -4
- package/package.json +1 -1
- package/src/acp-bridge.mjs +7 -2
- package/src/server.mjs +22 -10
- package/src/store.mjs +19 -4
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.7
|
|
8
|
+
|
|
9
|
+
- Read a larger pinned input set as one verified bundle over several replies. Each reply requires the current claim.
|
|
10
|
+
- Keep blocked pull requests out of queue forecasts and prevent old availability notices from waking workers for them.
|
|
11
|
+
- Ignore credential-path hints on full-repository build markers and keep those files out of the worker workspace.
|
|
12
|
+
|
|
7
13
|
## 0.9.6
|
|
8
14
|
|
|
9
15
|
- Delegate a full feature to a remote worker from a pushed commit. The worker can use the whole authorized repository, with known credential paths withheld.
|
|
@@ -57,7 +57,7 @@ Reference: a Claude Code `Agent` subagent or a Codex `spawn_agent` child. Gap ki
|
|
|
57
57
|
| `assignments.thread_id`, `environment_id` NOT NULL; delivery string only `none` or `t3:` | **Changes** | Delivery becomes `{adapter, address, adapter_version}`, with T3 columns moved into the T3 adapter's own table. The core names no host. |
|
|
58
58
|
| Worker catalog `read_file`, `apply_patch`, `run_check` | **Changes**: kept for workers without a computer | A worker with its own computer gets the work as repo, base and task, and returns a branch or patch with evidence. |
|
|
59
59
|
| Host `run_check` allowlist and `scope_paths_read_isolation_unavailable` | **Changes**: becomes acceptance evidence, not the worker's only test route | Owner-side checks still run on the returned branch when configured. They label their evidence `bridge_observed`; the worker's own runs are labeled `worker_reported`. |
|
|
60
|
-
| Name-based refusals (`auth`, `sign*`, `token`, `*secret*` soft names) | **Changes**:
|
|
60
|
+
| Name-based refusals (`auth`, `sign*`, `token`, `*secret*` soft names) | **Changes**: withhold files from the delivered inputs | A repository build retains implementation scope when it contains a known credential path. Dalan omits that file, records the exclusion, and enforces it on reads, writes and returned patches. A request for the excluded bytes or a patch to modify them is refused at that operation. Secrets in the brief or patch remain inadmissible. Content scanning is defense in depth. |
|
|
61
61
|
| `status.dispatch` scoped to `dot` | **Changes**: per worker | It stays as a simple dispatch diagnostic, keyed by worker name. The admission answer (section 6) does not replace it. |
|
|
62
62
|
| `dalan wait` loops as the wake for non-T3 callers (`docs/local-agent-requester.md`) | **Goes** as the documented wake | It stays as a tool for scripts. Section 4.3 gives native wakes. |
|
|
63
63
|
|
|
@@ -76,7 +76,7 @@ Operations, the same on every route: `delegate`, `forecast`, `status`, `result`,
|
|
|
76
76
|
|
|
77
77
|
## 4. Requester routes (versioned, disposable adapters)
|
|
78
78
|
|
|
79
|
-
The rule: **the caller uses the subagent call its host already has.** Dalan supplies an adapter per host. Each adapter states which capabilities it actually delivers (design for the expected capabilities; advertise only the delivered ones).
|
|
79
|
+
The rule: **the caller uses the subagent call its host already has.** Dalan supplies an adapter per host. Each adapter states which capabilities it actually delivers (design for the expected capabilities; advertise only the delivered ones). When a compatible authorized worker is available, use this route first for any coding task a caller would give a local child, including full features. Pick the worker by the tools the job needs and current availability. Use a local child when the work depends on unpublished files or local tools. Callers supply real demand through these routes.
|
|
80
80
|
|
|
81
81
|
### 4.1 T3 Code child task (primary; covers Claude and Codex threads in T3)
|
|
82
82
|
|
|
@@ -123,13 +123,31 @@ When a peer speaks A2A, Dalan maps A2A task, message and artifact to work, quest
|
|
|
123
123
|
## 6. Admission, forecast and track record
|
|
124
124
|
|
|
125
125
|
- Priority classes: `normal` (queue, with an estimate) and `background` (queue behind normal), as stored today (`CHECK(priority IN ('normal','background'))`). A start-or-refuse class would need a schema and admission change; v2 does not add one. The parent gets the admission answer within seconds and can cancel and route elsewhere.
|
|
126
|
-
- A free lane or a first claim is not a start. Today `queueWaitEvidence` (`src/store.mjs#queueWaitEvidence`) measures to the first stored claim and uses lower bounds for work that expired unclaimed. v2 measures two latencies: **claimed** (first claim) and **started** (the worker's first substantive event on the work, such as a workspace read or a progress event). Censored samples (expired or cancelled before a claim or a start) are counted in their own group and never mixed into the percentiles.
|
|
126
|
+
- A free lane or a first claim is not a start. Today `queueWaitEvidence` (`src/store.mjs#queueWaitEvidence`) measures to the first stored claim and uses lower bounds for work that expired unclaimed. v2 measures two latencies: **claimed** (first claim) and **started** (the worker's first substantive event on the work, such as a workspace read or a substantive progress event on the live claim and epoch. A heartbeat renews the lease without proving work started). Censored samples (expired or cancelled before a claim or a start) are counted in their own group and never mixed into the percentiles.
|
|
127
127
|
- Admission answer, computed before submit with a defined stale-answer policy: `start: "now"` only when Dalan has reserved a lane for this work and the worker's subscription is live at that moment. Otherwise `start: "queued"` with the facts: eligible ready work ahead (count and oldest age, same or higher class), measured claimed and started latencies (p50/p90, n, window, censored count), and the worker state (`live`, `break until T`, `no live subscription`). Below the existing minimum of 5 samples (`QUEUE_WINDOW.minSamples`, `src/store.mjs#QUEUE_WINDOW`) it says `insufficient_history` and gives no number. Lower bounds from work that expired unclaimed are reported as their own group; today they are mixed into the percentiles, which understates waits.
|
|
128
128
|
- A preview reports a forecast. A normal waiting caller can reserve capacity for its request as part of a successful submit when it is the eligible queue head. The reservation expires at `reserved_until` after at most 15 seconds, and a delayed native reply displays it as queued. Replaying a submit does not extend a reservation. Claiming the request consumes the hold. Its claim and first substantive worker event remain separate measurements.
|
|
129
129
|
- Track record, with outcomes kept apart: `unable_to_run`, `checks_failed`, `check_passed`, `landed` (merged or applied by the owner), plus `refused_by_provider`, n and window. "No passing check" is never reported as one blocked number.
|
|
130
130
|
- `status.dispatch` stays as a simple diagnostic beside this answer (section 2).
|
|
131
131
|
- No delegated-agent product shows a reliable ETA (see the prior-art list). Dalan reports only measured values with their basis, so a caller can judge them.
|
|
132
132
|
|
|
133
|
+
### 6.1 Worker capacity and pacing
|
|
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.
|
|
136
|
+
|
|
137
|
+
| Decision | Dalan parity rows from §1.1 | Acceptance |
|
|
138
|
+
|---|---|---|
|
|
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. |
|
|
142
|
+
| 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
|
+
| 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
|
+
| 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. |
|
|
145
|
+
| Count unsuccessful runs by observed reason, alongside the cohort size. Keep rate-limit evidence distinct from worker-reported inability to run. | D13 policy refusals, D15 output quality, D17 track record | Compare live intervals by worker, kind and release. A reason breakdown sums to the displayed count. An inferred reason never becomes a confirmed provider refusal. |
|
|
146
|
+
|
|
147
|
+
Verify the combined journey with a synthetic repository: reserve a slot, claim it, verify the input digest, return an exact check, hand back the patch or authorized draft, and observe the native receipt or durable inbox. Repeat with a blocked head and an expired or revoked claim.
|
|
148
|
+
|
|
149
|
+
The D-numbers here are the caller's parity rows. Section 14 names its separate taxonomy and protocol packet identifiers. Fixtures prove the relevant decisions in isolation. Update the deployment parity evidence after the corresponding live requester and worker journeys.
|
|
150
|
+
|
|
133
151
|
## 7. Worker capability (full native ability)
|
|
134
152
|
|
|
135
153
|
### 7.1 Inputs
|
|
@@ -152,7 +170,7 @@ Authority to push is a **standing grant** on the relationship (the C2 #33 author
|
|
|
152
170
|
|
|
153
171
|
### 7.4 What a worker may receive
|
|
154
172
|
|
|
155
|
-
|
|
173
|
+
A repository build can work across the whole authorized repository at the pushed anchor. A declared read-only set remains limited to its authorized paths. Dalan withholds known secret, token and credential files from the delivered inputs and prevents changes to those files through the bridge. File-name and path hints in a build marker describe the job's focus without changing repository authority. Content scanning stays as defense in depth.
|
|
156
174
|
|
|
157
175
|
## 8. What Dalan reports
|
|
158
176
|
|
|
@@ -223,6 +241,8 @@ Where the line is crossed today, and where each piece moves:
|
|
|
223
241
|
| Patch landing (turning a worker patch into a branch and draft PR) done by operator tooling | Tooling doing bridge work | Dalan's materialize step, under the owner's standing grant (section 7.3). Tooling keeps only its own merge policy. |
|
|
224
242
|
| Admission decisions in an operator gate (deny, then override on repeat) | Tooling doing bridge work | Dalan's admission answer at the call (section 6). An operator gate may still apply its own routing policy on top. |
|
|
225
243
|
|
|
244
|
+
Operator filler and campaign queues use the public API. Dalan works with zero filler: ordinary callers hand coding jobs to their compatible remote child by default (section 4). Measure that requester demand outside the bridge. Dalan owns only which admitted work is eligible, when a worker can claim it, and what the caller sees (D1, D2 and D17).
|
|
245
|
+
|
|
226
246
|
Test for the rule: a second operator with no fleet could install Dalan, use every requester route, and see no name or rule from this operator. And this operator's tooling keeps working across a Dalan schema change.
|
|
227
247
|
|
|
228
248
|
## 13. Consumers and the product-neutrality check
|
package/package.json
CHANGED
package/src/acp-bridge.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { promisify } from 'node:util';
|
|
|
12
12
|
import { packRepoDiff, stripPacked } from './acp-context.mjs';
|
|
13
13
|
import { hostCheckRefusal } from './host-execution-policy.mjs';
|
|
14
14
|
import { redactLogEntry } from './redaction.mjs';
|
|
15
|
-
import { isLiteralScopePath, submissionLimits } from './submission-policy.mjs';
|
|
15
|
+
import { isLiteralScopePath, submissionLimits, matchesCredentialPathTerm, withheldRepoPath } from './submission-policy.mjs';
|
|
16
16
|
import { readablePath } from './path-syntax.mjs';
|
|
17
17
|
import { readOrCreateSecret, ownerToken } from './owner-capability.mjs';
|
|
18
18
|
import { CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock, parseIdentity } from '../integrations/t3/acp-kit/src/t3-envelope.mjs';
|
|
@@ -494,13 +494,18 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
|
|
|
494
494
|
if (build && (!context.inputs.length || context.packBase || context.note))
|
|
495
495
|
throw new Refusal(env.DOT_ACP_TEXT_ONLY === '1' ? BUILD_NEEDS_PUSHED : await buildCheckoutRefusal(cwd, options));
|
|
496
496
|
let denyPathTerms;
|
|
497
|
+
let brief=request.brief;
|
|
497
498
|
if (build) {
|
|
498
499
|
const policy = buildRepositoryPolicy(context.inputs[0].github_repo, env);
|
|
499
500
|
if (policy.reason) throw new Refusal(policy.reason);
|
|
500
501
|
denyPathTerms = policy.terms;
|
|
502
|
+
const [marker,...body]=brief.split('\n');
|
|
503
|
+
const hints=marker.trim().split(/[ ]+/).slice(1)
|
|
504
|
+
.filter(file=>!matchesCredentialPathTerm(file,denyPathTerms)&&!withheldRepoPath(file));
|
|
505
|
+
brief=[[BUILD_MARKER,...hints].join(' '),...body].join('\n');
|
|
501
506
|
}
|
|
502
507
|
// Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
|
|
503
|
-
let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, denyPathTerms }), acp_brief_hash: sha256(request.brief), ...(explicitRead ? { scope_paths: explicitRead.scope, read_paths: explicitRead.scope } : {}) };
|
|
508
|
+
let assignment = { ...buildAssignment({ ...request, brief, inputs: context.inputs, build, denyPathTerms }), acp_brief_hash: sha256(request.brief), ...(explicitRead ? { scope_paths: explicitRead.scope, read_paths: explicitRead.scope } : {}) };
|
|
504
509
|
let packedPaths = new Set();
|
|
505
510
|
if (context.packBase) ({ assignment, packedPaths } = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE));
|
|
506
511
|
else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
|
package/src/server.mjs
CHANGED
|
@@ -196,13 +196,14 @@ function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_M
|
|
|
196
196
|
|
|
197
197
|
// A normal workspace reader can get the already-verified inputs in one reply. The explicit registry
|
|
198
198
|
// artifact still has its own narrower grant and delivery receipts. This never fetches a missing mirror.
|
|
199
|
-
function
|
|
199
|
+
function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_offset:offset=0,input_sha256:expected}) {
|
|
200
200
|
const {worker,subject}=principal;
|
|
201
201
|
const {assignment,request_id:requestId}=row;
|
|
202
|
-
if(!workspaceEnabled||row.status!=='claimed'||row.cancelled_at||assignment.execution_scope!=='read-only'||
|
|
202
|
+
if(!claimId||!workspaceEnabled||row.status!=='claimed'||row.cancelled_at||assignment.execution_scope!=='read-only'||
|
|
203
203
|
assignment.paged_read_scope||!assignment.scope_paths?.length||assignment.scope_paths.includes('.')) return {};
|
|
204
204
|
const grant=store.liveHeldClaim(requestId,claimId,subject,worker);
|
|
205
205
|
if(!grant) return {};
|
|
206
|
+
if(offset%scopedSourceChunk!==0||(offset!==0&&!expected)) throw new Error('invalid pinned input offset');
|
|
206
207
|
try {
|
|
207
208
|
if(oauth) needScope(principal,scopeFor('read_file'));
|
|
208
209
|
if(!workerWorkspaceAllowed(worker,requestId)) return {};
|
|
@@ -211,12 +212,20 @@ function inlinePinnedSource(row,principal,connectionId,claimId) {
|
|
|
211
212
|
const input=assignmentInput(assignment);
|
|
212
213
|
if(input.input_patch) return {};
|
|
213
214
|
const mirror=mirrorPath(input.github_repo,{worker});
|
|
214
|
-
const {manifest,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,
|
|
215
|
-
|
|
215
|
+
const {manifest,refusedPaths,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,SCOPED_SOURCE_MAX_BYTES,input.head_sha??input.base_sha);
|
|
216
|
+
if(expected!==undefined&&expected!==sha256) return {pinned_input_error:'bundle_changed'};
|
|
217
|
+
if(offset>=bytes.length) return {pinned_input_error:'offset_out_of_range'};
|
|
218
|
+
const end=Math.min(offset+scopedSourceChunk,bytes.length);
|
|
219
|
+
const bundle={sha256,pin:manifest.pin,encoding:'base64-json',size:bytes.length,offset,
|
|
220
|
+
next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
|
|
216
221
|
if(JSON.stringify(redactOutput(bundle))!==JSON.stringify(bundle)) return {};
|
|
222
|
+
store.recordScopedInputChunk(requestId,{
|
|
223
|
+
epoch:grant.epoch,worker,sha256,chunk:offset/scopedSourceChunk,chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
|
|
224
|
+
metadata:{...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})},
|
|
225
|
+
});
|
|
217
226
|
return {pinned_input_bundle:bundle};
|
|
218
227
|
} catch {
|
|
219
|
-
//
|
|
228
|
+
// An unavailable snapshot must not discard a valid claim or deny ordinary workspace reads.
|
|
220
229
|
return {};
|
|
221
230
|
}
|
|
222
231
|
}
|
|
@@ -582,8 +591,10 @@ if(batchClaimProfile) {
|
|
|
582
591
|
// No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
|
|
583
592
|
// The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
|
|
584
593
|
const get=tools.find(item=>item.name==='get');
|
|
585
|
-
get.description='Read assignment, available checks and delivery facts. For your active claim, pass claim_id to refresh activity and receive heartbeat guidance.
|
|
586
|
-
get.inputSchema.properties
|
|
594
|
+
get.description='Read assignment, available checks and delivery facts. For your active claim, pass claim_id to refresh activity and receive heartbeat guidance. For pinned read-only input, decode pinned_input_bundle.data_base64. If next_offset is present, pass it as input_offset and the same bundle sha256 as input_sha256; concatenate decoded bytes as one JSON bundle.';
|
|
595
|
+
Object.assign(get.inputSchema.properties,{
|
|
596
|
+
claim_id:string,input_offset:{type:'integer',minimum:0,maximum:SCOPED_SOURCE_MAX_BYTES},input_sha256:hashField,
|
|
597
|
+
});
|
|
587
598
|
}
|
|
588
599
|
// Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
|
|
589
600
|
if(catalogProfile==='legacy-v46') {
|
|
@@ -1450,9 +1461,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1450
1461
|
if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
|
|
1451
1462
|
store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
|
|
1452
1463
|
const row=store.get(requestId);
|
|
1453
|
-
const claimId=a.claim_id??(row.claim?.epoch===1?row.claim.claim_id:undefined);
|
|
1454
1464
|
return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),
|
|
1455
|
-
...
|
|
1465
|
+
...pinnedSourceReply(row,principal,connectionId,a),guidance:store.guidanceFor(worker)};
|
|
1456
1466
|
}
|
|
1457
1467
|
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};}
|
|
1458
1468
|
case 'progress': {
|
|
@@ -1801,7 +1811,9 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1801
1811
|
},
|
|
1802
1812
|
preflight:p=>preflightPR(p),
|
|
1803
1813
|
// Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
|
|
1804
|
-
state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,
|
|
1814
|
+
state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,
|
|
1815
|
+
worker_break:store.holdingBreak(r.target),
|
|
1816
|
+
...store.admissionQueueCounts(r.target,body.background===true?'background':'normal',body.caller_waiting===true,supersedes?.target_id??null)}),
|
|
1805
1817
|
kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
|
|
1806
1818
|
defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
|
|
1807
1819
|
retryAfterSeconds:r=>{const w=store.queueWaitsMs(r.target,r.meta?.task_kind??(r.review?'review':'unknown'));return w.length?Math.min(3600,Math.max(60,Math.round(w[Math.floor(w.length/2)]/1000))):300;},
|
package/src/store.mjs
CHANGED
|
@@ -1426,6 +1426,7 @@ export class Store {
|
|
|
1426
1426
|
const aheadRows=this.db.prepare(`SELECT request_id,created_at,
|
|
1427
1427
|
EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments
|
|
1428
1428
|
WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
|
|
1429
|
+
AND ${noPrClaimBlock('assignments')}
|
|
1429
1430
|
AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)
|
|
1430
1431
|
AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
|
|
1431
1432
|
.all(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
|
|
@@ -1816,10 +1817,10 @@ export class Store {
|
|
|
1816
1817
|
if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
|
|
1817
1818
|
// Waiting callers count only waiting peers of the same priority; backlog cannot refuse them.
|
|
1818
1819
|
// Other callers keep the same-priority cap.
|
|
1819
|
-
const queued=this.
|
|
1820
|
+
const queued=this.admissionQueueCounts(targetWorker??'dot',priority,callerWaiting,supersededId).queued_same_priority;
|
|
1820
1821
|
if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
|
|
1821
1822
|
}
|
|
1822
|
-
if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
|
|
1823
|
+
if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
|
|
1823
1824
|
// The target is a column, not payload: an omitted worker means 'dot'.
|
|
1824
1825
|
this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities,delivery_adapter,delivery_address,delivery_adapter_version,caller_waiting) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null,deliveryAdapter,deliveryAddress,deliveryAdapterVersion,callerWaiting?1:0);
|
|
1825
1826
|
if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
|
|
@@ -2100,6 +2101,12 @@ export class Store {
|
|
|
2100
2101
|
this.db.prepare('INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,?)').run(eventId,'event',id,sub.id,body,this.stamp(),wakeKind);
|
|
2101
2102
|
return eventId;
|
|
2102
2103
|
}
|
|
2104
|
+
admissionQueueCounts(worker,priority,callerWaiting,excludeId=null) {
|
|
2105
|
+
return this.db.prepare(`SELECT count(*) queued,
|
|
2106
|
+
count(*) FILTER (WHERE priority=? AND (?=0 OR caller_waiting=1)) queued_same_priority
|
|
2107
|
+
FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND ${live(this.nowMs())}
|
|
2108
|
+
AND ${noPrClaimBlock('assignments')}`).get(priority,callerWaiting?1:0,worker,excludeId);
|
|
2109
|
+
}
|
|
2103
2110
|
// Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
|
|
2104
2111
|
queuedRows() {
|
|
2105
2112
|
return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} AND ${noPrClaimBlock('a')} ORDER BY ${LIST_ORDER}`).all();
|
|
@@ -4045,6 +4052,14 @@ export class Store {
|
|
|
4045
4052
|
if(row.kind==='event'&&row.request_id&&this.isProtocolJob(row.request_id)&&!this.protocolListingLive(row.request_id)) {
|
|
4046
4053
|
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='protocol retention expired' WHERE id=?").run(id);return null;
|
|
4047
4054
|
}
|
|
4055
|
+
if(row.kind==='event'&&(row.wake_kind==='submit'||row.wake_kind==='rewake')) {
|
|
4056
|
+
const blocked=this.db.prepare(`SELECT 1 FROM pr_claim_blocks
|
|
4057
|
+
WHERE request_id IN (?1,CASE WHEN json_valid(?2) THEN json_extract(?2,'$.data.request_id') END)`).get(row.request_id,row.body);
|
|
4058
|
+
if(blocked) {
|
|
4059
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='queued PR is blocked' WHERE id=?").run(id);
|
|
4060
|
+
return null;
|
|
4061
|
+
}
|
|
4062
|
+
}
|
|
4048
4063
|
// A re-wake no longer valid is suppressed unsent: it is no last wake, so the next tick recomputes the head. A still
|
|
4049
4064
|
// valid retry keeps its id and body.
|
|
4050
4065
|
const stale=row.wake_kind==='rewake'&&this.rewakeStale(row);
|
|
@@ -4328,7 +4343,7 @@ export class Store {
|
|
|
4328
4343
|
// Queued counts are live: rows past valid_until are reported as queued_expired, and protocol jobs past retention are
|
|
4329
4344
|
// left out, never counted as queue, cap or throttle room.
|
|
4330
4345
|
const queuedExpired=this.queuedExpired(), queuedExpiredRequeued=this.queuedExpiredRequeued();
|
|
4331
|
-
const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR ${live(this.nowMs())} GROUP BY status`).all().filter(x=>x.count>0);
|
|
4346
|
+
const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR (${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}) GROUP BY status`).all().filter(x=>x.count>0);
|
|
4332
4347
|
const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
|
|
4333
4348
|
const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
|
|
4334
4349
|
const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}`).get().oldest;
|
|
@@ -4343,7 +4358,7 @@ export class Store {
|
|
|
4343
4358
|
SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
|
|
4344
4359
|
const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')} LIMIT 1`).get();
|
|
4345
4360
|
const subscription={state:!sub?'absent':sub.state==='revoked'?'revoked':sub.rotation_blocked?'rotation_blocked':sub.auth_failures>=3?'callback_blocked':sub.expires_at<=this.stamp()?'expired':'active',expires_at:sub?.expires_at||null,last_verified_at:sub?.verified_at||null,last_event_2xx_at:sub?.last_event_2xx_at||null,last_claim_at:lastClaim,principal:sub?.principal||null,auth_failures:sub?.auth_failures||0};
|
|
4346
|
-
const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR ${live(this.nowMs())})`).get(priority,status).n]))]));
|
|
4361
|
+
const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR (${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}))`).get(priority,status).n]))]));
|
|
4347
4362
|
const throttle=this.rollingUsage(limits);
|
|
4348
4363
|
const budget={window:'rolling_24h',calls_used:throttle.tool_calls_last_24h,calls_cap:throttle.max_tool_calls_per_24h,
|
|
4349
4364
|
bytes_used:throttle.response_bytes_last_24h,bytes_cap:throttle.max_response_bytes_per_24h};
|