@tnunamak/dalan 0.9.8 → 0.9.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/bin/dot-acp-agent.mjs +145 -28
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +58 -2
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +5 -1
- package/package.json +1 -1
- package/src/acp-bridge.mjs +23 -11
- package/src/as-files.mjs +6 -3
- package/src/cli-help.mjs +4 -2
- package/src/get-summary.mjs +5 -0
- package/src/local-attachment-authority.mjs +174 -0
- package/src/local-attachment-capture.mjs +136 -0
- package/src/local-attachment-cli.mjs +46 -0
- package/src/local-attachment-gateway.mjs +93 -0
- package/src/local-attachment-owner-verify.mjs +152 -0
- package/src/local-attachment-result.mjs +64 -0
- package/src/local-attachment-snapshot.mjs +142 -0
- package/src/mcp-stdio.mjs +189 -7
- package/src/patch-apply.mjs +28 -6
- package/src/publication-authority.mjs +1 -0
- package/src/pull-pacing.mjs +10 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +53 -16
- package/src/store.mjs +199 -15
- package/src/tool-registry.mjs +15 -4
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
package/src/store.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {migrateWorkRecovery,isRecoveryCheckpoint,saveWorkCheckpoint,projectWorkRecovery} from './work-recovery.mjs';
|
|
1
2
|
import {PullQueue,migratePullQueue,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
3
|
import { defaultPath } from './paths.mjs';
|
|
3
4
|
import { readEnv } from './env.mjs';
|
|
@@ -18,6 +19,8 @@ import fs from 'node:fs';
|
|
|
18
19
|
import {migrateClaimCommands,createClaimCommands} from './claim-command-ledger.mjs';
|
|
19
20
|
import {migrateArtifactJournal} from './artifact-journal.mjs';
|
|
20
21
|
import {migrateResultBindings} from './result-binding.mjs';
|
|
22
|
+
import {migrateLocalAttachments} from './local-attachment-authority.mjs';
|
|
23
|
+
import {localAttachmentPublicationRestriction,assertOrdinaryLocalAttachmentBoundary,hasLocalAttachment} from './local-attachment-result.mjs';
|
|
21
24
|
import {migrateJobRetention} from './job-retention.mjs';
|
|
22
25
|
import {migrateProtocolOwnerWaiters,materializeProtocolWaiters} from './protocol-owner-waiters.mjs';
|
|
23
26
|
import {finishProtocol} from './protocol-finish.mjs';
|
|
@@ -68,7 +71,7 @@ function waiterOwnerGone(attemptId) {
|
|
|
68
71
|
return !!(owner.boot&&owner.start&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
69
72
|
}
|
|
70
73
|
|
|
71
|
-
const SUPPORTED_SCHEMA_VERSION =
|
|
74
|
+
const SUPPORTED_SCHEMA_VERSION = 76;
|
|
72
75
|
const ADMISSION_RESERVATION_MS = 15_000;
|
|
73
76
|
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
74
77
|
function systemBootId() {
|
|
@@ -1136,6 +1139,18 @@ export class Store {
|
|
|
1136
1139
|
prior_id TEXT NOT NULL REFERENCES assignments(request_id),
|
|
1137
1140
|
at TEXT NOT NULL
|
|
1138
1141
|
); PRAGMA user_version=75;`);
|
|
1142
|
+
if(version<76) { migrateLocalAttachments(this.db); this.db.exec('PRAGMA user_version=76;'); }
|
|
1143
|
+
// These owner-only projections need no backfill and leave existing job receipts intact.
|
|
1144
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS continuing_subagents(
|
|
1145
|
+
subagent_id TEXT PRIMARY KEY, owner_hash TEXT NOT NULL,
|
|
1146
|
+
target_worker TEXT NOT NULL, relationship_id TEXT
|
|
1147
|
+
);
|
|
1148
|
+
CREATE TABLE IF NOT EXISTS continuing_subagent_jobs(
|
|
1149
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1150
|
+
subagent_id TEXT NOT NULL REFERENCES continuing_subagents(subagent_id),
|
|
1151
|
+
request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE
|
|
1152
|
+
);
|
|
1153
|
+
CREATE INDEX IF NOT EXISTS continuing_subagent_history ON continuing_subagent_jobs(subagent_id,seq);`);
|
|
1139
1154
|
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='run_timeout_ms'").get())
|
|
1140
1155
|
this.db.exec('ALTER TABLE claims ADD COLUMN run_timeout_ms INTEGER');
|
|
1141
1156
|
// Older bridges read every open row of worker_breaks as a primary-worker hold.
|
|
@@ -1155,6 +1170,15 @@ export class Store {
|
|
|
1155
1170
|
request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1156
1171
|
progress_id INTEGER UNIQUE REFERENCES progress(id) ON DELETE SET NULL
|
|
1157
1172
|
);`);
|
|
1173
|
+
// Additive evidence; legacy projections and ordinary unkeyed withdraw replies remain unchanged.
|
|
1174
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS offer_withdraw_receipts(
|
|
1175
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1176
|
+
key_digest TEXT NOT NULL, owner_digest TEXT NOT NULL, receipt TEXT NOT NULL
|
|
1177
|
+
);
|
|
1178
|
+
CREATE TABLE IF NOT EXISTS offer_start_evidence(
|
|
1179
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1180
|
+
epoch INTEGER NOT NULL, at TEXT NOT NULL
|
|
1181
|
+
);`);
|
|
1158
1182
|
this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
|
|
1159
1183
|
worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1160
1184
|
subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
|
|
@@ -1173,6 +1197,7 @@ export class Store {
|
|
|
1173
1197
|
due_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, kept INTEGER NOT NULL DEFAULT 0,
|
|
1174
1198
|
PRIMARY KEY(request_id,owner_hash)
|
|
1175
1199
|
) WITHOUT ROWID;`);
|
|
1200
|
+
migrateWorkRecovery(this.db);
|
|
1176
1201
|
// Worker run receipts (D9), hosted-session lifetimes (D14) and the publication grant on a relationship (D10).
|
|
1177
1202
|
// Additive and idempotent, so it needs no schema number: older code ignores these tables and column.
|
|
1178
1203
|
{
|
|
@@ -1760,11 +1785,60 @@ export class Store {
|
|
|
1760
1785
|
if(relationship?.ended_at) throw new Error('relationship_ended');
|
|
1761
1786
|
return relationship;
|
|
1762
1787
|
}
|
|
1788
|
+
// The first job's owner receipt controls this handle, independently of the shared worker relationship.
|
|
1789
|
+
// Per-job operations still require each job's original owner receipt.
|
|
1790
|
+
subagentOwner(subagentId, credential) {
|
|
1791
|
+
if(typeof subagentId!=='string'||!/^sg_[A-Za-z0-9_-]{22,80}$/.test(subagentId)||
|
|
1792
|
+
typeof credential!=='string'||!credential||credential.length>128) throw new Error('subagent_unavailable');
|
|
1793
|
+
const row=this.db.prepare('SELECT * FROM continuing_subagents WHERE subagent_id=?').get(subagentId);
|
|
1794
|
+
const expected=Buffer.from(row?.owner_hash??'00'.repeat(32),'hex');
|
|
1795
|
+
const permitted=timingSafeEqual(expected,Buffer.from(hash(credential),'hex'));
|
|
1796
|
+
if(!row||!permitted) throw new Error('subagent_unavailable');
|
|
1797
|
+
return row;
|
|
1798
|
+
}
|
|
1799
|
+
checkSubagentSubmission(requestId, ownerToken, options, links=[]) {
|
|
1800
|
+
const known=this.db.prepare('SELECT subagent_id FROM continuing_subagent_jobs WHERE request_id=?').get(requestId);
|
|
1801
|
+
const subagentId=options?.id;
|
|
1802
|
+
if(subagentId===undefined) {
|
|
1803
|
+
if(known||options?.credential!==undefined) throw new Error('subagent_unavailable');
|
|
1804
|
+
return null;
|
|
1805
|
+
}
|
|
1806
|
+
if(typeof subagentId!=='string'||!/^sg_[A-Za-z0-9_-]{22,80}$/.test(subagentId)||
|
|
1807
|
+
(options.credential!==undefined&&(typeof options.credential!=='string'||!options.credential||options.credential.length>128)))
|
|
1808
|
+
throw new Error('subagent_unavailable');
|
|
1809
|
+
if(known?.subagent_id!==subagentId&&(known||this.hasAssignment(requestId))) throw new Error('subagent_unavailable');
|
|
1810
|
+
const exists=this.db.prepare('SELECT 1 FROM continuing_subagents WHERE subagent_id=?').get(subagentId);
|
|
1811
|
+
// An explicit prior receipt must never create a replacement for a missing handle.
|
|
1812
|
+
const binding=exists||options.credential!==undefined?this.subagentOwner(subagentId,options.credential??ownerToken):null;
|
|
1813
|
+
for(const linked of links.filter(Boolean)) {
|
|
1814
|
+
if(this.db.prepare('SELECT subagent_id FROM continuing_subagent_jobs WHERE request_id=?').get(linked)?.subagent_id!==subagentId)
|
|
1815
|
+
throw new Error('subagent_unavailable');
|
|
1816
|
+
}
|
|
1817
|
+
return {id:subagentId,binding};
|
|
1818
|
+
}
|
|
1819
|
+
subagentHistory(subagentId, credential, after=0, limit=30) {
|
|
1820
|
+
this.subagentOwner(subagentId,credential);
|
|
1821
|
+
if(!Number.isSafeInteger(after)||after<0||!Number.isSafeInteger(limit)||limit<1||limit>30)
|
|
1822
|
+
throw new Error('invalid_subagent_page');
|
|
1823
|
+
const rows=this.db.prepare('SELECT seq,request_id FROM continuing_subagent_jobs WHERE subagent_id=? AND seq>? ORDER BY seq LIMIT ?')
|
|
1824
|
+
.all(subagentId,after,limit+1);
|
|
1825
|
+
const work=rows.slice(0,limit).map(({request_id})=>{
|
|
1826
|
+
const item=this.get(request_id), report=item.report;
|
|
1827
|
+
return {request_id,status:item.status,created_at:item.created_at,follows:item.follows??null,
|
|
1828
|
+
revises:item.revises??null,report:report?{receipt_id:report.receipt_id,outcome:report.outcome,
|
|
1829
|
+
summary:report.summary,result:report.result,created_at:report.created_at}:null};
|
|
1830
|
+
});
|
|
1831
|
+
return {subagent_id:subagentId,work,next_after:rows.length>limit?rows[limit-1].seq:null};
|
|
1832
|
+
}
|
|
1763
1833
|
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1764
|
-
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null, follows=null, callerWaiting=undefined) {
|
|
1834
|
+
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null, follows=null, callerWaiting=undefined, subagentOptions=undefined) {
|
|
1765
1835
|
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1766
1836
|
if(callerWaiting!==undefined&&typeof callerWaiting!=='boolean') throw new Error('invalid caller_waiting');
|
|
1767
1837
|
if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
|
|
1838
|
+
if(subagentOptions?.id!==undefined&&(inheritedOwnerHash||Object.hasOwn(payload,'protocol')))
|
|
1839
|
+
throw new Error('subagent_unavailable');
|
|
1840
|
+
const subagent=this.checkSubagentSubmission(payload.request_id,ownerToken,subagentOptions,
|
|
1841
|
+
[follows?.prior_id,revises?.prior_id,supersedes?.target_id]);
|
|
1768
1842
|
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
1769
1843
|
if(protocol)identity={...identity,protocol};
|
|
1770
1844
|
if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
@@ -1772,7 +1846,7 @@ export class Store {
|
|
|
1772
1846
|
const m=normalizeMeta(meta);
|
|
1773
1847
|
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1774
1848
|
const retry=this.checkRetry(payload,deliveryOrThreadId,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,callerWaiting);
|
|
1775
|
-
if(retry) return retry;
|
|
1849
|
+
if(retry) return subagent?{...retry,subagent_id:subagent.id}:retry;
|
|
1776
1850
|
let relationship;
|
|
1777
1851
|
if(inheritedOwnerHash) {
|
|
1778
1852
|
const order=this.pullQueue.row(payload.request_id);
|
|
@@ -1827,6 +1901,16 @@ export class Store {
|
|
|
1827
1901
|
this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities,delivery_adapter,delivery_address,delivery_adapter_version,caller_waiting) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null,deliveryAdapter,deliveryAddress,deliveryAdapterVersion,callerWaiting?1:0);
|
|
1828
1902
|
if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
|
|
1829
1903
|
if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
|
|
1904
|
+
if(subagent) {
|
|
1905
|
+
const worker=targetWorker??'dot', relation=relationship?.relationship_id??null;
|
|
1906
|
+
if(subagent.binding) {
|
|
1907
|
+
if(subagent.binding.target_worker!==worker||subagent.binding.relationship_id!==relation)
|
|
1908
|
+
throw new Error('subagent_unavailable');
|
|
1909
|
+
} else this.db.prepare('INSERT INTO continuing_subagents VALUES(?,?,?,?)')
|
|
1910
|
+
.run(subagent.id,ownerHash,worker,relation);
|
|
1911
|
+
this.db.prepare('INSERT INTO continuing_subagent_jobs(subagent_id,request_id) VALUES(?,?)').run(subagent.id,id);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1830
1914
|
if(disclosure)this.db.prepare('INSERT INTO destination_approvals(request_id,revision,snapshot,actor,approved_at) VALUES(?,?,?,?,?)').run(id,disclosure.revision,JSON.stringify(disclosure),JSON.stringify({kind:'owner_capability',id:ownerHash}),this.stamp());
|
|
1831
1915
|
const requestedValidUntil=validUntilOf(payload);
|
|
1832
1916
|
const mayUseDefault=priority==='normal'&&!this.paused()&&!this.holdingBreak(targetWorker??'dot');
|
|
@@ -1870,7 +1954,7 @@ export class Store {
|
|
|
1870
1954
|
if(callerWaiting===true&&priority==='normal'&&!protocol&&!inheritedOwnerHash) this.reserveAdmissionLane(id,targetWorker??'dot');
|
|
1871
1955
|
for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
|
|
1872
1956
|
}
|
|
1873
|
-
const receipt={request_id:id,status,duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
|
|
1957
|
+
const receipt={request_id:id,status,duplicate:false,...(subagent?{subagent_id:subagent.id}:{}),...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
|
|
1874
1958
|
if(commandKey!==null) {
|
|
1875
1959
|
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1876
1960
|
this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
|
|
@@ -2411,17 +2495,23 @@ export class Store {
|
|
|
2411
2495
|
// `authorize` runs on the live claim row before the write. An exact claim retry passes none: assertRetryConnection already proved the holder.
|
|
2412
2496
|
touchHeldClaim(id,claimId,subject,worker,authorize=null) {
|
|
2413
2497
|
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
2414
|
-
if(!c)return;
|
|
2498
|
+
if(!c)return false;
|
|
2415
2499
|
authorize?.(c);
|
|
2416
|
-
this.refreshClaimActivity(id,claimId);
|
|
2500
|
+
const deadline=this.refreshClaimActivity(id,claimId);
|
|
2501
|
+
return deadline!==null&&deadline>this.leaseExpiresAt(c);
|
|
2417
2502
|
}
|
|
2418
2503
|
refreshClaimActivity(id,claimId) {
|
|
2419
2504
|
const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id,claimed_at,run_timeout_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
|
|
2420
2505
|
const leaseMs=Math.min(this.handoffWorkLeaseMs(claim)??claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
|
|
2421
2506
|
const deadline=Math.min(Date.parse(at)+leaseMs,claim.run_timeout_ms==null?Infinity:Date.parse(claim.claimed_at)+claim.run_timeout_ms);
|
|
2422
|
-
if(this.isProtocolJob(id))
|
|
2423
|
-
|
|
2424
|
-
|
|
2507
|
+
if(this.isProtocolJob(id)) {
|
|
2508
|
+
this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
|
|
2509
|
+
return null;
|
|
2510
|
+
}
|
|
2511
|
+
const expiresAt=iso(deadline);
|
|
2512
|
+
this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
|
|
2513
|
+
.run(at,leaseMs,expiresAt,this.leaseBootId,this.monotonicDeadlineFor(deadline),id,claimId);
|
|
2514
|
+
return expiresAt;
|
|
2425
2515
|
}
|
|
2426
2516
|
handoffWorkingLeaseMs(worker) {
|
|
2427
2517
|
const cap=this.workerClaimLeaseCap(worker);
|
|
@@ -2463,12 +2553,19 @@ export class Store {
|
|
|
2463
2553
|
// Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
|
|
2464
2554
|
markNotesSeen(id,subject,worker='dot') { if(!this.mayAct(worker,id)) return; this.db.prepare("UPDATE claims SET last_seen_note_seq=COALESCE((SELECT max(sequence) FROM owner_notes n WHERE n.request_id=claims.request_id),0) WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(id,subject,worker); }
|
|
2465
2555
|
// One UPDATE per tool call that names an assignment; it matches only that worker's active claim, so a denied or foreign call counts nowhere.
|
|
2466
|
-
recordToolActivity(id,subject,worker,tool,{workspace=false,error=null,connectionId=null}={}) { return this.inTransaction(()=>{
|
|
2556
|
+
recordToolActivity(id,subject,worker,tool,{workspace=false,error=null,connectionId=null,claimId=null}={}) { return this.inTransaction(()=>{
|
|
2467
2557
|
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND subject=? AND worker=? AND state='active'").get(id,subject,worker);
|
|
2468
2558
|
if(!claim)return;
|
|
2469
2559
|
this.assertMutationConnection(id,claim,connectionId);
|
|
2470
2560
|
const at=this.stamp();
|
|
2471
2561
|
this.db.prepare("UPDATE claims SET tool_calls=tool_calls+1,last_tool=?,last_tool_at=?,last_tool_error=?,first_workspace_tool_at=CASE WHEN ? THEN COALESCE(first_workspace_tool_at,?) ELSE first_workspace_tool_at END WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(tool,at,error===null?null:String(error).slice(0,200),workspace?1:0,at,id,subject,worker);
|
|
2562
|
+
if(workspace&&error===null&&claimId===claim.claim_id&&!this.leaseExpired(claim)&&
|
|
2563
|
+
['read_file','apply_patch','run_check'].includes(tool)) {
|
|
2564
|
+
this.db.prepare(`INSERT INTO offer_start_evidence VALUES(?,?,?)
|
|
2565
|
+
ON CONFLICT(request_id) DO UPDATE SET epoch=excluded.epoch,at=excluded.at
|
|
2566
|
+
WHERE excluded.epoch>offer_start_evidence.epoch`).run(id,claim.epoch,at);
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2472
2569
|
}); }
|
|
2473
2570
|
static toolActivity(c) { return {acquisition_id:c.acquisition_id??null,tool_calls:c.tool_calls??0,last_tool:c.last_tool??null,last_tool_at:c.last_tool_at??null,last_tool_error:c.last_tool_error??null,first_workspace_tool_at:c.first_workspace_tool_at??null}; }
|
|
2474
2571
|
// For example: "lease_expired: <calls>, last <tool> at <time>, no workspace tool".
|
|
@@ -2756,6 +2853,8 @@ export class Store {
|
|
|
2756
2853
|
}
|
|
2757
2854
|
// D10: the work's current publication authority, read fresh at each effect. null when the work has no relationship.
|
|
2758
2855
|
publicationAuthority(id) {
|
|
2856
|
+
const restriction=localAttachmentPublicationRestriction(this.db,id);
|
|
2857
|
+
if(restriction) return {publish_restriction:restriction};
|
|
2759
2858
|
const row=this.db.prepare('SELECT r.relationship_id,r.ended_at,r.publish_grant FROM assignments a JOIN relationships r USING(relationship_id) WHERE a.request_id=?').get(id);
|
|
2760
2859
|
return row?{relationship_id:row.relationship_id,ended:row.ended_at!==null,publish_grant:row.publish_grant===null?null:JSON.parse(row.publish_grant)}:null;
|
|
2761
2860
|
}
|
|
@@ -3032,6 +3131,18 @@ export class Store {
|
|
|
3032
3131
|
const c=row.claim;
|
|
3033
3132
|
return row.status==='claimed'&&!row.cancellation_requested&&c?.state==='active'&&c.worker===worker&&c.subject===subject&&(claimId===undefined||c.claim_id===claimId)&&!this.leaseExpired(c)?this.workerHeartbeatFields(worker,c):{};
|
|
3034
3133
|
}
|
|
3134
|
+
workerGetLease(id,worker,subject,claimId,connectionId=null,renewed=false) {
|
|
3135
|
+
if(claimId===undefined) return {claim_lease:{mode:'request_only',
|
|
3136
|
+
guidance:'Use progress with your current claim ID. After reacquisition, a get without claim_id cannot renew the new claim.'}};
|
|
3137
|
+
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
3138
|
+
if(!c) return {claim_lease:{mode:'not_current',renewed:false,
|
|
3139
|
+
guidance:'This claim is not a current live grant. Stop using it; do not borrow another claim ID from get.'}};
|
|
3140
|
+
this.assertMutationConnection(id,c,connectionId);
|
|
3141
|
+
const explicit=this.isProtocolJob(id);
|
|
3142
|
+
return {claim_lease:{mode:explicit?'explicit_renewal':'current',renewed:!explicit&&renewed===true,
|
|
3143
|
+
epoch:c.epoch,lease_expires_at:this.leaseExpiresAt(c),
|
|
3144
|
+
guidance:explicit?'Protocol jobs require renew_claim before this deadline; get does not renew them.':'Send progress with this claim while working and stop if it expires.'}};
|
|
3145
|
+
}
|
|
3035
3146
|
heartbeatForHeldClaim(id,claimId,worker) {
|
|
3036
3147
|
if(this.workerHeartbeatMs(worker)===null||!claimId) return {};
|
|
3037
3148
|
return this.workerHeartbeatFields(worker,this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND worker=? AND state='active'").get(id,claimId,worker));
|
|
@@ -3148,14 +3259,15 @@ export class Store {
|
|
|
3148
3259
|
const reservedId=this.admissionReservation(worker)?.request_id;
|
|
3149
3260
|
const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
|
|
3150
3261
|
let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
|
|
3151
|
-
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked, EXISTS(SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=assignments.request_id) stale_pr FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.stale_pr||!!a.blocked&&blocked(a.request_id)}))
|
|
3262
|
+
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked, EXISTS(SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=assignments.request_id) stale_pr,EXISTS(SELECT 1 FROM local_attachment_bindings b WHERE b.work=assignments.request_id) attachment_unqualified FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.attachment_unqualified||!!a.stale_pr||!!a.blocked&&blocked(a.request_id)}))
|
|
3152
3263
|
.sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
|
|
3153
3264
|
.filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
|
|
3154
|
-
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true,...(a.stale_pr?{block_reason:'pr_head_mismatch'}:{})}:triageFields(JSON.parse(a.payload),a))}));
|
|
3265
|
+
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true,...(a.attachment_unqualified?{block_reason:'attachment_recipient_unavailable'}:a.stale_pr?{block_reason:'pr_head_mismatch'}:{})}:triageFields(JSON.parse(a.payload),a))}));
|
|
3155
3266
|
if(batch||handoffExclusions!==null) return assignments;
|
|
3156
3267
|
const messages=this.listMessages(worker).map(({preview,...m})=>({kind:'message',request_id:m.message_id,title:preview,...m})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
|
|
3157
3268
|
const resumes=this.idleClaims(worker).filter(c=>this.protocolListingLive(c.request_id)).map(c=>({kind:'assignment',request_id:c.request_id,resume:true,idle_seconds:Math.floor(this.claimIdleMs(c)/1000),previous_epoch:c.epoch,
|
|
3158
|
-
...(this.db
|
|
3269
|
+
...(hasLocalAttachment(this.db,c.request_id)?{blocked:true,block_reason:'attachment_recipient_unavailable'}:
|
|
3270
|
+
this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
|
|
3159
3271
|
note:'The prior lease expired. Call claim(request_id, claimant, acquisition_id) to request a new epoch after old host work has verifiably stopped. Read progress and owner notes with get first.'}));
|
|
3160
3272
|
return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)||reserveOrder(a,b)).slice(0,50);
|
|
3161
3273
|
}
|
|
@@ -3287,6 +3399,7 @@ export class Store {
|
|
|
3287
3399
|
const old=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
3288
3400
|
if(old&&old.worker!==worker) throw new Error('invalid claim');
|
|
3289
3401
|
this.assertLiveConnection(id,worker,connectionId);
|
|
3402
|
+
this.assertAttachmentRecipientQualified(id);
|
|
3290
3403
|
const laneScope=old?.lane_scope??this.workers.laneScope;
|
|
3291
3404
|
const laneKey=laneScope==='subject'?subject:worker;
|
|
3292
3405
|
const takeover=old?.state==='active';
|
|
@@ -3356,7 +3469,15 @@ export class Store {
|
|
|
3356
3469
|
}
|
|
3357
3470
|
// The one re-grant of an existing claim row: new claim_id and epoch, and every old-epoch field (progress, tool counters, acquisition, lease) reset.
|
|
3358
3471
|
// rotateIdleClaim (claim wake) and resume both call it, so the two paths cannot drift.
|
|
3472
|
+
// Hosted claims attest holder and registered connection, but not an independent
|
|
3473
|
+
// worker destination address, relationship side or attachment materialization.
|
|
3474
|
+
// No runtime adapter qualifies yet, so a reserved/queued ordinary offer must
|
|
3475
|
+
// never be upgraded to a grant for a job bound to a local attachment.
|
|
3476
|
+
assertAttachmentRecipientQualified(id) {
|
|
3477
|
+
if(hasLocalAttachment(this.db,id))throw Object.assign(new Error('attachment_recipient_unavailable'),{code:'attachment_recipient_unavailable'});
|
|
3478
|
+
}
|
|
3359
3479
|
startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs=null) {
|
|
3480
|
+
this.assertAttachmentRecipientQualified(old.request_id);
|
|
3360
3481
|
const id=old.request_id, claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
|
|
3361
3482
|
const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
|
|
3362
3483
|
this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
|
|
@@ -3371,6 +3492,7 @@ export class Store {
|
|
|
3371
3492
|
const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
3372
3493
|
if(!old||old.subject!==subject||a.status!=='claimed') throw new Error('no active claim for this subject');
|
|
3373
3494
|
this.assertLiveConnection(id,old.worker,connectionId);
|
|
3495
|
+
this.assertAttachmentRecipientQualified(id);
|
|
3374
3496
|
this.assertRegrantReady(old);
|
|
3375
3497
|
this.assertWorkerClaimSlot(old.worker,id);
|
|
3376
3498
|
this.assertReservationLane(subject,old.worker,id);
|
|
@@ -3600,9 +3722,23 @@ export class Store {
|
|
|
3600
3722
|
if(this.db.prepare("SELECT 1 FROM lifecycle_events e WHERE e.type IN ('completed','abandoned','cancelled') AND e.at>? AND e.worker=? AND EXISTS(SELECT 1 FROM claims c WHERE c.request_id=e.request_id) LIMIT 1").get(at,worker)) return null;
|
|
3601
3723
|
return iso(Date.parse(at)+capacityHoldMaxMs);
|
|
3602
3724
|
}
|
|
3725
|
+
workerRecovery(id,claimId,subject,worker,connectionId=null) {
|
|
3726
|
+
if(!this.mayAct(worker,id)||this.isProtocolJob(id))return null;
|
|
3727
|
+
const status=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status;
|
|
3728
|
+
if(status==='finished')return projectWorkRecovery(this,id);
|
|
3729
|
+
const grant=claimId?this.liveHeldClaim(id,claimId,subject,worker):null;
|
|
3730
|
+
if(!grant||status!=='claimed')return null;
|
|
3731
|
+
try {this.assertMutationConnection(id,grant,connectionId);}
|
|
3732
|
+
catch {return null;}
|
|
3733
|
+
return projectWorkRecovery(this,id,grant);
|
|
3734
|
+
}
|
|
3603
3735
|
progress(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null,ctx=null,connectionId=null) {
|
|
3604
3736
|
const result=this.transaction(()=>{
|
|
3605
3737
|
if(!this.isProtocolJob(id)) {
|
|
3738
|
+
if(!question&&isRecoveryCheckpoint(note)) {
|
|
3739
|
+
if(blocker)throw new Error('checkpoint must not be a blocker message');
|
|
3740
|
+
return saveWorkCheckpoint(this,{work:id,claimId,subject,worker,connectionId},note);
|
|
3741
|
+
}
|
|
3606
3742
|
this.assertMutationConnection(id,this.assertClaim(id,claimId,subject,worker),connectionId);
|
|
3607
3743
|
return this.progressInTransaction(id,claimId,note,subject,blocker,worker,question);
|
|
3608
3744
|
}
|
|
@@ -3728,6 +3864,7 @@ export class Store {
|
|
|
3728
3864
|
finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence=null,connectionId=null) {
|
|
3729
3865
|
const claim=this.assertFinishClaim(id,claimId,subject,worker);
|
|
3730
3866
|
this.assertMutationConnection(id,claim,connectionId);
|
|
3867
|
+
assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
3731
3868
|
const submittedOutcome=outcome;
|
|
3732
3869
|
({outcome,summary}=this.finishPatchOutcome(id,claimId,outcome,summary));
|
|
3733
3870
|
const old=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
|
|
@@ -3869,7 +4006,52 @@ export class Store {
|
|
|
3869
4006
|
// Cancel only while the row is still queued, in one transaction, so a claim cannot slip in between a check and the cancel.
|
|
3870
4007
|
// Returns the resulting state either way: cancelled:true when this call cancelled it, false when it was already claimed,
|
|
3871
4008
|
// finished or cancelled (the status then says which). A claimed row keeps running; nothing is revoked.
|
|
3872
|
-
|
|
4009
|
+
offerView(id) {
|
|
4010
|
+
const row=this.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(id);
|
|
4011
|
+
if(!row||this.isProtocolJob(id)||this.pullQueue.row(id))return null;
|
|
4012
|
+
if(row.status==='queued') {
|
|
4013
|
+
const prior=this.db.prepare('SELECT claimed_at FROM claims WHERE request_id=?').get(id);
|
|
4014
|
+
if(prior)return {state:'queued',started_at:null,previous_acceptance_at:prior.claimed_at};
|
|
4015
|
+
const reservation=this.admissionReservation(row.target_worker);
|
|
4016
|
+
if(reservation?.request_id===id&&this.admissionOpen()&&!this.paused()&&!this.holdingBreak(row.target_worker)&&
|
|
4017
|
+
!this.capacityHoldUntil(row.target_worker)&&!this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=?').get(id))
|
|
4018
|
+
return {state:'reserved',reserved_until:reservation.expires_at,started_at:null};
|
|
4019
|
+
return {state:'queued',started_at:null};
|
|
4020
|
+
}
|
|
4021
|
+
if(row.status!=='claimed')return {state:'terminal',status:row.status};
|
|
4022
|
+
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
4023
|
+
if(!claim||this.leaseExpired(claim)) return {state:'unresolved',status:'claimed',started_at:null};
|
|
4024
|
+
const start=this.db.prepare('SELECT at FROM offer_start_evidence WHERE request_id=? AND epoch=?').get(id,claim.epoch);
|
|
4025
|
+
return {state:start?'started':'accepted',claim_epoch:claim.epoch,accepted_at:claim.claimed_at,
|
|
4026
|
+
started_at:start?.at??null,...(start?{start_source:'successful_fenced_workspace_operation'}:{})};
|
|
4027
|
+
}
|
|
4028
|
+
cancelIfQueued(id,{key,owner}={}) { return this.transaction(() => {
|
|
4029
|
+
if(key===undefined)return this.cancelIfQueuedInTransaction(id);
|
|
4030
|
+
this.owner(id,owner);
|
|
4031
|
+
if(typeof key!=='string'||!key||key.length>128)throw new Error('invalid withdrawal command key');
|
|
4032
|
+
if(this.isProtocolJob(id)||this.pullQueue.row(id))throw new Error('keyed offer withdrawal requires an ordinary assignment');
|
|
4033
|
+
const prior=this.db.prepare('SELECT * FROM offer_withdraw_receipts WHERE request_id=?').get(id);
|
|
4034
|
+
const keyDigest=hash(key), ownerDigest=hash(owner);
|
|
4035
|
+
if(prior) {
|
|
4036
|
+
if(prior.key_digest!==keyDigest||prior.owner_digest!==ownerDigest)throw new Error('KEY_CONFLICT: withdrawal key changed');
|
|
4037
|
+
return JSON.parse(prior.receipt);
|
|
4038
|
+
}
|
|
4039
|
+
const view=this.offerView(id);
|
|
4040
|
+
// A claim can end and release its lane without proving the worker stopped.
|
|
4041
|
+
const requeuedAfterAcceptance=view?.previous_acceptance_at!=null;
|
|
4042
|
+
const result=requeuedAfterAcceptance
|
|
4043
|
+
?{request_id:id,status:'queued',cancelled:false}
|
|
4044
|
+
:this.cancelIfQueuedInTransaction(id);
|
|
4045
|
+
const disposition=result.cancelled?'withdrawn_while_queued':
|
|
4046
|
+
view?.state==='accepted'||view?.state==='started'||requeuedAfterAcceptance?'already_accepted':
|
|
4047
|
+
view?.state==='unresolved'?'acceptance_unresolved':'already_terminal';
|
|
4048
|
+
const receipt={...result,disposition,offer_at_decision:view};
|
|
4049
|
+
this.db.prepare('INSERT INTO offer_withdraw_receipts VALUES(?,?,?,?)')
|
|
4050
|
+
.run(id,keyDigest,ownerDigest,JSON.stringify(receipt));
|
|
4051
|
+
return receipt;
|
|
4052
|
+
}); }
|
|
4053
|
+
cancelIfQueuedInTransaction(id) {
|
|
4054
|
+
if(!this.db.isTransaction)throw new Error('transaction_required');
|
|
3873
4055
|
const pendingWork=this.pullQueue.row(id);
|
|
3874
4056
|
if(pendingWork&&!pendingWork.child_request_id) {const status=this.pullQueue.project(pendingWork).status;if(status!=='queued')return {request_id:id,status,cancelled:false};return {...this.pullQueue.cancel(id),cancelled:true};}
|
|
3875
4057
|
this.assertProtocolAvailable(id);
|
|
@@ -3883,7 +4065,7 @@ export class Store {
|
|
|
3883
4065
|
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
3884
4066
|
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
3885
4067
|
return {request_id:id,status:'cancelled',cancelled:true};
|
|
3886
|
-
}
|
|
4068
|
+
}
|
|
3887
4069
|
// Lease sweep: a claim whose lease ran out with no claim activity is abandoned (actor system, reason lease_expired) through the
|
|
3888
4070
|
// same path as `dalan abandon`, so the row is requeued and its lane is free at once. Before this, an expired lease only
|
|
3889
4071
|
// let another claimant take the item over, and a dead claim held its lane for as long as nobody did. A usage break neither holds
|
|
@@ -4187,6 +4369,7 @@ export class Store {
|
|
|
4187
4369
|
// revised job's result is never recorded accepted or applied. A refused takeover of an open reservation records nothing.
|
|
4188
4370
|
reserveApply(id) {
|
|
4189
4371
|
const result=this.transaction(() => {
|
|
4372
|
+
assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
4190
4373
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
4191
4374
|
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|
|
4192
4375
|
const open=this.db.prepare("SELECT reserved_at FROM apply_reservations WHERE request_id=? AND state='applying'").get(id);
|
|
@@ -4226,6 +4409,7 @@ export class Store {
|
|
|
4226
4409
|
return {request_id:id,state:'released'};
|
|
4227
4410
|
}); }
|
|
4228
4411
|
recordDecision(id,decision,{note=null,actor='owner',via='cli',fenced=false}={}) {
|
|
4412
|
+
if(actor==='owner'&&(decision==='accepted'||decision==='applied'))assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
4229
4413
|
if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
|
|
4230
4414
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
4231
4415
|
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|
package/src/tool-registry.mjs
CHANGED
|
@@ -80,6 +80,18 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
|
|
|
80
80
|
const scope = grantScope(grant);
|
|
81
81
|
return scope && Date.parse(scope.expires_at) > now() ? grant : null;
|
|
82
82
|
};
|
|
83
|
+
const authorizedGrant = (row, worker, args) => {
|
|
84
|
+
const grant = currentGrant(row, worker);
|
|
85
|
+
if (!grant) return null;
|
|
86
|
+
const scope = grant.worker === scopedGrantWorker(worker) ? grantScope(grant) : null;
|
|
87
|
+
if (scope && !handlerFor(row).authorizeGrant(scope, args)) return null;
|
|
88
|
+
return { scope };
|
|
89
|
+
};
|
|
90
|
+
function hasScopedReadGrant(tool, worker, args) {
|
|
91
|
+
const row = getTool(tool);
|
|
92
|
+
return !!row && row.enabled === 1 && toolClass(row) === 'read' &&
|
|
93
|
+
authorizedGrant(row, worker, args)?.scope != null;
|
|
94
|
+
}
|
|
83
95
|
const callerHash = (row, worker) => sha256(canonical({
|
|
84
96
|
name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), handler: JSON.parse(row.handler),
|
|
85
97
|
caller: worker, grants: db.prepare('SELECT tool,scope FROM tool_grants WHERE worker IN (?,?) ORDER BY tool,worker')
|
|
@@ -283,10 +295,9 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
|
|
|
283
295
|
const stale = () => ({ outcome: 'stale_registry', error: new RegistryError('stale_registry', 'call list_tools again') });
|
|
284
296
|
const authorize = (current, previousHash) => {
|
|
285
297
|
if (!current || JSON.parse(current.handler).kind === 't3_control') return unavailable('unknown_tool');
|
|
286
|
-
const grant =
|
|
298
|
+
const grant = authorizedGrant(current, name, args);
|
|
287
299
|
if (!grant) return unavailable('not_granted');
|
|
288
|
-
const scope = grant
|
|
289
|
-
if (scope && !handlerFor(current).authorizeGrant(scope, args)) return unavailable('not_granted');
|
|
300
|
+
const { scope } = grant;
|
|
290
301
|
if (current.enabled !== 1) return unavailable('disabled');
|
|
291
302
|
const cls = toolClass(current);
|
|
292
303
|
if (callClass !== cls) return { outcome: 'wrong_class', error: new RegistryError('wrong_class', 'wrong class for this tool; see list_tools') };
|
|
@@ -507,7 +518,7 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
|
|
|
507
518
|
return {...row,worker:publicGrantWorker(row.worker),scope,expires_at:scope?.expires_at??null};
|
|
508
519
|
});
|
|
509
520
|
}
|
|
510
|
-
return { register, remove, grant, revoke, list, listGrants, listTools, hasWorkerTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, initializeWorkerTools, t3Threads };
|
|
521
|
+
return { register, remove, grant, revoke, list, listGrants, listTools, hasWorkerTools, registryVersion, callTool, hasScopedReadGrant, setEnabled, lastChange, initializeT3Grants, initializeWorkerTools, t3Threads };
|
|
511
522
|
}
|
|
512
523
|
|
|
513
524
|
// ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { artifactSecretRule, hasCredentialFieldText, hasSecretContent, redactOutput } from './redaction.mjs';
|
|
3
|
+
import { localAttachmentPublicationRestriction } from './local-attachment-result.mjs';
|
|
4
|
+
|
|
5
|
+
const prefix='CHECKPOINT v1: ';
|
|
6
|
+
export const isRecoveryCheckpoint=note=>typeof note==='string'&¬e.startsWith(prefix);
|
|
7
|
+
const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
8
|
+
const fail=code=>{throw Object.assign(new Error(code),{code});};
|
|
9
|
+
const id=v=>typeof v==='string'&&/^art_[A-Za-z0-9_-]{8,128}$/.test(v);
|
|
10
|
+
|
|
11
|
+
export function migrateWorkRecovery(db) {
|
|
12
|
+
db.exec(`CREATE TABLE IF NOT EXISTS work_checkpoints(
|
|
13
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
14
|
+
request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
15
|
+
worker TEXT NOT NULL, epoch INTEGER NOT NULL, operation TEXT NOT NULL, intent TEXT NOT NULL,
|
|
16
|
+
summary TEXT NOT NULL, artifact_refs TEXT NOT NULL, accepted_at TEXT NOT NULL,
|
|
17
|
+
UNIQUE(request_id,epoch,operation)
|
|
18
|
+
);
|
|
19
|
+
CREATE INDEX IF NOT EXISTS work_checkpoint_latest ON work_checkpoints(request_id,worker,seq);`);
|
|
20
|
+
}
|
|
21
|
+
function parse(note) {
|
|
22
|
+
let value;
|
|
23
|
+
try { value=JSON.parse(note.slice(prefix.length)); } catch { fail('invalid_work_checkpoint'); }
|
|
24
|
+
if(!value||Object.keys(value).sort().join(',')!=='artifact_ids,key,summary'||
|
|
25
|
+
typeof value.key!=='string'||!/^[A-Za-z0-9_-]{1,80}$/.test(value.key)||
|
|
26
|
+
typeof value.summary!=='string'||!value.summary.trim()||Buffer.byteLength(value.summary)>2048||
|
|
27
|
+
/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value.summary)||
|
|
28
|
+
!Array.isArray(value.artifact_ids)||value.artifact_ids.length>4||
|
|
29
|
+
value.artifact_ids.some(v=>!id(v))||new Set(value.artifact_ids).size!==value.artifact_ids.length)
|
|
30
|
+
fail('invalid_work_checkpoint');
|
|
31
|
+
if(hasSecretContent(value.summary)||hasCredentialFieldText(value.summary)||artifactSecretRule(Buffer.from(value.summary)))
|
|
32
|
+
fail('work_checkpoint_withheld');
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
export function saveWorkCheckpoint(store,context,note) {
|
|
36
|
+
const {db}=store;
|
|
37
|
+
if(!db.isTransaction)fail('transaction_required');
|
|
38
|
+
const {work,claimId,subject,worker,connectionId}=context;
|
|
39
|
+
const claim=store.assertClaim(work,claimId,subject,worker);
|
|
40
|
+
store.assertMutationConnection(work,claim,connectionId);
|
|
41
|
+
if(db.prepare('SELECT status FROM assignments WHERE request_id=?').get(work)?.status!=='claimed')
|
|
42
|
+
fail('work_checkpoint_not_active');
|
|
43
|
+
const value=parse(note);
|
|
44
|
+
const intent=digest(JSON.stringify([value.summary,value.artifact_ids]));
|
|
45
|
+
const previous=db.prepare('SELECT seq,intent,accepted_at FROM work_checkpoints WHERE request_id=? AND epoch=? AND operation=?')
|
|
46
|
+
.get(work,claim.epoch,value.key);
|
|
47
|
+
if(previous) {
|
|
48
|
+
if(previous.intent!==intent)fail('work_checkpoint_key_conflict');
|
|
49
|
+
return {recorded:true,checkpoint:{sequence:previous.seq,accepted_at:previous.accepted_at,epoch:claim.epoch},duplicate:true};
|
|
50
|
+
}
|
|
51
|
+
const sealed=db.prepare("SELECT id,sha256,size FROM artifacts WHERE request_id=? AND id=? AND kind='upload' AND sealed=1 AND origin_claim_id=? AND origin_epoch=?");
|
|
52
|
+
const artifacts=value.artifact_ids.map(ref=>{
|
|
53
|
+
const found=sealed.get(work,ref,claimId,claim.epoch);
|
|
54
|
+
if(!found||!/^[a-f0-9]{64}$/.test(found.sha256??'')||!Number.isSafeInteger(found.size)||found.size<0)
|
|
55
|
+
fail('work_checkpoint_artifact_not_bound');
|
|
56
|
+
return {artifact_id:found.id,sha256:found.sha256,size:found.size};
|
|
57
|
+
});
|
|
58
|
+
const accepted_at=store.stamp();
|
|
59
|
+
const saved=db.prepare('INSERT INTO work_checkpoints(request_id,worker,epoch,operation,intent,summary,artifact_refs,accepted_at) VALUES(?,?,?,?,?,?,?,?)')
|
|
60
|
+
.run(work,worker,claim.epoch,value.key,intent,value.summary,JSON.stringify(artifacts),accepted_at);
|
|
61
|
+
// Keep the ordinary progress log useful without duplicating private checkpoint
|
|
62
|
+
// content into the unfenced legacy get projection or its notifications.
|
|
63
|
+
store.progressInTransaction(work,claimId,'A continuation checkpoint was accepted.',subject,false,worker);
|
|
64
|
+
return {recorded:true,checkpoint:{sequence:Number(saved.lastInsertRowid),accepted_at,epoch:claim.epoch},duplicate:false};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const priorMaxBytes=8*1024;
|
|
68
|
+
function priorWorkReference(store,work,grant) {
|
|
69
|
+
const {db}=store;
|
|
70
|
+
// A mere common worker, shared policy relationship, request string, or
|
|
71
|
+
// copied brief has no disclosure authority. Only the sealed follow edge
|
|
72
|
+
// under the same continuing handle is considered.
|
|
73
|
+
const edge=db.prepare(`SELECT f.prior_id,a.relationship_id,p.relationship_id AS prior_relationship,
|
|
74
|
+
a.target_worker,p.target_worker AS prior_worker,p.status AS prior_status,
|
|
75
|
+
r.counterpart_ref,r.ended_at
|
|
76
|
+
FROM job_follows f
|
|
77
|
+
JOIN assignments a ON a.request_id=f.request_id
|
|
78
|
+
JOIN assignments p ON p.request_id=f.prior_id
|
|
79
|
+
JOIN continuing_subagent_jobs c ON c.request_id=f.request_id
|
|
80
|
+
JOIN continuing_subagent_jobs d ON d.request_id=f.prior_id AND d.subagent_id=c.subagent_id
|
|
81
|
+
LEFT JOIN relationships r ON r.relationship_id=a.relationship_id
|
|
82
|
+
WHERE f.request_id=?`).get(work);
|
|
83
|
+
if(!edge)return undefined;
|
|
84
|
+
const omit=reason=>({kind:'prior_result_omitted',reason,runtime_state:'not_resumed'});
|
|
85
|
+
if(!edge.relationship_id||edge.relationship_id!==edge.prior_relationship||edge.ended_at!==null||
|
|
86
|
+
edge.counterpart_ref!==grant.worker||edge.target_worker!==grant.worker||edge.prior_worker!==grant.worker||
|
|
87
|
+
typeof grant.connection_id!=='string'||!grant.connection_id)
|
|
88
|
+
return omit('recipient_unavailable');
|
|
89
|
+
// The same exact recipient can reuse a result from a selected text brief.
|
|
90
|
+
// A repository snapshot still requires its own disclosure binding.
|
|
91
|
+
if(localAttachmentPublicationRestriction(db,work,{includeLocalText:false}))
|
|
92
|
+
return omit('unpublished_lineage_withheld');
|
|
93
|
+
const receipt=db.prepare(`SELECT p.request_id,p.receipt_id,p.claim_id,p.summary,p.result,p.outcome,
|
|
94
|
+
p.created_at,c.subject,c.worker,c.connection_id
|
|
95
|
+
FROM reports p JOIN claims c ON c.request_id=p.request_id AND c.claim_id=p.claim_id
|
|
96
|
+
WHERE p.request_id=? AND p.late=0`).get(edge.prior_id);
|
|
97
|
+
if(edge.prior_status!=='finished'||!receipt||receipt.outcome!=='completed'||
|
|
98
|
+
typeof receipt.summary!=='string'||typeof receipt.result!=='string'||!receipt.result.length)
|
|
99
|
+
return omit('unavailable');
|
|
100
|
+
if(receipt.worker!==grant.worker||receipt.subject!==grant.subject||receipt.connection_id!==grant.connection_id)
|
|
101
|
+
return omit('recipient_unavailable');
|
|
102
|
+
const maxGate=Buffer.byteLength(receipt.summary)+Buffer.byteLength(receipt.result);
|
|
103
|
+
if(maxGate>priorMaxBytes)return omit('size_limit');
|
|
104
|
+
const source={summary:receipt.summary,result:receipt.result};
|
|
105
|
+
if(hasSecretContent(source)||Object.values(source).some(text=>hasCredentialFieldText(text)||
|
|
106
|
+
artifactSecretRule(Buffer.from(text))||text.includes('[redacted secret]'))||
|
|
107
|
+
JSON.stringify(redactOutput(source))!==JSON.stringify(source))
|
|
108
|
+
return omit('redaction');
|
|
109
|
+
try {
|
|
110
|
+
if(!store.liveHeldClaim(work,grant.claim_id,grant.subject,grant.worker))return undefined;
|
|
111
|
+
store.assertMutationConnection(work,grant,grant.connection_id);
|
|
112
|
+
} catch {return undefined;}
|
|
113
|
+
const hasArtifacts=!!db.prepare('SELECT 1 FROM artifacts WHERE request_id=? AND sealed=1 LIMIT 1').get(edge.prior_id);
|
|
114
|
+
return {kind:'prior_result_reference',request_id:receipt.request_id,receipt_id:receipt.receipt_id,
|
|
115
|
+
issuer:'worker_report_accepted',...source,runtime_state:'not_resumed',
|
|
116
|
+
...(hasArtifacts?{omissions:['artifact_delivery_not_verified']}:{}),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function projectWorkRecovery(store,work,grant=null) {
|
|
121
|
+
const {db}=store;
|
|
122
|
+
const status=db.prepare('SELECT status FROM assignments WHERE request_id=?').get(work)?.status;
|
|
123
|
+
if(status==='finished'){
|
|
124
|
+
const receipt=db.prepare('SELECT receipt_id,outcome FROM reports WHERE request_id=?').get(work);
|
|
125
|
+
return receipt?{kind:'completed_result',...receipt}:{kind:'completed_result_unavailable'};
|
|
126
|
+
}
|
|
127
|
+
if(!status||status==='cancelled')return null;
|
|
128
|
+
const latest=grant?db.prepare('SELECT * FROM work_checkpoints WHERE request_id=? AND worker=? AND epoch<=? ORDER BY seq DESC LIMIT 1')
|
|
129
|
+
.get(work,grant.worker,grant.epoch):null;
|
|
130
|
+
const questionRows=grant?db.prepare('SELECT question_id,epoch,purpose FROM job_questions WHERE request_id=? AND worker=? AND answered_at IS NULL ORDER BY rowid DESC LIMIT 12')
|
|
131
|
+
.all(work,grant.worker):[];
|
|
132
|
+
const present=db.prepare('SELECT 1 FROM artifacts WHERE request_id=? AND id=? AND sealed=1 AND sha256=? AND size=?');
|
|
133
|
+
const artifacts=latest?JSON.parse(latest.artifact_refs).map(a=>({...a,
|
|
134
|
+
availability:present.get(work,a.artifact_id,a.sha256,a.size)?'owner_artifact_lookup_required':'retained_artifact_unavailable'})):[];
|
|
135
|
+
const predecessor=grant?priorWorkReference(store,work,grant):undefined;
|
|
136
|
+
return {kind:'open_work',claim_epoch:grant?.epoch??null,...(predecessor?{predecessor}:{}),
|
|
137
|
+
prior_runtime_stop:'not_observed_by_bridge_lease',
|
|
138
|
+
checkpoint:latest?{summary:latest.summary,accepted_at:latest.accepted_at,epoch:latest.epoch,sequence:latest.seq,
|
|
139
|
+
evidence:'worker_report_accepted',artifacts}:null,
|
|
140
|
+
context_availability:!grant?'current_claim_required':latest?'checkpoint_only_no_runtime_state':'no_accepted_checkpoint',
|
|
141
|
+
questions:questionRows.map(({question_id,epoch,purpose})=>({question_id,purpose,epoch,
|
|
142
|
+
state:epoch===grant.epoch?'open':'requires_new_question'}))};
|
|
143
|
+
}
|
package/src/worker-runs.mjs
CHANGED
|
@@ -33,3 +33,28 @@ export function parseWorkerSession(session, nowMs) {
|
|
|
33
33
|
if (end - start > SESSION_MAX_MS) throw new Error('invalid session: longer than 24 hours is not a hosted session');
|
|
34
34
|
return { started_at: new Date(start).toISOString(), ended_at: new Date(end).toISOString(), duration_ms: end - start };
|
|
35
35
|
}
|
|
36
|
+
|
|
37
|
+
// Requester views reuse stored, redacted evidence. Keep the raw bounded record in get --json;
|
|
38
|
+
// display only a small inert preview so a worker tail cannot create new report headings.
|
|
39
|
+
const RUN_PREVIEW_BYTES = 512;
|
|
40
|
+
const quoteText = value => JSON.stringify(value).replace(/[\u007f-\u009f\u2028\u2029]/gu,
|
|
41
|
+
c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
|
|
42
|
+
const oneLine = value => /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value) ? quoteText(value) : value;
|
|
43
|
+
|
|
44
|
+
export function workerRunEvidenceLines(row) {
|
|
45
|
+
const runs = (row.worker_runs ?? []).slice(0, WORKER_RUNS_MAX);
|
|
46
|
+
const lines = [];
|
|
47
|
+
if ((runs.length || row.worker_run_limit) && row.report?.receipt_id)
|
|
48
|
+
lines.push(`Result receipt: ${oneLine(row.report.receipt_id)}`);
|
|
49
|
+
if (runs.length) {
|
|
50
|
+
lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.map(run => `${oneLine(run.command)} exit ${run.exit_code}`).join('; ')}`);
|
|
51
|
+
runs.forEach((run, index) => {
|
|
52
|
+
if (!run.output_tail) return;
|
|
53
|
+
const bytes = Buffer.from(run.output_tail);
|
|
54
|
+
const preview = bytes.subarray(Math.max(0, bytes.length - RUN_PREVIEW_BYTES)).toString();
|
|
55
|
+
lines.push(` output ${index + 1} (quoted worker data${bytes.length > RUN_PREVIEW_BYTES ? '; tail preview truncated' : ''}): ${quoteText(preview)}`);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${oneLine(row.worker_run_limit)}`);
|
|
59
|
+
return lines;
|
|
60
|
+
}
|