@tnunamak/dalan 0.8.1 → 0.8.3

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.
Files changed (124) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +136 -21
  100. package/src/service-update.mjs +207 -51
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -4,6 +4,8 @@
4
4
  // Shared ACP support lives in integrations/t3/acp-kit/.
5
5
  import { Readable, Writable } from 'node:stream';
6
6
  import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { answerThroughJournal, journalPath, readJournal } from '../src/answer-journal.mjs';
7
9
  import { randomUUID } from 'node:crypto';
8
10
  import * as acp from '@agentclientprotocol/sdk';
9
11
  import { sessionPath, readJsonPrivate, writeJsonPrivate } from '../integrations/t3/acp-kit/src/session-store.mjs';
@@ -11,8 +13,8 @@ import { acquireLock, LockBusyError } from '../integrations/t3/acp-kit/src/lock.
11
13
  import { createRefuse, cancelBudgetMs, CANCEL_CLEANUP_MS } from '../integrations/t3/acp-kit/src/errors.mjs';
12
14
  import { detectPresentPatches } from '../src/patch-apply.mjs';
13
15
  import {
14
- paths, adminRequest, transient, sha256, parsePrompt, attemptId, ownerToken, readOrCreateSecret, bridgeRefusal,
15
- prepareAssignment, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, buildResultText, decideHint, runBuildProseCheck, adminArtifact,
16
+ buildExecution, paths, adminRequest, adminRequestThroughRestart, transient, sha256, parsePrompt, attemptId, ownerToken, readOrCreateSecret, bridgeRefusal,
17
+ prepareAssignmentWithContext, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait,
16
18
  } from '../src/acp-bridge.mjs';
17
19
 
18
20
  const num = (name, fallback) => { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; };
@@ -21,6 +23,7 @@ const IN_FLIGHT_CAP = num('DOT_ACP_INFLIGHT_CAP', 10);
21
23
  const VALID_MS = num('DOT_ACP_VALID_MINUTES', 30) * 60_000;
22
24
  const OUTAGE_MS = num('DOT_ACP_OUTAGE_MS', 600_000);
23
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 QUEUE_WAIT_MS = num('DALAN_ACP_BREAK_WAIT_MS', 30 * 60_000); // Keep the existing setting for ordinary queued waits.
24
27
  // Submit does server-side work that reads never do (it reads the pinned repository to scan the scope, checks pull request
25
28
  // state and, for builds, runs the check-readiness probes), so it gets its own deadline; every other call keeps the 5 s
26
29
  // DOT_ACP_HTTP_TIMEOUT_MS. A submit that times out is retried by request id, which the bridge treats as the same job.
@@ -45,22 +48,53 @@ const sleep = (ms, signal) => new Promise(resolve => {
45
48
  // ---------------------------------------------------------------- durable session state
46
49
  // One file per session (several adapter processes share the directory). Written atomically, mode 0600.
47
50
  const sessions = new Map();
51
+ const MAX_RESIDENT_SESSIONS = 256;
52
+ function requireResidentSessionCapacity() {
53
+ if (sessions.size < MAX_RESIDENT_SESSIONS) return;
54
+ // Insertion order is LRU order. A live controller means a prompt (including
55
+ // its wait/cleanup) owns this object; only a quiescent entry may be removed.
56
+ for (const [id, session] of sessions) {
57
+ if (session.ctl === null) {
58
+ sessions.delete(id);
59
+ return;
60
+ }
61
+ }
62
+ throw acp.RequestError.invalidRequest(null, 'session capacity reached');
63
+ }
64
+ function touchSession(id) {
65
+ const session = sessions.get(id);
66
+ if (session) {
67
+ sessions.delete(id);
68
+ sessions.set(id, session);
69
+ }
70
+ return session;
71
+ }
48
72
  const sessionFile = id => {
49
73
  try { return sessionPath(P.stateDir, id); }
50
74
  catch (e) { if (e.code === 'invalid_session_id') throw acp.RequestError.invalidParams(null, 'invalid session id'); throw e; }
51
75
  };
52
- // Only a session that holds an assignment needs a file; probes and idle sessions leave nothing behind.
76
+ // Keep active work and terminal receipts; probes and idle sessions leave nothing behind.
53
77
  function saveSession(s) {
54
- if (!s.pending && !s.builds?.length) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
55
- writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, builds: s.builds ?? [] });
78
+ 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 ?? [] });
56
80
  }
57
81
  const readSession = id => readJsonPrivate(sessionFile(id));
82
+ // Independent of the session lock: never overwrite another process's live session record.
83
+ const cancellationFile = id => `${sessionFile(id)}.cancel`;
58
84
 
59
85
  // Hold the session's lock file for the whole turn (portable O_EXCL lock; a crashed owner is detected by pid and start
60
86
  // time). Every writer/deleter runs while the session has one owner.
61
- async function lockSession(id) {
62
- try { return await acquireLock(`${sessionFile(id)}.lock`); }
63
- catch (e) { if (e instanceof LockBusyError) throw refuse(`session ${id} is active in another adapter`,{failure_type:'adapter_error',failure_type_source:'dot_acp_adapter'}); throw e; }
87
+ async function lockSession(id, retryMs = 0) {
88
+ const deadline = performance.now() + retryMs;
89
+ for (;;) {
90
+ try { return await acquireLock(`${sessionFile(id)}.lock`); }
91
+ catch (e) {
92
+ if (!(e instanceof LockBusyError)) throw e;
93
+ const remaining = deadline - performance.now();
94
+ if (remaining <= 0) throw refuse(`session ${id} is active in another adapter`,{failure_type:'adapter_error',failure_type_source:'dot_acp_adapter'});
95
+ await sleep(Math.min(50, remaining));
96
+ }
97
+ }
64
98
  }
65
99
 
66
100
  const configOptions = current => [{
@@ -72,17 +106,19 @@ const refuse = createRefuse(acp.RequestError); // T3 records a prompt error as a
72
106
  // ---------------------------------------------------------------- bridge operations
73
107
  let secret = null;
74
108
  const tokenFor = rid => ownerToken(secret ??= readOrCreateSecret(P.secretFile), rid);
75
- const call = (route, rid, opts = {}) => adminRequest(P.socket, route, { ...opts, token: rid ? tokenFor(rid) : undefined });
109
+ const call = (route, rid, opts = {}) => adminRequestThroughRestart(P.socket, route, { ...opts, token: rid ? tokenFor(rid) : undefined });
76
110
 
77
111
  // 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.
78
- async function readRow(rid) {
79
- try { return await call(`/get?id=${encodeURIComponent(rid)}&peek=1`, rid); }
112
+ async function readRow(rid, signal, admission = false) {
113
+ try { return await call(`/get?id=${encodeURIComponent(rid)}&peek=1${admission ? '&admission=1' : ''}`, rid, { signal }); }
80
114
  catch (e) {
81
115
  if (e.message === 'message not found' || e.message === 'assignment not found') return null;
82
- if (e.message === 'invalid owner capability') throw new Refusal(`request ${rid} exists under another owner`);
116
+ // Not an admission refusal: the bridge holds this id for another owner, so label it as the bridge response it is.
117
+ if (e.message === 'invalid owner capability') throw new Refusal(`request ${rid} exists under another owner`,'adapter_error',{failure_type_source:'dot_acp_bridge_response'});
83
118
  throw e;
84
119
  }
85
120
  }
121
+ const attachedAdmission = row => ({ status: row.status, execution: row.execution, ...(row.status === 'queued' ? row.admission : {}) });
86
122
 
87
123
  // Find the assignment for this brief, or submit one. A retried or restarted task attaches to the row it already
88
124
  // submitted, so the worker never gets the same brief twice:
@@ -90,28 +126,36 @@ async function readRow(rid) {
90
126
  // row with another brief -> refuse (one root token must not serve two briefs)
91
127
  // row cancelled or expired -> next attempt id `<root>_r<n>`
92
128
  // row queued/claimed/finished-> attach; the wait returns the result or keeps waiting
93
- async function acquire(s, parsed) {
129
+ async function acquire(s, parsed, ctl) {
94
130
  const briefHash = sha256(parsed.brief);
95
131
  let submitRetries = 0;
132
+ let conflictExhausted = false;
96
133
  const preparedByAttempt=new Map();
97
134
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
135
+ ctl.abort.signal.throwIfAborted();
98
136
  const rid = attemptId(parsed.requestRoot, attempt);
99
- const row = await readRow(rid);
137
+ const row = await readRow(rid, undefined, true);
100
138
  if (row) {
101
139
  const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
102
140
  if (storedHash !== briefHash) throw new Refusal(`token ${parsed.requestRoot} was already used with a different brief`);
103
- if (row.status === 'cancelled') continue;
104
- return { root: parsed.requestRoot, rid, attempt, briefHash, validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
141
+ if (row.status === 'cancelled' && !conflictExhausted) continue;
142
+ if (row.status === 'cancelled') throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
143
+ return { root: parsed.requestRoot, rid, attempt, briefHash, admission: attachedAdmission(row),
144
+ repositoryContext: preparedByAttempt.get(rid)?.repositoryContext ?? storedRepositoryContext(row.assignment),
145
+ validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
105
146
  }
147
+ // On the last conflict still reread once: the same brief may already exist.
148
+ if (conflictExhausted) throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
106
149
  const status = await call('/status', null);
107
- const refusal = bridgeRefusal(status, IN_FLIGHT_CAP);
150
+ const refusal = bridgeRefusal(status, IN_FLIGHT_CAP, WORKER, parsed.priority, true);
108
151
  if (refusal) throw new Refusal(refusal,'deferred',{failure_type_source:'bridge_status_refusal',verdict:'defer'});
109
152
  let prepared=preparedByAttempt.get(rid);
110
153
  if(!prepared) {
111
154
  const validUntil = new Date(Date.now() + VALID_MS).toISOString();
112
- const assignment = await prepareAssignment({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
113
- const body = { max_queued: IN_FLIGHT_CAP, delivery: 'none', ...(WORKER ? { worker: WORKER } : {}), assignment, owner_token: tokenFor(rid), meta: { source: 'agent', ...(assignment.execution_scope === 'implementation' ? { task_kind: 'build' } : {}) }, ...(assignment.inputs.length && assignment.execution_scope !== 'implementation' ? { exclude_sensitive: true } : {}) };
114
- prepared={body,validUntil}; preparedByAttempt.set(rid,prepared);
155
+ const {assignment, repositoryContext} = await prepareAssignmentWithContext({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
156
+ const body = { ...(parsed.priority === 'background' ? {background:true} : {}), required_capabilities: parsed.requirements ?? [], max_queued: IN_FLIGHT_CAP, caller_waiting: true, delivery: 'none', ...(WORKER ? { worker: WORKER } : {}), assignment, owner_token: tokenFor(rid), meta: { source: 'agent', ...(assignment.execution_scope === 'implementation' ? { task_kind: 'build' } : {}) }, ...(assignment.execution_scope === 'implementation' && buildExecution() ? { execution: buildExecution() } : {}), ...(assignment.inputs.length && assignment.execution_scope !== 'implementation' ? { exclude_sensitive: true } : {}) };
157
+ // max_queued makes admission atomic; the bridge counts only this worker's waiting callers of the same priority.
158
+ prepared={body,validUntil,repositoryContext}; preparedByAttempt.set(rid,prepared);
115
159
  }
116
160
  const {body,validUntil}=prepared;
117
161
  try {
@@ -128,10 +172,33 @@ async function acquire(s, parsed) {
128
172
  if(transient(e)&&submitRetries++<SUBMIT_RETRIES) { attempt--; continue; }
129
173
  throw e;
130
174
  }
131
- try { await call('/submit', null, { method: 'POST', payload: body, timeoutMs: SUBMIT_DEADLINE_MS }); }
175
+ // Persist only the deterministic work identity, not the request body or capability.
176
+ // A late response may arrive after bounded cancel has released the session lock.
177
+ ctl.abort.signal.throwIfAborted();
178
+ if (!currentTurn(s, ctl)) throw new Error('Cannot submit outside the active ACP turn.');
179
+ const intent = { root: parsed.requestRoot, rid, attempt, briefHash, validUntil, repositoryContext: prepared.repositoryContext,
180
+ priority: parsed.priority, requirements: parsed.requirements, notes: ctl.pending?.notes ?? [],
181
+ work_id: rid, original_host_task_id: ctl.hostTaskId ?? null, original_prompt_request_id: ctl.promptRequestId,
182
+ later_prompt_request_ids: [], later_host_task_ids: [], startedAt: Date.now(), submission_pending: true };
183
+ ctl.pending = intent;
184
+ publishPending(s, ctl);
185
+ // Admission belongs to the bridge; the richer forecast can replace this reply without changing ACP.
186
+ try { const admitted = await call('/submit', null, { method: 'POST', payload: body, timeoutMs: SUBMIT_DEADLINE_MS }); prepared.admission = admitted.admission ?? {status:admitted.status ?? 'queued', execution:admitted.execution, submission_warnings:admitted.submission_warnings}; }
132
187
  catch (e) {
133
- if (e.message === 'request_id conflict') { attempt--; continue; } // lost a race: re-read the row
134
- if(e.verdict) throw verdictRefusal(e);
188
+ if (e.message === 'request_id conflict') {
189
+ if (submitRetries >= SUBMIT_RETRIES) conflictExhausted = true;
190
+ else submitRetries++;
191
+ attempt--; continue;
192
+ }
193
+ if(e.verdict) {
194
+ // A first explicit admission refusal did not create work. After an ambiguous
195
+ // send, even a later refusal cannot prove the original submit did not land.
196
+ if (submitRetries === 0 && currentTurn(s, ctl) && ctl.pending === intent) {
197
+ ctl.pending = null;
198
+ publishPending(s, ctl);
199
+ }
200
+ throw verdictRefusal(e);
201
+ }
135
202
  // The bridge may have stored the job before the deadline; the same id and brief make the retry attach to it.
136
203
  if (transient(e) && submitRetries++ < SUBMIT_RETRIES) { attempt--; continue; }
137
204
  if (/^(?:worker|dot) queue is full/.test(e.message)) throw new Refusal(e.message);
@@ -139,20 +206,23 @@ async function acquire(s, parsed) {
139
206
  if (size) throw new Refusal(size);
140
207
  throw e;
141
208
  }
142
- return { root: parsed.requestRoot, rid, attempt, briefHash, validUntil:prepared.validUntil, notes: [], startedAt: Date.now() };
209
+ return { root: parsed.requestRoot, rid, attempt, briefHash, admission: prepared.admission, validUntil, repositoryContext: prepared.repositoryContext,
210
+ expectedWaitLine: withExpectedWait('', status, WORKER).trimStart(), notes: [], startedAt: Date.now() };
143
211
  }
144
212
  throw new Refusal(`no usable assignment after ${MAX_ATTEMPTS} attempts for ${parsed.requestRoot}`);
145
213
  }
146
214
 
147
- async function resultText(row) {
215
+ async function resultText(row, s) {
148
216
  const r = row.report;
217
+ if (r?.outcome === 'refused_by_provider') return `[worker outcome: refused_by_provider]\n${r.result ?? r.summary ?? ''}`;
149
218
  let text = (r?.result || r?.summary || '').trim() || '(the worker finished without a result)';
150
219
  if (r && r.outcome !== 'completed') text = `[worker outcome: ${r.outcome}]\n${text}`;
151
220
  if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) return `${text}\n\n${decideHint(row.request_id)}`;
152
221
  const art = r?.workspace_evidence?.patch_artifact;
153
222
  const patch = art?.artifact_id && art.size ? await adminArtifact(P.socket, art.artifact_id, tokenFor(row.request_id)) : null;
154
223
  const proseCheck = await runBuildProseCheck(row.assignment?.inputs?.[0]?.github_repo, patch);
155
- return buildResultText(row, text, patch, proseCheck);
224
+ return materializeBuildResult(row, text, patch, proseCheck, {cwd:s.cwd,
225
+ getCurrent:()=>call('/get?id='+encodeURIComponent(row.request_id)+'&peek=1',row.request_id)});
156
226
  }
157
227
 
158
228
  // ---------------------------------------------------------------- patch observations
@@ -183,29 +253,132 @@ function publishPending(s, ctl) {
183
253
  s.pending = ctl.pending;
184
254
  saveSession(s);
185
255
  }
186
- async function runTurn(s, ctl, text, say) {
256
+
257
+ function storedRepositoryContext(assignment) {
258
+ const input = assignment?.inputs?.[0];
259
+ if (!input) return 'No repository input was submitted. The worker sees only the local material included in the brief.';
260
+ return `Repository input: ${input.github_repo} at pinned commit ${input.head_sha ?? input.base_sha}. The worker can see local changes included in the brief. Other local work is unseen.`;
261
+ }
262
+
263
+ function admissionText(admission, attached) {
264
+ const {start, status, execution, ahead, latency, worker_state, until, until_source, duration_ms, track_record, submission_warnings} = admission ?? {};
265
+ const count = value => Number.isSafeInteger(value) && value >= 0;
266
+ const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
267
+ const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
268
+ const window = days => count(days) ? `, ${days} days` : '';
269
+ const line = [start === 'now' ? 'starts now' : start === 'queued' ? 'queued' :
270
+ ['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
271
+ if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
272
+ if (count(ahead?.count)) {
273
+ const age = count(ahead.oldest_age_ms) ? ` (oldest ${duration(ahead.oldest_age_ms)})` : '';
274
+ line.push(`${ahead.count} ${ahead.count === 1 ? 'job' : 'jobs'} ahead${age}`);
275
+ }
276
+ for (const [label, sample] of [['claimed', latency?.claimed], ['observed start', latency?.started]]) {
277
+ if (!count(sample?.n)) continue;
278
+ const basis = `n ${sample.n}${window(latency.window_days)}`;
279
+ if (sample.insufficient_history) line.push(`${label}: not enough history (${basis})`);
280
+ else if (count(sample.p50_ms) && count(sample.p90_ms)) line.push(`${label} p50 ${duration(sample.p50_ms)}, p90 ${duration(sample.p90_ms)} (${basis})`);
281
+ }
282
+ const censored = counts(latency?.censored, ['expired_unclaimed', 'cancelled_unclaimed', 'claimed_not_started', 'finished_unobserved_start']);
283
+ if (censored.length) line.push(`censored: ${censored.join(', ')}`);
284
+ if (worker_state === 'break') {
285
+ const end = until_source === 'owner_reported' && typeof until === 'string' && Number.isFinite(Date.parse(until)) ? `estimated end ${until} (owner-reported)` : 'end unknown';
286
+ line.push(`worker break ${end}${count(duration_ms) ? ` (${duration(duration_ms)} elapsed)` : ''}`);
287
+ } else if (['live', 'paused', 'no_live_subscription'].includes(worker_state)) {
288
+ line.push(`worker ${worker_state.replaceAll('_', ' ')}`);
289
+ }
290
+ if (count(track_record?.n)) {
291
+ const kind = typeof track_record.kind === 'string' ? ` for ${track_record.kind}` : '';
292
+ const basis = `n ${track_record.n}${window(track_record.window_days)}`;
293
+ const outcomes = counts({ ...track_record.outcomes,
294
+ accepted: track_record.accepted ?? track_record.outcomes?.accepted,
295
+ check_passed: track_record.check_passed ?? track_record.outcomes?.check_passed,
296
+ }, ['accepted', 'check_passed', 'landed', 'checks_failed', 'refused_by_provider', 'unable_to_run', 'owner_cancelled', 'finished_unchecked']);
297
+ line.push(`track record${kind} (${basis})${outcomes.length ? `: ${outcomes.join(', ')}` : ''}`);
298
+ }
299
+ const timing = admission?.claim_to_report ?? track_record?.claim_to_report;
300
+ if (count(timing?.n)) {
301
+ const basis = timing.source === 'final_claim_to_report' ? `claim to report, n ${timing.n}` : `n ${timing.n}`;
302
+ if (count(timing.p50_ms)) line.push(`claim-to-report duration ~${duration(timing.p50_ms)} (${basis})`);
303
+ else if (timing.p50_ms === null) line.push(`claim-to-report duration: not enough history (${basis})`);
304
+ }
305
+ const session = admission?.session_length ?? track_record?.session_length;
306
+ if (session?.source === 'worker_reported_sessions') {
307
+ if (count(session.p50_ms)) line.push(`typical session ~${duration(session.p50_ms)} (worker reported, n ${session.n}${window(session.window_days)})`);
308
+ else line.push(`typical session: not enough history (worker reported, n ${count(session.n) ? session.n : 0})`);
309
+ }
310
+ const warnings = Array.isArray(submission_warnings) ? submission_warnings.filter(value => typeof value === 'string') : [];
311
+ return [`${line.join('; ')}.`, ...warnings.map(warning => `Submission warning: ${warning}`)].join('\n');
312
+ }
313
+
314
+ async function runTurn(s, ctl, text, say, client) {
187
315
  const incoming = parsePrompt(text);
188
316
  let parsed = incoming;
189
317
  const notes = ctl.pending?.notes ?? [];
190
318
  if (ctl.pending) {
191
- const row = await readRowOrThrow(ctl.pending.rid);
192
- parsed = { brief: withoutNote(row.assignment.brief), requestRoot: ctl.pending.root };
319
+ const row = ctl.pending.submission_pending ? await readRow(ctl.pending.rid, undefined, true) : await readRowOrThrow(ctl.pending.rid, undefined, true);
320
+ if (!row) {
321
+ const { rid, validUntil } = ctl.pending;
322
+ if (Date.parse(validUntil ?? '') <= Date.now()) {
323
+ // The authoritative lookup still found no row after its admission window.
324
+ // Clear the stale intent, but never reinterpret a continuation as new work.
325
+ ctl.pending = null;
326
+ publishPending(s, ctl);
327
+ throw new Refusal(`submission ${rid} did not appear before its admission window ended; no new work was submitted`);
328
+ }
329
+ throw new Refusal(`submission ${rid} is not yet confirmed; retained its identity and did not submit again`);
330
+ }
331
+ if (ctl.pending.submission_pending) {
332
+ const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
333
+ if (storedHash !== ctl.pending.briefHash) throw new Refusal(`request ${ctl.pending.rid} resolved to a different brief`);
334
+ delete ctl.pending.submission_pending;
335
+ }
336
+ ctl.pending.admission = attachedAdmission(row);
337
+ ctl.pending.repositoryContext ??= storedRepositoryContext(row.assignment);
338
+ parsed = { brief: withoutNote(row.assignment.brief), priority: ctl.pending.priority ?? 'normal', requirements: ctl.pending.requirements ?? [], requestRoot: ctl.pending.root };
193
339
  }
194
340
  for (let expiries = 0; ; expiries++) {
341
+ const attached = !!ctl.pending;
195
342
  if (ctl.pending) {
196
343
  // Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
197
344
  const steerText = text.trim();
198
345
  if (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));
199
- await say('agent_thought_chunk', `re-attached to ${ctl.pending.rid}\n`);
200
346
  } else {
201
- ctl.pending = await acquire(s, parsed);
347
+ // An explicit withdrawal may still have landed despite a failed submit reply; clean up only that scoped request.
348
+ try { ctl.pending = await acquire(s, parsed, ctl); }
349
+ catch (e) { if (ctl.cancelled && ctl.withdrawWork && ctl.pending) await cancelPending(s, ctl); throw e; }
202
350
  ctl.pending.notes = notes;
203
- await say('agent_thought_chunk', `worker assignment ${ctl.pending.rid}\n`);
351
+ if (ctl.cancelled) {
352
+ if (ctl.withdrawWork) {
353
+ ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl));
354
+ }
355
+ return { cancelled: true };
356
+ }
204
357
  }
358
+ ctl.pending.priority ??= parsed.priority;
359
+ ctl.pending.requirements ??= parsed.requirements;
360
+ ctl.pending.work_id ??= ctl.pending.rid;
361
+ if (!Object.hasOwn(ctl.pending, 'original_host_task_id')) ctl.pending.original_host_task_id = ctl.hostTaskId;
362
+ ctl.pending.original_prompt_request_id ??= ctl.promptRequestId;
363
+ ctl.pending.later_prompt_request_ids ??= [];
364
+ if (ctl.promptRequestId !== ctl.pending.original_prompt_request_id && !ctl.pending.later_prompt_request_ids.includes(ctl.promptRequestId)) ctl.pending.later_prompt_request_ids.push(ctl.promptRequestId);
365
+ ctl.pending.later_host_task_ids ??= [];
366
+ if (ctl.hostTaskId && ctl.hostTaskId !== ctl.pending.original_host_task_id && !ctl.pending.later_host_task_ids.includes(ctl.hostTaskId)) ctl.pending.later_host_task_ids.push(ctl.hostTaskId);
205
367
  publishPending(s, ctl);
206
- // A cancel that arrived while acquire was submitting found nothing to cancel; cancel the job it created now.
207
- if (ctl.cancelled) { ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl)); return { cancelled: true }; }
208
- const outcome = await waitLoop(s, ctl, say);
368
+ const admission = ctl.pending.admission;
369
+ const line = admissionText(admission, attached);
370
+ const contextLine = ctl.pending.repositoryContext ? `\n${ctl.pending.repositoryContext}` : '';
371
+ const waitLine = !attached && ctl.pending.expectedWaitLine && !['break', 'no_live_subscription'].includes(admission?.worker_state)
372
+ ? `\n${ctl.pending.expectedWaitLine}` : '';
373
+ await say('agent_message_chunk', `Work ${ctl.pending.rid}${attached ? ': re-attached' : ''}. Admission: ${line}${contextLine}${waitLine}\n\n`);
374
+ for (const [type, message] of ctl.observations.splice(0)) await say(type, message);
375
+ // A local interruption leaves the submitted work running. Only a scoped withdrawal changes its authority.
376
+ if (ctl.cancelled) {
377
+ if (ctl.withdrawWork) ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl));
378
+ return { cancelled: true };
379
+ }
380
+ if (ctl.pending.terminal) return {text:ctl.pending.terminal.text};
381
+ const outcome = await waitLoop(s, ctl, say, client);
209
382
  if (outcome.expired) {
210
383
  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'});
211
384
  await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
@@ -217,47 +390,122 @@ async function runTurn(s, ctl, text, say) {
217
390
  }
218
391
  }
219
392
 
220
- async function heartbeat(s, ctl, say, note = '') {
221
- let state = '';
393
+ // Reports the job's state to the requester. Returns the bridge's owner-states reply, or null when the bridge did not answer.
394
+ async function heartbeat(s, ctl, say, note = '', signal = ctl.abort.signal) {
395
+ let state = '', reply = null;
222
396
  try {
223
- const r = await call('/owner-states', null, { method: 'POST', payload: { items: [{ id: ctl.pending.rid, capability: tokenFor(ctl.pending.rid) }] } });
224
- state = r.states?.[0]?.status ?? 'unknown';
225
- } catch { state = 'bridge unreachable'; }
397
+ reply = await call('/owner-states', null, { method: 'POST', payload: { items: [{ id: ctl.pending.rid, capability: tokenFor(ctl.pending.rid) }] }, signal });
398
+ state = reply.states?.[0]?.status ?? 'unknown';
399
+ } catch (e) {
400
+ state = Number.isInteger(e.http_status) ? `status unavailable (HTTP ${e.http_status})` : 'bridge unreachable';
401
+ }
226
402
  const age = Math.round((Date.now() - ctl.pending.startedAt) / 1000);
227
403
  await say('agent_thought_chunk', `worker ${state}, ${age < 120 ? `${age} s` : `${Math.round(age / 60)} min`}${note}\n`);
404
+ return reply;
228
405
  }
229
406
 
230
- // Block until the assignment ends. Returns {text}, {blocked,text}, {cancelled} or {expired}; throws on a hard failure.
231
- async function waitLoop(s, ctl, say) {
407
+ // Block until the assignment ends. Returns {text}, {cancelled} or {expired}; throws on a hard failure.
408
+ async function waitLoop(s, ctl, say, client) {
232
409
  const slice = Math.max(1, Math.ceil(HEARTBEAT_MS / 1000));
233
410
  let outageSince = null;
411
+ let reportedWaiterConflict = false;
412
+ let queuedSince = null;
413
+ let breakActive = false;
234
414
  for (;;) {
235
415
  if (ctl.cancelled) return { cancelled: true };
236
- let r;
416
+ const signal = ctl.abort.signal;
417
+ let r, row, waiting = true;
237
418
  try {
238
- r = await call(`/wait?id=${encodeURIComponent(ctl.pending.rid)}&timeout=${slice}&peek=1`, ctl.pending.rid, { signal: ctl.abort.signal });
419
+ r = await call(`/wait?id=${encodeURIComponent(ctl.pending.rid)}&timeout=${slice}&peek=1`, ctl.pending.rid, { signal });
420
+ waiting = false;
421
+ if (ctl.cancelled) return { cancelled: true };
422
+ if (r.status !== 'progress' && r.status !== 'ack_message') {
423
+ row = await readRowOrThrow(ctl.pending.rid, signal);
424
+ }
425
+ // A successful /wait alone is not recovery if its follow-up read still fails.
239
426
  outageSince = null;
427
+ reportedWaiterConflict = false;
240
428
  } catch (e) {
241
429
  if (ctl.cancelled) return { cancelled: true };
242
- if (e.http_status === 409) { await sleep(1000, ctl.abort.signal); continue; } // our previous process's waiter has not detached yet
430
+ if (waiting && e.http_status === 409) {
431
+ outageSince ??= Date.now();
432
+ if (Date.now() - outageSince > OUTAGE_MS) throw refuse('worker bridge unreachable: previous waiter still attached',{failure_type:'transport_error',failure_type_source:'dot_acp_transport'});
433
+ if (!reportedWaiterConflict) {
434
+ reportedWaiterConflict = true;
435
+ await say('agent_thought_chunk', 'previous waiter still attached; retrying\n');
436
+ }
437
+ await sleep(1000, signal);
438
+ continue;
439
+ }
440
+ if (e instanceof acp.RequestError || e instanceof Refusal) throw e;
243
441
  if (!transient(e)) throw refuse(`worker bridge error: ${e.message}`,{failure_type:'adapter_error',failure_type_source:'dot_acp_bridge_response'});
244
442
  outageSince ??= Date.now();
245
443
  if (Date.now() - outageSince > OUTAGE_MS) throw refuse(`worker bridge unreachable for ${Math.round(OUTAGE_MS / 60000)} min: ${e.message}`,{failure_type:'transport_error',failure_type_source:'dot_acp_transport'});
246
444
  await say('agent_thought_chunk', `bridge unreachable (${e.message}); retrying\n`);
247
- await sleep(Math.min(2000, HEARTBEAT_MS), ctl.abort.signal);
445
+ await sleep(Math.min(2000, HEARTBEAT_MS), signal);
446
+ continue;
447
+ }
448
+ if (ctl.cancelled) return { cancelled: true };
449
+ if (r.status === 'progress' || r.status === 'ack_message') { await say('agent_message_chunk', `${r.note ?? r.message?.text ?? r.text ?? r.status}\n\n`); continue; }
450
+ await relayProgress(s, ctl, say, row);
451
+ if (ctl.cancelled) return { cancelled: true };
452
+ if (['finished', 'cancelled'].includes(row.status)) r = {status:row.status};
453
+ if (r.status === 'worker_break') {
454
+ breakActive = true;
455
+ queuedSince = null;
456
+ await say('agent_message_chunk', `Work ${ctl.pending.rid}: worker usage break: ${r.notice ?? ''}; expected end: ${r.until ?? r.expected_end ?? 'unknown'}. The child turn remains held.\n\n`);
457
+ await sleep(HEARTBEAT_MS, signal);
458
+ continue;
459
+ }
460
+ if (r.status === 'timeout') {
461
+ const timeoutAt = Date.now();
462
+ const status = await heartbeat(s, ctl, say, '', signal);
463
+ if (ctl.cancelled) return { cancelled: true };
464
+ // Refill reports the default worker's break. A missing reply cannot clear a known break.
465
+ const confirmedBreak = status?.refill?.worker_break;
466
+ if ((row.target_worker === 'dot' || (breakActive && !row.target_worker)) && typeof confirmedBreak === 'boolean') {
467
+ if (confirmedBreak && !breakActive) {
468
+ await say('agent_message_chunk', `Work ${ctl.pending.rid}: worker usage break; expected end: unknown. The child turn remains held.\n\n`);
469
+ }
470
+ breakActive = confirmedBreak;
471
+ }
472
+ if (breakActive || row.status !== 'queued') queuedSince = null;
473
+ else {
474
+ queuedSince ??= timeoutAt;
475
+ if (Date.now() - queuedSince >= QUEUE_WAIT_MS) {
476
+ return { resumable: true, text: `The worker has not picked up this request yet. Request ${ctl.pending.rid} stays queued. Continue this conversation to check again.` };
477
+ }
478
+ }
479
+ continue;
480
+ }
481
+ queuedSince = null;
482
+ if (r.status === 'question' || r.status === 'blocker') {
483
+ // A question never ends the child turn: the job is still open, so report the failure once and try again next round.
484
+ try { await handleQuestions(s, ctl, say, client, r); }
485
+ catch (error) {
486
+ if (ctl.cancelled) return { cancelled: true };
487
+ if (error instanceof acp.RequestError) throw error;
488
+ const message = String(error?.message ?? error);
489
+ if (ctl.lastQuestionError !== message) {
490
+ ctl.lastQuestionError = message;
491
+ await say('agent_message_chunk', `Work ${ctl.pending.rid}: a worker question could not be handled: ${message} (child turn held; trying again).\n\n`);
492
+ }
493
+ }
494
+ await sleep(Math.min(1000, HEARTBEAT_MS), signal);
248
495
  continue;
249
496
  }
250
- if (r.status === 'timeout') { await heartbeat(s, ctl, say); continue; }
251
- if (r.status === 'worker_break') { await say('agent_thought_chunk', `worker usage break: ${r.notice ?? ''}\n`); continue; }
252
- if (r.status === 'blocker' || r.status === 'question') return { blocked: true, text: `[worker ${r.status}] ${r.blocker_text ?? ''}`.trim() };
253
497
  if (r.status === 'finished') {
254
- const row = await readRowOrThrow(ctl.pending.rid), text = await resultText(row);
498
+ const text = await resultText(row, s);
499
+ if (ctl.cancelled) return { cancelled: true };
255
500
  trackBuild(s, row);
501
+ const terminal = row.delivery?.findLast(e => ['result','t3','wait'].includes(e.kind) && !e.terminal_reason?.includes('question'));
502
+ ctl.pending.terminal_event_id = terminal?.id ?? row.report?.receipt_id ?? null;
503
+ ctl.pending.terminal = { text, report_receipt_id: row.report?.receipt_id ?? null };
504
+ publishPending(s, ctl);
256
505
  return { text };
257
506
  }
258
507
  if (r.status === 'cancelled') {
259
508
  if (ctl.cancelled) return { cancelled: true };
260
- const row = await readRowOrThrow(ctl.pending.rid);
261
509
  if (row.cancelled_reason === 'expired') return { expired: true };
262
510
  const rid = ctl.pending.rid;
263
511
  ctl.pending = null;
@@ -267,8 +515,90 @@ async function waitLoop(s, ctl, say) {
267
515
  throw refuse(`unexpected wait status ${r.status}`,{failure_type:'adapter_error',failure_type_source:'dot_acp_adapter'});
268
516
  }
269
517
  }
270
- async function readRowOrThrow(rid) {
271
- const row = await readRow(rid);
518
+ // Progress stays on this child transcript. The cursor survives adapter restarts.
519
+ async function relayProgress(s, ctl, say, row) {
520
+ const progress = row.progress ?? [];
521
+ for (const event of progress.slice(ctl.pending.progress_count ?? 0)) await say('agent_message_chunk', `${event.note}\n\n`);
522
+ ctl.pending.progress_count = progress.length;
523
+ publishPending(s, ctl);
524
+ }
525
+ async function handleQuestions(s, ctl, say, client, notice) {
526
+ const rid = ctl.pending.rid, receiptsDir = path.join(P.stateDir,'answers');
527
+ const listQuestions = async () => (await call(`/questions?id=${encodeURIComponent(rid)}`, rid)).questions ?? [];
528
+ // Read the question again before each step: the parent may take minutes, and meanwhile the job can finish, be claimed
529
+ // again, or get the answer elsewhere. Only an open question of an open job under the current claim is live.
530
+ const live = async questionId => {
531
+ const q = (await listQuestions()).find(item => item.question_id === questionId), row = await readRowOrThrow(rid);
532
+ if (!q || ['finished','cancelled'].includes(row.status) || q.answered_at || q.answer != null) return null;
533
+ const claim = row.claim, expires = Date.parse(claim?.lease_expires_at);
534
+ if (!claim || claim.state !== 'active' || !Number.isFinite(expires) || expires <= Date.now() ||
535
+ q.epoch !== claim.epoch || q.claim_id !== claim.claim_id) return null;
536
+ return q;
537
+ };
538
+ const questions = await listQuestions();
539
+ if (ctl.cancelled) return;
540
+ for (const listed of questions) {
541
+ const q = await live(listed.question_id);
542
+ if (ctl.cancelled) return;
543
+ if (!q) continue;
544
+ const purpose = q.purpose ?? 'clarification';
545
+ const expectedRespondent = purpose === 'clarification' ? 'parent_agent' : 'human_owner';
546
+ const identity = {work_id:rid, question_id:q.question_id, purpose, expected_respondent:expectedRespondent};
547
+ if (expectedRespondent === 'human_owner') {
548
+ if (!ctl.humanNotices?.has(q.question_id)) {
549
+ (ctl.humanNotices ??= new Set()).add(q.question_id);
550
+ await say('agent_message_chunk', `${JSON.stringify(identity)}: ${q.text}. This question requires the human owner; it cannot be answered by the parent agent.\n\n`);
551
+ }
552
+ continue;
553
+ }
554
+ // An answer saved before a restart is sent again as saved; the parent is not asked a second time.
555
+ const saved = readJournal(journalPath(receiptsDir, rid, q.question_id), rid, q.question_id);
556
+ let text = saved && saved.state !== 'committed' ? saved.text : null;
557
+ if (text === null) {
558
+ if (saved || ctl.askedQuestions?.has(q.question_id)) continue;
559
+ let response;
560
+ try {
561
+ response = await client.request(acp.methods.client.elicitation.create, {
562
+ sessionId:s.id, mode:'form', message:`${JSON.stringify(identity)}\n${q.text}`,
563
+ requestedSchema:{type:'object', properties:{answer:{type:'string', title:q.question_id, description:q.text}}, required:['answer']},
564
+ });
565
+ } catch (error) {
566
+ if (ctl.cancelled) return;
567
+ if (!Number.isInteger(error?.code)) throw error;
568
+ (ctl.askedQuestions ??= new Set()).add(q.question_id);
569
+ const why = error?.code === -32601 ? 'this client cannot ask question' : `asking failed (${String(error?.message ?? error).slice(0,120)}) for question`;
570
+ await say('agent_message_chunk', `Work ${rid}: ${why} ${q.question_id}. The question is still open. To answer it: dot-worker answer ${rid} ${q.question_id} TEXT\n\n`);
571
+ continue;
572
+ }
573
+ if (ctl.cancelled) return;
574
+ (ctl.askedQuestions ??= new Set()).add(q.question_id);
575
+ if (response.action !== 'accept') {
576
+ await say('agent_message_chunk', `Work ${rid}: you declined to answer question ${q.question_id}. The question is still open and the job waits for an answer (child turn held).\n\n`);
577
+ continue;
578
+ }
579
+ const stillOpen = await live(q.question_id);
580
+ if (ctl.cancelled) return;
581
+ if (!stillOpen) {
582
+ await say('agent_message_chunk', `Work ${rid}: question ${q.question_id} was answered or closed while you decided, so your answer was not sent.\n\n`);
583
+ continue;
584
+ }
585
+ text = response.content?.answer;
586
+ }
587
+ await answerThroughJournal({receiptsDir, job:rid, questionId:q.question_id, text,
588
+ readRevision:async () => (await readRowOrThrow(rid)).protocol_revision ?? null,
589
+ post:payload => call('/answer',rid,{method:'POST',payload}),
590
+ readQuestion:async () => (await call(`/questions?id=${encodeURIComponent(rid)}`,rid)).questions.find(item => item.question_id === q.question_id)});
591
+ if (ctl.cancelled) return;
592
+ await say('agent_message_chunk', `Answer recorded for work ${rid}, question ${q.question_id}.\n\n`);
593
+ }
594
+ if (ctl.cancelled) return;
595
+ if (!questions.length && notice.blocker_text && ctl.lastBlocker !== notice.blocker_text) {
596
+ ctl.lastBlocker = notice.blocker_text;
597
+ await say('agent_message_chunk', `Work ${rid}: ${notice.blocker_text} (waiting; child turn held).\n\n`);
598
+ }
599
+ }
600
+ async function readRowOrThrow(rid, signal, admission = false) {
601
+ const row = await readRow(rid, signal, admission);
272
602
  if (!row) throw refuse(`assignment ${rid} disappeared from the bridge`,{failure_type:'adapter_error',failure_type_source:'dot_acp_bridge_response'});
273
603
  return row;
274
604
  }
@@ -283,28 +613,42 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
283
613
  }))
284
614
  // Free and instant: T3's discovery probe calls this every refresh. Never touches the bridge; params.mcpServers is ignored.
285
615
  .onRequest(acp.methods.agent.session.new, ({ params }) => {
616
+ requireResidentSessionCapacity();
286
617
  const s = { id: randomUUID(), cwd: params.cwd, model: MODEL, pending: null, ctl: null };
287
618
  sessions.set(s.id, s);
288
619
  return { sessionId: s.id, configOptions: configOptions(s.model) };
289
620
  })
290
621
  .onRequest(acp.methods.agent.session.load, ({ params }) => {
291
622
  sessionFile(params.sessionId); // validates the id
623
+ const resident = touchSession(params.sessionId);
624
+ if (resident) {
625
+ resident.loaded = true;
626
+ if (!resident.ctl) resident.cwd = params.cwd ?? resident.cwd;
627
+ return { configOptions: configOptions(resident.model) };
628
+ }
629
+ requireResidentSessionCapacity();
292
630
  const saved = readSession(params.sessionId); // a session without an assignment has no file: it restores empty
293
- sessions.set(params.sessionId, { id: params.sessionId, cwd: params.cwd ?? saved?.cwd, model: MODEL, pending: saved?.pending ?? null, builds: saved?.builds ?? [], ctl: null });
631
+ 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 });
294
632
  return { configOptions: configOptions(MODEL) };
295
633
  })
296
634
  .onRequest(acp.methods.agent.session.setConfigOption, ({ params }) => {
297
- const s = sessions.get(params.sessionId);
635
+ const s = touchSession(params.sessionId);
298
636
  if (!s) throw acp.RequestError.invalidParams(null, 'unknown session');
299
637
  // T3 lists a `default` slug beside the advertised model, so accept it as the same single model.
300
638
  if (params.configId !== 'model' || ![MODEL, 'default'].includes(params.value)) throw acp.RequestError.invalidParams(null, `only model "${MODEL}" exists`);
301
639
  return { configOptions: configOptions(MODEL) };
302
640
  })
303
- .onRequest(acp.methods.agent.session.prompt, async ({ params, client }) => {
304
- const s = sessions.get(params.sessionId);
641
+ .onRequest(acp.methods.agent.session.prompt, async ({ params, client, requestId }) => {
642
+ const s = touchSession(params.sessionId);
305
643
  if (!s) throw acp.RequestError.invalidParams(null, `unknown session ${params.sessionId}`);
306
- if (s.ctl) throw acp.RequestError.invalidRequest(null, 'prompt already active');
307
- const ctl = s.ctl = { abort: new AbortController(), cancelled: false, cancelDone: null, pending: null, generation: s.generation = (s.generation ?? 0) + 1 };
644
+ if (s.ctl) {
645
+ const rid = s.ctl.pending?.rid;
646
+ const correction = rid
647
+ ? `Submit corrected work with dalan correct ${rid} or dalan_correct with revises=${rid}.`
648
+ : 'Once the work ID is available, submit corrected work with dalan correct WORK_ID or dalan_correct with revises=WORK_ID.';
649
+ throw acp.RequestError.invalidRequest(null, `prompt already active. Steering a held ACP child is unprobed. ${correction}`);
650
+ }
651
+ const ctl = s.ctl = { abort: new AbortController(), cancelled: false, cancelDone: null, pending: null, hostTaskId: params._meta?.delegatedTaskId ?? null, promptRequestId: requestId, generation: s.generation = (s.generation ?? 0) + 1 };
308
652
  const say = (type, text) => !currentTurn(s, ctl) ? Promise.resolve() : client.notify(acp.methods.client.session.update, { sessionId: s.id, update: { sessionUpdate: type, content: { type: 'text', text } } }).catch(() => {});
309
653
  let lock;
310
654
  try {
@@ -313,19 +657,58 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
313
657
  const saved = readSession(s.id);
314
658
  ctl.pending = s.pending = saved?.pending ?? null;
315
659
  s.builds = saved?.builds ?? s.builds ?? [];
316
- await reportPresentPatches(s, say);
660
+ s.completed = saved?.completed ?? s.completed ?? [];
661
+ const text = promptText(params.prompt);
662
+ s.cancelledRid = saved?.cancelledRid ?? null;
663
+ const intent = readJsonPrivate(cancellationFile(s.id));
664
+ if (ctl.pending?.cancel_requested || (ctl.pending && intent?.rid === ctl.pending.rid)) {
665
+ const completed = await withdrawSavedCancellation(s, ctl);
666
+ if (completed?.terminal) {
667
+ await say('agent_message_chunk', completed.terminal.text + (completed.notes ?? []).map(n => `\n\nnot sent to the worker: ${n}`).join(''));
668
+ return { stopReason: 'end_turn' };
669
+ }
670
+ if (!ctl.pending || ctl.pending.cancel_requested) {
671
+ await say('agent_message_chunk', s.cancelledRid
672
+ ? `Wait for work ${s.cancelledRid} was cancelled.\n`
673
+ : 'Cancellation requested; continue to retry if it is not yet confirmed.\n');
674
+ return { stopReason: 'cancelled' };
675
+ }
676
+ }
677
+ if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
678
+ await say('agent_message_chunk', `Wait for work ${s.cancelledRid} was cancelled.\n`);
679
+ return { stopReason: 'cancelled' };
680
+ }
681
+ if (!ctl.pending && s.cancelledRid) {
682
+ s.cancelledRid = null;
683
+ saveSession(s);
684
+ }
685
+ const replay = completedReplay(s, text);
686
+ s.loaded = false;
687
+ if (!ctl.pending && replay) {
688
+ if (ctl.hostTaskId && !replay.later_host_task_ids.includes(ctl.hostTaskId)) replay.later_host_task_ids.push(ctl.hostTaskId);
689
+ if (requestId !== replay.original_prompt_request_id && !replay.later_prompt_request_ids.includes(requestId)) replay.later_prompt_request_ids.push(requestId);
690
+ saveSession(s);
691
+ // Replay what the first delivery sent, notes included.
692
+ await say('agent_message_chunk', replay.terminal.text + (replay.notes ?? []).map(n => `\n\nnot sent to the worker: ${n}`).join(''));
693
+ return { stopReason: 'end_turn' };
694
+ }
695
+ ctl.observations = [];
696
+ await reportPresentPatches(s, async (type, message) => { ctl.observations.push([type, message]); });
317
697
  if (ctl.cancelled) {
318
- await Promise.race([cancelPending(s, ctl), sleep(CANCEL_CLEANUP_MS)]);
698
+ if (ctl.withdrawWork) {
699
+ await Promise.race([cancelPending(s, ctl), sleep(CANCEL_CLEANUP_MS)]);
700
+ }
319
701
  return { stopReason: 'cancelled' };
320
702
  }
321
703
  let outcome;
322
704
  // T3 allows 10 s after session/cancel; if acquire or a notification stalls, answer anyway and let runTurn finish
323
- // in the background (its own cancelled check then cancels any job it created).
705
+ // in the background. The background operation preserves work unless a scoped withdrawal was requested.
324
706
  const cancelled = new Promise(r => ctl.abort.signal.addEventListener('abort', () => setTimeout(() => r({ cancelled: true }), CANCEL_BUDGET_MS), { once: true }));
325
- const turn = runTurn(s, ctl, promptText(params.prompt), say);
707
+ const turn = runTurn(s, ctl, text, say, client);
326
708
  turn.catch(() => {});
327
709
  try { outcome = await Promise.race([turn, cancelled]); }
328
710
  catch (e) {
711
+ for (const [type, message] of ctl.observations.splice(0)) await say(type, message);
329
712
  if (ctl.cancelled) outcome = { cancelled: true };
330
713
  else if (e instanceof Refusal) {
331
714
  const data={};
@@ -336,37 +719,143 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
336
719
  else throw refuse(`worker adapter error: ${e.message}`,{failure_type:transient(e)?'transport_error':'adapter_error',failure_type_source:'dot_acp_adapter'});
337
720
  }
338
721
  // Bounded: the 5 s fallback plus at most 2 s here stays inside T3's 10 s cancel window.
339
- if (outcome.cancelled) { await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]); return { stopReason: 'cancelled' }; }
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' }; }
723
+ if (outcome.resumable) {
724
+ // A yielded wait is not a terminal receipt. Keep the request attached for a later prompt.
725
+ publishPending(s, ctl);
726
+ await say('agent_message_chunk', outcome.text);
727
+ return { stopReason: 'end_turn' };
728
+ }
340
729
  const notes = ctl.pending.notes.map(n => `\n\nnot sent to the worker: ${n}`).join('');
341
- await say('agent_message_chunk', outcome.text + notes);
342
- if (!outcome.blocked) ctl.pending = null; // finished: the next prompt is a new request
730
+ // Record completion before sending: a crash between the two then replays the saved result once on
731
+ // CONTINUE_PROMPT, instead of finding the terminal still pending and sending it a second time.
732
+ s.completed.push(ctl.pending);
733
+ ctl.pending = null;
343
734
  publishPending(s, ctl);
735
+ await say('agent_message_chunk', outcome.text + notes);
344
736
  return { stopReason: 'end_turn' };
345
737
  } finally {
346
- if (currentTurn(s, ctl)) s.ctl = null;
738
+ if (currentTurn(s, ctl)) {
739
+ s.ctl = null;
740
+ touchSession(s.id);
741
+ }
347
742
  lock?.release();
348
743
  }
349
744
  })
350
- // Answer the pending prompt as cancelled, then cancel the assignment only if no one claimed it. A claimed assignment keeps
351
- // running and stays retrievable: the next prompt (or a relaunch with the same token) re-attaches.
745
+ // ACP cancel is a local interruption. Work withdrawal needs an explicit host control intent bound to one job ID.
352
746
  .onNotification(acp.methods.agent.session.cancel, ({ params }) => {
353
747
  const s = sessions.get(params.sessionId);
354
748
  const ctl = s?.ctl;
355
- if (!ctl || ctl.cancelled) return;
749
+ if (!s) return;
750
+ const withdrawalRid = explicitWithdrawalRid(params._meta);
751
+ if (!ctl) { if (withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
752
+ if (ctl.cancelled) return;
356
753
  ctl.cancelled = true;
357
- ctl.cancelDone = cancelPending(s, ctl);
754
+ ctl.withdrawWork = !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
755
+ ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
358
756
  ctl.abort.abort();
359
757
  });
360
758
 
759
+ function explicitWithdrawalRid(meta) {
760
+ const control = meta?.dalanControl;
761
+ if (control?.intent !== 'withdraw_work' || typeof control.scope !== 'string') return null;
762
+ const match = /^job:([A-Za-z0-9][A-Za-z0-9._-]{0,127})$/.exec(control.scope);
763
+ return match?.[1] ?? null;
764
+ }
765
+
766
+ function completedReplay(s, text) {
767
+ const last = s.completed.at(-1);
768
+ return s.completed.findLast(item => text.includes(item.work_id)) ??
769
+ (text.trim() === CONTINUE_PROMPT && (s.loaded || last?.preserved_on_cancel) ? last : null);
770
+ }
771
+ async function cancelYieldedSession(s, rid) {
772
+ const ctl = s.ctl = { cancelled: true, pending: null, generation: s.generation = (s.generation ?? 0) + 1 };
773
+ // Keep the intent bound to the job the user cancelled, not whichever job next owns this session.
774
+ let lock;
775
+ try {
776
+ if (!rid || readSession(s.id)?.pending?.rid !== rid) return;
777
+ writeJsonPrivate(cancellationFile(s.id), { rid });
778
+ lock = await lockSession(s.id, CANCEL_BUDGET_MS);
779
+ const saved = readSession(s.id);
780
+ if (saved?.pending?.rid !== rid) {
781
+ if (readJsonPrivate(cancellationFile(s.id))?.rid === rid) fs.rmSync(cancellationFile(s.id), { force: true });
782
+ log('Stop target changed before lock acquisition; later work was not cancelled.');
783
+ return;
784
+ }
785
+ ctl.pending = s.pending = saved.pending;
786
+ s.completed = saved.completed ?? [];
787
+ s.builds = saved.builds ?? [];
788
+ await withdrawSavedCancellation(s, ctl);
789
+ } catch (error) {
790
+ log(`ERROR: could not withdraw paused work; will retry before continuing: ${error.message}`);
791
+ } finally {
792
+ if (currentTurn(s, ctl)) s.ctl = null;
793
+ lock?.release();
794
+ }
795
+ }
796
+
797
+ async function withdrawSavedCancellation(s, ctl) {
798
+ ctl.pending.cancel_requested = true;
799
+ publishPending(s, ctl);
800
+ const rid = ctl.pending.rid;
801
+ const completed = await cancelPending(s, ctl);
802
+ if (!ctl.pending && (s.cancelledRid === rid || completed?.rid === rid) && readJsonPrivate(cancellationFile(s.id))?.rid === rid) {
803
+ fs.rmSync(cancellationFile(s.id), { force: true });
804
+ }
805
+ return completed;
806
+ }
807
+
361
808
  async function cancelPending(s, ctl) {
362
809
  const pending = ctl.pending;
363
810
  if (!pending) return;
364
811
  try {
365
- const r = await Promise.race([call('/cancel-if-queued', pending.rid, { method: 'POST', payload: { id: pending.rid } }), sleep(CANCEL_BUDGET_MS).then(() => null)]);
366
- // Cancelled here or already (another session on the same token, or the operator): nothing is left to re-attach to.
367
- if ((r?.cancelled || r?.status === 'cancelled') && ctl.pending === pending) { ctl.pending = null; publishPending(s, ctl); log(`cancelled queued ${pending.rid}`); }
368
- else log(`cancel left ${pending.rid} ${r?.status ?? 'unknown'}`);
369
- } catch (e) { log(`cancel-if-queued failed for ${pending.rid}: ${e.message}`); }
812
+ if (currentTurn(s, ctl)) {
813
+ pending.cancel_requested = true;
814
+ publishPending(s, ctl);
815
+ writeJsonPrivate(cancellationFile(s.id), { rid: pending.rid });
816
+ }
817
+ const clearIntent = () => {
818
+ if (currentTurn(s, ctl) && readJsonPrivate(cancellationFile(s.id))?.rid === pending.rid) {
819
+ fs.rmSync(cancellationFile(s.id), { force: true });
820
+ }
821
+ };
822
+ ctl.cancelledWorkId = pending.rid;
823
+ const row = await readRowOrThrow(pending.rid);
824
+ // A worker may have already finished. Cancel the wait, not its result.
825
+ if (row.status === 'finished') {
826
+ const text = pending.terminal?.text ?? await resultText(row, s);
827
+ if (ctl.pending !== pending) return;
828
+ trackBuild(s, row);
829
+ const terminal = row.delivery?.findLast(e => ['result','t3','wait'].includes(e.kind) && !e.terminal_reason?.includes('question'));
830
+ const completed = {...pending,work_id:pending.work_id ?? pending.rid,preserved_on_cancel:true,
831
+ terminal_event_id:terminal?.id ?? row.report?.receipt_id ?? null,
832
+ terminal:{text,report_receipt_id:row.report?.receipt_id ?? null}};
833
+ s.completed ??= [];
834
+ if (!s.completed.some(item => item.rid === completed.rid)) s.completed.push(completed);
835
+ s.cancelledRid = null; ctl.pending = null; publishPending(s, ctl);
836
+ clearIntent();
837
+ return completed;
838
+ }
839
+ // 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
+ if (pending.cancel_requested && row.status === 'cancelled') {
845
+ s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl);
846
+ clearIntent();
847
+ return;
848
+ }
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)]);
850
+ ctl.computeStopped = r?.compute_stopped === true ? true : r?.compute_stopped === false ? false : null;
851
+ 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
+ if (r?.status === 'cancelled' && ctl.pending === pending) {
853
+ s.cancelledRid = pending.rid;
854
+ ctl.pending = null;
855
+ publishPending(s, ctl);
856
+ clearIntent();
857
+ }
858
+ } catch (e) { ctl.workerState = 'still_running'; log(`cancel failed for ${pending.rid}: ${e.message}`); }
370
859
  }
371
860
 
372
861
  // T3 closing our stdin means it is done with this session. Exit without cancelling anything: queued rows expire by
@@ -374,4 +863,11 @@ async function cancelPending(s, ctl) {
374
863
  process.stdin.on('end', () => process.exit(0));
375
864
  process.stdin.on('close', () => process.exit(0));
376
865
  agent.connect(acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
866
+ const buildExecutionSetting = process.env.DALAN_ACP_BUILD_EXECUTION || process.env.DOT_ACP_BUILD_EXECUTION || '';
867
+ // The adapter can request host execution without knowing whether the bridge can run this build's checks.
868
+ if (buildExecutionSetting === 'host') {
869
+ log('builds: host mode is configured; bridge check availability is determined per build. A build can still be refused or left unchecked.');
870
+ } else {
871
+ log(`builds: DALAN_ACP_BUILD_EXECUTION is ${buildExecutionSetting ? `${JSON.stringify(buildExecutionSetting.slice(0, 20))}, not host` : 'unset'}, so delegated builds may run without the bridge's checks; set it to host where the bridge runs host checks (docs/t3-integration.md)`);
872
+ }
377
873
  log('ready');