@tnunamak/dalan 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -2
- package/CONTRIBUTING.md +2 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +121 -34
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +2 -1
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +77 -14
- package/docs/pull-workers.md +11 -1
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +4 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/test-suite-isolation.md +7 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +21 -7
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/cli-help.mjs +14 -3
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +44 -9
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +212 -7
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +503 -98
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +64 -19
- package/src/service-update.mjs +193 -48
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/store.mjs +876 -120
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +34 -7
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/src/try-hosted.mjs
CHANGED
|
@@ -12,11 +12,14 @@ import { waitForChildExit } from './child-exit.mjs';
|
|
|
12
12
|
import { createLineMasker, safeDiagnostic } from './diagnostic.mjs';
|
|
13
13
|
import { registerSecret } from './redaction.mjs';
|
|
14
14
|
import { defaultPath } from './paths.mjs';
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
15
|
+
import { adminSocketPath } from './admin-socket.mjs';
|
|
16
|
+
import { PAIRING_MINUTES, writeAtomic } from './as-files.mjs';
|
|
17
|
+
import { verifyPublicReady, watchPublicIdentity } from './try-exposure.mjs';
|
|
18
|
+
import { RouteError, closeExactRoute, observeRetainedRoute, routeNotDispatched, monitorRoute, waitForPublication, resolveRouteWord, buildQuery, describeCandidate, describeDisclosure, ensureDurableRoute, explainRouteError, gozarHomeFor, resolveGozar, startSessionRoute } from './gozar-routes.mjs';
|
|
19
|
+
import { muteableTerminal, runRouteSetup } from './route-setup.mjs';
|
|
18
20
|
import { readRouteSetting } from './route-setting.mjs';
|
|
19
21
|
import { childRegistry, registerChild, sweepChildren } from './child-registry.mjs';
|
|
22
|
+
import { acquirePrivateLock } from './service-update-lock.mjs';
|
|
20
23
|
|
|
21
24
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
22
25
|
const HOSTED_WORKER = 'hosted';
|
|
@@ -33,31 +36,45 @@ export const hostedPrompt = (requestId, requestPhrase) =>
|
|
|
33
36
|
export const handoffText = ({ url }) => [`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, '', ...STEPS.map((step, i) => `${i + 1}. ${step}`)].map(line => terminalSafe(line)).join('\n');
|
|
34
37
|
// Files that hold a credential of a finished trial. The job history stays.
|
|
35
38
|
// A home that a restart reuses keeps the bridge's own config (its path secret); the others lose it.
|
|
36
|
-
export function removeTrialSecrets(home, configDir, { keepConfig = false } = {}) {
|
|
37
|
-
for (const file of [path.join(home, 'resource-url'), ...(keepConfig ? [] : [path.join(configDir, 'env')])]) fs.rmSync(file, { force: true });
|
|
39
|
+
export function removeTrialSecrets(home, configDir, { keepConfig = false, skipHandoff = false } = {}) {
|
|
40
|
+
for (const file of [...(skipHandoff ? [] : [path.join(home, 'resource-url')]), ...(keepConfig ? [] : [path.join(configDir, 'env')])]) fs.rmSync(file, { force: true });
|
|
38
41
|
}
|
|
39
42
|
const REPORT = 'bridge first report';
|
|
40
43
|
|
|
41
|
-
//
|
|
44
|
+
// Keep a kernel-released lock while checking or replacing the PID marker used by older trials.
|
|
42
45
|
export function acquireHomeLock(home) {
|
|
43
46
|
const file = path.join(home, '.hosted-lock');
|
|
44
47
|
const token = `${process.pid} ${randomBytes(8).toString('hex')}`;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
const message = `another trial is using this home; stop it first or choose a new --home (if none is running, delete ${file})`;
|
|
49
|
+
const busy = () => Object.assign(new Error(message), { tryKind: 'already_running' });
|
|
50
|
+
let releaseLock;
|
|
51
|
+
try { releaseLock = acquirePrivateLock(path.join(home, '.hosted-lock.sqlite'), message); }
|
|
52
|
+
catch (error) { if (error.message === message) throw busy(); throw error; }
|
|
53
|
+
try {
|
|
54
|
+
let fd;
|
|
55
|
+
try { fd = fs.openSync(file, 'wx', 0o600); }
|
|
56
|
+
catch (error) {
|
|
51
57
|
if (error.code !== 'EEXIST') throw error;
|
|
52
58
|
const raw = fs.readFileSync(file, 'utf8').trim();
|
|
53
59
|
const match = /^([1-9]\d*)(?:\s+\S+)?$/.exec(raw);
|
|
54
60
|
const pid = match ? Number(match[1]) : NaN;
|
|
55
61
|
if (!Number.isSafeInteger(pid)) throw busy();
|
|
56
|
-
try { process.kill(pid, 0); throw busy(); } catch (probe) { if (probe.
|
|
57
|
-
fs.rmSync(file
|
|
62
|
+
try { process.kill(pid, 0); throw busy(); } catch (probe) { if (probe.code !== 'ESRCH') throw busy(); }
|
|
63
|
+
fs.rmSync(file);
|
|
64
|
+
fd = fs.openSync(file, 'wx', 0o600);
|
|
58
65
|
}
|
|
66
|
+
try { fs.writeSync(fd, token); }
|
|
67
|
+
catch (error) { fs.rmSync(file, { force: true }); throw error; }
|
|
68
|
+
finally { fs.closeSync(fd); }
|
|
69
|
+
return () => {
|
|
70
|
+
try { if (fs.readFileSync(file, 'utf8') === token) fs.rmSync(file); }
|
|
71
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
72
|
+
finally { releaseLock(); }
|
|
73
|
+
};
|
|
74
|
+
} catch (error) {
|
|
75
|
+
releaseLock();
|
|
76
|
+
throw error;
|
|
59
77
|
}
|
|
60
|
-
throw busy();
|
|
61
78
|
}
|
|
62
79
|
|
|
63
80
|
// Said once, before any public address exists. Setup chooses a route; it does not install a service.
|
|
@@ -69,7 +86,8 @@ export const REAL_NOTICE = fromSetup => `Using a stable route${fromSetup ? ', th
|
|
|
69
86
|
|
|
70
87
|
// Reads answers from one terminal reader and closes it, so the trial's own reader starts clean.
|
|
71
88
|
export async function chooseMode({ input, out, signal }) {
|
|
72
|
-
const
|
|
89
|
+
const terminal = muteableTerminal(input, out);
|
|
90
|
+
const lines = readline.createInterface({ input, terminal: terminal.terminal, output: terminal.output });
|
|
73
91
|
let ended = false;
|
|
74
92
|
lines.once('close', () => { ended = true; });
|
|
75
93
|
const ask = question => ended || signal?.aborted ? Promise.resolve(null) : new Promise(resolve => {
|
|
@@ -97,12 +115,12 @@ export async function chooseMode({ input, out, signal }) {
|
|
|
97
115
|
// A stable route keeps its home (and so its sign-in); a temporary route gets a new home each time.
|
|
98
116
|
export const restartCommand = ({ cli, home, freshHome, shellQuote, route, stable }) => `${cli} try --public${route === undefined ? '' : ` --route ${shellQuote(route)}`} --home ${shellQuote(stable ? home : freshHome)}`;
|
|
99
117
|
|
|
100
|
-
export async function runHosted({ options, env, out, input, signal, errorContext, clock = { now:
|
|
118
|
+
export async function runHosted({ options, env, out, input, signal, errorContext, clock = { now: () => performance.now(), sleep }, deps = {}, helpers }) {
|
|
101
119
|
const { prepareHome, portFree, socketAnswers, choosePort, shellQuote, commandLine, parsePending, describeAttempt, MARKER, DIAGNOSE_AFTER_MS, DIAGNOSE_EVERY_MS, DIAGNOSE_LIMIT, POLL_MS, repo } = helpers;
|
|
102
120
|
const say = line => out.write(`${terminalSafe(line)}\n`);
|
|
103
121
|
// With no --route, a route saved by `dalan setup` is used as a durable route; an explicit --route name is a session route for this trial.
|
|
104
122
|
const saved = options.route === undefined ? readRouteSetting(env) : null;
|
|
105
|
-
const durable = saved !== null && saved.
|
|
123
|
+
const durable = saved !== null && saved.routeId !== null;
|
|
106
124
|
const realHome = fs.realpathSync(os.homedir());
|
|
107
125
|
let stableAddress = durable; // a session route learns its stability from Gozar once it exists
|
|
108
126
|
const home = prepareHome(options.home ?? env.DALAN_HOME ?? path.join(realHome, '.local/share', durable ? 'dalan-hosted' : `dalan-hosted-${randomBytes(3).toString('hex')}`), realHome);
|
|
@@ -115,21 +133,27 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
115
133
|
errorContext.shellHome = shellQuote(home); errorContext.logFile = logFile; errorContext.shellLog = shellQuote(logFile);
|
|
116
134
|
errorContext.tryFlags = ` --public${options.route === undefined ? '' : ` --route ${shellQuote(options.route)}`}`;
|
|
117
135
|
const freshRestartHome = path.join(realHome, '.local/share', `dalan-hosted-${randomBytes(3).toString('hex')}`);
|
|
118
|
-
const retry = () => commandLine(restartCommand({ cli, home, freshHome: freshRestartHome, shellQuote, route: options.route, stable: stableAddress }));
|
|
136
|
+
const retry = (keepReference = false) => commandLine(restartCommand({ cli, home, freshHome: freshRestartHome, shellQuote, route: options.route, stable: stableAddress || keepReference }));
|
|
119
137
|
errorContext.freshTrialCommand = retry().trim();
|
|
120
138
|
|
|
121
139
|
// 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.
|
|
122
140
|
const registry = childRegistry(env);
|
|
123
|
-
|
|
141
|
+
let leftovers = [];
|
|
142
|
+
try { leftovers = await (deps.sweepChildren ?? sweepChildren)({ registry }); }
|
|
143
|
+
catch (error) {
|
|
144
|
+
const detail = safeDiagnostic(error?.message ?? String(error), 160);
|
|
145
|
+
out.write(`Could not check for leftovers from earlier trials (${detail}). Run gozar route list to check for old routes.\n`);
|
|
146
|
+
}
|
|
124
147
|
if (leftovers.length) out.write(`Ended ${leftovers.length} process${leftovers.length === 1 ? '' : 'es'} left by an earlier trial.\n`);
|
|
125
148
|
// A home that already has a bridge or another trial's profile is never reused silently.
|
|
126
|
-
const adminSock = defaultPath(home, '.local/share/dot-bridge'
|
|
149
|
+
const adminSock = adminSocketPath(defaultPath(home, '.local/share/dot-bridge'));
|
|
127
150
|
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' });
|
|
128
151
|
let freshHome = true, storedOrigin = null;
|
|
129
152
|
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; }
|
|
130
153
|
try { storedOrigin = new URL(JSON.parse(fs.readFileSync(path.join(configDir, 'as.json'), 'utf8')).public_url).origin; } catch { /* a new home */ }
|
|
131
154
|
|
|
132
|
-
const
|
|
155
|
+
const terminal = muteableTerminal(input, out);
|
|
156
|
+
const lines = readline.createInterface({ input, terminal: terminal.terminal, output: terminal.output });
|
|
133
157
|
let inputEnded = false;
|
|
134
158
|
lines.once('close', () => { inputEnded = true; });
|
|
135
159
|
const stopRequested = () => signal?.aborted || inputEnded;
|
|
@@ -141,6 +165,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
141
165
|
if (routeDied) return;
|
|
142
166
|
routeDied = true;
|
|
143
167
|
routeLossReason = reason;
|
|
168
|
+
if (reason !== 'handoff_failed') fs.rmSync(path.join(home, 'resource-url'), { force: true });
|
|
144
169
|
resolveRouteGone();
|
|
145
170
|
};
|
|
146
171
|
// 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.
|
|
@@ -160,7 +185,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
160
185
|
|
|
161
186
|
const baseEnv = {
|
|
162
187
|
...Object.fromEntries(['PATH', 'TMPDIR', 'LANG', 'NODE_OPTIONS'].filter(k => env[k] !== undefined).map(k => [k, env[k]])),
|
|
163
|
-
HOME: home, DALAN_AUTH_MODE: 'builtin', DALAN_TRIAL_SSE: '1', ...(deps.serverEnv ?? {}),
|
|
188
|
+
HOME: home, DALAN_AUTH_MODE: 'builtin', DALAN_TRIAL_SSE: '1', DALAN_GOZAR_SERVICE: '1', ...(deps.serverEnv ?? {}),
|
|
164
189
|
};
|
|
165
190
|
let bindPort = null;
|
|
166
191
|
// `abortable: false` is for cleanup: Ctrl-C must not cancel the revocation.
|
|
@@ -171,7 +196,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
171
196
|
const startServer = () => {
|
|
172
197
|
const log = fs.openSync(logFile, 'w', 0o600); fs.fchmodSync(log, 0o600); fs.closeSync(log);
|
|
173
198
|
exited = false;
|
|
174
|
-
server = spawn(process.execPath, [path.join(repo, 'src/server.mjs')], { env: { ...baseEnv, DALAN_PORT: String(bindPort) }, cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
199
|
+
server = (deps.spawnServer ?? spawn)(process.execPath, [path.join(repo, 'src/server.mjs')], { env: { ...baseEnv, DALAN_PORT: String(bindPort) }, cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
175
200
|
const forgetServer = registerChild({ registry, child: server });
|
|
176
201
|
server.once('close', forgetServer);
|
|
177
202
|
const child = server;
|
|
@@ -188,15 +213,27 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
188
213
|
if (!exited) { server.kill('SIGKILL'); await stopped; }
|
|
189
214
|
};
|
|
190
215
|
const waitForListening = async () => {
|
|
191
|
-
|
|
192
|
-
|
|
216
|
+
const deadline = performance.now() + 20_000;
|
|
217
|
+
while (!exited && performance.now() < deadline) {
|
|
193
218
|
signal?.throwIfAborted();
|
|
194
|
-
|
|
219
|
+
if (/MCP listening/.test(fs.readFileSync(logFile, 'utf8'))) return true;
|
|
220
|
+
await Promise.race([stopped, sleep(100)]);
|
|
195
221
|
}
|
|
196
|
-
return
|
|
222
|
+
return false;
|
|
197
223
|
};
|
|
198
224
|
|
|
199
|
-
let
|
|
225
|
+
let gozar, route = null, routeStopped = null, cleaned = true;
|
|
226
|
+
const earlyStop = Symbol('hosted trial stopped');
|
|
227
|
+
let cleanupError, cleanupStep, trialError, trialFailed = false, handoffAnnounced = false;
|
|
228
|
+
const stopResult = { workerAccessRevocationWarning: null };
|
|
229
|
+
const referenceFile = path.join(home, '.route-reference.json');
|
|
230
|
+
let routeRef, dispatchedHere = false;
|
|
231
|
+
const remember = ref => {
|
|
232
|
+
const entry = { ...ref, port: bindPort };
|
|
233
|
+
writeAtomic(referenceFile, JSON.stringify(entry));
|
|
234
|
+
routeRef = entry;
|
|
235
|
+
if (ref.phase === 'dispatching') dispatchedHere = true;
|
|
236
|
+
};
|
|
200
237
|
let identityWatcher = null;
|
|
201
238
|
let trialEndsAt = null;
|
|
202
239
|
let releaseHome;
|
|
@@ -204,29 +241,67 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
204
241
|
try {
|
|
205
242
|
say(durable ? REAL_NOTICE(true) : TRIAL_NOTICE);
|
|
206
243
|
say('Checking public routes…');
|
|
207
|
-
|
|
244
|
+
const configuredHome = saved?.gozarHome ?? gozarHomeFor(env);
|
|
245
|
+
try {
|
|
246
|
+
routeRef = JSON.parse(fs.readFileSync(referenceFile, 'utf8'));
|
|
247
|
+
errorContext.freshTrialCommand = retry(true).trim();
|
|
248
|
+
if (typeof routeRef?.home !== 'string' || !path.isAbsolute(routeRef.home) || typeof routeRef.operationId !== 'string') {
|
|
249
|
+
throw new RouteError('route_conflict', 'The saved trial route reference is invalid.');
|
|
250
|
+
}
|
|
251
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
252
|
+
const routeHome = routeRef?.home ?? configuredHome;
|
|
253
|
+
gozar = deps.gozar ?? await resolveGozar({ env, home: routeHome });
|
|
254
|
+
if (routeRef) {
|
|
255
|
+
const observed = await observeRetainedRoute(gozar, routeRef);
|
|
256
|
+
if (observed.state === 'recorded') {
|
|
257
|
+
const { view } = observed;
|
|
258
|
+
const result = view.state === 'released' && view.published === null && view.cleanup.state === 'confirmed' ? { removed: true }
|
|
259
|
+
: await closeExactRoute(gozar, { ...routeRef, handle: view.handle });
|
|
260
|
+
if (!result.removed) throw new RouteError('cleanup_debt', result.detail);
|
|
261
|
+
fs.unlinkSync(referenceFile);
|
|
262
|
+
routeRef = null;
|
|
263
|
+
} else if (durable || (options.port && routeRef.port && options.port !== routeRef.port)) {
|
|
264
|
+
throw new RouteError('route_conflict', 'Resume the saved trial operation with its original route mode and port.');
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
bindPort = await (deps.pickPort ?? choosePort)({ requested: options.port, stored: routeRef?.port ?? (durable ? 8789 : null), skip: new Set() });
|
|
268
|
+
errorContext.bindPort = bindPort;
|
|
208
269
|
signal?.throwIfAborted();
|
|
209
270
|
trialEndsAt = trialMs === null ? null : clock.now() + trialMs;
|
|
210
271
|
// Gozar answers the owner's questions; Dalan only shows what it returned and asks once.
|
|
211
|
-
const
|
|
212
|
-
say(
|
|
272
|
+
const askRoute = question => {
|
|
273
|
+
say(question);
|
|
213
274
|
return new Promise(resolve => {
|
|
214
|
-
if (inputEnded || signal?.aborted) { resolve(
|
|
215
|
-
const finish = answer => { lines.off('line', onLine); lines.off('close', onClose); signal?.removeEventListener('abort', onClose); resolve(
|
|
275
|
+
if (inputEnded || signal?.aborted) { resolve(null); return; }
|
|
276
|
+
const finish = answer => { lines.off('line', onLine); lines.off('close', onClose); signal?.removeEventListener('abort', onClose); resolve(answer); };
|
|
216
277
|
const onLine = answer => finish(answer);
|
|
217
278
|
const onClose = () => finish(null);
|
|
218
279
|
lines.once('line', onLine); lines.once('close', onClose); signal?.addEventListener('abort', onClose, { once: true });
|
|
219
280
|
});
|
|
220
281
|
};
|
|
282
|
+
const consent = async candidate => {
|
|
283
|
+
say(describeCandidate(candidate).join('\n'));
|
|
284
|
+
say(describeDisclosure(candidate).join('\n'));
|
|
285
|
+
return /^y(es)?$/i.test(String(await askRoute('Use this route? [y/N]') ?? '').trim());
|
|
286
|
+
};
|
|
287
|
+
const setup = candidate => runRouteSetup({ gozar, candidate, home: routeHome, env, say, ask: askRoute,
|
|
288
|
+
...(terminal.terminal && {
|
|
289
|
+
async askSecret(label) {
|
|
290
|
+
terminal.mute(true);
|
|
291
|
+
try { return Buffer.from(await askRoute(`${label} (hidden):`) ?? ''); }
|
|
292
|
+
finally { terminal.mute(false); out.write('\n'); }
|
|
293
|
+
},
|
|
294
|
+
handoff(href) { out.write(`${href}\n`); },
|
|
295
|
+
}),
|
|
296
|
+
});
|
|
221
297
|
try {
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
usage: durable ? { kind: 'durable', routeId: saved.routeId } : { kind: 'session', lifetimeMs: trialMs }, ...(durable ? { origin: saved.origin, address: 'stable' } : {}) });
|
|
298
|
+
const wanted = buildQuery({ home: routeHome, target: `127.0.0.1:${bindPort}`, route: options.route ?? saved?.routeName ?? undefined,
|
|
299
|
+
usage: durable ? { kind: 'durable', routeId: saved.routeId } : { kind: 'session', lifetimeMs: trialMs }, ...(durable ? { ...(saved.origin ? { origin: saved.origin } : {}), address: 'stable' } : {}) });
|
|
225
300
|
const { query, pick } = await resolveRouteWord({ gozar, query: wanted });
|
|
226
301
|
if (durable) {
|
|
227
|
-
const view = await ensureDurableRoute({ gozar, query, consent, pick });
|
|
228
|
-
route = {
|
|
229
|
-
} else route = await startSessionRoute({ gozar, query, consent, signal, wait: 'allocated', pick });
|
|
302
|
+
const view = await ensureDurableRoute({ gozar, query, consent, pick, setup });
|
|
303
|
+
route = monitorRoute({ gozar, home: query.home, view, remove: false });
|
|
304
|
+
} else route = await startSessionRoute({ gozar, query, consent, signal, wait: 'allocated', pick, remember, setup, recovery: routeRef });
|
|
230
305
|
if (!durable) stableAddress = route.view?.properties?.address?.stability === 'stable';
|
|
231
306
|
}
|
|
232
307
|
catch (error) {
|
|
@@ -241,8 +316,11 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
241
316
|
throw error;
|
|
242
317
|
}
|
|
243
318
|
if (route.exited) route.exited.then(() => markRouteLost(route.endedBecause() ?? 'route_lost'));
|
|
319
|
+
const checkHandoff = () => {
|
|
320
|
+
const error = route.handoffFailure?.();
|
|
321
|
+
if (error) { error.tryKind = 'handoff'; throw error; }
|
|
322
|
+
};
|
|
244
323
|
const origin = route.origin;
|
|
245
|
-
say('Public route ready.');
|
|
246
324
|
if (storedOrigin && storedOrigin !== origin) {
|
|
247
325
|
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 with: ${retry().trim()}`);
|
|
248
326
|
error.tryKind = 'identity';
|
|
@@ -251,28 +329,48 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
251
329
|
signal?.throwIfAborted();
|
|
252
330
|
|
|
253
331
|
say('Starting isolated trial…');
|
|
254
|
-
bindPort = await (deps.pickPort ?? choosePort)({ requested: options.port, stored: null, skip: new Set() });
|
|
255
|
-
errorContext.bindPort = bindPort;
|
|
256
332
|
if (freshHome) await dalan(['init', '--worker', HOSTED_WORKER, '--public-url', origin]);
|
|
333
|
+
const readSecret = () => /^BRIDGE_PATH_SECRET=(.+)$/m.exec(fs.readFileSync(path.join(configDir, 'env'), 'utf8'))?.[1];
|
|
334
|
+
try { registerSecret(readSecret()); }
|
|
335
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
257
336
|
startServer();
|
|
258
337
|
if (!await waitForListening()) {
|
|
259
|
-
const
|
|
338
|
+
const log = fs.readFileSync(logFile, 'utf8');
|
|
339
|
+
const portInUse = /(?:^|\n)(?:Error:[ \t]*)?listen EADDRINUSE(?=[: \t\r\n]|$)/.test(log);
|
|
340
|
+
const error = new Error(portInUse ? 'the bridge did not start: listen EADDRINUSE' : 'the bridge did not start; see the private server log');
|
|
260
341
|
error.tryKind = 'startup';
|
|
261
342
|
throw error;
|
|
262
343
|
}
|
|
263
344
|
errorContext.started = true;
|
|
264
|
-
const secret =
|
|
345
|
+
const secret = readSecret();
|
|
265
346
|
registerSecret(secret);
|
|
266
347
|
const mcpUrl = `${origin}/${secret}/mcp`;
|
|
267
348
|
const shownResource = `${origin}/<secret>/mcp`;
|
|
268
349
|
const urlFile = path.join(home, 'resource-url');
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
350
|
+
try { await waitForPublication({ gozar, home: routeHome, handle: route.handle, origin, signal, timeoutMs: deps.readyMs ?? PUBLIC_READY_MS }); }
|
|
351
|
+
catch (error) {
|
|
352
|
+
const { fix } = explainRouteError(error);
|
|
353
|
+
if (fix) say(`Next: ${fix}`);
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
let sdkPublished = false, handoffEnabled = false;
|
|
357
|
+
let publication = Promise.withResolvers();
|
|
358
|
+
const writeHandoff = () => writeAtomic(urlFile, `${mcpUrl}\n`);
|
|
359
|
+
void route.watchPublished(available => {
|
|
360
|
+
sdkPublished = available;
|
|
361
|
+
if (available) {
|
|
362
|
+
if (handoffEnabled && !routeDied && !stopRequested()) writeHandoff();
|
|
363
|
+
publication.resolve();
|
|
364
|
+
} else {
|
|
365
|
+
fs.rmSync(urlFile, { force: true });
|
|
366
|
+
publication = Promise.withResolvers();
|
|
367
|
+
if (handoffEnabled) say('Gozar withdrew route proof. Waiting for verification of the same address.');
|
|
368
|
+
}
|
|
369
|
+
});
|
|
370
|
+
// A local handoff failure the route watcher already recorded is the cause; a readiness failure it raced with is a symptom.
|
|
371
|
+
const ready = await verifyPublicReady({ origin, secret, fetchImpl: deps.fetchImpl ?? fetch, clock, timeoutMs: deps.readyMs ?? PUBLIC_READY_MS, say, signal })
|
|
372
|
+
.catch(error => { if (!stopRequested()) checkHandoff(); throw error; });
|
|
373
|
+
if (!ready.ready) { if (!stopRequested()) checkHandoff(); const error = new Error(`The public route is not ready (${ready.last}); the trial is stopping.`); error.tryKind = 'route'; throw error; }
|
|
276
374
|
say("Public HTTPS, OAuth discovery and the authorization server's metadata verified.");
|
|
277
375
|
|
|
278
376
|
if (!durable) {
|
|
@@ -283,9 +381,12 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
283
381
|
identityWatcher.lost.then(loss => markRouteLost(loss.reason));
|
|
284
382
|
const watcherReady = await identityWatcher.ready;
|
|
285
383
|
if (!watcherReady) markRouteLost('identity_changed');
|
|
384
|
+
checkHandoff();
|
|
286
385
|
if (routeDied) throw Object.assign(new Error('The temporary demo link changed or stopped responding during startup; the trial is stopping.'), { tryKind: 'route_lost' });
|
|
287
386
|
}
|
|
288
387
|
|
|
388
|
+
checkHandoff();
|
|
389
|
+
if (routeDied) throw Object.assign(new Error('Gozar withdrew the public route during startup.'), { tryKind: 'route_lost' });
|
|
289
390
|
await dalan(['connect', 'start', '--worker', HOSTED_WORKER]);
|
|
290
391
|
const requestId = `req_${randomUUID()}`;
|
|
291
392
|
const phrase = `${REPORT} ${randomBytes(4).toString('hex')}`;
|
|
@@ -301,8 +402,20 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
301
402
|
routeGone = Promise.race([routeGone, expiry]);
|
|
302
403
|
}
|
|
303
404
|
const trialLeft = () => trialEndsAt === null ? '' : ` Local shutdown limit: ${timeLeft(trialEndsAt - clock.now())}. The temporary link can stop earlier.`;
|
|
405
|
+
const proofDeadline = AbortSignal.timeout(deps.readyMs ?? PUBLIC_READY_MS);
|
|
406
|
+
const proofTimedOut = new Promise(resolve => proofDeadline.addEventListener('abort', resolve, { once: true }));
|
|
407
|
+
while (!sdkPublished && !routeDied && !stopRequested() && !trialOver() && !proofDeadline.aborted) {
|
|
408
|
+
await Promise.race([publication.promise, untilStopRequested(), proofTimedOut]);
|
|
409
|
+
}
|
|
410
|
+
if (stopRequested()) throw earlyStop;
|
|
411
|
+
checkHandoff();
|
|
412
|
+
if (routeDied) throw Object.assign(new Error('Gozar withdrew the public route during startup.'), { tryKind: 'route_lost' });
|
|
413
|
+
if (!sdkPublished || trialOver()) throw Object.assign(new Error('Gozar did not verify the same public address before the handoff deadline.'), { tryKind: 'route' });
|
|
414
|
+
handoffEnabled = true;
|
|
415
|
+
writeHandoff();
|
|
304
416
|
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 a stable route. Setup does not install a background service.`);
|
|
305
417
|
say('');
|
|
418
|
+
handoffAnnounced = true;
|
|
306
419
|
say(handoffText({ url: mcpUrl }));
|
|
307
420
|
say('');
|
|
308
421
|
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 steps again. The URL is also in ${urlFile}.`);
|
|
@@ -318,16 +431,21 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
318
431
|
}[stage]);
|
|
319
432
|
const stillCurrent = async attempt => (await pendingNow()).pending.some(p => p.code === attempt.code && !p.superseded);
|
|
320
433
|
const approve = async attempt => {
|
|
321
|
-
if (routeDied || !await stillCurrent(attempt) || routeDied) return false;
|
|
434
|
+
if (!sdkPublished || routeDied || !await stillCurrent(attempt) || !sdkPublished || routeDied) return false;
|
|
322
435
|
try { return JSON.parse(await dalan(['connect', 'approve', attempt.code, '--worker', HOSTED_WORKER, '--replace', '--json'])).result ?? true; }
|
|
323
436
|
catch (error) { if (routeDied) return false; if (exited || await stillCurrent(attempt)) throw error; return false; }
|
|
324
437
|
};
|
|
325
438
|
// Help is read from the same input as the answers: a line that is not an answer is checked for it.
|
|
326
439
|
let asking = false;
|
|
327
|
-
lines.on('line', line => { if (line.trim().toLowerCase() === 'help' && !asking) {
|
|
440
|
+
lines.on('line', line => { if (line.trim().toLowerCase() === 'help' && !asking) {
|
|
441
|
+
if (!sdkPublished) { say('Waiting for Gozar to verify the public route.'); return; }
|
|
442
|
+
if (stage === 'approved') { showPrompt(); return; }
|
|
443
|
+
say(`${STEPS.map((step, i) => `${i + 1}. ${step}`).join('\n')}\n(The connector URL is in ${urlFile}.)`);
|
|
444
|
+
} });
|
|
328
445
|
const askOnce = async question => { asking = true; try { return await ask(question); } finally { asking = false; } };
|
|
329
446
|
|
|
330
447
|
while (!exited && !stopRequested() && !routeDied && !trialOver()) {
|
|
448
|
+
if (!sdkPublished) { await Promise.race([publication.promise, untilStopRequested()]); continue; }
|
|
331
449
|
const current = await job();
|
|
332
450
|
if (current.status === 'finished') {
|
|
333
451
|
const result = String(current.report?.result ?? '');
|
|
@@ -362,6 +480,11 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
362
480
|
const answer = await askOnce('Approve this connection? [y/N] ');
|
|
363
481
|
remindAt = Math.max(remindAt, clock.now() + DIAGNOSE_AFTER_MS);
|
|
364
482
|
if (answer?.trim().toLowerCase() === 'y' && !routeDied) {
|
|
483
|
+
if (!sdkPublished) {
|
|
484
|
+
seen.delete(attempt.code);
|
|
485
|
+
say('The route is waiting for proof. Approval was not recorded.');
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
365
488
|
const result = await approve(attempt);
|
|
366
489
|
if (routeDied) {
|
|
367
490
|
break;
|
|
@@ -381,6 +504,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
381
504
|
if (retryNow) { retryNow = false; continue; }
|
|
382
505
|
await Promise.race([clock.sleep(POLL_MS), untilStopRequested()]);
|
|
383
506
|
}
|
|
507
|
+
if (!stopRequested()) checkHandoff();
|
|
384
508
|
if (routeDied && !stopRequested()) {
|
|
385
509
|
const changed = routeLossReason === 'rotated' || routeLossReason === 'identity_changed';
|
|
386
510
|
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.`);
|
|
@@ -389,26 +513,89 @@ export async function runHosted({ options, env, out, input, signal, errorContext
|
|
|
389
513
|
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 a stable route. Setup does not install a background service.`); error.tryKind = 'route'; throw error; }
|
|
390
514
|
if (exited && !stopRequested()) { const error = new Error('the bridge stopped unexpectedly'); error.tryKind = 'unexpected'; throw error; }
|
|
391
515
|
} catch (error) {
|
|
392
|
-
if (signal?.aborted) {
|
|
393
|
-
|
|
516
|
+
if (error !== earlyStop && !signal?.aborted) {
|
|
517
|
+
trialFailed = true;
|
|
518
|
+
trialError = error;
|
|
519
|
+
}
|
|
520
|
+
|
|
394
521
|
} finally {
|
|
522
|
+
|
|
523
|
+
const cleanup = async (step, run) => {
|
|
524
|
+
try { await run(); }
|
|
525
|
+
catch (cause) {
|
|
526
|
+
if (!cleanupError) {
|
|
527
|
+
cleanupStep = step;
|
|
528
|
+
cleanupError = new Error(`Trial shutdown could not confirm ${step}.`, { cause });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
};
|
|
395
532
|
lines.close();
|
|
396
533
|
clearTimeout(expireTimer);
|
|
397
|
-
await identityWatcher?.stop();
|
|
398
|
-
//
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
534
|
+
await cleanup('identity watcher cleanup', () => identityWatcher?.stop());
|
|
535
|
+
// Withdraw handoff, revoke the trial's app credentials, then close the retained route.
|
|
536
|
+
let ignoredHandoffCleanup = false;
|
|
537
|
+
await cleanup('handoff cleanup', () => {
|
|
538
|
+
try { fs.rmSync(path.join(home, 'resource-url'), { force: true }); }
|
|
539
|
+
catch (error) {
|
|
540
|
+
if (handoffAnnounced || !route?.handoffFailure?.()) throw error;
|
|
541
|
+
ignoredHandoffCleanup = true;
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
if (errorContext.started) {
|
|
545
|
+
if (exited) stopResult.workerAccessRevocationWarning = 'worker access revocation not confirmed';
|
|
546
|
+
else {
|
|
547
|
+
try {
|
|
548
|
+
const revoke = deps.revokeWorkerAccess ?? (() => dalan(['connect', 'revoke', HOSTED_WORKER], { abortable: false }));
|
|
549
|
+
await revoke();
|
|
550
|
+
} catch {
|
|
551
|
+
stopResult.workerAccessRevocationWarning = 'worker access revocation not confirmed';
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
errorContext.stopResult = stopResult;
|
|
556
|
+
if (route || (dispatchedHere && routeRef && !routeNotDispatched(routeRef))) {
|
|
557
|
+
await cleanup('route cleanup', async () => {
|
|
558
|
+
try { routeStopped = route ? await route.stop() : await closeExactRoute(gozar, routeRef); }
|
|
559
|
+
catch (error) {
|
|
560
|
+
routeStopped = { removed: false, detail: safeDiagnostic(error.message, 240) };
|
|
561
|
+
throw error;
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
if (routeRef && routeStopped?.removed) {
|
|
566
|
+
await cleanup('route reference cleanup', () => fs.rmSync(referenceFile, { force: true }));
|
|
567
|
+
}
|
|
568
|
+
if (routeRef && !routeStopped?.removed) errorContext.freshTrialCommand = retry(true).trim();
|
|
569
|
+
await cleanup('bridge shutdown', stopServer);
|
|
570
|
+
// Stable routes retain the bridge configuration, including its path secret, for the next run.
|
|
571
|
+
// A failed handoff can also leave a private resource file when its removal was already attempted.
|
|
572
|
+
await cleanup('trial secrets cleanup', () => removeTrialSecrets(home, configDir, { keepConfig: stableAddress, skipHandoff: ignoredHandoffCleanup }));
|
|
573
|
+
await cleanup('trial home release', releaseHome);
|
|
574
|
+
if (stopResult.workerAccessRevocationWarning) say(`${stopResult.workerAccessRevocationWarning}.`);
|
|
407
575
|
cleaned = routeStopped ? routeStopped.removed : true;
|
|
408
|
-
if (!cleaned)
|
|
576
|
+
if (!cleaned) out.write(`dalan: Bridge stopped; public-route cleanup is unconfirmed: ${terminalSafe(routeStopped.detail)}\n`);
|
|
577
|
+
if (cleanupError) {
|
|
578
|
+
stopResult.cleanupWarning = cleanupError.message;
|
|
579
|
+
out.write(`dalan: ${cleanupError.message}\n`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (trialFailed) {
|
|
583
|
+
// Cleanup that threw, or a started route whose removal was not confirmed, is reported with the trial failure as its
|
|
584
|
+
// cause. A route that never started keeps the trial's own error.
|
|
585
|
+
if (cleanupError || (route && !cleaned)) {
|
|
586
|
+
const debt = new RouteError('cleanup_debt', cleanupError?.message ?? 'Gozar could not confirm route removal.');
|
|
587
|
+
throw Object.assign(debt, { cause: trialError });
|
|
588
|
+
}
|
|
589
|
+
throw trialError;
|
|
590
|
+
}
|
|
591
|
+
if (!cleaned && (!cleanupError || cleanupStep === 'route cleanup')) throw new RouteError('cleanup_debt', 'Gozar could not confirm route removal.');
|
|
592
|
+
if (stopResult.cleanupWarning) {
|
|
593
|
+
throw Object.assign(cleanupError, { tryKind: 'unexpected' });
|
|
409
594
|
}
|
|
410
|
-
if (route
|
|
411
|
-
else if (
|
|
595
|
+
if (route) say(durable ? 'Bridge stopped. The saved route remains.' : 'Public route removed. Bridge stopped.');
|
|
596
|
+
else if (routeRef) say('Bridge stopped. The saved route operation is retained.');
|
|
597
|
+
else say('No public route was started. Bridge stopped.');
|
|
412
598
|
say(`Trial history kept at ${home}`);
|
|
413
|
-
say(`To run it again: ${retry().trim()}`);
|
|
599
|
+
say(`To run it again: ${retry(!!routeRef && !routeStopped?.removed).trim()}`);
|
|
600
|
+
return stopResult;
|
|
414
601
|
}
|