@tnunamak/dalan 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,17 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.2
8
+
9
+ - An operator can limit private scoped-file reads to one held read-only assignment and set them to expire within its claim lease. The worker needs a separate grant for other assignments.
10
+
11
+ - Muse can accept a delegated review of specific files at a pushed commit and return its work ID.
12
+ - The requester reports an oversized bridge reply and stops retrying it, including when the bridge reports a server error.
13
+ - Work that fails, is blocked, or is refused shows its outcome without suggesting acceptance. Linked corrections remain available.
14
+ - If a worker cannot verify a required capability, Dalan points to a supported adapter.
15
+ - A caller can require identified questions on a worker configured for them. The worker must have both question tools enabled and granted.
16
+ - Use `dalan tell --work ID` to attach a lightweight message to your open work. While work is open, a worker-inbox acknowledgment appears in that child's transcript without waking the parent.
17
+
7
18
  ## 0.9.0
8
19
 
9
20
  - **Before upgrading, keep a verified backup and the previous installation.** The bridge still uses schema 75 and adds records for native withdrawal, lane reservations and worker-scoped breaks. Before rolling back, verify the old package can use the retained state. Keep newer reports, receipts, artifacts and delivery acknowledgments.
@@ -721,7 +721,17 @@ async function main() {
721
721
  post:envelope=>request('/answer','POST',envelope,owner(),ANSWER_TIMEOUT_MS),
722
722
  readQuestion:async()=>(await request('/questions?id='+encodeURIComponent(id),'GET',null,owner())).questions.find(q=>q.question_id===questionId)});
723
723
  break; }
724
- case 'tell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker');if(rest.some(a=>a.startsWith('-')&&a!=='--json')) throw new Error('tell accepts --worker NAME and --json');const text=rest.filter(a=>a!=='--json').join(' ');if(!text) throw new Error('tell requires text');result=await request('/tell','POST',{text,...(worker?{worker}:{})});break; }
724
+ case 'tell': {
725
+ const worker=option('--worker'), work=option('--work'), valued=new Set(['--worker','--work']);
726
+ if((args.includes('--worker')&&!worker)||(args.includes('--work')&&!work)) throw new Error('tell options require a value');
727
+ const rest=args.filter((arg,index)=>!valued.has(arg)&&!valued.has(args[index-1])&&arg!=='--json');
728
+ if(rest.some(arg=>arg.startsWith('-'))) throw new Error('tell accepts --worker NAME, --work ID and --json');
729
+ const text=rest.join(' ');
730
+ if(!text) throw new Error('tell requires text');
731
+ const headers=work?{'x-owner-capability':receipt(work).token}:{};
732
+ result=await request('/tell','POST',{text,...(worker?{worker}:{}),...(work?{request_id:work}:{})},headers);
733
+ break;
734
+ }
725
735
  case 'untell': { const worker=option('--worker'),rest=args.filter((a,i)=>a!=='--worker'&&args[i-1]!=='--worker'&&a!=='--json');if(rest.length!==1||rest[0].startsWith('-')) throw new Error('untell requires message ID (optional --worker NAME, --json)');result=await request('/untell','POST',{message_id:rest[0],...(worker?{worker}:{})});break; }
726
736
  case 'audit': { const since=option('--since'); result=await request('/audit'+(since?'?since='+encodeURIComponent(since):''),'GET',null,{'x-operator-key':operator()}); break; }
727
737
  case 'pause': { const reason=option('--reason'); if(!reason) throw new Error('pause requires --reason'); result=await request('/pause','POST',{reason},{'x-operator-key':operator()}); break; }
@@ -249,6 +249,23 @@ The service checks subscription lapse, missing active subscriptions, repeated ca
249
249
 
250
250
  Optional self-check timers are deployment-specific, so review their endpoint, issuer, TLS and repository assumptions before enabling them. For token and subscription lifetime guidance, see [connection longevity](connection-longevity.md).
251
251
 
252
+ ## Scoped-file grants for one assignment
253
+
254
+ Use the operator-authenticated local admin endpoint `POST /tools/grant` with
255
+ `name: "fetch_scoped_input"`, the exact `worker`, and a `scope` containing
256
+ `request_id`, `claim_id`, and ISO `expires_at`. Choose an expiration at or before
257
+ the current claim deadline. The assignment must already be claimed, read-only,
258
+ and pinned to a GitHub revision with explicitly approved files. Directory
259
+ expansion is refused for assignment grants.
260
+
261
+ Each chunk still requires the original live claim, its authenticated worker
262
+ and connection, and the current repository and file policy. The grant ends
263
+ at its own expiry even if the claim is renewed. A new claim or a changed
264
+ assignment requires a fresh grant. Use the existing operator revoke operation
265
+ to remove the grant earlier. A grant for a single assignment supersedes a
266
+ worker-wide grant on this tool. Revoke it before deliberately adding a
267
+ worker-wide grant. Older versions cannot use the assignment grant.
268
+
252
269
  ## Upgrade and rollback
253
270
 
254
271
  The package version is `0.6.0`; the bridge database schema is version 66. Stop the service and every other writer before making a backup or replacing files; keep them stopped until the complete backup set is captured. Keep each backup set consistent: include `<home>/.local/share/dalan/bridge.db`, `delivery-acks.db`, `notify-sent.db`, `<config>/dalan/as.sqlite` when built-in authorization is used, the private `<config>/dalan` files, owner receipts in `<home>/.local/share/dalan/receipts`, and artifact ownership entries in `<home>/.local/share/dalan/artifact-index`. Preserve file permissions. Do not copy either `bridge.db.secrets/owner.sqlite` or `as-owner.sqlite` lock database; recreate them locally after restoring with the service stopped, as described above. If external OAuth is used, its issuer database is managed separately and is not part of this bridge backup.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.0",
3
+ "version": "0.9.2",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,10 +1,10 @@
1
1
  # Adapter qualification
2
2
 
3
- A worker profile may name an `adapter`: `mcp` or `protocol-v0`. Omission means unqualified. This field is independent of the `t3` authority grant and of Gozar tunnel routes.
3
+ A worker profile may name an `adapter`: `mcp`, `protocol-v0`, or `registry-questions-v1`. Omission means unqualified. This field is independent of the `t3` authority grant and of Gozar tunnel routes.
4
4
 
5
5
  Records follow [the adapter schema](../contracts/adapter-qualification.schema.json), copied from the handoff schema with adapter naming. `yes` with a passing observation maps to `verified`; `no` with a passing observation maps to `unsupported`; everything else maps to `unknown`. Unknown capabilities never satisfy a submission requirement.
6
6
 
7
- `protocol-v0` qualifies identified question/answer/consume behavior through the local real-server fixture. Its declaration applies only with the `protocol-v0` catalog profile. `mcp` makes no verified capability claims. Neither record qualifies a hosted model, native session continuity, activation, or a worker sandbox. The source pin identifies the baseline exercised by the probe, rather than a live provider version.
7
+ `protocol-v0` qualifies identified question/answer/consume behavior through the local real-server fixture and applies only with the `protocol-v0` catalog profile. `registry-questions-v1` qualifies the keyed question path in the authenticated `batch-claim-v1` fixture. Admission requires current write grants for both `ask_question` and `consume_answer`. Its catalog fingerprint covers the granted registry tools returned to the fixture worker. `mcp` makes no verified capability claims. The records cover local fixtures. Hosted models, native session continuity, activation, and worker sandboxes remain unqualified. The source pins identify the probe baselines.
8
8
 
9
9
  Run `node scripts/qualification-gate-test.mjs` to validate the records, compare them with the runtime capability table, and rerun their observations. The gate refuses missing observations, failed probes, mismatched values, duplicate or missing capability names, and unbound evidence. Run `node scripts/adapter-qualification-test.mjs` to exercise actual `/submit` admission and inspect SQLite after refusals. `node scripts/pull-catalog-hash-test.mjs` pins the unchanged worker catalog for all profiles with T3 tools on and off.
10
10
 
@@ -0,0 +1,126 @@
1
+ {
2
+ "schema_version": 1,
3
+ "record_kind": "draft_internal_qualification_record_not_wire_protocol",
4
+ "adapter_id": "registry-questions-v1",
5
+ "observed_on": "2026-12-04",
6
+ "pins": {
7
+ "dalan_commit": "f9faa4805a4fa6d9f1831acad33559ebe9bff9a1",
8
+ "requester_ref": "private admin HTTP",
9
+ "worker_host_ref": "local authenticated batch-claim-v1 registry fixture",
10
+ "protocol": "batch-claim-v1",
11
+ "sdk": null,
12
+ "catalog_fingerprint": "57b24428f36fbf0a4d41afa186f64873a4fa17c6118281f683813f83cf769ddd"
13
+ },
14
+ "roles": [
15
+ "worker"
16
+ ],
17
+ "continuity": "unknown",
18
+ "activation": "unknown",
19
+ "capabilities": [
20
+ {
21
+ "name": "private_loopback",
22
+ "declared": "unknown",
23
+ "observed": "not_tested",
24
+ "required": false
25
+ },
26
+ {
27
+ "name": "host_loopback_denied",
28
+ "declared": "unknown",
29
+ "observed": "not_tested",
30
+ "required": false
31
+ },
32
+ {
33
+ "name": "lan_denied",
34
+ "declared": "unknown",
35
+ "observed": "not_tested",
36
+ "required": false
37
+ },
38
+ {
39
+ "name": "unix_sockets_denied",
40
+ "declared": "unknown",
41
+ "observed": "not_tested",
42
+ "required": false
43
+ },
44
+ {
45
+ "name": "credential_services_denied",
46
+ "declared": "unknown",
47
+ "observed": "not_tested",
48
+ "required": false
49
+ },
50
+ {
51
+ "name": "closed_inherited_fds",
52
+ "declared": "unknown",
53
+ "observed": "not_tested",
54
+ "required": false
55
+ },
56
+ {
57
+ "name": "read_scope_enforced",
58
+ "declared": "unknown",
59
+ "observed": "not_tested",
60
+ "required": false
61
+ },
62
+ {
63
+ "name": "write_scope_enforced",
64
+ "declared": "unknown",
65
+ "observed": "not_tested",
66
+ "required": false
67
+ },
68
+ {
69
+ "name": "full_tree_cancel_verified",
70
+ "declared": "unknown",
71
+ "observed": "not_tested",
72
+ "required": false
73
+ },
74
+ {
75
+ "name": "offline_transition_revokes_connections",
76
+ "declared": "unknown",
77
+ "observed": "not_tested",
78
+ "required": false
79
+ },
80
+ {
81
+ "name": "artifact_export_no_follow",
82
+ "declared": "unknown",
83
+ "observed": "not_tested",
84
+ "required": false
85
+ },
86
+ {
87
+ "name": "runner_observed_evidence",
88
+ "declared": "unknown",
89
+ "observed": "not_tested",
90
+ "required": false
91
+ },
92
+ {
93
+ "name": "native_darwin_execution",
94
+ "declared": "unknown",
95
+ "observed": "not_tested",
96
+ "required": false
97
+ },
98
+ {
99
+ "name": "immutable_input_snapshot",
100
+ "declared": "unknown",
101
+ "observed": "not_tested",
102
+ "required": false
103
+ },
104
+ {
105
+ "name": "identified_questions",
106
+ "declared": "yes",
107
+ "observed": "passed",
108
+ "required": false,
109
+ "evidence_refs": [
110
+ "scripts/adapter-qualification-test.mjs"
111
+ ]
112
+ }
113
+ ],
114
+ "qualification": {
115
+ "state": "passed_for_declared_scope",
116
+ "evidence_level": "actual_store_integration",
117
+ "run_refs": [
118
+ "scripts/adapter-qualification-test.mjs"
119
+ ]
120
+ },
121
+ "limits": [
122
+ "Applies only to batch-claim-v1 with current write grants for ask_question and consume_answer.",
123
+ "No live hosted-worker qualification or native session continuity or activation guarantee.",
124
+ "Sandbox capabilities remain unknown. Host execution keeps its separate backend admission."
125
+ ]
126
+ }
@@ -37,7 +37,7 @@ export function paths(env = process.env) {
37
37
  export class BridgeError extends Error {
38
38
  constructor(message, kind, httpStatus) { super(message); this.kind = kind; this.http_status = httpStatus ?? null; }
39
39
  }
40
- export const transient = e => e.kind === 'transport' || e.http_status >= 500;
40
+ export const transient = e => e.retryable !== false && (e.kind === 'transport' || e.http_status >= 500);
41
41
 
42
42
  const isReplyRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
43
43
  function validAdminVerdict(value) {
@@ -48,7 +48,7 @@ function validAdminVerdict(value) {
48
48
  reason.candidates.every(candidate => typeof candidate === 'string'))));
49
49
  }
50
50
 
51
- export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs } = {}) {
51
+ export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs, maxResponseBytes } = {}) {
52
52
  const positive = (value, fallback) => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
53
53
  const baseMs = positive(process.env.DOT_ACP_HTTP_TIMEOUT_MS, 20000);
54
54
  const graceMs = positive(process.env.DOT_ACP_HTTP_GRACE_MS, 1000);
@@ -62,13 +62,43 @@ export function adminRequest(socket, route, { method = 'GET', payload, token, si
62
62
  let timer;
63
63
  const fail = error => { clearTimeout(timer); reject(error instanceof BridgeError ? error : Object.assign(new BridgeError(error.message, 'transport'), { name: error.name })); };
64
64
  const headers = { 'content-type': 'application/json', 'content-length': Buffer.byteLength(bytes), ...(token ? { 'x-owner-capability': token } : {}) };
65
+ // A response intrinsically over the cap will be over it on every retry, so it is a
66
+ // deterministic, nonretryable diagnostic (kind 'local'), never a transport error the
67
+ // restart wrapper repeats. Output stays bounded: chunks past the cap are not retained.
68
+ // An interrupted response (error/aborted/deadline) remains transport and retryable.
69
+ const capBytes = positive(maxResponseBytes ?? process.env.DOT_ACP_ADMIN_RESPONSE_CAP_BYTES, 16 * 1024 * 1024);
70
+ const tooLarge = status => Object.assign(
71
+ new BridgeError(`admin response too large: ${method} ${url.pathname} exceeds the ${capBytes}-byte response cap (HTTP ${status}); not retrying`, 'local', status),
72
+ { code: 'admin_response_too_large', retryable: false, cap_bytes: capBytes });
65
73
  const req = http.request({ socketPath: socket, path: route, method, headers, signal }, res => {
66
- let out = '';
67
- res.on('data', b => { out += b; });
68
- res.on('error', fail);
69
- res.on('aborted', () => fail(new Error('admin response aborted')));
74
+ const chunks = [];
75
+ let received = 0, capped = false;
76
+ const declared = Number(res.headers['content-length']);
77
+ if (Number.isFinite(declared) && declared > capBytes) {
78
+ capped = true;
79
+ res.destroy();
80
+ req.destroy();
81
+ return fail(tooLarge(res.statusCode));
82
+ }
83
+ res.on('data', b => {
84
+ if (capped) return;
85
+ received += b.length;
86
+ if (received > capBytes) {
87
+ capped = true;
88
+ chunks.length = 0;
89
+ res.destroy();
90
+ req.destroy();
91
+ fail(tooLarge(res.statusCode));
92
+ return;
93
+ }
94
+ chunks.push(b);
95
+ });
96
+ res.on('error', error => { if (!capped) fail(error); });
97
+ res.on('aborted', () => { if (!capped) fail(new Error('admin response aborted')); });
70
98
  res.on('end', () => {
99
+ if (capped) return;
71
100
  clearTimeout(timer);
101
+ const out = Buffer.concat(chunks).toString('utf8');
72
102
  let value;
73
103
  try { value = JSON.parse(out); } catch { return fail(new Error('invalid admin response')); }
74
104
  const admission = url.pathname === '/submit' || url.pathname === '/submit-preview';
@@ -101,7 +131,7 @@ export async function adminRequestThroughRestart(socket, route, options = {}) {
101
131
  catch (e) {
102
132
  const unsent = ['ECONNREFUSED', 'ENOENT'].includes(e.code) || /ECONNREFUSED|ENOENT/.test(e.message ?? '');
103
133
  const quiescing = /bridge_quiescing/.test(e.message ?? '');
104
- const retry = unsent || quiescing || (read && e.kind === 'transport');
134
+ const retry = e.retryable !== false && e.code !== 'admin_response_too_large' && (unsent || quiescing || (read && e.kind === 'transport'));
105
135
  if (!retry || options.signal?.aborted || Date.now() + stepMs > until) throw e;
106
136
  await new Promise(resolve => setTimeout(resolve, stepMs));
107
137
  }
@@ -143,7 +173,10 @@ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000, wallC
143
173
  // T3's delegate_task puts `Act as the <role> sub-agent for this task.\n\n` before the task for every role except general
144
174
  // (and none); parseIdentity strips it, because otherwise the token line and a [dot-build] line are no longer first.
145
175
  export function parsePrompt(prompt, { worker = null } = {}) {
146
- const { id: root, text, brief } = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
176
+ const legacy = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
177
+ const { id: root, text, brief } = worker === 'muse' && legacy.text.startsWith('[muse-decision:')
178
+ ? parseIdentity(prompt, { prefix: 'muse-decision', idPattern })
179
+ : legacy;
147
180
  // Without a token the identity is the text after the T3 preamble, so a resend with or without a role maps to one request.
148
181
  const lines = brief.split('\n');
149
182
  let priority = 'normal', requirements = [];
package/src/cli-help.mjs CHANGED
@@ -110,7 +110,7 @@ export const COMMANDS = [
110
110
  { name: 'note', summary: 'Add a note to a job', usage: 'dalan note ID TEXT [--json]' },
111
111
  { name: 'questions', summary: 'List a job\'s open worker questions', usage: 'dalan questions ID [--json]' },
112
112
  { name: 'answer', summary: 'Answer a worker question', usage: 'dalan answer ID QUESTION_ID TEXT [--json]' },
113
- { name: 'tell', summary: 'Send a message to workers', usage: 'dalan tell [--worker NAME] TEXT [--json]' },
113
+ { name: 'tell', summary: 'Send a worker-inbox message, optionally linked to open work', usage: 'dalan tell [--worker NAME] [--work ID] TEXT [--json]' },
114
114
  { name: 'untell', summary: 'Withdraw a message', usage: 'dalan untell MESSAGE_ID [--worker NAME] [--json]' },
115
115
  { name: 'audit', summary: 'Show the audit trail', usage: 'dalan audit [--since RFC3339]' },
116
116
  { name: 'claims', summary: 'List active worker claims', usage: 'dalan claims [--json]' },
package/src/execution.mjs CHANGED
@@ -117,13 +117,17 @@ export function withEvidence(row) {
117
117
  // Committed adapter qualification is independent of per-worker authority grants.
118
118
  export const ADAPTER_QUALIFICATIONS = Object.freeze({
119
119
  mcp: Object.freeze({capabilities: Object.freeze({})}),
120
+ 'registry-questions-v1': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
120
121
  'protocol-v0': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
121
122
  });
122
123
 
123
- export function admitAdapterCapabilities(adapter, required, catalogProfile) {
124
+ export function admitAdapterCapabilities(adapter, required, catalogProfile, {registryQuestions=false}={}) {
124
125
  const qualification = Object.hasOwn(ADAPTER_QUALIFICATIONS, adapter) ? ADAPTER_QUALIFICATIONS[adapter] : null;
126
+ const profileMatches = adapter === 'protocol-v0' ? catalogProfile === 'protocol-v0'
127
+ : adapter === 'registry-questions-v1' ? catalogProfile === 'batch-claim-v1' && registryQuestions
128
+ : true;
125
129
  for (const name of required ?? []) {
126
- const state = adapter === 'protocol-v0' && catalogProfile !== 'protocol-v0' ? 'unknown' : qualification?.capabilities[name] ?? 'unknown';
130
+ const state = profileMatches ? qualification?.capabilities[name] ?? 'unknown' : 'unknown';
127
131
  if (state !== 'verified') throw new Error(
128
132
  'capability_not_available: ' + name + ' (adapter ' + (adapter ?? 'undeclared') + ' declares ' + state + ')');
129
133
  }
@@ -16,7 +16,7 @@ export function formatGetSummary(job, { id, cli }) {
16
16
  const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
17
17
  const artifacts = (job.artifacts?.length ?? 0) || (job.artifact_ids?.length ?? 0), checks = job.checks?.length ?? 0;
18
18
  if (artifacts || checks) lines.push('', `Evidence: ${[artifacts && count(artifacts, 'artifact'), checks && count(checks, 'check')].filter(Boolean).join(', ')}`);
19
- const next = correctionAction(job, cli) ?? (state === 'finished' ? `${cli} decide ${id} accepted`
19
+ const next = correctionAction(job, cli) ?? (state === 'finished' ? (hasSuccessfulReport(job) ? `${cli} decide ${id} accepted` : null)
20
20
  : state === 'cancelled' ? null
21
21
  : `${cli} wait ${id} --timeout 3600, then ${cli} get ${id}`);
22
22
  if (next) lines.push('', `Next: ${next}`);
@@ -25,11 +25,12 @@ export function formatGetSummary(job, { id, cli }) {
25
25
  }
26
26
 
27
27
  const correctionAction = (job, cli) => job?.revised_by?.request_id ? `${cli} get ${job.revised_by.request_id}` : null;
28
+ const hasSuccessfulReport = job => ['completed', 'done'].includes(job?.report?.outcome);
28
29
 
29
30
  // Piped human output retains the full JSON record and adds only this stderr guidance.
30
31
  export function formatGetEndNote(job, { id, cli, decideWords }) {
31
32
  const correction = correctionAction(job, cli);
32
- return correction ? `Next: ${correction}` : job?.status === 'finished' ? `decide: ${cli} decide ${id} ${decideWords}` : null;
33
+ return correction ? `Next: ${correction}` : job?.status === 'finished' && hasSuccessfulReport(job) ? `decide: ${cli} decide ${id} ${decideWords}` : null;
33
34
  }
34
35
 
35
36
  // `dalan wait` on a terminal: one line, in place of the JSON status document.
package/src/server.mjs CHANGED
@@ -182,6 +182,9 @@ const scopedSourceChunk=18*1024;
182
182
  const phaseTrace = createPhaseTrace({ log });
183
183
  logShutdownSignals(log);
184
184
  // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
185
+ // The job owns repository, pin and path policy. A grant pins those stored values without copying them.
186
+ const scopedInputIdentity = row => createHash('sha256')
187
+ .update(JSON.stringify([row.assignment, row.claim.epoch])).digest('hex');
185
188
  const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
186
189
  const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
187
190
  t3_post:t3PostHandler,
@@ -191,6 +194,35 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
191
194
  validateConfig(_config,{name}) {
192
195
  if(name!==scopedInputRegistration.name) throw new RegistryError('invalid_tool','unknown scoped input tool');
193
196
  },
197
+ prepareGrant({worker,scope}) {
198
+ const keys = Object.keys(scope).sort().join();
199
+ if (keys !== 'claim_id,expires_at,request_id')
200
+ throw new RegistryError('invalid_tool','scoped input grant requires request_id, claim_id and expires_at');
201
+ const requestId=id(scope.request_id),claimId=id(scope.claim_id,'claim_id');
202
+ const row=store.get(requestId);
203
+ const expires=typeof scope.expires_at==='string' ? Date.parse(scope.expires_at) : NaN;
204
+ if (row.status!=='claimed'||row.cancelled_at||!row.claim)
205
+ throw new RegistryError('invalid_tool','scoped input grant requires a live assignment claim');
206
+ const claim=store.assertClaim(requestId,claimId,row.claim.subject,worker);
207
+ store.assertMutationConnection(requestId,claim,claim.connection_id??null);
208
+ if (!Number.isFinite(expires)||expires<=store.nowMs()||expires>store.leaseDeadlineClockMs(claim))
209
+ throw new RegistryError('invalid_tool','scoped input grant expiry must be within the current claim lease');
210
+ const {inputs,scope_paths,execution_scope,paged_read_scope}=row.assignment;
211
+ const input=inputs?.[0];
212
+ if (execution_scope!=='read-only'||paged_read_scope||inputs?.length!==1||!input?.github_repo||
213
+ !/^[a-f0-9]{40}$/.test(input.base_sha??'')||(input.head_sha&&input.head_sha!==input.base_sha)||
214
+ !scope_paths?.length||scope_paths.includes('.'))
215
+ throw new RegistryError('invalid_tool','scoped input grant requires a pinned read-only assignment with explicit paths');
216
+ assertRepoAllowed(worker,row.assignment);
217
+ return {request_id:requestId,claim_id:claimId,expires_at:new Date(expires).toISOString(),assignment_digest:scopedInputIdentity(row)};
218
+ },
219
+ authorizeGrant(scope,args) {
220
+ if (scope.request_id!==args?.request_id||scope.claim_id!==args?.claim_id) return false;
221
+ try {
222
+ const row=store.get(scope.request_id);
223
+ return scope.assignment_digest===scopedInputIdentity(row);
224
+ } catch { return false; }
225
+ },
194
226
  authorizeReplay({args,context}) {
195
227
  const {worker,subject,builtin,connection_id}=context,connection=builtin?(connection_id??''):null;
196
228
  const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
@@ -207,7 +239,7 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
207
239
  return [requestId,claim.claim_id,claim.epoch,subject,connection];
208
240
  } catch(error) { throw assignmentRegistryRefusal(error); }
209
241
  },
210
- run({args,context:{worker,subject}}) {
242
+ run({args,context:{worker,subject},grantScope}) {
211
243
  const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
212
244
  const offset=args.offset??0;
213
245
  if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
@@ -215,6 +247,8 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
215
247
  const {a,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
216
248
  if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
217
249
  const {manifest,blobs}=pinnedScopedSource(mirror,a.assignment);
250
+ if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
251
+ throw new Error('assignment grant requires exact scoped files');
218
252
  if(!manifest.files.length) throw new Error('no approved scoped input files');
219
253
  const files=manifest.files.map(file=>{
220
254
  const bytes=blobs.get(file.path);
@@ -1663,6 +1697,16 @@ const adminServer=http.createServer(async(req,res)=>{
1663
1697
  // Reject immutable retry conflicts using the persisted binding before any external destination inspection.
1664
1698
  // A matching retry still validates the current destination below; this does not accept stale environment evidence.
1665
1699
  store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,body.caller_waiting);
1700
+ const assignedWorker=storedTarget??target??'dot';
1701
+ const requiredAdapterCapabilities=jobExecution==='host'
1702
+ ?requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name))
1703
+ :requiredCapabilities;
1704
+ const admitWorkerAdapter=()=>{
1705
+ const adapter=workers.workers.get(assignedWorker)?.adapter;
1706
+ const registryQuestions=adapter==='registry-questions-v1'&&requiredAdapterCapabilities?.includes('identified_questions')
1707
+ &&toolRegistry.hasWorkerTools(assignedWorker,questionDefinitions,{kind:'worker_question'});
1708
+ admitAdapterCapabilities(adapter,requiredAdapterCapabilities,catalogProfile,{registryQuestions});
1709
+ };
1666
1710
  let order=null;
1667
1711
  if(isNew) {
1668
1712
  // checkRetry has already verified the prior owner's capability and the active worker.
@@ -1672,8 +1716,7 @@ const adminServer=http.createServer(async(req,res)=>{
1672
1716
  excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
1673
1717
  render:renderAssignment,
1674
1718
  admitExecution:(p,r)=>{
1675
- const adapterRequired=r.jobExecution==='host'?r.requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name)):r.requiredCapabilities;
1676
- admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
1719
+ admitWorkerAdapter();
1677
1720
  // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
1678
1721
  if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
1679
1722
  },
@@ -1716,10 +1759,14 @@ const adminServer=http.createServer(async(req,res)=>{
1716
1759
  const readiness=order?.check_readiness??null;
1717
1760
  const preflight=order?.preflight??null;
1718
1761
  const defaultValidity=order?.defaultValidity??null;
1719
- if(body.facade_submit_until!==undefined&&!store.hasAssignment(payload.request_id)) {
1720
- const until=body.facade_submit_until;
1721
- if(!Number.isSafeInteger(until)||until>requestStartedAt+600_000) throw new Error('invalid facade submission deadline');
1722
- if(until<=store.nowMs()) throw new Error('facade submission deadline expired');
1762
+ // I/O can outlive a grant or an overlapping submit. Store.submit checks the immutable identity of any replay.
1763
+ if(!store.hasAssignment(payload.request_id)) {
1764
+ if(body.facade_submit_until!==undefined) {
1765
+ const until=body.facade_submit_until;
1766
+ if(!Number.isSafeInteger(until)||until>requestStartedAt+600_000) throw new Error('invalid facade submission deadline');
1767
+ if(until<=store.nowMs()) throw new Error('facade submission deadline expired');
1768
+ }
1769
+ admitWorkerAdapter();
1723
1770
  }
1724
1771
  const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null,body.relationship_id??null,revises,follows,body.caller_waiting);
1725
1772
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
@@ -1857,7 +1904,14 @@ const adminServer=http.createServer(async(req,res)=>{
1857
1904
  if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
1858
1905
  if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1859
1906
  if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1860
- if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1907
+ if(url.pathname==='/tell'&&req.method==='POST') {
1908
+ const text=str(body.text,'text',4096);
1909
+ if(body.request_id!==undefined) {
1910
+ const worker=body.worker===undefined?null:assertTarget(workers,body.worker);
1911
+ return json(res,200,store.tell(text,worker,{requestId:id(body.request_id),capability:req.headers['x-owner-capability']}));
1912
+ }
1913
+ return json(res,200,store.tell(text,body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1914
+ }
1861
1915
  if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
1862
1916
  if(url.pathname==='/relationships'&&req.method==='GET') { adminOperator(req); return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all()}); }
1863
1917
  if(url.pathname==='/relationships/publish'&&req.method==='POST') {
@@ -1876,7 +1930,7 @@ const adminServer=http.createServer(async(req,res)=>{
1876
1930
  const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
1877
1931
  const grants=[
1878
1932
  ...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
1879
- ...store.db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1').all().map(row=>({...row,scope:row.scope===null?null:JSON.parse(row.scope),enforcer:'tool_registry',expires_at:null})),
1933
+ ...toolRegistry.listGrants().map(row=>({...row,enforcer:'tool_registry'})),
1880
1934
  ...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
1881
1935
  ...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
1882
1936
  ...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
package/src/store.mjs CHANGED
@@ -1143,6 +1143,11 @@ export class Store {
1143
1143
  end_source TEXT, last_probe_at TEXT
1144
1144
  ); CREATE UNIQUE INDEX IF NOT EXISTS scoped_worker_breaks_one_open
1145
1145
  ON scoped_worker_breaks(worker) WHERE until IS NULL;`);
1146
+ this.db.exec(`CREATE TABLE IF NOT EXISTS work_messages(
1147
+ message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
1148
+ request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
1149
+ progress_id INTEGER UNIQUE REFERENCES progress(id) ON DELETE SET NULL
1150
+ );`);
1146
1151
  this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
1147
1152
  worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
1148
1153
  subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
@@ -1336,7 +1341,8 @@ export class Store {
1336
1341
  // Use persisted worker progress for the start proxy. A reclaim resets the
1337
1342
  // first workspace call on the single current claim row, so mixing that time
1338
1343
  // in would make a job's measured first start change as it is reclaimed. Notes the bridge writes itself (the resume note)
1339
- // start with `[bridge] ` and are not a start. A finished job with no worker note did start, at an unobserved time.
1344
+ // start with `[bridge] `. Inbox acknowledgments also don't attest to work starting.
1345
+ // A finished job without observed progress started at an unobserved time.
1340
1346
  admissionEvidence(worker,kind,days=7) {
1341
1347
  kind=canonicalKindLabel(kind);
1342
1348
  const since=iso(this.nowMs()-days*86400000);
@@ -1354,6 +1360,7 @@ export class Store {
1354
1360
  (SELECT p.created_at FROM progress p INDEXED BY progress_request WHERE p.request_id=a.request_id
1355
1361
  AND (p.worker IS NULL OR p.worker=a.target_worker)
1356
1362
  AND p.note NOT LIKE '[bridge] %'
1363
+ AND NOT EXISTS (SELECT 1 FROM work_messages m WHERE m.progress_id=p.id)
1357
1364
  ORDER BY p.id LIMIT 1) started
1358
1365
  FROM selected a JOIN lifecycle l ON l.request_id=a.request_id
1359
1366
  LEFT JOIN claims c ON c.request_id=a.request_id`).all(since,worker,kind);
@@ -2686,7 +2693,10 @@ export class Store {
2686
2693
  if(report) { report.trust=TRUST.worker; Object.assign(report,Store.resultAuthority(!!report.late)); }
2687
2694
  const lateRow=this.db.prepare('SELECT summary,truncated,full_sha256,created_at FROM late_evidence WHERE request_id=? ORDER BY created_at LIMIT 1').get(id);
2688
2695
  const late_evidence=lateRow?{...lateRow,truncated:!!lateRow.truncated}:null;
2689
- const progress=this.db.prepare('SELECT note,created_at FROM progress WHERE request_id=? ORDER BY id').all(id);
2696
+ const progress=this.db.prepare(`SELECT p.note,p.created_at,p.worker,m.message_id
2697
+ FROM progress p LEFT JOIN work_messages m ON m.progress_id=p.id
2698
+ WHERE p.request_id=? ORDER BY p.id`).all(id).map(({worker,message_id,...event})=>
2699
+ message_id===null?event:{...event,kind:'ack_message',message_id,acknowledged_by_worker:worker});
2690
2700
  const delivery=this.db.prepare('SELECT id,kind,state,attempts,last_error,argv,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason,terminal_at,terminal_reason FROM notifications WHERE request_id=? ORDER BY created_at').all(id).map(n=>({...n,argv:n.argv?JSON.parse(n.argv):null}));
2691
2701
  const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
2692
2702
  const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
@@ -2852,12 +2862,21 @@ export class Store {
2852
2862
  try { validateOwnerNote(text,this.ownerNotes(priorId)); } catch { return; }
2853
2863
  this.noteInTransaction(priorId,text);
2854
2864
  }
2855
- tell(text,worker='dot') { return this.transaction(() => {
2865
+ tell(text,worker=null,work=null) { return this.transaction(() => {
2866
+ if(work) {
2867
+ this.owner(work.requestId,work.capability);
2868
+ const row=this.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(work.requestId);
2869
+ if(!row||!['queued','claimed'].includes(row.status)) throw new Error('work message requires an open assignment');
2870
+ if(worker!==null&&worker!==row.target_worker) throw new Error('work message worker must match the assignment');
2871
+ worker=row.target_worker;
2872
+ }
2873
+ worker??='dot';
2856
2874
  if(worker==='pool') throw new Error('worker \"pool\" is not supported');
2857
2875
  const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
2858
2876
  this.db.prepare('INSERT INTO messages(message_id,text,text_sha256,preview,created_at,target_worker) VALUES(?,?,?,?,?,?)').run(messageId,text,hash(text),preview,createdAt,worker);
2877
+ if(work) this.db.prepare('INSERT INTO work_messages(message_id,request_id) VALUES(?,?)').run(messageId,work.requestId);
2859
2878
  for(const sub of this.activeSubscriptions()) this.queueMessageEvent(messageId,preview,sub);
2860
- return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview};
2879
+ return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview,...(work?{request_id:work.requestId}:{})};
2861
2880
  }); }
2862
2881
  queueMessageEvent(messageId,title,sub) {
2863
2882
  sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(sub.id);
@@ -2876,19 +2895,40 @@ export class Store {
2876
2895
  }
2877
2896
  return this.getMessage(id);
2878
2897
  }); }
2879
- listMessages(worker='dot') { return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all().filter(r=>this.mayAct(worker,r.message_id)).slice(0,50); }
2898
+ messageBindingForWorker(id,worker) {
2899
+ const binding=this.db.prepare(`SELECT m.request_id,a.status FROM work_messages m
2900
+ JOIN assignments a ON a.request_id=m.request_id WHERE m.message_id=?`).get(id);
2901
+ if(!binding||!this.mayAct(worker,binding.request_id)) return {};
2902
+ return {bound_request_id:binding.request_id,stale:!['queued','claimed'].includes(binding.status)};
2903
+ }
2904
+ listMessages(worker='dot') {
2905
+ return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all()
2906
+ .filter(r=>this.mayAct(worker,r.message_id)).slice(0,50)
2907
+ .map(r=>({...r,...this.messageBindingForWorker(r.message_id,worker)}));
2908
+ }
2880
2909
  getMessage(id,worker=null) {
2881
2910
  if(worker!==null&&!this.mayAct(worker,id)) throw new Error('message not found');
2882
2911
  const row=this.db.prepare('SELECT message_id,text,text_sha256,preview,status,created_at,acknowledged_at FROM messages WHERE message_id=?').get(id);
2883
2912
  if(!row) throw new Error('message not found');
2884
- return row;
2913
+ return worker===null?row:{...row,...this.messageBindingForWorker(id,worker)};
2885
2914
  }
2886
2915
  ackMessage(id,worker='dot') { return this.transaction(() => {
2887
2916
  if(!this.mayAct(worker,id)) throw new Error('message not found');
2888
2917
  const row=this.db.prepare('SELECT status FROM messages WHERE message_id=?').get(id);
2889
2918
  if(!row) throw new Error('message not found');
2890
2919
  if(row.status==='withdrawn') throw new Error('message withdrawn');
2891
- if(row.status!=='acknowledged') this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(this.stamp(),id);
2920
+ if(row.status!=='acknowledged') {
2921
+ const at=this.stamp();
2922
+ this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(at,id);
2923
+ const binding=this.db.prepare(`SELECT m.request_id FROM work_messages m JOIN assignments a ON a.request_id=m.request_id
2924
+ WHERE m.message_id=? AND a.status IN ('queued','claimed')`).get(id);
2925
+ if(binding) {
2926
+ // This receipt records worker-inbox acknowledgment while work is open. It does not wake the parent.
2927
+ const event=this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)')
2928
+ .run(binding.request_id,`Worker inbox ${worker} acknowledged message ${id}.`,at,worker);
2929
+ this.db.prepare('UPDATE work_messages SET progress_id=? WHERE message_id=?').run(event.lastInsertRowid,id);
2930
+ }
2931
+ }
2892
2932
  return this.getMessage(id);
2893
2933
  }); }
2894
2934
  // Resume wake. DALAN_RESUME_IDLE_MS (default 120000; 0 disables everything below). A claim is idle when its holder made no
@@ -3049,7 +3089,7 @@ export class Store {
3049
3089
  .filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
3050
3090
  .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}:triageFields(JSON.parse(a.payload),a))}));
3051
3091
  if(batch||handoffExclusions!==null) return assignments;
3052
- const messages=this.listMessages(worker).map(m=>({kind:'message',request_id:m.message_id,message_id:m.message_id,title:m.preview,created_at:m.created_at})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
3092
+ 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));
3053
3093
  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,
3054
3094
  ...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
3055
3095
  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.'}));
@@ -37,6 +37,10 @@ export const schemaHash = ({ name, description, input_schema, class: toolClass,
37
37
  const leaseMs = impl => (impl?.timeoutMs ?? HANDLER_TIMEOUT_MS) + LEASE_MARGIN_MS;
38
38
  const iso = ms => new Date(ms).toISOString();
39
39
  const workerName = worker => typeof worker === 'string' ? worker : worker?.name;
40
+ // Older dispatchers ignore scope on ordinary grants. The reserved key never matches an authenticated worker.
41
+ const scopedGrantWorker = worker => '@' + worker;
42
+ const publicGrantWorker = worker => worker.startsWith('@') ? worker.slice(1) : worker;
43
+ const grantScope = row => row.scope === null ? null : JSON.parse(row.scope);
40
44
  const configStrings = (value, out = []) => {
41
45
  if (typeof value === 'string') out.push(value);
42
46
  else if (Array.isArray(value)) value.forEach(v => configStrings(v, out));
@@ -64,10 +68,22 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
64
68
  // so a changed description, schema, class, handler kind or config (target thread, argv template) or grant set moves it.
65
69
  // A handler kind that declares an effect class (impl.effectClass) fixes the class of every tool that uses it. A stored row
66
70
  // whose class disagrees (written by an older build, or by hand) is served and enforced as the declared class.
67
- const toolClass = row => handlers[JSON.parse(row.handler).kind]?.effectClass ?? row.class;
71
+ const handlerFor = row => handlers[JSON.parse(row.handler).kind];
72
+ const toolClass = row => handlerFor(row)?.effectClass ?? row.class;
73
+ const readGrant = (tool, worker) => db.prepare('SELECT worker,scope FROM tool_grants WHERE tool=? AND worker=?').get(tool, worker);
74
+ const currentGrant = (row, worker) => {
75
+ if (typeof worker !== 'string' || !WORKER.test(worker)) return null;
76
+ const grant = db.prepare('SELECT worker,scope FROM tool_grants WHERE tool=? AND worker IN (?,?) ORDER BY worker LIMIT 1')
77
+ .get(row.name, worker, scopedGrantWorker(worker));
78
+ if (!grant || grant.worker === worker) return grant;
79
+ if (!handlerFor(row)?.authorizeGrant || toolClass(row) !== 'read') return null;
80
+ const scope = grantScope(grant);
81
+ return scope && Date.parse(scope.expires_at) > now() ? grant : null;
82
+ };
68
83
  const callerHash = (row, worker) => sha256(canonical({
69
84
  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,scope FROM tool_grants WHERE worker=? ORDER BY tool').all(worker),
85
+ caller: worker, grants: db.prepare('SELECT tool,scope FROM tool_grants WHERE worker IN (?,?) ORDER BY tool,worker')
86
+ .all(worker,scopedGrantWorker(worker)),
71
87
  }));
72
88
  // Owner views retain the registration/audit definition hash; only worker views pin caller grants.
73
89
  // Never bind an absent owner caller to the worker-specific SQLite query.
@@ -142,12 +158,30 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
142
158
  const row = getTool(name);
143
159
  if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
144
160
  if (typeof worker !== 'string' || !WORKER.test(worker)) refuse('invalid_tool', 'worker must be a worker name');
145
- 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]}');
146
- if(scope!==undefined && scope!==null && JSON.parse(row.handler).kind!=='t3_control') refuse('invalid_tool','thread scope applies only to T3 control grants');
161
+ const impl = handlerFor(row);
162
+ const restricted = scope != null && typeof impl?.prepareGrant === 'function' && toolClass(row) === 'read';
163
+ if (scope != null && !restricted) {
164
+ if (!scope || Object.keys(scope).join() !== 'threads' || !Array.isArray(scope.threads) ||
165
+ scope.threads.some(id=>typeof id!=='string'||!id||id.length>128)) refuse('invalid_tool', 'scope must be {threads: [thread IDs]}');
166
+ if (JSON.parse(row.handler).kind !== 't3_control') refuse('invalid_tool','thread scope applies only to T3 control grants');
167
+ }
147
168
  atomically(() => {
148
- if (kind === 'grant' && scope === undefined) db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name,worker,iso(now()));
149
- 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));
150
- else { db.prepare('DELETE FROM tool_grants WHERE tool=? AND worker=?').run(name, worker); dropQueued(name, worker); }
169
+ const reserved = scopedGrantWorker(worker);
170
+ const remove = db.prepare('DELETE FROM tool_grants WHERE tool=? AND worker=?');
171
+ if (kind === 'revoke') {
172
+ remove.run(name, worker);
173
+ remove.run(name, reserved);
174
+ dropQueued(name, worker);
175
+ } else if (restricted) {
176
+ const bound = impl.prepareGrant({ worker, scope });
177
+ remove.run(name, worker);
178
+ db.prepare('INSERT INTO tool_grants(tool,worker,granted_at,scope) VALUES(?,?,?,?) ON CONFLICT(tool,worker) DO UPDATE SET scope=excluded.scope,granted_at=excluded.granted_at')
179
+ .run(name, reserved, iso(now()), JSON.stringify(bound));
180
+ } else {
181
+ if (readGrant(name, reserved)) refuse('invalid_tool', 'revoke the assignment grant before adding a worker-wide grant');
182
+ if (scope === undefined) db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name,worker,iso(now()));
183
+ else 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));
184
+ }
151
185
  bump();
152
186
  record({ kind, tool: name, worker, outcome: 'ok', schema_hash: row.schema_hash });
153
187
  });
@@ -158,14 +192,29 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
158
192
  function list() {
159
193
  return db.prepare('SELECT * FROM registered_tools ORDER BY name').all().map(row => ({
160
194
  ...view(row), handler: JSON.parse(row.handler), enabled: row.enabled === 1, created_at: row.created_at,
161
- workers: db.prepare('SELECT worker FROM tool_grants WHERE tool=? ORDER BY worker').all(row.name).map(g => g.worker),
195
+ workers: db.prepare('SELECT worker FROM tool_grants WHERE tool=? ORDER BY worker').all(row.name).map(g => publicGrantWorker(g.worker)),
162
196
  uncertain: db.prepare('SELECT count(*) n FROM tool_outbox WHERE tool=? AND sent_at IS NULL AND uncertain_at IS NOT NULL').get(row.name).n,
163
197
  }));
164
198
  }
199
+ function availableWorkerTools(name) {
200
+ if (typeof name !== 'string' || !WORKER.test(name)) return [];
201
+ return db.prepare("SELECT t.* FROM registered_tools t WHERE t.enabled=1 AND json_extract(t.handler,'$.kind')!='t3_control' AND EXISTS (SELECT 1 FROM tool_grants g WHERE g.tool=t.name AND g.worker IN (?,?)) ORDER BY t.name")
202
+ .all(name, scopedGrantWorker(name)).filter(row => currentGrant(row, name));
203
+ }
165
204
  function listTools(worker) {
166
205
  const name = workerName(worker);
167
- 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));
168
- return { registry_version: registryVersion(), tools };
206
+ return { registry_version: registryVersion(), tools: availableWorkerTools(name).map(row => view(row, name)) };
207
+ }
208
+ function hasWorkerTools(worker, definitions, handler) {
209
+ const available=new Map(availableWorkerTools(workerName(worker)).map(row=>[row.name,row]));
210
+ return definitions.every(definition=>{
211
+ const row=available.get(definition.name);
212
+ if(!row||toolClass(row)!=='write'||canonical(JSON.parse(row.handler))!==canonical(handler)) return false;
213
+ const actual=JSON.parse(row.input_schema), expected=compileSchema(definition.inputSchema);
214
+ // An older registration can retain optional protocol fields after a catalog switch.
215
+ return canonical([...(actual.required??[])].sort())===canonical([...(expected.required??[])].sort())
216
+ &&Object.entries(expected.properties).every(([key,schema])=>canonical(actual.properties?.[key])===canonical(schema));
217
+ });
169
218
  }
170
219
  function lastChange() {
171
220
  const row = db.prepare("SELECT at,kind,tool,worker,schema_hash FROM tool_registry_log WHERE kind IN ('register','remove','grant','revoke','enable','disable') ORDER BY id DESC LIMIT 1").get();
@@ -234,13 +283,16 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
234
283
  const stale = () => ({ outcome: 'stale_registry', error: new RegistryError('stale_registry', 'call list_tools again') });
235
284
  const authorize = (current, previousHash) => {
236
285
  if (!current || JSON.parse(current.handler).kind === 't3_control') return unavailable('unknown_tool');
237
- if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(current.name, name)) return unavailable('not_granted');
286
+ const grant = currentGrant(current, name);
287
+ if (!grant) return unavailable('not_granted');
288
+ const scope = grant.worker === scopedGrantWorker(name) ? grantScope(grant) : null;
289
+ if (scope && !handlerFor(current).authorizeGrant(scope, args)) return unavailable('not_granted');
238
290
  if (current.enabled !== 1) return unavailable('disabled');
239
291
  const cls = toolClass(current);
240
292
  if (callClass !== cls) return { outcome: 'wrong_class', error: new RegistryError('wrong_class', 'wrong class for this tool; see list_tools') };
241
293
  const hash = callerHash(current, name);
242
294
  if ((pinnedHash === undefined ? cls === 'write' : pinnedHash !== hash) || (previousHash !== undefined && previousHash !== hash)) return stale();
243
- return { hash };
295
+ return { hash, scope };
244
296
  };
245
297
  const deny = ({ outcome, error }) => { if (error) done(outcome, error); };
246
298
  const initial = authorize(row);
@@ -251,7 +303,7 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
251
303
  const impl = handlers[config.kind];
252
304
  if (impl?.requireCurrentRead && key !== undefined)
253
305
  done('invalid_arguments', new RegistryError('invalid_arguments', 'omit idempotency_key for live reads'));
254
- const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context };
306
+ const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context, grantScope: initial.scope };
255
307
  const assertArguments = () => {
256
308
  const errors = validateValue(JSON.parse(row.input_schema), args);
257
309
  if (errors.length) done('invalid_arguments', new RegistryError('invalid_arguments', errors.slice(0, 5).join('; ')));
@@ -441,7 +493,14 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
441
493
  }
442
494
  return threads;
443
495
  }
444
- return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, initializeWorkerTools, t3Threads };
496
+ function listGrants() {
497
+ return db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1')
498
+ .all().map(row => {
499
+ const scope = grantScope(row);
500
+ return {...row,worker:publicGrantWorker(row.worker),scope,expires_at:scope?.expires_at??null};
501
+ });
502
+ }
503
+ return { register, remove, grant, revoke, list, listGrants, listTools, hasWorkerTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, initializeWorkerTools, t3Threads };
445
504
  }
446
505
 
447
506
  // ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
@@ -57,6 +57,10 @@ const rules = [
57
57
  [/^regression_test_scope: /, m => ({ verdict: 'clarify', code: 'missing_test_scope', field: 'scope_paths', message: m.input, fix: 'add a test path to scope_paths, or drop the regression-test request from expected_output' })],
58
58
  [/^BLOCKED: check prerequisites unmet: /, m => ({ verdict: 'defer', code: 'check_prerequisites_unmet', field: 'checks', message: m.input.replace(/^BLOCKED: /, ''), fix: 'install the missing prerequisite on the bridge host, or submit with --execution worker', retry: true, blocking: true })],
59
59
  [/^BLOCKED: check metadata unreadable/, m => ({ verdict: 'reject', code: 'check_metadata_unreadable', field: 'checks', message: m.input.replace(/^BLOCKED: /, ''), fix: 'fix the check metadata file at base_sha, or submit with --execution worker' })],
60
+ [/^capability_not_available: (\w+) \((adapter [\w-]+ declares (?:unknown|unsupported))\)$/, m => ({
61
+ verdict: 'reject', code: 'capability_unsupported', field: 'required_capabilities', message: `${m[1]}: ${m[2]}`,
62
+ fix: 'choose a worker adapter and catalog profile that verify the required capability',
63
+ })],
60
64
  [/^capability_not_available: (\w+) \((.*)\)$/, m => /declares unsupported/.test(m[2])
61
65
  ? { verdict: 'reject', code: 'capability_unsupported', field: 'required_capabilities', message: `${m[1]} ${m[2]}`, fix: 'drop this required capability or run the job where the backend supports it' }
62
66
  : { verdict: 'defer', code: 'capability_unavailable', field: 'required_capabilities', message: `${m[1]}: ${m[2]}`, fix: 'wait until the host provides it (install the executor), or submit with --execution worker', retry: true, blocking: true }],