@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
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,20 @@ This file lists user-visible changes, newest first. Check the section for your t
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.9.11
|
|
8
|
+
|
|
9
|
+
- Offer work to a remote subagent through ordinary MCP and keep working while the worker picks it up. Use the same handle to recover the original result and send a follow-up.
|
|
10
|
+
- Select a local text brief for the job. Dalan records the selected bytes and refuses missing or withheld files before submitting.
|
|
11
|
+
- Take a queued offer back only while it remains unaccepted. Retrying the same withdrawal returns its original decision.
|
|
12
|
+
- Resume open work from an accepted checkpoint after a worker loses its run. The bridge labels whether it observed the original work start.
|
|
13
|
+
- See the commands and exit codes a worker reported for a repository job. Owners with a standing publication grant can receive a verified draft pull request for eligible work.
|
|
14
|
+
|
|
15
|
+
## 0.9.8
|
|
16
|
+
|
|
17
|
+
- Let a worker declare the slots it can start on this poll. Hosted clients without slot declarations get advice that adjusts to observed completion and capacity pressure.
|
|
18
|
+
- Timed claims report an effective heartbeat interval and an independent run deadline.
|
|
19
|
+
- Report a reserved worker slot separately from the moment work starts.
|
|
20
|
+
|
|
7
21
|
## 0.9.7
|
|
8
22
|
|
|
9
23
|
- Read a larger pinned input set as one verified bundle over several replies. Each reply requires the current claim.
|
package/bin/dot-acp-agent.mjs
CHANGED
|
@@ -15,7 +15,7 @@ import { createRefuse, cancelBudgetMs, CANCEL_CLEANUP_MS } from '../integrations
|
|
|
15
15
|
import { detectPresentPatches } from '../src/patch-apply.mjs';
|
|
16
16
|
import {
|
|
17
17
|
buildExecution, paths, adminRequest, adminRequestThroughRestart, transient, sha256, parsePrompt, attemptId, ownerToken, readOrCreateSecret, bridgeRefusal,
|
|
18
|
-
prepareAssignmentWithContext, correctionRepositoryContext, explicitReadIntent, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait, workerRunEvidenceLines,
|
|
18
|
+
prepareAssignmentWithContext, correctionRepositoryContext, explicitReadIntent, nativeContinuingHandle, parseNativeFollow, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait, workerRunEvidenceLines,
|
|
19
19
|
} from '../src/acp-bridge.mjs';
|
|
20
20
|
|
|
21
21
|
const num = (name, fallback) => { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; };
|
|
@@ -76,8 +76,8 @@ const sessionFile = id => {
|
|
|
76
76
|
};
|
|
77
77
|
// Keep active work and terminal receipts; probes and idle sessions leave nothing behind.
|
|
78
78
|
function saveSession(s) {
|
|
79
|
-
if (!s.pending && !s.completed?.length && !s.builds?.length && !s.cancelledRid) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
|
|
80
|
-
writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, cancelledRid: s.cancelledRid ?? null, cancelledAt:s.cancelledAt ?? null, cancelledByGrace:s.cancelledByGrace === true, finishedAfterCancel:s.finishedAfterCancel===true, builds: s.builds ?? [], completed: s.completed ?? [] });
|
|
79
|
+
if (!s.pending && !s.completed?.length && !s.builds?.length && !s.cancelledRid && !s.continuing) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
|
|
80
|
+
writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, continuing:s.continuing??null, cancelledRid: s.cancelledRid ?? null, cancelledAt:s.cancelledAt ?? null, cancelledByGrace:s.cancelledByGrace === true, finishedAfterCancel:s.finishedAfterCancel===true, builds: s.builds ?? [], completed: s.completed ?? [] });
|
|
81
81
|
}
|
|
82
82
|
const readSession = id => readJsonPrivate(sessionFile(id));
|
|
83
83
|
// Independent of the session lock: never overwrite another process's live session record.
|
|
@@ -124,6 +124,34 @@ async function readRow(rid, signal, admission = false, matchingWorkerOnly = fals
|
|
|
124
124
|
throw e;
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
|
+
function assertNativeBinding(s,continuing,row,follow=null) {
|
|
128
|
+
if(!continuing) {
|
|
129
|
+
if(row.subagent_id)throw new Refusal('Existing work belongs to a different continuation; no new work was submitted.');
|
|
130
|
+
} else if(continuing.id!==nativeContinuingHandle(s.id)||row.subagent_id!==continuing.id||
|
|
131
|
+
(s.continuing&&s.continuing.root_rid!==continuing.root_rid)) {
|
|
132
|
+
throw new Refusal('The bridge did not confirm the original native continuation binding.');
|
|
133
|
+
}
|
|
134
|
+
if((row.follows?.request_id??null)!==follow)throw new Refusal('The bridge did not confirm the original predecessor link.');
|
|
135
|
+
if(continuing&&!s.continuing)s.continuing=continuing;
|
|
136
|
+
}
|
|
137
|
+
// A per-job decision can observe that exact authenticated row without adopting its
|
|
138
|
+
// continuing handle. Persist the membership separately from native session identity.
|
|
139
|
+
function decisionMembership(row) {
|
|
140
|
+
const assignment=row.assignment;
|
|
141
|
+
return {rid:row.request_id,worker:row.target_worker,handle:row.subagent_id??null,
|
|
142
|
+
briefHash:assignment.acp_brief_hash??sha256(withoutNote(assignment.brief??'')),
|
|
143
|
+
pinHash:sha256(JSON.stringify([assignment.inputs??[],assignment.scope_paths??[],assignment.read_paths??[]]))};
|
|
144
|
+
}
|
|
145
|
+
function assertDecisionMembership(attachment,row) {
|
|
146
|
+
const current=decisionMembership(row);
|
|
147
|
+
if(row.follows||row.revises||Object.keys(current).some(key=>current[key]!==attachment[key]))
|
|
148
|
+
throw new Refusal('The bridge did not confirm the original decision attachment. No new work was submitted.');
|
|
149
|
+
}
|
|
150
|
+
function attachExistingDecision(parsed,attempt,row,worker) {
|
|
151
|
+
if(!parsed.root||row.request_id!==attemptId(parsed.root,attempt)||!worker||row.target_worker!==worker||row.follows||row.revises)
|
|
152
|
+
throw new Refusal('Existing work belongs to a different continuation; no new work was submitted.');
|
|
153
|
+
return decisionMembership(row);
|
|
154
|
+
}
|
|
127
155
|
const attachedAdmission = row => ({ status: row.status, execution: row.execution, ...(row.status === 'queued' ? row.admission : {}) });
|
|
128
156
|
|
|
129
157
|
function assertReadIntent(intent,assignment) {
|
|
@@ -156,7 +184,7 @@ async function acquire(s, parsed, ctl) {
|
|
|
156
184
|
const readIntent=explicitReadIntent(parsed.brief);
|
|
157
185
|
// Reuse work admitted before worker-scoped anonymous identities were introduced.
|
|
158
186
|
// A legacy row belongs to this retry only when its authenticated worker matches.
|
|
159
|
-
if (!parsed.root && !ctl.correction && parsed.legacyRequestRoot !== parsed.requestRoot) {
|
|
187
|
+
if (!ctl.continuingSupported && !parsed.root && !ctl.correction && parsed.legacyRequestRoot !== parsed.requestRoot) {
|
|
160
188
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
161
189
|
const legacy = await readRow(attemptId(parsed.legacyRequestRoot, attempt), undefined, true, true);
|
|
162
190
|
if (!legacy || legacy.status === 'cancelled') continue;
|
|
@@ -175,18 +203,31 @@ async function acquire(s, parsed, ctl) {
|
|
|
175
203
|
const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
|
|
176
204
|
if (storedHash !== briefHash) throw new Refusal(`token ${parsed.requestRoot} was already used with a different brief`);
|
|
177
205
|
assertReadIntent(readIntent,row.assignment);
|
|
206
|
+
const prepared=preparedByAttempt.get(rid);
|
|
207
|
+
const ownHandle=row.subagent_id&&row.subagent_id===nativeContinuingHandle(s.id);
|
|
208
|
+
const expected=ctl.correction?ctl.correction.prior.continuing??null:
|
|
209
|
+
prepared?prepared.continuing??null:
|
|
210
|
+
ctl.pending?ctl.pending.continuing??null:
|
|
211
|
+
ownHandle?s.continuing??{id:row.subagent_id,root_rid:rid}:null;
|
|
212
|
+
const independent=!prepared&&!ctl.pending&&!ctl.correction&&!ctl.followup&&!expected;
|
|
213
|
+
const attachment=independent&&row.status!=='cancelled'&&(row.subagent_id||ctl.continuingSupported)&&parsed.root
|
|
214
|
+
?attachExistingDecision(parsed,attempt,row,WORKER??ctl.initialStatus?.default_worker):null;
|
|
215
|
+
if(!attachment&&(expected||ctl.followup||row.subagent_id&&(row.status!=='cancelled'||!independent)))
|
|
216
|
+
assertNativeBinding(s,expected,row,ctl.followup?.prior??null);
|
|
178
217
|
if (ctl.correction && row.revises?.request_id !== ctl.correction.prior.rid) throw new Refusal('the stored work does not match the requested correction');
|
|
179
218
|
if (ctl.correction && row.status === 'cancelled') throw new Refusal(`correction ${rid} was withdrawn; no new work was submitted`);
|
|
180
219
|
if (row.status === 'cancelled' && !conflictExhausted) continue;
|
|
181
220
|
if (row.status === 'cancelled') throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
|
|
182
221
|
return { root: parsed.requestRoot, rid, attempt, briefHash, admission: attachedAdmission(row),
|
|
183
222
|
...(row.revises?.request_id ? { revises: row.revises.request_id } : {}),
|
|
223
|
+
...(expected?{continuing:expected}:{}),...(attachment?{decisionAttachment:attachment}:{}),...(ctl.followup?{follows:ctl.followup.prior}:{}),
|
|
184
224
|
repositoryContext: storedRepositoryContext(row.assignment, preparedByAttempt.get(rid)?.repositoryContext),
|
|
185
225
|
validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
|
|
186
226
|
}
|
|
187
227
|
// On the last conflict still reread once: the same brief may already exist.
|
|
188
228
|
if (conflictExhausted) throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
|
|
189
|
-
const status = await call('/status', null);
|
|
229
|
+
const status = ctl.initialStatus??await call('/status', null);
|
|
230
|
+
ctl.initialStatus=null;
|
|
190
231
|
const target = WORKER ?? status.default_worker ?? 'dot';
|
|
191
232
|
const workerBreak = status.by_worker?.[target]?.worker_break ?? (target==='dot'?status.worker_break:null);
|
|
192
233
|
const refusal = bridgeRefusal({...status,worker_break:workerBreak}, IN_FLIGHT_CAP+(ctl.correction?.row.status==='queued'?1:0), WORKER, parsed.priority, true);
|
|
@@ -209,13 +250,24 @@ async function acquire(s, parsed, ctl) {
|
|
|
209
250
|
if(correction.row.execution) body.execution=correction.row.execution;
|
|
210
251
|
if(correction.row.review) body.review=true;
|
|
211
252
|
}
|
|
253
|
+
// Legacy corrections retain their original one-job semantics. A continued
|
|
254
|
+
// correction, follow-up, or ordinary submission uses the same owner anchor.
|
|
255
|
+
const continuing=ctl.correction?ctl.correction.prior.continuing??null:
|
|
256
|
+
ctl.continuingSupported?(s.continuing??{id:nativeContinuingHandle(s.id),root_rid:rid}):null;
|
|
257
|
+
if(continuing) {
|
|
258
|
+
if(!ctl.continuingSupported)throw new Refusal('This bridge no longer advertises native continuation. No work was submitted.');
|
|
259
|
+
body.subagent_id=continuing.id;
|
|
260
|
+
body.command_key??='acp-continuing:'+rid;
|
|
261
|
+
}
|
|
262
|
+
if(ctl.followup)body.follows={prior_id:ctl.followup.prior,prior_token:tokenFor(ctl.followup.prior)};
|
|
263
|
+
const subagentOwner=continuing&&continuing.root_rid!==rid?tokenFor(continuing.root_rid):undefined;
|
|
212
264
|
// max_queued makes admission atomic; the bridge counts only this worker's waiting callers of the same priority.
|
|
213
|
-
prepared={body,validUntil,repositoryContext}; preparedByAttempt.set(rid,prepared);
|
|
265
|
+
prepared={body,validUntil,repositoryContext,continuing,subagentOwner}; preparedByAttempt.set(rid,prepared);
|
|
214
266
|
}
|
|
215
|
-
const {body,validUntil}=prepared;
|
|
267
|
+
const {body,validUntil,continuing,subagentOwner}=prepared;
|
|
216
268
|
try {
|
|
217
269
|
let preview;
|
|
218
|
-
try { preview=await call('/submit-preview',null,{method:'POST',payload:body,timeoutMs:SUBMIT_DEADLINE_MS}); }
|
|
270
|
+
try { preview=await call('/submit-preview',null,{method:'POST',payload:body,subagentOwner,timeoutMs:SUBMIT_DEADLINE_MS}); }
|
|
219
271
|
catch(error) {
|
|
220
272
|
if(error.http_status===404) throw new Refusal('bridge does not support safe /submit-preview; no assignment was submitted','adapter_error',{failure_type_source:'bridge_compatibility'});
|
|
221
273
|
throw error;
|
|
@@ -237,13 +289,19 @@ async function acquire(s, parsed, ctl) {
|
|
|
237
289
|
priority: parsed.priority, requirements: parsed.requirements, notes: ctl.pending?.notes ?? [],
|
|
238
290
|
...(ctl.correction ? { revises:ctl.correction.prior.rid, correctionPrior:ctl.correction.prior,
|
|
239
291
|
admitUntil:body.facade_submit_until } : {}),
|
|
292
|
+
...(continuing?{continuing}:{}), ...(ctl.followup?{follows:ctl.followup.prior}:{}),
|
|
240
293
|
work_id: rid, original_host_task_id: ctl.hostTaskId ?? null, original_prompt_request_id: ctl.promptRequestId,
|
|
241
294
|
later_prompt_request_ids: [], later_host_task_ids: [], startedAt: Date.now(), submission_pending: true };
|
|
242
295
|
ctl.pending = intent;
|
|
243
296
|
publishPending(s, ctl);
|
|
244
297
|
// Admission belongs to the bridge; the richer forecast can replace this reply without changing ACP.
|
|
245
298
|
try {
|
|
246
|
-
const admitted=await call('/submit',null,{method:'POST',payload:body,timeoutMs:SUBMIT_DEADLINE_MS});
|
|
299
|
+
const admitted=await call('/submit',null,{method:'POST',payload:body,subagentOwner,timeoutMs:SUBMIT_DEADLINE_MS});
|
|
300
|
+
if(continuing) {
|
|
301
|
+
if(admitted.subagent_id!==continuing.id||admitted.request_id!==rid)
|
|
302
|
+
throw new Refusal('The bridge did not confirm the work binding. Recover the original work before retrying.');
|
|
303
|
+
s.continuing=continuing;
|
|
304
|
+
}
|
|
247
305
|
prepared.admission=admitted.admission??{status:admitted.status??'queued',execution:admitted.execution,submission_warnings:admitted.submission_warnings};
|
|
248
306
|
prepared.repositoryContext=withReadScope(prepared.repositoryContext,admitted.repository_scope?.scope_paths,admitted.repository_scope?.file_count);
|
|
249
307
|
}
|
|
@@ -271,17 +329,22 @@ async function acquire(s, parsed, ctl) {
|
|
|
271
329
|
}
|
|
272
330
|
return { root: parsed.requestRoot, rid, attempt, briefHash, admission: prepared.admission, validUntil, repositoryContext: prepared.repositoryContext,
|
|
273
331
|
...(ctl.correction ? { revises:ctl.correction.prior.rid } : {}),
|
|
332
|
+
...(continuing?{continuing}:{}),...(ctl.followup?{follows:ctl.followup.prior}:{}),
|
|
274
333
|
expectedWaitLine: withExpectedWait('', status, WORKER).trimStart(), notes: [], startedAt: Date.now() };
|
|
275
334
|
}
|
|
276
335
|
throw new Refusal(`no usable assignment after ${MAX_ATTEMPTS} attempts for ${parsed.requestRoot}`);
|
|
277
336
|
}
|
|
278
337
|
|
|
279
|
-
async function resultText(row, s) {
|
|
338
|
+
async function resultText(row, s, observeOnly = false) {
|
|
280
339
|
const r = row.report;
|
|
281
|
-
if (r?.outcome === 'refused_by_provider')
|
|
340
|
+
if (r?.outcome === 'refused_by_provider') {
|
|
341
|
+
const text = `[worker outcome: refused_by_provider]\n${r.result ?? r.summary ?? ''}`;
|
|
342
|
+
const evidence = workerRunEvidenceLines(row);
|
|
343
|
+
return [text, ...evidence].join('\n');
|
|
344
|
+
}
|
|
282
345
|
let text = (r?.result || r?.summary || '').trim() || '(the worker finished without a result)';
|
|
283
346
|
if (r && r.outcome !== 'completed') text = `[worker outcome: ${r.outcome}]\n${text}`;
|
|
284
|
-
if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) {
|
|
347
|
+
if (observeOnly || !isBuild(withoutNote(row.assignment?.brief ?? ''))) {
|
|
285
348
|
const evidence = workerRunEvidenceLines(row);
|
|
286
349
|
return [text, ...(evidence.length ? [evidence.join('\n')] : []), decideHint(row.request_id)].join('\n\n');
|
|
287
350
|
}
|
|
@@ -335,7 +398,7 @@ function admissionText(admission, attached) {
|
|
|
335
398
|
const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
|
|
336
399
|
const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
|
|
337
400
|
const window = days => count(days) ? `, ${days} days` : '';
|
|
338
|
-
const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? '
|
|
401
|
+
const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'slot reserved' : ['queued','now'].includes(start) ? 'queued' :
|
|
339
402
|
['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
|
|
340
403
|
if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
|
|
341
404
|
if (count(ahead?.count)) {
|
|
@@ -386,9 +449,34 @@ function admissionText(admission, attached) {
|
|
|
386
449
|
async function runTurn(s, ctl, text, say, client) {
|
|
387
450
|
const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
|
|
388
451
|
let parsed = incoming;
|
|
452
|
+
const follow=parseNativeFollow(incoming.brief);
|
|
453
|
+
let feature;
|
|
454
|
+
if(!ctl.pending||follow||ctl.pending.continuing) {
|
|
455
|
+
feature=await call('/status',null,{signal:ctl.abort.signal});
|
|
456
|
+
ctl.continuingSupported=feature.owner_features?.continuing_subagents===1;
|
|
457
|
+
ctl.initialStatus=feature;
|
|
458
|
+
}
|
|
459
|
+
if(follow) {
|
|
460
|
+
if(!ctl.continuingSupported)throw new Refusal('This bridge does not support native follow-up. No work was submitted.');
|
|
461
|
+
if(!s.continuing)throw new Refusal('This native session does not own the named completed work. No work was submitted.');
|
|
462
|
+
const completed=s.completed.find(item=>item.rid===follow.prior&&item.continuing?.id===s.continuing.id);
|
|
463
|
+
if(!completed?.terminal?.report_receipt_id)throw new Refusal('This native session does not own the named completed work. No work was submitted.');
|
|
464
|
+
const original=await readRow(follow.prior,ctl.abort.signal);
|
|
465
|
+
if(original?.status!=='finished'||original.subagent_id!==s.continuing.id||
|
|
466
|
+
original.report?.receipt_id!==completed.terminal.report_receipt_id)
|
|
467
|
+
throw new Refusal('The bridge could not confirm the named original result. No work was submitted.');
|
|
468
|
+
const linkedRoot='acp-'+sha256(JSON.stringify([s.continuing.id,WORKER,follow.prior,follow.brief,incoming.priority,incoming.requirements])).slice(0,24);
|
|
469
|
+
if(ctl.pending&&(ctl.pending.follows!==follow.prior||ctl.pending.root!==linkedRoot))
|
|
470
|
+
throw new Refusal('A different job is already open in this native session. No follow-up was submitted.');
|
|
471
|
+
ctl.followup=follow;
|
|
472
|
+
parsed={...incoming,brief:follow.brief,requestRoot:linkedRoot,legacyRequestRoot:linkedRoot,root:linkedRoot};
|
|
473
|
+
} else if(!ctl.pending&&ctl.continuingSupported&&!incoming.root) {
|
|
474
|
+
const nativeRoot='acp-'+sha256(JSON.stringify([nativeContinuingHandle(s.id),incoming.requestRoot])).slice(0,24);
|
|
475
|
+
parsed={...incoming,requestRoot:nativeRoot,legacyRequestRoot:nativeRoot};
|
|
476
|
+
}
|
|
389
477
|
const notes = ctl.pending?.notes ?? [];
|
|
390
478
|
const correction=/^Correct ([-\w]{8,128})\r?\n([\s\S]+)$/i.exec(incoming.brief);
|
|
391
|
-
const incomingRead=explicitReadIntent(correction?correction[2].trim():incoming.brief);
|
|
479
|
+
const incomingRead=explicitReadIntent(correction?correction[2].trim():follow?follow.brief:incoming.brief);
|
|
392
480
|
const correctionRoot=correction ? `acp-${sha256(JSON.stringify([WORKER,correction[1],correction[2].trim()])).slice(0,24)}` : null;
|
|
393
481
|
let correctionRetry=correction&&ctl.pending?.revises===correction[1]&&ctl.pending.root===correctionRoot;
|
|
394
482
|
if(correction&&!correctionRetry&&ctl.pending?.rid!==correction[1]) throw new Refusal('the named work is not held by this child; no correction was sent');
|
|
@@ -413,6 +501,11 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
413
501
|
publishPending(s, ctl);
|
|
414
502
|
if (!correction) await say('agent_message_chunk', `The correction was not admitted. Continuing earlier work ${prior.rid}.\n`);
|
|
415
503
|
}
|
|
504
|
+
if(ctl.pending.decisionAttachment) {
|
|
505
|
+
assertDecisionMembership(ctl.pending.decisionAttachment,row);
|
|
506
|
+
if(correction&&ctl.pending.decisionAttachment.handle)
|
|
507
|
+
throw new Refusal('This session can wait for the original decision, but cannot correct another continuation.');
|
|
508
|
+
} else if(ctl.pending.continuing||row.subagent_id)assertNativeBinding(s,ctl.pending.continuing,row,ctl.pending.follows??null);
|
|
416
509
|
assertReadIntent(incomingRead,row.assignment);
|
|
417
510
|
if (ctl.pending.submission_pending) {
|
|
418
511
|
const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
|
|
@@ -426,6 +519,7 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
426
519
|
ctl.pending.revises ??= row.revises?.request_id;
|
|
427
520
|
ctl.pending.repositoryContext = storedRepositoryContext(row.assignment, ctl.pending.repositoryContext);
|
|
428
521
|
parsed = { brief: withoutNote(row.assignment.brief), priority: ctl.pending.priority ?? 'normal', requirements: ctl.pending.requirements ?? [], requestRoot: ctl.pending.root };
|
|
522
|
+
if(ctl.pending.follows&&!ctl.followup)ctl.followup={prior:ctl.pending.follows};
|
|
429
523
|
if(correction&&!correctionRetry) {
|
|
430
524
|
const rawDelta=correction[2].trim();
|
|
431
525
|
const delta=incomingRead?rawDelta.split(/\r?\n/).slice(1).join('\n').trim():rawDelta;
|
|
@@ -443,7 +537,7 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
443
537
|
if (ctl.pending) {
|
|
444
538
|
// Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
|
|
445
539
|
const steerText = text.trim();
|
|
446
|
-
if (!correctionRetry && steerText && steerText !== CONTINUE_PROMPT && sha256(incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
|
|
540
|
+
if (!correctionRetry && steerText && steerText !== CONTINUE_PROMPT && sha256(follow?follow.brief:incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
|
|
447
541
|
} else {
|
|
448
542
|
// An explicit withdrawal may still have landed despite a failed submit reply; clean up only that scoped request.
|
|
449
543
|
try { ctl.pending = await acquire(s, parsed, ctl); }
|
|
@@ -485,6 +579,7 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
485
579
|
if (ctl.pending.terminal) return {text:ctl.pending.terminal.text};
|
|
486
580
|
const outcome = await waitLoop(s, ctl, say, client);
|
|
487
581
|
if (outcome.expired) {
|
|
582
|
+
if(ctl.pending.decisionAttachment?.handle)throw new Refusal('The observed decision expired. This session did not submit replacement work.');
|
|
488
583
|
if(ctl.pending.revises) throw refuse(`correction ${ctl.pending.rid} expired before it was claimed`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
|
|
489
584
|
if (expiries + 1 >= MAX_EXPIRIES) throw refuse(`assignment ${ctl.pending.rid} expired ${MAX_EXPIRIES} times before the worker claimed it`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
|
|
490
585
|
await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
|
|
@@ -524,8 +619,9 @@ async function waitLoop(s, ctl, say, client) {
|
|
|
524
619
|
r = await call(`/wait?id=${encodeURIComponent(ctl.pending.rid)}&timeout=${slice}&peek=1`, ctl.pending.rid, { signal });
|
|
525
620
|
waiting = false;
|
|
526
621
|
if (ctl.cancelled) return { cancelled: true };
|
|
527
|
-
if (r.status !== 'progress' && r.status !== 'ack_message') {
|
|
622
|
+
if (ctl.pending.decisionAttachment||r.status !== 'progress' && r.status !== 'ack_message') {
|
|
528
623
|
row = await readRowOrThrow(ctl.pending.rid, signal);
|
|
624
|
+
if(ctl.pending.decisionAttachment)assertDecisionMembership(ctl.pending.decisionAttachment,row);
|
|
529
625
|
}
|
|
530
626
|
// A successful /wait alone is not recovery if its follow-up read still fails.
|
|
531
627
|
outageSince = null;
|
|
@@ -578,7 +674,7 @@ async function waitLoop(s, ctl, say, client) {
|
|
|
578
674
|
}
|
|
579
675
|
if (r.status === 'question' || r.status === 'blocker') {
|
|
580
676
|
// A question never ends the child turn: the job is still open, so report the failure once and try again next round.
|
|
581
|
-
try { await handleQuestions(s, ctl, say, client, r); }
|
|
677
|
+
try { if(!ctl.pending.decisionAttachment?.handle)await handleQuestions(s, ctl, say, client, r); }
|
|
582
678
|
catch (error) {
|
|
583
679
|
if (ctl.cancelled) return { cancelled: true };
|
|
584
680
|
if (error instanceof acp.RequestError) throw error;
|
|
@@ -592,7 +688,7 @@ async function waitLoop(s, ctl, say, client) {
|
|
|
592
688
|
continue;
|
|
593
689
|
}
|
|
594
690
|
if (r.status === 'finished') {
|
|
595
|
-
const text = await resultText(row, s);
|
|
691
|
+
const text = await resultText(row, s, !!ctl.pending.decisionAttachment?.handle);
|
|
596
692
|
if (ctl.cancelled) return { cancelled: true };
|
|
597
693
|
trackBuild(s, row);
|
|
598
694
|
const terminal = row.delivery?.findLast(e => ['result','t3','wait'].includes(e.kind) && !e.terminal_reason?.includes('question'));
|
|
@@ -732,7 +828,7 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
732
828
|
}
|
|
733
829
|
requireResidentSessionCapacity();
|
|
734
830
|
const saved = readSession(params.sessionId); // a session without an assignment has no file: it restores empty
|
|
735
|
-
sessions.set(params.sessionId, { id: params.sessionId, cwd: params.cwd ?? saved?.cwd, model: MODEL, pending: saved?.pending ?? null, builds: saved?.builds ?? [], completed: saved?.completed ?? [], loaded: true, ctl: null });
|
|
831
|
+
sessions.set(params.sessionId, { id: params.sessionId, cwd: params.cwd ?? saved?.cwd, model: MODEL, pending: saved?.pending ?? null, builds: saved?.builds ?? [], completed: saved?.completed ?? [], continuing:saved?.continuing??null, loaded: true, ctl: null });
|
|
736
832
|
return { configOptions: configOptions(MODEL) };
|
|
737
833
|
})
|
|
738
834
|
.onRequest(acp.methods.agent.session.setConfigOption, ({ params }) => {
|
|
@@ -767,6 +863,7 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
767
863
|
const saved = readSession(s.id);
|
|
768
864
|
ctl.pending = s.pending = saved?.pending ?? null;
|
|
769
865
|
s.builds = saved?.builds ?? s.builds ?? [];
|
|
866
|
+
s.continuing = saved?.continuing ?? null;
|
|
770
867
|
s.completed = saved?.completed ?? s.completed ?? [];
|
|
771
868
|
const text = promptText(params.prompt);
|
|
772
869
|
s.cancelledRid = saved?.cancelledRid ?? null;
|
|
@@ -817,9 +914,19 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
817
914
|
s.cancelledRid = null;
|
|
818
915
|
saveSession(s);
|
|
819
916
|
}
|
|
820
|
-
const
|
|
917
|
+
const recovery=/^(?:Recover|Retrieve|Read) ([-\w]{8,128})$/i.exec(text.trim())?.[1];
|
|
918
|
+
const replay = completedReplay(s, text, recovery);
|
|
919
|
+
if(recovery&&!replay&&ctl.pending?.rid!==recovery)
|
|
920
|
+
throw refuse('This child cannot recover the named work. No new job was submitted.',{failure_type:'adapter_error'});
|
|
821
921
|
s.loaded = false;
|
|
822
922
|
if (!ctl.pending && replay) {
|
|
923
|
+
if(replay.continuing||replay.decisionAttachment) {
|
|
924
|
+
const original=await readRow(replay.rid,ctl.abort.signal);
|
|
925
|
+
if(!original||original.status!=='finished'||original.report?.receipt_id!==replay.terminal?.report_receipt_id)
|
|
926
|
+
throw new Refusal('The bridge could not confirm the original result receipt.');
|
|
927
|
+
if(replay.decisionAttachment)assertDecisionMembership(replay.decisionAttachment,original);
|
|
928
|
+
else assertNativeBinding(s,replay.continuing,original,replay.follows??null);
|
|
929
|
+
}
|
|
823
930
|
if (ctl.hostTaskId && !replay.later_host_task_ids.includes(ctl.hostTaskId)) replay.later_host_task_ids.push(ctl.hostTaskId);
|
|
824
931
|
if (requestId !== replay.original_prompt_request_id && !replay.later_prompt_request_ids.includes(requestId)) replay.later_prompt_request_ids.push(requestId);
|
|
825
932
|
saveSession(s);
|
|
@@ -886,11 +993,13 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
886
993
|
const explicitControl = params._meta?.dalanControl !== undefined;
|
|
887
994
|
const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
|
|
888
995
|
: ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
|
|
889
|
-
const
|
|
890
|
-
|
|
996
|
+
const observed=ctl?.pending??s.pending??readSession(s.id)?.pending;
|
|
997
|
+
const waitOnly=!!observed?.decisionAttachment?.handle;
|
|
998
|
+
const grace = !waitOnly&&!explicitControl&&withdrawalRid ? armWithdrawalGrace(s, withdrawalRid, ctl) : null;
|
|
999
|
+
if (!ctl) { if (!waitOnly&&explicitControl&&withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
|
|
891
1000
|
ctl.cancelled = true;
|
|
892
|
-
ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
|
|
893
|
-
if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
|
|
1001
|
+
ctl.withdrawWork = !waitOnly&&explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
|
|
1002
|
+
if(!waitOnly&&!explicitControl) ctl.workerState='withdrawal_pending_grace';
|
|
894
1003
|
ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : grace ?? Promise.resolve();
|
|
895
1004
|
ctl.abort.abort();
|
|
896
1005
|
});
|
|
@@ -942,9 +1051,13 @@ function explicitWithdrawalRid(meta) {
|
|
|
942
1051
|
return match?.[1] ?? null;
|
|
943
1052
|
}
|
|
944
1053
|
|
|
945
|
-
function completedReplay(s, text) {
|
|
1054
|
+
function completedReplay(s, text, recovery) {
|
|
946
1055
|
const last = s.completed.at(-1);
|
|
947
|
-
|
|
1056
|
+
const exact=recovery??text.trim();
|
|
1057
|
+
const explicitFollow=/^Follow-up(?:\s|$)/i.test(parsePrompt(text,{worker:WORKER}).brief.trim());
|
|
1058
|
+
if(explicitFollow)return null;
|
|
1059
|
+
return s.completed.findLast(item=>item.work_id===exact||
|
|
1060
|
+
(!item.continuing&&!item.decisionAttachment&&!recovery&&text.includes(item.work_id))) ??
|
|
948
1061
|
(text.trim() === CONTINUE_PROMPT && (s.loaded || last?.preserved_on_cancel) ? last : null);
|
|
949
1062
|
}
|
|
950
1063
|
const cancellationRetries = new Map();
|
|
@@ -970,7 +1083,8 @@ async function cancelYieldedSession(s, rid) {
|
|
|
970
1083
|
// Keep the intent bound to the job the user cancelled, not whichever job next owns this session.
|
|
971
1084
|
let lock;
|
|
972
1085
|
try {
|
|
973
|
-
|
|
1086
|
+
const original=readSession(s.id)?.pending;
|
|
1087
|
+
if (!rid||original?.rid!==rid||original.decisionAttachment?.handle) return;
|
|
974
1088
|
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
975
1089
|
writeJsonPrivate(cancellationFile(s.id), { ...(intent?.rid===rid?intent:{}), rid });
|
|
976
1090
|
lock = await lockSession(s.id, CANCEL_BUDGET_MS);
|
|
@@ -980,8 +1094,10 @@ async function cancelYieldedSession(s, rid) {
|
|
|
980
1094
|
log('Stop target changed before lock acquisition; later work was not cancelled.');
|
|
981
1095
|
return;
|
|
982
1096
|
}
|
|
1097
|
+
if(saved.pending.decisionAttachment?.handle) return;
|
|
983
1098
|
ctl.pending = s.pending = saved.pending;
|
|
984
1099
|
s.completed = saved.completed ?? [];
|
|
1100
|
+
s.continuing = saved.continuing ?? null;
|
|
985
1101
|
s.builds = saved.builds ?? [];
|
|
986
1102
|
await withdrawSavedCancellation(s, ctl);
|
|
987
1103
|
} catch (error) {
|
|
@@ -993,6 +1109,7 @@ async function cancelYieldedSession(s, rid) {
|
|
|
993
1109
|
}
|
|
994
1110
|
|
|
995
1111
|
async function withdrawSavedCancellation(s, ctl) {
|
|
1112
|
+
if(ctl.pending.decisionAttachment?.handle) return;
|
|
996
1113
|
ctl.pending.cancel_requested = true;
|
|
997
1114
|
publishPending(s, ctl);
|
|
998
1115
|
const rid = ctl.pending.rid;
|
|
@@ -1005,7 +1122,7 @@ async function withdrawSavedCancellation(s, ctl) {
|
|
|
1005
1122
|
|
|
1006
1123
|
async function cancelPending(s, ctl) {
|
|
1007
1124
|
const pending = ctl.pending;
|
|
1008
|
-
if (!pending) return;
|
|
1125
|
+
if (!pending||pending.decisionAttachment?.handle) return;
|
|
1009
1126
|
try {
|
|
1010
1127
|
if (currentTurn(s, ctl)) {
|
|
1011
1128
|
pending.cancel_requested = true;
|
|
@@ -1048,7 +1165,7 @@ async function cancelPending(s, ctl) {
|
|
|
1048
1165
|
}
|
|
1049
1166
|
// A worker may have already finished. Cancel the wait, not its result.
|
|
1050
1167
|
if (row.status === 'finished') {
|
|
1051
|
-
const text = pending.terminal?.text ?? await resultText(row, s);
|
|
1168
|
+
const text = pending.terminal?.text ?? await resultText(row, s, !!pending.decisionAttachment?.handle);
|
|
1052
1169
|
if (ctl.pending !== pending) return;
|
|
1053
1170
|
trackBuild(s, row);
|
|
1054
1171
|
const terminal = row.delivery?.findLast(e => ['result','t3','wait'].includes(e.kind) && !e.terminal_reason?.includes('question'));
|
package/bin/dot-worker.mjs
CHANGED
|
@@ -22,6 +22,7 @@ import { decideDrained, drainedExitCodes, terminal } from '../src/drained.mjs';
|
|
|
22
22
|
import { takeSlot, releaseSlot } from '../src/drained-slot.mjs';
|
|
23
23
|
import { liveWaiter } from '../src/drained-owner.mjs';
|
|
24
24
|
import { resolveHelp } from '../src/cli-help.mjs';
|
|
25
|
+
import { localAttachmentCommand } from '../src/local-attachment-cli.mjs';
|
|
25
26
|
import { readLines } from '../src/request-log.mjs';
|
|
26
27
|
import { lintChecksFile, formatChecksReport } from '../src/check-lint.mjs';
|
|
27
28
|
import { parseExecution, parseRequiredCapabilities, hostReadiness, hostBackend } from '../src/execution.mjs';
|
|
@@ -435,6 +436,17 @@ async function main() {
|
|
|
435
436
|
const help=resolveHelp([command,...args]);
|
|
436
437
|
if(help){ if(help.stream==='stdout') console.log(help.text); else console.error(help.text); process.exitCode=help.code; return; }
|
|
437
438
|
switch (command) {
|
|
439
|
+
case 'attachment': {
|
|
440
|
+
result=localAttachmentCommand(args);
|
|
441
|
+
if(!json) {
|
|
442
|
+
const lines=[`Local preview for ${result.repo}. Nothing sent; sending is not available.`,
|
|
443
|
+
`Manifest ${result.manifest_sha256} (${result.patch_bytes} patch bytes)`,
|
|
444
|
+
...result.selected.map(({path,disposition})=>`Include ${path}: ${disposition}`),
|
|
445
|
+
...result.omitted.map(({path,reason})=>`Omit ${path}: ${reason.replaceAll('_',' ')}`)];
|
|
446
|
+
result=lines.join('\n');plainOutput=true;
|
|
447
|
+
}
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
438
450
|
case 'paths': {
|
|
439
451
|
const selectors={'--workspace-root':()=>workspaceRoot(home),'--config-root':()=>defaultPath(home,'.config/dot-bridge'),'--data-root':()=>root,'--state-root':()=>defaultPath(home,'.local/state/dot-bridge')};
|
|
440
452
|
if(args.some(arg=>arg!=='--json'&&!Object.hasOwn(selectors,arg))||args.filter(arg=>Object.hasOwn(selectors,arg)).length>1)throw new Error('usage: dalan paths [--json | --workspace-root | --config-root | --data-root | --state-root]');
|
|
@@ -773,19 +785,20 @@ async function main() {
|
|
|
773
785
|
}
|
|
774
786
|
case 'materialize': {
|
|
775
787
|
const id=args[0], flags=args.slice(1), parsed=new Map();
|
|
776
|
-
const usage='usage: dalan materialize ID [--dir PATH] [--approve] [--dry-run] [--json]';
|
|
788
|
+
const usage='usage: dalan materialize ID [--dir PATH] [--approve | --standing-only] [--dry-run] [--json]';
|
|
777
789
|
for(let i=0;i<flags.length;i++) {
|
|
778
790
|
const flag=flags[i];
|
|
779
|
-
if(!['--dir','--approve','--dry-run','--json'].includes(flag) || parsed.has(flag)) throw new Error(usage);
|
|
791
|
+
if(!['--dir','--approve','--standing-only','--dry-run','--json'].includes(flag) || parsed.has(flag)) throw new Error(usage);
|
|
780
792
|
const value=flag==='--dir' ? flags[++i] : true;
|
|
781
793
|
if(!value || (flag==='--dir' && value.startsWith('--'))) throw new Error(usage);
|
|
782
794
|
parsed.set(flag,value);
|
|
783
795
|
}
|
|
784
|
-
if(!/^[-\w]{8,128}$/.test(id??'') || parsed.has('--dry-run') && parsed.has('--approve')) throw new Error(usage);
|
|
796
|
+
if(!/^[-\w]{8,128}$/.test(id??'') || (parsed.has('--dry-run') || parsed.has('--standing-only')) && parsed.has('--approve')) throw new Error(usage);
|
|
785
797
|
readMaterializeGrant(defaultPath(home,'.config/dot-bridge/materialize.json'));
|
|
786
798
|
const headers={'x-owner-capability':receipt(id).token};
|
|
787
799
|
result=await materialize({id, got:await request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers), grantFile:defaultPath(home,'.config/dot-bridge/materialize.json'),
|
|
788
800
|
dir:path.resolve(parsed.get('--dir')||process.cwd()), dryRun:parsed.has('--dry-run'), approve:parsed.has('--approve'),
|
|
801
|
+
standingOnly:parsed.has('--standing-only'), fetchBase:parsed.has('--standing-only'),
|
|
789
802
|
recheck:()=>request('/get?id='+encodeURIComponent(id)+'&peek=1','GET',null,headers),
|
|
790
803
|
download:async art=>{
|
|
791
804
|
const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-download-')), file=path.join(temp,'patch.diff');
|
|
@@ -794,7 +807,7 @@ async function main() {
|
|
|
794
807
|
}});
|
|
795
808
|
delete result.published; if(!result.pr_url) delete result.branch; delete result.reason;
|
|
796
809
|
if(!json) {
|
|
797
|
-
const message=result.pr_url ? 'Draft pull request: '+result.pr_url : (parsed.has('--dry-run')?'Dry run only: ':'Not published: ')+result.decision.reason+'; branch '+result.decision.branch;
|
|
810
|
+
const message=result.pr_url ? 'Draft pull request: '+result.pr_url : (parsed.has('--dry-run')?'Dry run only: ':'Not published: ')+result.decision.reason+(result.decision.branch ? '; branch '+result.decision.branch : '');
|
|
798
811
|
result=[result.repo+' at '+result.base_sha, message, ...result.files.map(file=>' '+file)].join('\n');
|
|
799
812
|
plainOutput=true;
|
|
800
813
|
}
|