@tnunamak/dalan 0.9.8 → 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.
- package/CHANGELOG.md +8 -0
- package/bin/dot-acp-agent.mjs +145 -28
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +58 -2
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +5 -1
- package/package.json +1 -1
- package/src/acp-bridge.mjs +23 -11
- package/src/as-files.mjs +6 -3
- package/src/cli-help.mjs +4 -2
- package/src/get-summary.mjs +5 -0
- package/src/local-attachment-authority.mjs +174 -0
- package/src/local-attachment-capture.mjs +136 -0
- package/src/local-attachment-cli.mjs +46 -0
- package/src/local-attachment-gateway.mjs +93 -0
- package/src/local-attachment-owner-verify.mjs +152 -0
- package/src/local-attachment-result.mjs +64 -0
- package/src/local-attachment-snapshot.mjs +142 -0
- package/src/mcp-stdio.mjs +189 -7
- package/src/patch-apply.mjs +28 -6
- package/src/publication-authority.mjs +1 -0
- package/src/pull-pacing.mjs +10 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +53 -16
- package/src/store.mjs +199 -15
- package/src/tool-registry.mjs +15 -4
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
|
@@ -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,4 +1,4 @@
|
|
|
1
|
-
import { createPullPacing, maxBatchPull } from './pull-pacing.mjs';
|
|
1
|
+
import { createPullPacing, describePullOffer, maxBatchPull } from './pull-pacing.mjs';
|
|
2
2
|
import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
|
|
3
3
|
import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
4
4
|
import {inspect} from 'node:util';
|
|
@@ -180,6 +180,12 @@ if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
|
|
|
180
180
|
const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
|
|
181
181
|
const pullPacing=createPullPacing({now:()=>store.nowMs(),log});
|
|
182
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
|
+
|
|
183
189
|
const scopedSourceChunk=18*1024;
|
|
184
190
|
function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin) {
|
|
185
191
|
const {manifest,blobs,refusedPaths}=pinnedScopedSource(mirror,assignment,maxBytes,pin);
|
|
@@ -196,8 +202,8 @@ function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_M
|
|
|
196
202
|
return {manifest,refusedPaths,bytes,sha256};
|
|
197
203
|
}
|
|
198
204
|
|
|
199
|
-
//
|
|
200
|
-
//
|
|
205
|
+
// Inline pinned inputs require the same assignment-scoped grant as the registry artifact.
|
|
206
|
+
// This never fetches a missing mirror.
|
|
201
207
|
function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_offset:offset=0,input_sha256:expected}) {
|
|
202
208
|
const {worker,subject}=principal;
|
|
203
209
|
const {assignment,request_id:requestId}=row;
|
|
@@ -205,22 +211,29 @@ function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_of
|
|
|
205
211
|
assignment.paged_read_scope||!assignment.scope_paths?.length||assignment.scope_paths.includes('.')) return {};
|
|
206
212
|
const grant=store.liveHeldClaim(requestId,claimId,subject,worker);
|
|
207
213
|
if(!grant) return {};
|
|
214
|
+
const binding={request_id:requestId,claim_id:claimId};
|
|
215
|
+
const canRead=()=>toolRegistry.hasScopedReadGrant(scopedInputRegistration.name,worker,binding);
|
|
216
|
+
if(!canRead()) return {};
|
|
208
217
|
if(offset%scopedSourceChunk!==0||(offset!==0&&!expected)) throw new Error('invalid pinned input offset');
|
|
209
218
|
try {
|
|
210
219
|
if(oauth) needScope(principal,scopeFor('read_file'));
|
|
211
220
|
if(!workerWorkspaceAllowed(worker,requestId)) return {};
|
|
212
221
|
assertRepoAllowed(worker,assignment);
|
|
213
222
|
store.assertMutationConnection(requestId,grant,connectionId);
|
|
223
|
+
if(hasUnqualifiedLocalAttachment(requestId))return {pinned_input_error:'attachment_recipient_unavailable'};
|
|
214
224
|
const input=assignmentInput(assignment);
|
|
215
225
|
if(input.input_patch) return {};
|
|
216
226
|
const mirror=mirrorPath(input.github_repo,{worker});
|
|
217
227
|
const {manifest,refusedPaths,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,SCOPED_SOURCE_MAX_BYTES,input.head_sha??input.base_sha);
|
|
228
|
+
if(manifest.files.some(file=>!assignment.scope_paths.includes(file.path))) return {};
|
|
229
|
+
if(!canRead()||!store.liveHeldClaim(requestId,claimId,subject,worker)) return {};
|
|
218
230
|
if(expected!==undefined&&expected!==sha256) return {pinned_input_error:'bundle_changed'};
|
|
219
231
|
if(offset>=bytes.length) return {pinned_input_error:'offset_out_of_range'};
|
|
220
232
|
const end=Math.min(offset+scopedSourceChunk,bytes.length);
|
|
221
233
|
const bundle={sha256,pin:manifest.pin,encoding:'base64-json',size:bytes.length,offset,
|
|
222
234
|
next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
|
|
223
235
|
if(JSON.stringify(redactOutput(bundle))!==JSON.stringify(bundle)) return {};
|
|
236
|
+
if(!canRead()||!store.liveHeldClaim(requestId,claimId,subject,worker)) return {};
|
|
224
237
|
store.recordScopedInputChunk(requestId,{
|
|
225
238
|
epoch:grant.epoch,worker,sha256,chunk:offset/scopedSourceChunk,chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
|
|
226
239
|
metadata:{...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})},
|
|
@@ -285,6 +298,7 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
|
|
|
285
298
|
if(row.status!=='claimed'||row.cancelled_at) throw new Error('assignment is not claimed');
|
|
286
299
|
const claim=store.assertClaim(requestId,claimId,subject,worker);
|
|
287
300
|
store.assertMutationConnection(requestId,claim,connection);
|
|
301
|
+
if(hasUnqualifiedLocalAttachment(requestId))throw new Error('attachment_recipient_unavailable');
|
|
288
302
|
if(row.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
|
|
289
303
|
if(!workspaceEnabled||!workerWorkspaceAllowed(worker,requestId)) throw new Error('capability_not_enabled');
|
|
290
304
|
assertRepoAllowed(worker,row.assignment);
|
|
@@ -976,8 +990,9 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
|
|
|
976
990
|
function batchRoom(principal,freeSlots) {
|
|
977
991
|
const {worker,subject}=principal;
|
|
978
992
|
const {free_lanes,ready,available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
979
|
-
const
|
|
980
|
-
|
|
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};
|
|
981
996
|
}
|
|
982
997
|
function batchCapacityReply(name,reply,principal,callId,onOffer,freeSlots) {
|
|
983
998
|
if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
|
|
@@ -987,17 +1002,19 @@ function batchCapacityReply(name,reply,principal,callId,onOffer,freeSlots) {
|
|
|
987
1002
|
return reply;
|
|
988
1003
|
}
|
|
989
1004
|
const {worker,subject}=principal;
|
|
990
|
-
const {free_lanes,ready,available,desired,next}=batchRoom(principal,freeSlots);
|
|
1005
|
+
const {free_lanes,ready,available,desired,next,evidence}=batchRoom(principal,freeSlots);
|
|
991
1006
|
const ready_queued=ready.length, demand_source=freeSlots===undefined?'hosted_advice':'worker_declared';
|
|
992
1007
|
const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
|
|
993
1008
|
store.paused()?['paused','Claims are paused; call list_pending again later.']:
|
|
994
1009
|
next>0?['ready',`claim with next=${next} now`]:
|
|
995
1010
|
available===0?['lanes_full','Continue held work and finish one before claiming more.']:
|
|
996
|
-
ready_queued>0&&desired===0?['no_worker_slots',
|
|
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.']:
|
|
997
1014
|
['no_ready_work','No ready queued work; call list_pending again later.'];
|
|
998
1015
|
const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
|
|
999
1016
|
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};
|
|
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}:{})};
|
|
1001
1018
|
if(recordListing) {
|
|
1002
1019
|
const readyIds=ready.slice(0,recommended_claims).map(item=>item.request_id);
|
|
1003
1020
|
logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims,demand_source,ready_head_ids:readyIds});
|
|
@@ -1290,7 +1307,7 @@ async function tool(name,a,principal,notifyMeta,signal,batchMode=null,registryDe
|
|
|
1290
1307
|
try {
|
|
1291
1308
|
const rid=a?.request_id;
|
|
1292
1309
|
if(typeof rid==='string'&&rid!==absentId&&(registryDefinition||toolNames.has(name))&&!t3Tools.has(name)&&!notifyTools.has(name)) {
|
|
1293
|
-
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 */ }
|
|
1294
1311
|
}
|
|
1295
1312
|
} finally { admittedInFlight--; }
|
|
1296
1313
|
}
|
|
@@ -1395,7 +1412,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1395
1412
|
sweepExpired();
|
|
1396
1413
|
// Strict commands validate authority, replay and revision in their transaction.
|
|
1397
1414
|
// The legacy implicit touch would mutate activity before a rejected CAS.
|
|
1398
|
-
|
|
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;
|
|
1399
1417
|
if(typeof a.request_id==='string') phaseTrace.action({requestId:a.request_id,tool:name,subject});
|
|
1400
1418
|
// Workspace tools (every one, reads included) refuse any caller but the live holding connection. Native jobs skip the implicit
|
|
1401
1419
|
// touch above, so this is their only check; legacy jobs get a second, post-await check. It runs synchronously right before
|
|
@@ -1489,7 +1507,9 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1489
1507
|
if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
|
|
1490
1508
|
store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
|
|
1491
1509
|
const row=store.get(requestId);
|
|
1492
|
-
|
|
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),
|
|
1493
1513
|
...pinnedSourceReply(row,principal,connectionId,a),guidance:store.guidanceFor(worker)};
|
|
1494
1514
|
}
|
|
1495
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};}
|
|
@@ -1506,7 +1526,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1506
1526
|
catch { /* Telemetry never changes a tool result. */ }
|
|
1507
1527
|
}
|
|
1508
1528
|
notifyAttachedWaiter(requestId);
|
|
1509
|
-
return {...receipt,...repaired.marks};
|
|
1529
|
+
return {...receipt,...(!strictJob?store.workerGetLease(requestId,worker,subject,claimId,connectionId,touchedLease):{}),...repaired.marks};
|
|
1510
1530
|
}
|
|
1511
1531
|
case 'ask_question': {
|
|
1512
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);
|
|
@@ -1725,7 +1745,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1725
1745
|
dryRequested=url.pathname==='/submit-preview';
|
|
1726
1746
|
log({kind:'admin_call',route:url.pathname,method:req.method});
|
|
1727
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');
|
|
1728
|
-
if((url.pathname==='/submit'||url.pathname==='/submit-preview')&&body.routing!==undefined)
|
|
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
|
+
}
|
|
1729
1752
|
if(url.pathname==='/submit'||url.pathname==='/submit-preview') {
|
|
1730
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');
|
|
1731
1754
|
// Set before any check below, so every refusal carries typed reasons, answers a dry run with a verdict and is logged.
|
|
@@ -1752,6 +1775,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1752
1775
|
if(catalogProfile!=='protocol-v0')throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
|
|
1753
1776
|
validateProtocol(body.assignment.protocol);
|
|
1754
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]);
|
|
1755
1782
|
let payload=renderAssignment(body.assignment);
|
|
1756
1783
|
if(!payload||payload.schema_version!==1||!payload.brief||!Array.isArray(payload.inputs)||typeof payload.expected_output!=='string'||typeof payload.execution_scope!=='string') {
|
|
1757
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):[];
|
|
@@ -1882,7 +1909,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1882
1909
|
}
|
|
1883
1910
|
admitWorkerAdapter();
|
|
1884
1911
|
}
|
|
1885
|
-
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);
|
|
1886
1913
|
// Only a committed first replacement wakes the TARGET's already-attached waiter.
|
|
1887
1914
|
if(supersedes&&!result.duplicate) {
|
|
1888
1915
|
const targetId=supersedes.target_id,waiter=waiters.get(targetId);
|
|
@@ -1896,6 +1923,12 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1896
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}:{})});
|
|
1897
1924
|
}
|
|
1898
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
|
+
}
|
|
1899
1932
|
if(url.pathname==='/get') {
|
|
1900
1933
|
const requestId=id(url.searchParams.get('id'));
|
|
1901
1934
|
if(!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
|
|
@@ -1906,6 +1939,10 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1906
1939
|
// Read before recording consumption: the response then matches a peek read, which records no consumption.
|
|
1907
1940
|
const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
|
|
1908
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;
|
|
1909
1946
|
const manifests=store.scopedInputManifests(requestId);
|
|
1910
1947
|
if(manifests.length) got.scoped_input_manifests=manifests;
|
|
1911
1948
|
if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
|
|
@@ -1989,7 +2026,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1989
2026
|
if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
|
|
1990
2027
|
} catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
|
|
1991
2028
|
}
|
|
1992
|
-
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});
|
|
1993
2030
|
if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
|
|
1994
2031
|
if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
|
|
1995
2032
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
@@ -2142,7 +2179,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
2142
2179
|
}
|
|
2143
2180
|
if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
|
|
2144
2181
|
const requestId=id(body.id); adminOwner(req,requestId);
|
|
2145
|
-
const result=store.cancelIfQueued(requestId);
|
|
2182
|
+
const result=store.cancelIfQueued(requestId,{key:body.command_key,owner:req.headers['x-owner-capability']});
|
|
2146
2183
|
if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
|
|
2147
2184
|
return json(res,200,result.cancelled?{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:false})}:result);
|
|
2148
2185
|
}
|