@tnunamak/dalan 0.8.3 → 0.8.4
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/bin/dot-acp-agent.mjs +115 -22
- package/package.json +1 -1
- package/src/acp-bridge.mjs +12 -4
- package/src/patch-apply.mjs +18 -3
- package/src/server.mjs +2 -2
- package/src/store.mjs +4 -0
package/bin/dot-acp-agent.mjs
CHANGED
|
@@ -23,6 +23,7 @@ const IN_FLIGHT_CAP = num('DOT_ACP_INFLIGHT_CAP', 10);
|
|
|
23
23
|
const VALID_MS = num('DOT_ACP_VALID_MINUTES', 30) * 60_000;
|
|
24
24
|
const OUTAGE_MS = num('DOT_ACP_OUTAGE_MS', 600_000);
|
|
25
25
|
const CANCEL_BUDGET_MS = cancelBudgetMs(process.env.DOT_ACP_CANCEL_BUDGET_MS); // T3 allows 10 s for the prompt to return after session/cancel
|
|
26
|
+
const CANCEL_GRACE_MS = 2000; // T3 uses cancel followed by a prompt for steering.
|
|
26
27
|
const QUEUE_WAIT_MS = num('DALAN_ACP_BREAK_WAIT_MS', 30 * 60_000); // Keep the existing setting for ordinary queued waits.
|
|
27
28
|
// Submit does server-side work that reads never do (it reads the pinned repository to scan the scope, checks pull request
|
|
28
29
|
// state and, for builds, runs the check-readiness probes), so it gets its own deadline; every other call keeps the 5 s
|
|
@@ -33,7 +34,7 @@ const MAX_ATTEMPTS = 6;
|
|
|
33
34
|
const MAX_EXPIRIES = 3;
|
|
34
35
|
// One adapter serves several bridge workers: DOT_ACP_WORKER picks the bridge worker that submissions target (unset = the
|
|
35
36
|
// bridge default, the worker), and DOT_ACP_MODEL/DOT_ACP_LABEL name the T3 model. DOT_ACP_SOCKET picks the bridge.
|
|
36
|
-
|
|
37
|
+
let WORKER = process.env.DOT_ACP_WORKER || null;
|
|
37
38
|
// Same rule as a worker name in workers.json (src/workers.mjs).
|
|
38
39
|
if (WORKER !== null && !/^[a-z][a-z0-9_-]{0,31}$/.test(WORKER)) throw new Error('DOT_ACP_WORKER must be a worker name');
|
|
39
40
|
const MODEL = process.env.DOT_ACP_MODEL || 'dot';
|
|
@@ -76,7 +77,7 @@ const sessionFile = id => {
|
|
|
76
77
|
// Keep active work and terminal receipts; probes and idle sessions leave nothing behind.
|
|
77
78
|
function saveSession(s) {
|
|
78
79
|
if (!s.pending && !s.completed?.length && !s.builds?.length && !s.cancelledRid) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
|
|
79
|
-
writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, cancelledRid: s.cancelledRid ?? null, builds: s.builds ?? [], completed: s.completed ?? [] });
|
|
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, builds: s.builds ?? [], completed: s.completed ?? [] });
|
|
80
81
|
}
|
|
81
82
|
const readSession = id => readJsonPrivate(sessionFile(id));
|
|
82
83
|
// Independent of the session lock: never overwrite another process's live session record.
|
|
@@ -109,8 +110,13 @@ const tokenFor = rid => ownerToken(secret ??= readOrCreateSecret(P.secretFile),
|
|
|
109
110
|
const call = (route, rid, opts = {}) => adminRequestThroughRestart(P.socket, route, { ...opts, token: rid ? tokenFor(rid) : undefined });
|
|
110
111
|
|
|
111
112
|
// The stored row for this request id with our token: null when the bridge has no such row, a Refusal when it is not ours.
|
|
112
|
-
async function readRow(rid, signal, admission = false) {
|
|
113
|
-
try {
|
|
113
|
+
async function readRow(rid, signal, admission = false, matchingWorkerOnly = false) {
|
|
114
|
+
try {
|
|
115
|
+
const row = await call(`/get?id=${encodeURIComponent(rid)}&peek=1${admission ? '&admission=1' : ''}`, rid, { signal });
|
|
116
|
+
if (WORKER !== null && row.target_worker !== WORKER && matchingWorkerOnly) return null;
|
|
117
|
+
if (WORKER !== null && row.target_worker !== WORKER) throw new Refusal(`request ${rid} belongs to a different worker`, 'adapter_error');
|
|
118
|
+
return row;
|
|
119
|
+
}
|
|
114
120
|
catch (e) {
|
|
115
121
|
if (e.message === 'message not found' || e.message === 'assignment not found') return null;
|
|
116
122
|
// Not an admission refusal: the bridge holds this id for another owner, so label it as the bridge response it is.
|
|
@@ -127,11 +133,20 @@ const attachedAdmission = row => ({ status: row.status, execution: row.execution
|
|
|
127
133
|
// row cancelled or expired -> next attempt id `<root>_r<n>`
|
|
128
134
|
// row queued/claimed/finished-> attach; the wait returns the result or keeps waiting
|
|
129
135
|
async function acquire(s, parsed, ctl) {
|
|
136
|
+
// Reuse work admitted before worker-scoped anonymous identities were introduced.
|
|
137
|
+
// A legacy row belongs to this retry only when its authenticated worker matches.
|
|
138
|
+
if (!parsed.root && !ctl.correction && parsed.legacyRequestRoot !== parsed.requestRoot) {
|
|
139
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
140
|
+
const legacy = await readRow(attemptId(parsed.legacyRequestRoot, attempt), undefined, true, true);
|
|
141
|
+
if (!legacy || legacy.status === 'cancelled') continue;
|
|
142
|
+
parsed = { ...parsed, requestRoot: parsed.legacyRequestRoot, legacyAttempt: attempt }; break;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
130
145
|
const briefHash = sha256(parsed.brief);
|
|
131
146
|
let submitRetries = 0;
|
|
132
147
|
let conflictExhausted = false;
|
|
133
148
|
const preparedByAttempt=new Map();
|
|
134
|
-
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
149
|
+
for (let attempt = parsed.legacyAttempt ?? 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
135
150
|
ctl.abort.signal.throwIfAborted();
|
|
136
151
|
const rid = attemptId(parsed.requestRoot, attempt);
|
|
137
152
|
const row = await readRow(rid, undefined, true);
|
|
@@ -306,13 +321,14 @@ function admissionText(admission, attached) {
|
|
|
306
321
|
if (session?.source === 'worker_reported_sessions') {
|
|
307
322
|
if (count(session.p50_ms)) line.push(`typical session ~${duration(session.p50_ms)} (worker reported, n ${session.n}${window(session.window_days)})`);
|
|
308
323
|
else line.push(`typical session: not enough history (worker reported, n ${count(session.n) ? session.n : 0})`);
|
|
324
|
+
|
|
309
325
|
}
|
|
310
326
|
const warnings = Array.isArray(submission_warnings) ? submission_warnings.filter(value => typeof value === 'string') : [];
|
|
311
327
|
return [`${line.join('; ')}.`, ...warnings.map(warning => `Submission warning: ${warning}`)].join('\n');
|
|
312
328
|
}
|
|
313
329
|
|
|
314
330
|
async function runTurn(s, ctl, text, say, client) {
|
|
315
|
-
const incoming = parsePrompt(text);
|
|
331
|
+
const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
|
|
316
332
|
let parsed = incoming;
|
|
317
333
|
const notes = ctl.pending?.notes ?? [];
|
|
318
334
|
if (ctl.pending) {
|
|
@@ -654,26 +670,47 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
654
670
|
try {
|
|
655
671
|
lock = await lockSession(s.id);
|
|
656
672
|
// session/load can precede another process finishing; read again under ownership.
|
|
673
|
+
if (WORKER === null) {
|
|
674
|
+
const status = await call('/status', null, { signal: ctl.abort.signal });
|
|
675
|
+
// Older bridges have only the legacy default and omit this field.
|
|
676
|
+
WORKER = status.default_worker === undefined ? 'dot' : status.default_worker;
|
|
677
|
+
if (typeof WORKER !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(WORKER)) throw new Refusal('the bridge requires an explicit worker');
|
|
678
|
+
}
|
|
657
679
|
const saved = readSession(s.id);
|
|
658
680
|
ctl.pending = s.pending = saved?.pending ?? null;
|
|
659
681
|
s.builds = saved?.builds ?? s.builds ?? [];
|
|
660
682
|
s.completed = saved?.completed ?? s.completed ?? [];
|
|
661
683
|
const text = promptText(params.prompt);
|
|
662
684
|
s.cancelledRid = saved?.cancelledRid ?? null;
|
|
663
|
-
|
|
685
|
+
s.cancelledAt = saved?.cancelledAt ?? null;
|
|
686
|
+
s.cancelledByGrace = saved?.cancelledByGrace === true;
|
|
687
|
+
let intent = readJsonPrivate(cancellationFile(s.id));
|
|
688
|
+
if (intent?.not_before && intent.rid === ctl.pending?.rid) {
|
|
689
|
+
if (text.trim() !== CONTINUE_PROMPT && Date.now() < intent.not_before) {
|
|
690
|
+
// A prompt in the native steer window keeps the original work attached.
|
|
691
|
+
fs.rmSync(cancellationFile(s.id), {force:true}); intent=null;
|
|
692
|
+
} else if (Date.now() < intent.not_before) {
|
|
693
|
+
await sleep(intent.not_before-Date.now(), ctl.abort.signal);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
664
696
|
if (ctl.pending?.cancel_requested || (ctl.pending && intent?.rid === ctl.pending.rid)) {
|
|
665
697
|
const completed = await withdrawSavedCancellation(s, ctl);
|
|
666
698
|
if (completed?.terminal) {
|
|
667
699
|
await say('agent_message_chunk', completed.terminal.text + (completed.notes ?? []).map(n => `\n\nnot sent to the worker: ${n}`).join(''));
|
|
668
700
|
return { stopReason: 'end_turn' };
|
|
669
701
|
}
|
|
670
|
-
if (!ctl.pending || ctl.pending
|
|
702
|
+
if ((!ctl.pending && text.trim() === CONTINUE_PROMPT) || ctl.pending?.cancel_requested) {
|
|
671
703
|
await say('agent_message_chunk', s.cancelledRid
|
|
672
704
|
? `Wait for work ${s.cancelledRid} was cancelled.\n`
|
|
673
705
|
: 'Cancellation requested; continue to retry if it is not yet confirmed.\n');
|
|
674
706
|
return { stopReason: 'cancelled' };
|
|
675
707
|
}
|
|
676
708
|
}
|
|
709
|
+
if (!ctl.pending && s.cancelledRid && s.cancelledByGrace && Date.now()-Date.parse(s.cancelledAt)<60000) {
|
|
710
|
+
s.cancelledByGrace=false;saveSession(s);
|
|
711
|
+
await say('agent_message_chunk', `Your earlier work ${s.cancelledRid} was cancelled at ${s.cancelledAt} (no follow-up within 2 s). This message was not submitted. Resend the full task if you want new work.\n`);
|
|
712
|
+
return {stopReason:'end_turn'};
|
|
713
|
+
}
|
|
677
714
|
if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
|
|
678
715
|
await say('agent_message_chunk', `Wait for work ${s.cancelledRid} was cancelled.\n`);
|
|
679
716
|
return { stopReason: 'cancelled' };
|
|
@@ -719,7 +756,12 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
719
756
|
else throw refuse(`worker adapter error: ${e.message}`,{failure_type:transient(e)?'transport_error':'adapter_error',failure_type_source:'dot_acp_adapter'});
|
|
720
757
|
}
|
|
721
758
|
// Bounded: the 5 s fallback plus at most 2 s here stays inside T3's 10 s cancel window.
|
|
722
|
-
if (outcome.cancelled) {
|
|
759
|
+
if (outcome.cancelled) {
|
|
760
|
+
await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]);
|
|
761
|
+
await say('agent_message_chunk', `requester_interrupted: true; worker_state: ${ctl.workerState ?? 'still_running'}; work_id: ${ctl.pending?.rid ?? ctl.cancelledWorkId ?? 'not yet assigned'}; compute_stopped: ${ctl.computeStopped === true ? 'true' : ctl.computeStopped === false ? 'false' : 'unknown'}\n`);
|
|
762
|
+
if (ctl.withdrawWork && ctl.pending?.cancel_requested) throw refuse('Cancellation requested; bridge withdrawal not yet confirmed. Retrying in the background.', {failure_type:'transport_error',failure_type_source:'dot_acp_cancel_pending'});
|
|
763
|
+
return { stopReason: 'cancelled' };
|
|
764
|
+
}
|
|
723
765
|
if (outcome.resumable) {
|
|
724
766
|
// A yielded wait is not a terminal receipt. Keep the request attached for a later prompt.
|
|
725
767
|
publishPending(s, ctl);
|
|
@@ -742,16 +784,24 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
742
784
|
lock?.release();
|
|
743
785
|
}
|
|
744
786
|
})
|
|
745
|
-
// ACP cancel is a local interruption
|
|
787
|
+
// ACP cancel is a local interruption; a prompt in the grace window is steering.
|
|
788
|
+
// Without a follow-up prompt, withdraw the bound work after the grace window.
|
|
746
789
|
.onNotification(acp.methods.agent.session.cancel, ({ params }) => {
|
|
747
790
|
const s = sessions.get(params.sessionId);
|
|
748
791
|
const ctl = s?.ctl;
|
|
749
792
|
if (!s) return;
|
|
750
|
-
const
|
|
751
|
-
|
|
793
|
+
const explicitControl = params._meta?.dalanControl !== undefined;
|
|
794
|
+
const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
|
|
795
|
+
: ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
|
|
796
|
+
if (!explicitControl && withdrawalRid) {
|
|
797
|
+
writeJsonPrivate(cancellationFile(s.id), {rid:withdrawalRid,not_before:Date.now()+CANCEL_GRACE_MS});
|
|
798
|
+
retryWithdrawal(s,withdrawalRid);
|
|
799
|
+
}
|
|
800
|
+
if (!ctl) { if (explicitControl && withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
|
|
752
801
|
if (ctl.cancelled) return;
|
|
753
802
|
ctl.cancelled = true;
|
|
754
|
-
ctl.withdrawWork = !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
|
|
803
|
+
ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
|
|
804
|
+
if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
|
|
755
805
|
ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
|
|
756
806
|
ctl.abort.abort();
|
|
757
807
|
});
|
|
@@ -768,13 +818,32 @@ function completedReplay(s, text) {
|
|
|
768
818
|
return s.completed.findLast(item => text.includes(item.work_id)) ??
|
|
769
819
|
(text.trim() === CONTINUE_PROMPT && (s.loaded || last?.preserved_on_cancel) ? last : null);
|
|
770
820
|
}
|
|
821
|
+
const cancellationRetries = new Map();
|
|
822
|
+
function retryWithdrawal(s, rid) {
|
|
823
|
+
if (cancellationRetries.has(s.id)) return;
|
|
824
|
+
const timer=setTimeout(async () => {
|
|
825
|
+
cancellationRetries.delete(s.id);
|
|
826
|
+
const pending=readSession(s.id)?.pending;
|
|
827
|
+
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
828
|
+
if(pending?.rid !== rid || (!pending.cancel_requested && intent?.rid !== rid)) return;
|
|
829
|
+
if(intent?.not_before && Date.now()<intent.not_before) {retryWithdrawal(s,rid);return;}
|
|
830
|
+
if(s.ctl) { retryWithdrawal(s,rid); return; }
|
|
831
|
+
try { await cancelYieldedSession(s,rid); }
|
|
832
|
+
finally {
|
|
833
|
+
const remaining=readSession(s.id)?.pending;
|
|
834
|
+
if(remaining?.rid===rid && (remaining.cancel_requested || readJsonPrivate(cancellationFile(s.id))?.rid===rid)) retryWithdrawal(s,rid);
|
|
835
|
+
}
|
|
836
|
+
},500);
|
|
837
|
+
timer.unref(); cancellationRetries.set(s.id,timer);
|
|
838
|
+
}
|
|
771
839
|
async function cancelYieldedSession(s, rid) {
|
|
772
840
|
const ctl = s.ctl = { cancelled: true, pending: null, generation: s.generation = (s.generation ?? 0) + 1 };
|
|
773
841
|
// Keep the intent bound to the job the user cancelled, not whichever job next owns this session.
|
|
774
842
|
let lock;
|
|
775
843
|
try {
|
|
776
844
|
if (!rid || readSession(s.id)?.pending?.rid !== rid) return;
|
|
777
|
-
|
|
845
|
+
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
846
|
+
writeJsonPrivate(cancellationFile(s.id), { ...(intent?.rid===rid?intent:{}), rid });
|
|
778
847
|
lock = await lockSession(s.id, CANCEL_BUDGET_MS);
|
|
779
848
|
const saved = readSession(s.id);
|
|
780
849
|
if (saved?.pending?.rid !== rid) {
|
|
@@ -812,15 +881,24 @@ async function cancelPending(s, ctl) {
|
|
|
812
881
|
if (currentTurn(s, ctl)) {
|
|
813
882
|
pending.cancel_requested = true;
|
|
814
883
|
publishPending(s, ctl);
|
|
815
|
-
|
|
884
|
+
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
885
|
+
writeJsonPrivate(cancellationFile(s.id), { ...(intent?.rid===pending.rid?intent:{}), rid: pending.rid });
|
|
816
886
|
}
|
|
817
887
|
const clearIntent = () => {
|
|
818
|
-
|
|
888
|
+
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
889
|
+
if (currentTurn(s, ctl) && intent?.rid === pending.rid) {
|
|
890
|
+
if(intent.not_before && s.cancelledRid===pending.rid) {
|
|
891
|
+
s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;saveSession(s);
|
|
892
|
+
}
|
|
819
893
|
fs.rmSync(cancellationFile(s.id), { force: true });
|
|
820
894
|
}
|
|
821
895
|
};
|
|
822
896
|
ctl.cancelledWorkId = pending.rid;
|
|
823
|
-
|
|
897
|
+
let row = await readRowOrThrow(pending.rid);
|
|
898
|
+
if (row.status === 'finished' && pending.withdrawal_started) {
|
|
899
|
+
ctl.workerState = 'finished_after_withdrawal_request';
|
|
900
|
+
s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl); clearIntent(); return;
|
|
901
|
+
}
|
|
824
902
|
// A worker may have already finished. Cancel the wait, not its result.
|
|
825
903
|
if (row.status === 'finished') {
|
|
826
904
|
const text = pending.terminal?.text ?? await resultText(row, s);
|
|
@@ -837,16 +915,30 @@ async function cancelPending(s, ctl) {
|
|
|
837
915
|
return completed;
|
|
838
916
|
}
|
|
839
917
|
// The bridge expired it unclaimed: nobody cancelled the work, so the next prompt resubmits it.
|
|
840
|
-
if (pending.cancel_requested && row.status === 'cancelled' && row.cancelled_reason === 'expired') {
|
|
841
|
-
delete pending.cancel_requested; publishPending(s, ctl); clearIntent();
|
|
842
|
-
return;
|
|
843
|
-
}
|
|
844
918
|
if (pending.cancel_requested && row.status === 'cancelled') {
|
|
845
919
|
s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl);
|
|
846
920
|
clearIntent();
|
|
847
921
|
return;
|
|
848
922
|
}
|
|
849
|
-
|
|
923
|
+
pending.withdrawal_started = true; publishPending(s, ctl);
|
|
924
|
+
let r;
|
|
925
|
+
const deadline = Date.now() + CANCEL_BUDGET_MS;
|
|
926
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
927
|
+
const remaining = deadline - Date.now();
|
|
928
|
+
if (remaining <= 0) break;
|
|
929
|
+
try {
|
|
930
|
+
r = await call('/cancel', pending.rid, { method: 'POST', timeoutMs: remaining, payload: {
|
|
931
|
+
id: pending.rid, command_key: `acp-cancel:${pending.rid}:${row.protocol_revision ?? 'legacy'}`,
|
|
932
|
+
...(Number.isSafeInteger(row.protocol_revision) ? {expected_revision:row.protocol_revision} : {}) } });
|
|
933
|
+
break;
|
|
934
|
+
} catch (error) {
|
|
935
|
+
if (!/revision_conflict/.test(error.message) || attempt === 2) throw error;
|
|
936
|
+
row = await readRowOrThrow(pending.rid);
|
|
937
|
+
if (row.status === 'finished') {
|
|
938
|
+
ctl.workerState='finished_after_withdrawal_request';s.cancelledRid=pending.rid;ctl.pending=null;publishPending(s,ctl);clearIntent();return;
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
}
|
|
850
942
|
ctl.computeStopped = r?.compute_stopped === true ? true : r?.compute_stopped === false ? false : null;
|
|
851
943
|
ctl.workerState = !r ? 'still_running' : (r.scope?.not_controlled === 'nothing was running, so there was no worker compute to stop' || !r.scope && row.status === 'queued') ? 'withdrawn' : r.compute_stopped === true ? 'withdrawn' : 'stop_requested';
|
|
852
944
|
if (r?.status === 'cancelled' && ctl.pending === pending) {
|
|
@@ -856,6 +948,7 @@ async function cancelPending(s, ctl) {
|
|
|
856
948
|
clearIntent();
|
|
857
949
|
}
|
|
858
950
|
} catch (e) { ctl.workerState = 'still_running'; log(`cancel failed for ${pending.rid}: ${e.message}`); }
|
|
951
|
+
if (ctl.pending === pending && pending.cancel_requested) retryWithdrawal(s, pending.rid);
|
|
859
952
|
}
|
|
860
953
|
|
|
861
954
|
// T3 closing our stdin means it is done with this session. Exit without cancelling anything: queued rows expire by
|
package/package.json
CHANGED
package/src/acp-bridge.mjs
CHANGED
|
@@ -141,7 +141,7 @@ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000, wallC
|
|
|
141
141
|
// The brief the worker sees is the prompt without the router's token line. The root decision id keys the bridge request.
|
|
142
142
|
// T3's delegate_task puts `Act as the <role> sub-agent for this task.\n\n` before the task for every role except general
|
|
143
143
|
// (and none); parseIdentity strips it, because otherwise the token line and a [dot-build] line are no longer first.
|
|
144
|
-
export function parsePrompt(prompt) {
|
|
144
|
+
export function parsePrompt(prompt, { worker = null } = {}) {
|
|
145
145
|
const { id: root, text, brief } = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
|
|
146
146
|
// Without a token the identity is the text after the T3 preamble, so a resend with or without a role maps to one request.
|
|
147
147
|
const lines = brief.split('\n');
|
|
@@ -153,7 +153,9 @@ export function parsePrompt(prompt) {
|
|
|
153
153
|
if (!['normal', 'background'].includes(priority)) throw new Refusal('priority must be normal or background');
|
|
154
154
|
} else requirements = line.slice(9).trim().split(/[,\s]+/).filter(Boolean);
|
|
155
155
|
}
|
|
156
|
-
|
|
156
|
+
// Anonymous retries share an identity only within the selected worker.
|
|
157
|
+
const identity = worker === null ? text : JSON.stringify([worker, text]);
|
|
158
|
+
return { brief: lines.join('\n').trim(), priority, requirements, root, requestRoot: root ?? `acp-${sha256(identity).slice(0, 24)}` };
|
|
157
159
|
}
|
|
158
160
|
// Attempt 1 is the root itself. After a cancelled or expired row the next attempt is `<root>_r<n>` (the bridge accepts only
|
|
159
161
|
// [-\w] in a request id, so the doc's `#` separator cannot be used).
|
|
@@ -615,7 +617,7 @@ export async function materializeBuildResult(row, text, patch, proseCheck, {cwd,
|
|
|
615
617
|
const result=await materialize({id:row.request_id, got:row, dir:cwd, recheck:getCurrent,
|
|
616
618
|
grantFile:path.join(os.homedir(),'.config/dot-bridge/materialize.json'),
|
|
617
619
|
download:async()=>patch, standingOnly:true, fetchBase:true});
|
|
618
|
-
publication=result
|
|
620
|
+
publication=result;
|
|
619
621
|
} catch(error) { publication='Not published: '+String(error?.message ?? error).replace(/[\r\n]+/g,' '); }
|
|
620
622
|
return buildResultText(row,text,patch,proseCheck,publication);
|
|
621
623
|
}
|
|
@@ -632,7 +634,9 @@ export function buildResultText(row, text, patch, proseCheck = null, publication
|
|
|
632
634
|
if (runs.length) lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.join('; ')}`);
|
|
633
635
|
if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${row.worker_run_limit}`);
|
|
634
636
|
if (proseCheck) lines.push(proseCheckText(proseCheck));
|
|
635
|
-
|
|
637
|
+
const published=publication?.published === true && /^[a-f0-9]{40}$/.test(publication.verified_head_sha ?? '');
|
|
638
|
+
if (published) lines.push(`Branch: ${publication.branch}\nDraft PR: ${publication.pr_url}\nVerified head SHA: ${publication.verified_head_sha} (remote head matches the sealed patch and pinned base)`);
|
|
639
|
+
else if (publication) lines.push(typeof publication === 'string' ? publication : `Not published: ${publication.reason ?? 'head not verified'}`);
|
|
636
640
|
if (!art?.artifact_id || !art.size) lines.push('patch: none (empty diff). Nothing to apply.');
|
|
637
641
|
else {
|
|
638
642
|
const body = patch === null || patch === undefined ? null : Buffer.from(patch).toString('utf8');
|
|
@@ -640,6 +644,10 @@ export function buildResultText(row, text, patch, proseCheck = null, publication
|
|
|
640
644
|
if (body !== null) lines.push(...diffstat(body), body.length <= PREVIEW_BYTES ? `\`\`\`diff\n${body}\`\`\`` : `(preview omitted: over ${PREVIEW_BYTES} bytes)`);
|
|
641
645
|
lines.push(`Fetch: dalan get ${rid} --json >/dev/null && dalan artifact ${art.artifact_id} --output <file>`);
|
|
642
646
|
}
|
|
647
|
+
if (published) {
|
|
648
|
+
lines.push(`Next: review the published draft and its checks. ${decideHint(rid)}`);
|
|
649
|
+
return lines.join('\n');
|
|
650
|
+
}
|
|
643
651
|
lines.push(`Next: on a clean checkout of that base, git apply the patch, re-run the tests yourself, push only if they pass. Then record the verdict: dalan accept ${rid}, or dalan reject ${rid} --note '<why>'. The delegation gate offers the worker builds only while these verdicts stay good.`);
|
|
644
652
|
lines.push(`Or apply it for you: dalan apply ${rid} [--dir <checkout>] (checks the digest and base, then records applied). ${decideHint(rid)}`);
|
|
645
653
|
return lines.join('\n');
|
package/src/patch-apply.mjs
CHANGED
|
@@ -123,8 +123,8 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
|
|
|
123
123
|
throw new Error('materialize needs a pinned GitHub repo and a scoped branch');
|
|
124
124
|
}
|
|
125
125
|
const run = (program, cwd, args, label) => {
|
|
126
|
-
const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024});
|
|
127
|
-
if(r.error || r.status!==0) throw new Error('materialize: '+label+' failed'+(r.status==null?'':' (exit '+r.status+')'));
|
|
126
|
+
const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024, timeout:10000, killSignal:'SIGKILL'});
|
|
127
|
+
if(r.error || r.status!==0) throw new Error('materialize: '+label+(r.error?.code === 'ETIMEDOUT' ? ' could not run (timed out)' : ' failed'+(r.status==null?'':' (exit '+r.status+')')));
|
|
128
128
|
return r.stdout.trim();
|
|
129
129
|
};
|
|
130
130
|
const gitCmd = (cwd, args, label) => run(process.env.DALAN_GIT || 'git',cwd,['-c','core.hooksPath=/dev/null', ...args],label);
|
|
@@ -165,6 +165,7 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
|
|
|
165
165
|
await recheck('push');
|
|
166
166
|
// Expect absence at the server, even if another publisher races this push.
|
|
167
167
|
if(!tip) gitCmd(worktree,['push','--no-follow-tags','--force-with-lease='+ref+':',remote,'HEAD:'+ref],'create scoped remote branch');
|
|
168
|
+
const expectedHead=tip ? tip.split(/\s+/)[0] : gitCmd(worktree,['rev-parse','HEAD'],'read published commit');
|
|
168
169
|
let pr_url;
|
|
169
170
|
try {
|
|
170
171
|
// The push can finish after the owner changes or withdraws approval.
|
|
@@ -185,10 +186,24 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
|
|
|
185
186
|
if(!pr_url.toLowerCase().startsWith(prefix) || !/^[1-9]\d*$/.test(pr_url.slice(prefix.length))) {
|
|
186
187
|
throw new Error('materialize did not receive the draft pull request URL');
|
|
187
188
|
}
|
|
189
|
+
const prHead=ghCmd(['api',`repos/${repo}/pulls/${pr_url.slice(prefix.length)}`,
|
|
190
|
+
'--jq','.head.repo.full_name + " " + .head.sha + " " + .head.ref + " " + .base.repo.full_name + " " + .base.ref + " " + .state + " " + (.draft|tostring)'],'verify draft repository and head');
|
|
191
|
+
const [headRepo,headSha,headRef,baseRepo,baseRef,prState,isDraft,...extra]=prHead.split(/\s+/);
|
|
192
|
+
if(headRepo?.toLowerCase()!==repo.toLowerCase() || headSha!==expectedHead || headRef!==branch || baseRepo?.toLowerCase()!==repo.toLowerCase() || baseRef!==targetBase || prState!=='open' || isDraft!=='true' || extra.length) {
|
|
193
|
+
throw new Error('draft identity or state changed; publication not verified');
|
|
194
|
+
}
|
|
195
|
+
|
|
188
196
|
} catch(error) {
|
|
189
197
|
throw new Error('materialize branch '+branch+' exists; draft pull request not confirmed. '+error.message);
|
|
190
198
|
}
|
|
191
|
-
|
|
199
|
+
// The existing scoped branch may have an equivalent tree under a different
|
|
200
|
+
// commit. Report its actual commit, and refuse success if the ref moved.
|
|
201
|
+
const remoteHead=gitCmd(worktree,['ls-remote','--heads',remote,ref],'verify published head');
|
|
202
|
+
const [head,remoteRef,...extra]=remoteHead.split(/\s+/);
|
|
203
|
+
if(head!==expectedHead || remoteRef!==ref || extra.length) {
|
|
204
|
+
throw new Error('materialize published head changed; draft may exist, publication not verified');
|
|
205
|
+
}
|
|
206
|
+
return {branch,pr_url,verified_head_sha:head};
|
|
192
207
|
} catch(error) {
|
|
193
208
|
failure=error;
|
|
194
209
|
throw error;
|
package/src/server.mjs
CHANGED
|
@@ -526,7 +526,7 @@ if(fs.existsSync(catalogGuardFile)) {
|
|
|
526
526
|
}
|
|
527
527
|
const refusalRegistration={
|
|
528
528
|
name:'finish_provider_refusal',
|
|
529
|
-
description:'Finish a held assignment when the provider explicitly refuses it. Put the
|
|
529
|
+
description:'Finish a held assignment when the provider or runtime safety check explicitly refuses it. Put the runtime’s exact refusal text in result without paraphrasing; safety redaction still applies.',
|
|
530
530
|
class:'write',
|
|
531
531
|
handler:{kind:'worker_refusal'},
|
|
532
532
|
inputSchema:schema({request_id:string,claim_id:string,result:{type:'string',minLength:1,maxLength:8000}},['request_id','claim_id','result']),
|
|
@@ -1709,7 +1709,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1709
1709
|
if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
|
|
1710
1710
|
} catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
|
|
1711
1711
|
}
|
|
1712
|
-
if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
|
|
1712
|
+
if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),default_worker:workers.legacy ? 'dot' : workers.workers.size === 1 ? [...workers.workers.keys()][0] : null,...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
|
|
1713
1713
|
if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
|
|
1714
1714
|
if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
|
|
1715
1715
|
const requestId=id(body.id); adminOwner(req,requestId);
|
package/src/store.mjs
CHANGED
|
@@ -3347,6 +3347,10 @@ export class Store {
|
|
|
3347
3347
|
finish(id,claimId,outcome,summary,result,subject='local-principal',evidence=null,worker='dot',ctx=null,captureEvidence=null,connectionId=null) {
|
|
3348
3348
|
if(this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled')
|
|
3349
3349
|
return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
|
|
3350
|
+
// Older worker runtimes report their safety rejection through ordinary finish.
|
|
3351
|
+
// Preserve the worker's text; only the explicit runtime cause changes classification.
|
|
3352
|
+
if (outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
|
|
3353
|
+
/(?:^|\n)(?:BLOCKED:\s*)?(?:The )?(?:claimed assignment content|claim tool result)\b[^\n]{0,240}\b(?:did not pass|failed)\b[^\n]{0,120}\b(?:safety|prompt-injection)[ -]check\b/i.test(text))) outcome=PROVIDER_REFUSAL;
|
|
3350
3354
|
const rollback=[];
|
|
3351
3355
|
let done;
|
|
3352
3356
|
try { done=this.transaction(() => this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null,connectionId)); }
|