@tnunamak/dalan 0.9.3 → 0.9.5

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/src/mcp-stdio.mjs CHANGED
@@ -8,7 +8,14 @@ import path from 'node:path';
8
8
  import { redactOutput, redactSinkText } from './redaction.mjs';
9
9
  import { safeDiagnostic } from './diagnostic.mjs';
10
10
  import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
11
+ import { createTaskRoute, TaskError, TASKS_CAPABILITIES, TASKS_EXTENSION } from './mcp-tasks.mjs';
11
12
 
13
+ const MODERN_VERSION = '2026-07-28';
14
+ const VERSION_META = 'io.modelcontextprotocol/protocolVersion';
15
+ const CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities';
16
+ const SERVER_INFO = { name: 'dalan-mcp', version: '1' };
17
+ const INSTRUCTIONS = 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it; on a waiting question call dalan_questions, dalan_answer, then dalan_wait again. dalan_result reads the report, dalan_status shows the bridge.';
18
+ const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
19
  export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
13
20
  export const RESULT_CAP_BYTES = 32 * 1024;
14
21
  export const MAX_INPUT_FRAME_BYTES = 1024 * 1024 + 1;
@@ -86,6 +93,16 @@ export const TOOLS = [
86
93
  inputSchema: { type: 'object', additionalProperties: false, properties: {} },
87
94
  annotations: { title: 'Bridge status', readOnlyHint: true, openWorldHint: false } }
88
95
  ];
96
+ const submitTool = TOOLS[0];
97
+ const { dry_run: _dryRun, ...delegateProperties } = submitTool.inputSchema.properties;
98
+ const delegateTool = {
99
+ ...submitTool,
100
+ name: 'dalan_delegate',
101
+ title: 'Delegate a job',
102
+ description: 'Delegate a bounded job to a Dalan worker and get the report when it finishes. Requires the MCP Tasks extension. Pass a unique assignment.request_id and keep it to recover a job after a disconnect. Resubmitting the same assignment is safe.',
103
+ inputSchema: { ...submitTool.inputSchema, properties: delegateProperties },
104
+ annotations: { ...submitTool.annotations, title: 'Delegate a job' },
105
+ };
89
106
 
90
107
  // A SafeError carries a message written by Dalan; any other thrown value is a crash whose text never reaches the client.
91
108
  class SafeError extends Error {}
@@ -208,10 +225,10 @@ async function submit(args, extraFlags = [], {forecast = false} = {}) {
208
225
  const run = await runCli(['submit', '--stdin', ...flags], { input: JSON.stringify(assignment) });
209
226
  const value = run.code === null ? undefined : parseJson(run.stdout);
210
227
  // A dry run exits non-zero for clarify, reject and defer but still prints the verdict on stdout.
211
- if (value !== undefined) return asResult({ value: projectAnswer(forecast ? forecastAnswer(value) : { ...value, next: SUBMIT_NEXT }), isError: run.code !== 0 && (value.verdict ? value.verdict !== 'admissible' : true) });
228
+ if (value !== undefined) return { value: projectAnswer(forecast ? forecastAnswer(value) : { ...value, next: SUBMIT_NEXT }), isError: run.code !== 0 && (value.verdict ? value.verdict !== 'admissible' : true) };
212
229
  const error = cliError(run, forecast ? 'forecast' : 'submit');
213
230
  if (error.value !== undefined) error.value = projectAnswer(forecast && error.value.verdict ? forecastAnswer(error.value) : error.value);
214
- return asResult(error);
231
+ return error;
215
232
  }
216
233
 
217
234
  async function ownerTransition(command, id, flag, text) {
@@ -221,10 +238,19 @@ async function ownerTransition(command, id, flag, text) {
221
238
  return value !== undefined ? asResult({ value }) : asResult(cliError(run, command));
222
239
  }
223
240
 
241
+ async function readCli(command, id, flags = []) {
242
+ const run = await runCli([command, id, ...flags]);
243
+ const value = run.code === 0 ? parseJson(run.stdout) : undefined;
244
+ return value !== undefined ? { value } : cliError(run, command);
245
+ }
246
+ const readJob = (id, { peek = false } = {}) => readCli('get', id, peek ? ['--peek'] : []);
247
+ const readQuestions = id => readCli('questions', id);
248
+ const submitJob = (args, flags = []) => submit(args, [...flags, ...(args.follows ? ['--follows', args.follows] : [])]);
249
+
224
250
  const handlers = {
225
- dalan_submit: args => submit(args, args.follows ? ['--follows', args.follows] : []),
226
- dalan_forecast: args => submit(args, [], {forecast: true}),
227
- dalan_correct: args => submit(args, ['--revises', args.revises]),
251
+ async dalan_submit(args) { return asResult(await submitJob(args)); },
252
+ async dalan_forecast(args) { return asResult(await submit(args, [], { forecast: true })); },
253
+ async dalan_correct(args) { return asResult(await submit(args, ['--revises', args.revises])); },
228
254
  dalan_cancel: args => ownerTransition('cancel', args.request_id, '--reason', args.reason),
229
255
  dalan_accept: args => ownerTransition(args.verdict, args.request_id, '--note', args.note),
230
256
  async dalan_wait(args) {
@@ -234,16 +260,8 @@ const handlers = {
234
260
  const value = run.code === null ? undefined : parseJson(run.stdout);
235
261
  return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'wait'));
236
262
  },
237
- async dalan_result(args) {
238
- const run = await runCli(['get', args.request_id]);
239
- const value = run.code === 0 ? parseJson(run.stdout) : undefined;
240
- return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'get'));
241
- },
242
- async dalan_questions(args) {
243
- const run = await runCli(['questions', args.id]);
244
- const value = run.code === 0 ? parseJson(run.stdout) : undefined;
245
- return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'questions'));
246
- },
263
+ async dalan_result(args) { return asResult(await readJob(args.request_id)); },
264
+ async dalan_questions(args) { return asResult(await readQuestions(args.id)); },
247
265
  async dalan_answer(args) {
248
266
  if (!args.text.trim()) throw fail('answer text must not be blank');
249
267
  if (Buffer.byteLength(args.text) > MAX_ANSWER_BYTES) throw fail(`answer text exceeds ${MAX_ANSWER_BYTES} UTF-8 bytes; nothing was sent or saved`);
@@ -261,22 +279,31 @@ const handlers = {
261
279
  }
262
280
  };
263
281
 
264
- export async function callTool(name, rawArgs) {
265
- const tool = TOOLS.find(t => t.name === name);
266
- if (!tool) return null;
267
- try { return await handlers[name](validate(tool, rawArgs)); }
282
+ const tasks = createTaskRoute({
283
+ submit: args => submitJob(args, args.priority_class === 'background' ? [] : ['--caller-waiting']), readJob, readQuestions,
284
+ answer: args => callTool('dalan_answer', args), cancel: requestId => callTool('dalan_cancel', { request_id: requestId }), asResult,
285
+ });
286
+
287
+ async function invokeTool(tool, rawArgs, call) {
288
+ try { return await call(validate(tool, rawArgs)); }
268
289
  catch (error) {
290
+ if (error instanceof TaskError) throw error;
269
291
  if (error instanceof SafeError) return asResult({ message: error.message });
270
292
  // Python MCP SDK pattern: the client gets the tool name and an error id; the redacted detail goes to the local log.
271
293
  const id = randomUUID().slice(0, 8);
272
- process.stderr.write(`dalan mcp: ${name}: error ${id}: ${safeDiagnostic(error.stack ?? error, 4000)}\n`);
273
- return asResult({ message: `Error executing tool ${name} (error id ${id}; details are in the dalan mcp log)` });
294
+ process.stderr.write(`dalan mcp: ${tool.name}: error ${id}: ${safeDiagnostic(error.stack ?? error, 4000)}\n`);
295
+ return asResult({ message: `Error executing tool ${tool.name} (error id ${id}; details are in the dalan mcp log)` });
274
296
  }
275
297
  }
298
+ export async function callTool(name, rawArgs) {
299
+ const tool = TOOLS.find(t => t.name === name);
300
+ return tool ? invokeTool(tool, rawArgs, handlers[name]) : null;
301
+ }
276
302
 
277
- const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message: redactSinkText(message) } });
303
+ const rpcError = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: { code, message: redactSinkText(message), ...(data ? { data: redactOutput(data) } : {}) } });
304
+ const taskMethods = new Set(['tasks/get', 'tasks/update', 'tasks/cancel']);
278
305
 
279
- // One JSON-RPC message in, zero or one frame out. Never throws.
306
+ // One JSON-RPC message in, zero or one frame out.
280
307
  export async function handleFrame(message) {
281
308
  const candidateId = message?.id;
282
309
  if (candidateId !== undefined && candidateId !== null && typeof candidateId !== 'string' &&
@@ -284,19 +311,46 @@ export async function handleFrame(message) {
284
311
  if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return rpcError(message?.id ?? null, -32600, 'invalid request');
285
312
  const { id, method, params } = message;
286
313
  if (id === undefined) return null; // notification
287
- const ok = result => ({ jsonrpc: '2.0', id, result });
288
- switch (method) {
289
- case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
290
- capabilities: { tools: {} }, serverInfo: { name: 'dalan-mcp', version: '1' },
291
- instructions: 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it; on a waiting question call dalan_questions, dalan_answer, then dalan_wait again. dalan_result reads the report, dalan_status shows the bridge.' });
292
- case 'ping': return ok({});
293
- case 'tools/list': return ok({ tools: TOOLS });
294
- case 'tools/call': {
295
- if (typeof params?.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name');
296
- const result = await callTool(params.name, params.arguments);
297
- return result ? ok(result) : rpcError(id, -32602, `unknown tool "${params.name}"`);
314
+ const meta = params?._meta;
315
+ const modern = method === 'server/discover' || (isRecord(meta) && (Object.hasOwn(meta, VERSION_META) || Object.hasOwn(meta, CLIENT_CAPABILITIES)));
316
+ const capabilities = meta?.[CLIENT_CAPABILITIES];
317
+ if (modern) {
318
+ const version = meta?.[VERSION_META];
319
+ if (typeof version !== 'string' || !isRecord(capabilities)) return rpcError(id, -32602, 'Missing MCP protocol version or client capabilities');
320
+ if (version !== MODERN_VERSION) {
321
+ return rpcError(id, -32022, 'Unsupported protocol version', { supported: [MODERN_VERSION, ...PROTOCOL_VERSIONS], requested: version });
322
+ }
323
+ }
324
+ const ok = result => ({ jsonrpc: '2.0', id, result: modern
325
+ ? { resultType: 'complete', ...result, _meta: { 'io.modelcontextprotocol/serverInfo': SERVER_INFO } } : result });
326
+ const hasTasks = modern && isRecord(capabilities.extensions) && Object.hasOwn(capabilities.extensions, TASKS_EXTENSION)
327
+ && isRecord(capabilities.extensions[TASKS_EXTENSION]);
328
+ const missingTasks = () => rpcError(id, -32021, 'Dalan delegation requires the MCP Tasks extension',
329
+ { requiredCapabilities: TASKS_CAPABILITIES });
330
+ try {
331
+ if (taskMethods.has(method) && modern) {
332
+ return hasTasks ? ok(await tasks.request(method, params, capabilities)) : missingTasks();
333
+ }
334
+ switch (method) {
335
+ case 'server/discover': return ok({ supportedVersions: [MODERN_VERSION], capabilities: { tools: {}, ...TASKS_CAPABILITIES },
336
+ instructions: `${INSTRUCTIONS} Use dalan_delegate to follow a job as an MCP task when the client supports the Tasks extension.` });
337
+ case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
338
+ capabilities: { tools: {} }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
339
+ case 'ping': return ok({});
340
+ case 'tools/list': return ok({ tools: modern ? [...TOOLS, delegateTool] : TOOLS });
341
+ case 'tools/call': {
342
+ if (typeof params?.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name');
343
+ if (params.name === delegateTool.name) {
344
+ return hasTasks ? ok(await invokeTool(delegateTool, params.arguments, tasks.delegate)) : missingTasks();
345
+ }
346
+ const result = await callTool(params.name, params.arguments);
347
+ return result ? ok(result) : rpcError(id, -32602, `unknown tool "${params.name}"`);
348
+ }
349
+ default: return rpcError(id, -32601, `method not found: ${method}`);
298
350
  }
299
- default: return rpcError(id, -32601, `method not found: ${method}`);
351
+ } catch (error) {
352
+ if (error instanceof TaskError) return rpcError(id, error.code, error.message);
353
+ throw error;
300
354
  }
301
355
  }
302
356
 
@@ -0,0 +1,164 @@
1
+ // MCP Tasks projects the bridge's durable job and question state. The signed handle can be
2
+ // resolved by a fresh stdio process in the same bridge home without another task database.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { timingSafeEqual } from 'node:crypto';
7
+ import { ownerToken } from './owner-capability.mjs';
8
+ import { defaultPath, ownerReceiptFile } from './paths.mjs';
9
+ import { safeDiagnostic } from './diagnostic.mjs';
10
+ import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
11
+ import { liveClaimQuestions } from './live-claim-questions.mjs';
12
+
13
+ export const TASKS_EXTENSION = 'io.modelcontextprotocol/tasks';
14
+ export const TASKS_CAPABILITIES = { extensions: { [TASKS_EXTENSION]: {} } };
15
+ const POLL_INTERVAL_MS = 10_000;
16
+ const handlePattern = /^(\w[-\w]{7,127})\.([a-f0-9]{32})$/;
17
+
18
+ // Domain separation keeps the handle distinct from the receipt's owner token.
19
+ function taskSignature(requestId) {
20
+ const home = path.resolve(process.env.DALAN_HOME || os.homedir());
21
+ const file = ownerReceiptFile(defaultPath(home, '.local/share/dot-bridge/receipts'), requestId);
22
+ const text = fs.readFileSync(file, 'utf8');
23
+ let receipt;
24
+ try { receipt = JSON.parse(text); } catch { throw new Error('Dalan task receipt is invalid'); }
25
+ if (receipt?.request_id !== requestId || typeof receipt.token !== 'string' || !receipt.token) {
26
+ throw new Error('Dalan task receipt is invalid');
27
+ }
28
+ return ownerToken(receipt.token, `mcp-task:${requestId}`).slice(0, 32);
29
+ }
30
+
31
+ function requestIdFor(taskId) {
32
+ const match = typeof taskId === 'string' && handlePattern.exec(taskId);
33
+ if (!match) throw new TaskError(-32602, 'Unknown Dalan task');
34
+ const [, requestId, signature] = match;
35
+ let expected;
36
+ try { expected = taskSignature(requestId); }
37
+ catch (error) {
38
+ if (error.code !== 'ENOENT') throw error;
39
+ throw new TaskError(-32602, 'Unknown Dalan task');
40
+ }
41
+ if (!timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'))) {
42
+ throw new TaskError(-32602, 'Unknown Dalan task');
43
+ }
44
+ return requestId;
45
+ }
46
+
47
+ export class TaskError extends Error {
48
+ constructor(code, message) {
49
+ super(message);
50
+ this.code = code;
51
+ }
52
+ }
53
+
54
+ function checkRead(reply) {
55
+ if (!reply.isError) return reply.value;
56
+ const { value } = reply;
57
+ if (value?.code === 'unknown_request' || value?.http_status === 404 ||
58
+ ['assignment not found', 'message not found', 'invalid owner capability'].includes(value?.error)) {
59
+ throw new TaskError(-32602, 'Unknown Dalan task');
60
+ }
61
+ throw new TaskError(-32603, 'Dalan could not read the task. Check the bridge and retry.');
62
+ }
63
+
64
+ function describeJob(row, taskId, dates = []) {
65
+ const lastEvent = row.lifecycle_events?.at(-1);
66
+ const progress = row.progress?.at(-1);
67
+ const lastUpdated = [row.created_at, row.cancelled_at, row.valid_until && row.cancelled_reason === 'expired' ? row.valid_until : null,
68
+ row.report?.created_at, lastEvent?.at, progress?.created_at, ...dates].filter(Boolean)
69
+ .map(value => Date.parse(value)).filter(Number.isFinite);
70
+ const status = { finished: 'completed', cancelled: 'cancelled' }[row.status] ?? 'working';
71
+ const detail = status === 'cancelled' ? row.cancelled_reason
72
+ : status === 'completed' ? row.report?.summary
73
+ : progress?.note ?? row.claim_denied?.message ?? row.target_worker;
74
+ return {
75
+ taskId, status, statusMessage: safeDiagnostic(`Work ${row.request_id}: ${row.status}${detail ? ` (${detail})` : ''}`, 500),
76
+ createdAt: row.created_at, lastUpdatedAt: new Date(Math.max(...lastUpdated)).toISOString(),
77
+ ttlMs: null, pollIntervalMs: POLL_INTERVAL_MS,
78
+ };
79
+ }
80
+
81
+ const formSupported = capabilities => {
82
+ const elicitation = capabilities.elicitation;
83
+ return elicitation && typeof elicitation === 'object' && !Array.isArray(elicitation) &&
84
+ (Object.keys(elicitation).length === 0 || Object.hasOwn(elicitation, 'form'));
85
+ };
86
+
87
+ const complete = { resultType: 'complete' };
88
+ const terminal = row => ['finished', 'cancelled'].includes(row.status);
89
+
90
+ export function createTaskRoute({ submit, readJob, readQuestions, answer, cancel, asResult }) {
91
+ const questionsFor = async row => row.claim?.state === 'active'
92
+ ? liveClaimQuestions(row, checkRead(await readQuestions(row.request_id)).questions) : [];
93
+
94
+ return {
95
+ async delegate(args) {
96
+ const requestId = args.assignment.request_id;
97
+ if (typeof requestId !== 'string' || !/^\w[-\w]{7,127}$/.test(requestId)) {
98
+ return { ...complete, ...asResult({ message: 'assignment.request_id must be a valid request ID' }) };
99
+ }
100
+ const admission = await submit(args);
101
+ if (admission.isError) return asResult(admission);
102
+ const taskId = `${requestId}.${taskSignature(requestId)}`;
103
+ const row = checkRead(await readJob(requestId, { peek: true }));
104
+ const seed = describeJob(row, taskId);
105
+ if (row.status === 'queued' && admission.value.admission?.worker_state === 'break') {
106
+ const until = admission.value.admission.until ?? 'unknown';
107
+ seed.statusMessage = safeDiagnostic(`Work ${requestId}: queued during worker usage break (expected end: ${until}).`, 500);
108
+ }
109
+ return { resultType: 'task', ...seed };
110
+ },
111
+
112
+ async request(method, params, capabilities) {
113
+ const requestId = requestIdFor(params.taskId);
114
+ if (method === 'tasks/get') {
115
+ const row = checkRead(await readJob(requestId));
116
+ const questions = terminal(row) ? [] : await questionsFor(row);
117
+ const task = { ...complete, ...describeJob(row, params.taskId, questions.map(question => question.asked_at)) };
118
+ if (task.status === 'completed') {
119
+ // Put the report ahead of the assignment and progress history so the tool cap preserves its opening.
120
+ const { request_id, status, target_worker, report, ...history } = row;
121
+ return { ...task, result: { ...complete, ...asResult({ value: { request_id, status, target_worker, report, ...history } }) } };
122
+ }
123
+ if (task.status === 'cancelled' || !questions.length) return task;
124
+ const inputRequests = Object.fromEntries(questions
125
+ .filter(question => (question.purpose ?? 'clarification') === 'clarification' && formSupported(capabilities))
126
+ .map(question => [question.question_id, {
127
+ method: 'elicitation/create',
128
+ params: {
129
+ mode: 'form', message: safeDiagnostic(`Work ${requestId}, question ${question.question_id}: ${question.text}`, 4500),
130
+ requestedSchema: { type: 'object', properties: { answer: { type: 'string', minLength: 1, maxLength: MAX_ANSWER_BYTES } }, required: ['answer'] },
131
+ },
132
+ }]));
133
+ if (Object.keys(inputRequests).length) return { ...task, status: 'input_required', inputRequests };
134
+ return { ...task, statusMessage: `Work ${requestId}: waiting for an answer. Read dalan_questions and answer through the requester or operator.` };
135
+ }
136
+
137
+ const row = checkRead(await readJob(requestId, { peek: true }));
138
+ if (method === 'tasks/cancel') {
139
+ if (terminal(row) || !(await cancel(requestId)).isError) return complete;
140
+ // The worker can finish between the read and the cancel. Keep the report in that case.
141
+ if (terminal(checkRead(await readJob(requestId, { peek: true })))) return complete;
142
+ throw new TaskError(-32603, 'Dalan could not cancel the task. Check the job state before retrying.');
143
+ }
144
+
145
+ const responses = params.inputResponses;
146
+ if (!responses || typeof responses !== 'object' || Array.isArray(responses)) {
147
+ throw new TaskError(-32602, 'inputResponses must be an object');
148
+ }
149
+ if (terminal(row)) return complete;
150
+ for (const question of await questionsFor(row)) {
151
+ if ((question.purpose ?? 'clarification') !== 'clarification' || !Object.hasOwn(responses, question.question_id)) continue;
152
+ const response = responses[question.question_id];
153
+ if (response?.action === 'decline' || response?.action === 'cancel') continue;
154
+ const text = response?.content?.answer;
155
+ if (response?.action !== 'accept' || typeof text !== 'string') {
156
+ throw new TaskError(-32602, 'A question response needs action accept and a text answer');
157
+ }
158
+ const reply = await answer({ id: requestId, question_id: question.question_id, text });
159
+ if (reply.isError) throw new TaskError(-32603, reply.content[0].text);
160
+ }
161
+ return complete;
162
+ },
163
+ };
164
+ }
@@ -0,0 +1,25 @@
1
+ // Reattach capability: HMAC-SHA256(secret, id). The secret is created once (mode 0600, published atomically). The token is
2
+ // derived, not stored, so it is the same after a requester restart.
3
+ import { createHmac, randomBytes } from 'node:crypto';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ // Read the secret, create it on first use. A file that is not exactly 0600 or is too short is an error, never replaced.
8
+ export function readOrCreateSecret(file) {
9
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
10
+ const read = () => {
11
+ const mode = fs.statSync(file).mode & 0o777;
12
+ if (mode !== 0o600) throw Object.assign(new Error(`${file} must be mode 0600 (found ${mode.toString(8)})`), { code: 'state_permissions' });
13
+ const secret = fs.readFileSync(file, 'utf8').trim();
14
+ if (secret.length < 32) throw new Error(`${file} is too short`);
15
+ return secret;
16
+ };
17
+ try { return read(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
18
+ // link() fails with EEXIST when another creator won: the file appears complete or not at all, and the first one is kept.
19
+ const tmp = `${file}.${process.pid}.tmp`;
20
+ fs.writeFileSync(tmp, randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
21
+ try { fs.linkSync(tmp, file); } catch (error) { if (error.code !== 'EEXIST') throw error; } finally { fs.rmSync(tmp, { force: true }); }
22
+ return read();
23
+ }
24
+
25
+ export const ownerToken = (secret, id) => createHmac('sha256', secret).update(id).digest('hex');
@@ -50,14 +50,15 @@ export function materializeDecision(grant, repo, requestId, authority) {
50
50
  throw grantError('materialize_result_invalid', 'expected one exact repository and a valid request ID');
51
51
  }
52
52
  const [org] = repo.toLowerCase().split('/');
53
- const installed = !!grant?.grant.some(entry => ['org:' + org, 'repo:' + repo.toLowerCase()].includes(entry.toLowerCase()));
54
- // The install file may only narrow what the work's own grant allows; it cannot stand in for it.
55
- const workProblem = installed ? workGrantProblem(authority, repo) : null;
56
- const eligible = installed && !workProblem;
53
+ const ownerPolicyCoversRepo = !!grant?.grant.some(entry => ['org:' + org, 'repo:' + repo.toLowerCase()].includes(entry.toLowerCase()));
54
+ // Both the owner's publication policy and the work's publication grant must cover the repository.
55
+ const workProblem = workGrantProblem(authority, repo);
56
+ const eligible = ownerPolicyCoversRepo && !workProblem;
57
57
  const push = eligible && grant.mode === 'standing';
58
58
  const needs_approval = eligible && grant.mode === 'per_pr';
59
- return { push, draft_pr: push, needs_approval, branch: 'dalan/' + requestId,
60
- reason: push ? 'standing_grant' : needs_approval ? 'per_pr_approval_required' : workProblem ?? 'no_standing_grant' };
59
+ const refusal = ownerPolicyCoversRepo ? workProblem : 'no_standing_grant';
60
+ const reason = push ? 'standing_grant' : needs_approval ? 'per_pr_approval_required' : refusal;
61
+ return { push, draft_pr: push, needs_approval, branch: 'dalan/' + requestId, reason };
61
62
  }
62
63
 
63
64
 
package/src/paths.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from 'node:fs';
2
+ import { createHash } from 'node:crypto';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
4
5
  import {readEnv} from './env.mjs';
@@ -65,3 +66,5 @@ export function rootWarnings(home=os.homedir()) {
65
66
  return [{area:['config','data','state'][index],chosen,passed_over:current,missing}];
66
67
  });
67
68
  }
69
+
70
+ export const ownerReceiptFile = (directory, requestId) => path.join(directory, createHash('sha256').update(requestId).digest('hex') + '.json');
package/src/server.mjs CHANGED
@@ -239,14 +239,14 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
239
239
  return [requestId,claim.claim_id,claim.epoch,subject,connection];
240
240
  } catch(error) { throw assignmentRegistryRefusal(error); }
241
241
  },
242
- run({args,context:{worker,subject},grantScope}) {
242
+ run({args,context:{worker,subject},grantScope,recordOnRead}) {
243
243
  const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
244
244
  const offset=args.offset??0;
245
245
  if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
246
246
  try {
247
- const {a,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
247
+ const {a,claim,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
248
248
  if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
249
- const {manifest,blobs}=pinnedScopedSource(mirror,a.assignment);
249
+ const {manifest,blobs,refusedPaths}=pinnedScopedSource(mirror,a.assignment);
250
250
  if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
251
251
  throw new Error('assignment grant requires exact scoped files');
252
252
  if(!manifest.files.length) throw new Error('no approved scoped input files');
@@ -264,6 +264,11 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
264
264
  const end=Math.min(offset+scopedSourceChunk,bytes.length);
265
265
  const result={sha256:hash,size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
266
266
  if(JSON.stringify(redactOutput(result))!==JSON.stringify(result)) throw new Error('scoped input encoding refused');
267
+ const metadata={...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})};
268
+ recordOnRead(()=>store.recordScopedInputChunk(requestId,{
269
+ epoch:claim.epoch,worker,sha256:hash,metadata,chunk:offset/scopedSourceChunk,
270
+ chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
271
+ }));
267
272
  return result;
268
273
  } catch(error) { throw assignmentRegistryRefusal(error); }
269
274
  },
@@ -790,6 +795,15 @@ function sweepSkipped() {
790
795
  for(const requestId of ids) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
791
796
  return ids;
792
797
  }
798
+ function notifyStalePrCancellation(requestId) {
799
+ log({kind:'pr_head_mismatch_cancelled',request_id:requestId});
800
+ const waiter=waiters.get(requestId);
801
+ if(waiter) {
802
+ waiters.delete(requestId);
803
+ clearTimeout(waiter.timer);
804
+ json(waiter.res,200,waitSummary(requestId));
805
+ }
806
+ }
793
807
  // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
794
808
  function sweepStaleLeases() {
795
809
  const ids=store.sweepStaleLeases();
@@ -1369,7 +1383,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1369
1383
  if(preflight) store.clearPrClaimMismatch(requestId,preflight);
1370
1384
  }
1371
1385
  catch(error) {
1372
- if(error.prHeadMismatch) store.recordPrClaimMismatch(requestId,error.prHeadMismatch);
1386
+ if(error.prHeadMismatch&&store.recordPrClaimMismatch(requestId,error.prHeadMismatch)) notifyStalePrCancellation(requestId);
1373
1387
  throw error;
1374
1388
  }
1375
1389
  }
@@ -1812,6 +1826,8 @@ const adminServer=http.createServer(async(req,res)=>{
1812
1826
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1813
1827
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1814
1828
  Object.assign(got,repositoryReadScope(got.assignment));
1829
+ const manifests=store.scopedInputManifests(requestId);
1830
+ if(manifests.length) got.scoped_input_manifests=manifests;
1815
1831
  if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
1816
1832
  const snapshot=store.admissionForQueuedRequest(requestId);
1817
1833
  if(snapshot) got.admission=snapshot;
@@ -2237,6 +2253,7 @@ function maintain() {
2237
2253
  } catch(error) { log({kind:'facade_withdrawal_error',request_id:requestId,reason:error.message}); }
2238
2254
  }
2239
2255
  sweepExpired();
2256
+ for(const requestId of store.sweepPrClaimMismatches()) notifyStalePrCancellation(requestId);
2240
2257
  sweepSkipped();
2241
2258
  sweepStaleLeases();
2242
2259
  store.retireUnknownSubscriptions();
package/src/store.mjs CHANGED
@@ -209,6 +209,7 @@ const live=nowMs=>`NOT ${expired(nowMs)} AND (request_id NOT IN (SELECT request_
209
209
  WHERE CAST(json_extract(p.settings,'$.retain_until_ms') AS INTEGER)>'${nowMs}'
210
210
  AND NOT EXISTS (SELECT 1 FROM job_retention_tombstones t WHERE t.job=p.request_id)
211
211
  ))`;
212
+ const noPrClaimBlock=table=>`NOT EXISTS (SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=${table}.request_id)`;
212
213
  export const expiredError=(validUntil,{cancelled=false,requeue=false}={})=>`assignment_expired: its prepared inputs were valid until ${validUntil}; ${cancelled?'the bridge cancelled it and will not requeue it':requeue?'the bridge has not cancelled it; the expiry sweep will evaluate whether it can requeue it':'the bridge has not cancelled it yet and will not requeue it'}. Call list_pending, then claim another listed assignment.`;
213
214
  const denialPattern=/auto-?review|guardian|denied|not approved|paused out of precaution/i;
214
215
  export const workerGuidance='If auto-review or Guardian denies an action, stop that line of work, report BLOCKED: with the denied action, and never retry or rephrase to get around it. A denial or error about one assignment does not affect another: an error naming a different request_id (for example a finished assignment) is not a revocation of this one. An assignment with a new request_id that the owner submitted is a separate, fresh owner request, made after the owner saw the earlier outcome; it is not a retry of a denied action, so judge it on its own merits. If finish answers assignment_cancelled, the owner withdrew that request: this is not a denial and nothing to work around or retry; stop work on it and move on. Read the response to see whether bounded audit evidence was retained; output after the lease deadline is dropped. Check owner_notes on this assignment with get before finishing. Reading UI source that renders or validates a credential input field is ordinary UI work; the restriction is on revealing, copying, changing or transmitting actual secret values.';
@@ -1184,6 +1185,12 @@ export class Store {
1184
1185
  UNIQUE(worker,subject,started_at));`);
1185
1186
  if(!this.db.prepare("SELECT 1 FROM pragma_table_info('relationships') WHERE name='publish_grant'").get()) this.db.exec('ALTER TABLE relationships ADD COLUMN publish_grant TEXT');
1186
1187
  }
1188
+ this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_input_receipts(
1189
+ request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
1190
+ epoch INTEGER NOT NULL, sha256 TEXT NOT NULL, worker TEXT NOT NULL, metadata TEXT NOT NULL,
1191
+ served_chunks INTEGER NOT NULL, all_chunks INTEGER NOT NULL,
1192
+ PRIMARY KEY(request_id,epoch,sha256)
1193
+ ) WITHOUT ROWID;`);
1187
1194
  // Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
1188
1195
  // spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
1189
1196
  this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
@@ -2090,7 +2097,7 @@ export class Store {
2090
2097
  }
2091
2098
  // Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
2092
2099
  queuedRows() {
2093
- return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all();
2100
+ return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} AND ${noPrClaimBlock('a')} ORDER BY ${LIST_ORDER}`).all();
2094
2101
  }
2095
2102
  // Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
2096
2103
  breakIntervals(worker='dot') {
@@ -2107,7 +2114,7 @@ export class Store {
2107
2114
  // sending owner delivery are left out: they wait for reconcile, not for the worker. Derived only: a requeue restarts the clock.
2108
2115
  unclaimedAfterReannounce(limits=this.limits,worker='dot') {
2109
2116
  const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=this.breakIntervals(worker);
2110
- const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
2117
+ const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} AND ${noPrClaimBlock('a')} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
2111
2118
  return {count:rows.length,oldest_age_ms:rows.length?now-Date.parse(rows[0].queued_at):null,request_ids:rows.slice(0,10).map(r=>r.request_id)};
2112
2119
  }
2113
2120
  // Honest classification of queued work after its first event 2xx. Observations only: nothing here reclaims or cancels a claim.
@@ -2131,7 +2138,7 @@ export class Store {
2131
2138
  const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
2132
2139
  const atCapacity=liveSubs.length>0&&liveSubs.every(sub=>this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity)===0);
2133
2140
  const hasSubscription=liveSubs.length>0;
2134
- const items=this.db.prepare(`SELECT request_id,created_at,skipped_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL ORDER BY created_at`).all(worker).map(row=>{
2141
+ const items=this.db.prepare(`SELECT request_id,created_at,skipped_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL AND ${noPrClaimBlock('assignments')} ORDER BY created_at`).all(worker).map(row=>{
2135
2142
  // A queued row past its preparation's valid_until, or a protocol row past its retention, is 'expired', never alive_not_claiming: the worker cannot claim it.
2136
2143
  if(row.expired) return {request_id:row.request_id,class:'expired',event_2xx_age_ms:null};
2137
2144
  if(row.skipped_at!==null) return {request_id:row.request_id,class:null,event_2xx_age_ms:null};
@@ -2739,12 +2746,37 @@ export class Store {
2739
2746
  if(!changed.changes) throw new Error('relationship_not_found');
2740
2747
  return this.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId);
2741
2748
  }
2742
- recordPrClaimMismatch(id,{pinned,observed}) {
2743
- this.db.prepare(`INSERT INTO pr_claim_blocks(request_id,pinned,observed,checked_at)
2744
- SELECT request_id,?,?,? FROM assignments WHERE request_id=? AND status='queued'
2749
+ recordScopedInputChunk(id, {epoch,worker,sha256,metadata,chunk,chunkCount}) {
2750
+ // At most 29 chunks fit the scoped source limit. An OR makes repeat and out-of-order reads idempotent.
2751
+ this.db.prepare(`INSERT INTO scoped_input_receipts(request_id,epoch,sha256,worker,metadata,served_chunks,all_chunks)
2752
+ VALUES(?,?,?,?,?,?,?) ON CONFLICT(request_id,epoch,sha256) DO UPDATE SET served_chunks=served_chunks | excluded.served_chunks
2753
+ WHERE (served_chunks & excluded.served_chunks)=0`)
2754
+ .run(id,epoch,sha256,worker,JSON.stringify(metadata),1<<chunk,(1<<chunkCount)-1);
2755
+ }
2756
+ scopedInputManifests(id) {
2757
+ return this.db.prepare(`SELECT epoch,worker,sha256,metadata,served_chunks=all_chunks AS complete
2758
+ FROM scoped_input_receipts WHERE request_id=? ORDER BY epoch,sha256`).all(id)
2759
+ .map(({epoch,worker,sha256,metadata,complete})=>({...JSON.parse(metadata),epoch,worker,sha256,all_chunks_served:!!complete}));
2760
+ }
2761
+ recordPrClaimMismatch(id,{pinned,observed}) { return this.transaction(()=>{
2762
+ const recorded=this.db.prepare(`INSERT INTO pr_claim_blocks(request_id,pinned,observed,checked_at)
2763
+ SELECT request_id,?,?,? FROM assignments WHERE request_id=? AND status='queued' AND json_extract(payload,'$.inputs[0].head_sha')=?
2745
2764
  ON CONFLICT(request_id) DO UPDATE SET observed=excluded.observed,checked_at=excluded.checked_at
2746
- WHERE pr_claim_blocks.pinned=excluded.pinned`).run(pinned,observed,this.stamp(),id);
2765
+ WHERE pr_claim_blocks.pinned=excluded.pinned`).run(pinned,observed,this.stamp(),id,pinned);
2766
+ return recorded.changes>0&&this.cancelQueuedPrClaimMismatch(id);
2767
+ }); }
2768
+ cancelQueuedPrClaimMismatch(id) {
2769
+ if(this.uncertainDeliveries(id)) return false;
2770
+ const reason='pr_head_mismatch';
2771
+ this.cancelInTransaction(id,reason,'system');
2772
+ if(this.isProtocolJob(id)) this.protocolEventInTransaction(id,'cancelled',{reason});
2773
+ return true;
2747
2774
  }
2775
+ sweepPrClaimMismatches(limit=100) { return this.transaction(()=>{
2776
+ const rows=this.db.prepare(`SELECT a.request_id FROM pr_claim_blocks b JOIN assignments a USING(request_id)
2777
+ WHERE a.status='queued' AND ${live(this.nowMs())} ORDER BY b.checked_at LIMIT ?`).all(limit);
2778
+ return rows.map(row=>row.request_id).filter(id=>this.cancelQueuedPrClaimMismatch(id));
2779
+ }); }
2748
2780
  clearPrClaimMismatch(id,{head_sha,checked_at}) {
2749
2781
  this.db.prepare('DELETE FROM pr_claim_blocks WHERE request_id=? AND pinned=? AND checked_at<=?')
2750
2782
  .run(id,head_sha,checked_at);
@@ -3800,7 +3832,7 @@ export class Store {
3800
3832
  const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
3801
3833
  return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
3802
3834
  }
3803
- cancelInTransaction(id,reason=null) {
3835
+ cancelInTransaction(id,reason=null,actor='owner') {
3804
3836
  if(!this.db.isTransaction)protocolError('transaction_required');
3805
3837
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found'); if(a.status==='finished') throw new Error('already finished');
3806
3838
  if(a.status!=='cancelled') {
@@ -3808,8 +3840,8 @@ export class Store {
3808
3840
  const released=this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0;
3809
3841
  if(a.status==='claimed'||released) this.laneFreed();
3810
3842
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
3811
- this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
3812
- this.lifecycle(id,'cancelled','owner',reason);
3843
+ this.lifecycle(id,'withdraw_work',actor,reason,undefined,{scope:`job:${id}`,outcome:'done'});
3844
+ this.lifecycle(id,'cancelled',actor,reason);
3813
3845
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
3814
3846
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
3815
3847
  }
@@ -4293,7 +4325,7 @@ export class Store {
4293
4325
  const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR ${live(this.nowMs())} GROUP BY status`).all().filter(x=>x.count>0);
4294
4326
  const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
4295
4327
  const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
4296
- const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())}`).get().oldest;
4328
+ const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}`).get().oldest;
4297
4329
  const lastClaim=this.db.prepare("SELECT max(claimed_at) last_claim FROM claims WHERE worker='dot'").get().last_claim;
4298
4330
  const uncertain=this.db.prepare("SELECT count(*) n FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','break','event')").get().n;
4299
4331
  const pause=this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get();
@@ -4301,9 +4333,9 @@ export class Store {
4301
4333
  SELECT target_worker worker,request_id,created_at,
4302
4334
  count(*) OVER (PARTITION BY target_worker) n,
4303
4335
  row_number() OVER (PARTITION BY target_worker ORDER BY created_at,request_id) rank
4304
- FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND skipped_at IS NULL AND ${live(this.nowMs())})
4336
+ FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND skipped_at IS NULL AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')})
4305
4337
  SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
4306
- const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} LIMIT 1`).get();
4338
+ const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')} LIMIT 1`).get();
4307
4339
  const subscription={state:!sub?'absent':sub.state==='revoked'?'revoked':sub.rotation_blocked?'rotation_blocked':sub.auth_failures>=3?'callback_blocked':sub.expires_at<=this.stamp()?'expired':'active',expires_at:sub?.expires_at||null,last_verified_at:sub?.verified_at||null,last_event_2xx_at:sub?.last_event_2xx_at||null,last_claim_at:lastClaim,principal:sub?.principal||null,auth_failures:sub?.auth_failures||0};
4308
4340
  const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR ${live(this.nowMs())})`).get(priority,status).n]))]));
4309
4341
  const throttle=this.rollingUsage(limits);