@tnunamak/dalan 0.6.2 → 0.8.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 +53 -0
- package/CONTRIBUTING.md +4 -0
- package/PROTOCOL.md +2 -0
- package/README.md +81 -84
- package/bin/dalan.mjs +9 -0
- package/bin/dot-worker.mjs +29 -4
- package/contracts/adapter-qualification.schema.json +170 -0
- package/docs/chatgpt-worker-onboarding.md +10 -14
- package/docs/claude-worker-onboarding.md +9 -8
- package/docs/codex-to-muse.md +21 -35
- package/docs/connect-chatgpt.md +10 -16
- package/docs/dalan-upgrade.md +4 -2
- package/docs/local-agent-mcp.md +24 -4
- package/docs/local-agent-requester.md +46 -0
- package/docs/manual-setup.md +2 -2
- package/docs/operations.md +12 -13
- package/docs/pull-workers.md +1 -2
- package/docs/service-setup.md +110 -163
- package/docs/setup-reference.md +6 -6
- package/docs/t3-question-relationship.md +43 -0
- package/docs/t3-reverse-control.md +12 -8
- package/docs/t3-wake-fence-r4.md +42 -0
- package/docs/test-suite-isolation.md +204 -0
- package/docs/worker-clients.md +6 -4
- package/package.json +5 -3
- package/qualification/README.md +13 -0
- package/qualification/mcp.json +121 -0
- package/qualification/protocol-v0.json +127 -0
- package/scripts/dalan-try-selfcheck.mjs +8 -7
- package/scripts/worker-bridge-setup.mjs +91 -81
- package/src/admin-socket.mjs +2 -1
- package/src/answer-journal.mjs +200 -0
- package/src/as-store.mjs +5 -3
- package/src/as.mjs +35 -26
- package/src/auth-check.mjs +59 -0
- package/src/cli-help.mjs +16 -16
- package/src/client-approval.mjs +57 -0
- package/src/client-convenience.mjs +166 -0
- package/src/client-conveniences.json +106 -0
- package/src/client-conveniences.schema.json +97 -0
- package/src/connect-cli.mjs +5 -5
- package/src/default-home.mjs +36 -0
- package/src/destinations/index.mjs +6 -0
- package/src/destinations/none.mjs +3 -0
- package/src/destinations/t3.mjs +63 -6
- package/src/execution.mjs +20 -2
- package/src/follow-current.mjs +27 -0
- package/src/gozar-routes.mjs +315 -0
- package/src/host-budget.mjs +17 -11
- package/src/host-execution-policy.mjs +2 -2
- package/src/host-stop-reverify.mjs +6 -4
- package/src/integrator.mjs +3 -1
- package/src/redirect-policy.mjs +61 -0
- package/src/route-setting.mjs +71 -12
- package/src/server.mjs +64 -12
- package/src/service-auto-update.mjs +8 -1
- package/src/service-launchd.mjs +186 -0
- package/src/service-migrate-workers.mjs +12 -2
- package/src/service-update-runtime.mjs +40 -6
- package/src/service-update.mjs +20 -14
- package/src/service.mjs +211 -63
- package/src/setup.mjs +55 -44
- package/src/store.mjs +77 -14
- package/src/submission-policy.mjs +8 -4
- package/src/t3.mjs +21 -2
- package/src/tool-registry.mjs +54 -8
- package/src/try-exposure.mjs +7 -657
- package/src/try-hosted.mjs +71 -101
- package/src/try-selfcheck.mjs +15 -8
- package/src/try.mjs +9 -13
- package/src/workers.mjs +4 -3
- package/src/workspace.mjs +94 -15
- package/scripts/lib/expose-tailscale.mjs +0 -408
- package/src/try-hosted-clients.mjs +0 -46
package/src/store.mjs
CHANGED
|
@@ -50,7 +50,7 @@ function waiterOwnerGone(attemptId) {
|
|
|
50
50
|
return !!(owner.boot&&owner.start&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
const SUPPORTED_SCHEMA_VERSION =
|
|
53
|
+
const SUPPORTED_SCHEMA_VERSION = 69;
|
|
54
54
|
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
55
55
|
function systemBootId() {
|
|
56
56
|
if(process.platform!=='linux') return null;
|
|
@@ -68,6 +68,8 @@ export function validateProtocol(value) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
const questionError=(code,message)=>Object.assign(new Error(`${code}: ${message}`),{code});
|
|
71
|
+
// A purpose other than clarification marks a question only a human may answer. SQLite cannot change a CHECK in place, so the schema 67 list below is the whole set.
|
|
72
|
+
export const QUESTION_PURPOSES=['clarification','human_decision','authentication','tool_permission'];
|
|
71
73
|
function validateQuestion(questionId,text) {
|
|
72
74
|
if(typeof questionId!=='string'||!/^[A-Za-z0-9_.:-]{1,128}$/.test(questionId)) throw new Error('invalid question_id');
|
|
73
75
|
if(arguments.length>1&&(typeof text!=='string'||!text.trim()||Buffer.byteLength(text)>4096)) throw new Error('question text must be 1-4096 UTF-8 bytes');
|
|
@@ -108,7 +110,7 @@ const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.
|
|
|
108
110
|
function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
|
|
109
111
|
return hash(JSON.stringify(canonical({payload:identity,delivery,environmentId:environmentId??'',review:!!review,priority,meta:storedMeta(normalizeMeta(meta),legacyFixNames),targetWorker,execution,requiredCapabilities,...(destinationRevision===null?{}:{destination_revision:destinationRevision})})));
|
|
110
112
|
}
|
|
111
|
-
const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,leaseMs:3600000,laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
|
|
113
|
+
const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,claimIdleWarningMs:900000,leaseMs:3600000,laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
|
|
112
114
|
const HOUR=3600000, iso=ms=>new Date(ms).toISOString();
|
|
113
115
|
export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
|
|
114
116
|
const queueKindSql=canonicalKindSql("COALESCE(a.task_kind,json_extract(a.payload,'$.task_kind'),CASE WHEN a.review=1 THEN 'review' ELSE json_extract(a.payload,'$.execution_scope') END,'unknown')");
|
|
@@ -155,6 +157,9 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
|
|
|
155
157
|
if(!Number.isInteger(intervalMs)||intervalMs<60000||intervalMs>86400000) throw new Error('invalid assignment_reannounce_interval_ms');
|
|
156
158
|
if(!Number.isInteger(maxCount)||maxCount<0||maxCount>10) throw new Error('invalid assignment_reannounce_max_count');
|
|
157
159
|
const silenceMs=value.pause_suspected_silence_ms??defaultRedeliveryLimits.silenceMs;
|
|
160
|
+
// Observational warning only: independent of lease expiry, takeover and cancellation.
|
|
161
|
+
const claimIdleWarningMs=value.claim_idle_warning_ms??defaultRedeliveryLimits.claimIdleWarningMs;
|
|
162
|
+
if(!Number.isInteger(claimIdleWarningMs)||claimIdleWarningMs<60000||claimIdleWarningMs>604800000) throw new Error('invalid claim_idle_warning_ms');
|
|
158
163
|
// A claim lease expires at last claim activity + leaseMs. stale_claim_ms is the legacy name, read only when claim_lease_ms is absent.
|
|
159
164
|
const leaseKey=value.claim_lease_ms!=null?'claim_lease_ms':value.stale_claim_ms!=null?'stale_claim_ms':null;
|
|
160
165
|
const leaseMs=leaseKey?value[leaseKey]:defaultRedeliveryLimits.leaseMs;
|
|
@@ -191,7 +196,7 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
|
|
|
191
196
|
if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
|
|
192
197
|
const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
|
|
193
198
|
if(!Number.isInteger(maxResponseBytesPer24h)||maxResponseBytesPer24h<1000000||maxResponseBytesPer24h>10000000000) throw new Error('invalid max_response_bytes_per_24h');
|
|
194
|
-
return {intervalMs,maxCount,silenceMs,leaseMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
|
|
199
|
+
return {intervalMs,maxCount,silenceMs,claimIdleWarningMs,leaseMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
|
|
195
200
|
}
|
|
196
201
|
|
|
197
202
|
// Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
|
|
@@ -924,6 +929,25 @@ export class Store {
|
|
|
924
929
|
this.db.exec('PRAGMA user_version=65;');
|
|
925
930
|
}
|
|
926
931
|
if(version<66) { migratePullQueue(this.db); this.db.exec('PRAGMA user_version=66;'); }
|
|
932
|
+
if(version<67) {
|
|
933
|
+
// What a question asks for. Every row that exists now is a clarification, the only kind before this step.
|
|
934
|
+
// A historical fixture that dropped the post-54 tables has no job_questions to alter; every real database has one.
|
|
935
|
+
if(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='job_questions'").get()&&!this.db.prepare("SELECT 1 FROM pragma_table_info('job_questions') WHERE name='purpose'").get()) this.db.exec("ALTER TABLE job_questions ADD COLUMN purpose TEXT NOT NULL DEFAULT 'clarification' CHECK(purpose IN ('clarification','human_decision','authentication','tool_permission'))");
|
|
936
|
+
this.db.exec('PRAGMA user_version=67;');
|
|
937
|
+
}
|
|
938
|
+
if(version<68) {
|
|
939
|
+
// The parent generation a destination recorded when the job was submitted. One opaque string: the destination
|
|
940
|
+
// module writes it (capture) and reads it (readGeneration); the Store never parses it. NULL means none was recorded
|
|
941
|
+
// (older rows, delivery none, policy-queue jobs).
|
|
942
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='parent_generation'").get()) this.db.exec('ALTER TABLE assignments ADD COLUMN parent_generation TEXT');
|
|
943
|
+
// The kind a notification had before a held parent moved it into the wait queue. Set only by holdDelivery.
|
|
944
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('notifications') WHERE name='held_kind'").get()) this.db.exec('ALTER TABLE notifications ADD COLUMN held_kind TEXT');
|
|
945
|
+
this.db.exec('PRAGMA user_version=68;');
|
|
946
|
+
}
|
|
947
|
+
if(version<69) {
|
|
948
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_grants') WHERE name='scope'").get()) this.db.exec('ALTER TABLE tool_grants ADD COLUMN scope TEXT');
|
|
949
|
+
this.db.exec('PRAGMA user_version=69;');
|
|
950
|
+
}
|
|
927
951
|
// Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
|
|
928
952
|
// spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
|
|
929
953
|
this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
|
|
@@ -1246,7 +1270,7 @@ export class Store {
|
|
|
1246
1270
|
}
|
|
1247
1271
|
// identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
|
|
1248
1272
|
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1249
|
-
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) {
|
|
1273
|
+
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) {
|
|
1250
1274
|
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1251
1275
|
if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
|
|
1252
1276
|
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
@@ -1299,6 +1323,7 @@ export class Store {
|
|
|
1299
1323
|
if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
|
|
1300
1324
|
// The target is a column, not payload: an omitted worker means 'dot'.
|
|
1301
1325
|
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) 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);
|
|
1326
|
+
if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
|
|
1302
1327
|
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());
|
|
1303
1328
|
const requestedValidUntil=validUntilOf(payload);
|
|
1304
1329
|
const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
|
|
@@ -1555,8 +1580,16 @@ export class Store {
|
|
|
1555
1580
|
const calls=this.db.prepare('SELECT max(last_call_at) call, max(last_list_pending_at) list FROM worker_activity WHERE worker=?').get(worker);
|
|
1556
1581
|
const lastCall=calls.call??null, lastList=calls.list??null;
|
|
1557
1582
|
const silence=lastCall?age(lastCall):Infinity;
|
|
1558
|
-
const claims=this.db.prepare("SELECT c.subject,c.worker,c.lane_key,c.lane_scope,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,c.last_progress_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker);
|
|
1559
|
-
|
|
1583
|
+
const claims=this.db.prepare("SELECT c.request_id,c.subject,c.worker,c.lane_key,c.lane_scope,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,c.last_progress_at,c.last_tool_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker);
|
|
1584
|
+
// Activity warnings are not lease expiry. Renewals and post-start holds must
|
|
1585
|
+
// not hide a silent claim; only progress or assignment-specific tool activity
|
|
1586
|
+
// refreshes this observation. claimed_at is the fallback for a new grant.
|
|
1587
|
+
const idleThresholdMs=limits.claimIdleWarningMs??defaultRedeliveryLimits.claimIdleWarningMs;
|
|
1588
|
+
const staleClaims=claims.map(c=>{
|
|
1589
|
+
const times=[c.claimed_at,c.last_progress_at,c.last_tool_at].map(t=>Date.parse(t)).filter(Number.isFinite);
|
|
1590
|
+
const last=times.length?Math.max(...times):now;
|
|
1591
|
+
return {request_id:c.request_id,idle_ms:Math.max(0,now-last),last_progress_at:c.last_progress_at??null,last_tool_at:c.last_tool_at??null};
|
|
1592
|
+
}).filter(c=>c.idle_ms>=idleThresholdMs).sort((a,b)=>b.idle_ms-a.idle_ms||a.request_id.localeCompare(b.request_id));
|
|
1560
1593
|
const liveSubs=this.activeSubscriptions().filter(sub=>sub.worker===worker);
|
|
1561
1594
|
const liveClaims=liveSubs.flatMap(sub=>this.activeClaims(sub.principal,sub.worker));
|
|
1562
1595
|
const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
|
|
@@ -1583,7 +1616,7 @@ export class Store {
|
|
|
1583
1616
|
oldest_claim_progress_age_ms:claims.length?Math.max(...claims.map(c=>age(c.last_progress_at??c.claimed_at))):null,
|
|
1584
1617
|
last_worker_call_at:lastCall,last_list_pending_at:lastList,
|
|
1585
1618
|
oldest_unclaimed_event_2xx_age_ms:ages.length?Math.max(...ages):null,
|
|
1586
|
-
queue_classes:queueClasses,stale_claims:{count:staleClaims.length,max_idle_ms:staleClaims
|
|
1619
|
+
queue_classes:queueClasses,stale_claims:{count:staleClaims.length,max_idle_ms:staleClaims[0]?.idle_ms??null,threshold_ms:idleThresholdMs,items:staleClaims.slice(0,20)},
|
|
1587
1620
|
worker_silence_ms:Number.isFinite(silence)?silence:null,unclaimed_after_reannounce:this.unclaimedAfterReannounce(limits,worker),items
|
|
1588
1621
|
};
|
|
1589
1622
|
}
|
|
@@ -1861,8 +1894,11 @@ export class Store {
|
|
|
1861
1894
|
return activity<this.startedMs&&this.nowMs()<this.startedMs+this.claimLeaseMs(claim);
|
|
1862
1895
|
}
|
|
1863
1896
|
leaseExpired(claim) {
|
|
1897
|
+
// Missing or malformed persisted deadlines carry no authority, even with a same-boot clock.
|
|
1898
|
+
const persistedDeadline=Date.parse(claim.lease_deadline_at);
|
|
1899
|
+
if(!Number.isFinite(persistedDeadline)) return true;
|
|
1864
1900
|
const deadline=this.leaseMonotonicDeadline(claim);
|
|
1865
|
-
return deadline===null?this.nowMs()>=
|
|
1901
|
+
return deadline===null?this.nowMs()>=persistedDeadline:this.monotonicNow()>=deadline;
|
|
1866
1902
|
}
|
|
1867
1903
|
// A revoked grant cannot authorize a successor until its deadline and all
|
|
1868
1904
|
// host effect channels have stopped. Unknown stop evidence fails closed.
|
|
@@ -2046,7 +2082,7 @@ export class Store {
|
|
|
2046
2082
|
const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
|
|
2047
2083
|
const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
|
|
2048
2084
|
const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
|
|
2049
|
-
return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2085
|
+
return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,parent_generation:a.parent_generation??null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2050
2086
|
}
|
|
2051
2087
|
recordPrPreflight(id,phase,assignment,evidence,replace=false) {
|
|
2052
2088
|
assertPreflight(assignment,evidence,this.nowMs());
|
|
@@ -2054,10 +2090,14 @@ export class Store {
|
|
|
2054
2090
|
}
|
|
2055
2091
|
hasAssignment(id) { return !!this.db.prepare('SELECT 1 FROM assignments WHERE request_id=?').get(id); }
|
|
2056
2092
|
ownerNotes(id) { return this.db.prepare('SELECT id,at,text FROM owner_notes WHERE request_id=? ORDER BY sequence').all(id); }
|
|
2057
|
-
|
|
2058
|
-
|
|
2093
|
+
// A clarification row keeps the shape it had before purposes existed; a row with another purpose shows it.
|
|
2094
|
+
questions(id) { this.assertProtocolAvailable(id);return this.db.prepare('SELECT * FROM job_questions WHERE request_id=? ORDER BY rowid').all(id).map(({purpose,...row})=>purpose==='clarification'?row:{...row,purpose}); }
|
|
2095
|
+
questionPurpose(id,questionId) { return this.db.prepare('SELECT purpose FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId)?.purpose??null; }
|
|
2096
|
+
askQuestion(id,claimId,questionId,text,subject='local-principal',worker='dot',ctx=null,connectionId=null,purpose='clarification') {
|
|
2059
2097
|
validateQuestion(questionId,text);
|
|
2060
|
-
|
|
2098
|
+
if(!QUESTION_PURPOSES.includes(purpose)) throw new Error(`invalid question purpose: use ${QUESTION_PURPOSES.join(' or ')}`);
|
|
2099
|
+
// The purpose joins the stored command only when it is not the default, so a clarification keeps its pre-existing receipt identity.
|
|
2100
|
+
return this.progress(id,claimId,`QUESTION: ${text}`,subject,false,worker,{questionId,text,...(purpose==='clarification'?{}:{purpose})},ctx,connectionId);
|
|
2061
2101
|
}
|
|
2062
2102
|
assertQuestionGrant(id,question) {
|
|
2063
2103
|
const claim=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
@@ -2573,9 +2613,10 @@ export class Store {
|
|
|
2573
2613
|
if(old) {
|
|
2574
2614
|
if(old.claim_id!==claimId||old.epoch!==claim.epoch) throw questionError('STALE_EPOCH','question identity belongs to an earlier grant');
|
|
2575
2615
|
if(old.text!==question.text) throw questionError('KEY_CONFLICT','question identity has different text');
|
|
2616
|
+
if(old.purpose!==(question.purpose??'clarification')) throw questionError('KEY_CONFLICT','question identity has a different purpose');
|
|
2576
2617
|
return {recorded:true,question_id:question.questionId,duplicate:true};
|
|
2577
2618
|
}
|
|
2578
|
-
this.db.prepare('INSERT INTO job_questions(request_id,question_id,claim_id,epoch,worker,subject,text,asked_at) VALUES(
|
|
2619
|
+
this.db.prepare('INSERT INTO job_questions(request_id,question_id,claim_id,epoch,worker,subject,text,asked_at,purpose) VALUES(?,?,?,?,?,?,?,?,?)').run(id,question.questionId,claimId,claim.epoch,worker,subject,question.text,this.stamp(),question.purpose??'clarification');
|
|
2579
2620
|
}
|
|
2580
2621
|
this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,note,this.stamp(),worker);
|
|
2581
2622
|
this.recordClaimDenials(id,note,worker);
|
|
@@ -2585,7 +2626,7 @@ export class Store {
|
|
|
2585
2626
|
this.lifecycle(id,question?'waiting':progressType(note,blocker),`worker:${subject}`,question?`question:ask:${question.questionId}`:null,claim);
|
|
2586
2627
|
if(isBlocker) {
|
|
2587
2628
|
const ownerNoteSeq=this.db.prepare('SELECT COALESCE(max(sequence),0) sequence FROM owner_notes WHERE request_id=?').get(id).sequence;
|
|
2588
|
-
const body=JSON.stringify({note,epoch:claim.epoch,owner_note_seq:ownerNoteSeq,...(question?{question_id:question.questionId}:{})});
|
|
2629
|
+
const body=JSON.stringify({note,epoch:claim.epoch,owner_note_seq:ownerNoteSeq,...(question?{question_id:question.questionId,...(question.purpose&&question.purpose!=='clarification'?{purpose:question.purpose}:{})}:{})});
|
|
2589
2630
|
// Legacy bodies have no generation fields. Preserve them only before any later answer/claim boundary;
|
|
2590
2631
|
// equal timestamps at a boundary cannot prove the original generation, so do not suppress a fresh question.
|
|
2591
2632
|
// Owner notes have no shared sequence with notifications; table-local rowids or a delivered-ID set cannot
|
|
@@ -2784,6 +2825,28 @@ export class Store {
|
|
|
2784
2825
|
this.db.prepare("UPDATE notifications SET kind=CASE WHEN kind='watch' THEN kind ELSE 'wait' END,state=CASE WHEN kind='watch' THEN 'quiet' ELSE 'pending' END,next_at=0,last_error=? WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(reason,id);
|
|
2785
2826
|
this.suppressFinishedQuestions(this.db.prepare('SELECT request_id FROM notifications WHERE id=?').get(id)?.request_id??null);
|
|
2786
2827
|
}
|
|
2828
|
+
// A parent that is not running (T3 reports its latest run as interrupted) holds the wake. The wake stays in the durable
|
|
2829
|
+
// queue like any quieted one, and held_kind remembers what it was so releaseHeld can put it back once the parent runs again.
|
|
2830
|
+
// One transaction: held_kind and the quiet state land together or not at all. A crash between two separate writes would
|
|
2831
|
+
// leave a sending row that recoverSends turns into uncertain, which heldDeliveries skips.
|
|
2832
|
+
holdDelivery(id,reason) {
|
|
2833
|
+
this.inTransaction(() => {
|
|
2834
|
+
this.db.prepare("UPDATE notifications SET held_kind=kind WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(id);
|
|
2835
|
+
this.quietDelivery(id,reason);
|
|
2836
|
+
});
|
|
2837
|
+
}
|
|
2838
|
+
// Oldest first. `after` is the {created_at,id} of the last row a caller saw, so a caller can page past rows it has already
|
|
2839
|
+
// inspected instead of reading the same oldest rows on every call.
|
|
2840
|
+
heldDeliveries(limit=20,after=null) {
|
|
2841
|
+
const base="SELECT * FROM notifications WHERE held_kind IS NOT NULL AND state IN ('pending','quiet')";
|
|
2842
|
+
return after
|
|
2843
|
+
? this.db.prepare(`${base} AND (created_at,id)>(?,?) ORDER BY created_at,id LIMIT ?`).all(after.created_at,after.id,limit)
|
|
2844
|
+
: this.db.prepare(`${base} ORDER BY created_at,id LIMIT ?`).all(limit);
|
|
2845
|
+
}
|
|
2846
|
+
// Back to the original kind, pending and due now. A waiter that already took the row (state 'waiting') is not touched.
|
|
2847
|
+
releaseHeld(id) {
|
|
2848
|
+
return this.db.prepare("UPDATE notifications SET kind=held_kind,held_kind=NULL,state='pending',next_at=0,last_error='' WHERE id=? AND held_kind IS NOT NULL AND state IN ('pending','quiet')").run(id).changes===1;
|
|
2849
|
+
}
|
|
2787
2850
|
quarantineDelivery(id,reason) {
|
|
2788
2851
|
return this.db.prepare("UPDATE notifications SET state='suppressed',last_error=?,uncertain_reason=NULL WHERE id=? AND state IN ('pending','failed')").run(String(reason).slice(0,500),id).changes===1;
|
|
2789
2852
|
}
|
|
@@ -391,6 +391,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
|
|
|
391
391
|
}
|
|
392
392
|
}
|
|
393
393
|
}
|
|
394
|
+
const repositoryImplementation=rendered.execution_scope==='implementation'&&scope.includes('.');
|
|
394
395
|
const dropped=[];let narrowedScope=null;
|
|
395
396
|
const firstPass=mentionedPaths(text,scope);
|
|
396
397
|
for(const file of firstPass) {
|
|
@@ -516,10 +517,13 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
|
|
|
516
517
|
if(rest.length) error.suggested_scope_paths=rest;
|
|
517
518
|
throw error;
|
|
518
519
|
}
|
|
519
|
-
//
|
|
520
|
-
//
|
|
521
|
-
//
|
|
520
|
+
// Repository-wide implementation scopes withhold unnamed sensitive files physically.
|
|
521
|
+
// Other scopes retain the explicit read-only exclusion option. Named paths and patch
|
|
522
|
+
// paths still refuse above and below; exclusions grant no access to those files.
|
|
522
523
|
for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
|
|
524
|
+
if(repositoryImplementation&&isSensitiveRepoPath(file,p.sensitive_paths)) {
|
|
525
|
+
dropped.push({path:file,reason:sensitiveReason(file)});continue;
|
|
526
|
+
}
|
|
523
527
|
try { inspectPath(file); }
|
|
524
528
|
catch(error) {
|
|
525
529
|
if(!/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) throw error;
|
|
@@ -535,7 +539,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
|
|
|
535
539
|
for(const file of scan.symlinks||[]) if(within(file,scope)&&!scope.includes(file)&&excludeSensitive&&rendered.execution_scope!=='implementation') dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
|
|
536
540
|
// A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
|
|
537
541
|
// would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
|
|
538
|
-
if(dropped.length) narrowedScope=narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
|
|
542
|
+
if(dropped.length) narrowedScope=repositoryImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
|
|
539
543
|
for(const file of scan.symlinks||[]) if(within(file,narrowedScope??scope)&&!dropped.some(d=>d.path===file)) throw new Error(`symlink in repository scope: ${file}`);
|
|
540
544
|
if(input.input_patch) {
|
|
541
545
|
if(/^new (?:file )?mode 120000$/m.test(input.input_patch)) throw new Error('symlink in input patch scope');
|
package/src/t3.mjs
CHANGED
|
@@ -179,12 +179,31 @@ export async function inspectThread(threadId, environmentId) {
|
|
|
179
179
|
const data=await inspectMetadata(threadId);
|
|
180
180
|
if (!data?.thread || data.thread.id!==threadId || data.thread.deletedAt ||
|
|
181
181
|
!environmentId || !data.runtime?.environmentId || data.runtime.environmentId!==environmentId) return {state:'unavailable'};
|
|
182
|
-
return classifyThread(data.thread);
|
|
182
|
+
return {...classifyThread(data.thread),generation:threadGeneration(data.thread,data.runtime.environmentId)};
|
|
183
|
+
}
|
|
184
|
+
// T3 has no 'stopped' run status. thread.stop and run.interrupt both leave the latest run 'interrupted', and inspect shows
|
|
185
|
+
// nothing else that tells them apart (measured on T3 4643: docs/t3-wake-fence-r4.md). A wake after either starts a new run.
|
|
186
|
+
// So a latest run in one of these states holds the wake. A held wake over-fences a plain interrupt: it costs a held wake, never a wrong one.
|
|
187
|
+
// A 'failed' run errored on its own, and a wake that restarts it is how a crashed or usage-limited parent resumes, so it is runnable.
|
|
188
|
+
export const runnableRunStatuses=['completed','running','failed'];
|
|
189
|
+
export const heldRunStatuses=['interrupted','cancelled','canceled'];
|
|
190
|
+
// The parent generation: the thread, its environment and the latest run seen in one inspect.
|
|
191
|
+
export const threadGeneration=(thread,environmentId)=>({threadId:thread.id,environmentId,runId:thread.latestRun?.runId??null,ordinal:Number.isInteger(thread.latestRun?.ordinal)?thread.latestRun.ordinal:null});
|
|
192
|
+
// Best-effort check of the generation recorded at submit against the one seen now. It catches a different thread or
|
|
193
|
+
// environment and a thread whose runs went backwards. It cannot see stop-then-resume: that needs a stopSeq from T3.
|
|
194
|
+
export function generationDrift(recorded,current) {
|
|
195
|
+
if(!recorded||!current) return null;
|
|
196
|
+
if(recorded.threadId!==current.threadId||recorded.environmentId!==current.environmentId) return 'parent thread or environment changed since submit';
|
|
197
|
+
if(Number.isInteger(recorded.ordinal)&&(!Number.isInteger(current.ordinal)||current.ordinal<recorded.ordinal)) return `parent runs went back since submit (run ${recorded.ordinal} to ${current.ordinal??'none'})`;
|
|
198
|
+
return null;
|
|
183
199
|
}
|
|
184
200
|
export function classifyThread(thread) {
|
|
185
201
|
if(thread.deletedAt) return {state:'deleted'};
|
|
186
202
|
if(thread.archivedAt) return {state:'archived'};
|
|
187
|
-
|
|
203
|
+
const runStatus=thread.latestRun?.status;
|
|
204
|
+
if(heldRunStatuses.includes(runStatus)) return {state:'held',reason:`latest run ${runStatus}`};
|
|
205
|
+
// Fail closed: only a status Dalan knows to be runnable lets a wake through. A thread with no run yet has none to check.
|
|
206
|
+
if(thread.latestRun&&!runnableRunStatuses.includes(runStatus)) return {state:'held',reason:`latest run status ${JSON.stringify(runStatus??null)} is not recognized`};
|
|
188
207
|
if(['stopped','settled','archived','deleted','cancelled','canceled'].includes(thread.status)) return {state:thread.status};
|
|
189
208
|
if(thread.status==='active') return {state:'active'};
|
|
190
209
|
return {state:'uncertain_lifecycle'};
|
package/src/tool-registry.mjs
CHANGED
|
@@ -14,7 +14,8 @@ const refuse = (code, message) => { throw new RegistryError(code, message); };
|
|
|
14
14
|
|
|
15
15
|
const NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
16
16
|
const WORKER = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
17
|
-
const
|
|
17
|
+
const T3_NAMES = new Set(['t3_thread_list','t3_thread_read','t3_thread_wait','t3_thread_create','t3_thread_send','t3_thread_set']);
|
|
18
|
+
const RESERVED = new Set(['list_tools', 'call_tool_read', 'call_tool_write', ...T3_NAMES]);
|
|
18
19
|
const FORBIDDEN_KIND = /(delete|overwrite|unlink|truncate|wipe|destroy|remove)/i;
|
|
19
20
|
const FORBIDDEN_WORD = /^(delete|overwrite|remove|unlink|truncate|wipe|destroy|rm|rmdir|erase|replace)$/i;
|
|
20
21
|
// The longest a handler may run (the t3-post command timeout), and the lease a pending reservation holds: that timeout plus
|
|
@@ -67,7 +68,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
67
68
|
const toolClass = row => handlers[JSON.parse(row.handler).kind]?.effectClass ?? row.class;
|
|
68
69
|
const callerHash = (row, worker) => sha256(canonical({
|
|
69
70
|
name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), handler: JSON.parse(row.handler),
|
|
70
|
-
caller: worker, grants: db.prepare('SELECT tool FROM tool_grants WHERE worker=? ORDER BY tool').all(worker)
|
|
71
|
+
caller: worker, grants: db.prepare('SELECT tool,scope FROM tool_grants WHERE worker=? ORDER BY tool').all(worker),
|
|
71
72
|
}));
|
|
72
73
|
// Owner views retain the registration/audit definition hash; only worker views pin caller grants.
|
|
73
74
|
// Never bind an absent owner caller to the worker-specific SQLite query.
|
|
@@ -138,18 +139,21 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
138
139
|
record({ kind: enabled ? 'enable' : 'disable', tool: name, outcome: 'ok', schema_hash: row.schema_hash });
|
|
139
140
|
});
|
|
140
141
|
}
|
|
141
|
-
function grantChange(kind, name, worker) {
|
|
142
|
+
function grantChange(kind, name, worker, scope) {
|
|
142
143
|
const row = getTool(name);
|
|
143
144
|
if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
|
|
144
145
|
if (typeof worker !== 'string' || !WORKER.test(worker)) refuse('invalid_tool', 'worker must be a worker name');
|
|
146
|
+
if(scope !== undefined && scope !== null && (!scope || Object.keys(scope).join() !== 'threads' || !Array.isArray(scope.threads) || scope.threads.some(id=>typeof id!=='string'||!id||id.length>128))) refuse('invalid_tool', 'scope must be {threads: [thread IDs]}');
|
|
147
|
+
if(scope!==undefined && scope!==null && JSON.parse(row.handler).kind!=='t3_control') refuse('invalid_tool','thread scope applies only to T3 control grants');
|
|
145
148
|
atomically(() => {
|
|
146
|
-
if (kind === 'grant') db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name,
|
|
149
|
+
if (kind === 'grant' && scope === undefined) db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name,worker,iso(now()));
|
|
150
|
+
else if (kind === 'grant') db.prepare('INSERT INTO tool_grants(tool,worker,granted_at,scope) VALUES(?,?,?,?) ON CONFLICT(tool,worker) DO UPDATE SET scope=excluded.scope').run(name, worker, iso(now()), scope===null?null:JSON.stringify(scope));
|
|
147
151
|
else { db.prepare('DELETE FROM tool_grants WHERE tool=? AND worker=?').run(name, worker); dropQueued(name, worker); }
|
|
148
152
|
bump();
|
|
149
153
|
record({ kind, tool: name, worker, outcome: 'ok', schema_hash: row.schema_hash });
|
|
150
154
|
});
|
|
151
155
|
}
|
|
152
|
-
const grant = (name, worker) => grantChange('grant', name, worker);
|
|
156
|
+
const grant = (name, worker, scope) => grantChange('grant', name, worker, scope);
|
|
153
157
|
const revoke = (name, worker) => grantChange('revoke', name, worker);
|
|
154
158
|
|
|
155
159
|
function list() {
|
|
@@ -161,7 +165,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
161
165
|
}
|
|
162
166
|
function listTools(worker) {
|
|
163
167
|
const name = workerName(worker);
|
|
164
|
-
const tools = typeof name !== 'string' ? [] : db.prepare(
|
|
168
|
+
const tools = typeof name !== 'string' ? [] : db.prepare("SELECT t.* FROM registered_tools t JOIN tool_grants g ON g.tool=t.name WHERE g.worker=? AND t.enabled=1 AND json_extract(t.handler,'$.kind')!='t3_control' ORDER BY t.name").all(name).map(row => view(row, name));
|
|
165
169
|
return { registry_version: registryVersion(), tools };
|
|
166
170
|
}
|
|
167
171
|
function lastChange() {
|
|
@@ -227,7 +231,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
227
231
|
done('replay_unfinished', new RegistryError('in_progress', `an earlier call with this idempotency_key is in progress; retry later with the same key in about ${seconds} s`));
|
|
228
232
|
};
|
|
229
233
|
const unavailable = outcome => done(outcome, new RegistryError('tool_unavailable', 'tool unavailable'));
|
|
230
|
-
if (!row) unavailable('unknown_tool');
|
|
234
|
+
if (!row || JSON.parse(row.handler).kind==='t3_control') unavailable('unknown_tool');
|
|
231
235
|
if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(row.name, name)) unavailable('not_granted');
|
|
232
236
|
if (row.enabled !== 1) unavailable('disabled');
|
|
233
237
|
if (callClass !== toolClass(row)) done('wrong_class', new RegistryError('wrong_class', 'wrong class for this tool; see list_tools'));
|
|
@@ -299,7 +303,49 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
|
|
|
299
303
|
return { ok: true, result: capped };
|
|
300
304
|
}
|
|
301
305
|
|
|
302
|
-
|
|
306
|
+
// Internal registrations share the existing grant/revoke/enable policy, but are never dispatch tools.
|
|
307
|
+
// Provision a worker once: restarting must not restore a revoked grant.
|
|
308
|
+
function initializeT3Grants(names, workers) {
|
|
309
|
+
atomically(()=>{
|
|
310
|
+
// Older registries allowed these names. Never turn an ordinary tool into an
|
|
311
|
+
// implicit grant while upgrading; leave it untouched for operator resolution.
|
|
312
|
+
for(const name of names) {
|
|
313
|
+
if(!T3_NAMES.has(name)) refuse('invalid_tool','unknown T3 authority tool');
|
|
314
|
+
const existing=getTool(name);
|
|
315
|
+
if(existing && JSON.parse(existing.handler).kind!=='t3_control') refuse('reserved_tool_conflict',`registered tool ${name} conflicts with T3 authority; remove or rename it before enabling T3 tools`);
|
|
316
|
+
}
|
|
317
|
+
for(const name of names) {
|
|
318
|
+
const definition={name,description:'Job-scoped T3 authority',input_schema:{type:'object',properties:{},additionalProperties:false},
|
|
319
|
+
class:['t3_thread_list','t3_thread_read','t3_thread_wait'].includes(name)?'read':'write',handler:{kind:'t3_control'}};
|
|
320
|
+
db.prepare(`INSERT OR IGNORE INTO registered_tools(name,description,input_schema,class,handler,schema_hash,created_at)
|
|
321
|
+
VALUES(?,?,?,?,?,?,?)`).run(name,definition.description,JSON.stringify(definition.input_schema),definition.class,JSON.stringify(definition.handler),schemaHash(definition),iso(now()));
|
|
322
|
+
}
|
|
323
|
+
for(const worker of workers) {
|
|
324
|
+
const key=`t3_initialized:${worker}`;
|
|
325
|
+
if(db.prepare('SELECT 1 FROM tool_registry_meta WHERE key=?').get(key)) continue;
|
|
326
|
+
for(const name of names) grant(name,worker);
|
|
327
|
+
db.prepare('INSERT INTO tool_registry_meta(key,value) VALUES(?,1)').run(key);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
function t3Threads(tool, principal) {
|
|
332
|
+
// The legacy local principal also resolves to a worker; it has no owner bypass.
|
|
333
|
+
const row=db.prepare("SELECT g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE g.tool=? AND g.worker=? AND t.enabled=1 AND json_extract(t.handler,'$.kind')='t3_control'").get(tool,principal.worker);
|
|
334
|
+
if(!row) refuse('tool_unavailable','tool unavailable');
|
|
335
|
+
const scope=row.scope===null?null:JSON.parse(row.scope);
|
|
336
|
+
if(scope!==null&&(!Array.isArray(scope.threads)||Object.keys(scope).join()!=='threads')) refuse('tool_unavailable','tool unavailable');
|
|
337
|
+
const threads=new Set();
|
|
338
|
+
for(const claim of db.prepare(`SELECT c.*,a.delivery FROM claims c JOIN assignments a USING(request_id)
|
|
339
|
+
WHERE c.worker=? AND c.subject=? AND c.state='active' AND a.status='claimed'`).all(principal.worker,principal.subject)) {
|
|
340
|
+
if(store.leaseExpired(claim)||!claim.delivery?.startsWith('t3:')) continue;
|
|
341
|
+
try { store.assertWorkerConnection(claim.request_id,claim.claim_id,principal.subject,principal.worker,principal.builtin?(principal.connection_id??''):null); }
|
|
342
|
+
catch { continue; }
|
|
343
|
+
const thread=claim.delivery.slice(3);
|
|
344
|
+
if(scope===null||scope.threads.includes(thread)) threads.add(thread);
|
|
345
|
+
}
|
|
346
|
+
return threads;
|
|
347
|
+
}
|
|
348
|
+
return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, t3Threads };
|
|
303
349
|
}
|
|
304
350
|
|
|
305
351
|
// ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
|