@tnunamak/dalan 0.8.3 → 0.8.5

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 CHANGED
@@ -4,6 +4,18 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.8.5 (2026-12-03)
8
+
9
+ - Look up delegated work with `dalan get` and the ID from its first reply, even without an original local receipt. This read uses the installed bridge owner's existing permission.
10
+ - Admission shows a run-length estimate when worker session reports are absent. It names its source and sample count: observed first claim to final report per worker run. Provider start and end times remain unknown.
11
+
12
+ ## 0.8.4 (2026-12-03)
13
+
14
+ - Identical requests to different workers stay separate. Retries still find matching work submitted before the upgrade.
15
+ - Cancelling withdraws queued or claimed work after a short grace window. An immediate follow-up keeps the original job attached; a late follow-up is not silently run as a new task.
16
+ - Published build results name the branch, draft PR and verified commit. They no longer ask callers to apply and push an already published patch. Changed publication details or verification timeouts keep the patch fallback.
17
+ - Worker-reported runtime safety blocks use the refusal outcome and preserve their text. Ordinary checkout and tool failures remain blocked.
18
+
7
19
  ## 0.8.3 (2026-12-03)
8
20
 
9
21
  ## 0.8.2 (2026-12-03)
@@ -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
- const WORKER = process.env.DOT_ACP_WORKER || null;
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 { return await call(`/get?id=${encodeURIComponent(rid)}&peek=1${admission ? '&admission=1' : ''}`, rid, { signal }); }
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,16 @@ 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
+ } else if (session?.source === 'bridge_observed_acquisition_runs') {
325
+ if (count(session.p50_ms)) line.push(`typical session estimate ~${duration(session.p50_ms)} (bridge-observed claim-to-final-report per run, n ${session.n}${window(session.window_days)})`);
326
+ else line.push(`typical session estimate: not enough history (bridge-observed run spans, n ${count(session.n) ? session.n : 0})`);
309
327
  }
310
328
  const warnings = Array.isArray(submission_warnings) ? submission_warnings.filter(value => typeof value === 'string') : [];
311
329
  return [`${line.join('; ')}.`, ...warnings.map(warning => `Submission warning: ${warning}`)].join('\n');
312
330
  }
313
331
 
314
332
  async function runTurn(s, ctl, text, say, client) {
315
- const incoming = parsePrompt(text);
333
+ const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
316
334
  let parsed = incoming;
317
335
  const notes = ctl.pending?.notes ?? [];
318
336
  if (ctl.pending) {
@@ -654,26 +672,47 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
654
672
  try {
655
673
  lock = await lockSession(s.id);
656
674
  // session/load can precede another process finishing; read again under ownership.
675
+ if (WORKER === null) {
676
+ const status = await call('/status', null, { signal: ctl.abort.signal });
677
+ // Older bridges have only the legacy default and omit this field.
678
+ WORKER = status.default_worker === undefined ? 'dot' : status.default_worker;
679
+ if (typeof WORKER !== 'string' || !/^[a-z][a-z0-9_-]{0,31}$/.test(WORKER)) throw new Refusal('the bridge requires an explicit worker');
680
+ }
657
681
  const saved = readSession(s.id);
658
682
  ctl.pending = s.pending = saved?.pending ?? null;
659
683
  s.builds = saved?.builds ?? s.builds ?? [];
660
684
  s.completed = saved?.completed ?? s.completed ?? [];
661
685
  const text = promptText(params.prompt);
662
686
  s.cancelledRid = saved?.cancelledRid ?? null;
663
- const intent = readJsonPrivate(cancellationFile(s.id));
687
+ s.cancelledAt = saved?.cancelledAt ?? null;
688
+ s.cancelledByGrace = saved?.cancelledByGrace === true;
689
+ let intent = readJsonPrivate(cancellationFile(s.id));
690
+ if (intent?.not_before && intent.rid === ctl.pending?.rid) {
691
+ if (text.trim() !== CONTINUE_PROMPT && Date.now() < intent.not_before) {
692
+ // A prompt in the native steer window keeps the original work attached.
693
+ fs.rmSync(cancellationFile(s.id), {force:true}); intent=null;
694
+ } else if (Date.now() < intent.not_before) {
695
+ await sleep(intent.not_before-Date.now(), ctl.abort.signal);
696
+ }
697
+ }
664
698
  if (ctl.pending?.cancel_requested || (ctl.pending && intent?.rid === ctl.pending.rid)) {
665
699
  const completed = await withdrawSavedCancellation(s, ctl);
666
700
  if (completed?.terminal) {
667
701
  await say('agent_message_chunk', completed.terminal.text + (completed.notes ?? []).map(n => `\n\nnot sent to the worker: ${n}`).join(''));
668
702
  return { stopReason: 'end_turn' };
669
703
  }
670
- if (!ctl.pending || ctl.pending.cancel_requested) {
704
+ if ((!ctl.pending && text.trim() === CONTINUE_PROMPT) || ctl.pending?.cancel_requested) {
671
705
  await say('agent_message_chunk', s.cancelledRid
672
706
  ? `Wait for work ${s.cancelledRid} was cancelled.\n`
673
707
  : 'Cancellation requested; continue to retry if it is not yet confirmed.\n');
674
708
  return { stopReason: 'cancelled' };
675
709
  }
676
710
  }
711
+ if (!ctl.pending && s.cancelledRid && s.cancelledByGrace && Date.now()-Date.parse(s.cancelledAt)<60000) {
712
+ s.cancelledByGrace=false;saveSession(s);
713
+ 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`);
714
+ return {stopReason:'end_turn'};
715
+ }
677
716
  if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
678
717
  await say('agent_message_chunk', `Wait for work ${s.cancelledRid} was cancelled.\n`);
679
718
  return { stopReason: 'cancelled' };
@@ -719,7 +758,12 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
719
758
  else throw refuse(`worker adapter error: ${e.message}`,{failure_type:transient(e)?'transport_error':'adapter_error',failure_type_source:'dot_acp_adapter'});
720
759
  }
721
760
  // Bounded: the 5 s fallback plus at most 2 s here stays inside T3's 10 s cancel window.
722
- if (outcome.cancelled) { await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]); 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`); return { stopReason: 'cancelled' }; }
761
+ if (outcome.cancelled) {
762
+ await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]);
763
+ 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`);
764
+ 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'});
765
+ return { stopReason: 'cancelled' };
766
+ }
723
767
  if (outcome.resumable) {
724
768
  // A yielded wait is not a terminal receipt. Keep the request attached for a later prompt.
725
769
  publishPending(s, ctl);
@@ -742,16 +786,24 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
742
786
  lock?.release();
743
787
  }
744
788
  })
745
- // ACP cancel is a local interruption. Work withdrawal needs an explicit host control intent bound to one job ID.
789
+ // ACP cancel is a local interruption; a prompt in the grace window is steering.
790
+ // Without a follow-up prompt, withdraw the bound work after the grace window.
746
791
  .onNotification(acp.methods.agent.session.cancel, ({ params }) => {
747
792
  const s = sessions.get(params.sessionId);
748
793
  const ctl = s?.ctl;
749
794
  if (!s) return;
750
- const withdrawalRid = explicitWithdrawalRid(params._meta);
751
- if (!ctl) { if (withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
795
+ const explicitControl = params._meta?.dalanControl !== undefined;
796
+ const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
797
+ : ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
798
+ if (!explicitControl && withdrawalRid) {
799
+ writeJsonPrivate(cancellationFile(s.id), {rid:withdrawalRid,not_before:Date.now()+CANCEL_GRACE_MS});
800
+ retryWithdrawal(s,withdrawalRid);
801
+ }
802
+ if (!ctl) { if (explicitControl && withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
752
803
  if (ctl.cancelled) return;
753
804
  ctl.cancelled = true;
754
- ctl.withdrawWork = !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
805
+ ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
806
+ if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
755
807
  ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
756
808
  ctl.abort.abort();
757
809
  });
@@ -768,13 +820,32 @@ function completedReplay(s, text) {
768
820
  return s.completed.findLast(item => text.includes(item.work_id)) ??
769
821
  (text.trim() === CONTINUE_PROMPT && (s.loaded || last?.preserved_on_cancel) ? last : null);
770
822
  }
823
+ const cancellationRetries = new Map();
824
+ function retryWithdrawal(s, rid) {
825
+ if (cancellationRetries.has(s.id)) return;
826
+ const timer=setTimeout(async () => {
827
+ cancellationRetries.delete(s.id);
828
+ const pending=readSession(s.id)?.pending;
829
+ const intent=readJsonPrivate(cancellationFile(s.id));
830
+ if(pending?.rid !== rid || (!pending.cancel_requested && intent?.rid !== rid)) return;
831
+ if(intent?.not_before && Date.now()<intent.not_before) {retryWithdrawal(s,rid);return;}
832
+ if(s.ctl) { retryWithdrawal(s,rid); return; }
833
+ try { await cancelYieldedSession(s,rid); }
834
+ finally {
835
+ const remaining=readSession(s.id)?.pending;
836
+ if(remaining?.rid===rid && (remaining.cancel_requested || readJsonPrivate(cancellationFile(s.id))?.rid===rid)) retryWithdrawal(s,rid);
837
+ }
838
+ },500);
839
+ timer.unref(); cancellationRetries.set(s.id,timer);
840
+ }
771
841
  async function cancelYieldedSession(s, rid) {
772
842
  const ctl = s.ctl = { cancelled: true, pending: null, generation: s.generation = (s.generation ?? 0) + 1 };
773
843
  // Keep the intent bound to the job the user cancelled, not whichever job next owns this session.
774
844
  let lock;
775
845
  try {
776
846
  if (!rid || readSession(s.id)?.pending?.rid !== rid) return;
777
- writeJsonPrivate(cancellationFile(s.id), { rid });
847
+ const intent=readJsonPrivate(cancellationFile(s.id));
848
+ writeJsonPrivate(cancellationFile(s.id), { ...(intent?.rid===rid?intent:{}), rid });
778
849
  lock = await lockSession(s.id, CANCEL_BUDGET_MS);
779
850
  const saved = readSession(s.id);
780
851
  if (saved?.pending?.rid !== rid) {
@@ -812,15 +883,24 @@ async function cancelPending(s, ctl) {
812
883
  if (currentTurn(s, ctl)) {
813
884
  pending.cancel_requested = true;
814
885
  publishPending(s, ctl);
815
- writeJsonPrivate(cancellationFile(s.id), { rid: pending.rid });
886
+ const intent=readJsonPrivate(cancellationFile(s.id));
887
+ writeJsonPrivate(cancellationFile(s.id), { ...(intent?.rid===pending.rid?intent:{}), rid: pending.rid });
816
888
  }
817
889
  const clearIntent = () => {
818
- if (currentTurn(s, ctl) && readJsonPrivate(cancellationFile(s.id))?.rid === pending.rid) {
890
+ const intent=readJsonPrivate(cancellationFile(s.id));
891
+ if (currentTurn(s, ctl) && intent?.rid === pending.rid) {
892
+ if(intent.not_before && s.cancelledRid===pending.rid) {
893
+ s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;saveSession(s);
894
+ }
819
895
  fs.rmSync(cancellationFile(s.id), { force: true });
820
896
  }
821
897
  };
822
898
  ctl.cancelledWorkId = pending.rid;
823
- const row = await readRowOrThrow(pending.rid);
899
+ let row = await readRowOrThrow(pending.rid);
900
+ if (row.status === 'finished' && pending.withdrawal_started) {
901
+ ctl.workerState = 'finished_after_withdrawal_request';
902
+ s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl); clearIntent(); return;
903
+ }
824
904
  // A worker may have already finished. Cancel the wait, not its result.
825
905
  if (row.status === 'finished') {
826
906
  const text = pending.terminal?.text ?? await resultText(row, s);
@@ -837,16 +917,30 @@ async function cancelPending(s, ctl) {
837
917
  return completed;
838
918
  }
839
919
  // 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
920
  if (pending.cancel_requested && row.status === 'cancelled') {
845
921
  s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl);
846
922
  clearIntent();
847
923
  return;
848
924
  }
849
- const r = await Promise.race([call('/cancel', pending.rid, { method: 'POST', payload: { id: pending.rid, command_key: `acp-cancel:${pending.rid}`, ...(Number.isSafeInteger(row.protocol_revision) ? {expected_revision:row.protocol_revision} : {}) } }), sleep(CANCEL_BUDGET_MS).then(() => null)]);
925
+ pending.withdrawal_started = true; publishPending(s, ctl);
926
+ let r;
927
+ const deadline = Date.now() + CANCEL_BUDGET_MS;
928
+ for (let attempt = 0; attempt < 3; attempt++) {
929
+ const remaining = deadline - Date.now();
930
+ if (remaining <= 0) break;
931
+ try {
932
+ r = await call('/cancel', pending.rid, { method: 'POST', timeoutMs: remaining, payload: {
933
+ id: pending.rid, command_key: `acp-cancel:${pending.rid}:${row.protocol_revision ?? 'legacy'}`,
934
+ ...(Number.isSafeInteger(row.protocol_revision) ? {expected_revision:row.protocol_revision} : {}) } });
935
+ break;
936
+ } catch (error) {
937
+ if (!/revision_conflict/.test(error.message) || attempt === 2) throw error;
938
+ row = await readRowOrThrow(pending.rid);
939
+ if (row.status === 'finished') {
940
+ ctl.workerState='finished_after_withdrawal_request';s.cancelledRid=pending.rid;ctl.pending=null;publishPending(s,ctl);clearIntent();return;
941
+ }
942
+ }
943
+ }
850
944
  ctl.computeStopped = r?.compute_stopped === true ? true : r?.compute_stopped === false ? false : null;
851
945
  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
946
  if (r?.status === 'cancelled' && ctl.pending === pending) {
@@ -856,6 +950,7 @@ async function cancelPending(s, ctl) {
856
950
  clearIntent();
857
951
  }
858
952
  } catch (e) { ctl.workerState = 'still_running'; log(`cancel failed for ${pending.rid}: ${e.message}`); }
953
+ if (ctl.pending === pending && pending.cancel_requested) retryWithdrawal(s, pending.rid);
859
954
  }
860
955
 
861
956
  // T3 closing our stdin means it is done with this session. Exit without cancelling anything: queued rows expire by
@@ -182,6 +182,20 @@ function writeReceipt(id, token, body, delivery, review=false, background=false,
182
182
  return receipt(id);
183
183
  }
184
184
  function operator() { const file=defaultPath(home,'.config/dot-bridge/operator.key'); const mode=fs.statSync(file).mode&0o777; if(mode!==0o600) throw new Error('operator key must be mode 0600'); return fs.readFileSync(file,'utf8').trim(); }
185
+ // Only local operator reads can recover facade handles without copying its host's secret.
186
+ // A saved receipt always keeps its own authority; this never applies to writes or waits.
187
+ function getReadHeaders(id) {
188
+ if(id.startsWith('msg_')) return {};
189
+ let missing=false;
190
+ try { fs.lstatSync(receiptPath(id)); }
191
+ catch(error) { if(error.code!=='ENOENT') throw error; missing=true; }
192
+ if(missing && /^acp-[a-f0-9]{24}(?:_r[2-6])?$/.test(id)) {
193
+ try { return {'x-operator-key':operator()}; }
194
+ catch(error) { if(error.code!=='ENOENT') throw error; }
195
+ }
196
+ return {'x-owner-capability':receipt(id).token};
197
+ }
198
+
185
199
  async function waitForAssignment(id, timeout) {
186
200
  const seconds=timeout===null?300:Number(timeout);
187
201
  if(!Number.isInteger(seconds)||seconds<1||seconds>3600) throw new Error('wait timeout must be an integer from 1 to 3600 seconds');
@@ -596,7 +610,7 @@ async function main() {
596
610
  if(!json&&!waitOutput&&process.stdout.isTTY) { result=`Request ID: ${id}${briefGiven?`\nSend your worker: ${workerPrompt(id)}`:''}`; plainOutput=true; endNote=endNote.split('\n').filter(l=>!l.startsWith('Request ID: ')&&!l.startsWith('Send your worker: ')).join('\n'); }
597
611
  break;
598
612
  }
599
- case 'get': { refuseUnknownOptions('get',{flags:['--json']}); const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`get needs a request ID: ${cli} get REQUEST_ID (list your jobs with: ${cli} inbox --all)`); const headers=id.startsWith('msg_')?{}:{'x-owner-capability':receipt(id).token}; result=await request('/get?id='+encodeURIComponent(id),'GET',null,headers); if(!id.startsWith('msg_')) indexArtifacts(id,result);
613
+ case 'get': { refuseUnknownOptions('get',{flags:['--json']}); const id=args[0]; if(!id||id.startsWith('-')) throw new Error(`get needs a request ID: ${cli} get REQUEST_ID (list your jobs with: ${cli} inbox --all)`); const headers=getReadHeaders(id); result=await request('/get?id='+encodeURIComponent(id)+(headers['x-operator-key']?'&peek=1':''),'GET',null,headers); if(!id.startsWith('msg_')) indexArtifacts(id,result);
600
614
  // Human mode: one extra line on stderr so stdout stays the JSON document.
601
615
  if(!json&&result?.claim?.activity) { const a=result.claim.activity, age=a.last_tool_at?Math.max(0,Math.round((Date.now()-Date.parse(a.last_tool_at))/1000)):null;
602
616
  console.error(`worker activity: ${a.tool_calls} call${a.tool_calls===1?'':'s'}${a.last_tool?`, last ${a.last_tool} at ${a.last_tool_at.slice(11,19)}Z (${age<90?age+'s':age<5400?Math.round(age/60)+'m':Math.round(age/3600)+'h'} ago)`:''}${a.first_workspace_tool_at?'':', no workspace tool'}${a.last_tool_error?`, last error: ${a.last_tool_error}`:''}`); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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
- return { brief: lines.join('\n').trim(), priority, requirements, root, requestRoot: root ?? `acp-${sha256(text).slice(0, 24)}` };
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.published ? `Branch: ${result.branch}\nDraft PR: ${result.pr_url}` : `Not published: ${result.reason}`;
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
- if (publication) lines.push(publication);
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');
@@ -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
- return {branch,pr_url};
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 provider’s exact refusal text in result.',
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']),
@@ -1624,7 +1624,8 @@ const adminServer=http.createServer(async(req,res)=>{
1624
1624
  if(url.pathname==='/get') {
1625
1625
  const requestId=id(url.searchParams.get('id'));
1626
1626
  if(!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)) return json(res,200,{kind:'message',message:store.getMessage(requestId)});
1627
- adminOwner(req,requestId);
1627
+ if(req.headers['x-operator-key']!==undefined && /^acp-[a-f0-9]{24}(?:_r[2-6])?$/.test(requestId)) adminOperator(req);
1628
+ else adminOwner(req,requestId);
1628
1629
  store.assertProtocolAvailable(requestId);
1629
1630
  store.recordFetched(requestId);
1630
1631
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
@@ -1709,7 +1710,7 @@ const adminServer=http.createServer(async(req,res)=>{
1709
1710
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1710
1711
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1711
1712
  }
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});
1713
+ 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
1714
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1714
1715
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1715
1716
  const requestId=id(body.id); adminOwner(req,requestId);
package/src/store.mjs CHANGED
@@ -1385,8 +1385,17 @@ export class Store {
1385
1385
  }
1386
1386
  sessionLength(worker,days=7) {
1387
1387
  const since=iso(this.nowMs()-days*86400000), min_samples=QUEUE_WINDOW.minSamples;
1388
- const lengths=this.db.prepare('SELECT duration_ms FROM worker_sessions WHERE worker=? AND ended_at>=? ORDER BY duration_ms').all(worker,since).map(row=>row.duration_ms);
1389
- return {source:'worker_reported_sessions',n:lengths.length,min_samples,window_days:days,
1388
+ const reported=this.db.prepare('SELECT duration_ms FROM worker_sessions WHERE worker=? AND ended_at>=? ORDER BY duration_ms').all(worker,since).map(row=>row.duration_ms);
1389
+ // A worker supplies one acquisition ID per run. These are observed work spans,
1390
+ // not provider start/end receipts: omit runs with an active or missing report.
1391
+ const spans=reported.length ? [] : this.db.prepare(`SELECT MIN(c.claimed_at) started_at,MAX(r.created_at) ended_at
1392
+ FROM claims c LEFT JOIN reports r ON r.request_id=c.request_id AND r.claim_id=c.claim_id
1393
+ WHERE c.worker=? AND c.acquisition_id IS NOT NULL AND c.acquisition_id NOT LIKE 'handoff-%'
1394
+ GROUP BY c.subject,c.acquisition_id
1395
+ HAVING MAX(r.created_at)>=? AND SUM(r.claim_id IS NULL)=0`).all(worker,since)
1396
+ .map(row=>Date.parse(row.ended_at)-Date.parse(row.started_at)).filter(ms=>Number.isFinite(ms)&&ms>=0).sort((a,b)=>a-b);
1397
+ const lengths=reported.length?reported:spans;
1398
+ return {source:reported.length?'worker_reported_sessions':'bridge_observed_acquisition_runs',n:lengths.length,min_samples,window_days:days,
1390
1399
  p50_ms:lengths.length<min_samples?null:lengths[Math.ceil(lengths.length/2)-1]};
1391
1400
  }
1392
1401
  trackRecord(worker,kind,days=7) {
@@ -3347,6 +3356,10 @@ export class Store {
3347
3356
  finish(id,claimId,outcome,summary,result,subject='local-principal',evidence=null,worker='dot',ctx=null,captureEvidence=null,connectionId=null) {
3348
3357
  if(this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled')
3349
3358
  return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
3359
+ // Older worker runtimes report their safety rejection through ordinary finish.
3360
+ // Preserve the worker's text; only the explicit runtime cause changes classification.
3361
+ if (outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
3362
+ /(?:^|\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
3363
  const rollback=[];
3351
3364
  let done;
3352
3365
  try { done=this.transaction(() => this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null,connectionId)); }