@lushly-dev/afd-server 2.4.0 → 3.0.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 (279) hide show
  1. package/README.md +239 -56
  2. package/dist/admission.d.ts +137 -0
  3. package/dist/admission.d.ts.map +1 -0
  4. package/dist/admission.js +144 -0
  5. package/dist/admission.js.map +1 -0
  6. package/dist/app-call-registry.d.ts +31 -0
  7. package/dist/app-call-registry.d.ts.map +1 -0
  8. package/dist/app-call-registry.js +64 -0
  9. package/dist/app-call-registry.js.map +1 -0
  10. package/dist/approval-admission.d.ts +139 -0
  11. package/dist/approval-admission.d.ts.map +1 -0
  12. package/dist/approval-admission.js +252 -0
  13. package/dist/approval-admission.js.map +1 -0
  14. package/dist/approval-crypto.d.ts +37 -17
  15. package/dist/approval-crypto.d.ts.map +1 -1
  16. package/dist/approval-crypto.js +84 -75
  17. package/dist/approval-crypto.js.map +1 -1
  18. package/dist/approval-process-state.d.ts +21 -0
  19. package/dist/approval-process-state.d.ts.map +1 -0
  20. package/dist/approval-process-state.js +29 -0
  21. package/dist/approval-process-state.js.map +1 -0
  22. package/dist/approval-relay.d.ts +192 -9
  23. package/dist/approval-relay.d.ts.map +1 -1
  24. package/dist/approval-relay.js +45 -9
  25. package/dist/approval-relay.js.map +1 -1
  26. package/dist/approval-up-front.d.ts +40 -0
  27. package/dist/approval-up-front.d.ts.map +1 -0
  28. package/dist/approval-up-front.js +409 -0
  29. package/dist/approval-up-front.js.map +1 -0
  30. package/dist/approval.d.ts +65 -12
  31. package/dist/approval.d.ts.map +1 -1
  32. package/dist/approval.js +311 -47
  33. package/dist/approval.js.map +1 -1
  34. package/dist/approver.d.ts +84 -0
  35. package/dist/approver.d.ts.map +1 -0
  36. package/dist/approver.js +107 -0
  37. package/dist/approver.js.map +1 -0
  38. package/dist/auth-middleware-check.d.ts +23 -0
  39. package/dist/auth-middleware-check.d.ts.map +1 -0
  40. package/dist/auth-middleware-check.js +48 -0
  41. package/dist/auth-middleware-check.js.map +1 -0
  42. package/dist/bootstrap/afd-context.d.ts.map +1 -1
  43. package/dist/bootstrap/afd-context.js +27 -3
  44. package/dist/bootstrap/afd-context.js.map +1 -1
  45. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  46. package/dist/bootstrap/afd-docs.js +4 -0
  47. package/dist/bootstrap/afd-docs.js.map +1 -1
  48. package/dist/bootstrap/afd-help.d.ts +4 -1
  49. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  50. package/dist/bootstrap/afd-help.js +19 -4
  51. package/dist/bootstrap/afd-help.js.map +1 -1
  52. package/dist/bootstrap/described-command.d.ts +3 -1
  53. package/dist/bootstrap/described-command.d.ts.map +1 -1
  54. package/dist/bootstrap/described-command.js.map +1 -1
  55. package/dist/command-allow.d.ts +4 -4
  56. package/dist/command-allow.d.ts.map +1 -1
  57. package/dist/command-allow.js +10 -15
  58. package/dist/command-allow.js.map +1 -1
  59. package/dist/command-routing.d.ts +56 -8
  60. package/dist/command-routing.d.ts.map +1 -1
  61. package/dist/command-routing.js +82 -16
  62. package/dist/command-routing.js.map +1 -1
  63. package/dist/command-timeout.d.ts +17 -0
  64. package/dist/command-timeout.d.ts.map +1 -0
  65. package/dist/command-timeout.js +99 -0
  66. package/dist/command-timeout.js.map +1 -0
  67. package/dist/confirmation-gate.d.ts +7 -7
  68. package/dist/confirmation-gate.d.ts.map +1 -1
  69. package/dist/confirmation-gate.js +26 -12
  70. package/dist/confirmation-gate.js.map +1 -1
  71. package/dist/confirmations.d.ts +28 -3
  72. package/dist/confirmations.d.ts.map +1 -1
  73. package/dist/confirmations.js +6 -7
  74. package/dist/confirmations.js.map +1 -1
  75. package/dist/context-fields.d.ts +16 -1
  76. package/dist/context-fields.d.ts.map +1 -1
  77. package/dist/context-fields.js +30 -13
  78. package/dist/context-fields.js.map +1 -1
  79. package/dist/context-scope.d.ts +3 -3
  80. package/dist/context-scope.d.ts.map +1 -1
  81. package/dist/context-scope.js +7 -8
  82. package/dist/context-scope.js.map +1 -1
  83. package/dist/define-core.d.ts +63 -1
  84. package/dist/define-core.d.ts.map +1 -1
  85. package/dist/define-core.js +27 -4
  86. package/dist/define-core.js.map +1 -1
  87. package/dist/define.d.ts +4 -3
  88. package/dist/define.d.ts.map +1 -1
  89. package/dist/define.js +1 -1
  90. package/dist/define.js.map +1 -1
  91. package/dist/direct-registry.d.ts +54 -8
  92. package/dist/direct-registry.d.ts.map +1 -1
  93. package/dist/direct-registry.js +64 -8
  94. package/dist/direct-registry.js.map +1 -1
  95. package/dist/direct-tool-surface.d.ts +1 -1
  96. package/dist/direct-tool-surface.d.ts.map +1 -1
  97. package/dist/direct-tool-surface.js +28 -6
  98. package/dist/direct-tool-surface.js.map +1 -1
  99. package/dist/direct.d.ts +6 -2
  100. package/dist/direct.d.ts.map +1 -1
  101. package/dist/direct.js +4 -1
  102. package/dist/direct.js.map +1 -1
  103. package/dist/elicitation-state.d.ts +5 -1
  104. package/dist/elicitation-state.d.ts.map +1 -1
  105. package/dist/elicitation-state.js +4 -1
  106. package/dist/elicitation-state.js.map +1 -1
  107. package/dist/execution.d.ts +52 -6
  108. package/dist/execution.d.ts.map +1 -1
  109. package/dist/execution.js +183 -19
  110. package/dist/execution.js.map +1 -1
  111. package/dist/host-state.d.ts +81 -0
  112. package/dist/host-state.d.ts.map +1 -0
  113. package/dist/host-state.js +62 -0
  114. package/dist/host-state.js.map +1 -0
  115. package/dist/http-handler.d.ts +48 -11
  116. package/dist/http-handler.d.ts.map +1 -1
  117. package/dist/http-handler.js +207 -58
  118. package/dist/http-handler.js.map +1 -1
  119. package/dist/http-security.d.ts +14 -1
  120. package/dist/http-security.d.ts.map +1 -1
  121. package/dist/http-security.js +79 -17
  122. package/dist/http-security.js.map +1 -1
  123. package/dist/http-sessions.d.ts +45 -5
  124. package/dist/http-sessions.d.ts.map +1 -1
  125. package/dist/http-sessions.js +52 -10
  126. package/dist/http-sessions.js.map +1 -1
  127. package/dist/http-sse.d.ts +9 -0
  128. package/dist/http-sse.d.ts.map +1 -1
  129. package/dist/http-sse.js +12 -3
  130. package/dist/http-sse.js.map +1 -1
  131. package/dist/human-relay.d.ts +195 -0
  132. package/dist/human-relay.d.ts.map +1 -0
  133. package/dist/human-relay.js +670 -0
  134. package/dist/human-relay.js.map +1 -0
  135. package/dist/idempotency-step.d.ts +231 -0
  136. package/dist/idempotency-step.d.ts.map +1 -0
  137. package/dist/idempotency-step.js +389 -0
  138. package/dist/idempotency-step.js.map +1 -0
  139. package/dist/idempotency-store.d.ts +107 -0
  140. package/dist/idempotency-store.d.ts.map +1 -0
  141. package/dist/idempotency-store.js +100 -0
  142. package/dist/idempotency-store.js.map +1 -0
  143. package/dist/index.d.ts +18 -8
  144. package/dist/index.d.ts.map +1 -1
  145. package/dist/index.js +15 -4
  146. package/dist/index.js.map +1 -1
  147. package/dist/instance-state.d.ts +53 -0
  148. package/dist/instance-state.d.ts.map +1 -0
  149. package/dist/instance-state.js +94 -0
  150. package/dist/instance-state.js.map +1 -0
  151. package/dist/journal-off-tape.d.ts +52 -0
  152. package/dist/journal-off-tape.d.ts.map +1 -0
  153. package/dist/journal-off-tape.js +150 -0
  154. package/dist/journal-off-tape.js.map +1 -0
  155. package/dist/journal-replay.d.ts.map +1 -1
  156. package/dist/journal-replay.js +48 -3
  157. package/dist/journal-replay.js.map +1 -1
  158. package/dist/journal-view.d.ts +50 -0
  159. package/dist/journal-view.d.ts.map +1 -0
  160. package/dist/journal-view.js +214 -0
  161. package/dist/journal-view.js.map +1 -0
  162. package/dist/journal.d.ts +34 -6
  163. package/dist/journal.d.ts.map +1 -1
  164. package/dist/journal.js +183 -47
  165. package/dist/journal.js.map +1 -1
  166. package/dist/json-rpc.d.ts +3 -2
  167. package/dist/json-rpc.d.ts.map +1 -1
  168. package/dist/json-rpc.js +5 -3
  169. package/dist/json-rpc.js.map +1 -1
  170. package/dist/lazy-tools.d.ts +27 -2
  171. package/dist/lazy-tools.d.ts.map +1 -1
  172. package/dist/lazy-tools.js +22 -4
  173. package/dist/lazy-tools.js.map +1 -1
  174. package/dist/mcp-auth-bearer.d.ts +2 -0
  175. package/dist/mcp-auth-bearer.d.ts.map +1 -1
  176. package/dist/mcp-auth-bearer.js +1 -1
  177. package/dist/mcp-auth-bearer.js.map +1 -1
  178. package/dist/mcp-auth-dispatch.d.ts +38 -0
  179. package/dist/mcp-auth-dispatch.d.ts.map +1 -0
  180. package/dist/mcp-auth-dispatch.js +113 -0
  181. package/dist/mcp-auth-dispatch.js.map +1 -0
  182. package/dist/mcp-auth-jwt.d.ts +3 -2
  183. package/dist/mcp-auth-jwt.d.ts.map +1 -1
  184. package/dist/mcp-auth-jwt.js.map +1 -1
  185. package/dist/mcp-auth-resource.d.ts +6 -2
  186. package/dist/mcp-auth-resource.d.ts.map +1 -1
  187. package/dist/mcp-auth-resource.js +6 -5
  188. package/dist/mcp-auth-resource.js.map +1 -1
  189. package/dist/mcp-auth-scopes.d.ts +84 -0
  190. package/dist/mcp-auth-scopes.d.ts.map +1 -0
  191. package/dist/mcp-auth-scopes.js +125 -0
  192. package/dist/mcp-auth-scopes.js.map +1 -0
  193. package/dist/mcp-auth-view.d.ts +50 -0
  194. package/dist/mcp-auth-view.d.ts.map +1 -0
  195. package/dist/mcp-auth-view.js +179 -0
  196. package/dist/mcp-auth-view.js.map +1 -0
  197. package/dist/mcp-auth.d.ts +94 -3
  198. package/dist/mcp-auth.d.ts.map +1 -1
  199. package/dist/mcp-auth.js +241 -23
  200. package/dist/mcp-auth.js.map +1 -1
  201. package/dist/mcp-modern.d.ts +80 -6
  202. package/dist/mcp-modern.d.ts.map +1 -1
  203. package/dist/mcp-modern.js +378 -91
  204. package/dist/mcp-modern.js.map +1 -1
  205. package/dist/meta-argument.d.ts +9 -8
  206. package/dist/meta-argument.d.ts.map +1 -1
  207. package/dist/meta-argument.js +28 -10
  208. package/dist/meta-argument.js.map +1 -1
  209. package/dist/meta-tools.js +2 -2
  210. package/dist/meta-tools.js.map +1 -1
  211. package/dist/middleware.d.ts +16 -1
  212. package/dist/middleware.d.ts.map +1 -1
  213. package/dist/middleware.js +57 -10
  214. package/dist/middleware.js.map +1 -1
  215. package/dist/output-budget.d.ts +77 -0
  216. package/dist/output-budget.d.ts.map +1 -0
  217. package/dist/output-budget.js +202 -0
  218. package/dist/output-budget.js.map +1 -0
  219. package/dist/principal-binding.js +1 -1
  220. package/dist/principal-binding.js.map +1 -1
  221. package/dist/relay-evidence.d.ts +74 -0
  222. package/dist/relay-evidence.d.ts.map +1 -0
  223. package/dist/relay-evidence.js +143 -0
  224. package/dist/relay-evidence.js.map +1 -0
  225. package/dist/resources.d.ts +35 -10
  226. package/dist/resources.d.ts.map +1 -1
  227. package/dist/resources.js +59 -18
  228. package/dist/resources.js.map +1 -1
  229. package/dist/schema.d.ts +4 -3
  230. package/dist/schema.d.ts.map +1 -1
  231. package/dist/schema.js +3 -3
  232. package/dist/schema.js.map +1 -1
  233. package/dist/scope-view.d.ts +65 -0
  234. package/dist/scope-view.d.ts.map +1 -0
  235. package/dist/scope-view.js +45 -0
  236. package/dist/scope-view.js.map +1 -0
  237. package/dist/server-types.d.ts +182 -27
  238. package/dist/server-types.d.ts.map +1 -1
  239. package/dist/server-types.js.map +1 -1
  240. package/dist/server.d.ts +26 -0
  241. package/dist/server.d.ts.map +1 -1
  242. package/dist/server.js +403 -61
  243. package/dist/server.js.map +1 -1
  244. package/dist/skills.d.ts.map +1 -1
  245. package/dist/skills.js +99 -3
  246. package/dist/skills.js.map +1 -1
  247. package/dist/task-dispatch.d.ts +35 -0
  248. package/dist/task-dispatch.d.ts.map +1 -0
  249. package/dist/task-dispatch.js +25 -0
  250. package/dist/task-dispatch.js.map +1 -0
  251. package/dist/tasks-runtime.d.ts +115 -0
  252. package/dist/tasks-runtime.d.ts.map +1 -0
  253. package/dist/tasks-runtime.js +760 -0
  254. package/dist/tasks-runtime.js.map +1 -0
  255. package/dist/tasks.d.ts +237 -0
  256. package/dist/tasks.d.ts.map +1 -0
  257. package/dist/tasks.js +321 -0
  258. package/dist/tasks.js.map +1 -0
  259. package/dist/tool-router.d.ts +68 -3
  260. package/dist/tool-router.d.ts.map +1 -1
  261. package/dist/tool-router.js +293 -70
  262. package/dist/tool-router.js.map +1 -1
  263. package/dist/tools.d.ts +32 -0
  264. package/dist/tools.d.ts.map +1 -1
  265. package/dist/tools.js +162 -55
  266. package/dist/tools.js.map +1 -1
  267. package/dist/up-front-steps.d.ts +35 -0
  268. package/dist/up-front-steps.d.ts.map +1 -0
  269. package/dist/up-front-steps.js +159 -0
  270. package/dist/up-front-steps.js.map +1 -0
  271. package/dist/validation.d.ts +38 -3
  272. package/dist/validation.d.ts.map +1 -1
  273. package/dist/validation.js +118 -23
  274. package/dist/validation.js.map +1 -1
  275. package/dist/verified-credentials.d.ts +13 -5
  276. package/dist/verified-credentials.d.ts.map +1 -1
  277. package/dist/verified-credentials.js +43 -10
  278. package/dist/verified-credentials.js.map +1 -1
  279. package/package.json +15 -11
@@ -0,0 +1,670 @@
1
+ /**
2
+ * @fileoverview Host-verified confirmation (`spec/confirmations.md`, "Host-verified
3
+ * confirmation"; `spec/approvals.md`, "Relay evidence"): the {@link HumanRelay} a host installs with
4
+ * `createMcpServer({ humanRelay })` or `createMcpHandler({ humanRelay })`, `inputDigest`, and the
5
+ * gate that enforces it on every MCP and HTTP surface regardless of `confirmations`.
6
+ *
7
+ * Node-only (uses `node:crypto` and `@modelcontextprotocol/server`); never imported by `/direct`
8
+ * or `/define`.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+ import { ErrorCodes, systemClock } from '@lushly-dev/afd-core';
12
+ import { inputRequired, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/server';
13
+ import { actorJson, canonicalJson } from './approval-crypto.js';
14
+ import { withoutApprovalRelay } from './approval-relay.js';
15
+ import { applyContextFields, RESERVED_CONTEXT_NAMES } from './context-fields.js';
16
+ import { hostState, withHostState } from './host-state.js';
17
+ import { credentialsBinding, principalBinding, } from './principal-binding.js';
18
+ import { attachRelayDispatchAdmission, attachRelayEvidence, attachRelayValidatedInput, } from './relay-evidence.js';
19
+ import { scopeViewOf } from './scope-view.js';
20
+ import { formatEnhancedValidationError, validateInputEnhanced, validationRecovery, } from './validation.js';
21
+ /** The `inputRequests` key of the URL-mode elicitation a {@link HumanRelay} prompt becomes. */
22
+ export const RELAY_INPUT_KEY = 'relay';
23
+ /** Return a copy of `context` carrying the lane's host-verified relay channel. */
24
+ export function bindHumanRelayChannel(context, channel) {
25
+ return withHostState(context, { humanRelayChannel: channel });
26
+ }
27
+ /** The host-verified relay channel bound to `context`, if any. */
28
+ export function humanRelayChannel(context) {
29
+ return hostState(context).humanRelayChannel;
30
+ }
31
+ /**
32
+ * Compute the relay input digest (`spec/confirmations.md`, "Host-verified confirmation",
33
+ * step 2): unpadded base64url SHA-256 of the canonical JSON (`spec/approvals.md`,
34
+ * "Approvals", rule 3) of `input`. `spec/authorization.json` (`inputDigests`) pins it.
35
+ *
36
+ * @throws TypeError when `input` has no exact canonical JSON form (e.g. `bigint`, non-finite
37
+ * number, cycle, `Map`, `Set`, class instance)
38
+ */
39
+ export function inputDigest(input) {
40
+ return createHash('sha256').update(canonicalJson(input), 'utf8').digest('base64url');
41
+ }
42
+ function canonicalOrUndefined(value) {
43
+ try {
44
+ return canonicalJson(value);
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ /** Reserved context keys that `approvedContext` must never replace. */
51
+ const RESERVED_APPROVED_KEYS = new Set([
52
+ ...RESERVED_CONTEXT_NAMES,
53
+ 'reportProgress',
54
+ '__proto__',
55
+ 'constructor',
56
+ 'prototype',
57
+ ]);
58
+ const MAX_PENDING_INPUTS = 4096;
59
+ const MAX_PENDING_INPUT_CHARS = 32_768;
60
+ const PENDING_INPUT_TTL_MS = 24 * 60 * 60_000;
61
+ function isRecord(value) {
62
+ return !!value && typeof value === 'object' && !Array.isArray(value);
63
+ }
64
+ /**
65
+ * Whether declared client capabilities include URL-mode elicitation (`elicitation.url`).
66
+ * `elicitation: {}` (form only) and `elicitation: { form: {} }` return `false`.
67
+ */
68
+ export function allowsUrlElicitation(capabilities) {
69
+ if (!isRecord(capabilities))
70
+ return false;
71
+ const elicitation = capabilities.elicitation;
72
+ if (!isRecord(elicitation))
73
+ return false;
74
+ return isRecord(elicitation.url);
75
+ }
76
+ const DNS_LABEL_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
77
+ const PORT_RE = /^[0-9]{1,5}$/;
78
+ const IPV6_CHARS_RE = /^[0-9A-Fa-f:.]+$/;
79
+ const DECISION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
80
+ function isValidPort(port) {
81
+ if (!PORT_RE.test(port))
82
+ return false;
83
+ const num = Number(port);
84
+ return num >= 1 && num <= 65_535;
85
+ }
86
+ function isValidDnsHost(host) {
87
+ if (host.length === 0 || host.length > 253)
88
+ return false;
89
+ return host.split('.').every((label) => DNS_LABEL_RE.test(label));
90
+ }
91
+ /**
92
+ * Whether `id` is a valid relay decision id: 1 to 128 ASCII letters, digits, `_` and `-`
93
+ * (`spec/confirmations.md`, "Host-verified confirmation"), so it carries no sentence, markup
94
+ * or link into a refusal suggestion.
95
+ */
96
+ export function isDecisionId(id) {
97
+ return typeof id === 'string' && DECISION_ID_RE.test(id);
98
+ }
99
+ /**
100
+ * Whether `url` is an absolute `https` URL with a valid host (DNS labels of ASCII letters, digits
101
+ * and `-`, or a bracketed IPv6 address), an optional port from 1 to 65535, no user information,
102
+ * and no whitespace, control character or unpaired surrogate.
103
+ */
104
+ export function isRelayUrl(url) {
105
+ if (typeof url !== 'string' || url.length <= 8)
106
+ return false;
107
+ if (!url.slice(0, 8).toLowerCase().startsWith('https://'))
108
+ return false;
109
+ for (let i = 0; i < url.length; i++) {
110
+ const code = url.charCodeAt(i);
111
+ if (code <= 0x20 || (code >= 0x7f && code <= 0x9f))
112
+ return false;
113
+ if (code >= 0xd800 && code <= 0xdbff) {
114
+ const next = url.charCodeAt(i + 1);
115
+ if (next >= 0xdc00 && next <= 0xdfff) {
116
+ i += 1;
117
+ continue;
118
+ }
119
+ return false;
120
+ }
121
+ if (code >= 0xdc00 && code <= 0xdfff)
122
+ return false;
123
+ if (/\s/.test(url[i] ?? ''))
124
+ return false;
125
+ }
126
+ if (url.includes('\\'))
127
+ return false;
128
+ const rest = url.slice(8);
129
+ const authority = rest.split(/[/?#]/, 1)[0] ?? '';
130
+ if (authority.length === 0 || authority.includes('@'))
131
+ return false;
132
+ if (authority.startsWith('[')) {
133
+ const closeIdx = authority.indexOf(']');
134
+ if (closeIdx === -1)
135
+ return false;
136
+ const addr = authority.slice(1, closeIdx);
137
+ if (addr.length === 0 || !addr.includes(':') || !IPV6_CHARS_RE.test(addr))
138
+ return false;
139
+ const after = authority.slice(closeIdx + 1);
140
+ if (after.length > 0 && (!after.startsWith(':') || !isValidPort(after.slice(1)))) {
141
+ return false;
142
+ }
143
+ }
144
+ else {
145
+ if (authority.includes('[') || authority.includes(']'))
146
+ return false;
147
+ const colonIdx = authority.indexOf(':');
148
+ const host = colonIdx === -1 ? authority : authority.slice(0, colonIdx);
149
+ const port = colonIdx === -1 ? undefined : authority.slice(colonIdx + 1);
150
+ if (!isValidDnsHost(host))
151
+ return false;
152
+ if (port !== undefined && !isValidPort(port))
153
+ return false;
154
+ }
155
+ try {
156
+ const parsed = new URL(url);
157
+ return (parsed.protocol === 'https:' &&
158
+ parsed.hostname.length > 0 &&
159
+ parsed.username === '' &&
160
+ parsed.password === '');
161
+ }
162
+ catch {
163
+ return false;
164
+ }
165
+ }
166
+ function quoted(names) {
167
+ return names.map((name) => `'${name}'`).join(', ');
168
+ }
169
+ function requiredError(names, suggestion) {
170
+ return {
171
+ code: ErrorCodes.CONFIRMATION_REQUIRED,
172
+ message: names.length === 1
173
+ ? `'${names[0]}' needs a person's confirmation through the host`
174
+ : `${quoted(names)} need a person's confirmation through the host`,
175
+ suggestion,
176
+ retryable: false,
177
+ details: { commands: [...names] },
178
+ // A person confirms through the host (`spec/recovery.md`, "Engine errors").
179
+ recovery: { kind: 'external' },
180
+ };
181
+ }
182
+ function declinedError(names) {
183
+ return {
184
+ code: ErrorCodes.CONFIRMATION_DECLINED,
185
+ message: `The user did not confirm ${quoted(names)}`,
186
+ suggestion: 'Do not run this again without asking the user first; the user chose not to proceed.',
187
+ retryable: false,
188
+ details: { commands: [...names] },
189
+ recovery: { kind: 'stop' },
190
+ };
191
+ }
192
+ /**
193
+ * Refusal for a host-verified command the server cannot relay: no relay is installed, or the call
194
+ * is a batch/pipeline step, a 2025-era request, or an HTTP `/rpc`, `/batch` or `/stream` route.
195
+ */
196
+ export function hostVerifiedUnrelayable(names, hasRelay) {
197
+ const suggestion = !hasRelay
198
+ ? `This server cannot confirm ${quoted(names)} over MCP: only the host can, and it has no way to ask the person here. Do not retry; ask the user to run it through the application.`
199
+ : `Call ${quoted(names)} on its own (its own tool, a grouped tool or afd-call) from an MCP 2026-07-28 client, so the host can ask the person.`;
200
+ return requiredError(names, suggestion);
201
+ }
202
+ function pendingRefusal(name, pending) {
203
+ if (!isRecord(pending) ||
204
+ !isDecisionId(pending.decision) ||
205
+ !isRelayUrl(pending.url) ||
206
+ !isRelayUrl(pending.list)) {
207
+ throw relayInternalError();
208
+ }
209
+ const { decision, url, list } = pending;
210
+ const suggestion = `Ask the person to open their pending decisions at ${list} (or this one at ${url}), check that it is decision ${decision} for '${name}', and decide there; then send this same call again.`;
211
+ return {
212
+ kind: 'error',
213
+ error: {
214
+ ...requiredError([name], suggestion),
215
+ retryable: true,
216
+ details: {
217
+ commands: [name],
218
+ reason: 'pending-list',
219
+ decision,
220
+ url,
221
+ list,
222
+ },
223
+ },
224
+ };
225
+ }
226
+ function relayInternalError() {
227
+ return new ProtocolError(ProtocolErrorCode.InternalError, 'Internal error');
228
+ }
229
+ function filterApprovedExtra(extra) {
230
+ if (extra === undefined)
231
+ return {};
232
+ if (!isRecord(extra))
233
+ throw relayInternalError();
234
+ const filtered = {};
235
+ for (const [key, value] of Object.entries(extra)) {
236
+ if (!RESERVED_APPROVED_KEYS.has(key))
237
+ filtered[key] = value;
238
+ }
239
+ return filtered;
240
+ }
241
+ function stateKey(state) {
242
+ return createHash('sha256').update(state, 'utf8').digest('base64url');
243
+ }
244
+ /**
245
+ * Create the host-verified confirmation gate wired into `createToolRouter` on MCP servers.
246
+ * Enforced on every MCP surface regardless of `confirmations` (`'off'` included).
247
+ */
248
+ export function createHumanRelayGate(options) {
249
+ const { relay, actor: defaultActor, devMode, contextFields, clock = systemClock, maxValidationIssues, onError, } = options;
250
+ const hostVerifiedNames = new Set(options.commands
251
+ .filter((command) => command.confirmationMode === 'host-verified')
252
+ .map((command) => command.name));
253
+ // Keeps the initial validated input across `begin` -> `resume` (and across pending-list
254
+ // retries, which carry no `requestState`) when a Zod schema computes a dynamic default (e.g. a
255
+ // generated id or timestamp), without altering the relay's `state` on the wire. Re-validated
256
+ // through the command's schema on retry (#1414 semantics).
257
+ const pendingInputs = new Map();
258
+ const pendingListInputs = new Map();
259
+ function prunePendingMap(store, now) {
260
+ for (const [key, entry] of store) {
261
+ if (entry.expiresAt <= now)
262
+ store.delete(key);
263
+ }
264
+ while (store.size >= MAX_PENDING_INPUTS) {
265
+ const oldest = store.keys().next().value;
266
+ if (oldest === undefined)
267
+ break;
268
+ store.delete(oldest);
269
+ }
270
+ }
271
+ function pendingListKey(command, rawCanonical, principal) {
272
+ return stateKey(JSON.stringify([command, rawCanonical, principal]));
273
+ }
274
+ function rememberInStore(store, key, command, rawCanonical, principal, canonical) {
275
+ if (rawCanonical === undefined || canonical.length > MAX_PENDING_INPUT_CHARS)
276
+ return;
277
+ const now = clock.now();
278
+ prunePendingMap(store, now);
279
+ store.set(key, {
280
+ command,
281
+ rawCanonical,
282
+ principal,
283
+ canonical,
284
+ expiresAt: now + PENDING_INPUT_TTL_MS,
285
+ });
286
+ }
287
+ function rememberPending(state, command, rawCanonical, principal, canonical) {
288
+ rememberInStore(pendingInputs, stateKey(state), command, rawCanonical, principal, canonical);
289
+ }
290
+ function rememberPendingList(command, rawCanonical, principal, canonical) {
291
+ if (rawCanonical === undefined)
292
+ return;
293
+ rememberInStore(pendingListInputs, pendingListKey(command, rawCanonical, principal), command, rawCanonical, principal, canonical);
294
+ }
295
+ function readFromStore(store, key, command, rawCanonical, principal) {
296
+ if (rawCanonical === undefined)
297
+ return undefined;
298
+ const entry = store.get(key);
299
+ if (!entry)
300
+ return undefined;
301
+ if (entry.expiresAt <= clock.now()) {
302
+ store.delete(key);
303
+ return undefined;
304
+ }
305
+ if (entry.command !== command.name ||
306
+ entry.rawCanonical !== rawCanonical ||
307
+ entry.principal !== principal) {
308
+ return undefined;
309
+ }
310
+ try {
311
+ const parsed = JSON.parse(entry.canonical);
312
+ const rechecked = validateInputEnhanced(command.inputSchema, parsed, maxValidationIssues);
313
+ if (rechecked.success && canonicalOrUndefined(rechecked.data) === entry.canonical) {
314
+ return rechecked;
315
+ }
316
+ }
317
+ catch {
318
+ // Fall back to validating the raw request input as sent.
319
+ }
320
+ return undefined;
321
+ }
322
+ function readPending(state, command, rawCanonical, principal) {
323
+ return readFromStore(pendingInputs, stateKey(state), command, rawCanonical, principal);
324
+ }
325
+ function readPendingList(command, rawCanonical, principal) {
326
+ if (rawCanonical === undefined)
327
+ return undefined;
328
+ return readFromStore(pendingListInputs, pendingListKey(command.name, rawCanonical, principal), command, rawCanonical, principal);
329
+ }
330
+ function forgetPendingIfMatching(state, command, rawCanonical, principal) {
331
+ if (!state || rawCanonical === undefined)
332
+ return;
333
+ const key = stateKey(state);
334
+ const entry = pendingInputs.get(key);
335
+ if (entry &&
336
+ entry.command === command &&
337
+ entry.rawCanonical === rawCanonical &&
338
+ entry.principal === principal) {
339
+ pendingInputs.delete(key);
340
+ }
341
+ }
342
+ function forgetPendingList(command, rawCanonical, principal) {
343
+ if (rawCanonical === undefined)
344
+ return;
345
+ pendingListInputs.delete(pendingListKey(command, rawCanonical, principal));
346
+ }
347
+ function present(commandName, capabilities, prompt, rawCanonical, principal, validatedCanonical) {
348
+ if (!allowsUrlElicitation(capabilities)) {
349
+ return {
350
+ kind: 'error',
351
+ error: requiredError([commandName], `Use an MCP client that supports URL-mode elicitation: only a person, through the link the host sends, can confirm '${commandName}'.`),
352
+ };
353
+ }
354
+ if (!isRecord(prompt) ||
355
+ !isRelayUrl(prompt.url) ||
356
+ typeof prompt.message !== 'string' ||
357
+ typeof prompt.state !== 'string' ||
358
+ prompt.state.length === 0) {
359
+ throw relayInternalError();
360
+ }
361
+ rememberPending(prompt.state, commandName, rawCanonical, principal, validatedCanonical);
362
+ // One id per URL, so a pending decision keeps one id.
363
+ const elicitationId = createHash('sha256').update(prompt.url, 'utf8').digest('base64url');
364
+ return {
365
+ kind: 'input-required',
366
+ result: inputRequired({
367
+ inputRequests: {
368
+ [RELAY_INPUT_KEY]: {
369
+ method: 'elicitation/create',
370
+ params: {
371
+ mode: 'url',
372
+ message: prompt.message,
373
+ url: prompt.url,
374
+ elicitationId,
375
+ },
376
+ },
377
+ },
378
+ requestState: prompt.state,
379
+ }),
380
+ };
381
+ }
382
+ return {
383
+ refuseSteps(steps) {
384
+ const names = [];
385
+ for (const step of steps) {
386
+ if (hostVerifiedNames.has(step.command) && !names.includes(step.command)) {
387
+ names.push(step.command);
388
+ }
389
+ }
390
+ return names.length > 0 ? hostVerifiedUnrelayable(names, Boolean(relay)) : undefined;
391
+ },
392
+ async check(command, input, callContext) {
393
+ const name = command.name;
394
+ if (!relay) {
395
+ return { kind: 'error', error: hostVerifiedUnrelayable([name], false) };
396
+ }
397
+ const channel = humanRelayChannel(callContext);
398
+ if (!channel?.modern) {
399
+ return { kind: 'error', error: hostVerifiedUnrelayable([name], true) };
400
+ }
401
+ // M8: credentials that cannot be bound never reach the relay, on first call or retry.
402
+ const actor = (callContext.actor ?? defaultActor);
403
+ const credentials = callContext.credentials;
404
+ let credsBinding;
405
+ let boundPrincipal;
406
+ try {
407
+ credsBinding = credentialsBinding(credentials);
408
+ boundPrincipal = principalBinding(actor, credentials);
409
+ }
410
+ catch {
411
+ throw relayInternalError();
412
+ }
413
+ // Step 2: validate first, as the execution engine will, so the person decides on
414
+ // exactly what will run. On an `accept` retry for the same raw input, command and
415
+ // principal — or a pending-list retry (which carries no `requestState`) — reuse the
416
+ // initial validated input if it still validates to the same canonical JSON (so dynamic
417
+ // Zod defaults stay bound across `begin` -> `resume` and across pending-list retries).
418
+ const isStopAnswer = channel.requestState !== undefined &&
419
+ (channel.relayAction === 'decline' || channel.relayAction === 'cancel');
420
+ const rawCanonical = canonicalOrUndefined(input);
421
+ const pendingValidation = channel.relayAction === 'accept' && channel.requestState
422
+ ? readPending(channel.requestState, command, rawCanonical, boundPrincipal)
423
+ : !isStopAnswer &&
424
+ !allowsUrlElicitation(channel.clientCapabilities) &&
425
+ relay.pendingList !== undefined
426
+ ? readPendingList(command, rawCanonical, boundPrincipal)
427
+ : undefined;
428
+ let validation = pendingValidation;
429
+ if (!validation) {
430
+ try {
431
+ validation = validateInputEnhanced(command.inputSchema, input, maxValidationIssues);
432
+ }
433
+ catch (err) {
434
+ const error = err instanceof Error ? err : new Error(String(err));
435
+ try {
436
+ onError?.(error);
437
+ }
438
+ catch { }
439
+ return {
440
+ kind: 'error',
441
+ error: {
442
+ code: ErrorCodes.VALIDATION_ERROR,
443
+ message: 'Input validation failed',
444
+ suggestion: devMode
445
+ ? `Input validation threw: ${error.message}`
446
+ : `Check the input against the input schema of '${name}' (afd-detail returns it) and retry`,
447
+ },
448
+ };
449
+ }
450
+ }
451
+ if (!validation.success) {
452
+ return {
453
+ kind: 'error',
454
+ error: {
455
+ code: ErrorCodes.VALIDATION_ERROR,
456
+ message: 'Input validation failed',
457
+ suggestion: formatEnhancedValidationError(validation.errors, {
458
+ expectedFields: validation.expectedFields,
459
+ unexpectedFields: validation.unexpectedFields,
460
+ missingFields: validation.missingFields,
461
+ truncated: validation.truncated,
462
+ limit: validation.limit,
463
+ }),
464
+ recovery: validationRecovery({
465
+ errors: validation.errors,
466
+ missingFields: validation.missingFields,
467
+ unexpectedFields: validation.unexpectedFields,
468
+ }),
469
+ details: {
470
+ errors: validation.errors,
471
+ expectedFields: validation.expectedFields,
472
+ unexpectedFields: validation.unexpectedFields,
473
+ missingFields: validation.missingFields,
474
+ ...(validation.truncated
475
+ ? {
476
+ truncated: true,
477
+ limit: validation.limit,
478
+ totalErrors: validation.totalErrors,
479
+ }
480
+ : {}),
481
+ },
482
+ },
483
+ };
484
+ }
485
+ // Re-check scopes on the validated input (M6) before asking anyone.
486
+ const view = scopeViewOf(callContext);
487
+ const scopeDecision = view?.decideExecution(name, validation.data);
488
+ if (view && scopeDecision && scopeDecision !== 'proceed') {
489
+ return { kind: 'error', error: view.insufficientScope(scopeDecision.forbidden) };
490
+ }
491
+ let validatedCanonical;
492
+ let digest;
493
+ try {
494
+ validatedCanonical = canonicalJson(validation.data);
495
+ digest = createHash('sha256').update(validatedCanonical, 'utf8').digest('base64url');
496
+ }
497
+ catch (err) {
498
+ return {
499
+ kind: 'error',
500
+ error: {
501
+ code: ErrorCodes.VALIDATION_ERROR,
502
+ message: err instanceof Error ? err.message : 'Input has no canonical JSON form',
503
+ suggestion: 'Pass plain JSON input: integers within ±2^53',
504
+ retryable: false,
505
+ },
506
+ };
507
+ }
508
+ const capabilities = channel.clientCapabilities;
509
+ const relayContext = {
510
+ ...withoutApprovalRelay(callContext),
511
+ ...(actor ? { actor: { ...actor } } : {}),
512
+ };
513
+ // Validate declared context fields before asking a person, so `call.context` matches
514
+ // what the command runs with and invalid `_meta` context fields fail fast.
515
+ if (contextFields?.length) {
516
+ const invalidField = applyContextFields(contextFields, relayContext, name, {
517
+ devMode,
518
+ // Guarded here: a hook that throws or rejects must not change the answer.
519
+ onError: (error) => {
520
+ try {
521
+ const returned = onError?.(error instanceof Error ? error : new Error(String(error)));
522
+ if (returned instanceof Promise)
523
+ returned.catch(() => { });
524
+ }
525
+ catch { }
526
+ },
527
+ });
528
+ if (invalidField?.error) {
529
+ return { kind: 'error', error: invalidField.error };
530
+ }
531
+ }
532
+ const call = {
533
+ command: name,
534
+ inputDigest: digest,
535
+ ...(actor ? { actor: { ...actor } } : {}),
536
+ ...(credentials !== undefined ? { credentials } : {}),
537
+ ...(capabilities !== undefined ? { clientCapabilities: capabilities } : {}),
538
+ input: validation.data,
539
+ context: relayContext,
540
+ principalBinding: () => boundPrincipal,
541
+ supportsUrlElicitation: () => allowsUrlElicitation(capabilities),
542
+ };
543
+ const approved = async (decisionId) => {
544
+ if (!isDecisionId(decisionId)) {
545
+ throw relayInternalError();
546
+ }
547
+ if (relay.approvedContext !== undefined && typeof relay.approvedContext !== 'function') {
548
+ throw relayInternalError();
549
+ }
550
+ const extra = relay.approvedContext
551
+ ? filterApprovedExtra(await relay.approvedContext(decisionId, call))
552
+ : {};
553
+ const evidence = {
554
+ command: name,
555
+ inputDigest: digest,
556
+ actor: actorJson(actor),
557
+ credentialsBinding: credsBinding,
558
+ decisionId,
559
+ };
560
+ // Build execution context: strip form-mode approval relay, merge host-owned
561
+ // approvedContext fields, attach private relay evidence, validated input,
562
+ // and one-shot host-verified dispatch admission (off-object WeakMap).
563
+ const execContext = {
564
+ ...withoutApprovalRelay(callContext),
565
+ ...extra,
566
+ };
567
+ attachRelayEvidence(execContext, evidence);
568
+ attachRelayValidatedInput(execContext, name, validation.data);
569
+ attachRelayDispatchAdmission(execContext, {
570
+ command: name,
571
+ canonical: validatedCanonical,
572
+ canonicalize: canonicalOrUndefined,
573
+ });
574
+ return { kind: 'proceed', context: execContext };
575
+ };
576
+ // Ending the elicitation is an answer only to stop: nothing is asked of the relay,
577
+ // whatever the client declared.
578
+ if (isStopAnswer) {
579
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
580
+ forgetPendingList(name, rawCanonical, boundPrincipal);
581
+ return { kind: 'error', error: declinedError([name]) };
582
+ }
583
+ // A client that cannot open a URL elicitation is never sent one: the relay's pending
584
+ // list, if it keeps one, is its only way (`spec/confirmations.md`, "The pending list").
585
+ if (!call.supportsUrlElicitation() && relay.pendingList !== undefined) {
586
+ if (typeof relay.pendingList !== 'function') {
587
+ throw relayInternalError();
588
+ }
589
+ const found = await relay.pendingList(call);
590
+ if (found === undefined) {
591
+ forgetPendingList(name, rawCanonical, boundPrincipal);
592
+ }
593
+ else {
594
+ if (!isRecord(found) || typeof found.kind !== 'string') {
595
+ throw relayInternalError();
596
+ }
597
+ switch (found.kind) {
598
+ case 'approved': {
599
+ const outcome = await approved(found.decisionId);
600
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
601
+ forgetPendingList(name, rawCanonical, boundPrincipal);
602
+ return outcome;
603
+ }
604
+ case 'declined':
605
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
606
+ forgetPendingList(name, rawCanonical, boundPrincipal);
607
+ return { kind: 'error', error: declinedError([name]) };
608
+ case 'pending': {
609
+ const outcome = pendingRefusal(name, found);
610
+ rememberPendingList(name, rawCanonical, boundPrincipal, validatedCanonical);
611
+ return outcome;
612
+ }
613
+ case 'error':
614
+ if (!isRecord(found.error) ||
615
+ typeof found.error.code !== 'string' ||
616
+ typeof found.error.message !== 'string') {
617
+ throw relayInternalError();
618
+ }
619
+ return { kind: 'error', error: found.error };
620
+ default:
621
+ throw relayInternalError();
622
+ }
623
+ }
624
+ }
625
+ // Step 4: retry carrying inputResponses.relay (accept) and requestState.
626
+ if (channel.relayAction === 'accept' && channel.requestState) {
627
+ const outcome = await relay.resume(channel.requestState, call);
628
+ if (!isRecord(outcome) || typeof outcome.kind !== 'string') {
629
+ throw relayInternalError();
630
+ }
631
+ switch (outcome.kind) {
632
+ case 'approved':
633
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
634
+ return approved(outcome.decisionId);
635
+ case 'declined':
636
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
637
+ return { kind: 'error', error: declinedError([name]) };
638
+ case 'pending':
639
+ if (outcome.prompt?.state !== channel.requestState) {
640
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
641
+ }
642
+ return present(name, capabilities, outcome.prompt, rawCanonical, boundPrincipal, validatedCanonical);
643
+ case 'invalid':
644
+ if (pendingValidation) {
645
+ forgetPendingIfMatching(channel.requestState, name, rawCanonical, boundPrincipal);
646
+ }
647
+ // State is not an answer: begin again (step 3).
648
+ break;
649
+ default:
650
+ throw relayInternalError();
651
+ }
652
+ }
653
+ // Step 3: begin.
654
+ const begun = await relay.begin(call);
655
+ if (!isRecord(begun) || typeof begun.ok !== 'boolean') {
656
+ throw relayInternalError();
657
+ }
658
+ if (!begun.ok) {
659
+ if (!isRecord(begun.error) ||
660
+ typeof begun.error.code !== 'string' ||
661
+ typeof begun.error.message !== 'string') {
662
+ throw relayInternalError();
663
+ }
664
+ return { kind: 'error', error: begun.error };
665
+ }
666
+ return present(name, capabilities, begun.prompt, rawCanonical, boundPrincipal, validatedCanonical);
667
+ },
668
+ };
669
+ }
670
+ //# sourceMappingURL=human-relay.js.map