@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +29 -25
  2. package/PROTOCOL.md +16 -4
  3. package/README.md +127 -260
  4. package/SECURITY.md +1 -1
  5. package/bin/dalan.mjs +5 -0
  6. package/bin/dot-worker.mjs +35 -26
  7. package/docs/chatgpt-worker-onboarding.md +5 -5
  8. package/docs/claude-worker-onboarding.md +5 -5
  9. package/docs/codex-to-muse.md +175 -0
  10. package/docs/connect-chatgpt.md +9 -4
  11. package/docs/connection-longevity.md +7 -1
  12. package/docs/dalan-upgrade.md +17 -13
  13. package/docs/deadman.md +5 -3
  14. package/docs/local-agent-mcp.md +8 -6
  15. package/docs/manual-setup.md +8 -8
  16. package/docs/mirror-fetch.md +1 -2
  17. package/docs/operations.md +90 -42
  18. package/docs/operator-duties.md +1 -1
  19. package/docs/owner-integrator.md +2 -2
  20. package/docs/portable-auth-profile.md +12 -14
  21. package/docs/pr-head-reviewer.md +21 -5
  22. package/docs/pr-preflight.md +2 -0
  23. package/docs/pull-queue.md +131 -0
  24. package/docs/pull-workers.md +7 -10
  25. package/docs/redaction.md +1 -1
  26. package/docs/service-setup.md +56 -3
  27. package/docs/setup-reference.md +1 -1
  28. package/docs/t3-integration.md +2 -0
  29. package/docs/t3-result-retry-delivery.md +2 -2
  30. package/docs/t3-reverse-control.md +7 -7
  31. package/docs/usage.md +19 -15
  32. package/docs/worker-clients.md +18 -13
  33. package/package.json +3 -1
  34. package/scripts/dalan-try-selfcheck.mjs +29 -0
  35. package/scripts/worker-bridge-setup.mjs +1 -1
  36. package/src/acp-bridge.mjs +18 -12
  37. package/src/as.mjs +41 -0
  38. package/src/child-exit.mjs +18 -0
  39. package/src/child-registry.mjs +94 -0
  40. package/src/cli-help.mjs +25 -11
  41. package/src/demo-worker.mjs +2 -2
  42. package/src/drained-owner.mjs +26 -0
  43. package/src/drained-slot.mjs +20 -3
  44. package/src/mcp-outcome.mjs +10 -1
  45. package/src/mcp-sse.mjs +62 -0
  46. package/src/pr-head-reviewer.mjs +3 -3
  47. package/src/process-inspection.mjs +36 -0
  48. package/src/pull-queue.mjs +159 -0
  49. package/src/route-setting.mjs +24 -0
  50. package/src/server.mjs +157 -29
  51. package/src/service-migrate-workers.mjs +113 -0
  52. package/src/service.mjs +388 -0
  53. package/src/setup.mjs +63 -0
  54. package/src/store.mjs +21 -9
  55. package/src/tool-registry.mjs +3 -1
  56. package/src/try-exposure.mjs +908 -0
  57. package/src/try-hosted-clients.mjs +46 -0
  58. package/src/try-hosted.mjs +444 -0
  59. package/src/try-selfcheck.mjs +168 -0
  60. package/src/try.mjs +63 -17
  61. package/src/workers.mjs +33 -23
  62. package/src/workspace.mjs +10 -3
@@ -10,7 +10,7 @@ Start from the section that matches your bridge:
10
10
  | `dalan try` is running on this computer | opencode on this computer | [opencode](#cli-worker-opencode) |
11
11
  | A bridge that you started by hand ([manual setup](manual-setup.md#step-by-step)) | Claude Code or Codex CLI on this computer | The same sections, "From a bridge you started by hand" |
12
12
  | A bridge with a public HTTPS address ([service guide](service-setup.md)) | A client on another computer | [Native client on a remote HTTPS bridge](#native-client-on-a-remote-https-bridge) |
13
- | A bridge with a public HTTPS address | ChatGPT or Claude on the web | [Connect ChatGPT](connect-chatgpt.md) or [Claude cloud worker](claude-worker-onboarding.md) |
13
+ | A bridge with a public HTTPS address | ChatGPT, Muse Spark or Claude on the web | [Connect ChatGPT](connect-chatgpt.md), [Codex CLI to Muse Spark](codex-to-muse.md) or [Claude cloud worker](claude-worker-onboarding.md) |
14
14
 
15
15
  Install your client and sign in to it first: [Claude Code](https://code.claude.com/docs/en/quickstart), [Codex CLI](https://developers.openai.com/codex/cli/) or opencode. Check that `claude --version` or `codex --version` works; Dalan does not require a particular client.
16
16
 
@@ -19,7 +19,7 @@ Install your client and sign in to it first: [Claude Code](https://code.claude.c
19
19
  - **HTTP MCP with OAuth.** The client connects to the bridge's MCP URL and signs in through the bridge's built-in OAuth server.
20
20
  - **An allowed callback.** OAuth returns to the client through a callback URI. The bridge accepts only the patterns that the owner allowed with `dalan connect allow-callback`; `dalan try` allows `http://127.0.0.1/callback` and `http://localhost/callback` on any port, and the [setup reference](setup-reference.md#callback-patterns) has the pattern rules.
21
21
  - **A reachable bridge.** A client on the bridge computer can use `127.0.0.1`. A client on another computer needs a route to the bridge, and a hosted client needs a public HTTPS address.
22
- - **A browser on the client's computer.** The browser must run on the computer that runs the client's callback listener.
22
+ - **A browser for sign-in.** For a native client with a loopback callback, open the sign-in page on the computer running that client's callback listener. For a hosted client, use the provider's browser sign-in flow.
23
23
 
24
24
  The MCP URL contains a secret path, so give it only to the client that you connect.
25
25
 
@@ -60,7 +60,7 @@ To remove the registration later, run `claude mcp remove --scope user WORKER`.
60
60
 
61
61
  ## CLI worker: opencode
62
62
 
63
- Use a model that supports tool calls; the worker does its job through tool calls.
63
+ This recipe describes opencode 2.2. Install and sign in to opencode, run `opencode --version`, and use a model that supports tool calls. If your version has different MCP or permission settings, check its documentation before using the commands below.
64
64
 
65
65
  Work in a project directory whose `opencode.json` already configures your model provider. Deny these tools there:
66
66
 
@@ -78,7 +78,7 @@ opencode's own prompt still suggests `execute`, and a model that follows it writ
78
78
 
79
79
  If you passed `--home DIR` to `try`, use `DIR/worker-instructions.md`. For a service bridge, use `BRIDGE_HOME/worker-instructions.md`.
80
80
 
81
- Register the bridge from `dalan try`:
81
+ Register the bridge from `dalan try`. If you used `--home DIR`, replace `~/.local/share/dalan-trial` below with `DIR`, as you did for `worker-instructions.md`:
82
82
 
83
83
  ```sh
84
84
  opencode mcp add local --url "$(cat ~/.local/share/dalan-trial/resource-url)"
@@ -205,18 +205,18 @@ To undo it, run `codex mcp remove NAME` on the worker computer, and `node "$(npm
205
205
 
206
206
  A worker name labels one connection and its job queue; it loads no vendor-specific code. Use a lowercase name of up to 32 characters that starts with a letter and contains letters, digits, `_` or `-`; `pool` and `unknown` are reserved.
207
207
 
208
- `try` and the README use the name `local`. To use another name, initialize it in a new bridge home and use it in every command that names a worker:
208
+ `try` and the README use the name `local`. To use another name, initialize it in a new bridge home and use it in every command that names a worker.
209
+
210
+ From the Dalan source checkout, initialize the new home and start its bridge in the first terminal:
209
211
 
210
212
  ```sh
211
- export DALAN_HOME="$HOME/.local/share/dalan-personal" DALAN_LOOPBACK=1
213
+ export DALAN_HOME="$HOME/.local/share/dalan-personal"
214
+ export DALAN_LOOPBACK=1 DALAN_AUTH_MODE=builtin DALAN_PORT=8799
212
215
  dalan init --worker personal --public-url http://127.0.0.1:8799
213
- dalan connect allow-callback 'CALLBACK_PATTERN'
214
- dalan connect start --worker personal
215
- dalan connect pending
216
- dalan connect approve CODE --worker personal
216
+ HOME="$DALAN_HOME" node src/server.mjs
217
217
  ```
218
218
 
219
- `DALAN_HOME` selects the new bridge home, and `init` accepts an `http://127.0.0.1` URL only with `DALAN_LOOPBACK=1`. Start the bridge for that home with `DALAN_LOOPBACK=1 DALAN_AUTH_MODE=builtin`, as [manual setup](manual-setup.md#owner-and-requester-setup) shows; the server refuses loopback mode without built-in OAuth. Export `DALAN_HOME` in every shell that runs these commands.
219
+ Leave that terminal running. If `8799` is occupied, choose a free port and use it in both `DALAN_PORT` and the public URL. In a second terminal, export the same `DALAN_HOME` and follow the [manual worker setup](manual-setup.md#worker-setup), replacing `local` with `personal`. That sequence allows the callback, opens a pairing window, registers the client, and approves its actual pending code.
220
220
 
221
221
  Run one `allow-callback` command, for the callback that your client really uses. For a native client, add `--confirm-redirect REDIRECT` to the approve command, with the exact redirect that `pending` shows. A fresh `init` creates one worker, refuses to overwrite an existing profile, grants no repositories and no T3 Code access, and sets execution to `none`. Approval binds the connection to that worker. Changing the model or vendor in the client does not change the connection or its repository grants.
222
222
 
@@ -256,8 +256,6 @@ On the bridge computer, run these commands. `WORKER` is the name of a configured
256
256
  dalan tool add --file owner_message.json
257
257
  dalan tool grant owner_message WORKER
258
258
  dalan tool list
259
- dalan tool revoke owner_message WORKER # take the ability back
260
- dalan tool remove owner_message # delete the tool and all its grants
261
259
  ```
262
260
 
263
261
  A new tool is denied to every worker until you grant it. `dalan tool list` shows each tool, its class and its granted workers. There is no command to disable or edit a tool. To change one, remove it and add the new file. A grant is lost when you remove the tool, so grant it again.
@@ -269,6 +267,13 @@ The worker calls `list_tools`. The reply holds `registry_version` and, for each
269
267
  "schema_hash": "<from list_tools>", "idempotency_key": "<new for each message>" }
270
268
  ```
271
269
 
270
+ **Remove it when you are done.** Run these only after completing the worker call:
271
+
272
+ ```sh
273
+ dalan tool revoke owner_message WORKER
274
+ dalan tool remove owner_message
275
+ ```
276
+
272
277
  If the registry changed, the call fails with `stale_registry`. Call `list_tools` again and use the new `schema_hash`. Limits, retries and errors for `owner_message` are in [the T3 guide](t3-reverse-control.md#adding-abilities-without-a-refresh).
273
278
 
274
279
  **A grant is standing authority.** The bridge has no per-call approval step. After you grant a tool, the worker can call it until you revoke the grant or remove the tool. A revoke or a remove also discards the messages that worker queued but the bridge has not yet delivered. A grant to a name that is not a configured worker has no effect, so check the spelling.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -20,6 +20,7 @@
20
20
  "!packages/job-core/test/",
21
21
  "integrations/t3/acp-kit/src/",
22
22
  "scripts/daily-selfcheck.mjs",
23
+ "scripts/dalan-try-selfcheck.mjs",
23
24
  "scripts/monitor-targets.mjs",
24
25
  "scripts/worker-bridge-setup.mjs",
25
26
  "scripts/upgrade-drain.mjs",
@@ -53,6 +54,7 @@
53
54
  },
54
55
  "dependencies": {
55
56
  "@agentclientprotocol/sdk": "1.8.0",
57
+ "@tnunamak/gozar": "0.1.0",
56
58
  "oidc-provider": "9.13.0"
57
59
  },
58
60
  "devDependencies": {
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // Run against a live `dalan try --public` trial before adding the connector in claude.ai or ChatGPT:
3
+ // node scripts/dalan-try-selfcheck.mjs --home <trial home> [--client claude|chatgpt] [--wait 300]
4
+ // The trial's authorization server must be on its public origin: a constraint of the trial, not of OAuth.
5
+ // It acts as a real OAuth client and waits for you to approve the connection (y) in the trial terminal.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { runSelfCheck } from '../src/try-selfcheck.mjs';
9
+
10
+ const args = process.argv.slice(2);
11
+ const option = name => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
12
+ const home = option('--home'), client = option('--client') ?? 'claude', wait = Number(option('--wait') ?? 300);
13
+ let url = process.env.DALAN_TRY_URL;
14
+ if (!url && home) { try { url = fs.readFileSync(path.join(home, 'resource-url'), 'utf8').trim(); } catch { /* reported below */ } }
15
+ if (!url || !['claude', 'chatgpt'].includes(client)) {
16
+ process.stderr.write('usage: node scripts/dalan-try-selfcheck.mjs --home <trial home> [--client claude|chatgpt] [--wait seconds]\n(or set DALAN_TRY_URL to the trial\'s MCP URL; it is a credential, so it is never taken from an argument)\n');
17
+ process.exit(2);
18
+ }
19
+ const controller = new AbortController();
20
+ process.once('SIGINT', () => controller.abort());
21
+ process.once('SIGTERM', () => controller.abort());
22
+ try {
23
+ const { ok } = await runSelfCheck({ url, client, approveWaitMs: wait * 1000, signal: controller.signal, say: line => process.stdout.write(`${line}\n`) });
24
+ process.exit(ok ? 0 : 1);
25
+ } catch {
26
+ // The error text can hold the credential URL, so none of it is printed.
27
+ process.stdout.write('FAIL self-check: stopped before it finished (cancelled or an unexpected error)\nRESULT FAIL\n');
28
+ process.exit(1);
29
+ }
@@ -310,7 +310,7 @@ function lintPlist(text, env) {
310
310
  }
311
311
 
312
312
  function runDotWorkerInit(options) {
313
- return spawnSync(options.node, [path.join(options.repo, 'bin/dalan.mjs'), 'init', '--worker', options.worker, '--public-url', options.publicUrl, '--json'], {
313
+ return spawnSync(options.node, [path.join(options.repo, 'bin/dalan.mjs'), 'init', '--worker', options.worker, ...(options.repoTools?['--enable-workspace']:[]), '--public-url', options.publicUrl, '--json'], {
314
314
  cwd: options.repo, env: { ...process.env, HOME: options.home, NODE_ENV: 'production' }, encoding: 'utf8',
315
315
  });
316
316
  }
@@ -320,17 +320,15 @@ const checkerEnv = home => ({ PATH: checkerPath(), HOME: home, TMPDIR: home, LAN
320
320
  // no sound containment without a sandbox or cgroup, so the checker also runs only when the host-check policy allows
321
321
  // unsandboxed host execution, and it must be a trusted local data-only command, not a security boundary.
322
322
  function descendantPids(rootPid) {
323
- try {
324
- const rows = execFileSync('ps', ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n').map(l => l.trim().split(/\s+/).map(Number));
325
- const kids = new Map();
326
- for (const [pid, ppid] of rows) { if (!kids.has(ppid)) kids.set(ppid, []); kids.get(ppid).push(pid); }
327
- const found = [], queue = [rootPid];
328
- while (queue.length) for (const pid of kids.get(queue.pop()) ?? []) { found.push(pid); queue.push(pid); }
329
- return found;
330
- } catch { return []; }
323
+ const rows = execFileSync('ps', ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n').map(l => l.trim().split(/\s+/).map(Number));
324
+ const kids = new Map();
325
+ for (const [pid, ppid] of rows) { if (!kids.has(ppid)) kids.set(ppid, []); kids.get(ppid).push(pid); }
326
+ const found = [], queue = [rootPid];
327
+ while (queue.length) for (const pid of kids.get(queue.pop()) ?? []) { found.push(pid); queue.push(pid); }
328
+ return found;
331
329
  }
332
330
  // Optional prose check of a build patch: pipes the added prose lines to an owner-configured linter command.
333
- export function runBuildProseCheck(repo, patch, env = process.env, { refusal = hostCheckRefusal, timeoutMs = 30000 } = {}) {
331
+ export function runBuildProseCheck(repo, patch, env = process.env, { refusal = hostCheckRefusal, timeoutMs = 30000, descendants = descendantPids } = {}) {
334
332
  const ownersName = 'DALAN_ACP_PROSE_CHECK_OWNERS';
335
333
  const command = env.DALAN_ACP_PROSE_CHECK;
336
334
  const owners = configuredOwners(env[ownersName]);
@@ -345,12 +343,20 @@ export function runBuildProseCheck(repo, patch, env = process.env, { refusal = h
345
343
  const home = fs.mkdtempSync(path.join(os.tmpdir(), 'prose-check-'));
346
344
  const child = spawn(command, ['check', '--stdin', '--kind', 'doc', '--json'], { env: checkerEnv(home), stdio: ['pipe', 'pipe', 'pipe'], detached: true });
347
345
  const killTree = () => {
348
- const tracked = descendantPids(child.pid);
346
+ let tracked;
347
+ try { tracked = descendants(child.pid); } catch { tracked = null; }
349
348
  try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); }
350
- for (const pid of tracked) { try { process.kill(pid, 'SIGKILL'); } catch {} }
349
+ for (const pid of tracked ?? []) { try { process.kill(pid, 'SIGKILL'); } catch {} }
350
+ return tracked !== null;
351
351
  };
352
352
  let stdout = '', stderr = '', settled = false;
353
- const finish = result => { if (settled) return; settled = true; clearTimeout(timer); killTree(); fs.rmSync(home, { recursive: true, force: true }); resolve(result); };
353
+ const finish = result => {
354
+ if (settled) return;
355
+ settled = true; clearTimeout(timer);
356
+ if (killTree()) fs.rmSync(home, { recursive: true, force: true });
357
+ else result = { ...result, status: 'ERROR', detail: `process inspection failed; temporary files retained at ${home}`, cleanupHome: home };
358
+ resolve(result);
359
+ };
354
360
  const timer = setTimeout(() => finish({ status: 'ERROR', detail: 'timed out' }), timeoutMs);
355
361
  child.stdout.setEncoding('utf8').on('data', chunk => { if (stdout.length < 256000) stdout += chunk; });
356
362
  child.stderr.setEncoding('utf8').on('data', chunk => { if (stderr.length < 4000) stderr += chunk; });
package/src/as.mjs CHANGED
@@ -1,3 +1,6 @@
1
+ import { uaToken } from './mcp-outcome.mjs';
2
+ const GRANT_TYPES = ['authorization_code', 'refresh_token', 'client_credentials'];
3
+ const TOKEN_PARAMS = ['grant_type', 'code', 'redirect_uri', 'client_id', 'client_secret', 'code_verifier', 'refresh_token', 'scope', 'resource', 'client_assertion', 'client_assertion_type'];
1
4
  import { Provider, errors } from 'oidc-provider';
2
5
  import { ACCEPTED_SCOPES, ADVERTISED_SCOPES, canonicalScopes } from './scopes.mjs';
3
6
  import { randomUUID } from 'node:crypto';
@@ -206,12 +209,24 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
206
209
  if (!store.window()) return reject(403, 'access_denied', 'Open a pairing window before registering.');
207
210
  if (!store.reserveRegistration()) return reject(429, 'temporarily_unavailable', 'Registration limit reached. Reuse the client this worker already registered. If you cannot, ask the owner to run dalan connect reset, then retry.');
208
211
  if (Number(ctx.get('content-length')) > 8192) return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
212
+ const normalized = await normalizeRegistration(ctx.req);
213
+ if (normalized === 'too_large') { ctx.req.destroy(); return; }
214
+ if (normalized === 'invalid') return reject(400, 'invalid_request', 'The registration body must be a UTF-8 JSON object.');
209
215
  let bytes = 0;
210
216
  const count = chunk => { bytes += chunk.length; if (bytes > 8192) ctx.req.destroy(); };
211
217
  ctx.req.on('data', count);
212
218
  try { await next(); } finally { ctx.req.off('data', count); }
213
219
  return;
214
220
  }
221
+ if (route === '/token' && ctx.method === 'POST') {
222
+ await next();
223
+ // Names and shapes only, never a value of a secret: what a client sent and what it was given back.
224
+ // Names come from fixed lists: a caller chooses the text of grant_type and the names of its parameters, so neither is logged as sent.
225
+ const sent = ctx.oidc?.body ?? {}, given = ctx.body && typeof ctx.body === 'object' ? ctx.body : {};
226
+ const names = Object.keys(sent), known = names.filter(k => TOKEN_PARAMS.includes(k)).sort();
227
+ log({ kind: 'as_token_detail', status: ctx.status, grant_type: typeof sent.grant_type === 'string' ? (GRANT_TYPES.includes(sent.grant_type) ? sent.grant_type : 'other') : null, request_params: known, unknown_params: names.length - known.length, response_has: ['access_token', 'refresh_token', 'id_token', 'scope', 'expires_in', 'token_type'].filter(k => given[k] !== undefined).map(k => k.replace('_token', 'Tok')), token_type: given.token_type === 'Bearer' ? 'Bearer' : null, scope: typeof given.scope === 'string' ? given.scope.split(' ').filter(x => ACCEPTED_SCOPES.includes(x) || x === 'openid').join(' ') : null, expires_in: Number.isInteger(given.expires_in) ? given.expires_in : null, has_resource: Boolean(sent.resource) });
228
+ return;
229
+ }
215
230
  if (route === '/auth' && ctx.query.response_type !== 'code') return refuse(400, 'Unsupported response type', 'Only response_type=code is supported.');
216
231
  if (route === '/auth' || route.startsWith('/auth/')) {
217
232
  // Only response_mode=query is supported: form_post would need a script-free page the CSP cannot allow.
@@ -264,6 +279,11 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
264
279
  const alias = WELL_KNOWN[pathname];
265
280
  if (!alias && pathname !== PREFIX && !pathname.startsWith(`${PREFIX}/`)) return false;
266
281
  const interaction = interactionPath.exec(pathname.slice(PREFIX.length));
282
+ // One line per request with a fixed route name and the status, never a path, query or body: a connection that stalls after
283
+ // approval can then be told apart (no token request vs a refused one) without the log holding a secret.
284
+ const routeName = alias ? 'discovery' : ({ '/reg': 'registration', '/auth': 'authorize', '/token': 'token', '/token/revocation': 'revocation', '/jwks': 'jwks' }[pathname.slice(PREFIX.length).toLowerCase().replace(/\/+$/, '')]
285
+ ?? (interaction ? 'interaction' : pathname.slice(PREFIX.length).startsWith('/auth/') ? 'authorize_resume' : 'other'));
286
+ res.once('finish', () => log({ kind: 'as_request', route: routeName, http_method: req.method, status: res.statusCode, ua: uaToken(req) }));
267
287
  try {
268
288
  if (interaction) await interactionPage(req, res, interaction[1]);
269
289
  else await provide(req, res, alias);
@@ -273,6 +293,27 @@ function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, wor
273
293
  }
274
294
  return true;
275
295
  }
296
+ // Every client here is public (PKCE, no secret). RFC 7591 §2 makes `client_secret_basic` the default when a registration omits
297
+ // `token_endpoint_auth_method`, and the library then issues a secret that the token endpoint and the metadata (only `none`)
298
+ // would never accept. RFC 7591 §3.2.1 lets the server replace requested values as long as the response shows what it registered,
299
+ // so an omitted or unsupported method is registered as `none`: the response carries `token_endpoint_auth_method: "none"` and no
300
+ // `client_secret`, in agreement with the metadata and the token endpoint. A strict client (claude.ai) stops on that mismatch.
301
+ // Returns 'ok', or 'invalid' for a body that is not a UTF-8 JSON object (the caller answers it as the library answers a bad body).
302
+ async function normalizeRegistration(req) {
303
+ const type = req.headers['content-type'] ?? '';
304
+ if (!/^application\/json\b/i.test(type)) return 'ok';
305
+ const charset = /;\s*charset\s*=\s*"?([^";\s]+)/i.exec(type)?.[1];
306
+ if (charset && !/^utf-?8$/i.test(charset)) return 'invalid';
307
+ const chunks = []; let size = 0;
308
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) { size += chunk.length; if (size > 8192) return 'too_large'; chunks.push(chunk); }
309
+ let body;
310
+ try { body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch { return 'invalid'; }
311
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid'; // parsed once, here; a JSON string is never parsed again
312
+ if (body.token_endpoint_auth_method !== 'none') body.token_endpoint_auth_method = 'none';
313
+ delete body.client_secret; delete body.client_secret_expires_at;
314
+ req.body = body;
315
+ return 'ok';
316
+ }
276
317
  async function provide(req, res, alias) {
277
318
  if (alias && !['GET', 'HEAD'].includes(req.method)) { res.writeHead(405, { allow: 'GET, HEAD' }); res.end(); return; }
278
319
  for (const name of Object.keys(req.headers)) if (name === 'forwarded' || name === 'x-real-ip' || name.startsWith('x-forwarded-')) delete req.headers[name];
@@ -0,0 +1,18 @@
1
+ // A ChildProcess can emit `error` while its PID is still alive (for example, a failed signal).
2
+ // Only `close` proves a started process ended. Spawn failure has no PID and needs no wait.
3
+ export function waitForChildExit(child, { onError = () => {}, onClose = () => {} } = {}) {
4
+ return new Promise(resolve => {
5
+ let settled = false;
6
+ const finish = (...args) => {
7
+ if (settled) return;
8
+ settled = true;
9
+ onClose(...args);
10
+ resolve();
11
+ };
12
+ child.once('close', (...args) => finish(...args));
13
+ child.once('error', error => {
14
+ onError(error);
15
+ if (!Number.isInteger(child.pid) || child.pid <= 0) finish();
16
+ });
17
+ });
18
+ }
@@ -0,0 +1,94 @@
1
+ // A trial's child processes (the public-route ssh, the bridge) are listed in a registry outside every trial home. If the trial's own
2
+ // process is killed without cleanup, the children keep running; the next trial sweeps the registry and ends them only after the
3
+ // recorded owner is confirmed gone and the child's recorded identity still matches.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { processCommand } from './process-inspection.mjs';
8
+
9
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
10
+ export const childRegistry = (env = process.env) => path.join(env.XDG_CACHE_HOME || path.join(env.HOME || os.homedir(), '.cache'), 'dalan', 'trial-children');
11
+
12
+ // Kept for callers that need only a command string. Cleanup uses the three-state processCommand result below.
13
+ export const commandOf = pid => {
14
+ const identity = processCommand(pid);
15
+ return identity.state === 'present' ? identity.command : null;
16
+ };
17
+
18
+ const inspect = (processCmd, pid) => {
19
+ try {
20
+ const result = processCmd(pid);
21
+ if (result && typeof result === 'object' && ['present', 'absent', 'unknown'].includes(result.state)) return result;
22
+ // Older injected inspectors returned a command string or null. A null result cannot prove absence.
23
+ if (typeof result === 'string' && result) return { state: 'present', command: result, start: null };
24
+ } catch { /* a failed inspection is unknown */ }
25
+ return { state: 'unknown' };
26
+ };
27
+
28
+ const childMatches = (identity, record) => {
29
+ if (identity.state === 'absent') return 'gone';
30
+ if (identity.state !== 'present' || !record.cmd) return 'unknown';
31
+ if (record.cmd !== identity.command) return 'different';
32
+ if (record.start && !identity.start) return 'unknown';
33
+ if (record.start && record.start !== identity.start) return 'different';
34
+ return 'same';
35
+ };
36
+
37
+ // Records one child. Returns a function that removes its record after the child exits.
38
+ export function registerChild({ registry, child, processCmd = processCommand, owner = process.pid }) {
39
+ if (!Number.isInteger(child?.pid)) return () => {};
40
+ const file = path.join(registry, `${child.pid}.json`);
41
+ try {
42
+ fs.mkdirSync(registry, { recursive: true, mode: 0o700 });
43
+ const childIdentity = inspect(processCmd, child.pid);
44
+ const ownerIdentity = inspect(processCmd, owner);
45
+ fs.writeFileSync(file, JSON.stringify({
46
+ pid: child.pid,
47
+ cmd: childIdentity.state === 'present' ? childIdentity.command : null,
48
+ start: childIdentity.state === 'present' ? childIdentity.start ?? null : null,
49
+ owner,
50
+ ownerCmd: ownerIdentity.state === 'present' ? ownerIdentity.command : null,
51
+ ownerStart: ownerIdentity.state === 'present' ? ownerIdentity.start ?? null : null,
52
+ }), { mode: 0o600 });
53
+ } catch { return () => {}; }
54
+ return () => fs.rmSync(file, { force: true });
55
+ }
56
+
57
+ // Ends listed children only after the recorded owner is known to be gone or its PID has a different start identity.
58
+ export async function sweepChildren({ registry, processCmd = processCommand, kill = (pid, sig) => process.kill(pid, sig), clock = { sleep }, graceMs = 2000 }) {
59
+ let names = [];
60
+ try { names = fs.readdirSync(registry).filter(n => n.endsWith('.json')); } catch { return []; }
61
+ const ended = [];
62
+ for (const name of names) {
63
+ const file = path.join(registry, name);
64
+ let record;
65
+ try { record = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
66
+ if (!record || typeof record !== 'object' || Array.isArray(record)) continue;
67
+
68
+ if (!Number.isInteger(record.owner)) continue;
69
+ const owner = inspect(processCmd, record.owner);
70
+ const ownerGone = owner.state === 'absent';
71
+ const ownerReused = owner.state === 'present' && Boolean(record.ownerStart) && Boolean(owner.start) && owner.start !== record.ownerStart;
72
+ if (!ownerGone && !ownerReused) continue;
73
+
74
+ let childState = childMatches(inspect(processCmd, record.pid), record);
75
+ if (childState === 'unknown') continue;
76
+ if (childState === 'same') {
77
+ try { kill(record.pid, 'SIGTERM'); } catch { /* inspect again: a signal error does not prove exit */ }
78
+ for (let waited = 0; waited < graceMs; waited += 100) {
79
+ await clock.sleep(100);
80
+ childState = childMatches(inspect(processCmd, record.pid), record);
81
+ if (childState !== 'same') break;
82
+ }
83
+ if (childState === 'same') {
84
+ try { kill(record.pid, 'SIGKILL'); } catch { /* inspect again before releasing the record */ }
85
+ childState = childMatches(inspect(processCmd, record.pid), record);
86
+ }
87
+ if (childState === 'same' || childState === 'unknown') continue;
88
+ ended.push(record.pid);
89
+ }
90
+ // An absent or reused child PID has no process left that this record can safely own.
91
+ fs.rmSync(file, { force: true });
92
+ }
93
+ return ended;
94
+ }
package/src/cli-help.mjs CHANGED
@@ -6,16 +6,30 @@ import { docsUrl } from './docs-url.mjs';
6
6
  // commands without a group only appear under `dalan help --all`, and internal maintenance commands only under
7
7
  // `dalan help --internal`. Every command runs and has its own help either way.
8
8
  export const COMMANDS = [
9
- { name: 'try', group: 'start', summary: 'Run a private trial bridge and finish a first job', usage: 'dalan try [--home DIR] [--port N] [--callback PATTERN]...',
10
- detail: ['Starts a bridge and a built-in demo worker in a private trial home and runs a self-check: the demo worker finishes one job,',
11
- 'and a repository grant is tested. In an interactive terminal it then waits for you to connect your own worker; press Ctrl-C to stop.',
12
- 'With standard input closed (dalan try < /dev/null) it stops after the self-check. Nothing outside the trial home is touched.', '',
13
- 'Options:', ' --home DIR trial home (default: DALAN_HOME if set, else ~/.local/share/dalan-trial)', ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN allow one more OAuth callback pattern; repeatable', '',
14
- 'Example: dalan try', `Then connect your worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
15
- { name: 'init', group: 'start', summary: 'Create a bridge home and its first worker profile', usage: 'dalan init --public-url URL (--worker NAME | --legacy) [--json]',
9
+ { name: 'try', group: 'start', summary: 'Try Dalan with a hosted MCP client, or on this computer only', usage: 'dalan try [--local | --public [--client chatgpt|claude] [--route auto|gozar|localhost.run|tailscale]] [--home DIR] [--port N] [--callback PATTERN]...',
10
+ detail: ['In an interactive terminal, asks where your worker runs. Choose a hosted MCP client such as ChatGPT or claude.ai (the default). `auto` honors a saved temporary-relay choice; otherwise it uses a usable Tailscale route and selects Gozar if no Tailscale route is usable. When it selects Gozar, Dalan names tunnl.gg, links its terms and privacy notice, and asks for consent before exposure. After consent, bundled Gozar creates an installation-owned key and opens the temporary demo link through tunnl.gg. Dalan never uses your SSH keys. The relay ends TLS and can see the connector URL and traffic; the link can stop or change without warning, including within minutes.',
11
+ 'Dalan checks the original public address and ends the trial when it detects a change or route loss. The trial itself ends after 3 hours at most. Ctrl-C stops the run; Dalan closes its forwarding gate and attempts to remove its route. If cleanup cannot be confirmed, it reports this and prints a recovery command. Keep private work out of the demo. A Tailscale route is separate from the temporary relay. Choose this computer only, or pass --local, for a',
12
+ 'self-check with a built-in demo worker; then connect a local client. With no terminal (dalan try < /dev/null) it runs the local self-check and never opens a route.', '',
13
+ 'Options:', ' --local this computer only', ' --public public trial with the chatgpt or claude sign-in profile (other clients: see Connect any MCP worker in the README)', ' --client NAME chatgpt (default) or claude; implies --public',
14
+ '', 'When `auto` selects Gozar because a temporary-relay choice was saved or Tailscale is unavailable, Gozar supplies the tunnl.gg key-bound relay; Dalan keeps OAuth sign-in and identity checks. After consent, Gozar creates a private key for this installation. Dalan does not use your SSH keys. Gozar is bundled; no separate install is needed.',
15
+ ' --route NAME auto (saved temporary-relay choice, otherwise usable Tailscale, then bundled Gozar with relay consent), gozar, localhost.run or tailscale; implies --public', ' --home DIR bridge home; otherwise DALAN_HOME if set (defaults by mode below)',
16
+ ' --port N bridge port (default: the home\'s previous port, else 8799 or the next free port)', ' --callback PATTERN local mode only: allow one more OAuth callback pattern; repeatable', '',
17
+ 'Example: dalan try', 'Use the Home this run prints for follow-up commands. With no --home or DALAN_HOME, local mode uses ~/.local/share/dalan-trial, a public trial creates a new home, and a usable Tailscale route on this computer uses ~/.local/share/dalan-hosted-<client>. A home is reused only at the same public address. --port is the local bridge port, never the public port.', `In local mode, connect your own worker and review its first result: ${docsUrl('README.md', 'connect-your-own-worker')}`] },
18
+ { name: 'setup', group: 'start', summary: 'Choose the route for public runs', usage: 'dalan setup',
19
+ detail: ['Saves a route choice. It does not move a trial\'s client connection or install a background service; a new address needs a new client sign-in. If Tailscale is installed and ready for Funnel, it asks whether to save Tailscale; choosing no saves Gozar for temporary links.', 'If not, it lists the choices (install Tailscale, or save Gozar for temporary links) and saves nothing until you choose.',
20
+ 'Afterwards `dalan try --public --route tailscale` selects Tailscale explicitly without a route question (Tailscale login, client sign-in and approval can still be asked). Auto honors a saved temporary-relay choice; otherwise it uses Tailscale when usable and bundled Gozar with consent when not. Explicit `--route tailscale` never falls back to a trial link.', '', 'Example: dalan setup'] },
21
+ { name: 'service', group: 'operator', summary: 'Install or migrate a long-running bridge service', usage: 'dalan service install|migrate-workers [options]',
22
+ detail: ['Install a bridge as a systemd user service and register its existing HTTPS origin with Gozar.', '',
23
+ 'Install: dalan service install --home DIR --public-url https://HOST --port N --target HOST:PORT [--lan-port N] [--enable-workspace] [--enable-t3] [--worker NAME ...] [--verify-cmd COMMAND] [--write-units-only]',
24
+ 'Use --worker once per worker for an empty home. To preserve existing repository allowlists, run `dalan service migrate-workers` first and omit --worker.',
25
+ 'The bridge listens on 127.0.0.1. For a Gozar target on another address, systemd forwards that target to the fixed loopback port.',
26
+ 'Migrate: dalan service migrate-workers --home DIR --source workers.json [--source workers.json ...]',
27
+ 'See docs/service-setup.md for routing and worker migration details.'] },
28
+ { name: 'init', group: 'start', summary: 'Create a bridge home and its first worker profile', usage: 'dalan init --public-url URL (--worker NAME [--enable-workspace] | --legacy) [--json]',
29
+
16
30
  detail: ['Writes the built-in authorization server files and the first worker profile into the bridge home (DALAN_HOME).', 'It needs no running bridge.', '',
17
31
  'Options:', ' --public-url URL the address clients will use to reach the bridge: https://HOST, or',
18
- ' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
32
+ ' http://127.0.0.1:PORT when DALAN_LOOPBACK=1 is set', ' --worker NAME create the first worker profile with this name', ' --enable-workspace allow this worker to use repository tools when the bridge enables them', ' --legacy keep the settings of an older single-worker host instead of creating a profile', ' --json print the result as JSON', '',
19
33
  'Example (a bridge on this computer only):', ' export DALAN_HOME="$HOME/.local/share/dalan-manual-trial"', ' export DALAN_LOOPBACK=1', ' dalan init --worker local --public-url http://127.0.0.1:8799'] },
20
34
  { name: 'connect', group: 'start', summary: 'Pair a worker client with the bridge', usage: 'dalan connect <subcommand> [options]',
21
35
  detail: ['Subcommands:', ' start --worker NAME [--minutes N] open a pairing window for a worker', ' pending [--json] show connection attempts waiting for approval',
@@ -24,10 +38,10 @@ export const COMMANDS = [
24
38
  ' add-client --redirect-uri URI [--name NAME] [--json] register an OAuth client', ' clients [--json] list OAuth clients', ' remove-client CLIENT_ID [--json] remove an OAuth client',
25
39
  ' allow-callback PATTERN allow another OAuth callback pattern', ' signal-token [--worker NAME] [--rotate] [--json] show or rotate a worker signal token', '',
26
40
  'Examples (pair a worker named local):', ' dalan connect start --worker local', ' dalan connect pending', ' dalan connect approve CODE --worker local --confirm-redirect URI',
27
- 'Replace CODE with the code that pending and the browser page both show, and URI with the', 'redirect that pending shows.'] },
41
+ 'Replace CODE with the code that pending and the browser page both show.', 'For URI, use the callback you expect from your client\'s own configuration and compare it', 'with pending: do not approve when they differ or you cannot verify it.'] },
28
42
  { name: 'submit', group: 'everyday', summary: 'Queue a job for a worker', usage: 'dalan submit (--file PATH | --stdin | --brief TEXT) [options]',
29
43
  detail: ['Queues a job. Give it a JSON assignment (request_id, inputs, brief, ...) or, with --brief, plain text for a question that needs no files.', 'Prints the request ID.', '',
30
- 'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
44
+ 'Options:', ' --file PATH | --stdin | --brief TEXT', ' where the job comes from (exactly one). --brief makes a read-only job with', ' no repository from TEXT, used exactly as typed', ' --eligible LIST route one read-only result to explicit workers; job needs valid_until', ' --policy PATH JSON routing policy and optional destination_revisions', ` pool setup and worker flow: ${docsUrl('docs/pull-queue.md')}`, ' --worker NAME queue for a named worker (default: the profile\'s only worker;', ' required when the profile has several)',
31
45
  ' --thread ID deliver the result to a T3 Code thread (optional integration)', ' --deliver none|t3:ID delivery target (default: none; not with --thread)', ' --review ask for a review of work already done',
32
46
  ' --wait wait for the result before returning', ' --timeout S with --wait: seconds to wait, 1 to 3600 (default: 300)', ' --dry-run check the assignment and store nothing',
33
47
  ' --queue-anyway queue even when the bridge would defer or warn', ' --refuse-defer fail instead of deferring',
@@ -101,7 +115,7 @@ export function shortHelp() {
101
115
  return ['Dalan: hand bounded jobs to a worker agent, follow their progress and review the results.', '',
102
116
  'Usage: dalan <command> [options]', '',
103
117
  ...GROUPS.flatMap(([key, title]) => [...section(title, COMMANDS.filter(c => c.group === key)), '']),
104
- 'Environment:', ' DALAN_HOME bridge home that commands use; for the trial: export DALAN_HOME=~/.local/share/dalan-trial', '',
118
+ 'Environment:', ' DALAN_HOME bridge home commands use: the Home line a run prints (local: ~/.local/share/dalan-trial)', '',
105
119
  'Start here: dalan try',
106
120
  'Details: dalan <command> --help', 'More: dalan help --all', 'Version: dalan --version', ''].join('\n').trimEnd();
107
121
  }
@@ -3,6 +3,7 @@
3
3
  // claim that any particular client works.
4
4
  import { createHash, randomBytes } from 'node:crypto';
5
5
  import { parseJsonBody, safeDiagnostic } from './diagnostic.mjs';
6
+ import { mcpResponseText } from './mcp-sse.mjs';
6
7
 
7
8
  // A loopback pattern without a port admits any port, so this URI matches the 'http://127.0.0.1/callback' pattern.
8
9
  export const DEMO_REDIRECT = 'http://127.0.0.1:43111/callback';
@@ -102,8 +103,7 @@ export async function openSession(mcpUrl, token, { signal } = {}) {
102
103
  return { res, text };
103
104
  };
104
105
  const parse = text => {
105
- const data = text.startsWith('event:') || text.startsWith('data:') ? text.split('\n').find(l => l.startsWith('data:'))?.slice(5) : text;
106
- return parseJsonBody(data ?? 'null', 'MCP response');
106
+ return parseJsonBody(mcpResponseText(text) ?? 'null', 'MCP response');
107
107
  };
108
108
 
109
109
  const init = await post({ jsonrpc: '2.0', id: ++nextId, method: 'initialize', params: { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: { name: 'dalan-demo', version: '1' } } });
@@ -0,0 +1,26 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+
4
+ // null means inspection could not establish liveness. Callers must retain the slot in that state.
5
+ export function liveWaiter(held, { platform = process.platform, run = execFileSync, readFile = fs.readFileSync, probe = pid => process.kill(pid, 0) } = {}) {
6
+ if (!Number.isSafeInteger(held?.pid) || held.pid <= 0) return null;
7
+ try { probe(held.pid); }
8
+ catch (error) {
9
+ if (error.code === 'ESRCH') return false;
10
+ if (error.code !== 'EPERM') return null;
11
+ }
12
+
13
+ let command;
14
+ try {
15
+ command = platform === 'darwin'
16
+ ? run('/bin/ps', ['-p', String(held.pid), '-o', 'command='], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 1000 })
17
+ : platform === 'linux' ? readFile(`/proc/${held.pid}/cmdline`, 'utf8') : null;
18
+ } catch (error) {
19
+ if (error.code === 'ENOENT') {
20
+ try { probe(held.pid); } catch (probeError) { if (probeError.code === 'ESRCH') return false; }
21
+ }
22
+ return null;
23
+ }
24
+ if (typeof command !== 'string' || !command) return null;
25
+ return command.includes('wait') && command.includes('--drained');
26
+ }
@@ -10,7 +10,24 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
 
12
12
  const entryName = owner => `${owner.pid}-${owner.token}.json`;
13
- const readEntry = file => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) { return error.code === 'ENOENT' ? undefined : null; } };
13
+ const readEntry = file => {
14
+ let raw;
15
+ try { raw = fs.readFileSync(file, 'utf8'); }
16
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
17
+ let entry;
18
+ try { entry = JSON.parse(raw); } catch { throw new Error(`invalid waiter entry: ${file}`); }
19
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !Number.isSafeInteger(entry.pid) || entry.pid <= 0 || (entry.token !== undefined && typeof entry.token !== 'string')) {
20
+ throw new Error(`invalid waiter entry: ${file}`);
21
+ }
22
+ return entry;
23
+ };
24
+
25
+ const waiterIsLive = (entry, isLive, file) => {
26
+ const state = isLive(entry);
27
+ if (state === true) return true;
28
+ if (state === false) return false;
29
+ throw new Error(`could not inspect waiter: ${file}`);
30
+ };
14
31
 
15
32
  // Returns null when `owner` now holds the slot, or the live holder's entry. Throws when the slot cannot be settled.
16
33
  export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
@@ -25,7 +42,7 @@ export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
25
42
  try { stat = fs.lstatSync(slot); } catch { continue; }
26
43
  if (stat.isFile()) { // a pidfile written by an earlier release
27
44
  const held = readEntry(slot);
28
- if (held && isLive(held)) return held;
45
+ if (held && waiterIsLive(held, isLive, slot)) return held;
29
46
  beforeRemoval?.();
30
47
  fs.rmSync(slot, { force: true });
31
48
  continue;
@@ -36,7 +53,7 @@ export function takeSlot(slot, owner, { isLive, beforeRemoval } = {}) {
36
53
  for (const name of names) {
37
54
  const entry = readEntry(path.join(slot, name));
38
55
  if (entry === undefined) continue;
39
- if (entry && isLive(entry)) return entry;
56
+ if (waiterIsLive(entry, isLive, path.join(slot, name))) return entry;
40
57
  stale.push(name);
41
58
  }
42
59
  if (!stale.length) continue; // empty: the next rename replaces it
@@ -3,6 +3,15 @@ import { performance } from 'node:perf_hooks';
3
3
  import { redactNote } from './alerts.mjs';
4
4
 
5
5
  const responses = new WeakMap();
6
+
7
+ // The caller's class, never its text: a User-Agent can hold anything, including a credential, so only a name from this fixed
8
+ // list is logged ("other" for the rest, null when absent). That is enough to tell an Anthropic or OpenAI caller from a generic one.
9
+ const UA_CLASSES = [['Claude-User', /^claude-user/i], ['ClaudeBot', /^claudebot/i], ['anthropic-ai', /^anthropic-ai/i], ['ChatGPT-User', /^chatgpt-user/i], ['OAI-SearchBot', /^oai-searchbot/i],
10
+ ['node', /^node(?![A-Za-z0-9._-])/i], ['undici', /^undici/i], ['curl', /^curl/i], ['python', /^python/i], ['Mozilla', /^mozilla/i]];
11
+ export const uaToken = req => {
12
+ const ua = String(req.headers?.['user-agent'] ?? '');
13
+ return ua === '' ? null : (UA_CLASSES.find(([, pattern]) => pattern.test(ua))?.[0] ?? 'other');
14
+ };
6
15
  const methods = new Set(['server/discover', 'initialize', 'ping', 'tools/list', 'tools/call', 'events/list', 'events/subscribe', 'events/unsubscribe', 'notifications/initialized', 'notifications/cancelled']);
7
16
 
8
17
  // Log only declared protocol names and numeric outcomes. RPC IDs, arguments,
@@ -22,7 +31,7 @@ export function beginMcpOutcome(req, res, log, toolNames, authRequired) {
22
31
  response_kind: 'empty', error_type: null,
23
32
  };
24
33
  responses.set(res, state);
25
- log({ kind: 'mcp_received', call_id: state.call_id, http_method: state.http_method });
34
+ log({ kind: 'mcp_received', call_id: state.call_id, http_method: state.http_method, ua: uaToken(req) });
26
35
  let recorded = false;
27
36
  const complete = completion => {
28
37
  if (recorded) return;