@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
package/src/deadman.mjs
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import { createServer, request as requestHttp, validateHeaderValue } from 'node:http';
|
|
2
|
+
import { request as requestHttps } from 'node:https';
|
|
3
|
+
import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const defaults = { deadlineMs: 5 * 60_000, clearMs: 15 * 60_000, reminderMs: 2 * 60 * 60_000, tickMs: 10_000, retryMs: 60_000 };
|
|
9
|
+
const digest = value => createHash('sha256').update(value).digest();
|
|
10
|
+
const safeTokenEqual = (token, expectedHash) => timingSafeEqual(digest(token), expectedHash);
|
|
11
|
+
const preSendCodes = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH', 'ENETDOWN', 'EHOSTUNREACH', 'UND_ERR_CONNECT_TIMEOUT']);
|
|
12
|
+
|
|
13
|
+
function safePreSendCode(error) {
|
|
14
|
+
const pending = [error], seen = new Set();
|
|
15
|
+
while (pending.length) {
|
|
16
|
+
const value = pending.pop();
|
|
17
|
+
if (!value || typeof value !== 'object' || seen.has(value)) continue;
|
|
18
|
+
seen.add(value);
|
|
19
|
+
if (preSendCodes.has(value.code)) return value.code.toLowerCase();
|
|
20
|
+
if (value.cause) pending.push(value.cause);
|
|
21
|
+
if (Array.isArray(value.errors)) pending.push(...value.errors);
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isLoopback(hostname) {
|
|
27
|
+
return ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(hostname);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function tlsConfigurationCode(error) {
|
|
31
|
+
if(error?.transportReady===true) return null;
|
|
32
|
+
const codes=new Set(['EPROTO','DEPTH_ZERO_SELF_SIGNED_CERT','SELF_SIGNED_CERT_IN_CHAIN','UNABLE_TO_GET_ISSUER_CERT','UNABLE_TO_GET_ISSUER_CERT_LOCALLY','UNABLE_TO_VERIFY_LEAF_SIGNATURE']);
|
|
33
|
+
const pending=[error],seen=new Set();
|
|
34
|
+
while(pending.length) {
|
|
35
|
+
const value=pending.pop();
|
|
36
|
+
if(!value||typeof value!=='object'||seen.has(value)) continue;
|
|
37
|
+
seen.add(value);
|
|
38
|
+
if(codes.has(value.code)||/^(CERT_|ERR_TLS_|ERR_SSL_)/.test(value.code??'')) return value.code.toLowerCase();
|
|
39
|
+
if(value.cause)pending.push(value.cause);
|
|
40
|
+
if(Array.isArray(value.errors))pending.push(...value.errors);
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function publisherFromEnv(env) {
|
|
46
|
+
const url = env.DOT_DEADMAN_NTFY_URL;
|
|
47
|
+
if (!url) return null;
|
|
48
|
+
let parsed;
|
|
49
|
+
try { parsed=new URL(url); } catch { throw new Error('invalid dead-man publisher URL'); }
|
|
50
|
+
if(parsed.username||parsed.password) throw new Error('dead-man publisher URL must not contain credentials');
|
|
51
|
+
if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && isLoopback(parsed.hostname))) throw new Error('dead-man publisher must use HTTPS');
|
|
52
|
+
const token = env.DOT_DEADMAN_NTFY_TOKEN;
|
|
53
|
+
if(token) {
|
|
54
|
+
try {
|
|
55
|
+
if(/[\x00-\x1f\x7f]/.test(token)) throw new Error();
|
|
56
|
+
validateHeaderValue('Authorization',`Bearer ${token}`);
|
|
57
|
+
} catch { throw new Error('invalid dead-man publisher authorization token'); }
|
|
58
|
+
}
|
|
59
|
+
return (title, message) => new Promise((resolve,reject) => {
|
|
60
|
+
const headers = { Title: title, 'Content-Type': 'text/plain', 'Content-Length': Buffer.byteLength(message) };
|
|
61
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
62
|
+
let transportReady=false,settled=false,req;
|
|
63
|
+
const fail=error => {
|
|
64
|
+
if(settled)return;
|
|
65
|
+
settled=true;
|
|
66
|
+
clearTimeout(deadline);
|
|
67
|
+
error.transportReady=transportReady;
|
|
68
|
+
reject(error);
|
|
69
|
+
req?.destroy();
|
|
70
|
+
};
|
|
71
|
+
const deadline=setTimeout(() => {
|
|
72
|
+
const error=new Error('publisher total timeout after 5000ms');
|
|
73
|
+
error.code='DOT_PUBLISH_TIMEOUT';
|
|
74
|
+
fail(error);
|
|
75
|
+
},5000);
|
|
76
|
+
const request=parsed.protocol==='https:'?requestHttps:requestHttp;
|
|
77
|
+
try {
|
|
78
|
+
req=request(parsed,{ method:'POST',headers,agent:false },res => {
|
|
79
|
+
if(settled){res.destroy();return;}
|
|
80
|
+
settled=true;
|
|
81
|
+
clearTimeout(deadline);
|
|
82
|
+
const status=res.statusCode;
|
|
83
|
+
resolve(status>=200&&status<300?{accepted:true}:{status});
|
|
84
|
+
res.destroy();
|
|
85
|
+
});
|
|
86
|
+
req.on('socket',socket => {
|
|
87
|
+
socket.once(parsed.protocol==='https:'?'secureConnect':'connect',() => {transportReady=true;});
|
|
88
|
+
});
|
|
89
|
+
req.on('error',fail);
|
|
90
|
+
req.end(message);
|
|
91
|
+
} catch(error) { fail(error); }
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export class Deadman {
|
|
96
|
+
constructor({ dbFile, token, publisher = null, now = Date.now, elapsedNow = () => performance.now(), ...config }) {
|
|
97
|
+
if (typeof token !== 'string' || token.length < 32) throw new Error('dead-man bearer token must contain at least 32 characters');
|
|
98
|
+
this.tokenHash = digest(token);
|
|
99
|
+
this.now = now;
|
|
100
|
+
this.elapsedNow = elapsedNow;
|
|
101
|
+
this.config = { ...defaults, ...config };
|
|
102
|
+
for (const key of ['deadlineMs', 'clearMs', 'reminderMs', 'tickMs', 'retryMs']) {
|
|
103
|
+
if (!Number.isInteger(this.config[key]) || this.config[key] < 1) throw new Error(`invalid ${key}`);
|
|
104
|
+
}
|
|
105
|
+
this.publisher = publisher;
|
|
106
|
+
fs.mkdirSync(path.dirname(dbFile), { recursive: true, mode: 0o700 });
|
|
107
|
+
this.db = new DatabaseSync(dbFile);
|
|
108
|
+
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
|
|
109
|
+
CREATE TABLE IF NOT EXISTS monitor (id INTEGER PRIMARY KEY CHECK(id=1), started_at INTEGER NOT NULL, logical_now INTEGER NOT NULL, wall_at INTEGER NOT NULL, last_heartbeat_at INTEGER, active_episode_id INTEGER, recovery_since INTEGER);
|
|
110
|
+
CREATE TABLE IF NOT EXISTS episodes (id INTEGER PRIMARY KEY AUTOINCREMENT, opened_at INTEGER NOT NULL, closed_at INTEGER, initial_state TEXT NOT NULL DEFAULT 'pending', initial_sent_at INTEGER, reminder_state TEXT NOT NULL DEFAULT 'waiting', next_attempt_at INTEGER NOT NULL DEFAULT 0, uncertain_at INTEGER, last_error TEXT, initial_publication_id TEXT, reminder_publication_id TEXT, initial_receipt_hash TEXT, reminder_receipt_hash TEXT);
|
|
111
|
+
`);
|
|
112
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('episodes')").all().map(row=>row.name));
|
|
113
|
+
for(const name of ['initial_publication_id','reminder_publication_id','initial_receipt_hash','reminder_receipt_hash'])
|
|
114
|
+
if(!columns.has(name))this.db.exec(`ALTER TABLE episodes ADD COLUMN ${name} TEXT`);
|
|
115
|
+
this.db.exec(`
|
|
116
|
+
UPDATE episodes SET initial_state='uncertain',uncertain_at=unixepoch('subsec') * 1000,last_error='process ended during publish' WHERE initial_state='sending';
|
|
117
|
+
UPDATE episodes SET reminder_state='uncertain',last_error='process ended during publish' WHERE reminder_state='sending';
|
|
118
|
+
UPDATE episodes SET initial_state='pending',next_attempt_at=0 WHERE initial_state='configuration_error';
|
|
119
|
+
UPDATE episodes SET reminder_state='waiting',next_attempt_at=0 WHERE reminder_state='configuration_error';`);
|
|
120
|
+
for(const row of this.db.prepare('SELECT id,initial_publication_id,reminder_publication_id FROM episodes').all())
|
|
121
|
+
this.db.prepare('UPDATE episodes SET initial_publication_id=COALESCE(initial_publication_id,?),reminder_publication_id=COALESCE(reminder_publication_id,?) WHERE id=?')
|
|
122
|
+
.run(randomUUID(),randomUUID(),row.id);
|
|
123
|
+
const wallAtStart = this.now(), elapsedAtStart = this.elapsedNow();
|
|
124
|
+
this.db.prepare('INSERT OR IGNORE INTO monitor(id,started_at,logical_now,wall_at) VALUES(1,?,?,?)').run(wallAtStart, wallAtStart, wallAtStart);
|
|
125
|
+
const previous = this.#row();
|
|
126
|
+
this.logicalAtStart = previous.logical_now + Math.max(0, wallAtStart - previous.wall_at);
|
|
127
|
+
this.elapsedAtStart = elapsedAtStart;
|
|
128
|
+
this.receivedHeartbeatSinceStart = false;
|
|
129
|
+
this.db.prepare('UPDATE monitor SET logical_now=?,wall_at=? WHERE id=1').run(this.logicalAtStart, Math.max(previous.wall_at, wallAtStart));
|
|
130
|
+
this.tickPromise = Promise.resolve();
|
|
131
|
+
this.timer = null;
|
|
132
|
+
this.server = null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#row() { return this.db.prepare('SELECT * FROM monitor WHERE id=1').get(); }
|
|
136
|
+
#episode(id) { return this.db.prepare('SELECT * FROM episodes WHERE id=?').get(id); }
|
|
137
|
+
|
|
138
|
+
#effectiveNow() {
|
|
139
|
+
const monitor = this.#row();
|
|
140
|
+
const elapsed = Math.max(0, this.elapsedNow() - this.elapsedAtStart);
|
|
141
|
+
const logicalNow = this.logicalAtStart + elapsed;
|
|
142
|
+
this.db.prepare('UPDATE monitor SET logical_now=?,wall_at=? WHERE id=1').run(logicalNow, Math.max(monitor.wall_at, this.now()));
|
|
143
|
+
return logicalNow;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#transaction(fn) {
|
|
147
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
148
|
+
try { const result = fn(); this.db.exec('COMMIT'); return result; }
|
|
149
|
+
catch (error) { this.db.exec('ROLLBACK'); throw error; }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async heartbeat(token, body) {
|
|
153
|
+
if (typeof token !== 'string' || !safeTokenEqual(token, this.tokenHash)) return { status: 401, body: { error: 'unauthorized' } };
|
|
154
|
+
if (!body || body.healthy !== true || Object.keys(body).some(key => key !== 'healthy')) return { status: 400, body: { error: 'expected {"healthy":true}' } };
|
|
155
|
+
await this.tick();
|
|
156
|
+
const at = this.#effectiveNow();
|
|
157
|
+
this.db.prepare('UPDATE monitor SET last_heartbeat_at=? WHERE id=1').run(at);
|
|
158
|
+
this.receivedHeartbeatSinceStart = true;
|
|
159
|
+
await this.tick();
|
|
160
|
+
return { status: 202, body: { accepted: true } };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async tick() {
|
|
164
|
+
const next = this.tickPromise.then(() => this.#advance());
|
|
165
|
+
this.tickPromise = next.catch(() => {});
|
|
166
|
+
return next;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async #advance() {
|
|
170
|
+
const now = this.#effectiveNow();
|
|
171
|
+
let monitor = this.#row();
|
|
172
|
+
const base = monitor.last_heartbeat_at ?? monitor.started_at;
|
|
173
|
+
const timely = monitor.last_heartbeat_at !== null && now >= monitor.last_heartbeat_at && now - monitor.last_heartbeat_at <= this.config.deadlineMs;
|
|
174
|
+
const startupGraceDone = this.receivedHeartbeatSinceStart || this.elapsedNow() - this.elapsedAtStart >= this.config.deadlineMs;
|
|
175
|
+
if (!monitor.active_episode_id && startupGraceDone && now - base > this.config.deadlineMs) {
|
|
176
|
+
const opened = base + this.config.deadlineMs;
|
|
177
|
+
this.#transaction(() => {
|
|
178
|
+
const result = this.db.prepare('INSERT INTO episodes(opened_at,initial_publication_id,reminder_publication_id) VALUES(?,?,?)')
|
|
179
|
+
.run(opened,randomUUID(),randomUUID());
|
|
180
|
+
this.db.prepare('UPDATE monitor SET active_episode_id=?,recovery_since=NULL WHERE id=1').run(Number(result.lastInsertRowid));
|
|
181
|
+
});
|
|
182
|
+
monitor = this.#row();
|
|
183
|
+
}
|
|
184
|
+
if (monitor.active_episode_id) {
|
|
185
|
+
if (timely) {
|
|
186
|
+
this.db.prepare('UPDATE monitor SET recovery_since=COALESCE(recovery_since,?) WHERE id=1').run(now);
|
|
187
|
+
monitor = this.#row();
|
|
188
|
+
if (now - monitor.recovery_since >= this.config.clearMs) {
|
|
189
|
+
this.#transaction(() => {
|
|
190
|
+
this.db.prepare(`UPDATE episodes SET closed_at=?,
|
|
191
|
+
initial_state=CASE WHEN initial_state='pending' THEN 'suppressed_recovered' ELSE initial_state END,
|
|
192
|
+
reminder_state=CASE WHEN reminder_state='waiting' THEN 'suppressed_recovered' ELSE reminder_state END
|
|
193
|
+
WHERE id=?`).run(now, monitor.active_episode_id);
|
|
194
|
+
this.db.prepare('UPDATE monitor SET active_episode_id=NULL,recovery_since=NULL WHERE id=1').run();
|
|
195
|
+
});
|
|
196
|
+
monitor = this.#row();
|
|
197
|
+
}
|
|
198
|
+
} else {
|
|
199
|
+
this.db.prepare('UPDATE monitor SET recovery_since=NULL WHERE id=1').run();
|
|
200
|
+
monitor = this.#row();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const episode = monitor.active_episode_id ? this.#episode(monitor.active_episode_id) : null;
|
|
204
|
+
if (!episode || !this.publisher) return;
|
|
205
|
+
if (episode.initial_state === 'pending' && now >= episode.next_attempt_at) {
|
|
206
|
+
const result = await this.#publish(episode.id, 'initial', episode.initial_publication_id, 'Dalan host heartbeat missed', 'The external dot-deadman monitor has not received a timely health heartbeat. Check the bridge host and network.');
|
|
207
|
+
if (result.state === 'sent') this.db.prepare("UPDATE episodes SET initial_state='sent',initial_sent_at=?,reminder_state='waiting',last_error=NULL WHERE id=? AND initial_state='sending'").run(now, episode.id);
|
|
208
|
+
else if (result.state === 'safe_failure') this.db.prepare("UPDATE episodes SET initial_state='pending',next_attempt_at=?,last_error=? WHERE id=? AND initial_state='sending'").run(now + this.config.retryMs, result.reason, episode.id);
|
|
209
|
+
else if (result.state === 'configuration_error') this.db.prepare("UPDATE episodes SET initial_state='configuration_error',last_error=? WHERE id=? AND initial_state='sending'").run(result.reason, episode.id);
|
|
210
|
+
else this.db.prepare("UPDATE episodes SET initial_state='uncertain',uncertain_at=?,last_error='publisher outcome uncertain' WHERE id=? AND initial_state='sending'").run(now, episode.id);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const fresh = this.#episode(episode.id);
|
|
214
|
+
if (fresh.initial_state === 'sent' && fresh.reminder_state === 'waiting' && now >= fresh.next_attempt_at && now - fresh.initial_sent_at >= this.config.reminderMs) {
|
|
215
|
+
const result = await this.#publish(episode.id, 'reminder', fresh.reminder_publication_id, 'Dalan still unreachable', 'The Dalan heartbeat is still unresolved two hours after the initial alert.');
|
|
216
|
+
if (result.state === 'sent') this.db.prepare("UPDATE episodes SET reminder_state='sent',last_error=NULL WHERE id=? AND reminder_state='sending'").run(episode.id);
|
|
217
|
+
else if (result.state === 'safe_failure') this.db.prepare("UPDATE episodes SET reminder_state='waiting',next_attempt_at=?,last_error=? WHERE id=? AND reminder_state='sending'").run(now + this.config.retryMs, result.reason, episode.id);
|
|
218
|
+
else if (result.state === 'configuration_error') this.db.prepare("UPDATE episodes SET reminder_state='configuration_error',last_error=? WHERE id=? AND reminder_state='sending'").run(result.reason, episode.id);
|
|
219
|
+
else this.db.prepare("UPDATE episodes SET reminder_state='uncertain',uncertain_at=?,last_error='publisher reminder outcome uncertain' WHERE id=? AND reminder_state='sending'").run(now, episode.id);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async #publish(id, kind, publicationId, title, message) {
|
|
224
|
+
const column = kind === 'initial' ? 'initial_state' : 'reminder_state';
|
|
225
|
+
this.db.prepare(`UPDATE episodes SET ${column}='sending' WHERE id=?`).run(id);
|
|
226
|
+
try {
|
|
227
|
+
const result = await this.publisher(title, `${message}\nDelivery reference: ${publicationId}`, publicationId);
|
|
228
|
+
if (result?.accepted === true) return { state: 'sent' };
|
|
229
|
+
if (Number.isInteger(result?.status) && result.status >= 300 && result.status < 400) return { state: 'configuration_error', reason: `publisher_redirect_http_${result.status}` };
|
|
230
|
+
if (Number.isInteger(result?.status) && result.status >= 400 && result.status < 500) return { state: 'safe_failure', reason: `publisher_http_${result.status}` };
|
|
231
|
+
return { state: 'uncertain' };
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if(error?.transportReady===true) return { state:'uncertain' };
|
|
234
|
+
const configurationCode=tlsConfigurationCode(error);
|
|
235
|
+
if(configurationCode) return { state:'configuration_error',reason:`publisher_tls_${configurationCode}` };
|
|
236
|
+
const code = error?.code==='DOT_PUBLISH_TIMEOUT'&&error.transportReady===false?'timeout':safePreSendCode(error)??(error?.transportReady===false?'before_transport_ready':null);
|
|
237
|
+
return code ? { state: 'safe_failure', reason: `publisher_connect_${code}` } : { state: 'uncertain' };
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async start({ host = '127.0.0.1', port = 8788 } = {}) {
|
|
242
|
+
await this.tick();
|
|
243
|
+
this.timer = setInterval(() => { this.tick().catch(() => {}); }, this.config.tickMs);
|
|
244
|
+
this.timer.unref();
|
|
245
|
+
this.server = createServer(async (req, res) => {
|
|
246
|
+
if (req.method !== 'POST' || !['/heartbeat','/reconcile'].includes(req.url)) return this.#reply(res, 404, { error: 'not found' });
|
|
247
|
+
const authorization = req.headers.authorization || '';
|
|
248
|
+
const token = authorization.startsWith('Bearer ') ? authorization.slice(7) : '';
|
|
249
|
+
if (!token || !safeTokenEqual(token, this.tokenHash)) return this.#reply(res, 401, { error: 'unauthorized' });
|
|
250
|
+
let raw = '';
|
|
251
|
+
try {
|
|
252
|
+
for await (const chunk of req) {
|
|
253
|
+
raw += chunk.toString('utf8');
|
|
254
|
+
if (Buffer.byteLength(raw) > 1024) { req.destroy(); return; }
|
|
255
|
+
}
|
|
256
|
+
const body=JSON.parse(raw);
|
|
257
|
+
if(req.url==='/heartbeat') {
|
|
258
|
+
const result=await this.heartbeat(token,body);
|
|
259
|
+
this.#reply(res,result.status,result.body);
|
|
260
|
+
} else {
|
|
261
|
+
const episode=this.reconcilePublication(body);
|
|
262
|
+
this.#reply(res,200,{episode_id:episode.id,phase:body.phase,state:body.phase==='initial'?episode.initial_state:episode.reminder_state});
|
|
263
|
+
}
|
|
264
|
+
} catch {
|
|
265
|
+
if (!res.headersSent && !res.destroyed) this.#reply(res, req.url==='/reconcile'?409:400, { error: req.url==='/reconcile'?'reconciliation refused':'invalid request' });
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
await new Promise((resolve, reject) => { this.server.once('error', reject); this.server.listen(port, host, resolve); });
|
|
269
|
+
return this.server.address();
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
#reply(res, status, body) {
|
|
273
|
+
const bytes = JSON.stringify(body);
|
|
274
|
+
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(bytes), 'cache-control': 'no-store' });
|
|
275
|
+
res.end(bytes);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
status() {
|
|
279
|
+
const monitor = this.#row();
|
|
280
|
+
const episodes = this.db.prepare('SELECT * FROM episodes ORDER BY id').all();
|
|
281
|
+
return { last_heartbeat_at: monitor.last_heartbeat_at, active_episode_id: monitor.active_episode_id, recovery_since: monitor.recovery_since, episodes };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
reconcilePublication({episodeId,phase,outcome,receipt}) {
|
|
285
|
+
if(!Number.isSafeInteger(episodeId)||episodeId<1||!['initial','reminder'].includes(phase)||
|
|
286
|
+
!['sent','unsent'].includes(outcome)||typeof receipt!=='string'||!receipt.trim()||receipt.length>512)
|
|
287
|
+
throw new Error('invalid publication reconciliation');
|
|
288
|
+
return this.#transaction(()=>{
|
|
289
|
+
const episode=this.#episode(episodeId);
|
|
290
|
+
if(!episode)throw new Error('dead-man episode not found');
|
|
291
|
+
const stateColumn=phase==='initial'?'initial_state':'reminder_state';
|
|
292
|
+
if(episode[stateColumn]!=='uncertain')throw new Error('publication is not uncertain');
|
|
293
|
+
const receiptColumn=phase==='initial'?'initial_receipt_hash':'reminder_receipt_hash';
|
|
294
|
+
const receiptHash=digest(receipt.trim()).toString('hex');
|
|
295
|
+
if(phase==='initial') {
|
|
296
|
+
if(outcome==='sent') this.db.prepare("UPDATE episodes SET initial_state='sent',initial_sent_at=COALESCE(initial_sent_at,?),initial_receipt_hash=?,uncertain_at=NULL,last_error='operator reconciled publication' WHERE id=? AND initial_state='uncertain'").run(this.#effectiveNow(),receiptHash,episodeId);
|
|
297
|
+
else if(episode.closed_at!==null) this.db.prepare("UPDATE episodes SET initial_state='suppressed_recovered',initial_receipt_hash=?,uncertain_at=NULL,last_error='operator confirmed publication absent after recovery' WHERE id=? AND initial_state='uncertain'").run(receiptHash,episodeId);
|
|
298
|
+
else this.db.prepare("UPDATE episodes SET initial_state='pending',next_attempt_at=?,initial_receipt_hash=?,uncertain_at=NULL,last_error='operator confirmed publication absent' WHERE id=? AND initial_state='uncertain'").run(this.#effectiveNow(),receiptHash,episodeId);
|
|
299
|
+
} else if(outcome==='sent') this.db.prepare("UPDATE episodes SET reminder_state='sent',reminder_receipt_hash=?,last_error='operator reconciled reminder' WHERE id=? AND reminder_state='uncertain'").run(receiptHash,episodeId);
|
|
300
|
+
else if(episode.closed_at!==null) this.db.prepare("UPDATE episodes SET reminder_state='suppressed_recovered',reminder_receipt_hash=?,last_error='operator confirmed reminder absent after recovery' WHERE id=? AND reminder_state='uncertain'").run(receiptHash,episodeId);
|
|
301
|
+
else this.db.prepare("UPDATE episodes SET reminder_state='waiting',next_attempt_at=?,reminder_receipt_hash=?,last_error='operator confirmed reminder absent' WHERE id=? AND reminder_state='uncertain'").run(this.#effectiveNow(),receiptHash,episodeId);
|
|
302
|
+
return this.#episode(episodeId);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
async close() {
|
|
307
|
+
if (this.timer) clearInterval(this.timer);
|
|
308
|
+
if (this.server) await new Promise(resolve => this.server.close(resolve));
|
|
309
|
+
await this.tickPromise;
|
|
310
|
+
this.db.close();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
export function createDeadmanFromEnv(env = process.env) {
|
|
315
|
+
const token = env.DOT_DEADMAN_TOKEN;
|
|
316
|
+
const dbFile = env.DOT_DEADMAN_DB || '/var/lib/dot-deadman/deadman.sqlite';
|
|
317
|
+
return new Deadman({ dbFile, token, publisher: publisherFromEnv(env) });
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function readDeadmanStatus(dbFile) {
|
|
321
|
+
const db=new DatabaseSync(dbFile,{readOnly:true});
|
|
322
|
+
try {
|
|
323
|
+
const monitor=db.prepare('SELECT * FROM monitor WHERE id=1').get();
|
|
324
|
+
const episodes=db.prepare('SELECT * FROM episodes ORDER BY id').all();
|
|
325
|
+
if(!monitor)throw new Error('dead-man monitor is not initialized');
|
|
326
|
+
return {last_heartbeat_at:monitor.last_heartbeat_at,active_episode_id:monitor.active_episode_id,
|
|
327
|
+
recovery_since:monitor.recovery_since,episodes};
|
|
328
|
+
} finally {db.close();}
|
|
329
|
+
}
|
package/src/delivery.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const t3ThreadIdPattern = /^[A-Za-z0-9._:%-]+$/;
|
|
2
|
+
export const maxT3ThreadIdLength = 1024;
|
|
3
|
+
|
|
4
|
+
// T3 uses UUIDs, `mcp:<uuid>`, and opaque delegated/provider IDs. Keep this
|
|
5
|
+
// deliberately bounded while accepting the characters present in those forms.
|
|
6
|
+
export function validT3ThreadId(value) {
|
|
7
|
+
return typeof value === 'string'
|
|
8
|
+
&& value.length >= 8
|
|
9
|
+
&& value.length <= maxT3ThreadIdLength
|
|
10
|
+
&& t3ThreadIdPattern.test(value);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function parseDelivery(value) {
|
|
14
|
+
if (value === 'none') return { mode: 'none', threadId: null };
|
|
15
|
+
if (typeof value === 'string' && value.startsWith('t3:') && validT3ThreadId(value.slice(3))) {
|
|
16
|
+
return { mode: 't3', threadId: value.slice(3) };
|
|
17
|
+
}
|
|
18
|
+
throw new Error('invalid delivery; expected none or t3:<thread-id>');
|
|
19
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// A minimal MCP worker for `dalan try`: the real OAuth path (discovery, dynamic registration, PKCE, pairing page,
|
|
2
|
+
// token) and the real job tools, with no vendor client. It proves that the bridge works end to end. It is not a
|
|
3
|
+
// claim that any particular client works.
|
|
4
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
5
|
+
import { parseJsonBody, safeDiagnostic } from './diagnostic.mjs';
|
|
6
|
+
|
|
7
|
+
// A loopback pattern without a port admits any port, so this URI matches the 'http://127.0.0.1/callback' pattern.
|
|
8
|
+
export const DEMO_REDIRECT = 'http://127.0.0.1:43111/callback';
|
|
9
|
+
|
|
10
|
+
// Each call opens a fresh connection: `dalan try` runs owner commands in child processes while these requests wait.
|
|
11
|
+
const get = (url, { headers = {}, ...init } = {}) => fetch(url, { redirect: 'manual', ...init, headers: { connection: 'close', ...headers } });
|
|
12
|
+
const json = async (url, label, signal) => {
|
|
13
|
+
const res = await get(url, { signal });
|
|
14
|
+
if (res.status !== 200) throw new Error(`${label} returned HTTP ${res.status}`);
|
|
15
|
+
return parseJsonBody(await res.text(), label);
|
|
16
|
+
};
|
|
17
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
18
|
+
|
|
19
|
+
// Start OAuth against the MCP URL. Resolves with the pairing code the owner must approve and a `complete()` that
|
|
20
|
+
// waits for that approval and returns an access token.
|
|
21
|
+
// `signal` aborts every request and the wait for approval.
|
|
22
|
+
export async function beginPairing(mcpUrl, { redirect = DEMO_REDIRECT, clientName = 'dalan demo worker', timeoutMs = 600_000, signal } = {}) {
|
|
23
|
+
const resource = new URL(mcpUrl);
|
|
24
|
+
const protectedResource = await json(new URL(`/.well-known/oauth-protected-resource${resource.pathname}`, resource.origin), 'resource metadata', signal);
|
|
25
|
+
const issuer = new URL(protectedResource.authorization_servers?.[0]);
|
|
26
|
+
const meta = await json(new URL(`/.well-known/oauth-authorization-server${issuer.pathname}`, issuer.origin), 'authorization-server metadata', signal);
|
|
27
|
+
const registration = await get(meta.registration_endpoint, {
|
|
28
|
+
signal, method: 'POST', headers: { 'content-type': 'application/json' },
|
|
29
|
+
body: JSON.stringify({ redirect_uris: [redirect], client_name: clientName, token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'] }),
|
|
30
|
+
});
|
|
31
|
+
if (registration.status !== 201) {
|
|
32
|
+
// Show what the server said. Only a refused callback is fixed by allowing it; a registration limit is not.
|
|
33
|
+
const body = await registration.text();
|
|
34
|
+
const said = (() => { try { return JSON.parse(body).error_description; } catch { return undefined; } })();
|
|
35
|
+
const detail = typeof said === 'string' && said ? `: ${safeDiagnostic(said, 300)}` : '';
|
|
36
|
+
throw new Error(registration.status === 429
|
|
37
|
+
? `client registration refused (HTTP 429)${detail || ': registration limit reached. Reuse the client this worker already registered; run dalan connect reset only if you cannot'}`
|
|
38
|
+
: `client registration refused (HTTP ${registration.status})${detail}; allow the callback with: dalan connect allow-callback '${redirect.replace(/:\d+/, '')}'`);
|
|
39
|
+
}
|
|
40
|
+
const { client_id: clientId } = parseJsonBody(await registration.text(), 'client registration');
|
|
41
|
+
|
|
42
|
+
const cookies = new Map();
|
|
43
|
+
const send = async (url, init) => {
|
|
44
|
+
const cookie = [...cookies].map(([k, v]) => `${k}=${v}`).join('; ');
|
|
45
|
+
const res = await get(url, { ...init, signal, headers: { ...(cookie ? { cookie } : {}) } });
|
|
46
|
+
for (const line of res.headers.getSetCookie()) {
|
|
47
|
+
const [pair] = line.split(';'), i = pair.indexOf('=');
|
|
48
|
+
if (pair.slice(i + 1) === '') cookies.delete(pair.slice(0, i)); else cookies.set(pair.slice(0, i), pair.slice(i + 1));
|
|
49
|
+
}
|
|
50
|
+
return res;
|
|
51
|
+
};
|
|
52
|
+
const here = location => new URL(location, issuer.origin).href;
|
|
53
|
+
const verifier = randomBytes(32).toString('base64url'), state = randomBytes(6).toString('hex');
|
|
54
|
+
const authorize = new URL(meta.authorization_endpoint);
|
|
55
|
+
for (const [k, v] of Object.entries({
|
|
56
|
+
client_id: clientId, response_type: 'code', redirect_uri: redirect, scope: 'dalan.read dalan.work', state, resource: resource.href,
|
|
57
|
+
code_challenge: createHash('sha256').update(verifier).digest('base64url'), code_challenge_method: 'S256',
|
|
58
|
+
})) authorize.searchParams.set(k, v);
|
|
59
|
+
const first = await send(authorize.href);
|
|
60
|
+
const interaction = first.headers.get('location');
|
|
61
|
+
if (first.status !== 303 || !interaction) throw new Error(`authorization request refused (HTTP ${first.status})`);
|
|
62
|
+
const code = (await (await send(here(interaction))).text()).match(/class="code">([A-Z0-9-]+)</)?.[1];
|
|
63
|
+
if (!code) throw new Error('the bridge showed no pairing code');
|
|
64
|
+
|
|
65
|
+
async function complete() {
|
|
66
|
+
const deadline = Date.now() + timeoutMs;
|
|
67
|
+
for (;;) {
|
|
68
|
+
const done = await send(here(interaction));
|
|
69
|
+
if (done.status === 303) {
|
|
70
|
+
const resume = await send(here(done.headers.get('location')));
|
|
71
|
+
const callback = new URL(resume.headers.get('location') ?? '', issuer.origin);
|
|
72
|
+
if (callback.searchParams.get('state') !== state || !callback.searchParams.get('code')) throw new Error('pairing ended without an authorization code');
|
|
73
|
+
const token = await get(meta.token_endpoint, {
|
|
74
|
+
signal, method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
75
|
+
body: new URLSearchParams({ client_id: clientId, grant_type: 'authorization_code', code: callback.searchParams.get('code'), redirect_uri: redirect, code_verifier: verifier, resource: resource.href }),
|
|
76
|
+
});
|
|
77
|
+
if (token.status !== 200) throw new Error(`token request refused (HTTP ${token.status})`);
|
|
78
|
+
return parseJsonBody(await token.text(), 'token response').access_token;
|
|
79
|
+
}
|
|
80
|
+
if (Date.now() > deadline) throw new Error('pairing was not approved in time');
|
|
81
|
+
signal?.throwIfAborted();
|
|
82
|
+
await sleep(500);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { code, complete };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const MCP_PROTOCOL = '2025-11-25';
|
|
89
|
+
|
|
90
|
+
// An MCP session as a real client opens one: `initialize`, then `notifications/initialized`, then tool calls that carry
|
|
91
|
+
// the negotiated protocol version (and the session id, if the server issues one).
|
|
92
|
+
export async function openSession(mcpUrl, token, { signal } = {}) {
|
|
93
|
+
let nextId = 0;
|
|
94
|
+
let sessionHeaders = {};
|
|
95
|
+
const post = async (message, { expect = 200 } = {}) => {
|
|
96
|
+
const res = await get(mcpUrl, {
|
|
97
|
+
signal, method: 'POST', body: JSON.stringify(message),
|
|
98
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${token}`, ...sessionHeaders },
|
|
99
|
+
});
|
|
100
|
+
const text = await res.text();
|
|
101
|
+
if (res.status !== expect) throw new Error(`${message.method} returned HTTP ${res.status}: ${safeDiagnostic(text, 200)}`);
|
|
102
|
+
return { res, text };
|
|
103
|
+
};
|
|
104
|
+
const parse = text => {
|
|
105
|
+
const data = text.startsWith('event:') || text.startsWith('data:') ? text.split('\n').find(l => l.startsWith('data:'))?.slice(5) : text;
|
|
106
|
+
return parseJsonBody(data ?? 'null', 'MCP response');
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const init = await post({ jsonrpc: '2.0', id: ++nextId, method: 'initialize', params: { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: { name: 'dalan-demo', version: '1' } } });
|
|
110
|
+
const negotiated = parse(init.text)?.result?.protocolVersion;
|
|
111
|
+
if (typeof negotiated !== 'string') throw new Error(`initialize returned no protocol version: ${safeDiagnostic(init.text, 200)}`);
|
|
112
|
+
sessionHeaders = { 'mcp-protocol-version': negotiated, ...(init.res.headers.get('mcp-session-id') ? { 'mcp-session-id': init.res.headers.get('mcp-session-id') } : {}) };
|
|
113
|
+
await post({ jsonrpc: '2.0', method: 'notifications/initialized' }, { expect: 202 });
|
|
114
|
+
|
|
115
|
+
return async function call(name, args) {
|
|
116
|
+
const { text } = await post({ jsonrpc: '2.0', id: ++nextId, method: 'tools/call', params: { name, arguments: args } }).catch(error => { throw new Error(`${name} failed: ${error.message}`); });
|
|
117
|
+
const result = parse(text)?.result;
|
|
118
|
+
const body = result?.content?.find(c => c.type === 'text')?.text;
|
|
119
|
+
if (result?.isError || body === undefined) throw new Error(`${name} failed: ${safeDiagnostic(body ?? text, 200)}`);
|
|
120
|
+
return parseJsonBody(body, `${name} result`);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// The job lifecycle a worker follows: initialize, list, claim, report progress, finish.
|
|
125
|
+
export async function workJob(mcpUrl, token, requestId, { claimant = 'dalan-demo', report, signal }) {
|
|
126
|
+
const call = await openSession(mcpUrl, token, { signal });
|
|
127
|
+
const pending = await call('list_pending', {});
|
|
128
|
+
if (!pending.assignments.some(a => a.request_id === requestId)) throw new Error(`job ${requestId} is not pending`);
|
|
129
|
+
const { claim_id } = await call('claim', { request_id: requestId, claimant });
|
|
130
|
+
await call('progress', { request_id: requestId, claim_id, note: 'writing the report' });
|
|
131
|
+
return call('finish', { request_id: requestId, claim_id, outcome: 'completed', summary: report, result: report });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// A repository job: the same lifecycle, plus the workspace tools. The report names the README title and the pinned revision.
|
|
135
|
+
export async function workRepositoryJob(mcpUrl, token, requestId, { claimant = 'dalan-demo', sha, signal } = {}) {
|
|
136
|
+
const call = await openSession(mcpUrl, token, { signal });
|
|
137
|
+
const pending = await call('list_pending', {});
|
|
138
|
+
if (!pending.assignments.some(a => a.request_id === requestId)) throw new Error(`job ${requestId} is not pending`);
|
|
139
|
+
const { claim_id } = await call('claim', { request_id: requestId, claimant });
|
|
140
|
+
const files = await call('list_files', { request_id: requestId, claim_id });
|
|
141
|
+
if (!JSON.stringify(files).includes('README.md')) throw new Error('the workspace does not list README.md');
|
|
142
|
+
const file = await call('read_file', { request_id: requestId, claim_id, path: 'README.md' });
|
|
143
|
+
const text = typeof file.text === 'string' ? file.text : '';
|
|
144
|
+
const title = /^#\s+(.+)$/m.exec(text)?.[1];
|
|
145
|
+
if (!title) throw new Error('README.md has no title line');
|
|
146
|
+
await call('progress', { request_id: requestId, claim_id, note: 'read README.md' });
|
|
147
|
+
const report = `README title: ${title}. Pinned revision: ${sha}.`;
|
|
148
|
+
await call('finish', { request_id: requestId, claim_id, outcome: 'completed', summary: report, result: report });
|
|
149
|
+
return report;
|
|
150
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createNoneDestination } from './none.mjs';
|
|
2
|
+
|
|
3
|
+
// Stored delivery values are 'none' or 't3:<thread>'; new submissions pass a parsed mode.
|
|
4
|
+
export const destinationName=delivery=>{
|
|
5
|
+
if(delivery===undefined) return 'none';
|
|
6
|
+
if(delivery==='none'||delivery?.mode==='none') return 'none';
|
|
7
|
+
if(delivery==='t3') return 't3';
|
|
8
|
+
// Persisted rows predate strict admission parsing and use t3:<opaque id>.
|
|
9
|
+
if(typeof delivery==='string'&&/^t3:.+$/.test(delivery)) return 't3';
|
|
10
|
+
if(delivery?.mode==='t3'&&typeof delivery.threadId==='string') return 't3';
|
|
11
|
+
const error=new Error(`invalid delivery mode: ${String(delivery)}`);
|
|
12
|
+
error.code='INVALID_DELIVERY_MODE';
|
|
13
|
+
throw error;
|
|
14
|
+
};
|
|
15
|
+
export function createDestinations(deps) {
|
|
16
|
+
const none=createNoneDestination(deps); let t3Promise;
|
|
17
|
+
const loadT3=deps.loadT3??(()=>import('./t3.mjs').then(({createT3Destination})=>createT3Destination(deps)));
|
|
18
|
+
const getT3=()=>{
|
|
19
|
+
if(!t3Promise) t3Promise=Promise.resolve().then(loadT3).catch(error=>{ t3Promise=null; throw error; });
|
|
20
|
+
return t3Promise;
|
|
21
|
+
};
|
|
22
|
+
return {none,for:async delivery=>destinationName(delivery)==='none'?none:getT3()};
|
|
23
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// delivery=none has no outbound channel: owner attention stays in the wait queue
|
|
2
|
+
// (store.deliveryKind already files it as 'wait', so drain never sees it). Must never import T3 code.
|
|
3
|
+
const reason='no outbound delivery destination';
|
|
4
|
+
|
|
5
|
+
export function createNoneDestination({store,notify=()=>{}}={}) {
|
|
6
|
+
return {
|
|
7
|
+
name:'none',
|
|
8
|
+
quietReason:()=>reason,
|
|
9
|
+
admit() {},
|
|
10
|
+
async validate() { return {environmentId:null}; },
|
|
11
|
+
argv:()=>null,
|
|
12
|
+
async send(item) { store.quietDelivery(item.id,reason); notify(item.request_id); return {state:'pending',reason:'',sendStarted:false}; },
|
|
13
|
+
async reconcile() { return {state:'ambiguous',reason}; },
|
|
14
|
+
};
|
|
15
|
+
}
|