@tnunamak/dalan 0.9.2 → 0.9.4

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.
@@ -272,10 +272,10 @@ export function bridgeRefusal(status, inFlightCap, worker, priority, callerWaiti
272
272
 
273
273
  const execFileAsync = promisify(execFile);
274
274
  // Async so a slow git never blocks the event loop (ACP notifications, the cancel window); each call is killed after the timeout.
275
- async function git(cwd, args) {
275
+ async function git(cwd, args, { raw = false } = {}) {
276
276
  try {
277
277
  const r = await execFileAsync('git', ['-C', cwd, ...args], { encoding: 'utf8', timeout: 15000, killSignal: 'SIGKILL', maxBuffer: 4 * 1024 * 1024 });
278
- return { ok: true, out: r.stdout.trim(), err: r.stderr.trim() };
278
+ return { ok: true, out: raw ? r.stdout : r.stdout.trim(), err: r.stderr.trim() };
279
279
  } catch (e) { return { ok: false, out: (e.stdout || '').trim(), err: (e.stderr || e.message).trim() }; }
280
280
  }
281
281
  export function githubRepoOf(url) {
@@ -341,6 +341,59 @@ export async function repoInputs(cwd, { repoOf = githubRepoOf } = {}) {
341
341
  return base ? { inputs: [{ github_repo: repo, base_sha: base, head_sha: base }], packBase: base } : { inputs: [], note: NO_REPO_NOTE };
342
342
  }
343
343
 
344
+ // This is requester-side evidence only. Report counts without putting local paths into the assignment.
345
+ async function omittedLocalChanges(cwd, base, packedPaths = new Set()) {
346
+ const revisionRange = ['HEAD', '--not', base, '--remotes=origin', '--'];
347
+ const [status, commits] = await Promise.all([
348
+ git(cwd, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames'], { raw: true }),
349
+ git(cwd, ['rev-list', '--count', ...revisionRange]),
350
+ ]);
351
+ const tracked = [], untracked = [], lines = [];
352
+ const paths = files => {
353
+ const list = files.slice(0, 10).map(file => JSON.stringify(file.length > 180 ? `${file.slice(0, 179)}…` : file));
354
+ if (files.length > list.length) list.push(`+${files.length - list.length} more`);
355
+ return list.length ? `: ${list.join(', ')}` : '';
356
+ };
357
+ if (status.ok) {
358
+ for (const entry of status.out.split('\0').filter(Boolean)) {
359
+ const file = entry.slice(3);
360
+ if (!packedPaths.has(file)) (entry.startsWith('?? ') ? untracked : tracked).push(file);
361
+ }
362
+ for (const [label, files] of [['uncommitted', tracked], ['untracked', untracked]]) {
363
+ if (files.length) lines.push(`${files.length} ${label} file${files.length === 1 ? '' : 's'}${paths(files)}`);
364
+ }
365
+ } else {
366
+ lines.push('Uncommitted and untracked files could not be listed.');
367
+ }
368
+ if (commits.ok) {
369
+ const count = Number(commits.out);
370
+ if (count) {
371
+ const touched = await git(cwd, ['log', '--format=', '--name-only', '-z', '--no-renames', '--diff-merges=first-parent', ...revisionRange], { raw: true });
372
+ const files = touched.ok ? [...new Set(touched.out.split('\0').filter(Boolean))].sort() : null;
373
+ const detail = files ? ` touching ${files.length} path${files.length === 1 ? '' : 's'}${paths(files)}` : ' (changed paths unavailable)';
374
+ lines.push(`${count} unpushed commit${count === 1 ? '' : 's'}${detail}`);
375
+ }
376
+ } else {
377
+ lines.push('Unpushed commits relative to the pin could not be listed.');
378
+ }
379
+ return lines.length ? `\nLocal changes excluded from the worker's checkout and brief (commit history is excluded even when a text diff is included):\n- ${lines.join('\n- ')}` : '';
380
+ }
381
+
382
+ async function checkoutMatchesInput(cwd, input, repoOf = githubRepoOf) {
383
+ if (!cwd || !input) return false;
384
+ const origin = await git(cwd, ['remote', 'get-url', 'origin']);
385
+ return origin.ok && repoOf(origin.out)?.toLowerCase() === input.github_repo.toLowerCase();
386
+ }
387
+
388
+ // A correction uses the stored pin but sends a new brief without the previous packed diff.
389
+ export async function correctionRepositoryContext(cwd, assignment) {
390
+ const input = assignment.inputs?.[0];
391
+ if (!input) return 'No repository input was submitted. The worker sees only the material in the brief.';
392
+ const base = input.head_sha ?? input.base_sha;
393
+ const omitted = await checkoutMatchesInput(cwd, input) ? await omittedLocalChanges(cwd, base) : '';
394
+ return `Repository input: ${input.github_repo} at pinned commit ${base}. The worker reads this commit and the brief.${omitted}`;
395
+ }
396
+
344
397
  // Async end to end (git runs as child processes with timeouts), so packing never blocks ACP notifications or the cancel window.
345
398
  // A text-only worker (DOT_ACP_TEXT_ONLY=1) never gets repository inputs; builds are then refused by the no-inputs rule below.
346
399
  export const TEXT_ONLY_NOTE = 'Text-only job: there is no repository or file access. Answer from this brief alone.';
@@ -457,19 +510,24 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
457
510
  }
458
511
  // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
459
512
  let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, newFiles, repoScope: build && buildExecution(env) === 'host' }), acp_brief_hash: sha256(request.brief), ...(explicitRead ? { scope_paths: explicitRead.scope, read_paths: explicitRead.scope } : {}) };
460
- if (context.packBase) assignment = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE);
513
+ let packedPaths = new Set();
514
+ if (context.packBase) ({ assignment, packedPaths } = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE));
461
515
  else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
462
516
  else if (context.note) assignment.brief = `${context.note}\n\n${assignment.brief}`;
463
517
  const input = assignment.inputs[0];
518
+ const base = input?.head_sha ?? context.packBase;
519
+ const reportLocalChanges = context.packBase || context.untracked ||
520
+ (named?.inputs && await checkoutMatchesInput(cwd, input, options?.repoOf));
521
+ const localChanges = reportLocalChanges ? await omittedLocalChanges(cwd, base, packedPaths) : '';
464
522
  if (!input) {
465
- const base = context.packBase ? ` The candidate pushed commit was ${context.packBase}.` : '';
466
- return { assignment, repositoryContext: `No repository input was submitted.${base} The worker sees only the local material included in the brief.` };
523
+ const candidate = base ? ` The candidate pushed commit was ${base}.` : '';
524
+ return { assignment, repositoryContext: `No repository input was submitted.${candidate} The worker sees only the local material included in the brief.${localChanges}` };
467
525
  }
468
526
  const revision = named?.inputs && !build ? 'pinned' : 'pushed';
469
527
  const visibility = context.packBase
470
528
  ? 'The brief includes a packed text diff. Local binary, sensitive, symlink, and ignored changes are unseen.'
471
- : 'No local diff was included. Untracked and other checkout-only work is unseen.';
472
- return { assignment, repositoryContext: `Repository input: ${input.github_repo} at ${revision} commit ${input.head_sha}. ${visibility}` };
529
+ : 'The worker reads this commit and the brief. No local diff was included.';
530
+ return { assignment, repositoryContext: `Repository input: ${input.github_repo} at ${revision} commit ${base}. ${visibility}${localChanges}` };
473
531
  }
474
532
 
475
533
  // ---------------------------------------------------------------- build tasks
@@ -81,9 +81,9 @@ export async function packRepoDiff(cwd, assignment, base, noRepoNote) {
81
81
  if (listed < changed.length) context += `\n${changed.length - listed} more changed file names exceed the brief limit.`;
82
82
  const out = { ...textOnly, brief: `${noRepoNote}\n\n${withContext(assignment.brief, context)}` };
83
83
  validateSubmission(out);
84
- return out;
84
+ return { assignment: out, packedPaths: new Set() };
85
85
  };
86
- const chunks = [], skipped = [];
86
+ const chunks = [], skipped = [], packedPaths = new Set();
87
87
  try {
88
88
  for (const file of changed) {
89
89
  if (omitted.has(file)) continue;
@@ -106,6 +106,7 @@ export async function packRepoDiff(cwd, assignment, base, noRepoNote) {
106
106
  if (error.code === 'DOT_BRIDGE_INFRASTRUCTURE') throw error;
107
107
  return fallback('submission policy rejected local context');
108
108
  }
109
+ if (diff) packedPaths.add(file);
109
110
  chunks.push(diff);
110
111
  if (Buffer.byteLength(chunks.join('')) > submissionLimits.brief) return fallback('diff exceeds assignment limits');
111
112
  }
@@ -134,5 +135,5 @@ export async function packRepoDiff(cwd, assignment, base, noRepoNote) {
134
135
  return fallback(sizeError(error) ? 'diff exceeds assignment limits' : 'submission policy rejected local context');
135
136
  }
136
137
  // The bridge owns scope_excluded and will repeat admission itself; never send the locally narrowed result.
137
- return out;
138
+ return { assignment: out, packedPaths };
138
139
  }
package/src/cli-help.mjs CHANGED
@@ -8,7 +8,7 @@ import { docsUrl } from './docs-url.mjs';
8
8
  export const COMMANDS = [
9
9
  { name: 'jobs', summary: 'Read a versioned page of jobs', usage: 'dalan jobs --json [--worker W] [--status S] [--since T] [--kind K] [--source S] [--limit N] [--cursor C]', detail: ['Reads local state without changing it. Default page size 100, maximum 1000. Pass next_cursor to --cursor for the next page. --since filters creation time (Nh, Nd, RFC3339, or all). See docs/operations.md#stable-read-interface for fields and compatibility.'] },
10
10
  { name: 'events', summary: 'Read a versioned page of lifecycle events', usage: 'dalan events --json [--since T] [--worker W] [--type TYPE] [--limit N] [--cursor C]', detail: ['Reads retained lifecycle events in ID order without changing state. Default page size 100, maximum 1000. --since takes Nh, Nd, RFC3339, or all. Pass next_cursor to --cursor for the next page. See docs/operations.md#stable-read-interface.'] },
11
- { name: 'relationships', group: 'operator', summary: 'List or end relationships', usage: 'dalan relationships list | end RELATIONSHIP_ID [--json]', detail: ['Ending a relationship blocks new work; existing jobs and grants remain.'] },
11
+ { name: 'relationships', group: 'operator', summary: 'Manage relationships and their publication grants', usage: 'dalan relationships list | end RELATIONSHIP_ID | publish RELATIONSHIP_ID (--grant org:NAME|repo:OWNER/NAME)... | publish RELATIONSHIP_ID --revoke [--json]', detail: ['Use publish RELATIONSHIP_ID --revoke to withdraw permission to publish results. Ending a relationship blocks new work. Existing jobs and read grants retain their own lifetimes.'] },
12
12
  { name: 'grants', group: 'operator', summary: 'List authority held by each enforcer', usage: 'dalan grants [--json]', detail: ['Shows relationship and grant lifetimes independently.'] },
13
13
  { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--route NAME]] [--home DIR] [--port N] [--callback PATTERN]...',
14
14
  detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client (the default) or this computer only. For a hosted client, Dalan asks Gozar for a public HTTPS route, shows what Gozar says about it (who can read the traffic, whether the address is stable, what it costs), and asks for consent before anything is exposed.',
@@ -0,0 +1,7 @@
1
+ // A question from an expired or replaced claim grants no authority to answer.
2
+ export function liveClaimQuestions(row, questions, now = Date.now()) {
3
+ const claim = row.claim;
4
+ if (row.status !== 'claimed' || claim?.state !== 'active' || !(Date.parse(claim.lease_expires_at) > now)) return [];
5
+ return questions.filter(question => !question.answered_at && question.answer == null &&
6
+ question.epoch === claim.epoch && question.claim_id === claim.claim_id);
7
+ }
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 '../integrations/t3/acp-kit/src/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
+ }
@@ -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
 
@@ -111,6 +112,7 @@ function publicationBudget(timeoutMs) {
111
112
  // Shared owner-side publication path. Approval and formatting belong to the caller.
112
113
  export async function materialize({id, got, dir, grantFile, download, recheck,
113
114
  dryRun=false, approve=false, standingOnly=false, fetchBase=false, timeoutMs=30000}) {
115
+ if(got?.request_id!==id) throw new Error('materialize result does not match the requested work');
114
116
  const grant=readMaterializeGrant(grantFile);
115
117
  if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
116
118
  const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
@@ -145,7 +147,7 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
145
147
  rememberCleanup:()=>{ cleanupPending=true; },recheck:async(phase='push')=>{
146
148
  const current=await budget.read(signal=>recheck({signal}));
147
149
  const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
148
- if(current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
150
+ if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
149
151
  throw new Error('materialize result changed before publication; '+after);
150
152
  }
151
153
  const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
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');