@tnunamak/dalan 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/t3.mjs CHANGED
@@ -102,6 +102,12 @@ async function settleProcessGroup(groupId) {
102
102
  }
103
103
 
104
104
  function add(args, flag, value) { if (value !== undefined && value !== null && value !== '') args.push(flag, String(value)); }
105
+ function addCount(args, flag, value) {
106
+ if (value === undefined || value === null) return;
107
+ if (!Number.isSafeInteger(value) || value < (flag === '--timeout' ? 1 : 0))
108
+ throw new TypeError(`${flag} requires ${flag === '--timeout' ? 'a positive' : 'a non-negative'} integer`);
109
+ add(args, flag, value);
110
+ }
105
111
  function addBool(args, flag, value) { if (value === true) args.push(flag); }
106
112
 
107
113
  export function listArgs({ cwd, project, status, workspace_mode } = {}) {
@@ -116,8 +122,8 @@ export function listArgs({ cwd, project, status, workspace_mode } = {}) {
116
122
  export function readArgs({ thread, detail, turns, max_chars, last_turn, first_turn } = {}) {
117
123
  const args = ['threads','read','--thread',thread];
118
124
  add(args,'--detail',detail);
119
- add(args,'--turns',turns);
120
- add(args,'--max-chars',max_chars);
125
+ addCount(args,'--turns',turns);
126
+ addCount(args,'--max-chars',max_chars);
121
127
  addBool(args,'--last-turn',last_turn);
122
128
  addBool(args,'--first-turn',first_turn);
123
129
  return args;
@@ -137,9 +143,9 @@ export function createArgs({ cwd, workspace_mode, project_policy, open, provider
137
143
  add(args,'--interaction-mode',interaction_mode);
138
144
  for (const option of options ?? []) add(args,'--option',option);
139
145
  addBool(args,'--wait',wait);
140
- add(args,'--timeout',timeout);
146
+ addCount(args,'--timeout',timeout);
141
147
  add(args,'--detail',detail);
142
- add(args,'--max-chars',max_chars);
148
+ addCount(args,'--max-chars',max_chars);
143
149
  return args;
144
150
  }
145
151
 
@@ -155,17 +161,17 @@ export function threadSendArgs({ thread, if_busy, provider, model, speed_mode, t
155
161
  for (const option of options ?? []) add(args,'--option',option);
156
162
  addBool(args,'--wake-settled',wake_settled);
157
163
  addBool(args,'--wait',wait);
158
- add(args,'--timeout',timeout);
164
+ addCount(args,'--timeout',timeout);
159
165
  add(args,'--detail',detail);
160
- add(args,'--max-chars',max_chars);
166
+ addCount(args,'--max-chars',max_chars);
161
167
  return args;
162
168
  }
163
169
 
164
170
  export function waitArgs({ thread, timeout, detail, max_chars } = {}) {
165
171
  const args = ['threads','wait','--thread',thread];
166
- add(args,'--timeout',timeout);
172
+ addCount(args,'--timeout',timeout);
167
173
  add(args,'--detail',detail);
168
- add(args,'--max-chars',max_chars);
174
+ addCount(args,'--max-chars',max_chars);
169
175
  return args;
170
176
  }
171
177
 
@@ -1,19 +1,21 @@
1
1
  // Text that a worker or a job supplied must not drive the operator's terminal. An ESC, BEL or C1 byte can retitle the
2
- // window, forge earlier lines or replace the clipboard (OSC 52). This is the one place that makes such text printable.
3
- const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029]/gu;
2
+ // window, forge earlier lines or replace the clipboard (OSC 52). Escape bidi embeddings/overrides, isolates and marks,
3
+ // zero-width space, BOM and lone surrogates too: they can hide or reorder displayed text. Preserve ZWNJ for Persian
4
+ // and ZWJ for emoji sequences. Unicode-mode matching preserves valid surrogate pairs (astral characters).
5
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u2028\u2029\u202a-\u202e\u2066-\u2069\u200e\u200f\u200b\ufeff\ud800-\udfff]/gu;
4
6
  const escapeChar = c => {
5
7
  const code = c.codePointAt(0);
6
8
  return code <= 0xff ? `\\x${code.toString(16).padStart(2, '0')}` : `\\u${code.toString(16).padStart(4, '0')}`;
7
9
  };
8
10
 
9
- // Human output: keep \n and \t, spell every other control character as \xNN so it shows and does nothing.
11
+ // Human output: keep \n and \t; spell unsafe characters as \xNN or \uNNNN so they show and do nothing.
10
12
  export function terminalSafe(text) { return String(text).replace(CONTROL, escapeChar); }
11
13
 
12
- // Machine JSON output: JSON.stringify already escapes C0 controls; DEL and C1 stay raw. Spell those as \uNNNN, which
13
- // parses back to the same string.
14
+ // Machine JSON output: JSON.stringify escapes C0 and lone surrogates; other unsafe characters can stay raw.
15
+ // Spell raw unsafe characters as \uNNNN, which parses back to the same string.
14
16
  export function jsonTerminalSafe(jsonText) {
15
- return String(jsonText).replace(/[\u007f-\u009f\u2028\u2029]/gu, c => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
17
+ return String(jsonText).replace(/[\u007f-\u009f\u061c\u2028\u2029\u202a-\u202e\u2066-\u2069\u200e\u200f\u200b\ufeff\ud800-\udfff]/gu, c => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
16
18
  }
17
19
 
18
20
  // One-line fields (inbox rows): newline and tab are spelled out too, so a field cannot start a forged line.
19
- export function terminalSafeLine(text) { return String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu, escapeChar); }
21
+ export function terminalSafeLine(text) { return String(text).replace(/[\u0000-\u001f\u007f-\u009f\u061c\u2028\u2029\u202a-\u202e\u2066-\u2069\u200e\u200f\u200b\ufeff\ud800-\udfff]/gu, escapeChar); }
@@ -18,8 +18,8 @@ const T3_NAMES = new Set(['t3_thread_list','t3_thread_read','t3_thread_wait','t3
18
18
  const RESERVED = new Set(['list_tools', 'call_tool_read', 'call_tool_write', ...T3_NAMES]);
19
19
  const FORBIDDEN_KIND = /(delete|overwrite|unlink|truncate|wipe|destroy|remove)/i;
20
20
  const FORBIDDEN_WORD = /^(delete|overwrite|remove|unlink|truncate|wipe|destroy|rm|rmdir|erase|replace)$/i;
21
- // The longest a handler may run (the t3-post command timeout), and the lease a pending reservation holds: that timeout plus
22
- // a margin. A crashed call leaves a pending row; once its lease passes, a retry under the same key takes the row over.
21
+ // A pending reservation keeps its lease for the handler timeout plus a margin. Expiry allows a read to run again.
22
+ // An unresolved write keeps its reservation unless its handler can repeat the same durable operation safely.
23
23
  export const HANDLER_TIMEOUT_MS = 15_000;
24
24
  const LEASE_MARGIN_MS = 30_000;
25
25
  export const LIMITS = Object.freeze({ resultBytes: 32768, callsPerMinute: 30, admissionPerMinute: 120, idempotencyKeyMax: 128, idempotencyTtlMs: 7 * 86_400_000, idempotencyLeaseMs: HANDLER_TIMEOUT_MS + LEASE_MARGIN_MS });
@@ -44,10 +44,9 @@ const configStrings = (value, out = []) => {
44
44
  return out;
45
45
  };
46
46
 
47
- // `now` defaults to Date.now for the bare registry. The server passes the Store's monotonic clock, so within one running
48
- // bridge process a wall-clock step cannot shorten or stretch a lease; lease expiry is not compared across processes.
47
+ // Reuse the Store's monotonic clock so a wall-clock step cannot shorten or stretch a lease in a running bridge.
49
48
  // `hooks.afterIdempotencyLookup` is a test seam that pauses a call between its lookup and its reservation.
50
- export function createToolRegistry({ store, now = Date.now, handlers = {}, audit = null, callsPerMinute = LIMITS.callsPerMinute, admissionPerMinute = LIMITS.admissionPerMinute, hooks = {} }) {
49
+ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, audit = null, callsPerMinute = LIMITS.callsPerMinute, admissionPerMinute = LIMITS.admissionPerMinute, hooks = {} }) {
51
50
  const db = store.db;
52
51
  const windows = new Map();
53
52
  const record = entry => {
@@ -196,11 +195,11 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
196
195
  const capResult = result => {
197
196
  const clean = redactOutput(result ?? null);
198
197
  const text = JSON.stringify(clean) ?? 'null';
199
- if (text.length <= LIMITS.resultBytes) return clean;
198
+ if (Buffer.byteLength(text, 'utf8') <= LIMITS.resultBytes) return clean;
200
199
  let length = LIMITS.resultBytes - 64;
201
200
  for (;;) {
202
201
  const capped = { truncated: true, preview: redactSecrets(text.slice(0, length)).text };
203
- if (JSON.stringify(capped).length <= LIMITS.resultBytes || length < 16) return capped;
202
+ if (Buffer.byteLength(JSON.stringify(capped), 'utf8') <= LIMITS.resultBytes) return capped;
204
203
  length = Math.floor(length * 0.9);
205
204
  }
206
205
  };
@@ -214,7 +213,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
214
213
  // The one enforcement function. Order: per-worker admission budget, exact lookup, grant, class, schema hash, idempotency, arguments, rate limit,
215
214
  // handler. Unknown, ungranted and disabled tools share one refusal (tool_unavailable) so a worker cannot enumerate
216
215
  // tools it cannot use. The handler takes its target and config only from the registry row.
217
- async function callTool({ worker, tool, class: callClass, args, schema_hash: pinnedHash, idempotency_key: key }) {
216
+ async function callTool({ worker, tool, class: callClass, args, schema_hash: pinnedHash, idempotency_key: key, context = null }) {
218
217
  const name = workerName(worker);
219
218
  if (!admit(name)) throw new RegistryError('rate_limited', 'too many calls; retry later');
220
219
  let digest = null;
@@ -230,28 +229,83 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
230
229
  const seconds = Math.max(1, Math.ceil((Date.parse(stored?.lease_expires_at ?? '') - now()) / 1000) || 1);
231
230
  done('replay_unfinished', new RegistryError('in_progress', `an earlier call with this idempotency_key is in progress; retry later with the same key in about ${seconds} s`));
232
231
  };
233
- const unavailable = outcome => done(outcome, new RegistryError('tool_unavailable', 'tool unavailable'));
234
- if (!row || JSON.parse(row.handler).kind==='t3_control') unavailable('unknown_tool');
235
- if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(row.name, name)) unavailable('not_granted');
236
- if (row.enabled !== 1) unavailable('disabled');
237
- if (callClass !== toolClass(row)) done('wrong_class', new RegistryError('wrong_class', 'wrong class for this tool; see list_tools'));
238
- const stale = () => done('stale_registry', new RegistryError('stale_registry', 'call list_tools again'));
239
- if (pinnedHash === undefined ? toolClass(row) === 'write' : pinnedHash !== callerHash(row, name)) stale();
240
- const keyError = keyProblem(key, toolClass(row) === 'write');
232
+ const uncertain = () => done('outcome_uncertain', new RegistryError('outcome_uncertain', 'an earlier write may have taken effect; check its destination before using a new key'));
233
+ const unavailable = outcome => ({ outcome, error: new RegistryError('tool_unavailable', 'tool unavailable') });
234
+ const stale = () => ({ outcome: 'stale_registry', error: new RegistryError('stale_registry', 'call list_tools again') });
235
+ const authorize = (current, previousHash) => {
236
+ if (!current || JSON.parse(current.handler).kind === 't3_control') return unavailable('unknown_tool');
237
+ if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(current.name, name)) return unavailable('not_granted');
238
+ if (current.enabled !== 1) return unavailable('disabled');
239
+ const cls = toolClass(current);
240
+ if (callClass !== cls) return { outcome: 'wrong_class', error: new RegistryError('wrong_class', 'wrong class for this tool; see list_tools') };
241
+ const hash = callerHash(current, name);
242
+ if ((pinnedHash === undefined ? cls === 'write' : pinnedHash !== hash) || (previousHash !== undefined && previousHash !== hash)) return stale();
243
+ return { hash };
244
+ };
245
+ const deny = ({ outcome, error }) => { if (error) done(outcome, error); };
246
+ const initial = authorize(row);
247
+ deny(initial);
248
+ const keyError = keyProblem(key, callClass === 'write');
241
249
  if (keyError) done('invalid_arguments', new RegistryError('invalid_arguments', keyError));
250
+ const config = JSON.parse(row.handler);
251
+ const impl = handlers[config.kind];
252
+ const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context };
253
+ const assertArguments = () => {
254
+ const errors = validateValue(JSON.parse(row.input_schema), args);
255
+ if (errors.length) done('invalid_arguments', new RegistryError('invalid_arguments', errors.slice(0, 5).join('; ')));
256
+ };
257
+ const claimAuthority = () => {
258
+ try { return { binding: sha256(canonical([impl.authorizeReplay(call), digest, row.schema_hash])) }; }
259
+ catch (error) { return { outcome: error.code ?? 'authorization_failed', error }; }
260
+ };
261
+ let binding;
262
+ if (impl?.authorizeReplay) {
263
+ // Claim-scoped receipts contain owner data. Check the live grant before any cached
264
+ // response, and bind reservation and receipt to the authenticated caller and payload.
265
+ assertArguments();
266
+ const scoped = claimAuthority();
267
+ deny(scoped);
268
+ binding = scoped.binding;
269
+ }
270
+ const latestAuthority = () => {
271
+ const authority = authorize(getTool(row.name), initial.hash);
272
+ if (authority.error || binding === undefined) return authority;
273
+ const scoped = claimAuthority();
274
+ if (scoped.error || scoped.binding === binding) return scoped;
275
+ return { outcome: 'idempotency_conflict', error: new RegistryError('idempotency_conflict', 'the call no longer belongs to the same claim authority') };
276
+ };
277
+ const mayRetakePending = callClass === 'read' || (impl?.recoverPendingWrite === true && binding !== undefined);
278
+ const checkBinding = outcome => {
279
+ if (binding !== undefined && binding !== outcome?.binding)
280
+ done('idempotency_conflict', new RegistryError('idempotency_conflict', 'the key already belongs to a different call'));
281
+ };
282
+ const pending = binding===undefined?null:JSON.stringify({binding});
283
+ const replay = outcome => {
284
+ checkBinding(outcome);
285
+ done('replayed');
286
+ return { ok: true, result: outcome.result, replayed: true };
287
+ };
288
+ const readKey = () => db.prepare('SELECT * FROM tool_idempotency WHERE worker=? AND tool=? AND key=?').get(name, row.name, key);
242
289
  if (key !== undefined) {
243
- // Retention runs from completion; a row without completed_at (pending, or from an older build) uses created_at.
244
- db.prepare('DELETE FROM tool_idempotency WHERE COALESCE(completed_at, created_at) < ?').run(iso(now() - LIMITS.idempotencyTtlMs));
290
+ // Age completed receipts only. Expiring an unresolved write would allow it to execute twice.
291
+ db.prepare("DELETE FROM tool_idempotency WHERE state='done' AND COALESCE(completed_at, created_at) < ?").run(iso(now() - LIMITS.idempotencyTtlMs));
245
292
  for (;;) {
246
- const stored = db.prepare('SELECT * FROM tool_idempotency WHERE worker=? AND tool=? AND key=?').get(name, row.name, key);
293
+ const stored = readKey();
247
294
  const paused = hooks.afterIdempotencyLookup?.(stored);
248
295
  if (paused) await paused;
296
+ deny(latestAuthority());
249
297
  if (stored?.state === 'pending') {
250
- // A live lease means the earlier call may still be running. An expired (or pre-lease, NULL) lease is taken over below.
298
+ if (binding !== undefined) checkBinding(JSON.parse(stored.outcome));
251
299
  if (leaseLive(stored)) inProgress(stored);
300
+ if (!mayRetakePending) {
301
+ const current = readKey();
302
+ if (current?.state !== 'pending' || current.lease_expires_at !== stored.lease_expires_at) continue;
303
+ uncertain();
304
+ }
252
305
  } else if (stored) {
253
306
  const outcome = JSON.parse(stored.outcome);
254
- if (outcome.ok) { done('replayed'); return { ok: true, result: outcome.result, replayed: true }; }
307
+ if (outcome.ok) return replay(outcome);
308
+ checkBinding(outcome);
255
309
  if (!outcome.retryable) done('replayed_failure', new RegistryError(outcome.code, outcome.message));
256
310
  // Free exactly the row we read (outcome, reservation time, lease and completion time). If another caller already
257
311
  // replaced it, this changes nothing and we read again instead of erasing theirs.
@@ -260,33 +314,40 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
260
314
  break;
261
315
  }
262
316
  }
263
- const schema = JSON.parse(row.input_schema);
264
- const errors = validateValue(schema, args);
265
- if (errors.length) done('invalid_arguments', new RegistryError('invalid_arguments', errors.slice(0, 5).join('; ')));
317
+ if (!impl?.authorizeReplay) assertArguments();
266
318
  if (rateLimited(`${row.name}\0${name}`)) done('rate_limited', new RegistryError('rate_limited', 'too many calls; retry later'));
267
- const config = JSON.parse(row.handler);
268
319
  // Every write below is bound to this call's own lease, so a first attempt that wakes up after a takeover cannot
269
320
  // overwrite or delete the taker's row.
270
- const lease = iso(now() + leaseMs(handlers[config.kind]));
321
+ const lease = iso(now() + leaseMs(impl));
271
322
  const mine = 'WHERE worker=? AND tool=? AND key=? AND state=\'pending\' AND lease_expires_at=?';
272
- const settle = outcome => { if (key !== undefined) db.prepare(`UPDATE tool_idempotency SET state='done', outcome=?, completed_at=? ${mine}`).run(JSON.stringify(outcome), iso(now()), name, row.name, key, lease); };
273
- // Reserve the key atomically. A fresh key is decided by the primary key. An expired pending row is taken over by a
274
- // conditional UPDATE, so of two concurrent takers (even in another process) exactly one changes the row.
323
+ const settle = outcome => { if (key !== undefined) db.prepare(`UPDATE tool_idempotency SET state='done', outcome=?, completed_at=? ${mine}`).run(JSON.stringify(binding===undefined?outcome:{...outcome,binding}), iso(now()), name, row.name, key, lease); };
324
+ // Authorize and claim in one transaction. No handler runs with authority from before the lookup pause.
275
325
  if (key !== undefined) {
276
326
  const stamp = iso(now());
277
- const taken = db.prepare("UPDATE tool_idempotency SET lease_expires_at=?, created_at=? WHERE worker=? AND tool=? AND key=? AND state='pending' AND (lease_expires_at IS NULL OR lease_expires_at <= ?)")
278
- .run(lease, stamp, name, row.name, key, stamp).changes === 1;
279
- if (!taken && db.prepare('INSERT INTO tool_idempotency(worker,tool,key,state,outcome,created_at,lease_expires_at) VALUES(?,?,?,\'pending\',NULL,?,?) ON CONFLICT DO NOTHING').run(name, row.name, key, stamp, lease).changes === 0) {
280
- const current = db.prepare('SELECT * FROM tool_idempotency WHERE worker=? AND tool=? AND key=?').get(name, row.name, key);
327
+ const reservation = atomically(() => {
328
+ const authority = latestAuthority();
329
+ if (authority.error) return authority;
330
+ const taken = mayRetakePending && db.prepare("UPDATE tool_idempotency SET lease_expires_at=?, created_at=? WHERE worker=? AND tool=? AND key=? AND state='pending' AND (lease_expires_at IS NULL OR lease_expires_at <= ?) AND (? IS NULL OR outcome=?)")
331
+ .run(lease, stamp, name, row.name, key, stamp, pending, pending).changes === 1;
332
+ if (taken) return {};
333
+ const inserted = db.prepare("INSERT INTO tool_idempotency(worker,tool,key,state,outcome,created_at,lease_expires_at) VALUES(?,?,?,'pending',?,?,?) ON CONFLICT DO NOTHING")
334
+ .run(name, row.name, key, pending, stamp, lease).changes === 1;
335
+ return inserted ? {} : { blocked: true };
336
+ });
337
+ deny(reservation);
338
+ if (reservation.blocked) {
339
+ const current = readKey();
281
340
  // The winner may already have finished: replay its result rather than report it as in progress.
282
341
  const finished = current?.state === 'done' ? JSON.parse(current.outcome) : null;
283
- if (finished?.ok) { done('replayed'); return { ok: true, result: finished.result, replayed: true }; }
342
+ if (finished?.ok) return replay(finished);
343
+ if (binding !== undefined && current) checkBinding(JSON.parse(current.outcome));
344
+ if (!mayRetakePending && current?.state === 'pending' && !leaseLive(current)) uncertain();
284
345
  inProgress(current);
285
346
  }
286
347
  }
287
348
  let result;
288
349
  try {
289
- result = await handlers[config.kind].run({ tool: row.name, worker: name, args, config, now, idempotencyKey: key });
350
+ result = await impl.run(call);
290
351
  } catch (error) {
291
352
  if (error instanceof RegistryError) {
292
353
  // The handler refused before doing anything, so the key is free to use again.
@@ -328,6 +389,35 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
328
389
  }
329
390
  });
330
391
  }
392
+ // Provision the built-in definitions and each worker's grant once. A removal or revocation
393
+ // stays in force after restart, and an existing owner tool keeps its name and grants.
394
+ function initializeWorkerTools(specs, workers) {
395
+ return atomically(()=>{
396
+ const conflicts=[];
397
+ const names=[...workers];
398
+ const seeded=db.prepare('SELECT 1 FROM tool_registry_meta WHERE key=?');
399
+ const mark=db.prepare('INSERT INTO tool_registry_meta(key,value) VALUES(?,1)');
400
+ for(const spec of specs) {
401
+ const key=`worker_tool:${spec.name}`, existing=getTool(spec.name);
402
+ if(existing && JSON.parse(existing.handler).kind!==spec.handler.kind) {
403
+ conflicts.push(spec.name);
404
+ continue;
405
+ }
406
+ if(!seeded.get(key)) {
407
+ if(!existing) register(spec);
408
+ mark.run(key);
409
+ }
410
+ if(!getTool(spec.name)) continue;
411
+ for(const worker of names) {
412
+ const grantKey=`${key}:${worker}`;
413
+ if(seeded.get(grantKey)) continue;
414
+ grant(spec.name,worker);
415
+ mark.run(grantKey);
416
+ }
417
+ }
418
+ return conflicts;
419
+ });
420
+ }
331
421
  function t3Threads(tool, principal) {
332
422
  // The legacy local principal also resolves to a worker; it has no owner bypass.
333
423
  const row=db.prepare("SELECT g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE g.tool=? AND g.worker=? AND t.enabled=1 AND json_extract(t.handler,'$.kind')='t3_control'").get(tool,principal.worker);
@@ -345,7 +435,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
345
435
  }
346
436
  return threads;
347
437
  }
348
- return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, t3Threads };
438
+ return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, initializeWorkerTools, t3Threads };
349
439
  }
350
440
 
351
441
  // ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
@@ -422,13 +512,15 @@ export function createT3PostHandler({ store, post, command, timeoutMs, now = Dat
422
512
  batch.push({ row, part }); chars += part.length;
423
513
  }
424
514
  const marks = batch.map(() => '?').join(',');
515
+ // An unresolved dispatch is durable before contacting the receiver.
516
+ db.prepare(`UPDATE tool_outbox SET uncertain_at=? WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
425
517
  try { await post({ threadId, label: worker, text: batch.map(b => b.part).join('\n\n') }); }
426
518
  catch (error) {
427
- if (error?.exitCode !== 3) db.prepare(`UPDATE tool_outbox SET uncertain_at=? WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
519
+ if (error?.exitCode === 3) db.prepare(`UPDATE tool_outbox SET uncertain_at=NULL WHERE id IN (${marks})`).run(...batch.map(b => b.row.id));
428
520
  if (attempt) settleLog(attempt, 'failed');
429
521
  throw error;
430
522
  }
431
- db.prepare(`UPDATE tool_outbox SET sent_at=? WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
523
+ db.prepare(`UPDATE tool_outbox SET sent_at=?, uncertain_at=NULL WHERE id IN (${marks})`).run(iso(now()), ...batch.map(b => b.row.id));
432
524
  if (attempt) settleLog(attempt, 'sent');
433
525
  return { sent: batch.length, remaining: rows.length - batch.length };
434
526
  });
@@ -467,14 +559,15 @@ export function createT3PostHandler({ store, post, command, timeoutMs, now = Dat
467
559
  async run({ tool, worker, args, config, idempotencyKey }) {
468
560
  if (!MESSAGE_KINDS.has(args.kind)) refuse('invalid_arguments', 'kind must be question or blocker');
469
561
  if (typeof args.text !== 'string' || !args.text.trim() || args.text.length > 2000) refuse('invalid_arguments', 'text must be 1-2000 characters');
470
- // Delivery is at least once. If an earlier attempt under this key already posted (its row is marked sent) but the
562
+ // A lost delivery acknowledgement stays uncertain. If an earlier attempt under this key already posted (its row is marked sent) but the
471
563
  // registry never settled, return that receipt instead of posting again.
472
564
  const digest = createHash('sha256').update(canonical([args.kind, args.text])).digest('hex');
473
- const earlier = idempotencyKey ? db.prepare('SELECT args_digest, sent_at FROM tool_outbox WHERE tool=? AND worker=? AND idempotency_key=? ORDER BY id DESC LIMIT 1').get(tool, worker, idempotencyKey) : undefined;
565
+ const earlier = idempotencyKey ? db.prepare('SELECT args_digest, sent_at, uncertain_at FROM tool_outbox WHERE tool=? AND worker=? AND idempotency_key=? ORDER BY id DESC LIMIT 1').get(tool, worker, idempotencyKey) : undefined;
474
566
  // A reused key must carry the same message. Rows from an older build have no digest and keep the old behaviour.
475
567
  if (earlier?.args_digest && earlier.args_digest !== digest) refuse('invalid_arguments', 'idempotency key reused with different content');
476
568
  const sentRow = earlier?.sent_at != null;
477
569
  if (sentRow) return { queued: false, sent: 1, remaining: 0, note: 'already sent; receipt reused' };
570
+ if (earlier?.uncertain_at != null) return { queued: false, sent: 0, remaining: 0, delivery_uncertain: true, note: 'Delivery is uncertain; check the destination before resending.' };
478
571
  const stamp = iso(now());
479
572
  // Budget first: every attempt that gets this far is logged with its kind, and counts until it ages out.
480
573
  if (overBudget()) { logPost('rate_limited', tool, worker, args.kind); refuse('rate_limited', 'message budget reached; retry later'); }
@@ -490,7 +583,7 @@ export function createT3PostHandler({ store, post, command, timeoutMs, now = Dat
490
583
  }
491
584
  catch (error) {
492
585
  settle('failed');
493
- // Exit code 3 and any transport failure keep the message queued. Only exit 3 proves nothing was delivered,
586
+ // Only exit 3 proves nothing was delivered,
494
587
  // which is the one case where the caller may retry under the same idempotency key.
495
588
  throw Object.assign(new Error('delivery failed'), { userMessage: error?.exitCode === 3 ? 'delivery failed; the message is kept queued, retry later' : 'delivery failed and the message may have been delivered; it is not retried automatically, check the thread', cause: error, notDelivered: error?.exitCode === 3 });
496
589
  }
@@ -1,6 +1,5 @@
1
1
  // The public-route checks for `dalan try --public`. Routes themselves come from Gozar (gozar-routes.mjs); this file holds what Dalan
2
- // owns around them: the loopback gate a route forwards to, and the readiness and identity checks run on the public origin.
3
- import http from 'node:http';
2
+ // owns around them: the OAuth readiness and identity checks run on the public origin.
4
3
  import { safeDiagnostic } from './diagnostic.mjs';
5
4
  export { processCommand } from './process-inspection.mjs';
6
5
 
@@ -21,38 +20,6 @@ export function lineBuffer(onLine, max = 65_536) {
21
20
  return push;
22
21
  }
23
22
 
24
- // ---- the gate ----------------------------------------------------------------------------------------------------------
25
- // The route forwards to this listener, never to the bridge. A tunnel reports its address only after it starts, and the
26
- // bridge needs that address at `init`, so the route must exist first. The gate answers 503 until the bridge is up, forwards to the
27
- // one bridge port after that, and answers 503 again once closed. Nothing else on the computer is ever reachable through the route.
28
- export async function createGate() {
29
- let upstream = null, publicHost = null;
30
- // A fresh connection per request: a kept-alive socket that the bridge closed in the meantime would fail the next request with a 502
31
- // that the bridge never sees.
32
- const agent = new http.Agent({ keepAlive: false });
33
- const server = http.createServer((req, res) => {
34
- if (!upstream) { res.writeHead(503, { 'content-type': 'text/plain', 'retry-after': '2' }); res.end('starting\n'); return; }
35
- // A route may forward with Host set to this loopback gate. Restore only that exact transport host to the
36
- // allocated public host; preserve other hosts and Origin for the bridge's identity checks.
37
- const headers = publicHost && req.headers.host === `127.0.0.1:${server.address().port}` ? { ...req.headers, host: publicHost } : req.headers;
38
- const forward = http.request({ agent, host: '127.0.0.1', port: upstream, method: req.method, path: req.url, headers }, answer => {
39
- res.writeHead(answer.statusCode, answer.headers);
40
- answer.pipe(res);
41
- });
42
- forward.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });
43
- res.on('close', () => forward.destroy());
44
- req.pipe(forward);
45
- });
46
- server.headersTimeout = 10_000; server.requestTimeout = 60_000;
47
- await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
48
- return {
49
- port: server.address().port,
50
- open(port, { publicOrigin } = {}) { upstream = port; publicHost = publicOrigin ? new URL(publicOrigin).host : null; },
51
- shut() { upstream = null; },
52
- async close() { upstream = null; server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); },
53
- };
54
- }
55
-
56
23
  // A trial constraint, not an OAuth rule: RFC 8414 lets an authorization server live on another origin. A trial's bridge serves its own
57
24
  // authorization server, so the check requires the issuer and every endpoint on the trial's public origin (a bare root issuer counts).
58
25
  export const TRIAL_ORIGIN_RULE = 'a trial constraint: the bridge serves its own authorization server on the public origin';
@@ -69,52 +36,44 @@ export function authorizationServerMetadataUrl(issuer) {
69
36
  // The public address answers as this bridge: trusted TLS (the platform's fetch checks it), discovery that names this origin and
70
37
  // resource, an OAuth challenge on an unauthenticated MCP request, and no owner route. The secret path is known only to this bridge,
71
38
  // so a matching discovery document also shows that the route reaches it and not another program.
72
- export async function verifyPublicReady({ origin, secret, fetchImpl = fetch, clock = { now: Date.now, sleep }, timeoutMs, say = () => {}, signal }) {
73
- const within = ms => signal ? AbortSignal.any([AbortSignal.timeout(ms), signal]) : AbortSignal.timeout(ms);
74
- const resource = `${origin}/${secret}/mcp`;
39
+ export async function verifyPublicReady({ origin, secret, fetchImpl = fetch, clock = { now: () => performance.now(), sleep }, timeoutMs = 30_000, say = () => {}, signal }) {
40
+ const end = clock.now() + timeoutMs;
41
+ const budget = AbortSignal.timeout(Math.max(0, Math.ceil(timeoutMs)));
42
+ const shared = signal ? AbortSignal.any([signal, budget]) : budget;
43
+ const expired = () => budget.aborted || clock.now() >= end;
44
+ const within = ms => AbortSignal.any([shared, AbortSignal.timeout(ms)]);
75
45
  const check = async () => {
76
- const meta = await fetchImpl(`${origin}/.well-known/oauth-protected-resource/${secret}/mcp`, { redirect: 'manual', signal: within(10_000) });
77
- if (meta.status !== 200) return `discovery returned HTTP ${meta.status}`;
78
- const doc = await meta.json().catch(() => null);
79
- if (doc?.resource !== resource) return 'discovery names a different resource';
80
- if (!Array.isArray(doc.authorization_servers) || doc.authorization_servers.length === 0) return 'discovery names no authorization server';
81
- if (!doc.authorization_servers.every(s => onOrigin(origin, String(s)))) return `discovery names an issuer outside this origin (${TRIAL_ORIGIN_RULE})`;
82
- // The issuer's own metadata: the exact issuer, and https endpoints for sign-in, tokens and registration on this origin.
83
- const issuer = String(doc.authorization_servers[0]);
84
- let asUrl; try { asUrl = authorizationServerMetadataUrl(issuer); } catch (error) { return error.message; }
85
- const asMeta = await fetchImpl(asUrl, { redirect: 'manual', signal: within(10_000) });
86
- if (asMeta.status !== 200) return `authorization-server metadata returned HTTP ${asMeta.status}`;
87
- const as = await asMeta.json().catch(() => null);
88
- if (as?.issuer !== issuer) return 'the authorization-server issuer does not match the issuer in discovery';
89
- for (const key of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) {
90
- if (typeof as[key] !== 'string' || !onOrigin(origin, as[key])) return `the authorization server's ${key} is missing or is not an address on this origin (${TRIAL_ORIGIN_RULE})`;
91
- }
92
- const challenge = await fetchImpl(resource, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: '{"jsonrpc":"2.0","id":1,"method":"ping"}', signal: within(10_000) });
93
- const isChallenge = challenge.status === 401 && /^Bearer/i.test(challenge.headers.get('www-authenticate') ?? '');
94
- void challenge.body?.cancel().catch(() => {});
95
- if (!isChallenge) return `an unauthenticated MCP request returned HTTP ${challenge.status}, not an OAuth challenge`;
46
+ const outcome = await raceSignal(checkPublicIdentity({ origin, secret, fetchImpl, signal: shared, timeoutMs: 30_000, requestTimeoutMs: 10_000, startup: true }), shared);
47
+ signal?.throwIfAborted();
48
+ if (outcome.kind !== 'ready') return outcome.detail ?? 'no answer yet';
96
49
  for (const owner of ['/admin', '/connect/pending', '/connect/list']) {
97
- const res = await fetchImpl(`${origin}${owner}`, { redirect: 'manual', signal: within(10_000) });
50
+ const requestSignal = within(10_000);
51
+ const res = await raceSignal(fetchImpl(`${origin}${owner}`, { redirect: 'manual', signal: requestSignal }), requestSignal);
98
52
  const status = res.status;
99
53
  void res.body?.cancel().catch(() => {});
100
54
  if (status === 200) return `${owner} answers on the public address`;
101
55
  }
102
- return {
103
- resource: doc.resource,
104
- authorizationServers: doc.authorization_servers,
105
- issuer,
106
- authorizationServer: as,
107
- };
56
+ return outcome.identity;
108
57
  };
109
- const end = clock.now() + timeoutMs;
110
58
  let last = 'no answer yet', nextSay = clock.now() + 15_000;
59
+ // Out of time, say what the last completed check found; only a run that never got an answer reports the deadline.
60
+ const overdue = () => ({ ready: false, last: last === 'no answer yet' ? 'public readiness deadline exceeded' : last });
111
61
  for (;;) {
112
62
  signal?.throwIfAborted();
113
- try { last = await check(); if (last && typeof last === 'object') return { ready: true, identity: last }; }
114
- catch (error) { if (signal?.aborted) throw error; last = safeDiagnostic(error.cause?.code ?? error.message, 120); }
115
- if (clock.now() >= end) return { ready: false, last };
63
+ if (expired()) return overdue();
64
+ try {
65
+ const observed = await check();
66
+ signal?.throwIfAborted();
67
+ if (observed && typeof observed === 'object' && !expired()) return { ready: true, identity: observed };
68
+ if (typeof observed === 'string') last = observed;
69
+ } catch (error) {
70
+ if (signal?.aborted) throw error;
71
+ if (!expired()) last = safeDiagnostic(error.cause?.code ?? error.message, 120);
72
+ }
73
+ if (expired()) return overdue();
116
74
  if (clock.now() >= nextSay) { say(`Still waiting for the public address to answer (${last})…`); nextSay += 15_000; }
117
- await raceAbort(clock.sleep(2000), signal);
75
+ try { await raceSignal(clock.sleep(Math.min(2000, Math.max(0, end - clock.now()))), shared); }
76
+ catch (error) { if (signal?.aborted) throw error; if (expired()) return overdue(); throw error; }
118
77
  }
119
78
  }
120
79
 
@@ -144,8 +103,8 @@ async function readIdentityJson(response, signal, label, maxBytes = 65_536) {
144
103
  }
145
104
  let value;
146
105
  try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
147
- catch { return { kind: 'identity_changed', detail: `${label} returned invalid JSON` }; }
148
- if (!value || typeof value !== 'object' || Array.isArray(value)) return { kind: 'identity_changed', detail: `${label} returned invalid JSON` };
106
+ catch { return { kind: 'unresponsive', detail: `${label} returned invalid JSON` }; }
107
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { kind: 'identity_changed', detail: `${label} returned a non-object identity document` };
149
108
  return { value };
150
109
  } finally { try { reader.releaseLock(); } catch { /* A timed-out stream may still be cancelling. */ } }
151
110
  }
@@ -165,31 +124,39 @@ function raceSignal(promise, signal, onAbort = () => {}) {
165
124
  }
166
125
 
167
126
  // One bounded identity check: one deadline covers TLS, all response bodies and every endpoint.
168
- export async function checkPublicIdentity({ origin, secret, fetchImpl = fetch, signal, timeoutMs = 5000 }) {
127
+ export async function checkPublicIdentity({ origin, secret, fetchImpl = fetch, signal, timeoutMs = 5000, requestTimeoutMs, startup = false }) {
169
128
  const deadline = AbortSignal.timeout(timeoutMs);
170
129
  const checkSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
171
- const request = (url, init = {}) => raceSignal(fetchImpl(url, { ...init, redirect: 'manual', signal: checkSignal }), checkSignal);
130
+ const requestSignal = () => requestTimeoutMs === undefined ? checkSignal : AbortSignal.any([checkSignal, AbortSignal.timeout(requestTimeoutMs)]);
131
+ const request = (url, init = {}, requestDeadline = requestSignal()) =>
132
+ raceSignal(fetchImpl(url, { ...init, redirect: 'manual', signal: requestDeadline }), requestDeadline);
133
+ const metadata = async (url, label) => {
134
+ const requestDeadline = requestSignal();
135
+ return readIdentityJson(await request(url, {}, requestDeadline), requestDeadline, label);
136
+ };
172
137
  const resource = `${origin}/${secret}/mcp`;
173
138
  try {
174
- const meta = await request(`${origin}/.well-known/oauth-protected-resource/${secret}/mcp`);
175
- const docResult = await readIdentityJson(meta, checkSignal, 'protected-resource metadata');
139
+ const docResult = await metadata(`${origin}/.well-known/oauth-protected-resource/${secret}/mcp`, 'protected-resource metadata');
176
140
  if (docResult.kind) return docResult;
177
141
  const doc = docResult.value;
178
- if (doc.resource !== resource || !Array.isArray(doc.authorization_servers) || !doc.authorization_servers.length ||
179
- doc.authorization_servers.some(value => typeof value !== 'string' || !onOrigin(origin, value))) {
180
- return { kind: 'identity_changed', detail: 'protected-resource identity changed' };
181
- }
142
+ const resourceChanged = detail => ({ kind: 'identity_changed', detail: startup ? detail : 'protected-resource identity changed' });
143
+ const issuerChanged = detail => ({ kind: 'identity_changed', detail: startup ? detail : 'authorization-server identity changed' });
144
+ if (doc.resource !== resource) return resourceChanged('discovery names a different resource');
145
+ if (!Array.isArray(doc.authorization_servers) || !doc.authorization_servers.length)
146
+ return resourceChanged('discovery names no authorization server');
147
+ if (doc.authorization_servers.some(value => typeof value !== 'string' || !onOrigin(origin, value)))
148
+ return resourceChanged('discovery names an authorization server outside this origin (' + TRIAL_ORIGIN_RULE + ')');
182
149
  const issuer = doc.authorization_servers[0];
183
150
  let asUrl;
184
151
  try { asUrl = authorizationServerMetadataUrl(issuer); }
185
- catch { return { kind: 'identity_changed', detail: 'authorization-server identity changed' }; }
186
- const asResponse = await request(asUrl);
187
- const asResult = await readIdentityJson(asResponse, checkSignal, 'authorization-server metadata');
152
+ catch { return issuerChanged('the issuer is not a plain address'); }
153
+ const asResult = await metadata(asUrl, 'authorization-server metadata');
188
154
  if (asResult.kind) return asResult;
189
155
  const as = asResult.value;
190
- if (as.issuer !== issuer || !['authorization_endpoint', 'token_endpoint', 'registration_endpoint'].every(key =>
191
- typeof as[key] === 'string' && onOrigin(origin, as[key]))) {
192
- return { kind: 'identity_changed', detail: 'authorization-server identity changed' };
156
+ if (as.issuer !== issuer) return issuerChanged('the discovered issuer does not match');
157
+ for (const key of ['authorization_endpoint', 'token_endpoint', 'registration_endpoint']) {
158
+ if (typeof as[key] !== 'string' || !onOrigin(origin, as[key]))
159
+ return issuerChanged('authorization-server metadata has an invalid ' + key + ' (' + TRIAL_ORIGIN_RULE + ')');
193
160
  }
194
161
  const challenge = await request(resource, {
195
162
  method: 'POST',
@@ -199,7 +166,7 @@ export async function checkPublicIdentity({ origin, secret, fetchImpl = fetch, s
199
166
  try {
200
167
  if (challenge.status >= 300 && challenge.status < 400) return { kind: 'identity_changed', detail: 'MCP endpoint redirected' };
201
168
  if (challenge.status !== 401 || !/^Bearer/i.test(challenge.headers.get('www-authenticate') ?? '')) {
202
- return { kind: 'unresponsive', detail: `MCP identity probe returned HTTP ${challenge.status}` };
169
+ return { kind: 'unresponsive', detail: startup ? `MCP readiness probe was not an OAuth challenge (HTTP ${challenge.status})` : `MCP identity probe returned HTTP ${challenge.status}` };
203
170
  }
204
171
  } finally { void challenge.body?.cancel().catch(() => {}); }
205
172
  const actual = { resource: doc.resource, authorizationServers: doc.authorization_servers, issuer, authorizationServer: as };