@tnunamak/dalan 0.8.5 → 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.
@@ -438,8 +438,9 @@ export function validateNamedCheckTargets(namedPaths, scan, outputSet) {
438
438
  throw namedCheckError(`entry ${index+1}: pin a revision with the regular test file, or declare a new file in output_paths`,index+1);
439
439
  }
440
440
  }
441
- export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker}={}) {
441
+ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker,inheritedExclusions=[],allowPagedReadScope=false,pagedReadPrior=null}={}) {
442
442
  const warn=message=>{if(warnings&&!warnings.includes(message)) warnings.push(message);};
443
+ if(assignment&&Object.hasOwn(assignment,'paged_read_scope')) throw new Error('only the bridge can record a paged read scope');
443
444
  let p;
444
445
  try { p=loadPolicy(); } catch(error) { throw infrastructureError(error.message); }
445
446
  let rendered=renderAssignment(assignment);
@@ -451,7 +452,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
451
452
  const total=instructionBytes(r);
452
453
  if(total>submissionLimits.instructions) throw Object.assign(new Error(`task instructions: ${total} UTF-8 bytes exceeds ${submissionLimits.instructions}; cut at least ${total-submissionLimits.instructions} bytes`),{expandedPayload:r});
453
454
  };
454
- checkInstructionSize(rendered);
455
+ checkInstructionSize(pagedReadPrior?{...rendered,scope_paths:[]}:rendered);
455
456
  if([authority,grantedAuthority].some(pattern=>pattern.test([rendered.brief,rendered.expected_output,scopeText].join('\n')))) throw new Error('live-slot or expanded-authority claim in instructions');
456
457
  if(hasSecretContent(rendered)) throw new Error('hard sensitive content exclusion');
457
458
  // Labelled values are medium precision: every output sink masks them, so intake warns instead of refusing.
@@ -487,9 +488,14 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
487
488
  const rule=entry?'owner sensitive_paths entry '+entry:'soft sensitive name: '+(/auth/i.test(base)?'auth':/secret/i.test(base)?'secret':/credential/i.test(base)?'credential':/(?:^|[_.-])sign(?:ing|ature)?(?=[_.-]|$)/i.test(base)?'signing':'credential-style token name');
488
489
  return sensitivePathError(`sensitive scope path: ${file}; ${rule}; rename the file or redact it and give it a name that does not look like a secret, or leave it out of scope_paths`,file);
489
490
  };
491
+ const priorOmittedPaths=new Set(inheritedExclusions.map(entry=>entry.path));
492
+ const priorExcluded=new Set([...priorOmittedPaths].map(outputPathKeys[3]));
490
493
  function inspectPath(file) {
491
494
  // A router group cannot hide a sensitive name: `(x).env` is also checked as `.env`.
492
495
  if(hardSensitive(file)) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
496
+ const parts=outputPathKeys[3](file).split('/');
497
+ if(priorExcluded.size&&parts.some((_,i)=>priorExcluded.has(parts.slice(0,i+1).join('/'))))
498
+ throw sensitivePathError(`sensitive scope path: ${file}; the prior assignment excluded this path`,file);
493
499
  if((softName(file)||policyEntry(file))&&(!exception||file!==exception.path)) throw sensitiveRefusal(file);
494
500
  }
495
501
  for(const file of scope) inspectPath(file);
@@ -505,6 +511,23 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
505
511
  }
506
512
  }
507
513
  const outputSet=new Set(outputs);
514
+ const canPage=allowPagedReadScope&&excludeSensitive&&sensitiveScopeOverride===null&&rendered.execution_scope==='read-only'&&
515
+ !outputs.length&&input&&input.input_patch===undefined&&(!input.head_sha||input.head_sha===input.base_sha);
516
+ if(pagedReadPrior) {
517
+ const prior=assignmentInput(pagedReadPrior),priorFiles=new Set(pagedReadPrior.scope_paths);
518
+ if(!canPage||input.github_repo!==prior.github_repo||input.base_sha!==prior.base_sha||scope.some(file=>!priorFiles.has(file))) {
519
+ throw new Error('a correction must keep the pinned revision and stay within the prior paged read scope');
520
+ }
521
+ }
522
+ const paged=(files)=>{
523
+ const note='Use list_files to see the approved files. Use read_file to read them at the pinned revision.';
524
+ const brief=rendered.brief.includes(note)?rendered.brief:`${rendered.brief}\n\n${note}`;
525
+ cap(brief,submissionLimits.brief,'brief');
526
+ const result={...rendered,brief,scope_paths:files,paged_read_scope:true,
527
+ ...(rendered.read_list!==undefined?{read_list:files}:{}),...(rendered.read_paths!==undefined?{read_paths:files}:{})};
528
+ checkInstructionSize({...result,scope_paths:[]});
529
+ return result;
530
+ };
508
531
  const namedPaths=submissionNamedCheckPaths(rendered,{review,policyPaths:p.sensitive_paths});
509
532
  // Unified-diff /dev/null markers are sentinels, not filesystem requests. An exact exclusion diagnostic grants no
510
533
  // read permission. Keep scanning its content for secrets above and checking scope/diff paths below; remove only
@@ -541,7 +564,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
541
564
  // Every implementation directory keeps its write grant while withholding sensitive files.
542
565
  // This must not depend on an opt-in: the worker receives no access to hard or soft secret paths.
543
566
  const withholdImplementation=rendered.execution_scope==='implementation';
544
- const dropped=[];let narrowedScope=null;
567
+ const dropped=input?[...inheritedExclusions]:[];let narrowedScope=null;
545
568
  const firstPass=mentionedPaths(text,scope);
546
569
  for(const file of firstPass) {
547
570
  const bare=bareToken(file)&&!firstPass.explicit.has(file);
@@ -566,7 +589,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
566
589
  // A free-form read-only or review assignment may grow its scope by the files its own brief names and its PR changes: the
567
590
  // submitter asked for them, each still passes inspectPath, and the workspace enforces the result. Implementation work,
568
591
  // structured briefs and explicit read lists keep the scope exactly as declared.
569
- const growable=(rendered.execution_scope==='read-only'||review)&&rendered.objective===undefined&&rendered.read_paths===undefined&&rendered.read_list===undefined&&!scope.includes('.');
592
+ const growable=!pagedReadPrior&&(rendered.execution_scope==='read-only'||review)&&rendered.objective===undefined&&rendered.read_paths===undefined&&rendered.read_list===undefined&&!scope.includes('.');
570
593
  const added=[],undeclared=[],fixable=[],ambiguous=[],mentionedAs=new Map();
571
594
  // Review mode cannot write (apply_patch refuses review submissions), so growing a review assignment's scope adds read access only.
572
595
  const maxGrowth=200;
@@ -695,6 +718,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
695
718
  // sensitive files. Read-only directory scopes are narrowed to exclude them.
696
719
  // Named paths and patch paths still refuse above and below.
697
720
  for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
721
+ if(priorOmittedPaths.has(file)) continue;
698
722
  if(withholdImplementation&&withheldRepoPath(file,p.sensitive_paths)) {
699
723
  dropped.push({path:file,reason:isSensitiveRepoPath(file,p.sensitive_paths)?sensitiveReason(file):'sensitive ancestor directory (withheld)'});continue;
700
724
  }
@@ -719,9 +743,18 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
719
743
  if(!dropped.some(d=>d.path===file)) dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
720
744
  }
721
745
  }
722
- // A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
723
- // would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
724
- if(dropped.length) narrowedScope=withholdImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
746
+ if(dropped.length) {
747
+ try {
748
+ narrowedScope=withholdImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
749
+ } catch(error) {
750
+ if(error.code!=='scope_representation_limit'||!canPage||scan.diff||scan.diffFiles.length||!Array.isArray(scan.regularFiles)) throw error;
751
+ // Persist exact approved files in the ordinary scope field. Older bridge
752
+ // binaries can enforce those paths without understanding paging.
753
+ const files=pagedReadFiles(scan.regularFiles,scope,dropped);
754
+ if(!files?.length) throw error;
755
+ return paged(files);
756
+ }
757
+ }
725
758
  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}`);
726
759
  const inspectPatchPath=file=>{
727
760
  inspectPath(file);
@@ -751,6 +784,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
751
784
  if(input.input_patch&&!/^diff --git /m.test(input.input_patch)) throw new Error('incomplete input patch');
752
785
  } else if(scope.length) throw new Error('scope_paths require pinned repository input');
753
786
  // Persist exactly the normalized scope used above, including the no-growth path.
787
+ if(pagedReadPrior) return paged(scope);
754
788
  const stored=rendered.scope_paths,same=Array.isArray(stored)&&stored.length===scope.length&&stored.every((path,i)=>path===scope[i]);
755
789
  const normalized=!same&&(stored!==undefined||scope.length>0)?{...rendered,scope_paths:[...scope]}:rendered;
756
790
  if(!dropped.length) {const done=withOutputPaths(withAllowList(normalized,warn));checkInstructionSize(done);return done;}
@@ -772,6 +806,23 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
772
806
  // The scope entries that cover every file under `scope` except `bad`: a directory with no bad file below it stays whole, one with
773
807
  // a bad file is replaced by its children. Throws when that needs more entries than a scope should hold.
774
808
  const maxNarrowedEntries=200;
809
+ function pagedReadFiles(regularFiles,scope,dropped) {
810
+ const key=path=>path.normalize('NFC').toLowerCase();
811
+ const excluded=new Set(dropped.map(entry=>key(entry.path)));
812
+ const parents=new Set();
813
+ for(const path of excluded) {
814
+ for(let i=path.indexOf('/');i>=0;i=path.indexOf('/',i+1)) parents.add(path.slice(0,i));
815
+ }
816
+ const matchesExcluded=path=>{
817
+ if(parents.has(path)||excluded.has(path)) return true;
818
+ for(let i=path.indexOf('/');i>=0;i=path.indexOf('/',i+1)) if(excluded.has(path.slice(0,i))) return true;
819
+ return false;
820
+ };
821
+ const files=regularFiles.filter(path=>within(path,scope)&&!matchesExcluded(key(path)));
822
+ if(files.some(path=>!isLiteralScopePath(path)||path.split('/').some(part=>part.toLowerCase()==='.git')||hasSecretContent(path))) return null;
823
+ // Bound the persisted and machine-readable list independently of the brief.
824
+ return bytes(JSON.stringify(files))<=256*1024?files:null;
825
+ }
775
826
  export function narrowScope(scope,files,bad) {
776
827
  const badSet=new Set(bad),badDirs=new Set(),children=new Map(),add=(dir,child)=>{if(!children.has(dir)) children.set(dir,new Set());children.get(dir).add(child);};
777
828
  for(const file of files) {
@@ -789,7 +840,7 @@ export function narrowScope(scope,files,bad) {
789
840
  for(const entry of scope) visit(entry==='.'?'':entry);
790
841
  const narrowed=[...new Set(out)];
791
842
  if(!narrowed.length) throw sensitivePathError(`sensitive scope path: ${bad[0]} (every file in the scope is sensitive)`,bad[0]);
792
- if(narrowed.length>maxNarrowedEntries) throw new Error(`sensitive scope path: ${bad[0]} (too many files to exclude from ${scope.map(s=>`"${s}"`).join(', ')}: dropping ${bad.length} sensitive file(s) would need ${narrowed.length} scope entries, over the ${maxNarrowedEntries} limit; submit a narrower scope that avoids them)`);
843
+ if(narrowed.length>maxNarrowedEntries) throw Object.assign(new Error(`sensitive scope path: ${bad[0]} (too many files to exclude from ${scope.map(s=>`"${s}"`).join(', ')}: dropping ${bad.length} sensitive file(s) would need ${narrowed.length} scope entries, over the ${maxNarrowedEntries} limit; submit a narrower scope that avoids them)`),{code:'scope_representation_limit'});
793
844
  const unnameable=narrowed.find(entry=>{try{paths([entry],'scope_paths');return false;}catch{return true;}});
794
845
  if(unnameable!==undefined) throw new Error(`sensitive scope path: ${bad[0]} (cannot narrow the scope: ${unnameable} has a name that scope_paths cannot hold; exclude it or name the files you want)`);
795
846
  return paths(narrowed,'scope_paths');
@@ -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);
@@ -249,7 +301,9 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
249
301
  if (keyError) done('invalid_arguments', new RegistryError('invalid_arguments', keyError));
250
302
  const config = JSON.parse(row.handler);
251
303
  const impl = handlers[config.kind];
252
- const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context };
304
+ if (impl?.requireCurrentRead && key !== undefined)
305
+ done('invalid_arguments', new RegistryError('invalid_arguments', 'omit idempotency_key for live reads'));
306
+ const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context, grantScope: initial.scope };
253
307
  const assertArguments = () => {
254
308
  const errors = validateValue(JSON.parse(row.input_schema), args);
255
309
  if (errors.length) done('invalid_arguments', new RegistryError('invalid_arguments', errors.slice(0, 5).join('; ')));
@@ -272,6 +326,8 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
272
326
  if (authority.error || binding === undefined) return authority;
273
327
  const scoped = claimAuthority();
274
328
  if (scoped.error || scoped.binding === binding) return scoped;
329
+ if (impl.requireCurrentRead)
330
+ return { outcome: 'authorization_failed', error: new RegistryError('authorization_failed', 'the claim changed during the read') };
275
331
  return { outcome: 'idempotency_conflict', error: new RegistryError('idempotency_conflict', 'the call no longer belongs to the same claim authority') };
276
332
  };
277
333
  const mayRetakePending = callClass === 'read' || (impl?.recoverPendingWrite === true && binding !== undefined);
@@ -358,6 +414,8 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
358
414
  settle({ ok: false, code: 'handler_failed', message, retryable: error?.notDelivered === true });
359
415
  done('handler_failed', new RegistryError('handler_failed', message));
360
416
  }
417
+ // Replies containing current private data may not outlive the grant that permitted the read.
418
+ if (impl?.requireCurrentRead) deny(latestAuthority());
361
419
  const capped = capResult(result);
362
420
  settle({ ok: true, result: capped });
363
421
  done('ok');
@@ -435,7 +493,14 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
435
493
  }
436
494
  return threads;
437
495
  }
438
- 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 };
439
504
  }
440
505
 
441
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 }],
package/src/workspace.mjs CHANGED
@@ -114,7 +114,7 @@ function closedWorkspace(a,requestId,claimId,claimEpoch,currentEpoch) {
114
114
  }
115
115
  const CHECK_GUIDANCE='run_check runs a listed check in the bridge sandbox on this claim\'s workspace, with your applied patches. It does not run on your machine. Call run_check with check_id (not check or name) after apply_patch and before finish. Its receipt is bridge-verified evidence; a test you ran yourself is not. available_check_details says what each id runs. If you finish with a patch and have not run the default check on it, the bridge runs default itself before it stores your report.';
116
116
  function git(args,opts={}) { const r=spawnSync('git',args,{encoding:'utf8',timeout:10000,maxBuffer:12*1024*1024,...opts,env:gitEnv(opts.env)}); if(r.error||r.status!==0) throw new Error(`git failed: ${(r.stderr||r.error?.message||'').slice(0,300)}`); return r.stdout; }
117
- function relative(p,allowDot=false) { if (allowDot && (p===undefined||p==='')) return ''; if(typeof p!=='string'||!p||Buffer.byteLength(p)>1024||p.includes('\0')||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..'||x==='.git'||x.includes('\\'))) throw new Error('invalid project-relative path'); return p; }
117
+ function relative(p,allowDot=false) { if (allowDot && (p===undefined||p==='')) return ''; if(typeof p!=='string'||!p||Buffer.byteLength(p)>1024||p.includes('\0')||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..'||x.toLowerCase()==='.git'||x.includes('\\'))) throw new Error('invalid project-relative path'); return p; }
118
118
  function safePath(dir,p,existing=false) { p=relative(p); let cursor=dir; for(const part of p.split('/')) { cursor=path.join(cursor,part); try { if(fs.lstatSync(cursor).isSymbolicLink()) throw new Error('symlink traversal denied'); } catch(e) { if(e.code!=='ENOENT') throw e; if(existing) throw new Error('file not found'); } } return cursor; }
119
119
  // scope_paths is the assignment's read/write allow-list (submission-policy `within`). No scope_paths, or the repo-wide
120
120
  // scope ".", means unrestricted, as before. Entries are normalised the same way submission-policy normalises them.
@@ -127,6 +127,15 @@ export const isExcludedPath=(p,excluded)=>{const parts=canonicalPath(p).split('/
127
127
  function scopeOf(assignment) {
128
128
  const raw=assignment.scope_paths, excluded=new Set((assignment.scope_excluded||[]).map(d=>canonicalPath(d.path)));
129
129
  const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
130
+ if(assignment.paged_read_scope===true) {
131
+ const files=new Set(scope),dirs=new Set();
132
+ for(const file of files) {
133
+ for(let i=file.indexOf('/');i>=0;i=file.indexOf('/',i+1)) dirs.add(file.slice(0,i));
134
+ }
135
+ const sensitive=sensitivePolicyPaths();
136
+ if(sensitive.error) throw new Error('sensitive_policy_unavailable');
137
+ return {files,dirs,excluded,outputs:new Set(),sensitive};
138
+ }
130
139
  const paths=!scope.length||scope.includes('.')?null:scope;
131
140
  const outputs=outputsOf(assignment);
132
141
  const sensitive=assignment.execution_scope==='implementation'&&excluded.size?sensitivePolicyPaths():null;
@@ -144,9 +153,10 @@ function existsAtHead(dir,file) {
144
153
  if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
145
154
  return r.stdout.length>0;
146
155
  }
147
- const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
156
+ const inScope=(p,scope)=>!scope||(scope.files?scope.files.has(p):!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
148
157
  // A directory that holds a scope entry may be listed so the walk can reach it.
149
- const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
158
+ const leadsToScope=(p,scope)=>!scope||!isExcludedPath(p,scope.excluded)&&
159
+ (scope.files?scope.dirs.has(p)||inScope(p,scope):!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`)));
150
160
  function outputDirectoryHint(file,outputs) {
151
161
  const parent=[...outputs].find(p=>file.startsWith(`${p}/`));
152
162
  return parent?` output_paths entry ${parent} names one new file, not a directory. List each new file in output_paths (for example ${file}); ask the owner to resubmit with the exact file paths.`:'';
@@ -157,7 +167,7 @@ function realRelative(dir,file,fallback) { try { const rel=path.relative(fs.real
157
167
  function requireScope(p,scope) { if(!inScope(p,scope)) throw new Error(`path outside scope_paths: ${p}${outputDirectoryHint(p,scope?.outputs??[])}`); }
158
168
  // Walk from `start` and stop at `max` files. Large repos used to throw 'file tree limit' on every call,
159
169
  // so the worker could not list anything; now it gets the first `max` files and truncated:true.
160
- export function guardedFiles(dir,start='',max=2000,scope=null,after='') { const out=[];let truncated=false,passed=!after; function walk(base,depth) { if(out.length>=max) { truncated=true; return; } if(depth>16) { truncated=true; return; } const entries=fs.readdirSync(path.join(dir,base),{withFileTypes:true}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0); for(const ent of entries) { if(out.length>=max) { truncated=true; return; } if(ent.name==='.git') continue; const rel=base?`${base}/${ent.name}`:ent.name; if(ent.isSymbolicLink()) continue; if(ent.isDirectory()) { if(leadsToScope(rel,scope)) walk(rel,depth+1); } else if(ent.isFile()&&inScope(rel,scope)) { if(!passed) { if(rel===after) passed=true; } else out.push(rel); } } } if(start&&!fs.lstatSync(path.join(dir,start)).isDirectory()) return {files:inScope(start,scope)?[start]:[],truncated:false}; walk(start,0); if(!passed) throw new Error('cursor not found: list again from the start'); return {files:out,truncated}; }
170
+ export function guardedFiles(dir,start='',max=2000,scope=null,after='') { const out=[];let truncated=false,passed=!after; function walk(base,depth) { if(out.length>=max) { truncated=true; return; } if(depth>16) { truncated=true; return; } const entries=fs.readdirSync(path.join(dir,base),{withFileTypes:true}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0); for(const ent of entries) { if(out.length>=max) { truncated=true; return; } if(ent.name.toLowerCase()==='.git') continue; const rel=base?`${base}/${ent.name}`:ent.name; if(ent.isSymbolicLink()) continue; if(ent.isDirectory()) { if(leadsToScope(rel,scope)) walk(rel,depth+1); } else if(ent.isFile()&&inScope(rel,scope)) { if(!passed) { if(rel===after) passed=true; } else out.push(rel); } } } if(start&&!fs.lstatSync(path.join(dir,start)).isDirectory()) return {files:inScope(start,scope)?[start]:[],truncated:false}; walk(start,0); if(!passed) throw new Error('cursor not found: list again from the start'); return {files:out,truncated}; }
161
171
  function patchPaths(patch) {
162
172
  const found=[];let current=null,inHeader=false,oldHeader=false,newHeader=false;
163
173
  for(const line of patch.split('\n')) {
@@ -492,6 +502,79 @@ export function excludedPathsAccountedAtBase(mirror,assignment) {
492
502
  try { excluded=new Set(assignment.scope_excluded.map(entry=>relative(entry.path))); } catch { return false; }
493
503
  return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>!withheldRepoPath(file,policy.paths));
494
504
  }
505
+ // Internal producer only: the caller must supply a persisted, validated assignment
506
+ // and its trusted mirror. Do not accept a request-supplied path/ref or reuse checkout files.
507
+ export const SCOPED_SOURCE_MAX_BYTES=512*1024;
508
+ export function pinnedScopedSource(mirror,assignment) {
509
+ if(assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
510
+ const pin=assignmentInput(assignment).base_sha;
511
+ if(typeof pin!=='string'||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(pin)||
512
+ !Array.isArray(assignment.scope_paths)||!assignment.scope_paths.length)
513
+ throw new Error('validated pinned source scope required');
514
+ const scope=scopeOf({...assignment,output_paths:[]});
515
+ const policy=sensitivePolicyPaths();
516
+ if(policy.error) throw new Error('sensitive_policy_unavailable');
517
+ const env={...gitEnv(),GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_OPTIONAL_LOCKS:'0'};
518
+ const readGit=(args,maxBuffer,input)=>spawnSync('git',['-C',mirror,...args],{env,timeout:3000,maxBuffer,input});
519
+ const anchor=readGit(['cat-file','-t',pin],1024);
520
+ if(anchor.status!==0||anchor.stdout.toString().trim()!=='commit')
521
+ throw new Error('pinned source commit unavailable');
522
+ const tree=readGit(['ls-tree','-rlz','--full-tree',pin],16*1024*1024);
523
+ if(tree.error||tree.status!==0) throw new Error('pinned source tree unavailable');
524
+ const decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
525
+ const entries=[],spellings=new Map();
526
+ let total=0,offset=0;
527
+ while(offset<tree.stdout.length) {
528
+ const end=tree.stdout.indexOf(0,offset);
529
+ if(end<0) throw new Error('invalid pinned source tree');
530
+ const entry=tree.stdout.subarray(offset,end);
531
+ offset=end+1;
532
+ const tab=entry.indexOf(9);
533
+ if(tab<0) throw new Error('invalid pinned source tree');
534
+ const meta=/^100(?:644|755) blob ([a-f0-9]+) +(\d+)$/.exec(entry.subarray(0,tab).toString('ascii'));
535
+ if(!meta||meta[1].length!==pin.length) continue;
536
+ let file;
537
+ try { file=relative(decoder.decode(entry.subarray(tab+1))); } catch { continue; }
538
+ if(file.split('/').some(part=>/[:]|[. ]$/.test(part))||canonicalPath(file).split('/').some(part=>part==='.git'||part==='.gitmodules')||!inScope(file,scope)||
539
+ withheldRepoPath(file,policy.paths)||secretContent.test(file)) continue;
540
+ const parts=file.split('/');
541
+ for(let i=1;i<=parts.length;i++) {
542
+ const spelling=parts.slice(0,i).join('/'),key=canonicalPath(spelling);
543
+ if(spellings.has(key)&&spellings.get(key)!==spelling) throw new Error('pinned source paths collide');
544
+ spellings.set(key,spelling);
545
+ }
546
+ const length=Number(meta[2]);
547
+ total+=length;
548
+ if(entries.length>=256||total>SCOPED_SOURCE_MAX_BYTES) throw new Error('pinned source snapshot exceeds limits');
549
+ entries.push({file,oid:meta[1],length});
550
+ }
551
+ const files=[],blobs=new Map();
552
+ const manifest={schema_version:1,pin,scope_complete:false,files};
553
+ if(!entries.length) return {manifest,blobs};
554
+ const batch=readGit(['cat-file','--batch'],total+entries.length*96,entries.map(entry=>entry.oid).join('\n')+'\n');
555
+ if(batch.error||batch.status!==0) throw new Error('pinned source blob unavailable');
556
+ let cursor=0;
557
+ for(const {file,oid,length} of entries) {
558
+ const header=Buffer.from(`${oid} blob ${length}\n`);
559
+ if(!batch.stdout.subarray(cursor,cursor+header.length).equals(header)) throw new Error('invalid pinned source batch');
560
+ cursor+=header.length;
561
+ const bytes=batch.stdout.subarray(cursor,cursor+length);
562
+ cursor+=length;
563
+ if(batch.stdout[cursor++]!==10) throw new Error('invalid pinned source batch');
564
+ if(bytes.includes(0)) continue;
565
+ let content;
566
+ try { content=decoder.decode(bytes); } catch { continue; }
567
+ if(secretContent.test(content)||redactSecrets(content).redacted) continue;
568
+ files.push({path:file,length,sha256:sha(bytes)});
569
+ blobs.set(file,bytes);
570
+ }
571
+ if(cursor!==batch.stdout.length) throw new Error('invalid pinned source batch');
572
+ // Claim completeness only for an exact file list. Directory scopes always
573
+ // describe the approved subset without disclosing whether paths were withheld.
574
+ manifest.scope_complete=Boolean(scope?.paths?.length&&!scope.excluded.size&&scope.paths.every(file=>blobs.has(file)));
575
+ return {manifest,blobs};
576
+ }
577
+
495
578
  // A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
496
579
  const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
497
580
  // The lists go to one bounded artifact; null when every list is empty. The cap counts the serialized JSON, envelope and separators
@@ -614,7 +697,9 @@ export class Workspace {
614
697
  const {dir,a}=this.ensure(requestId,claimId,subject,false,worker),scope=scopeOf(a.assignment);
615
698
  relative(p,true);
616
699
  if(p&&!leadsToScope(p,scope)) throw new Error(`path outside scope_paths: ${p}`);
617
- const missing=p&&!fs.lstatSync(safePath(dir,p),{throwIfNoEntry:false});
700
+ const start=p?safePath(dir,p):null;
701
+ if(start&&!leadsToScope(realRelative(dir,start,p),scope)) throw new Error(`path outside scope_paths: ${p}`);
702
+ const missing=start&&!fs.lstatSync(start,{throwIfNoEntry:false});
618
703
  const outputs=outputsOf(a.assignment);
619
704
  const creatable=(!cursor||missing)&&outputs.size?[...outputs].filter(output=>{
620
705
  if(!inScope(output,scope)||(p&&!output.startsWith(p+'/'))) return false;
@@ -1335,6 +1420,7 @@ export class Workspace {
1335
1420
  if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
1336
1421
  const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
1337
1422
  if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
1423
+ if(a.assignment.paged_read_scope===true) throw new Error('paged read scope only supports listing and reading files');
1338
1424
  const artifacts=this.store.db.prepare("SELECT COALESCE(client_artifact_id,id) id,size,sha256 FROM artifacts WHERE request_id=? AND claim_id=? AND kind='upload' AND sealed=1").all(requestId,claimId);
1339
1425
  if(!a.assignment.inputs?.some(input=>input.github_repo)) return {checks:[],artifacts:artifacts};
1340
1426
  const {dir,input}=this.ensure(requestId,claimId,subject,true,worker);
@@ -1378,6 +1464,7 @@ export class Workspace {
1378
1464
  if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
1379
1465
  const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
1380
1466
  if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
1467
+ if(a.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
1381
1468
  if(typeof id!=='string'||!/^art_[a-zA-Z0-9_-]{8,128}$/.test(id)) throw new Error('invalid artifact_id: must match art_ followed by 8 to 128 letters, digits, _ or -');
1382
1469
  if(!Number.isInteger(offset)||offset<0) throw new Error('invalid offset: must be a whole number, 0 or more, equal to the bytes stored so far');
1383
1470
  if(typeof base64!=='string') throw new Error('invalid data_base64: must be a string (an empty string is allowed)');