@tnunamak/dalan 0.5.2 → 0.6.1
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 +37 -25
- package/PROTOCOL.md +16 -4
- package/README.md +127 -260
- package/SECURITY.md +1 -1
- package/bin/dalan.mjs +5 -0
- package/bin/dot-worker.mjs +35 -26
- package/docs/chatgpt-worker-onboarding.md +5 -5
- package/docs/claude-worker-onboarding.md +5 -5
- package/docs/codex-to-muse.md +181 -0
- package/docs/connect-chatgpt.md +9 -4
- package/docs/connection-longevity.md +7 -1
- package/docs/dalan-upgrade.md +18 -14
- package/docs/deadman.md +5 -3
- package/docs/local-agent-mcp.md +8 -6
- package/docs/manual-setup.md +8 -8
- package/docs/mirror-fetch.md +1 -2
- package/docs/operations.md +90 -42
- package/docs/operator-duties.md +1 -1
- package/docs/owner-integrator.md +2 -2
- package/docs/portable-auth-profile.md +12 -14
- package/docs/pr-head-reviewer.md +21 -5
- package/docs/pr-preflight.md +2 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +7 -10
- package/docs/redaction.md +1 -1
- package/docs/service-setup.md +56 -3
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +3 -1
- package/docs/t3-result-retry-delivery.md +2 -2
- package/docs/t3-reverse-control.md +7 -7
- package/docs/usage.md +19 -15
- package/docs/worker-clients.md +18 -13
- package/package.json +3 -1
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +1 -1
- package/scripts/worker-bridge-setup.mjs +1 -1
- package/src/acp-bridge.mjs +18 -12
- package/src/as.mjs +41 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/cli-help.mjs +25 -11
- package/src/demo-worker.mjs +2 -2
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +20 -3
- package/src/mcp-outcome.mjs +10 -1
- package/src/mcp-sse.mjs +62 -0
- package/src/pr-head-reviewer.mjs +3 -3
- package/src/process-inspection.mjs +36 -0
- package/src/pull-queue.mjs +159 -0
- package/src/route-setting.mjs +24 -0
- package/src/server.mjs +157 -29
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +423 -0
- package/src/setup.mjs +63 -0
- package/src/store.mjs +21 -9
- package/src/tool-registry.mjs +3 -1
- package/src/try-exposure.mjs +918 -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 +63 -17
- package/src/workers.mjs +33 -23
- package/src/workspace.mjs +10 -3
package/src/cli-help.mjs
CHANGED
|
@@ -6,16 +6,30 @@ import { docsUrl } from './docs-url.mjs';
|
|
|
6
6
|
// commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
|
|
7
7
|
// `dalan help --internal`. Every command runs and has its own help either way.
|
|
8
8
|
export const COMMANDS = [
|
|
9
|
-
{ name: 'try', group: 'start', summary: '
|
|
10
|
-
detail: ['
|
|
11
|
-
'
|
|
12
|
-
'With
|
|
13
|
-
'Options:', ' --
|
|
14
|
-
'
|
|
15
|
-
|
|
9
|
+
{ name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...',
|
|
10
|
+
detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client such as ChatGPT or claude.ai (the default). `auto` honors a saved temporary-relay choice; otherwise it uses a usable Tailscale route and selects Gozar if no Tailscale route is usable. When it selects Gozar, Dalan names tunnl.gg, links its terms and privacy notice, and asks for consent before exposure. After consent, bundled Gozar creates an installation-owned key and opens the temporary demo link through tunnl.gg. Dalan never uses your SSH keys. The relay ends TLS and can see the connector URL and traffic; the link can stop or change without warning, including within minutes.',
|
|
11
|
+
'Dalan checks the original public address and ends the trial when it detects a change or route loss. The trial itself ends after 3 hours at most. Ctrl-C stops the run; Dalan closes its forwarding gate and attempts to remove its route. If cleanup cannot be confirmed, it reports this and prints a recovery command. Keep private work out of the demo. A Tailscale route is separate from the temporary relay. Choose this computer only, or pass --local, for a',
|
|
12
|
+
'self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
|
|
13
|
+
'Options:', ' --local this computer only', ' --public public trial with the chatgpt or claude sign-in profile (other clients: see Connect any MCP worker in the README)', ' --client NAME chatgpt (default) or claude; implies --public',
|
|
14
|
+
'', 'When `auto` selects Gozar because a temporary-relay choice was saved or Tailscale is unavailable, Gozar supplies the tunnl.gg key-bound relay; Dalan keeps OAuth sign-in and identity checks. After consent, Gozar creates a private key for this installation. Dalan does not use your SSH keys. Gozar is bundled; no separate install is needed.',
|
|
15
|
+
' --route NAME auto (saved temporary-relay choice, otherwise usable Tailscale, then bundled Gozar with relay consent), gozar, localhost.run or tailscale; implies --public', ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
|
|
16
|
+
' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
|
|
17
|
+
'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a public trial creates a new home, and a usable Tailscale route on this computer uses ~/.local/share/dalan-hosted-<client>. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
|
|
18
|
+
{ name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
|
|
19
|
+
detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
|
|
20
|
+
'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
|
|
21
|
+
{ name: 'service', group: 'operator', summary: 'Install or migrate a long-running bridge service', usage: 'dalan service install|migrate-workers [options]',
|
|
22
|
+
detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
|
|
23
|
+
'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]',
|
|
24
|
+
'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
|
|
25
|
+
'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
|
|
26
|
+
'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
|
|
27
|
+
'See docs/service-setup.md for routing and worker migration details.'] },
|
|
28
|
+
{ name: 'init', group: 'start', summary: 'Create a bridge home and its first worker profile', usage: 'dalan init --public-url URL (--worker NAME [--enable-workspace] | --legacy) [--json]',
|
|
29
|
+
|
|
16
30
|
detail: ['Writes the built-in authorization server files and the first worker profile into the bridge home (DALAN_HOME).', 'It needs no running bridge.', '',
|
|
17
31
|
'Options:', ' --public-url URL the address clients will use to reach the bridge: https://HOST, or',
|
|
18
|
-
' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
|
|
32
|
+
' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --enable-workspace allow this worker to use repository tools when the bridge enables them', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
|
|
19
33
|
'Example (a bridge on this computer only):', ' export DALAN_HOME="$HOME/.local/share/dalan-manual-trial"', ' export DALAN_LOOPBACK=1', ' dalan init --worker local --public-url http://127.0.0.1:8799'] },
|
|
20
34
|
{ name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
|
|
21
35
|
detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
|
|
@@ -24,10 +38,10 @@ export const COMMANDS = [
|
|
|
24
38
|
' add-client --redirect-uri URI [--name NAME] [--json] register an OAuth client', ' clients [--json] list OAuth clients', ' remove-client CLIENT_ID [--json] remove an OAuth client',
|
|
25
39
|
' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
|
|
26
40
|
'Examples (pair a worker named local):', ' dalan connect start --worker local', ' dalan connect pending', ' dalan connect approve CODE --worker local --confirm-redirect URI',
|
|
27
|
-
'Replace CODE with the code that pending and the browser page both show,
|
|
41
|
+
'Replace CODE with the code that pending and the browser page both show.', 'For URI, use the callback you expect from your client\'s own configuration and compare it', 'with pending: do not approve when they differ or you cannot verify it.'] },
|
|
28
42
|
{ name: 'submit', group: 'everyday', summary: 'Queue a job for a worker', usage: 'dalan submit (--file PATH | --stdin | --brief TEXT) [options]',
|
|
29
43
|
detail: ['Queues a job. Give it a JSON assignment (request_id, inputs, brief, ...) or, with --brief, plain text for a question that needs no files.', 'Prints the request ID.', '',
|
|
30
|
-
'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
|
|
44
|
+
'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --eligible LIST route one read-only result to explicit workers; job needs valid_until', ' --policy PATH JSON routing policy and optional destination_revisions', ` pool setup and worker flow: ${docsUrl('docs/pull-queue.md')}`, ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
|
|
31
45
|
' --thread ID deliver the result to a T3 Code thread (optional integration)', ' --deliver none|t3:ID delivery target (default: none; not with --thread)', ' --review ask for a review of work already done',
|
|
32
46
|
' --wait wait for the result before returning', ' --timeout S with --wait: seconds to wait, 1 to 3600 (default: 300)', ' --dry-run check the assignment and store nothing',
|
|
33
47
|
' --queue-anyway queue even when the bridge would defer or warn', ' --refuse-defer fail instead of deferring',
|
|
@@ -101,7 +115,7 @@ export function shortHelp() {
|
|
|
101
115
|
return ['Dalan: hand bounded jobs to a worker agent, follow their progress and review the results.', '',
|
|
102
116
|
'Usage: dalan <command> [options]', '',
|
|
103
117
|
...GROUPS.flatMap(([key, title]) => [...section(title, COMMANDS.filter(c => c.group === key)), '']),
|
|
104
|
-
'Environment:', ' DALAN_HOME bridge home
|
|
118
|
+
'Environment:', ' DALAN_HOME bridge home commands use: the Home line a run prints (local: ~/.local/share/dalan-trial)', '',
|
|
105
119
|
'Start here: dalan try',
|
|
106
120
|
'Details: dalan <command> --help', 'More: dalan help --all', 'Version: dalan --version', ''].join('\n').trimEnd();
|
|
107
121
|
}
|
package/src/demo-worker.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// claim that any particular client works.
|
|
4
4
|
import { createHash, randomBytes } from 'node:crypto';
|
|
5
5
|
import { parseJsonBody, safeDiagnostic } from './diagnostic.mjs';
|
|
6
|
+
import { mcpResponseText } from './mcp-sse.mjs';
|
|
6
7
|
|
|
7
8
|
// A loopback pattern without a port admits any port, so this URI matches the 'http://127.0.0.1/callback' pattern.
|
|
8
9
|
export const DEMO_REDIRECT = 'http://127.0.0.1:43111/callback';
|
|
@@ -102,8 +103,7 @@ export async function openSession(mcpUrl, token, { signal } = {}) {
|
|
|
102
103
|
return { res, text };
|
|
103
104
|
};
|
|
104
105
|
const parse = text => {
|
|
105
|
-
|
|
106
|
-
return parseJsonBody(data ?? 'null', 'MCP response');
|
|
106
|
+
return parseJsonBody(mcpResponseText(text) ?? 'null', 'MCP response');
|
|
107
107
|
};
|
|
108
108
|
|
|
109
109
|
const init = await post({ jsonrpc: '2.0', id: ++nextId, method: 'initialize', params: { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: { name: 'dalan-demo', version: '1' } } });
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
|
|
4
|
+
// null means inspection could not establish liveness. Callers must retain the slot in that state.
|
|
5
|
+
export function liveWaiter(held, { platform = process.platform, run = execFileSync, readFile = fs.readFileSync, probe = pid => process.kill(pid, 0) } = {}) {
|
|
6
|
+
if (!Number.isSafeInteger(held?.pid) || held.pid <= 0) return null;
|
|
7
|
+
try { probe(held.pid); }
|
|
8
|
+
catch (error) {
|
|
9
|
+
if (error.code === 'ESRCH') return false;
|
|
10
|
+
if (error.code !== 'EPERM') return null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
let command;
|
|
14
|
+
try {
|
|
15
|
+
command = platform === 'darwin'
|
|
16
|
+
? run('/bin/ps', ['-p', String(held.pid), '-o', 'command='], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1000 })
|
|
17
|
+
: platform === 'linux' ? readFile(`/proc/${held.pid}/cmdline`, 'utf8') : null;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error.code === 'ENOENT') {
|
|
20
|
+
try { probe(held.pid); } catch (probeError) { if (probeError.code === 'ESRCH') return false; }
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
if (typeof command !== 'string' || !command) return null;
|
|
25
|
+
return command.includes('wait') && command.includes('--drained');
|
|
26
|
+
}
|
package/src/drained-slot.mjs
CHANGED
|
@@ -10,7 +10,24 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
|
|
12
12
|
const entryName = owner => `${owner.pid}-${owner.token}.json`;
|
|
13
|
-
const readEntry = file => {
|
|
13
|
+
const readEntry = file => {
|
|
14
|
+
let raw;
|
|
15
|
+
try { raw = fs.readFileSync(file, 'utf8'); }
|
|
16
|
+
catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
|
|
17
|
+
let entry;
|
|
18
|
+
try { entry = JSON.parse(raw); } catch { throw new Error(`invalid waiter entry: ${file}`); }
|
|
19
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !Number.isSafeInteger(entry.pid) || entry.pid <= 0 || (entry.token !== undefined && typeof entry.token !== 'string')) {
|
|
20
|
+
throw new Error(`invalid waiter entry: ${file}`);
|
|
21
|
+
}
|
|
22
|
+
return entry;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const waiterIsLive = (entry, isLive, file) => {
|
|
26
|
+
const state = isLive(entry);
|
|
27
|
+
if (state === true) return true;
|
|
28
|
+
if (state === false) return false;
|
|
29
|
+
throw new Error(`could not inspect waiter: ${file}`);
|
|
30
|
+
};
|
|
14
31
|
|
|
15
32
|
// Returns null when `owner` now holds the slot, or the live holder's entry. Throws when the slot cannot be settled.
|
|
16
33
|
export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
|
|
@@ -25,7 +42,7 @@ export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
|
|
|
25
42
|
try { stat = fs.lstatSync(slot); } catch { continue; }
|
|
26
43
|
if (stat.isFile()) { // a pidfile written by an earlier release
|
|
27
44
|
const held = readEntry(slot);
|
|
28
|
-
if (held &&
|
|
45
|
+
if (held && waiterIsLive(held, isLive, slot)) return held;
|
|
29
46
|
beforeRemoval?.();
|
|
30
47
|
fs.rmSync(slot, { force: true });
|
|
31
48
|
continue;
|
|
@@ -36,7 +53,7 @@ export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
|
|
|
36
53
|
for (const name of names) {
|
|
37
54
|
const entry = readEntry(path.join(slot, name));
|
|
38
55
|
if (entry === undefined) continue;
|
|
39
|
-
if (entry
|
|
56
|
+
if (waiterIsLive(entry, isLive, path.join(slot, name))) return entry;
|
|
40
57
|
stale.push(name);
|
|
41
58
|
}
|
|
42
59
|
if (!stale.length) continue; // empty: the next rename replaces it
|
package/src/mcp-outcome.mjs
CHANGED
|
@@ -3,6 +3,15 @@ import { performance } from 'node:perf_hooks';
|
|
|
3
3
|
import { redactNote } from './alerts.mjs';
|
|
4
4
|
|
|
5
5
|
const responses = new WeakMap();
|
|
6
|
+
|
|
7
|
+
// The caller's class, never its text: a User-Agent can hold anything, including a credential, so only a name from this fixed
|
|
8
|
+
// list is logged ("other" for the rest, null when absent). That is enough to tell an Anthropic or OpenAI caller from a generic one.
|
|
9
|
+
const UA_CLASSES = [['Claude-User', /^claude-user/i], ['ClaudeBot', /^claudebot/i], ['anthropic-ai', /^anthropic-ai/i], ['ChatGPT-User', /^chatgpt-user/i], ['OAI-SearchBot', /^oai-searchbot/i],
|
|
10
|
+
['node', /^node(?![A-Za-z0-9._-])/i], ['undici', /^undici/i], ['curl', /^curl/i], ['python', /^python/i], ['Mozilla', /^mozilla/i]];
|
|
11
|
+
export const uaToken = req => {
|
|
12
|
+
const ua = String(req.headers?.['user-agent'] ?? '');
|
|
13
|
+
return ua === '' ? null : (UA_CLASSES.find(([, pattern]) => pattern.test(ua))?.[0] ?? 'other');
|
|
14
|
+
};
|
|
6
15
|
const methods = new Set(['server/discover', 'initialize', 'ping', 'tools/list', 'tools/call', 'events/list', 'events/subscribe', 'events/unsubscribe', 'notifications/initialized', 'notifications/cancelled']);
|
|
7
16
|
|
|
8
17
|
// Log only declared protocol names and numeric outcomes. RPC IDs, arguments,
|
|
@@ -22,7 +31,7 @@ export function beginMcpOutcome(req, res, log, toolNames, authRequired) {
|
|
|
22
31
|
response_kind: 'empty', error_type: null,
|
|
23
32
|
};
|
|
24
33
|
responses.set(res, state);
|
|
25
|
-
log({ kind: 'mcp_received', call_id: state.call_id, http_method: state.http_method });
|
|
34
|
+
log({ kind: 'mcp_received', call_id: state.call_id, http_method: state.http_method, ua: uaToken(req) });
|
|
26
35
|
let recorded = false;
|
|
27
36
|
const complete = completion => {
|
|
28
37
|
if (recorded) return;
|
package/src/mcp-sse.mjs
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const HEARTBEAT = ': keepalive\n\n';
|
|
2
|
+
|
|
3
|
+
export function acceptsMcpEventStream(accept) {
|
|
4
|
+
return typeof accept === 'string' && accept.split(',').some(entry => {
|
|
5
|
+
const [mediaType, ...parameters] = entry.trim().toLowerCase().split(';').map(part => part.trim());
|
|
6
|
+
if (mediaType !== 'text/event-stream') return false;
|
|
7
|
+
const quality = parameters.find(parameter => parameter.startsWith('q='));
|
|
8
|
+
return !quality || Number(quality.slice(2)) > 0;
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function beginMcpEventStream(res, { heartbeatMs = 20_000, setIntervalFn = setInterval, clearIntervalFn = clearInterval } = {}) {
|
|
13
|
+
let active = true, timer = null, writtenBytes = 0;
|
|
14
|
+
const stop = () => {
|
|
15
|
+
if (!active) return;
|
|
16
|
+
active = false;
|
|
17
|
+
if (timer !== null) clearIntervalFn(timer);
|
|
18
|
+
};
|
|
19
|
+
res.once('close', stop);
|
|
20
|
+
res.once('finish', stop);
|
|
21
|
+
res.once('error', stop);
|
|
22
|
+
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform' });
|
|
23
|
+
const heartbeat = () => {
|
|
24
|
+
if (!active || res.destroyed) { stop(); return; }
|
|
25
|
+
res.write(HEARTBEAT);
|
|
26
|
+
writtenBytes += Buffer.byteLength(HEARTBEAT);
|
|
27
|
+
};
|
|
28
|
+
heartbeat();
|
|
29
|
+
if(active) {
|
|
30
|
+
timer = setIntervalFn(heartbeat, heartbeatMs);
|
|
31
|
+
timer?.unref?.();
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
finish(jsonText, beforeEnd = () => {}) {
|
|
35
|
+
if (!active || res.destroyed) { stop(); return 0; }
|
|
36
|
+
const frame = `event: message\ndata: ${jsonText}\n\n`;
|
|
37
|
+
const bytes = writtenBytes + Buffer.byteLength(frame);
|
|
38
|
+
stop();
|
|
39
|
+
beforeEnd(bytes);
|
|
40
|
+
res.write(frame);
|
|
41
|
+
res.end();
|
|
42
|
+
return bytes;
|
|
43
|
+
},
|
|
44
|
+
close: stop,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function mcpResponseText(text) {
|
|
49
|
+
const normalized = String(text).replace(/\r\n?/g, '\n');
|
|
50
|
+
const lines = normalized.split('\n');
|
|
51
|
+
if (!lines.some(line => line.startsWith(':') || /^(?:data|event|id|retry):/.test(line))) return normalized;
|
|
52
|
+
const frames = [];
|
|
53
|
+
let data = [];
|
|
54
|
+
const endFrame = () => { if (data.length) frames.push(data.join('\n')); data = []; };
|
|
55
|
+
for (const line of lines) {
|
|
56
|
+
if (line === '') { endFrame(); continue; }
|
|
57
|
+
if (line.startsWith(':')) continue;
|
|
58
|
+
if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
|
|
59
|
+
}
|
|
60
|
+
endFrame();
|
|
61
|
+
return frames.at(-1);
|
|
62
|
+
}
|
package/src/pr-head-reviewer.mjs
CHANGED
|
@@ -586,9 +586,9 @@ export function acquireLock(dir) {
|
|
|
586
586
|
try { fs.writeFileSync(file, String(process.pid), { flag: 'wx' }); return () => { try { fs.unlinkSync(file); } catch { /* gone */ } }; }
|
|
587
587
|
catch (e) {
|
|
588
588
|
if (e.code !== 'EEXIST') throw e;
|
|
589
|
-
const
|
|
590
|
-
|
|
591
|
-
if (
|
|
589
|
+
const raw = fs.readFileSync(file, 'utf8').trim();
|
|
590
|
+
if (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw))) return null;
|
|
591
|
+
try { process.kill(Number(raw), 0); return null; } catch (err) { if (err.code !== 'ESRCH') return null; }
|
|
592
592
|
try { fs.unlinkSync(file); } catch { /* raced */ }
|
|
593
593
|
}
|
|
594
594
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
|
|
4
|
+
// Inspection failure is not evidence of exit. Read Linux start ticks on both sides of ps so command and identity belong
|
|
5
|
+
// to the same process. macOS supplies its start timestamp and command in one ps snapshot, with a fixed locale and timezone.
|
|
6
|
+
export const processCommand = (pid, { platform = process.platform, run = spawnSync, readFile = fs.readFileSync, probe = pid => process.kill(pid, 0) } = {}) => {
|
|
7
|
+
const unknown = { state: 'unknown' }, absent = { state: 'absent' };
|
|
8
|
+
if (!Number.isInteger(pid) || pid <= 0) return unknown;
|
|
9
|
+
const startTicks = () => {
|
|
10
|
+
const stat = readFile(`/proc/${pid}/stat`, 'utf8');
|
|
11
|
+
const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
|
|
12
|
+
if (!/^\d+$/.test(fields[19] ?? '')) throw new Error('invalid process start time');
|
|
13
|
+
return fields[19];
|
|
14
|
+
};
|
|
15
|
+
try {
|
|
16
|
+
const before = platform === 'linux' ? startTicks() : null;
|
|
17
|
+
if (!['linux', 'darwin'].includes(platform)) return unknown;
|
|
18
|
+
const out = run('ps', ['-p', String(pid), '-o', platform === 'darwin' ? 'lstart=,command=' : 'command='], { encoding: 'utf8', timeout: 5000, env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' } });
|
|
19
|
+
if (out.error || out.status !== 0 || !out.stdout?.trim()) {
|
|
20
|
+
// Even ps exit 1 can be an inspection failure; only ESRCH confirms absence.
|
|
21
|
+
try { probe(pid); } catch (error) { if (error.code === 'ESRCH') return absent; }
|
|
22
|
+
return unknown;
|
|
23
|
+
}
|
|
24
|
+
if (platform === 'linux') {
|
|
25
|
+
const after = startTicks();
|
|
26
|
+
return before === after ? { state: 'present', command: out.stdout.trim(), start: before } : unknown;
|
|
27
|
+
}
|
|
28
|
+
const match = /^(\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/.exec(out.stdout.trim());
|
|
29
|
+
return match ? { state: 'present', command: match[2], start: match[1].replace(/\s+/g, ' ') } : unknown;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (['ENOENT', 'ESRCH'].includes(error.code)) {
|
|
32
|
+
try { probe(pid); } catch (probeError) { if (probeError.code === 'ESRCH') return absent; }
|
|
33
|
+
}
|
|
34
|
+
return unknown;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import {createHash, timingSafeEqual, randomBytes,createCipheriv,createDecipheriv} from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
4
|
+
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
|
|
5
|
+
export const PULL_PAGE_PREFIX='pullpage_';
|
|
6
|
+
export function routingPolicy(value,assignment) {
|
|
7
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['version','allowed_workers','fan_out','deadline_at'].includes(key))) throw new Error('invalid routing policy: supported fields are version, allowed_workers, fan_out, deadline_at');
|
|
8
|
+
if(value.version!==1||value.fan_out!==undefined&&value.fan_out!==1) throw new Error('routing v1 supports version=1 and fan_out=1 only');
|
|
9
|
+
const names=value.allowed_workers;
|
|
10
|
+
if(!Array.isArray(names)||!names.length||names.length>100||names.some(name=>typeof name!=='string'||!(/^[a-z][a-z0-9_-]{0,31}$/).test(name))||new Set(names).size!==names.length) throw new Error('routing requires 1-100 distinct explicit allowed_workers');
|
|
11
|
+
if(assignment.execution_scope!=='read-only'||Object.hasOwn(assignment,'protocol')) throw new Error('routing v1 supports read-only assignments without protocol only');
|
|
12
|
+
const deadline=value.deadline_at??assignment.valid_until;
|
|
13
|
+
if(typeof deadline!=='string'||!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(deadline)||!Number.isFinite(Date.parse(deadline))) throw new Error('routing requires an explicit RFC3339 deadline_at or assignment.valid_until');
|
|
14
|
+
const assignmentDeadline=assignment.valid_until===undefined?null:Date.parse(assignment.valid_until);
|
|
15
|
+
if(assignmentDeadline!==null&&!Number.isFinite(assignmentDeadline))throw new Error('invalid assignment valid_until');
|
|
16
|
+
return {version:1,allowed_workers:[...names].sort(),fan_out:1,deadline_at:new Date(Math.min(Date.parse(deadline),assignmentDeadline??Infinity)).toISOString()};
|
|
17
|
+
}
|
|
18
|
+
export function migratePullQueue(db) {
|
|
19
|
+
db.exec(`CREATE TABLE policy_work_orders (
|
|
20
|
+
work_order_id TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE, intent_digest TEXT NOT NULL,
|
|
21
|
+
owner_hash TEXT NOT NULL, payload TEXT NOT NULL, options TEXT NOT NULL, routing TEXT NOT NULL,
|
|
22
|
+
approvals TEXT NOT NULL, created_at TEXT NOT NULL, priority TEXT NOT NULL,
|
|
23
|
+
state TEXT NOT NULL DEFAULT 'queued', owner_read_at TEXT, cancelled_at TEXT, cancelled_reason TEXT,
|
|
24
|
+
child_request_id TEXT UNIQUE REFERENCES assignments(request_id),
|
|
25
|
+
receipt TEXT, worker TEXT, subject TEXT, connection_id TEXT, acquisition_id TEXT
|
|
26
|
+
); CREATE INDEX policy_work_backlog ON policy_work_orders(state,priority,created_at);
|
|
27
|
+
CREATE TRIGGER policy_work_intent_immutable BEFORE UPDATE OF work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority ON policy_work_orders BEGIN SELECT RAISE(ABORT,'policy work intent is immutable'); END;`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A work order reserves the submitted request ID. Its one execution child takes
|
|
31
|
+
// that ID at acquisition, so the owner's durable capability and wait path survive.
|
|
32
|
+
export class PullQueue {
|
|
33
|
+
constructor(store) {
|
|
34
|
+
this.store=store;this.db=store.db;
|
|
35
|
+
this.db.prepare("INSERT OR IGNORE INTO bridge_state(key,value) VALUES('pull_cursor_key',?)").run(randomBytes(32).toString('hex'));
|
|
36
|
+
this.cursorKey=Buffer.from(this.db.prepare("SELECT value FROM bridge_state WHERE key='pull_cursor_key'").get().value,'hex');
|
|
37
|
+
}
|
|
38
|
+
cursor(worker,value) {
|
|
39
|
+
const nonce=randomBytes(12),cipher=createCipheriv('aes-256-gcm',this.cursorKey,nonce);cipher.setAAD(Buffer.from(worker));
|
|
40
|
+
const encrypted=Buffer.concat([cipher.update(JSON.stringify(value)),cipher.final()]);
|
|
41
|
+
return PULL_PAGE_PREFIX+Buffer.concat([nonce,cipher.getAuthTag(),encrypted]).toString('base64url');
|
|
42
|
+
}
|
|
43
|
+
readCursor(worker,cursor) {
|
|
44
|
+
try {
|
|
45
|
+
const bytes=Buffer.from(cursor.slice(PULL_PAGE_PREFIX.length),'base64url'),decipher=createDecipheriv('aes-256-gcm',this.cursorKey,bytes.subarray(0,12));
|
|
46
|
+
decipher.setAAD(Buffer.from(worker));decipher.setAuthTag(bytes.subarray(12,28));
|
|
47
|
+
const value=JSON.parse(Buffer.concat([decipher.update(bytes.subarray(28)),decipher.final()]).toString());
|
|
48
|
+
if(!Array.isArray(value)||value.length!==3||value.some(n=>!Number.isSafeInteger(n)||n<0)||value[1]>1||value[2]>value[0])throw new Error();
|
|
49
|
+
return value;
|
|
50
|
+
}catch{throw new Error('assignment not found');}
|
|
51
|
+
}
|
|
52
|
+
row(id) { return this.db.prepare('SELECT rowid AS sequence,* FROM policy_work_orders WHERE request_id=?').get(id); }
|
|
53
|
+
ownerRow(id) { return this.row(id); }
|
|
54
|
+
inbox(id) {
|
|
55
|
+
const row=this.row(id);if(!row||row.child_request_id)return null;
|
|
56
|
+
const projected=this.project(row);
|
|
57
|
+
return {target_worker:null,work_order_id:row.work_order_id,brief:projected.assignment.brief,created_at:row.created_at,finished_at:null,outcome:null,consumed:false,decision:null,delivered_t3:false,
|
|
58
|
+
cancelled_at:projected.cancelled_at,cancelled_reason:projected.cancelled_reason,cancelled_by_owner:row.state==='cancelled',read:row.owner_read_at!==null,failure_type:projected.cancelled_reason==='expired'?'expired':row.state==='cancelled'?'owner_cancelled':null,failure_type_source:projected.cancelled_reason==='expired'?'bridge_observed_transition':row.state==='cancelled'?'bridge_observed_transition':null,unanswered_blocker:null};
|
|
59
|
+
}
|
|
60
|
+
consume(id) {
|
|
61
|
+
const row=this.row(id);if(!row||row.child_request_id)return;
|
|
62
|
+
if(this.project(row).status==='cancelled')this.db.prepare('UPDATE policy_work_orders SET owner_read_at=COALESCE(owner_read_at,?) WHERE request_id=?').run(this.store.stamp(),id);
|
|
63
|
+
}
|
|
64
|
+
assertOwner(row,token) {
|
|
65
|
+
const got=createHash('sha256').update(token??'').digest();
|
|
66
|
+
if(!row||!timingSafeEqual(got,Buffer.from(row.owner_hash,'hex'))) throw new Error('invalid owner capability');
|
|
67
|
+
}
|
|
68
|
+
project(row) {
|
|
69
|
+
const assignment=JSON.parse(row.payload),routing=JSON.parse(row.routing),options=JSON.parse(row.options);
|
|
70
|
+
const expired=row.state==='queued'&&Date.parse(routing.deadline_at)<=this.store.nowMs();
|
|
71
|
+
return {request_id:row.request_id,work_order_id:row.work_order_id,child_request_id:row.child_request_id,
|
|
72
|
+
status:expired?'cancelled':row.state,assignment,routing,created_at:row.created_at,
|
|
73
|
+
target_worker:null,execution:options.execution,delivery_mode:options.delivery.mode==='t3'?`t3:${options.delivery.threadId}`:'none',
|
|
74
|
+
thread_id:options.delivery.threadId??null,environment_id:options.environmentId??null,
|
|
75
|
+
valid_until:routing.deadline_at,cancelled_at:row.cancelled_at,cancelled_reason:row.cancelled_reason??(expired?'expired':null),
|
|
76
|
+
claim:null,report:null,progress:[],owner_notes:[],delivery:[],lifecycle_events:[],required_capabilities:[]};
|
|
77
|
+
}
|
|
78
|
+
submit(payload,identity,options,routing,approvals,ownerToken,{dryRun=false}={}) {
|
|
79
|
+
const ownerHash=createHash('sha256').update(ownerToken).digest('hex');
|
|
80
|
+
const intent=digest(canonical({identity,options,routing,approvals}));
|
|
81
|
+
return this.store.inTransaction(()=>{
|
|
82
|
+
const old=this.row(payload.request_id);
|
|
83
|
+
if(old) {
|
|
84
|
+
this.assertOwner(old,ownerToken);
|
|
85
|
+
if(old.intent_digest!==intent) throw new Error('request_id conflict');
|
|
86
|
+
return {request_id:old.request_id,work_order_id:old.work_order_id,status:old.child_request_id?this.store.get(old.child_request_id).status:this.project(old).status,duplicate:true,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
|
|
87
|
+
}
|
|
88
|
+
if(this.store.hasAssignment(payload.request_id)) throw new Error('request_id conflict');
|
|
89
|
+
if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
|
|
90
|
+
const workId='work_'+digest(payload.request_id).slice(0,32);
|
|
91
|
+
if(!dryRun) this.db.prepare('INSERT INTO policy_work_orders(work_order_id,request_id,intent_digest,owner_hash,payload,options,routing,approvals,created_at,priority) VALUES(?,?,?,?,?,?,?,?,?,?)').run(workId,payload.request_id,intent,ownerHash,JSON.stringify(payload),JSON.stringify(options),JSON.stringify(routing),JSON.stringify(approvals),this.store.stamp(),options.priority);
|
|
92
|
+
return {request_id:payload.request_id,work_order_id:workId,status:'queued',duplicate:false,...(dryRun?{dry_run:true,stored:false,verdict:'admissible'}:{})};
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
eligible(row,worker,admit) {
|
|
96
|
+
if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) return false;
|
|
97
|
+
try { admit(worker,JSON.parse(row.payload),JSON.parse(row.options).execution,JSON.parse(row.approvals)[worker]); return true; } catch { return false; }
|
|
98
|
+
}
|
|
99
|
+
get(id,worker,admit) {
|
|
100
|
+
const row=this.row(id);
|
|
101
|
+
if(!row||row.state!=='queued'||Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) throw new Error('assignment not found');
|
|
102
|
+
return {...this.project(row),guidance:'Claim this request_id with a fresh acquisition_id. The receipt names the immutable execution child; use its request_id and claim_id for all later tools.'};
|
|
103
|
+
}
|
|
104
|
+
list(worker,admit,cursor=null) {
|
|
105
|
+
let after=0,rank=0,snapshot=this.db.prepare('SELECT COALESCE(max(rowid),0) n FROM policy_work_orders').get().n;
|
|
106
|
+
if(cursor)[snapshot,rank,after]=this.readCursor(worker,cursor);
|
|
107
|
+
const rows=this.db.prepare("SELECT rowid AS sequence,CASE priority WHEN 'normal' THEN 0 ELSE 1 END AS rank,* FROM policy_work_orders WHERE state='queued' AND rowid<=? AND (CASE priority WHEN 'normal' THEN 0 ELSE 1 END>? OR (CASE priority WHEN 'normal' THEN 0 ELSE 1 END=? AND rowid>?)) ORDER BY rank,rowid").iterate(snapshot,rank,rank,after);
|
|
108
|
+
const items=[];let next=null;
|
|
109
|
+
for(const row of rows) {
|
|
110
|
+
if(Date.parse(JSON.parse(row.routing).deadline_at)<=this.store.nowMs()||!this.eligible(row,worker,admit)) continue;
|
|
111
|
+
if(items.length===50) { const last=items.at(-1);next=this.cursor(worker,[snapshot,last._rank,last._sequence]);break; }
|
|
112
|
+
items.push({request_id:row.request_id,work_order_id:row.work_order_id,title:JSON.parse(row.payload).brief.slice(0,160),created_at:row.created_at,priority:row.priority,deadline_at:JSON.parse(row.routing).deadline_at,remaining_result_slots:1,_sequence:row.sequence,_rank:row.rank});
|
|
113
|
+
}
|
|
114
|
+
return {items:items.map(({_sequence,_rank,...item})=>item),next_page_request_id:next,guidance:'Use get with next_page_request_id to read the next page. Use claim with an offered request_id and fresh acquisition_id to acquire its single result slot. Capacity limits claims, not this backlog.'};
|
|
115
|
+
}
|
|
116
|
+
acquire(id,{worker,subject,connectionId,claimant,acquisitionId,leaseMs,capacity,preflight,admit}) {
|
|
117
|
+
if(typeof acquisitionId!=='string'||!(/^[A-Za-z0-9_-]{1,128}$/).test(acquisitionId)) throw new Error('policy work requires a fresh acquisition_id');
|
|
118
|
+
return this.store.transaction(()=>{
|
|
119
|
+
const row=this.row(id);
|
|
120
|
+
if(!row||!JSON.parse(row.routing).allowed_workers.includes(worker)) throw new Error('assignment not found');
|
|
121
|
+
if(row.child_request_id) {
|
|
122
|
+
if(row.worker!==worker||row.subject!==subject||row.connection_id!==(connectionId??null)||row.acquisition_id!==acquisitionId) throw new Error('work order already acquired');
|
|
123
|
+
if(this.store.get(id).status!=='claimed')throw new Error('assignment finished or cancelled');
|
|
124
|
+
const receipt=JSON.parse(row.receipt),held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
125
|
+
if(held?.claimant!==claimant||held?.lease_ms!==(leaseMs??this.store.limits.leaseMs))throw new Error('acquisition_id conflict');
|
|
126
|
+
this.store.assertClaim(id,receipt.claim_id,subject,worker);
|
|
127
|
+
this.store.assertRetryConnection(id,held,worker,connectionId);
|
|
128
|
+
return {...receipt,duplicate:true};
|
|
129
|
+
}
|
|
130
|
+
if(row.state!=='queued') throw new Error('assignment cancelled');
|
|
131
|
+
const payload=JSON.parse(row.payload),options=JSON.parse(row.options),routing=JSON.parse(row.routing),approval=JSON.parse(row.approvals)[worker];
|
|
132
|
+
if(Date.parse(routing.deadline_at)<=this.store.nowMs()) throw new Error('routing deadline expired');
|
|
133
|
+
admit(worker,payload,options.execution,approval);
|
|
134
|
+
// Both insert and ordinary claim join this transaction. A failed capacity,
|
|
135
|
+
// destination or preflight check leaves no child and no consumed slot.
|
|
136
|
+
this.store.submitInTransaction({...payload,valid_until:routing.deadline_at},options.delivery,options.environmentId,'',options.review,preflight,options.priority,options.meta,payload,null,worker,options.execution,options.execution,null,null,null,null,approval??null,row.owner_hash);
|
|
137
|
+
const claimed=this.store.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs??this.store.limits.leaseMs,connectionId);
|
|
138
|
+
if(!claimed.claim_id) throw new Error('policy child admission refused');
|
|
139
|
+
const held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
140
|
+
const receipt={...claimed,lease_expires_at:this.store.leaseExpiresAt(held),work_order_id:row.work_order_id,child_request_id:id};
|
|
141
|
+
this.db.prepare("UPDATE policy_work_orders SET state='acquired',child_request_id=?,receipt=?,worker=?,subject=?,connection_id=?,acquisition_id=? WHERE request_id=?").run(id,JSON.stringify(receipt),worker,subject,connectionId??null,acquisitionId,id);
|
|
142
|
+
return receipt;
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
cancel(id,reason=null) {
|
|
146
|
+
return this.store.inTransaction(()=>{
|
|
147
|
+
const row=this.row(id);if(!row||row.child_request_id) return null;
|
|
148
|
+
this.db.prepare("UPDATE policy_work_orders SET state='cancelled',cancelled_at=COALESCE(cancelled_at,?),cancelled_reason=COALESCE(cancelled_reason,?) WHERE request_id=?").run(this.store.stamp(),reason,id);
|
|
149
|
+
return {request_id:id,status:'cancelled',cancellation_requested:true,authority_revoked:true,compute_stopped:false};
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
sweepExpired(limit=100) {
|
|
153
|
+
return this.store.inTransaction(()=>{
|
|
154
|
+
const rows=this.db.prepare("SELECT request_id FROM policy_work_orders WHERE state='queued' AND json_extract(routing,'$.deadline_at')<=? ORDER BY json_extract(routing,'$.deadline_at'),rowid LIMIT ?").all(this.store.stamp(),limit);
|
|
155
|
+
for(const row of rows)this.cancel(row.request_id,'expired');
|
|
156
|
+
return rows.map(row=>row.request_id);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The owner's saved choice of public route, written by `dalan setup`. One small file in the user's config directory, outside every
|
|
2
|
+
// trial home, so a trial that is deleted never loses it and a trial never writes it. Values: 'tailscale' or 'gozar'. The old
|
|
3
|
+
// 'localhost.run' value remains readable so existing installs keep selecting the trial relay. No file means no saved choice.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
export const ROUTE_CHOICES = ['tailscale', 'gozar', 'localhost.run'];
|
|
9
|
+
export const routeSettingPath = (env = process.env) => path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'dalan', 'route.json');
|
|
10
|
+
|
|
11
|
+
export function readRouteSetting(env = process.env) {
|
|
12
|
+
try {
|
|
13
|
+
const route = JSON.parse(fs.readFileSync(routeSettingPath(env), 'utf8'))?.route;
|
|
14
|
+
return ROUTE_CHOICES.includes(route) ? route : null;
|
|
15
|
+
} catch { return null; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function writeRouteSetting(route, env = process.env) {
|
|
19
|
+
if (!ROUTE_CHOICES.includes(route)) throw new Error(`unknown route ${JSON.stringify(route)}`);
|
|
20
|
+
const file = routeSettingPath(env);
|
|
21
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
22
|
+
fs.writeFileSync(file, `${JSON.stringify({ route })}\n`, { mode: 0o600 });
|
|
23
|
+
return file;
|
|
24
|
+
}
|