@tnunamak/dalan 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/CONTRIBUTING.md +26 -0
  3. package/LICENSE +204 -0
  4. package/PROTOCOL.md +339 -0
  5. package/README.md +348 -2
  6. package/SECURITY.md +30 -0
  7. package/bin/dalan.mjs +38 -0
  8. package/bin/dot-acp-agent.mjs +377 -0
  9. package/bin/dot-alert.mjs +9 -0
  10. package/bin/dot-deadman.mjs +82 -0
  11. package/bin/dot-heartbeat.mjs +29 -0
  12. package/bin/dot-pr-reviewer.mjs +32 -0
  13. package/bin/dot-worker.mjs +755 -0
  14. package/docs/chatgpt-worker-onboarding.md +112 -0
  15. package/docs/claude-worker-onboarding.md +113 -0
  16. package/docs/connect-chatgpt.md +78 -0
  17. package/docs/connection-longevity.md +37 -0
  18. package/docs/dalan-upgrade.md +242 -0
  19. package/docs/deadman.md +59 -0
  20. package/docs/dot-pr-reviewer.config.example.json +9 -0
  21. package/docs/durability-audit.md +27 -0
  22. package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
  23. package/docs/keycloak-oauth-setup.md +30 -0
  24. package/docs/local-agent-mcp.md +39 -0
  25. package/docs/manual-setup.md +135 -0
  26. package/docs/mirror-fetch.md +98 -0
  27. package/docs/operations.md +751 -0
  28. package/docs/operator-duties.md +68 -0
  29. package/docs/owner-integrator.md +27 -0
  30. package/docs/portable-auth-profile.md +109 -0
  31. package/docs/pr-head-reviewer.md +54 -0
  32. package/docs/pr-preflight.md +26 -0
  33. package/docs/pull-workers.md +97 -0
  34. package/docs/redaction.md +27 -0
  35. package/docs/service-setup.md +166 -0
  36. package/docs/setup-reference.md +80 -0
  37. package/docs/t3-connector-icon.png +0 -0
  38. package/docs/t3-integration.md +49 -0
  39. package/docs/t3-result-retry-delivery.md +41 -0
  40. package/docs/t3-reverse-control.md +107 -0
  41. package/docs/usage.md +439 -0
  42. package/docs/worker-clients.md +285 -0
  43. package/integrations/t3/acp-kit/src/capability.mjs +25 -0
  44. package/integrations/t3/acp-kit/src/errors.mjs +13 -0
  45. package/integrations/t3/acp-kit/src/index.mjs +5 -0
  46. package/integrations/t3/acp-kit/src/lock.mjs +155 -0
  47. package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
  48. package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
  49. package/package.json +65 -4
  50. package/packages/job-core/README.md +18 -0
  51. package/packages/job-core/index.mjs +2 -0
  52. package/packages/job-core/package.json +8 -0
  53. package/packages/job-core/protocol/canonical.mjs +11 -0
  54. package/packages/job-core/protocol/v0/command.schema.json +1154 -0
  55. package/packages/job-core/protocol/v0/event.schema.json +77 -0
  56. package/packages/job-core/protocol/v0/reply.schema.json +59 -0
  57. package/packages/job-core/transitions.mjs +25 -0
  58. package/scripts/daily-selfcheck.mjs +135 -0
  59. package/scripts/lib/expose-tailscale.mjs +408 -0
  60. package/scripts/live-trial/common.mjs +272 -0
  61. package/scripts/monitor-targets.mjs +44 -0
  62. package/scripts/upgrade-drain.mjs +39 -0
  63. package/scripts/worker-bridge-setup.mjs +925 -0
  64. package/src/ack-ledger.mjs +37 -0
  65. package/src/acp-bridge.mjs +412 -0
  66. package/src/acp-context.mjs +138 -0
  67. package/src/admin-socket.mjs +14 -0
  68. package/src/alerts.mjs +147 -0
  69. package/src/artifact-journal.mjs +75 -0
  70. package/src/as-files.mjs +347 -0
  71. package/src/as-store.mjs +456 -0
  72. package/src/as.mjs +497 -0
  73. package/src/auth.mjs +166 -0
  74. package/src/builtin-http.mjs +22 -0
  75. package/src/check-coverage.mjs +38 -0
  76. package/src/check-lint.mjs +88 -0
  77. package/src/check-readiness.mjs +112 -0
  78. package/src/check-response.mjs +19 -0
  79. package/src/claim-command-ledger.mjs +51 -0
  80. package/src/cli-help.mjs +172 -0
  81. package/src/cli-name.mjs +16 -0
  82. package/src/connect-cli.mjs +126 -0
  83. package/src/consumers.mjs +61 -0
  84. package/src/deadman.mjs +329 -0
  85. package/src/delivery.mjs +19 -0
  86. package/src/demo-worker.mjs +150 -0
  87. package/src/destinations/index.mjs +23 -0
  88. package/src/destinations/none.mjs +15 -0
  89. package/src/destinations/t3.mjs +109 -0
  90. package/src/diagnostic.mjs +78 -0
  91. package/src/docs-url.mjs +9 -0
  92. package/src/drain-runner.mjs +9 -0
  93. package/src/drained-slot.mjs +53 -0
  94. package/src/drained.mjs +40 -0
  95. package/src/durable-waiters.mjs +236 -0
  96. package/src/env.mjs +19 -0
  97. package/src/execution.mjs +112 -0
  98. package/src/failure-type.mjs +28 -0
  99. package/src/get-summary.mjs +32 -0
  100. package/src/git-env.mjs +15 -0
  101. package/src/host-budget-receipts.mjs +154 -0
  102. package/src/host-budget-seccomp.py +33 -0
  103. package/src/host-budget-service.mjs +54 -0
  104. package/src/host-budget-stop.mjs +26 -0
  105. package/src/host-budget-storage.py +259 -0
  106. package/src/host-budget.mjs +149 -0
  107. package/src/host-cgroup.mjs +23 -0
  108. package/src/host-check-allowlist.mjs +42 -0
  109. package/src/host-execution-policy.mjs +38 -0
  110. package/src/host-health.mjs +34 -0
  111. package/src/host-stop-reverify.mjs +44 -0
  112. package/src/inbox.mjs +55 -0
  113. package/src/integrator.mjs +322 -0
  114. package/src/job-retention.mjs +69 -0
  115. package/src/legacy-names.mjs +8 -0
  116. package/src/lifecycle.mjs +291 -0
  117. package/src/limits.mjs +31 -0
  118. package/src/loopback.mjs +9 -0
  119. package/src/mcp-outcome.mjs +70 -0
  120. package/src/mcp-stdio.mjs +191 -0
  121. package/src/mirror-fetch-lock.py +164 -0
  122. package/src/mirror-fetch.mjs +174 -0
  123. package/src/notify-ledger.mjs +82 -0
  124. package/src/objectives.mjs +129 -0
  125. package/src/owner-report-artifact.mjs +66 -0
  126. package/src/patch-apply.mjs +84 -0
  127. package/src/path-syntax.mjs +16 -0
  128. package/src/paths.mjs +67 -0
  129. package/src/pr-head-reviewer.mjs +596 -0
  130. package/src/pr-preflight.mjs +51 -0
  131. package/src/prepared-node-modules.mjs +129 -0
  132. package/src/projects.mjs +480 -0
  133. package/src/protocol-artifact-commands.mjs +52 -0
  134. package/src/protocol-delivery-driver.mjs +167 -0
  135. package/src/protocol-finish.mjs +100 -0
  136. package/src/protocol-owner-command.mjs +35 -0
  137. package/src/protocol-owner-mutations.mjs +22 -0
  138. package/src/protocol-owner-waiters.mjs +67 -0
  139. package/src/protocol-retention.mjs +52 -0
  140. package/src/protocol-services.mjs +61 -0
  141. package/src/protocol-stop-observer.mjs +131 -0
  142. package/src/publish-plan.mjs +245 -0
  143. package/src/redaction.mjs +763 -0
  144. package/src/rejections.mjs +18 -0
  145. package/src/request-log.mjs +102 -0
  146. package/src/restore-check.mjs +90 -0
  147. package/src/result-binding.mjs +65 -0
  148. package/src/runtime-check.mjs +13 -0
  149. package/src/sandbox-supervisor.mjs +105 -0
  150. package/src/schema-subset.mjs +186 -0
  151. package/src/scopes.mjs +15 -0
  152. package/src/server.mjs +1340 -0
  153. package/src/shutdown-signal.mjs +12 -0
  154. package/src/signal-sandbox-processes.py +56 -0
  155. package/src/signal.mjs +119 -0
  156. package/src/status-evidence.mjs +47 -0
  157. package/src/status-summary.mjs +54 -0
  158. package/src/store.mjs +3057 -0
  159. package/src/submission-policy.mjs +623 -0
  160. package/src/subscription-storage.mjs +64 -0
  161. package/src/t3-audit.mjs +120 -0
  162. package/src/t3-control.mjs +102 -0
  163. package/src/t3-transport.mjs +158 -0
  164. package/src/t3.mjs +209 -0
  165. package/src/terminal-safe.mjs +19 -0
  166. package/src/tool-registry.mjs +451 -0
  167. package/src/try-command.mjs +11 -0
  168. package/src/try.mjs +589 -0
  169. package/src/webhooks.mjs +86 -0
  170. package/src/work-order.mjs +265 -0
  171. package/src/worker-instructions.mjs +26 -0
  172. package/src/worker-prompt.mjs +4 -0
  173. package/src/workers.mjs +622 -0
  174. package/src/workspace.mjs +1058 -0
  175. package/systemd/dot-bridge-heartbeat.service +18 -0
  176. package/systemd/dot-bridge-heartbeat.timer +10 -0
  177. package/systemd/dot-bridge-selfcheck.service +12 -0
  178. package/systemd/dot-bridge-selfcheck.timer +11 -0
  179. package/systemd/dot-bridge.service +17 -0
  180. package/systemd/dot-deadman.service +30 -0
  181. package/systemd/dot-pr-reviewer.service +11 -0
  182. package/systemd/dot-pr-reviewer.timer +10 -0
package/src/try.mjs ADDED
@@ -0,0 +1,589 @@
1
+ // `dalan try`: the README's same-machine walk as one command. It creates a private trial home, starts the loopback
2
+ // server, pairs a built-in demo worker through the real OAuth flow and finishes one job. Then it queues a second
3
+ // job for the user's own worker, asks before approving that worker, and waits for its report.
4
+ // Every bridge action is the ordinary `dalan` command or `src/server.mjs`, run as a child process with the trial home as HOME.
5
+ import { terminalSafe } from './terminal-safe.mjs';
6
+ import { execFile, spawn } from 'node:child_process';
7
+ import { randomUUID } from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import net from 'node:net';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import readline from 'node:readline';
13
+ import { defaultPath } from './paths.mjs';
14
+ import { cliCommand } from './cli-name.mjs';
15
+ import { docsUrl } from './docs-url.mjs';
16
+ import { workerPrompt } from './worker-prompt.mjs';
17
+ import { createLineMasker, safeDiagnostic } from './diagnostic.mjs';
18
+ import { registerSecret } from './redaction.mjs';
19
+ import { PAIRING_MINUTES, untrusted } from './as-files.mjs';
20
+ import { beginPairing, DEMO_REDIRECT, workJob, workRepositoryJob } from './demo-worker.mjs';
21
+ import { writeWorkerInstructions } from './worker-instructions.mjs';
22
+ import { SOCKET_PATH_LIMIT } from './admin-socket.mjs';
23
+
24
+
25
+ const repo = path.resolve(import.meta.dirname, '..');
26
+ const WORKER = 'local';
27
+ const BRIEF = 'Report the exact phrase: bridge first report. Do not read files, run commands or call external services.';
28
+ const REPORT = 'bridge first report';
29
+ const MARKER = '.dalan-trial';
30
+ const DEFAULT_CALLBACKS = ['http://127.0.0.1/callback', 'http://localhost/callback'];
31
+ const USAGE = 'usage: dalan try [--home DIR] [--port N] [--callback PATTERN]...';
32
+ const DEMO_REPO = 'dalan-demo/hello';
33
+ const DENIED_REPO = 'dalan-demo/other';
34
+ const DEMO_TITLE = 'Hello from the Dalan demo repository';
35
+ const DIAGNOSE_AFTER_MS = 60_000; // no worker has claimed the job after this long: say what to check
36
+ const DIAGNOSE_EVERY_MS = 300_000;
37
+ const DIAGNOSE_LIMIT = 3;
38
+ const POLL_MS = 1500;
39
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
40
+ const shellQuote = value => `'${String(value).replaceAll("'", "'\\''")}'`;
41
+
42
+ // Every command the user must run sits alone on a line, indented, with nothing after it, so it can be pasted as written.
43
+ const commandLine = command => ` ${command}`;
44
+ const commandBlock = (label, ...commands) => `${label}\n${commands.map(commandLine).join('\n')}`;
45
+
46
+ // A home that does not exist yet and a port that is free now, for the "start over somewhere else" command. A reused trial home
47
+ // is tied to its port, so a new port needs a new home.
48
+ async function alternateTrial(preferPort) {
49
+ const free = async skip => {
50
+ if (preferPort && await portFree(preferPort)) return preferPort;
51
+ for (let port = 8799; port < 8820; port++) if (port !== skip && await portFree(port)) return port;
52
+ return null;
53
+ };
54
+ for (const base of [fs.realpathSync(os.homedir()), fs.realpathSync(os.tmpdir())]) {
55
+ for (let n = 2; n < 100; n++) {
56
+ const home = path.join(base, `.dalan-trial-${n}`);
57
+ if (fs.existsSync(home) || Buffer.byteLength(defaultPath(home, '.local/share/dot-bridge', 'admin.sock')) > SOCKET_PATH_LIMIT) continue;
58
+ return { home, port: await free(null) };
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function formatTryError(error, context, alternate = null) {
65
+ const cause = safeDiagnostic(error?.message ?? String(error), 4000);
66
+ const cli = context.cli ?? `node ${context.shellCli}`;
67
+ const newHome = label => alternate && commandBlock(label, `${cli} try --home ${shellQuote(alternate.home)}${alternate.port ? ` --port ${alternate.port}` : ''}`);
68
+ const recover = (head, withNewHome) => [`${cause}${head}`, commandBlock('Read the log with:', `cat ${context.shellLog}`),
69
+ commandBlock('Retry this home with:', `${cli} try --home ${context.shellHome}`), withNewHome ? newHome('To try again in a new home instead, run:') : null].filter(Boolean).join('\n');
70
+ if (error?.tryKind === 'startup') return recover(`\nThe bridge did not start. Full log: ${context.logFile}`, true);
71
+ if (context.started) {
72
+ const invariant = error?.tryKind === 'invariant' ? '\nStop and report this failure; do not grant broader access.' : '';
73
+ return recover(`${invariant}\nServer log: ${context.logFile}`, error?.tryKind === 'unexpected');
74
+ }
75
+ if (error?.tryKind === 'already_running') return cause;
76
+ const notStarted = `${cause}\nThe server has not started; no server log was created for this attempt.`;
77
+ if (error?.freePort && context.shellHome) return `${notStarted}\n${commandBlock('Stop that program, or run the trial on a free port:', `${cli} try --home ${context.shellHome} --port ${error.freePort}`)}`;
78
+ return `${notStarted}\nFix the problem above, then run the command again.${alternate ? ` ${newHome('Or start a trial in a new home:')}` : ''}`;
79
+ }
80
+
81
+ function printTryError(out, error, context) { out.write(`dalan: ${formatTryError(error, context)}\n`); }
82
+
83
+ // The message `dalan try` prints for a failure, with a concrete new-home command where one helps.
84
+ export async function describeTryError(error, context) {
85
+ return formatTryError(error, context, await alternateTrial(error?.alternatePort).catch(() => null));
86
+ }
87
+
88
+ export function parseTryArgs(argv) {
89
+ const out = { home: null, port: null, callbacks: [] };
90
+ for (let i = 0; i < argv.length; i++) {
91
+ const [flag, value] = [argv[i], argv[i + 1]];
92
+ if (!['--home', '--port', '--callback'].includes(flag)) throw new Error(`unknown option ${JSON.stringify(flag)}\n${USAGE}`);
93
+ if (value === undefined || value.startsWith('--')) throw new Error(`${flag} needs a value\n${USAGE}`);
94
+ i++;
95
+ if (flag === '--home') out.home = value;
96
+ else if (flag === '--callback') out.callbacks.push(value);
97
+ else if (/^\d+$/.test(value) && Number(value) > 0 && Number(value) < 65536) out.port = Number(value);
98
+ else throw new Error('--port requires a number from 1 to 65535');
99
+ }
100
+ return out;
101
+ }
102
+
103
+ // The shape of `dalan connect pending --json`. Anything else is an error: this decides what the owner is asked to
104
+ // approve, so a changed format must stop the command, not leave a connection silently unasked.
105
+ export function parsePending(result) {
106
+ const bad = why => new Error(`unexpected output from \`dalan connect pending --json\` (${why}); not guessing which connection to approve`);
107
+ if (!result || typeof result !== 'object' || !Array.isArray(result.pending)) throw bad('no pending list');
108
+ if (result.window !== null && typeof result.window?.worker !== 'string') throw bad('bad window');
109
+ const pending = result.pending.map(p => {
110
+ for (const key of ['code', 'client_id', 'redirect_uri']) if (typeof p?.[key] !== 'string' || !p[key]) throw bad(`attempt without ${key}`);
111
+ if (!Array.isArray(p.scopes)) throw bad('attempt without scopes');
112
+ return {
113
+ code: p.code, worker: typeof p.worker === 'string' ? p.worker : '', client_id: p.client_id, client_name: typeof p.client_name === 'string' ? p.client_name : '', redirect_uri: p.redirect_uri,
114
+ resource: typeof p.resource === 'string' ? p.resource : '', scopes: p.scopes.map(String), superseded: p.superseded === true, native: p.native === true,
115
+ expires_in_seconds: Number.isFinite(p.expires_in_seconds) ? p.expires_in_seconds : null,
116
+ };
117
+ });
118
+ // The trial bridge listens on loopback only and its one owner is the one person starting the client, so a client that
119
+ // starts again abandons its older attempt: only the newest native attempt is put to the owner. The bridge itself never
120
+ // supersedes a native attempt, so this is a choice of what `try` asks, not a rule it enforces.
121
+ const newestNative = pending.filter(p => p.native && !p.superseded).at(-1);
122
+ return { window: result.window, pending: pending.map(p => p.native && !p.superseded && p !== newestNative ? { ...p, superseded: true } : p) };
123
+ }
124
+
125
+ // What the owner sees for one attempt. The resource is the MCP URL the app asked to use. A bridge that does not report
126
+ // it is shown as such (not hidden), and a resource that is not this bridge's own URL blocks approval.
127
+ export function describeAttempt(attempt, expectedResource) {
128
+ const q = value => JSON.stringify(untrusted(value, 200));
129
+ const resourceMatches = attempt.resource === '' ? null : attempt.resource === expectedResource;
130
+ const resourceLine = resourceMatches === null ? 'resource (not reported: this bridge did not say which resource the app asked for)'
131
+ : resourceMatches ? `resource ${q(attempt.resource)}` : `resource ${q(attempt.resource)} <-- NOT this bridge's MCP URL`;
132
+ const text = [
133
+ `code ${attempt.code}`, `client_id ${q(attempt.client_id)}`, `client_name [untrusted, set by the app] ${q(attempt.client_name)}`,
134
+ `redirect ${JSON.stringify(String(attempt.redirect_uri ?? '').replace(/[\p{C}\p{Z}]+/gu, ' ').trim())}`, resourceLine, `scopes ${attempt.scopes.map(q).join(' ')}`,
135
+ ...(attempt.native ? ['WARNING native client identity is unverified; host and name prove nothing. Approve only if this code matches the browser page you opened, or the code the person at the worker read to you over a trusted channel.'] : []),
136
+ ].join('\n');
137
+ return { text, blocked: resourceMatches === false, resourceReported: resourceMatches !== null };
138
+ }
139
+
140
+ const portFree = port => new Promise(resolve => {
141
+ const probe = net.createServer();
142
+ probe.once('error', () => resolve(false));
143
+ probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(true)));
144
+ });
145
+
146
+ // Whether a bridge answers on this admin socket: then the trial bridge for that home is already running.
147
+ const socketAnswers = file => new Promise(resolve => {
148
+ const probe = net.connect(file);
149
+ const done = value => { probe.destroy(); resolve(value); };
150
+ probe.setTimeout(1000, () => done(false));
151
+ probe.once('connect', () => done(true));
152
+ probe.once('error', () => done(false));
153
+ });
154
+
155
+ // A free port is a hint: another process can take it before the server binds, so the caller retries on a bind failure.
156
+ async function choosePort({ requested, stored, skip = new Set() }) {
157
+ const wanted = requested ?? stored;
158
+ if (wanted) {
159
+ if (await portFree(wanted)) return wanted;
160
+ // A reused home is tied to its saved port: its issuer URL names it. Another port needs another home.
161
+ if (stored) throw new Error(`port ${wanted} is in use (is another trial still running?). This trial home is tied to port ${stored}. Stop the process that uses it, or start a separate trial in a new home`);
162
+ // This home is not tied to a port yet, so the same home can run on a free one.
163
+ const error = new Error(`cannot start the trial bridge: port ${wanted} is in use by another program`);
164
+ for (let port = 8799; port < 8820; port++) if (port !== wanted && !skip.has(port) && await portFree(port)) { error.freePort = port; break; }
165
+ throw error;
166
+ }
167
+ for (let port = 8799; port < 8820; port++) if (!skip.has(port) && await portFree(port)) return port;
168
+ throw new Error('no free port in 8799-8819; choose one with --port N');
169
+ }
170
+
171
+ // The real path of `target` even when it does not exist yet: the nearest existing ancestor, resolved, plus the rest.
172
+ function realPathThroughAncestors(target) {
173
+ const rest = [];
174
+ let existing = target;
175
+ while (!fs.existsSync(existing) && path.dirname(existing) !== existing) { rest.unshift(path.basename(existing)); existing = path.dirname(existing); }
176
+ return path.join(fs.realpathSync(existing), ...rest);
177
+ }
178
+
179
+ // Decide the trial home, and create it, only after every refusal has been checked. Nothing is created for a refused home.
180
+ function prepareHome(candidate, realHome) {
181
+ const home = path.resolve(candidate);
182
+ if (realPathThroughAncestors(home) === realHome) throw new Error('refusing to use your real home as the trial home; choose another with --home DIR');
183
+ if (fs.existsSync(home)) {
184
+ if (!fs.statSync(home).isDirectory()) throw new Error(`${home} is not a directory; choose another with --home DIR`);
185
+ if (!fs.existsSync(path.join(home, MARKER)) && fs.readdirSync(home).length) {
186
+ throw new Error(`${home} already holds files that a trial did not create (it could be a real Dalan home); choose a new or empty directory with --home DIR`);
187
+ }
188
+ }
189
+ const socket = defaultPath(home, '.local/share/dot-bridge', 'admin.sock');
190
+ if (Buffer.byteLength(socket) > SOCKET_PATH_LIMIT) throw new Error(`the trial home path is too long for the bridge's admin socket (${Buffer.byteLength(socket)} bytes, limit ${SOCKET_PATH_LIMIT}); choose a shorter --home DIR`);
191
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
192
+ fs.chmodSync(home, 0o700);
193
+ fs.writeFileSync(path.join(home, MARKER), 'created by `dalan try`\n', { mode: 0o600 });
194
+ return home;
195
+ }
196
+
197
+ // A one-commit repository that lives in the trial home. The commit time is fixed, so the revision is the same on every run.
198
+ // Returns the bare repository path and the full revision, or null with a reason when git or python3 (which the mirror
199
+ // fetch needs) is missing.
200
+ async function prepareDemoRepository(home, signal, tryAgain) {
201
+ const run = (cmd, args, options = {}) => new Promise((resolve, reject) => execFile(cmd, args, { timeout: 30_000, signal, ...options },
202
+ (error, stdout, stderr) => error ? reject(new Error(`${cmd} ${args.join(' ')} failed: ${safeDiagnostic((stderr || error.message).trim(), 4000)}`)) : resolve(stdout.trim())));
203
+ for (const [tool, arg, fix] of [['git', '--version', 'install Git'], ['python3', '--version', 'install Python 3.8 or newer']]) {
204
+ try { await run(tool, [arg]); } catch (error) { if (signal?.aborted) throw error; return { reason: `${tool} was not found on PATH; ${fix}, then run this command again to see the repository step:\n${commandLine(tryAgain)}` }; }
205
+ }
206
+ const dir = path.join(home, 'demo'), bare = path.join(dir, 'hello.git');
207
+ if (fs.existsSync(dir) && (fs.lstatSync(dir).isSymbolicLink() || !fs.lstatSync(dir).isDirectory())) throw new Error(`${dir} is not a plain directory; remove it, then run this command again:\n${commandLine(tryAgain)}`);
208
+ if (fs.existsSync(bare) && fs.lstatSync(bare).isSymbolicLink()) throw new Error(`${bare} is a symbolic link; remove it, then run this command again:\n${commandLine(tryAgain)}`);
209
+ // The same sanitized environment builds the repository and reads its revision, so no host Git setting reaches either step.
210
+ const when = '2026-01-01T00:00:00Z';
211
+ const env = { PATH: process.env.PATH, HOME: home, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Dalan demo', GIT_AUTHOR_EMAIL: 'demo@example.invalid', GIT_COMMITTER_NAME: 'Dalan demo', GIT_COMMITTER_EMAIL: 'demo@example.invalid', GIT_AUTHOR_DATE: when, GIT_COMMITTER_DATE: when };
212
+ if (!fs.existsSync(bare)) {
213
+ fs.mkdirSync(dir, { recursive: true });
214
+ // A fresh scratch directory each time: an interrupted earlier run or a planted link cannot be reused or followed.
215
+ const work = fs.mkdtempSync(path.join(dir, 'work-'));
216
+ try {
217
+ fs.writeFileSync(path.join(work, 'README.md'), `# ${DEMO_TITLE}\n\nThis repository exists only for \`dalan try\`.\n`);
218
+ await run('git', ['-c', 'init.templateDir=', '-C', work, 'init', '-q', '-b', 'main', '--object-format=sha1'], { env });
219
+ await run('git', ['-C', work, 'add', 'README.md'], { env });
220
+ await run('git', ['-C', work, '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-q', '--no-verify', '-m', 'Add the demo README'], { env });
221
+ await run('git', ['-c', 'init.templateDir=', 'clone', '-q', '--bare', work, bare], { env });
222
+ } finally { fs.rmSync(work, { recursive: true, force: true }); }
223
+ }
224
+ return { bare, sha: await run('git', ['-C', bare, 'rev-parse', 'refs/heads/main'], { env }) };
225
+ }
226
+
227
+ // `pickPort` and `clock` are seams for tests: the first stands in for the free-port search so a lost race can be reproduced,
228
+ // the second for the time and the wait between polls so minutes of waiting need no real minutes.
229
+ // The worker wrote the report; it reaches the terminal only through terminalSafe, right before the acceptance prompt.
230
+ export function finishedNotice(jobId, job) { return terminalSafe(`\n✔ Your worker finished ${jobId}. Report:\n${job.report?.result ?? '(empty)'}`); }
231
+
232
+ export async function runTry({ argv = [], env = process.env, out = process.stdout, input = process.stdin, signal, pickPort = choosePort, errorContext = {}, clock = { now: Date.now, sleep }, beforeCommand = null } = {}) {
233
+ const options = parseTryArgs(argv);
234
+ const realHome = fs.realpathSync(os.homedir());
235
+ const home = prepareHome(options.home ?? env.DALAN_HOME ?? path.join(realHome, '.local/share/dalan-trial'), realHome);
236
+ errorContext.home = home;
237
+ const say = line => out.write(`${terminalSafe(line)}\n`);
238
+ // Commands the user is told to run: the checkout's own CLI by absolute path (dalan need not be on PATH), with the trial home.
239
+ const cliPath = errorContext.shellCli ?? shellQuote(path.join(repo, 'bin/dalan.mjs'));
240
+ const cli = errorContext.cli ?? `node ${cliPath}`;
241
+ const ownCommand = (...words) => `DALAN_HOME=${shellQuote(home)} ${cli} ${words.join(' ')}`;
242
+ const started = Date.now();
243
+ say(`Dalan trial. Home: ${home}`);
244
+ const shellHome = shellQuote(home);
245
+ errorContext.shellHome = shellHome;
246
+
247
+ const configDir = defaultPath(home, '.config/dot-bridge');
248
+ const freshHome = !fs.existsSync(path.join(configDir, 'workers.json'));
249
+ let storedPort = null;
250
+ try { storedPort = Number(new URL(JSON.parse(fs.readFileSync(path.join(configDir, 'as.json'), 'utf8')).public_url).port) || null; } catch { /* a new home */ }
251
+ // This home's own bridge already holds its port. Say so before anything below touches the running trial's grant or files.
252
+ if (storedPort && !await portFree(storedPort) && await socketAnswers(defaultPath(home, '.local/share/dot-bridge', 'admin.sock'))) {
253
+ const error = new Error(`the trial bridge for this home is already running on http://127.0.0.1:${storedPort}. Use it from another terminal (export DALAN_HOME=${shellHome}), or stop it with Ctrl-C in its terminal first.`);
254
+ error.tryKind = 'already_running';
255
+ throw error;
256
+ }
257
+ // The saved public URL names the port and is the issuer; changing it ends every connection. Do not start on another port.
258
+ if (storedPort && options.port && options.port !== storedPort) {
259
+ const error = new Error(`this trial home is tied to port ${storedPort}; it cannot run on port ${options.port}. Start a separate trial in a new home on that port`);
260
+ error.alternatePort = options.port;
261
+ throw error;
262
+ }
263
+
264
+ // Input that has ended (`dalan try < /dev/null`, a closed terminal) is treated like Ctrl-C once the demo is done:
265
+ // nobody can answer a question or press Ctrl-C, so the bridge stops instead of waiting for a signal that cannot come.
266
+ const lines = readline.createInterface({ input });
267
+ let inputEnded = false;
268
+ lines.once('close', () => { inputEnded = true; });
269
+ const stopRequested = () => signal?.aborted || inputEnded;
270
+ const stopPromise = new Promise(resolve => {
271
+ if (signal?.aborted) resolve();
272
+ signal?.addEventListener('abort', resolve, { once: true });
273
+ lines.once('close', resolve);
274
+ });
275
+ // A wait for the owner also ends when the bridge process ends: nobody can finish what the owner is being asked about.
276
+ // `stopped` is replaced when the server restarts, so it is read at the time of the wait.
277
+ const untilStopRequested = () => Promise.race([stopPromise, stopped]);
278
+ // null means no answer: Ctrl-C, the input ended, or the bridge exited.
279
+ const ask = question => {
280
+ if (stopRequested() || exited) return null;
281
+ out.write(question);
282
+ return new Promise(resolve => {
283
+ const done = answer => { lines.off('line', done); lines.off('close', onClose); signal?.removeEventListener('abort', onClose); resolve(answer); };
284
+ const onClose = () => done(null);
285
+ lines.once('line', done); lines.once('close', onClose); signal?.addEventListener('abort', onClose, { once: true });
286
+ stopped.then(onClose);
287
+ });
288
+ };
289
+
290
+ // Repository workspaces are on in the trial. Only the demo repository is redirected, to the local copy above, so the
291
+ // repository step needs no network and no GitHub login. Every other repository is denied until the owner grants it.
292
+ const baseEnv = {
293
+ ...Object.fromEntries(['PATH', 'TMPDIR', 'LANG', 'NODE_OPTIONS'].filter(k => env[k] !== undefined).map(k => [k, env[k]])),
294
+ // A clone URL for a repository the owner names (a local path works), so a worker can use a local clone with no GitHub login.
295
+ ...Object.fromEntries(Object.entries(env).filter(([k, v]) => /^DALAN_GITHUB_URL_[A-Z0-9_]+$/.test(k) && v)),
296
+ HOME: home, DALAN_LOOPBACK: '1', DALAN_AUTH_MODE: 'builtin',
297
+ DALAN_ENABLE_WORKSPACE: '1', DALAN_WORKSPACE_ROOT: path.join(home, 'workspace'), DALAN_MIN_FREE_BYTES: String(256 * 2 ** 20),
298
+ };
299
+ let demoRepo = { reason: 'not prepared' };
300
+ let port = null;
301
+ const dalan = async args => { await beforeCommand?.(args); return runDalan(args); };
302
+ const runDalan = args => new Promise((resolve, reject) => execFile(process.execPath, [path.join(repo, 'bin/dalan.mjs'), ...args],
303
+ { env: { ...baseEnv, DALAN_PORT: String(port) }, cwd: repo, timeout: 30_000, signal }, (error, stdout, stderr) =>
304
+ error ? reject(new Error(`dalan ${args.slice(0, 2).join(' ')} failed: ${safeDiagnostic((stderr || stdout || error.message).trim(), 4000)}`)) : resolve(stdout)));
305
+
306
+ // The trial owns `demo/` and the `req_*.json` request files in its home. Its one authority change is the demo grant.
307
+ // Cleanup runs from the same place on every exit, and again at the next start for a run that was killed. It uses no abort
308
+ // signal, so Ctrl-C cannot cancel the revocation. Job history stays in the trial home: only the grant and the files go.
309
+ const grantHeld = () => {
310
+ try { return JSON.parse(fs.readFileSync(path.join(configDir, 'workers.json'), 'utf8')).workers?.[WORKER]?.repos?.some(r => String(r).toLowerCase() === DEMO_REPO) === true; }
311
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
312
+ };
313
+ // Returns true only when the grant is confirmed gone and the demo files are removed.
314
+ const cleanupTrial = async () => {
315
+ let clean = true;
316
+ try {
317
+ if (grantHeld()) {
318
+ await new Promise((resolve, reject) => execFile(process.execPath, [path.join(repo, 'bin/dalan.mjs'), 'worker', 'deny', WORKER, DEMO_REPO],
319
+ { env: { ...baseEnv, DALAN_PORT: String(port ?? storedPort ?? 8799) }, cwd: repo, timeout: 30_000 }, error => error ? reject(error) : resolve()));
320
+ if (grantHeld()) throw new Error('the grant is still in the profile');
321
+ }
322
+ } catch (error) {
323
+ clean = false;
324
+ printTryError(out, new Error(`Could not revoke the demo grant (${error.message.split('\n')[0]}).\n${commandBlock('Revoke it with:', ownCommand('worker', 'deny', WORKER, DEMO_REPO))}`), errorContext);
325
+ process.exitCode = 1;
326
+ }
327
+ try {
328
+ fs.rmSync(path.join(home, 'demo'), { recursive: true, force: true });
329
+ for (const name of fs.readdirSync(home)) if (/^req_[0-9a-f-]+\.json$/.test(name)) fs.rmSync(path.join(home, name), { force: true });
330
+ } catch (error) { clean = false; printTryError(out, new Error(`Could not remove the demo files in ${home}: ${error.message}`), errorContext); }
331
+ return clean;
332
+ };
333
+
334
+ const logFile = path.join(home, 'server.log');
335
+ errorContext.logFile = logFile;
336
+ errorContext.shellLog = shellQuote(logFile);
337
+ let server = null, exited = true, stopped = Promise.resolve();
338
+ const startServer = () => {
339
+ const log = fs.openSync(logFile, 'w', 0o600);
340
+ fs.fchmodSync(log, 0o600);
341
+ exited = false;
342
+ fs.closeSync(log);
343
+ // Server output is sanitized line by line before it is persisted; a partial line is held until it completes.
344
+ server = spawn(process.execPath, [path.join(repo, 'src/server.mjs')], { env: { ...baseEnv, DALAN_PORT: String(port) }, cwd: repo, stdio: ['ignore', 'pipe', 'pipe'] });
345
+ const child = server;
346
+ const sinks = [child.stdout, child.stderr].map(stream => {
347
+ const persist = createLineMasker(text => fs.appendFileSync(logFile, text));
348
+ stream.setEncoding('utf8').on('data', chunk => persist(chunk));
349
+ return persist;
350
+ });
351
+ stopped = new Promise(resolve => {
352
+ child.once('close', () => { for (const flush of sinks) flush('', true); exited = true; resolve(); });
353
+ child.once('error', error => { fs.appendFileSync(logFile, `spawn failed: ${safeDiagnostic(error.message, 1000)}\n`); exited = true; resolve(); });
354
+ });
355
+ };
356
+ const stop = async () => {
357
+ if (exited) return;
358
+ server.kill('SIGTERM');
359
+ await Promise.race([stopped, sleep(5000)]);
360
+ if (!exited) { server.kill('SIGKILL'); await stopped; }
361
+ };
362
+ const waitForListening = async () => {
363
+ for (let waited = 0; !/MCP listening/.test(fs.readFileSync(logFile, 'utf8')); waited += 100) {
364
+ if (exited || waited > 20_000) return false;
365
+ signal?.throwIfAborted();
366
+ await sleep(100);
367
+ }
368
+ return true;
369
+ };
370
+
371
+ let cleaned = false;
372
+ try {
373
+ await cleanupTrial(); // state left by a run that was killed
374
+ signal?.throwIfAborted();
375
+ demoRepo = await prepareDemoRepository(home, signal, `${cli} try --home ${shellHome}`);
376
+ if (demoRepo.bare) baseEnv.DALAN_GITHUB_URL_DALAN_DEMO_HELLO = demoRepo.bare;
377
+ // The probe for a free port can lose a race with another process, so a bind failure on a port this command chose
378
+ // retries on the next free one. A port the user named, or one a reused home already points at, is not changed.
379
+ const tried = new Set();
380
+ for (let attempt = 1; ; attempt++) {
381
+ port = await pickPort({ requested: options.port, stored: storedPort, skip: tried });
382
+ tried.add(port);
383
+ if (freshHome) await dalan(['init', '--worker', WORKER, '--public-url', `http://127.0.0.1:${port}`]);
384
+ startServer();
385
+ if (await waitForListening()) break;
386
+ const logged = fs.readFileSync(logFile, 'utf8').trim();
387
+ const tail = logged.split('\n').slice(-5).join('\n');
388
+ await stop();
389
+ if (attempt < 3 && freshHome && !options.port && /EADDRINUSE/.test(logged)) { fs.rmSync(configDir, { recursive: true, force: true }); continue; }
390
+ const error = new Error(`the bridge did not start; last log lines:\n${tail}`);
391
+ error.tryKind = 'startup';
392
+ throw error;
393
+ }
394
+ errorContext.started = true;
395
+ say(`✔ Bridge up on http://127.0.0.1:${port}. Loopback only. Log: ${logFile}`);
396
+ const secret = /^BRIDGE_PATH_SECRET=(.+)$/m.exec(fs.readFileSync(path.join(configDir, 'env'), 'utf8'))?.[1];
397
+ registerSecret(secret);
398
+ const mcpUrl = `http://127.0.0.1:${port}/${secret}/mcp`;
399
+ // `connect pending` masks the path secret, so compare against the masked form.
400
+ const shownMcpUrl = `${new URL(mcpUrl).origin}/<secret>/mcp`;
401
+ // The URL is a credential, so it goes to a private file in the trial home, never to the output.
402
+ const urlFile = path.join(home, 'resource-url');
403
+ fs.rmSync(urlFile, { force: true });
404
+ fs.writeFileSync(urlFile, `${mcpUrl}\n`, { mode: 0o600 });
405
+ fs.chmodSync(urlFile, 0o600);
406
+ writeWorkerInstructions(home);
407
+
408
+ for (const pattern of [...DEFAULT_CALLBACKS, ...options.callbacks]) await dalan(['connect', 'allow-callback', pattern]);
409
+ await dalan(['connect', 'start', '--worker', WORKER]);
410
+
411
+ const submit = async () => {
412
+ const requestId = `req_${randomUUID()}`;
413
+ const file = path.join(home, `${requestId}.json`);
414
+ fs.writeFileSync(file, JSON.stringify({ schema_version: 1, request_id: requestId, brief: BRIEF, inputs: [], expected_output: `Text report containing: ${REPORT}.`, execution_scope: 'read-only' }), { mode: 0o600 });
415
+ await dalan(['submit', '--worker', WORKER, '--execution', 'none', '--deliver', 'none', '--file', file, '--json']);
416
+ return requestId;
417
+ };
418
+ const job = async requestId => JSON.parse(await dalan(['get', requestId, '--json']));
419
+ const pendingNow = async () => parsePending(JSON.parse(await dalan(['connect', 'pending', '--json'])));
420
+
421
+ // 1. The built-in demo worker: real pairing, a real MCP session, real job tools. Ctrl-C stops every step.
422
+ const demoId = await submit();
423
+ const pairing = await beginPairing(mcpUrl, { signal });
424
+ await dalan(['connect', 'approve', pairing.code, '--worker', WORKER, '--confirm-redirect', DEMO_REDIRECT, '--replace']);
425
+ const token = await pairing.complete();
426
+ await workJob(mcpUrl, token, demoId, { report: REPORT, signal });
427
+ const done = await job(demoId);
428
+ if (done.status !== 'finished' || done.report?.result !== REPORT) throw new Error(`demo job did not finish as expected: ${done.status}`);
429
+ await dalan(['decide', demoId, 'accepted']);
430
+ const firstJobSeconds = ((Date.now() - started) / 1000).toFixed(1);
431
+ let selfCheck = `a demo worker, approved by this command, finished a job`;
432
+
433
+ // 2. A repository job: refused before a grant, then finished by the same demo worker through the real claim path.
434
+ if (!demoRepo.bare) printTryError(out, new Error(`Repository step skipped: ${demoRepo.reason}`), errorContext);
435
+ else {
436
+ const submitRepo = async (repoName, requestId) => {
437
+ const file = path.join(home, `${requestId}.json`);
438
+ fs.writeFileSync(file, JSON.stringify({ schema_version: 1, request_id: requestId, brief: 'Read README.md at the pinned commit and report its title. Do not run checks or change files.',
439
+ inputs: [{ github_repo: repoName, base_sha: demoRepo.sha }], expected_output: 'README title and pinned revision; no patch or check claim.', scope_paths: ['README.md'], execution_scope: 'read-only' }), { mode: 0o600 });
440
+ return dalan(['submit', '--worker', WORKER, '--execution', 'none', '--deliver', 'none', '--file', file, '--json']);
441
+ };
442
+ let refusal = null;
443
+ const deniedId = `req_${randomUUID()}`;
444
+ try { await submitRepo(DENIED_REPO, deniedId); } catch (error) { refusal = error.message; }
445
+ // The refusal must also leave no job behind: `get` must not find it.
446
+ const leftBehind = await job(deniedId).then(() => true, error => { if (!/"code":"unknown_request"/.test(error.message)) throw error; return false; });
447
+ if (!refusal || !/not allowed/.test(refusal) || leftBehind) { const error = new Error(`a repository job for ${DENIED_REPO} was not refused cleanly before any grant; stopping`); error.tryKind = 'invariant'; throw error; }
448
+ await dalan(['worker', 'allow', WORKER, DEMO_REPO]);
449
+ // The grant is exact: another repository is still refused, and the refusal is recorded.
450
+ const stillDenied = await submitRepo(DENIED_REPO, `req_${randomUUID()}`).then(() => false, error => /not allowed/.test(error.message));
451
+ if (!stillDenied) { const error = new Error(`a repository job for ${DENIED_REPO} was not refused after the grant; stopping`); error.tryKind = 'invariant'; throw error; }
452
+ const repoId = `req_${randomUUID()}`;
453
+ await submitRepo(DEMO_REPO, repoId);
454
+ await workRepositoryJob(mcpUrl, token, repoId, { sha: demoRepo.sha, signal });
455
+ const repoDone = await job(repoId);
456
+ if (repoDone.status !== 'finished' || !repoDone.report?.result?.includes(DEMO_TITLE) || !repoDone.report.result.includes(demoRepo.sha)) throw new Error(`repository demo job did not finish as expected: ${repoDone.status}`);
457
+ await dalan(['decide', repoId, 'accepted']);
458
+ selfCheck += '; the repository grant works and a second repository is refused';
459
+ }
460
+ say(`✔ Self-check passed in ${firstJobSeconds} s: ${selfCheck}.`);
461
+ // The demo's work is done, so end its connection. Your worker then pairs without replacing anything.
462
+ await dalan(['connect', 'revoke', WORKER]);
463
+
464
+ // 3. The user's own worker.
465
+ if (inputEnded && !signal?.aborted) {
466
+ say('\nInput ended, so nobody can approve a worker. Stopping the bridge. To connect your worker, run:');
467
+ say(` ${cli} try --home ${shellHome}`);
468
+ } else {
469
+ const jobId = await submit();
470
+ say('');
471
+ say('Connect your worker as an HTTP MCP server with OAuth:');
472
+ say(` MCP URL file: ${urlFile}`);
473
+ say(` MCP URL (secret hidden): ${shownMcpUrl}`);
474
+ say(' Keep the URL private.');
475
+ say(` How to connect Claude Code, Codex or another client: ${docsUrl('README.md', 'connect-your-own-worker')}`);
476
+ say(` Callbacks: ${[...DEFAULT_CALLBACKS, ...options.callbacks].join(', ')}. To add one, restart with:`);
477
+ say(commandLine(`${cli} try --home ${shellHome}${options.callbacks.map(pattern => ` --callback ${shellQuote(pattern)}`).join('')} --callback PATTERN`));
478
+ say(`Job ${jobId} is queued for your worker. When it is connected, send it:`);
479
+ say(` "${workerPrompt(jobId)}"`);
480
+ say('Waiting for your worker. Ctrl-C stops the bridge.');
481
+
482
+ const seen = new Set();
483
+ let approved = false, reminded = 0, retryNow = false;
484
+ let remindAt = clock.now() + DIAGNOSE_AFTER_MS;
485
+ const remind = () => {
486
+ say(`\nStill waiting for your worker to claim ${jobId}.${approved ? ' It was approved but has not claimed the job yet. If you have not sent it the prompt above, send it now; if its sign-in failed, a new attempt appears here for approval.' : ''} Check from another terminal:`);
487
+ for (const words of [['connect', 'pending'], ['connect', 'start', '--worker', WORKER], ['status']]) say(commandLine(ownCommand(...words)));
488
+ };
489
+ // The owner can answer after the client has started a newer attempt or the bridge dropped this one. An answer to such an
490
+ // attempt is a refresh, not a failure: approve only an attempt that is still pending and newest, and if the bridge
491
+ // refuses an approval, look again before treating it as an error.
492
+ const deadlines = new Map();
493
+ const stillCurrent = async attempt => (await pendingNow()).pending.some(p => p.code === attempt.code && !p.superseded);
494
+ const approveIfCurrent = async attempt => {
495
+ if (!await stillCurrent(attempt)) return false;
496
+ try {
497
+ const { replaced } = JSON.parse(await dalan(['connect', 'approve', attempt.code, '--worker', WORKER, ...(attempt.native ? ['--confirm-redirect', attempt.redirect_uri] : []), '--replace', '--json']));
498
+ if (replaced) say(`Replaced connection ${replaced}, your worker's earlier sign-in.`);
499
+ return true;
500
+ }
501
+ catch (error) { if (exited || await stillCurrent(attempt)) throw error; return false; }
502
+ };
503
+ while (!exited && !stopRequested()) {
504
+ const current = await job(jobId);
505
+ if (current.status === 'finished') {
506
+ say(finishedNotice(jobId, current));
507
+ const answer = await ask('Accept this result? [y/N] ');
508
+ if (exited && !stopRequested()) break;
509
+ if (answer?.trim().toLowerCase() === 'y') { await dalan(['decide', jobId, 'accepted']); say('Recorded as accepted.'); }
510
+ else say(stopRequested() ? '\nNot recorded.' : `Not recorded. Decide later while the bridge runs:\n${commandLine(ownCommand('decide', jobId, 'accepted'))}`);
511
+ if (!stopRequested()) { say('The bridge stays up. Ctrl-C stops it.'); await untilStopRequested(); }
512
+ break;
513
+ }
514
+ // Until the worker claims the job, a client can still retry (its sign-in can fail after the owner approved), and
515
+ // a retry is a new attempt that needs its own approval.
516
+ if (current.status === 'queued') {
517
+ let view = await pendingNow();
518
+ if (!view.window) { await dalan(['connect', 'start', '--worker', WORKER]); view = await pendingNow(); }
519
+ // A client can retry, so ask about each new code, newest last; superseded ones cannot finish.
520
+ for (const attempt of view.pending) {
521
+ if (seen.has(attempt.code) || attempt.superseded) continue;
522
+ seen.add(attempt.code);
523
+ if (attempt.expires_in_seconds !== null) deadlines.set(attempt.code, clock.now() + attempt.expires_in_seconds * 1000);
524
+ const { text, blocked, resourceReported } = describeAttempt(attempt, shownMcpUrl);
525
+ say(`\n${text}`);
526
+ if (blocked) { say('Not approving: this attempt names a different MCP URL than this bridge.'); continue; }
527
+ const note = resourceReported ? '' : ' The resource is not reported, so check that the redirect host is your client\'s.';
528
+ const answer = await ask(`Approve this connection for worker "${WORKER}"?${note} [y/N] `);
529
+ remindAt = Math.max(remindAt, clock.now() + DIAGNOSE_AFTER_MS);
530
+ if (exited && !stopRequested()) break;
531
+ if (answer?.trim().toLowerCase() === 'y') {
532
+ if (await approveIfCurrent(attempt)) { approved = true; say('Approved. Waiting for the worker to finish the job.'); }
533
+ else {
534
+ if (deadlines.has(attempt.code) && clock.now() >= deadlines.get(attempt.code)) say(`That attempt expired after ${PAIRING_MINUTES} minutes. Start the sign-in again in your worker. If the pairing window closed, reopen it with:\n${commandLine(ownCommand('connect', 'start', '--worker', WORKER))}`);
535
+ else say('That attempt is no longer current.');
536
+ // Show the newest attempt at once; the next pass of the loop asks about it without waiting.
537
+ const newest = (await pendingNow()).pending.filter(p => !p.superseded).at(-1);
538
+ if (!newest) say('No newer attempt is waiting. Start the sign-in again in your worker; its new code appears here.');
539
+ else if (seen.has(newest.code)) say(`The current code is ${newest.code}. Approve it with:\n${commandLine(ownCommand('connect', 'approve', newest.code, '--worker', WORKER, ...(newest.native ? ['--confirm-redirect', newest.redirect_uri] : []), '--replace'))}`);
540
+ else retryNow = true;
541
+ }
542
+ break;
543
+ }
544
+ if (stopRequested()) { say('\nNot approved.'); break; }
545
+ say(`Not approved. Approve later with:\n${commandLine(ownCommand('connect', 'approve', attempt.code, '--worker', WORKER, ...(attempt.native ? ['--confirm-redirect', attempt.redirect_uri] : []), '--replace'))}`);
546
+ }
547
+ if (reminded < DIAGNOSE_LIMIT && !exited && !stopRequested() && clock.now() >= remindAt) {
548
+ remind();
549
+ reminded++;
550
+ remindAt = clock.now() + DIAGNOSE_EVERY_MS;
551
+ }
552
+ }
553
+ if (retryNow) { retryNow = false; continue; }
554
+ await Promise.race([clock.sleep(POLL_MS), untilStopRequested()]);
555
+ }
556
+ if (exited && !stopRequested()) { const error = new Error('the bridge stopped unexpectedly'); error.tryKind = 'unexpected'; throw error; }
557
+ if (inputEnded && !signal?.aborted) say('Input ended. Stopping the bridge.');
558
+ }
559
+ } catch (error) {
560
+ // Ctrl-C can land anywhere (a child command, a request, a wait); that is a normal stop, not a failure.
561
+ if (signal?.aborted) { /* a normal stop */ }
562
+ else if (exited && errorContext.started && !error.tryKind) {
563
+ // A command failed because the bridge is gone: say that, with the same recovery as any other unexpected exit.
564
+ const gone = new Error(`the bridge stopped unexpectedly (${String(error.message).split('\n')[0]})`);
565
+ gone.tryKind = 'unexpected';
566
+ throw gone;
567
+ } else throw error;
568
+ } finally {
569
+ lines.close();
570
+ await stop();
571
+ cleaned = await cleanupTrial();
572
+ }
573
+ say(`Stopped. Trial home kept at ${home}; delete it to start over.${cleaned ? ' The demo grant and files are removed.' : ''}`);
574
+ say(`Next steps (connect your own worker, repository jobs, other machines): ${docsUrl('README.md', 'next-steps')}`);
575
+ }
576
+
577
+ export { cliCommand };
578
+
579
+ export async function main() {
580
+ const controller = new AbortController();
581
+ // The first signal starts the stop. Later ones are ignored so the cleanup can finish: npx forwards the terminal's
582
+ // Ctrl-C to this process, so one keypress can arrive twice. The stop is bounded (server 5 s, revoke 30 s).
583
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => controller.abort());
584
+ const errorContext = { started: false };
585
+ errorContext.shellCli = shellQuote(path.resolve(process.argv[1] ?? path.join(repo, 'bin/dalan.mjs')));
586
+ errorContext.cli = cliCommand(process.argv[1], process.env);
587
+ try { await runTry({ argv: process.argv.slice(3), signal: controller.signal, errorContext }); }
588
+ catch (error) { process.stderr.write(`dalan: ${await describeTryError(error, errorContext)}\n`); process.exitCode = 1; }
589
+ }