@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,377 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Stdio ACP agent (v1) that fronts the dot-bridge for T3 Code's acpRegistry "local" driver.
|
|
3
|
+
// One process per T3 thread. stdout carries only protocol frames; every log line goes to stderr.
|
|
4
|
+
// Shared ACP support lives in integrations/t3/acp-kit/.
|
|
5
|
+
import { Readable, Writable } from 'node:stream';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import * as acp from '@agentclientprotocol/sdk';
|
|
9
|
+
import { sessionPath, readJsonPrivate, writeJsonPrivate } from '../integrations/t3/acp-kit/src/session-store.mjs';
|
|
10
|
+
import { acquireLock, LockBusyError } from '../integrations/t3/acp-kit/src/lock.mjs';
|
|
11
|
+
import { createRefuse, cancelBudgetMs, CANCEL_CLEANUP_MS } from '../integrations/t3/acp-kit/src/errors.mjs';
|
|
12
|
+
import { detectPresentPatches } from '../src/patch-apply.mjs';
|
|
13
|
+
import {
|
|
14
|
+
paths, adminRequest, transient, sha256, parsePrompt, attemptId, ownerToken, readOrCreateSecret, bridgeRefusal,
|
|
15
|
+
prepareAssignment, sizeRefusal, withoutNote, Refusal, verdictRefusal, CONTINUE_PROMPT, promptText, isBuild, buildResultText, decideHint, runBuildProseCheck, adminArtifact,
|
|
16
|
+
} from '../src/acp-bridge.mjs';
|
|
17
|
+
|
|
18
|
+
const num = (name, fallback) => { const v = Number(process.env[name]); return Number.isFinite(v) && v > 0 ? v : fallback; };
|
|
19
|
+
const HEARTBEAT_MS = num('DOT_ACP_HEARTBEAT_MS', 30_000);
|
|
20
|
+
const IN_FLIGHT_CAP = num('DOT_ACP_INFLIGHT_CAP', 10);
|
|
21
|
+
const VALID_MS = num('DOT_ACP_VALID_MINUTES', 30) * 60_000;
|
|
22
|
+
const OUTAGE_MS = num('DOT_ACP_OUTAGE_MS', 600_000);
|
|
23
|
+
const CANCEL_BUDGET_MS = cancelBudgetMs(process.env.DOT_ACP_CANCEL_BUDGET_MS); // T3 allows 10 s for the prompt to return after session/cancel
|
|
24
|
+
// Submit does server-side work that reads never do (it reads the pinned repository to scan the scope, checks pull request
|
|
25
|
+
// state and, for builds, runs the check-readiness probes), so it gets its own deadline; every other call keeps the 5 s
|
|
26
|
+
// DOT_ACP_HTTP_TIMEOUT_MS. A submit that times out is retried by request id, which the bridge treats as the same job.
|
|
27
|
+
const SUBMIT_DEADLINE_MS = num('DOT_ACP_SUBMIT_DEADLINE_MS', 30_000);
|
|
28
|
+
const SUBMIT_RETRIES = 2;
|
|
29
|
+
const MAX_ATTEMPTS = 6;
|
|
30
|
+
const MAX_EXPIRIES = 3;
|
|
31
|
+
// One adapter serves several bridge workers: DOT_ACP_WORKER picks the bridge worker that submissions target (unset = the
|
|
32
|
+
// bridge default, the worker), and DOT_ACP_MODEL/DOT_ACP_LABEL name the T3 model. DOT_ACP_SOCKET picks the bridge.
|
|
33
|
+
const WORKER = process.env.DOT_ACP_WORKER || null;
|
|
34
|
+
// Same rule as a worker name in workers.json (src/workers.mjs).
|
|
35
|
+
if (WORKER !== null && !/^[a-z][a-z0-9_-]{0,31}$/.test(WORKER)) throw new Error('DOT_ACP_WORKER must be a worker name');
|
|
36
|
+
const MODEL = process.env.DOT_ACP_MODEL || 'dot';
|
|
37
|
+
const LABEL = process.env.DOT_ACP_LABEL || (WORKER ? `Dalan worker: ${WORKER}` : 'Dalan worker');
|
|
38
|
+
const P = paths();
|
|
39
|
+
const log = (...a) => console.error('[dot-acp]', ...a);
|
|
40
|
+
const sleep = (ms, signal) => new Promise(resolve => {
|
|
41
|
+
const t = setTimeout(resolve, ms);
|
|
42
|
+
signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------- durable session state
|
|
46
|
+
// One file per session (several adapter processes share the directory). Written atomically, mode 0600.
|
|
47
|
+
const sessions = new Map();
|
|
48
|
+
const sessionFile = id => {
|
|
49
|
+
try { return sessionPath(P.stateDir, id); }
|
|
50
|
+
catch (e) { if (e.code === 'invalid_session_id') throw acp.RequestError.invalidParams(null, 'invalid session id'); throw e; }
|
|
51
|
+
};
|
|
52
|
+
// Only a session that holds an assignment needs a file; probes and idle sessions leave nothing behind.
|
|
53
|
+
function saveSession(s) {
|
|
54
|
+
if (!s.pending && !s.builds?.length) { fs.rmSync(sessionFile(s.id), { force: true }); return; }
|
|
55
|
+
writeJsonPrivate(sessionFile(s.id), { id: s.id, cwd: s.cwd, model: s.model, pending: s.pending, builds: s.builds ?? [] });
|
|
56
|
+
}
|
|
57
|
+
const readSession = id => readJsonPrivate(sessionFile(id));
|
|
58
|
+
|
|
59
|
+
// Hold the session's lock file for the whole turn (portable O_EXCL lock; a crashed owner is detected by pid and start
|
|
60
|
+
// time). Every writer/deleter runs while the session has one owner.
|
|
61
|
+
async function lockSession(id) {
|
|
62
|
+
try { return await acquireLock(`${sessionFile(id)}.lock`); }
|
|
63
|
+
catch (e) { if (e instanceof LockBusyError) throw refuse(`session ${id} is active in another adapter`,{failure_type:'adapter_error',failure_type_source:'dot_acp_adapter'}); throw e; }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const configOptions = current => [{
|
|
67
|
+
id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: current,
|
|
68
|
+
options: [{ value: MODEL, name: LABEL }],
|
|
69
|
+
}];
|
|
70
|
+
const refuse = createRefuse(acp.RequestError); // T3 records a prompt error as a provider_error failure
|
|
71
|
+
|
|
72
|
+
// ---------------------------------------------------------------- bridge operations
|
|
73
|
+
let secret = null;
|
|
74
|
+
const tokenFor = rid => ownerToken(secret ??= readOrCreateSecret(P.secretFile), rid);
|
|
75
|
+
const call = (route, rid, opts = {}) => adminRequest(P.socket, route, { ...opts, token: rid ? tokenFor(rid) : undefined });
|
|
76
|
+
|
|
77
|
+
// The stored row for this request id with our token: null when the bridge has no such row, a Refusal when it is not ours.
|
|
78
|
+
async function readRow(rid) {
|
|
79
|
+
try { return await call(`/get?id=${encodeURIComponent(rid)}&peek=1`, rid); }
|
|
80
|
+
catch (e) {
|
|
81
|
+
if (e.message === 'message not found' || e.message === 'assignment not found') return null;
|
|
82
|
+
if (e.message === 'invalid owner capability') throw new Refusal(`request ${rid} exists under another owner`);
|
|
83
|
+
throw e;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Find the assignment for this brief, or submit one. A retried or restarted task attaches to the row it already
|
|
88
|
+
// submitted, so the worker never gets the same brief twice:
|
|
89
|
+
// no row -> check eligibility, submit
|
|
90
|
+
// row with another brief -> refuse (one root token must not serve two briefs)
|
|
91
|
+
// row cancelled or expired -> next attempt id `<root>_r<n>`
|
|
92
|
+
// row queued/claimed/finished-> attach; the wait returns the result or keeps waiting
|
|
93
|
+
async function acquire(s, parsed) {
|
|
94
|
+
const briefHash = sha256(parsed.brief);
|
|
95
|
+
let submitRetries = 0;
|
|
96
|
+
const preparedByAttempt=new Map();
|
|
97
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
98
|
+
const rid = attemptId(parsed.requestRoot, attempt);
|
|
99
|
+
const row = await readRow(rid);
|
|
100
|
+
if (row) {
|
|
101
|
+
const storedHash = row.assignment.acp_brief_hash ?? sha256(withoutNote(row.assignment.brief ?? ''));
|
|
102
|
+
if (storedHash !== briefHash) throw new Refusal(`token ${parsed.requestRoot} was already used with a different brief`);
|
|
103
|
+
if (row.status === 'cancelled') continue;
|
|
104
|
+
return { root: parsed.requestRoot, rid, attempt, briefHash, validUntil: row.assignment.valid_until ?? null, notes: [], startedAt: Date.now() };
|
|
105
|
+
}
|
|
106
|
+
const status = await call('/status', null);
|
|
107
|
+
const refusal = bridgeRefusal(status, IN_FLIGHT_CAP);
|
|
108
|
+
if (refusal) throw new Refusal(refusal,'deferred',{failure_type_source:'bridge_status_refusal',verdict:'defer'});
|
|
109
|
+
let prepared=preparedByAttempt.get(rid);
|
|
110
|
+
if(!prepared) {
|
|
111
|
+
const validUntil = new Date(Date.now() + VALID_MS).toISOString();
|
|
112
|
+
const assignment = await prepareAssignment({ cwd: s.cwd, requestId: rid, brief: parsed.brief, validUntil });
|
|
113
|
+
const body = { max_queued: IN_FLIGHT_CAP, delivery: 'none', ...(WORKER ? { worker: WORKER } : {}), assignment, owner_token: tokenFor(rid), meta: { source: 'agent', ...(assignment.execution_scope === 'implementation' ? { task_kind: 'build' } : {}) }, ...(assignment.inputs.length && assignment.execution_scope !== 'implementation' ? { exclude_sensitive: true } : {}) };
|
|
114
|
+
prepared={body,validUntil}; preparedByAttempt.set(rid,prepared);
|
|
115
|
+
}
|
|
116
|
+
const {body,validUntil}=prepared;
|
|
117
|
+
try {
|
|
118
|
+
let preview;
|
|
119
|
+
try { preview=await call('/submit-preview',null,{method:'POST',payload:body,timeoutMs:SUBMIT_DEADLINE_MS}); }
|
|
120
|
+
catch(error) {
|
|
121
|
+
if(error.http_status===404) throw new Refusal('bridge does not support safe /submit-preview; no assignment was submitted','adapter_error',{failure_type_source:'bridge_compatibility'});
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
if(preview.verdict!=='admissible') throw verdictRefusal(preview);
|
|
125
|
+
preparedByAttempt.set(rid,prepared);
|
|
126
|
+
} catch(e) {
|
|
127
|
+
if(e instanceof Refusal) throw e;
|
|
128
|
+
if(transient(e)&&submitRetries++<SUBMIT_RETRIES) { attempt--; continue; }
|
|
129
|
+
throw e;
|
|
130
|
+
}
|
|
131
|
+
try { await call('/submit', null, { method: 'POST', payload: body, timeoutMs: SUBMIT_DEADLINE_MS }); }
|
|
132
|
+
catch (e) {
|
|
133
|
+
if (e.message === 'request_id conflict') { attempt--; continue; } // lost a race: re-read the row
|
|
134
|
+
if(e.verdict) throw verdictRefusal(e);
|
|
135
|
+
// The bridge may have stored the job before the deadline; the same id and brief make the retry attach to it.
|
|
136
|
+
if (transient(e) && submitRetries++ < SUBMIT_RETRIES) { attempt--; continue; }
|
|
137
|
+
if (/^(?:worker|dot) queue is full/.test(e.message)) throw new Refusal(e.message);
|
|
138
|
+
const size = e.http_status === 400 ? sizeRefusal(e.message, Buffer.byteLength(parsed.brief)) : null;
|
|
139
|
+
if (size) throw new Refusal(size);
|
|
140
|
+
throw e;
|
|
141
|
+
}
|
|
142
|
+
return { root: parsed.requestRoot, rid, attempt, briefHash, validUntil:prepared.validUntil, notes: [], startedAt: Date.now() };
|
|
143
|
+
}
|
|
144
|
+
throw new Refusal(`no usable assignment after ${MAX_ATTEMPTS} attempts for ${parsed.requestRoot}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function resultText(row) {
|
|
148
|
+
const r = row.report;
|
|
149
|
+
let text = (r?.result || r?.summary || '').trim() || '(the worker finished without a result)';
|
|
150
|
+
if (r && r.outcome !== 'completed') text = `[worker outcome: ${r.outcome}]\n${text}`;
|
|
151
|
+
if (!isBuild(withoutNote(row.assignment?.brief ?? ''))) return `${text}\n\n${decideHint(row.request_id)}`;
|
|
152
|
+
const art = r?.workspace_evidence?.patch_artifact;
|
|
153
|
+
const patch = art?.artifact_id && art.size ? await adminArtifact(P.socket, art.artifact_id, tokenFor(row.request_id)) : null;
|
|
154
|
+
const proseCheck = await runBuildProseCheck(row.assignment?.inputs?.[0]?.github_repo, patch);
|
|
155
|
+
return buildResultText(row, text, patch, proseCheck);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------- patch observations
|
|
159
|
+
// A build result with a patch is remembered for this session (the last few). On the next prompt the adapter checks, read-only,
|
|
160
|
+
// whether that patch reverses cleanly against the requester's working tree. This
|
|
161
|
+
// is an advisory observation; only explicit owner actions record dispositions.
|
|
162
|
+
const MAX_TRACKED_BUILDS = 5;
|
|
163
|
+
function trackBuild(s, row) {
|
|
164
|
+
const art = row.report?.workspace_evidence?.patch_artifact;
|
|
165
|
+
if (!isBuild(withoutNote(row.assignment?.brief ?? '')) || !art?.artifact_id || !art.size) return;
|
|
166
|
+
s.builds = [...(s.builds ?? []).filter(b => b.rid !== row.request_id), { rid: row.request_id, artifact_id: art.artifact_id, observed: false }].slice(-MAX_TRACKED_BUILDS);
|
|
167
|
+
}
|
|
168
|
+
async function reportPresentPatches(s, say) {
|
|
169
|
+
const observed = await detectPresentPatches(s.builds ?? [], s.cwd, {
|
|
170
|
+
fetchPatch: b => adminArtifact(P.socket, b.artifact_id, tokenFor(b.rid)),
|
|
171
|
+
onError: (b, e) => log(`patch observation for ${b.rid} failed: ${e.message}`),
|
|
172
|
+
});
|
|
173
|
+
if (!observed.length) return;
|
|
174
|
+
s.builds = s.builds.filter(b => !b.observed);
|
|
175
|
+
saveSession(s);
|
|
176
|
+
await say('agent_message_chunk', `worker: patch for ${observed.join(', ')} matches the working tree; no owner decision recorded.\n\n`);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------- the turn
|
|
180
|
+
function currentTurn(s, ctl) { return s.ctl === ctl && s.generation === ctl.generation; }
|
|
181
|
+
function publishPending(s, ctl) {
|
|
182
|
+
if (!currentTurn(s, ctl)) return;
|
|
183
|
+
s.pending = ctl.pending;
|
|
184
|
+
saveSession(s);
|
|
185
|
+
}
|
|
186
|
+
async function runTurn(s, ctl, text, say) {
|
|
187
|
+
const incoming = parsePrompt(text);
|
|
188
|
+
let parsed = incoming;
|
|
189
|
+
const notes = ctl.pending?.notes ?? [];
|
|
190
|
+
if (ctl.pending) {
|
|
191
|
+
const row = await readRowOrThrow(ctl.pending.rid);
|
|
192
|
+
parsed = { brief: withoutNote(row.assignment.brief), requestRoot: ctl.pending.root };
|
|
193
|
+
}
|
|
194
|
+
for (let expiries = 0; ; expiries++) {
|
|
195
|
+
if (ctl.pending) {
|
|
196
|
+
// Attached already (a steer, or T3's continuation prompt after a restart): do not submit; report what was not sent.
|
|
197
|
+
const steerText = text.trim();
|
|
198
|
+
if (steerText && steerText !== CONTINUE_PROMPT && sha256(incoming.brief) !== ctl.pending.briefHash && !ctl.pending.notes.includes(steerText.slice(0, 200))) ctl.pending.notes.push(steerText.slice(0, 200));
|
|
199
|
+
await say('agent_thought_chunk', `re-attached to ${ctl.pending.rid}\n`);
|
|
200
|
+
} else {
|
|
201
|
+
ctl.pending = await acquire(s, parsed);
|
|
202
|
+
ctl.pending.notes = notes;
|
|
203
|
+
await say('agent_thought_chunk', `worker assignment ${ctl.pending.rid}\n`);
|
|
204
|
+
}
|
|
205
|
+
publishPending(s, ctl);
|
|
206
|
+
// A cancel that arrived while acquire was submitting found nothing to cancel; cancel the job it created now.
|
|
207
|
+
if (ctl.cancelled) { ctl.cancelDone = Promise.resolve(ctl.cancelDone).then(() => cancelPending(s, ctl)); return { cancelled: true }; }
|
|
208
|
+
const outcome = await waitLoop(s, ctl, say);
|
|
209
|
+
if (outcome.expired) {
|
|
210
|
+
if (expiries + 1 >= MAX_EXPIRIES) throw refuse(`assignment ${ctl.pending.rid} expired ${MAX_EXPIRIES} times before the worker claimed it`,{failure_type:'expired',failure_type_source:'bridge_observed_transition'});
|
|
211
|
+
await say('agent_thought_chunk', `${ctl.pending.rid} expired unclaimed; resubmitting\n`);
|
|
212
|
+
ctl.pending = null;
|
|
213
|
+
publishPending(s, ctl);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
return outcome;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function heartbeat(s, ctl, say, note = '') {
|
|
221
|
+
let state = '';
|
|
222
|
+
try {
|
|
223
|
+
const r = await call('/owner-states', null, { method: 'POST', payload: { items: [{ id: ctl.pending.rid, capability: tokenFor(ctl.pending.rid) }] } });
|
|
224
|
+
state = r.states?.[0]?.status ?? 'unknown';
|
|
225
|
+
} catch { state = 'bridge unreachable'; }
|
|
226
|
+
const age = Math.round((Date.now() - ctl.pending.startedAt) / 1000);
|
|
227
|
+
await say('agent_thought_chunk', `worker ${state}, ${age < 120 ? `${age} s` : `${Math.round(age / 60)} min`}${note}\n`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Block until the assignment ends. Returns {text}, {blocked,text}, {cancelled} or {expired}; throws on a hard failure.
|
|
231
|
+
async function waitLoop(s, ctl, say) {
|
|
232
|
+
const slice = Math.max(1, Math.ceil(HEARTBEAT_MS / 1000));
|
|
233
|
+
let outageSince = null;
|
|
234
|
+
for (;;) {
|
|
235
|
+
if (ctl.cancelled) return { cancelled: true };
|
|
236
|
+
let r;
|
|
237
|
+
try {
|
|
238
|
+
r = await call(`/wait?id=${encodeURIComponent(ctl.pending.rid)}&timeout=${slice}&peek=1`, ctl.pending.rid, { signal: ctl.abort.signal });
|
|
239
|
+
outageSince = null;
|
|
240
|
+
} catch (e) {
|
|
241
|
+
if (ctl.cancelled) return { cancelled: true };
|
|
242
|
+
if (e.http_status === 409) { await sleep(1000, ctl.abort.signal); continue; } // our previous process's waiter has not detached yet
|
|
243
|
+
if (!transient(e)) throw refuse(`worker bridge error: ${e.message}`,{failure_type:'adapter_error',failure_type_source:'dot_acp_bridge_response'});
|
|
244
|
+
outageSince ??= Date.now();
|
|
245
|
+
if (Date.now() - outageSince > OUTAGE_MS) throw refuse(`worker bridge unreachable for ${Math.round(OUTAGE_MS / 60000)} min: ${e.message}`,{failure_type:'transport_error',failure_type_source:'dot_acp_transport'});
|
|
246
|
+
await say('agent_thought_chunk', `bridge unreachable (${e.message}); retrying\n`);
|
|
247
|
+
await sleep(Math.min(2000, HEARTBEAT_MS), ctl.abort.signal);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
if (r.status === 'timeout') { await heartbeat(s, ctl, say); continue; }
|
|
251
|
+
if (r.status === 'worker_break') { await say('agent_thought_chunk', `worker usage break: ${r.notice ?? ''}\n`); continue; }
|
|
252
|
+
if (r.status === 'blocker' || r.status === 'question') return { blocked: true, text: `[worker ${r.status}] ${r.blocker_text ?? ''}`.trim() };
|
|
253
|
+
if (r.status === 'finished') {
|
|
254
|
+
const row = await readRowOrThrow(ctl.pending.rid), text = await resultText(row);
|
|
255
|
+
trackBuild(s, row);
|
|
256
|
+
return { text };
|
|
257
|
+
}
|
|
258
|
+
if (r.status === 'cancelled') {
|
|
259
|
+
if (ctl.cancelled) return { cancelled: true };
|
|
260
|
+
const row = await readRowOrThrow(ctl.pending.rid);
|
|
261
|
+
if (row.cancelled_reason === 'expired') return { expired: true };
|
|
262
|
+
const rid = ctl.pending.rid;
|
|
263
|
+
ctl.pending = null;
|
|
264
|
+
publishPending(s, ctl);
|
|
265
|
+
throw refuse(`assignment ${rid} was cancelled (not by this session)`,{failure_type:'owner_cancelled',failure_type_source:'bridge_observed_transition'});
|
|
266
|
+
}
|
|
267
|
+
throw refuse(`unexpected wait status ${r.status}`,{failure_type:'adapter_error',failure_type_source:'dot_acp_adapter'});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async function readRowOrThrow(rid) {
|
|
271
|
+
const row = await readRow(rid);
|
|
272
|
+
if (!row) throw refuse(`assignment ${rid} disappeared from the bridge`,{failure_type:'adapter_error',failure_type_source:'dot_acp_bridge_response'});
|
|
273
|
+
return row;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// ---------------------------------------------------------------- agent
|
|
277
|
+
const agent = acp.agent({ name: 'dot-acp', version: '0.1.0' })
|
|
278
|
+
.onRequest(acp.methods.agent.initialize, () => ({
|
|
279
|
+
protocolVersion: acp.PROTOCOL_VERSION,
|
|
280
|
+
agentInfo: { name: 'dot-acp', version: '0.1.0' },
|
|
281
|
+
agentCapabilities: { loadSession: true, promptCapabilities: { image: false, audio: false, embeddedContext: false } },
|
|
282
|
+
authMethods: [],
|
|
283
|
+
}))
|
|
284
|
+
// Free and instant: T3's discovery probe calls this every refresh. Never touches the bridge; params.mcpServers is ignored.
|
|
285
|
+
.onRequest(acp.methods.agent.session.new, ({ params }) => {
|
|
286
|
+
const s = { id: randomUUID(), cwd: params.cwd, model: MODEL, pending: null, ctl: null };
|
|
287
|
+
sessions.set(s.id, s);
|
|
288
|
+
return { sessionId: s.id, configOptions: configOptions(s.model) };
|
|
289
|
+
})
|
|
290
|
+
.onRequest(acp.methods.agent.session.load, ({ params }) => {
|
|
291
|
+
sessionFile(params.sessionId); // validates the id
|
|
292
|
+
const saved = readSession(params.sessionId); // a session without an assignment has no file: it restores empty
|
|
293
|
+
sessions.set(params.sessionId, { id: params.sessionId, cwd: params.cwd ?? saved?.cwd, model: MODEL, pending: saved?.pending ?? null, builds: saved?.builds ?? [], ctl: null });
|
|
294
|
+
return { configOptions: configOptions(MODEL) };
|
|
295
|
+
})
|
|
296
|
+
.onRequest(acp.methods.agent.session.setConfigOption, ({ params }) => {
|
|
297
|
+
const s = sessions.get(params.sessionId);
|
|
298
|
+
if (!s) throw acp.RequestError.invalidParams(null, 'unknown session');
|
|
299
|
+
// T3 lists a `default` slug beside the advertised model, so accept it as the same single model.
|
|
300
|
+
if (params.configId !== 'model' || ![MODEL, 'default'].includes(params.value)) throw acp.RequestError.invalidParams(null, `only model "${MODEL}" exists`);
|
|
301
|
+
return { configOptions: configOptions(MODEL) };
|
|
302
|
+
})
|
|
303
|
+
.onRequest(acp.methods.agent.session.prompt, async ({ params, client }) => {
|
|
304
|
+
const s = sessions.get(params.sessionId);
|
|
305
|
+
if (!s) throw acp.RequestError.invalidParams(null, `unknown session ${params.sessionId}`);
|
|
306
|
+
if (s.ctl) throw acp.RequestError.invalidRequest(null, 'prompt already active');
|
|
307
|
+
const ctl = s.ctl = { abort: new AbortController(), cancelled: false, cancelDone: null, pending: null, generation: s.generation = (s.generation ?? 0) + 1 };
|
|
308
|
+
const say = (type, text) => !currentTurn(s, ctl) ? Promise.resolve() : client.notify(acp.methods.client.session.update, { sessionId: s.id, update: { sessionUpdate: type, content: { type: 'text', text } } }).catch(() => {});
|
|
309
|
+
let lock;
|
|
310
|
+
try {
|
|
311
|
+
lock = await lockSession(s.id);
|
|
312
|
+
// session/load can precede another process finishing; read again under ownership.
|
|
313
|
+
const saved = readSession(s.id);
|
|
314
|
+
ctl.pending = s.pending = saved?.pending ?? null;
|
|
315
|
+
s.builds = saved?.builds ?? s.builds ?? [];
|
|
316
|
+
await reportPresentPatches(s, say);
|
|
317
|
+
if (ctl.cancelled) {
|
|
318
|
+
await Promise.race([cancelPending(s, ctl), sleep(CANCEL_CLEANUP_MS)]);
|
|
319
|
+
return { stopReason: 'cancelled' };
|
|
320
|
+
}
|
|
321
|
+
let outcome;
|
|
322
|
+
// T3 allows 10 s after session/cancel; if acquire or a notification stalls, answer anyway and let runTurn finish
|
|
323
|
+
// in the background (its own cancelled check then cancels any job it created).
|
|
324
|
+
const cancelled = new Promise(r => ctl.abort.signal.addEventListener('abort', () => setTimeout(() => r({ cancelled: true }), CANCEL_BUDGET_MS), { once: true }));
|
|
325
|
+
const turn = runTurn(s, ctl, promptText(params.prompt), say);
|
|
326
|
+
turn.catch(() => {});
|
|
327
|
+
try { outcome = await Promise.race([turn, cancelled]); }
|
|
328
|
+
catch (e) {
|
|
329
|
+
if (ctl.cancelled) outcome = { cancelled: true };
|
|
330
|
+
else if (e instanceof Refusal) {
|
|
331
|
+
const data={};
|
|
332
|
+
for(const key of ['failure_type','failure_type_source','verdict','reasons','bytes']) if(e[key]!==undefined) data[key]=e[key];
|
|
333
|
+
throw refuse(`worker refused: ${e.message}`,data);
|
|
334
|
+
}
|
|
335
|
+
else if (e instanceof acp.RequestError) throw e;
|
|
336
|
+
else throw refuse(`worker adapter error: ${e.message}`,{failure_type:transient(e)?'transport_error':'adapter_error',failure_type_source:'dot_acp_adapter'});
|
|
337
|
+
}
|
|
338
|
+
// Bounded: the 5 s fallback plus at most 2 s here stays inside T3's 10 s cancel window.
|
|
339
|
+
if (outcome.cancelled) { await Promise.race([ctl.cancelDone, sleep(CANCEL_CLEANUP_MS)]); return { stopReason: 'cancelled' }; }
|
|
340
|
+
const notes = ctl.pending.notes.map(n => `\n\nnot sent to the worker: ${n}`).join('');
|
|
341
|
+
await say('agent_message_chunk', outcome.text + notes);
|
|
342
|
+
if (!outcome.blocked) ctl.pending = null; // finished: the next prompt is a new request
|
|
343
|
+
publishPending(s, ctl);
|
|
344
|
+
return { stopReason: 'end_turn' };
|
|
345
|
+
} finally {
|
|
346
|
+
if (currentTurn(s, ctl)) s.ctl = null;
|
|
347
|
+
lock?.release();
|
|
348
|
+
}
|
|
349
|
+
})
|
|
350
|
+
// Answer the pending prompt as cancelled, then cancel the assignment only if no one claimed it. A claimed assignment keeps
|
|
351
|
+
// running and stays retrievable: the next prompt (or a relaunch with the same token) re-attaches.
|
|
352
|
+
.onNotification(acp.methods.agent.session.cancel, ({ params }) => {
|
|
353
|
+
const s = sessions.get(params.sessionId);
|
|
354
|
+
const ctl = s?.ctl;
|
|
355
|
+
if (!ctl || ctl.cancelled) return;
|
|
356
|
+
ctl.cancelled = true;
|
|
357
|
+
ctl.cancelDone = cancelPending(s, ctl);
|
|
358
|
+
ctl.abort.abort();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
async function cancelPending(s, ctl) {
|
|
362
|
+
const pending = ctl.pending;
|
|
363
|
+
if (!pending) return;
|
|
364
|
+
try {
|
|
365
|
+
const r = await Promise.race([call('/cancel-if-queued', pending.rid, { method: 'POST', payload: { id: pending.rid } }), sleep(CANCEL_BUDGET_MS).then(() => null)]);
|
|
366
|
+
// Cancelled here or already (another session on the same token, or the operator): nothing is left to re-attach to.
|
|
367
|
+
if ((r?.cancelled || r?.status === 'cancelled') && ctl.pending === pending) { ctl.pending = null; publishPending(s, ctl); log(`cancelled queued ${pending.rid}`); }
|
|
368
|
+
else log(`cancel left ${pending.rid} ${r?.status ?? 'unknown'}`);
|
|
369
|
+
} catch (e) { log(`cancel-if-queued failed for ${pending.rid}: ${e.message}`); }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// T3 closing our stdin means it is done with this session. Exit without cancelling anything: queued rows expire by
|
|
373
|
+
// valid_until, claimed rows finish and stay retrievable.
|
|
374
|
+
process.stdin.on('end', () => process.exit(0));
|
|
375
|
+
process.stdin.on('close', () => process.exit(0));
|
|
376
|
+
agent.connect(acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
|
|
377
|
+
log('ready');
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Send one ntfy alert through the bridge's configured publisher (~/.config/dot-bridge/alerts.env),
|
|
3
|
+
// so scheduled agents can alert the owner without handling the notification token themselves.
|
|
4
|
+
// Usage: dalan-alert "title" "message"
|
|
5
|
+
import { publishAlert } from '../src/alerts.mjs';
|
|
6
|
+
const [title, message] = process.argv.slice(2);
|
|
7
|
+
if (!title || !message) { console.error('usage: dalan-alert TITLE MESSAGE'); process.exit(2); }
|
|
8
|
+
await publishAlert(title, message, () => {}, { requirePublisher: true });
|
|
9
|
+
console.log('sent');
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readEnv } from '../src/env.mjs';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createDeadmanFromEnv, readDeadmanStatus } from '../src/deadman.mjs';
|
|
7
|
+
|
|
8
|
+
if (Number(process.versions.node.split('.')[0]) < 24) throw new Error('dalan-deadman requires Node 24+');
|
|
9
|
+
|
|
10
|
+
const [command = 'serve', ...args] = process.argv.slice(2);
|
|
11
|
+
const envFile = process.env.DOT_DEADMAN_ENV || path.join(os.homedir(), '.config/dot-deadman/env');
|
|
12
|
+
|
|
13
|
+
function loadEnv() {
|
|
14
|
+
if (!fs.existsSync(envFile)) return;
|
|
15
|
+
if ((fs.statSync(envFile).mode & 0o777) !== 0o600) throw new Error('dead-man env file must be mode 0600');
|
|
16
|
+
for (const line of fs.readFileSync(envFile, 'utf8').split('\n')) {
|
|
17
|
+
const match = line.replace(/\r$/, '').match(/^([A-Z0-9_]+)=(.*)$/);
|
|
18
|
+
if (match && process.env[match[1]] === undefined) {
|
|
19
|
+
let value = match[2];
|
|
20
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
|
|
21
|
+
else if (value.startsWith('"') || value.startsWith("'")) throw new Error('malformed quoted value in dead-man env file');
|
|
22
|
+
process.env[match[1]] = value;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function heartbeat() {
|
|
28
|
+
const file = readEnv('DALAN_HEALTH_FILE');
|
|
29
|
+
const url = process.env.DOT_DEADMAN_URL;
|
|
30
|
+
const token = process.env.DOT_DEADMAN_TOKEN;
|
|
31
|
+
if (!file || !url || !token) throw new Error('heartbeat requires health file, URL, and bearer token');
|
|
32
|
+
if (token.length < 32 || !/^[A-Za-z0-9._~+\/-]+=*$/.test(token)) throw new Error('heartbeat bearer token must contain at least 32 valid bearer characters');
|
|
33
|
+
const target = new URL(url);
|
|
34
|
+
if (target.username || target.password) throw new Error('heartbeat URL must not contain credentials');
|
|
35
|
+
if (target.protocol !== 'https:' && !(target.protocol === 'http:' && ['127.0.0.1', 'localhost', '::1', '[::1]'].includes(target.hostname))) throw new Error('remote heartbeat URL must use HTTPS');
|
|
36
|
+
if (target.search || target.hash) throw new Error('heartbeat base URL cannot include a query or fragment');
|
|
37
|
+
const health = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
38
|
+
const observed = Date.parse(health.observed_at);
|
|
39
|
+
if (health.healthy !== true || !Number.isFinite(observed) || Date.now() - observed > 90_000 || observed > Date.now() + 30_000) {
|
|
40
|
+
throw new Error('bridge health evidence is absent, unhealthy, or stale');
|
|
41
|
+
}
|
|
42
|
+
target.pathname = `${target.pathname.replace(/\/+$/, '')}/heartbeat`;
|
|
43
|
+
const response = await fetch(target, {
|
|
44
|
+
method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
45
|
+
body: JSON.stringify({ healthy: true }), redirect: 'error', signal: AbortSignal.timeout(5000)
|
|
46
|
+
});
|
|
47
|
+
if (response.status !== 202) throw new Error(`heartbeat rejected with HTTP ${response.status}`);
|
|
48
|
+
console.log('heartbeat accepted');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
loadEnv();
|
|
53
|
+
if (command === 'heartbeat') await heartbeat();
|
|
54
|
+
else if(command==='status') {
|
|
55
|
+
if(args.length)throw new Error('usage: dalan-deadman status');
|
|
56
|
+
const dbFile=process.env.DOT_DEADMAN_DB||'/var/lib/dot-deadman/deadman.sqlite';
|
|
57
|
+
console.log(JSON.stringify(readDeadmanStatus(dbFile),null,2));
|
|
58
|
+
}
|
|
59
|
+
else if(command==='reconcile') {
|
|
60
|
+
if(args.length!==5||!['initial','reminder'].includes(args[1])||!['sent','unsent'].includes(args[2])||args[3]!=='--evidence')
|
|
61
|
+
throw new Error('usage: dalan-deadman reconcile EPISODE initial|reminder sent|unsent --evidence RECEIPT');
|
|
62
|
+
const episodeId=Number(args[0]);
|
|
63
|
+
const port=Number(process.env.DOT_DEADMAN_PORT||8788);
|
|
64
|
+
if(!Number.isInteger(port)||port<1||port>65535)throw new Error('invalid dead-man service port');
|
|
65
|
+
const response=await fetch(`http://127.0.0.1:${port}/reconcile`,{
|
|
66
|
+
method:'POST',headers:{Authorization:`Bearer ${process.env.DOT_DEADMAN_TOKEN||''}`,'Content-Type':'application/json'},
|
|
67
|
+
body:JSON.stringify({episodeId,phase:args[1],outcome:args[2],receipt:args[4]}),signal:AbortSignal.timeout(5000)
|
|
68
|
+
});
|
|
69
|
+
if(!response.ok)throw new Error(response.status===409?'owning publisher has not settled this publication':'owning dead-man service is unavailable');
|
|
70
|
+
console.log(JSON.stringify(await response.json()));
|
|
71
|
+
}
|
|
72
|
+
else if (command === 'serve') {
|
|
73
|
+
const monitor = createDeadmanFromEnv();
|
|
74
|
+
const address = await monitor.start({ host: process.env.DOT_DEADMAN_HOST || '127.0.0.1', port: Number(process.env.DOT_DEADMAN_PORT || 8788) });
|
|
75
|
+
console.log(`dead-man listening on ${typeof address === 'object' ? `${address.address}:${address.port}` : address}`);
|
|
76
|
+
const stop = async () => { await monitor.close(); process.exit(0); };
|
|
77
|
+
process.once('SIGTERM', stop); process.once('SIGINT', stop);
|
|
78
|
+
} else throw new Error('usage: dalan-deadman [serve|heartbeat|status|reconcile]');
|
|
79
|
+
} catch (error) {
|
|
80
|
+
console.error(`dalan-deadman: ${error.message}`);
|
|
81
|
+
process.exitCode = 1;
|
|
82
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { defaultPath } from '../src/paths.mjs';
|
|
3
|
+
import { readEnv } from '../src/env.mjs';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { execFile } from 'node:child_process';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { bridgeHealth } from '../src/host-health.mjs';
|
|
11
|
+
|
|
12
|
+
const root = defaultPath(os.homedir(),'.local/share/dot-bridge');
|
|
13
|
+
const healthFile = readEnv('DALAN_HEALTH_FILE') || path.join(root, 'health.json');
|
|
14
|
+
const temporary = `${healthFile}.${process.pid}`;
|
|
15
|
+
try {
|
|
16
|
+
const health = await bridgeHealth({ socketPath: path.join(root, 'admin.sock'), drainerFile: readEnv('DALAN_DRAINER_HEALTH_FILE') });
|
|
17
|
+
fs.writeFileSync(temporary, JSON.stringify(health) + '\n', { mode: 0o600 });
|
|
18
|
+
fs.renameSync(temporary, healthFile);
|
|
19
|
+
const { stdout } = await promisify(execFile)(process.execPath, [fileURLToPath(new URL('./dot-deadman.mjs', import.meta.url)), 'heartbeat'], {
|
|
20
|
+
env: { ...process.env, DOT_BRIDGE_HEALTH_FILE: healthFile }, timeout: 10000,
|
|
21
|
+
});
|
|
22
|
+
process.stdout.write(stdout);
|
|
23
|
+
} catch {
|
|
24
|
+
fs.rmSync(temporary, { force: true });
|
|
25
|
+
// Remove stale positive evidence; a failed local check must not ping externally.
|
|
26
|
+
fs.rmSync(healthFile, { force: true });
|
|
27
|
+
console.error('dalan-heartbeat: health check or external heartbeat failed');
|
|
28
|
+
process.exitCode = 1;
|
|
29
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Submit one read-only review per open PR head that has no worker review yet. Deterministic; see docs/pr-head-reviewer.md.
|
|
3
|
+
import { loadConfig, realDeps, run, acquireLock, paths, parseOnly } from '../src/pr-head-reviewer.mjs';
|
|
4
|
+
|
|
5
|
+
const usage = `usage: dalan-pr-reviewer [--dry-run] [--only OWNER/REPO#N] [--max N] [--ignore-capacity] [--config FILE] [--state-dir DIR]
|
|
6
|
+
--dry-run print what would be submitted; submit and write nothing
|
|
7
|
+
--only OWNER/REPO#N consider only that PR (still deduped and gated)
|
|
8
|
+
--max N submit at most N this run (default: config max_submits_per_run)
|
|
9
|
+
--ignore-capacity with --dry-run only: preview candidates even when no lane is free`;
|
|
10
|
+
const args = process.argv.slice(2), has = f => args.includes(f), opt = f => { const i = args.indexOf(f); return i < 0 ? null : args[i + 1]; };
|
|
11
|
+
try {
|
|
12
|
+
const known = new Set(['--dry-run', '--only', '--max', '--ignore-capacity', '--config', '--state-dir', '--help']);
|
|
13
|
+
const values = new Set(['--only', '--max', '--config', '--state-dir']);
|
|
14
|
+
for (let i = 0; i < args.length; i++) { if (!known.has(args[i])) throw new Error(`unknown argument ${args[i]}`); if (values.has(args[i])) i++; }
|
|
15
|
+
if (has('--help')) { console.log(usage); process.exit(0); }
|
|
16
|
+
const dryRun = has('--dry-run');
|
|
17
|
+
if (has('--ignore-capacity') && !dryRun) throw new Error('--ignore-capacity requires --dry-run');
|
|
18
|
+
let only = null;
|
|
19
|
+
// A present --only with a missing or malformed value must fail, never fall through to every open PR.
|
|
20
|
+
if (args.includes('--only')) only = parseOnly(opt('--only'));
|
|
21
|
+
const max = opt('--max') === null ? null : Number(opt('--max'));
|
|
22
|
+
if (max !== null && !(Number.isInteger(max) && max >= 0)) throw new Error('--max expects a non-negative integer');
|
|
23
|
+
const cfg = loadConfig(opt('--config') ?? paths.config), stateDir = opt('--state-dir') ?? paths.stateDir;
|
|
24
|
+
const release = dryRun ? () => {} : acquireLock(stateDir);
|
|
25
|
+
if (!release) { console.error('dalan-pr-reviewer: another run is active'); process.exit(0); }
|
|
26
|
+
try {
|
|
27
|
+
await run({ cfg, deps: realDeps(cfg), stateDir, dryRun, only, maxSubmits: max, ignoreCapacity: has('--ignore-capacity'), print: line => console.log(line) });
|
|
28
|
+
} finally { release(); }
|
|
29
|
+
} catch (error) {
|
|
30
|
+
console.error(`dalan-pr-reviewer: ${error.message}`);
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|