@tnunamak/dalan 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +70 -1
- package/CONTRIBUTING.md +2 -0
- package/PROTOCOL.md +6 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +215 -40
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +3 -2
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +78 -14
- package/docs/pull-workers.md +11 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +6 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/t3-wake-fence-r4.md +1 -1
- package/docs/test-suite-isolation.md +8 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +35 -9
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +29 -10
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/inbox.mjs +13 -3
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +104 -11
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +285 -19
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +619 -88
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +64 -19
- package/src/service-update.mjs +193 -48
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +1086 -127
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +49 -4
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
|
|
3
|
+
// A bridge that stops answering leaves no trace in its own request log: a request that never reaches a handler is never logged.
|
|
4
|
+
// The probe asks the bridge's own loopback listener a question on a timer and records how long the answer took, plus how late the
|
|
5
|
+
// timer itself fired (the event loop's lag). A stall then shows up in the log and in `dalan status --json` as a number.
|
|
6
|
+
const answered = (url, timeoutMs) => new Promise(resolve => {
|
|
7
|
+
const req = http.get(url, { agent: false, timeout: timeoutMs }, res => { res.resume(); res.once('end', () => resolve({ status: res.statusCode })); res.once('error', error => resolve({ error: error.code ?? 'error' })); });
|
|
8
|
+
req.once('timeout', () => { req.destroy(); resolve({ error: 'timeout' }); });
|
|
9
|
+
req.once('error', error => resolve({ error: error.code ?? 'error' }));
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export function createLoopbackProbe({
|
|
13
|
+
url, log, intervalMs = 30000, slowMs = 1000, timeoutMs = 30000, heartbeatEvery = 10, keep = 120,
|
|
14
|
+
request = answered, clock = () => Number(process.hrtime.bigint()) / 1e6, wall = () => new Date().toISOString(),
|
|
15
|
+
} = {}) {
|
|
16
|
+
const samples = [];
|
|
17
|
+
let timer = null, expectedAt = null, count = 0, running = false;
|
|
18
|
+
const record = sample => { samples.push(sample); if (samples.length > keep) samples.shift(); };
|
|
19
|
+
const percentile = (values, p) => values.length ? [...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * p))] : null;
|
|
20
|
+
async function tick() {
|
|
21
|
+
const lagMs = expectedAt === null ? 0 : Math.max(0, Math.round(clock() - expectedAt));
|
|
22
|
+
if (running) return; running = true;
|
|
23
|
+
try {
|
|
24
|
+
const started = clock();
|
|
25
|
+
const result = await request(typeof url === 'function' ? url() : url, timeoutMs);
|
|
26
|
+
const ms = Math.round(clock() - started);
|
|
27
|
+
const sample = { at: wall(), ms, lag_ms: lagMs, ...(result.error ? { error: result.error } : { status: result.status }) };
|
|
28
|
+
record(sample); count++;
|
|
29
|
+
if (result.error || ms >= slowMs || lagMs >= slowMs) log({ kind: 'loopback_probe_slow', ms, lag_ms: lagMs, ...(result.error ? { error: result.error } : { status: result.status }) });
|
|
30
|
+
else if (count % heartbeatEvery === 0) {
|
|
31
|
+
const recent = samples.slice(-heartbeatEvery);
|
|
32
|
+
log({ kind: 'loopback_probe', samples: recent.length, p50_ms: percentile(recent.map(s => s.ms), 0.5), max_ms: Math.max(...recent.map(s => s.ms)), max_lag_ms: Math.max(...recent.map(s => s.lag_ms)) });
|
|
33
|
+
}
|
|
34
|
+
} finally { running = false; expectedAt = clock() + intervalMs; }
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
start() { if (timer === null) { expectedAt = clock() + intervalMs; timer = setInterval(() => { tick().catch(() => {}); }, intervalMs); timer.unref(); } return this; },
|
|
38
|
+
stop() { if (timer !== null) { clearInterval(timer); timer = null; } },
|
|
39
|
+
tick,
|
|
40
|
+
// For `dalan status --json`: the last answer, and the worst of the samples kept (about an hour at the default interval).
|
|
41
|
+
snapshot() {
|
|
42
|
+
const last = samples.at(-1) ?? null;
|
|
43
|
+
return { interval_ms: intervalMs, samples: samples.length, last, worst_ms: samples.length ? Math.max(...samples.map(s => s.ms)) : null, worst_lag_ms: samples.length ? Math.max(...samples.map(s => s.lag_ms)) : null, failures: samples.filter(s => s.error).length };
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
package/src/mcp-outcome.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import { redactNote } from './alerts.mjs';
|
|
|
4
4
|
|
|
5
5
|
const responses = new WeakMap();
|
|
6
6
|
|
|
7
|
+
// `worker` is the configured worker name the verified connection maps to (set after auth; null before it), so a call can be
|
|
8
|
+
// attributed to one worker. It is a name from the owner's workers.json, never a client-provided string.
|
|
7
9
|
// The caller's class, never its text: a User-Agent can hold anything, including a credential, so only a name from this fixed
|
|
8
10
|
// list is logged ("other" for the rest, null when absent). That is enough to tell an Anthropic or OpenAI caller from a generic one.
|
|
9
11
|
const UA_CLASSES = [['Claude-User', /^claude-user/i], ['ClaudeBot', /^claudebot/i], ['anthropic-ai', /^anthropic-ai/i], ['ChatGPT-User', /^chatgpt-user/i], ['OAI-SearchBot', /^oai-searchbot/i],
|
|
@@ -24,7 +26,7 @@ export function beginMcpOutcome(req, res, log, toolNames, authRequired) {
|
|
|
24
26
|
const state = {
|
|
25
27
|
call_id: randomUUID(), started_at: new Date().toISOString(),
|
|
26
28
|
http_method: ['POST', 'GET', 'DELETE', 'PUT', 'PATCH', 'HEAD', 'OPTIONS'].includes(req.method) ? req.method : 'other',
|
|
27
|
-
rpc_method: null, tool: null, request_id: null, phase: authRequired ? 'auth' : 'body', auth_outcome: authRequired ? 'pending' : 'disabled',
|
|
29
|
+
rpc_method: null, tool: null, request_id: null, worker: null, phase: authRequired ? 'auth' : 'body', auth_outcome: authRequired ? 'pending' : 'disabled',
|
|
28
30
|
auth_reason: null, auth_duration_ms: null, jwks_outcome: 'not_attempted',
|
|
29
31
|
jwks_duration_ms: null, jwks_http_status: null,
|
|
30
32
|
rpc_error_code: null, tool_error: null, tool_error_message: null, response_bytes: 0,
|
package/src/mcp-sse.mjs
CHANGED
|
@@ -22,7 +22,8 @@ export function beginMcpEventStream(res, { heartbeatMs = 20_000, setIntervalFn =
|
|
|
22
22
|
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
|
|
23
23
|
const heartbeat = () => {
|
|
24
24
|
if (!active || res.destroyed) { stop(); return; }
|
|
25
|
-
res.write(HEARTBEAT);
|
|
25
|
+
try { res.write(HEARTBEAT); }
|
|
26
|
+
catch { stop(); res.destroy(); return; }
|
|
26
27
|
writtenBytes += Buffer.byteLength(HEARTBEAT);
|
|
27
28
|
};
|
|
28
29
|
heartbeat();
|
package/src/mcp-stdio.mjs
CHANGED
|
@@ -5,30 +5,63 @@
|
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
-
import readline from 'node:readline';
|
|
9
8
|
import { redactOutput, redactSinkText } from './redaction.mjs';
|
|
10
9
|
import { safeDiagnostic } from './diagnostic.mjs';
|
|
10
|
+
import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
|
|
11
11
|
|
|
12
12
|
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
13
13
|
export const RESULT_CAP_BYTES = 32 * 1024;
|
|
14
|
+
export const MAX_INPUT_FRAME_BYTES = 1024 * 1024 + 1;
|
|
14
15
|
const WAIT_DEFAULT = 120, WAIT_MAX = 300;
|
|
16
|
+
const SUBMIT_NEXT = 'Check dalan_status or dalan_result later, or read the inbox.';
|
|
15
17
|
const CLI = path.join(import.meta.dirname, '../bin/dalan.mjs');
|
|
16
|
-
const requestId = { type: 'string', pattern: '
|
|
18
|
+
const requestId = { type: 'string', pattern: '^\\w[-\\w]{7,127}$', description: 'The request_id of a submitted job; it cannot start with a dash.' };
|
|
19
|
+
|
|
20
|
+
const submitProperties = {
|
|
21
|
+
assignment: { type: 'object', description: 'The assignment: request_id (8-128 letters, digits, _ or -; cannot start with a dash), brief, inputs (array; [] for none), expected_output, and the other fields `dalan submit` accepts.',
|
|
22
|
+
required: ['request_id'], properties: { request_id: requestId, brief: { type: 'string' }, inputs: { type: 'array' } } },
|
|
23
|
+
task: { type: 'string', description: 'Task text; maps to assignment.brief. Omit when assignment contains brief, objective or stop_rule.' },
|
|
24
|
+
priority_class: { type: 'string', enum: ['normal', 'background'], description: 'Queue priority (default normal).' },
|
|
25
|
+
requirements: { type: 'array', items: { type: 'string' }, description: 'Required supported backend or adapter capability names.' },
|
|
26
|
+
repo: { type: 'string', description: 'GitHub owner/repo; supply with base and an empty assignment.inputs.' },
|
|
27
|
+
base: { type: 'string', description: 'Full pushed commit SHA; supply with repo.' },
|
|
28
|
+
worker: { type: 'string', description: 'Name of the worker to queue for. Optional with a one-worker profile.' },
|
|
29
|
+
execution: { type: 'string', enum: ['none', 'worker', 'host'], description: 'Execution capability for the job.' }
|
|
30
|
+
};
|
|
17
31
|
|
|
18
32
|
export const TOOLS = [
|
|
19
33
|
{ name: 'dalan_submit', title: 'Submit a job',
|
|
20
34
|
description: 'Queue a bounded job for a Dalan worker (same checks as `dalan submit`). Returns the request_id and the bridge verdict. A clarify or reject verdict comes back as an error result with the reasons; fix the assignment and submit again. Resubmitting the same assignment is safe.',
|
|
21
35
|
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
worker: { type: 'string', description: 'Name of the worker to queue for. Optional with a one-worker profile.' },
|
|
25
|
-
execution: { type: 'string', enum: ['none', 'worker', 'host'], description: 'Execution capability for the job.' },
|
|
36
|
+
...submitProperties,
|
|
37
|
+
follows: { ...requestId, description: 'A finished predecessor this bridge home owns. Its result is not copied.' },
|
|
26
38
|
dry_run: { type: 'boolean', description: 'Check the assignment and store nothing.' },
|
|
27
39
|
queue_anyway: { type: 'boolean', description: 'Queue even when the bridge would defer or warn.' },
|
|
28
40
|
refuse_defer: { type: 'boolean', description: 'Fail instead of deferring.' } } },
|
|
29
41
|
annotations: { title: 'Submit a job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
42
|
+
{ name: 'dalan_forecast', title: 'Forecast a job',
|
|
43
|
+
description: 'Check a bounded job and estimate its admission without submitting it or reserving capacity. Returns the same verdict as a submit dry run, plus available queue and worker estimates.',
|
|
44
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: submitProperties },
|
|
45
|
+
annotations: { title: 'Forecast a job', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
46
|
+
{ name: 'dalan_cancel', title: 'Cancel a job',
|
|
47
|
+
description: 'Stop a queued job or ask the worker on a claimed job to stop. The reply states the job’s state.',
|
|
48
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
49
|
+
request_id: requestId,
|
|
50
|
+
reason: { type: 'string', description: 'Optional reason for cancelling the job.' } } },
|
|
51
|
+
annotations: { title: 'Cancel a job', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false } },
|
|
52
|
+
{ name: 'dalan_accept', title: 'Accept or reject a job result',
|
|
53
|
+
description: 'Record an accept or reject verdict for a job result as its requester, using the existing CLI checks.',
|
|
54
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id', 'verdict'], properties: {
|
|
55
|
+
request_id: requestId, verdict: { type: 'string', enum: ['accept', 'reject'] },
|
|
56
|
+
note: { type: 'string', description: 'Optional note explaining the verdict.' } } },
|
|
57
|
+
annotations: { title: 'Accept or reject a job result', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
58
|
+
{ name: 'dalan_correct', title: 'Correct an earlier job',
|
|
59
|
+
description: 'Submit a new job to correct an earlier job you submitted. This cancels nothing; the earlier job’s result can no longer be accepted. Returns the new request_id and verdict.',
|
|
60
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['revises', 'assignment'], properties: {
|
|
61
|
+
revises: requestId, ...submitProperties } },
|
|
62
|
+
annotations: { title: 'Correct an earlier job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
30
63
|
{ name: 'dalan_wait', title: 'Wait for a job',
|
|
31
|
-
description: `Wait for a job to reach a stop (finished, blocker, question, cancelled, worker_break). Returns after at most timeout_seconds (default ${WAIT_DEFAULT}, maximum ${WAIT_MAX}) with the current state; status "timeout" means it is still running, so call again.`,
|
|
64
|
+
description: `Wait for a job to reach a stop (finished, blocker, question, cancelled, worker_break). Returns after at most timeout_seconds (default ${WAIT_DEFAULT}, maximum ${WAIT_MAX}) with the current state; status "timeout" means it is still running, so call again. If dalan_wait reports a waiting question: call dalan_questions, then dalan_answer, then dalan_wait again.`,
|
|
32
65
|
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
33
66
|
request_id: requestId,
|
|
34
67
|
timeout_seconds: { type: 'integer', minimum: 1, maximum: WAIT_MAX, default: WAIT_DEFAULT, description: `Seconds to wait; values above ${WAIT_MAX} are lowered to ${WAIT_MAX}.` } } },
|
|
@@ -37,6 +70,17 @@ export const TOOLS = [
|
|
|
37
70
|
description: `Read the current state of a job, with the worker's report once it has finished. Secrets are redacted and output is capped at ${RESULT_CAP_BYTES / 1024} KiB.`,
|
|
38
71
|
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: { request_id: requestId } },
|
|
39
72
|
annotations: { title: 'Read a job result', readOnlyHint: true, openWorldHint: false } },
|
|
73
|
+
{ name: 'dalan_questions', title: 'Read job questions',
|
|
74
|
+
description: 'Read identified questions with the local owner receipt. Several can be open at once; answer each by its question_id, then wait again. Human-only questions still require operator action.',
|
|
75
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['id'], properties: { id: requestId } },
|
|
76
|
+
annotations: { title: 'Read job questions', readOnlyHint: true, openWorldHint: false } },
|
|
77
|
+
{ name: 'dalan_answer', title: 'Answer a job question',
|
|
78
|
+
description: 'Answer an identified clarification through the CLI answer journal. Exact retries reuse the saved envelope; different text for the same saved attempt is refused. Then call dalan_wait again. This cannot answer human-only questions with owner authority alone.',
|
|
79
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['id', 'question_id', 'text'], properties: {
|
|
80
|
+
id: requestId,
|
|
81
|
+
question_id: { type: 'string', pattern: '^(?!-)[A-Za-z0-9_.:-]{1,128}$' },
|
|
82
|
+
text: { type: 'string', description: `Nonblank answer, at most ${MAX_ANSWER_BYTES} UTF-8 bytes. Text beginning with a dash is not supported by the CLI.` } } },
|
|
83
|
+
annotations: { title: 'Answer a job question', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
40
84
|
{ name: 'dalan_status', title: 'Bridge status',
|
|
41
85
|
description: 'Show the bridge status (`dalan status --json`): queue, workers and health.',
|
|
42
86
|
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
@@ -58,9 +102,10 @@ function validate(tool, args) {
|
|
|
58
102
|
for (const [key, value] of Object.entries(args)) {
|
|
59
103
|
const spec = properties[key];
|
|
60
104
|
if (spec.type === 'object' ? !value || typeof value !== 'object' || Array.isArray(value)
|
|
61
|
-
: spec.type === 'integer' ? !Number.isInteger(value) : typeof value !== spec.type) throw fail(`argument "${key}" must be ${spec.type === 'object' ? 'an object' : `a ${spec.type}`}`);
|
|
105
|
+
: spec.type === 'integer' ? !Number.isInteger(value) : spec.type === 'array' ? !Array.isArray(value) : typeof value !== spec.type) throw fail(`argument "${key}" must be ${spec.type === 'object' ? 'an object' : `a ${spec.type}`}`);
|
|
106
|
+
if (spec.type === 'array' && value.some(item => typeof item !== 'string' || !item || item.includes(',') || item.includes('\u0000'))) throw fail(`argument "${key}" must contain nonempty capability names`);
|
|
62
107
|
if (spec.enum && !spec.enum.includes(value)) throw fail(`argument "${key}" must be one of ${spec.enum.join(', ')}`);
|
|
63
|
-
if (spec.pattern && !new RegExp(spec.pattern).test(value)) throw fail(`argument "${key}" is not a valid request id (8-128 letters, digits, _ or
|
|
108
|
+
if (spec.pattern && !new RegExp(spec.pattern).test(value)) throw fail(`argument "${key}" is not a valid request id (8-128 letters, digits, _ or -; cannot start with a dash)`);
|
|
64
109
|
if (spec.type === 'string' && value.startsWith('--')) throw fail(`argument "${key}" must not start with --`);
|
|
65
110
|
}
|
|
66
111
|
return args;
|
|
@@ -69,14 +114,19 @@ function validate(tool, args) {
|
|
|
69
114
|
// Run `dalan <args> --json`. stdout and stderr are collected, never forwarded: stdout of this process is the protocol.
|
|
70
115
|
function runCli(args, { input, timeoutMs = 60_000, env = process.env } = {}) {
|
|
71
116
|
return new Promise(resolve => {
|
|
72
|
-
|
|
117
|
+
let child;
|
|
118
|
+
try { child = spawn(process.execPath, [CLI, ...args, '--json'], { env, stdio: ['pipe', 'pipe', 'pipe'] }); }
|
|
119
|
+
catch { resolve({ code: null, termination: 'exec_failed' }); return; }
|
|
73
120
|
let stdout = '', stderr = '', done = false;
|
|
74
121
|
const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };
|
|
75
|
-
const timer = setTimeout(() => {
|
|
122
|
+
const timer = setTimeout(() => {
|
|
123
|
+
finish({ code: null, termination: 'deadline', timeoutMs });
|
|
124
|
+
child.kill('SIGKILL');
|
|
125
|
+
}, timeoutMs);
|
|
76
126
|
child.stdout.on('data', chunk => { stdout += chunk; });
|
|
77
127
|
child.stderr.on('data', chunk => { stderr += chunk; });
|
|
78
|
-
child.on('error',
|
|
79
|
-
child.on('close', code => finish({ code, stdout, stderr }));
|
|
128
|
+
child.on('error', () => finish({ code: null, termination: 'exec_failed' }));
|
|
129
|
+
child.on('close', (code, signal) => finish({ code, signal, stdout, stderr }));
|
|
80
130
|
child.stdin.on('error', () => {});
|
|
81
131
|
child.stdin.end(input ?? '');
|
|
82
132
|
});
|
|
@@ -85,10 +135,19 @@ const parseJson = text => { try { return JSON.parse(text); } catch { return unde
|
|
|
85
135
|
// stderr may hold warnings before the final error JSON line.
|
|
86
136
|
const lastJsonLine = text => text.trim().split('\n').reverse().map(parseJson).find(v => v && typeof v === 'object');
|
|
87
137
|
|
|
138
|
+
const RETRYABLE_CLI_READS = new Set(['forecast', 'wait', 'get', 'questions', 'status']);
|
|
88
139
|
export function cliError(run, label) {
|
|
89
|
-
|
|
140
|
+
if (run.termination === 'deadline') {
|
|
141
|
+
return { isError: true, value: { code: 'cli_deadline', retryable: RETRYABLE_CLI_READS.has(label),
|
|
142
|
+
error: `dalan ${label} did not answer within ${Math.round(run.timeoutMs / 1000)}s` } };
|
|
143
|
+
}
|
|
144
|
+
if (run.termination === 'exec_failed') {
|
|
145
|
+
return { isError: true, value: { code: 'cli_exec_failed', retryable: false, error: `could not start dalan ${label}` } };
|
|
146
|
+
}
|
|
147
|
+
const body = run.code === null ? undefined : lastJsonLine(run.stderr) ?? lastJsonLine(run.stdout);
|
|
90
148
|
if (body) return { isError: true, value: body };
|
|
91
|
-
|
|
149
|
+
const exit = run.signal ? ` (signal ${run.signal})` : run.code === null ? '' : ` (exit ${run.code})`;
|
|
150
|
+
return { isError: true, message: `${label} failed${exit}: ${safeDiagnostic((run.stderr || run.stdout).trim(), 4000) || 'no output'}` };
|
|
92
151
|
}
|
|
93
152
|
|
|
94
153
|
function capped(value) {
|
|
@@ -106,23 +165,73 @@ const asResult = ({ isError, value, message }) => {
|
|
|
106
165
|
return { content: [{ type: 'text', text }], ...(structured && typeof structured === 'object' ? { structuredContent: structured } : {}), ...(isError ? { isError: true } : {}) };
|
|
107
166
|
};
|
|
108
167
|
|
|
168
|
+
const pick = (value, keys) => Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
169
|
+
const claimDurationProjection = value => pick(value, ['source', 'n', 'min_samples', 'p50_ms']);
|
|
170
|
+
const sessionLengthProjection = value => pick(value, ['source', 'n', 'min_samples', 'window_days', 'p50_ms']);
|
|
171
|
+
const recordProjection = record => ({ ...pick(record, ['worker', 'kind', 'window_days', 'n', 'accepted', 'check_passed']),
|
|
172
|
+
...(record.claim_to_report ? { claim_to_report: claimDurationProjection(record.claim_to_report) } : {}),
|
|
173
|
+
...(record.session_length ? { session_length: sessionLengthProjection(record.session_length) } : {}),
|
|
174
|
+
...(record.outcomes ? { outcomes: pick(record.outcomes, ['landed', 'check_passed', 'checks_failed', 'refused_by_provider', 'unable_to_run', 'owner_cancelled', 'finished_unchecked']) } : {}) });
|
|
175
|
+
export function projectAdmission(admission) {
|
|
176
|
+
const answer = pick(admission, ['start', 'worker_state', 'until', 'until_source', 'at']);
|
|
177
|
+
if (admission.ahead) answer.ahead = pick(admission.ahead, ['count', 'oldest_age_ms']);
|
|
178
|
+
if (admission.latency) {
|
|
179
|
+
const latency = admission.latency;
|
|
180
|
+
answer.latency = pick(latency, ['worker', 'kind', 'window_days', 'min_samples']);
|
|
181
|
+
if (latency.censored) answer.latency.censored = pick(latency.censored, ['expired_unclaimed', 'cancelled_unclaimed', 'claimed_not_started', 'finished_unobserved_start']);
|
|
182
|
+
for (const key of ['claimed', 'started']) if (latency[key]) answer.latency[key] = pick(latency[key], ['n', 'p50_ms', 'p90_ms', 'insufficient_history']);
|
|
183
|
+
}
|
|
184
|
+
if (admission.track_record) answer.track_record = recordProjection(admission.track_record);
|
|
185
|
+
if (admission.claim_to_report) answer.claim_to_report = claimDurationProjection(admission.claim_to_report);
|
|
186
|
+
if (admission.session_length) answer.session_length = sessionLengthProjection(admission.session_length);
|
|
187
|
+
return answer;
|
|
188
|
+
}
|
|
189
|
+
const projectAnswer = value => ({ ...value, ...(value.admission ? { admission: projectAdmission(value.admission) } : {}),
|
|
190
|
+
...(value.track_record ? { track_record: recordProjection(value.track_record) } : {}) });
|
|
191
|
+
|
|
192
|
+
const forecastAnswer = value => Object.fromEntries(['verdict', 'reasons', 'admission', 'track_record']
|
|
193
|
+
.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
|
|
194
|
+
|
|
195
|
+
async function submit(args, extraFlags = [], {forecast = false} = {}) {
|
|
196
|
+
if (args.worker?.startsWith('-') || args.worker?.includes('\u0000')) throw fail('worker name must not start with a dash or contain NUL');
|
|
197
|
+
if ((args.repo === undefined) !== (args.base === undefined)) throw fail('repo and base must be supplied together');
|
|
198
|
+
if (args.task !== undefined && ['brief', 'objective', 'stop_rule'].some(field => args.assignment[field] !== undefined)) throw fail('supply task or assignment brief/objective/stop_rule, not both');
|
|
199
|
+
if (args.repo !== undefined && (!Array.isArray(args.assignment.inputs) || args.assignment.inputs.length)) throw fail('repo and base require empty assignment.inputs');
|
|
200
|
+
const assignment = { ...args.assignment, ...(args.task !== undefined ? { brief: args.task } : {}),
|
|
201
|
+
...(args.repo !== undefined ? { inputs: [{ github_repo: args.repo, base_sha: args.base, head_sha: args.base }] } : {}) };
|
|
202
|
+
const flags = [...extraFlags, ...(forecast ? ['--dry-run'] : [])];
|
|
203
|
+
if (args.worker) flags.push('--worker', args.worker);
|
|
204
|
+
if (args.execution) flags.push('--execution', args.execution);
|
|
205
|
+
if (args.priority_class === 'background') flags.push('--background');
|
|
206
|
+
if (args.requirements?.length) flags.push('--require-capability', args.requirements.join(','));
|
|
207
|
+
for (const [key, flag] of [['dry_run', '--dry-run'], ['queue_anyway', '--queue-anyway'], ['refuse_defer', '--refuse-defer']]) if (!forecast && args[key]) flags.push(flag);
|
|
208
|
+
const run = await runCli(['submit', '--stdin', ...flags], { input: JSON.stringify(assignment) });
|
|
209
|
+
const value = run.code === null ? undefined : parseJson(run.stdout);
|
|
210
|
+
// 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) });
|
|
212
|
+
const error = cliError(run, forecast ? 'forecast' : 'submit');
|
|
213
|
+
if (error.value !== undefined) error.value = projectAnswer(forecast && error.value.verdict ? forecastAnswer(error.value) : error.value);
|
|
214
|
+
return asResult(error);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function ownerTransition(command, id, flag, text) {
|
|
218
|
+
if (text?.startsWith('-') || text?.includes('\u0000')) throw fail(flag.slice(2) + ' text must not start with a dash or contain NUL');
|
|
219
|
+
const run = await runCli([command, id, ...(text === undefined ? [] : [flag, text])]);
|
|
220
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
221
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, command));
|
|
222
|
+
}
|
|
223
|
+
|
|
109
224
|
const handlers = {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const run = await runCli(['submit', '--stdin', ...flags], { input: JSON.stringify(args.assignment) });
|
|
116
|
-
const value = parseJson(run.stdout);
|
|
117
|
-
// A dry run exits non-zero for clarify, reject and defer but still prints the verdict on stdout.
|
|
118
|
-
if (value !== undefined) return asResult({ value, isError: run.code !== 0 && (value.verdict ? value.verdict !== 'admissible' : true) });
|
|
119
|
-
return asResult(cliError(run, 'submit'));
|
|
120
|
-
},
|
|
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]),
|
|
228
|
+
dalan_cancel: args => ownerTransition('cancel', args.request_id, '--reason', args.reason),
|
|
229
|
+
dalan_accept: args => ownerTransition(args.verdict, args.request_id, '--note', args.note),
|
|
121
230
|
async dalan_wait(args) {
|
|
122
231
|
const seconds = Math.min(args.timeout_seconds ?? WAIT_DEFAULT, WAIT_MAX);
|
|
123
232
|
const run = await runCli(['wait', args.request_id, '--timeout', String(Math.max(1, seconds))], { timeoutMs: (seconds + 30) * 1000 });
|
|
124
233
|
// wait exits 3, 4, 5 and 124 for non-finished states; the JSON on stdout is the state, not a failure.
|
|
125
|
-
const value = parseJson(run.stdout);
|
|
234
|
+
const value = run.code === null ? undefined : parseJson(run.stdout);
|
|
126
235
|
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'wait'));
|
|
127
236
|
},
|
|
128
237
|
async dalan_result(args) {
|
|
@@ -130,6 +239,21 @@ const handlers = {
|
|
|
130
239
|
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
131
240
|
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'get'));
|
|
132
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
|
+
},
|
|
247
|
+
async dalan_answer(args) {
|
|
248
|
+
if (!args.text.trim()) throw fail('answer text must not be blank');
|
|
249
|
+
if (Buffer.byteLength(args.text) > MAX_ANSWER_BYTES) throw fail(`answer text exceeds ${MAX_ANSWER_BYTES} UTF-8 bytes; nothing was sent or saved`);
|
|
250
|
+
// The CLI treats leading dashes as options and argv cannot carry NUL.
|
|
251
|
+
if (args.text.startsWith('-') || args.text.includes('\u0000')) throw fail('answer text must not start with a dash or contain NUL');
|
|
252
|
+
if (args.question_id.startsWith('-') || args.question_id.includes('\u0000')) throw fail('question_id must not start with a dash or contain NUL');
|
|
253
|
+
const run = await runCli(['answer', args.id, args.question_id, args.text]);
|
|
254
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
255
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'answer'));
|
|
256
|
+
},
|
|
133
257
|
async dalan_status() {
|
|
134
258
|
const run = await runCli(['status']);
|
|
135
259
|
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
@@ -154,6 +278,9 @@ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, me
|
|
|
154
278
|
|
|
155
279
|
// One JSON-RPC message in, zero or one frame out. Never throws.
|
|
156
280
|
export async function handleFrame(message) {
|
|
281
|
+
const candidateId = message?.id;
|
|
282
|
+
if (candidateId !== undefined && candidateId !== null && typeof candidateId !== 'string' &&
|
|
283
|
+
(typeof candidateId !== 'number' || !Number.isFinite(candidateId))) return rpcError(null, -32600, 'invalid request');
|
|
157
284
|
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return rpcError(message?.id ?? null, -32600, 'invalid request');
|
|
158
285
|
const { id, method, params } = message;
|
|
159
286
|
if (id === undefined) return null; // notification
|
|
@@ -161,7 +288,7 @@ export async function handleFrame(message) {
|
|
|
161
288
|
switch (method) {
|
|
162
289
|
case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
163
290
|
capabilities: { tools: {} }, serverInfo: { name: 'dalan-mcp', version: '1' },
|
|
164
|
-
instructions: 'Local requester tools for a Dalan bridge: dalan_submit queues a job, dalan_wait waits for it, dalan_result reads the report, dalan_status shows the bridge.' });
|
|
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.' });
|
|
165
292
|
case 'ping': return ok({});
|
|
166
293
|
case 'tools/list': return ok({ tools: TOOLS });
|
|
167
294
|
case 'tools/call': {
|
|
@@ -173,10 +300,45 @@ export async function handleFrame(message) {
|
|
|
173
300
|
}
|
|
174
301
|
}
|
|
175
302
|
|
|
176
|
-
|
|
303
|
+
// One reusable bounded byte buffer; don't decode a frame that exceeded the
|
|
304
|
+
// limit. The extra byte admits CRLF without charging the CR to the JSON body.
|
|
305
|
+
async function* inputFrames(input, limit) {
|
|
306
|
+
const frame = Buffer.allocUnsafe(limit + 1);
|
|
307
|
+
let used = 0, discard = false;
|
|
308
|
+
const read = () => {
|
|
309
|
+
const size = used && frame[used - 1] === 13 ? used - 1 : used;
|
|
310
|
+
return discard || size > limit ? null : frame.subarray(0, size).toString('utf8');
|
|
311
|
+
};
|
|
312
|
+
for await (const chunk of input) {
|
|
313
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
314
|
+
for (let offset = 0; offset < bytes.length;) {
|
|
315
|
+
const newline = bytes.indexOf(10, offset);
|
|
316
|
+
const end = newline === -1 ? bytes.length : newline;
|
|
317
|
+
if (!discard) {
|
|
318
|
+
if (end - offset > frame.length - used) discard = true;
|
|
319
|
+
else {
|
|
320
|
+
bytes.copy(frame, used, offset, end);
|
|
321
|
+
used += end - offset;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
if (newline === -1) break;
|
|
325
|
+
yield read();
|
|
326
|
+
used = 0;
|
|
327
|
+
discard = false;
|
|
328
|
+
offset = newline + 1;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (used || discard) yield read();
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
export async function main({ input = process.stdin, output = process.stdout, maxFrameBytes = MAX_INPUT_FRAME_BYTES } = {}) {
|
|
335
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0 || maxFrameBytes > MAX_INPUT_FRAME_BYTES) {
|
|
336
|
+
throw new RangeError('invalid stdio frame limit');
|
|
337
|
+
}
|
|
177
338
|
const inflight = new Set();
|
|
178
339
|
const write = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
179
|
-
for await (const line of
|
|
340
|
+
for await (const line of inputFrames(input, maxFrameBytes)) {
|
|
341
|
+
if (line === null) { write(rpcError(null, -32600, 'request frame exceeds byte limit')); continue; }
|
|
180
342
|
if (!line.trim()) continue;
|
|
181
343
|
let message;
|
|
182
344
|
try { message = JSON.parse(line); }
|