@tnunamak/dalan 0.5.2 → 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 +29 -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 +175 -0
- package/docs/connect-chatgpt.md +9 -4
- package/docs/connection-longevity.md +7 -1
- package/docs/dalan-upgrade.md +17 -13
- 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 +2 -0
- 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/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 +388 -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 +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 +63 -17
- package/src/workers.mjs +33 -23
- package/src/workspace.mjs +10 -3
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// What the owner is told to click in a hosted client, and which OAuth callback that client uses. This is data and copy only:
|
|
2
|
+
// the bridge's OAuth rules live in src/as.mjs. The callbacks below are the vendors' published ones and are also in the bridge's
|
|
3
|
+
// default callback list (src/as-files.mjs), so a hosted trial adds no new trust.
|
|
4
|
+
import { terminalSafe } from './terminal-safe.mjs';
|
|
5
|
+
|
|
6
|
+
export const CONNECTOR_NAME = 'Dalan Trial';
|
|
7
|
+
|
|
8
|
+
export const CLIENTS = {
|
|
9
|
+
chatgpt: {
|
|
10
|
+
label: 'ChatGPT',
|
|
11
|
+
// https://developers.openai.com/apps-sdk/build/auth: the stable redirect, and the connection-specific one that ChatGPT
|
|
12
|
+
// uses when it does not accept the issuer's identification. Both are vendor-published; anything else is refused here.
|
|
13
|
+
callbacks: ['https://chatgpt.com/connector_platform_oauth_redirect', /^https:\/\/chatgpt\.com\/connector\/oauth\/[A-Za-z0-9_-]+$/],
|
|
14
|
+
steps: [
|
|
15
|
+
'Open ChatGPT, then Settings → Apps (older accounts: Settings → Connectors → Advanced → Developer mode), and choose Create or Add a custom MCP server.',
|
|
16
|
+
`Name it "${CONNECTOR_NAME}", paste the URL above, choose OAuth (automatic registration if asked), accept the notice and create it.`,
|
|
17
|
+
`Open a new chat, enable "${CONNECTOR_NAME}" from the + menu, start sign-in, and approve the matching code in this terminal.`,
|
|
18
|
+
],
|
|
19
|
+
},
|
|
20
|
+
claude: {
|
|
21
|
+
label: 'claude.ai',
|
|
22
|
+
callbacks: ['https://claude.ai/api/mcp/auth_callback'],
|
|
23
|
+
steps: [
|
|
24
|
+
'Open claude.ai, then Customize → Connectors → + → Add custom connector. (If your organization manages connectors, an owner adds it under Organization settings → Connectors first.)',
|
|
25
|
+
`Name it "${CONNECTOR_NAME}", paste the URL above, leave the OAuth client fields empty (automatic registration), then Add and sign in.`,
|
|
26
|
+
`Approve the matching code in this terminal when Dalan asks.`,
|
|
27
|
+
],
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const CLIENT_NAMES = Object.keys(CLIENTS);
|
|
32
|
+
|
|
33
|
+
export const callbackAllowed = (client, redirect) => CLIENTS[client].callbacks.some(c => typeof c === 'string' ? c === redirect : c.test(redirect));
|
|
34
|
+
|
|
35
|
+
export const hostedPrompt = (requestId, requestPhrase) =>
|
|
36
|
+
`Use ${CONNECTOR_NAME} to list pending jobs, claim only ${requestId}, read its brief, and finish it with the requested report (${requestPhrase}). Stop if the job is missing or cancelled. Do not read files, run commands, or call other services.`;
|
|
37
|
+
|
|
38
|
+
// The connector handoff: every value is filled in. `url` is a credential, so the caller writes this text to the owner's terminal
|
|
39
|
+
// only, never to a log.
|
|
40
|
+
export function handoffText({ client, url }) {
|
|
41
|
+
const spec = CLIENTS[client];
|
|
42
|
+
return [
|
|
43
|
+
`Connector name: ${CONNECTOR_NAME}`, 'Paste this URL into your connector (it is a secret; it stays on this terminal and in the private resource-url file):', url, '',
|
|
44
|
+
spec.label, ...spec.steps.map((step, i) => `${i + 1}. ${step}`),
|
|
45
|
+
].map(line => terminalSafe(line)).join('\n');
|
|
46
|
+
}
|
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
// `dalan try --public`: the same trial, reached by a hosted MCP client (for example ChatGPT or claude.ai). It starts a public route, a bridge whose
|
|
2
|
+
// OAuth issuer is that route's address, queues one demo job, prints the connector URL and the clicks, asks the owner to approve the
|
|
3
|
+
// sign-in, and calls the trial a success only when the hosted client finishes that job. The local flow in try.mjs is unchanged.
|
|
4
|
+
import { execFile, spawn } from 'node:child_process';
|
|
5
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import readline from 'node:readline';
|
|
10
|
+
import { terminalSafe } from './terminal-safe.mjs';
|
|
11
|
+
import { waitForChildExit } from './child-exit.mjs';
|
|
12
|
+
import { createLineMasker, safeDiagnostic } from './diagnostic.mjs';
|
|
13
|
+
import { registerSecret } from './redaction.mjs';
|
|
14
|
+
import { defaultPath } from './paths.mjs';
|
|
15
|
+
import { PAIRING_MINUTES } from './as-files.mjs';
|
|
16
|
+
import { CLIENTS, CONNECTOR_NAME, callbackAllowed, handoffText, hostedPrompt } from './try-hosted-clients.mjs';
|
|
17
|
+
import { PUBLIC_READY_MS, createGate, gozarProvider, localhostRunProvider, selectRouteProvider, startRoute, tailscaleNodeProvider, tailscaleProvider, verifyPublicReady, watchPublicIdentity } from './try-exposure.mjs';
|
|
18
|
+
import { readRouteSetting } from './route-setting.mjs';
|
|
19
|
+
import { childRegistry, registerChild, sweepChildren } from './child-registry.mjs';
|
|
20
|
+
|
|
21
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
22
|
+
const HOSTED_WORKER = 'hosted';
|
|
23
|
+
// Files that hold a credential of a finished trial. The job history stays.
|
|
24
|
+
// A home that a restart reuses keeps the bridge's own config (its path secret); the others lose it.
|
|
25
|
+
export function removeTrialSecrets(home, configDir, { keepConfig = false, keepNode = false } = {}) {
|
|
26
|
+
for (const file of [path.join(home, 'resource-url'), ...(keepConfig ? [] : [path.join(configDir, 'env')])]) fs.rmSync(file, { force: true });
|
|
27
|
+
fs.rmSync(path.join(home, 'localhost-run'), { recursive: true, force: true });
|
|
28
|
+
if (!keepNode) fs.rmSync(path.join(home, 'tsnode'), { recursive: true, force: true }); // else a child still holds files there: the next sweep removes them
|
|
29
|
+
}
|
|
30
|
+
const REPORT = 'bridge first report';
|
|
31
|
+
|
|
32
|
+
// One trial at a time per home. A lock file names its owner; a loser exits before it creates, truncates or removes anything.
|
|
33
|
+
export function acquireHomeLock(home) {
|
|
34
|
+
const file = path.join(home, '.hosted-lock');
|
|
35
|
+
const token = `${process.pid} ${randomBytes(8).toString('hex')}`;
|
|
36
|
+
const busy = () => Object.assign(new Error(`another trial is using this home; stop it first or choose a new --home (if none is running, delete ${file})`), { tryKind: 'already_running' });
|
|
37
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
38
|
+
try {
|
|
39
|
+
const fd = fs.openSync(file, 'wx', 0o600); fs.writeSync(fd, token); fs.closeSync(fd);
|
|
40
|
+
return () => { try { if (fs.readFileSync(file, 'utf8') === token) fs.rmSync(file, { force: true }); } catch { /* gone */ } };
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code !== 'EEXIST') throw error;
|
|
43
|
+
const raw = fs.readFileSync(file, 'utf8').trim();
|
|
44
|
+
const match = /^([1-9]\d*)(?:\s+\S+)?$/.exec(raw);
|
|
45
|
+
const pid = match ? Number(match[1]) : NaN;
|
|
46
|
+
if (!Number.isSafeInteger(pid)) throw busy();
|
|
47
|
+
try { process.kill(pid, 0); throw busy(); } catch (probe) { if (probe.tryKind || probe.code !== 'ESRCH') throw busy(); }
|
|
48
|
+
fs.rmSync(file, { force: true }); // its owner is gone
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
throw busy();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Said once, before any public address exists. Setup chooses a route; it does not install a service.
|
|
55
|
+
export const TRIAL_NOTICE = 'Temporary demo link. It can change or stop without warning. Run dalan setup to choose Tailscale when available, or keep using temporary Gozar links. Setup does not install a background service.';
|
|
56
|
+
// A trial's maximum local lifetime is a shutdown limit, not a promise that a public route will stay available.
|
|
57
|
+
export const TRIAL_MS = 3 * 60 * 60 * 1000;
|
|
58
|
+
export const timeLeft = ms => { const minutes = Math.max(0, Math.ceil(ms / 60_000)); return minutes >= 60 ? `${Math.floor(minutes / 60)} h ${String(minutes % 60).padStart(2, '0')} min` : `${minutes} min`; };
|
|
59
|
+
export const REAL_NOTICE = fromSetup => `Using Tailscale${fromSetup ? ', the address you saved with `dalan setup`' : ''}. This is not a trial link.`;
|
|
60
|
+
|
|
61
|
+
// Reads answers from one terminal reader and closes it, so the trial's own reader starts clean.
|
|
62
|
+
export async function chooseMode({ input, out, signal }) {
|
|
63
|
+
const lines = readline.createInterface({ input });
|
|
64
|
+
let ended = false;
|
|
65
|
+
lines.once('close', () => { ended = true; });
|
|
66
|
+
const ask = question => ended || signal?.aborted ? Promise.resolve(null) : new Promise(resolve => {
|
|
67
|
+
const finish = answer => { lines.off('line', finish); lines.off('close', onClose); resolve(answer); };
|
|
68
|
+
const onClose = () => finish(null);
|
|
69
|
+
out.write(question);
|
|
70
|
+
lines.once('line', finish); lines.once('close', onClose);
|
|
71
|
+
});
|
|
72
|
+
const pick = async (question, count) => {
|
|
73
|
+
for (;;) {
|
|
74
|
+
const answer = (await ask(question))?.trim();
|
|
75
|
+
if (answer === null || answer === undefined) return null;
|
|
76
|
+
if (answer === '') return 1;
|
|
77
|
+
if (/^\d+$/.test(answer) && Number(answer) >= 1 && Number(answer) <= count) return Number(answer);
|
|
78
|
+
out.write(`Type 1${count > 1 ? ` to ${count}` : ''}, or press Enter for 1.\n`);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
try {
|
|
82
|
+
out.write(`Where will your worker run?\n 1. A hosted MCP client (for example ChatGPT or claude.ai)\n 2. Only on this computer\n`);
|
|
83
|
+
const where = await pick('Choose [1]: ', 2);
|
|
84
|
+
if (where === null) return { mode: 'local' };
|
|
85
|
+
if (where === 2) return { mode: 'local' };
|
|
86
|
+
out.write('Which client?\n 1. ChatGPT\n 2. claude.ai\n');
|
|
87
|
+
const which = await pick('Choose [1]: ', 2);
|
|
88
|
+
return which === null ? { mode: 'local' } : { mode: 'public', client: which === 2 ? 'claude' : 'chatgpt' };
|
|
89
|
+
} finally { lines.close(); }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function defaultProviders({ env, say, client, hostedDeps = {} }) {
|
|
93
|
+
return [gozarProvider({ env, ...hostedDeps.gozar }), localhostRunProvider({ env, ...hostedDeps.localhostRun }), tailscaleProvider({ env, ...hostedDeps.tailscale }), tailscaleNodeProvider({ env, ...hostedDeps.tailscaleNode })];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The restart command keeps a stable Tailscale home and gives each temporary route a new home.
|
|
97
|
+
const STABLE_ORIGIN_ROUTES = new Set(['tailscale']);
|
|
98
|
+
export const restartCommand = ({ cli, home, freshHome, shellQuote, client, route, provider }) => `${cli} try --public --client ${client} --route ${route} --home ${shellQuote(STABLE_ORIGIN_ROUTES.has(provider) ? home : freshHome)}`;
|
|
99
|
+
|
|
100
|
+
export async function runHosted({ options, env, out, input, signal, errorContext, clock = { now: Date.now, sleep }, deps = {}, helpers }) {
|
|
101
|
+
const { prepareHome, portFree, socketAnswers, choosePort, shellQuote, commandLine, parsePending, describeAttempt, MARKER, DIAGNOSE_AFTER_MS, DIAGNOSE_EVERY_MS, DIAGNOSE_LIMIT, POLL_MS, repo } = helpers;
|
|
102
|
+
const client = options.client ?? 'chatgpt';
|
|
103
|
+
const say = line => out.write(`${terminalSafe(line)}\n`);
|
|
104
|
+
const providers = deps.providers ?? defaultProviders({ env, say, client, hostedDeps: deps });
|
|
105
|
+
// An explicit route wins. Auto uses a usable Tailscale route first, then the consented Gozar trial relay.
|
|
106
|
+
const autoRoute = options.route === undefined || options.route === 'auto';
|
|
107
|
+
const saved = autoRoute ? readRouteSetting(env) : null;
|
|
108
|
+
const tailscale = providers.find(provider => provider.name === 'tailscale');
|
|
109
|
+
// Explicit routes are probed by the selector once; a saved relay needs no Tailscale preflight.
|
|
110
|
+
const tailscaleProbe = autoRoute && saved !== 'gozar' && saved !== 'localhost.run' ? tailscale?.probe() : null;
|
|
111
|
+
const automaticRoute = saved === 'gozar' || saved === 'localhost.run' ? 'gozar' :
|
|
112
|
+
tailscaleProbe?.ok ? 'tailscale' : providers.some(provider => provider.name === 'gozar') ? 'gozar' : 'localhost.run';
|
|
113
|
+
const routeChoice = options.route && options.route !== 'auto' ? options.route : automaticRoute;
|
|
114
|
+
const realRoute = routeChoice === 'tailscale';
|
|
115
|
+
const spec = CLIENTS[client];
|
|
116
|
+
const realHome = fs.realpathSync(os.homedir());
|
|
117
|
+
// Only the host's usable Funnel has a stable identity; its ephemeral fallback needs a new home.
|
|
118
|
+
const routeMessages = [];
|
|
119
|
+
let selectedProvider, selectionError;
|
|
120
|
+
try {
|
|
121
|
+
signal?.throwIfAborted();
|
|
122
|
+
selectedProvider = autoRoute && routeChoice === 'tailscale' ? tailscale :
|
|
123
|
+
selectRouteProvider({ route: routeChoice, providers, say: line => routeMessages.push(line), signal });
|
|
124
|
+
if (selectedProvider?.name === 'localhost.run') {
|
|
125
|
+
routeMessages.push('localhost.run is a third-party relay that can inspect forwarded traffic.');
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (error) { selectionError = error; } // Report startup failures after the home and cleanup context are ready.
|
|
129
|
+
const stableHome = selectedProvider?.name === 'tailscale';
|
|
130
|
+
const home = prepareHome(options.home ?? env.DALAN_HOME ?? path.join(realHome, '.local/share', stableHome ? `dalan-hosted-${client}` : `dalan-hosted-${randomBytes(3).toString('hex')}`), realHome);
|
|
131
|
+
errorContext.home = home;
|
|
132
|
+
const cliPath = errorContext.shellCli ?? shellQuote(path.join(repo, 'bin/dalan.mjs'));
|
|
133
|
+
const cli = errorContext.cli ?? `node ${cliPath}`;
|
|
134
|
+
const ownCommand = (...words) => `DALAN_HOME=${shellQuote(home)} ${cli} ${words.join(' ')}`;
|
|
135
|
+
const configDir = defaultPath(home, '.config/dot-bridge');
|
|
136
|
+
const logFile = path.join(home, 'server.log');
|
|
137
|
+
errorContext.shellHome = shellQuote(home); errorContext.logFile = logFile; errorContext.shellLog = shellQuote(logFile);
|
|
138
|
+
errorContext.tryFlags = ` --public --client ${client} --route ${routeChoice}`;
|
|
139
|
+
const freshRestartHome = path.join(realHome, '.local/share', `dalan-hosted-${randomBytes(3).toString('hex')}`);
|
|
140
|
+
const retry = () => commandLine(restartCommand({ cli, home, freshHome: freshRestartHome, shellQuote, client, route: routeChoice, provider: selectedProvider?.name ?? (realRoute ? 'tailscale' : null) }));
|
|
141
|
+
errorContext.freshTrialCommand = retry().trim();
|
|
142
|
+
|
|
143
|
+
// A bridge or ssh that an earlier trial left behind (its process was killed without cleanup) is ended first; only a recorded, matching process is touched.
|
|
144
|
+
const registry = childRegistry(env);
|
|
145
|
+
const leftovers = await sweepChildren({ registry }).catch(() => []);
|
|
146
|
+
if (leftovers.length) out.write(`Ended ${leftovers.length} process${leftovers.length === 1 ? '' : 'es'} left by an earlier trial.\n`);
|
|
147
|
+
// A home that already has a bridge or another trial's profile is never reused silently.
|
|
148
|
+
const adminSock = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
|
|
149
|
+
if (await socketAnswers(adminSock)) throw Object.assign(new Error('the bridge for this home is already running; stop it with Ctrl-C in its terminal first, or choose a new --home'), { tryKind: 'already_running' });
|
|
150
|
+
let freshHome = true, storedOrigin = null;
|
|
151
|
+
try { freshHome = !JSON.parse(fs.readFileSync(path.join(configDir, 'workers.json'), 'utf8')).workers?.[HOSTED_WORKER]; if (freshHome) throw new Error(`${home} holds another trial's worker profile; choose a new --home`); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
152
|
+
try { storedOrigin = new URL(JSON.parse(fs.readFileSync(path.join(configDir, 'as.json'), 'utf8')).public_url).origin; } catch { /* a new home */ }
|
|
153
|
+
|
|
154
|
+
const lines = readline.createInterface({ input });
|
|
155
|
+
let inputEnded = false;
|
|
156
|
+
lines.once('close', () => { inputEnded = true; });
|
|
157
|
+
const stopRequested = () => signal?.aborted || inputEnded;
|
|
158
|
+
let exited = true, stopped = Promise.resolve(), server = null, routeDied = false, routeLossReason = null;
|
|
159
|
+
const stopPromise = new Promise(resolve => { if (signal?.aborted) resolve(); signal?.addEventListener('abort', resolve, { once: true }); lines.once('close', resolve); });
|
|
160
|
+
let resolveRouteGone;
|
|
161
|
+
let routeGone = new Promise(resolve => { resolveRouteGone = resolve; });
|
|
162
|
+
const markRouteLost = reason => {
|
|
163
|
+
if (routeDied) return;
|
|
164
|
+
routeDied = true;
|
|
165
|
+
routeLossReason = reason;
|
|
166
|
+
resolveRouteGone();
|
|
167
|
+
};
|
|
168
|
+
// The trial's lifetime is a real timer, not a check in the polling loop, so it also ends an unanswered question or a wait after a result.
|
|
169
|
+
const trialMs = realRoute ? null : (deps.trialMs ?? TRIAL_MS);
|
|
170
|
+
let expired = false, expireTimer = null;
|
|
171
|
+
const untilStopRequested = () => Promise.race([stopPromise, stopped, routeGone]);
|
|
172
|
+
const ask = question => {
|
|
173
|
+
if (stopRequested() || exited || routeDied || expired) return null;
|
|
174
|
+
out.write(question);
|
|
175
|
+
return new Promise(resolve => {
|
|
176
|
+
const done = answer => { lines.off('line', done); lines.off('close', onClose); signal?.removeEventListener('abort', onClose); resolve(answer); };
|
|
177
|
+
const onClose = () => done(null);
|
|
178
|
+
lines.once('line', done); lines.once('close', onClose); signal?.addEventListener('abort', onClose, { once: true });
|
|
179
|
+
stopped.then(onClose); routeGone.then(onClose);
|
|
180
|
+
});
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const baseEnv = {
|
|
184
|
+
...Object.fromEntries(['PATH', 'TMPDIR', 'LANG', 'NODE_OPTIONS'].filter(k => env[k] !== undefined).map(k => [k, env[k]])),
|
|
185
|
+
HOME: home, DALAN_AUTH_MODE: 'builtin', DALAN_TRIAL_SSE: '1', ...(deps.serverEnv ?? {}),
|
|
186
|
+
};
|
|
187
|
+
let bindPort = null;
|
|
188
|
+
// `abortable: false` is for cleanup: Ctrl-C must not cancel the revocation.
|
|
189
|
+
const dalan = (args, { abortable = true } = {}) => new Promise((resolve, reject) => execFile(process.execPath, [path.join(repo, 'bin/dalan.mjs'), ...args],
|
|
190
|
+
{ env: { ...baseEnv, DALAN_PORT: String(bindPort ?? 8799) }, cwd: repo, timeout: 30_000, ...(abortable ? { signal } : {}) }, (error, stdout, stderr) =>
|
|
191
|
+
error ? reject(new Error(`dalan ${args.slice(0, 2).join(' ')} failed: ${safeDiagnostic((stderr || stdout || error.message).trim(), 4000)}`)) : resolve(stdout)));
|
|
192
|
+
|
|
193
|
+
const startServer = () => {
|
|
194
|
+
const log = fs.openSync(logFile, 'w', 0o600); fs.fchmodSync(log, 0o600); fs.closeSync(log);
|
|
195
|
+
exited = false;
|
|
196
|
+
server = spawn(process.execPath, [path.join(repo, 'src/server.mjs')], { env: { ...baseEnv, DALAN_PORT: String(bindPort) }, cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
197
|
+
const forgetServer = registerChild({ registry, child: server });
|
|
198
|
+
server.once('close', forgetServer);
|
|
199
|
+
const child = server;
|
|
200
|
+
const sinks = [child.stdout, child.stderr].map(stream => { const persist = createLineMasker(text => fs.appendFileSync(logFile, text)); stream.setEncoding('utf8').on('data', chunk => persist(chunk)); return persist; });
|
|
201
|
+
stopped = waitForChildExit(child, {
|
|
202
|
+
onClose: () => { for (const flush of sinks) flush('', true); exited = true; },
|
|
203
|
+
onError: error => { fs.appendFileSync(logFile, `process error: ${safeDiagnostic(error.message, 1000)}\n`); },
|
|
204
|
+
});
|
|
205
|
+
};
|
|
206
|
+
const stopServer = async () => {
|
|
207
|
+
if (exited) return;
|
|
208
|
+
server.kill('SIGTERM');
|
|
209
|
+
await Promise.race([stopped, sleep(5000)]);
|
|
210
|
+
if (!exited) { server.kill('SIGKILL'); await stopped; }
|
|
211
|
+
};
|
|
212
|
+
const waitForListening = async () => {
|
|
213
|
+
for (let waited = 0; !/MCP listening/.test(fs.readFileSync(logFile, 'utf8')); waited += 100) {
|
|
214
|
+
if (exited || waited > 20_000) return false;
|
|
215
|
+
signal?.throwIfAborted();
|
|
216
|
+
await sleep(100);
|
|
217
|
+
}
|
|
218
|
+
return true;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
let gate = null, route = null, routeStopped = null, cleaned = true, keepRecoveredNode = false;
|
|
222
|
+
let identityWatcher = null;
|
|
223
|
+
let trialEndsAt = null;
|
|
224
|
+
let releaseHome;
|
|
225
|
+
try { releaseHome = acquireHomeLock(home); } catch (error) { lines.close(); throw error; }
|
|
226
|
+
try {
|
|
227
|
+
say(realRoute ? REAL_NOTICE(saved === 'tailscale') : TRIAL_NOTICE);
|
|
228
|
+
say('Checking public routes…');
|
|
229
|
+
gate = await createGate();
|
|
230
|
+
// A trial that was killed earlier may have left a Tailscale node of its own running; end it before this one starts.
|
|
231
|
+
for (const provider of providers) {
|
|
232
|
+
const recovery = await provider.recover?.().catch(() => ({ retained: [{ home: null, sock: null }] }));
|
|
233
|
+
const ended = Array.isArray(recovery) ? recovery : recovery?.ended;
|
|
234
|
+
keepRecoveredNode ||= recovery?.retained?.some(debt => debt.home === home || debt.sock === path.join(home, 'tsnode/tailscaled.sock') || (!debt.home && !debt.sock)) ?? false;
|
|
235
|
+
if (ended?.length) say(`Ended ${ended.join(', ')} left by an earlier trial.`);
|
|
236
|
+
}
|
|
237
|
+
signal?.throwIfAborted();
|
|
238
|
+
if (selectedProvider?.name === 'gozar') {
|
|
239
|
+
say('This public demo uses tunnl.gg, a third-party relay that can inspect forwarded traffic. Gozar creates an installation-specific relay key after your consent; Dalan does not pass your SSH keys. Terms: https://tunnl.gg/terms. Privacy: https://tunnl.gg/privacy. Continue? [y/N]');
|
|
240
|
+
const consent = await new Promise(resolve => {
|
|
241
|
+
if (inputEnded || signal?.aborted) { resolve(false); return; }
|
|
242
|
+
const finish = answer => {
|
|
243
|
+
lines.off('line', onLine); lines.off('close', onClose); signal?.removeEventListener('abort', onClose);
|
|
244
|
+
resolve(['y', 'yes'].includes(String(answer ?? '').trim().toLowerCase()));
|
|
245
|
+
};
|
|
246
|
+
const onLine = answer => finish(answer);
|
|
247
|
+
const onClose = () => finish(null);
|
|
248
|
+
lines.once('line', onLine); lines.once('close', onClose); signal?.addEventListener('abort', onClose, { once: true });
|
|
249
|
+
});
|
|
250
|
+
if (!consent) throw Object.assign(new Error('No public route was started because relay consent was not given.'), { tryKind: 'consent' });
|
|
251
|
+
}
|
|
252
|
+
trialEndsAt = trialMs === null ? null : clock.now() + trialMs;
|
|
253
|
+
try {
|
|
254
|
+
for (const message of routeMessages) say(message);
|
|
255
|
+
if (selectionError) throw selectionError;
|
|
256
|
+
route = await startRoute({ selectedProvider, gatePort: gate.port, home, say, signal, ...(trialEndsAt === null ? {} : { lifetimeEndsAt: trialEndsAt }) });
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
routeStopped = error?.routeCleanup ?? routeStopped;
|
|
260
|
+
if (error?.tryKind === 'node_retained') {
|
|
261
|
+
keepRecoveredNode = true;
|
|
262
|
+
error.message += `\nStart a fresh trial with: ${cli} try --public --client ${client} --route ${routeChoice} --home ${shellQuote(path.join(realHome, '.local/share', `dalan-hosted-${randomBytes(3).toString('hex')}`))}`;
|
|
263
|
+
}
|
|
264
|
+
if (error && typeof error === 'object' && !signal?.aborted) {
|
|
265
|
+
error.tryKind ??= 'route_start';
|
|
266
|
+
// A real route never turns into a trial link without the owner choosing it.
|
|
267
|
+
if (realRoute && error instanceof Error) error.message += '\nA Tailscale route never falls back to a trial relay on its own. Fix Tailscale and run again, or choose the Gozar demo route.';
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
if (route.exited) route.exited.then(() => markRouteLost(route.endedBecause?.() ?? route.provider.endedBecause?.() ?? 'provider_lost'));
|
|
272
|
+
const origin = route.origin;
|
|
273
|
+
say(`Public route ready (${route.provider.name}).`);
|
|
274
|
+
if (storedOrigin && storedOrigin !== origin) {
|
|
275
|
+
const error = new Error(`this home was set up for ${storedOrigin}, but the new public address is ${origin}. A new address is a new sign-in identity. Start a fresh trial instead${route.provider.name === 'tailscale-node' ? ` with: ${cli} try --public --client ${client} --route ${routeChoice} --home ${shellQuote(path.join(realHome, '.local/share', `dalan-hosted-${randomBytes(3).toString('hex')}`))}` : ''}`);
|
|
276
|
+
error.tryKind = 'identity';
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
signal?.throwIfAborted();
|
|
280
|
+
|
|
281
|
+
say('Starting isolated trial…');
|
|
282
|
+
bindPort = await (deps.pickPort ?? choosePort)({ requested: options.port, stored: null, skip: new Set() });
|
|
283
|
+
errorContext.bindPort = bindPort;
|
|
284
|
+
if (freshHome) await dalan(['init', '--worker', HOSTED_WORKER, '--public-url', origin]);
|
|
285
|
+
startServer();
|
|
286
|
+
if (!await waitForListening()) {
|
|
287
|
+
const error = new Error(`the bridge did not start; last log lines:\n${fs.readFileSync(logFile, 'utf8').trim().split('\n').slice(-5).join('\n')}`);
|
|
288
|
+
error.tryKind = 'startup';
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
errorContext.started = true;
|
|
292
|
+
const secret = /^BRIDGE_PATH_SECRET=(.+)$/m.exec(fs.readFileSync(path.join(configDir, 'env'), 'utf8'))?.[1];
|
|
293
|
+
registerSecret(secret);
|
|
294
|
+
const mcpUrl = `${origin}/${secret}/mcp`;
|
|
295
|
+
const shownResource = `${origin}/<secret>/mcp`;
|
|
296
|
+
const urlFile = path.join(home, 'resource-url');
|
|
297
|
+
fs.rmSync(urlFile, { force: true });
|
|
298
|
+
fs.writeFileSync(urlFile, `${mcpUrl}\n`, { mode: 0o600 });
|
|
299
|
+
fs.chmodSync(urlFile, 0o600);
|
|
300
|
+
|
|
301
|
+
gate.open(bindPort, route.provider.name === 'gozar' ? { gozarOrigin: origin } : {});
|
|
302
|
+
const ready = await verifyPublicReady({ origin, secret, fetchImpl: deps.fetchImpl ?? fetch, clock, timeoutMs: deps.readyMs ?? PUBLIC_READY_MS[route.provider.name], say, signal });
|
|
303
|
+
if (!ready.ready) { if (!signal?.aborted) await route.provider.diagnose?.({ home, say, signal }).catch(() => {}); const error = new Error(`The public route is not ready (${ready.last}); the trial is stopping.`); error.tryKind = 'route'; throw error; }
|
|
304
|
+
say("Public HTTPS, OAuth discovery and the authorization server's metadata verified.");
|
|
305
|
+
|
|
306
|
+
if (!realRoute) {
|
|
307
|
+
identityWatcher = await (deps.watchPublicIdentity ?? watchPublicIdentity)({
|
|
308
|
+
origin, secret, identity: ready.identity, fetchImpl: deps.fetchImpl ?? fetch,
|
|
309
|
+
onStatus: status => { if (status === 'retrying') say('The temporary public link is not responding; checking again.'); },
|
|
310
|
+
});
|
|
311
|
+
identityWatcher.lost.then(loss => markRouteLost(loss.reason));
|
|
312
|
+
const watcherReady = await identityWatcher.ready;
|
|
313
|
+
if (!watcherReady) markRouteLost('identity_changed');
|
|
314
|
+
if (routeDied) throw Object.assign(new Error('The temporary demo link changed or stopped responding during startup; the trial is stopping.'), { tryKind: 'route_lost' });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// The default callback list already holds both clients' published callbacks; the approval below accepts only the selected client's.
|
|
318
|
+
await dalan(['connect', 'start', '--worker', HOSTED_WORKER]);
|
|
319
|
+
const requestId = `req_${randomUUID()}`;
|
|
320
|
+
const phrase = `${REPORT} ${randomBytes(4).toString('hex')}`;
|
|
321
|
+
const requestFile = path.join(home, `${requestId}.json`);
|
|
322
|
+
fs.writeFileSync(requestFile, JSON.stringify({ schema_version: 1, request_id: requestId, brief: `Report the exact phrase: ${phrase}. Do not read files, run commands or call external services.`, inputs: [], expected_output: `Text report containing: ${phrase}.`, execution_scope: 'read-only' }), { mode: 0o600 });
|
|
323
|
+
await dalan(['submit', '--worker', HOSTED_WORKER, '--execution', 'none', '--deliver', 'none', '--file', requestFile, '--json']);
|
|
324
|
+
const job = async () => JSON.parse(await dalan(['get', requestId, '--json']));
|
|
325
|
+
const pendingNow = async () => parsePending(JSON.parse(await dalan(['connect', 'pending', '--json'])));
|
|
326
|
+
|
|
327
|
+
const trialOver = () => expired || (trialEndsAt !== null && clock.now() >= trialEndsAt);
|
|
328
|
+
if (trialMs !== null) {
|
|
329
|
+
const expiry = new Promise(resolve => { expireTimer = setTimeout(() => { expired = true; resolve(); }, Math.max(0, trialEndsAt - clock.now())); expireTimer.unref?.(); });
|
|
330
|
+
routeGone = Promise.race([routeGone, expiry]);
|
|
331
|
+
}
|
|
332
|
+
const trialLeft = () => trialEndsAt === null ? '' : ` Local shutdown limit: ${timeLeft(trialEndsAt - clock.now())}. The temporary link can stop earlier.`;
|
|
333
|
+
if (trialEndsAt !== null) say(`This trial has a local shutdown limit of ${timeLeft(trialEndsAt - clock.now())}; the temporary link can stop earlier or without warning. Run \`dalan setup\` to choose Tailscale when available, or keep using temporary Gozar links. Setup does not install a background service.`);
|
|
334
|
+
say('');
|
|
335
|
+
say(handoffText({ client, url: mcpUrl }));
|
|
336
|
+
say('');
|
|
337
|
+
say(`Waiting for sign-in. Ctrl-C stops the trial and attempts to remove its public route. This terminal shows the connection code. Type help here to see the ${spec.label} steps again. The URL is also in ${urlFile}.`);
|
|
338
|
+
|
|
339
|
+
const showPrompt = () => say(`Finish sign-in in its browser tab, then enable "${CONNECTOR_NAME}" in a ${spec.label} chat. Paste this into the chat:\n${hostedPrompt(requestId, phrase)}`);
|
|
340
|
+
const seen = new Set();
|
|
341
|
+
let approvedConnection = null, reminded = 0, retryNow = false, stage = 'signin';
|
|
342
|
+
let remindAt = clock.now() + DIAGNOSE_AFTER_MS;
|
|
343
|
+
const stageNote = () => ({
|
|
344
|
+
signin: `No sign-in request yet. Add ${CONNECTOR_NAME} in ${spec.label} and start sign-in. Type help here to see the steps again.`,
|
|
345
|
+
approved: 'Approval succeeded, but the client has not claimed the job. Finish sign-in and send this prompt in a chat with the connector enabled.',
|
|
346
|
+
claimed: 'The demo is claimed. Check the chat for a tool approval or a stopped response.',
|
|
347
|
+
}[stage]);
|
|
348
|
+
const stillCurrent = async attempt => (await pendingNow()).pending.some(p => p.code === attempt.code && !p.superseded);
|
|
349
|
+
const approve = async attempt => {
|
|
350
|
+
if (routeDied || !await stillCurrent(attempt) || routeDied) return false;
|
|
351
|
+
try { return JSON.parse(await dalan(['connect', 'approve', attempt.code, '--worker', HOSTED_WORKER, '--replace', '--json'])).result ?? true; }
|
|
352
|
+
catch (error) { if (routeDied) return false; if (exited || await stillCurrent(attempt)) throw error; return false; }
|
|
353
|
+
};
|
|
354
|
+
// Help is read from the same input as the answers: a line that is not an answer is checked for it.
|
|
355
|
+
let asking = false;
|
|
356
|
+
lines.on('line', line => { if (line.trim().toLowerCase() === 'help' && !asking) { if (stage === 'approved') { showPrompt(); return; } say(`${spec.label}\n${spec.steps.map((step, i) => `${i + 1}. ${step}`).join('\n')}\n(The connector URL is in ${urlFile}.)`); } });
|
|
357
|
+
const askOnce = async question => { asking = true; try { return await ask(question); } finally { asking = false; } };
|
|
358
|
+
|
|
359
|
+
while (!exited && !stopRequested() && !routeDied && !trialOver()) {
|
|
360
|
+
const current = await job();
|
|
361
|
+
if (current.status === 'finished') {
|
|
362
|
+
const result = String(current.report?.result ?? '');
|
|
363
|
+
// Proof: this job, finished as completed, with this run's own phrase, by the one connection this owner approved.
|
|
364
|
+
const connection = JSON.parse(await dalan(['connect', 'list', '--json'])).connections?.find(c => c.worker === HOSTED_WORKER && c.revoked_at === null);
|
|
365
|
+
const proven = current.report?.outcome === 'completed' && result.includes(phrase) && approvedConnection !== null && connection?.connection_id === approvedConnection;
|
|
366
|
+
if (!proven) {
|
|
367
|
+
say(`\nThe hosted client finished ${requestId}, but not as the demo asked (outcome ${terminalSafe(String(current.report?.outcome ?? 'unknown'))}). Not counting this as a confirmed run. Report:\n${terminalSafe(result || '(empty)')}`);
|
|
368
|
+
say('Ctrl-C stops the trial.');
|
|
369
|
+
await untilStopRequested();
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
say('Hosted worker completed the demo.');
|
|
373
|
+
say(`Report: ${terminalSafe(result)}`);
|
|
374
|
+
const answer = await askOnce('Accept this result? [y/N] ');
|
|
375
|
+
if (answer?.trim().toLowerCase() === 'y') { await dalan(['decide', requestId, 'accepted']); say(`Recorded as accepted. The trial stays available until you press Ctrl-C.`); }
|
|
376
|
+
else say(stopRequested() ? '\nNot recorded.' : `Not recorded. Decide later while the trial runs:\n${commandLine(ownCommand('decide', requestId, 'accepted'))}`);
|
|
377
|
+
if (!stopRequested() && !routeDied && !exited && !trialOver()) await untilStopRequested();
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
if (current.status === 'queued') {
|
|
381
|
+
let view = await pendingNow();
|
|
382
|
+
if (!view.window) { await dalan(['connect', 'start', '--worker', HOSTED_WORKER]); view = await pendingNow(); }
|
|
383
|
+
for (const attempt of view.pending) {
|
|
384
|
+
if (seen.has(attempt.code) || attempt.superseded) continue;
|
|
385
|
+
seen.add(attempt.code);
|
|
386
|
+
const { text, blocked } = describeAttempt(attempt, shownResource);
|
|
387
|
+
say(`\nConnection waiting for your approval\n${text}\naccess the trial worker's demo queue`);
|
|
388
|
+
if (blocked) { say('Not approving: this attempt names a different resource than this trial.'); continue; }
|
|
389
|
+
if (!callbackAllowed(client, attempt.redirect_uri)) { say(`Not approving: its callback is not ${spec.label}'s. If you are using the other client, restart with --client ${client === 'chatgpt' ? 'claude' : 'chatgpt'}.`); continue; }
|
|
390
|
+
if (attempt.native) { say('Not approving: this is a local program, not a hosted client.'); continue; }
|
|
391
|
+
say('Check that the code matches the Dalan sign-in page you opened.');
|
|
392
|
+
const answer = await askOnce('Approve this connection? [y/N] ');
|
|
393
|
+
remindAt = Math.max(remindAt, clock.now() + DIAGNOSE_AFTER_MS);
|
|
394
|
+
if (answer?.trim().toLowerCase() === 'y' && !routeDied) {
|
|
395
|
+
const result = await approve(attempt);
|
|
396
|
+
if (routeDied) {
|
|
397
|
+
break;
|
|
398
|
+
}
|
|
399
|
+
if (result) { approvedConnection = result.connection_id ?? (await dalan(['connect', 'list', '--json']).then(t => JSON.parse(t).connections.find(c => c.worker === HOSTED_WORKER && c.revoked_at === null)?.connection_id ?? null)); stage = 'approved'; say('Connection approved.'); showPrompt(); }
|
|
400
|
+
else {
|
|
401
|
+
say(`That attempt is no longer current or expired (attempts last ${PAIRING_MINUTES} minutes). Start the sign-in again in ${spec.label}; its new code appears here.`);
|
|
402
|
+
retryNow = (await pendingNow()).pending.some(p => !p.superseded && !seen.has(p.code));
|
|
403
|
+
}
|
|
404
|
+
break;
|
|
405
|
+
}
|
|
406
|
+
if (stopRequested()) { say('\nNot approved.'); break; }
|
|
407
|
+
say(`Not approved. Start sign-in again in ${spec.label}; approve the new matching code here to get the demo prompt.`);
|
|
408
|
+
}
|
|
409
|
+
} else if (stage !== 'claimed') { stage = 'claimed'; say(`Hosted worker claimed ${requestId}.`); }
|
|
410
|
+
if (reminded < DIAGNOSE_LIMIT && !exited && !stopRequested() && clock.now() >= remindAt) { say(`\n${stageNote()}${trialLeft()}`); if (stage === 'approved') showPrompt(); reminded++; remindAt = clock.now() + DIAGNOSE_EVERY_MS; }
|
|
411
|
+
if (retryNow) { retryNow = false; continue; }
|
|
412
|
+
await Promise.race([clock.sleep(POLL_MS), untilStopRequested()]);
|
|
413
|
+
}
|
|
414
|
+
if (routeDied && !stopRequested()) {
|
|
415
|
+
const changed = routeLossReason === 'rotated' || routeLossReason === 'identity_changed';
|
|
416
|
+
const error = new Error(`The temporary demo link ${changed ? 'changed its address' : 'stopped responding'}. The connector cannot use this URL; the trial is stopping. Its saved reports stay in the trial Home.`);
|
|
417
|
+
error.tryKind = 'route_lost'; throw error;
|
|
418
|
+
}
|
|
419
|
+
if (trialOver() && !stopRequested()) { const error = new Error(`The temporary trial reached its ${timeLeft(trialMs)} shutdown limit. Route cleanup will be attempted. Start a fresh trial for a new link, or run dalan setup to choose Tailscale when available. Setup does not install a background service.`); error.tryKind = 'route'; throw error; }
|
|
420
|
+
if (exited && !stopRequested()) { const error = new Error('the bridge stopped unexpectedly'); error.tryKind = 'unexpected'; throw error; }
|
|
421
|
+
} catch (error) {
|
|
422
|
+
if (signal?.aborted) { /* a normal stop */ }
|
|
423
|
+
else throw error;
|
|
424
|
+
} finally {
|
|
425
|
+
lines.close();
|
|
426
|
+
clearTimeout(expireTimer);
|
|
427
|
+
await identityWatcher?.stop();
|
|
428
|
+
// Close forwarding first, then end the connection while the bridge can still answer, then remove the route and stop the bridge.
|
|
429
|
+
gate?.shut();
|
|
430
|
+
if (errorContext.started && !exited) await dalan(['connect', 'revoke', HOSTED_WORKER], { abortable: false }).catch(() => {});
|
|
431
|
+
if (route) routeStopped = await route.stop().catch(error => ({ removed: false, keepNode: true, detail: error.message }));
|
|
432
|
+
await stopServer();
|
|
433
|
+
await gate?.close();
|
|
434
|
+
// The connector URL and the bridge's secrets are no use after the trial and stay on disk for nobody.
|
|
435
|
+
removeTrialSecrets(home, configDir, { keepConfig: STABLE_ORIGIN_ROUTES.has(route?.provider.name), keepNode: keepRecoveredNode || Boolean(routeStopped?.keepNode) });
|
|
436
|
+
releaseHome();
|
|
437
|
+
cleaned = routeStopped ? routeStopped.removed : true;
|
|
438
|
+
if (!cleaned) { process.exitCode = 1; out.write(`dalan: Bridge stopped; public-route cleanup is unconfirmed: ${terminalSafe(routeStopped.detail)}\n${routeStopped.command ? `Remove it with:\n${commandLine(routeStopped.command)}\n` : ''}`); }
|
|
439
|
+
}
|
|
440
|
+
if (route && cleaned) say('Public route removed. Bridge stopped.');
|
|
441
|
+
else if (!route) say('No public route was started. Bridge stopped.');
|
|
442
|
+
say(`Trial history kept at ${home}`);
|
|
443
|
+
say(`To run it again: ${retry().trim()}`);
|
|
444
|
+
}
|