@tnunamak/dalan 0.9.0 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,6 +74,10 @@ async function cwdForProject(a) {
74
74
  return project.workspaceRoot;
75
75
  }
76
76
 
77
+ export function destinationDeniedEvent(tool, worker, callId) {
78
+ return {kind:'t3_destination_denied',tool,worker,call_id:callId,reason:'no_live_destination_grant'};
79
+ }
80
+
77
81
  export async function runT3Tool(name, a) {
78
82
  switch(name) {
79
83
  case 't3_thread_list':
@@ -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 ----------------------------------------------------------------------------
@@ -398,7 +398,10 @@ export async function runHosted({ options, env, out, input, signal, errorContext
398
398
 
399
399
  const trialOver = () => expired || (trialEndsAt !== null && clock.now() >= trialEndsAt);
400
400
  if (trialMs !== null) {
401
- const expiry = new Promise(resolve => { expireTimer = setTimeout(() => { expired = true; resolve(); }, Math.max(0, trialEndsAt - clock.now())); expireTimer.unref?.(); });
401
+ const expiry = new Promise(resolve => {
402
+ expireTimer = (clock.setTimeout ?? setTimeout)(() => { expired = true; resolve(); }, Math.max(0, trialEndsAt - clock.now()));
403
+ expireTimer?.unref?.();
404
+ });
402
405
  routeGone = Promise.race([routeGone, expiry]);
403
406
  }
404
407
  const trialLeft = () => trialEndsAt === null ? '' : ` Local shutdown limit: ${timeLeft(trialEndsAt - clock.now())}. The temporary link can stop earlier.`;
@@ -530,7 +533,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
530
533
  }
531
534
  };
532
535
  lines.close();
533
- clearTimeout(expireTimer);
536
+ if (expireTimer !== null) (clock.clearTimeout ?? clearTimeout)(expireTimer);
534
537
  await cleanup('identity watcher cleanup', () => identityWatcher?.stop());
535
538
  // Withdraw handoff, revoke the trial's app credentials, then close the retained route.
536
539
  let ignoredHandoffCleanup = false;
@@ -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 }],