@tnunamak/dalan 0.0.0-stage → 0.6.0
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 +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -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 +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -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 +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -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 +67 -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/dalan-try-selfcheck.mjs +29 -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 +418 -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 +538 -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/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -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-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -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 +79 -0
- package/src/mcp-sse.mjs +62 -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/process-inspection.mjs +36 -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/pull-queue.mjs +159 -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/route-setting.mjs +24 -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 +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -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 +3069 -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 +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -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 +632 -0
- package/src/workspace.mjs +1065 -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,272 @@
|
|
|
1
|
+
import { defaultPath } from '../../src/paths.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
export const REPO = fileURLToPath(new URL('../..', import.meta.url));
|
|
12
|
+
export const MANIFEST_NAME = 'live-trial.json';
|
|
13
|
+
export const RESOURCE_URL_FILE = 'resource-url';
|
|
14
|
+
export const JOBS_FILE = 'jobs.json';
|
|
15
|
+
export const MANIFEST_PATH = home => path.join(home, MANIFEST_NAME);
|
|
16
|
+
export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
17
|
+
|
|
18
|
+
export function parseArgs(argv, { values = [], flags = [] } = {}) {
|
|
19
|
+
const valueNames = new Set(values);
|
|
20
|
+
const flagNames = new Set(flags);
|
|
21
|
+
const result = { _: [] };
|
|
22
|
+
for (let i = 0; i < argv.length; i++) {
|
|
23
|
+
const raw = argv[i];
|
|
24
|
+
const equals = raw.indexOf('=');
|
|
25
|
+
const name = equals < 0 ? raw : raw.slice(0, equals);
|
|
26
|
+
if (valueNames.has(name)) {
|
|
27
|
+
const value = equals < 0 ? argv[++i] : raw.slice(equals + 1);
|
|
28
|
+
if (!value || value.startsWith('--')) throw new Error(`${name} requires a value`);
|
|
29
|
+
result[name] = value;
|
|
30
|
+
} else if (flagNames.has(name)) {
|
|
31
|
+
if (equals >= 0) throw new Error(`${name} does not take a value`);
|
|
32
|
+
result[name] = true;
|
|
33
|
+
} else if (raw.startsWith('--')) {
|
|
34
|
+
throw new Error(`unknown option ${name}`);
|
|
35
|
+
} else {
|
|
36
|
+
result._.push(raw);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function writeJsonPrivate(file, value) {
|
|
43
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
44
|
+
fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
45
|
+
fs.chmodSync(file, 0o600);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function readJson(file, what = 'JSON file') {
|
|
49
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
50
|
+
catch { throw new Error(`${what} is missing or invalid`); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function readManifest(home) {
|
|
54
|
+
const absoluteHome = path.resolve(home);
|
|
55
|
+
const manifest = readJson(MANIFEST_PATH(absoluteHome), 'trial manifest');
|
|
56
|
+
if (manifest.schema_version !== 1 || manifest.kind !== 'dot-bridge-live-trial' || manifest.home !== absoluteHome) {
|
|
57
|
+
throw new Error('trial manifest does not own this home');
|
|
58
|
+
}
|
|
59
|
+
if (!Array.isArray(manifest.pids) || !manifest.pids.every(Number.isInteger)) throw new Error('trial manifest has invalid process ids');
|
|
60
|
+
if (manifest.resource_url_file !== RESOURCE_URL_FILE) throw new Error('trial manifest has an invalid resource URL file');
|
|
61
|
+
return manifest;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function resourceUrlFromManifest(manifest) {
|
|
65
|
+
if (manifest.resource_url_file !== RESOURCE_URL_FILE) {
|
|
66
|
+
throw new Error('trial manifest has an invalid resource URL file');
|
|
67
|
+
}
|
|
68
|
+
let value;
|
|
69
|
+
const file = path.join(manifest.home, RESOURCE_URL_FILE);
|
|
70
|
+
try {
|
|
71
|
+
if ((fs.statSync(file).mode & 0o777) !== 0o600) throw new Error('wrong mode');
|
|
72
|
+
value = fs.readFileSync(file, 'utf8').trim();
|
|
73
|
+
}
|
|
74
|
+
catch { throw new Error('private resource URL file is missing or unreadable'); }
|
|
75
|
+
let parsed;
|
|
76
|
+
try { parsed = new URL(value); }
|
|
77
|
+
catch { throw new Error('private resource URL file is invalid'); }
|
|
78
|
+
const issuer = new URL(manifest.public_url);
|
|
79
|
+
if (parsed.origin !== issuer.origin || parsed.search || parsed.hash || parsed.username || parsed.password
|
|
80
|
+
|| !/^\/[a-f0-9]{64}\/mcp$/.test(parsed.pathname)) {
|
|
81
|
+
throw new Error('private resource URL does not match the trial issuer');
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function readJobs(manifest) {
|
|
87
|
+
if (!manifest.jobs_file) throw new Error('no trial jobs have been submitted');
|
|
88
|
+
const jobs = readJson(path.join(manifest.home, manifest.jobs_file), 'trial job state');
|
|
89
|
+
if (jobs.worker !== manifest.worker || !jobs.worker_request_id || !jobs.dot_request_id || !jobs.nonce) {
|
|
90
|
+
throw new Error('trial job state is invalid');
|
|
91
|
+
}
|
|
92
|
+
return jobs;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function runDot(home, args, { input, timeout = 30_000, env = {} } = {}) {
|
|
96
|
+
const result = spawnSync(process.execPath, [path.join(REPO, 'bin/dalan.mjs'), ...args], {
|
|
97
|
+
cwd: REPO,
|
|
98
|
+
env: { HOME: home, PATH: process.env.PATH ?? '', ...env },
|
|
99
|
+
input,
|
|
100
|
+
encoding: 'utf8',
|
|
101
|
+
timeout,
|
|
102
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
103
|
+
});
|
|
104
|
+
return { status: result.status, error: result.error, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function dotJson(home, args, options = {}) {
|
|
108
|
+
const result = runDot(home, args, options);
|
|
109
|
+
if (result.error || result.status !== 0) throw new Error(`dalan ${args[0] ?? 'command'} failed`);
|
|
110
|
+
try { return JSON.parse(result.stdout); }
|
|
111
|
+
catch { throw new Error(`dalan ${args[0] ?? 'command'} returned invalid JSON`); }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function fileList(root) {
|
|
115
|
+
const files = [];
|
|
116
|
+
const visit = current => {
|
|
117
|
+
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
|
|
118
|
+
const absolute = path.join(current, entry.name);
|
|
119
|
+
const relative = path.relative(root, absolute);
|
|
120
|
+
files.push(relative);
|
|
121
|
+
if (entry.isDirectory()) visit(absolute);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
visit(root);
|
|
125
|
+
return files.sort();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function bridgeSecret(home) {
|
|
129
|
+
const envFile = defaultPath(home,'.config/dot-bridge/env');
|
|
130
|
+
const contents = fs.readFileSync(envFile, 'utf8');
|
|
131
|
+
const secret = /^BRIDGE_PATH_SECRET=([a-f0-9]{64})$/m.exec(contents)?.[1];
|
|
132
|
+
if (!secret) throw new Error('bridge path secret is missing or invalid');
|
|
133
|
+
return secret;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function localMcpPath(manifest) {
|
|
137
|
+
const publicUrl = new URL(manifest.public_url);
|
|
138
|
+
const resourceUrl = new URL(resourceUrlFromManifest(manifest));
|
|
139
|
+
return { path: resourceUrl.pathname, host: publicUrl.host };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Always connects to 127.0.0.1. The Host header is the configured issuer host so the
|
|
143
|
+
// built-in AS keeps its canonical-host check when a future operator uses a reverse proxy.
|
|
144
|
+
export async function mcpRpc(manifest, bearer, method, params = {}) {
|
|
145
|
+
const endpoint = localMcpPath(manifest);
|
|
146
|
+
const body = JSON.stringify({ jsonrpc: '2.0', id: randomUUID(), method, params });
|
|
147
|
+
return await new Promise((resolve, reject) => {
|
|
148
|
+
const req = http.request({
|
|
149
|
+
host: '127.0.0.1',
|
|
150
|
+
port: manifest.port,
|
|
151
|
+
path: endpoint.path,
|
|
152
|
+
method: 'POST',
|
|
153
|
+
headers: {
|
|
154
|
+
host: endpoint.host,
|
|
155
|
+
accept: 'application/json, text/event-stream',
|
|
156
|
+
'content-type': 'application/json',
|
|
157
|
+
'content-length': Buffer.byteLength(body),
|
|
158
|
+
...(bearer ? { authorization: `Bearer ${bearer}` } : {}),
|
|
159
|
+
},
|
|
160
|
+
timeout: 5_000,
|
|
161
|
+
}, response => {
|
|
162
|
+
let text = '';
|
|
163
|
+
response.setEncoding('utf8');
|
|
164
|
+
response.on('data', chunk => { text += chunk; });
|
|
165
|
+
response.on('end', () => {
|
|
166
|
+
let parsed = null;
|
|
167
|
+
try { parsed = text ? JSON.parse(text) : null; } catch { /* returned as a null body */ }
|
|
168
|
+
resolve({ status: response.statusCode, body: parsed });
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
req.on('timeout', () => req.destroy(new Error('loopback MCP request timed out')));
|
|
172
|
+
req.on('error', reject);
|
|
173
|
+
req.end(body);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function mcpTool(manifest, bearer, name, args = {}) {
|
|
178
|
+
const response = await mcpRpc(manifest, bearer, 'tools/call', { name, arguments: args });
|
|
179
|
+
if (response.status !== 200) return { status: response.status, isError: true, value: null, text: '' };
|
|
180
|
+
const result = response.body?.result;
|
|
181
|
+
const text = result?.content?.find(item => item.type === 'text')?.text ?? '';
|
|
182
|
+
let value = null;
|
|
183
|
+
try { value = text ? JSON.parse(text) : null; } catch { /* the caller can check isError */ }
|
|
184
|
+
return { status: response.status, isError: result?.isError === true, value, text };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function freeLoopbackPort() {
|
|
188
|
+
const server = net.createServer();
|
|
189
|
+
await new Promise((resolve, reject) => {
|
|
190
|
+
server.once('error', reject);
|
|
191
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
192
|
+
});
|
|
193
|
+
const port = server.address().port;
|
|
194
|
+
await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
195
|
+
return port;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
export async function isLoopbackPortClosed(port) {
|
|
199
|
+
return await new Promise(resolve => {
|
|
200
|
+
const socket = net.createConnection({ host: '127.0.0.1', port });
|
|
201
|
+
let done = false;
|
|
202
|
+
const finish = closed => {
|
|
203
|
+
if (done) return;
|
|
204
|
+
done = true;
|
|
205
|
+
socket.destroy();
|
|
206
|
+
resolve(closed);
|
|
207
|
+
};
|
|
208
|
+
socket.setTimeout(1_000, () => finish(false));
|
|
209
|
+
socket.once('connect', () => finish(false));
|
|
210
|
+
socket.once('error', error => finish(error.code === 'ECONNREFUSED'));
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function processExists(pid, kill = process.kill) {
|
|
215
|
+
try {
|
|
216
|
+
kill(pid, 0);
|
|
217
|
+
return true;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
if (error.code === 'ESRCH') return false;
|
|
220
|
+
throw new Error(`could not inspect process ${pid} liveness (${error.code ?? 'unknown'})`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function processCommand(pid, { kill = process.kill, spawn = spawnSync } = {}) {
|
|
225
|
+
if (!processExists(pid, kill)) return null;
|
|
226
|
+
const result = spawn('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf8', timeout: 2_000, maxBuffer: 8_192 });
|
|
227
|
+
if (result.error || result.status !== 0) {
|
|
228
|
+
// ps can race with process exit. Only the kernel liveness check can prove it is gone.
|
|
229
|
+
if (!processExists(pid, kill)) return null;
|
|
230
|
+
throw new Error(`could not inspect process ${pid} command (${result.error?.code ?? `exit ${result.status ?? 'unknown'}`})`);
|
|
231
|
+
}
|
|
232
|
+
const command = (result.stdout ?? '').trim();
|
|
233
|
+
if (!command) throw new Error(`could not inspect process ${pid} command (empty result)`);
|
|
234
|
+
return command;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function assertLoopbackListener(pid, port) {
|
|
238
|
+
const result = spawnSync('lsof', ['-nP', '-a', '-p', String(pid), `-iTCP:${port}`, '-sTCP:LISTEN', '-Fn'], {
|
|
239
|
+
encoding: 'utf8', timeout: 2_000, maxBuffer: 8_192,
|
|
240
|
+
});
|
|
241
|
+
if (result.error || result.status !== 0) throw new Error('could not prove the bridge listener belongs to its manifest process');
|
|
242
|
+
|
|
243
|
+
const processes = (result.stdout ?? '').split('\n').filter(line => line.startsWith('p')).map(line => line.slice(1));
|
|
244
|
+
const listeners = (result.stdout ?? '').split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1));
|
|
245
|
+
if (processes.length !== 1 || processes[0] !== String(pid)
|
|
246
|
+
|| listeners.length !== 1 || listeners[0] !== `127.0.0.1:${port}`) {
|
|
247
|
+
throw new Error('bridge listener is not exclusively bound to 127.0.0.1 by its manifest process');
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function manifestProcessAlive(manifest) {
|
|
252
|
+
return manifest.pids.some(pid => processCommand(pid)?.includes(manifest.process_title) ?? false);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export async function waitForManifestProcesses(manifest, timeoutMs = 10_000) {
|
|
256
|
+
const end = Date.now() + timeoutMs;
|
|
257
|
+
while (Date.now() < end) {
|
|
258
|
+
if (!manifestProcessAlive(manifest)) return true;
|
|
259
|
+
await sleep(100);
|
|
260
|
+
}
|
|
261
|
+
return !manifestProcessAlive(manifest);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export async function readStdin() {
|
|
265
|
+
const chunks = [];
|
|
266
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
267
|
+
return Buffer.concat(chunks).toString('utf8').trim();
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function trialHome(worker, suffix = randomUUID().slice(0, 8)) {
|
|
271
|
+
return path.resolve(os.homedir(), '.tmp', `live-trial-${worker}-${Date.now()}-${suffix}`);
|
|
272
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
import { domainToASCII } from 'node:url';
|
|
3
|
+
|
|
4
|
+
export function endpoint(name, value, { loopbackHttp = false, base = false } = {}) {
|
|
5
|
+
let url;
|
|
6
|
+
try { url = new URL(value); } catch { throw new Error(`${name} must be a valid HTTPS URL`); }
|
|
7
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
8
|
+
if (value !== value.trim() || (url.protocol !== 'https:' && !(loopbackHttp && loopback && url.protocol === 'http:')) ||
|
|
9
|
+
url.username || url.password || url.hash || (base && url.search)) throw new Error(`${name} must be a valid HTTPS URL without credentials, query or fragment`);
|
|
10
|
+
return url;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function hostname(name, value) {
|
|
14
|
+
const ascii = domainToASCII(value);
|
|
15
|
+
if (value !== value.trim() || (!isIP(value) && (!ascii || ascii.length > 253 || !ascii.split('.').every(label => /^(?!-)[a-z0-9-]{1,63}(?<!-)$/i.test(label)))))
|
|
16
|
+
throw new Error(`${name} must be a hostname or IP address without a port or path`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function appendPath(url, suffix) {
|
|
20
|
+
const result = new URL(url);
|
|
21
|
+
result.pathname = result.pathname.replace(/\/+$/, '') + suffix;
|
|
22
|
+
return result.href;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function protectedResourceMetadataUrl(resource) {
|
|
26
|
+
const result = new URL(resource);
|
|
27
|
+
result.pathname = '/.well-known/oauth-protected-resource' + (result.pathname === '/' ? '' : result.pathname);
|
|
28
|
+
return result.href;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// RFC 9728 authorization_servers is an array of issuer identifiers. A string must be
|
|
32
|
+
// refused: String.prototype.includes would accept any value that merely contains the issuer.
|
|
33
|
+
export function listsIssuer(metadata, issuer) {
|
|
34
|
+
return Array.isArray(metadata?.authorization_servers) && metadata.authorization_servers.includes(issuer);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function fetchProbe(name, url, options = {}) {
|
|
38
|
+
const response = await fetch(url, { ...options, redirect: 'manual' });
|
|
39
|
+
if (response.status >= 300 && response.status < 400) {
|
|
40
|
+
await response.body?.cancel();
|
|
41
|
+
throw Object.assign(new Error(`${name} probe must not redirect`), { targetValidation: true, probeRedirect: true });
|
|
42
|
+
}
|
|
43
|
+
return response;
|
|
44
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {spawnSync} from 'node:child_process';
|
|
3
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
4
|
+
|
|
5
|
+
const recovery='If the old service is paused, keep it running. Let workers finish or wait for their leases to expire, run `dalan resume` under the old HOME, then retry this drain.';
|
|
6
|
+
async function main() {
|
|
7
|
+
const timeoutMs=Number(process.env.DALAN_UPGRADE_DRAIN_TIMEOUT_MS??300000);
|
|
8
|
+
if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1000)throw new Error('DALAN_UPGRADE_DRAIN_TIMEOUT_MS must be an integer of at least 1000');
|
|
9
|
+
const deadline=Date.now()+timeoutMs;
|
|
10
|
+
const fail=message=>{throw new Error(message);};
|
|
11
|
+
const cli=(...args)=>{
|
|
12
|
+
const remaining=deadline-Date.now();
|
|
13
|
+
if(remaining<=0)fail(`Upgrade drain timed out during ${args[0]}.`);
|
|
14
|
+
const result=spawnSync(process.execPath,['bin/dot-worker.mjs',...args,'--json'],{encoding:'utf8',timeout:remaining,killSignal:'SIGKILL'});
|
|
15
|
+
if(result.error?.code==='ETIMEDOUT')fail(`Upgrade drain timed out during ${args[0]}.`);
|
|
16
|
+
if(result.status!==0)fail(`dalan ${args[0]} failed: ${(result.stderr||result.stdout||`exit ${result.status}`).trim()}.`);
|
|
17
|
+
try { return JSON.parse(result.stdout); } catch { fail(`dalan ${args[0]} printed no JSON.`); }
|
|
18
|
+
};
|
|
19
|
+
cli('pause','--reason','upgrade drain');
|
|
20
|
+
console.log('Claims paused. New submissions are still accepted while the drain waits.');
|
|
21
|
+
while(true) {
|
|
22
|
+
const {claims=[]}=cli('claims');
|
|
23
|
+
const open=claims.filter(claim=>{
|
|
24
|
+
const expiry=Date.parse(claim.lease_expires_at);
|
|
25
|
+
return !Number.isFinite(expiry)||expiry>Date.now();
|
|
26
|
+
});
|
|
27
|
+
if(!open.length)break;
|
|
28
|
+
for(const claim of open)console.log(`Waiting for ${claim.request_id}; lease expires ${claim.lease_expires_at}.`);
|
|
29
|
+
if(Date.now()>=deadline)fail('Upgrade drain timed out while claims were still active.');
|
|
30
|
+
await delay(Math.min(1000,Math.max(50,deadline-Date.now())));
|
|
31
|
+
}
|
|
32
|
+
console.log('No unexpired claims remain. An expired lease revokes its old claim ID but does not prove its process stopped; the new service will sweep the row back to the queue, where the claimant can resume the work only with a fresh claim epoch after stopping the old run.');
|
|
33
|
+
console.log('Stop the old service, update the code, start the new service with the same HOME and configuration, then run `dalan resume` to release the persisted pause.');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
main().catch(error=>{
|
|
37
|
+
console.error(`${error?.message??String(error)}\n${recovery}`);
|
|
38
|
+
process.exitCode=1;
|
|
39
|
+
});
|