@tnunamak/dalan 0.0.0-stage → 0.5.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 +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// Append-only lifecycle events: one row per state change, written in the same transaction as the change.
|
|
2
|
+
// Metrics derive from these rows only; anything the rows cannot show is reported as unknown with a reason, never as zero.
|
|
3
|
+
import { fromStoredSource, canonicalObjectiveKey, canonicalKindSql, canonicalKindLabel } from './objectives.mjs';
|
|
4
|
+
export const lifecycleTypes=['queued','claimed','working','waiting','blocked','completed','consumed','accepted','integrated','abandoned','cancelled','delivery_sent','delivery_uncertain','reconciled','check_started','check_passed','check_failed','check_skipped'];
|
|
5
|
+
export const retentionDays=90;
|
|
6
|
+
// Two consecutive claim activity events no more than this far apart count as working time (see docs/usage.md, "Metrics").
|
|
7
|
+
export const activeGapMs=20*60000;
|
|
8
|
+
const defaultWindowMs=30*86400000;
|
|
9
|
+
// Kind of an assignment (alias a): the submitter's task_kind (column, else payload), else review or execution_scope; then the priority.
|
|
10
|
+
export const kindSql=`${canonicalKindSql("COALESCE(a.task_kind,json_extract(a.payload,'$.task_kind'),CASE WHEN a.review=1 THEN 'review' ELSE json_extract(a.payload,'$.execution_scope') END,'unknown')")}||'/'||COALESCE(a.priority,'normal')`;
|
|
11
|
+
// Same rule as the blocker forwarding in Store.progress: BLOCKED: or blocker:true is blocked, QUESTION: is waiting for the owner.
|
|
12
|
+
export const progressType=(note,blocker=false)=>blocker||/^\s*BLOCKED:/im.test(note)?'blocked':/^\s*QUESTION:/im.test(note)?'waiting':'working';
|
|
13
|
+
|
|
14
|
+
// Retention deletes go through one guarded path: the trigger admits a DELETE only for rows older than the cutoff that
|
|
15
|
+
// retainLifecycle sets and clears inside its own transaction. This guards against accidental writes, not against a
|
|
16
|
+
// process that can rewrite the schema.
|
|
17
|
+
export const lifecycleSchema=`CREATE TABLE IF NOT EXISTS lifecycle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, request_id TEXT NOT NULL, claim_id TEXT, epoch INTEGER, type TEXT NOT NULL CHECK(type IN (${lifecycleTypes.map(t=>`'${t}'`).join(',')})), at TEXT NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('live','backfill')), reason TEXT);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS lifecycle_events_request ON lifecycle_events(request_id,id);
|
|
19
|
+
CREATE INDEX IF NOT EXISTS lifecycle_events_type_at ON lifecycle_events(type,at);
|
|
20
|
+
CREATE TABLE IF NOT EXISTS lifecycle_daily (day TEXT NOT NULL, type TEXT NOT NULL, kind TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY(day,type,kind));
|
|
21
|
+
CREATE TABLE IF NOT EXISTS lifecycle_retention (id INTEGER PRIMARY KEY CHECK(id=1), cutoff TEXT, rolled_up_before TEXT);
|
|
22
|
+
INSERT OR IGNORE INTO lifecycle_retention(id) VALUES(1);
|
|
23
|
+
CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_update BEFORE UPDATE ON lifecycle_events BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;
|
|
24
|
+
CREATE TRIGGER IF NOT EXISTS lifecycle_events_no_delete BEFORE DELETE ON lifecycle_events WHEN NOT EXISTS (SELECT 1 FROM lifecycle_retention WHERE id=1 AND cutoff IS NOT NULL AND old.at<cutoff) BEGIN SELECT RAISE(ABORT, 'lifecycle events are append-only'); END;`;
|
|
25
|
+
|
|
26
|
+
export const checkOutcome=(job,run)=>{
|
|
27
|
+
const base=`check_id=${job.check_id};check_run_id=${job.id}`;
|
|
28
|
+
const skipped=job.skipped_segments??run?.skipped_segments??(run?.exit_code===77?1:0);
|
|
29
|
+
const detail=job.check_summary??run?.check_summary??(skipped?`skipped_segments=${skipped}`:null);
|
|
30
|
+
const suffix=detail?`;${detail}`:'';
|
|
31
|
+
if(['completed','skipped','failed'].includes(job.status)&&run) {
|
|
32
|
+
const clean=job.status!=='failed'&&run.phase==='check'&&[0,77].includes(run.exit_code)&&!run.timed_out&&!run.cancelled;
|
|
33
|
+
if(clean&&(skipped||job.status==='skipped')) return ['check_skipped',base+suffix];
|
|
34
|
+
return clean&&run.exit_code===0?['check_passed',base]:['check_failed',`${base};phase=${run.phase};exit=${run.exit_code}${run.timed_out?';timed_out':''}${run.cancelled?';cancelled':''}${suffix}`];
|
|
35
|
+
}
|
|
36
|
+
if(job.status==='failed') return ['check_failed',`${base};error${suffix}`];
|
|
37
|
+
if(job.status==='interrupted') return ['check_failed',`${base};interrupted`];
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// History from rows that predate lifecycle events. Only what the rows prove: claims keep their current epoch only, and
|
|
42
|
+
// consumed, accepted, integrated, abandoned and check_skipped leave no trace before v21, so none is invented.
|
|
43
|
+
export function backfillLifecycle(db) {
|
|
44
|
+
// Idempotent: a table that already holds any event (backfilled or live) is never backfilled again.
|
|
45
|
+
if(db.prepare('SELECT 1 FROM lifecycle_events LIMIT 1').get()) return 0;
|
|
46
|
+
const claims=new Map(db.prepare('SELECT request_id,claim_id,epoch,claimed_at FROM claims').all().map(c=>[c.request_id,c]));
|
|
47
|
+
const byClaimId=new Map([...claims.values()].map(c=>[c.claim_id,c]));
|
|
48
|
+
const inClaim=(id,at)=>{ const c=claims.get(id); return c&&at>=c.claimed_at?c:null; };
|
|
49
|
+
const events=[], add=(requestId,type,at,claim,reason=null)=>{ if(requestId&&at) events.push([requestId,claim?.claim_id??null,claim?.epoch??null,type,at,reason]); };
|
|
50
|
+
for(const a of db.prepare('SELECT request_id,created_at,cancelled_at FROM assignments').all()) {
|
|
51
|
+
add(a.request_id,'queued',a.created_at,null);
|
|
52
|
+
if(a.cancelled_at) add(a.request_id,'cancelled',a.cancelled_at,inClaim(a.request_id,a.cancelled_at));
|
|
53
|
+
}
|
|
54
|
+
for(const c of claims.values()) add(c.request_id,'claimed',c.claimed_at,c,c.epoch>1?'current epoch only; earlier epochs unknown':null);
|
|
55
|
+
for(const p of db.prepare('SELECT request_id,note,created_at FROM progress ORDER BY id').all()) add(p.request_id,progressType(p.note),p.created_at,inClaim(p.request_id,p.created_at));
|
|
56
|
+
for(const r of db.prepare('SELECT request_id,claim_id,outcome,late,created_at FROM reports').all()) {
|
|
57
|
+
const claim=byClaimId.get(r.claim_id)??{claim_id:r.claim_id,epoch:null};
|
|
58
|
+
add(r.request_id,'completed',r.created_at,claim,`outcome=${r.outcome}${r.late?';late':''}`);
|
|
59
|
+
if(r.outcome==='blocked') add(r.request_id,'blocked',r.created_at,claim);
|
|
60
|
+
}
|
|
61
|
+
for(const n of db.prepare("SELECT request_id,kind,state,attempt_started_at,last_reconciled_at,uncertain_reason FROM notifications WHERE kind IN ('t3','blocker','watch') AND attempt_started_at IS NOT NULL AND state IN ('delivered','uncertain')").all()) {
|
|
62
|
+
const claim=inClaim(n.request_id,n.attempt_started_at);
|
|
63
|
+
if(n.state==='uncertain') add(n.request_id,'delivery_uncertain',n.attempt_started_at,claim,n.kind);
|
|
64
|
+
else if(n.last_reconciled_at) { add(n.request_id,'delivery_uncertain',n.attempt_started_at,claim,n.kind); add(n.request_id,'reconciled',n.last_reconciled_at,inClaim(n.request_id,n.last_reconciled_at),n.kind); }
|
|
65
|
+
else add(n.request_id,'delivery_sent',n.attempt_started_at,claim,n.kind);
|
|
66
|
+
}
|
|
67
|
+
for(const job of db.prepare('SELECT j.*,r.phase,r.exit_code,r.timed_out FROM check_jobs j LEFT JOIN check_runs r ON r.id=j.id').all()) {
|
|
68
|
+
const claim=byClaimId.get(job.claim_id)??{claim_id:job.claim_id,epoch:null};
|
|
69
|
+
add(job.request_id,'check_started',job.started_at,claim,`check_id=${job.check_id};check_run_id=${job.id}`);
|
|
70
|
+
const outcome=checkOutcome(job,job.phase==null?null:job);
|
|
71
|
+
if(outcome) add(job.request_id,outcome[0],job.finished_at??job.started_at,claim,outcome[1]);
|
|
72
|
+
}
|
|
73
|
+
events.sort((a,b)=>a[4]<b[4]?-1:a[4]>b[4]?1:0);
|
|
74
|
+
const insert=db.prepare("INSERT INTO lifecycle_events(request_id,claim_id,epoch,type,at,actor,source,reason) VALUES(?,?,?,?,?,'system','backfill',?)");
|
|
75
|
+
for(const e of events) insert.run(...e);
|
|
76
|
+
return events.length;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Events older than the retention window become per-day counts by type and kind, then leave the event table.
|
|
80
|
+
export function retainLifecycle(store,days=retentionDays) { return store.transaction(()=>{
|
|
81
|
+
const db=store.db, cutoff=new Date(store.nowMs()-days*86400000).toISOString();
|
|
82
|
+
db.prepare(`INSERT INTO lifecycle_daily(day,type,kind,count) SELECT substr(e.at,1,10),e.type,${kindSql},count(*) FROM lifecycle_events e LEFT JOIN assignments a ON a.request_id=e.request_id WHERE e.at<? GROUP BY 1,2,3
|
|
83
|
+
ON CONFLICT(day,type,kind) DO UPDATE SET count=count+excluded.count`).run(cutoff);
|
|
84
|
+
db.prepare('UPDATE lifecycle_retention SET cutoff=? WHERE id=1').run(cutoff);
|
|
85
|
+
const deleted=db.prepare('DELETE FROM lifecycle_events WHERE at<?').run(cutoff).changes;
|
|
86
|
+
db.prepare('UPDATE lifecycle_retention SET cutoff=NULL,rolled_up_before=CASE WHEN ?>0 THEN ? ELSE rolled_up_before END WHERE id=1').run(deleted,cutoff);
|
|
87
|
+
return {cutoff,rolled_up:deleted};
|
|
88
|
+
}); }
|
|
89
|
+
|
|
90
|
+
const metric=(value,unit)=>({value,unit}), unknown=reason=>({value:null,unknown_reason:reason});
|
|
91
|
+
const rank=(xs,p)=>{ const s=[...xs].sort((a,b)=>a-b); return s[Math.max(0,Math.ceil(p*s.length)-1)]; };
|
|
92
|
+
const distribution=(xs,why)=>({n:metric(xs.length,'count'),p50:xs.length?metric(rank(xs,0.5),'ms'):unknown(why),p90:xs.length?metric(rank(xs,0.9),'ms'):unknown(why)});
|
|
93
|
+
const ratio=(num,den,unit,why)=>den>0?metric(Math.round(num/den*1000)/1000,unit):unknown(why);
|
|
94
|
+
const activity=new Set(['claimed','working','blocked','waiting','check_started','check_passed','check_failed','check_skipped','completed']);
|
|
95
|
+
const firstActivity=new Set(['working','blocked','waiting','check_started']);
|
|
96
|
+
const closes=new Set(['completed','abandoned','cancelled']);
|
|
97
|
+
|
|
98
|
+
// Claim intervals of one request timeline: claimed .. the next claimed, completed, abandoned or cancelled (or now while open).
|
|
99
|
+
function claimSpans(events,nowMs) {
|
|
100
|
+
const spans=[];
|
|
101
|
+
events.forEach((claim,i)=>{
|
|
102
|
+
if(claim.type!=='claimed') return;
|
|
103
|
+
let end=events.length;
|
|
104
|
+
for(let j=i+1;j<events.length;j++) if(events[j].type==='claimed'||closes.has(events[j].type)) { end=j; break; }
|
|
105
|
+
const open=end===events.length;
|
|
106
|
+
spans.push({claim,open,closedBy:open?null:events[end].type,endMs:open?nowMs:events[end].ms,inside:events.slice(i,end).filter(e=>activity.has(e.type))});
|
|
107
|
+
});
|
|
108
|
+
return spans;
|
|
109
|
+
}
|
|
110
|
+
// Each activity event holds until the next one (or the claim end): blocked/waiting by type, working for a running check or a gap within activeGapMs, else idle.
|
|
111
|
+
const segmentsOf=({inside,endMs})=>inside.map((e,k)=>{
|
|
112
|
+
const next=k+1<inside.length?inside[k+1].ms:endMs;
|
|
113
|
+
return {kind:e.type==='blocked'||e.type==='waiting'?e.type:e.type==='check_started'||next-e.ms<=activeGapMs?'working':'idle',from:e.ms,to:next};
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// A queued item that has waited longer than this is a claiming gap, not a normal pickup delay.
|
|
117
|
+
export const pickupBudgetMs=180000;
|
|
118
|
+
const minLevelMs=10*60000;
|
|
119
|
+
const windows=[['24h','last_24h',86400000],['7d','last_7d',7*86400000]];
|
|
120
|
+
// Fixed windows ending now, independent of --since. A sweep over interval endpoints splits covered wall time into three shares
|
|
121
|
+
// that add up: queue empty, all lanes busy, and idle-while-queued (queued_count>0 and active_claims<laneCapacity).
|
|
122
|
+
// Time before the first lifecycle event (or before the retention roll-up) is unknown, not idle: it leaves the denominator.
|
|
123
|
+
function laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore) {
|
|
124
|
+
const db=store.db, startOfAll=nowMs-windows.at(-1)[2], startText=new Date(startOfAll).toISOString();
|
|
125
|
+
const rows=db.prepare(`SELECT request_id,type,at,epoch,source,actor FROM lifecycle_events WHERE request_id IN (SELECT request_id FROM lifecycle_events WHERE at>=? UNION SELECT request_id FROM assignments WHERE status IN ('queued','claimed')) ORDER BY request_id,at,id`).all(startText);
|
|
126
|
+
const queuedNow=new Set(db.prepare("SELECT request_id FROM assignments WHERE status='queued'").all().map(a=>a.request_id));
|
|
127
|
+
const timelines=new Map();
|
|
128
|
+
for(const row of rows) { row.ms=Date.parse(row.at); (timelines.get(row.request_id)??timelines.set(row.request_id,[]).get(row.request_id)).push(row); }
|
|
129
|
+
// delta = [ms, queued, claims, stale (queued longer than the pickup budget), completion marker, worker active (a claim event by the worker within activeGapMs), owner break]
|
|
130
|
+
const deltas=[], work=[], pickups=[];
|
|
131
|
+
const queuedSpan=(from,to)=>{ deltas.push([from,1,0,0,0],[to,-1,0,0,0]); if(to-from>pickupBudgetMs) deltas.push([from+pickupBudgetMs,0,0,1,0],[to,0,0,-1,0]); };
|
|
132
|
+
for(const [requestId,events] of timelines) {
|
|
133
|
+
let queuedFrom=null;
|
|
134
|
+
for(const e of events) {
|
|
135
|
+
if(e.actor?.startsWith('worker:')||e.actor?.startsWith('dot:')) deltas.push([e.ms,0,0,0,0,1,0],[e.ms+activeGapMs,0,0,0,0,-1,0]);
|
|
136
|
+
if(e.type==='queued'&&queuedFrom===null) queuedFrom=e.ms;
|
|
137
|
+
else if((e.type==='claimed'||e.type==='cancelled')&&queuedFrom!==null) { queuedSpan(queuedFrom,e.ms); if(e.type==='claimed'&&!(e.source==='backfill'&&e.epoch>1)) pickups.push([e.ms,e.ms-queuedFrom]); queuedFrom=null; }
|
|
138
|
+
}
|
|
139
|
+
if(queuedFrom!==null&&queuedNow.has(requestId)) queuedSpan(queuedFrom,nowMs);
|
|
140
|
+
for(const span of claimSpans(events,nowMs)) {
|
|
141
|
+
deltas.push([span.claim.ms,0,1,0,0],[span.endMs,0,-1,0,0]);
|
|
142
|
+
if(span.closedBy==='completed') deltas.push([span.endMs,0,0,0,1]);
|
|
143
|
+
for(const seg of segmentsOf(span)) if(seg.kind==='working') work.push([seg.from,Math.min(seg.to,nowMs)]);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
for(const b of db.prepare("SELECT since,until FROM worker_breaks WHERE source='owner'").all()) deltas.push([Date.parse(b.since),0,0,0,0,0,1],[b.until?Date.parse(b.until):nowMs,0,0,0,0,0,-1]);
|
|
147
|
+
deltas.sort((a,b)=>a[0]-b[0]||b[4]-a[4]); // a completion counts at the concurrency that still includes its own claim
|
|
148
|
+
const coveredFrom=Math.max(startOfAll,firstEventMs===null?nowMs:Date.parse(firstEventMs),rolledUpBefore?Date.parse(rolledUpBefore):0);
|
|
149
|
+
const overlap=(from,to,lo,hi)=>Math.max(0,Math.min(to,hi)-Math.max(from,lo));
|
|
150
|
+
const share=(ms,of,why)=>of>0?{value:Math.round(ms/of*1000)/1000,unit:'ratio',ms,of_ms:of}:unknown(why);
|
|
151
|
+
return {lanes:metric(laneCapacity,'count'),...Object.fromEntries(windows.map(([,key,span])=>{
|
|
152
|
+
const lo=nowMs-span, from=Math.max(lo,coveredFrom), covered=Math.max(0,nowMs-from);
|
|
153
|
+
const t={empty:0,busy:0,idle:0,waiting:0}, waitingBy={owner_break:0,worker_inactive:0,worker_active:0}, level=new Map();
|
|
154
|
+
let q=0,c=0,stale=0,active=0,brk=0,prev=-Infinity,maxClaims=0;
|
|
155
|
+
const bump=(k,field,n)=>{ const l=level.get(k)??level.set(k,{ms:0,done:0}).get(k); l[field]+=n; };
|
|
156
|
+
const add=(to)=>{ const ms=overlap(prev,to,from,nowMs); if(!ms) return; const state=q===0?'empty':c>=laneCapacity?'busy':stale>0?'waiting':'idle'; t[state]+=ms; if(state==='waiting') waitingBy[brk>0?'owner_break':active>0?'worker_active':'worker_inactive']+=ms; maxClaims=Math.max(maxClaims,c); bump(c,'ms',ms); };
|
|
157
|
+
for(const [at,dq,dc,ds,done,da=0,dbrk=0] of deltas) { add(at); prev=at; if(done&&at>=from&&at<=nowMs) bump(c,'done',1); q+=dq; c+=dc; stale+=ds; active+=da; brk+=dbrk; }
|
|
158
|
+
add(nowMs);
|
|
159
|
+
const waits=pickups.filter(([at])=>at>=lo&&at<=nowMs).map(([,w])=>w);
|
|
160
|
+
const byConcurrency=[...level].filter(([k,l])=>k>0&&l.ms>=minLevelMs).sort((a,b)=>a[0]-b[0]).map(([k,l])=>{ const perHour=l.done/(l.ms/3600000); return {claims_held:k,time_ms:l.ms,completions:l.done,completions_per_hour:Math.round(perHour*100)/100,per_claim_per_hour:Math.round(perHour/k*100)/100}; });
|
|
161
|
+
const numerator=work.reduce((sum,[a,b])=>sum+overlap(a,b,from,nowMs),0), denominator=laneCapacity*covered, why='the window has no covered time (no lifecycle events yet)';
|
|
162
|
+
return [key,{window:{since:new Date(lo).toISOString(),wall_ms:span,covered_ms:covered,covered_fraction:Math.round(covered/span*1000)/1000},
|
|
163
|
+
utilization:denominator>0?{value:Math.round(numerator/denominator*1000)/1000,unit:'ratio',numerator_ms:numerator,denominator_ms:denominator,lanes:laneCapacity}:unknown(why),
|
|
164
|
+
idle_while_queued:share(t.idle+t.waiting,covered,why),idle_while_fresh_queued:share(t.idle,covered,why),idle_while_waiting_queued:share(t.waiting,covered,why),idle_while_waiting_by_cause:Object.fromEntries(Object.entries(waitingBy).map(([k,ms])=>[k,share(ms,covered,why)])),pickup_budget_ms:pickupBudgetMs,
|
|
165
|
+
pickup_wait:distribution(waits,'no assignment was claimed from the queue in the window'),max_concurrent_claims:covered>0?metric(maxClaims,'count'):unknown(why),throughput_by_concurrency:byConcurrency,queue_empty:share(t.empty,covered,why),all_lanes_busy:share(t.busy,covered,why)}];
|
|
166
|
+
}))};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function lifecycleMetrics(store,{since=null,laneCapacity=store.limits.laneCapacity??6}={}) {
|
|
170
|
+
const db=store.db, nowMs=store.nowMs();
|
|
171
|
+
if(since!==null&&(!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(since)||!Number.isFinite(Date.parse(since)))) throw new Error('since must be an RFC 3339 time with offset');
|
|
172
|
+
const sinceMs=since===null?nowMs-defaultWindowMs:Date.parse(since), sinceText=new Date(sinceMs).toISOString();
|
|
173
|
+
if(sinceMs>=nowMs) throw new Error('since must be in the past');
|
|
174
|
+
const rolledUpBefore=db.prepare('SELECT rolled_up_before FROM lifecycle_retention WHERE id=1').get().rolled_up_before;
|
|
175
|
+
const rolledUp=!!rolledUpBefore&&sinceText<rolledUpBefore;
|
|
176
|
+
const rows=db.prepare(`SELECT e.*,${kindSql} kind FROM lifecycle_events e LEFT JOIN assignments a ON a.request_id=e.request_id
|
|
177
|
+
WHERE e.request_id IN (SELECT request_id FROM lifecycle_events WHERE at>=?) ORDER BY e.request_id,e.at,e.id`).all(sinceText);
|
|
178
|
+
const timelines=new Map();
|
|
179
|
+
for(const row of rows) { row.ms=Date.parse(row.at); (timelines.get(row.request_id)??timelines.set(row.request_id,[]).get(row.request_id)).push(row); }
|
|
180
|
+
const statuses=new Map(db.prepare('SELECT request_id,status FROM assignments').all().map(a=>[a.request_id,a.status]));
|
|
181
|
+
const inWindow=e=>e.ms>=sinceMs;
|
|
182
|
+
const queueLatency=[], firstActivityMs=[], totals={working:0,blocked:0,waiting:0,idle:0,claimed:0};
|
|
183
|
+
let stillQueued=0, earlierEpochUnknown=0, noActivity=0, awaitingActivity=0, openClaims=0;
|
|
184
|
+
const clip=(from,to)=>Math.max(0,Math.min(to,nowMs)-Math.max(from,sinceMs));
|
|
185
|
+
for(const [requestId,events] of timelines) {
|
|
186
|
+
events.forEach((e,i)=>{
|
|
187
|
+
if(e.type!=='queued'||!inWindow(e)) return;
|
|
188
|
+
const claimed=events.slice(i+1).find(x=>x.type==='claimed'||x.type==='cancelled'||x.type==='queued');
|
|
189
|
+
if(claimed?.type!=='claimed') { if(!claimed&&statuses.get(requestId)==='queued') stillQueued++; return; }
|
|
190
|
+
if(claimed.source==='backfill'&&claimed.epoch>1) { earlierEpochUnknown++; return; }
|
|
191
|
+
queueLatency.push(claimed.ms-e.ms);
|
|
192
|
+
});
|
|
193
|
+
for(const span of claimSpans(events,nowMs)) {
|
|
194
|
+
if(span.open) openClaims++;
|
|
195
|
+
if(inWindow(span.claim)) {
|
|
196
|
+
const first=span.inside.find(e=>firstActivity.has(e.type));
|
|
197
|
+
if(first) firstActivityMs.push(first.ms-span.claim.ms); else if(span.open) awaitingActivity++; else noActivity++;
|
|
198
|
+
}
|
|
199
|
+
totals.claimed+=clip(span.claim.ms,span.endMs);
|
|
200
|
+
for(const seg of segmentsOf(span)) totals[seg.kind]+=clip(seg.from,seg.to);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const firstEventMs=db.prepare('SELECT min(at) at FROM lifecycle_events').get().at??null;
|
|
204
|
+
const wallStart=Math.max(sinceMs,firstEventMs?Date.parse(firstEventMs):nowMs), wallMs=Math.max(0,nowMs-wallStart);
|
|
205
|
+
const rolled=why=>({n:unknown(why),p50:unknown(why),p90:unknown(why)});
|
|
206
|
+
const duration=value=>rolledUp?unknown('rolled up'):metric(value,'ms');
|
|
207
|
+
const windowed=rows.filter(inWindow);
|
|
208
|
+
const count=type=>windowed.filter(e=>e.type===type).length;
|
|
209
|
+
const backfilled=windowed.some(e=>e.source==='backfill');
|
|
210
|
+
// Throughput: completed (terminal worker report) events per UTC day and kind, plus daily roll-ups when the window reaches them.
|
|
211
|
+
const perDay=new Map();
|
|
212
|
+
for(const e of windowed.filter(e=>e.type==='completed')) { const key=`${e.at.slice(0,10)}\0${e.kind}`; perDay.set(key,(perDay.get(key)??0)+1); }
|
|
213
|
+
if(rolledUp) for(const r of db.prepare("SELECT day,kind,count FROM lifecycle_daily WHERE type='completed' AND day>=?").all(sinceText.slice(0,10))) { const key=`${r.day}\0${canonicalKindLabel(r.kind)}`; perDay.set(key,(perDay.get(key)??0)+r.count); }
|
|
214
|
+
const byDay=[...perDay].map(([key,n])=>{ const [day,kind]=key.split('\0'); return {day,kind,completed:n}; }).sort((a,b)=>a.day.localeCompare(b.day)||a.kind.localeCompare(b.kind));
|
|
215
|
+
const completedTotal=byDay.reduce((sum,x)=>sum+x.completed,0), days=Math.max(1,Math.ceil(wallMs/86400000));
|
|
216
|
+
const byKind={}; for(const x of byDay) byKind[x.kind]=(byKind[x.kind]??0)+x.completed;
|
|
217
|
+
// Rework: an earlier submission of the same objective_key had another revision. Duplicate: an earlier one had the same
|
|
218
|
+
// objective_key and revision under another request_id. Columns first, then payload fields (older hand-written payloads).
|
|
219
|
+
// A row cancelled because its preparation expired was never worked: it is neither repeated nor makes its re-preparation one.
|
|
220
|
+
const all=db.prepare("SELECT request_id,created_at,COALESCE(objective_key,json_extract(payload,'$.objective_key')) k,COALESCE(revision,json_extract(payload,'$.revision')) r,COALESCE(source,'unknown') src,cancelled_reason FROM assignments ORDER BY created_at,request_id").all().map(x=>({...x,k:canonicalObjectiveKey(x.k),src:fromStoredSource(x.src)}));
|
|
221
|
+
const seen=new Map(), repeat={rework:{value:0,by_source:{}},duplicates:{value:0,by_source:{}}}, coverage={keyed:0,total:0,by_source:{}};
|
|
222
|
+
for(const x of all) {
|
|
223
|
+
const inside=x.created_at>=sinceText, keyed=x.k!=null&&x.r!=null;
|
|
224
|
+
if(inside) { coverage.total++; const c=coverage.by_source[x.src]??={keyed:0,total:0}; c.total++; if(keyed) { coverage.keyed++; c.keyed++; } }
|
|
225
|
+
if(!keyed||x.cancelled_reason==='expired') continue;
|
|
226
|
+
const revisions=seen.get(x.k)??seen.set(x.k,new Set()).get(x.k);
|
|
227
|
+
if(inside) for(const [name,hit] of [['rework',revisions.size>(revisions.has(x.r)?1:0)],['duplicates',revisions.has(x.r)]]) if(hit) { repeat[name].value++; repeat[name].by_source[x.src]=(repeat[name].by_source[x.src]??0)+1; }
|
|
228
|
+
revisions.add(x.r);
|
|
229
|
+
}
|
|
230
|
+
const noKey=coverage.total?`none of the ${coverage.total} assignments submitted in the window has an objective_key and revision (submitters send them as meta; run dalan backfill-objectives for older rows)`:'no assignment was submitted in the window';
|
|
231
|
+
const repeated=name=>coverage.keyed?{value:repeat[name].value,unit:'count',n:coverage.keyed,by_source:repeat[name].by_source}:unknown(noKey);
|
|
232
|
+
// Owner acceptance of requests whose terminal report landed in the window. The latest verdict wins.
|
|
233
|
+
const verdicts={accepted:0,rejected:0,consumed_only:0,unknown:0};
|
|
234
|
+
for(const [requestId,events] of timelines) {
|
|
235
|
+
if(!events.some(e=>e.type==='completed'&&inWindow(e))) continue;
|
|
236
|
+
const verdict=events.filter(e=>e.type==='accepted'||e.type==='consumed'&&/^rejected/.test(e.reason??'')).at(-1);
|
|
237
|
+
verdicts[verdict?verdict.type==='accepted'?'accepted':'rejected':events.some(e=>e.type==='consumed')?'consumed_only':'unknown']++;
|
|
238
|
+
}
|
|
239
|
+
const finished=Object.values(verdicts).reduce((a,b)=>a+b,0);
|
|
240
|
+
const passed=count('check_passed'), failed=count('check_failed'), skipped=count('check_skipped');
|
|
241
|
+
const notes=[`lane_utilization = working lane time / (worker_lane_capacity x covered wall time) over fixed windows ending now (not --since); idle_while_queued is the share of covered time with work queued and fewer active claims than lanes, split into idle_while_fresh_queued (every queued item has waited at most pickup_budget_ms) and idle_while_waiting_queued (some queued item has waited longer, which indicates a wake-up or claiming gap, not a supply gap); idle_while_waiting_by_cause splits idle_while_waiting_queued into owner_break (an owner-confirmed usage break was active), worker_inactive (no claim event by the worker, such as a claim, progress or finish, in the last ${activeGapMs/60000} min: the worker is silent or away) and worker_active (the worker was working claims but left a free lane unused); queue_empty + all_lanes_busy + idle_while_queued = 1; time before the first lifecycle event is unknown and excluded`,`working time = sum of gaps of at most ${activeGapMs/60000} min between consecutive claim activity events, plus running checks; longer gaps are idle; gaps after blocked/waiting count as blocked/waiting`];
|
|
242
|
+
if(backfilled) notes.push('window includes backfilled history: claims show the current epoch only; consumed, accepted, integrated, abandoned and check_skipped before lifecycle events are unknown');
|
|
243
|
+
if(rolledUp) notes.push(`events before ${rolledUpBefore} are rolled up to daily counts: durations are unknown`);
|
|
244
|
+
// Resume wake, per worker: resumed = 'claimed' events with reason 'resume' (an idle own claim rotated to a new epoch);
|
|
245
|
+
// lease_expiry_retries = 'abandoned' events whose reason starts lease_expired (sweep or takeover). Time to finish = first
|
|
246
|
+
// 'queued' event to 'completed' (submit to finish) for requests that finished in the window; a request that was resumed
|
|
247
|
+
// counts as resumed, one that only went through lease expiry as lease_expiry. duplicate_epoch_claims must be 0: it counts
|
|
248
|
+
// (request, epoch) pairs that more than one claim_id acted under.
|
|
249
|
+
const resumeWake={};
|
|
250
|
+
const resumeRow=worker=>resumeWake[worker]??={resumed:0,lease_expiry_retries:0,_resumed:[],_expiry:[]};
|
|
251
|
+
for(const events of timelines.values()) {
|
|
252
|
+
const done=events.find(e=>e.type==='completed'&&inWindow(e)), queued=events.find(e=>e.type==='queued');
|
|
253
|
+
const resumes=events.filter(e=>e.type==='claimed'&&e.reason==='resume'), expiries=events.filter(e=>e.type==='abandoned'&&/^lease_expired\b/.test(e.reason??''));
|
|
254
|
+
for(const e of resumes) if(inWindow(e)) resumeRow(e.worker).resumed++;
|
|
255
|
+
for(const e of expiries) if(inWindow(e)) resumeRow(e.worker).lease_expiry_retries++;
|
|
256
|
+
if(done&&queued&&(resumes.length||expiries.length)) resumeRow(done.worker)[resumes.length?'_resumed':'_expiry'].push(done.ms-queued.ms);
|
|
257
|
+
}
|
|
258
|
+
const resumeByWorker=Object.fromEntries(Object.entries(resumeWake).map(([worker,r])=>[worker,{resumed:metric(r.resumed,'count'),lease_expiry_retries:metric(r.lease_expiry_retries,'count'),
|
|
259
|
+
time_to_finish_resumed:distribution(r._resumed,'no resumed request finished in the window'),time_to_finish_lease_expiry:distribution(r._expiry,'no request that went through lease expiry finished in the window')}]));
|
|
260
|
+
const duplicateEpochs=db.prepare("SELECT count(*) n FROM (SELECT request_id,epoch FROM lifecycle_events WHERE claim_id IS NOT NULL AND epoch IS NOT NULL AND source='live' AND request_id IN (SELECT request_id FROM lifecycle_events WHERE at>=?) GROUP BY request_id,epoch HAVING count(DISTINCT claim_id)>1)").get(sinceText).n;
|
|
261
|
+
return {
|
|
262
|
+
resume_wake:{by_worker:resumeByWorker,duplicate_epoch_claims:metric(duplicateEpochs,'count')},
|
|
263
|
+
window:{since:sinceText,until:new Date(nowMs).toISOString(),wall_ms:wallMs,rolled_up:rolledUp},
|
|
264
|
+
queue_latency:rolledUp?rolled('rolled up'):{...distribution(queueLatency,'no queued event in the window was claimed'),still_queued:metric(stillQueued,'count'),earlier_epoch_unknown:metric(earlierEpochUnknown,'count')},
|
|
265
|
+
claim_to_first_activity:rolledUp?rolled('rolled up'):{...distribution(firstActivityMs,'no claim in the window has recorded activity'),closed_without_activity:metric(noActivity,'count'),awaiting_activity:metric(awaitingActivity,'count')},
|
|
266
|
+
time:{claimed:duration(totals.claimed),working:duration(totals.working),blocked:duration(totals.blocked),waiting:duration(totals.waiting),idle:duration(totals.idle),open_claims:metric(openClaims,'count')},
|
|
267
|
+
utilization:{working_over_claimed:rolledUp?unknown('rolled up'):ratio(totals.working,totals.claimed,'ratio','no claimed time in the window')},
|
|
268
|
+
lane_utilization:laneUtilization(store,laneCapacity,nowMs,firstEventMs,rolledUpBefore),
|
|
269
|
+
throughput:{completed:metric(completedTotal,'count'),per_day:metric(Math.round(completedTotal/days*100)/100,'count/day'),by_kind:Object.fromEntries(Object.entries(byKind).map(([k,n])=>[k,metric(n,'count')])),by_day:byDay},
|
|
270
|
+
rework:repeated('rework'),
|
|
271
|
+
duplicates:repeated('duplicates'),
|
|
272
|
+
objective_coverage:coverage.total?{value:Math.round(coverage.keyed/coverage.total*1000)/1000,unit:'ratio',keyed:coverage.keyed,total:coverage.total,by_source:coverage.by_source}:unknown('no assignment was submitted in the window'),
|
|
273
|
+
// Output filed after cancel. Not a completion: throughput counts results only; late reports before migration 42 stay counted as completed.
|
|
274
|
+
late_evidence:metric(db.prepare('SELECT count(*) n FROM late_evidence WHERE created_at>=?').get(sinceText).n,'count'),
|
|
275
|
+
orphaned_claims:{current:metric(store.claims().filter(c=>c.expired).length,'count'),lease_expired_takeovers:metric(windowed.filter(e=>e.type==='abandoned'&&/^lease_expired\b/.test(e.reason??'')).length,'count'),abandoned:metric(count('abandoned'),'count')},
|
|
276
|
+
checks:{passed:metric(passed,'count'),failed:metric(failed,'count'),skipped:metric(skipped,'count'),pass_rate:ratio(passed,passed+failed+skipped,'ratio','no check passed, failed or skipped in the window'),started:metric(count('check_started'),'count')},
|
|
277
|
+
acceptance:{finished:metric(finished,'count'),accepted:metric(verdicts.accepted,'count'),rejected:metric(verdicts.rejected,'count'),consumed_only:metric(verdicts.consumed_only,'count'),unknown:metric(verdicts.unknown,'count'),
|
|
278
|
+
accept_rate:ratio(verdicts.accepted,verdicts.accepted+verdicts.rejected,'ratio','no owner accept or reject in the window'),integrated:metric(count('integrated'),'count')},
|
|
279
|
+
notes,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const show=(m,format=x=>x)=>m?.value==null?'unknown':format(m.value);
|
|
284
|
+
const minutes=ms=>ms<60000?`${Math.round(ms/1000)}s`:`${Math.round(ms/6000)/10}m`, percent=x=>`${Math.round(x*1000)/10}%`;
|
|
285
|
+
const laneText=l=>['24h','7d'].map(w=>{ const x=l[`last_${w}`], cover=x.window.covered_fraction<1?`,covered ${percent(x.window.covered_fraction)}`:''; return `util${w}=${show(x.utilization,percent)}(of ${l.lanes.value} lanes${cover}) idle_while_queued${w}=${show(x.idle_while_queued,percent)} iwq_waiting${w}=${show(x.idle_while_waiting_queued,percent)}(break:${show(x.idle_while_waiting_by_cause.owner_break,percent)},worker_inactive:${show(x.idle_while_waiting_by_cause.worker_inactive,percent)},worker_active:${show(x.idle_while_waiting_by_cause.worker_active,percent)}) idle_no_queue${w}=${show(x.queue_empty,percent)}`; }).join(' ');
|
|
286
|
+
export function explainMetrics(m) {
|
|
287
|
+
return `metrics(since=${m.window.since}) queue_latency=p50:${show(m.queue_latency.p50,minutes)},p90:${show(m.queue_latency.p90,minutes)},n=${show(m.queue_latency.n)} claim_to_activity=p50:${show(m.claim_to_first_activity.p50,minutes)} `+
|
|
288
|
+
`working/claimed=${show(m.utilization.working_over_claimed,percent)} ${laneText(m.lane_utilization)} completed=${show(m.throughput.completed)}(${show(m.throughput.per_day)}/day) `+
|
|
289
|
+
`checks=passed:${show(m.checks.passed)},failed:${show(m.checks.failed)},skipped:${show(m.checks.skipped)} acceptance=accepted:${show(m.acceptance.accepted)},rejected:${show(m.acceptance.rejected)},consumed_only:${show(m.acceptance.consumed_only)},unknown:${show(m.acceptance.unknown)} `+
|
|
290
|
+
`resumed=${Object.entries(m.resume_wake?.by_worker??{}).map(([w,r])=>`${w}:${r.resumed.value}/expiry:${r.lease_expiry_retries.value}/ttf_resumed_p50:${show(r.time_to_finish_resumed.p50,minutes)}/ttf_expiry_p50:${show(r.time_to_finish_lease_expiry.p50,minutes)}`).join(',')||'none'} duplicate_epochs=${show(m.resume_wake?.duplicate_epoch_claims)} orphaned=${show(m.orphaned_claims.current)} rework=${show(m.rework)} duplicates=${show(m.duplicates)} objective_coverage=${m.objective_coverage?.total?`${m.objective_coverage.keyed}/${m.objective_coverage.total}`:'unknown'}`;
|
|
291
|
+
}
|
package/src/limits.mjs
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { validT3ThreadId } from './delivery.mjs';
|
|
6
|
+
|
|
7
|
+
// Protected T3 destinations: operator admission on submit, quiet retention at delivery.
|
|
8
|
+
export function loadMainThreadIds(file=defaultPath(os.homedir(),'.config/dot-bridge/limits.json')) {
|
|
9
|
+
if(!fs.existsSync(file)) return [];
|
|
10
|
+
if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('limits policy must be mode 0600');
|
|
11
|
+
const ids=JSON.parse(fs.readFileSync(file,'utf8')).main_thread_ids??[];
|
|
12
|
+
if(!Array.isArray(ids)||ids.some(x=>!validT3ThreadId(x))) throw new Error('invalid main_thread_ids');
|
|
13
|
+
return ids;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function loadBackgroundMaxInFlight(file=defaultPath(os.homedir(),'.config/dot-bridge/limits.json')) {
|
|
17
|
+
if(!fs.existsSync(file)) return 4;
|
|
18
|
+
if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('limits policy must be mode 0600');
|
|
19
|
+
const limit=JSON.parse(fs.readFileSync(file,'utf8')).background_max_in_flight??4;
|
|
20
|
+
if(!Number.isInteger(limit)||limit<1||limit>10) throw new Error('invalid background_max_in_flight');
|
|
21
|
+
return limit;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Backstop for agents that sweep T3 history: off makes the read tools answer with a short stub.
|
|
25
|
+
export function t3ReadToolsOff(file=defaultPath(os.homedir(),'.config/dot-bridge/limits.json')) {
|
|
26
|
+
if(!fs.existsSync(file)) return false;
|
|
27
|
+
if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('limits policy must be mode 0600');
|
|
28
|
+
const value=JSON.parse(fs.readFileSync(file,'utf8')).t3_read_tools??'on';
|
|
29
|
+
if(value!=='on'&&value!=='off') throw new Error('invalid t3_read_tools');
|
|
30
|
+
return value==='off';
|
|
31
|
+
}
|
package/src/loopback.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Check authority before routing, discovery, OAuth or MCP. Forwarded headers cannot
|
|
2
|
+
// substitute a trusted authority on a listener intended for direct local clients.
|
|
3
|
+
export function loopbackRequestAllowed(req, origin) {
|
|
4
|
+
const count = name => req.rawHeaders.filter((_, i) => i % 2 === 0 && req.rawHeaders[i].toLowerCase() === name).length;
|
|
5
|
+
if (count('host') !== 1 || req.headers.host !== new URL(origin).host) return false;
|
|
6
|
+
if (Object.keys(req.headers).some(name => name === 'forwarded' || name.startsWith('x-forwarded-'))) return false;
|
|
7
|
+
if (count('origin') > 1) return false;
|
|
8
|
+
return req.headers.origin === undefined || req.headers.origin === origin;
|
|
9
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
import { redactNote } from './alerts.mjs';
|
|
4
|
+
|
|
5
|
+
const responses = new WeakMap();
|
|
6
|
+
const methods = new Set(['server/discover', 'initialize', 'ping', 'tools/list', 'tools/call', 'events/list', 'events/subscribe', 'events/unsubscribe', 'notifications/initialized', 'notifications/cancelled']);
|
|
7
|
+
|
|
8
|
+
// Log only declared protocol names and numeric outcomes. RPC IDs, arguments,
|
|
9
|
+
// headers, URLs and exception messages can all contain credentials. The one
|
|
10
|
+
// exception is tool_error_message: a failed tool call's bridge-generated error
|
|
11
|
+
// text, redacted (redactNote) and cut to 300 characters, so an incident can be
|
|
12
|
+
// read from the log without inference.
|
|
13
|
+
export function beginMcpOutcome(req, res, log, toolNames, authRequired) {
|
|
14
|
+
const started = performance.now();
|
|
15
|
+
const state = {
|
|
16
|
+
call_id: randomUUID(), started_at: new Date().toISOString(),
|
|
17
|
+
http_method: ['POST', 'GET', 'DELETE', 'PUT', 'PATCH', 'HEAD', 'OPTIONS'].includes(req.method) ? req.method : 'other',
|
|
18
|
+
rpc_method: null, tool: null, request_id: null, phase: authRequired ? 'auth' : 'body', auth_outcome: authRequired ? 'pending' : 'disabled',
|
|
19
|
+
auth_reason: null, auth_duration_ms: null, jwks_outcome: 'not_attempted',
|
|
20
|
+
jwks_duration_ms: null, jwks_http_status: null,
|
|
21
|
+
rpc_error_code: null, tool_error: null, tool_error_message: null, response_bytes: 0,
|
|
22
|
+
response_kind: 'empty', error_type: null,
|
|
23
|
+
};
|
|
24
|
+
responses.set(res, state);
|
|
25
|
+
log({ kind: 'mcp_received', call_id: state.call_id, http_method: state.http_method });
|
|
26
|
+
let recorded = false;
|
|
27
|
+
const complete = completion => {
|
|
28
|
+
if (recorded) return;
|
|
29
|
+
recorded = true;
|
|
30
|
+
if (req.aborted && state.error_type === null) state.error_type = 'request_aborted';
|
|
31
|
+
log({ kind: 'mcp_outcome', jwks_outcome: 'not_attempted', jwks_duration_ms: null, jwks_http_status: null,
|
|
32
|
+
...state, http_status: res.headersSent ? res.statusCode : null,
|
|
33
|
+
completion, duration_ms: Math.round((performance.now() - started) * 1000) / 1000 });
|
|
34
|
+
};
|
|
35
|
+
res.once('finish', () => complete('finished'));
|
|
36
|
+
res.once('close', () => complete('closed'));
|
|
37
|
+
return {
|
|
38
|
+
state,
|
|
39
|
+
identify(rpc) {
|
|
40
|
+
state.rpc_method = methods.has(rpc.method) ? rpc.method : 'unknown';
|
|
41
|
+
if (rpc.method === 'tools/call') {
|
|
42
|
+
state.tool = toolNames.has(rpc.params?.name) ? rpc.params.name : 'unknown';
|
|
43
|
+
// Only an ID-shaped request_id is logged (the same shape the bridge accepts); never the rest of the arguments.
|
|
44
|
+
const requestId = rpc.params?.arguments?.request_id;
|
|
45
|
+
if (state.tool !== 'unknown' && typeof requestId === 'string' && /^[-\w]{8,128}$/.test(requestId)) state.request_id = requestId;
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function recordMcpResponse(res, value, bytes) {
|
|
52
|
+
const state = responses.get(res);
|
|
53
|
+
if (!state) return;
|
|
54
|
+
state.response_bytes = bytes;
|
|
55
|
+
state.phase = 'responding';
|
|
56
|
+
state.rpc_error_code = Number.isInteger(value?.error?.code) ? value.error.code : null;
|
|
57
|
+
state.tool_error = typeof value?.result?.isError === 'boolean' ? value.result.isError : null;
|
|
58
|
+
const text = value?.result?.content?.[0]?.text;
|
|
59
|
+
state.tool_error_message = state.tool_error === true && typeof text === 'string' ? redactNote(text).slice(0, 300) : null;
|
|
60
|
+
state.response_kind = value?.jsonrpc === '2.0' ? (value.error ? 'rpc_error' : 'rpc_result') : 'other_json';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The shape of a path that matched no route. Only names of public routes survive; every other segment, including the
|
|
64
|
+
// secret MCP path and any token a client put in a wrong URL, becomes its length. Enough to tell a client that probes a
|
|
65
|
+
// well-known URL from one that holds a stale connector URL.
|
|
66
|
+
const PUBLIC_SEGMENTS = new Set(['mcp', '.well-known', 'oauth-protected-resource', 'oauth-authorization-server', 'openid-configuration', 'authorize', 'token', 'register', 'revoke', 'callback', 'favicon.ico', 'robots.txt']);
|
|
67
|
+
export function pathShape(url) {
|
|
68
|
+
const segments = String(url ?? '').split(/[?#]/)[0].split('/').slice(1, 7);
|
|
69
|
+
return '/' + segments.map(segment => PUBLIC_SEGMENTS.has(segment) ? segment : `<${Math.min(segment.length, 999)} chars>`).join('/');
|
|
70
|
+
}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// `dalan mcp`: a local MCP server on stdio. It lets an agent on the bridge computer submit jobs, wait for them and read
|
|
2
|
+
// their results as tool calls. It is not the worker-facing endpoint in server.mjs. Each tool runs the matching `dalan`
|
|
3
|
+
// CLI command with --json, so owner receipts, admin-socket access, assignment checks and verdicts stay in one place.
|
|
4
|
+
// Trust is the CLI's: whoever can run `dalan` here (the admin socket) can use these tools.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import readline from 'node:readline';
|
|
9
|
+
import { redactOutput, redactSinkText } from './redaction.mjs';
|
|
10
|
+
import { safeDiagnostic } from './diagnostic.mjs';
|
|
11
|
+
|
|
12
|
+
export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
13
|
+
export const RESULT_CAP_BYTES = 32 * 1024;
|
|
14
|
+
const WAIT_DEFAULT = 120, WAIT_MAX = 300;
|
|
15
|
+
const CLI = path.join(import.meta.dirname, '../bin/dalan.mjs');
|
|
16
|
+
const requestId = { type: 'string', pattern: '^[-\\w]{8,128}$', description: 'The request_id of a submitted job.' };
|
|
17
|
+
|
|
18
|
+
export const TOOLS = [
|
|
19
|
+
{ name: 'dalan_submit', title: 'Submit a job',
|
|
20
|
+
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
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['assignment'], properties: {
|
|
22
|
+
assignment: { type: 'object', description: 'The assignment: request_id (8-128 letters, digits, _ or -), brief, inputs (array; [] for none), expected_output, and the other fields `dalan submit` accepts.',
|
|
23
|
+
required: ['request_id'], properties: { request_id: requestId, brief: { type: 'string' }, inputs: { type: 'array' } } },
|
|
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.' },
|
|
26
|
+
dry_run: { type: 'boolean', description: 'Check the assignment and store nothing.' },
|
|
27
|
+
queue_anyway: { type: 'boolean', description: 'Queue even when the bridge would defer or warn.' },
|
|
28
|
+
refuse_defer: { type: 'boolean', description: 'Fail instead of deferring.' } } },
|
|
29
|
+
annotations: { title: 'Submit a job', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false } },
|
|
30
|
+
{ 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.`,
|
|
32
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: {
|
|
33
|
+
request_id: requestId,
|
|
34
|
+
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}.` } } },
|
|
35
|
+
annotations: { title: 'Wait for a job', readOnlyHint: true, openWorldHint: false } },
|
|
36
|
+
{ name: 'dalan_result', title: 'Read a job result',
|
|
37
|
+
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
|
+
inputSchema: { type: 'object', additionalProperties: false, required: ['request_id'], properties: { request_id: requestId } },
|
|
39
|
+
annotations: { title: 'Read a job result', readOnlyHint: true, openWorldHint: false } },
|
|
40
|
+
{ name: 'dalan_status', title: 'Bridge status',
|
|
41
|
+
description: 'Show the bridge status (`dalan status --json`): queue, workers and health.',
|
|
42
|
+
inputSchema: { type: 'object', additionalProperties: false, properties: {} },
|
|
43
|
+
annotations: { title: 'Bridge status', readOnlyHint: true, openWorldHint: false } }
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
// A SafeError carries a message written by Dalan; any other thrown value is a crash whose text never reaches the client.
|
|
47
|
+
class SafeError extends Error {}
|
|
48
|
+
const fail = (message, detail) => Object.assign(new SafeError(message), { detail });
|
|
49
|
+
// Untrusted names appear in a message only when they are plain identifiers.
|
|
50
|
+
const shown = name => /^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name) ? `"${name}"` : '(name withheld)';
|
|
51
|
+
|
|
52
|
+
function validate(tool, args) {
|
|
53
|
+
if (args === undefined) args = {};
|
|
54
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) throw fail('arguments must be an object');
|
|
55
|
+
const { properties = {}, required = [] } = tool.inputSchema;
|
|
56
|
+
for (const key of Object.keys(args)) if (!(key in properties)) throw fail(`unknown argument ${shown(key)} for ${tool.name}`);
|
|
57
|
+
for (const key of required) if (args[key] === undefined) throw fail(`missing required argument "${key}"`);
|
|
58
|
+
for (const [key, value] of Object.entries(args)) {
|
|
59
|
+
const spec = properties[key];
|
|
60
|
+
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}`}`);
|
|
62
|
+
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 -)`);
|
|
64
|
+
if (spec.type === 'string' && value.startsWith('--')) throw fail(`argument "${key}" must not start with --`);
|
|
65
|
+
}
|
|
66
|
+
return args;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Run `dalan <args> --json`. stdout and stderr are collected, never forwarded: stdout of this process is the protocol.
|
|
70
|
+
function runCli(args, { input, timeoutMs = 60_000, env = process.env } = {}) {
|
|
71
|
+
return new Promise(resolve => {
|
|
72
|
+
const child = spawn(process.execPath, [CLI, ...args, '--json'], { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
73
|
+
let stdout = '', stderr = '', done = false;
|
|
74
|
+
const finish = value => { if (!done) { done = true; clearTimeout(timer); resolve(value); } };
|
|
75
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); finish({ code: null, stdout, stderr: `${stderr}dalan did not answer within ${Math.round(timeoutMs / 1000)}s` }); }, timeoutMs);
|
|
76
|
+
child.stdout.on('data', chunk => { stdout += chunk; });
|
|
77
|
+
child.stderr.on('data', chunk => { stderr += chunk; });
|
|
78
|
+
child.on('error', error => finish({ code: null, stdout, stderr: error.message }));
|
|
79
|
+
child.on('close', code => finish({ code, stdout, stderr }));
|
|
80
|
+
child.stdin.on('error', () => {});
|
|
81
|
+
child.stdin.end(input ?? '');
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const parseJson = text => { try { return JSON.parse(text); } catch { return undefined; } };
|
|
85
|
+
// stderr may hold warnings before the final error JSON line.
|
|
86
|
+
const lastJsonLine = text => text.trim().split('\n').reverse().map(parseJson).find(v => v && typeof v === 'object');
|
|
87
|
+
|
|
88
|
+
export function cliError(run, label) {
|
|
89
|
+
const body = lastJsonLine(run.stderr) ?? lastJsonLine(run.stdout);
|
|
90
|
+
if (body) return { isError: true, value: body };
|
|
91
|
+
return { isError: true, message: `${label} failed${run.code === null ? '' : ` (exit ${run.code})`}: ${safeDiagnostic((run.stderr || run.stdout).trim(), 4000) || 'no output'}` };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function capped(value) {
|
|
95
|
+
const text = JSON.stringify(redactOutput(value));
|
|
96
|
+
if (Buffer.byteLength(text) <= RESULT_CAP_BYTES) return { text, structured: JSON.parse(text) };
|
|
97
|
+
const cut = Buffer.from(text).subarray(0, RESULT_CAP_BYTES).toString('utf8').replace(/�$/, '');
|
|
98
|
+
// The note is part of the frame the client sees, so it is redacted too.
|
|
99
|
+
return { text: `${cut}\n${redactSinkText(`[truncated: output was ${Buffer.byteLength(text)} bytes, cap is ${RESULT_CAP_BYTES}. Read the rest with \`dalan get ${value.request_id ?? 'REQUEST_ID'} --json\` or fetch artifacts with \`dalan artifact\`.]`)}` };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// The one exit for tool results: every message and value is redacted, success or error.
|
|
103
|
+
const asResult = ({ isError, value, message }) => {
|
|
104
|
+
if (message !== undefined) return { content: [{ type: 'text', text: redactSinkText(message) }], isError: true };
|
|
105
|
+
const { text, structured } = capped(value);
|
|
106
|
+
return { content: [{ type: 'text', text }], ...(structured && typeof structured === 'object' ? { structuredContent: structured } : {}), ...(isError ? { isError: true } : {}) };
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const handlers = {
|
|
110
|
+
async dalan_submit(args) {
|
|
111
|
+
const flags = [];
|
|
112
|
+
if (args.worker) flags.push('--worker', args.worker);
|
|
113
|
+
if (args.execution) flags.push('--execution', args.execution);
|
|
114
|
+
for (const [key, flag] of [['dry_run', '--dry-run'], ['queue_anyway', '--queue-anyway'], ['refuse_defer', '--refuse-defer']]) if (args[key]) flags.push(flag);
|
|
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
|
+
},
|
|
121
|
+
async dalan_wait(args) {
|
|
122
|
+
const seconds = Math.min(args.timeout_seconds ?? WAIT_DEFAULT, WAIT_MAX);
|
|
123
|
+
const run = await runCli(['wait', args.request_id, '--timeout', String(Math.max(1, seconds))], { timeoutMs: (seconds + 30) * 1000 });
|
|
124
|
+
// 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);
|
|
126
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'wait'));
|
|
127
|
+
},
|
|
128
|
+
async dalan_result(args) {
|
|
129
|
+
const run = await runCli(['get', args.request_id]);
|
|
130
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
131
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'get'));
|
|
132
|
+
},
|
|
133
|
+
async dalan_status() {
|
|
134
|
+
const run = await runCli(['status']);
|
|
135
|
+
const value = run.code === 0 ? parseJson(run.stdout) : undefined;
|
|
136
|
+
return value !== undefined ? asResult({ value }) : asResult(cliError(run, 'status'));
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export async function callTool(name, rawArgs) {
|
|
141
|
+
const tool = TOOLS.find(t => t.name === name);
|
|
142
|
+
if (!tool) return null;
|
|
143
|
+
try { return await handlers[name](validate(tool, rawArgs)); }
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof SafeError) return asResult({ message: error.message });
|
|
146
|
+
// Python MCP SDK pattern: the client gets the tool name and an error id; the redacted detail goes to the local log.
|
|
147
|
+
const id = randomUUID().slice(0, 8);
|
|
148
|
+
process.stderr.write(`dalan mcp: ${name}: error ${id}: ${safeDiagnostic(error.stack ?? error, 4000)}\n`);
|
|
149
|
+
return asResult({ message: `Error executing tool ${name} (error id ${id}; details are in the dalan mcp log)` });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message: redactSinkText(message) } });
|
|
154
|
+
|
|
155
|
+
// One JSON-RPC message in, zero or one frame out. Never throws.
|
|
156
|
+
export async function handleFrame(message) {
|
|
157
|
+
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
|
+
const { id, method, params } = message;
|
|
159
|
+
if (id === undefined) return null; // notification
|
|
160
|
+
const ok = result => ({ jsonrpc: '2.0', id, result });
|
|
161
|
+
switch (method) {
|
|
162
|
+
case 'initialize': return ok({ protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
163
|
+
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.' });
|
|
165
|
+
case 'ping': return ok({});
|
|
166
|
+
case 'tools/list': return ok({ tools: TOOLS });
|
|
167
|
+
case 'tools/call': {
|
|
168
|
+
if (typeof params?.name !== 'string') return rpcError(id, -32602, 'tools/call requires a tool name');
|
|
169
|
+
const result = await callTool(params.name, params.arguments);
|
|
170
|
+
return result ? ok(result) : rpcError(id, -32602, `unknown tool "${params.name}"`);
|
|
171
|
+
}
|
|
172
|
+
default: return rpcError(id, -32601, `method not found: ${method}`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function main({ input = process.stdin, output = process.stdout } = {}) {
|
|
177
|
+
const inflight = new Set();
|
|
178
|
+
const write = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
179
|
+
for await (const line of readline.createInterface({ input, crlfDelay: Infinity })) {
|
|
180
|
+
if (!line.trim()) continue;
|
|
181
|
+
let message;
|
|
182
|
+
try { message = JSON.parse(line); }
|
|
183
|
+
catch { write(rpcError(null, -32700, 'parse error')); continue; }
|
|
184
|
+
// Requests run concurrently: a long dalan_wait must not block a ping or another tool.
|
|
185
|
+
const work = handleFrame(message).then(frame => { if (frame) write(frame); }, error => {
|
|
186
|
+
process.stderr.write(`dalan mcp: ${safeDiagnostic(error.stack ?? error, 4000)}\n`); write(rpcError(message?.id ?? null, -32603, 'internal error'));
|
|
187
|
+
}).finally(() => inflight.delete(work));
|
|
188
|
+
inflight.add(work);
|
|
189
|
+
}
|
|
190
|
+
await Promise.all(inflight);
|
|
191
|
+
}
|