@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,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);
|
package/src/patch-apply.mjs
CHANGED
|
@@ -115,6 +115,14 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
|
|
|
115
115
|
if(got?.request_id!==id) throw new Error('materialize result does not match the requested work');
|
|
116
116
|
const grant=readMaterializeGrant(grantFile);
|
|
117
117
|
if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
|
|
118
|
+
const completed = row => row.report?.outcome === 'completed' && row.report.late !== true && row.report.result_authority !== false;
|
|
119
|
+
// Automatic materialization is only for successful, authoritative results.
|
|
120
|
+
// Explicit owner materialization keeps its existing review/approval policy.
|
|
121
|
+
if(standingOnly && !completed(got)) {
|
|
122
|
+
const decision={push:false,draft_pr:false,needs_approval:false,branch:null,reason:'report_not_completed'};
|
|
123
|
+
return {request_id:id,repo:got.assignment?.inputs?.[0]?.github_repo??null,
|
|
124
|
+
base_sha:got.assignment?.inputs?.[0]?.base_sha??null,files:[],decision,published:false,reason:decision.reason};
|
|
125
|
+
}
|
|
118
126
|
const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
|
|
119
127
|
if(!Array.isArray(inputs)||inputs.length!==1||!art?.artifact_id||!art.size||!/^[a-f0-9]{64}$/.test(art.sha256??'')) {
|
|
120
128
|
throw new Error('materialize needs one repository and a sealed patch');
|
|
@@ -141,13 +149,27 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
|
|
|
141
149
|
}
|
|
142
150
|
if(!dryRun && (decision.push || decision.needs_approval && approve)) {
|
|
143
151
|
const title=String(got.assignment?.title ?? 'Dalan patch '+id).split(/\r?\n/,1)[0].trim().slice(0,240) || 'Dalan patch '+id;
|
|
144
|
-
const
|
|
152
|
+
const introduction='The requester can review the changes a worker made and decide whether to merge them.';
|
|
153
|
+
const summary=String(got.report?.summary ?? '').trim().slice(0,30000);
|
|
154
|
+
const evidence=[
|
|
155
|
+
'## Worker result and evidence',
|
|
156
|
+
...summary.split(/\r?\n/u).filter(Boolean).map(line => '> '+line),
|
|
157
|
+
'Job: `'+id+'`',
|
|
158
|
+
'Published base: `'+base_sha+'`',
|
|
159
|
+
'Sealed patch SHA-256: `'+art.sha256+'`',
|
|
160
|
+
];
|
|
161
|
+
if (typeof got.report.receipt_id === 'string' && /^[-\w]+$/u.test(got.report.receipt_id)) {
|
|
162
|
+
evidence.push('Result receipt: `'+got.report.receipt_id+'`');
|
|
163
|
+
}
|
|
164
|
+
const exits=(got.worker_runs ?? []).map(run => run.exit_code).filter(Number.isInteger);
|
|
165
|
+
if (exits.length) evidence.push('Worker-reported exit codes: '+exits.join(', ')+'.');
|
|
166
|
+
const description=[introduction,...evidence].join('\n\n');
|
|
145
167
|
Object.assign(result,await materializePatch({dir,temp,body,sha256:art.sha256,baseSha:base_sha,
|
|
146
|
-
repo,branch:decision.branch,title,
|
|
168
|
+
repo,branch:decision.branch,title,description,introduction,fetchBase,budget,
|
|
147
169
|
rememberCleanup:()=>{ cleanupPending=true; },recheck:async(phase='push')=>{
|
|
148
170
|
const current=await budget.read(signal=>recheck({signal}));
|
|
149
171
|
const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
|
|
150
|
-
if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
|
|
172
|
+
if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256 || (standingOnly && !completed(current))) {
|
|
151
173
|
throw new Error('materialize result changed before publication; '+after);
|
|
152
174
|
}
|
|
153
175
|
const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
|
|
@@ -178,7 +200,7 @@ function githubPushRepo(url) {
|
|
|
178
200
|
return (ssh?.[1] ?? absolute?.[1])?.replace(/\.git$/i, '').toLowerCase();
|
|
179
201
|
}
|
|
180
202
|
|
|
181
|
-
async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title,
|
|
203
|
+
async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, description, introduction, recheck, fetchBase, budget, rememberCleanup}) {
|
|
182
204
|
if(typeof dir!=='string' || !path.isAbsolute(dir)) throw new Error('materialize requires a checkout directory');
|
|
183
205
|
const ref = 'refs/heads/' + branch;
|
|
184
206
|
if (!materializeRepo.test(repo) || !/^dalan\/[-\w]{8,128}$/.test(branch) || !/^[a-f0-9]{40}$/.test(baseSha)) {
|
|
@@ -217,7 +239,7 @@ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch,
|
|
|
217
239
|
gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
|
|
218
240
|
applyPatch({dir:worktree, patch:body, sha256, baseSha, runGit:budget.git});
|
|
219
241
|
gitCmd(worktree,['add','-A','--','.'],'stage patch');
|
|
220
|
-
gitCmd(worktree,['commit','--no-gpg-sign','-m','
|
|
242
|
+
gitCmd(worktree,['commit','--no-gpg-sign','-m',title,'-m',introduction],'commit patch with local identity');
|
|
221
243
|
const tip = gitCmd(worktree,['ls-remote','--heads',remote,ref],'inspect scoped remote branch');
|
|
222
244
|
if(tip) {
|
|
223
245
|
const cols=tip.split(/\s+/);
|
|
@@ -243,7 +265,7 @@ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch,
|
|
|
243
265
|
draftAttempted = true;
|
|
244
266
|
try {
|
|
245
267
|
pr_url=ghCmd(['pr','create','--repo',ghRepo,'--draft','--base',targetBase,'--head',branch,
|
|
246
|
-
'--title',title,'--body',
|
|
268
|
+
'--title',title,'--body',description],'open draft pull request');
|
|
247
269
|
} catch(error) {
|
|
248
270
|
// A create call can fail after the draft was opened, and a replay can find the draft
|
|
249
271
|
// the first publication opened. Look for it before reporting failure.
|
|
@@ -13,6 +13,7 @@ export function parsePublishGrant(value) {
|
|
|
13
13
|
|
|
14
14
|
// authority is the bridge's current answer for the job: {relationship_id, ended, publish_grant} or null.
|
|
15
15
|
export function workGrantProblem(authority, repo) {
|
|
16
|
+
if (['attachment_standing_publication_forbidden','attachment_lineage_unverified'].includes(authority?.publish_restriction)) return authority.publish_restriction;
|
|
16
17
|
if (!authority?.relationship_id) return 'no_work_grant';
|
|
17
18
|
if (authority.ended) return 'relationship_ended';
|
|
18
19
|
const [org] = String(repo).toLowerCase().split('/');
|
package/src/pull-pacing.mjs
CHANGED
|
@@ -30,3 +30,13 @@ export function createPullPacing({ now, log }) {
|
|
|
30
30
|
observe,
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
+
|
|
34
|
+
// Evidence is descriptive only. It uses the same intersection as the live offer; absent demand uses advice, not the service limit.
|
|
35
|
+
export function describePullOffer({declared,advised,free,available,ready}) {
|
|
36
|
+
const chosen=declared??advised, next=Math.min(chosen,available,ready,maxBatchPull);
|
|
37
|
+
const limits={worker_slots:chosen,claimable_lanes:available,ready_jobs:ready,batch_cap:maxBatchPull};
|
|
38
|
+
return {next,evidence:{declared_worker_free_slots:declared??null,
|
|
39
|
+
advised_worker_free_slots:declared===undefined?advised:null,effective_worker_slots:chosen,service_free_lanes:free,
|
|
40
|
+
service_claimable_lanes:available,ready_jobs:ready,max_batch_claims:maxBatchPull,
|
|
41
|
+
limiting_inputs:Object.keys(limits).filter(key=>limits[key]===next)}};
|
|
42
|
+
}
|