@tnunamak/dalan 0.8.5 → 0.9.0
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 +9 -0
- package/bin/dot-acp-agent.mjs +197 -43
- package/bin/dot-worker.mjs +75 -11
- package/docs/design/target-architecture-v2.md +1 -0
- package/docs/t3-integration.md +6 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +20 -2
- package/package.json +1 -1
- package/src/acp-bridge.mjs +80 -15
- package/src/host-execution-policy.mjs +1 -1
- package/src/inbox.mjs +44 -2
- package/src/patch-apply.mjs +125 -42
- package/src/server.mjs +196 -46
- package/src/store.mjs +371 -68
- package/src/submission-policy.mjs +59 -8
- package/src/tool-registry.mjs +6 -0
- package/src/workspace.mjs +92 -5
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,15 @@ This file lists user-visible changes, newest first. Check the section for your t
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.9.0
|
|
8
|
+
|
|
9
|
+
- **Before upgrading, keep a verified backup and the previous installation.** The bridge still uses schema 75 and adds records for native withdrawal, lane reservations and worker-scoped breaks. Before rolling back, verify the old package can use the retained state. Keep newer reports, receipts, artifacts and delivery acknowledgments.
|
|
10
|
+
- **Native cancellation survives the requester exiting.** Unclaimed work is withdrawn. The caller sees whether the requester stopped and what the bridge knows about the worker. An explicit correction creates a linked revision and keeps the original repository restrictions.
|
|
11
|
+
- **Admission shows eligible work ahead of you.** It says work can start immediately only when a current worker subscription has a lane reserved for that request. Admission and dispatch respect a confirmed break for the affected worker, and a worker's own refusal text remains visible.
|
|
12
|
+
- **Reconnect to paused or interrupted work.** The native adapter restores the existing work handle and approved file list. The recovery inbox uses passive reads. When it can read some pages, it returns their results and flags any unread pages. When every attempted page fails, it reports the bridge error or unavailability.
|
|
13
|
+
- **Review an exact revision and file set.** Native repository reviews can name a pushed revision and approved files. Wide read-only scopes can be paged without passing excluded files or granting host execution. Download manifests confirm completeness for an exact file list when every requested file was included.
|
|
14
|
+
- **Use verified publication and check results.** Successful publication names the draft, its branch and verified commit. If a remote write may have occurred but verification is incomplete, the reply gives the known remote state and retains the patch. Worker-reported checks are labeled separately from bridge checks.
|
|
15
|
+
|
|
7
16
|
## 0.8.5 (2026-12-03)
|
|
8
17
|
|
|
9
18
|
- 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.
|
package/bin/dot-acp-agent.mjs
CHANGED
|
@@ -14,7 +14,7 @@ import { createRefuse, cancelBudgetMs, CANCEL_CLEANUP_MS } from '../integrations
|
|
|
14
14
|
import { detectPresentPatches } from '../src/patch-apply.mjs';
|
|
15
15
|
import {
|
|
16
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,
|
|
17
|
+
prepareAssignmentWithContext, explicitReadIntent, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, materializeBuildResult, decideHint, runBuildProseCheck, adminArtifact, withExpectedWait, workerRunEvidenceLines,
|
|
18
18
|
} from '../src/acp-bridge.mjs';
|
|
19
19
|
|
|
20
20
|
const num = (name, fallback) => { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; };
|
|
@@ -77,7 +77,7 @@ const sessionFile = id => {
|
|
|
77
77
|
// Keep active work and terminal receipts; probes and idle sessions leave nothing behind.
|
|
78
78
|
function saveSession(s) {
|
|
79
79
|
if (!s.pending && !s.completed?.length && !s.builds?.length && !s.cancelledRid) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
|
|
80
|
-
writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, cancelledRid: s.cancelledRid ?? null, cancelledAt:s.cancelledAt ?? null, cancelledByGrace:s.cancelledByGrace === true, 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, finishedAfterCancel:s.finishedAfterCancel===true, builds: s.builds ?? [], completed: s.completed ?? [] });
|
|
81
81
|
}
|
|
82
82
|
const readSession = id => readJsonPrivate(sessionFile(id));
|
|
83
83
|
// Independent of the session lock: never overwrite another process's live session record.
|
|
@@ -126,6 +126,26 @@ async function readRow(rid, signal, admission = false, matchingWorkerOnly = fals
|
|
|
126
126
|
}
|
|
127
127
|
const attachedAdmission = row => ({ status: row.status, execution: row.execution, ...(row.status === 'queued' ? row.admission : {}) });
|
|
128
128
|
|
|
129
|
+
function assertReadIntent(intent,assignment) {
|
|
130
|
+
if(!intent) return;
|
|
131
|
+
const input=assignment.inputs?.[0], paths=assignment.scope_paths;
|
|
132
|
+
const original=explicitReadIntent(withoutNote(assignment.brief));
|
|
133
|
+
if(!original||original.repo.toLowerCase()!==intent.repo.toLowerCase()||original.sha!==intent.sha||
|
|
134
|
+
original.scope.length!==intent.scope.length||!original.scope.every(file=>intent.scope.includes(file))||
|
|
135
|
+
input?.github_repo?.toLowerCase()!==intent.repo.toLowerCase()||input.base_sha!==intent.sha||input.head_sha!==intent.sha||
|
|
136
|
+
!Array.isArray(paths)||!paths.length||!Array.isArray(assignment.read_paths)||
|
|
137
|
+
assignment.read_paths.length!==paths.length||!paths.every(file=>assignment.read_paths.includes(file)&&
|
|
138
|
+
intent.scope.some(entry=>file===entry||file.startsWith(entry+'/')))) {
|
|
139
|
+
throw new Refusal('The existing work does not match the requested repository revision and read scope. Submit new work with the full task.');
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function withReadScope(context,scope,count) {
|
|
144
|
+
const accepted=Number.isSafeInteger(count)&&count>0?`${count} files. Use list_files to page through them`
|
|
145
|
+
:Array.isArray(scope)&&scope.length?JSON.stringify(scope):null;
|
|
146
|
+
return accepted===null?context:`${context.split('\nAccepted read scope: ',1)[0]}\nAccepted read scope: ${accepted}.`;
|
|
147
|
+
}
|
|
148
|
+
|
|
129
149
|
// Find the assignment for this brief, or submit one. A retried or restarted task attaches to the row it already
|
|
130
150
|
// submitted, so the worker never gets the same brief twice:
|
|
131
151
|
// no row -> check eligibility, submit
|
|
@@ -133,6 +153,7 @@ const attachedAdmission = row => ({ status: row.status, execution: row.execution
|
|
|
133
153
|
// row cancelled or expired -> next attempt id `<root>_r<n>`
|
|
134
154
|
// row queued/claimed/finished-> attach; the wait returns the result or keeps waiting
|
|
135
155
|
async function acquire(s, parsed, ctl) {
|
|
156
|
+
const readIntent=explicitReadIntent(parsed.brief);
|
|
136
157
|
// Reuse work admitted before worker-scoped anonymous identities were introduced.
|
|
137
158
|
// A legacy row belongs to this retry only when its authenticated worker matches.
|
|
138
159
|
if (!parsed.root && !ctl.correction && parsed.legacyRequestRoot !== parsed.requestRoot) {
|
|
@@ -153,22 +174,41 @@ async function acquire(s, parsed, ctl) {
|
|
|
153
174
|
if (row) {
|
|
154
175
|
const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
|
|
155
176
|
if (storedHash !== briefHash) throw new Refusal(`token ${parsed.requestRoot} was already used with a different brief`);
|
|
177
|
+
assertReadIntent(readIntent,row.assignment);
|
|
178
|
+
if (ctl.correction && row.revises?.request_id !== ctl.correction.prior.rid) throw new Refusal('the stored work does not match the requested correction');
|
|
179
|
+
if (ctl.correction && row.status === 'cancelled') throw new Refusal(`correction ${rid} was withdrawn; no new work was submitted`);
|
|
156
180
|
if (row.status === 'cancelled' && !conflictExhausted) continue;
|
|
157
181
|
if (row.status === 'cancelled') throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
|
|
158
182
|
return { root: parsed.requestRoot, rid, attempt, briefHash, admission: attachedAdmission(row),
|
|
159
|
-
|
|
183
|
+
...(row.revises?.request_id ? { revises: row.revises.request_id } : {}),
|
|
184
|
+
repositoryContext: storedRepositoryContext(row.assignment, preparedByAttempt.get(rid)?.repositoryContext),
|
|
160
185
|
validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
|
|
161
186
|
}
|
|
162
187
|
// On the last conflict still reread once: the same brief may already exist.
|
|
163
188
|
if (conflictExhausted) throw new Refusal('request conflict persisted after the submit retry budget', 'adapter_error');
|
|
164
189
|
const status = await call('/status', null);
|
|
165
|
-
const
|
|
190
|
+
const target = WORKER ?? status.default_worker ?? 'dot';
|
|
191
|
+
const workerBreak = status.by_worker?.[target]?.worker_break ?? (target==='dot'?status.worker_break:null);
|
|
192
|
+
const refusal = bridgeRefusal({...status,worker_break:workerBreak}, IN_FLIGHT_CAP+(ctl.correction?.row.status==='queued'?1:0), WORKER, parsed.priority, true);
|
|
166
193
|
if (refusal) throw new Refusal(refusal,'deferred',{failure_type_source:'bridge_status_refusal',verdict:'defer'});
|
|
167
194
|
let prepared=preparedByAttempt.get(rid);
|
|
168
195
|
if(!prepared) {
|
|
169
196
|
const validUntil = new Date(Date.now() + VALID_MS).toISOString();
|
|
170
|
-
const
|
|
197
|
+
const correction=ctl.correction;
|
|
198
|
+
const {assignment, repositoryContext} = correction
|
|
199
|
+
? {assignment:{...correction.row.assignment,request_id:rid,brief:parsed.brief,valid_until:validUntil,acp_brief_hash:briefHash},repositoryContext:correction.prior.repositoryContext}
|
|
200
|
+
: await prepareAssignmentWithContext({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
|
|
171
201
|
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 } : {}) };
|
|
202
|
+
if(correction) {
|
|
203
|
+
// The bridge derives inherited exclusions after checking the prior owner capability.
|
|
204
|
+
delete assignment.scope_excluded;
|
|
205
|
+
delete assignment.paged_read_scope;
|
|
206
|
+
if(assignment.inputs.length) assignment.read_paths=assignment.scope_paths;
|
|
207
|
+
body.revises={prior_id:correction.prior.rid,prior_token:tokenFor(correction.prior.rid),withdraw_prior:true,require_active_prior:true};
|
|
208
|
+
body.command_key=`acp-correct:${rid}`;
|
|
209
|
+
if(correction.row.execution) body.execution=correction.row.execution;
|
|
210
|
+
if(correction.row.review) body.review=true;
|
|
211
|
+
}
|
|
172
212
|
// max_queued makes admission atomic; the bridge counts only this worker's waiting callers of the same priority.
|
|
173
213
|
prepared={body,validUntil,repositoryContext}; preparedByAttempt.set(rid,prepared);
|
|
174
214
|
}
|
|
@@ -191,14 +231,22 @@ async function acquire(s, parsed, ctl) {
|
|
|
191
231
|
// A late response may arrive after bounded cancel has released the session lock.
|
|
192
232
|
ctl.abort.signal.throwIfAborted();
|
|
193
233
|
if (!currentTurn(s, ctl)) throw new Error('Cannot submit outside the active ACP turn.');
|
|
234
|
+
// All retries use the same deadline, within the bridge's pre-admission withdrawal retention.
|
|
235
|
+
body.facade_submit_until ??= Math.min(Date.parse(validUntil),Date.now()+600_000);
|
|
194
236
|
const intent = { root: parsed.requestRoot, rid, attempt, briefHash, validUntil, repositoryContext: prepared.repositoryContext,
|
|
195
237
|
priority: parsed.priority, requirements: parsed.requirements, notes: ctl.pending?.notes ?? [],
|
|
238
|
+
...(ctl.correction ? { revises:ctl.correction.prior.rid, correctionPrior:ctl.correction.prior,
|
|
239
|
+
admitUntil:body.facade_submit_until } : {}),
|
|
196
240
|
work_id: rid, original_host_task_id: ctl.hostTaskId ?? null, original_prompt_request_id: ctl.promptRequestId,
|
|
197
241
|
later_prompt_request_ids: [], later_host_task_ids: [], startedAt: Date.now(), submission_pending: true };
|
|
198
242
|
ctl.pending = intent;
|
|
199
243
|
publishPending(s, ctl);
|
|
200
244
|
// Admission belongs to the bridge; the richer forecast can replace this reply without changing ACP.
|
|
201
|
-
try {
|
|
245
|
+
try {
|
|
246
|
+
const admitted=await call('/submit',null,{method:'POST',payload:body,timeoutMs:SUBMIT_DEADLINE_MS});
|
|
247
|
+
prepared.admission=admitted.admission??{status:admitted.status??'queued',execution:admitted.execution,submission_warnings:admitted.submission_warnings};
|
|
248
|
+
prepared.repositoryContext=withReadScope(prepared.repositoryContext,admitted.repository_scope?.scope_paths,admitted.repository_scope?.file_count);
|
|
249
|
+
}
|
|
202
250
|
catch (e) {
|
|
203
251
|
if (e.message === 'request_id conflict') {
|
|
204
252
|
if (submitRetries >= SUBMIT_RETRIES) conflictExhausted = true;
|
|
@@ -222,6 +270,7 @@ async function acquire(s, parsed, ctl) {
|
|
|
222
270
|
throw e;
|
|
223
271
|
}
|
|
224
272
|
return { root: parsed.requestRoot, rid, attempt, briefHash, admission: prepared.admission, validUntil, repositoryContext: prepared.repositoryContext,
|
|
273
|
+
...(ctl.correction ? { revises:ctl.correction.prior.rid } : {}),
|
|
225
274
|
expectedWaitLine: withExpectedWait('', status, WORKER).trimStart(), notes: [], startedAt: Date.now() };
|
|
226
275
|
}
|
|
227
276
|
throw new Refusal(`no usable assignment after ${MAX_ATTEMPTS} attempts for ${parsed.requestRoot}`);
|
|
@@ -232,12 +281,15 @@ async function resultText(row, s) {
|
|
|
232
281
|
if (r?.outcome === 'refused_by_provider') return `[worker outcome: refused_by_provider]\n${r.result ?? r.summary ?? ''}`;
|
|
233
282
|
let text = (r?.result || r?.summary || '').trim() || '(the worker finished without a result)';
|
|
234
283
|
if (r && r.outcome !== 'completed') text = `[worker outcome: ${r.outcome}]\n${text}`;
|
|
235
|
-
if (!isBuild(withoutNote(row.assignment?.brief ?? '')))
|
|
284
|
+
if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) {
|
|
285
|
+
const evidence = workerRunEvidenceLines(row);
|
|
286
|
+
return [text, ...(evidence.length ? [evidence.join('\n')] : []), decideHint(row.request_id)].join('\n\n');
|
|
287
|
+
}
|
|
236
288
|
const art = r?.workspace_evidence?.patch_artifact;
|
|
237
289
|
const patch = art?.artifact_id && art.size ? await adminArtifact(P.socket, art.artifact_id, tokenFor(row.request_id)) : null;
|
|
238
290
|
const proseCheck = await runBuildProseCheck(row.assignment?.inputs?.[0]?.github_repo, patch);
|
|
239
291
|
return materializeBuildResult(row, text, patch, proseCheck, {cwd:s.cwd,
|
|
240
|
-
getCurrent:()=>call('/get?id='+encodeURIComponent(row.request_id)+'&peek=1',row.request_id)});
|
|
292
|
+
getCurrent:({signal})=>call('/get?id='+encodeURIComponent(row.request_id)+'&peek=1',row.request_id,{signal})});
|
|
241
293
|
}
|
|
242
294
|
|
|
243
295
|
// ---------------------------------------------------------------- patch observations
|
|
@@ -269,19 +321,21 @@ function publishPending(s, ctl) {
|
|
|
269
321
|
saveSession(s);
|
|
270
322
|
}
|
|
271
323
|
|
|
272
|
-
function storedRepositoryContext(assignment) {
|
|
324
|
+
function storedRepositoryContext(assignment, preparedContext) {
|
|
273
325
|
const input = assignment?.inputs?.[0];
|
|
274
|
-
if (!input) return 'No repository input was submitted. The worker sees only the local material included in the brief.';
|
|
275
|
-
|
|
326
|
+
if (!input) return preparedContext ?? 'No repository input was submitted. The worker sees only the local material included in the brief.';
|
|
327
|
+
const context = preparedContext ?? `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.`;
|
|
328
|
+
const fileCount = assignment.paged_read_scope === true ? assignment.scope_paths.length : undefined;
|
|
329
|
+
return withReadScope(context, assignment.read_paths, fileCount);
|
|
276
330
|
}
|
|
277
331
|
|
|
278
332
|
function admissionText(admission, attached) {
|
|
279
|
-
const {start, status, execution, ahead, latency, worker_state, until, until_source, duration_ms, track_record, submission_warnings} = admission ?? {};
|
|
333
|
+
const {start, status, execution, ahead, latency, worker_state, until, until_source, duration_ms, track_record, submission_warnings, reserved_until} = admission ?? {};
|
|
280
334
|
const count = value => Number.isSafeInteger(value) && value >= 0;
|
|
281
335
|
const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
|
|
282
336
|
const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
|
|
283
337
|
const window = days => count(days) ? `, ${days} days` : '';
|
|
284
|
-
const line = [start === 'now' ? 'starts now' :
|
|
338
|
+
const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'starts now' : ['queued','now'].includes(start) ? 'queued' :
|
|
285
339
|
['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
|
|
286
340
|
if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
|
|
287
341
|
if (count(ahead?.count)) {
|
|
@@ -333,39 +387,72 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
333
387
|
const incoming = { ...parsePrompt(text, { worker: WORKER }), legacyRequestRoot: parsePrompt(text).requestRoot };
|
|
334
388
|
let parsed = incoming;
|
|
335
389
|
const notes = ctl.pending?.notes ?? [];
|
|
390
|
+
const correction=/^Correct ([-\w]{8,128})\r?\n([\s\S]+)$/i.exec(incoming.brief);
|
|
391
|
+
const incomingRead=explicitReadIntent(correction?correction[2].trim():incoming.brief);
|
|
392
|
+
const correctionRoot=correction ? `acp-${sha256(JSON.stringify([WORKER,correction[1],correction[2].trim()])).slice(0,24)}` : null;
|
|
393
|
+
let correctionRetry=correction&&ctl.pending?.revises===correction[1]&&ctl.pending.root===correctionRoot;
|
|
394
|
+
if(correction&&!correctionRetry&&ctl.pending?.rid!==correction[1]) throw new Refusal('the named work is not held by this child; no correction was sent');
|
|
336
395
|
if (ctl.pending) {
|
|
337
|
-
const
|
|
396
|
+
const pending = ctl.pending;
|
|
397
|
+
// Take the deadline sample before the authoritative read. A read that
|
|
398
|
+
// started before the deadline can still miss a concurrent first admission.
|
|
399
|
+
const admissionExpired = (pending.admitUntil ?? Date.parse(pending.validUntil ?? '')) <= Date.now();
|
|
400
|
+
let row = pending.submission_pending ? await readRow(pending.rid, undefined, true) : await readRowOrThrow(pending.rid, undefined, true);
|
|
338
401
|
if (!row) {
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
402
|
+
if (!admissionExpired) throw new Refusal(`submission ${pending.rid} is not yet confirmed; retained its identity and did not submit again`);
|
|
403
|
+
const prior = pending.correctionPrior;
|
|
404
|
+
if (prior) row = await readRow(prior.rid, undefined, true);
|
|
405
|
+
if (!row || !['queued','claimed'].includes(row.status) || row.cancellation_requested) {
|
|
343
406
|
ctl.pending = null;
|
|
344
407
|
publishPending(s, ctl);
|
|
345
|
-
|
|
408
|
+
const priorLocation = prior ? ` Find the earlier work with dalan get ${prior.rid}.` : '';
|
|
409
|
+
throw new Refusal(`submission ${pending.rid} did not appear before its admission window ended; no new work was submitted.${priorLocation}`);
|
|
346
410
|
}
|
|
347
|
-
|
|
411
|
+
ctl.pending = prior;
|
|
412
|
+
correctionRetry = false;
|
|
413
|
+
publishPending(s, ctl);
|
|
414
|
+
if (!correction) await say('agent_message_chunk', `The correction was not admitted. Continuing earlier work ${prior.rid}.\n`);
|
|
348
415
|
}
|
|
416
|
+
assertReadIntent(incomingRead,row.assignment);
|
|
349
417
|
if (ctl.pending.submission_pending) {
|
|
350
418
|
const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
|
|
351
419
|
if (storedHash !== ctl.pending.briefHash) throw new Refusal(`request ${ctl.pending.rid} resolved to a different brief`);
|
|
420
|
+
if (ctl.pending.revises && row.revises?.request_id !== ctl.pending.revises) throw new Refusal('the stored work does not match the requested correction');
|
|
352
421
|
delete ctl.pending.submission_pending;
|
|
422
|
+
delete ctl.pending.correctionPrior;
|
|
423
|
+
delete ctl.pending.admitUntil;
|
|
353
424
|
}
|
|
354
425
|
ctl.pending.admission = attachedAdmission(row);
|
|
355
|
-
ctl.pending.
|
|
426
|
+
ctl.pending.revises ??= row.revises?.request_id;
|
|
427
|
+
ctl.pending.repositoryContext = storedRepositoryContext(row.assignment, ctl.pending.repositoryContext);
|
|
356
428
|
parsed = { brief: withoutNote(row.assignment.brief), priority: ctl.pending.priority ?? 'normal', requirements: ctl.pending.requirements ?? [], requestRoot: ctl.pending.root };
|
|
429
|
+
if(correction&&!correctionRetry) {
|
|
430
|
+
const rawDelta=correction[2].trim();
|
|
431
|
+
const delta=incomingRead?rawDelta.split(/\r?\n/).slice(1).join('\n').trim():rawDelta;
|
|
432
|
+
const prior=ctl.pending;
|
|
433
|
+
if(!delta)throw new Refusal('write the correction on the next line');
|
|
434
|
+
ctl.correction={prior,row};
|
|
435
|
+
parsed.brief=`${parsed.brief}\n\nRequester correction:\n${delta}`;
|
|
436
|
+
parsed.requestRoot=correctionRoot;
|
|
437
|
+
// Save the successor only when acquire has a durable submit identity to reconcile.
|
|
438
|
+
ctl.pending=null;
|
|
439
|
+
}
|
|
357
440
|
}
|
|
358
441
|
for (let expiries = 0; ; expiries++) {
|
|
359
442
|
const attached = !!ctl.pending;
|
|
360
443
|
if (ctl.pending) {
|
|
361
444
|
// Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
|
|
362
445
|
const steerText = text.trim();
|
|
363
|
-
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));
|
|
446
|
+
if (!correctionRetry && steerText && steerText !== CONTINUE_PROMPT && sha256(incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
|
|
364
447
|
} else {
|
|
365
448
|
// An explicit withdrawal may still have landed despite a failed submit reply; clean up only that scoped request.
|
|
366
449
|
try { ctl.pending = await acquire(s, parsed, ctl); }
|
|
367
|
-
catch (e) {
|
|
368
|
-
|
|
450
|
+
catch (e) {
|
|
451
|
+
if(!ctl.pending&&ctl.correction) { ctl.pending=ctl.correction.prior; publishPending(s,ctl); }
|
|
452
|
+
if (ctl.cancelled && ctl.withdrawWork && ctl.pending) await cancelPending(s, ctl);
|
|
453
|
+
throw e;
|
|
454
|
+
}
|
|
455
|
+
ctl.pending.notes = ctl.correction ? [] : notes;
|
|
369
456
|
if (ctl.cancelled) {
|
|
370
457
|
if (ctl.withdrawWork) {
|
|
371
458
|
ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl));
|
|
@@ -388,7 +475,7 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
388
475
|
const contextLine = ctl.pending.repositoryContext ? `\n${ctl.pending.repositoryContext}` : '';
|
|
389
476
|
const waitLine = !attached && ctl.pending.expectedWaitLine && !['break', 'no_live_subscription'].includes(admission?.worker_state)
|
|
390
477
|
? `\n${ctl.pending.expectedWaitLine}` : '';
|
|
391
|
-
await say('agent_message_chunk', `Work ${ctl.pending.rid}${attached ? ': re-attached' : ''}. Admission: ${line}${contextLine}${waitLine}\n\n`);
|
|
478
|
+
await say('agent_message_chunk', `Work ${ctl.pending.rid}${attached ? ': re-attached' : ''}${ctl.correction ? ` corrects ${ctl.correction.prior.rid}` : ''}. Admission: ${line}${contextLine}${waitLine}\n\n`);
|
|
392
479
|
for (const [type, message] of ctl.observations.splice(0)) await say(type, message);
|
|
393
480
|
// A local interruption leaves the submitted work running. Only a scoped withdrawal changes its authority.
|
|
394
481
|
if (ctl.cancelled) {
|
|
@@ -398,6 +485,7 @@ async function runTurn(s, ctl, text, say, client) {
|
|
|
398
485
|
if (ctl.pending.terminal) return {text:ctl.pending.terminal.text};
|
|
399
486
|
const outcome = await waitLoop(s, ctl, say, client);
|
|
400
487
|
if (outcome.expired) {
|
|
488
|
+
if(ctl.pending.revises) throw refuse(`correction ${ctl.pending.rid} expired before it was claimed`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
|
|
401
489
|
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'});
|
|
402
490
|
await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
|
|
403
491
|
ctl.pending = null;
|
|
@@ -479,9 +567,10 @@ async function waitLoop(s, ctl, say, client) {
|
|
|
479
567
|
const timeoutAt = Date.now();
|
|
480
568
|
const status = await heartbeat(s, ctl, say, '', signal);
|
|
481
569
|
if (ctl.cancelled) return { cancelled: true };
|
|
482
|
-
|
|
483
|
-
const
|
|
484
|
-
|
|
570
|
+
const ownedBreak = status?.states?.find(state=>state.request_id===ctl.pending.rid)?.worker_break;
|
|
571
|
+
const legacyBreak = (row.target_worker==='dot'||(breakActive&&!row.target_worker)) ? status?.refill?.worker_break : undefined;
|
|
572
|
+
const confirmedBreak = typeof ownedBreak==='boolean' ? ownedBreak : legacyBreak;
|
|
573
|
+
if (typeof confirmedBreak === 'boolean') {
|
|
485
574
|
if (confirmedBreak && !breakActive) {
|
|
486
575
|
await say('agent_message_chunk', `Work ${ctl.pending.rid}: worker usage break; expected end: unknown. The child turn remains held.\n\n`);
|
|
487
576
|
}
|
|
@@ -662,9 +751,9 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
662
751
|
if (s.ctl) {
|
|
663
752
|
const rid = s.ctl.pending?.rid;
|
|
664
753
|
const correction = rid
|
|
665
|
-
? `
|
|
754
|
+
? `Steer with "Correct ${rid}" on the first line and your correction on the next. You can also submit corrected work with dalan correct ${rid}.`
|
|
666
755
|
: 'Once the work ID is available, submit corrected work with dalan correct WORK_ID or dalan_correct with revises=WORK_ID.';
|
|
667
|
-
throw acp.RequestError.invalidRequest(null, `prompt already active.
|
|
756
|
+
throw acp.RequestError.invalidRequest(null, `prompt already active. ${correction}`);
|
|
668
757
|
}
|
|
669
758
|
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 };
|
|
670
759
|
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(() => {});
|
|
@@ -686,11 +775,18 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
686
775
|
s.cancelledRid = saved?.cancelledRid ?? null;
|
|
687
776
|
s.cancelledAt = saved?.cancelledAt ?? null;
|
|
688
777
|
s.cancelledByGrace = saved?.cancelledByGrace === true;
|
|
778
|
+
s.finishedAfterCancel = saved?.finishedAfterCancel === true;
|
|
689
779
|
let intent = readJsonPrivate(cancellationFile(s.id));
|
|
690
780
|
if (intent?.not_before && intent.rid === ctl.pending?.rid) {
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
781
|
+
const followUp = text.trim() !== CONTINUE_PROMPT;
|
|
782
|
+
const insideGrace = Date.now() < intent.not_before;
|
|
783
|
+
const kept = intent.bridge
|
|
784
|
+
? (await askGraceBridge(intent, followUp && insideGrace ? 'keep' : 'state', ctl.abort.signal)).kept
|
|
785
|
+
: followUp && insideGrace;
|
|
786
|
+
if (kept) {
|
|
787
|
+
delete ctl.pending.cancel_requested; publishPending(s, ctl);
|
|
788
|
+
fs.rmSync(cancellationFile(s.id), {force:true});
|
|
789
|
+
intent=null;
|
|
694
790
|
} else if (Date.now() < intent.not_before) {
|
|
695
791
|
await sleep(intent.not_before-Date.now(), ctl.abort.signal);
|
|
696
792
|
}
|
|
@@ -710,7 +806,10 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
710
806
|
}
|
|
711
807
|
if (!ctl.pending && s.cancelledRid && s.cancelledByGrace && Date.now()-Date.parse(s.cancelledAt)<60000) {
|
|
712
808
|
s.cancelledByGrace=false;saveSession(s);
|
|
713
|
-
|
|
809
|
+
const state = s.finishedAfterCancel
|
|
810
|
+
? 'finished after cancellation was requested. Its result was not delivered to this turn.'
|
|
811
|
+
: `was cancelled at ${s.cancelledAt} (no follow-up within 2 s).`;
|
|
812
|
+
await say('agent_message_chunk', `Your earlier work ${s.cancelledRid} ${state} This message was not submitted. Resend the full task if you want new work.\n`);
|
|
714
813
|
return {stopReason:'end_turn'};
|
|
715
814
|
}
|
|
716
815
|
if (!ctl.pending && s.cancelledRid && text.trim() === CONTINUE_PROMPT) {
|
|
@@ -761,7 +860,7 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
761
860
|
if (outcome.cancelled) {
|
|
762
861
|
await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]);
|
|
763
862
|
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'});
|
|
863
|
+
if (ctl.graceUnconfirmed || 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
864
|
return { stopReason: 'cancelled' };
|
|
766
865
|
}
|
|
767
866
|
if (outcome.resumable) {
|
|
@@ -792,22 +891,59 @@ const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
|
792
891
|
const s = sessions.get(params.sessionId);
|
|
793
892
|
const ctl = s?.ctl;
|
|
794
893
|
if (!s) return;
|
|
894
|
+
if (ctl?.cancelled) return;
|
|
795
895
|
const explicitControl = params._meta?.dalanControl !== undefined;
|
|
796
896
|
const withdrawalRid = explicitControl ? explicitWithdrawalRid(params._meta)
|
|
797
897
|
: ctl?.pending?.rid ?? s.pending?.rid ?? readSession(s.id)?.pending?.rid;
|
|
798
|
-
|
|
799
|
-
writeJsonPrivate(cancellationFile(s.id), {rid:withdrawalRid,not_before:Date.now()+CANCEL_GRACE_MS});
|
|
800
|
-
retryWithdrawal(s,withdrawalRid);
|
|
801
|
-
}
|
|
898
|
+
const grace = !explicitControl && withdrawalRid ? armWithdrawalGrace(s, withdrawalRid, ctl) : null;
|
|
802
899
|
if (!ctl) { if (explicitControl && withdrawalRid) void cancelYieldedSession(s, withdrawalRid); return; }
|
|
803
|
-
if (ctl.cancelled) return;
|
|
804
900
|
ctl.cancelled = true;
|
|
805
901
|
ctl.withdrawWork = explicitControl && !!withdrawalRid && withdrawalRid === ctl.pending?.rid;
|
|
806
902
|
if(!explicitControl) ctl.workerState='withdrawal_pending_grace';
|
|
807
|
-
ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : Promise.resolve();
|
|
903
|
+
ctl.cancelDone = ctl.withdrawWork ? cancelPending(s, ctl) : grace ?? Promise.resolve();
|
|
808
904
|
ctl.abort.abort();
|
|
809
905
|
});
|
|
810
906
|
|
|
907
|
+
function askGraceBridge(intent, action, signal) {
|
|
908
|
+
return adminRequest(P.socket,'/cancel-grace',{method:'POST',token:tokenFor(intent.rid),timeoutMs:1500,signal,
|
|
909
|
+
payload:{id:intent.rid,intent:intent.bridge,action,...(intent.before_admission?{before_admission:true}:{})}});
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
async function armWithdrawalGrace(s, rid, ctl) {
|
|
913
|
+
if (ctl) ctl.graceUnconfirmed=true;
|
|
914
|
+
const file = cancellationFile(s.id);
|
|
915
|
+
const saved = readJsonPrivate(file);
|
|
916
|
+
const newIntent=()=>({rid,requested_at:Date.now(),not_before:Date.now()+CANCEL_GRACE_MS,bridge:randomUUID(),
|
|
917
|
+
before_admission:(ctl?.pending??s.pending)?.submission_pending===true});
|
|
918
|
+
let intent = saved?.rid===rid && saved.not_before ? saved :newIntent();
|
|
919
|
+
writeJsonPrivate(file,intent);
|
|
920
|
+
try {
|
|
921
|
+
if (intent.bridge) {
|
|
922
|
+
let reply = await askGraceBridge(intent,'arm');
|
|
923
|
+
if(reply.kept) {
|
|
924
|
+
// A new cancellation of this session must not inherit an earlier keep decision.
|
|
925
|
+
intent=newIntent(); writeJsonPrivate(file,intent);
|
|
926
|
+
reply=await askGraceBridge(intent,'arm');
|
|
927
|
+
}
|
|
928
|
+
intent.not_before=reply.not_before;
|
|
929
|
+
writeJsonPrivate(file,intent);
|
|
930
|
+
}
|
|
931
|
+
if (ctl) {
|
|
932
|
+
ctl.graceUnconfirmed=false;
|
|
933
|
+
ctl.workerState=intent.bridge ? 'withdrawal_scheduled' : 'withdrawal_pending_grace';
|
|
934
|
+
}
|
|
935
|
+
} catch (error) {
|
|
936
|
+
if (error.http_status===404 || error.message==='unknown route') {
|
|
937
|
+
// Compatibility with a serving bridge from before durable withdrawal.
|
|
938
|
+
delete intent.bridge; writeJsonPrivate(file,intent);
|
|
939
|
+
if (ctl) ctl.graceUnconfirmed=false;
|
|
940
|
+
} else {
|
|
941
|
+
log(`grace withdrawal was not confirmed for ${rid}: ${error.message}`);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
retryWithdrawal(s,rid);
|
|
945
|
+
}
|
|
946
|
+
|
|
811
947
|
function explicitWithdrawalRid(meta) {
|
|
812
948
|
const control = meta?.dalanControl;
|
|
813
949
|
if (control?.intent !== 'withdraw_work' || typeof control.scope !== 'string') return null;
|
|
@@ -890,14 +1026,32 @@ async function cancelPending(s, ctl) {
|
|
|
890
1026
|
const intent=readJsonPrivate(cancellationFile(s.id));
|
|
891
1027
|
if (currentTurn(s, ctl) && intent?.rid === pending.rid) {
|
|
892
1028
|
if(intent.not_before && s.cancelledRid===pending.rid) {
|
|
893
|
-
s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;
|
|
1029
|
+
s.cancelledAt=new Date().toISOString();s.cancelledByGrace=true;
|
|
1030
|
+
s.finishedAfterCancel=ctl.workerState==='finished_after_withdrawal_request';saveSession(s);
|
|
894
1031
|
}
|
|
895
1032
|
fs.rmSync(cancellationFile(s.id), { force: true });
|
|
896
1033
|
}
|
|
897
1034
|
};
|
|
898
1035
|
ctl.cancelledWorkId = pending.rid;
|
|
899
1036
|
let row = await readRowOrThrow(pending.rid);
|
|
900
|
-
|
|
1037
|
+
const grace = readJsonPrivate(cancellationFile(s.id));
|
|
1038
|
+
if (grace?.bridge && !ctl.withdrawWork) {
|
|
1039
|
+
const decision=await askGraceBridge(grace,'settle');
|
|
1040
|
+
if(decision.kept) {
|
|
1041
|
+
delete pending.cancel_requested;
|
|
1042
|
+
publishPending(s,ctl);
|
|
1043
|
+
clearIntent();
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
if(decision.status==='queued'||decision.status==='claimed') {
|
|
1047
|
+
if(!decision.pending) await askGraceBridge(grace,'arm');
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
if(decision.status!==row.status) row=await readRowOrThrow(pending.rid);
|
|
1051
|
+
}
|
|
1052
|
+
const requestedAt = grace?.requested_at ?? (grace?.not_before-CANCEL_GRACE_MS);
|
|
1053
|
+
const finishedDuringGrace = Date.parse(row.report?.created_at)>=requestedAt;
|
|
1054
|
+
if (row.status === 'finished' && (pending.withdrawal_started || finishedDuringGrace)) {
|
|
901
1055
|
ctl.workerState = 'finished_after_withdrawal_request';
|
|
902
1056
|
s.cancelledRid = pending.rid; ctl.pending = null; publishPending(s, ctl); clearIntent(); return;
|
|
903
1057
|
}
|
package/bin/dot-worker.mjs
CHANGED
|
@@ -17,7 +17,7 @@ import { formatStatusSummary } from '../src/status-summary.mjs';
|
|
|
17
17
|
import { explainMetrics } from '../src/lifecycle.mjs';
|
|
18
18
|
import { normalizeMeta, metaFields, deriveObjectives } from '../src/objectives.mjs';
|
|
19
19
|
import { legacyFixLedgerPath } from '../src/legacy-names.mjs';
|
|
20
|
-
import { buildInbox, formatInbox, parseWhen, decideWords } from '../src/inbox.mjs';
|
|
20
|
+
import { buildInbox, formatInbox, parseWhen, decideWords, readInboxPages } from '../src/inbox.mjs';
|
|
21
21
|
import { decideDrained, drainedExitCodes, terminal } from '../src/drained.mjs';
|
|
22
22
|
import { takeSlot, releaseSlot } from '../src/drained-slot.mjs';
|
|
23
23
|
import { liveWaiter } from '../src/drained-owner.mjs';
|
|
@@ -41,6 +41,7 @@ import { terminalSafe, jsonTerminalSafe } from '../src/terminal-safe.mjs';
|
|
|
41
41
|
import { loadOwnerWorkers, parseWorkers, submitTarget, updateWorkerRepoPolicy, writeGenericProfile, writeLegacyMarker, readWorkerRepoHistory, seedWorkerRepos, inspectGrantAudit, ensureWorkerRelationship, AUDIT_INTEGRITY_HINT } from '../src/workers.mjs';
|
|
42
42
|
import { adminSocketPathError, adminSocketPath } from '../src/admin-socket.mjs';
|
|
43
43
|
import { answerThroughJournal } from '../src/answer-journal.mjs';
|
|
44
|
+
import { SESSION_ID, readJsonPrivate, sessionPath } from '../integrations/t3/acp-kit/src/session-store.mjs';
|
|
44
45
|
// An answer reply that takes longer than this counts as lost; the journaled envelope is sent again.
|
|
45
46
|
const ANSWER_TIMEOUT_MS=30000;
|
|
46
47
|
|
|
@@ -92,7 +93,7 @@ function bridgeNotRunning(error) {
|
|
|
92
93
|
if(selected) return Object.assign(error,{message:`cannot reach the bridge: no bridge is running for DALAN_HOME=${selected} (${cause})`,fix:[`start the bridge for this home the way you set it up (${docsUrl('docs/manual-setup.md','owner-and-requester-setup')}), then run this command again`]});
|
|
93
94
|
return Object.assign(error,{message:`cannot reach the bridge: DALAN_HOME is not set and no bridge is running in ${home} (${cause})`,fix:[`export DALAN_HOME=DIR for the bridge home you made, or start a trial bridge with: ${cli} try`]});
|
|
94
95
|
}
|
|
95
|
-
function request(route, method = 'GET', payload, headers={}, timeoutMs=30000) {
|
|
96
|
+
function request(route, method = 'GET', payload, headers={}, timeoutMs=30000, wallDeadline=false) {
|
|
96
97
|
return new Promise((resolve, reject) => {
|
|
97
98
|
const bytes = payload ? JSON.stringify(payload) : '';
|
|
98
99
|
const transportFailure=error=>reject(Object.assign(error.syscall==='connect'&&['ENOENT','ECONNREFUSED'].includes(error.code)?bridgeNotRunning(error):error,{kind:'transport'}));
|
|
@@ -110,7 +111,11 @@ function request(route, method = 'GET', payload, headers={}, timeoutMs=30000) {
|
|
|
110
111
|
else resolve(value);
|
|
111
112
|
});
|
|
112
113
|
});
|
|
113
|
-
if(timeoutMs>0)
|
|
114
|
+
if(timeoutMs>0) {
|
|
115
|
+
const expire=()=>req.destroy(Object.assign(new Error(`admin request timed out after ${timeoutMs} ms`),{code:'ETIMEDOUT'}));
|
|
116
|
+
if(wallDeadline) { const deadline=setTimeout(expire,timeoutMs); req.once('close',()=>clearTimeout(deadline)); }
|
|
117
|
+
else req.setTimeout(timeoutMs,expire);
|
|
118
|
+
}
|
|
114
119
|
req.on('error',transportFailure); req.end(bytes);
|
|
115
120
|
});
|
|
116
121
|
}
|
|
@@ -163,12 +168,18 @@ function receipt(id) {
|
|
|
163
168
|
}
|
|
164
169
|
// A row the ACP adapter (T3 worker provider) submitted has no CLI receipt: its owner token is HMAC(acp-secret, request id).
|
|
165
170
|
// Deriving it lets the T3 parent get, download, accept and reject that row. The bridge still checks the token.
|
|
166
|
-
function
|
|
171
|
+
function acpOwnerSecret() {
|
|
167
172
|
const file=process.env.DOT_ACP_SECRET_FILE||defaultPath(home,'.config/dot-bridge/acp-secret');
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
173
|
+
try {
|
|
174
|
+
if((fs.statSync(file).mode&0o777)!==0o600) return null;
|
|
175
|
+
const secret=fs.readFileSync(file,'utf8').trim();
|
|
176
|
+
return secret.length>=32?secret:null;
|
|
177
|
+
} catch { return null; }
|
|
178
|
+
}
|
|
179
|
+
const acpOwnerToken=(secret,id)=>createHmac('sha256',secret).update(id).digest('hex');
|
|
180
|
+
function acpReceipt(id) {
|
|
181
|
+
const secret=acpOwnerSecret();
|
|
182
|
+
return secret?{request_id:id,token:acpOwnerToken(secret,id),acp:true}:null;
|
|
172
183
|
}
|
|
173
184
|
function writeReceipt(id, token, body, delivery, review=false, background=false, meta=null, producer=null, routing=null, destinationRevisions=null, revises=null, follows=null, callerWaiting=false) {
|
|
174
185
|
fs.mkdirSync(receipts,{recursive:true,mode:0o700});
|
|
@@ -272,6 +283,35 @@ function producerReceipts(producer,cache) {
|
|
|
272
283
|
}
|
|
273
284
|
return [...cache.values()].filter(Boolean);
|
|
274
285
|
}
|
|
286
|
+
// Native sessions are a local discovery index, never proof of owner authority.
|
|
287
|
+
function nativeInboxReceipts(producer) {
|
|
288
|
+
const dir=process.env.DOT_ACP_STATE_DIR||defaultPath(home,'.local/state/dot-bridge/acp');
|
|
289
|
+
let files;
|
|
290
|
+
try { files=fs.readdirSync(dir,{withFileTypes:true}); }
|
|
291
|
+
catch(error) { if(error.code==='ENOENT') return []; throw error; }
|
|
292
|
+
const secret=acpOwnerSecret();
|
|
293
|
+
if(!secret) return [];
|
|
294
|
+
const owned=new Map();
|
|
295
|
+
for(const file of files) {
|
|
296
|
+
const sessionId=file.name.slice(0,-5);
|
|
297
|
+
if(!file.isFile()||!file.name.endsWith('.json')||!SESSION_ID.test(sessionId)) continue;
|
|
298
|
+
let saved;
|
|
299
|
+
try { saved=readJsonPrivate(sessionPath(dir,sessionId)); }
|
|
300
|
+
catch(error) { if(['invalid_session_state','state_permissions'].includes(error.code)) continue; throw error; }
|
|
301
|
+
if(saved?.id!==sessionId) continue;
|
|
302
|
+
const completed=Array.isArray(saved.completed)?saved.completed:[];
|
|
303
|
+
for(const work of [saved.pending,...completed]) {
|
|
304
|
+
const id=work?.rid;
|
|
305
|
+
if(typeof id!=='string'||!/^[-\w]{8,128}$/.test(id)||owned.has(id)) continue;
|
|
306
|
+
if(producer!==null&&producer!==sessionId&&producer!==work.original_host_task_id) continue;
|
|
307
|
+
if(fs.existsSync(receiptPath(id))) continue;
|
|
308
|
+
owned.set(id,{id,token:acpOwnerToken(secret,id)});
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return [...owned.values()];
|
|
312
|
+
}
|
|
313
|
+
const peekInboxPage=(items,timeoutMs)=>request('/owner-states','POST',{items},{},timeoutMs,true);
|
|
314
|
+
|
|
275
315
|
// A failure worth retrying: the bridge restarting (transport) or unavailable (5xx).
|
|
276
316
|
const transient=e=>e.kind==='transport'||e.http_status>=500;
|
|
277
317
|
// /owner-states is explicitly non-consuming. A bridge lacking it might also
|
|
@@ -316,9 +356,17 @@ async function inbox() {
|
|
|
316
356
|
if(missing.length) throw new Error(`no receipt on this host for ${missing.join(', ')}`);
|
|
317
357
|
return markInboxRead(ids.map(x=>byId.get(x)));
|
|
318
358
|
}
|
|
359
|
+
if(!markRead) {
|
|
360
|
+
const owned=new Map(nativeInboxReceipts(producer).map(r=>[r.id,r]));
|
|
361
|
+
for(const receipt of receiptsInScope) owned.set(receipt.id,receipt);
|
|
362
|
+
const read=await readInboxPages([...owned.values()],peekInboxPage);
|
|
363
|
+
if(read.legacy) throw new Error('this bridge predates dalan inbox; update and restart it');
|
|
364
|
+
if(read.error) throw read.error;
|
|
365
|
+
if(read.partial_read) process.exitCode=1;
|
|
366
|
+
return {...buildInbox(read.states,scopeAll?'all':producer,{cutoff}),...(read.partial_read?{partial_read:read.partial_read}:{})};
|
|
367
|
+
}
|
|
319
368
|
const read=await ownerStates(receiptsInScope,legacy);
|
|
320
369
|
if(legacy.on) throw new Error('this bridge predates dalan inbox; update and restart it');
|
|
321
|
-
if(!markRead) return buildInbox(read.states,scopeAll?'all':producer,{cutoff});
|
|
322
370
|
const due=buildInbox(read.states,all?'all':producer).items.filter(i=>i.group!=='question'&&i.group!=='undecided'&&Date.parse(i.updated_at)<beforeCutoff);
|
|
323
371
|
const byId=new Map(receiptsInScope.map(r=>[r.id,r]));
|
|
324
372
|
return markInboxRead(due.map(i=>byId.get(i.request_id)));
|
|
@@ -572,6 +620,10 @@ async function main() {
|
|
|
572
620
|
// scope paths dropped) are applied and the submit retried once only with --allow-scope-prune (--fix-scope is its old spelling).
|
|
573
621
|
// The refused first submit stored nothing, so the same request_id and receipt stay valid.
|
|
574
622
|
if(!(error.kind==='http'&&error.http_status===400&&error.suggested_scope_paths)) throw error;
|
|
623
|
+
if(body.read_paths!==undefined||body.read_list!==undefined) {
|
|
624
|
+
error.fix=['Correct the explicit read paths and scope_paths together in the assignment.'];
|
|
625
|
+
throw error;
|
|
626
|
+
}
|
|
575
627
|
const was=body.scope_paths||[], added=error.suggested_scope_paths.filter(p=>!was.includes(p)), removed=was.filter(p=>!error.suggested_scope_paths.includes(p));
|
|
576
628
|
const change=`${added.length?`added ${added.join(', ')}`:''}${added.length&&removed.length?'; ':''}${removed.length?`removed ${removed.join(', ')}`:''}`;
|
|
577
629
|
if(!args.includes('--allow-scope-prune')&&!args.includes('--fix-scope')) {
|
|
@@ -624,13 +676,25 @@ async function main() {
|
|
|
624
676
|
case 'status': {
|
|
625
677
|
refuseUnknownOptions('status',{flags:['--json','--explain']});
|
|
626
678
|
result = await request('/status');
|
|
679
|
+
let recoveryLine='';
|
|
680
|
+
const native=nativeInboxReceipts(producerId());
|
|
681
|
+
if(native.length) {
|
|
682
|
+
const recovery=await readInboxPages(native,peekInboxPage,{budgetMs:500});
|
|
683
|
+
if(!recovery.legacy) {
|
|
684
|
+
const available=buildInbox(recovery.states,'native').counts.finished_unread;
|
|
685
|
+
result={...result,native_results_available:available,
|
|
686
|
+
...(recovery.partial_read?{native_recovery_partial:recovery.partial_read}:{})};
|
|
687
|
+
if(available) recoveryLine=`\n${available} unread native result(s) available (dalan inbox --all).`;
|
|
688
|
+
if(recovery.partial_read) recoveryLine+='\nNative inbox scan incomplete (dalan inbox --all).';
|
|
689
|
+
}
|
|
690
|
+
}
|
|
627
691
|
if (args.includes('--explain')) {
|
|
628
692
|
let metrics = null;
|
|
629
693
|
try { metrics = await request('/metrics'); if (!metrics?.window) metrics = null; } catch { /* an older bridge has no /metrics */ }
|
|
630
694
|
const explanation = explainStatus(result) + '\n' + (metrics ? explainMetrics(metrics) : 'metrics=unavailable');
|
|
631
695
|
if (json) result = { ...result, explanation, ...(metrics ? { metrics } : {}) };
|
|
632
|
-
else { result = explanation; plainOutput = true; }
|
|
633
|
-
} else if (!json) { result = formatStatusSummary(result, { home, url: bridgeOrigin(), trial: fs.existsSync(path.join(home, '.dalan-trial')), cli, envHome: process.env.DALAN_HOME }); plainOutput = true; }
|
|
696
|
+
else { result = explanation+recoveryLine; plainOutput = true; }
|
|
697
|
+
} else if (!json) { result = formatStatusSummary(result, { home, url: bridgeOrigin(), trial: fs.existsSync(path.join(home, '.dalan-trial')), cli, envHome: process.env.DALAN_HOME })+recoveryLine; plainOutput = true; }
|
|
634
698
|
break;
|
|
635
699
|
}
|
|
636
700
|
case 'tool': {
|