@tnunamak/dalan 0.9.10 → 0.9.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/bin/dot-acp-agent.mjs +146 -29
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +71 -5
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +8 -2
- 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 +42 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +96 -33
- package/src/store.mjs +225 -35
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { gitEnv } from './git-env.mjs';
|
|
7
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
8
|
+
|
|
9
|
+
const oid = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
10
|
+
const sha = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
11
|
+
const decode = bytes => new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);
|
|
12
|
+
const error = code => Object.assign(new Error(code),{code});
|
|
13
|
+
const maxBytes = 4 * 1024 * 1024;
|
|
14
|
+
const env = {...gitEnv(),GIT_TERMINAL_PROMPT:'0'};
|
|
15
|
+
const git = (cwd,args,{input,override=env}={})=>{
|
|
16
|
+
const r=spawnSync('git',args,{cwd,env:override,input,maxBuffer:16*1024*1024,timeout:15000});
|
|
17
|
+
if(r.status!==0) throw error('attachment_verification_git_failed');
|
|
18
|
+
return r.stdout;
|
|
19
|
+
};
|
|
20
|
+
function rows(bytes) {
|
|
21
|
+
return decode(bytes).split('\0').filter(Boolean).map(row=>{
|
|
22
|
+
const m=/^(\d+) (\S+) ([a-f0-9]+)\t(.+)$/.exec(row);
|
|
23
|
+
if(!m) throw error('attachment_unsupported_tree_entry');
|
|
24
|
+
return {mode:m[1],type:m[2],oid:m[3],path:m[4]};
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function sealedBytes(data) {
|
|
28
|
+
if(!Buffer.isBuffer(data)||data.length>maxBytes) throw error('attachment_invalid_patch');
|
|
29
|
+
return Buffer.from(data);
|
|
30
|
+
}
|
|
31
|
+
function unchanged(a,b) {
|
|
32
|
+
return a.dev===b.dev&&a.ino===b.ino&&a.mode===b.mode&&a.size===b.size&&
|
|
33
|
+
a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs;
|
|
34
|
+
}
|
|
35
|
+
function liveFile(cwd,rel,expectedMode,expectedOid,format) {
|
|
36
|
+
let file=cwd;
|
|
37
|
+
for(const part of rel.split('/')) {
|
|
38
|
+
if(!part||part==='.'||part==='..'||part.toLowerCase()==='.git') return false;
|
|
39
|
+
file=path.join(file,part);
|
|
40
|
+
const s=fs.lstatSync(file,{bigint:true,throwIfNoEntry:false});
|
|
41
|
+
if(!s||s.isSymbolicLink()) return false;
|
|
42
|
+
}
|
|
43
|
+
const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
|
|
44
|
+
try {
|
|
45
|
+
const before=fs.fstatSync(fd,{bigint:true});
|
|
46
|
+
if(!before.isFile()||fs.realpathSync(file)!==file||(before.mode&0o100n?'100755':'100644')!==expectedMode) return false;
|
|
47
|
+
const hasher=createHash(format).update(`blob ${before.size}\0`);
|
|
48
|
+
const data=Buffer.alloc(65536);
|
|
49
|
+
let bytes=0n;
|
|
50
|
+
for(;;) {
|
|
51
|
+
const n=fs.readSync(fd,data,0,data.length,null);
|
|
52
|
+
if(!n) break;
|
|
53
|
+
bytes+=BigInt(n);
|
|
54
|
+
if(bytes>before.size) return false;
|
|
55
|
+
hasher.update(data.subarray(0,n));
|
|
56
|
+
}
|
|
57
|
+
return bytes===before.size&&unchanged(before,fs.fstatSync(fd,{bigint:true}))&&
|
|
58
|
+
unchanged(before,fs.lstatSync(file,{bigint:true}))&&hasher.digest('hex')===expectedOid;
|
|
59
|
+
} finally {fs.closeSync(fd);}
|
|
60
|
+
}
|
|
61
|
+
function existsOrHasUnsafeAncestor(cwd,rel) {
|
|
62
|
+
let file=cwd;
|
|
63
|
+
const parts=rel.split('/');
|
|
64
|
+
for(const [i,part] of parts.entries()){
|
|
65
|
+
if(!part||part==='..'||part==='.'||part.toLowerCase()==='.git') return true;
|
|
66
|
+
file=path.join(file,part);
|
|
67
|
+
const s=fs.lstatSync(file,{throwIfNoEntry:false});
|
|
68
|
+
if(!s) return false;
|
|
69
|
+
if(i===parts.length-1||!s.isDirectory()||s.isSymbolicLink()) return true;
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Returns a proof and a fresh guard, not permission or a live apply operation.
|
|
75
|
+
// The integration must serialize the final guard with the apply it controls.
|
|
76
|
+
export function verifyLocalAttachmentResult({
|
|
77
|
+
checkout, repo, manifest, manifestSha256, sealedPatch, expectedInputTree,
|
|
78
|
+
outputDelta, deltaBase, expectedOutputTree, expiresAtMs, now=Date.now,
|
|
79
|
+
}) {
|
|
80
|
+
const fresh=()=>{
|
|
81
|
+
if(!Number.isSafeInteger(expiresAtMs)||now()>=expiresAtMs) throw error('attachment_input_expired');
|
|
82
|
+
};
|
|
83
|
+
fresh();
|
|
84
|
+
if(!path.isAbsolute(checkout??'') || typeof repo!=='string' || manifest?.version!==1 || manifest.repo!==repo ||
|
|
85
|
+
![manifest.published_base,manifest.published_tree,manifest.input_tree,deltaBase,expectedOutputTree].every(v=>oid.test(v??'')) ||
|
|
86
|
+
manifest.input_tree!==expectedInputTree || deltaBase!==expectedInputTree ||
|
|
87
|
+
sha(Buffer.from(canonicalJson(manifest)))!==manifestSha256) throw error('attachment_result_binding_mismatch');
|
|
88
|
+
const patch=sealedBytes(sealedPatch), delta=sealedBytes(outputDelta);
|
|
89
|
+
if(sha(patch)!==manifest.patch_sha256) throw error('attachment_patch_digest_mismatch');
|
|
90
|
+
const root=fs.realpathSync(checkout);
|
|
91
|
+
const q=(...args)=>decode(git(root,args)).trimEnd();
|
|
92
|
+
if(q('rev-parse','--show-toplevel')!==root||q('rev-parse',manifest.published_base+'^{commit}')!==manifest.published_base||
|
|
93
|
+
q('rev-parse',manifest.published_base+'^{tree}')!==manifest.published_tree) throw error('attachment_published_tree_mismatch');
|
|
94
|
+
const format=q('rev-parse','--show-object-format'), objects=q('rev-parse','--path-format=absolute','--git-path','objects');
|
|
95
|
+
const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-local-verify-'));
|
|
96
|
+
let inputRows, publishedPaths, additions;
|
|
97
|
+
try {
|
|
98
|
+
git(scratch,['init','--quiet','--bare','--object-format='+format,'repo']);
|
|
99
|
+
const override={...env,GIT_ALTERNATE_OBJECT_DIRECTORIES:JSON.stringify(objects),GIT_INDEX_FILE:path.join(scratch,'index')};
|
|
100
|
+
const privateGit=(args,input)=>git(scratch,['--git-dir='+path.join(scratch,'repo'),...args],{input,override});
|
|
101
|
+
privateGit(['read-tree',manifest.published_tree]);
|
|
102
|
+
if(patch.length) privateGit(['apply','--cached','--whitespace=nowarn','-'],patch);
|
|
103
|
+
if(decode(privateGit(['write-tree'])).trim()!==expectedInputTree) throw error('attachment_input_tree_mismatch');
|
|
104
|
+
inputRows=rows(privateGit(['ls-tree','-r','-z',expectedInputTree]));
|
|
105
|
+
const originRows=rows(privateGit(['ls-tree','-r','-z',manifest.published_tree]));
|
|
106
|
+
const origin=new Map(originRows.map(e=>[e.path,e])),input=new Map(inputRows.map(e=>[e.path,e]));
|
|
107
|
+
publishedPaths=[...origin.keys()];
|
|
108
|
+
const changed=[...new Set([...origin.keys(),...input.keys()])].sort().filter(p=>
|
|
109
|
+
origin.get(p)?.oid!==input.get(p)?.oid||origin.get(p)?.mode!==input.get(p)?.mode);
|
|
110
|
+
if(!Array.isArray(manifest.entries)||manifest.entries.length!==changed.length||!Array.isArray(manifest.omissions)||
|
|
111
|
+
manifest.omissions.some(e=>!e||typeof e.path!=='string'||changed.includes(e.path)))
|
|
112
|
+
throw error('attachment_manifest_entries_mismatch');
|
|
113
|
+
const observed=(e)=>e?sha(privateGit(['cat-file','blob',e.oid])):null;
|
|
114
|
+
for(const [i,p] of changed.entries()){
|
|
115
|
+
const a=origin.get(p),b=input.get(p),e=manifest.entries[i];
|
|
116
|
+
if(!e||e.path!==p||e.disposition!==(!a?'added':!b?'deleted':'modified')||
|
|
117
|
+
e.before_mode!==(a?.mode??null)||e.after_mode!==(b?.mode??null)||
|
|
118
|
+
e.before_sha256!==observed(a)||e.after_sha256!==observed(b)) throw error('attachment_manifest_entries_mismatch');
|
|
119
|
+
}
|
|
120
|
+
if(delta.length) privateGit(['apply','--cached','--whitespace=nowarn','-'],delta);
|
|
121
|
+
if(decode(privateGit(['write-tree'])).trim()!==expectedOutputTree) throw error('attachment_output_tree_mismatch');
|
|
122
|
+
const before=new Map(inputRows.map(e=>[e.path,e]));
|
|
123
|
+
const outputRows=rows(privateGit(['ls-tree','-r','-z',expectedOutputTree]));
|
|
124
|
+
additions=outputRows.filter(e=>!before.has(e.path)).map(e=>e.path);
|
|
125
|
+
if([...inputRows,...outputRows].some(e=>e.type!=='blob'||!['100644','100755'].includes(e.mode))) throw error('attachment_unsupported_tree_entry');
|
|
126
|
+
} finally {fs.rmSync(scratch,{recursive:true,force:true});}
|
|
127
|
+
const assertCallerUnchanged=()=>{
|
|
128
|
+
fresh();
|
|
129
|
+
const beforeHead=q('rev-parse','HEAD');
|
|
130
|
+
try {
|
|
131
|
+
const actualIndex=decode(git(root,['ls-files','-z','--cached'])).split('\0').filter(Boolean);
|
|
132
|
+
const expectedPaths=new Set(inputRows.map(e=>e.path));
|
|
133
|
+
// Extra staged tracked files (including a selected deletion still present in the old index)
|
|
134
|
+
// cannot stand in for actual worktree identity; allow only those whose bytes are absent.
|
|
135
|
+
const extra=[...new Set([...actualIndex,...publishedPaths])].filter(rel=>!expectedPaths.has(rel));
|
|
136
|
+
if(inputRows.some(e=>!liveFile(root,e.path,e.mode,e.oid,format))||
|
|
137
|
+
[...extra,...additions].some(rel=>existsOrHasUnsafeAncestor(root,rel))||
|
|
138
|
+
q('rev-parse','HEAD')!==beforeHead) throw error('attachment_caller_conflict');
|
|
139
|
+
} catch(e) {
|
|
140
|
+
if(['ENOENT','ENOTDIR','ELOOP'].includes(e.code)) throw error('attachment_caller_conflict');
|
|
141
|
+
throw e;
|
|
142
|
+
}
|
|
143
|
+
fresh();
|
|
144
|
+
return true;
|
|
145
|
+
};
|
|
146
|
+
fresh();
|
|
147
|
+
let callerMatches;
|
|
148
|
+
try {callerMatches=assertCallerUnchanged();}
|
|
149
|
+
catch(e) {if(e.code!=='attachment_caller_conflict')throw e;callerMatches=false;}
|
|
150
|
+
return {input_tree:expectedInputTree,output_tree:expectedOutputTree,output_delta_sha256:sha(delta),
|
|
151
|
+
caller_matches:callerMatches,apply_conflict:callerMatches?null:'attachment_caller_conflict',assertCallerUnchanged};
|
|
152
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
import { requesterLocalContextMarker } from './requester-local-context.mjs';
|
|
4
|
+
const digest=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
|
|
5
|
+
const tree=v=>typeof v==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v);
|
|
6
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
7
|
+
const dispositionKey='attachment_standing_publication_forbidden';
|
|
8
|
+
|
|
9
|
+
// Uses only durable server-owned ancestry and binding rows. Treat an unwalkable ancestry as restricted.
|
|
10
|
+
export function localAttachmentPublicationRestriction(db,id,{includeLocalText=true}={}) {
|
|
11
|
+
const pending=[id],seen=new Set();
|
|
12
|
+
const attachment=db.prepare('SELECT 1 FROM local_attachment_bindings WHERE work=?');
|
|
13
|
+
const localBrief=db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND instr(json_extract(payload,'$.brief'),?)>0");
|
|
14
|
+
const parents=db.prepare(`SELECT prior_id AS prior FROM job_revisions WHERE request_id=?
|
|
15
|
+
UNION SELECT prior_id FROM job_follows WHERE request_id=?
|
|
16
|
+
UNION SELECT target_id FROM submit_supersedes WHERE request_id=?`);
|
|
17
|
+
while(pending.length) {
|
|
18
|
+
const next=pending.pop();
|
|
19
|
+
if(seen.has(next))continue;
|
|
20
|
+
if(seen.size>=1024||typeof next!=='string')return 'attachment_lineage_unverified';
|
|
21
|
+
if(attachment.get(next)||(includeLocalText&&localBrief.get(next,requesterLocalContextMarker)))return dispositionKey;
|
|
22
|
+
seen.add(next);
|
|
23
|
+
for(const {prior} of parents.all(next,next,next))pending.push(prior);
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
export function hasLocalAttachment(db,id) {
|
|
28
|
+
return !!db.prepare('SELECT 1 FROM local_attachment_bindings WHERE work=?').get(id);
|
|
29
|
+
}
|
|
30
|
+
export function assertOrdinaryLocalAttachmentBoundary(db,id) {
|
|
31
|
+
if(hasLocalAttachment(db,id)) fail('attachment_requires_verified_result_path');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Owner-side consumer adapter. The caller supplies existing trusted Store and workspace adapters;
|
|
35
|
+
// neither an unverified worker string nor an arbitrary artifact reference is accepted as evidence.
|
|
36
|
+
export function makeLocalAttachmentResultConsumer({db,authority,lookupSealedOutput,readVerifiedReceipt}) {
|
|
37
|
+
if([lookupSealedOutput,readVerifiedReceipt].some(f=>typeof f!=='function'))fail('attachment_result_adapters_required');
|
|
38
|
+
const binding=work=>db.prepare('SELECT identity,binding FROM local_attachment_bindings WHERE work=?').get(work);
|
|
39
|
+
function finish(context,envelope) {
|
|
40
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
41
|
+
const prior=binding(context.work);
|
|
42
|
+
if(!prior){if(envelope!==undefined)fail('attachment_result_without_binding');return null;}
|
|
43
|
+
if(!envelope||Object.keys(envelope).sort().join(',')!=='binding_sha256,delta_artifact_id,delta_sha256,input_tree,output_tree'||
|
|
44
|
+
!digest(envelope.binding_sha256)||envelope.binding_sha256!==prior.identity||
|
|
45
|
+
!digest(envelope.delta_sha256)||!tree(envelope.input_tree)||!tree(envelope.output_tree)||
|
|
46
|
+
envelope.input_tree!==JSON.parse(prior.binding).input_tree||
|
|
47
|
+
typeof envelope.delta_artifact_id!=='string'||!/^art_[A-Za-z0-9_-]{8,128}$/.test(envelope.delta_artifact_id))fail('attachment_result_envelope_invalid');
|
|
48
|
+
const art=lookupSealedOutput({work:context.work,id:envelope.delta_artifact_id});
|
|
49
|
+
if(art?.work!==context.work||art?.id!==envelope.delta_artifact_id||art?.sha256!==envelope.delta_sha256||
|
|
50
|
+
art?.origin_claim!==context.claim_id||art?.origin_epoch!==context.epoch||art?.sealed!==true)
|
|
51
|
+
fail('attachment_output_artifact_not_bound');
|
|
52
|
+
const result_sha256=createHash('sha256').update(canonicalJson(envelope)).digest('hex');
|
|
53
|
+
return authority.finish({...context,input_tree:envelope.input_tree,output_tree:envelope.output_tree,result_sha256});
|
|
54
|
+
}
|
|
55
|
+
function accept(context,verificationId) {
|
|
56
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
57
|
+
const prior=binding(context.work);
|
|
58
|
+
if(!prior)fail('attachment_result_without_binding');
|
|
59
|
+
const receipt=readVerifiedReceipt({work:context.work,id:verificationId});
|
|
60
|
+
if(receipt?.work!==context.work||receipt.binding_sha256!==prior.identity||!digest(receipt.result_sha256))fail('attachment_verification_not_bound');
|
|
61
|
+
return authority.accept({...context,verification_id:verificationId,result_sha256:receipt.result_sha256});
|
|
62
|
+
}
|
|
63
|
+
return {finish,accept};
|
|
64
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { canonicalJson } from '../packages/job-core/protocol/canonical.mjs';
|
|
3
|
+
import { captureLocalAttachment } from './local-attachment-capture.mjs';
|
|
4
|
+
import { verifyLocalAttachmentResult } from './local-attachment-owner-verify.mjs';
|
|
5
|
+
|
|
6
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
7
|
+
const digest = value => /^[a-f0-9]{64}$/.test(value ?? '');
|
|
8
|
+
const fail = code => { throw Object.assign(new Error(code), {code}); };
|
|
9
|
+
const maxPatch = 4 * 1024 * 1024;
|
|
10
|
+
const fields = ['relationship_side', 'principal', 'route', 'adapter_binding', 'address'];
|
|
11
|
+
function exactRecipient(value) {
|
|
12
|
+
if (!value || !fields.every(k => typeof value[k] === 'string' &&
|
|
13
|
+
value[k].length > 0 && value[k].length <= 512 && !/[\x00-\x1f\x7f]/.test(value[k]))) {
|
|
14
|
+
fail('attachment_recipient_unavailable');
|
|
15
|
+
}
|
|
16
|
+
return Object.fromEntries(fields.map(k => [k, value[k]]));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// This seam is not a transport or authentication endpoint. The owner supplies
|
|
20
|
+
// synchronous trusted adapters; writes run in the same transaction as authority.
|
|
21
|
+
// putArtifact must stage a sealed artifact in that transaction, not deliver bytes.
|
|
22
|
+
export function localAttachmentSnapshots({db, authority, now, resolveRecipient, hasConsent, putArtifact, getArtifact}) {
|
|
23
|
+
if ([now, resolveRecipient, hasConsent, putArtifact, getArtifact,
|
|
24
|
+
authority?.assertOwner, authority?.assertLiveWorker].some(f => typeof f !== 'function')) {
|
|
25
|
+
fail('attachment_snapshot_adapters_unavailable');
|
|
26
|
+
}
|
|
27
|
+
function clock() {
|
|
28
|
+
const n = now();
|
|
29
|
+
if (!Number.isSafeInteger(n) || n < 0) fail('attachment_clock_unavailable');
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
32
|
+
function check(intent, context) {
|
|
33
|
+
if (clock() >= intent.expires_at) fail('attachment_input_expired');
|
|
34
|
+
const resolved = exactRecipient(resolveRecipient(context));
|
|
35
|
+
if (canonicalJson(resolved) !== canonicalJson(intent.recipient)) fail('attachment_audience_mismatch');
|
|
36
|
+
if (hasConsent(intent, context) !== true) fail('attachment_consent_unavailable');
|
|
37
|
+
return resolved;
|
|
38
|
+
}
|
|
39
|
+
function tx() {
|
|
40
|
+
if (!db.isTransaction) fail('transaction_required');
|
|
41
|
+
}
|
|
42
|
+
function intentFor(work, recipient, manifest_sha256, patch_sha256, expires_at) {
|
|
43
|
+
if (typeof work !== 'string' || !work || !digest(manifest_sha256) ||
|
|
44
|
+
!digest(patch_sha256) || !Number.isSafeInteger(expires_at)) fail('attachment_invalid_snapshot');
|
|
45
|
+
return {work, recipient: exactRecipient(recipient), manifest_sha256, patch_sha256, expires_at};
|
|
46
|
+
}
|
|
47
|
+
function proof(checkout, manifest, intent, patch, delta, deltaBase, outputTree) {
|
|
48
|
+
return verifyLocalAttachmentResult({
|
|
49
|
+
checkout, repo: manifest.repo, manifest, manifestSha256: intent.manifest_sha256,
|
|
50
|
+
sealedPatch: patch, expectedInputTree: manifest.input_tree, outputDelta: delta,
|
|
51
|
+
deltaBase, expectedOutputTree: outputTree, expiresAtMs: intent.expires_at, now: clock,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function seal({owner, work, checkout, repo, publishedBase, paths, policy, approval}) {
|
|
55
|
+
tx();
|
|
56
|
+
const intent = intentFor(work, approval?.recipient, approval?.manifest_sha256,
|
|
57
|
+
approval?.patch_sha256, approval?.expires_at);
|
|
58
|
+
authority.assertOwner(work, owner);
|
|
59
|
+
const context = {work, actor: owner, operation: 'seal'};
|
|
60
|
+
check(intent, context);
|
|
61
|
+
const captureApproved = () => {
|
|
62
|
+
const selected = captureLocalAttachment({checkout, repo, publishedBase, paths, policy});
|
|
63
|
+
if (selected.manifest_sha256 !== intent.manifest_sha256 ||
|
|
64
|
+
selected.manifest.patch_sha256 !== intent.patch_sha256) fail('attachment_snapshot_changed');
|
|
65
|
+
return selected;
|
|
66
|
+
};
|
|
67
|
+
const {manifest, patch, manifest_sha256} = captureApproved();
|
|
68
|
+
check(intent, context);
|
|
69
|
+
const prior = db.prepare('SELECT binding FROM local_attachment_bindings WHERE work=?').get(work);
|
|
70
|
+
const artifact_id = prior ? JSON.parse(prior.binding).artifact_id :
|
|
71
|
+
putArtifact({work, manifest, bytes: Buffer.from(patch), ...intent});
|
|
72
|
+
captureApproved();
|
|
73
|
+
check(intent, context);
|
|
74
|
+
const sealed = authority.seal({work, capability: owner, recipient: intent.recipient, repo,
|
|
75
|
+
published_base: manifest.published_base, published_tree: manifest.published_tree,
|
|
76
|
+
input_tree: manifest.input_tree, artifact_id, expires_at: intent.expires_at,
|
|
77
|
+
manifest_sha256, patch_sha256: intent.patch_sha256});
|
|
78
|
+
check(intent, context);
|
|
79
|
+
return {...sealed, input_tree: manifest.input_tree, omitted: manifest.omissions};
|
|
80
|
+
}
|
|
81
|
+
function authorizeRead({work, actor, claim_id, epoch}) {
|
|
82
|
+
tx();
|
|
83
|
+
const row=db.prepare('SELECT identity,binding FROM local_attachment_bindings WHERE work=?').get(work);
|
|
84
|
+
if(!row)fail('attachment_missing');
|
|
85
|
+
const binding=JSON.parse(row.binding);
|
|
86
|
+
const context={work,actor,claim_id,epoch,operation:'read'};
|
|
87
|
+
const intent=intentFor(work,binding.recipient,binding.manifest_sha256,binding.patch_sha256,binding.expires_at);
|
|
88
|
+
const recipient=check(intent,context);
|
|
89
|
+
const current=authority.admit({work,recipient});
|
|
90
|
+
authority.assertLiveWorker({work,recipient,claim_id,epoch});
|
|
91
|
+
return current;
|
|
92
|
+
}
|
|
93
|
+
function read({work, actor, claim_id, epoch}) {
|
|
94
|
+
tx();
|
|
95
|
+
// Never use the request's own recipient label as authentication.
|
|
96
|
+
const row = db.prepare('SELECT identity,binding FROM local_attachment_bindings WHERE work=?').get(work);
|
|
97
|
+
if (!row) fail('attachment_missing');
|
|
98
|
+
const b = JSON.parse(row.binding);
|
|
99
|
+
const intent = intentFor(work, b.recipient, b.manifest_sha256, b.patch_sha256, b.expires_at);
|
|
100
|
+
const context = {work, actor, claim_id, epoch, operation: 'read'};
|
|
101
|
+
const recipient = check(intent, context);
|
|
102
|
+
const {bytes, binding_sha256} = authority.read({work, recipient, claim_id, epoch});
|
|
103
|
+
const artifact = getArtifact({work, artifact_id: b.artifact_id, mode: 'metadata'});
|
|
104
|
+
const manifest = artifact?.manifest;
|
|
105
|
+
if (artifact?.work !== work || artifact?.sealed !== true || !manifest ||
|
|
106
|
+
hash(canonicalJson(manifest)) !== intent.manifest_sha256 ||
|
|
107
|
+
manifest.input_tree !== b.input_tree || manifest.published_tree !== b.published_tree ||
|
|
108
|
+
manifest.published_base !== b.published_base || manifest.repo !== b.repo ||
|
|
109
|
+
manifest.patch_sha256 !== b.patch_sha256 || binding_sha256 !== row.identity ||
|
|
110
|
+
bytes.length > maxPatch) fail('attachment_artifact_mismatch');
|
|
111
|
+
// Final consent check after artifact adapters; a throw rolls back served bookkeeping.
|
|
112
|
+
check(intent, context);
|
|
113
|
+
authority.assertLiveWorker({work, recipient, claim_id, epoch});
|
|
114
|
+
return {binding_sha256, manifest: JSON.parse(canonicalJson(manifest)), bytes};
|
|
115
|
+
}
|
|
116
|
+
// Owner-only reassembly/proof. The caller never becomes the worker's patch target.
|
|
117
|
+
// A caller that changes after this proof still needs assertCallerUnchanged at apply time.
|
|
118
|
+
function verify({work, owner, checkout, binding_sha256, outputDelta, deltaBase, outputTree}) {
|
|
119
|
+
tx();
|
|
120
|
+
const row = db.prepare('SELECT identity,binding FROM local_attachment_bindings WHERE work=?').get(work);
|
|
121
|
+
if (!row || row.identity !== binding_sha256) fail('attachment_result_binding_mismatch');
|
|
122
|
+
const b = JSON.parse(row.binding);
|
|
123
|
+
const intent = intentFor(work, b.recipient, b.manifest_sha256, b.patch_sha256, b.expires_at);
|
|
124
|
+
const context = {work, actor: owner, operation: 'verify'};
|
|
125
|
+
check(intent, context);
|
|
126
|
+
const retained = authority.reopen({work, capability: owner, includeBytes:true});
|
|
127
|
+
if (retained.revoked_at !== null) fail('attachment_revoked');
|
|
128
|
+
const artifact = getArtifact({work, artifact_id:b.artifact_id, mode:'metadata'});
|
|
129
|
+
if (!artifact?.manifest || artifact.work !== work || artifact.sealed !== true ||
|
|
130
|
+
!Buffer.isBuffer(retained.bytes) || deltaBase !== b.input_tree) fail('attachment_artifact_mismatch');
|
|
131
|
+
const result = proof(checkout, artifact.manifest, intent, retained.bytes, outputDelta, deltaBase, outputTree);
|
|
132
|
+
result.assertCallerUnchanged();
|
|
133
|
+
check(intent, context);
|
|
134
|
+
return {...result, assertCallerUnchanged() {
|
|
135
|
+
result.assertCallerUnchanged();
|
|
136
|
+
check(intent, context);
|
|
137
|
+
if (authority.reopen({work, capability:owner}).revoked_at !== null) fail('attachment_revoked');
|
|
138
|
+
return true;
|
|
139
|
+
}};
|
|
140
|
+
}
|
|
141
|
+
return {seal, read, verify, authorizeRead};
|
|
142
|
+
}
|
package/src/mcp-stdio.mjs
CHANGED
|
@@ -3,18 +3,29 @@
|
|
|
3
3
|
// CLI command with --json, so owner receipts, admin-socket access, assignment checks and verdicts stay in one place.
|
|
4
4
|
// Trust is the CLI's: whoever can run `dalan` here (the admin socket) can use these tools.
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
|
-
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
7
9
|
import path from 'node:path';
|
|
8
10
|
import { redactOutput, redactSinkText } from './redaction.mjs';
|
|
9
11
|
import { safeDiagnostic } from './diagnostic.mjs';
|
|
12
|
+
import { failureTypes } from './failure-type.mjs';
|
|
10
13
|
import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
|
|
14
|
+
import { adminRequest } from './acp-bridge.mjs';
|
|
15
|
+
import { adminSocketPath } from './admin-socket.mjs';
|
|
16
|
+
import { defaultPath, ownerReceiptFile } from './paths.mjs';
|
|
17
|
+
import { writeAtomic } from './as-files.mjs';
|
|
18
|
+
import { serviceHomeFor } from './default-home.mjs';
|
|
19
|
+
import { ownerToken, readOrCreateSecret } from './owner-capability.mjs';
|
|
20
|
+
import { captureRequesterLocalContext, withRequesterLocalContext } from './requester-local-context.mjs';
|
|
21
|
+
import { sensitivePolicyPaths } from './submission-policy.mjs';
|
|
11
22
|
import { createTaskRoute, TaskError, TASKS_CAPABILITIES, TASKS_EXTENSION } from './mcp-tasks.mjs';
|
|
12
23
|
|
|
13
24
|
const MODERN_VERSION = '2026-07-28';
|
|
14
25
|
const VERSION_META = 'io.modelcontextprotocol/protocolVersion';
|
|
15
26
|
const CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities';
|
|
16
27
|
const SERVER_INFO = { name: 'dalan-mcp', version: '1' };
|
|
17
|
-
const INSTRUCTIONS = 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it; on a waiting question call dalan_questions, dalan_answer, then dalan_wait again. dalan_result reads the report, dalan_status shows the bridge.';
|
|
28
|
+
const INSTRUCTIONS = 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it; on a waiting question call dalan_questions, dalan_answer, then dalan_wait again. dalan_result reads the report, dalan_status shows the bridge. For reconnectable ordinary work, start with dalan_work_offer and save the two returned IDs.';
|
|
18
29
|
const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
19
30
|
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
20
31
|
export const RESULT_CAP_BYTES = 32 * 1024;
|
|
@@ -93,6 +104,33 @@ export const TOOLS = [
|
|
|
93
104
|
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
94
105
|
annotations: { title: 'Bridge status', readOnlyHint: true, openWorldHint: false } }
|
|
95
106
|
];
|
|
107
|
+
const handleId = {type:'string',pattern:'^sg_[A-Za-z0-9_-]{22,80}$'};
|
|
108
|
+
const nativePolicy = {type:'boolean',description:'Refuse ordinary work if native MCP Tasks semantics are required.'};
|
|
109
|
+
const workIdProps = {subagent_id:handleId,request_id:requestId};
|
|
110
|
+
const localSelectionProps = {
|
|
111
|
+
local_context_file:{type:'string',description:'One relative Markdown or text file in the local operator-configured requester context root.'},
|
|
112
|
+
require_local_context:{type:'boolean',description:'Refuse without creating a job if no local_context_file is provided.'},
|
|
113
|
+
};
|
|
114
|
+
function workTool(name,title,description,properties,required,readOnlyHint=false,destructiveHint=false) {
|
|
115
|
+
return {name,title,description,inputSchema:{type:'object',additionalProperties:false,properties,required},
|
|
116
|
+
annotations:{title,readOnlyHint,destructiveHint,idempotentHint:true,openWorldHint:false}};
|
|
117
|
+
}
|
|
118
|
+
const workTools = [
|
|
119
|
+
workTool('dalan_work_offer','Offer continuing work','Submit immediately and return durable work IDs, without waiting or using native Tasks.',
|
|
120
|
+
{...submitProperties,subagent_id:handleId,require_native_tasks:nativePolicy,...localSelectionProps},['assignment']),
|
|
121
|
+
workTool('dalan_work_recover','Recover continuing work','Read authenticated job history, or the original result for a specified request ID.',
|
|
122
|
+
{...workIdProps,after:{type:'integer',minimum:0}},['subagent_id'],true),
|
|
123
|
+
workTool('dalan_work_follow','Follow up on continuing work','Offer a new request on the same handle after an identified predecessor.',
|
|
124
|
+
{...submitProperties,subagent_id:handleId,prior_request_id:requestId,require_native_tasks:nativePolicy,...localSelectionProps},['assignment','subagent_id','prior_request_id']),
|
|
125
|
+
workTool('dalan_work_questions','Read continuing work questions','Read current clarification questions using the local owner credential.',
|
|
126
|
+
workIdProps,['subagent_id','request_id'],true),
|
|
127
|
+
workTool('dalan_work_answer','Answer a continuing work question','Answer an existing clarification; the owner route enforces question and grant authority.',
|
|
128
|
+
{...workIdProps,question_id:TOOLS.find(t=>t.name==='dalan_answer').inputSchema.properties.question_id,text:{type:'string'}},
|
|
129
|
+
['subagent_id','request_id','question_id','text']),
|
|
130
|
+
workTool('dalan_work_withdraw','Withdraw unaccepted work','Withdraw only still-queued work and return the exact keyed disposition; never cancel a grant.',
|
|
131
|
+
{...workIdProps,command_key:{type:'string',pattern:'^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$'}},
|
|
132
|
+
['subagent_id','request_id','command_key'],false,true),
|
|
133
|
+
];
|
|
96
134
|
const submitTool = TOOLS[0];
|
|
97
135
|
const { dry_run: _dryRun, ...delegateProperties } = submitTool.inputSchema.properties;
|
|
98
136
|
const delegateTool = {
|
|
@@ -188,6 +226,7 @@ const sessionLengthProjection = value => pick(value, ['source', 'n', 'min_sample
|
|
|
188
226
|
const recordProjection = record => ({ ...pick(record, ['worker', 'kind', 'window_days', 'n', 'accepted', 'check_passed']),
|
|
189
227
|
...(record.claim_to_report ? { claim_to_report: claimDurationProjection(record.claim_to_report) } : {}),
|
|
190
228
|
...(record.session_length ? { session_length: sessionLengthProjection(record.session_length) } : {}),
|
|
229
|
+
...(isRecord(record.unable_to_run_reasons) ? { unable_to_run_reasons: pick(record.unable_to_run_reasons, failureTypes) } : {}),
|
|
191
230
|
...(record.outcomes ? { outcomes: pick(record.outcomes, ['landed', 'check_passed', 'checks_failed', 'refused_by_provider', 'unable_to_run', 'owner_cancelled', 'finished_unchecked']) } : {}) });
|
|
192
231
|
export function projectAdmission(admission) {
|
|
193
232
|
const answer = pick(admission, ['start', 'worker_state', 'until', 'until_source', 'at']);
|
|
@@ -209,13 +248,18 @@ const projectAnswer = value => ({ ...value, ...(value.admission ? { admission: p
|
|
|
209
248
|
const forecastAnswer = value => Object.fromEntries(['verdict', 'reasons', 'admission', 'track_record']
|
|
210
249
|
.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
211
250
|
|
|
212
|
-
|
|
251
|
+
function normalizedAssignment(args) {
|
|
213
252
|
if (args.worker?.startsWith('-') || args.worker?.includes('\u0000')) throw fail('worker name must not start with a dash or contain NUL');
|
|
214
253
|
if ((args.repo === undefined) !== (args.base === undefined)) throw fail('repo and base must be supplied together');
|
|
215
254
|
if (args.task !== undefined && ['brief', 'objective', 'stop_rule'].some(field => args.assignment[field] !== undefined)) throw fail('supply task or assignment brief/objective/stop_rule, not both');
|
|
216
255
|
if (args.repo !== undefined && (!Array.isArray(args.assignment.inputs) || args.assignment.inputs.length)) throw fail('repo and base require empty assignment.inputs');
|
|
217
256
|
const assignment = { ...args.assignment, ...(args.task !== undefined ? { brief: args.task } : {}),
|
|
218
257
|
...(args.repo !== undefined ? { inputs: [{ github_repo: args.repo, base_sha: args.base, head_sha: args.base }] } : {}) };
|
|
258
|
+
return assignment;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function submit(args, extraFlags = [], {forecast = false} = {}) {
|
|
262
|
+
const assignment = normalizedAssignment(args);
|
|
219
263
|
const flags = [...extraFlags, ...(forecast ? ['--dry-run'] : [])];
|
|
220
264
|
if (args.worker) flags.push('--worker', args.worker);
|
|
221
265
|
if (args.execution) flags.push('--execution', args.execution);
|
|
@@ -279,6 +323,136 @@ const handlers = {
|
|
|
279
323
|
}
|
|
280
324
|
};
|
|
281
325
|
|
|
326
|
+
// Leave the existing CLI a private receipt for a confirmed assignment. Only
|
|
327
|
+
// the bridge's matching reply authorizes recording it under this request ID.
|
|
328
|
+
function rememberContinuingReceipt(directory, requestId, token) {
|
|
329
|
+
const file=ownerReceiptFile(directory,requestId);
|
|
330
|
+
fs.mkdirSync(directory,{recursive:true,mode:0o700});
|
|
331
|
+
try {
|
|
332
|
+
writeAtomic(file,JSON.stringify({request_id:requestId,token,body:'{}',delivery:'none'})+'\n',{createOnly:true});
|
|
333
|
+
} catch(error) {
|
|
334
|
+
if(error.code!=='EEXIST')throw error;
|
|
335
|
+
const stat=fs.lstatSync(file);
|
|
336
|
+
if(!stat.isFile()||(stat.mode&0o777)!==0o600)throw new Error('unsafe owner receipt');
|
|
337
|
+
const saved=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
338
|
+
if(saved.request_id!==requestId||saved.token!==token)throw new Error('different owner receipt');
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// No raw owner credential crosses stdio.
|
|
343
|
+
function localWorkLink() {
|
|
344
|
+
const home=serviceHomeFor();
|
|
345
|
+
const dataDir=defaultPath(home,'.local/share/dot-bridge');
|
|
346
|
+
const socket=process.env.DOT_ACP_SOCKET||adminSocketPath(dataDir);
|
|
347
|
+
const secretFile=process.env.DOT_ACP_SECRET_FILE||defaultPath(home,'.config/dot-bridge/acp-secret');
|
|
348
|
+
return {
|
|
349
|
+
call:(route,options)=>adminRequest(socket,route,options),
|
|
350
|
+
credential:handle=>ownerToken(readOrCreateSecret(secretFile),'ordinary-stdio-work:'+handle),
|
|
351
|
+
remember:(id,token)=>rememberContinuingReceipt(path.join(dataDir,'receipts'),id,token),
|
|
352
|
+
capture:selection=>{
|
|
353
|
+
const root=process.env.DALAN_REQUESTER_CONTEXT_ROOT;
|
|
354
|
+
if(!root)throw Object.assign(new Error('context_root_unavailable'),{code:'context_root_unavailable'});
|
|
355
|
+
const policy=sensitivePolicyPaths();
|
|
356
|
+
return captureRequesterLocalContext({root,selection,localRequester:true,
|
|
357
|
+
policy:{excludedPaths:policy.paths,credentialPathTerms:[],error:policy.error}});
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
export function createRequesterWorkRoute({call, credential, capture, remember}) {
|
|
362
|
+
const unavailable=(code,message)=>({kind:'work_error',code,message});
|
|
363
|
+
const esc=encodeURIComponent;
|
|
364
|
+
function receiptStatus(id,token) {
|
|
365
|
+
if(!remember)return {};
|
|
366
|
+
try { remember(id,token); return {cli_receipt:'saved'}; }
|
|
367
|
+
catch { return {cli_receipt:'unavailable'}; }
|
|
368
|
+
}
|
|
369
|
+
const ownerUnsupported=()=>unavailable('owner_work_capability_unavailable','The local bridge does not expose the continuing work owner capability. No fallback was used.');
|
|
370
|
+
function send(route,token,method='GET',payload) {return call(route,{method,token,payload});}
|
|
371
|
+
async function history(handle,token,after=0,allowMissing=false) {
|
|
372
|
+
if(!Number.isSafeInteger(after)||after<0) throw fail('after must be a non-negative safe integer');
|
|
373
|
+
try {
|
|
374
|
+
const result=await send('/subagent?id='+esc(handle)+'&after='+after,token);
|
|
375
|
+
if(result?.subagent_id!==handle||!Array.isArray(result.work)) throw ownerUnsupported();
|
|
376
|
+
return result;
|
|
377
|
+
} catch(e) {
|
|
378
|
+
if(e?.http_status===404) throw ownerUnsupported();
|
|
379
|
+
if(e?.message==='subagent_unavailable') {
|
|
380
|
+
if(allowMissing)return null;
|
|
381
|
+
throw unavailable('work_handle_unavailable','The continuing work handle does not exist or is not owned here.');
|
|
382
|
+
}
|
|
383
|
+
throw e;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return async (name,args) => {
|
|
387
|
+
try {
|
|
388
|
+
let a=args.assignment===undefined?null:normalizedAssignment(args);
|
|
389
|
+
if(a&&!new RegExp(requestId.pattern).test(a.request_id??'')) throw fail('assignment requires a valid request_id');
|
|
390
|
+
if(a&&(a.protocol!==undefined||a.routing!==undefined)) throw fail('continuing work requires an ordinary assignment');
|
|
391
|
+
if(args.require_local_context===true&&args.local_context_file===undefined)
|
|
392
|
+
throw unavailable('context_selection_required','Select one relative local text file before offering this work.');
|
|
393
|
+
if(args.local_context_file!==undefined) {
|
|
394
|
+
if(!a||typeof capture!=='function')
|
|
395
|
+
throw unavailable('context_root_unavailable','This requester does not have a local text root configured.');
|
|
396
|
+
try { a=withRequesterLocalContext(a,capture(args.local_context_file)); }
|
|
397
|
+
catch(e) {
|
|
398
|
+
const code=typeof e?.code==='string'&&/^context_[a-z_]{1,80}$/.test(e.code)?e.code:'context_selection_unavailable';
|
|
399
|
+
throw unavailable(code,'The selected local text could not be shared. No request was submitted.');
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
const root=a?.request_id;
|
|
403
|
+
const handle=args.subagent_id??'sg_'+createHash('sha256').update(root).digest('base64url');
|
|
404
|
+
const token=credential(handle);
|
|
405
|
+
if(name==='dalan_work_offer'||name==='dalan_work_follow') {
|
|
406
|
+
const prior=args.prior_request_id;
|
|
407
|
+
if(prior===a.request_id) throw fail('follow-up requires a distinct request_id');
|
|
408
|
+
// On an older /submit, an unknown field might be ignored and work would
|
|
409
|
+
// still be queued. Prove the owner endpoint first; do not fall back.
|
|
410
|
+
await history(handle,token,0,prior===undefined);
|
|
411
|
+
const payload={assignment:a,subagent_id:handle,delivery:'none',owner_token:token,command_key:a.request_id,
|
|
412
|
+
...(args.worker?{worker:args.worker}:{}),...(args.execution?{execution:args.execution}:{}),
|
|
413
|
+
...(args.priority_class==='background'?{background:true}:{}),
|
|
414
|
+
...(args.requirements?{required_capabilities:args.requirements}:{}),
|
|
415
|
+
...(prior?{follows:{prior_id:prior,prior_token:token}}:{})};
|
|
416
|
+
const reply=await send('/submit',token,'POST',payload);
|
|
417
|
+
if(reply?.subagent_id!==handle||reply.request_id!==a.request_id) {
|
|
418
|
+
throw unavailable('work_receipt_unconfirmed','The bridge did not return the matching work receipt. Recover the original request ID before retrying.');
|
|
419
|
+
}
|
|
420
|
+
return asResult({value:{...pick(reply,['subagent_id','request_id','status','duplicate','admission']),...receiptStatus(a.request_id,token)}});
|
|
421
|
+
}
|
|
422
|
+
if(name==='dalan_work_recover'&&args.request_id===undefined) return asResult({value:await history(handle,token,args.after)});
|
|
423
|
+
const work=args.request_id, suffix='?id='+esc(work);
|
|
424
|
+
if(name==='dalan_work_recover') {
|
|
425
|
+
const result=await send('/get'+suffix+'&peek=1',token);
|
|
426
|
+
if(result?.request_id!==work||result.subagent_id!==handle)
|
|
427
|
+
throw unavailable('work_receipt_unconfirmed','The owner reply did not identify the original request and subagent.');
|
|
428
|
+
return asResult({value:{...pick(result,['request_id','status','report','offer','worker_runs','checks','artifacts']),
|
|
429
|
+
subagent_id:handle,...receiptStatus(work,token)}});
|
|
430
|
+
}
|
|
431
|
+
if(name==='dalan_work_questions') return asResult({value:await send('/questions'+suffix,token)});
|
|
432
|
+
if(name==='dalan_work_answer') {
|
|
433
|
+
if(!args.text.trim()||Buffer.byteLength(args.text)>MAX_ANSWER_BYTES||args.text.includes('\0')) throw fail('invalid clarification text');
|
|
434
|
+
return asResult({value:await send('/answer',token,'POST',{id:work,question_id:args.question_id,text:args.text})});
|
|
435
|
+
}
|
|
436
|
+
if(name==='dalan_work_withdraw') {
|
|
437
|
+
const view=await send('/get'+suffix+'&peek=1',token);
|
|
438
|
+
if(view?.request_id!==work||!isRecord(view.offer)) throw ownerUnsupported();
|
|
439
|
+
const result=await send('/cancel-if-queued',token,'POST',{id:work,command_key:args.command_key});
|
|
440
|
+
if(result?.request_id!==work||!['withdrawn_while_queued','already_accepted','already_terminal','acceptance_unresolved'].includes(result.disposition))
|
|
441
|
+
throw unavailable('work_receipt_unconfirmed','Withdrawal did not return an exact matching disposition. Check the original request before retrying.');
|
|
442
|
+
return asResult({value:result});
|
|
443
|
+
}
|
|
444
|
+
throw fail('unknown continuing work operation');
|
|
445
|
+
} catch(e) {
|
|
446
|
+
if(e?.kind==='work_error')return asResult({isError:true,value:{code:e.code,error:e.message}});
|
|
447
|
+
if(e instanceof SafeError)throw e;
|
|
448
|
+
if(e?.http_status===404)return asResult({isError:true,value:{code:'owner_work_capability_unavailable',error:'The local owner route is unavailable. No fallback was used.'}});
|
|
449
|
+
return asResult({isError:true,value:{code:e?.kind==='http'?'owner_request_refused':'owner_result_unconfirmed',
|
|
450
|
+
error:e?.kind==='http'?'The local bridge refused this owner request. Check its authority and state.':'The local owner reply could not be confirmed. Recover the original request before repeating any action.'}});
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
const localRequesterWork = (name,args)=>createRequesterWorkRoute(localWorkLink())(name,args);
|
|
455
|
+
|
|
282
456
|
const tasks = createTaskRoute({
|
|
283
457
|
submit: args => submitJob(args, args.priority_class === 'background' ? [] : ['--caller-waiting']), readJob, readQuestions,
|
|
284
458
|
answer: args => callTool('dalan_answer', args), cancel: requestId => callTool('dalan_cancel', { request_id: requestId }), asResult,
|
|
@@ -304,7 +478,7 @@ const rpcError = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: { co
|
|
|
304
478
|
const taskMethods = new Set(['tasks/get', 'tasks/update', 'tasks/cancel']);
|
|
305
479
|
|
|
306
480
|
// One JSON-RPC message in, zero or one frame out.
|
|
307
|
-
export async function handleFrame(message) {
|
|
481
|
+
export async function handleFrame(message, {requesterWork=localRequesterWork}={}) {
|
|
308
482
|
const candidateId = message?.id;
|
|
309
483
|
if (candidateId !== undefined && candidateId !== null && typeof candidateId !== 'string' &&
|
|
310
484
|
(typeof candidateId !== 'number' || !Number.isFinite(candidateId))) return rpcError(null, -32600, 'invalid request');
|
|
@@ -337,12 +511,20 @@ export async function handleFrame(message) {
|
|
|
337
511
|
case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
338
512
|
capabilities: { tools: {} }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
|
|
339
513
|
case 'ping': return ok({});
|
|
340
|
-
case 'tools/list': return ok({ tools: modern ? [...TOOLS,
|
|
514
|
+
case 'tools/list': return ok({ tools: modern ? [...TOOLS,...workTools,delegateTool] : [...TOOLS,...workTools] });
|
|
341
515
|
case 'tools/call': {
|
|
342
516
|
if (typeof params?.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name');
|
|
343
517
|
if (params.name === delegateTool.name) {
|
|
344
518
|
return hasTasks ? ok(await invokeTool(delegateTool, params.arguments, tasks.delegate)) : missingTasks();
|
|
345
519
|
}
|
|
520
|
+
const workTool = workTools.find(tool=>tool.name===params.name);
|
|
521
|
+
if(workTool) {
|
|
522
|
+
if(isRecord(params.arguments)&¶ms.arguments.require_native_tasks===true) {
|
|
523
|
+
if(!hasTasks)return missingTasks();
|
|
524
|
+
return rpcError(id,-32602,'This ordinary application tool does not use native Tasks; call dalan_delegate explicitly.');
|
|
525
|
+
}
|
|
526
|
+
return ok(await invokeTool(workTool,params.arguments,args=>requesterWork(workTool.name,args)));
|
|
527
|
+
}
|
|
346
528
|
const result = await callTool(params.name, params.arguments);
|
|
347
529
|
return result ? ok(result) : rpcError(id, -32602, `unknown tool "${params.name}"`);
|
|
348
530
|
}
|
|
@@ -385,7 +567,7 @@ async function* inputFrames(input, limit) {
|
|
|
385
567
|
if (used || discard) yield read();
|
|
386
568
|
}
|
|
387
569
|
|
|
388
|
-
export async function main({ input = process.stdin, output = process.stdout, maxFrameBytes = MAX_INPUT_FRAME_BYTES } = {}) {
|
|
570
|
+
export async function main({ input = process.stdin, output = process.stdout, maxFrameBytes = MAX_INPUT_FRAME_BYTES, requesterWork = localRequesterWork } = {}) {
|
|
389
571
|
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0 || maxFrameBytes > MAX_INPUT_FRAME_BYTES) {
|
|
390
572
|
throw new RangeError('invalid stdio frame limit');
|
|
391
573
|
}
|
|
@@ -398,7 +580,7 @@ export async function main({ input = process.stdin, output = process.stdout, max
|
|
|
398
580
|
try { message = JSON.parse(line); }
|
|
399
581
|
catch { write(rpcError(null, -32700, 'parse error')); continue; }
|
|
400
582
|
// Requests run concurrently: a long dalan_wait must not block a ping or another tool.
|
|
401
|
-
const work = handleFrame(message).then(frame => { if (frame) write(frame); }, error => {
|
|
583
|
+
const work = handleFrame(message,{requesterWork}).then(frame => { if (frame) write(frame); }, error => {
|
|
402
584
|
process.stderr.write(`dalan mcp: ${safeDiagnostic(error.stack ?? error, 4000)}\n`); write(rpcError(message?.id ?? null, -32603, 'internal error'));
|
|
403
585
|
}).finally(() => inflight.delete(work));
|
|
404
586
|
inflight.add(work);
|